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
280cebe01bca639542b13e5ea643ef557cc8b0a7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/group_action/prod.lean
d373216994e15fd200af2b0b840903c36a0261c3
[ "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,353
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Eric Wieser -/ import algebra.group.prod import group_theory.group_action.defs /-! # Prod instances for additive and multiplicative actions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines instances for binary product of additive and multiplicative actions and provides scalar multiplication as a homomorphism from `α × β` to `β`. ## Main declarations * `smul_mul_hom`/`smul_monoid_hom`: Scalar multiplication bundled as a multiplicative/monoid homomorphism. ## See also * `group_theory.group_action.option` * `group_theory.group_action.pi` * `group_theory.group_action.sigma` * `group_theory.group_action.sum` -/ variables {M N P E α β : Type*} namespace prod section variables [has_smul M α] [has_smul M β] [has_smul N α] [has_smul N β] (a : M) (x : α × β) @[to_additive prod.has_vadd] instance : has_smul M (α × β) := ⟨λa p, (a • p.1, a • p.2)⟩ @[simp, to_additive] theorem smul_fst : (a • x).1 = a • x.1 := rfl @[simp, to_additive] theorem smul_snd : (a • x).2 = a • x.2 := rfl @[simp, to_additive] theorem smul_mk (a : M) (b : α) (c : β) : a • (b, c) = (a • b, a • c) := rfl @[to_additive] theorem smul_def (a : M) (x : α × β) : a • x = (a • x.1, a • x.2) := rfl @[simp, to_additive] theorem smul_swap : (a • x).swap = a • x.swap := rfl lemma smul_zero_mk {α : Type*} [monoid M] [add_monoid α] [distrib_mul_action M α] (a : M) (c : β) : a • ((0 : α), c) = (0, a • c) := by rw [prod.smul_mk, smul_zero] lemma smul_mk_zero {β : Type*} [monoid M] [add_monoid β] [distrib_mul_action M β] (a : M) (b : α) : a • (b, (0 : β)) = (a • b, 0) := by rw [prod.smul_mk, smul_zero] variables [has_pow α E] [has_pow β E] @[to_additive has_smul] instance has_pow : has_pow (α × β) E := { pow := λ p c, (p.1 ^ c, p.2 ^ c) } @[simp, to_additive smul_fst, to_additive_reorder 6] lemma pow_fst (p : α × β) (c : E) : (p ^ c).fst = p.fst ^ c := rfl @[simp, to_additive smul_snd, to_additive_reorder 6] lemma pow_snd (p : α × β) (c : E) : (p ^ c).snd = p.snd ^ c := rfl /- Note that the `c` arguments to this lemmas cannot be in the more natural right-most positions due to limitations in `to_additive` and `to_additive_reorder`, which will silently fail to reorder more than two adjacent arguments -/ @[simp, to_additive smul_mk, to_additive_reorder 6] lemma pow_mk (c : E) (a : α) (b : β) : (prod.mk a b) ^ c = prod.mk (a ^ c) (b ^ c) := rfl @[to_additive smul_def, to_additive_reorder 6] lemma pow_def (p : α × β) (c : E) : p ^ c = (p.1 ^ c, p.2 ^ c) := rfl @[simp, to_additive smul_swap, to_additive_reorder 6] lemma pow_swap (p : α × β) (c : E) : (p ^ c).swap = p.swap ^ c := rfl @[to_additive] instance [has_smul M N] [is_scalar_tower M N α] [is_scalar_tower M N β] : is_scalar_tower M N (α × β) := ⟨λ x y z, mk.inj_iff.mpr ⟨smul_assoc _ _ _, smul_assoc _ _ _⟩⟩ @[to_additive] instance [smul_comm_class M N α] [smul_comm_class M N β] : smul_comm_class M N (α × β) := { smul_comm := λ r s x, mk.inj_iff.mpr ⟨smul_comm _ _ _, smul_comm _ _ _⟩ } @[to_additive] instance [has_smul Mᵐᵒᵖ α] [has_smul Mᵐᵒᵖ β] [is_central_scalar M α] [is_central_scalar M β] : is_central_scalar M (α × β) := ⟨λ r m, prod.ext (op_smul_eq_smul _ _) (op_smul_eq_smul _ _)⟩ @[to_additive] instance has_faithful_smul_left [has_faithful_smul M α] [nonempty β] : has_faithful_smul M (α × β) := ⟨λ x y h, let ⟨b⟩ := ‹nonempty β› in eq_of_smul_eq_smul $ λ a : α, by injection h (a, b)⟩ @[to_additive] instance has_faithful_smul_right [nonempty α] [has_faithful_smul M β] : has_faithful_smul M (α × β) := ⟨λ x y h, let ⟨a⟩ := ‹nonempty α› in eq_of_smul_eq_smul $ λ b : β, by injection h (a, b)⟩ end @[to_additive] instance smul_comm_class_both [has_mul N] [has_mul P] [has_smul M N] [has_smul M P] [smul_comm_class M N N] [smul_comm_class M P P] : smul_comm_class M (N × P) (N × P) := ⟨λ c x y, by simp [smul_def, mul_def, mul_smul_comm]⟩ instance is_scalar_tower_both [has_mul N] [has_mul P] [has_smul M N] [has_smul M P] [is_scalar_tower M N N] [is_scalar_tower M P P] : is_scalar_tower M (N × P) (N × P) := ⟨λ c x y, by simp [smul_def, mul_def, smul_mul_assoc]⟩ @[to_additive] instance {m : monoid M} [mul_action M α] [mul_action M β] : mul_action M (α × β) := { mul_smul := λ a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩, one_smul := λ ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩ } instance {R M N : Type*} [has_zero M] [has_zero N] [smul_zero_class R M] [smul_zero_class R N] : smul_zero_class R (M × N) := { smul_zero := λ a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩ } instance {R M N : Type*} [add_zero_class M] [add_zero_class N] [distrib_smul R M] [distrib_smul R N] : distrib_smul R (M × N) := { smul_add := λ a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩ } instance {R M N : Type*} {r : monoid R} [add_monoid M] [add_monoid N] [distrib_mul_action R M] [distrib_mul_action R N] : distrib_mul_action R (M × N) := { ..prod.distrib_smul } instance {R M N : Type*} {r : monoid R} [monoid M] [monoid N] [mul_distrib_mul_action R M] [mul_distrib_mul_action R N] : mul_distrib_mul_action R (M × N) := { smul_mul := λ a p₁ p₂, mk.inj_iff.mpr ⟨smul_mul' _ _ _, smul_mul' _ _ _⟩, smul_one := λ a, mk.inj_iff.mpr ⟨smul_one _, smul_one _⟩ } end prod /-! ### Scalar multiplication as a homomorphism -/ section bundled_smul /-- Scalar multiplication as a multiplicative homomorphism. -/ @[simps] def smul_mul_hom [monoid α] [has_mul β] [mul_action α β] [is_scalar_tower α β β] [smul_comm_class α β β] : (α × β) →ₙ* β := { to_fun := λ a, a.1 • a.2, map_mul' := λ a b, (smul_mul_smul _ _ _ _).symm } /-- Scalar multiplication as a monoid homomorphism. -/ @[simps] def smul_monoid_hom [monoid α] [mul_one_class β] [mul_action α β] [is_scalar_tower α β β] [smul_comm_class α β β] : α × β →* β := { map_one' := one_smul _ _, .. smul_mul_hom } end bundled_smul
ffa212fd9ca740898851fcef13f73e1df9e37a24
618003631150032a5676f229d13a079ac875ff77
/src/algebra/pointwise.lean
7204e8aa037b30ecb479e60ce102c53147210fac
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
12,341
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.module /-! # Pointwise addition, multiplication, and scalar multiplication of sets. This file defines `pointwise_mul`: for a type `α` with multiplication, multiplication is defined on `set α` by taking `s * t` to be the set of all `x * y` where `x ∈ s` and `y ∈ t`. Pointwise multiplication on `set α` where `α` is a semigroup makes `set α` into a semigroup. If `α` is additionally a (commutative) monoid, `set α` becomes a (commutative) semiring with union as addition. These are given by `pointwise_mul_semigroup` and `pointwise_mul_semiring`. Definitions and results are also transported to the additive theory via `to_additive`. For a type `β` with scalar multiplication by another type `α`, this file defines `pointwise_smul`. Separately it defines `smul_set`, for scalar multiplication of `set β` by a single term of type `α`. ## Implementation notes Elsewhere, one should register local instances to use the definitions in this file. -/ namespace set open function variables {α : Type*} {β : Type*} (f : α → β) @[to_additive] def pointwise_one [has_one α] : has_one (set α) := ⟨{1}⟩ local attribute [instance] pointwise_one @[simp, to_additive] lemma mem_pointwise_one [has_one α] (a : α) : a ∈ (1 : set α) ↔ a = 1 := mem_singleton_iff @[to_additive] def pointwise_mul [has_mul α] : has_mul (set α) := ⟨λ s t, {a | ∃ x ∈ s, ∃ y ∈ t, a = x * y}⟩ local attribute [instance] pointwise_one pointwise_mul pointwise_add @[to_additive] lemma mem_pointwise_mul [has_mul α] {s t : set α} {a : α} : a ∈ s * t ↔ ∃ x ∈ s, ∃ y ∈ t, a = x * y := iff.rfl @[to_additive] lemma mul_mem_pointwise_mul [has_mul α] {s t : set α} {a b : α} (ha : a ∈ s) (hb : b ∈ t) : a * b ∈ s * t := ⟨_, ha, _, hb, rfl⟩ @[to_additive] lemma pointwise_mul_eq_image [has_mul α] {s t : set α} : s * t = (λ x : α × α, x.fst * x.snd) '' s.prod t := set.ext $ λ a, ⟨ by { rintros ⟨_, _, _, _, rfl⟩, exact ⟨(_, _), mem_prod.mpr ⟨‹_›, ‹_›⟩, rfl⟩ }, by { rintros ⟨_, _, rfl⟩, exact ⟨_, (mem_prod.mp ‹_›).1, _, (mem_prod.mp ‹_›).2, rfl⟩ }⟩ @[to_additive] lemma pointwise_mul_finite [has_mul α] {s t : set α} (hs : finite s) (ht : finite t) : finite (s * t) := by { rw pointwise_mul_eq_image, apply set.finite_image, exact set.finite_prod hs ht } @[to_additive pointwise_add_add_semigroup] def pointwise_mul_semigroup [semigroup α] : semigroup (set α) := { mul_assoc := λ _ _ _, set.ext $ λ _, begin split, { rintros ⟨_, ⟨_, _, _, _, rfl⟩, _, _, rfl⟩, exact ⟨_, ‹_›, _, ⟨_, ‹_›, _, ‹_›, rfl⟩, mul_assoc _ _ _⟩ }, { rintros ⟨_, _, _, ⟨_, _, _, _, rfl⟩, rfl⟩, exact ⟨_, ⟨_, ‹_›, _, ‹_›, rfl⟩, _, ‹_›, (mul_assoc _ _ _).symm⟩ } end, ..pointwise_mul } @[to_additive pointwise_add_add_monoid] def pointwise_mul_monoid [monoid α] : monoid (set α) := { one_mul := λ s, set.ext $ λ a, ⟨by {rintros ⟨_, _, _, _, rfl⟩, simp * at *}, λ h, ⟨1, mem_singleton 1, a, h, (one_mul a).symm⟩⟩, mul_one := λ s, set.ext $ λ a, ⟨by {rintros ⟨_, _, _, _, rfl⟩, simp * at *}, λ h, ⟨a, h, 1, mem_singleton 1, (mul_one a).symm⟩⟩, ..pointwise_mul_semigroup, ..pointwise_one } local attribute [instance] pointwise_mul_monoid @[to_additive] lemma singleton.is_mul_hom [has_mul α] : is_mul_hom (singleton : α → set α) := { map_mul := λ x y, set.ext $ λ a, by simp [mem_singleton_iff, mem_pointwise_mul] } @[to_additive is_add_monoid_hom] lemma singleton.is_monoid_hom [monoid α] : is_monoid_hom (singleton : α → set α) := { map_one := rfl, ..singleton.is_mul_hom } @[to_additive] def pointwise_inv [has_inv α] : has_inv (set α) := ⟨λ s, {a | a⁻¹ ∈ s}⟩ @[simp, to_additive] lemma pointwise_mul_empty [has_mul α] (s : set α) : s * ∅ = ∅ := set.ext $ λ a, ⟨by {rintros ⟨_, _, _, _, rfl⟩, tauto}, false.elim⟩ @[simp, to_additive] lemma empty_pointwise_mul [has_mul α] (s : set α) : ∅ * s = ∅ := set.ext $ λ a, ⟨by {rintros ⟨_, _, _, _, rfl⟩, tauto}, false.elim⟩ @[to_additive] lemma pointwise_mul_subset_mul [has_mul α] {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ * s₂ ⊆ t₁ * t₂ := by {rintros _ ⟨_, _, _, _, rfl⟩, exact ⟨_, h₁ ‹_›, _, h₂ ‹_›, rfl⟩ } @[to_additive] lemma pointwise_mul_union [has_mul α] (s t u : set α) : s * (t ∪ u) = (s * t) ∪ (s * u) := begin ext a, split, { rintros ⟨_, _, _, H, rfl⟩, cases H; [left, right]; exact ⟨_, ‹_›, _, ‹_›, rfl⟩ }, { intro H, cases H with H H; { rcases H with ⟨_, _, _, _, rfl⟩, refine ⟨_, ‹_›, _, _, rfl⟩, erw mem_union, simp * } } end @[to_additive] lemma union_pointwise_mul [has_mul α] (s t u : set α) : (s ∪ t) * u = (s * u) ∪ (t * u) := begin ext a, split, { rintros ⟨_, H, _, _, rfl⟩, cases H; [left, right]; exact ⟨_, ‹_›, _, ‹_›, rfl⟩ }, { intro H, cases H with H H; { rcases H with ⟨_, _, _, _, rfl⟩; refine ⟨_, _, _, ‹_›, rfl⟩; erw mem_union; simp * } } end @[to_additive] lemma pointwise_mul_eq_Union_mul_left [has_mul α] {s t : set α} : s * t = ⋃a∈s, (λx, a * x) '' t := by { ext y; split; simp only [mem_Union]; rintros ⟨a, ha, x, hx, ax⟩; exact ⟨a, ha, x, hx, ax.symm⟩ } @[to_additive] lemma pointwise_mul_eq_Union_mul_right [has_mul α] {s t : set α} : s * t = ⋃a∈t, (λx, x * a) '' s := by { ext y; split; simp only [mem_Union]; rintros ⟨a, ha, x, hx, ax⟩; exact ⟨x, hx, a, ha, ax.symm⟩ } @[to_additive] lemma nonempty.pointwise_mul [has_mul α] {s t : set α} : s.nonempty → t.nonempty → (s * t).nonempty | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨x * y, ⟨x, hx, y, hy, rfl⟩⟩ @[simp, to_additive] lemma univ_pointwise_mul_univ [monoid α] : (univ : set α) * univ = univ := begin have : ∀x, ∃a b : α, x = a * b := λx, ⟨x, ⟨1, (mul_one x).symm⟩⟩, show {a | ∃ x ∈ univ, ∃ y ∈ univ, a = x * y} = univ, simpa [eq_univ_iff_forall] end def pointwise_mul_fintype [has_mul α] [decidable_eq α] (s t : set α) [hs : fintype s] [ht : fintype t] : fintype (s * t : set α) := by { rw pointwise_mul_eq_image, apply set.fintype_image } def pointwise_add_fintype [has_add α] [decidable_eq α] (s t : set α) [hs : fintype s] [ht : fintype t] : fintype (s + t : set α) := by { rw pointwise_add_eq_image, apply set.fintype_image } attribute [to_additive] set.pointwise_mul_fintype /-- Pointwise scalar multiplication by a set of scalars. -/ def pointwise_smul [has_scalar α β] : has_scalar (set α) (set β) := ⟨λ s t, { x | ∃ a ∈ s, ∃ y ∈ t, x = a • y }⟩ /-- Scaling a set: multiplying every element by a scalar. -/ def smul_set [has_scalar α β] : has_scalar α (set β) := ⟨λ a s, { x | ∃ y ∈ s, x = a • y }⟩ local attribute [instance] pointwise_smul smul_set lemma mem_smul_set [has_scalar α β] (a : α) (s : set β) (x : β) : x ∈ a • s ↔ ∃ y ∈ s, x = a • y := iff.rfl lemma smul_set_eq_image [has_scalar α β] (a : α) (s : set β) : a • s = (λ x, a • x) '' s := set.ext $ λ x, iff.intro (λ ⟨_, hy₁, hy₂⟩, ⟨_, hy₁, hy₂.symm⟩) (λ ⟨_, hy₁, hy₂⟩, ⟨_, hy₁, hy₂.symm⟩) lemma smul_set_eq_pointwise_smul_singleton [has_scalar α β] (a : α) (s : set β) : a • s = ({a} : set α) • s := set.ext $ λ x, iff.intro (λ ⟨_, h⟩, ⟨a, mem_singleton _, _, h⟩) (λ ⟨_, h, y, hy, hx⟩, ⟨_, hy, by { rw mem_singleton_iff at h; rwa h at hx }⟩) lemma smul_mem_smul_set [has_scalar α β] (a : α) {s : set β} {y : β} (hy : y ∈ s) : a • y ∈ a • s := by rw mem_smul_set; use [y, hy] lemma smul_set_union [has_scalar α β] (a : α) (s t : set β) : a • (s ∪ t) = a • s ∪ a • t := by simp only [smul_set_eq_image, image_union] @[simp] lemma smul_set_empty [has_scalar α β] (a : α) : a • (∅ : set β) = ∅ := by rw [smul_set_eq_image, image_empty] lemma smul_set_mono [has_scalar α β] (a : α) {s t : set β} (h : s ⊆ t) : a • s ⊆ a • t := by { rw [smul_set_eq_image, smul_set_eq_image], exact image_subset _ h } section monoid def pointwise_mul_semiring [monoid α] : semiring (set α) := { add := (⊔), zero := ∅, add_assoc := set.union_assoc, zero_add := set.empty_union, add_zero := set.union_empty, add_comm := set.union_comm, zero_mul := empty_pointwise_mul, mul_zero := pointwise_mul_empty, left_distrib := pointwise_mul_union, right_distrib := union_pointwise_mul, ..pointwise_mul_monoid } def pointwise_mul_comm_semiring [comm_monoid α] : comm_semiring (set α) := { mul_comm := λ s t, set.ext $ λ a, by split; { rintros ⟨_, _, _, _, rfl⟩, exact ⟨_, ‹_›, _, ‹_›, mul_comm _ _⟩ }, ..pointwise_mul_semiring } local attribute [instance] pointwise_mul_semiring def comm_monoid [comm_monoid α] : comm_monoid (set α) := @comm_semiring.to_comm_monoid (set α) pointwise_mul_comm_semiring def add_comm_monoid [add_comm_monoid α] : add_comm_monoid (set α) := show @add_comm_monoid (additive (set (multiplicative α))), from @additive.add_comm_monoid _ set.comm_monoid attribute [to_additive set.add_comm_monoid] set.comm_monoid /-- A multiplicative action of a monoid on a type β gives also a multiplicative action on the subsets of β. -/ def smul_set_action [monoid α] [mul_action α β] : mul_action α (set β) := { smul := λ a s, a • s, mul_smul := λ a b s, set.ext $ λ x, iff.intro (λ ⟨_, hy, _⟩, ⟨b • _, smul_mem_smul_set _ hy, by rwa ←mul_smul⟩) (λ ⟨_, hy, _⟩, let ⟨_, hz, h⟩ := (mem_smul_set _ _ _).2 hy in ⟨_, hz, by rwa [mul_smul, ←h]⟩), one_smul := λ b, set.ext $ λ x, iff.intro (λ ⟨_, _, h⟩, by { rw [one_smul] at h; rwa h }) (λ h, ⟨_, h, by rw one_smul⟩) } section is_mul_hom open is_mul_hom variables [has_mul α] [has_mul β] (m : α → β) [is_mul_hom m] @[to_additive] lemma image_pointwise_mul (s t : set α) : m '' (s * t) = m '' s * m '' t := set.ext $ assume y, begin split, { rintros ⟨_, ⟨_, _, _, _, rfl⟩, rfl⟩, refine ⟨_, mem_image_of_mem _ ‹_›, _, mem_image_of_mem _ ‹_›, map_mul _ _ _⟩ }, { rintros ⟨_, ⟨_, _, rfl⟩, _, ⟨_, _, rfl⟩, rfl⟩, refine ⟨_, ⟨_, ‹_›, _, ‹_›, rfl⟩, map_mul _ _ _⟩ } end @[to_additive] lemma preimage_pointwise_mul_preimage_subset (s t : set β) : m ⁻¹' s * m ⁻¹' t ⊆ m ⁻¹' (s * t) := begin rintros _ ⟨_, _, _, _, rfl⟩, exact ⟨_, ‹_›, _, ‹_›, map_mul _ _ _⟩, end end is_mul_hom variables [monoid α] [monoid β] [is_monoid_hom f] lemma pointwise_mul_image_is_semiring_hom : is_semiring_hom (image f) := { map_zero := image_empty _, map_one := by erw [image_singleton, is_monoid_hom.map_one f]; refl, map_add := image_union _, map_mul := image_pointwise_mul _ } end monoid end set section open set variables {α : Type*} {β : Type*} local attribute [instance] set.smul_set /-- A nonempty set in a semimodule is scaled by zero to the singleton containing 0 in the semimodule. -/ lemma zero_smul_set [semiring α] [add_comm_monoid β] [semimodule α β] {s : set β} (h : s.nonempty) : (0 : α) • s = {(0 : β)} := set.ext $ λ x, iff.intro (λ ⟨_, _, hx⟩, mem_singleton_iff.mpr (by { rwa [hx, zero_smul] })) (λ hx, let ⟨_, hs⟩ := h in ⟨_, hs, by { rw mem_singleton_iff at hx; rw [hx, zero_smul] }⟩) lemma mem_inv_smul_set_iff [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a⁻¹ • A ↔ a • x ∈ A := iff.intro (λ ⟨y, hy, h⟩, by rwa [h, ←mul_smul, mul_inv_cancel ha, one_smul]) (λ h, ⟨_, h, by rw [←mul_smul, inv_mul_cancel ha, one_smul]⟩) lemma mem_smul_set_iff_inv_smul_mem [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a • A ↔ a⁻¹ • x ∈ A := by conv_lhs { rw ← inv_inv'' a }; exact (mem_inv_smul_set_iff (inv_ne_zero ha) _ _) end
22b5e2feadbfa66bc7386fd590251cc2cc4782bf
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/topology/sequences.lean
7ff664d7e5f83eb54e56e1561a4c9b2049b14280
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
18,955
lean
/- Copyright (c) 2018 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Patrick Massot -/ import topology.bases import topology.subset_properties import topology.metric_space.basic /-! # Sequences in topological spaces In this file we define sequences in topological spaces and show how they are related to filters and the topology. In particular, we * define the sequential closure of a set and prove that it's contained in the closure, * define a type class "sequential_space" in which closure and sequential closure agree, * define sequential continuity and show that it coincides with continuity in sequential spaces, * provide an instance that shows that every first-countable (and in particular metric) space is a sequential space. * define sequential compactness, prove that compactness implies sequential compactness in first countable spaces, and prove they are equivalent for uniform spaces having a countable uniformity basis (in particular metric spaces). -/ open set filter open_locale topological_space variables {α : Type*} {β : Type*} local notation f ` ⟶ ` limit := tendsto f at_top (𝓝 limit) /-! ### Sequential closures, sequential continuity, and sequential spaces. -/ section topological_space variables [topological_space α] [topological_space β] /-- A sequence converges in the sence of topological spaces iff the associated statement for filter holds. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma topological_space.seq_tendsto_iff {x : ℕ → α} {limit : α} : tendsto x at_top (𝓝 limit) ↔ ∀ U : set α, limit ∈ U → is_open U → ∃ N, ∀ n ≥ N, (x n) ∈ U := (at_top_basis.tendsto_iff (nhds_basis_opens limit)).trans $ by simp only [and_imp, exists_prop, true_and, set.mem_Ici, ge_iff_le, id] /-- The sequential closure of a subset M ⊆ α of a topological space α is the set of all p ∈ α which arise as limit of sequences in M. -/ def sequential_closure (M : set α) : set α := {p | ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ M) ∧ (x ⟶ p)} lemma subset_sequential_closure (M : set α) : M ⊆ sequential_closure M := assume p (_ : p ∈ M), show p ∈ sequential_closure M, from ⟨λ n, p, assume n, ‹p ∈ M›, tendsto_const_nhds⟩ /-- A set `s` is sequentially closed if for any converging sequence `x n` of elements of `s`, the limit belongs to `s` as well. -/ def is_seq_closed (s : set α) : Prop := s = sequential_closure s /-- A convenience lemma for showing that a set is sequentially closed. -/ lemma is_seq_closed_of_def {A : set α} (h : ∀(x : ℕ → α) (p : α), (∀ n : ℕ, x n ∈ A) → (x ⟶ p) → p ∈ A) : is_seq_closed A := show A = sequential_closure A, from subset.antisymm (subset_sequential_closure A) (show ∀ p, p ∈ sequential_closure A → p ∈ A, from (assume p ⟨x, _, _⟩, show p ∈ A, from h x p ‹∀ n : ℕ, ((x n) ∈ A)› ‹(x ⟶ p)›)) /-- The sequential closure of a set is contained in the closure of that set. The converse is not true. -/ lemma sequential_closure_subset_closure (M : set α) : sequential_closure M ⊆ closure M := assume p ⟨x, xM, xp⟩, mem_closure_of_tendsto xp (univ_mem_sets' xM) /-- A set is sequentially closed if it is closed. -/ lemma is_seq_closed_of_is_closed (M : set α) (_ : is_closed M) : is_seq_closed M := suffices sequential_closure M ⊆ M, from set.eq_of_subset_of_subset (subset_sequential_closure M) this, calc sequential_closure M ⊆ closure M : sequential_closure_subset_closure M ... = M : is_closed.closure_eq ‹is_closed M› /-- The limit of a convergent sequence in a sequentially closed set is in that set.-/ lemma mem_of_is_seq_closed {A : set α} (_ : is_seq_closed A) {x : ℕ → α} (_ : ∀ n, x n ∈ A) {limit : α} (_ : (x ⟶ limit)) : limit ∈ A := have limit ∈ sequential_closure A, from show ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ A) ∧ (x ⟶ limit), from ⟨x, ‹∀ n, x n ∈ A›, ‹(x ⟶ limit)›⟩, eq.subst (eq.symm ‹is_seq_closed A›) ‹limit ∈ sequential_closure A› /-- The limit of a convergent sequence in a closed set is in that set.-/ lemma mem_of_is_closed_sequential {A : set α} (_ : is_closed A) {x : ℕ → α} (_ : ∀ n, x n ∈ A) {limit : α} (_ : x ⟶ limit) : limit ∈ A := mem_of_is_seq_closed (is_seq_closed_of_is_closed A ‹is_closed A›) ‹∀ n, x n ∈ A› ‹(x ⟶ limit)› /-- A sequential space is a space in which 'sequences are enough to probe the topology'. This can be formalised by demanding that the sequential closure and the closure coincide. The following statements show that other topological properties can be deduced from sequences in sequential spaces. -/ class sequential_space (α : Type*) [topological_space α] : Prop := (sequential_closure_eq_closure : ∀ M : set α, sequential_closure M = closure M) /-- In a sequential space, a set is closed iff it's sequentially closed. -/ lemma is_seq_closed_iff_is_closed [sequential_space α] {M : set α} : is_seq_closed M ↔ is_closed M := iff.intro (assume _, closure_eq_iff_is_closed.mp (eq.symm (calc M = sequential_closure M : by assumption ... = closure M : sequential_space.sequential_closure_eq_closure M))) (is_seq_closed_of_is_closed M) /-- In a sequential space, a point belongs to the closure of a set iff it is a limit of a sequence taking values in this set. -/ lemma mem_closure_iff_seq_limit [sequential_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ s) ∧ (x ⟶ a) := by { rw ← sequential_space.sequential_closure_eq_closure, exact iff.rfl } /-- A function between topological spaces is sequentially continuous if it commutes with limit of convergent sequences. -/ def sequentially_continuous (f : α → β) : Prop := ∀ (x : ℕ → α), ∀ {limit : α}, (x ⟶ limit) → (f∘x ⟶ f limit) /- A continuous function is sequentially continuous. -/ lemma continuous.to_sequentially_continuous {f : α → β} (_ : continuous f) : sequentially_continuous f := assume x limit (_ : x ⟶ limit), have tendsto f (𝓝 limit) (𝓝 (f limit)), from continuous.tendsto ‹continuous f› limit, show (f ∘ x) ⟶ (f limit), from tendsto.comp this ‹(x ⟶ limit)› /-- In a sequential space, continuity and sequential continuity coincide. -/ lemma continuous_iff_sequentially_continuous {f : α → β} [sequential_space α] : continuous f ↔ sequentially_continuous f := iff.intro (assume _, ‹continuous f›.to_sequentially_continuous) (assume : sequentially_continuous f, show continuous f, from suffices h : ∀ {A : set β}, is_closed A → is_seq_closed (f ⁻¹' A), from continuous_iff_is_closed.mpr (assume A _, is_seq_closed_iff_is_closed.mp $ h ‹is_closed A›), assume A (_ : is_closed A), is_seq_closed_of_def $ assume (x : ℕ → α) p (_ : ∀ n, f (x n) ∈ A) (_ : x ⟶ p), have (f ∘ x) ⟶ (f p), from ‹sequentially_continuous f› x ‹(x ⟶ p)›, show f p ∈ A, from mem_of_is_closed_sequential ‹is_closed A› ‹∀ n, f (x n) ∈ A› ‹(f∘x ⟶ f p)›) end topological_space namespace topological_space namespace first_countable_topology variables [topological_space α] [first_countable_topology α] /-- Every first-countable space is sequential. -/ @[priority 100] -- see Note [lower instance priority] instance : sequential_space α := ⟨show ∀ M, sequential_closure M = closure M, from assume M, suffices closure M ⊆ sequential_closure M, from set.subset.antisymm (sequential_closure_subset_closure M) this, -- For every p ∈ closure M, we need to construct a sequence x in M that converges to p: assume (p : α) (hp : p ∈ closure M), -- Since we are in a first-countable space, the neighborhood filter around `p` has a decreasing -- basis `U` indexed by `ℕ`. let ⟨U, hU ⟩ := (nhds_generated_countable p).has_antimono_basis in -- Since `p ∈ closure M`, there is an element in each `M ∩ U i` have hp : ∀ (i : ℕ), ∃ (y : α), y ∈ M ∧ y ∈ U i, by simpa using (mem_closure_iff_nhds_basis hU.1).mp hp, begin -- The axiom of (countable) choice builds our sequence from the later fact choose u hu using hp, rw forall_and_distrib at hu, -- It clearly takes values in `M` use [u, hu.1], -- and converges to `p` because the basis is decreasing. apply hU.tendsto hu.2, end⟩ end first_countable_topology end topological_space section seq_compact open topological_space topological_space.first_countable_topology variables [topological_space α] /-- A set `s` is sequentially compact if every sequence taking values in `s` has a converging subsequence. -/ def is_seq_compact (s : set α) := ∀ ⦃u : ℕ → α⦄, (∀ n, u n ∈ s) → ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) /-- A space `α` is sequentially compact if every sequence in `α` has a converging subsequence. -/ class seq_compact_space (α : Type*) [topological_space α] : Prop := (seq_compact_univ : is_seq_compact (univ : set α)) lemma is_seq_compact.subseq_of_frequently_in {s : set α} (hs : is_seq_compact s) {u : ℕ → α} (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := let ⟨ψ, hψ, huψ⟩ := extraction_of_frequently_at_top hu, ⟨x, x_in, φ, hφ, h⟩ := hs huψ in ⟨x, x_in, ψ ∘ φ, hψ.comp hφ, h⟩ lemma seq_compact_space.tendsto_subseq [seq_compact_space α] (u : ℕ → α) : ∃ x (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := let ⟨x, _, φ, mono, h⟩ := seq_compact_space.seq_compact_univ (by simp : ∀ n, u n ∈ univ) in ⟨x, φ, mono, h⟩ section first_countable_topology variables [first_countable_topology α] open topological_space.first_countable_topology lemma is_compact.is_seq_compact {s : set α} (hs : is_compact s) : is_seq_compact s := λ u u_in, let ⟨x, x_in, hx⟩ := @hs (map u at_top) _ (le_principal_iff.mpr (univ_mem_sets' u_in : _)) in ⟨x, x_in, tendsto_subseq hx⟩ lemma is_compact.tendsto_subseq' {s : set α} {u : ℕ → α} (hs : is_compact s) (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := hs.is_seq_compact.subseq_of_frequently_in hu lemma is_compact.tendsto_subseq {s : set α} {u : ℕ → α} (hs : is_compact s) (hu : ∀ n, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := hs.is_seq_compact hu @[priority 100] -- see Note [lower instance priority] instance first_countable_topology.seq_compact_of_compact [compact_space α] : seq_compact_space α := ⟨compact_univ.is_seq_compact⟩ lemma compact_space.tendsto_subseq [compact_space α] (u : ℕ → α) : ∃ x (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := seq_compact_space.tendsto_subseq u end first_countable_topology end seq_compact section uniform_space_seq_compact open_locale uniformity open uniform_space prod variables [uniform_space β] {s : set β} lemma lebesgue_number_lemma_seq {ι : Type*} {c : ι → set β} (hs : is_seq_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) (hU : is_countably_generated (𝓤 β)) : ∃ V ∈ 𝓤 β, symmetric_rel V ∧ ∀ x ∈ s, ∃ i, ball x V ⊆ c i := begin classical, obtain ⟨V, hV, Vsymm⟩ : ∃ V : ℕ → set (β × β), (𝓤 β).has_antimono_basis (λ _, true) V ∧ ∀ n, swap ⁻¹' V n = V n, from uniform_space.has_seq_basis hU, clear hU, suffices : ∃ n, ∀ x ∈ s, ∃ i, ball x (V n) ⊆ c i, { cases this with n hn, exact ⟨V n, hV.to_has_basis.mem_of_mem trivial, Vsymm n, hn⟩ }, by_contradiction H, obtain ⟨x, x_in, hx⟩ : ∃ x : ℕ → β, (∀ n, x n ∈ s) ∧ ∀ n i, ¬ ball (x n) (V n) ⊆ c i, { push_neg at H, choose x hx using H, exact ⟨x, forall_and_distrib.mp hx⟩ }, clear H, obtain ⟨x₀, x₀_in, φ, φ_mono, hlim⟩ : ∃ (x₀ ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ (x ∘ φ ⟶ x₀), from hs x_in, clear hs, obtain ⟨i₀, x₀_in⟩ : ∃ i₀, x₀ ∈ c i₀, { rcases hc₂ x₀_in with ⟨_, ⟨i₀, rfl⟩, x₀_in_c⟩, exact ⟨i₀, x₀_in_c⟩ }, clear hc₂, obtain ⟨n₀, hn₀⟩ : ∃ n₀, ball x₀ (V n₀) ⊆ c i₀, { rcases (nhds_basis_uniformity hV.to_has_basis).mem_iff.mp (is_open_iff_mem_nhds.mp (hc₁ i₀) _ x₀_in) with ⟨n₀, _, h⟩, use n₀, rwa ← ball_eq_of_symmetry (Vsymm n₀) at h }, clear hc₁, obtain ⟨W, W_in, hWW⟩ : ∃ W ∈ 𝓤 β, W ○ W ⊆ V n₀, from comp_mem_uniformity_sets (hV.to_has_basis.mem_of_mem trivial), obtain ⟨N, x_φ_N_in, hVNW⟩ : ∃ N, x (φ N) ∈ ball x₀ W ∧ V (φ N) ⊆ W, { obtain ⟨N₁, h₁⟩ : ∃ N₁, ∀ n ≥ N₁, x (φ n) ∈ ball x₀ W, from (tendsto_at_top' (λ (b : ℕ), (x ∘ φ) b) (𝓝 x₀)).mp hlim _ (mem_nhds_left x₀ W_in), obtain ⟨N₂, h₂⟩ : ∃ N₂, V (φ N₂) ⊆ W, { rcases hV.to_has_basis.mem_iff.mp W_in with ⟨N, _, hN⟩, use N, exact subset.trans (hV.decreasing trivial trivial $ φ_mono.id_le _) hN }, have : φ N₂ ≤ φ (max N₁ N₂), from φ_mono.le_iff_le.mpr (le_max_right _ _), exact ⟨max N₁ N₂, h₁ _ (le_max_left _ _), subset.trans (hV.decreasing trivial trivial this) h₂⟩ }, suffices : ball (x (φ N)) (V (φ N)) ⊆ c i₀, from hx (φ N) i₀ this, calc ball (x $ φ N) (V $ φ N) ⊆ ball (x $ φ N) W : preimage_mono hVNW ... ⊆ ball x₀ (V n₀) : ball_subset_of_comp_subset x_φ_N_in hWW ... ⊆ c i₀ : hn₀, end lemma is_seq_compact.totally_bounded (h : is_seq_compact s) : totally_bounded s := begin classical, apply totally_bounded_of_forall_symm, unfold is_seq_compact at h, contrapose! h, rcases h with ⟨V, V_in, V_symm, h⟩, simp_rw [not_subset] at h, have : ∀ (t : set β), finite t → ∃ a, a ∈ s ∧ a ∉ ⋃ y ∈ t, ball y V, { intros t ht, obtain ⟨a, a_in, H⟩ : ∃ a ∈ s, ∀ (x : β), x ∈ t → (x, a) ∉ V, by simpa [ht] using h t, use [a, a_in], intro H', obtain ⟨x, x_in, hx⟩ := mem_bUnion_iff.mp H', exact H x x_in hx }, cases seq_of_forall_finite_exists this with u hu, clear h this, simp [forall_and_distrib] at hu, cases hu with u_in hu, use [u, u_in], clear u_in, intros x x_in φ, intros hφ huφ, obtain ⟨N, hN⟩ : ∃ N, ∀ p q, p ≥ N → q ≥ N → (u (φ p), u (φ q)) ∈ V, from (cauchy_seq_of_tendsto_nhds _ huφ).mem_entourage V_in, specialize hN N (N+1) (le_refl N) (nat.le_succ N), specialize hu (φ $ N+1) (φ N) (hφ $ lt_add_one N), exact hu hN, end protected lemma is_seq_compact.is_compact (h : is_countably_generated $ 𝓤 β) (hs : is_seq_compact s) : is_compact s := begin classical, rw compact_iff_finite_subcover, intros ι U Uop s_sub, rcases lebesgue_number_lemma_seq hs Uop s_sub h with ⟨V, V_in, Vsymm, H⟩, rcases totally_bounded_iff_subset.mp hs.totally_bounded V V_in with ⟨t,t_sub, tfin, ht⟩, have : ∀ x : t, ∃ (i : ι), ball x.val V ⊆ U i, { rintros ⟨x, x_in⟩, exact H x (t_sub x_in) }, choose i hi using this, haveI : fintype t := tfin.fintype, use finset.image i finset.univ, transitivity ⋃ y ∈ t, ball y V, { intros x x_in, specialize ht x_in, rw mem_bUnion_iff at *, simp_rw ball_eq_of_symmetry Vsymm, exact ht }, { apply bUnion_subset_bUnion, intros x x_in, exact ⟨i ⟨x, x_in⟩, finset.mem_image_of_mem _ (finset.mem_univ _), hi ⟨x, x_in⟩⟩ }, end protected lemma uniform_space.compact_iff_seq_compact (h : is_countably_generated $ 𝓤 β) : is_compact s ↔ is_seq_compact s := begin haveI := uniform_space.first_countable_topology h, exact ⟨λ H, H.is_seq_compact, λ H, H.is_compact h⟩ end lemma uniform_space.compact_space_iff_seq_compact_space (H : is_countably_generated $ 𝓤 β) : compact_space β ↔ seq_compact_space β := have key : is_compact univ ↔ is_seq_compact univ := uniform_space.compact_iff_seq_compact H, ⟨λ ⟨h⟩, ⟨key.mp h⟩, λ ⟨h⟩, ⟨key.mpr h⟩⟩ end uniform_space_seq_compact section metric_seq_compact variables [metric_space β] {s : set β} open metric /-- A version of Bolzano-Weistrass: in a metric space, is_compact s ↔ is_seq_compact s -/ lemma metric.compact_iff_seq_compact : is_compact s ↔ is_seq_compact s := uniform_space.compact_iff_seq_compact emetric.uniformity_has_countable_basis /-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ℝ^n$), every bounded sequence has a converging subsequence. This version assumes only that the sequence is frequently in some bounded set. -/ lemma tendsto_subseq_of_frequently_bounded [proper_space β] (hs : bounded s) {u : ℕ → β} (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ b ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 b) := begin have hcs : is_compact (closure s) := compact_iff_closed_bounded.mpr ⟨is_closed_closure, bounded_closure_of_bounded hs⟩, replace hcs : is_seq_compact (closure s), by rwa metric.compact_iff_seq_compact at hcs, have hu' : ∃ᶠ n in at_top, u n ∈ closure s, { apply frequently.mono hu, intro n, apply subset_closure }, exact hcs.subseq_of_frequently_in hu', end /-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ℝ^n$), every bounded sequence has a converging subsequence. -/ lemma tendsto_subseq_of_bounded [proper_space β] (hs : bounded s) {u : ℕ → β} (hu : ∀ n, u n ∈ s) : ∃ b ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 b) := tendsto_subseq_of_frequently_bounded hs $ frequently_of_forall hu lemma metric.compact_space_iff_seq_compact_space : compact_space β ↔ seq_compact_space β := uniform_space.compact_space_iff_seq_compact_space emetric.uniformity_has_countable_basis @[nolint ge_or_gt] -- see Note [nolint_ge] lemma seq_compact.lebesgue_number_lemma_of_metric {ι : Type*} {c : ι → set β} (hs : is_seq_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := begin rcases lebesgue_number_lemma_seq hs hc₁ hc₂ emetric.uniformity_has_countable_basis with ⟨V, V_in, _, hV⟩, rcases uniformity_basis_dist.mem_iff.mp V_in with ⟨δ, δ_pos, h⟩, use [δ, δ_pos], intros x x_in, rcases hV x x_in with ⟨i, hi⟩, use i, have := ball_mono h x, rw ball_eq_ball' at this, exact subset.trans this hi, end end metric_seq_compact
82d87eca5ab27d27bf8758f751403ac9eddfd860
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/quotient_noetherian.lean
2bbef7744a475f9f1715ff367c9fbac44528605c
[ "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
622
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.noetherian import ring_theory.quotient_nilpotent /-! # Noetherian quotient rings and quotient modules > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ instance ideal.quotient.is_noetherian_ring {R : Type*} [comm_ring R] [h : is_noetherian_ring R] (I : ideal R) : is_noetherian_ring (R ⧸ I) := is_noetherian_ring_iff.mpr $ is_noetherian_of_tower R $ submodule.quotient.is_noetherian _
3b4977237c7029ff69bbea7d23a21fe0c7572832
bc3bab676131ea3e06edb46172d92cf30b89311d
/tutorial 4.lean
04c590e345f21f247f90c4911cdb64040896edb9
[]
no_license
enharsha/hello-world
fc13031788876fdab33d28c0834370896e85f356
ef81d688af1aed47ffadf6662b80db5d9eba587d
refs/heads/master
1,597,391,078,827
1,575,926,406,000
1,575,926,406,000
215,125,509
0
0
null
null
null
null
UTF-8
Lean
false
false
868
lean
namespace hidden inductive nat : Type | zero : nat | succ : nat → nat namespace nat def add (m n:nat):nat:= nat.rec_on n m (λ a (add_m_n),succ (add_m_n)) def mult (m n:nat):nat:= nat.rec_on n zero (λ a mult_m_n,add m mult_m_n) def pred (m:nat):nat:= nat.rec_on m zero (λ a pred_m,a) def exp (m n:nat):nat:= nat.rec_on n succ(zero)) (λ a exp_m_n,mult m exp_m_n) end nat inductive list (α : Type u) | nil {} : list | cons : α → list → list namespace list variable {α : Type} notation h :: t := cons h t def append (s t : list α) : list α := list.rec t (λ x l u, x::u) s def length (s:list α) :nat := list.rec s nat.zero (λ x l n,(nat.succ n) ) end list end hidden /-Question 3-/ inductive test : Type |const: nat→ test |var:nat→ test |plus:nat→ nat→ test |times:nat→ nat→ test
f8fe7e41037df5943b618c3adf9f75d90b2f3a96
aa5a655c05e5359a70646b7154e7cac59f0b4132
/stage0/src/Init/Data/List/Control.lean
915a2c85c4f26d24334622014c832a7f9e3753f7
[ "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,506
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Control.Basic import Init.Data.List.Basic namespace List universes u v w u₁ u₂ /- Remark: we can define `mapM`, `mapM₂` and `forM` using `Applicative` instead of `Monad`. Example: ``` def mapM {m : Type u → Type v} [Applicative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β) | [] => pure [] | a::as => List.cons <$> (f a) <*> mapM as ``` However, we consider `f <$> a <*> b` an anti-idiom because the generated code may produce unnecessary closure allocations. Suppose `m` is a `Monad`, and it uses the default implementation for `Applicative.seq`. Then, the compiler expands `f <$> a <*> b <*> c` into something equivalent to ``` (Functor.map f a >>= fun g_1 => Functor.map g_1 b) >>= fun g_2 => Functor.map g_2 c ``` In an ideal world, the compiler may eliminate the temporary closures `g_1` and `g_2` after it inlines `Functor.map` and `Monad.bind`. However, this can easily fail. For example, suppose `Functor.map f a >>= fun g_1 => Functor.map g_1 b` expanded into a match-expression. This is not unreasonable and can happen in many different ways, e.g., we are using a monad that may throw exceptions. Then, the compiler has to decide whether it will create a join-point for the continuation of the match or float it. If the compiler decides to float, then it will be able to eliminate the closures, but it may not be feasible since floating match expressions may produce exponential blowup in the code size. Finally, we rarely use `mapM` with something that is not a `Monad`. Users that want to use `mapM` with `Applicative` should use `mapA` instead. -/ @[specialize] def mapM {m : Type u → Type v} [Monad m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β) | [] => pure [] | a::as => return (← f a) :: (← mapM f as) @[specialize] def mapA {m : Type u → Type v} [Applicative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β) | [] => pure [] | a::as => List.cons <$> f a <*> mapA f as @[specialize] def forM {m : Type u → Type v} [Monad m] {α : Type w} (f : α → m PUnit) : List α → m PUnit | [] => pure ⟨⟩ | h :: t => do f h; forM f t @[specialize] def forA {m : Type u → Type v} [Applicative m] {α : Type w} (f : α → m PUnit) : List α → m PUnit | [] => pure ⟨⟩ | h :: t => f h *> forA f t @[specialize] def filterAuxM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) : List α → List α → m (List α) | [], acc => pure acc | h :: t, acc => do let b ← f h filterAuxM f t (cond b (h :: acc) acc) @[inline] def filterM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) (as : List α) : m (List α) := do let as ← filterAuxM f as [] pure as.reverse @[inline] def filterRevM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) (as : List α) : m (List α) := filterAuxM f as.reverse [] @[inline] def filterMapM {m : Type u → Type v} [Monad m] {α β : Type u} (f : α → m (Option β)) (as : List α) : m (List β) := let rec @[specialize] loop | [], bs => pure bs | a :: as, bs => do match (← f a) with | none => loop as bs | some b => loop as (b::bs) loop as.reverse [] @[specialize] def foldlM {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} : (f : s → α → m s) → (init : s) → List α → m s | f, s, [] => pure s | f, s, a :: as => do let s' ← f s a foldlM f s' as @[specialize] def foldrM {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} : (f : α → s → m s) → (init : s) → List α → m s | f, s, [] => pure s | f, s, a :: as => do let s' ← foldrM f s as f a s' @[specialize] def firstM {m : Type u → Type v} [Monad m] [Alternative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m β | [] => failure | a::as => f a <|> firstM f as @[specialize] def anyM {m : Type → Type u} [Monad m] {α : Type v} (f : α → m Bool) : List α → m Bool | [] => pure false | a::as => do match (← f a) with | true => pure true | false => anyM f as @[specialize] def allM {m : Type → Type u} [Monad m] {α : Type v} (f : α → m Bool) : List α → m Bool | [] => pure true | a::as => do match (← f a) with | true => allM f as | false => pure false @[specialize] def findM? {m : Type → Type u} [Monad m] {α : Type} (p : α → m Bool) : List α → m (Option α) | [] => pure none | a::as => do match (← p a) with | true => pure (some a) | false => findM? p as @[specialize] def findSomeM? {m : Type u → Type v} [Monad m] {α : Type w} {β : Type u} (f : α → m (Option β)) : List α → m (Option β) | [] => pure none | a::as => do match (← f a) with | some b => pure (some b) | none => findSomeM? f as @[inline] protected def forIn {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : List α) (init : β) (f : α → β → m (ForInStep β)) : m β := let rec @[specialize] loop | [], b => pure b | a::as, b => do match (← f a b) with | ForInStep.done b => pure b | ForInStep.yield b => loop as b loop as init instance : ForIn m (List α) α where forIn := List.forIn end List
373d1110c4a2adca7197d4245f42fddff885bae5
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch2/ex0404.lean
8c0213a286bc415856a7fbf83e665ce27e06e96c
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
144
lean
def double : ℕ → ℕ := λ x, x + x def square : ℕ → ℕ := λ x, x * x def do_twice : (ℕ → ℕ) → ℕ → ℕ := λ f x, f (f x)
869346f3d48eb729851ea195ab6b4a449376361a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/ack.lean
851f45af2c8f44101e8fd7de81fd5eef47e01f83
[ "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
650
lean
open nat definition iter (f : nat → nat) (n : nat) : nat := nat.rec_on n (f 1) (λ (n₁ : nat) (r : nat), f r) definition ack (m : nat) : nat → nat := nat.rec_on m nat.succ (λ (m₁ : nat) (r : nat → nat), iter r) theorem ack_0_n (n : nat) : ack 0 n = n + 1 := rfl theorem ack_m_0 (m : nat) : ack (m + 1) 0 = ack m 1 := rfl theorem ack_m_n (m n : nat) : ack (m + 1) (n + 1) = ack m (ack (m + 1) n) := rfl example : ack 3 2 = 29 := rfl example : ack 3 3 = 61 := rfl /- Defining Ack using well founded recursion -/ def Ack : nat → nat → nat | 0 y := y+1 | (x+1) 0 := Ack x 1 | (x+1) (y+1) := Ack x (Ack (x+1) y)
61d162c75a78c115991b7b57b8babe3320c15044
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/algebra/infinite_sum.lean
391e3c6217f20d03442defc0654da512656198ee
[ "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
31,639
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 Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `has_sum.tendsto_sum_nat`. Reference: * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ import logic.function algebra.big_operators data.set.lattice data.finset topology.metric_space.basic topology.algebra.uniform_group topology.algebra.ring topology.algebra.ordered topology.instances.real noncomputable theory open finset filter function classical open_locale topological_space classical variables {α : Type*} {β : Type*} {γ : Type*} section has_sum variables [add_comm_monoid α] [topological_space α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset α` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is still invariant under reordering, and a absolute sum operator. This is based on Mario Carneiro's infinite sum in Metamath. For the definition or many statements, α does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, s.sum f) at_top (𝓝 a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable (f : β → α) : Prop := ∃a, has_sum f a /-- `tsum f` is the sum of `f` it exists, or 0 otherwise -/ def tsum (f : β → α) := if h : summable f then classical.some h else 0 notation `∑` binders `, ` r:(scoped f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma summable.has_sum (ha : summable f) : has_sum f (∑b, f b) := by simp [ha, tsum]; exact some_spec ha lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩ /-- Constant zero function has sum `0` -/ lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 := by simp [has_sum, tendsto_const_nhds] lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : (∑b, f b) = 0 := by simp [tsum, h] /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `s.sum f`. -/ lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (s.sum f) := tendsto_infi' s $ tendsto.congr' (assume t (ht : s ⊆ t), show s.sum f = t.sum f, from sum_subset ht $ assume x _, hf _) tendsto_const_nhds lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (finset.univ.sum f) := has_sum_sum_of_ne_finset_zero $ λ a h, h.elim (mem_univ _) lemma summable_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f := (has_sum_sum_of_ne_finset_zero hf).summable lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : has_sum f (f b) := suffices has_sum f (({b} : finset β).sum f), by simpa using this, has_sum_sum_of_ne_finset_zero $ by simpa [hf] lemma has_sum_ite_eq (b : β) (a : α) : has_sum (λb', if b' = b then a else 0) a := begin convert has_sum_single b _, { exact (if_pos rfl).symm }, assume b' hb', exact if_neg hb' end lemma has_sum_of_iso {j : γ → β} {i : β → γ} (hf : has_sum f a) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : has_sum (f ∘ j) a := have ∀x y, j x = j y → x = y, from assume x y h, have i (j x) = i (j y), by rw [h], by rwa [h₁, h₁] at this, have (λs:finset γ, s.sum (f ∘ j)) = (λs:finset β, s.sum f) ∘ (λs:finset γ, s.image j), from funext $ assume s, (sum_image $ assume x _ y _, this x y).symm, show tendsto (λs:finset γ, s.sum (f ∘ j)) at_top (𝓝 a), by rw [this]; apply hf.comp (tendsto_finset_image_at_top_at_top h₂) lemma has_sum_iff_has_sum_of_iso {j : γ → β} (i : β → γ) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : has_sum (f ∘ j) a ↔ has_sum f a := iff.intro (assume hfj, have has_sum ((f ∘ j) ∘ i) a, from has_sum_of_iso hfj h₂ h₁, by simp [(∘), h₂] at this; assumption) (assume hf, has_sum_of_iso hf h₁ h₂) lemma equiv.has_sum_iff (e : γ ≃ β) : has_sum (f ∘ e) a ↔ has_sum f a := has_sum_iff_has_sum_of_iso e.symm e.left_inv e.right_inv lemma equiv.summable_iff (e : γ ≃ β) : summable (f ∘ e) ↔ summable f := ⟨λ H, (e.has_sum_iff.1 H.has_sum).summable, λ H, (e.has_sum_iff.2 H.has_sum).summable⟩ lemma has_sum_hom (g : α → γ) [add_comm_monoid γ] [topological_space γ] [is_add_monoid_hom g] (h₃ : continuous g) (hf : has_sum f a) : has_sum (g ∘ f) (g a) := have (λs:finset β, s.sum (g ∘ f)) = g ∘ (λs:finset β, s.sum f), from funext $ assume s, s.sum_hom g, show tendsto (λs:finset β, s.sum (g ∘ f)) at_top (𝓝 (g a)), by rw [this]; exact tendsto.comp (continuous_iff_continuous_at.mp h₃ a) hf /-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/ lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) : tendsto (λn:ℕ, (range n).sum f) at_top (𝓝 a) := @tendsto.comp _ _ _ finset.range (λ s : finset ℕ, s.sum f) _ _ _ h tendsto_finset_range lemma has_sum_unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique at_top_ne_bot variable [topological_add_monoid α] lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) := by simp [has_sum, sum_add_distrib]; exact hf.add hg lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) := (hf.has_sum.add hg.has_sum).summable lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, has_sum (f i) (a i)) → has_sum (λb, s.sum $ λi, f i b) (s.sum a) := finset.induction_on s (by simp [has_sum_zero]) (by simp [has_sum.add] {contextual := tt}) lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : summable (λb, s.sum $ λi, f i b) := (has_sum_sum $ assume i hi, (hf i hi).has_sum).summable lemma has_sum.sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a := assume s' hs', let ⟨s, hs, hss', hsc⟩ := nhds_is_closed hs', ⟨u, hu⟩ := mem_at_top_sets.mp $ ha hs, fsts := u.image sigma.fst, snds := λb, u.bind (λp, (if h : p.1 = b then {cast (congr_arg γ h) p.2} else ∅ : finset (γ b))) in have u_subset : u ⊆ fsts.sigma snds, from subset_iff.mpr $ assume ⟨b, c⟩ hu, have hb : b ∈ fsts, from finset.mem_image.mpr ⟨_, hu, rfl⟩, have hc : c ∈ snds b, from mem_bind.mpr ⟨_, hu, by simp; refl⟩, by simp [mem_sigma, hb, hc] , mem_at_top_sets.mpr $ exists.intro fsts $ assume bs (hbs : fsts ⊆ bs), have h : ∀cs : Π b ∈ bs, finset (γ b), ((⋂b (hb : b ∈ bs), (λp:Πb, finset (γ b), p b) ⁻¹' {cs' | cs b hb ⊆ cs' }) ∩ (λp, bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) ⁻¹' s).nonempty, from assume cs, let cs' := λb, (if h : b ∈ bs then cs b h else ∅) ∪ snds b in have sum_eq : bs.sum (λb, (cs' b).sum (λc, f ⟨b, c⟩)) = (bs.sigma cs').sum f, from sum_sigma.symm, have (bs.sigma cs').sum f ∈ s, from hu _ $ finset.subset.trans u_subset $ sigma_mono hbs $ assume b, @finset.subset_union_right (γ b) _ _ _, exists.intro cs' $ by simp [sum_eq, this]; { intros b hb, simp [cs', hb, finset.subset_union_left] }, have tendsto (λp:(Πb:β, finset (γ b)), bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) (⨅b (h : b ∈ bs), at_top.comap (λp, p b)) (𝓝 (bs.sum g)), from tendsto_finset_sum bs $ assume c hc, tendsto_infi' c $ tendsto_infi' hc $ by apply tendsto.comp (hf c) tendsto_comap, have bs.sum g ∈ s, from mem_of_closed_of_tendsto' this hsc $ forall_sets_nonempty_iff_ne_bot.mp $ begin simp only [mem_inf_sets, exists_imp_distrib, forall_and_distrib, and_imp, filter.mem_infi_sets_finset, mem_comap_sets, mem_at_top_sets, and_comm, mem_principal_sets, set.preimage_subset_iff, exists_prop, skolem], intros s₁ s₂ s₃ hs₁ hs₃ p hs₂ p' hp cs hp', have : (⋂b (h : b ∈ bs), (λp:(Πb, finset (γ b)), p b) ⁻¹' {cs' | cs b h ⊆ cs' }) ≤ (⨅b∈bs, p b), from (infi_le_infi $ assume b, infi_le_infi $ assume hb, le_trans (set.preimage_mono $ hp' b hb) (hp b hb)), exact (h _).mono (set.subset.trans (set.inter_subset_inter (le_trans this hs₂) hs₃) hs₁) end, hss' this lemma summable.sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) : summable (λb, ∑c, f ⟨b, c⟩) := (ha.has_sum.sigma (assume b, (hf b).has_sum)).summable lemma has_sum.sigma_of_has_sum [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) : has_sum f a := by simpa [has_sum_unique (hf'.has_sum.sigma hf) ha] using hf'.has_sum end has_sum section has_sum_iff_has_sum_of_iso_ne_zero variables [add_comm_monoid α] [topological_space α] variables {f : β → α} {g : γ → α} {a : α} lemma has_sum.has_sum_of_sum_eq (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f) (hf : has_sum g a) : has_sum f a := suffices at_top.map (λs:finset β, s.sum f) ≤ at_top.map (λs:finset γ, s.sum g), from le_trans this hf, by rw [map_at_top_eq, map_at_top_eq]; from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $ by simp [set.image_subset_iff]; exact hv) lemma has_sum_iff_has_sum (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ v'.sum f = u'.sum g) : has_sum f a ↔ has_sum g a := ⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩ variables (i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0) (j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0) (hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c) (hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b) (hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b) include hi hj hji hij hgj -- FIXME this causes a deterministic timeout with `-T50000` lemma has_sum.has_sum_ne_zero : has_sum g a → has_sum f a := have j_inj : ∀x y (hx : f x ≠ 0) (hy : f y ≠ 0), (j hx = j hy ↔ x = y), from assume x y hx hy, ⟨assume h, have i (hj hx) = i (hj hy), by simp [h], by rwa [hij, hij] at this; assumption, by simp {contextual := tt}⟩, let ii : finset γ → finset β := λu, u.bind $ λc, if h : g c = 0 then ∅ else {i h} in let jj : finset β → finset γ := λv, v.bind $ λb, if h : f b = 0 then ∅ else {j h} in has_sum.has_sum_of_sum_eq $ assume u, exists.intro (ii u) $ assume v hv, exists.intro (u ∪ jj v) $ and.intro (subset_union_left _ _) $ have ∀c:γ, c ∈ u ∪ jj v → c ∉ jj v → g c = 0, from assume c hc hnc, classical.by_contradiction $ assume h : g c ≠ 0, have c ∈ u, from (finset.mem_union.1 hc).resolve_right hnc, have i h ∈ v, from hv $ by simp [mem_bind]; existsi c; simp [h, this], have j (hi h) ∈ jj v, by simp [mem_bind]; existsi i h; simp [h, hi, this], by rw [hji h] at this; exact hnc this, calc (u ∪ jj v).sum g = (jj v).sum g : (sum_subset (subset_union_right _ _) this).symm ... = v.sum _ : sum_bind $ by intros x _ y _ _; by_cases f x = 0; by_cases f y = 0; simp [*]; cc ... = v.sum f : sum_congr rfl $ by intros x hx; by_cases f x = 0; simp [*] lemma has_sum_iff_has_sum_of_ne_zero : has_sum f a ↔ has_sum g a := iff.intro (has_sum.has_sum_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji]) (has_sum.has_sum_ne_zero i hi j hj hji hij hgj) lemma summable_iff_summable_ne_zero : summable g ↔ summable f := exists_congr $ assume a, has_sum_iff_has_sum_of_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji] end has_sum_iff_has_sum_of_iso_ne_zero section has_sum_iff_has_sum_of_bij_ne_zero variables [add_comm_monoid α] [topological_space α] variables {f : β → α} {g : γ → α} {a : α} (i : Π⦃c⦄, g c ≠ 0 → β) (h₁ : ∀⦃c₁ c₂⦄ (h₁ : g c₁ ≠ 0) (h₂ : g c₂ ≠ 0), i h₁ = i h₂ → c₁ = c₂) (h₂ : ∀⦃b⦄, f b ≠ 0 → ∃c (h : g c ≠ 0), i h = b) (h₃ : ∀⦃c⦄ (h : g c ≠ 0), f (i h) = g c) include i h₁ h₂ h₃ lemma has_sum_iff_has_sum_of_ne_zero_bij : has_sum f a ↔ has_sum g a := have hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0, from assume c h, by simp [h₃, h], let j : Π⦃b⦄, f b ≠ 0 → γ := λb h, some $ h₂ h in have hj : ∀⦃b⦄ (h : f b ≠ 0), ∃(h : g (j h) ≠ 0), i h = b, from assume b h, some_spec $ h₂ h, have hj₁ : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0, from assume b h, let ⟨h₁, _⟩ := hj h in h₁, have hj₂ : ∀⦃b⦄ (h : f b ≠ 0), i (hj₁ h) = b, from assume b h, let ⟨h₁, h₂⟩ := hj h in h₂, has_sum_iff_has_sum_of_ne_zero i hi j hj₁ (assume c h, h₁ (hj₁ _) h $ hj₂ _) hj₂ (assume b h, by rw [←h₃ (hj₁ _), hj₂]) lemma summable_iff_summable_ne_zero_bij : summable f ↔ summable g := exists_congr $ assume a, has_sum_iff_has_sum_of_ne_zero_bij @i h₁ h₂ h₃ end has_sum_iff_has_sum_of_bij_ne_zero section tsum variables [add_comm_monoid α] [topological_space α] [t2_space α] variables {f g : β → α} {a a₁ a₂ : α} lemma tsum_eq_has_sum (ha : has_sum f a) : (∑b, f b) = a := has_sum_unique (summable.has_sum ⟨a, ha⟩) ha lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ (∑b, f b) = a := iff.intro tsum_eq_has_sum (assume eq, eq ▸ h.has_sum) @[simp] lemma tsum_zero : (∑b:β, 0:α) = 0 := tsum_eq_has_sum has_sum_zero lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : (∑b, f b) = s.sum f := tsum_eq_has_sum $ has_sum_sum_of_ne_finset_zero hf lemma tsum_fintype [fintype β] (f : β → α) : (∑b, f b) = finset.univ.sum f := tsum_eq_has_sum $ has_sum_fintype f lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : (∑b, f b) = f b := tsum_eq_has_sum $ has_sum_single b hf @[simp] lemma tsum_ite_eq (b : β) (a : α) : (∑b', if b' = b then a else 0) = a := tsum_eq_has_sum (has_sum_ite_eq b a) lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α} (h : ∀{a}, has_sum f a ↔ has_sum g a) : (∑b, f b) = (∑c, g c) := by_cases (assume : ∃a, has_sum f a, let ⟨a, hfa⟩ := this in have hga : has_sum g a, from h.mp hfa, by rw [tsum_eq_has_sum hfa, tsum_eq_has_sum hga]) (assume hf : ¬ summable f, have hg : ¬ summable g, from assume ⟨a, hga⟩, hf ⟨a, h.mpr hga⟩, by simp [tsum, hf, hg]) lemma tsum_eq_tsum_of_ne_zero {f : β → α} {g : γ → α} (i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0) (j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0) (hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c) (hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b) (hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b) : (∑i, f i) = (∑j, g j) := tsum_eq_tsum_of_has_sum_iff_has_sum $ assume a, has_sum_iff_has_sum_of_ne_zero i hi j hj hji hij hgj lemma tsum_eq_tsum_of_ne_zero_bij {f : β → α} {g : γ → α} (i : Π⦃c⦄, g c ≠ 0 → β) (h₁ : ∀⦃c₁ c₂⦄ (h₁ : g c₁ ≠ 0) (h₂ : g c₂ ≠ 0), i h₁ = i h₂ → c₁ = c₂) (h₂ : ∀⦃b⦄, f b ≠ 0 → ∃c (h : g c ≠ 0), i h = b) (h₃ : ∀⦃c⦄ (h : g c ≠ 0), f (i h) = g c) : (∑i, f i) = (∑j, g j) := tsum_eq_tsum_of_has_sum_iff_has_sum $ assume a, has_sum_iff_has_sum_of_ne_zero_bij i h₁ h₂ h₃ lemma tsum_eq_tsum_of_iso (j : γ → β) (i : β → γ) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : (∑c, f (j c)) = (∑b, f b) := tsum_eq_tsum_of_has_sum_iff_has_sum $ assume a, has_sum_iff_has_sum_of_iso i h₁ h₂ lemma tsum_equiv (j : γ ≃ β) : (∑c, f (j c)) = (∑b, f b) := tsum_eq_tsum_of_iso j j.symm (by simp) (by simp) variable [topological_add_monoid α] lemma tsum_add (hf : summable f) (hg : summable g) : (∑b, f b + g b) = (∑b, f b) + (∑b, g b) := tsum_eq_has_sum $ hf.has_sum.add hg.has_sum lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : (∑b, s.sum (λi, f i b)) = s.sum (λi, ∑b, f i b) := tsum_eq_has_sum $ has_sum_sum $ assume i hi, (hf i hi).has_sum lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : (∑p, f p) = (∑b c, f ⟨b, c⟩) := (tsum_eq_has_sum $ h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).symm end tsum section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.neg : has_sum f a → has_sum (λb, - f b) (- a) := has_sum_hom has_neg.neg continuous_neg lemma summable.neg (hf : summable f) : summable (λb, - f b) := hf.has_sum.neg.summable lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) := by { simp [sub_eq_add_neg], exact hf.add hg.neg } lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) := (hf.has_sum.sub hg.has_sum).summable section tsum variables [t2_space α] lemma tsum_neg (hf : summable f) : (∑b, - f b) = - (∑b, f b) := tsum_eq_has_sum $ hf.has_sum.neg lemma tsum_sub (hf : summable f) (hg : summable g) : (∑b, f b - g b) = (∑b, f b) - (∑b, g b) := tsum_eq_has_sum $ hf.has_sum.sub hg.has_sum lemma tsum_eq_zero_add {f : ℕ → α} (hf : summable f) : (∑b, f b) = f 0 + (∑b, f (b + 1)) := begin let f₁ : ℕ → α := λ n, nat.rec (f 0) (λ _ _, 0) n, let f₂ : ℕ → α := λ n, nat.rec 0 (λ k _, f (k+1)) n, have : f = λ n, f₁ n + f₂ n, { ext n, symmetry, cases n, apply add_zero, apply zero_add }, have hf₁ : summable f₁, { fapply summable_sum_of_ne_finset_zero, { exact finset.singleton 0 }, { rintros (_ | n) hn, { exfalso, apply hn, apply finset.mem_singleton_self }, { refl } } }, have hf₂ : summable f₂, { have : f₂ = λ n, f n - f₁ n, ext, rw [eq_sub_iff_add_eq', this], rw [this], apply hf.sub hf₁ }, conv_lhs { rw [this] }, rw [tsum_add hf₁ hf₂, tsum_eq_single 0], { congr' 1, fapply tsum_eq_tsum_of_ne_zero_bij (λ n _, n + 1), { intros _ _ _ _, exact nat.succ_inj }, { rintros (_ | n) h, { contradiction }, { exact ⟨n, h, rfl⟩ } }, { intros, refl }, { apply_instance } }, { rintros (_ | n) hn, { contradiction }, { refl } }, { apply_instance } end end tsum end topological_group section topological_semiring variables [semiring α] [topological_space α] [topological_semiring α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.mul_left (a₂) : has_sum f a₁ → has_sum (λb, a₂ * f b) (a₂ * a₁) := has_sum_hom _ (continuous_const.mul continuous_id) lemma has_sum.mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) := @has_sum_hom _ _ _ _ _ f a₁ (λa, a * a₂) _ _ _ (continuous_id.mul continuous_const) hf lemma summable.mul_left (a) (hf : summable f) : summable (λb, a * f b) := (hf.has_sum.mul_left _).summable lemma summable.mul_right (a) (hf : summable f) : summable (λb, f b * a) := (hf.has_sum.mul_right _).summable section tsum variables [t2_space α] lemma tsum_mul_left (a) (hf : summable f) : (∑b, a * f b) = a * (∑b, f b) := tsum_eq_has_sum $ hf.has_sum.mul_left _ lemma tsum_mul_right (a) (hf : summable f) : (∑b, f b * a) = (∑b, f b) * a := tsum_eq_has_sum $ hf.has_sum.mul_right _ end tsum end topological_semiring section field variables [field α] [topological_space α] [topological_semiring α] {f g : β → α} {a a₁ a₂ : α} lemma has_sum_mul_left_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, a₂ * f b) (a₂ * a₁) := ⟨has_sum.mul_left _, λ H, by simpa [← mul_assoc, inv_mul_cancel h] using H.mul_left a₂⁻¹⟩ lemma has_sum_mul_right_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, f b * a₂) (a₁ * a₂) := by { simp only [mul_comm _ a₂], exact has_sum_mul_left_iff h } lemma summable_mul_left_iff (h : a ≠ 0) : summable f ↔ summable (λb, a * f b) := ⟨λ H, H.mul_left _, λ H, by simpa [← mul_assoc, inv_mul_cancel h] using H.mul_left a⁻¹⟩ lemma summable_mul_right_iff (h : a ≠ 0) : summable f ↔ summable (λb, f b * a) := by { simp only [mul_comm _ a], exact summable_mul_left_iff h } end field section order_topology variables [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto' at_top_ne_bot hf hg $ assume s, sum_le_sum $ assume b _, h b lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁, begin refine (has_sum_iff_has_sum_of_ne_zero_bij (λb _, i b) _ _ _).2 hf, { assume c₁ c₂ h₁ h₂ eq, exact hi eq }, { assume c hc, cases eq : partial_inv i c with b; rw eq at hc, { contradiction }, { rw [partial_inv_of_injective hi] at eq, exact ⟨b, hc, eq⟩ } }, { assume c hc, rw [partial_inv_left hi, option.cases_on'] } end, begin refine has_sum_le (assume c, _) this hg, by_cases c ∈ set.range i, { rcases h with ⟨b, rfl⟩, rw [partial_inv_left hi, option.cases_on'], exact h _ }, { have : partial_inv i c = none := dif_neg h, rw [this, option.cases_on'], exact hs _ h } end lemma tsum_le_tsum_of_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g := has_sum_le_inj i hi hs h hf.has_sum hg.has_sum lemma sum_le_has_sum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : has_sum f a) : s.sum f ≤ a := ge_of_tendsto at_top_ne_bot hf (eventually_at_top.2 ⟨s, λ t hst, sum_le_sum_of_subset_of_nonneg hst $ λ b hbt hbs, hs b hbs⟩) lemma sum_le_tsum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : summable f) : s.sum f ≤ tsum f := sum_le_has_sum s hs hf.has_sum lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : (∑b, f b) ≤ (∑b, g b) := has_sum_le h hf.has_sum hg.has_sum lemma tsum_nonneg (h : ∀ b, 0 ≤ g b) : 0 ≤ (∑b, g b) := begin by_cases hg : summable g, { simpa using tsum_le_tsum h summable_zero hg }, { simp [tsum_eq_zero_of_not_summable hg] } end lemma tsum_nonpos (h : ∀ b, f b ≤ 0) : (∑b, f b) ≤ 0 := begin by_cases hf : summable f, { simpa using tsum_le_tsum h hf summable_zero}, { simp [tsum_eq_zero_of_not_summable hf] } end end order_topology section uniform_group variables [add_comm_group α] [uniform_space α] variables {f g : β → α} {a a₁ a₂ : α} lemma summable_iff_cauchy_seq_finset [complete_space α] : summable f ↔ cauchy_seq (λ (s : finset β), s.sum f) := (cauchy_map_iff_exists_tendsto at_top_ne_bot).symm variable [uniform_add_group α] lemma cauchy_seq_finset_iff_vanishing : cauchy_seq (λ (s : finset β), s.sum f) ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → t.sum f ∈ e) := begin simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot, prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)], rw [tendsto_at_top' (_ : finset β × finset β → α)], split, { assume h e he, rcases h e he with ⟨⟨s₁, s₂⟩, h⟩, use [s₁ ∪ s₂], assume t ht, specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_left_of_le le_sup_right⟩, simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h }, { assume h e he, rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩, rcases h d hd with ⟨s, h⟩, use [(s, s)], rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩, have : t₂.sum f - t₁.sum f = (t₂ \ s).sum f - (t₁ \ s).sum f, { simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm, add_sub_add_right_eq_sub] }, simp only [this], exact hde _ _ (h _ finset.sdiff_disjoint) (h _ finset.sdiff_disjoint) } end variable [complete_space α] lemma summable_iff_vanishing : summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → t.sum f ∈ e) := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing] /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) : summable g := summable_iff_vanishing.2 $ assume e he, let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in ⟨s, assume t ht, have eq : (t.filter (λb, g b = f b)).sum f = t.sum g := calc (t.filter (λb, g b = f b)).sum f = (t.filter (λb, g b = f b)).sum g : finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm) ... = t.sum g : begin refine finset.sum_subset (finset.filter_subset _) _, assume b hbt hb, simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb, exact (h b).resolve_right hb end, eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _) ht⟩ lemma summable.summable_comp_of_injective {i : γ → β} (hf : summable f) (hi : injective i) : summable (f ∘ i) := suffices summable (λb, if b ∈ set.range i then f b else 0), begin refine (summable_iff_summable_ne_zero_bij (λc _, i c) _ _ _).1 this, { assume c₁ c₂ hc₁ hc₂ eq, exact hi eq }, { assume b hb, split_ifs at hb, { rcases h with ⟨c, rfl⟩, exact ⟨c, hb, rfl⟩ }, { contradiction } }, { assume c hc, exact if_pos (set.mem_range_self _) } end, hf.summable_of_eq_zero_or_self $ assume b, by by_cases b ∈ set.range i; simp [h] lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) := ha.summable_comp_of_injective (λ x y hxy, by simpa using hxy) lemma summable.sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : summable (λb, ∑c, f ⟨b, c⟩) := ha.sigma (λ b, ha.sigma_factor b) lemma tsum_sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : (∑p, f p) = (∑b c, f ⟨b, c⟩) := tsum_sigma (λ b, ha.sigma_factor b) ha end uniform_group section cauchy_seq open finset.Ico filter /-- If the extended distance between consequent points of a sequence is estimated by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_edist_le_of_summable [emetric_space α] {f : ℕ → α} (d : ℕ → nnreal) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine emetric.cauchy_seq_iff_nnreal.2 (λ ε εpos, _), -- Actually we need partial sums of `d` to be a Cauchy sequence replace hd : cauchy_seq (λ (n : ℕ), (range n).sum d) := let ⟨_, H⟩ := hd in cauchy_seq_of_tendsto_nhds _ H.tendsto_sum_nat, -- Now we take the same `N` as in one of the definitions of a Cauchy sequence refine (metric.cauchy_seq_iff'.1 hd ε (nnreal.coe_pos.2 εpos)).imp (λ N hN n hn, _), have hsum := hN n hn, -- We simplify the known inequality rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, nnreal.add_sub_cancel'] at hsum, norm_cast at hsum, replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum, rw edist_comm, -- Then use `hf` to simplify the goal to the same form apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (λ k _ _, hf k)), assumption_mod_cast end /-- If the distance between consequent points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_dist_le_of_summable [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine metric.cauchy_seq_iff'.2 (λε εpos, _), replace hd : cauchy_seq (λ (n : ℕ), (range n).sum d) := let ⟨_, H⟩ := hd in cauchy_seq_of_tendsto_nhds _ H.tendsto_sum_nat, refine (metric.cauchy_seq_iff'.1 hd ε εpos).imp (λ N hN n hn, _), have hsum := hN n hn, rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum, calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _ ... ≤ (Ico N n).sum d : dist_le_Ico_sum_of_dist_le hn (λ k _ _, hf k) ... ≤ abs ((Ico N n).sum d) : le_abs_self _ ... < ε : hsum end lemma cauchy_seq_of_summable_dist [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ (λ _, le_refl _) h lemma dist_le_tsum_of_dist_le_of_tendsto [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ ∑ m, d (n + m) := begin refine le_of_tendsto at_top_ne_bot (tendsto_const_nhds.dist ha) (eventually_at_top.2 ⟨n, λ m hnm, _⟩), refine le_trans (dist_le_Ico_sum_of_dist_le hnm (λ k _ _, hf k)) _, rw [sum_Ico_eq_sum_range], refine sum_le_tsum (range _) (λ _ _, le_trans dist_nonneg (hf _)) _, exact hd.summable_comp_of_injective (add_left_injective n) end lemma dist_le_tsum_of_dist_le_of_tendsto₀ [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ tsum d := by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0 lemma dist_le_tsum_dist_of_tendsto [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) (n) : dist (f n) a ≤ ∑ m, dist (f (n+m)) (f (n+m).succ) := show dist (f n) a ≤ ∑ m, (λx, dist (f x) (f x.succ)) (n + m), from dist_le_tsum_of_dist_le_of_tendsto (λ n, dist (f n) (f n.succ)) (λ _, le_refl _) h ha n lemma dist_le_tsum_dist_of_tendsto₀ [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ ∑ n, dist (f n) (f n.succ) := by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0 end cauchy_seq
586ee3bf47c58c5900a66f1f77e5fcbdd997c07f
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Elab/Match.lean
0ee1960efdb3a34e2f0551d235a1c1b9aa76ebe9
[ "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
38,485
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.Match.MatchPatternAttr import Lean.Meta.Match.Match import Lean.Elab.SyntheticMVars import Lean.Elab.App namespace Lean.Elab.Term open Meta /- This modules assumes "match"-expressions use the following syntax. ```lean def matchAlt : Parser := nodeWithAntiquot "matchAlt" `Lean.Parser.Term.matchAlt $ sepBy1 termParser ", " >> darrow >> termParser def matchAlts (optionalFirstBar := true) : Parser := group $ withPosition $ fun pos => (if optionalFirstBar then optional "| " else "| ") >> sepBy1 matchAlt (checkColGe pos.column "alternatives must be indented" >> "|") def matchDiscr := parser! optional (try (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> termParser def «match» := parser!:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` -/ structure MatchAltView := (ref : Syntax) (patterns : Array Syntax) (rhs : Syntax) def mkMatchAltView (ref : Syntax) (matchAlt : Syntax) : MatchAltView := { ref := ref, patterns := matchAlt[0].getSepArgs, rhs := matchAlt[2] } private def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let newStx ← `(let $lhsVar := $discr; $rhs) withMacroExpansion stx newStx $ elabTerm newStx expectedType? private def expandSimpleMatchWithType (stx discr lhsVar type rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let newStx ← `(let $lhsVar : $type := $discr; $rhs) withMacroExpansion stx newStx $ elabTerm newStx expectedType? private def elabDiscrsWitMatchType (discrStxs : Array Syntax) (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr) := do let mut discrs := #[] let mut i := 0 let mut matchType := matchType for discrStx in discrStxs do i := i + 1 matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let discr ← fullApproxDefEq $ elabTermEnsuringType discrStx[1] d trace[Elab.match]! "discr #{i} {discr} : {d}" matchType ← b.instantiate1 discr discrs := discrs.push discr | _ => throwError! "invalid type provided to match-expression, function type with arity #{discrStxs.size} expected" pure discrs private def mkUserNameFor (e : Expr) : TermElabM Name := match e with | Expr.fvar fvarId _ => do pure (← getLocalDecl fvarId).userName | _ => mkFreshBinderName -- `expandNonAtomicDiscrs?` create auxiliary variables with base name `_discr` private def isAuxDiscrName (n : Name) : Bool := n.eraseMacroScopes == `_discr -- See expandNonAtomicDiscrs? private def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do let term := discr[1] match (← isLocalIdent? term) with | some e@(Expr.fvar fvarId _) => let localDecl ← getLocalDecl fvarId if !isAuxDiscrName localDecl.userName then pure e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?` else pure localDecl.value | _ => throwErrorAt discr "unexpected discriminant" private def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr) : TermElabM (Array Expr × Expr × Array MatchAltView) := do let numDiscrs := discrStxs.size if matchOptType.isNone then let rec loop (i : Nat) (discrs : Array Expr) (matchType : Expr) (matchAltViews : Array MatchAltView) := do match i with | 0 => pure (discrs.reverse, matchType, matchAltViews) | i+1 => let discrStx := discrStxs[i] let discr ← elabAtomicDiscr discrStx let discr ← instantiateMVars discr let discrType ← inferType discr let discrType ← instantiateMVars discrType let matchTypeBody ← kabstract matchType discr let userName ← mkUserNameFor discr if discrStx[0].isNone then loop i (discrs.push discr) (Lean.mkForall userName BinderInfo.default discrType matchTypeBody) matchAltViews else let identStx := discrStx[0][0] withLocalDeclD userName discrType fun x => do let eqType ← mkEq discr x withLocalDeclD identStx.getId eqType fun h => do let matchTypeBody := matchTypeBody.instantiate1 x let matchType ← mkForallFVars #[x, h] matchTypeBody let refl ← mkEqRefl discr let discrs := (discrs.push refl).push discr let matchAltViews := matchAltViews.map fun altView => { altView with patterns := altView.patterns.insertAt (i+1) identStx } loop i discrs matchType matchAltViews loop discrStxs.size #[] expectedType matchAltViews else let matchTypeStx := matchOptType[0][1] let matchType ← elabType matchTypeStx let discrs ← elabDiscrsWitMatchType discrStxs matchType expectedType pure (discrs, matchType, matchAltViews) /- nodeWithAntiquot "matchAlt" `Lean.Parser.Term.matchAlt $ sepBy1 termParser ", " >> darrow >> termParser -/ def expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do matchAlts.mapM fun matchAlt => do let patterns ← matchAlt.patterns.mapM expandMacros pure { matchAlt with patterns := patterns } /- Given `stx` a match-expression, return its alternatives. -/ private def getMatchAlts (stx : Syntax) : Array MatchAltView := do let matchAlts := stx[4] let firstVBar := matchAlts[0] let mut ref := firstVBar let mut result := #[] for arg in matchAlts[1].getArgs do if ref.isNone then ref := arg -- The first vertical bar is optional if arg.getKind == `Lean.Parser.Term.matchAlt then result := result.push (mkMatchAltView ref arg) else ref := arg -- current `arg` is a vertical bar pure result /-- Auxiliary annotation used to mark terms marked with the "inaccessible" annotation `.(t)` and `_` in patterns. -/ def mkInaccessible (e : Expr) : Expr := mkAnnotation `_inaccessible e def inaccessible? (e : Expr) : Option Expr := annotation? `_inaccessible e inductive PatternVar | localVar (userName : Name) -- anonymous variables (`_`) are encoded using metavariables | anonymousVar (mvarId : MVarId) instance : ToString PatternVar := ⟨fun | PatternVar.localVar x => toString x | PatternVar.anonymousVar mvarId => s!"?m{mvarId}"⟩ builtin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind /-- Create an auxiliary Syntax node wrapping a fresh metavariable id. We use this kind of Syntax for representing `_` occurring in patterns. The metavariables are created before we elaborate the patterns into `Expr`s. -/ private def mkMVarSyntax : TermElabM Syntax := do let mvarId ← mkFreshId pure $ Syntax.node `MVarWithIdKind #[Syntax.node mvarId #[]] /-- Given a syntax node constructed using `mkMVarSyntax`, return its MVarId -/ private def getMVarSyntaxMVarId (stx : Syntax) : MVarId := stx[0].getKind /-- The elaboration function for `Syntax` created using `mkMVarSyntax`. It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/ @[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? => pure $ mkInaccessible $ mkMVar (getMVarSyntaxMVarId stx) @[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? pure $ mkInaccessible e /- Patterns define new local variables. This module collect them and preprocess `_` occurring in patterns. Recall that an `_` may represent anonymous variables or inaccessible terms that are implied by typing constraints. Thus, we represent them with fresh named holes `?x`. After we elaborate the pattern, if the metavariable remains unassigned, we transform it into a regular pattern variable. Otherwise, it becomes an inaccessible term. Macros occurring in patterns are expanded before the `collectPatternVars` method is executed. The following kinds of Syntax are handled by this module - Constructor applications - Applications of functions tagged with the `[matchPattern]` attribute - Identifiers - Anonymous constructors - Structure instances - Inaccessible terms - Named patterns - Tuple literals - Type ascriptions - Literals: num, string and char -/ namespace CollectPatternVars structure State := (found : NameSet := {}) (vars : Array PatternVar := #[]) abbrev M := StateRefT State TermElabM private def throwCtorExpected {α} : M α := throwError "invalid pattern, constructor or constant marked with '[matchPattern]' expected" private def getNumExplicitCtorParams (ctorVal : ConstructorVal) : TermElabM Nat := forallBoundedTelescope ctorVal.type ctorVal.nparams fun ps _ => do let mut result := 0 for p in ps do let localDecl ← getLocalDecl p.fvarId! if localDecl.binderInfo.isExplicit then result := result+1 pure result private def throwAmbiguous {α} (fs : List Expr) : M α := throwError! "ambiguous pattern, use fully qualified name, possible interpretations {fs}" def resolveId? (stx : Syntax) : M (Option Expr) := match stx with | Syntax.ident _ _ val preresolved => do let rs ← try resolveName val preresolved [] catch _ => pure [] let rs := rs.filter fun ⟨f, projs⟩ => projs.isEmpty let fs := rs.map fun (f, _) => f match fs with | [] => pure none | [f] => pure (some f) | _ => throwAmbiguous fs | _ => throwError "identifier expected" private def throwInvalidPattern {α} : M α := throwError "invalid pattern" namespace CtorApp /- An application in a pattern can be 1- A constructor application The elaborator assumes fields are accessible and inductive parameters are not accessible. 2- A regular application `(f ...)` where `f` is tagged with `[matchPattern]`. The elaborator assumes implicit arguments are not accessible and explicit ones are accessible. -/ structure Context := (funId : Syntax) (ctorVal? : Option ConstructorVal) -- It is `some`, if constructor application (explicit : Bool) (ellipsis : Bool) (paramDecls : Array LocalDecl) (paramDeclIdx : Nat := 0) (namedArgs : Array NamedArg) (args : List Arg) (newArgs : Array Syntax := #[]) instance : Inhabited Context := ⟨⟨arbitrary _, none, false, false, #[], 0, #[], [], #[]⟩⟩ private def isDone (ctx : Context) : Bool := ctx.paramDeclIdx ≥ ctx.paramDecls.size private def finalize (ctx : Context) : M Syntax := do if ctx.namedArgs.isEmpty && ctx.args.isEmpty then let fStx ← `(@$(ctx.funId):ident) pure $ Syntax.mkApp fStx ctx.newArgs else throwError "too many arguments" private def isNextArgAccessible (ctx : Context) : Bool := let i := ctx.paramDeclIdx match ctx.ctorVal? with | some ctorVal => i ≥ ctorVal.nparams -- For constructor applications only fields are accessible | none => if h : i < ctx.paramDecls.size then -- For `[matchPattern]` applications, only explicit parameters are accessible. let d := ctx.paramDecls.get ⟨i, h⟩ d.binderInfo.isExplicit else false private def getNextParam (ctx : Context) : LocalDecl × Context := let i := ctx.paramDeclIdx let d := ctx.paramDecls[i] (d, { ctx with paramDeclIdx := ctx.paramDeclIdx + 1 }) private def pushNewArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) (arg : Arg) : M Context := match arg with | Arg.stx stx => do let stx ← if accessible then collect stx else pure stx pure { ctx with newArgs := ctx.newArgs.push stx } | _ => unreachable! private def processExplicitArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) : M Context := match ctx.args with | [] => if ctx.ellipsis then do let hole ← `(_) pushNewArg collect accessible ctx (Arg.stx hole) else throwError! "explicit parameter is missing, unused named arguments {ctx.namedArgs.map fun narg => narg.name}" | arg::args => do let ctx := { ctx with args := args } pushNewArg collect accessible ctx arg private def processImplicitArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) : M Context := if ctx.explicit then processExplicitArg collect accessible ctx else do let hole ← `(_) pushNewArg collect accessible ctx (Arg.stx hole) private partial def processCtorAppAux (collect : Syntax → M Syntax) (ctx : Context) : M Syntax := do if isDone ctx then finalize ctx else let accessible := isNextArgAccessible ctx let (d, ctx) := getNextParam ctx match ctx.namedArgs.findIdx? fun namedArg => namedArg.name == d.userName with | some idx => let arg := ctx.namedArgs[idx] let ctx := { ctx with namedArgs := ctx.namedArgs.eraseIdx idx } let ctx ← pushNewArg collect accessible ctx arg.val processCtorAppAux collect ctx | none => let ctx ← match d.binderInfo with | BinderInfo.implicit => processImplicitArg collect accessible ctx | BinderInfo.instImplicit => processImplicitArg collect accessible ctx | _ => processExplicitArg collect accessible ctx processCtorAppAux collect ctx def processCtorApp (collect : Syntax → M Syntax) (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) : M Syntax := do let args := args.toList let (fId, explicit) ← match_syntax f with | `($fId:ident) => pure (fId, false) | `(@$fId:ident) => pure (fId, true) | _ => throwError "identifier expected" let some (Expr.const fName _ _) ← resolveId? fId | throwCtorExpected let fInfo ← getConstInfo fName forallTelescopeReducing fInfo.type fun xs _ => do let paramDecls ← xs.mapM getFVarLocalDecl match fInfo with | ConstantInfo.ctorInfo val => processCtorAppAux collect { funId := fId, explicit := explicit, ctorVal? := val, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } | _ => let env ← getEnv if hasMatchPatternAttribute env fName then processCtorAppAux collect { funId := fId, explicit := explicit, ctorVal? := none, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } else throwCtorExpected end CtorApp def processCtorApp (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do let (f, namedArgs, args, ellipsis) ← liftM $ expandApp stx true CtorApp.processCtorApp collect f namedArgs args ellipsis def processCtor (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do CtorApp.processCtorApp collect stx #[] #[] false private def processVar (idStx : Syntax) : M Syntax := do unless idStx.isIdent do throwErrorAt idStx "identifier expected" let id := idStx.getId unless id.eraseMacroScopes.isAtomic do throwError "invalid pattern variable, must be atomic" let s ← get if s.found.contains id then throwError! "invalid pattern, variable '{id}' occurred more than once" modify fun s => { s with vars := s.vars.push (PatternVar.localVar id), found := s.found.insert id } pure idStx /- Check whether `stx` is a pattern variable or constructor-like (i.e., constructor or constant tagged with `[matchPattern]` attribute) -/ private def processId (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do let env ← getEnv match (← resolveId? stx) with | none => processVar stx | some f => match f with | Expr.const fName _ _ => match env.find? fName with | some (ConstantInfo.ctorInfo _) => processCtor collect stx | some _ => if hasMatchPatternAttribute env fName then processCtor collect stx else processVar stx | none => throwCtorExpected | _ => processVar stx private def nameToPattern : Name → TermElabM Syntax | Name.anonymous => `(Name.anonymous) | Name.str p s _ => do let p ← nameToPattern p; `(Name.str $p $(quote s) _) | Name.num p n _ => do let p ← nameToPattern p; `(Name.num $p $(quote n) _) private def quotedNameToPattern (stx : Syntax) : TermElabM Syntax := match stx[0].isNameLit? with | some val => nameToPattern val | none => throwIllFormedSyntax partial def collect : Syntax → M Syntax | stx@(Syntax.node k args) => withRef stx $ withFreshMacroScope do if k == `Lean.Parser.Term.app then processCtorApp collect stx else if k == `Lean.Parser.Term.anonymousCtor then let elems ← args[1].getArgs.mapSepElemsM collect pure $ Syntax.node k (args.set! 1 $ mkNullNode elems) else if k == `Lean.Parser.Term.structInst then /- { " >> optional (try (termParser >> " with ")) >> sepBy structInstField ", " true >> optional ".." >> optional (" : " >> termParser) >> " }" -/ let withMod := args[1] unless withMod.isNone do throwErrorAt withMod "invalid struct instance pattern, 'with' is not allowed in patterns" let fields := args[2].getArgs let fields ← fields.mapSepElemsM fun field => do -- parser! structInstLVal >> " := " >> termParser let newVal ← collect field[3] -- `structInstLVal` has arity 2 pure $ field.setArg 3 newVal pure $ Syntax.node k (args.set! 2 $ mkNullNode fields) else if k == `Lean.Parser.Term.hole then let r ← mkMVarSyntax modify fun s => { s with vars := s.vars.push $ PatternVar.anonymousVar $ getMVarSyntaxMVarId r } pure r else if k == `Lean.Parser.Term.paren then let arg := args[1] if arg.isNone then pure stx -- `()` else let t := arg[0] let s := arg[1] if s.isNone || s[0].getKind == `Lean.Parser.Term.typeAscription then -- Ignore `s`, since it empty or it is a type ascription let t ← collect t let arg := arg.setArg 0 t pure $ Syntax.node k (args.set! 1 arg) else -- Tuple literal is a constructor let t ← collect t let arg := arg.setArg 0 t let tupleTail := s[0] let tupleTailElems := tupleTail[1].getArgs let tupleTailElems ← tupleTailElems.mapSepElemsM collect let tupleTail := tupleTail.setArg 1 $ mkNullNode tupleTailElems let s := s.setArg 0 tupleTail let arg := arg.setArg 1 s pure $ Syntax.node k (args.set! 1 arg) else if k == `Lean.Parser.Term.explicitUniv then processCtor collect stx[0] else if k == `Lean.Parser.Term.namedPattern then /- Recall that def namedPattern := check... >> tparser! "@" >> termParser -/ let id := stx[0] processVar id let pat := stx[2] let pat ← collect pat `(namedPattern $id $pat) else if k == `Lean.Parser.Term.inaccessible then pure stx else if k == strLitKind then pure stx else if k == numLitKind then pure stx else if k == charLitKind then pure stx else if k == `Lean.Parser.Term.quotedName then /- Quoted names have an elaboration function associated with them, and they will not be macro expanded. Note that macro expansion is not a good option since it produces a term using the smart constructors `Name.mkStr`, `Name.mkNum` instead of the constructors `Name.str` and `Name.num` -/ quotedNameToPattern stx else if k == choiceKind then throwError "invalid pattern, notation is ambiguous" else throwInvalidPattern | stx@(Syntax.ident _ _ _ _) => processId collect stx | stx => throwInvalidPattern def main (alt : MatchAltView) : M MatchAltView := do let patterns ← alt.patterns.mapM fun p => do trace[Elab.match]! "collecting variables at pattern: {p}" collect p pure { alt with patterns := patterns } end CollectPatternVars private def collectPatternVars (alt : MatchAltView) : TermElabM (Array PatternVar × MatchAltView) := do let (alt, s) ← (CollectPatternVars.main alt).run {} pure (s.vars, alt) /- Return the pattern variables in the given pattern. Remark: this method is not used here, but in other macros (e.g., at `Do.lean`). -/ def getPatternVars (patternStx : Syntax) : TermElabM (Array PatternVar) := do let patternStx ← liftMacroM $ expandMacros patternStx let (_, s) ← (CollectPatternVars.collect patternStx).run {} pure s.vars def getPatternsVars (patterns : Array Syntax) : TermElabM (Array PatternVar) := do let collect : CollectPatternVars.M Unit := do for pattern in patterns do CollectPatternVars.collect (← liftMacroM $ expandMacros pattern) pure () let (_, s) ← collect.run {} pure s.vars /- We convert the collected `PatternVar`s intro `PatternVarDecl` -/ inductive PatternVarDecl /- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable when it is not assigned during pattern elaboration. -/ | anonymousVar (mvarId : MVarId) (fvarId : FVarId) | localVar (fvarId : FVarId) private partial def withPatternVars {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : TermElabM α := let rec loop (i : Nat) (decls : Array PatternVarDecl) := do if h : i < pVars.size then match pVars.get ⟨i, h⟩ with | PatternVar.anonymousVar mvarId => let type ← mkFreshTypeMVar let userName ← mkFreshBinderName withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!)) | PatternVar.localVar userName => let type ← mkFreshTypeMVar withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!)) else /- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`. Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/ decls.forM fun decl => match decl with | PatternVarDecl.anonymousVar mvarId fvarId => do let type ← inferType (mkFVar fvarId) mkFreshExprMVarWithId mvarId type pure () | _ => pure () k decls loop 0 #[] private def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : TermElabM (Array Expr × Expr) := do let mut patterns := #[] let mut matchType := matchType for patternStx in patternStxs do matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let pattern ← elabTermEnsuringType patternStx d matchType := b.instantiate1 pattern patterns := patterns.push pattern | _ => throwError "unexpected match type" pure (patterns, matchType) def finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := do let mut decls := #[] for pdecl in patternVarDecls do match pdecl with | PatternVarDecl.localVar fvarId => let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | PatternVarDecl.anonymousVar mvarId fvarId => let e ← instantiateMVars (mkMVar mvarId); trace[Elab.match]! "finalizePatternDecls: mvarId: {mvarId} := {e}, fvar: {mkFVar fvarId}" match e with | Expr.mvar newMVarId _ => /- Metavariable was not assigned, or assigned to another metavariable. So, we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/ assignExprMVar newMVarId (mkFVar fvarId) trace[Elab.match]! "finalizePatternDecls: {mkMVar newMVarId} := {mkFVar fvarId}" let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | _ => pure () pure decls open Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult) namespace ToDepElimPattern structure State := (found : NameSet := {}) (localDecls : Array LocalDecl) (newLocals : NameSet := {}) abbrev M := StateRefT State TermElabM private def alreadyVisited (fvarId : FVarId) : M Bool := do let s ← get pure $ s.found.contains fvarId private def markAsVisited (fvarId : FVarId) : M Unit := modify fun s => { s with found := s.found.insert fvarId } private def throwInvalidPattern {α} (e : Expr) : M α := throwError! "invalid pattern {indentExpr e}" /- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/ private def mkLocalDeclFor (mvar : Expr) : M Pattern := do let mvarId := mvar.mvarId! let s ← get match (← getExprMVarAssignment? mvarId) with | some val => pure $ Pattern.inaccessible val | none => let fvarId ← mkFreshId let type ← inferType mvar /- HACK: `fvarId` is not in the scope of `mvarId` If this generates problems in the future, we should update the metavariable declarations. -/ assignExprMVar mvarId (mkFVar fvarId) let userName ← liftM $ mkFreshBinderName let newDecl := LocalDecl.cdecl (arbitrary _) fvarId userName type BinderInfo.default; modify fun s => { s with newLocals := s.newLocals.insert fvarId, localDecls := match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with | none => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar` | some i => s.localDecls.insertAt i newDecl } pure $ Pattern.var fvarId partial def main (e : Expr) : M Pattern := do let isLocalDecl (fvarId : FVarId) : M Bool := do let s ← get pure $ s.localDecls.any fun d => d.fvarId == fvarId let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do if (← alreadyVisited fvarId) then pure $ Pattern.inaccessible e else markAsVisited fvarId pure $ Pattern.var e.fvarId! let mkInaccessible (e : Expr) : M Pattern := do match e with | Expr.fvar fvarId _ => if (← isLocalDecl fvarId) then mkPatternVar fvarId e else pure $ Pattern.inaccessible e | _ => pure $ Pattern.inaccessible e match inaccessible? e with | some t => mkInaccessible t | none => match e.arrayLit? with | some (α, lits) => let ps ← lits.mapM main; pure $ Pattern.arrayLit α ps | none => if e.isAppOfArity `namedPattern 3 then let p ← main $ e.getArg! 2; match e.getArg! 1 with | Expr.fvar fvarId _ => pure $ Pattern.as fvarId p | _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" else if e.isNatLit || e.isStringLit || e.isCharLit then pure $ Pattern.val e else if e.isFVar then let fvarId := e.fvarId! unless(← isLocalDecl fvarId) do throwInvalidPattern e mkPatternVar fvarId e else if e.isMVar then mkLocalDeclFor e else let newE ← whnf e if newE != e then main newE else matchConstCtor e.getAppFn (fun _ => throwInvalidPattern e) fun v us => do let args := e.getAppArgs unless args.size == v.nparams + v.nfields do throwInvalidPattern e let params := args.extract 0 v.nparams let fields := args.extract v.nparams args.size let fields ← fields.mapM main pure $ Pattern.ctor v.name us params.toList fields.toList end ToDepElimPattern def withDepElimPatterns {α} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl → Array Pattern → TermElabM α) : TermElabM α := do let (patterns, s) ← (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls } let localDecls ← s.localDecls.mapM fun d => instantiateLocalDeclMVars d /- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/ let lctx ← getLCtx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) $ k localDecls patterns private def withElaboratedLHS {α} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr) (k : AltLHS → Expr → TermElabM α) : TermElabM α := do let (patterns, matchType) ← withSynthesize $ elabPatterns patternStxs matchType let localDecls ← finalizePatternDecls patternVarDecls let patterns ← patterns.mapM instantiateMVars withDepElimPatterns localDecls patterns fun localDecls patterns => k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : TermElabM (AltLHS × Expr) := withRef alt.ref do let (patternVars, alt) ← collectPatternVars alt trace[Elab.match]! "patternVars: {patternVars}" withPatternVars patternVars fun patternVarDecls => do withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do let rhs ← elabTermEnsuringType alt.rhs matchType let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr let rhs ← if xs.isEmpty then pure $ mkSimpleThunk rhs else mkLambdaFVars xs rhs trace[Elab.match]! "rhs: {rhs}" pure (altLHS, rhs) def mkMatcher (elimName : Name) (matchType : Expr) (numDiscrs : Nat) (lhss : List AltLHS) : TermElabM MatcherResult := liftMetaM $ Meta.Match.mkMatcher elimName matchType numDiscrs lhss def reportMatcherResultErrors (result : MatcherResult) : TermElabM Unit := do -- TODO: improve error messages unless result.counterExamples.isEmpty do throwError! "missing cases:\n{Meta.Match.counterExamplesToMessageData result.counterExamples}" unless result.unusedAltIdxs.isEmpty do throwError! "unused alternatives: {result.unusedAltIdxs.map fun idx => s!"#{idx+1}"}" private def elabMatchAux (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr) : TermElabM Expr := do let (discrs, matchType, altViews) ← elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType let matchAlts ← liftMacroM $ expandMacrosInPatterns altViews trace[Elab.match]! "matchType: {matchType}" let alts ← matchAlts.mapM $ fun alt => elabMatchAltView alt matchType /- We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be able to elaborate examples such as: ``` def f (x : Nat) : Option Nat := none def g (xs : List (Nat × Nat)) : IO Unit := xs.forM fun x => match f x.fst with | _ => pure () ``` If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because the type of `x` is only available adfer we proces the last argument of `List.forM`. -/ synthesizeSyntheticMVars /- We apply pending default types to make sure we can process examples such as ``` let (a, b) := (0, 0) ``` -/ synthesizeUsingDefault let rhss := alts.map Prod.snd let matchType ← instantiateMVars matchType let altLHSS ← alts.toList.mapM fun alt => do let altLHS ← Match.instantiateAltLHSMVars alt.1 withRef altLHS.ref do for d in altLHS.fvarDecls do if d.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do throwError! "invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}" for p in altLHS.patterns do if p.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do throwError! "invalid match-expression, pattern contains metavariables{indentExpr (← p.toExpr)}" pure altLHS let numDiscrs := discrs.size let matcherName ← mkAuxName `match let matcherResult ← mkMatcher matcherName matchType numDiscrs altLHSS let motive ← forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType reportMatcherResultErrors matcherResult let r := mkApp matcherResult.matcher motive let r := mkAppN r discrs let r := mkAppN r rhss trace[Elab.match]! "result: {r}" pure r private def getDiscrs (matchStx : Syntax) : Array Syntax := matchStx[1].getSepArgs private def getMatchOptType (matchStx : Syntax) : Syntax := matchStx[2] private def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) := let matchOptType := getMatchOptType matchStx; if matchOptType.isNone then do let discrs := getDiscrs matchStx; let allLocal ← discrs.allM fun discr => Option.isSome <$> isLocalIdent? discr[1] if allLocal then pure none else let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) := do match discrs with | [] => let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx ", "); pure (matchStx.setArg 1 discrs) | discr :: discrs => -- Recall that -- matchDiscr := parser! optional (ident >> ":") >> termParser let term := discr[1] match (← isLocalIdent? term) with | some _ => loop discrs (discrsNew.push discr) | none => withFreshMacroScope do let d ← `(_discr); unless isAuxDiscrName d.getId do -- Use assertion? throwError "unexpected internal auxiliary discriminant name" let discrNew := discr.setArg 1 d; let r ← loop discrs (discrsNew.push discrNew) `(let _discr := $term; $r) pure (some (← loop discrs.toList #[])) else -- We do not pull non atomic discriminants when match type is provided explicitly by the user pure none private def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => pure expectedType | none => mkFreshTypeMVar private def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do -- We don't wait for the discriminants types when match type is provided by user if getMatchOptType matchStx $.isNone then let discrs := getDiscrs matchStx for discr in discrs do let term := discr[1] match (← isLocalIdent? term) with | none => throwErrorAt discr "unexpected discriminant" -- see `expandNonAtomicDiscrs? | some d => let dType ← inferType d trace[Elab.match]! "discr {d} : {dType}" tryPostponeIfMVar dType /- We (try to) elaborate a `match` only when the expected type is available. If the `matchType` has not been provided by the user, we also try to postpone elaboration if the type of a discriminant is not available. That is, it is of the form `(?m ...)`. We use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables. This is a standard trick we use in the elaborator, and it is also used to elaborate structure instances. Suppose, we are trying to elaborate ``` match g x with | ... => ... ``` `expandNonAtomicDiscrs?` converts it intro ``` let _discr := g x match _discr with | ... => ... ``` Thus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`. Note that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`. This elaboration technique is needed to elaborate terms such as: ```lean xs.filter fun (a, b) => a > b ``` which are syntax sugar for ```lean List.filter (fun p => match p with | (a, b) => a > b) xs ``` When we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet. -/ private def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? tryPostponeIfDiscrTypeIsMVar matchStx match expectedType? with | some expectedType => pure expectedType | none => mkFreshTypeMVar /- ``` parser!:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` Remark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`. -/ private def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← waitExpectedTypeAndDiscrs stx expectedType? let discrStxs := (getDiscrs stx).map fun d => d let altViews := getMatchAlts stx let matchOptType := getMatchOptType stx elabMatchAux discrStxs altViews matchOptType expectedType -- parser! "match " >> sepBy1 termParser ", " >> optType >> " with " >> matchAlts @[builtinTermElab «match»] def elabMatch : TermElab := fun stx expectedType? => match_syntax stx with | `(match $discr:term with $y:ident => $rhs:term) => expandSimpleMatch stx discr y rhs expectedType? | `(match $discr:term with | $y:ident => $rhs:term) => expandSimpleMatch stx discr y rhs expectedType? | `(match $discr:term : $type with $y:ident => $rhs:term) => expandSimpleMatchWithType stx discr y type rhs expectedType? | `(match $discr:term : $type with | $y:ident => $rhs:term) => expandSimpleMatchWithType stx discr y type rhs expectedType? | _ => do match (← expandNonAtomicDiscrs? stx) with | some stxNew => withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? | none => let discrs := getDiscrs stx; let matchOptType := getMatchOptType stx; if !matchOptType.isNone && discrs.any fun d => !d[0].isNone then throwErrorAt matchOptType "match expected type should not be provided when discriminants with equality proofs are used" elabMatchCore stx expectedType? @[builtinInit] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.match; pure () -- parser!:leadPrec "nomatch " >> termParser @[builtinTermElab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? => match_syntax stx with | `(nomatch $discrExpr) => do let expectedType ← waitExpectedType expectedType? let discr := Syntax.node `Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr] elabMatchAux #[discr] #[] mkNullNode expectedType | _ => throwUnsupportedSyntax end Term end Elab end Lean
09a1a2e998015a70f9b591c65153c0258449f6d8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/concrete_category/reflects_isomorphisms_auto.lean
f6446c5580f9d87f6ad3ca22cb223b9568d1f311
[]
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,783
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.concrete_category.basic import Mathlib.category_theory.reflects_isomorphisms import Mathlib.PostPort universes u u_1 u_2 namespace Mathlib /-! A `forget₂ C D` forgetful functor between concrete categories `C` and `D` whose forgetful functors both reflect isomorphisms, itself reflects isomorphisms. -/ protected instance category_theory.forget.category_theory.reflects_isomorphisms : category_theory.reflects_isomorphisms (category_theory.forget (Type u)) := category_theory.reflects_isomorphisms.mk fun (X Y : Type u) (f : X ⟶ Y) (i : category_theory.is_iso (category_theory.functor.map (category_theory.forget (Type u)) f)) => i /-- A `forget₂ C D` forgetful functor between concrete categories `C` and `D` where `forget C` reflects isomorphisms, itself reflects isomorphisms. -/ protected instance category_theory.forget₂.category_theory.reflects_isomorphisms (C : Type (u + 1)) [category_theory.category C] [category_theory.concrete_category C] (D : Type (u + 1)) [category_theory.category D] [category_theory.concrete_category D] [category_theory.has_forget₂ C D] [category_theory.reflects_isomorphisms (category_theory.forget C)] : category_theory.reflects_isomorphisms (category_theory.forget₂ C D) := category_theory.reflects_isomorphisms.mk fun (X Y : C) (f : X ⟶ Y) (i : category_theory.is_iso (category_theory.functor.map (category_theory.forget₂ C D) f)) => category_theory.is_iso_of_reflects_iso f (category_theory.forget C) end Mathlib
afd7385cc26ad3de880b925214d2f7f7a1166b7c
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/measure/complex_lebesgue.lean
65712d77cba8b46fb7ef47900094b775ff3088de
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
1,589
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 measure_theory.measure.lebesgue /-! # Lebesgue measure on `ℂ` In this file we define Lebesgue measure on `ℂ`. Since `ℂ` is defined as a `structure` as the push-forward of the volume on `ℝ²` under the natural isomorphism. There are (at least) two frequently used ways to represent `ℝ²` in `mathlib`: `ℝ × ℝ` and `fin 2 → ℝ`. We define measurable equivalences (`measurable_equiv`) to both types and prove that both of them are volume preserving (in the sense of `measure_theory.measure_preserving`). -/ open measure_theory noncomputable theory namespace complex /-- Lebesgue measure on `ℂ`. -/ instance measure_space : measure_space ℂ := ⟨measure.map basis_one_I.equiv_fun.symm volume⟩ /-- Measurable equivalence between `ℂ` and `ℝ² = fin 2 → ℝ`. -/ def measurable_equiv_pi : ℂ ≃ᵐ (fin 2 → ℝ) := basis_one_I.equiv_fun.to_continuous_linear_equiv.to_homeomorph.to_measurable_equiv /-- Measurable equivalence between `ℂ` and `ℝ × ℝ`. -/ def measurable_equiv_real_prod : ℂ ≃ᵐ (ℝ × ℝ) := equiv_real_prodₗ.to_homeomorph.to_measurable_equiv lemma volume_preserving_equiv_pi : measure_preserving measurable_equiv_pi := (measurable_equiv_pi.symm.measurable.measure_preserving _).symm lemma volume_preserving_equiv_real_prod : measure_preserving measurable_equiv_real_prod := (volume_preserving_fin_two_arrow ℝ).comp volume_preserving_equiv_pi end complex
b92da5415624fedeab360f77bb065f5823a900bb
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/perm/fin.lean
8873c22971ebbe9de9a3c8dd4d0233a3c6ba56ee
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
10,757
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import group_theory.perm.cycle_type import group_theory.perm.option import logic.equiv.fin import logic.equiv.fintype /-! # Permutations of `fin n` -/ open equiv /-- Permutations of `fin (n + 1)` are equivalent to fixing a single `fin (n + 1)` and permuting the remaining with a `perm (fin n)`. The fixed `fin (n + 1)` is swapped with `0`. -/ def equiv.perm.decompose_fin {n : ℕ} : perm (fin n.succ) ≃ fin n.succ × perm (fin n) := ((equiv.perm_congr $ fin_succ_equiv n).trans equiv.perm.decompose_option).trans (equiv.prod_congr (fin_succ_equiv n).symm (equiv.refl _)) @[simp] lemma equiv.perm.decompose_fin_symm_of_refl {n : ℕ} (p : fin (n + 1)) : equiv.perm.decompose_fin.symm (p, equiv.refl _) = swap 0 p := by simp [equiv.perm.decompose_fin, equiv.perm_congr_def] @[simp] lemma equiv.perm.decompose_fin_symm_of_one {n : ℕ} (p : fin (n + 1)) : equiv.perm.decompose_fin.symm (p, 1) = swap 0 p := equiv.perm.decompose_fin_symm_of_refl p @[simp] lemma equiv.perm.decompose_fin_symm_apply_zero {n : ℕ} (p : fin (n + 1)) (e : perm (fin n)) : equiv.perm.decompose_fin.symm (p, e) 0 = p := by simp [equiv.perm.decompose_fin] @[simp] lemma equiv.perm.decompose_fin_symm_apply_succ {n : ℕ} (e : perm (fin n)) (p : fin (n + 1)) (x : fin n) : equiv.perm.decompose_fin.symm (p, e) x.succ = swap 0 p (e x).succ := begin refine fin.cases _ _ p, { simp [equiv.perm.decompose_fin, equiv_functor.map] }, { intros i, by_cases h : i = e x, { simp [h, equiv.perm.decompose_fin, equiv_functor.map] }, { have h' : some (e x) ≠ some i := λ H, h (option.some_injective _ H).symm, have h'' : (e x).succ ≠ i.succ := λ H, h (fin.succ_injective _ H).symm, simp [h, h'', fin.succ_ne_zero, equiv.perm.decompose_fin, equiv_functor.map, swap_apply_of_ne_of_ne, swap_apply_of_ne_of_ne (option.some_ne_none (e x)) h'] } } end @[simp] lemma equiv.perm.decompose_fin_symm_apply_one {n : ℕ} (e : perm (fin (n + 1))) (p : fin (n + 2)) : equiv.perm.decompose_fin.symm (p, e) 1 = swap 0 p (e 0).succ := by rw [← fin.succ_zero_eq_one, equiv.perm.decompose_fin_symm_apply_succ e p 0] @[simp] lemma equiv.perm.decompose_fin.symm_sign {n : ℕ} (p : fin (n + 1)) (e : perm (fin n)) : perm.sign (equiv.perm.decompose_fin.symm (p, e)) = ite (p = 0) 1 (-1) * perm.sign e := by { refine fin.cases _ _ p; simp [equiv.perm.decompose_fin, fin.succ_ne_zero] } /-- The set of all permutations of `fin (n + 1)` can be constructed by augmenting the set of permutations of `fin n` by each element of `fin (n + 1)` in turn. -/ lemma finset.univ_perm_fin_succ {n : ℕ} : @finset.univ (perm $ fin n.succ) _ = (finset.univ : finset $ fin n.succ × perm (fin n)).map equiv.perm.decompose_fin.symm.to_embedding := (finset.univ_map_equiv_to_embedding _).symm section cycle_range /-! ### `cycle_range` section Define the permutations `fin.cycle_range i`, the cycle `(0 1 2 ... i)`. -/ open equiv.perm lemma fin_rotate_succ {n : ℕ} : fin_rotate n.succ = decompose_fin.symm (1, fin_rotate n) := begin ext i, cases n, { simp }, refine fin.cases _ (λ i, _) i, { simp }, rw [coe_fin_rotate, decompose_fin_symm_apply_succ, if_congr (i.succ_eq_last_succ) rfl rfl], split_ifs with h, { simp [h] }, { rw [fin.coe_succ, function.injective.map_swap fin.coe_injective, fin.coe_succ, coe_fin_rotate, if_neg h, fin.coe_zero, fin.coe_one, swap_apply_of_ne_of_ne (nat.succ_ne_zero _) (nat.succ_succ_ne_one _)] } end @[simp] lemma sign_fin_rotate (n : ℕ) : perm.sign (fin_rotate (n + 1)) = (-1) ^ n := begin induction n with n ih, { simp }, { rw fin_rotate_succ, simp [ih, pow_succ] }, end @[simp] lemma support_fin_rotate {n : ℕ} : support (fin_rotate (n + 2)) = finset.univ := by { ext, simp } lemma support_fin_rotate_of_le {n : ℕ} (h : 2 ≤ n) : support (fin_rotate n) = finset.univ := begin obtain ⟨m, rfl⟩ := exists_add_of_le h, rw [add_comm, support_fin_rotate], end lemma is_cycle_fin_rotate {n : ℕ} : is_cycle (fin_rotate (n + 2)) := begin refine ⟨0, dec_trivial, λ x hx', ⟨x, _⟩⟩, clear hx', cases x with x hx, rw [coe_coe, zpow_coe_nat, fin.ext_iff, fin.coe_mk], induction x with x ih, { refl }, rw [pow_succ, perm.mul_apply, coe_fin_rotate_of_ne_last, ih (lt_trans x.lt_succ_self hx)], rw [ne.def, fin.ext_iff, ih (lt_trans x.lt_succ_self hx), fin.coe_last], exact ne_of_lt (nat.lt_of_succ_lt_succ hx), end lemma is_cycle_fin_rotate_of_le {n : ℕ} (h : 2 ≤ n) : is_cycle (fin_rotate n) := begin obtain ⟨m, rfl⟩ := exists_add_of_le h, rw [add_comm], exact is_cycle_fin_rotate end @[simp] lemma cycle_type_fin_rotate {n : ℕ} : cycle_type (fin_rotate (n + 2)) = {n + 2} := begin rw [is_cycle_fin_rotate.cycle_type, support_fin_rotate, ← fintype.card, fintype.card_fin], refl, end lemma cycle_type_fin_rotate_of_le {n : ℕ} (h : 2 ≤ n) : cycle_type (fin_rotate n) = {n} := begin obtain ⟨m, rfl⟩ := exists_add_of_le h, rw [add_comm, cycle_type_fin_rotate] end namespace fin /-- `fin.cycle_range i` is the cycle `(0 1 2 ... i)` leaving `(i+1 ... (n-1))` unchanged. -/ def cycle_range {n : ℕ} (i : fin n) : perm (fin n) := (fin_rotate (i + 1)) .extend_domain (equiv.of_left_inverse' (fin.cast_le (nat.succ_le_of_lt i.is_lt)).to_embedding coe (by { intros x, ext, simp })) lemma cycle_range_of_gt {n : ℕ} {i j : fin n.succ} (h : i < j) : cycle_range i j = j := begin rw [cycle_range, of_left_inverse'_eq_of_injective, ←function.embedding.to_equiv_range_eq_of_injective, ←via_fintype_embedding, via_fintype_embedding_apply_not_mem_range], simpa end lemma cycle_range_of_le {n : ℕ} {i j : fin n.succ} (h : j ≤ i) : cycle_range i j = if j = i then 0 else j + 1 := begin cases n, { simp }, have : j = (fin.cast_le (nat.succ_le_of_lt i.is_lt)).to_embedding ⟨j, lt_of_le_of_lt h (nat.lt_succ_self i)⟩, { simp }, ext, rw [this, cycle_range, of_left_inverse'_eq_of_injective, ←function.embedding.to_equiv_range_eq_of_injective, ←via_fintype_embedding, via_fintype_embedding_apply_image, rel_embedding.coe_fn_to_embedding, coe_cast_le, coe_fin_rotate], simp only [fin.ext_iff, coe_last, coe_mk, coe_zero, fin.eta, apply_ite coe, cast_le_mk], split_ifs with heq, { refl }, { rw fin.coe_add_one_of_lt, exact lt_of_lt_of_le (lt_of_le_of_ne h (mt (congr_arg coe) heq)) (le_last i) } end lemma coe_cycle_range_of_le {n : ℕ} {i j : fin n.succ} (h : j ≤ i) : (cycle_range i j : ℕ) = if j = i then 0 else j + 1 := by { rw [cycle_range_of_le h], split_ifs with h', { refl }, exact coe_add_one_of_lt (calc (j : ℕ) < i : fin.lt_iff_coe_lt_coe.mp (lt_of_le_of_ne h h') ... ≤ n : nat.lt_succ_iff.mp i.2) } lemma cycle_range_of_lt {n : ℕ} {i j : fin n.succ} (h : j < i) : cycle_range i j = j + 1 := by rw [cycle_range_of_le h.le, if_neg h.ne] lemma coe_cycle_range_of_lt {n : ℕ} {i j : fin n.succ} (h : j < i) : (cycle_range i j : ℕ) = j + 1 := by rw [coe_cycle_range_of_le h.le, if_neg h.ne] lemma cycle_range_of_eq {n : ℕ} {i j : fin n.succ} (h : j = i) : cycle_range i j = 0 := by rw [cycle_range_of_le h.le, if_pos h] @[simp] lemma cycle_range_self {n : ℕ} (i : fin n.succ) : cycle_range i i = 0 := cycle_range_of_eq rfl lemma cycle_range_apply {n : ℕ} (i j : fin n.succ) : cycle_range i j = if j < i then j + 1 else if j = i then 0 else j := begin split_ifs with h₁ h₂, { exact cycle_range_of_lt h₁ }, { exact cycle_range_of_eq h₂ }, { exact cycle_range_of_gt (lt_of_le_of_ne (le_of_not_gt h₁) (ne.symm h₂)) }, end @[simp] lemma cycle_range_zero (n : ℕ) : cycle_range (0 : fin n.succ) = 1 := begin ext j, refine fin.cases _ (λ j, _) j, { simp }, { rw [cycle_range_of_gt (fin.succ_pos j), one_apply] }, end @[simp] lemma cycle_range_last (n : ℕ) : cycle_range (last n) = fin_rotate (n + 1) := by { ext i, rw [coe_cycle_range_of_le (le_last _), coe_fin_rotate] } @[simp] lemma cycle_range_zero' {n : ℕ} (h : 0 < n) : cycle_range ⟨0, h⟩ = 1 := begin cases n with n, { cases h }, exact cycle_range_zero n end @[simp] lemma sign_cycle_range {n : ℕ} (i : fin n) : perm.sign (cycle_range i) = (-1) ^ (i : ℕ) := by simp [cycle_range] @[simp] lemma succ_above_cycle_range {n : ℕ} (i j : fin n) : i.succ.succ_above (i.cycle_range j) = swap 0 i.succ j.succ := begin cases n, { rcases j with ⟨_, ⟨⟩⟩ }, rcases lt_trichotomy j i with hlt | heq | hgt, { have : (j + 1).cast_succ = j.succ, { ext, rw [coe_cast_succ, coe_succ, fin.coe_add_one_of_lt (lt_of_lt_of_le hlt i.le_last)] }, rw [fin.cycle_range_of_lt hlt, fin.succ_above_below, this, swap_apply_of_ne_of_ne], { apply fin.succ_ne_zero }, { exact (fin.succ_injective _).ne hlt.ne }, { rw fin.lt_iff_coe_lt_coe, simpa [this] using hlt } }, { rw [heq, fin.cycle_range_self, fin.succ_above_below, swap_apply_right, fin.cast_succ_zero], { rw fin.cast_succ_zero, apply fin.succ_pos } }, { rw [fin.cycle_range_of_gt hgt, fin.succ_above_above, swap_apply_of_ne_of_ne], { apply fin.succ_ne_zero }, { apply (fin.succ_injective _).ne hgt.ne.symm }, { simpa [fin.le_iff_coe_le_coe] using hgt } }, end @[simp] lemma cycle_range_succ_above {n : ℕ} (i : fin (n + 1)) (j : fin n) : i.cycle_range (i.succ_above j) = j.succ := begin cases lt_or_ge j.cast_succ i with h h, { rw [fin.succ_above_below _ _ h, fin.cycle_range_of_lt h, fin.coe_succ_eq_succ] }, { rw [fin.succ_above_above _ _ h, fin.cycle_range_of_gt (fin.le_cast_succ_iff.mp h)] } end @[simp] lemma cycle_range_symm_zero {n : ℕ} (i : fin (n + 1)) : i.cycle_range.symm 0 = i := i.cycle_range.injective (by simp) @[simp] lemma cycle_range_symm_succ {n : ℕ} (i : fin (n + 1)) (j : fin n) : i.cycle_range.symm j.succ = i.succ_above j := i.cycle_range.injective (by simp) lemma is_cycle_cycle_range {n : ℕ} {i : fin (n + 1)} (h0 : i ≠ 0) : is_cycle (cycle_range i) := begin cases i with i hi, cases i, { exact (h0 rfl).elim }, exact is_cycle_fin_rotate.extend_domain _, end @[simp] lemma cycle_type_cycle_range {n : ℕ} {i : fin (n + 1)} (h0 : i ≠ 0) : cycle_type (cycle_range i) = {i + 1} := begin cases i with i hi, cases i, { exact (h0 rfl).elim }, rw [cycle_range, cycle_type_extend_domain], exact cycle_type_fin_rotate, end lemma is_three_cycle_cycle_range_two {n : ℕ} : is_three_cycle (cycle_range 2 : perm (fin (n + 3))) := begin rw [is_three_cycle, cycle_type_cycle_range]; dec_trivial end end fin end cycle_range
11d1736209314b65986dc627f5111713321e3f98
fe84e287c662151bb313504482b218a503b972f3
/src/order/lattice_extra.lean
fb0395db69e34ab762570803231dfd60eaedeb48
[]
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,687
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland Some additional typeclass instances: * A set with decidable linear order and top and bottom elements is a bounded distributive lattice * If we take a set with decidable linear order and adjoin top and bottom elements, we again get a bounded distributive lattice * A sup-semilattice becomes a monoid under the sup operation. * Dually, an inf-semilattice becomes a monoid under the inf operation. -/ import data.fin.basic import order.lattice namespace lattice open lattice instance wtb_dl_of_dlo (α : Type*) [linear_order α] : distrib_lattice (with_top (with_bot α)) := begin exact linear_order.to_distrib_lattice, end instance wtb_bo_of_dlo (α : Type*) [linear_order α] : bounded_order (with_top (with_bot α)) := { top := ⊤, bot := ⊥, le_top := λ a, by { exact le_top, }, bot_le := λ a, by { exact bot_le } } instance inf_monoid {α : Type*} [semilattice_inf α] [order_top α]: comm_monoid α := { mul := has_inf.inf, one := has_top.top, one_mul := λ a, top_inf_eq, mul_one := λ a, inf_top_eq, mul_comm := @inf_comm α _, mul_assoc := @inf_assoc α _, } instance sup_monoid {α : Type*} [semilattice_sup α] [order_bot α]: comm_monoid α := { mul := has_sup.sup, one := has_bot.bot, one_mul := λ a, bot_sup_eq, mul_one := λ a, sup_bot_eq, mul_comm := @sup_comm α _, mul_assoc := @sup_assoc α _, } end lattice namespace fin instance (n : ℕ) : distrib_lattice (fin n.succ) := linear_order.to_distrib_lattice end fin
87ca4688450c66fdb482f103a01ec5c5c3103493
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/zsqrtd/gaussian_int.lean
587fa293cdff2cbe2cc2dbf515949b9fb1442191
[]
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
8,537
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.zsqrtd.basic import Mathlib.data.complex.basic import Mathlib.ring_theory.principal_ideal_domain import Mathlib.number_theory.quadratic_reciprocity import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Gaussian integers The Gaussian integers are complex integer, complex numbers whose real and imaginary parts are both integers. ## Main definitions The Euclidean domain structure on `ℤ[i]` is defined in this file. The homomorphism `to_complex` into the complex numbers is also defined in this file. ## Main statements `prime_iff_mod_four_eq_three_of_nat_prime` A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4` ## Notations This file uses the local notation `ℤ[i]` for `gaussian_int` ## Implementation notes Gaussian integers are implemented using the more general definition `zsqrtd`, the type of integers adjoined a square root of `d`, in this case `-1`. The definition is reducible, so that properties and definitions about `zsqrtd` can easily be used. -/ def gaussian_int := ℤ√(-1) namespace gaussian_int protected instance has_repr : has_repr gaussian_int := has_repr.mk fun (x : gaussian_int) => string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit1 (bit0 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit0 (bit0 1)))))))))))))) ++ repr (zsqrtd.re x) ++ string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit1 (bit1 (bit0 1))))))) (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++ repr (zsqrtd.im x) ++ string.str string.empty (char.of_nat (bit1 (bit0 (bit0 (bit1 (bit0 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit0 (bit0 1)))))))))))))) protected instance comm_ring : comm_ring gaussian_int := zsqrtd.comm_ring /-- The embedding of the Gaussian integers into the complex numbers, as a ring homomorphism. -/ def to_complex : gaussian_int →+* ℂ := coe_fn zsqrtd.lift { val := complex.I, property := sorry } protected instance complex.has_coe : has_coe gaussian_int ℂ := has_coe.mk ⇑to_complex theorem to_complex_def (x : gaussian_int) : ↑x = ↑(zsqrtd.re x) + ↑(zsqrtd.im x) * complex.I := rfl theorem to_complex_def' (x : ℤ) (y : ℤ) : ↑(zsqrtd.mk x y) = ↑x + ↑y * complex.I := sorry theorem to_complex_def₂ (x : gaussian_int) : ↑x = complex.mk ↑(zsqrtd.re x) ↑(zsqrtd.im x) := sorry @[simp] theorem to_real_re (x : gaussian_int) : ↑(zsqrtd.re x) = complex.re ↑x := sorry @[simp] theorem to_real_im (x : gaussian_int) : ↑(zsqrtd.im x) = complex.im ↑x := sorry @[simp] theorem to_complex_re (x : ℤ) (y : ℤ) : complex.re ↑(zsqrtd.mk x y) = ↑x := sorry @[simp] theorem to_complex_im (x : ℤ) (y : ℤ) : complex.im ↑(zsqrtd.mk x y) = ↑y := sorry @[simp] theorem to_complex_add (x : gaussian_int) (y : gaussian_int) : ↑(x + y) = ↑x + ↑y := ring_hom.map_add to_complex x y @[simp] theorem to_complex_mul (x : gaussian_int) (y : gaussian_int) : ↑(x * y) = ↑x * ↑y := ring_hom.map_mul to_complex x y @[simp] theorem to_complex_one : ↑1 = 1 := ring_hom.map_one to_complex @[simp] theorem to_complex_zero : ↑0 = 0 := ring_hom.map_zero to_complex @[simp] theorem to_complex_neg (x : gaussian_int) : ↑(-x) = -↑x := ring_hom.map_neg to_complex x @[simp] theorem to_complex_sub (x : gaussian_int) (y : gaussian_int) : ↑(x - y) = ↑x - ↑y := ring_hom.map_sub to_complex x y @[simp] theorem to_complex_inj {x : gaussian_int} {y : gaussian_int} : ↑x = ↑y ↔ x = y := sorry @[simp] theorem to_complex_eq_zero {x : gaussian_int} : ↑x = 0 ↔ x = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (↑x = 0 ↔ x = 0)) (Eq.symm to_complex_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑x = ↑0 ↔ x = 0)) (propext to_complex_inj))) (iff.refl (x = 0))) @[simp] theorem nat_cast_real_norm (x : gaussian_int) : ↑(zsqrtd.norm x) = coe_fn complex.norm_sq ↑x := sorry @[simp] theorem nat_cast_complex_norm (x : gaussian_int) : ↑(zsqrtd.norm x) = ↑(coe_fn complex.norm_sq ↑x) := sorry theorem norm_nonneg (x : gaussian_int) : 0 ≤ zsqrtd.norm x := zsqrtd.norm_nonneg (eq.mpr (id (eq_true_intro (neg_nonpos_of_nonneg (norm_num.nonneg_pos 1 zero_lt_one')))) trivial) x @[simp] theorem norm_eq_zero {x : gaussian_int} : zsqrtd.norm x = 0 ↔ x = 0 := sorry theorem norm_pos {x : gaussian_int} : 0 < zsqrtd.norm x ↔ x ≠ 0 := sorry @[simp] theorem coe_nat_abs_norm (x : gaussian_int) : ↑(int.nat_abs (zsqrtd.norm x)) = zsqrtd.norm x := int.nat_abs_of_nonneg (norm_nonneg x) @[simp] theorem nat_cast_nat_abs_norm {α : Type u_1} [ring α] (x : gaussian_int) : ↑(int.nat_abs (zsqrtd.norm x)) = ↑(zsqrtd.norm x) := sorry theorem nat_abs_norm_eq (x : gaussian_int) : int.nat_abs (zsqrtd.norm x) = int.nat_abs (zsqrtd.re x) * int.nat_abs (zsqrtd.re x) + int.nat_abs (zsqrtd.im x) * int.nat_abs (zsqrtd.im x) := sorry protected def div (x : gaussian_int) (y : gaussian_int) : gaussian_int := let n : ℚ := rat.of_int (zsqrtd.norm y)⁻¹; let c : ℤ√(-1) := zsqrtd.conj y; zsqrtd.mk (round (rat.of_int (zsqrtd.re (x * c)) * n)) (round (rat.of_int (zsqrtd.im (x * c)) * n)) protected instance has_div : Div gaussian_int := { div := gaussian_int.div } theorem div_def (x : gaussian_int) (y : gaussian_int) : x / y = zsqrtd.mk (round (↑(zsqrtd.re (x * zsqrtd.conj y)) / ↑(zsqrtd.norm y))) (round (↑(zsqrtd.im (x * zsqrtd.conj y)) / ↑(zsqrtd.norm y))) := sorry theorem to_complex_div_re (x : gaussian_int) (y : gaussian_int) : complex.re ↑(x / y) = ↑(round (complex.re (↑x / ↑y))) := sorry theorem to_complex_div_im (x : gaussian_int) (y : gaussian_int) : complex.im ↑(x / y) = ↑(round (complex.im (↑x / ↑y))) := sorry theorem norm_sq_le_norm_sq_of_re_le_of_im_le {x : ℂ} {y : ℂ} (hre : abs (complex.re x) ≤ abs (complex.re y)) (him : abs (complex.im x) ≤ abs (complex.im y)) : coe_fn complex.norm_sq x ≤ coe_fn complex.norm_sq y := sorry theorem norm_sq_div_sub_div_lt_one (x : gaussian_int) (y : gaussian_int) : coe_fn complex.norm_sq (↑x / ↑y - ↑(x / y)) < 1 := sorry protected def mod (x : gaussian_int) (y : gaussian_int) : gaussian_int := x - y * (x / y) protected instance has_mod : Mod gaussian_int := { mod := gaussian_int.mod } theorem mod_def (x : gaussian_int) (y : gaussian_int) : x % y = x - y * (x / y) := rfl theorem norm_mod_lt (x : gaussian_int) {y : gaussian_int} (hy : y ≠ 0) : zsqrtd.norm (x % y) < zsqrtd.norm y := sorry theorem nat_abs_norm_mod_lt (x : gaussian_int) {y : gaussian_int} (hy : y ≠ 0) : int.nat_abs (zsqrtd.norm (x % y)) < int.nat_abs (zsqrtd.norm y) := sorry theorem norm_le_norm_mul_left (x : gaussian_int) {y : gaussian_int} (hy : y ≠ 0) : int.nat_abs (zsqrtd.norm x) ≤ int.nat_abs (zsqrtd.norm (x * y)) := sorry protected instance nontrivial : nontrivial gaussian_int := nontrivial.mk (Exists.intro 0 (Exists.intro 1 (of_as_true trivial))) protected instance euclidean_domain : euclidean_domain gaussian_int := euclidean_domain.mk comm_ring.add comm_ring.add_assoc comm_ring.zero comm_ring.zero_add comm_ring.add_zero comm_ring.neg comm_ring.sub comm_ring.add_left_neg comm_ring.add_comm comm_ring.mul comm_ring.mul_assoc comm_ring.one comm_ring.one_mul comm_ring.mul_one comm_ring.left_distrib comm_ring.right_distrib comm_ring.mul_comm nontrivial.exists_pair_ne Div.div sorry Mod.mod sorry (measure (int.nat_abs ∘ zsqrtd.norm)) sorry nat_abs_norm_mod_lt sorry theorem mod_four_eq_three_of_nat_prime_of_prime (p : ℕ) [hp : fact (nat.prime p)] (hpi : prime ↑p) : p % bit0 (bit0 1) = bit1 1 := sorry theorem sum_two_squares_of_nat_prime_of_not_irreducible (p : ℕ) [hp : fact (nat.prime p)] (hpi : ¬irreducible ↑p) : ∃ (a : ℕ), ∃ (b : ℕ), a ^ bit0 1 + b ^ bit0 1 = p := sorry theorem prime_of_nat_prime_of_mod_four_eq_three (p : ℕ) [hp : fact (nat.prime p)] (hp3 : p % bit0 (bit0 1) = bit1 1) : prime ↑p := sorry /-- A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4` -/ theorem prime_iff_mod_four_eq_three_of_nat_prime (p : ℕ) [hp : fact (nat.prime p)] : prime ↑p ↔ p % bit0 (bit0 1) = bit1 1 := { mp := mod_four_eq_three_of_nat_prime_of_prime p, mpr := prime_of_nat_prime_of_mod_four_eq_three p }
c331a21d7a7550a4250b194d8d971dbc7519fd94
626e312b5c1cb2d88fca108f5933076012633192
/src/analysis/convex/caratheodory.lean
01081ba52cb2a4a4835f8fb34833c05e540ad865
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,556
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import analysis.convex.basic import linear_algebra.affine_space.independent /-! # Carathéodory's convexity theorem Convex hull can be regarded as a refinement of affine span. Both are closure operators but whereas convex hull takes values in the lattice of convex subsets, affine span takes values in the much coarser sublattice of affine subspaces. The cost of this refinement is that one no longer has bases. However Carathéodory's convexity theorem offers some compensation. Given a set `s` together with a point `x` in its convex hull, Carathéodory says that one may find an affine-independent family of elements `s` whose convex hull contains `x`. Thus the difference from the case of affine span is that the affine-independent family depends on `x`. In particular, in finite dimensions Carathéodory's theorem implies that the convex hull of a set `s` in `ℝᵈ` is the union of the convex hulls of the `(d+1)`-tuples in `s`. ## Main results * `convex_hull_eq_union`: Carathéodory's convexity theorem ## Implementation details This theorem was formalized as part of the Sphere Eversion project. ## Tags convex hull, caratheodory -/ universes u open set finset open_locale big_operators variables {E : Type u} [add_comm_group E] [module ℝ E] namespace caratheodory /-- If `x` is in the convex hull of some finset `t` whose elements are not affine-independent, then it is in the convex hull of a strict subset of `t`. -/ lemma mem_convex_hull_erase [decidable_eq E] {t : finset E} (h : ¬ affine_independent ℝ (coe : t → E)) {x : E} (m : x ∈ convex_hull (↑t : set E)) : ∃ (y : (↑t : set E)), x ∈ convex_hull (↑(t.erase y) : set E) := begin simp only [finset.convex_hull_eq, mem_set_of_eq] at m ⊢, obtain ⟨f, fpos, fsum, rfl⟩ := m, obtain ⟨g, gcombo, gsum, gpos⟩ := exists_nontrivial_relation_sum_zero_of_not_affine_ind h, replace gpos := exists_pos_of_sum_zero_of_exists_nonzero g gsum gpos, clear h, let s := t.filter (λ z : E, 0 < g z), obtain ⟨i₀, mem, w⟩ : ∃ i₀ ∈ s, ∀ i ∈ s, f i₀ / g i₀ ≤ f i / g i, { apply s.exists_min_image (λ z, f z / g z), obtain ⟨x, hx, hgx⟩ : ∃ x ∈ t, 0 < g x := gpos, exact ⟨x, mem_filter.mpr ⟨hx, hgx⟩⟩, }, have hg : 0 < g i₀ := by { rw mem_filter at mem, exact mem.2 }, have hi₀ : i₀ ∈ t := filter_subset _ _ mem, let k : E → ℝ := λ z, f z - (f i₀ / g i₀) * g z, have hk : k i₀ = 0 := by field_simp [k, ne_of_gt hg], have ksum : ∑ e in t.erase i₀, k e = 1, { calc ∑ e in t.erase i₀, k e = ∑ e in t, k e : by conv_rhs { rw [← insert_erase hi₀, sum_insert (not_mem_erase i₀ t), hk, zero_add], } ... = ∑ e in t, (f e - f i₀ / g i₀ * g e) : rfl ... = 1 : by rw [sum_sub_distrib, fsum, ← mul_sum, gsum, mul_zero, sub_zero] }, refine ⟨⟨i₀, hi₀⟩, k, _, ksum, _⟩, { simp only [and_imp, sub_nonneg, mem_erase, ne.def, subtype.coe_mk], intros e hei₀ het, by_cases hes : e ∈ s, { have hge : 0 < g e := by { rw mem_filter at hes, exact hes.2 }, rw ← le_div_iff hge, exact w _ hes, }, { calc _ ≤ 0 : mul_nonpos_of_nonneg_of_nonpos _ _ -- prove two goals below ... ≤ f e : fpos e het, { apply div_nonneg (fpos i₀ (mem_of_subset (filter_subset _ t) mem)) (le_of_lt hg) }, { simpa only [mem_filter, het, true_and, not_lt] using hes }, } }, { simp only [subtype.coe_mk, center_mass_eq_of_sum_1 _ id ksum, id], calc ∑ e in t.erase i₀, k e • e = ∑ e in t, k e • e : sum_erase _ (by rw [hk, zero_smul]) ... = ∑ e in t, (f e - f i₀ / g i₀ * g e) • e : rfl ... = t.center_mass f id : _, simp only [sub_smul, mul_smul, sum_sub_distrib, ← smul_sum, gcombo, smul_zero, sub_zero, center_mass, fsum, inv_one, one_smul, id.def], }, end variables {s : set E} {x : E} (hx : x ∈ convex_hull s) include hx /-- Given a point `x` in the convex hull of a set `s`, this is a finite subset of `s` of minimum cardinality, whose convex hull contains `x`. -/ noncomputable def min_card_finset_of_mem_convex_hull : finset E := function.argmin_on finset.card nat.lt_wf { t | ↑t ⊆ s ∧ x ∈ convex_hull (t : set E) } (by simpa only [convex_hull_eq_union_convex_hull_finite_subsets s, exists_prop, mem_Union] using hx) lemma min_card_finset_of_mem_convex_hull_subseteq : ↑(min_card_finset_of_mem_convex_hull hx) ⊆ s := (function.argmin_on_mem _ _ { t : finset E | ↑t ⊆ s ∧ x ∈ convex_hull (t : set E) } _).1 lemma mem_min_card_finset_of_mem_convex_hull : x ∈ convex_hull (min_card_finset_of_mem_convex_hull hx : set E) := (function.argmin_on_mem _ _ { t : finset E | ↑t ⊆ s ∧ x ∈ convex_hull (t : set E) } _).2 lemma min_card_finset_of_mem_convex_hull_nonempty : (min_card_finset_of_mem_convex_hull hx).nonempty := begin rw [← finset.coe_nonempty, ← convex_hull_nonempty_iff], exact ⟨x, mem_min_card_finset_of_mem_convex_hull hx⟩, end lemma min_card_finset_of_mem_convex_hull_card_le_card {t : finset E} (ht₁ : ↑t ⊆ s) (ht₂ : x ∈ convex_hull (t : set E)) : (min_card_finset_of_mem_convex_hull hx).card ≤ t.card := function.argmin_on_le _ _ _ ⟨ht₁, ht₂⟩ lemma affine_independent_min_card_finset_of_mem_convex_hull : affine_independent ℝ (coe : min_card_finset_of_mem_convex_hull hx → E) := begin let k := (min_card_finset_of_mem_convex_hull hx).card - 1, have hk : (min_card_finset_of_mem_convex_hull hx).card = k + 1, { exact (nat.succ_pred_eq_of_pos (finset.card_pos.mpr (min_card_finset_of_mem_convex_hull_nonempty hx))).symm, }, classical, by_contra, obtain ⟨p, hp⟩ := mem_convex_hull_erase h (mem_min_card_finset_of_mem_convex_hull hx), have contra := min_card_finset_of_mem_convex_hull_card_le_card hx (set.subset.trans (finset.erase_subset ↑p (min_card_finset_of_mem_convex_hull hx)) (min_card_finset_of_mem_convex_hull_subseteq hx)) hp, rw [← not_lt] at contra, apply contra, erw [card_erase_of_mem p.2, hk], exact lt_add_one _, end end caratheodory variables {s : set E} /-- **Carathéodory's convexity theorem** -/ lemma convex_hull_eq_union : convex_hull s = ⋃ (t : finset E) (hss : ↑t ⊆ s) (hai : affine_independent ℝ (coe : t → E)), convex_hull ↑t := begin apply set.subset.antisymm, { intros x hx, simp only [exists_prop, set.mem_Union], exact ⟨caratheodory.min_card_finset_of_mem_convex_hull hx, caratheodory.min_card_finset_of_mem_convex_hull_subseteq hx, caratheodory.affine_independent_min_card_finset_of_mem_convex_hull hx, caratheodory.mem_min_card_finset_of_mem_convex_hull hx⟩, }, { iterate 3 { convert set.Union_subset _, intro, }, exact convex_hull_mono ‹_›, }, end /-- A more explicit version of `convex_hull_eq_union`. -/ theorem eq_pos_convex_span_of_mem_convex_hull {x : E} (hx : x ∈ convex_hull s) : ∃ (ι : Sort (u+1)) [fintype ι], by exactI ∃ (z : ι → E) (w : ι → ℝ) (hss : set.range z ⊆ s) (hai : affine_independent ℝ z) (hw : ∀ i, 0 < w i), ∑ i, w i = 1 ∧ ∑ i, w i • z i = x := begin rw convex_hull_eq_union at hx, simp only [exists_prop, set.mem_Union] at hx, obtain ⟨t, ht₁, ht₂, ht₃⟩ := hx, simp only [t.convex_hull_eq, exists_prop, set.mem_set_of_eq] at ht₃, obtain ⟨w, hw₁, hw₂, hw₃⟩ := ht₃, let t' := t.filter (λ i, w i ≠ 0), refine ⟨t', t'.fintype_coe_sort, (coe : t' → E), w ∘ (coe : t' → E), _, _, _, _, _⟩, { rw subtype.range_coe_subtype, exact set.subset.trans (finset.filter_subset _ t) ht₁, }, { exact affine_independent_embedding_of_affine_independent ⟨_, inclusion_injective (finset.filter_subset (λ i, w i ≠ 0) t)⟩ ht₂, }, { intros i, suffices : w i ≠ 0, { cases this.lt_or_lt with hneg hpos, { exfalso, rw ← not_le at hneg, apply hneg, exact hw₁ _ (finset.mem_filter.mp i.2).1, }, { exact hpos, }, }, exact (finset.mem_filter.mp i.property).2, }, { erw [finset.sum_attach, finset.sum_filter_ne_zero, hw₂], }, { change ∑ (i : t') in t'.attach, (λ e, w e • e) ↑i = x, erw [finset.sum_attach, finset.sum_filter_of_ne], { rw t.center_mass_eq_of_sum_1 id hw₂ at hw₃, exact hw₃, }, { intros e he hwe contra, apply hwe, rw [contra, zero_smul], }, }, end
92a4612e8bdf66260f05d0bbccc89416792e4fad
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/model_theory/elementary_maps.lean
d62105d2b95d043480b87a8489f1bc23281044e1
[ "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
14,903
lean
/- Copyright (c) 2022 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.fintype.basic import model_theory.substructures /-! # Elementary Maps Between First-Order Structures ## Main Definitions * A `first_order.language.elementary_embedding` is an embedding that commutes with the realizations of formulas. * A `first_order.language.elementary_substructure` is a substructure where the realization of each formula agrees with the realization in the larger model. * The `first_order.language.elementary_diagram` of a structure is the set of all sentences with parameters that the structure satisfies. * `first_order.language.elementary_embedding.of_models_elementary_diagram` is the canonical elementary embedding of any structure into a model of its elementary diagram. ## Main Results * The Tarski-Vaught Test for embeddings: `first_order.language.embedding.is_elementary_of_exists` gives a simple criterion for an embedding to be elementary. * The Tarski-Vaught Test for substructures: `first_order.language.embedding.is_elementary_of_exists` gives a simple criterion for a substructure to be elementary. -/ open_locale first_order namespace first_order namespace language open Structure variables (L : language) (M : Type*) (N : Type*) {P : Type*} {Q : Type*} variables [L.Structure M] [L.Structure N] [L.Structure P] [L.Structure Q] /-- An elementary embedding of first-order structures is an embedding that commutes with the realizations of formulas. -/ structure elementary_embedding := (to_fun : M → N) (map_formula' : ∀ {{n}} (φ : L.formula (fin n)) (x : fin n → M), φ.realize (to_fun ∘ x) ↔ φ.realize x . obviously) localized "notation (name := elementary_embedding) A ` ↪ₑ[`:25 L `] ` B := first_order.language.elementary_embedding L A B" in first_order variables {L} {M} {N} namespace elementary_embedding instance fun_like : fun_like (M ↪ₑ[L] N) M (λ _, N) := { coe := λ f, f.to_fun, coe_injective' := λ f g h, begin cases f, cases g, simp only, ext x, exact function.funext_iff.1 h x end } instance : has_coe_to_fun (M ↪ₑ[L] N) (λ _, M → N) := fun_like.has_coe_to_fun @[simp] lemma map_bounded_formula (f : M ↪ₑ[L] N) {α : Type} {n : ℕ} (φ : L.bounded_formula α n) (v : α → M) (xs : fin n → M) : φ.realize (f ∘ v) (f ∘ xs) ↔ φ.realize v xs := begin classical, rw [← bounded_formula.realize_restrict_free_var set.subset.rfl, set.inclusion_eq_id, iff_eq_eq], swap, { apply_instance }, have h := f.map_formula' ((φ.restrict_free_var id).to_formula.relabel (fintype.equiv_fin _)) ((sum.elim (v ∘ coe) xs) ∘ (fintype.equiv_fin _).symm), simp only [formula.realize_relabel, bounded_formula.realize_to_formula, iff_eq_eq] at h, rw [← function.comp.assoc _ _ ((fintype.equiv_fin _).symm), function.comp.assoc _ ((fintype.equiv_fin _).symm) (fintype.equiv_fin _), equiv.symm_comp_self, function.comp.right_id, function.comp.assoc, sum.elim_comp_inl, function.comp.assoc _ _ sum.inr, sum.elim_comp_inr, ← function.comp.assoc] at h, refine h.trans _, rw [function.comp.assoc _ _ (fintype.equiv_fin _), equiv.symm_comp_self, function.comp.right_id, sum.elim_comp_inl, sum.elim_comp_inr, ← set.inclusion_eq_id, bounded_formula.realize_restrict_free_var set.subset.rfl], end @[simp] lemma map_formula (f : M ↪ₑ[L] N) {α : Type} (φ : L.formula α) (x : α → M) : φ.realize (f ∘ x) ↔ φ.realize x := by rw [formula.realize, formula.realize, ← f.map_bounded_formula, unique.eq_default (f ∘ default)] lemma map_sentence (f : M ↪ₑ[L] N) (φ : L.sentence) : M ⊨ φ ↔ N ⊨ φ := by rw [sentence.realize, sentence.realize, ← f.map_formula, unique.eq_default (f ∘ default)] lemma Theory_model_iff (f : M ↪ₑ[L] N) (T : L.Theory) : M ⊨ T ↔ N ⊨ T := by simp only [Theory.model_iff, f.map_sentence] lemma elementarily_equivalent (f : M ↪ₑ[L] N) : M ≅[L] N := elementarily_equivalent_iff.2 f.map_sentence @[simp] lemma injective (φ : M ↪ₑ[L] N) : function.injective φ := begin intros x y, have h := φ.map_formula ((var 0).equal (var 1) : L.formula (fin 2)) (λ i, if i = 0 then x else y), rw [formula.realize_equal, formula.realize_equal] at h, simp only [nat.one_ne_zero, term.realize, fin.one_eq_zero_iff, if_true, eq_self_iff_true, function.comp_app, if_false] at h, exact h.1, end instance embedding_like : embedding_like (M ↪ₑ[L] N) M N := { injective' := injective, .. show fun_like (M ↪ₑ[L] N) M (λ _, N), from infer_instance } @[simp] lemma map_fun (φ : M ↪ₑ[L] N) {n : ℕ} (f : L.functions n) (x : fin n → M) : φ (fun_map f x) = fun_map f (φ ∘ x) := begin have h := φ.map_formula (formula.graph f) (fin.cons (fun_map f x) x), rw [formula.realize_graph, fin.comp_cons, formula.realize_graph] at h, rw [eq_comm, h] end @[simp] lemma map_rel (φ : M ↪ₑ[L] N) {n : ℕ} (r : L.relations n) (x : fin n → M) : rel_map r (φ ∘ x) ↔ rel_map r x := begin have h := φ.map_formula (r.formula var) x, exact h end instance strong_hom_class : strong_hom_class L (M ↪ₑ[L] N) M N := { map_fun := map_fun, map_rel := map_rel } @[simp] lemma map_constants (φ : M ↪ₑ[L] N) (c : L.constants) : φ c = c := hom_class.map_constants φ c /-- An elementary embedding is also a first-order embedding. -/ def to_embedding (f : M ↪ₑ[L] N) : M ↪[L] N := { to_fun := f, inj' := f.injective, } /-- An elementary embedding is also a first-order homomorphism. -/ def to_hom (f : M ↪ₑ[L] N) : M →[L] N := { to_fun := f } @[simp] lemma to_embedding_to_hom (f : M ↪ₑ[L] N) : f.to_embedding.to_hom = f.to_hom := rfl @[simp] lemma coe_to_hom {f : M ↪ₑ[L] N} : (f.to_hom : M → N) = (f : M → N) := rfl @[simp] lemma coe_to_embedding (f : M ↪ₑ[L] N) : (f.to_embedding : M → N) = (f : M → N) := rfl lemma coe_injective : @function.injective (M ↪ₑ[L] N) (M → N) coe_fn := fun_like.coe_injective @[ext] lemma ext ⦃f g : M ↪ₑ[L] N⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h lemma ext_iff {f g : M ↪ₑ[L] N} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff variables (L) (M) /-- The identity elementary embedding from a structure to itself -/ @[refl] def refl : M ↪ₑ[L] M := { to_fun := id } variables {L} {M} instance : inhabited (M ↪ₑ[L] M) := ⟨refl L M⟩ @[simp] lemma refl_apply (x : M) : refl L M x = x := rfl /-- Composition of elementary embeddings -/ @[trans] def comp (hnp : N ↪ₑ[L] P) (hmn : M ↪ₑ[L] N) : M ↪ₑ[L] P := { to_fun := hnp ∘ hmn } @[simp] lemma comp_apply (g : N ↪ₑ[L] P) (f : M ↪ₑ[L] N) (x : M) : g.comp f x = g (f x) := rfl /-- Composition of elementary embeddings is associative. -/ lemma comp_assoc (f : M ↪ₑ[L] N) (g : N ↪ₑ[L] P) (h : P ↪ₑ[L] Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl end elementary_embedding variables (L) (M) /-- The elementary diagram of an `L`-structure is the set of all sentences with parameters it satisfies. -/ abbreviation elementary_diagram : L[[M]].Theory := L[[M]].complete_theory M /-- The canonical elementary embedding of an `L`-structure into any model of its elementary diagram -/ @[simps] def elementary_embedding.of_models_elementary_diagram (N : Type*) [L.Structure N] [L[[M]].Structure N] [(Lhom_with_constants L M).is_expansion_on N] [N ⊨ L.elementary_diagram M] : M ↪ₑ[L] N := ⟨(coe : L[[M]].constants → N) ∘ sum.inr, λ n φ x, begin refine trans _ ((realize_iff_of_model_complete_theory M N (((L.Lhom_with_constants M).on_bounded_formula φ).subst (constants.term ∘ sum.inr ∘ x)).alls).trans _), { simp_rw [sentence.realize, bounded_formula.realize_alls, bounded_formula.realize_subst, Lhom.realize_on_bounded_formula, formula.realize, unique.forall_iff, realize_constants] }, { simp_rw [sentence.realize, bounded_formula.realize_alls, bounded_formula.realize_subst, Lhom.realize_on_bounded_formula, formula.realize, unique.forall_iff], refl } end⟩ variables {L M} namespace embedding /-- The Tarski-Vaught test for elementarity of an embedding. -/ theorem is_elementary_of_exists (f : M ↪[L] N) (htv : ∀ (n : ℕ) (φ : L.bounded_formula empty (n + 1)) (x : fin n → M) (a : N), φ.realize default (fin.snoc (f ∘ x) a : _ → N) → ∃ b : M, φ.realize default (fin.snoc (f ∘ x) (f b) : _ → N)) : ∀{n} (φ : L.formula (fin n)) (x : fin n → M), φ.realize (f ∘ x) ↔ φ.realize x := begin suffices h : ∀ (n : ℕ) (φ : L.bounded_formula empty n) (xs : fin n → M), φ.realize (f ∘ default) (f ∘ xs) ↔ φ.realize default xs, { intros n φ x, refine φ.realize_relabel_sum_inr.symm.trans (trans (h n _ _) φ.realize_relabel_sum_inr), }, refine λ n φ, φ.rec_on _ _ _ _ _, { exact λ _ _, iff.rfl }, { intros, simp [bounded_formula.realize, ← sum.comp_elim, embedding.realize_term] }, { intros, simp [bounded_formula.realize, ← sum.comp_elim, embedding.realize_term] }, { intros _ _ _ ih1 ih2 _, simp [ih1, ih2] }, { intros n φ ih xs, simp only [bounded_formula.realize_all], refine ⟨λ h a, _, _⟩, { rw [← ih, fin.comp_snoc], exact h (f a) }, { contrapose!, rintro ⟨a, ha⟩, obtain ⟨b, hb⟩ := htv n φ.not xs a _, { refine ⟨b, λ h, hb (eq.mp _ ((ih _).2 h))⟩, rw [unique.eq_default (f ∘ default), fin.comp_snoc], }, { rw [bounded_formula.realize_not, ← unique.eq_default (f ∘ default)], exact ha } } }, end /-- Bundles an embedding satisfying the Tarski-Vaught test as an elementary embedding. -/ @[simps] def to_elementary_embedding (f : M ↪[L] N) (htv : ∀ (n : ℕ) (φ : L.bounded_formula empty (n + 1)) (x : fin n → M) (a : N), φ.realize default (fin.snoc (f ∘ x) a : _ → N) → ∃ b : M, φ.realize default (fin.snoc (f ∘ x) (f b) : _ → N)) : M ↪ₑ[L] N := ⟨f, λ _, f.is_elementary_of_exists htv⟩ end embedding namespace equiv /-- A first-order equivalence is also an elementary embedding. -/ def to_elementary_embedding (f : M ≃[L] N) : M ↪ₑ[L] N := { to_fun := f } @[simp] lemma to_elementary_embedding_to_embedding (f : M ≃[L] N) : f.to_elementary_embedding.to_embedding = f.to_embedding := rfl @[simp] lemma coe_to_elementary_embedding (f : M ≃[L] N) : (f.to_elementary_embedding : M → N) = (f : M → N) := rfl end equiv @[simp] lemma realize_term_substructure {α : Type*} {S : L.substructure M} (v : α → S) (t : L.term α) : t.realize (coe ∘ v) = (↑(t.realize v) : M) := S.subtype.realize_term t namespace substructure @[simp] lemma realize_bounded_formula_top {α : Type*} {n : ℕ} {φ : L.bounded_formula α n} {v : α → (⊤ : L.substructure M)} {xs : fin n → (⊤ : L.substructure M)} : φ.realize v xs ↔ φ.realize ((coe : _ → M) ∘ v) (coe ∘ xs) := begin rw ← substructure.top_equiv.realize_bounded_formula φ, simp, end @[simp] lemma realize_formula_top {α : Type*} {φ : L.formula α} {v : α → (⊤ : L.substructure M)} : φ.realize v ↔ φ.realize ((coe : (⊤ : L.substructure M) → M) ∘ v) := begin rw ← substructure.top_equiv.realize_formula φ, simp, end /-- A substructure is elementary when every formula applied to a tuple in the subtructure agrees with its value in the overall structure. -/ def is_elementary (S : L.substructure M) : Prop := ∀ {{n}} (φ : L.formula (fin n)) (x : fin n → S), φ.realize ((coe : _ → M) ∘ x) ↔ φ.realize x end substructure variables (L M) /-- An elementary substructure is one in which every formula applied to a tuple in the subtructure agrees with its value in the overall structure. -/ structure elementary_substructure := (to_substructure : L.substructure M) (is_elementary' : to_substructure.is_elementary) variables {L M} namespace elementary_substructure instance : has_coe (L.elementary_substructure M) (L.substructure M) := ⟨elementary_substructure.to_substructure⟩ instance : set_like (L.elementary_substructure M) M := ⟨λ x, x.to_substructure.carrier, λ ⟨⟨s, hs1⟩, hs2⟩ ⟨⟨t, ht1⟩, ht2⟩ h, begin congr, exact h, end⟩ instance induced_Structure (S : L.elementary_substructure M) : L.Structure S := substructure.induced_Structure @[simp] lemma is_elementary (S : L.elementary_substructure M) : (S : L.substructure M).is_elementary := S.is_elementary' /-- The natural embedding of an `L.substructure` of `M` into `M`. -/ def subtype (S : L.elementary_substructure M) : S ↪ₑ[L] M := { to_fun := coe, map_formula' := S.is_elementary } @[simp] theorem coe_subtype {S : L.elementary_substructure M} : ⇑S.subtype = coe := rfl /-- The substructure `M` of the structure `M` is elementary. -/ instance : has_top (L.elementary_substructure M) := ⟨⟨⊤, λ n φ x, substructure.realize_formula_top.symm⟩⟩ instance : inhabited (L.elementary_substructure M) := ⟨⊤⟩ @[simp] lemma mem_top (x : M) : x ∈ (⊤ : L.elementary_substructure M) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : L.elementary_substructure M) : set M) = set.univ := rfl @[simp] lemma realize_sentence (S : L.elementary_substructure M) (φ : L.sentence) : S ⊨ φ ↔ M ⊨ φ := S.subtype.map_sentence φ @[simp] lemma Theory_model_iff (S : L.elementary_substructure M) (T : L.Theory) : S ⊨ T ↔ M ⊨ T := by simp only [Theory.model_iff, realize_sentence] instance Theory_model {T : L.Theory} [h : M ⊨ T] {S : L.elementary_substructure M} : S ⊨ T := (Theory_model_iff S T).2 h instance [h : nonempty M] {S : L.elementary_substructure M} : nonempty S := (model_nonempty_theory_iff L).1 infer_instance lemma elementarily_equivalent (S : L.elementary_substructure M) : S ≅[L] M := S.subtype.elementarily_equivalent end elementary_substructure namespace substructure /-- The Tarski-Vaught test for elementarity of a substructure. -/ theorem is_elementary_of_exists (S : L.substructure M) (htv : ∀ (n : ℕ) (φ : L.bounded_formula empty (n + 1)) (x : fin n → S) (a : M), φ.realize default (fin.snoc (coe ∘ x) a : _ → M) → ∃ b : S, φ.realize default (fin.snoc (coe ∘ x) b : _ → M)) : S.is_elementary := λ n, S.subtype.is_elementary_of_exists htv /-- Bundles a substructure satisfying the Tarski-Vaught test as an elementary substructure. -/ @[simps] def to_elementary_substructure (S : L.substructure M) (htv : ∀ (n : ℕ) (φ : L.bounded_formula empty (n + 1)) (x : fin n → S) (a : M), φ.realize default (fin.snoc (coe ∘ x) a : _ → M) → ∃ b : S, φ.realize default (fin.snoc (coe ∘ x) b : _ → M)) : L.elementary_substructure M := ⟨S, S.is_elementary_of_exists htv⟩ end substructure end language end first_order
46ee526761207039e5fb6f8126a5546b44ad4b5a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/mv_polynomial/comm_ring.lean
ab4afa025b69429fb7aad6b86fa9f1a2ae4229f0
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,516
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import data.mv_polynomial.variables /-! # Multivariate polynomials over a ring Many results about polynomials hold when the coefficient ring is a commutative semiring. Some stronger results can be derived when we assume this semiring is a ring. This file does not define any new operations, but proves some of these stronger results. ## Notation As in other polynomial files, we typically use the notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_ring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v variables {R : Type u} {S : Type v} namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_ring variable [comm_ring R] variables {p q : mv_polynomial σ R} instance : comm_ring (mv_polynomial σ R) := add_monoid_algebra.comm_ring variables (σ a a') @[simp] lemma C_sub : (C (a - a') : mv_polynomial σ R) = C a - C a' := ring_hom.map_sub _ _ _ @[simp] lemma C_neg : (C (-a) : mv_polynomial σ R) = -C a := ring_hom.map_neg _ _ @[simp] lemma coeff_neg (m : σ →₀ ℕ) (p : mv_polynomial σ R) : coeff m (-p) = -coeff m p := finsupp.neg_apply _ _ @[simp] lemma coeff_sub (m : σ →₀ ℕ) (p q : mv_polynomial σ R) : coeff m (p - q) = coeff m p - coeff m q := finsupp.sub_apply _ _ _ @[simp] lemma support_neg : (- p).support = p.support := finsupp.support_neg p lemma support_sub (p q : mv_polynomial σ R) : (p - q).support ⊆ p.support ∪ q.support := finsupp.support_sub variables {σ} (p) section degrees lemma degrees_neg (p : mv_polynomial σ R) : (- p).degrees = p.degrees := by rw [degrees, support_neg]; refl lemma degrees_sub (p q : mv_polynomial σ R) : (p - q).degrees ≤ p.degrees ⊔ q.degrees := by simpa only [sub_eq_add_neg] using le_trans (degrees_add p (-q)) (by rw degrees_neg) end degrees section vars variables (p q) @[simp] lemma vars_neg : (-p).vars = p.vars := by simp [vars, degrees_neg] lemma vars_sub_subset : (p - q).vars ⊆ p.vars ∪ q.vars := by convert vars_add_subset p (-q) using 2; simp [sub_eq_add_neg] variables {p q} @[simp] lemma vars_sub_of_disjoint (hpq : disjoint p.vars q.vars) : (p - q).vars = p.vars ∪ q.vars := begin rw ←vars_neg q at hpq, convert vars_add_of_disjoint hpq using 2; simp [sub_eq_add_neg] end end vars section eval₂ variables [comm_ring S] variables (f : R →+* S) (g : σ → S) @[simp] lemma eval₂_sub : (p - q).eval₂ f g = p.eval₂ f g - q.eval₂ f g := (eval₂_hom f g).map_sub _ _ @[simp] lemma eval₂_neg : (-p).eval₂ f g = -(p.eval₂ f g) := (eval₂_hom f g).map_neg _ lemma hom_C (f : mv_polynomial σ ℤ →+* S) (n : ℤ) : f (C n) = (n : S) := eq_int_cast (f.comp C) n /-- A ring homomorphism f : Z[X_1, X_2, ...] → R is determined by the evaluations f(X_1), f(X_2), ... -/ @[simp] lemma eval₂_hom_X {R : Type u} (c : ℤ →+* S) (f : mv_polynomial R ℤ →+* S) (x : mv_polynomial R ℤ) : eval₂ c (f ∘ X) x = f x := mv_polynomial.induction_on x (λ n, by { rw [hom_C f, eval₂_C], exact eq_int_cast c n }) (λ p q hp hq, by { rw [eval₂_add, hp, hq], exact (f.map_add _ _).symm }) (λ p n hp, by { rw [eval₂_mul, eval₂_X, hp], exact (f.map_mul _ _).symm }) /-- Ring homomorphisms out of integer polynomials on a type `σ` are the same as functions out of the type `σ`, -/ def hom_equiv : (mv_polynomial σ ℤ →+* S) ≃ (σ → S) := { to_fun := λ f, ⇑f ∘ X, inv_fun := λ f, eval₂_hom (int.cast_ring_hom S) f, left_inv := λ f, ring_hom.ext $ eval₂_hom_X _ _, right_inv := λ f, funext $ λ x, by simp only [coe_eval₂_hom, function.comp_app, eval₂_X] } end eval₂ section degree_of lemma degree_of_sub_lt {x : σ} {f g : mv_polynomial σ R} {k : ℕ} (h : 0 < k) (hf : ∀ (m : σ →₀ ℕ), m ∈ f.support → (k ≤ m x) → coeff m f = coeff m g) (hg : ∀ (m : σ →₀ ℕ), m ∈ g.support → (k ≤ m x) → coeff m f = coeff m g) : degree_of x (f - g) < k := begin rw degree_of_lt_iff h, intros m hm, by_contra hc, simp only [not_lt] at hc, have h := support_sub σ f g hm, simp only [mem_support_iff, ne.def, coeff_sub, sub_eq_zero] at hm, cases (finset.mem_union).1 h with cf cg, { exact hm (hf m cf hc), }, { exact hm (hg m cg hc), }, end end degree_of section total_degree @[simp] lemma total_degree_neg (a : mv_polynomial σ R) : (-a).total_degree = a.total_degree := by simp only [total_degree, support_neg] lemma total_degree_sub (a b : mv_polynomial σ R) : (a - b).total_degree ≤ max a.total_degree b.total_degree := calc (a - b).total_degree = (a + -b).total_degree : by rw sub_eq_add_neg ... ≤ max a.total_degree (-b).total_degree : total_degree_add a (-b) ... = max a.total_degree b.total_degree : by rw total_degree_neg end total_degree end comm_ring end mv_polynomial
9fc2ac8a0b1cdae3378082d03453c5604c10ef23
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/linear_algebra/matrix/fpow.lean
b1561b96ecc25077a94582636e5b8752e87e8b93
[ "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
12,342
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import linear_algebra.matrix.nonsingular_inverse /-! # Integer powers of square matrices In this file, we define integer power of matrices, relying on the nonsingular inverse definition for negative powers. ## Implementation details The main definition is a direct recursive call on the integer inductive type, as provided by the `div_inv_monoid.gpow` default implementation. The lemma names are taken from `algebra.group_with_zero.power`. ## Tags matrix inverse, matrix powers -/ open_locale matrix namespace matrix variables {n' : Type*} [decidable_eq n'] [fintype n'] {R : Type*} [comm_ring R] local notation `M` := matrix n' n' R noncomputable instance : div_inv_monoid M := { ..(show monoid M, by apply_instance), ..(show has_inv M, by apply_instance) } section nat_pow @[simp] theorem inv_pow' (A : M) (n : ℕ) : (A⁻¹) ^ n = (A ^ n)⁻¹ := begin induction n with n ih, { simp }, { rw [pow_succ A, mul_eq_mul, mul_inv_rev, ← ih, ← mul_eq_mul, ← pow_succ'] } end theorem pow_sub' (A : M) {m n : ℕ} (ha : is_unit A.det) (h : n ≤ m) : A ^ (m - n) = A ^ m ⬝ (A ^ n)⁻¹ := begin rw [←nat.sub_add_cancel h, pow_add, mul_eq_mul, matrix.mul_assoc, mul_nonsing_inv, nat.sub_add_cancel h, matrix.mul_one], simpa using ha.pow n end theorem pow_inv_comm' (A : M) (m n : ℕ) : (A⁻¹) ^ m ⬝ A ^ n = A ^ n ⬝ (A⁻¹) ^ m := begin induction n with n IH generalizing m, { simp }, cases m, { simp }, rcases nonsing_inv_cancel_or_zero A with ⟨h, h'⟩ | h, { calc A⁻¹ ^ (m + 1) ⬝ A ^ (n + 1) = A⁻¹ ^ m ⬝ (A⁻¹ ⬝ A) ⬝ A ^ n : by simp only [pow_succ' A⁻¹, pow_succ A, mul_eq_mul, matrix.mul_assoc] ... = A ^ n ⬝ A⁻¹ ^ m : by simp only [h, matrix.mul_one, matrix.one_mul, IH m] ... = A ^ n ⬝ (A ⬝ A⁻¹) ⬝ A⁻¹ ^ m : by simp only [h', matrix.mul_one, matrix.one_mul] ... = A ^ (n + 1) ⬝ A⁻¹ ^ (m + 1) : by simp only [pow_succ' A, pow_succ A⁻¹, mul_eq_mul, matrix.mul_assoc] }, { simp [h] } end end nat_pow section int_pow open int @[simp] theorem one_fpow : ∀ (n : ℤ), (1 : M) ^ n = 1 | (n : ℕ) := by rw [gpow_coe_nat, one_pow] | -[1+ n] := by rw [gpow_neg_succ_of_nat, one_pow, inv_one] lemma zero_fpow : ∀ z : ℤ, z ≠ 0 → (0 : M) ^ z = 0 | (n : ℕ) h := by { rw [gpow_coe_nat, zero_pow], refine lt_of_le_of_ne n.zero_le (ne.symm _), simpa using h } | -[1+n] h := by simp [zero_pow n.zero_lt_succ] lemma zero_fpow_eq (n : ℤ) : (0 : M) ^ n = if n = 0 then 1 else 0 := begin split_ifs with h, { rw [h, gpow_zero] }, { rw [zero_fpow _ h] } end theorem inv_fpow (A : M) : ∀n:ℤ, A⁻¹ ^ n = (A ^ n)⁻¹ | (n : ℕ) := by rw [gpow_coe_nat, gpow_coe_nat, inv_pow'] | -[1+ n] := by rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, inv_pow'] @[simp] lemma fpow_neg_one (A : M) : A ^ (-1 : ℤ) = A⁻¹ := begin convert div_inv_monoid.gpow_neg' 0 A, simp only [gpow_one, int.coe_nat_zero, int.coe_nat_succ, gpow_eq_pow, zero_add] end theorem fpow_coe_nat (A : M) (n : ℕ) : A ^ (n : ℤ) = (A ^ n) := gpow_coe_nat _ _ @[simp] theorem fpow_neg_coe_nat (A : M) (n : ℕ) : A ^ (-n : ℤ) = (A ^ n)⁻¹ := begin cases n, { simp }, { exact div_inv_monoid.gpow_neg' _ _ } end lemma _root_.is_unit.det_fpow {A : M} (h : is_unit A.det) (n : ℤ) : is_unit (A ^ n).det := begin cases n, { simpa using h.pow n }, { simpa using h.pow n.succ } end lemma is_unit_det_fpow_iff {A : M} {z : ℤ} : is_unit (A ^ z).det ↔ is_unit A.det ∨ z = 0 := begin induction z using int.induction_on with z IH z IH, { simp }, { rw [←int.coe_nat_succ, fpow_coe_nat, det_pow, is_unit_pos_pow_iff (z.zero_lt_succ), ←int.coe_nat_zero, int.coe_nat_eq_coe_nat_iff], simp }, { rw [←neg_add', ←int.coe_nat_succ, fpow_neg_coe_nat, is_unit_nonsing_inv_det_iff, det_pow, is_unit_pos_pow_iff (z.zero_lt_succ), neg_eq_zero, ←int.coe_nat_zero, int.coe_nat_eq_coe_nat_iff], simp } end theorem fpow_neg {A : M} (h : is_unit A.det) : ∀ (n : ℤ), A ^ -n = (A ^ n)⁻¹ | (n : ℕ) := fpow_neg_coe_nat _ _ | -[1+ n] := by { rw [gpow_neg_succ_of_nat, neg_neg_of_nat_succ, of_nat_eq_coe, fpow_coe_nat, nonsing_inv_nonsing_inv], rw det_pow, exact h.pow _ } lemma inv_fpow' {A : M} (h : is_unit A.det) (n : ℤ) : (A ⁻¹) ^ n = A ^ (-n) := by rw [fpow_neg h, inv_fpow] lemma fpow_add_one {A : M} (h : is_unit A.det) : ∀ n : ℤ, A ^ (n + 1) = A ^ n * A | (n : ℕ) := by simp [← int.coe_nat_succ, pow_succ'] | -((n : ℕ) + 1) := calc A ^ (-(n + 1) + 1 : ℤ) = (A ^ n)⁻¹ : by rw [neg_add, neg_add_cancel_right, fpow_neg h, fpow_coe_nat] ... = (A ⬝ A ^ n)⁻¹ ⬝ A : by rw [mul_inv_rev, matrix.mul_assoc, nonsing_inv_mul _ h, matrix.mul_one] ... = A ^ -(n + 1 : ℤ) * A : by rw [fpow_neg h, ← int.coe_nat_succ, fpow_coe_nat, pow_succ, mul_eq_mul, mul_eq_mul] lemma fpow_sub_one {A : M} (h : is_unit A.det) (n : ℤ) : A ^ (n - 1) = A ^ n * A⁻¹ := calc A ^ (n - 1) = A ^ (n - 1) * A * A⁻¹ : by rw [mul_assoc, mul_eq_mul A, mul_nonsing_inv _ h, mul_one] ... = A^n * A⁻¹ : by rw [← fpow_add_one h, sub_add_cancel] lemma fpow_add {A : M} (ha : is_unit A.det) (m n : ℤ) : A ^ (m + n) = A ^ m * A ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, fpow_add_one ha, ihn, mul_assoc] }, { rw [fpow_sub_one ha, ← mul_assoc, ← ihn, ← fpow_sub_one ha, add_sub_assoc] } end lemma fpow_add_of_nonpos {A : M} {m n : ℤ} (hm : m ≤ 0) (hn : n ≤ 0) : A ^ (m + n) = A ^ m * A ^ n := begin rcases nonsing_inv_cancel_or_zero A with ⟨h, h'⟩ | h, { exact fpow_add (is_unit_det_of_left_inverse h) m n }, { obtain ⟨k, rfl⟩ := exists_eq_neg_of_nat hm, obtain ⟨l, rfl⟩ := exists_eq_neg_of_nat hn, simp_rw [←neg_add, ←int.coe_nat_add, fpow_neg_coe_nat, ←inv_pow', h, pow_add] } end lemma fpow_add_of_nonneg {A : M} {m n : ℤ} (hm : 0 ≤ m) (hn : 0 ≤ n) : A ^ (m + n) = A ^ m * A ^ n := begin rcases nonsing_inv_cancel_or_zero A with ⟨h, h'⟩ | h, { exact fpow_add (is_unit_det_of_left_inverse h) m n }, { obtain ⟨k, rfl⟩ := eq_coe_of_zero_le hm, obtain ⟨l, rfl⟩ := eq_coe_of_zero_le hn, rw [←int.coe_nat_add, fpow_coe_nat, fpow_coe_nat, fpow_coe_nat, pow_add] } end theorem fpow_one_add {A : M} (h : is_unit A.det) (i : ℤ) : A ^ (1 + i) = A * A ^ i := by rw [fpow_add h, gpow_one] theorem semiconj_by.fpow_right {A X Y : M} (hx : is_unit X.det) (hy : is_unit Y.det) (h : semiconj_by A X Y) : ∀ m : ℤ, semiconj_by A (X^m) (Y^m) | (n : ℕ) := by simp [h.pow_right n] | -[1+n] := begin by_cases ha : A = 0, { simp only [ha, semiconj_by.zero_left] }, have hx' : is_unit (X ^ n.succ).det, { rw det_pow, exact hx.pow n.succ }, have hy' : is_unit (Y ^ n.succ).det, { rw det_pow, exact hy.pow n.succ }, rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, nonsing_inv_apply _ hx', nonsing_inv_apply _ hy', semiconj_by], refine (is_regular_of_is_left_regular_det hy'.is_regular.left).left _, rw [←mul_assoc, ←(h.pow_right n.succ).eq, mul_assoc, mul_eq_mul (X ^ _), mul_smul, mul_adjugate, mul_eq_mul, mul_eq_mul, mul_eq_mul, ←matrix.mul_assoc, mul_smul (Y ^ _) (hy'.unit)⁻¹, mul_adjugate, units.smul_def, units.smul_def, smul_smul, smul_smul, hx'.coe_inv_mul, hy'.coe_inv_mul, one_smul, matrix.mul_one, matrix.one_mul] end theorem commute.fpow_right {A B : M} (h : commute A B) (m : ℤ) : commute A (B^m) := begin rcases nonsing_inv_cancel_or_zero B with ⟨hB, hB'⟩ | hB, { refine semiconj_by.fpow_right _ _ h _; exact is_unit_det_of_left_inverse hB }, { cases m, { simpa using h.pow_right _ }, { simp [←inv_pow', hB] } } end theorem commute.fpow_left {A B : M} (h : commute A B) (m : ℤ) : commute (A^m) B := (commute.fpow_right h.symm m).symm theorem commute.fpow_fpow {A B : M} (h : commute A B) (m n : ℤ) : commute (A^m) (B^n) := commute.fpow_right (commute.fpow_left h _) _ theorem commute.fpow_self (A : M) (n : ℤ) : commute (A^n) A := commute.fpow_left (commute.refl A) _ theorem commute.self_fpow (A : M) (n : ℤ) : commute A (A^n) := commute.fpow_right (commute.refl A) _ theorem commute.fpow_fpow_self (A : M) (m n : ℤ) : commute (A^m) (A^n) := commute.fpow_fpow (commute.refl A) _ _ theorem fpow_bit0 (A : M) (n : ℤ) : A ^ bit0 n = A ^ n * A ^ n := begin cases le_total 0 n with nonneg nonpos, { exact fpow_add_of_nonneg nonneg nonneg }, { exact fpow_add_of_nonpos nonpos nonpos } end lemma fpow_add_one_of_ne_neg_one {A : M} : ∀ (n : ℤ), n ≠ -1 → A ^ (n + 1) = A ^ n * A | (n : ℕ) _ := by simp [← int.coe_nat_succ, pow_succ'] | (-1) h := absurd rfl h | (-((n : ℕ) + 2)) _ := begin rcases nonsing_inv_cancel_or_zero A with ⟨h, h'⟩ | h, { apply fpow_add_one (is_unit_det_of_left_inverse h) }, { show A ^ (-((n + 1 : ℕ) : ℤ)) = A ^ -((n + 2 : ℕ) : ℤ) * A, simp_rw [fpow_neg_coe_nat, ←inv_pow', h, zero_pow nat.succ_pos', zero_mul] } end theorem fpow_bit1 (A : M) (n : ℤ) : A ^ bit1 n = A ^ n * A ^ n * A := begin rw [bit1, fpow_add_one_of_ne_neg_one, fpow_bit0], intro h, simpa using congr_arg bodd h end theorem fpow_mul (A : M) (h : is_unit A.det) : ∀ m n : ℤ, A ^ (m * n) = (A ^ m) ^ n | (m : ℕ) (n : ℕ) := by rw [gpow_coe_nat, gpow_coe_nat, ← pow_mul, ← gpow_coe_nat, int.coe_nat_mul] | (m : ℕ) -[1+ n] := by rw [gpow_coe_nat, gpow_neg_succ_of_nat, ← pow_mul, coe_nat_mul_neg_succ, ←int.coe_nat_mul, fpow_neg_coe_nat] | -[1+ m] (n : ℕ) := by rw [gpow_coe_nat, gpow_neg_succ_of_nat, ← inv_pow', ← pow_mul, neg_succ_mul_coe_nat, ←int.coe_nat_mul, fpow_neg_coe_nat, inv_pow'] | -[1+ m] -[1+ n] := by { rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, neg_succ_mul_neg_succ, ←int.coe_nat_mul, fpow_coe_nat, inv_pow', ←pow_mul, nonsing_inv_nonsing_inv], rw det_pow, exact h.pow _ } theorem fpow_mul' (A : M) (h : is_unit A.det) (m n : ℤ) : A ^ (m * n) = (A ^ n) ^ m := by rw [mul_comm, fpow_mul _ h] @[simp, norm_cast] lemma units.coe_inv'' (u : units M) : ((u⁻¹ : units M) : M) = u⁻¹ := begin refine (inv_eq_left_inv _).symm, rw [←mul_eq_mul, ←units.coe_mul, inv_mul_self, units.coe_one] end @[simp, norm_cast] lemma units.coe_fpow (u : units M) : ∀ (n : ℤ), ((u ^ n : units M) : M) = u ^ n | (n : ℕ) := by rw [gpow_coe_nat, gpow_coe_nat, units.coe_pow] | -[1+k] := by rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, ←inv_pow, u⁻¹.coe_pow, ←inv_pow', units.coe_inv''] lemma fpow_ne_zero_of_is_unit_det [nonempty n'] [nontrivial R] {A : M} (ha : is_unit A.det) (z : ℤ) : A ^ z ≠ 0 := begin have := ha.det_fpow z, contrapose! this, rw [this, det_zero ‹_›], exact not_is_unit_zero end lemma fpow_sub {A : M} (ha : is_unit A.det) (z1 z2 : ℤ) : A ^ (z1 - z2) = A ^ z1 / A ^ z2 := by rw [sub_eq_add_neg, fpow_add ha, fpow_neg ha, div_eq_mul_inv] lemma commute.mul_fpow {A B : M} (h : commute A B) : ∀ (i : ℤ), (A * B) ^ i = (A ^ i) * (B ^ i) | (n : ℕ) := by simp [h.mul_pow n, -mul_eq_mul] | -[1+n] := by rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, mul_eq_mul (_⁻¹), ←mul_inv_rev, ←mul_eq_mul, h.mul_pow n.succ, (h.pow_pow _ _).eq] theorem fpow_bit0' (A : M) (n : ℤ) : A ^ bit0 n = (A * A) ^ n := (fpow_bit0 A n).trans (commute.mul_fpow (commute.refl A) n).symm theorem fpow_bit1' (A : M) (n : ℤ) : A ^ bit1 n = (A * A) ^ n * A := by rw [fpow_bit1, commute.mul_fpow (commute.refl A)] theorem fpow_neg_mul_fpow_self (n : ℤ) {A : M} (h : is_unit A.det) : A ^ (-n) * A ^ n = 1 := by rw [fpow_neg h, mul_eq_mul, nonsing_inv_mul _ (h.det_fpow _)] theorem one_div_pow {A : M} (n : ℕ) : (1 / A) ^ n = 1 / A ^ n := by simp only [one_div, inv_pow'] theorem one_div_fpow {A : M} (n : ℤ) : (1 / A) ^ n = 1 / A ^ n := by simp only [one_div, inv_fpow] end int_pow end matrix
51d1bce74997edcd7ad7658311a0b929b7435320
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/category_theory/adjunction/basic.lean
19c4c3807e750ded928b4ccd6bf0d24ac7de1719
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,132
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 category_theory.equivalence namespace category_theory open category -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ u₁ u₂ u₃ local attribute [elab_simple] whisker_left whisker_right variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- `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 (F : C ⥤ D) (G : D ⥤ C) := (hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) (unit : 𝟭 C ⟶ F.comp G) (counit : G.comp F ⟶ 𝟭 D) (hom_equiv_unit' : Π {X Y f}, (hom_equiv X Y) f = (unit : _ ⟶ _).app X ≫ G.map f . obviously) (hom_equiv_counit' : Π {X Y g}, (hom_equiv X Y).symm g = F.map g ≫ counit.app Y . obviously) infix ` ⊣ `:15 := adjunction /-- A class giving a chosen right adjoint to the functor `left`. -/ class is_left_adjoint (left : C ⥤ D) := (right : D ⥤ C) (adj : left ⊣ right) /-- A class giving a chosen left adjoint to the functor `right`. -/ class is_right_adjoint (right : D ⥤ C) := (left : C ⥤ D) (adj : left ⊣ right) /-- Extract the left adjoint from the instance giving the chosen adjoint. -/ def left_adjoint (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 (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 (left : C ⥤ D) [is_left_adjoint left] : adjunction 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 (right : C ⥤ D) [is_right_adjoint right] : adjunction (left_adjoint right) right := is_right_adjoint.adj namespace adjunction restate_axiom hom_equiv_unit' restate_axiom hom_equiv_counit' attribute [simp, priority 10] hom_equiv_unit hom_equiv_counit section variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X' X : C} {Y Y' : D} @[simp, priority 10] lemma hom_equiv_naturality_left_symm (f : X' ⟶ X) (g : X ⟶ G.obj Y) : (adj.hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (adj.hom_equiv X Y).symm g := by rw [hom_equiv_counit, F.map_comp, assoc, adj.hom_equiv_counit.symm] @[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) : (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g := by rw [← equiv.eq_symm_apply]; simp [-hom_equiv_unit] @[simp, priority 10] lemma hom_equiv_naturality_right (f : F.obj X ⟶ Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y') (f ≫ g) = (adj.hom_equiv X Y) f ≫ G.map g := by rw [hom_equiv_unit, G.map_comp, ← assoc, ←hom_equiv_unit] @[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g := by rw [equiv.symm_apply_eq]; simp [-hom_equiv_counit] @[simp] lemma left_triangle : (whisker_right adj.unit F) ≫ (whisker_left F adj.counit) = nat_trans.id _ := begin ext, dsimp, erw [← adj.hom_equiv_counit, equiv.symm_apply_eq, adj.hom_equiv_unit], simp end @[simp] lemma right_triangle : (whisker_left G adj.unit) ≫ (whisker_right adj.counit G) = nat_trans.id _ := begin ext, dsimp, erw [← adj.hom_equiv_unit, ← equiv.eq_symm_apply, adj.hom_equiv_counit], simp end @[simp, reassoc] lemma left_triangle_components : F.map (adj.unit.app X) ≫ adj.counit.app (F.obj X) = 𝟙 (F.obj X) := congr_arg (λ (t : nat_trans _ (𝟭 C ⋙ F)), t.app X) adj.left_triangle @[simp, reassoc] lemma right_triangle_components {Y : D} : adj.unit.app (G.obj Y) ≫ G.map (adj.counit.app Y) = 𝟙 (G.obj Y) := congr_arg (λ (t : nat_trans _ (G ⋙ 𝟭 C)), t.app Y) adj.right_triangle @[simp, reassoc] lemma counit_naturality {X Y : D} (f : X ⟶ Y) : F.map (G.map f) ≫ (adj.counit).app Y = (adj.counit).app X ≫ f := adj.counit.naturality f @[simp, reassoc] lemma unit_naturality {X Y : C} (f : X ⟶ Y) : (adj.unit).app X ≫ G.map (F.map f) = f ≫ (adj.unit).app Y := (adj.unit.naturality f).symm lemma hom_equiv_apply_eq {A : C} {B : D} (f : F.obj A ⟶ B) (g : A ⟶ G.obj B) : adj.hom_equiv A B f = g ↔ f = (adj.hom_equiv A B).symm g := ⟨λ h, by {cases h, simp}, λ h, by {cases h, simp}⟩ lemma eq_hom_equiv_apply {A : C} {B : D} (f : F.obj A ⟶ B) (g : A ⟶ G.obj B) : g = adj.hom_equiv A B f ↔ (adj.hom_equiv A B).symm g = f := ⟨λ h, by {cases h, simp}, λ h, by {cases h, simp}⟩ end 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. -/ @[nolint has_inhabited_instance] structure core_hom_equiv (F : C ⥤ D) (G : D ⥤ C) := (hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) (hom_equiv_naturality_left_symm' : Π {X' X Y} (f : X' ⟶ X) (g : X ⟶ G.obj Y), (hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (hom_equiv X Y).symm g . obviously) (hom_equiv_naturality_right' : Π {X Y Y'} (f : F.obj X ⟶ Y) (g : Y ⟶ Y'), (hom_equiv X Y') (f ≫ g) = (hom_equiv X Y) f ≫ G.map g . obviously) namespace core_hom_equiv restate_axiom hom_equiv_naturality_left_symm' restate_axiom hom_equiv_naturality_right' attribute [simp, priority 10] hom_equiv_naturality_left_symm hom_equiv_naturality_right variables {F : C ⥤ D} {G : D ⥤ C} (adj : core_hom_equiv F G) {X' X : C} {Y Y' : D} @[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) : (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g := by rw [← equiv.eq_symm_apply]; simp @[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g := by rw [equiv.symm_apply_eq]; simp end core_hom_equiv /-- This is an auxiliary data structure useful for constructing adjunctions. See `adjunction.mk_of_unit_counit`. This structure won't typically be used anywhere else. -/ @[nolint has_inhabited_instance] structure core_unit_counit (F : C ⥤ D) (G : D ⥤ C) := (unit : 𝟭 C ⟶ F.comp G) (counit : G.comp F ⟶ 𝟭 D) (left_triangle' : whisker_right unit F ≫ (functor.associator F G F).hom ≫ whisker_left F counit = nat_trans.id (𝟭 C ⋙ F) . obviously) (right_triangle' : whisker_left G unit ≫ (functor.associator G F G).inv ≫ whisker_right counit G = nat_trans.id (G ⋙ 𝟭 C) . obviously) namespace core_unit_counit restate_axiom left_triangle' restate_axiom right_triangle' attribute [simp] left_triangle right_triangle end core_unit_counit variables {F : C ⥤ D} {G : D ⥤ C} /-- Construct an adjunction between `F` and `G` out of a natural bijection between each `F.obj X ⟶ Y` and `X ⟶ G.obj Y`. -/ @[simps] def mk_of_hom_equiv (adj : core_hom_equiv F G) : F ⊣ G := { unit := { app := λ X, (adj.hom_equiv X (F.obj X)) (𝟙 (F.obj X)), naturality' := begin intros, erw [← adj.hom_equiv_naturality_left, ← adj.hom_equiv_naturality_right], dsimp, simp -- See note [dsimp, simp]. end }, counit := { app := λ Y, (adj.hom_equiv _ _).inv_fun (𝟙 (G.obj Y)), naturality' := begin intros, erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm], dsimp, simp end }, hom_equiv_unit' := λ X Y f, by erw [← adj.hom_equiv_naturality_right]; simp, hom_equiv_counit' := λ X Y f, by erw [← adj.hom_equiv_naturality_left_symm]; simp, .. adj } /-- Construct an adjunction between functors `F` and `G` given a unit and counit for the adjunction satisfying the triangle identities. -/ @[simps] def mk_of_unit_counit (adj : core_unit_counit F G) : F ⊣ G := { hom_equiv := λ X Y, { to_fun := λ f, adj.unit.app X ≫ G.map f, inv_fun := λ g, F.map g ≫ adj.counit.app Y, left_inv := λ f, begin change F.map (_ ≫ _) ≫ _ = _, rw [F.map_comp, assoc, ←functor.comp_map, adj.counit.naturality, ←assoc], convert id_comp f, have t := congr_arg (λ t : nat_trans _ _, t.app _) adj.left_triangle, dsimp at t, simp only [id_comp] at t, exact t, end, right_inv := λ g, begin change _ ≫ G.map (_ ≫ _) = _, rw [G.map_comp, ←assoc, ←functor.comp_map, ←adj.unit.naturality, assoc], convert comp_id g, have t := congr_arg (λ t : nat_trans _ _, t.app _) adj.right_triangle, dsimp at t, simp only [id_comp] at t, exact t, end }, .. adj } /-- The adjunction between the identity functor on a category and itself. -/ def id : 𝟭 C ⊣ 𝟭 C := { hom_equiv := λ X Y, equiv.refl _, unit := 𝟙 _, counit := 𝟙 _ } -- Satisfy the inhabited linter. instance : inhabited (adjunction (𝟭 C) (𝟭 C)) := ⟨id⟩ /-- If F and G are naturally isomorphic functors, establish an equivalence of hom-sets. -/ @[simps] def equiv_homset_left_of_nat_iso {F F' : C ⥤ D} (iso : F ≅ F') {X : C} {Y : D} : (F.obj X ⟶ Y) ≃ (F'.obj X ⟶ Y) := { to_fun := λ f, iso.inv.app _ ≫ f, inv_fun := λ g, iso.hom.app _ ≫ g, left_inv := λ f, by simp, right_inv := λ g, by simp } /-- If G and H are naturally isomorphic functors, establish an equivalence of hom-sets. -/ @[simps] def equiv_homset_right_of_nat_iso {G G' : D ⥤ C} (iso : G ≅ G') {X : C} {Y : D} : (X ⟶ G.obj Y) ≃ (X ⟶ G'.obj Y) := { to_fun := λ f, f ≫ iso.hom.app _, inv_fun := λ g, g ≫ iso.inv.app _, left_inv := λ f, by simp, right_inv := λ g, by simp } /-- Transport an adjunction along an natural isomorphism on the left. -/ def of_nat_iso_left {F G : C ⥤ D} {H : D ⥤ C} (adj : F ⊣ H) (iso : F ≅ G) : G ⊣ H := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, (equiv_homset_left_of_nat_iso iso.symm).trans (adj.hom_equiv X Y) } /-- Transport an adjunction along an natural isomorphism on the right. -/ def of_nat_iso_right {F : C ⥤ D} {G H : D ⥤ C} (adj : F ⊣ G) (iso : G ≅ H) : F ⊣ H := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, (adj.hom_equiv X Y).trans (equiv_homset_right_of_nat_iso iso) } /-- Transport being a right adjoint along a natural isomorphism. -/ def right_adjoint_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [r : is_right_adjoint F] : is_right_adjoint G := { left := r.left, adj := of_nat_iso_right r.adj h } /-- Transport being a left adjoint along a natural isomorphism. -/ def left_adjoint_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [r : is_left_adjoint F] : is_left_adjoint G := { right := r.right, adj := of_nat_iso_left r.adj h } section variables {E : Type u₃} [ℰ : category.{v₃} E] (H : D ⥤ E) (I : E ⥤ D) /-- Composition of adjunctions. See https://stacks.math.columbia.edu/tag/0DV0. -/ def comp (adj₁ : F ⊣ G) (adj₂ : H ⊣ I) : F ⋙ H ⊣ I ⋙ G := { hom_equiv := λ X Z, equiv.trans (adj₂.hom_equiv _ _) (adj₁.hom_equiv _ _), unit := adj₁.unit ≫ (whisker_left F $ whisker_right adj₂.unit G) ≫ (functor.associator _ _ _).inv, counit := (functor.associator _ _ _).hom ≫ (whisker_left I $ whisker_right adj₁.counit H) ≫ adj₂.counit } /-- If `F` and `G` are left adjoints then `F ⋙ G` is a left adjoint too. -/ instance left_adjoint_of_comp {E : Type u₃} [ℰ : category.{v₃} E] (F : C ⥤ D) (G : D ⥤ E) [Fl : is_left_adjoint F] [Gl : is_left_adjoint G] : is_left_adjoint (F ⋙ G) := { right := Gl.right ⋙ Fl.right, adj := comp _ _ Fl.adj Gl.adj } /-- If `F` and `G` are right adjoints then `F ⋙ G` is a right adjoint too. -/ instance right_adjoint_of_comp {E : Type u₃} [ℰ : category.{v₃} E] {F : C ⥤ D} {G : D ⥤ E} [Fr : is_right_adjoint F] [Gr : is_right_adjoint G] : is_right_adjoint (F ⋙ G) := { left := Gr.left ⋙ Fr.left, adj := comp _ _ Gr.adj Fr.adj } end section construct_left -- 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. variables {F_obj : C → D} {G} variables (e : Π X Y, (F_obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) variables (he : ∀ X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g) include he private lemma he' {X Y Y'} (f g) : (e X Y').symm (f ≫ G.map g) = (e X Y).symm f ≫ g := by intros; rw [equiv.symm_apply_eq, he]; simp /-- 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`. -/ @[simps] def left_adjoint_of_equiv : C ⥤ D := { obj := F_obj, map := λ X X' f, (e X (F_obj X')).symm (f ≫ e X' (F_obj X') (𝟙 _)), map_comp' := λ X X' X'' f f', begin rw [equiv.symm_apply_eq, he, equiv.apply_symm_apply], conv { to_rhs, rw [assoc, ←he, id_comp, equiv.apply_symm_apply] }, simp end } /-- Show that the functor given by `left_adjoint_of_equiv` is indeed left adjoint to `G`. Dual to `adjunction_of_equiv_right`. -/ @[simps] def adjunction_of_equiv_left : left_adjoint_of_equiv e he ⊣ G := mk_of_hom_equiv { hom_equiv := e, hom_equiv_naturality_left_symm' := begin intros, erw [← he' e he, ← equiv.apply_eq_iff_eq], simp [(he _ _ _ _ _).symm] end } end construct_left section construct_right -- Construction of a right adjoint, analogous to the above. variables {F} {G_obj : D → C} variables (e : Π X Y, (F.obj X ⟶ Y) ≃ (X ⟶ G_obj Y)) variables (he : ∀ X' X Y f g, e X' Y (F.map f ≫ g) = f ≫ e X Y g) include he private lemma he' {X' X Y} (f g) : F.map f ≫ (e X Y).symm g = (e X' Y).symm (f ≫ g) := by intros; rw [equiv.eq_symm_apply, he]; simp /-- 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`. -/ @[simps] def right_adjoint_of_equiv : D ⥤ C := { obj := G_obj, map := λ Y Y' g, (e (G_obj Y) Y') ((e (G_obj Y) Y).symm (𝟙 _) ≫ g), map_comp' := λ Y Y' Y'' g g', begin rw [← equiv.eq_symm_apply, ← he' e he, equiv.symm_apply_apply], conv { to_rhs, rw [← assoc, he' e he, comp_id, equiv.symm_apply_apply] }, simp end } /-- Show that the functor given by `right_adjoint_of_equiv` is indeed right adjoint to `F`. Dual to `adjunction_of_equiv_left`. -/ @[simps] def adjunction_of_equiv_right : F ⊣ right_adjoint_of_equiv e he := mk_of_hom_equiv { hom_equiv := e, hom_equiv_naturality_left_symm' := by intros; rw [equiv.symm_apply_eq, he]; simp, hom_equiv_naturality_right' := begin intros X Y Y' g h, erw [←he, equiv.apply_eq_iff_eq, ←assoc, he' e he, comp_id, equiv.symm_apply_apply] end } end construct_right /-- If the unit and counit of a given adjunction are (pointwise) isomorphisms, then we can upgrade the adjunction to an equivalence. -/ @[simps] noncomputable def to_equivalence (adj : F ⊣ G) [∀ X, is_iso (adj.unit.app X)] [∀ Y, is_iso (adj.counit.app Y)] : C ≌ D := { functor := F, inverse := G, unit_iso := nat_iso.of_components (λ X, as_iso (adj.unit.app X)) (by simp), counit_iso := nat_iso.of_components (λ Y, as_iso (adj.counit.app Y)) (by simp) } /-- 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. -/ @[simps] noncomputable def is_right_adjoint_to_is_equivalence [is_right_adjoint G] [∀ X, is_iso ((adjunction.of_right_adjoint G).unit.app X)] [∀ Y, is_iso ((adjunction.of_right_adjoint G).counit.app Y)] : is_equivalence G := is_equivalence.of_equivalence_inverse (adjunction.of_right_adjoint G).to_equivalence end adjunction open 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 (e : C ≌ D) : e.functor ⊣ e.inverse := mk_of_unit_counit ⟨e.unit, e.counit, by { ext, dsimp, simp only [id_comp], exact e.functor_unit_comp _, }, by { ext, dsimp, simp only [id_comp], exact e.unit_inverse_comp _, }⟩ end equivalence namespace functor /-- An equivalence `E` is left adjoint to its inverse. -/ def adjunction (E : C ⥤ D) [is_equivalence E] : E ⊣ E.inv := (E.as_equivalence).to_adjunction /-- If `F` is an equivalence, it's a left adjoint. -/ @[priority 10] instance left_adjoint_of_equivalence {F : C ⥤ D} [is_equivalence F] : is_left_adjoint F := { right := _, adj := functor.adjunction F } @[simp] lemma right_adjoint_of_is_equivalence {F : C ⥤ D} [is_equivalence F] : right_adjoint F = inv F := rfl /-- If `F` is an equivalence, it's a right adjoint. -/ @[priority 10] instance right_adjoint_of_equivalence {F : C ⥤ D} [is_equivalence F] : is_right_adjoint F := { left := _, adj := functor.adjunction F.inv } @[simp] lemma left_adjoint_of_is_equivalence {F : C ⥤ D} [is_equivalence F] : left_adjoint F = inv F := rfl end functor end category_theory
6fede13255374ee687e6fd699f8a09239b569513
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/test/numbertheory-notequiv2i2jasqbsqdiv8.lean
bd3d7664d2188da4fbc1767983e14479007f0e52
[ "Apache-2.0", "MIT" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
277
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import data.real.basic example ( a b : ℤ) : ¬ ( (∃ i j, a = 2*i ∧ b=2*j) ↔ (∃ k, a^2 + b^2 = 8*k) ) := begin sorry end
6eda035ab9edae3e73757c255619b34757d2e920
572fb32b6f5b7c2bf26921ffa2abea054cce881a
/src/week_1/Part_B_sets.lean
2ad8289568ba96c28ad4c6c043de627665b11d1b
[ "Apache-2.0" ]
permissive
kgeorgiy/lean-formalising-mathematics
2deb30756d5a54bee1cfa64873e86f641c59c7dc
73429a8ded68f641c896b6ba9342450d4d3ae50f
refs/heads/master
1,683,029,640,682
1,621,403,041,000
1,621,403,041,000
367,790,347
0
0
null
null
null
null
UTF-8
Lean
false
false
4,249
lean
import tactic -- Let `Ω` be a "big underlying set" and let `X` and `Y` and `Z` be subsets variables (Ω : Type) (X Y Z : set Ω) (a b c x y z : Ω) namespace xena /-! # subsets Let's think about `X ⊆ Y`. Typeset `⊆` with `\sub` or `\ss` -/ -- `X ⊆ Y` is the same as `∀ a, a ∈ X → a ∈ Y` , by definition. lemma subset_def : X ⊆ Y ↔ ∀ a, a ∈ X → a ∈ Y := begin -- true by definition refl end lemma subset_refl : X ⊆ X := λ x hX, hX lemma subset_trans (hXY : X ⊆ Y) (hYZ : Y ⊆ Z) : X ⊆ Z := begin -- If you start with `rw subset_def at *` then you -- will have things like `hYZ : ∀ (a : Ω), a ∈ Y → a ∈ Z` -- You need to think of `hYZ` as a function, which has two -- inputs: first a term `a` of type `Ω`, and second a proof `haY` that `a ∈ Y`. -- It then produces one output `haZ`, a proof that `a ∈ Z`. -- You can also think of it as an implication: -- "if a is in Ω, and if a ∈ Y, then a ∈ Z". Because it's an implication, -- you can `apply hYZ`. This is a really useful skill! intros x hX, rw subset_def at *, exact hYZ x (hXY x hX), end /-! # Equality of sets Two sets are equal if and only if they have the same elements. The name of this theorem is `set.ext_iff`. -/ example : X = Y ↔ (∀ a, a ∈ X ↔ a ∈ Y) := set.ext_iff -- In practice, you often have a goal `⊢ X = Y` and you want to reduce -- it to `a ∈ X ↔ a ∈ Y` for an arbitary `a : Ω`. This can be done with -- the `ext` tactic. lemma subset.antisymm (hXY : X ⊆ Y) (hYX : Y ⊆ X) : X = Y := begin -- start with `ext a`, ext a, rw subset_def at *, exact ⟨hXY a, hYX a⟩ end /-! ### Unions and intersections Type `\cup` or `\un` for `∪`, and `\cap` or `\i` for `∩` -/ lemma union_def : a ∈ X ∪ Y ↔ a ∈ X ∨ a ∈ Y := begin -- true by definition refl, end lemma inter_def : a ∈ X ∩ Y ↔ a ∈ X ∧ a ∈ Y := begin -- true by definition refl, end -- You can rewrite with those lemmas above if you're not comfortable with -- assuming they're true by definition. -- union lemmas lemma union_cases {P : Prop} : (a ∈ X → P) → (a ∈ Y → P) → a ∈ X ∪ Y → P := begin intros hX hY haXuY, cases haXuY, {exact hX haXuY}, {exact hY haXuY}, end lemma union_self : X ∪ X = X := begin ext a, exact ⟨ union_cases Ω X X a (λ hxU, hxU) (λ hxU, hxU), or.inl ⟩ end lemma subset_union_left : X ⊆ X ∪ Y := λ a, or.inl lemma subset_union_right : Y ⊆ X ∪ Y := λ a, or.inr lemma union_subset_iff : X ∪ Y ⊆ Z ↔ X ⊆ Z ∧ Y ⊆ Z := ⟨ λ ha, ⟨ subset_trans Ω X (X ∪ Y) Z (subset_union_left Ω X Y) ha, subset_trans Ω Y (X ∪ Y) Z (subset_union_right Ω X Y) ha ⟩, λ ⟨hXZ, hYZ⟩ a, union_cases Ω X Y a (λ haX, hXZ haX) (λ haY, hYZ haY) ⟩ variable (W : set Ω) lemma union_subset_union (hWX : W ⊆ X) (hYZ : Y ⊆ Z) : W ∪ Y ⊆ X ∪ Z := λ a, union_cases Ω W Y a (λ aW, or.inl (hWX aW)) (λ aY, or.inr (hYZ aY)) lemma union_subset_union_left (hXY : X ⊆ Y) : X ∪ Z ⊆ Y ∪ Z := union_subset_union Ω Y Z Z X hXY (subset_refl Ω Z) -- etc etc -- intersection lemmas lemma inter_subset_left : X ∩ Y ⊆ X := λ x ⟨hxX, _⟩, hxX -- don't forget `ext` to make progress with equalities of sets lemma inter_self : X ∩ X = X := subset.antisymm _ _ _ (inter_subset_left _ _ _) (λ x hxX, ⟨hxX, hxX⟩) lemma inter_comm : X ∩ Y = Y ∩ X := subset.antisymm _ _ _ (λ x ⟨hxX, hxY⟩, ⟨hxY, hxX⟩) (λ x ⟨hxY, hxX⟩, ⟨hxX, hxY⟩) lemma inter_assoc : X ∩ (Y ∩ Z) = (X ∩ Y) ∩ Z := subset.antisymm _ _ _ (λ x ⟨hxX, ⟨hxY, hxZ⟩⟩, ⟨⟨hxX, hxY⟩, hxZ⟩) (λ x ⟨⟨hxX, hxY⟩, hxZ⟩, ⟨hxX, ⟨hxY, hxZ⟩⟩) /-! ### Forall and exists -/ lemma not_exists_iff_forall_not : ¬ (∃ a, a ∈ X) ↔ ∀ b, ¬ (b ∈ X) := ⟨ λ ha b hb, ha ⟨b, hb⟩, λ hb ⟨a, ha⟩, hb a ha ⟩ theorem contra {P : Prop}: ¬ (¬ P) → P := begin intro hnnP, by_contra, exact hnnP h, end example : ¬ (∀ a, a ∈ X) ↔ ∃ b, ¬ (b ∈ X) := ⟨ λ ha, contra (λ hX, ha (λ a, contra (λ hanX, hX ⟨a, hanX⟩))), λ ⟨b, hb⟩ ha, hb (ha b), ⟩ end xena
3b7a53be8fbfd7f388188701588858be85d25750
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/analysis/calculus/fderiv.lean
e4d2a835ab6de1bd49ff393501d33b4025035bee
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
121,660
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.tangent_cone import analysis.normed_space.units import analysis.asymptotic_equivalent import analysis.analytic.basic /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` Finally, `has_strict_fderiv_at f f' x` means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability, i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse function theorem, and is defined here only to avoid proving theorems like `is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for `has_strict_fderiv_at`. ## Main results In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * sum of finitely many functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) * inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are translated to this more elementary point of view on the derivative in the file `deriv.lean`. The derivative of polynomials is handled there, as it is naturally one-dimensional. The simplifier is set up to prove automatically that some functions are differentiable, or differentiable at a point (but not differentiable on a set or within a set at a point, as checking automatically that the good domains are mapped one to the other when using composition is not something the simplifier can easily do). This means that one can write `example (x : ℝ) : differentiable ℝ (λ x, sin (exp (3 + x^2)) - 5 * cos x) := by simp`. If there are divisions, one needs to supply to the simplifier proofs that the denominators do not vanish, as in ```lean example (x : ℝ) (h : 1 + sin x ≠ 0) : differentiable_at ℝ (λ x, exp x / (1 + sin x)) x := by simp [h] ``` Of course, these examples only work once `exp`, `cos` and `sin` have been shown to be differentiable, in `analysis.special_functions.trigonometric`. The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general complicated multidimensional linear maps), but it will compute one-dimensional derivatives, see `deriv.lean`. ## Implementation details The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. To make sure that the simplifier can prove automatically that functions are differentiable, we tag many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable functions is differentiable, as well as their product, their cartesian product, and so on. A notable exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are differentiable, then their composition also is: `simp` would always be able to match this lemma, by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`), we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding some boilerplate lemmas, but these can also be useful in their own right. Tests for this ability of the simplifier (with more examples) are provided in `tests/differentiable.lean`. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set metric open_locale topological_space classical nnreal asymptotics filter noncomputable theory section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G'] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = 𝓝[s] x` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := 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 (𝓝[s] x) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) /-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability* if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required, e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/ def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := is_o (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s) (clim : tendsto (λ n, ∥c n∥) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (𝓝[s] x), { conv in (𝓝[s] x) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (𝓝[s] x) := 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 /-- If `f'` and `f₁'` are two derivatives of `f` within `s` at `x`, then they are equal on the tangent cone to `s` at `x` -/ theorem has_fderiv_within_at.unique_on (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : eq_on f' f₁' (tangent_cone_at 𝕜 s x) := λ y ⟨c, d, dtop, clim, cdlim⟩, tendsto_nhds_unique (hf.lim at_top dtop clim cdlim) (hg.lim at_top dtop clim cdlim) /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x) (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : f' = f₁' := continuous_linear_map.ext_on H.1 (hf.unique_on hg) theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := (H x hx).eq h h₁ end derivative_uniqueness section fderiv_properties /-! ### Basic properties of the derivative -/ theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) := have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx', by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto_congr (λ _, div_eq_inv_mul), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝[s] x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) := begin rw [has_fderiv_at, has_fderiv_at_filter, ← map_add_left_nhds_zero x, is_o_map], simp [(∘)] end /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. -/ lemma has_fderiv_at.le_of_lip {f : E → F} {f' : E →L[𝕜] F} {x₀ : E} (hf : has_fderiv_at f f' x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥f'∥ ≤ C := begin refine le_of_forall_pos_le_add (λ ε ε0, op_norm_le_of_nhds_zero _ _), exact add_nonneg C.coe_nonneg ε0.le, have hs' := hs, rw [← map_add_left_nhds_zero x₀, mem_map] at hs', filter_upwards [is_o_iff.1 (has_fderiv_at_iff_is_o_nhds_zero.1 hf) ε0, hs'], intros y hy hys, have := hlip.norm_sub_le hys (mem_of_nhds hs), rw add_sub_cancel' at this, calc ∥f' y∥ ≤ ∥f (x₀ + y) - f x₀∥ + ∥f (x₀ + y) - f x₀ - f' y∥ : norm_le_insert _ _ ... ≤ C * ∥y∥ + ε * ∥y∥ : add_le_add this hy ... = (C + ε) * ∥y∥ : (add_mul _ _ _).symm end theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := h.mono hst theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono (nhds_within_mono _ hst) theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) : is_O (λ p : E × E, f p.1 - f p.2) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) := hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _) lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.is_O.congr_of_sub.2 (f'.is_O_sub _ _) protected lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) : has_fderiv_at f f' x := begin rw [has_fderiv_at, has_fderiv_at_filter, is_o_iff], exact (λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (is_o_iff.1 hf hc)) end protected lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) : differentiable_at 𝕜 f x := hf.has_fderiv_at.differentiable_at /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_nhds hU, dsimp only, rw [← mul_smul, mul_inv_cancel hy, one_smul] end theorem has_fderiv_at_unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.join ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.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 } /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. Version using `fderiv`. -/ lemma fderiv_at.le_of_lip {f : E → F} {x₀ : E} (hf : differentiable_at 𝕜 f x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥fderiv 𝕜 f x₀∥ ≤ C := hf.has_fderiv_at.le_of_lip hs hlip lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := (hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp only [mem_closure_iff_nhds_within_ne_bot, ne_bot, ne.def, not_not] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_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 lemma fderiv_within_of_mem_nhds (h : s ∈ 𝓝 x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin have : s = univ ∩ s, by simp only [univ_inter], rw [this, ← fderiv_within_univ], exact fderiv_within_inter h (unique_diff_on_univ _ (mem_univ _)) end lemma fderiv_within_of_open (hs : is_open s) (hx : x ∈ s) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := fderiv_within_of_mem_nhds (mem_nhds_sets hs hx) lemma fderiv_within_eq_fderiv (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_at 𝕜 f x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin rw ← fderiv_within_univ, exact fderiv_within_subset (subset_univ _) hs h.differentiable_within_at end lemma fderiv_mem_iff {f : E → F} {s : set (E →L[𝕜] F)} {x : E} : fderiv 𝕜 f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ s) ∨ (0 : E →L[𝕜] F) ∈ s ∧ ¬differentiable_at 𝕜 f x := begin split, { intro hfx, by_cases hx : differentiable_at 𝕜 f x, { exact or.inl ⟨hx, hfx⟩ }, { rw [fderiv_zero_of_not_differentiable_at hx] at hfx, exact or.inr ⟨hfx, hx⟩ } }, { rintro (⟨hf, hf'⟩|⟨h₀, hx⟩), { exact hf' }, { rwa [fderiv_zero_of_not_differentiable_at hx] } } end end fderiv_properties section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto.mono_left _ hL), rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds }, have := tendsto.add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at protected lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) : continuous_at f x := hf.has_fderiv_at.continuous_at lemma has_strict_fderiv_at.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) x) : is_O (λ p : E × E, p.1 - p.2) (λ p : E × E, f p.1 - f p.2) (𝓝 (x, x)) := ((f'.is_O_comp_rev _ _).trans (hf.trans_is_O (f'.is_O_comp_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) lemma has_fderiv_at_filter.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_fderiv_at_filter f (f' : E →L[𝕜] F) x L) : is_O (λ x', x' - x) (λ x', f x' - f x) L := ((f'.is_O_sub_rev _ _).trans (hf.trans_is_O (f'.is_O_sub_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) end continuous section congr /-! ### congr properties of the derivative -/ theorem filter.eventually_eq.has_strict_fderiv_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) (h' : ∀ y, f₀' y = f₁' y) : has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x := begin refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall $ λ _, rfl), rintros p ⟨hp₁, hp₂⟩, simp only [*] end theorem has_strict_fderiv_at.congr_of_eventually_eq (h : has_strict_fderiv_at f f' x) (h₁ : f =ᶠ[𝓝 x] f₁) : has_strict_fderiv_at f₁ f' x := (h₁.has_strict_fderiv_at_iff (λ _, rfl)).1 h theorem filter.eventually_eq.has_fderiv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall $ λ _, rfl) lemma has_fderiv_at_filter.congr_of_eventually_eq (h : has_fderiv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := (hL.has_fderiv_at_filter_iff hx $ λ _, rfl).2 h lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr_of_eventually_eq (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr_of_eventually_eq (h : has_fderiv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_fderiv_at.congr_of_eventually_eq (h : has_fderiv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ (mem_of_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_eventually_eq (h : differentiable_within_at 𝕜 f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_eventually_eq h₁ hx).differentiable_within_at lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s := λ x hx, (h x hx).congr h' (h' x hx) lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s := ⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm), λ h, differentiable_on.congr h h'⟩ lemma differentiable_at.congr_of_eventually_eq (h : differentiable_at 𝕜 f x) (hL : f₁ =ᶠ[𝓝 x] f) : differentiable_at 𝕜 f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_eventually_eq h.has_fderiv_at hL (mem_of_nhds hL : _)) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma filter.eventually_eq.fderiv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then has_fderiv_within_at.fderiv_within (h.has_fderiv_within_at.congr_of_eventually_eq hL hx) hs else have h' : ¬ differentiable_within_at 𝕜 f₁ s x, from mt (λ h, h.congr_of_eventually_eq (hL.mono $ λ x, eq.symm) hx.symm) h, by rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at h'] lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply filter.eventually_eq.fderiv_within_eq hs _ hx, apply mem_sets_of_superset self_mem_nhds_within, exact hL end lemma filter.eventually_eq.fderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := hL.eq_of_nhds, rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact hL.fderiv_within_eq unique_diff_within_at_univ A end end congr section id /-! ### Derivative of the identity -/ theorem has_strict_fderiv_at_id (x : E) : has_strict_fderiv_at id (id 𝕜 E) x := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id 𝕜 E) x L := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_within_at_id (x : E) (s : set E) : has_fderiv_within_at id (id 𝕜 E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id 𝕜 E) x := has_fderiv_at_filter_id _ _ @[simp] lemma differentiable_at_id : differentiable_at 𝕜 id x := (has_fderiv_at_id x).differentiable_at @[simp] lemma differentiable_at_id' : differentiable_at 𝕜 (λ x, x) x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x := differentiable_at_id.differentiable_within_at @[simp] lemma differentiable_id : differentiable 𝕜 (id : E → E) := λx, differentiable_at_id @[simp] lemma differentiable_id' : differentiable 𝕜 (λ (x : E), x) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on 𝕜 id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv 𝕜 id x = id 𝕜 E := has_fderiv_at.fderiv (has_fderiv_at_id x) @[simp] lemma fderiv_id' : fderiv 𝕜 (λ (x : E), x) x = continuous_linear_map.id 𝕜 E := fderiv_id lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id 𝕜 E := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end lemma fderiv_within_id' (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ (x : E), x) s x = continuous_linear_map.id 𝕜 E := fderiv_within_id hxs end id section const /-! ### derivative of a constant function -/ theorem has_strict_fderiv_at_const (c : F) (x : E) : has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x := has_fderiv_at_filter_const _ _ _ @[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) @[simp] lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 := by { ext m, rw fderiv_const_apply, refl } lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const_apply _ end @[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} : has_strict_fderiv_at e e x := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter @[simp] protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at @[simp] protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end @[simp] protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := h.to_continuous_linear_map.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on end continuous_linear_map section analytic variables {p : formal_multilinear_series 𝕜 E F} {r : ennreal} lemma has_fpower_series_at.has_strict_fderiv_at (h : has_fpower_series_at f p x) : has_strict_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x := begin refine h.is_O_image_sub_norm_mul_norm_sub.trans_is_o (is_o.of_norm_right _), refine is_o_iff_exists_eq_mul.2 ⟨λ y, ∥y - (x, x)∥, _, eventually_eq.rfl⟩, refine (continuous_id.sub continuous_const).norm.tendsto' _ _ _, rw [_root_.id, sub_self, norm_zero] end lemma has_fpower_series_at.has_fderiv_at (h : has_fpower_series_at f p x) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x := h.has_strict_fderiv_at.has_fderiv_at lemma has_fpower_series_at.differentiable_at (h : has_fpower_series_at f p x) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma analytic_at.differentiable_at : analytic_at 𝕜 f x → differentiable_at 𝕜 f x | ⟨p, hp⟩ := hp.differentiable_at lemma analytic_at.differentiable_within_at (h : analytic_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma has_fpower_series_at.fderiv (h : has_fpower_series_at f p x) : fderiv 𝕜 f x = continuous_multilinear_curry_fin1 𝕜 E F (p 1) := h.has_fderiv_at.fderiv lemma has_fpower_series_on_ball.differentiable_on [complete_space F] (h : has_fpower_series_on_ball f p x r) : differentiable_on 𝕜 f (emetric.ball x r) := λ y hy, (h.analytic_at_of_mem hy).differentiable_within_at end analytic 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 (𝓝[s] x) ≤ 𝓝[f '' s] (f x) : hf.continuous_within_at.tendsto_nhds_within_image ... ≤ 𝓝[t] (f x) : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := (hg.mono hf.continuous_at).comp x hf theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin rw ← has_fderiv_within_at_univ at hg, exact has_fderiv_within_at.comp x hg hf subset_preimage_univ end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩ end lemma differentiable_within_at.comp' {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma differentiable_at.comp_differentiable_within_at {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) s x := (differentiable_within_at_univ.2 hg).comp x hf (by simp) lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma fderiv.comp_fderiv_within {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at) end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (g ∘ f) s := (differentiable_on_univ.2 hg).comp hf (by simp) /-- The chain rule for derivatives in the sense of strict differentiability. -/ protected lemma has_strict_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_strict_fderiv_at g g' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, g (f x)) (g'.comp f') x := ((hg.comp_tendsto (hf.continuous_at.prod_map' hf.continuous_at)).trans_is_O hf.is_O_sub).triangle $ by simpa only [g'.map_sub, f'.coe_comp'] using (g'.is_O_comp _ _).trans_is_o hf protected lemma differentiable.iterate {f : E → E} (hf : differentiable 𝕜 f) (n : ℕ) : differentiable 𝕜 (f^[n]) := nat.rec_on n differentiable_id (λ n ihn, ihn.comp hf) protected lemma differentiable_on.iterate {f : E → E} (hf : differentiable_on 𝕜 f s) (hs : maps_to f s s) (n : ℕ) : differentiable_on 𝕜 (f^[n]) s := nat.rec_on n differentiable_on_id (λ n ihn, ihn.comp hf hs) variable {x} protected lemma has_fderiv_at_filter.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_fderiv_at_filter (f^[n]) (f'^n) x L := begin induction n with n ihn, { exact has_fderiv_at_filter_id x L }, { change has_fderiv_at_filter (f^[n] ∘ f) (f'^(n+1)) x L, rw [pow_succ'], refine has_fderiv_at_filter.comp x _ hf, rw hx, exact ihn.mono hL } end protected lemma has_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_fderiv_at (f^[n]) (f'^n) x := begin refine hf.iterate _ hx n, convert hf.continuous_at, exact hx.symm end protected lemma has_fderiv_within_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_fderiv_within_at (f^[n]) (f'^n) s x := begin refine hf.iterate _ hx n, convert tendsto_inf.2 ⟨hf.continuous_within_at, _⟩, exacts [hx.symm, (tendsto_principal_principal.2 hs).mono_left inf_le_right] end protected lemma has_strict_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_strict_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_fderiv_at (f^[n]) (f'^n) x := begin induction n with n ihn, { exact has_strict_fderiv_at_id x }, { change has_strict_fderiv_at (f^[n] ∘ f) (f'^(n+1)) x, rw [pow_succ'], refine has_strict_fderiv_at.comp x _ hf, rwa hx } end protected lemma differentiable_at.iterate {f : E → E} (hf : differentiable_at 𝕜 f x) (hx : f x = x) (n : ℕ) : differentiable_at 𝕜 (f^[n]) x := exists.elim hf $ λ f' hf, (hf.iterate hx n).differentiable_at protected lemma differentiable_within_at.iterate {f : E → E} (hf : differentiable_within_at 𝕜 f s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : differentiable_within_at 𝕜 (f^[n]) s x := exists.elim hf $ λ f' hf, (hf.iterate hx hs n).differentiable_within_at end composition section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ section prod variables {f₂ : E → G} {f₂' : E →L[𝕜] G} protected lemma has_strict_fderiv_at.prod (hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x := hf₁.prod_left hf₂ lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x L := hf₁.prod_left hf₂ lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod hf₂ lemma differentiable_within_at.prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) @[simp] lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = (fderiv 𝕜 f₁ x).prod (fderiv 𝕜 f₂ x) := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).fderiv lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = (fderiv_within 𝕜 f₁ s x).prod (fderiv_within 𝕜 f₂ s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at end end prod section fst variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_fst : has_strict_fderiv_at prod.fst (fst 𝕜 E F) p := (fst 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.fst (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := has_strict_fderiv_at_fst.comp x h lemma has_fderiv_at_filter_fst {L : filter (E × F)} : has_fderiv_at_filter prod.fst (fst 𝕜 E F) p L := (fst 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.fst (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_fst.comp x h lemma has_fderiv_at_fst : has_fderiv_at prod.fst (fst 𝕜 E F) p := has_fderiv_at_filter_fst protected lemma has_fderiv_at.fst (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := h.fst lemma has_fderiv_within_at_fst {s : set (E × F)} : has_fderiv_within_at prod.fst (fst 𝕜 E F) s p := has_fderiv_at_filter_fst protected lemma has_fderiv_within_at.fst (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') s x := h.fst lemma differentiable_at_fst : differentiable_at 𝕜 prod.fst p := has_fderiv_at_fst.differentiable_at @[simp] protected lemma differentiable_at.fst (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).1) x := differentiable_at_fst.comp x h lemma differentiable_fst : differentiable 𝕜 (prod.fst : E × F → E) := λ x, differentiable_at_fst @[simp] protected lemma differentiable.fst (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).1) := differentiable_fst.comp h lemma differentiable_within_at_fst {s : set (E × F)} : differentiable_within_at 𝕜 prod.fst s p := differentiable_at_fst.differentiable_within_at protected lemma differentiable_within_at.fst (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).1) s x := differentiable_at_fst.comp_differentiable_within_at x h lemma differentiable_on_fst {s : set (E × F)} : differentiable_on 𝕜 prod.fst s := differentiable_fst.differentiable_on protected lemma differentiable_on.fst (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).1) s := differentiable_fst.comp_differentiable_on h lemma fderiv_fst : fderiv 𝕜 prod.fst p = fst 𝕜 E F := has_fderiv_at_fst.fderiv lemma fderiv.fst (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).1) x = (fst 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.fst.fderiv lemma fderiv_within_fst {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.fst s p = fst 𝕜 E F := has_fderiv_within_at_fst.fderiv_within hs lemma fderiv_within.fst (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).1) s x = (fst 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.fst.fderiv_within hs end fst section snd variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_snd : has_strict_fderiv_at prod.snd (snd 𝕜 E F) p := (snd 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.snd (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := has_strict_fderiv_at_snd.comp x h lemma has_fderiv_at_filter_snd {L : filter (E × F)} : has_fderiv_at_filter prod.snd (snd 𝕜 E F) p L := (snd 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.snd (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_snd.comp x h lemma has_fderiv_at_snd : has_fderiv_at prod.snd (snd 𝕜 E F) p := has_fderiv_at_filter_snd protected lemma has_fderiv_at.snd (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := h.snd lemma has_fderiv_within_at_snd {s : set (E × F)} : has_fderiv_within_at prod.snd (snd 𝕜 E F) s p := has_fderiv_at_filter_snd protected lemma has_fderiv_within_at.snd (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') s x := h.snd lemma differentiable_at_snd : differentiable_at 𝕜 prod.snd p := has_fderiv_at_snd.differentiable_at @[simp] protected lemma differentiable_at.snd (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).2) x := differentiable_at_snd.comp x h lemma differentiable_snd : differentiable 𝕜 (prod.snd : E × F → F) := λ x, differentiable_at_snd @[simp] protected lemma differentiable.snd (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).2) := differentiable_snd.comp h lemma differentiable_within_at_snd {s : set (E × F)} : differentiable_within_at 𝕜 prod.snd s p := differentiable_at_snd.differentiable_within_at protected lemma differentiable_within_at.snd (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).2) s x := differentiable_at_snd.comp_differentiable_within_at x h lemma differentiable_on_snd {s : set (E × F)} : differentiable_on 𝕜 prod.snd s := differentiable_snd.differentiable_on protected lemma differentiable_on.snd (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).2) s := differentiable_snd.comp_differentiable_on h lemma fderiv_snd : fderiv 𝕜 prod.snd p = snd 𝕜 E F := has_fderiv_at_snd.fderiv lemma fderiv.snd (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).2) x = (snd 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.snd.fderiv lemma fderiv_within_snd {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.snd s p = snd 𝕜 E F := has_fderiv_within_at_snd.fderiv_within hs lemma fderiv_within.snd (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).2) s x = (snd 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.snd.fderiv_within hs end snd section prod_map variables {f₂ : G → G'} {f₂' : G →L[𝕜] G'} {y : G} (p : E × G) -- TODO (Lean 3.8): use `prod.map f f₂`` protected theorem has_strict_fderiv_at.prod_map (hf : has_strict_fderiv_at f f' p.1) (hf₂ : has_strict_fderiv_at f₂ f₂' p.2) : has_strict_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_strict_fderiv_at_fst).prod (hf₂.comp p has_strict_fderiv_at_snd) protected theorem has_fderiv_at.prod_map (hf : has_fderiv_at f f' p.1) (hf₂ : has_fderiv_at f₂ f₂' p.2) : has_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_fderiv_at_fst).prod (hf₂.comp p has_fderiv_at_snd) @[simp] protected theorem differentiable_at.prod_map (hf : differentiable_at 𝕜 f p.1) (hf₂ : differentiable_at 𝕜 f₂ p.2) : differentiable_at 𝕜 (λ p : E × G, (f p.1, f₂ p.2)) p := (hf.comp p differentiable_at_fst).prod (hf₂.comp p differentiable_at_snd) end prod_map end cartesian_product section const_smul /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : 𝕜) : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ y, f y + g y) (f' + g') x := (hf.add hg).congr_left $ λ y, by simp; abel theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp; abel theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) @[simp] lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, f y + c) f' x := add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _) theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at @[simp] lemma differentiable_within_at_add_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at @[simp] lemma differentiable_at_add_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y + c) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c @[simp] lemma differentiable_on_add_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y + c) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c @[simp] lemma differentiable_add_const_iff (c : F) : differentiable 𝕜 (λ y, f y + c) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := if hf : differentiable_within_at 𝕜 f s x then (hf.has_fderiv_within_at.add_const c).fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf, fderiv_within_zero_of_not_differentiable_within_at], simpa } lemma fderiv_add_const (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_add_const unique_diff_within_at_univ] theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, c + f y) f' x := zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at @[simp] lemma differentiable_within_at_const_add_iff (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at @[simp] lemma differentiable_at_const_add_iff (c : F) : differentiable_at 𝕜 (λ y, c + f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c @[simp] lemma differentiable_on_const_add_iff (c : F) : differentiable_on 𝕜 (λ y, c + f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c @[simp] lemma differentiable_const_add_iff (c : F) : differentiable 𝕜 (λ y, c + f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := by simpa only [add_comm] using fderiv_within_add_const hxs c lemma fderiv_const_add (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := by simp only [add_comm c, fderiv_add_const] end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (E → F)} {A' : ι → (E →L[𝕜] F)} theorem has_strict_fderiv_at.sum (h : ∀ i ∈ u, has_strict_fderiv_at (A i) (A' i) x) : has_strict_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := begin dsimp [has_strict_fderiv_at] at *, convert is_o.sum h, simp [finset.sum_sub_distrib, continuous_linear_map.sum_apply] end theorem has_fderiv_at_filter.sum (h : ∀ i ∈ u, has_fderiv_at_filter (A i) (A' i) x L) : has_fderiv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := begin dsimp [has_fderiv_at_filter] at *, convert is_o.sum h, simp [continuous_linear_map.sum_apply] end theorem has_fderiv_within_at.sum (h : ∀ i ∈ u, has_fderiv_within_at (A i) (A' i) s x) : has_fderiv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_fderiv_at_filter.sum h theorem has_fderiv_at.sum (h : ∀ i ∈ u, has_fderiv_at (A i) (A' i) x) : has_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_fderiv_at_filter.sum h theorem differentiable_within_at.sum (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : differentiable_within_at 𝕜 (λ y, ∑ i in u, A i y) s x := has_fderiv_within_at.differentiable_within_at $ has_fderiv_within_at.sum $ λ i hi, (h i hi).has_fderiv_within_at @[simp] theorem differentiable_at.sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : differentiable_at 𝕜 (λ y, ∑ i in u, A i y) x := has_fderiv_at.differentiable_at $ has_fderiv_at.sum $ λ i hi, (h i hi).has_fderiv_at theorem differentiable_on.sum (h : ∀ i ∈ u, differentiable_on 𝕜 (A i) s) : differentiable_on 𝕜 (λ y, ∑ i in u, A i y) s := λ x hx, differentiable_within_at.sum $ λ i hi, h i hi x hx @[simp] theorem differentiable.sum (h : ∀ i ∈ u, differentiable 𝕜 (A i)) : differentiable 𝕜 (λ y, ∑ i in u, A i y) := λ x, differentiable_at.sum $ λ i hi, h i hi x theorem fderiv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : fderiv_within 𝕜 (λ y, ∑ i in u, A i y) s x = (∑ i in u, fderiv_within 𝕜 (A i) s x) := (has_fderiv_within_at.sum (λ i hi, (h i hi).has_fderiv_within_at)).fderiv_within hxs theorem fderiv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : fderiv 𝕜 (λ y, ∑ i in u, A i y) x = (∑ i in u, fderiv 𝕜 (A i) x) := (has_fderiv_at.sum (λ i hi, (h i hi).has_fderiv_at)).fderiv end sum section neg /-! ### Derivative of the negative of a function -/ theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, -f x) (-f') x := (-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at @[simp] lemma differentiable_within_at_neg_iff : differentiable_within_at 𝕜 (λy, -f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at @[simp] lemma differentiable_at_neg_iff : differentiable_at 𝕜 (λy, -f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg @[simp] lemma differentiable_on_neg_iff : differentiable_on 𝕜 (λy, -f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg @[simp] lemma differentiable_neg_iff : differentiable 𝕜 (λy, -f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then h.has_fderiv_within_at.neg.fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at, neg_zero], simpa } @[simp] lemma fderiv_neg : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_neg unique_diff_within_at_univ] end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_strict_fderiv_at.sub (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ x, f x - g x) (f' - g') x := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) @[simp] lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.sub_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, f x - c) f' x := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at @[simp] lemma differentiable_within_at_sub_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x ↔ differentiable_within_at 𝕜 f s x := by simp only [sub_eq_add_neg, differentiable_within_at_add_const_iff] lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at @[simp] lemma differentiable_at_sub_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y - c) x ↔ differentiable_at 𝕜 f x := by simp only [sub_eq_add_neg, differentiable_at_add_const_iff] lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c @[simp] lemma differentiable_on_sub_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y - c) s ↔ differentiable_on 𝕜 f s := by simp only [sub_eq_add_neg, differentiable_on_add_const_iff] lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c @[simp] lemma differentiable_sub_const_iff (c : F) : differentiable 𝕜 (λ y, f y - c) ↔ differentiable 𝕜 f := by simp only [sub_eq_add_neg, differentiable_add_const_iff] lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_add_const hxs] lemma fderiv_sub_const (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := by simp only [sub_eq_add_neg, fderiv_add_const] theorem has_strict_fderiv_at.const_sub (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, c - f x) (-f') x := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at @[simp] lemma differentiable_within_at_const_sub_iff (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x ↔ differentiable_within_at 𝕜 f s x := by simp [sub_eq_add_neg] lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at @[simp] lemma differentiable_at_const_sub_iff (c : F) : differentiable_at 𝕜 (λ y, c - f y) x ↔ differentiable_at 𝕜 f x := by simp [sub_eq_add_neg] lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c @[simp] lemma differentiable_on_const_sub_iff (c : F) : differentiable_on 𝕜 (λ y, c - f y) s ↔ differentiable_on 𝕜 f s := by simp [sub_eq_add_neg] lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c @[simp] lemma differentiable_const_sub_iff (c : F) : differentiable 𝕜 (λ y, c - f y) ↔ differentiable 𝕜 f := by simp [sub_eq_add_neg] lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_const_add, fderiv_within_neg, hxs] lemma fderiv_const_sub (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_const_sub unique_diff_within_at_univ] end sub section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_strict_fderiv_at b (h.deriv p) p := begin rw has_strict_fderiv_at, set T := (E × F) × (E × F), have : is_o (λ q : T, b (q.1 - q.2)) (λ q : T, ∥q.1 - q.2∥ * 1) (𝓝 (p, p)), { refine (h.is_O'.comp_tendsto le_top).trans_is_o _, simp only [(∘)], refine (is_O_refl (λ q : T, ∥q.1 - q.2∥) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _), rw [← sub_self p], exact continuous_at_fst.sub continuous_at_snd }, simp only [mul_one, is_o_norm_right] at this, refine (is_o.congr_of_sub _).1 this, clear this, convert_to is_o (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) (λ q : T, q.1 - q.2) (𝓝 (p, p)), { ext ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩, simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right], abel }, have : is_o (λ q : T, p - q.2) (λ q, (1:ℝ)) (𝓝 (p, p)), from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd), apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o, refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right, refine is_o.mul_is_O _ (is_O_refl _ _), exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top : _).trans_is_o this).norm_left end lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := (h.has_strict_fderiv_at p).has_fderiv_at lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) : continuous b := h.differentiable.continuous lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} : continuous (λe, b (e, f)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} : continuous (λf, b (e, f)) := h.continuous.comp (continuous_const.prod_mk continuous_id) end bilinear_map namespace continuous_linear_equiv /-! ### The set of continuous linear equivalences between two Banach spaces is open In this section we establish that the set of continuous linear equivalences between two Banach spaces is an open subset of the space of linear maps between them. These facts are placed here because the proof uses `is_bounded_bilinear_map.continuous_left`, proved just above as a consequence of its differentiability. -/ protected lemma is_open [complete_space E] : is_open (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) := begin nontriviality E, rw [is_open_iff_mem_nhds, forall_range_iff], refine λ e, mem_nhds_sets _ (mem_range_self _), let O : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : F →L[𝕜] E).comp f, have h_O : continuous O := is_bounded_bilinear_map_comp.continuous_left, convert units.is_open.preimage h_O using 1, ext f', split, { rintros ⟨e', rfl⟩, exact ⟨(e'.trans e.symm).to_unit, rfl⟩ }, { rintros ⟨w, hw⟩, use (units_equiv 𝕜 E w).trans e, ext x, simp [hw] } end protected lemma nhds [complete_space E] (e : E ≃L[𝕜] F) : (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) ∈ 𝓝 (e : E →L[𝕜] F) := mem_nhds_sets continuous_linear_equiv.is_open (by simp) end continuous_linear_equiv section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function -/ variables {c : E → 𝕜} {c' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) @[simp] lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x) lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two scalar-valued functions -/ variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.mul (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } lemma differentiable_within_at.mul (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) @[simp] lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, c y * d) (d • c') x := by simpa only [smul_zero, zero_add] using hc.mul (has_strict_fderiv_at_const d x) theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, c y * d) (d • c') s x := by simpa only [smul_zero, zero_add] using hc.mul (has_fderiv_within_at_const d x s) theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, c y * d) (d • c') x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.mul_const d end lemma differentiable_within_at.mul_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, c y * d) s x := (hc.has_fderiv_within_at.mul_const d).differentiable_within_at lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, c y * d) x := (hc.has_fderiv_at.mul_const d).differentiable_at lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, c y * d) s := λx hx, (hc x hx).mul_const d lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, c y * d) := λx, (hc x).mul_const d lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_strict_fderiv_at.const_mul (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_within_at.const_mul (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, d * c y) (d • c') s x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end lemma differentiable_within_at.const_mul (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, d * c y) s x := (hc.has_fderiv_within_at.const_mul d).differentiable_within_at lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, d * c y) x := (hc.has_fderiv_at.const_mul d).differentiable_at lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, d * c y) s := λx hx, (hc x hx).const_mul d lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, d * c y) := λx, (hc x).const_mul d lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.const_mul d).fderiv_within hxs lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.const_mul d).fderiv end mul section algebra_inverse variables {R : Type*} [normed_ring R] [normed_algebra 𝕜 R] [complete_space R] open normed_ring continuous_linear_map ring /-- At an invertible element `x` of a normed algebra `R`, the Fréchet derivative of the inversion operation is the linear map `λ t, - x⁻¹ * t * x⁻¹`. -/ lemma has_fderiv_at_ring_inverse (x : units R) : has_fderiv_at ring.inverse (- (lmul_right 𝕜 R ↑x⁻¹).comp (lmul_left 𝕜 R ↑x⁻¹)) x := begin have h_is_o : is_o (λ (t : R), inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) (λ (t : R), t) (𝓝 0), { refine (inverse_add_norm_diff_second_order x).trans_is_o ((is_o_norm_norm).mp _), simp only [normed_field.norm_pow, norm_norm], have h12 : 1 < 2 := by norm_num, convert (asymptotics.is_o_pow_pow h12).comp_tendsto tendsto_norm_zero, ext, simp }, have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0), { refine tendsto_zero_iff_norm_tendsto_zero.mpr _, exact tendsto_iff_norm_tendsto_zero.mp tendsto_id }, simp only [has_fderiv_at, has_fderiv_at_filter], convert h_is_o.comp_tendsto h_lim, ext y, simp only [coe_comp', function.comp_app, lmul_right_apply, lmul_left_apply, neg_apply, inverse_unit x, units.inv_mul, add_sub_cancel'_right, mul_sub, sub_mul, one_mul], abel end lemma differentiable_at_inverse (x : units R) : differentiable_at 𝕜 (@ring.inverse R _) x := (has_fderiv_at_ring_inverse x).differentiable_at lemma fderiv_inverse (x : units R) : fderiv 𝕜 (@ring.inverse R _) x = - (lmul_right 𝕜 R ↑x⁻¹).comp (lmul_left 𝕜 R ↑x⁻¹) := (has_fderiv_at_ring_inverse x).fderiv end algebra_inverse section continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma continuous_linear_equiv.has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_strict_fderiv_at protected lemma continuous_linear_equiv.has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := iso.to_continuous_linear_map.has_fderiv_within_at protected lemma continuous_linear_equiv.has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma continuous_linear_equiv.differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma continuous_linear_equiv.differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma continuous_linear_equiv.fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma continuous_linear_equiv.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := iso.to_continuous_linear_map.fderiv_within hxs protected lemma continuous_linear_equiv.differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma continuous_linear_equiv.differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma continuous_linear_equiv.comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := begin refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩, have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x := iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H, rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this, end lemma continuous_linear_equiv.comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ, iso.comp_differentiable_within_at_iff] lemma continuous_linear_equiv.comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := begin rw [differentiable_on, differentiable_on], simp only [iso.comp_differentiable_within_at_iff], end lemma continuous_linear_equiv.comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := begin rw [← differentiable_on_univ, ← differentiable_on_univ], exact iso.comp_differentiable_on_iff end lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := begin refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩, have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl }, have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'), by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.id_comp], rw [A, B], exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H end lemma continuous_linear_equiv.comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := begin refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩, convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm end lemma continuous_linear_equiv.comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp] lemma continuous_linear_equiv.comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma continuous_linear_equiv.comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := begin by_cases h : differentiable_within_at 𝕜 f s x, { rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] }, { have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x, from mt iso.comp_differentiable_within_at_iff.1 h, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this, continuous_linear_map.comp_zero] } end lemma continuous_linear_equiv.comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := begin rw [← fderiv_within_univ, ← fderiv_within_univ], exact iso.comp_fderiv_within unique_diff_within_at_univ, end end continuous_linear_equiv /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin replace hg := hg.prod_map' hg, replace hfg := hfg.prod_mk_nhds hfg, have : is_O (λ p : F × F, g p.1 - g p.2 - f'.symm (p.1 - p.2)) (λ p : F × F, f' (g p.1 - g p.2) - (p.1 - p.2)) (𝓝 (a, a)), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p ⟨hp1, hp2⟩, simp [hp1, hp2] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p ⟨hp1, hp2⟩, simp only [(∘), hp1, hp2] } end /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin have : is_O (λ x : F, g x - g a - f'.symm (x - a)) (λ x : F, f' (g x - g a) - (x - a)) (𝓝 a), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p hp, simp [hp, hfg.self_of_nhds] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p hp, simp only [(∘), hp, hfg.self_of_nhds] } end /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` in the sense of strict differentiability at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_strict_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_strict_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_strict_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) lemma has_fderiv_within_at.eventually_ne (h : has_fderiv_within_at f f' s x) (hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) : ∀ᶠ z in 𝓝[s \ {x}] x, f z ≠ f x := begin rw [nhds_within, diff_eq, ← inf_principal, ← inf_assoc, eventually_inf_principal], have A : is_O (λ z, z - x) (λ z, f' (z - x)) (𝓝[s] x) := (is_O_iff.2 $ hf'.imp $ λ C hC, eventually_of_forall $ λ z, hC _), have : (λ z, f z - f x) ~[𝓝[s] x] (λ z, f' (z - x)) := h.trans_is_O A, simpa [not_imp_not, sub_eq_zero] using (A.trans this.is_O_symm).eq_zero_imp end lemma has_fderiv_at.eventually_ne (h : has_fderiv_at f f' x) (hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) : ∀ᶠ z in 𝓝[{x}ᶜ] x, f z ≠ f x := by simpa only [compl_eq_univ_diff] using (has_fderiv_within_at_univ.2 h).eventually_ne hf' end section /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) : maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) := begin rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : dense_range f') : unique_diff_within_at 𝕜 (f '' s) (f x) := begin refine ⟨h'.dense_of_maps_to f'.continuous hs.1 _, h.continuous_within_at.mem_closure_image hs.2⟩, show submodule.span 𝕜 (tangent_cone_at 𝕜 s x) ≤ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))).comap f', rw [submodule.span_le], exact h.maps_to_tangent_cone.mono (subset.refl _) submodule.subset_span end lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := h.unique_diff_within_at hs e'.surjective.dense_range lemma continuous_linear_equiv.unique_diff_on_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 𝕜] variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [normed_space 𝕜' E] variables [is_scalar_tower 𝕜 𝕜' E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [normed_space 𝕜' F] variables [is_scalar_tower 𝕜 𝕜' F] variables {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_at.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 /-! ### Multiplying by a complex function respects real differentiability Consider two functions `c : E → ℂ` and `f : E → F` where `F` is a complex vector space. If both `c` and `f` are differentiable over `ℝ`, then so is their product. This paragraph proves this statement, in the general version where `ℝ` is replaced by a field `𝕜`, and `ℂ` is replaced by a normed algebra `𝕜'` over `𝕜`. -/ section smul_algebra variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [normed_space 𝕜' F] variables [is_scalar_tower 𝕜 𝕜' F] variables {f : E → F} {f' : E →L[𝕜] F} {s : set E} {x : E} variables {c : E → 𝕜'} {c' : E →L[𝕜] 𝕜'} {L : filter E} theorem has_strict_fderiv_at.smul_algebra (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_algebra_right (f x)) x := (is_bounded_bilinear_map_smul_algebra.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul_algebra (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_algebra_right (f x)) s x := (is_bounded_bilinear_map_smul_algebra.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul_algebra (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_algebra_right (f x)) x := (is_bounded_bilinear_map_smul_algebra.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul_algebra (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_algebra hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul_algebra (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul_algebra hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul_algebra (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul_algebra (hf x hx) @[simp] lemma differentiable.smul_algebra (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul_algebra (hf x) lemma fderiv_within_smul_algebra (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_algebra_right (f x) := (hc.has_fderiv_within_at.smul_algebra hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul_algebra (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_algebra_right (f x) := (hc.has_fderiv_at.smul_algebra hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_algebra_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_algebra_right f) x := by simpa only [smul_zero, zero_add] using hc.smul_algebra (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_algebra_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_algebra_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul_algebra (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_algebra_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_algebra_right f) x := by simpa only [smul_zero, zero_add] using hc.smul_algebra (has_fderiv_at_const f x) lemma differentiable_within_at.smul_algebra_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_algebra_const f).differentiable_within_at lemma differentiable_at.smul_algebra_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_algebra_const f).differentiable_at lemma differentiable_on.smul_algebra_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_algebra_const f lemma differentiable.smul_algebra_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_algebra_const f lemma fderiv_within_smul_algebra_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_algebra_right f := (hc.has_fderiv_within_at.smul_algebra_const f).fderiv_within hxs lemma fderiv_smul_algebra_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_algebra_right f := (hc.has_fderiv_at.smul_algebra_const f).fderiv theorem has_strict_fderiv_at.const_smul_algebra (h : has_strict_fderiv_at f f' x) (c : 𝕜') : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul_algebra (h : has_fderiv_at_filter f f' x L) (c : 𝕜') : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul_algebra (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_algebra c theorem has_fderiv_at.const_smul_algebra (h : has_fderiv_at f f' x) (c : 𝕜') : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul_algebra c lemma differentiable_within_at.const_smul_algebra (h : differentiable_within_at 𝕜 f s x) (c : 𝕜') : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul_algebra c).differentiable_within_at lemma differentiable_at.const_smul_algebra (h : differentiable_at 𝕜 f x) (c : 𝕜') : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul_algebra c).differentiable_at lemma differentiable_on.const_smul_algebra (h : differentiable_on 𝕜 f s) (c : 𝕜') : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul_algebra c lemma differentiable.const_smul_algebra (h : differentiable 𝕜 f) (c : 𝕜') : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul_algebra c lemma fderiv_within_const_smul_algebra (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_algebra c).fderiv_within hxs lemma fderiv_const_smul_algebra (h : differentiable_at 𝕜 f x) (c : 𝕜') : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul_algebra c).fderiv end smul_algebra
b35a6dc1f1b9490df4c4493d04210f0555eab526
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/ring_theory/polynomial/cyclotomic.lean
eede9008dc62178f5123b97e4008ba9f4c0593f9
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,772
lean
/- Copyright (c) 2020 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Riccardo Brasca -/ import field_theory.splitting_field import ring_theory.roots_of_unity import algebra.polynomial.big_operators import number_theory.arithmetic_function import data.polynomial.lifts import analysis.complex.roots_of_unity import field_theory.separable /-! # Cyclotomic polynomials. For `n : ℕ` and an integral domain `R`, we define a modified version of the `n`-th cyclotomic polynomial with coefficients in `R`, denoted `cyclotomic' n R`, as `∏ (X - μ)`, where `μ` varies over the primitive `n`th roots of unity. If there is a primitive `n`th root of unity in `R` then this the standard definition. We then define the standard cyclotomic polynomial `cyclotomic n R` with coefficients in any ring `R`. ## Main definition * `cyclotomic n R` : the `n`-th cyclotomic polynomial with coefficients in `R`. ## Main results * `int_coeff_of_cycl` : If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a polynomial with integer coefficients. * `deg_of_cyclotomic` : The degree of `cyclotomic n` is `totient n`. * `prod_cyclotomic_eq_X_pow_sub_one` : `X ^ n - 1 = ∏ (cyclotomic i)`, where `i` divides `n`. * `cyclotomic_eq_prod_X_pow_sub_one_pow_moebius` : The Möbius inversion formula for `cyclotomic n R` over an abstract fraction field for `polynomial R`. * `cyclotomic.irreducible` : `cyclotomic n ℤ` is irreducible. ## Implementation details Our definition of `cyclotomic' n R` makes sense in any integral domain `R`, but the interesting results hold if there is a primitive `n`-th root of unity in `R`. In particular, our definition is not the standard one unless there is a primitive `n`th root of unity in `R`. For example, `cyclotomic' 3 ℤ = 1`, since there are no primitive cube roots of unity in `ℤ`. The main example is `R = ℂ`, we decided to work in general since the difficulties are essentially the same. To get the standard cyclotomic polynomials, we use `int_coeff_of_cycl`, with `R = ℂ`, to get a polynomial with integer coefficients and then we map it to `polynomial R`, for any ring `R`. To prove `cyclotomic.irreducible`, the irreducibility of `cyclotomic n ℤ`, we show in `minpoly_primitive_root_eq_cyclotomic` that `cyclotomic n ℤ` is the minimal polynomial of any `n`-th primitive root of unity `μ : K`, where `K` is a field of characteristic `0`. -/ open_locale classical big_operators noncomputable theory universe u namespace polynomial section cyclotomic' section integral_domain variables {R : Type*} [integral_domain R] /-- The modified `n`-th cyclotomic polynomial with coefficients in `R`, it is the usual cyclotomic polynomial if there is a primitive `n`-th root of unity in `R`. -/ def cyclotomic' (n : ℕ) (R : Type*) [integral_domain R] : polynomial R := ∏ μ in primitive_roots n R, (X - C μ) /-- The zeroth modified cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic'_zero (R : Type*) [integral_domain R] : cyclotomic' 0 R = 1 := by simp only [cyclotomic', finset.prod_empty, is_primitive_root.primitive_roots_zero] /-- The first modified cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic'_one (R : Type*) [integral_domain R] : cyclotomic' 1 R = X - 1 := begin simp only [cyclotomic', finset.prod_singleton, ring_hom.map_one, is_primitive_root.primitive_roots_one] end /-- The second modified cyclotomic polyomial is `X + 1` if the characteristic of `R` is not `2`. -/ @[simp] lemma cyclotomic'_two (R : Type*) [integral_domain R] (p : ℕ) [char_p R p] (hp : p ≠ 2) : cyclotomic' 2 R = X + 1 := begin rw [cyclotomic'], have prim_root_two : primitive_roots 2 R = {(-1 : R)}, { apply finset.eq_singleton_iff_unique_mem.2, split, { simp only [is_primitive_root.neg_one p hp, nat.succ_pos', mem_primitive_roots] }, { intros x hx, rw [mem_primitive_roots zero_lt_two] at hx, exact is_primitive_root.eq_neg_one_of_two_right hx } }, simp only [prim_root_two, finset.prod_singleton, ring_hom.map_neg, ring_hom.map_one, sub_neg_eq_add] end /-- `cyclotomic' n R` is monic. -/ lemma cyclotomic'.monic (n : ℕ) (R : Type*) [integral_domain R] : (cyclotomic' n R).monic := monic_prod_of_monic _ _ $ λ z hz, monic_X_sub_C _ /-- `cyclotomic' n R` is different from `0`. -/ lemma cyclotomic'_ne_zero (n : ℕ) (R : Type*) [integral_domain R] : cyclotomic' n R ≠ 0 := (cyclotomic'.monic n R).ne_zero /-- The natural degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma nat_degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).nat_degree = nat.totient n := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, cyclotomic'_zero, nat.totient_zero, nat_degree_one] }, rw [cyclotomic'], rw nat_degree_prod (primitive_roots n R) (λ (z : R), (X - C z)), simp only [is_primitive_root.card_primitive_roots h hpos, mul_one, nat_degree_X_sub_C, nat.cast_id, finset.sum_const, nsmul_eq_mul], intros z hz, exact X_sub_C_ne_zero z end /-- The degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).degree = nat.totient n := by simp only [degree_eq_nat_degree (cyclotomic'_ne_zero n R), nat_degree_cyclotomic' h] /-- The roots of `cyclotomic' n R` are the primitive `n`-th roots of unity. -/ lemma roots_of_cyclotomic (n : ℕ) (R : Type*) [integral_domain R] : (cyclotomic' n R).roots = (primitive_roots n R).val := by { rw cyclotomic', exact roots_prod_X_sub_C (primitive_roots n R) } end integral_domain section field variables {K : Type*} [field K] /-- If there is a primitive `n`th root of unity in `K`, then `X ^ n - 1 = ∏ (X - μ)`, where `μ` varies over the `n`-th roots of unity. -/ lemma X_pow_sub_one_eq_prod {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : X ^ n - 1 = ∏ ζ in nth_roots_finset n K, (X - C ζ) := begin rw [nth_roots_finset, ← multiset.to_finset_eq (is_primitive_root.nth_roots_nodup h)], simp only [finset.prod_mk, ring_hom.map_one], rw [nth_roots], have hmonic : (X ^ n - C (1 : K)).monic := monic_X_pow_sub_C (1 : K) (ne_of_lt hpos).symm, symmetry, apply prod_multiset_X_sub_C_of_monic_of_roots_card_eq hmonic, rw [@nat_degree_X_pow_sub_C K _ _ n hpos 1, ← nth_roots], exact is_primitive_root.card_nth_roots h end /-- `cyclotomic' n K` splits. -/ lemma cyclotomic'_splits (n : ℕ) : splits (ring_hom.id K) (cyclotomic' n K) := begin apply splits_prod (ring_hom.id K), intros z hz, simp only [splits_X_sub_C (ring_hom.id K)] end /-- If there is a primitive `n`-th root of unity in `K`, then `X ^ n - 1`splits. -/ lemma X_pow_sub_one_splits {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : splits (ring_hom.id K) (X ^ n - C (1 : K)) := begin by_cases hzero : n = 0, { simp only [hzero, ring_hom.map_one, splits_zero, pow_zero, sub_self] }, rw [splits_iff_card_roots, ← nth_roots, is_primitive_root.card_nth_roots h, nat_degree_X_pow_sub_C], exact nat.pos_of_ne_zero hzero end /-- If there is a primitive `n`-th root of unity in `K`, then `∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1`. -/ lemma prod_cyclotomic'_eq_X_pow_sub_one {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : ∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1 := begin rw [X_pow_sub_one_eq_prod hpos h], have rwcyc : ∀ i ∈ nat.divisors n, cyclotomic' i K = ∏ μ in primitive_roots i K, (X - C μ), { intros i hi, simp only [cyclotomic'] }, conv_lhs { apply_congr, skip, simp [rwcyc, H] }, rw ← finset.prod_bUnion, { simp only [is_primitive_root.nth_roots_one_eq_bUnion_primitive_roots hpos h] }, intros x hx y hy hdiff, simp only [nat.mem_divisors, and_true, ne.def, pnat.ne_zero, not_false_iff] at hx hy, refine is_primitive_root.disjoint _ _ hdiff, { exact @nat.pos_of_mem_divisors n x (nat.mem_divisors.2 hx) }, { exact @nat.pos_of_mem_divisors n y (nat.mem_divisors.2 hy) } end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic' i K)`. -/ lemma cyclotomic'_eq_X_pow_sub_one_div {ζ : K} {n : ℕ} (hpos: 0 < n) (h : is_primitive_root ζ n) : cyclotomic' n K = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic' i K) := begin rw [←prod_cyclotomic'_eq_X_pow_sub_one hpos h, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic' i K).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic'.monic i K }, rw (div_mod_by_monic_unique (cyclotomic' n K) 0 prod_monic _).1, simp only [degree_zero, zero_add], split, { rw mul_comm }, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a polynomial with integer coefficients. -/ lemma int_coeff_of_cyclotomic {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : (∃ (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K ∧ P.degree = (cyclotomic' n K).degree ∧ P.monic) := begin refine lifts_and_degree_eq_and_monic _ (cyclotomic'.monic n K), revert h ζ, apply nat.strong_induction_on n, intros k hk z hzeta, cases nat.eq_zero_or_pos k with hzero hpos, { use 1, simp only [hzero, cyclotomic'_zero, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, map_one, ring_hom.coe_of, and_self], }, by_cases hone : k = 1, { use X - 1, simp only [hone, cyclotomic'_one K, set.mem_univ, pnat.one_coe, subsemiring.coe_top, eq_self_iff_true, map_X, map_one, ring_hom.coe_of, and_self, map_sub] }, let B : polynomial K := ∏ i in nat.proper_divisors k, cyclotomic' i K, have Bmo : B.monic, { apply monic_prod_of_monic, intros i hi, exact (cyclotomic'.monic i K) }, have Bint : B ∈ lifts (int.cast_ring_hom K), { refine subsemiring.prod_mem (lifts (int.cast_ring_hom K)) _, intros x hx, have xsmall := (nat.mem_proper_divisors.1 hx).2, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hx).1, rw [mul_comm] at hd, exact hk x xsmall (is_primitive_root.pow hpos hzeta hd) }, replace Bint := lifts_and_degree_eq_and_monic Bint Bmo, obtain ⟨B₁, hB₁, hB₁deg, hB₁mo⟩ := Bint, let Q₁ : polynomial ℤ := (X ^ k - 1) /ₘ B₁, have huniq : 0 + B * cyclotomic' k K = X ^ k - 1 ∧ (0 : polynomial K).degree < B.degree, { split, { rw [zero_add, mul_comm, ←(prod_cyclotomic'_eq_X_pow_sub_one hpos hzeta), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], simp only [true_and, finset.prod_insert, not_lt, nat.mem_proper_divisors, dvd_refl] }, rw [degree_zero, bot_lt_iff_ne_bot], intro habs, exact (monic.ne_zero Bmo) (degree_eq_bot.1 habs) }, replace huniq := div_mod_by_monic_unique (cyclotomic' k K) (0 : polynomial K) Bmo huniq, simp only [lifts, ring_hom.coe_of, ring_hom.mem_srange], use Q₁, rw [(map_div_by_monic (int.cast_ring_hom K) hB₁mo), hB₁, ← huniq.1], simp end /-- If `K` is of characteristic `0` and there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K` comes from a unique polynomial with integer coefficients. -/ lemma unique_int_coeff_of_cycl [char_zero K] {ζ : K} {n : ℕ+} (h : is_primitive_root ζ n) : (∃! (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K) := begin obtain ⟨P, hP⟩ := int_coeff_of_cyclotomic h, rw exists_unique, use [P, hP.1], intros Q hQ, have mapinj : function.injective (map (int.cast_ring_hom K)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, rw [function.injective] at mapinj, apply mapinj, rw [hP.1, hQ] end end field end cyclotomic' section cyclotomic /-- The `n`-th cyclotomic polynomial with coefficients in `R`. -/ def cyclotomic (n : ℕ) (R : Type*) [ring R] : polynomial R := if h : n = 0 then 1 else map (int.cast_ring_hom R) (classical.some (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n h))) lemma int_cyclotomic_rw {n : ℕ} (h : n ≠ 0) : cyclotomic n ℤ = (classical.some (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n h))) := begin simp only [cyclotomic, h, dif_neg, not_false_iff], ext i, simp only [coeff_map, int.cast_id, ring_hom.eq_int_cast] end /-- `cyclotomic n R` comes from `cyclotomic n ℤ`. -/ lemma map_cyclotomic_int (n : ℕ) (R : Type*) [ring R] : map (int.cast_ring_hom R) (cyclotomic n ℤ) = cyclotomic n R := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, dif_pos, map_one] }, simp only [cyclotomic, int_cyclotomic_rw, hzero, ne.def, dif_neg, not_false_iff] end lemma int_cyclotomic_spec (n : ℕ) : map (int.cast_ring_hom ℂ) (cyclotomic n ℤ) = cyclotomic' n ℂ ∧ (cyclotomic n ℤ).degree = (cyclotomic' n ℂ).degree ∧ (cyclotomic n ℤ).monic := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, degree_one, monic_one, cyclotomic'_zero, dif_pos, eq_self_iff_true, map_one, and_self] }, rw int_cyclotomic_rw hzero, exact classical.some_spec (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n hzero)) end lemma int_cyclotomic_unique {n : ℕ} {P : polynomial ℤ} (h : map (int.cast_ring_hom ℂ) P = cyclotomic' n ℂ) : P = cyclotomic n ℤ := begin have mapinj : function.injective (map (int.cast_ring_hom ℂ)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, apply mapinj, rw [h, (int_cyclotomic_spec n).1] end /-- The definition of `cyclotomic n R` commutes with any ring homomorphism. -/ @[simp] lemma map_cyclotomic (n : ℕ) {R S : Type*} [ring R] [ring S] (f : R →+* S) : map f (cyclotomic n R) = cyclotomic n S := begin rw [←map_cyclotomic_int n R, ←map_cyclotomic_int n S], ext i, simp only [coeff_map, ring_hom.eq_int_cast, ring_hom.map_int_cast] end /-- The zeroth cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic_zero (R : Type*) [ring R] : cyclotomic 0 R = 1 := by simp only [cyclotomic, dif_pos] /-- The first cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic_one (R : Type*) [ring R] : cyclotomic 1 R = X - 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X - 1) = cyclotomic' 1 ℂ, { simp only [cyclotomic'_one, pnat.one_coe, map_X, map_one, map_sub] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_X, map_one, map_sub] end /-- The second cyclotomic polyomial is `X + 1`. -/ @[simp] lemma cyclotomic_two (R : Type*) [ring R] : cyclotomic 2 R = X + 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X + 1) = cyclotomic' 2 ℂ, { simp only [cyclotomic'_two ℂ 0 two_ne_zero.symm, map_add, map_X, map_one] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_add, map_X, map_one] end /-- `cyclotomic n` is monic. -/ lemma cyclotomic.monic (n : ℕ) (R : Type*) [ring R] : (cyclotomic n R).monic := begin rw ←map_cyclotomic_int, apply monic_map, exact (int_cyclotomic_spec n).2.2 end /-- `cyclotomic n R` is different from `0`. -/ lemma cyclotomic_ne_zero (n : ℕ) (R : Type*) [ring R] [nontrivial R] : cyclotomic n R ≠ 0 := monic.ne_zero (cyclotomic.monic n R) /-- The degree of `cyclotomic n` is `totient n`. -/ lemma degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).degree = nat.totient n := begin rw ←map_cyclotomic_int, rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom R) _, { cases n with k, { simp only [cyclotomic, degree_one, dif_pos, nat.totient_zero, with_top.coe_zero]}, rw [←degree_cyclotomic' (complex.is_primitive_root_exp k.succ (nat.succ_ne_zero k))], exact (int_cyclotomic_spec k.succ).2.1 }, simp only [(int_cyclotomic_spec n).right.right, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def, not_false_iff, one_ne_zero] end /-- The natural degree of `cyclotomic n` is `totient n`. -/ lemma nat_degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).nat_degree = nat.totient n := begin have hdeg := degree_cyclotomic n R, rw degree_eq_nat_degree (cyclotomic_ne_zero n R) at hdeg, norm_cast at hdeg, exact hdeg end /-- The degree of `cyclotomic n R` is positive. -/ lemma degree_cyclotomic_pos (n : ℕ) (R : Type*) (hpos : 0 < n) [ring R] [nontrivial R] : 0 < (cyclotomic n R).degree := by { rw degree_cyclotomic n R; exact_mod_cast (nat.totient_pos hpos) } /-- `∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1`. -/ lemma prod_cyclotomic_eq_X_pow_sub_one {n : ℕ} (hpos : 0 < n) (R : Type*) [comm_ring R] : ∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1 := begin have integer : ∏ i in nat.divisors n, cyclotomic i ℤ = X ^ n - 1, { have mapinj : function.injective (map (int.cast_ring_hom ℂ)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, apply mapinj, rw map_prod (int.cast_ring_hom ℂ) (λ i, cyclotomic i ℤ), simp only [int_cyclotomic_spec, map_pow, nat.cast_id, map_X, map_one, ring_hom.coe_of, map_sub], exact prod_cyclotomic'_eq_X_pow_sub_one hpos (complex.is_primitive_root_exp n (ne_of_lt hpos).symm) }, have coerc : X ^ n - 1 = map (int.cast_ring_hom R) (X ^ n - 1), { simp only [map_pow, map_X, map_one, map_sub] }, have h : ∀ i ∈ n.divisors, cyclotomic i R = map (int.cast_ring_hom R) (cyclotomic i ℤ), { intros i hi, exact (map_cyclotomic_int i R).symm }, rw [finset.prod_congr (refl n.divisors) h, coerc, ←map_prod (int.cast_ring_hom R) (λ i, cyclotomic i ℤ), integer] end section arithmetic_function open nat.arithmetic_function open_locale arithmetic_function /-- `cyclotomic n R` can be expressed as a product in a fraction field of `polynomial R` using Möbius inversion. -/ lemma cyclotomic_eq_prod_X_pow_sub_one_pow_moebius {n : ℕ} (hpos : 0 < n) (R : Type*) [comm_ring R] [nontrivial R] {K : Type*} [field K] (f : fraction_map (polynomial R) K) : f.to_map (cyclotomic n R) = ∏ i in n.divisors_antidiagonal, (f.to_map (X ^ i.snd - 1)) ^ μ i.fst := begin have h : ∀ (n : ℕ), 0 < n → ∏ i in nat.divisors n, f.to_map (cyclotomic i R) = f.to_map (X ^ n - 1), { intros n hn, rw [← prod_cyclotomic_eq_X_pow_sub_one hn R, ring_hom.map_prod] }, rw (prod_eq_iff_prod_pow_moebius_eq_of_nonzero (λ n hn, _) (λ n hn, _)).1 h n hpos; rw [ne.def, fraction_map.to_map_eq_zero_iff], { apply cyclotomic_ne_zero }, { apply monic.ne_zero, apply monic_X_pow_sub_C _ (ne_of_gt hn) } end end arithmetic_function /-- We have `cyclotomic n R = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic i K)`. -/ lemma cyclotomic_eq_X_pow_sub_one_div {R : Type*} [comm_ring R] [nontrivial R] {n : ℕ} (hpos: 0 < n) : cyclotomic n R = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic i R) := begin rw [←prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw (div_mod_by_monic_unique (cyclotomic n R) 0 prod_monic _).1, simp only [degree_zero, zero_add], split, { rw mul_comm }, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If `m` is a proper divisor of `n`, then `X ^ m - 1` divides `∏ i in nat.proper_divisors n, cyclotomic i R`. -/ lemma X_pow_sub_one_dvd_prod_cyclotomic (R : Type*) [comm_ring R] {n m : ℕ} (hpos : 0 < n) (hm : m ∣ n) (hdiff : m ≠ n) : X ^ m - 1 ∣ ∏ i in nat.proper_divisors n, cyclotomic i R := begin replace hm := nat.mem_proper_divisors.2 ⟨hm, lt_of_le_of_ne (nat.divisor_le (nat.mem_divisors.2 ⟨hm, (ne_of_lt hpos).symm⟩)) hdiff⟩, rw [← finset.sdiff_union_of_subset (nat.divisors_subset_proper_divisors (ne_of_lt hpos).symm (nat.mem_proper_divisors.1 hm).1 (ne_of_lt (nat.mem_proper_divisors.1 hm).2)), finset.prod_union finset.sdiff_disjoint, prod_cyclotomic_eq_X_pow_sub_one (nat.pos_of_mem_proper_divisors hm)], exact ⟨(∏ (x : ℕ) in n.proper_divisors \ m.divisors, cyclotomic x R), by rw mul_comm⟩ end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K = ∏ μ in primitive_roots n R, (X - C μ)`. In particular, `cyclotomic n K = cyclotomic' n K` -/ lemma cyclotomic_eq_prod_X_sub_primitive_roots {K : Type*} [field K] {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : cyclotomic n K = ∏ μ in primitive_roots n K, (X - C μ) := begin rw ←cyclotomic', revert h ζ, apply nat.strong_induction_on n, intros k hk z hz, cases nat.eq_zero_or_pos k with hzero hpos, { simp only [hzero, cyclotomic'_zero, cyclotomic_zero] }, have h : ∀ i ∈ k.proper_divisors, cyclotomic i K = cyclotomic' i K, { intros i hi, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hi).1, rw mul_comm at hd, exact hk i (nat.mem_proper_divisors.1 hi).2 (is_primitive_root.pow hpos hz hd) }, rw [@cyclotomic_eq_X_pow_sub_one_div _ _ (field.to_nontrivial K) _ hpos, cyclotomic'_eq_X_pow_sub_one_div hpos hz, finset.prod_congr (refl k.proper_divisors) h] end /-- Any `n`-th primitive root of unity is a root of `cyclotomic n ℤ`.-/ lemma is_root_cyclotomic {n : ℕ} {K : Type*} [field K] (hpos : 0 < n) {μ : K} (h : is_primitive_root μ n) : is_root (cyclotomic n K) μ := begin rw [← mem_roots (cyclotomic_ne_zero n K), cyclotomic_eq_prod_X_sub_primitive_roots h, roots_prod_X_sub_C, ← finset.mem_def], rwa [← mem_primitive_roots hpos] at h, end lemma eq_cyclotomic_iff {R : Type*} [comm_ring R] [nontrivial R] {n : ℕ} (hpos: 0 < n) (P : polynomial R) : P = cyclotomic n R ↔ P * (∏ i in nat.proper_divisors n, polynomial.cyclotomic i R) = X ^ n - 1 := begin split, { intro hcycl, rw [hcycl, ← finset.prod_insert (@nat.proper_divisors.not_self_mem n), ← nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], exact prod_cyclotomic_eq_X_pow_sub_one hpos R }, { intro hP, have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw [@cyclotomic_eq_X_pow_sub_one_div R _ _ _ hpos, (div_mod_by_monic_unique P 0 prod_monic _).1], split, { rwa [zero_add, mul_comm] }, rw [degree_zero, bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) }, end /-- If `p` is prime, then `cyclotomic p R = geom_series X p`. -/ lemma cyclotomic_eq_geom_series {R : Type*} [comm_ring R] [nontrivial R] {p : ℕ} (hp : nat.prime p) : cyclotomic p R = geom_series X p := begin symmetry, refine (eq_cyclotomic_iff hp.pos _).mpr _, simp only [nat.prime.proper_divisors hp, geom_sum_mul, finset.prod_singleton, cyclotomic_one], end /-- The constant term of `cyclotomic n R` is `1` if `2 ≤ n`. -/ lemma cyclotomic_coeff_zero (R : Type*) [comm_ring R] {n : ℕ} (hn : 2 ≤ n) : (cyclotomic n R).coeff 0 = 1 := begin induction n using nat.strong_induction_on with n hi, have hprod : (∏ i in nat.proper_divisors n, (polynomial.cyclotomic i R).coeff 0) = -1, { rw [←finset.insert_erase (nat.one_mem_proper_divisors_iff_one_lt.2 (lt_of_lt_of_le one_lt_two hn)), finset.prod_insert (finset.not_mem_erase 1 _), cyclotomic_one R], have hleq : ∀ j ∈ n.proper_divisors.erase 1, 2 ≤ j, { intros j hj, apply nat.succ_le_of_lt, exact (ne.le_iff_lt ((finset.mem_erase.1 hj).1).symm).mp (nat.succ_le_of_lt (nat.pos_of_mem_proper_divisors (finset.mem_erase.1 hj).2)) }, have hcongr : ∀ j ∈ n.proper_divisors.erase 1, (cyclotomic j R).coeff 0 = 1, { intros j hj, exact hi j (nat.mem_proper_divisors.1 (finset.mem_erase.1 hj).2).2 (hleq j hj) }, have hrw : ∏ (x : ℕ) in n.proper_divisors.erase 1, (cyclotomic x R).coeff 0 = 1, { rw finset.prod_congr (refl (n.proper_divisors.erase 1)) hcongr, simp only [finset.prod_const_one] }, simp only [hrw, mul_one, zero_sub, coeff_one_zero, coeff_X_zero, coeff_sub] }, have heq : (X ^ n - 1).coeff 0 = -(cyclotomic n R).coeff 0, { rw [←prod_cyclotomic_eq_X_pow_sub_one (lt_of_lt_of_le zero_lt_two hn), nat.divisors_eq_proper_divisors_insert_self_of_pos (lt_of_lt_of_le zero_lt_two hn), finset.prod_insert nat.proper_divisors.not_self_mem, mul_coeff_zero, coeff_zero_prod, hprod, mul_neg_eq_neg_mul_symm, mul_one] }, have hzero : (X ^ n - 1).coeff 0 = (-1 : R), { rw coeff_zero_eq_eval_zero _, simp only [zero_pow (lt_of_lt_of_le zero_lt_two hn), eval_X, eval_one, zero_sub, eval_pow, eval_sub] }, rw hzero at heq, exact neg_inj.mp (eq.symm heq) end /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime, then `a` and `p` are coprime. -/ lemma coprime_of_root_cyclotomic {n : ℕ} (hpos : 0 < n) {p : ℕ} [hprime : fact p.prime] {a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : a.coprime p := begin apply nat.coprime.symm, rw [nat.prime.coprime_iff_not_dvd hprime], by_contra h, replace h := (zmod.nat_coe_zmod_eq_zero_iff_dvd a p).2 h, rw [is_root.def, ring_hom.eq_nat_cast, h, ← coeff_zero_eq_eval_zero] at hroot, by_cases hone : n = 1, { simp only [hone, cyclotomic_one, zero_sub, coeff_one_zero, coeff_X_zero, neg_eq_zero, one_ne_zero, coeff_sub] at hroot, exact hroot }, rw [cyclotomic_coeff_zero (zmod p) (nat.succ_le_of_lt (lt_of_le_of_ne (nat.succ_le_of_lt hpos) (ne.symm hone)))] at hroot, exact one_ne_zero hroot end end cyclotomic section order /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, then the multiplicative order of `a` modulo `p` divides `n`. -/ lemma order_of_root_cyclotomic_dvd {n : ℕ} (hpos : 0 < n) {p : ℕ} [hprime : fact p.prime] {a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) ∣ n := begin apply order_of_dvd_of_pow_eq_one, suffices hpow : eval (nat.cast_ring_hom (zmod p) a) (X ^ n - 1 : polynomial (zmod p)) = 0, { simp only [eval_X, eval_one, eval_pow, eval_sub, ring_hom.eq_nat_cast] at hpow, apply units.coe_eq_one.1, simp only [sub_eq_zero.mp hpow, zmod.cast_unit_of_coprime, units.coe_pow] }, rw [is_root.def] at hroot, rw [← prod_cyclotomic_eq_X_pow_sub_one hpos (zmod p), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem, eval_mul, hroot, zero_mul] end /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime that does not divide `n`, then the multiplicative order of `a` modulo `p` is exactly `n`. -/ lemma order_of_root_cyclotomic {n : ℕ} (hpos : 0 < n) {p : ℕ} [hprime : fact p.prime] {a : ℕ} (hn : ¬ p ∣ n) (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) = n := begin set m := order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)), have ha := coprime_of_root_cyclotomic hpos hroot, have hdivcycl : map (int.cast_ring_hom (zmod p)) (X - a) ∣ (cyclotomic n (zmod p)), { replace hrootdiv := dvd_iff_is_root.2 hroot, simp only [C_eq_nat_cast, ring_hom.eq_nat_cast] at hrootdiv, simp only [hrootdiv, map_nat_cast, map_X, map_sub] }, by_contra hdiff, have hdiv : map (int.cast_ring_hom (zmod p)) (X - a) ∣ ∏ i in nat.proper_divisors n, cyclotomic i (zmod p), { suffices hdivm : map (int.cast_ring_hom (zmod p)) (X - a) ∣ X ^ m - 1, { exact dvd_trans hdivm (X_pow_sub_one_dvd_prod_cyclotomic (zmod p) hpos (order_of_root_cyclotomic_dvd hpos hroot) hdiff) }, rw [map_sub, map_X, map_nat_cast, ← C_eq_nat_cast, dvd_iff_is_root, is_root.def, eval_sub, eval_pow, eval_one, eval_X, sub_eq_zero, ← zmod.cast_unit_of_coprime a ha, ← units.coe_pow, units.coe_eq_one], exact pow_order_of_eq_one (zmod.unit_of_coprime a ha) }, have habs : (map (int.cast_ring_hom (zmod p)) (X - a)) ^ 2 ∣ X ^ n - 1, { obtain ⟨P, hP⟩ := hdivcycl, obtain ⟨Q, hQ⟩ := hdiv, rw [← prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem, hP, hQ], exact ⟨P * Q, by ring⟩ }, have hnzero : ↑n ≠ (0 : (zmod p)), { intro ha, exact hn (int.coe_nat_dvd.1 ((zmod.int_coe_zmod_eq_zero_iff_dvd n p).1 ha)) }, rw [pow_two] at habs, replace habs := squarefree_X_pow_sub_C (1 : (zmod p)) hnzero one_ne_zero (map (int.cast_ring_hom (zmod p)) (X - a)) habs, simp only [map_nat_cast, map_X, map_sub] at habs, replace habs := degree_eq_zero_of_is_unit habs, rw [← C_eq_nat_cast, degree_X_sub_C] at habs, norm_cast at habs end end order end polynomial section minpoly open is_primitive_root polynomial complex /-- The minimal polynomial of a primitive `n`-th root of unity `μ` divides `cyclotomic n ℤ`. -/ lemma minpoly_primitive_root_dvd_cyclotomic {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : minpoly ℤ μ ∣ cyclotomic n ℤ := begin apply minpoly.integer_dvd (is_integral h hpos) (cyclotomic.monic n ℤ).is_primitive, simpa [aeval_def, eval₂_eq_eval_map, is_root.def] using is_root_cyclotomic hpos h end /-- `cyclotomic n ℤ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma cyclotomic_eq_minpoly {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : cyclotomic n ℤ = minpoly ℤ μ := begin refine eq_of_monic_of_dvd_of_nat_degree_le (minpoly.monic (is_integral h hpos)) (cyclotomic.monic n ℤ) (minpoly_primitive_root_dvd_cyclotomic h hpos) _, simpa [nat_degree_cyclotomic n ℤ] using totient_le_degree_minpoly h hpos end /-- `cyclotomic n ℤ` is irreducible. -/ lemma cyclotomic.irreducible {n : ℕ} (hpos : 0 < n) : irreducible (cyclotomic n ℤ) := begin have h0 := (ne_of_lt hpos).symm, rw [cyclotomic_eq_minpoly (is_primitive_root_exp n h0) hpos], exact minpoly.irreducible (is_integral (is_primitive_root_exp n h0) hpos) end end minpoly
72220c2ec1c92d93d9424ad2c24fe4baa3fd0142
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/meta/name.lean
e55e4e0090d3449747b13841fdb17ea5c03332ef
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,381
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.ordering init.coe /- Reflect a C++ name object. The VM replaces it with the C++ implementation. -/ inductive name | anonymous : name | mk_string : string → name → name | mk_numeral : unsigned → name → name /-- Gadget for automatic parameter support. This is similar to the opt_param gadget, but it uses the tactic declaration names tac_name to synthesize the argument. Like opt_param, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ @[reducible] def {u} auto_param (α : Sort u) (tac_name : name) : Sort u := α instance : inhabited name := ⟨name.anonymous⟩ def mk_str_name (n : name) (s : string) : name := name.mk_string s n def mk_num_name (n : name) (v : nat) : name := name.mk_numeral (unsigned.of_nat' v) n def mk_simple_name (s : string) : name := mk_str_name name.anonymous s instance string_to_name : has_coe string name := ⟨mk_simple_name⟩ infix ` <.> `:65 := mk_str_name open name def name.get_prefix : name → name | anonymous := anonymous | (mk_string s p) := p | (mk_numeral s p) := p def name.update_prefix : name → name → name | anonymous new_p := anonymous | (mk_string s p) new_p := mk_string s new_p | (mk_numeral s p) new_p := mk_numeral s new_p def name.to_string_with_sep (sep : string) : name → string | anonymous := "[anonymous]" | (mk_string s anonymous) := s | (mk_numeral v anonymous) := to_string v | (mk_string s n) := name.to_string_with_sep n ++ sep ++ s | (mk_numeral v n) := name.to_string_with_sep n ++ sep ++ to_string v private def name.components' : name -> list name | anonymous := [] | (mk_string s n) := mk_string s anonymous :: name.components' n | (mk_numeral v n) := mk_numeral v anonymous :: name.components' n def name.components (n : name) : list name := (name.components' n)^.reverse def name.to_string : name → string := name.to_string_with_sep "." instance : has_to_string name := ⟨name.to_string⟩ /- TODO(Leo): provide a definition in Lean. -/ meta constant name.has_decidable_eq : decidable_eq name /- Both cmp and lex_cmp are total orders, but lex_cmp implements a lexicographical order. -/ meta constant name.cmp : name → name → ordering meta constant name.lex_cmp : name → name → ordering meta constant name.append : name → name → name meta constant name.is_internal : name → bool attribute [instance] name.has_decidable_eq meta instance : has_ordering name := ⟨name.cmp⟩ meta instance : has_append name := ⟨name.append⟩ /- (name.append_after n i) return a name of the form n_i -/ meta constant name.append_after : name → nat → name meta def name.is_prefix_of : name → name → bool | p name.anonymous := ff | p n := if p = n then tt else name.is_prefix_of p n^.get_prefix meta def name.replace_prefix : name → name → name → name | anonymous p p' := anonymous | (mk_string s c) p p' := if c = p then mk_string s p' else mk_string s (name.replace_prefix c p p') | (mk_numeral v c) p p' := if c = p then mk_numeral v p' else mk_numeral v (name.replace_prefix c p p')
46ecc651b223f805f7c954dcbeb2837aeafd30e9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/multiset/antidiagonal.lean
b6559484d44a88b23ea456ea0a666b940ff04f78
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,416
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.multiset.powerset import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # The antidiagonal on a multiset. The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)` such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/ namespace multiset /-- The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)` such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/ def antidiagonal {α : Type u_1} (s : multiset α) : multiset (multiset α × multiset α) := quot.lift_on s (fun (l : List α) => ↑(list.revzip (powerset_aux l))) sorry theorem antidiagonal_coe {α : Type u_1} (l : List α) : antidiagonal ↑l = ↑(list.revzip (powerset_aux l)) := rfl @[simp] theorem antidiagonal_coe' {α : Type u_1} (l : List α) : antidiagonal ↑l = ↑(list.revzip (powerset_aux' l)) := quot.sound revzip_powerset_aux_perm_aux' /-- A pair `(t₁, t₂)` of multisets is contained in `antidiagonal s` if and only if `t₁ + t₂ = s`. -/ @[simp] theorem mem_antidiagonal {α : Type u_1} {s : multiset α} {x : multiset α × multiset α} : x ∈ antidiagonal s ↔ prod.fst x + prod.snd x = s := sorry @[simp] theorem antidiagonal_map_fst {α : Type u_1} (s : multiset α) : map prod.fst (antidiagonal s) = powerset s := sorry @[simp] theorem antidiagonal_map_snd {α : Type u_1} (s : multiset α) : map prod.snd (antidiagonal s) = powerset s := sorry @[simp] theorem antidiagonal_zero {α : Type u_1} : antidiagonal 0 = (0, 0) ::ₘ 0 := rfl @[simp] theorem antidiagonal_cons {α : Type u_1} (a : α) (s : multiset α) : antidiagonal (a ::ₘ s) = map (prod.map id (cons a)) (antidiagonal s) + map (prod.map (cons a) id) (antidiagonal s) := sorry @[simp] theorem card_antidiagonal {α : Type u_1} (s : multiset α) : coe_fn card (antidiagonal s) = bit0 1 ^ coe_fn card s := sorry theorem prod_map_add {α : Type u_1} {β : Type u_2} [comm_semiring β] {s : multiset α} {f : α → β} {g : α → β} : prod (map (fun (a : α) => f a + g a) s) = sum (map (fun (p : multiset α × multiset α) => prod (map f (prod.fst p)) * prod (map g (prod.snd p))) (antidiagonal s)) := sorry
49885f9ea1fdbaadac195c2471dab5735ecce3e7
7282d49021d38dacd06c4ce45a48d09627687fe0
/tests/lean/simp23.lean
39a6bb18558add64dbf1f6ebf348c1a94cafbf05
[ "Apache-2.0" ]
permissive
steveluc/lean
5a0b4431acefaf77f15b25bbb49294c2449923ad
92ba4e8b2d040a799eda7deb8d2a7cdd3e69c496
refs/heads/master
1,611,332,256,930
1,391,013,244,000
1,391,013,244,000
16,361,079
1
0
null
null
null
null
UTF-8
Lean
false
false
1,112
lean
import cast variable vec : Nat → Type variable concat {n m : Nat} (v : vec n) (w : vec m) : vec (n + m) infixl 65 ; : concat axiom concat_assoc {n1 n2 n3 : Nat} (v1 : vec n1) (v2 : vec n2) (v3 : vec n3) : (v1 ; v2) ; v3 = cast (congr2 vec (symm (Nat::add_assoc n1 n2 n3))) (v1 ; (v2 ; v3)) variable empty : vec 0 axiom concat_empty {n : Nat} (v : vec n) : v ; empty = cast (congr2 vec (symm (Nat::add_zeror n))) v rewrite_set simple add_rewrite concat_assoc concat_empty Nat::add_assoc Nat::add_zeror and_truer eq_id : simple variable n : Nat variable v : vec n variable w : vec n variable f {A : TypeM} : A → A variable p {A : TypeM} : A → Bool axiom fax {n m : Nat} (v : vec n) (w : vec m) : f (v; (w; v)) = v; (w; v) add_rewrite fax : simple (* local t = parse_lean([[ p (f ((v ; w) ; empty ; (v ; empty))) ∧ v = cast (congr2 vec (Nat::add_zeror n)) (v ; empty) ]]) print(t) print("===>") local t2, pr = simplify(t, "simple") print(t2) print("checking proof") print (get_environment():type_check(pr)) *)
2306ae83d0af02251fd60bb4df18a75dfd883702
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/measure_theory/hausdorff_measure.lean
bc02198e0843c6a237030237aab882f3eb6ff069
[ "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
25,595
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 topology.metric_space.metric_separated import measure_theory.borel_space import analysis.special_functions.pow /-! # Hausdorff measure and metric (outer) measures In this file we define the `d`-dimensional Hausdorff measure on an (extended) metric space `X` and the Hausdorff dimension of a set in an (extended) metric space. Let `μ d δ` be the maximal outer measure such that `μ d δ s ≤ (emetric.diam s) ^ d` for every set of diameter less than `δ`. Then the Hausdorff measure `μH[d] s` of `s` is defined as `⨆ δ > 0, μ d δ s`. By Caratheodory theorem `measure_theory.outer_measure.is_metric.borel_le_caratheodory`, this is a Borel measure on `X`. The value of `μH[d]`, `d > 0`, on a set `s` (measurable or not) is given by ``` μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, emetric.diam (t n) ≤ r), ∑' n, emetric.diam (t n) ^ d ``` For every set `s` for any `d < d'` we have either `μH[d] s = ∞` or `μH[d'] s = 0`, see `measure_theory.measure.hausdorff_measure_zero_or_top`. The Hausdorff dimension `dimH s : ℝ≥0∞` of a set `s` is the supremum of `d : ℝ≥0` such that `μH[d] s = ∞`. Then `μH[d] s = ∞` for `d < dimH s` and `μH[d] s = 0` for `dimH s < d`. We also define two generalizations of the Hausdorff measure. In one generalization (see `measure_theory.measure.mk_metric`) we take any function `m (diam s)` instead of `(diam s) ^ d`. In an even more general definition (see `measure_theory.measure.mk_metric'`) we use any function of `m : set X → ℝ≥0∞`. Some authors start with a partial function `m` defined only on some sets `s : set X` (e.g., only on balls or only on measurable sets). This is equivalent to our definition applied to `measure_theory.extend m`. We also define a predicate `measure_theory.outer_measure.is_metric` which says that an outer measure is additive on metric separated pairs of sets: `μ (s ∪ t) = μ s + μ t` provided that `⨅ (x ∈ s) (y ∈ t), edist x y ≠ 0`. This is the property required for the Caratheodory theorem `measure_theory.outer_measure.is_metric.borel_le_caratheodory`, so we prove this theorem for any metric outer measure, then prove that outer measures constructed using `mk_metric'` are metric outer measures. ## Notations We use the following notation localized in `measure_theory`. - `μH[d]` : `measure_theory.measure.hausdorff_measure d` ## Implementation notes There are a few similar constructions called the `d`-dimensional Hausdorff measure. E.g., some sources only allow coverings by balls and use `r ^ d` instead of `(diam s) ^ d`. While these construction lead to different Hausdorff measures, they lead to the same notion of the Hausdorff dimension. ## References * [Herbert Federer, Geometric Measure Theory, Chapter 2.10][Federer1996] ## Tags Hausdorff measure, Hausdorff dimension, dimension, measure, metric measure -/ open_locale nnreal ennreal topological_space big_operators open emetric set function filter noncomputable theory variables {ι X Y : Type*} [emetric_space X] [emetric_space Y] namespace measure_theory namespace outer_measure /-! ### Metric outer measures In this section we define metric outer measures and prove Caratheodory theorem: a metric outer measure has the Caratheodory property. -/ /-- We say that an outer measure `μ` in an (e)metric space is *metric* if `μ (s ∪ t) = μ s + μ t` for any two metric separated sets `s`, `t`. -/ def is_metric (μ : outer_measure X) : Prop := ∀ (s t : set X), is_metric_separated s t → μ (s ∪ t) = μ s + μ t namespace is_metric variables {μ : outer_measure X} /-- A metric outer measure is additive on a finite set of pairwise metric separated sets. -/ lemma finset_Union_of_pairwise_separated (hm : is_metric μ) {I : finset ι} {s : ι → set X} (hI : ∀ (i ∈ I) (j ∈ I), i ≠ j → is_metric_separated (s i) (s j)) : μ (⋃ i ∈ I, s i) = ∑ i in I, μ (s i) := begin classical, induction I using finset.induction_on with i I hiI ihI hI, { simp }, simp only [finset.mem_insert] at hI, rw [finset.set_bUnion_insert, hm, ihI, finset.sum_insert hiI], exacts [λ i hi j hj hij, (hI i (or.inr hi) j (or.inr hj) hij), is_metric_separated.finset_Union_right (λ j hj, hI i (or.inl rfl) j (or.inr hj) (ne_of_mem_of_not_mem hj hiI).symm)] end /-- Caratheodory theorem. If `m` is a metric outer measure, then every Borel measurable set `t` is Caratheodory measurable: for any (not necessarily measurable) set `s` we have `μ (s ∩ t) + μ (s \ t) = μ s`. -/ lemma borel_le_caratheodory (hm : is_metric μ) : borel X ≤ μ.caratheodory := begin rw [borel_eq_generate_from_is_closed], refine measurable_space.generate_from_le (λ t ht, μ.is_caratheodory_iff_le.2 $ λ s, _), set S : ℕ → set X := λ n, {x ∈ s | (↑n)⁻¹ ≤ inf_edist x t}, have n0 : ∀ {n : ℕ}, (n⁻¹ : ℝ≥0∞) ≠ 0, from λ n, ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top, have Ssep : ∀ n, is_metric_separated (S n) t, from λ n, ⟨n⁻¹, n0, λ x hx y hy, hx.2.trans $ inf_edist_le_edist_of_mem hy⟩, have Ssep' : ∀ n, is_metric_separated (S n) (s ∩ t), from λ n, (Ssep n).mono subset.rfl (inter_subset_right _ _), have S_sub : ∀ n, S n ⊆ s \ t, from λ n, subset_inter (inter_subset_left _ _) (Ssep n).subset_compl_right, have hSs : ∀ n, μ (s ∩ t) + μ (S n) ≤ μ s, from λ n, calc μ (s ∩ t) + μ (S n) = μ (s ∩ t ∪ S n) : eq.symm $ hm _ _ $ (Ssep' n).symm ... ≤ μ (s ∩ t ∪ s \ t) : by { mono*, exact le_rfl } ... = μ s : by rw [inter_union_diff], have Union_S : (⋃ n, S n) = s \ t, { refine subset.antisymm (Union_subset S_sub) _, rintro x ⟨hxs, hxt⟩, rw mem_iff_inf_edist_zero_of_closed ht at hxt, rcases ennreal.exists_inv_nat_lt hxt with ⟨n, hn⟩, exact mem_Union.2 ⟨n, hxs, hn.le⟩ }, /- Now we have `∀ n, μ (s ∩ t) + μ (S n) ≤ μ s` and we need to prove `μ (s ∩ t) + μ (⋃ n, S n) ≤ μ s`. We can't pass to the limit because `μ` is only an outer measure. -/ by_cases htop : μ (s \ t) = ∞, { rw [htop, ennreal.add_top, ← htop], exact μ.mono (diff_subset _ _) }, suffices : μ (⋃ n, S n) ≤ ⨆ n, μ (S n), calc μ (s ∩ t) + μ (s \ t) = μ (s ∩ t) + μ (⋃ n, S n) : by rw Union_S ... ≤ μ (s ∩ t) + ⨆ n, μ (S n) : add_le_add le_rfl this ... = ⨆ n, μ (s ∩ t) + μ (S n) : ennreal.add_supr ... ≤ μ s : supr_le hSs, /- It suffices to show that `∑' k, μ (S (k + 1) \ S k) ≠ ∞`. Indeed, if we have this, then for all `N` we have `μ (⋃ n, S n) ≤ μ (S N) + ∑' k, m (S (N + k + 1) \ S (N + k))` and the second term tends to zero, see `outer_measure.Union_nat_of_monotone_of_tsum_ne_top` for details. -/ have : ∀ n, S n ⊆ S (n + 1), from λ n x hx, ⟨hx.1, le_trans (ennreal.inv_le_inv.2 $ ennreal.coe_nat_le_coe_nat.2 n.le_succ) hx.2⟩, refine (μ.Union_nat_of_monotone_of_tsum_ne_top this _).le, clear this, /- While the sets `S (k + 1) \ S k` are not pairwise metric separated, the sets in each subsequence `S (2 * k + 1) \ S (2 * k)` and `S (2 * k + 2) \ S (2 * k)` are metric separated, so `m` is additive on each of those sequences. -/ rw [← tsum_even_add_odd ennreal.summable ennreal.summable, ennreal.add_ne_top], suffices : ∀ a, (∑' (k : ℕ), μ (S (2 * k + 1 + a) \ S (2 * k + a))) ≠ ∞, from ⟨by simpa using this 0, by simpa using this 1⟩, refine λ r, ne_top_of_le_ne_top htop _, rw [← Union_S, ennreal.tsum_eq_supr_nat, supr_le_iff], intro n, rw [← hm.finset_Union_of_pairwise_separated], { exact μ.mono (Union_subset $ λ i, Union_subset $ λ hi x hx, mem_Union.2 ⟨_, hx.1⟩) }, suffices : ∀ i j, i < j → is_metric_separated (S (2 * i + 1 + r)) (s \ S (2 * j + r)), from λ i _ j _ hij, hij.lt_or_lt.elim (λ h, (this i j h).mono (inter_subset_left _ _) (λ x hx, ⟨hx.1.1, hx.2⟩)) (λ h, (this j i h).symm.mono (λ x hx, ⟨hx.1.1, hx.2⟩) (inter_subset_left _ _)), intros i j hj, have A : ((↑(2 * j + r))⁻¹ : ℝ≥0∞) < (↑(2 * i + 1 + r))⁻¹, by { rw [ennreal.inv_lt_inv, ennreal.coe_nat_lt_coe_nat], linarith }, refine ⟨(↑(2 * i + 1 + r))⁻¹ - (↑(2 * j + r))⁻¹, by simpa using A, λ x hx y hy, _⟩, have : inf_edist y t < (↑(2 * j + r))⁻¹, from not_le.1 (λ hle, hy.2 ⟨hy.1, hle⟩), rcases exists_edist_lt_of_inf_edist_lt this with ⟨z, hzt, hyz⟩, have hxz : (↑(2 * i + 1 + r))⁻¹ ≤ edist x z, from le_inf_edist.1 hx.2 _ hzt, apply ennreal.le_of_add_le_add_right (hyz.trans_le le_top), refine le_trans _ (edist_triangle _ _ _), refine (add_le_add le_rfl hyz.le).trans (eq.trans_le _ hxz), rw [ennreal.sub_add_cancel_of_le A.le] end lemma le_caratheodory [measurable_space X] [borel_space X] (hm : is_metric μ) : ‹measurable_space X› ≤ μ.caratheodory := by { rw @borel_space.measurable_eq X _ _, exact hm.borel_le_caratheodory } end is_metric /-! ### Constructors of metric outer measures In this section we provide constructors `measure_theory.outer_measure.mk_metric'` and `measure_theory.outer_measure.mk_metric` and prove that these outer measures are metric outer measures. We also prove basic lemmas about `map`/`comap` of these measures. -/ /-- Auxiliary definition for `outer_measure.mk_metric'`: given a function on sets `m : set X → ℝ≥0∞`, returns the maximal outer measure `μ` such that `μ s ≤ m s` for any set `s` of diameter at most `r`.-/ def mk_metric'.pre (m : set X → ℝ≥0∞) (r : ℝ≥0∞) : outer_measure X := bounded_by $ extend (λ s (hs : diam s ≤ r), m s) /-- Given a function `m : set X → ℝ≥0∞`, `mk_metric' m` is the supremum of `mk_metric'.pre m r` over `r > 0`. Equivalently, it is the limit of `mk_metric'.pre m r` as `r` tends to zero from the right. -/ def mk_metric' (m : set X → ℝ≥0∞) : outer_measure X := ⨆ r > 0, mk_metric'.pre m r /-- Given a function `m : ℝ≥0∞ → ℝ≥0∞` and `r > 0`, let `μ r` be the maximal outer measure such that `μ s = 0` on subsingletons and `μ s ≤ m (emetric.diam s)` whenever `emetric.diam s < r`. Then `mk_metric m = ⨆ r > 0, μ r`. We add `⨆ (hs : ¬s.subsingleton)` to ensure that in the case `m x = x ^ d` the definition gives the expected result for `d = 0`. -/ def mk_metric (m : ℝ≥0∞ → ℝ≥0∞) : outer_measure X := mk_metric' (λ s, ⨆ (hs : ¬s.subsingleton), m (diam s)) namespace mk_metric' variables {m : set X → ℝ≥0∞} {r : ℝ≥0∞} {μ : outer_measure X} {s : set X} lemma le_pre : μ ≤ pre m r ↔ ∀ s : set X, diam s ≤ r → μ s ≤ m s := by simp only [pre, le_bounded_by, extend, le_infi_iff] lemma pre_le (hs : diam s ≤ r) : pre m r s ≤ m s := (bounded_by_le _).trans $ infi_le _ hs lemma mono_pre (m : set X → ℝ≥0∞) {r r' : ℝ≥0∞} (h : r ≤ r') : pre m r' ≤ pre m r := le_pre.2 $ λ s hs, pre_le (hs.trans h) lemma mono_pre_nat (m : set X → ℝ≥0∞) : monotone (λ k : ℕ, pre m k⁻¹) := λ k l h, le_pre.2 $ λ s hs, pre_le (hs.trans $ by simpa) lemma tendsto_pre (m : set X → ℝ≥0∞) (s : set X) : tendsto (λ r, pre m r s) (𝓝[Ioi 0] 0) (𝓝 $ mk_metric' m s) := begin rw [← map_coe_Ioi_at_bot, tendsto_map'_iff], simp only [mk_metric', outer_measure.supr_apply, supr_subtype'], exact tendsto_at_bot_supr (λ r r' hr, mono_pre _ hr _) end lemma tendsto_pre_nat (m : set X → ℝ≥0∞) (s : set X) : tendsto (λ n : ℕ, pre m n⁻¹ s) at_top (𝓝 $ mk_metric' m s) := begin refine (tendsto_pre m s).comp (tendsto_inf.2 ⟨ennreal.tendsto_inv_nat_nhds_zero, _⟩), refine tendsto_principal.2 (eventually_of_forall $ λ n, _), simp end lemma eq_supr_nat (m : set X → ℝ≥0∞) : mk_metric' m = ⨆ n : ℕ, mk_metric'.pre m n⁻¹ := begin ext1 s, rw supr_apply, refine tendsto_nhds_unique (mk_metric'.tendsto_pre_nat m s) (tendsto_at_top_supr $ λ k l hkl, mk_metric'.mono_pre_nat m hkl s) end lemma trim_pre [measurable_space X] [opens_measurable_space X] (m : set X → ℝ≥0∞) (hcl : ∀ s, m (closure s) = m s) (r : ℝ≥0∞) : (pre m r).trim = pre m r := begin refine le_antisymm (le_pre.2 $ λ s hs, _) (le_trim _), rw trim_eq_infi, refine (infi_le_of_le (closure s) $ infi_le_of_le subset_closure $ infi_le_of_le measurable_set_closure ((pre_le _).trans_eq (hcl _))), rwa diam_closure end end mk_metric' /-- An outer measure constructed using `outer_measure.mk_metric'` is a metric outer measure. -/ lemma mk_metric'_is_metric (m : set X → ℝ≥0∞) : (mk_metric' m).is_metric := begin rintros s t ⟨r, r0, hr⟩, refine tendsto_nhds_unique_of_eventually_eq (mk_metric'.tendsto_pre _ _) ((mk_metric'.tendsto_pre _ _).add (mk_metric'.tendsto_pre _ _)) _, rw [← pos_iff_ne_zero] at r0, filter_upwards [Ioo_mem_nhds_within_Ioi ⟨le_rfl, r0⟩], rintro ε ⟨ε0, εr⟩, refine bounded_by_union_of_top_of_nonempty_inter _, rintro u ⟨x, hxs, hxu⟩ ⟨y, hyt, hyu⟩, have : ε < diam u, from εr.trans_le ((hr x hxs y hyt).trans $ edist_le_diam_of_mem hxu hyu), exact infi_eq_top.2 (λ h, (this.not_le h).elim) end /-- If `c ∉ {0, ∞}` and `m₁ d ≤ c * m₂ d` for `0 < d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[Ioi 0]]` to state this), then `mk_metric m₁ hm₁ ≤ c • mk_metric m₂ hm₂`. -/ lemma mk_metric_mono_smul {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} {c : ℝ≥0∞} (hc : c ≠ ∞) (h0 : c ≠ 0) (hle : m₁ ≤ᶠ[𝓝[Ioi 0] 0] c • m₂) : (mk_metric m₁ : outer_measure X) ≤ c • mk_metric m₂ := begin classical, rcases (mem_nhds_within_Ioi_iff_exists_Ioo_subset' ennreal.zero_lt_one).1 hle with ⟨r, hr0, hr⟩, refine λ s, le_of_tendsto_of_tendsto (mk_metric'.tendsto_pre _ s) (ennreal.tendsto.const_mul (mk_metric'.tendsto_pre _ s) (or.inr hc)) (mem_sets_of_superset (Ioo_mem_nhds_within_Ioi ⟨le_rfl, hr0⟩) (λ r' hr', _)), simp only [mem_set_of_eq, mk_metric'.pre], rw [← smul_apply, smul_bounded_by hc], refine le_bounded_by.2 (λ t, (bounded_by_le _).trans _) _, simp only [smul_eq_mul, pi.smul_apply, extend, infi_eq_if], split_ifs with ht ht, { refine supr_le (λ ht₁, _), rw [supr_eq_if, if_pos ht₁], refine hr ⟨_, ht.trans_lt hr'.2⟩, exact pos_iff_ne_zero.2 (mt diam_eq_zero_iff.1 ht₁) }, { simp [h0] } end /-- If `m₁ d ≤ m₂ d` for `0 < d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[Ioi 0]]` to state this), then `mk_metric m₁ hm₁ ≤ mk_metric m₂ hm₂`-/ lemma mk_metric_mono {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} (hle : m₁ ≤ᶠ[𝓝[Ioi 0] 0] m₂) : (mk_metric m₁ : outer_measure X) ≤ mk_metric m₂ := by { convert mk_metric_mono_smul ennreal.one_ne_top ennreal.zero_lt_one.ne' _; simp * } lemma isometry_comap_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) {f : X → Y} (hf : isometry f) (H : monotone (λ d : {d : ℝ≥0∞ | d ≠ 0}, m d) ∨ surjective f) : comap f (mk_metric m) = mk_metric m := begin simp only [mk_metric, mk_metric', mk_metric'.pre, induced_outer_measure, comap_supr], refine supr_congr id surjective_id (λ ε, supr_congr id surjective_id $ λ hε, _), rw comap_bounded_by _ (H.imp (λ h_mono, _) id), { congr' with s : 1, apply extend_congr, { simp [hf.ediam_image] }, { intros, simp [hf.injective.subsingleton_image_iff, hf.ediam_image] } }, { refine λ s t hst, infi_le_infi2 (λ ht, ⟨(diam_mono hst).trans ht, supr_le $ λ hs, _⟩), have ht : ¬(t : set Y).subsingleton, from λ ht, hs (ht.mono hst), refine (@h_mono ⟨_, mt diam_eq_zero_iff.1 hs⟩ ⟨_, mt diam_eq_zero_iff.1 ht⟩ (diam_mono hst)).trans _, exact le_supr (λ h : ¬(t : set Y).subsingleton, m (diam (t : set Y))) ht } end lemma isometry_map_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) {f : X → Y} (hf : isometry f) (H : monotone (λ d : {d : ℝ≥0∞ | d ≠ 0}, m d) ∨ surjective f) : map f (mk_metric m) = restrict (range f) (mk_metric m) := by rw [← isometry_comap_mk_metric _ hf H, map_comap] lemma isometric_comap_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (f : X ≃ᵢ Y) : comap f (mk_metric m) = mk_metric m := isometry_comap_mk_metric _ f.isometry (or.inr f.surjective) lemma isometric_map_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (f : X ≃ᵢ Y) : map f (mk_metric m) = mk_metric m := by rw [← isometric_comap_mk_metric _ f, map_comap_of_surjective f.surjective] lemma trim_mk_metric [measurable_space X] [borel_space X] (m : ℝ≥0∞ → ℝ≥0∞) : (mk_metric m : outer_measure X).trim = mk_metric m := begin simp only [mk_metric, mk_metric'.eq_supr_nat, trim_supr], congr' 1 with n : 1, refine mk_metric'.trim_pre _ (λ s, _) _, simp end end outer_measure /-! ### Metric measures In this section we use `measure_theory.outer_measure.to_measure` and theorems about `measure_theory.outer_measure.mk_metric'`/`measure_theory.outer_measure.mk_metric` to define `measure_theory.measure.mk_metric'`/`measure_theory.measure.mk_metric`. We also restate some lemmas about metric outer measures for metric measures. -/ namespace measure variables [measurable_space X] [borel_space X] /-- Given a function `m : set X → ℝ≥0∞`, `mk_metric' m` is the supremum of `μ r` over `r > 0`, where `μ r` is the maximal outer measure `μ` such that `μ s ≤ m s` for all `s`. While each `μ r` is an *outer* measure, the supremum is a measure. -/ def mk_metric' (m : set X → ℝ≥0∞) : measure X := (outer_measure.mk_metric' m).to_measure (outer_measure.mk_metric'_is_metric _).le_caratheodory /-- Given a function `m : ℝ≥0∞ → ℝ≥0∞`, `mk_metric m` is the supremum of `μ r` over `r > 0`, where `μ r` is the maximal outer measure `μ` such that `μ s ≤ m s` for all sets `s` that contain at least two points. While each `mk_metric'.pre` is an *outer* measure, the supremum is a measure. -/ def mk_metric (m : ℝ≥0∞ → ℝ≥0∞) : measure X := (outer_measure.mk_metric m).to_measure (outer_measure.mk_metric'_is_metric _).le_caratheodory @[simp] lemma mk_metric'_to_outer_measure (m : set X → ℝ≥0∞) : (mk_metric' m).to_outer_measure = (outer_measure.mk_metric' m).trim := rfl @[simp] lemma mk_metric_to_outer_measure (m : ℝ≥0∞ → ℝ≥0∞) : (mk_metric m : measure X).to_outer_measure = outer_measure.mk_metric m := outer_measure.trim_mk_metric m end measure lemma outer_measure.coe_mk_metric [measurable_space X] [borel_space X] (m : ℝ≥0∞ → ℝ≥0∞) : ⇑(outer_measure.mk_metric m : outer_measure X) = measure.mk_metric m := by rw [← measure.mk_metric_to_outer_measure, coe_to_outer_measure] variables [measurable_space X] [borel_space X] namespace measure /-- If `c ∉ {0, ∞}` and `m₁ d ≤ c * m₂ d` for `0 < d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[Ioi 0]]` to state this), then `mk_metric m₁ hm₁ ≤ c • mk_metric m₂ hm₂`. -/ lemma mk_metric_mono_smul {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} {c : ℝ≥0∞} (hc : c ≠ ∞) (h0 : c ≠ 0) (hle : m₁ ≤ᶠ[𝓝[Ioi 0] 0] c • m₂) : (mk_metric m₁ : measure X) ≤ c • mk_metric m₂ := begin intros s hs, rw [← outer_measure.coe_mk_metric, coe_smul, ← outer_measure.coe_mk_metric], exact outer_measure.mk_metric_mono_smul hc h0 hle s end /-- If `m₁ d ≤ m₂ d` for `0 < d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[Ioi 0]]` to state this), then `mk_metric m₁ hm₁ ≤ mk_metric m₂ hm₂`-/ lemma mk_metric_mono {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} (hle : m₁ ≤ᶠ[𝓝[Ioi 0] 0] m₂) : (mk_metric m₁ : measure X) ≤ mk_metric m₂ := by { convert mk_metric_mono_smul ennreal.one_ne_top ennreal.zero_lt_one.ne' _; simp * } /-- A formula for `measure_theory.measure.mk_metric`. -/ lemma mk_metric_apply (m : ℝ≥0∞ → ℝ≥0∞) (s : set X) : mk_metric m s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ r), ∑' n, ⨆ (ht : ¬(t n).subsingleton), m (diam (t n)) := begin -- We mostly unfold the definitions but we need to switch the order of `∑'` and `⨅` -- and merge `(t n).nonempty` with `¬subsingleton (t n)` classical, simp only [← outer_measure.coe_mk_metric, outer_measure.mk_metric, outer_measure.mk_metric', outer_measure.supr_apply, outer_measure.mk_metric'.pre, outer_measure.bounded_by_apply, extend], refine supr_congr (λ r, r) surjective_id (λ r, supr_congr_Prop iff.rfl $ λ hr, infi_congr _ surjective_id $ λ t, infi_congr_Prop iff.rfl $ λ ht, _), by_cases htr : ∀ n, diam (t n) ≤ r, { rw [infi_eq_if, if_pos htr], congr' 1 with n : 1, simp only [infi_eq_if, htr n, id, if_true, supr_and'], refine supr_congr_Prop (and_iff_right_of_imp $ λ h, _) (λ _, rfl), contrapose! h, rw [not_nonempty_iff_eq_empty.1 h], exact subsingleton_empty }, { rw [infi_eq_if, if_neg htr], push_neg at htr, rcases htr with ⟨n, hn⟩, refine ennreal.tsum_eq_top_of_eq_top ⟨n, _⟩, rw [supr_eq_if, if_pos, infi_eq_if, if_neg], exact hn.not_le, rcases diam_pos_iff.1 ((zero_le r).trans_lt hn) with ⟨x, hx, -⟩, exact ⟨x, hx⟩ } end /-! ### Hausdorff measure and Hausdorff dimension -/ /-- Hausdorff measure on an (e)metric space. -/ def hausdorff_measure (d : ℝ) : measure X := mk_metric (λ r, r ^ d) localized "notation `μH[` d `]` := measure_theory.measure.hausdorff_measure d" in measure_theory /-- A formula for `μH[d] s` that works for all `d`. In case of a positive `d` a simpler formula is available as `measure_theory.measure.hausdorff_measure_apply`. -/ lemma hausdorff_measure_apply' (d : ℝ) (s : set X) : μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ r), ∑' n, ⨆ (ht : ¬(t n).subsingleton), (diam (t n)) ^ d := mk_metric_apply _ _ /-- A formula for `μH[d] s` that works for all positive `d`. -/ lemma hausdorff_measure_apply {d : ℝ} (hd : 0 < d) (s : set X) : μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ r), ∑' n, diam (t n) ^ d := begin classical, rw hausdorff_measure_apply', -- I wish `congr'` was able to generate this refine supr_congr id surjective_id (λ r, supr_congr_Prop iff.rfl $ λ hr, infi_congr id surjective_id $ λ t, infi_congr_Prop iff.rfl $ λ hts, infi_congr_Prop iff.rfl $ λ ht, tsum_congr $ λ n, _), rw [supr_eq_if], split_ifs with ht', { erw [diam_eq_zero_iff.2 ht', ennreal.zero_rpow_of_pos hd, ennreal.bot_eq_zero] }, { refl } end /-- If `d₁ < d₂`, then for any set `s` we have either `μH[d₂] s = 0`, or `μH[d₁] s = ∞`. -/ lemma hausdorff_measure_zero_or_top {d₁ d₂ : ℝ} (h : d₁ < d₂) (s : set X) : μH[d₂] s = 0 ∨ μH[d₁] s = ∞ := begin by_contra H, push_neg at H, suffices : ∀ (c : ℝ≥0), c ≠ 0 → μH[d₂] s ≤ c * μH[d₁] s, { rcases ennreal.exists_nnreal_pos_mul_lt H.2 H.1 with ⟨c, hc0, hc⟩, exact hc.not_le (this c (pos_iff_ne_zero.1 hc0)) }, intros c hc, refine le_iff'.1 (mk_metric_mono_smul ennreal.coe_ne_top (by exact_mod_cast hc) _) s, have : 0 < (c ^ (d₂ - d₁)⁻¹ : ℝ≥0∞), { rw [ennreal.coe_rpow_of_ne_zero hc, pos_iff_ne_zero, ne.def, ennreal.coe_eq_zero, nnreal.rpow_eq_zero_iff], exact mt and.left hc }, filter_upwards [Ioo_mem_nhds_within_Ioi ⟨le_rfl, this⟩], rintro r ⟨hr₀, hrc⟩, lift r to ℝ≥0 using ne_top_of_lt hrc, rw [pi.smul_apply, smul_eq_mul, ← ennreal.div_le_iff_le_mul (or.inr ennreal.coe_ne_top) (or.inr $ mt ennreal.coe_eq_zero.1 hc), ← ennreal.rpow_sub _ _ hr₀.ne' ennreal.coe_ne_top], refine (ennreal.rpow_lt_rpow hrc (sub_pos.2 h)).le.trans _, rw [← ennreal.rpow_mul, inv_mul_cancel (sub_pos.2 h).ne', ennreal.rpow_one], exact le_rfl end /-- Hausdorff measure `μH[d] s` is monotone in `d`. -/ lemma hausdorff_measure_mono {d₁ d₂ : ℝ} (h : d₁ ≤ d₂) (s : set X) : μH[d₂] s ≤ μH[d₁] s := begin rcases h.eq_or_lt with rfl|h, { exact le_rfl }, cases hausdorff_measure_zero_or_top h s with hs hs, { rw hs, exact zero_le _ }, { rw hs, exact le_top } end end measure open_locale measure_theory open measure /-- Hausdorff dimension of a set in an (e)metric space. -/ def dimH (s : set X) : ℝ≥0∞ := ⨆ (d : ℝ≥0) (hd : μH[d] s = ∞), d lemma hausdorff_measure_of_lt_dimH {s : set X} {d : ℝ≥0} (h : ↑d < dimH s) : μH[d] s = ∞ := begin simp only [dimH, lt_supr_iff] at h, rcases h with ⟨d', hsd', hdd'⟩, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at hdd', refine (hausdorff_measure_zero_or_top hdd' s).resolve_left (λ h, _), exact (ennreal.zero_ne_top $ h.symm.trans hsd').elim end lemma hausdorff_measure_of_dimH_lt {s : set X} {d : ℝ≥0} (h : dimH s < d) : μH[d] s = 0 := begin rcases ennreal.lt_iff_exists_nnreal_btwn.1 h with ⟨d', hsd', hd'd⟩, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at hd'd, exact (hausdorff_measure_zero_or_top hd'd s).resolve_right (λ h, hsd'.not_le (le_bsupr d' h)) end lemma measure_zero_of_dimH_lt {μ : measure X} {d : ℝ≥0} (h : μ ≪ μH[d]) {s : set X} (hd : dimH s < d) : μ s = 0 := h $ hausdorff_measure_of_dimH_lt hd end measure_theory
191b7524472eefc2b9957e4d267f36fa8cbddbc2
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/clifford_algebra/star.lean
9c340fcbcb04f27cba593af0e99d686c7f616833
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,977
lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import linear_algebra.clifford_algebra.conjugation /-! # Star structure on `clifford_algebra` This file defines the "clifford conjugation", equal to `reverse (involute x)`, and assigns it the `star` notation. This choice is somewhat non-canonical; a star structure is also possible under `reverse` alone. However, defining it gives us access to constructions like `unitary`. Most results about `star` can be obtained by unfolding it via `clifford_algebra.star_def`. ## Main definitions * `clifford_algebra.star_ring` -/ variables {R : Type*} [comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables {Q : quadratic_form R M} namespace clifford_algebra instance : star_ring (clifford_algebra Q) := { star := λ x, reverse (involute x), star_involutive := λ x, by simp only [reverse_involute_commute.eq, reverse_reverse, involute_involute], star_mul := λ x y, by simp only [map_mul, reverse.map_mul], star_add := λ x y, by simp only [map_add] } lemma star_def (x : clifford_algebra Q) : star x = reverse (involute x) := rfl lemma star_def' (x : clifford_algebra Q) : star x = involute (reverse x) := reverse_involute _ @[simp] lemma star_ι (m : M) : star (ι Q m) = -ι Q m := by rw [star_def, involute_ι, map_neg, reverse_ι] /-- Note that this not match the `star_smul` implied by `star_module`; it certainly could if we also conjugated all the scalars, but there appears to be nothing in the literature that advocates doing this. -/ @[simp] lemma star_smul (r : R) (x : clifford_algebra Q) : star (r • x) = r • star x := by rw [star_def, star_def, map_smul, map_smul] @[simp] lemma star_algebra_map (r : R) : star (algebra_map R (clifford_algebra Q) r) = algebra_map R (clifford_algebra Q) r := by rw [star_def, involute.commutes, reverse.commutes] end clifford_algebra
35d321109dba0234bc2a5172505db2907f23d1b1
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/have3.lean
ae1a6f209dd542e4b1b598a7678df888d6127a45
[ "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
231
lean
prelude definition Prop : Type.{1} := Type.{0} constants a b c : Prop axiom Ha : a axiom Hb : b axiom Hc : c #check have H1 : a, from Ha, have H2 : a, from H1, have H3 : a, from H2, have H4 : a, from H3, H4
5198ea5393a29073db9f2334414dd2be7983e948
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/real/cardinality.lean
ca19a4cd7f123555357da13f5d5d58150e4c0ecb
[]
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
6,478
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.set_theory.cardinal_ordinal import Mathlib.analysis.specific_limits import Mathlib.data.rat.denumerable import Mathlib.data.set.intervals.image_preimage import Mathlib.PostPort namespace Mathlib /-! # The cardinality of the reals This file shows that the real numbers have cardinality continuum, i.e. `#ℝ = 2^ω`. We shows that `#ℝ ≤ 2^ω` by noting that every real number is determined by a Cauchy-sequence of the form `ℕ → ℚ`, which has cardinality `2^ω`. To show that `#ℝ ≥ 2^ω` we define an injection from `{0, 1} ^ ℕ` to `ℝ` with `f ↦ Σ n, f n * (1 / 3) ^ n`. We conclude that all intervals with distinct endpoints have cardinality continuum. ## Main definitions * `cardinal.cantor_function` is the function that sends `f` in `{0, 1} ^ ℕ` to `ℝ` by `f ↦ Σ' n, f n * (1 / 3) ^ n` ## Main statements * `cardinal.mk_real : #ℝ = 2 ^ omega`: the reals have cardinality continuum. * `cardinal.not_countable_real`: the universal set of real numbers is not countable. We can use this same proof to show that all the other sets in this file are not countable. * 8 lemmas of the form `mk_Ixy_real` for `x,y ∈ {i,o,c}` state that intervals on the reals have cardinality continuum. ## Tags continuum, cardinality, reals, cardinality of the reals -/ namespace cardinal /-- The body of the sum in `cantor_function`. `cantor_function_aux c f n = c ^ n` if `f n = tt`; `cantor_function_aux c f n = 0` if `f n = ff`. -/ def cantor_function_aux (c : ℝ) (f : ℕ → Bool) (n : ℕ) : ℝ := cond (f n) (c ^ n) 0 @[simp] theorem cantor_function_aux_tt {c : ℝ} {f : ℕ → Bool} {n : ℕ} (h : f n = tt) : cantor_function_aux c f n = c ^ n := sorry @[simp] theorem cantor_function_aux_ff {c : ℝ} {f : ℕ → Bool} {n : ℕ} (h : f n = false) : cantor_function_aux c f n = 0 := sorry theorem cantor_function_aux_nonneg {c : ℝ} {f : ℕ → Bool} {n : ℕ} (h : 0 ≤ c) : 0 ≤ cantor_function_aux c f n := sorry theorem cantor_function_aux_eq {c : ℝ} {f : ℕ → Bool} {g : ℕ → Bool} {n : ℕ} (h : f n = g n) : cantor_function_aux c f n = cantor_function_aux c g n := sorry theorem cantor_function_aux_succ {c : ℝ} (f : ℕ → Bool) : (fun (n : ℕ) => cantor_function_aux c f (n + 1)) = fun (n : ℕ) => c * cantor_function_aux c (fun (n : ℕ) => f (n + 1)) n := sorry theorem summable_cantor_function {c : ℝ} (f : ℕ → Bool) (h1 : 0 ≤ c) (h2 : c < 1) : summable (cantor_function_aux c f) := sorry /-- `cantor_function c (f : ℕ → bool)` is `Σ n, f n * c ^ n`, where `tt` is interpreted as `1` and `ff` is interpreted as `0`. It is implemented using `cantor_function_aux`. -/ def cantor_function (c : ℝ) (f : ℕ → Bool) : ℝ := tsum fun (n : ℕ) => cantor_function_aux c f n theorem cantor_function_le {c : ℝ} {f : ℕ → Bool} {g : ℕ → Bool} (h1 : 0 ≤ c) (h2 : c < 1) (h3 : ∀ (n : ℕ), ↥(f n) → ↥(g n)) : cantor_function c f ≤ cantor_function c g := sorry theorem cantor_function_succ {c : ℝ} (f : ℕ → Bool) (h1 : 0 ≤ c) (h2 : c < 1) : cantor_function c f = cond (f 0) 1 0 + c * cantor_function c fun (n : ℕ) => f (n + 1) := sorry /-- `cantor_function c` is strictly increasing with if `0 < c < 1/2`, if we endow `ℕ → bool` with a lexicographic order. The lexicographic order doesn't exist for these infinitary products, so we explicitly write out what it means. -/ theorem increasing_cantor_function {c : ℝ} (h1 : 0 < c) (h2 : c < 1 / bit0 1) {n : ℕ} {f : ℕ → Bool} {g : ℕ → Bool} (hn : ∀ (k : ℕ), k < n → f k = g k) (fn : f n = false) (gn : g n = tt) : cantor_function c f < cantor_function c g := sorry /-- `cantor_function c` is injective if `0 < c < 1/2`. -/ theorem cantor_function_injective {c : ℝ} (h1 : 0 < c) (h2 : c < 1 / bit0 1) : function.injective (cantor_function c) := sorry /-- The cardinality of the reals, as a type. -/ theorem mk_real : mk ℝ = bit0 1 ^ omega := sorry /-- The cardinality of the reals, as a set. -/ theorem mk_univ_real : mk ↥set.univ = bit0 1 ^ omega := eq.mpr (id (Eq._oldrec (Eq.refl (mk ↥set.univ = bit0 1 ^ omega)) mk_univ)) (eq.mpr (id (Eq._oldrec (Eq.refl (mk ℝ = bit0 1 ^ omega)) mk_real)) (Eq.refl (bit0 1 ^ omega))) /-- The reals are not countable. -/ theorem not_countable_real : ¬set.countable set.univ := eq.mpr (id (Eq._oldrec (Eq.refl (¬set.countable set.univ)) (propext (countable_iff set.univ)))) (eq.mpr (id (Eq._oldrec (Eq.refl (¬mk ↥set.univ ≤ omega)) (propext not_le))) (eq.mpr (id (Eq._oldrec (Eq.refl (omega < mk ↥set.univ)) mk_univ_real)) (cantor omega))) /-- The cardinality of the interval (a, ∞). -/ theorem mk_Ioi_real (a : ℝ) : mk ↥(set.Ioi a) = bit0 1 ^ omega := sorry /-- The cardinality of the interval [a, ∞). -/ theorem mk_Ici_real (a : ℝ) : mk ↥(set.Ici a) = bit0 1 ^ omega := le_antisymm (mk_real ▸ mk_set_le (set.Ici a)) (mk_Ioi_real a ▸ mk_le_mk_of_subset set.Ioi_subset_Ici_self) /-- The cardinality of the interval (-∞, a). -/ theorem mk_Iio_real (a : ℝ) : mk ↥(set.Iio a) = bit0 1 ^ omega := sorry /-- The cardinality of the interval (-∞, a]. -/ theorem mk_Iic_real (a : ℝ) : mk ↥(set.Iic a) = bit0 1 ^ omega := le_antisymm (mk_real ▸ mk_set_le (set.Iic a)) (mk_Iio_real a ▸ mk_le_mk_of_subset set.Iio_subset_Iic_self) /-- The cardinality of the interval (a, b). -/ theorem mk_Ioo_real {a : ℝ} {b : ℝ} (h : a < b) : mk ↥(set.Ioo a b) = bit0 1 ^ omega := sorry /-- The cardinality of the interval [a, b). -/ theorem mk_Ico_real {a : ℝ} {b : ℝ} (h : a < b) : mk ↥(set.Ico a b) = bit0 1 ^ omega := le_antisymm (mk_real ▸ mk_set_le (set.Ico a b)) (mk_Ioo_real h ▸ mk_le_mk_of_subset set.Ioo_subset_Ico_self) /-- The cardinality of the interval [a, b]. -/ theorem mk_Icc_real {a : ℝ} {b : ℝ} (h : a < b) : mk ↥(set.Icc a b) = bit0 1 ^ omega := le_antisymm (mk_real ▸ mk_set_le (set.Icc a b)) (mk_Ioo_real h ▸ mk_le_mk_of_subset set.Ioo_subset_Icc_self) /-- The cardinality of the interval (a, b]. -/ theorem mk_Ioc_real {a : ℝ} {b : ℝ} (h : a < b) : mk ↥(set.Ioc a b) = bit0 1 ^ omega := le_antisymm (mk_real ▸ mk_set_le (set.Ioc a b)) (mk_Ioo_real h ▸ mk_le_mk_of_subset set.Ioo_subset_Ioc_self)
c5781ff9cfd4e821a1e24ed77c40c7b8ed321ab9
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/Util.lean
a1c7f82c00c23d5e08856a700c741e8239ebc27d
[ "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
2,856
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.CoreM import Lean.MonadEnv import Lean.Util.Recognizers namespace Lean.Compiler.LCNF /-- Return `true` if `mdata` should be preserved. Right now, we don't preserve any `MData`, but this may change in the future when we add support for debugging information -/ def isCompilerRelevantMData (_mdata : MData) : Bool := false /-- Return `true` if `e` is a `lcCast` application. -/ def isLcCast? (e : Expr) : Option Expr := if e.isAppOfArity ``lcCast 3 then some e.appArg! else none /-- Store information about `casesOn` declarations. We treat them uniformly in the code generator. -/ structure CasesInfo where declName : Name arity : Nat numParams : Nat discrPos : Nat altsRange : Std.Range altNumParams : Array Nat motivePos : Nat def CasesInfo.numAlts (c : CasesInfo) : Nat := c.altNumParams.size private def getCasesOnInductiveVal? (declName : Name) : CoreM (Option InductiveVal) := do unless isCasesOnRecursor (← getEnv) declName do return none let .inductInfo val ← getConstInfo declName.getPrefix | return none return some val def getCasesInfo? (declName : Name) : CoreM (Option CasesInfo) := do let some val ← getCasesOnInductiveVal? declName | return none let numParams := val.numParams let motivePos := numParams let arity := numParams + 1 /- motive -/ + val.numIndices + 1 /- major -/ + val.numCtors let discrPos := numParams + 1 /- motive -/ + val.numIndices -- We view indices as discriminants let altsRange := { start := discrPos + 1, stop := arity } let altNumParams ← val.ctors.toArray.mapM fun ctor => do let .ctorInfo ctorVal ← getConstInfo ctor | unreachable! return ctorVal.numFields return some { declName, numParams, motivePos, arity, discrPos, altsRange, altNumParams } def isCasesApp? (e : Expr) : CoreM (Option CasesInfo) := do let .const declName _ := e.getAppFn | return none if let some info ← getCasesInfo? declName then assert! info.arity == e.getAppNumArgs return some info else return none def getCtorArity? (declName : Name) : CoreM (Option Nat) := do let .ctorInfo val ← getConstInfo declName | return none return val.numParams + val.numFields /-- List of types that have builtin runtime support -/ def builtinRuntimeTypes : List Name := [ ``String, ``UInt8, ``UInt16, ``UInt32, ``UInt64, ``USize, ``Float, ``Thunk, ``Task, ``Array, ``ByteArray, ``FloatArray, ``Nat, ``Int ] /-- Return `true` iff `declName` is the name of a type with builtin support in the runtime. -/ def isRuntimeBultinType (declName : Name) : Bool := builtinRuntimeTypes.contains declName end Lean.Compiler.LCNF
35710f85dbbcfa99c7991eeafb41d7a6e728c906
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/stage0/src/Lean/Util/MonadCache.lean
3a19810a269fe6d2bf63c517d39b60729f7874b3
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,653
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 Std.Data.HashMap namespace Lean /-- Interface for caching results. -/ class MonadCache (α β : Type) (m : Type → Type) where findCached? : α → m (Option β) cache : α → β → m Unit /-- If entry `a := b` is already in the cache, then return `b`. Otherwise, execute `b ← f a`, store `a := b` in the cache and return `b`. -/ @[inline] def checkCache {α β : Type} {m : Type → Type} [MonadCache α β m] [Monad m] (a : α) (f : Unit → m β) : m β := do match (← MonadCache.findCached? a) with | some b => pure b | none => do let b ← f () MonadCache.cache a b pure b instance {α β ρ : Type} {m : Type → Type} [MonadCache α β m] : MonadCache α β (ReaderT ρ m) where findCached? a r := MonadCache.findCached? a cache a b r := MonadCache.cache a b instance {α β ε : Type} {m : Type → Type} [MonadCache α β m] [Monad m] : MonadCache α β (ExceptT ε m) where findCached? a := ExceptT.lift $ MonadCache.findCached? a cache a b := ExceptT.lift $ MonadCache.cache a b open Std (HashMap) /-- Adapter for implementing `MonadCache` interface using `HashMap`s. We just have to specify how to extract/modify the `HashMap`. -/ class MonadHashMapCacheAdapter (α β : Type) (m : Type → Type) [BEq α] [Hashable α] where getCache : m (HashMap α β) modifyCache : (HashMap α β → HashMap α β) → m Unit namespace MonadHashMapCacheAdapter @[inline] def findCached? {α β : Type} {m : Type → Type} [BEq α] [Hashable α] [Monad m] [MonadHashMapCacheAdapter α β m] (a : α) : m (Option β) := do let c ← getCache pure (c.find? a) @[inline] def cache {α β : Type} {m : Type → Type} [BEq α] [Hashable α] [MonadHashMapCacheAdapter α β m] (a : α) (b : β) : m Unit := modifyCache fun s => s.insert a b instance {α β : Type} {m : Type → Type} [BEq α] [Hashable α] [Monad m] [MonadHashMapCacheAdapter α β m] : MonadCache α β m where findCached? := MonadHashMapCacheAdapter.findCached? cache := MonadHashMapCacheAdapter.cache end MonadHashMapCacheAdapter def MonadCacheT {ω} (α β : Type) (m : Type → Type) [STWorld ω m] [BEq α] [Hashable α] := StateRefT (HashMap α β) m namespace MonadCacheT variables {ω α β : Type} {m : Type → Type} [STWorld ω m] [BEq α] [Hashable α] [MonadLiftT (ST ω) m] [Monad m] instance : MonadHashMapCacheAdapter α β (MonadCacheT α β m) where getCache := (get : StateRefT' ..) modifyCache f := (modify f : StateRefT' ..) @[inline] def run {σ} (x : MonadCacheT α β m σ) : m σ := x.run' Std.mkHashMap instance : Monad (MonadCacheT α β m) := inferInstanceAs (Monad (StateRefT' _ _ _)) instance : MonadLift m (MonadCacheT α β m) := inferInstanceAs (MonadLift m (StateRefT' _ _ _)) instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (MonadCacheT α β m) := inferInstanceAs (MonadExceptOf ε (StateRefT' _ _ _)) instance : MonadControl m (MonadCacheT α β m) := inferInstanceAs (MonadControl m (StateRefT' _ _ _)) instance [MonadFinally m] : MonadFinally (MonadCacheT α β m) := inferInstanceAs (MonadFinally (StateRefT' _ _ _)) instance [MonadRef m] : MonadRef (MonadCacheT α β m) := inferInstanceAs (MonadRef (StateRefT' _ _ _)) end MonadCacheT /- Similar to `MonadCacheT`, but using `StateT` instead of `StateRefT` -/ def MonadStateCacheT (α β : Type) (m : Type → Type) [BEq α] [Hashable α] := StateT (HashMap α β) m namespace MonadStateCacheT variables {ω α β : Type} {m : Type → Type} [STWorld ω m] [BEq α] [Hashable α] [MonadLiftT (ST ω) m] [Monad m] instance : MonadHashMapCacheAdapter α β (MonadStateCacheT α β m) where getCache := (get : StateT ..) modifyCache f := (modify f : StateT ..) @[inline] def run {σ} (x : MonadStateCacheT α β m σ) : m σ := x.run' Std.mkHashMap instance : Monad (MonadStateCacheT α β m) := inferInstanceAs (Monad (StateT _ _)) instance : MonadLift m (MonadStateCacheT α β m) := inferInstanceAs (MonadLift m (StateT _ _)) instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (MonadStateCacheT α β m) := inferInstanceAs (MonadExceptOf ε (StateT _ _)) instance : MonadControl m (MonadStateCacheT α β m) := inferInstanceAs (MonadControl m (StateT _ _)) instance [MonadFinally m] : MonadFinally (MonadStateCacheT α β m) := inferInstanceAs (MonadFinally (StateT _ _)) instance [MonadRef m] : MonadRef (MonadStateCacheT α β m) := inferInstanceAs (MonadRef (StateT _ _)) end MonadStateCacheT end Lean
8bd174c7af6b9dc185b49c373feb1cd6c6881704
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/interactive/goal_info_rw.lean
0c0de6b09d92f7af7594ae37c2e163738bb69c34
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
249
lean
example (p q r : Prop) (h₁ : p = q) (h₂ : q = r) : p = r := by rw [h₁, --^ "command": "info" -h₂, --^ "command": "info" -h₁ --^ "command": "info" --^ "command": "info" ] --^ "command": "info"
5df923048b5e08b91fc0cd46a8e8114aa35f95f8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/set/intervals/infinite.lean
ab693de07cb173b1d14af4a5fe8596bca18452a1
[]
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,675
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
1d299cdbb085ddf845b9d405e26a639084f14013
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Util/ForEachExprWhere.lean
18a9e33d09fc35644a1ee16c20e05880019be16b
[ "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
2,844
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr import Lean.Util.MonadCache namespace Lean /-! `forEachWhere p f e` is similar to `forEach f e`, but only applies `f` to subterms that satisfy the (pure) predicate `p`. It also uses the caching trick used at `FindExpr` and `ReplaceExpr`. This can be very effective if the number of subterms satisfying `p` is a small subset of the set of subterms. If `p` holds for most subterms, then it is more efficient to use `forEach f e`. -/ variable {ω : Type} {m : Type → Type} [STWorld ω m] [MonadLiftT (ST ω) m] [Monad m] namespace ForEachExprWhere abbrev cacheSize : USize := 8192 - 1 structure State where /-- Implements caching trick similar to the one used at `FindExpr` and `ReplaceExpr`. -/ visited : Array Expr -- Remark: our "unsafe" implementation relies on the fact that `()` is not a valid Expr /-- Set of visited subterms that satisfy the predicate `p`. We have to use this set to make sure `f` is applied at most once of each subterm that satisfies `p`. -/ checked : HashSet Expr unsafe def initCache : State := { visited := mkArray cacheSize.toNat (cast lcProof ()) checked := {} } abbrev ForEachM {ω : Type} (m : Type → Type) [STWorld ω m] [MonadLiftT (ST ω) m] [Monad m] := StateRefT' ω State m unsafe def visited (e : Expr) : ForEachM m Bool := do let s ← get let h := ptrAddrUnsafe e let i := h % cacheSize let k := s.visited.uget i lcProof if ptrAddrUnsafe k == h then return true else modify fun s => { s with visited := s.visited.uset i e lcProof } return false def checked (e : Expr) : ForEachM m Bool := do if (← get).checked.contains e then return true else modify fun s => { s with checked := s.checked.insert e } return false /-- `Expr.forEachWhere` (unsafe) implementation -/ unsafe def visit (p : Expr → Bool) (f : Expr → m Unit) (e : Expr) : m Unit := do go e |>.run' initCache where go (e : Expr) : StateRefT' ω State m Unit := do unless (← visited e) do if p e then unless (← checked e) do f e match e with | .forallE _ d b _ => go d; go b | .lam _ d b _ => go d; go b | .letE _ t v b _ => go t; go v; go b | .app f a => go f; go a | .mdata _ b => go b | .proj _ _ b => go b | _ => return () end ForEachExprWhere /-- `e.forEachWhere p f` applies `f` to each subterm that satisfies `p`. -/ @[implemented_by ForEachExprWhere.visit] opaque Expr.forEachWhere {ω : Type} {m : Type → Type} [STWorld ω m] [MonadLiftT (ST ω) m] [Monad m] (p : Expr → Bool) (f : Expr → m Unit) (e : Expr) : m Unit end Lean
31395efc873f375b6487c6bea9daf984205c026f
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Meta/Instances.lean
065460fa710d3dd5d8eff11c31c49d6c43a08924
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
4,941
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.ScopedEnvExtension import Lean.Meta.DiscrTree namespace Lean.Meta structure InstanceEntry where keys : Array DiscrTree.Key val : Expr priority : Nat globalName? : Option Name := none deriving Inhabited instance : BEq InstanceEntry where beq e₁ e₂ := e₁.val == e₂.val instance : ToFormat InstanceEntry where format e := match e.globalName? with | some n => fmt n | _ => "<local>" structure Instances where discrTree : DiscrTree InstanceEntry := DiscrTree.empty globalInstances : NameSet := {} deriving Inhabited def addInstanceEntry (d : Instances) (e : InstanceEntry) : Instances := { d with discrTree := d.discrTree.insertCore e.keys e globalInstances := match e.globalName? with | some n => d.globalInstances.insert n | none => d.globalInstances } builtin_initialize instanceExtension : SimpleScopedEnvExtension InstanceEntry Instances ← registerSimpleScopedEnvExtension { name := `instanceExt initial := {} addEntry := addInstanceEntry } private def mkInstanceKey (e : Expr) : MetaM (Array DiscrTree.Key) := do let type ← inferType e withNewMCtxDepth do let (_, _, type) ← forallMetaTelescopeReducing type DiscrTree.mkPath type def addInstance (declName : Name) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do let c ← mkConstWithLevelParams declName let keys ← mkInstanceKey c instanceExtension.add { keys := keys, val := c, priority := prio, globalName? := declName } attrKind builtin_initialize registerBuiltinAttribute { name := `instance descr := "type class instance" add := fun declName stx attrKind => do let prio ← getAttrParamOptPrio stx[1] discard <| addInstance declName attrKind prio |>.run {} {} } @[export lean_is_instance] def isGlobalInstance (env : Environment) (declName : Name) : Bool := Meta.instanceExtension.getState env |>.globalInstances.contains declName def getGlobalInstancesIndex : MetaM (DiscrTree InstanceEntry) := return Meta.instanceExtension.getState (← getEnv) |>.discrTree /- Default instance support -/ structure DefaultInstanceEntry where className : Name instanceName : Name priority : Nat abbrev PrioritySet := Std.RBTree Nat (fun x y => compare y x) structure DefaultInstances where defaultInstances : NameMap (List (Name × Nat)) := {} priorities : PrioritySet := {} deriving Inhabited def addDefaultInstanceEntry (d : DefaultInstances) (e : DefaultInstanceEntry) : DefaultInstances := let d := { d with priorities := d.priorities.insert e.priority } match d.defaultInstances.find? e.className with | some insts => { d with defaultInstances := d.defaultInstances.insert e.className <| (e.instanceName, e.priority) :: insts } | none => { d with defaultInstances := d.defaultInstances.insert e.className [(e.instanceName, e.priority)] } builtin_initialize defaultInstanceExtension : SimplePersistentEnvExtension DefaultInstanceEntry DefaultInstances ← registerSimplePersistentEnvExtension { name := `defaultInstanceExt addEntryFn := addDefaultInstanceEntry addImportedFn := fun es => (mkStateFromImportedEntries addDefaultInstanceEntry {} es) } def addDefaultInstance (declName : Name) (prio : Nat := 0) : MetaM Unit := do match (← getEnv).find? declName with | none => throwError "unknown constant '{declName}'" | some info => forallTelescopeReducing info.type fun _ type => do match type.getAppFn with | Expr.const className _ _ => unless isClass (← getEnv) className do throwError "invalid default instance '{declName}', it has type '({className} ...)', but {className}' is not a type class" setEnv <| defaultInstanceExtension.addEntry (← getEnv) { className := className, instanceName := declName, priority := prio } | _ => throwError "invalid default instance '{declName}', type must be of the form '(C ...)' where 'C' is a type class" builtin_initialize registerBuiltinAttribute { name := `defaultInstance descr := "type class default instance" add := fun declName stx kind => do let prio ← getAttrParamOptPrio stx[1] unless kind == AttributeKind.global do throwError "invalid attribute 'defaultInstance', must be global" discard <| addDefaultInstance declName prio |>.run {} {} } def getDefaultInstancesPriorities [Monad m] [MonadEnv m] : m PrioritySet := return defaultInstanceExtension.getState (← getEnv) |>.priorities def getDefaultInstances [Monad m] [MonadEnv m] (className : Name) : m (List (Name × Nat)) := return defaultInstanceExtension.getState (← getEnv) |>.defaultInstances.find? className |>.getD [] end Lean.Meta
8a82d384739e167001b1d18de5af73669f93cfde
7541ac8517945d0f903ff5397e13e2ccd7c10573
/src/category_theory/equivalence/characterisation.lean
e0111a32ef1a41038c64a7cbf65cd42a54da49c5
[]
no_license
ramonfmir/lean-category-theory
29b6bad9f62c2cdf7517a3135e5a12b340b4ed90
be516bcbc2dc21b99df2bcb8dde0d1e8de79c9ad
refs/heads/master
1,586,110,684,637
1,541,927,184,000
1,541,927,184,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,451
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import category_theory.equivalence import category_theory.natural_isomorphism import tidy.rewrite_search import tidy.command.rfl_lemma open category_theory namespace category_theory.equivalence universes u₁ u₂ variables {C : Type (u₁+1)} [large_category C] {D : Type (u₂+1)} [large_category D] def ess_surj_of_equivalence (F : C ⥤ D) [is_equivalence F] : ess_surj F := ⟨ λ Y : D, F.inv.obj Y, λ Y : D, (nat_iso.app F.inv_fun_id Y) ⟩ instance faithful_of_equivalence (F : C ⥤ D) [is_equivalence F] : faithful F := { injectivity' := λ X Y f g w, begin have p := congr_arg (@category_theory.functor.map _ _ _ _ F.inv _ _) w, simp at *, assumption end }. open tidy.rewrite_search.tracer open tidy.rewrite_search.strategy open tidy.rewrite_search.metric instance full_of_equivalence (F : C ⥤ D) [is_equivalence F] : full F := { preimage := λ X Y f, (nat_iso.app F.fun_inv_id X).inv ≫ (F.inv.map f) ≫ (nat_iso.app F.fun_inv_id Y).hom, witness' := λ X Y f, begin apply F.inv.injectivity, tidy, rewrite_search_using [`search] { --view := visualiser, trace_summary := tt, strategy := pexplore {pop_size := 3}, }, end }. section @[simp] private def equivalence_inverse (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : D ⥤ C := { obj := λ X, F.obj_preimage X, map := λ X Y f, F.preimage ((F.fun_obj_preimage_iso X).hom ≫ f ≫ (F.fun_obj_preimage_iso Y).inv), map_id' := λ X, begin apply F.injectivity, obviously, end, map_comp' := λ X Y Z f g, begin apply F.injectivity, obviously, end }. def equivalence_of_fully_faithfully_ess_surj (F : C ⥤ D) [full F] [faithful : faithful F] [ess_surj F] : is_equivalence F := { inverse := equivalence_inverse F, fun_inv_id' := nat_iso.of_components (λ X, preimage_iso (F.fun_obj_preimage_iso (F.obj X))) (λ X Y f, begin apply F.injectivity, obviously, end), inv_fun_id' := nat_iso.of_components (λ Y, (F.fun_obj_preimage_iso Y)) (by obviously) } end end category_theory.equivalence
f82e0950e3b6dab299a7f464ea30c2308e23a2ca
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/empty_thm.lean
07e0611a1a909e7f07344ede19da245bee46692e
[ "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
164
lean
import logic tools.tactic open tactic definition simple := apply trivial tactic_hint simple theorem foo : true theorem foo2 (a : Prop) : a : theorem foo3 : true
24373328b1e90d20923d9da9c6bdb6e9b1920739
4727251e0cd73359b15b664c3170e5d754078599
/src/field_theory/polynomial_galois_group.lean
dd73712774cc3960e5fc35c036c940787949c933
[ "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
21,826
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import group_theory.perm.cycle_type import analysis.complex.polynomial import field_theory.galois /-! # Galois Groups of Polynomials In this file, we introduce the Galois group of a polynomial `p` over a field `F`, defined as the automorphism group of its splitting field. We also provide some results about some extension `E` above `p.splitting_field`, and some specific results about the Galois groups of ℚ-polynomials with specific numbers of non-real roots. ## Main definitions - `polynomial.gal p`: the Galois group of a polynomial p. - `polynomial.gal.restrict p E`: the restriction homomorphism `(E ≃ₐ[F] E) → gal p`. - `polynomial.gal.gal_action p E`: the action of `gal p` on the roots of `p` in `E`. ## Main results - `polynomial.gal.restrict_smul`: `restrict p E` is compatible with `gal_action p E`. - `polynomial.gal.gal_action_hom_injective`: `gal p` acting on the roots of `p` in `E` is faithful. - `polynomial.gal.restrict_prod_injective`: `gal (p * q)` embeds as a subgroup of `gal p × gal q`. - `polynomial.gal.card_of_separable`: For a separable polynomial, its Galois group has cardinality equal to the dimension of its splitting field over `F`. - `polynomial.gal.gal_action_hom_bijective_of_prime_degree`: An irreducible polynomial of prime degree with two non-real roots has full Galois group. ## Other results - `polynomial.gal.card_complex_roots_eq_card_real_add_card_not_gal_inv`: The number of complex roots equals the number of real roots plus the number of roots not fixed by complex conjugation (i.e. with some imaginary component). -/ noncomputable theory open_locale classical polynomial open finite_dimensional namespace polynomial variables {F : Type*} [field F] (p q : F[X]) (E : Type*) [field E] [algebra F E] /-- The Galois group of a polynomial. -/ @[derive [group, fintype]] def gal := p.splitting_field ≃ₐ[F] p.splitting_field namespace gal instance : has_coe_to_fun p.gal (λ _, p.splitting_field → p.splitting_field) := alg_equiv.has_coe_to_fun @[ext] lemma ext {σ τ : p.gal} (h : ∀ x ∈ p.root_set p.splitting_field, σ x = τ x) : σ = τ := begin refine alg_equiv.ext (λ x, (alg_hom.mem_equalizer σ.to_alg_hom τ.to_alg_hom x).mp ((set_like.ext_iff.mp _ x).mpr algebra.mem_top)), rwa [eq_top_iff, ←splitting_field.adjoin_roots, algebra.adjoin_le_iff], end /-- If `p` splits in `F` then the `p.gal` is trivial. -/ def unique_gal_of_splits (h : p.splits (ring_hom.id F)) : unique p.gal := { default := 1, uniq := λ f, alg_equiv.ext (λ x, by { obtain ⟨y, rfl⟩ := algebra.mem_bot.mp ((set_like.ext_iff.mp ((is_splitting_field.splits_iff _ p).mp h) x).mp algebra.mem_top), rw [alg_equiv.commutes, alg_equiv.commutes] }) } instance [h : fact (p.splits (ring_hom.id F))] : unique p.gal := unique_gal_of_splits _ (h.1) instance unique_gal_zero : unique (0 : F[X]).gal := unique_gal_of_splits _ (splits_zero _) instance unique_gal_one : unique (1 : F[X]).gal := unique_gal_of_splits _ (splits_one _) instance unique_gal_C (x : F) : unique (C x).gal := unique_gal_of_splits _ (splits_C _ _) instance unique_gal_X : unique (X : F[X]).gal := unique_gal_of_splits _ (splits_X _) instance unique_gal_X_sub_C (x : F) : unique (X - C x).gal := unique_gal_of_splits _ (splits_X_sub_C _) instance unique_gal_X_pow (n : ℕ) : unique (X ^ n : F[X]).gal := unique_gal_of_splits _ (splits_X_pow _ _) instance [h : fact (p.splits (algebra_map F E))] : algebra p.splitting_field E := (is_splitting_field.lift p.splitting_field p h.1).to_ring_hom.to_algebra instance [h : fact (p.splits (algebra_map F E))] : is_scalar_tower F p.splitting_field E := is_scalar_tower.of_algebra_map_eq (λ x, ((is_splitting_field.lift p.splitting_field p h.1).commutes x).symm) -- The `algebra p.splitting_field E` instance above behaves badly when -- `E := p.splitting_field`, since it may result in a unification problem -- `is_splitting_field.lift.to_ring_hom.to_algebra =?= algebra.id`, -- which takes an extremely long time to resolve, causing timeouts. -- Since we don't really care about this definition, marking it as irreducible -- causes that unification to error out early. attribute [irreducible] gal.algebra /-- Restrict from a superfield automorphism into a member of `gal p`. -/ def restrict [fact (p.splits (algebra_map F E))] : (E ≃ₐ[F] E) →* p.gal := alg_equiv.restrict_normal_hom p.splitting_field lemma restrict_surjective [fact (p.splits (algebra_map F E))] [normal F E] : function.surjective (restrict p E) := alg_equiv.restrict_normal_hom_surjective E section roots_action /-- The function taking `roots p p.splitting_field` to `roots p E`. This is actually a bijection, see `polynomial.gal.map_roots_bijective`. -/ def map_roots [fact (p.splits (algebra_map F E))] : root_set p p.splitting_field → root_set p E := λ x, ⟨is_scalar_tower.to_alg_hom F p.splitting_field E x, begin have key := subtype.mem x, by_cases p = 0, { simp only [h, root_set_zero] at key, exact false.rec _ key }, { rw [mem_root_set h, aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩ lemma map_roots_bijective [h : fact (p.splits (algebra_map F E))] : function.bijective (map_roots p E) := begin split, { exact λ _ _ h, subtype.ext (ring_hom.injective _ (subtype.ext_iff.mp h)) }, { intro y, -- this is just an equality of two different ways to write the roots of `p` as an `E`-polynomial have key := roots_map (is_scalar_tower.to_alg_hom F p.splitting_field E : p.splitting_field →+* E) ((splits_id_iff_splits _).mpr (is_splitting_field.splits p.splitting_field p)), rw [map_map, alg_hom.comp_algebra_map] at key, have hy := subtype.mem y, simp only [root_set, finset.mem_coe, multiset.mem_to_finset, key, multiset.mem_map] at hy, rcases hy with ⟨x, hx1, hx2⟩, exact ⟨⟨x, multiset.mem_to_finset.mpr hx1⟩, subtype.ext hx2⟩ } end /-- The bijection between `root_set p p.splitting_field` and `root_set p E`. -/ def roots_equiv_roots [fact (p.splits (algebra_map F E))] : (root_set p p.splitting_field) ≃ (root_set p E) := equiv.of_bijective (map_roots p E) (map_roots_bijective p E) instance gal_action_aux : mul_action p.gal (root_set p p.splitting_field) := { smul := λ ϕ x, ⟨ϕ x, begin have key := subtype.mem x, --simp only [root_set, finset.mem_coe, multiset.mem_to_finset] at *, by_cases p = 0, { simp only [h, root_set_zero] at key, exact false.rec _ key }, { rw mem_root_set h, change aeval (ϕ.to_alg_hom x) p = 0, rw [aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩, one_smul := λ _, by { ext, refl }, mul_smul := λ _ _ _, by { ext, refl } } /-- The action of `gal p` on the roots of `p` in `E`. -/ instance gal_action [fact (p.splits (algebra_map F E))] : mul_action p.gal (root_set p E) := { smul := λ ϕ x, roots_equiv_roots p E (ϕ • ((roots_equiv_roots p E).symm x)), one_smul := λ _, by simp only [equiv.apply_symm_apply, one_smul], mul_smul := λ _ _ _, by simp only [equiv.apply_symm_apply, equiv.symm_apply_apply, mul_smul] } variables {p E} /-- `polynomial.gal.restrict p E` is compatible with `polynomial.gal.gal_action p E`. -/ @[simp] lemma restrict_smul [fact (p.splits (algebra_map F E))] (ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑((restrict p E ϕ) • x) = ϕ x := begin let ψ := alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F p.splitting_field E), change ↑(ψ (ψ.symm _)) = ϕ x, rw alg_equiv.apply_symm_apply ψ, change ϕ (roots_equiv_roots p E ((roots_equiv_roots p E).symm x)) = ϕ x, rw equiv.apply_symm_apply (roots_equiv_roots p E), end variables (p E) /-- `polynomial.gal.gal_action` as a permutation representation -/ def gal_action_hom [fact (p.splits (algebra_map F E))] : p.gal →* equiv.perm (root_set p E) := { to_fun := λ ϕ, equiv.mk (λ x, ϕ • x) (λ x, ϕ⁻¹ • x) (λ x, inv_smul_smul ϕ x) (λ x, smul_inv_smul ϕ x), map_one' := by { ext1 x, exact mul_action.one_smul x }, map_mul' := λ x y, by { ext1 z, exact mul_action.mul_smul x y z } } lemma gal_action_hom_restrict [fact (p.splits (algebra_map F E))] (ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑(gal_action_hom p E (restrict p E ϕ) x) = ϕ x := restrict_smul ϕ x /-- `gal p` embeds as a subgroup of permutations of the roots of `p` in `E`. -/ lemma gal_action_hom_injective [fact (p.splits (algebra_map F E))] : function.injective (gal_action_hom p E) := begin rw injective_iff_map_eq_one, intros ϕ hϕ, ext x hx, have key := equiv.perm.ext_iff.mp hϕ (roots_equiv_roots p E ⟨x, hx⟩), change roots_equiv_roots p E (ϕ • (roots_equiv_roots p E).symm (roots_equiv_roots p E ⟨x, hx⟩)) = roots_equiv_roots p E ⟨x, hx⟩ at key, rw equiv.symm_apply_apply at key, exact subtype.ext_iff.mp (equiv.injective (roots_equiv_roots p E) key), end end roots_action variables {p q} /-- `polynomial.gal.restrict`, when both fields are splitting fields of polynomials. -/ def restrict_dvd (hpq : p ∣ q) : q.gal →* p.gal := if hq : q = 0 then 1 else @restrict F _ p _ _ _ ⟨splits_of_splits_of_dvd (algebra_map F q.splitting_field) hq (splitting_field.splits q) hpq⟩ lemma restrict_dvd_surjective (hpq : p ∣ q) (hq : q ≠ 0) : function.surjective (restrict_dvd hpq) := by simp only [restrict_dvd, dif_neg hq, restrict_surjective] variables (p q) /-- The Galois group of a product maps into the product of the Galois groups. -/ def restrict_prod : (p * q).gal →* p.gal × q.gal := monoid_hom.prod (restrict_dvd (dvd_mul_right p q)) (restrict_dvd (dvd_mul_left q p)) /-- `polynomial.gal.restrict_prod` is actually a subgroup embedding. -/ lemma restrict_prod_injective : function.injective (restrict_prod p q) := begin by_cases hpq : (p * q) = 0, { haveI : unique (p * q).gal, { rw hpq, apply_instance }, exact λ f g h, eq.trans (unique.eq_default f) (unique.eq_default g).symm }, intros f g hfg, dsimp only [restrict_prod, restrict_dvd] at hfg, simp only [dif_neg hpq, monoid_hom.prod_apply, prod.mk.inj_iff] at hfg, ext x hx, rw [root_set, polynomial.map_mul, polynomial.roots_mul] at hx, cases multiset.mem_add.mp (multiset.mem_to_finset.mp hx) with h h, { haveI : fact (p.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_right p q)⟩, have key : x = algebra_map (p.splitting_field) (p * q).splitting_field ((roots_equiv_roots p _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots p _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.1 _) }, { haveI : fact (q.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_left q p)⟩, have key : x = algebra_map (q.splitting_field) (p * q).splitting_field ((roots_equiv_roots q _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots q _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.2 _) }, { rwa [ne.def, mul_eq_zero, map_eq_zero, map_eq_zero, ←mul_eq_zero] } end lemma mul_splits_in_splitting_field_of_mul {p₁ q₁ p₂ q₂ : F[X]} (hq₁ : q₁ ≠ 0) (hq₂ : q₂ ≠ 0) (h₁ : p₁.splits (algebra_map F q₁.splitting_field)) (h₂ : p₂.splits (algebra_map F q₂.splitting_field)) : (p₁ * p₂).splits (algebra_map F (q₁ * q₂).splitting_field) := begin apply splits_mul, { rw ← (splitting_field.lift q₁ (splits_of_splits_of_dvd _ (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_right q₁ q₂))).comp_algebra_map, exact splits_comp_of_splits _ _ h₁, }, { rw ← (splitting_field.lift q₂ (splits_of_splits_of_dvd _ (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_left q₂ q₁))).comp_algebra_map, exact splits_comp_of_splits _ _ h₂, }, end /-- `p` splits in the splitting field of `p ∘ q`, for `q` non-constant. -/ lemma splits_in_splitting_field_of_comp (hq : q.nat_degree ≠ 0) : p.splits (algebra_map F (p.comp q).splitting_field) := begin let P : F[X] → Prop := λ r, r.splits (algebra_map F (r.comp q).splitting_field), have key1 : ∀ {r : F[X]}, irreducible r → P r, { intros r hr, by_cases hr' : nat_degree r = 0, { exact splits_of_nat_degree_le_one _ (le_trans (le_of_eq hr') zero_le_one) }, obtain ⟨x, hx⟩ := exists_root_of_splits _ (splitting_field.splits (r.comp q)) (λ h, hr' ((mul_eq_zero.mp (nat_degree_comp.symm.trans (nat_degree_eq_of_degree_eq_some h))).resolve_right hq)), rw [←aeval_def, aeval_comp] at hx, have h_normal : normal F (r.comp q).splitting_field := splitting_field.normal (r.comp q), have qx_int := normal.is_integral h_normal (aeval x q), exact splits_of_splits_of_dvd _ (minpoly.ne_zero qx_int) (normal.splits h_normal _) ((minpoly.irreducible qx_int).dvd_symm hr (minpoly.dvd F _ hx)) }, have key2 : ∀ {p₁ p₂ : F[X]}, P p₁ → P p₂ → P (p₁ * p₂), { intros p₁ p₂ hp₁ hp₂, by_cases h₁ : p₁.comp q = 0, { cases comp_eq_zero_iff.mp h₁ with h h, { rw [h, zero_mul], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, by_cases h₂ : p₂.comp q = 0, { cases comp_eq_zero_iff.mp h₂ with h h, { rw [h, mul_zero], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, have key := mul_splits_in_splitting_field_of_mul h₁ h₂ hp₁ hp₂, rwa ← mul_comp at key }, exact wf_dvd_monoid.induction_on_irreducible p (splits_zero _) (λ _, splits_of_is_unit _) (λ _ _ _ h, key2 (key1 h)), end /-- `polynomial.gal.restrict` for the composition of polynomials. -/ def restrict_comp (hq : q.nat_degree ≠ 0) : (p.comp q).gal →* p.gal := @restrict F _ p _ _ _ ⟨splits_in_splitting_field_of_comp p q hq⟩ lemma restrict_comp_surjective (hq : q.nat_degree ≠ 0) : function.surjective (restrict_comp p q hq) := by simp only [restrict_comp, restrict_surjective] variables {p q} /-- For a separable polynomial, its Galois group has cardinality equal to the dimension of its splitting field over `F`. -/ lemma card_of_separable (hp : p.separable) : fintype.card p.gal = finrank F p.splitting_field := begin haveI : is_galois F p.splitting_field := is_galois.of_separable_splitting_field hp, exact is_galois.card_aut_eq_finrank F p.splitting_field, end lemma prime_degree_dvd_card [char_zero F] (p_irr : irreducible p) (p_deg : p.nat_degree.prime) : p.nat_degree ∣ fintype.card p.gal := begin rw gal.card_of_separable p_irr.separable, have hp : p.degree ≠ 0 := λ h, nat.prime.ne_zero p_deg (nat_degree_eq_zero_iff_degree_le_zero.mpr (le_of_eq h)), let α : p.splitting_field := root_of_splits (algebra_map F p.splitting_field) (splitting_field.splits p) hp, have hα : is_integral F α := algebra.is_integral_of_finite _ _ α, use finite_dimensional.finrank F⟮α⟯ p.splitting_field, suffices : (minpoly F α).nat_degree = p.nat_degree, { rw [←finite_dimensional.finrank_mul_finrank F F⟮α⟯ p.splitting_field, intermediate_field.adjoin.finrank hα, this] }, suffices : minpoly F α ∣ p, { have key := (minpoly.irreducible hα).dvd_symm p_irr this, apply le_antisymm, { exact nat_degree_le_of_dvd this p_irr.ne_zero }, { exact nat_degree_le_of_dvd key (minpoly.ne_zero hα) } }, apply minpoly.dvd F α, rw [aeval_def, map_root_of_splits _ (splitting_field.splits p) hp], end section rationals lemma splits_ℚ_ℂ {p : ℚ[X]} : fact (p.splits (algebra_map ℚ ℂ)) := ⟨is_alg_closed.splits_codomain p⟩ local attribute [instance] splits_ℚ_ℂ /-- The number of complex roots equals the number of real roots plus the number of roots not fixed by complex conjugation (i.e. with some imaginary component). -/ lemma card_complex_roots_eq_card_real_add_card_not_gal_inv (p : ℚ[X]) : (p.root_set ℂ).to_finset.card = (p.root_set ℝ).to_finset.card + (gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ))).support.card := begin by_cases hp : p = 0, { simp_rw [hp, root_set_zero, set.to_finset_eq_empty_iff.mpr rfl, finset.card_empty, zero_add], refine eq.symm (nat.le_zero_iff.mp ((finset.card_le_univ _).trans (le_of_eq _))), simp_rw [hp, root_set_zero, fintype.card_eq_zero_iff], apply_instance }, have inj : function.injective (is_scalar_tower.to_alg_hom ℚ ℝ ℂ) := (algebra_map ℝ ℂ).injective, rw [←finset.card_image_of_injective _ subtype.coe_injective, ←finset.card_image_of_injective _ inj], let a : finset ℂ := _, let b : finset ℂ := _, let c : finset ℂ := _, change a.card = b.card + c.card, have ha : ∀ z : ℂ, z ∈ a ↔ aeval z p = 0 := λ z, by rw [set.mem_to_finset, mem_root_set hp], have hb : ∀ z : ℂ, z ∈ b ↔ aeval z p = 0 ∧ z.im = 0, { intro z, simp_rw [finset.mem_image, exists_prop, set.mem_to_finset, mem_root_set hp], split, { rintros ⟨w, hw, rfl⟩, exact ⟨by rw [aeval_alg_hom_apply, hw, alg_hom.map_zero], rfl⟩ }, { rintros ⟨hz1, hz2⟩, have key : is_scalar_tower.to_alg_hom ℚ ℝ ℂ z.re = z := by { ext, refl, rw hz2, refl }, exact ⟨z.re, inj (by rwa [←aeval_alg_hom_apply, key, alg_hom.map_zero]), key⟩ } }, have hc0 : ∀ w : p.root_set ℂ, gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ)) w = w ↔ w.val.im = 0, { intro w, rw [subtype.ext_iff, gal_action_hom_restrict], exact complex.eq_conj_iff_im }, have hc : ∀ z : ℂ, z ∈ c ↔ aeval z p = 0 ∧ z.im ≠ 0, { intro z, simp_rw [finset.mem_image, exists_prop], split, { rintros ⟨w, hw, rfl⟩, exact ⟨(mem_root_set hp).mp w.2, mt (hc0 w).mpr (equiv.perm.mem_support.mp hw)⟩ }, { rintros ⟨hz1, hz2⟩, exact ⟨⟨z, (mem_root_set hp).mpr hz1⟩, equiv.perm.mem_support.mpr (mt (hc0 _).mp hz2), rfl⟩ } }, rw ← finset.card_disjoint_union, { apply congr_arg finset.card, simp_rw [finset.ext_iff, finset.mem_union, ha, hb, hc], tauto }, { intro z, rw [finset.inf_eq_inter, finset.mem_inter, hb, hc], tauto }, { apply_instance }, end /-- An irreducible polynomial of prime degree with two non-real roots has full Galois group. -/ lemma gal_action_hom_bijective_of_prime_degree {p : ℚ[X]} (p_irr : irreducible p) (p_deg : p.nat_degree.prime) (p_roots : fintype.card (p.root_set ℂ) = fintype.card (p.root_set ℝ) + 2) : function.bijective (gal_action_hom p ℂ) := begin have h1 : fintype.card (p.root_set ℂ) = p.nat_degree, { simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe], rw [multiset.to_finset_card_of_nodup, ←nat_degree_eq_card_roots], { exact is_alg_closed.splits_codomain p }, { exact nodup_roots ((separable_map (algebra_map ℚ ℂ)).mpr p_irr.separable) } }, have h2 : fintype.card p.gal = fintype.card (gal_action_hom p ℂ).range := fintype.card_congr (monoid_hom.of_injective (gal_action_hom_injective p ℂ)).to_equiv, let conj := restrict p ℂ (complex.conj_ae.restrict_scalars ℚ), refine ⟨gal_action_hom_injective p ℂ, λ x, (congr_arg (has_mem.mem x) (show (gal_action_hom p ℂ).range = ⊤, from _)).mpr (subgroup.mem_top x)⟩, apply equiv.perm.subgroup_eq_top_of_swap_mem, { rwa h1 }, { rw h1, convert prime_degree_dvd_card p_irr p_deg using 1, convert h2.symm }, { exact ⟨conj, rfl⟩ }, { rw ← equiv.perm.card_support_eq_two, apply nat.add_left_cancel, rw [←p_roots, ←set.to_finset_card (root_set p ℝ), ←set.to_finset_card (root_set p ℂ)], exact (card_complex_roots_eq_card_real_add_card_not_gal_inv p).symm }, end /-- An irreducible polynomial of prime degree with 1-3 non-real roots has full Galois group. -/ lemma gal_action_hom_bijective_of_prime_degree' {p : ℚ[X]} (p_irr : irreducible p) (p_deg : p.nat_degree.prime) (p_roots1 : fintype.card (p.root_set ℝ) + 1 ≤ fintype.card (p.root_set ℂ)) (p_roots2 : fintype.card (p.root_set ℂ) ≤ fintype.card (p.root_set ℝ) + 3) : function.bijective (gal_action_hom p ℂ) := begin apply gal_action_hom_bijective_of_prime_degree p_irr p_deg, let n := (gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ))).support.card, have hn : 2 ∣ n := equiv.perm.two_dvd_card_support (by rw [←monoid_hom.map_pow, ←monoid_hom.map_pow, show alg_equiv.restrict_scalars ℚ complex.conj_ae ^ 2 = 1, from alg_equiv.ext complex.conj_conj, monoid_hom.map_one, monoid_hom.map_one]), have key := card_complex_roots_eq_card_real_add_card_not_gal_inv p, simp_rw [set.to_finset_card] at key, rw [key, add_le_add_iff_left] at p_roots1 p_roots2, rw [key, add_right_inj], suffices : ∀ m : ℕ, 2 ∣ m → 1 ≤ m → m ≤ 3 → m = 2, { exact this n hn p_roots1 p_roots2 }, rintros m ⟨k, rfl⟩ h2 h3, exact le_antisymm (nat.lt_succ_iff.mp (lt_of_le_of_ne h3 (show 2 * k ≠ 2 * 1 + 1, from nat.two_mul_ne_two_mul_add_one))) (nat.succ_le_iff.mpr (lt_of_le_of_ne h2 (show 2 * 0 + 1 ≠ 2 * k, from nat.two_mul_ne_two_mul_add_one.symm))), end end rationals end gal end polynomial
da428a79ae890b2f37ed5d82e370c7289848c281
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/meta/smt/smt_tactic.lean
fa0b5ebf3d8082d2383debd857806a332e51abef
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
15,317
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.category import init.meta.simp_tactic import init.meta.smt.congruence_closure import init.meta.smt.ematch universe u run_cmd mk_simp_attr `pre_smt run_cmd mk_hinst_lemma_attr_set `ematch [] [`ematch_lhs] /-- Configuration for the smt tactic preprocessor. The preprocessor is applied whenever a new hypothesis is introduced. - simp_attr: is the attribute name for the simplification lemmas that are used during the preprocessing step. - max_steps: it is the maximum number of steps performed by the simplifier. - zeta: if tt, then zeta reduction (i.e., unfolding let-expressions) is used during preprocessing. -/ structure smt_pre_config := (simp_attr : name := `pre_smt) (max_steps : nat := 1000000) (zeta : bool := ff) /-- Configuration for the smt_state object. - em_attr: is the attribute name for the hinst_lemmas that are used for ematching -/ structure smt_config := (cc_cfg : cc_config := {}) (em_cfg : ematch_config := {}) (pre_cfg : smt_pre_config := {}) (em_attr : name := `ematch) meta def smt_config.set_classical (c : smt_config) (b : bool) : smt_config := {c with cc_cfg := { (c.cc_cfg) with em := b}} meta constant smt_goal : Type meta def smt_state := list smt_goal meta constant smt_state.mk : smt_config → tactic smt_state meta constant smt_state.to_format : smt_state → tactic_state → format /-- Return tt iff classical excluded middle was enabled at smt_state.mk -/ meta constant smt_state.classical : smt_state → bool meta def smt_tactic := state_t smt_state tactic meta instance : has_append smt_state := list.has_append meta instance : monad smt_tactic := state_t.monad _ _ /- We don't use the default state_t lift operation because only tactics that do not change hypotheses can be automatically lifted to smt_tactic. -/ meta constant tactic_to_smt_tactic (α : Type) : tactic α → smt_tactic α meta instance : monad.has_monad_lift tactic smt_tactic := ⟨tactic_to_smt_tactic⟩ meta instance (α : Type) : has_coe (tactic α) (smt_tactic α) := ⟨monad.monad_lift⟩ meta def smt_tactic_orelse {α : Type} (t₁ t₂ : smt_tactic α) : smt_tactic α := λ ss ts, result.cases_on (t₁ ss ts) result.success (λ e₁ ref₁ s', result.cases_on (t₂ ss ts) result.success result.exception) meta instance : monad_fail smt_tactic := { smt_tactic.monad with fail := λ α s, (tactic.fail (to_fmt s) : smt_tactic α) } meta instance : alternative smt_tactic := { smt_tactic.monad with failure := λ α, @tactic.failed α, orelse := @smt_tactic_orelse } namespace smt_tactic open tactic (transparency) meta constant intros : smt_tactic unit meta constant intron : nat → smt_tactic unit meta constant intro_lst : list name → smt_tactic unit /-- Try to close main goal by using equalities implied by the congruence closure module. -/ meta constant close : smt_tactic unit /-- Produce new facts using heuristic lemma instantiation based on E-matching. This tactic tries to match patterns from lemmas in the main goal with terms in the main goal. The set of lemmas is populated with theorems tagged with the attribute specified at smt_config.em_attr, and lemmas added using tactics such as `smt_tactic.add_lemmas`. The current set of lemmas can be retrieved using the tactic `smt_tactic.get_lemmas`. Remark: the given predicate is applied to every new instance. The instance is only added to the state if the predicate returns tt. -/ meta constant ematch_core : (expr → bool) → smt_tactic unit /-- Produce new facts using heuristic lemma instantiation based on E-matching. This tactic tries to match patterns from the given lemmas with terms in the main goal. -/ meta constant ematch_using : hinst_lemmas → smt_tactic unit meta constant mk_ematch_eqn_lemmas_for_core : transparency → name → smt_tactic hinst_lemmas meta constant to_cc_state : smt_tactic cc_state meta constant to_em_state : smt_tactic ematch_state meta constant get_config : smt_tactic smt_config /-- Preprocess the given term using the same simplifications rules used when we introduce a new hypothesis. The result is pair containing the resulting term and a proof that it is equal to the given one. -/ meta constant preprocess : expr → smt_tactic (expr × expr) meta constant get_lemmas : smt_tactic hinst_lemmas meta constant set_lemmas : hinst_lemmas → smt_tactic unit meta constant add_lemmas : hinst_lemmas → smt_tactic unit meta def add_ematch_lemma_core (md : transparency) (as_simp : bool) (e : expr) : smt_tactic unit := do h ← hinst_lemma.mk_core md e as_simp, add_lemmas (mk_hinst_singleton h) meta def add_ematch_lemma_from_decl_core (md : transparency) (as_simp : bool) (n : name) : smt_tactic unit := do h ← hinst_lemma.mk_from_decl_core md n as_simp, add_lemmas (mk_hinst_singleton h) meta def add_ematch_eqn_lemmas_for_core (md : transparency) (n : name) : smt_tactic unit := do hs ← mk_ematch_eqn_lemmas_for_core md n, add_lemmas hs meta def ematch : smt_tactic unit := ematch_core (λ _, tt) meta def failed {α} : smt_tactic α := tactic.failed meta def fail {α : Type} {β : Type u} [has_to_format β] (msg : β) : smt_tactic α := tactic.fail msg meta def try {α : Type} (t : smt_tactic α) : smt_tactic unit := λ ss ts, result.cases_on (t ss ts) (λ ⟨a, new_ss⟩, result.success ((), new_ss)) (λ e ref s', result.success ((), ss) ts) /-- `repeat_at_most n t`: repeat the given tactic at most n times or until t fails -/ meta def repeat_at_most : nat → smt_tactic unit → smt_tactic unit | 0 t := return () | (n+1) t := (do t, repeat_at_most n t) <|> return () /-- `repeat_exactly n t` : execute t n times -/ meta def repeat_exactly : nat → smt_tactic unit → smt_tactic unit | 0 t := return () | (n+1) t := do t, repeat_exactly n t meta def repeat : smt_tactic unit → smt_tactic unit := repeat_at_most 100000 meta def eblast : smt_tactic unit := repeat (ematch >> try close) open tactic protected meta def read : smt_tactic (smt_state × tactic_state) := do s₁ ← state_t.read, s₂ ← tactic.read, return (s₁, s₂) protected meta def write : smt_state × tactic_state → smt_tactic unit := λ ⟨ss, ts⟩ _ _, result.success ((), ss) ts private meta def mk_smt_goals_for (cfg : smt_config) : list expr → list smt_goal → list expr → tactic (list smt_goal × list expr) | [] sr tr := return (sr.reverse, tr.reverse) | (tg::tgs) sr tr := do tactic.set_goals [tg], [new_sg] ← smt_state.mk cfg | tactic.failed, [new_tg] ← get_goals | tactic.failed, mk_smt_goals_for tgs (new_sg::sr) (new_tg::tr) /- See slift -/ meta def slift_aux {α : Type} (t : tactic α) (cfg : smt_config) : smt_tactic α := λ ss, do _::sgs ← return ss | tactic.fail "slift tactic failed, there no smt goals to be solved", tg::tgs ← tactic.get_goals | tactic.failed, tactic.set_goals [tg], a ← t, new_tgs ← tactic.get_goals, (new_sgs, new_tgs) ← mk_smt_goals_for cfg new_tgs [] [], tactic.set_goals (new_tgs ++ tgs), return (a, new_sgs ++ sgs) /-- This lift operation will restart the SMT state. It is useful for using tactics that change the set of hypotheses. -/ meta def slift {α : Type} (t : tactic α) : smt_tactic α := get_config >>= slift_aux t meta def trace_state : smt_tactic unit := do (s₁, s₂) ← smt_tactic.read, trace (smt_state.to_format s₁ s₂) meta def trace {α : Type} [has_to_tactic_format α] (a : α) : smt_tactic unit := tactic.trace a meta def to_expr (q : pexpr) (allow_mvars := tt) : smt_tactic expr := tactic.to_expr q allow_mvars meta def classical : smt_tactic bool := do s ← state_t.read, return s.classical meta def num_goals : smt_tactic nat := λ ss, return (ss.length, ss) /- Low level primitives for managing set of goals -/ meta def get_goals : smt_tactic (list smt_goal × list expr) := do (g₁, _) ← smt_tactic.read, g₂ ← tactic.get_goals, return (g₁, g₂) meta def set_goals : list smt_goal → list expr → smt_tactic unit := λ g₁ g₂ ss, tactic.set_goals g₂ >> return ((), g₁) private meta def all_goals_core (tac : smt_tactic unit) : list smt_goal → list expr → list smt_goal → list expr → smt_tactic unit | [] ts acs act := set_goals acs (ts ++ act) | (s :: ss) [] acs act := fail "ill-formed smt_state" | (s :: ss) (t :: ts) acs act := do set_goals [s] [t], tac, (new_ss, new_ts) ← get_goals, all_goals_core ss ts (acs ++ new_ss) (act ++ new_ts) /-- Apply the given tactic to all goals. -/ meta def all_goals (tac : smt_tactic unit) : smt_tactic unit := do (ss, ts) ← get_goals, all_goals_core tac ss ts [] [] /-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : smt_tactic unit) (tac2 : smt_tactic unit) : smt_tactic unit := do (s::ss, t::ts) ← get_goals, set_goals [s] [t], tac1, all_goals tac2, (new_ss, new_ts) ← get_goals, set_goals (new_ss ++ ss) (new_ts ++ ts) meta instance : has_andthen (smt_tactic unit) (smt_tactic unit) (smt_tactic unit) := ⟨seq⟩ meta def focus1 {α} (tac : smt_tactic α) : smt_tactic α := do (s::ss, t::ts) ← get_goals, match ss with | [] := tac | _ := do set_goals [s] [t], a ← tac, (ss', ts') ← get_goals, set_goals (ss' ++ ss) (ts' ++ ts), return a end meta def solve1 (tac : smt_tactic unit) : smt_tactic unit := do (ss, gs) ← get_goals, match ss, gs with | [], _ := fail "solve1 tactic failed, there isn't any goal left to focus" | _, [] := fail "solve1 tactic failed, there isn't any smt goal left to focus" | s::ss, g::gs := do set_goals [s] [g], tac, (ss', gs') ← get_goals, match ss', gs' with | [], [] := set_goals ss gs | _, _ := fail "solve1 tactic failed, focused goal has not been solved" end end meta def swap : smt_tactic unit := do (ss, ts) ← get_goals, match ss, ts with | (s₁ :: s₂ :: ss), (t₁ :: t₂ :: ts) := set_goals (s₂ :: s₁ :: ss) (t₂ :: t₁ :: ts) | _, _ := failed end /-- Add a new goal for t, and the hypothesis (h : t) in the current goal. -/ meta def assert (h : name) (t : expr) : smt_tactic unit := tactic.assert_core h t >> swap >> intros >> swap >> try close /-- Add the hypothesis (h : t) in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : smt_tactic unit := tactic.assertv_core h t v >> intros >> return () /-- Add a new goal for t, and the hypothesis (h : t := ?M) in the current goal. -/ meta def define (h : name) (t : expr) : smt_tactic unit := tactic.define_core h t >> swap >> intros >> swap >> try close /-- Add the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : smt_tactic unit := tactic.definev_core h t v >> intros >> return () /-- Add (h : t := pr) to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : smt_tactic unit := match t with | none := do t ← infer_type pr, definev h t pr | some t := definev h t pr end /-- Add (h : t) to the current goal, given a proof (pr : t) -/ meta def note (h : name) (t : option expr := none) (pr : expr) : smt_tactic unit := match t with | none := do t ← infer_type pr, assertv h t pr | some t := assertv h t pr end meta def destruct (e : expr) : smt_tactic unit := smt_tactic.seq (tactic.destruct e) smt_tactic.intros meta def by_cases (e : expr) : smt_tactic unit := do c ← classical, if c then destruct (expr.app (expr.const `classical.em []) e) else do dec_e ← (mk_app `decidable [e] <|> fail "by_cases smt_tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases smt_tactic failed, type of given expression is not decidable"), em ← mk_app `decidable.em [e, inst], destruct em meta def by_contradiction : smt_tactic unit := do t ← target, c ← classical, if t.is_false then skip else if c then do apply (expr.app (expr.const `classical.by_contradiction []) t), intros else do dec_t ← (mk_app `decidable [t] <|> fail "by_contradiction smt_tactic failed, target is not a proposition"), inst ← (mk_instance dec_t <|> fail "by_contradiction smt_tactic failed, target is not decidable"), a ← mk_mapp `decidable.by_contradiction [some t, some inst], apply a, intros /-- Return a proof for e, if 'e' is a known fact in the main goal. -/ meta def proof_for (e : expr) : smt_tactic expr := do cc ← to_cc_state, cc.proof_for e /-- Return a refutation for e (i.e., a proof for (not e)), if 'e' has been refuted in the main goal. -/ meta def refutation_for (e : expr) : smt_tactic expr := do cc ← to_cc_state, cc.refutation_for e meta def get_facts : smt_tactic (list expr) := do cc ← to_cc_state, return $ cc.eqc_of expr.mk_true meta def get_refuted_facts : smt_tactic (list expr) := do cc ← to_cc_state, return $ cc.eqc_of expr.mk_false meta def add_ematch_lemma : expr → smt_tactic unit := add_ematch_lemma_core reducible ff meta def add_ematch_lhs_lemma : expr → smt_tactic unit := add_ematch_lemma_core reducible tt meta def add_ematch_lemma_from_decl : name → smt_tactic unit := add_ematch_lemma_from_decl_core reducible ff meta def add_ematch_lhs_lemma_from_decl : name → smt_tactic unit := add_ematch_lemma_from_decl_core reducible ff meta def add_ematch_eqn_lemmas_for : name → smt_tactic unit := add_ematch_eqn_lemmas_for_core reducible meta def add_lemmas_from_facts_core : list expr → smt_tactic unit | [] := return () | (f::fs) := do try (is_prop f >> guard (f.is_pi && bnot (f.is_arrow)) >> proof_for f >>= add_ematch_lemma_core reducible ff), add_lemmas_from_facts_core fs meta def add_lemmas_from_facts : smt_tactic unit := get_facts >>= add_lemmas_from_facts_core meta def induction (e : expr) (ids : list name := []) (rec : option name := none) : smt_tactic unit := slift (tactic.induction e ids rec >> return ()) -- pass on the information? meta def when (c : Prop) [decidable c] (tac : smt_tactic unit) : smt_tactic unit := if c then tac else skip meta def when_tracing (n : name) (tac : smt_tactic unit) : smt_tactic unit := when (is_trace_enabled_for n = tt) tac end smt_tactic open smt_tactic meta def using_smt {α} (t : smt_tactic α) (cfg : smt_config := {}) : tactic α := do ss ← smt_state.mk cfg, (a, _) ← (do a ← t, repeat close, return a) ss, return a meta def using_smt_with {α} (cfg : smt_config) (t : smt_tactic α) : tactic α := using_smt t cfg
c242ba923c86a9e0c28387b752d83b4bf4d99d08
1437b3495ef9020d5413178aa33c0a625f15f15f
/ring_theory/unique_factorization_domain.lean
dacb4784ea3fd97d92fc1f3ebb9d0f6dd0c2018b
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,851
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker Theory of unique factorization domains. @TODO: setup the complete lattice structure on `factor_set`. -/ import ring_theory.associated algebra.gcd_domain variables {α : Type*} local infix ` ~ᵤ ` : 50 := associated /-- Unique factorization domains. In a unique factorization domain each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. This is equivalent to defining a unique factorization domain as a domain in which each element (except zero) is non-uniquely represented as a multiset of prime factors. This definition is used. To define a UFD using the traditional definition in terms of multisets of irreducible factors, use the definition `of_unique_irreducible_factorization` -/ class unique_factorization_domain (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (prime_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, prime x) namespace unique_factorization_domain variables [integral_domain α] [unique_factorization_domain α] @[elab_as_eliminator] lemma induction_on_prime {P : α → Prop} (a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x) (h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a := by haveI := classical.dec_eq α; exact if ha0 : a = 0 then ha0.symm ▸ h₁ else @multiset.induction_on _ (λ s : multiset α, ∀ (a : α), a ≠ 0 → s.prod ~ᵤ a → (∀ p ∈ s, prime p) → P a) (factors a) (λ _ _ h _, h₂ _ ((is_unit_iff_of_associated h.symm).2 is_unit_one)) (λ p s ih a ha0 ⟨u, hu⟩ hsp, have ha : a = (p * u) * s.prod, by simp [hu.symm, mul_comm, mul_assoc], have hs0 : s.prod ≠ 0, from λ _ : s.prod = 0, by simp * at *, ha.symm ▸ h₃ _ _ hs0 (prime_of_associated ⟨u, rfl⟩ (hsp p (multiset.mem_cons_self _ _))) (ih _ hs0 (by refl) (λ p hp, hsp p (multiset.mem_cons.2 (or.inr hp))))) _ ha0 (factors_prod ha0) (prime_factors ha0) lemma factors_irreducible {a : α} (ha : irreducible a) : ∃ p, a ~ᵤ p ∧ factors a = p :: 0 := by haveI := classical.dec_eq α; exact multiset.induction_on (factors a) (λ h, (ha.1 (associated_one_iff_is_unit.1 h.symm)).elim) (λ p s _ hp hs, let ⟨u, hu⟩ := hp in ⟨p, have hs0 : s = 0, from classical.by_contradiction (λ hs0, let ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0 in (hs q (by simp [hq])).2.1 $ (ha.2 ((p * u) * (s.erase q).prod) _ (by rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq]; simp [hu.symm, mul_comm, mul_assoc])).resolve_left $ mt is_unit_of_mul_is_unit_left $ mt is_unit_of_mul_is_unit_left (hs p (multiset.mem_cons_self _ _)).2.1), ⟨associated.symm (by clear _let_match; simp * at *), hs0 ▸ rfl⟩⟩) (factors_prod (nonzero_of_irreducible ha)) (prime_factors (nonzero_of_irreducible ha)) lemma irreducible_iff_prime {p : α} : irreducible p ↔ prime p := by letI := classical.dec_eq α; exact if hp0 : p = 0 then by simp [hp0] else ⟨λ h, let ⟨q, hq⟩ := factors_irreducible h in have prime q, from hq.2 ▸ prime_factors hp0 _ (by simp [hq.2]), suffices prime (factors p).prod, from prime_of_associated (factors_prod hp0) this, hq.2.symm ▸ by simp [this], irreducible_of_prime⟩ lemma irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x := by simp only [irreducible_iff_prime]; exact @prime_factors _ _ _ lemma unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).1 (is_unit_iff_dvd_one.2 (dvd.trans (multiset.dvd_prod hx) (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (irreducible_iff_prime.1 (hf p (by simp))) (λ q hq, irreducible_iff_prime.1 (hg _ hq)) $ (dvd_iff_dvd_of_rel_right hfg).1 (show p ∣ (p :: f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated_mul_left_cancel (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (nonzero_of_irreducible (hf p (by simp))))) end) end unique_factorization_domain structure unique_irreducible_factorization (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x) (unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) namespace unique_factorization_domain def of_unique_irreducible_factorization {α : Type*} [integral_domain α] (o : unique_irreducible_factorization α) : unique_factorization_domain α := by letI := classical.dec_eq α; exact { prime_factors := λ a h p (hpa : p ∈ o.factors a), have hpi : irreducible p, from o.irreducible_factors h _ hpa, ⟨nonzero_of_irreducible hpi, hpi.1, λ a b ⟨x, hx⟩, if hab0 : a * b = 0 then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim (λ ha0, by simp [ha0]) (λ hb0, by simp [hb0]) else have hx0 : x ≠ 0, from λ hx0, by simp * at *, have ha0 : a ≠ 0, from ne_zero_of_mul_ne_zero_right hab0, have hb0 : b ≠ 0, from ne_zero_of_mul_ne_zero_left hab0, have multiset.rel associated (p :: o.factors x) (o.factors a + o.factors b), from o.unique (λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (o.irreducible_factors hx0 _)) (show ∀ x ∈ o.factors a + o.factors b, irreducible x, from λ x hx, (multiset.mem_add.1 hx).elim (o.irreducible_factors (ne_zero_of_mul_ne_zero_right hab0) _) (o.irreducible_factors (ne_zero_of_mul_ne_zero_left hab0) _)) $ calc multiset.prod (p :: o.factors x) ~ᵤ a * b : by rw [hx, multiset.prod_cons]; exact associated_mul_mul (by refl) (o.factors_prod hx0) ... ~ᵤ (o.factors a).prod * (o.factors b).prod : associated_mul_mul (o.factors_prod ha0).symm (o.factors_prod hb0).symm ... = _ : by rw multiset.prod_add, let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem this (multiset.mem_cons_self p _) in (multiset.mem_add.1 hqf).elim (λ hqa, or.inl $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod ha0)).1 (multiset.dvd_prod hqa)) (λ hqb, or.inr $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod hb0)).1 (multiset.dvd_prod hqb))⟩, ..o } end unique_factorization_domain namespace associates open unique_factorization_domain associated lattice variables [integral_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] /-- `factor_set α` representation elements of unique factorization domain as multisets. `multiset α` produced by `factors` are only unique up to associated elements, while the multisets in `factor_set α` are unqiue by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ @[reducible] def {u} factor_set (α : Type u) [integral_domain α] [unique_factorization_domain α] : Type u := with_top (multiset { a : associates α // irreducible a }) local attribute [instance] associated.setoid theorem unique' {p q : multiset (associates α)} : (∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q := begin apply multiset.induction_on_multiset_quot p, apply multiset.induction_on_multiset_quot q, assume s t hs ht eq, refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_domain.unique _ _ _), { exact assume a ha, ((irreducible_mk_iff _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) }, { exact assume a ha, ((irreducible_mk_iff _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) }, simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq end private theorem forall_map_mk_factors_irreducible (x : α) (hx : x ≠ 0) : ∀(a : associates α), a ∈ multiset.map associates.mk (factors x) → irreducible a := begin assume a ha, rcases multiset.mem_map.1 ha with ⟨c, hc, rfl⟩, exact (irreducible_mk_iff c).2 (irreducible_factors hx _ hc) end theorem prod_le_prod_iff_le {p q : multiset (associates α)} (hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) : p.prod ≤ q.prod ↔ p ≤ q := iff.intro begin rintros ⟨⟨c⟩, eq⟩, have : c ≠ 0, from (mt mk_eq_zero_iff_eq_zero.2 $ assume (hc : quot.mk setoid.r c = 0), have (0 : associates α) ∈ q, from prod_eq_zero_iff.1 $ eq ▸ hc.symm ▸ mul_zero _, not_irreducible_zero ((irreducible_mk_iff 0).1 $ hq _ this)), have : associates.mk (factors c).prod = quot.mk setoid.r c, from mk_eq_mk_iff_associated.2 (factors_prod this), refine le_iff_exists_add.2 ⟨(factors c).map associates.mk, unique' hq _ _⟩, { assume x hx, rcases multiset.mem_add.1 hx with h | h, exact hp x h, exact forall_map_mk_factors_irreducible c ‹c ≠ 0› _ h }, { simp [multiset.prod_add, prod_mk, *] at * } end prod_le_prod @[simp] theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} : (↑a + ↑b : factor_set α) = ↑(a + b) := with_top.coe_add lemma factor_set.sup_add_inf_eq_add : ∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b | none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp | a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp | (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from begin rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add, with_top.coe_eq_coe], exact multiset.union_add_inter _ _ end def factors' (a : α) (ha : a ≠ 0) : multiset { a : associates α // irreducible a } := (factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk_iff _).2 ha⟩) (irreducible_factors $ ha) @[simp] theorem map_subtype_val_factors' {a : α} (ha : a ≠ 0) : (factors' a ha).map subtype.val = (factors a).map associates.mk := by simp [factors', multiset.map_pmap, multiset.pmap_eq_map] theorem factors'_cong {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : a ~ᵤ b) : factors' a ha = factors' b hb := have multiset.rel associated (factors a) (factors b), from unique (irreducible_factors ha) (irreducible_factors hb) ((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm), by simpa [(multiset.map_eq_map subtype.val_injective).symm, rel_associated_iff_map_eq_map.symm] def factors (a : associates α) : factor_set α := begin refine (if h : a = 0 then ⊤ else quotient.hrec_on a (λx h, some $ factors' x (mt mk_eq_zero_iff_eq_zero.2 h)) _ h), assume a b hab, apply function.hfunext, { have : a ~ᵤ 0 ↔ b ~ᵤ 0, from iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0), simp [quotient_mk_eq_mk, mk_eq_zero_iff_eq_zero, (associated_zero_iff_eq_zero _).symm, this] }, exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong _ _ hab) end @[simp] theorem factors_0 : (0 : associates α).factors = ⊤ := dif_pos rfl @[simp] theorem factors_mk (a : α) (h : a ≠ 0) : (associates.mk a).factors = factors' a h := dif_neg (mt mk_eq_zero_iff_eq_zero.1 h) def factor_set.prod : factor_set α → associates α | none := 0 | (some s) := (s.map subtype.val).prod @[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl @[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} : (s : factor_set α).prod = (s.map subtype.val).prod := rfl theorem prod_factors : ∀(s : factor_set α), s.prod.factors = s | none := by simp [factor_set.prod]; refl | (some s) := begin unfold factor_set.prod, generalize eq_a : (s.map subtype.val).prod = a, rcases a with ⟨a⟩, rw quot_mk_eq_mk at *, have : (s.map subtype.val).prod ≠ 0, from assume ha, let ⟨⟨a, ha⟩, h, eq⟩ := multiset.mem_map.1 (prod_eq_zero_iff.1 ha) in have irreducible (0 : associates α), from eq ▸ ha, not_irreducible_zero ((irreducible_mk_iff _).1 this), have ha : a ≠ 0, by simp [*] at *, suffices : (unique_factorization_domain.factors a).map associates.mk = s.map subtype.val, { rw [factors_mk a ha], apply congr_arg some _, simpa [(multiset.map_eq_map subtype.val_injective).symm] }, refine unique' (forall_map_mk_factors_irreducible _ ha) (assume a ha, let ⟨⟨x, hx⟩, ha, eq⟩ := multiset.mem_map.1 ha in eq ▸ hx) _, rw [prod_mk, eq_a, mk_eq_mk_iff_associated], exact factors_prod ha end theorem factors_prod (a : associates α) : a.factors.prod = a := quotient.induction_on a $ assume a, decidable.by_cases (assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this]) (assume : associates.mk a ≠ 0, have a ≠ 0, by simp * at *, by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)]) theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b := have a.factors.prod = b.factors.prod, by rw h, by rwa [factors_prod, factors_prod] at this theorem eq_of_prod_eq_prod {a b : factor_set α} (h : a.prod = b.prod) : a = b := have a.prod.factors = b.prod.factors, by rw h, by rwa [prod_factors, prod_factors] at this @[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod | none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp | a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp | (some a) (some b) := show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod, by rw [factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add] theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod | none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_refl _ | a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top | (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h @[simp] theorem factors_mul (a b : associates α) : (a * b).factors = a.factors + b.factors := eq_of_prod_eq_prod $ eq_of_factors_eq_factors $ by rw [prod_add, factors_prod, factors_prod, factors_prod] theorem factors_mono : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors | s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right' bot_le theorem factors_le {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b := iff.intro (assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h, by rwa [factors_prod, factors_prod] at this) factors_mono theorem prod_le {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b := iff.intro (assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h, by rwa [prod_factors, prod_factors] at this) prod_mono instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩ instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩ instance : bounded_lattice (associates α) := { sup := (⊔), inf := (⊓), sup_le := assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)), le_sup_left := assume a b, le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left, le_sup_right := assume a b, le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right, le_inf := assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)), inf_le_left := assume a b, le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)), inf_le_right := assume a b, le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)), .. associates.partial_order, .. associates.lattice.order_top, .. associates.lattice.order_bot } lemma sup_mul_inf (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b := show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b, begin refine eq_of_factors_eq_factors _, rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add] end end associates section open associates unique_factorization_domain lattice /-- `to_gcd_domain` constructs a GCD domain out of a unique factorization domain over a normalization domain. -/ def unique_factorization_domain.to_gcd_domain (α : Type*) [normalization_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] : gcd_domain α := { gcd := λa b, (associates.mk a ⊓ associates.mk b).out, lcm := λa b, (associates.mk a ⊔ associates.mk b).out, gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left, gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right, dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out, by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩, lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp, lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp, gcd_mul_lcm := assume a b, show (associates.mk a ⊓ associates.mk b).out * (associates.mk a ⊔ associates.mk b).out = a * b * norm_unit (a * b), by rw [← out_mk, ← out_mul, mul_comm, sup_mul_inf]; refl, norm_unit_gcd := assume a b, norm_unit_out _, .. ‹normalization_domain α› } end
407b77b8da2f7b4a766e294ba3abbc05e3c751f1
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/occurrences.lean
c0b7d33486e33ded43bb8b2786d687e86e6d1485
[]
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,318
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.logic import Mathlib.Lean3Lib.init.data.repr import Mathlib.Lean3Lib.init.meta.format import Mathlib.Lean3Lib.init.meta.contradiction_tactic import Mathlib.Lean3Lib.init.meta.constructor_tactic import Mathlib.Lean3Lib.init.meta.relation_tactics import Mathlib.Lean3Lib.init.meta.injection_tactic universes l namespace Mathlib /-- We can specify the scope of application of some tactics using the following type. - all : all occurrences of a given term are considered. - pos [1, 3] : only the first and third occurrences of a given term are consiered. - neg [2] : all but the second occurrence of a given term are considered. -/ inductive occurrences where | all : occurrences | pos : List ℕ → occurrences | neg : List ℕ → occurrences def occurrences.contains : occurrences → ℕ → Bool := sorry protected instance occurrences.inhabited : Inhabited occurrences := { default := occurrences.all } def occurrences_repr : occurrences → string := sorry protected instance occurrences.has_repr : has_repr occurrences := has_repr.mk occurrences_repr
2e837afd9a1b92d2690c1dea11ad2ab26b41a434
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/bigop.lean
49e1515dc8a76d36f444e3c2aa6f786ab2e31266
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
4,179
lean
def Seq (α : Type) := List α def BigBody (β α) := α × (β → β → β) × Bool × β def applyBig {α β : Type} (body : BigBody β α) (x : β) : β := let (_, op, b, v) := body; if b then op v x else x def reducebig {α β : Type} (idx : β) (r : Seq α) (body : α → BigBody β α) : β := r.foldr (applyBig ∘ body) idx def bigop := @reducebig def iota : Nat → Nat → List Nat | m, 0 => [] | m, n+1 => m :: iota (m+1) n def index_iota (m n : Nat) := iota m (n - m) class Enumerable (α : Type) := (elems : List α) instance : Enumerable Bool := { elems := [false, true] } instance {α β} [Enumerable α] [Enumerable β]: Enumerable (α × β) := { elems := do a ← Enumerable.elems α; b ← Enumerable.elems β; pure (a, b) } def finElemsAux (n : Nat) : forall (i : Nat), i < n → List (Fin n) | 0, h => [⟨0, h⟩] | i+1, h => ⟨i+1, h⟩ :: finElemsAux i (Nat.ltOfSuccLt h) def finElems : forall (n : Nat), List (Fin n) | 0 => [] | (n+1) => finElemsAux (n+1) n (Nat.ltSuccSelf n) instance {n} : Enumerable (Fin n) := { elems := (finElems n).reverse } instance {n} : HasOfNat (Fin (Nat.succ n)) := ⟨Fin.ofNat⟩ new_frontend -- Declare a new syntax category for "indexing" big operators declare_syntax_cat index syntax term:50 "≤" ident "<" term : index syntax term:50 "≤" ident "<" term "|" term : index syntax ident "<-" term : index syntax ident "<-" term "|" term : index -- Primitive notation for big operators syntax "_big" "[" term "," term "]" "(" index ")" term : term -- We define how to expand `_bigop` with the different kinds of index macro_rules | `(_big [$op, $idx] ($i:ident <- $r | $p) $F) => `(bigop $idx $r (fun $i:ident => ($i:ident, $op, $p, $F))) | `(_big [$op, $idx] ($i:ident <- $r) $F) => `(bigop $idx $r (fun $i:ident => ($i:ident, $op, true, $F))) | `(_big [$op, $idx] ($lower ≤ $i:ident < $upper) $F) => `(bigop $idx (index_iota $lower $upper) (fun $i:ident => ($i:ident, $op, true, $F))) | `(_big [$op, $idx] ($lower ≤ $i:ident < $upper | $p) $F) => `(bigop $idx (index_iota $lower $upper) (fun $i:ident => ($i:ident, $op, $p, $F))) -- Define `Sum` syntax "Sum" "(" index ")" term : term macro_rules `(Sum ($idx:index) $F:term) => `(_big [HasAdd.add, 0] ($idx:index) $F:term) -- We can already use `Sum` with the different kinds of index. #check Sum (i <- [0, 2, 4] | i != 2) i #check Sum (10 ≤ i < 20 | i != 5) i+1 #check Sum (10 ≤ i < 20) i+1 -- Define `Prod` syntax "Prod" "(" index ")" term : term macro_rules `(Prod ($idx:index) $F:term) => `(_big [HasMul.mul, 1] ($idx:index) $F:term) -- The examples above now also work for `Prod` #check Prod (i <- [0, 2, 4] | i != 2) i #check Prod (10 ≤ i < 20 | i != 5) i+1 #check Prod (10 ≤ i < 20) i+1 -- We can extend our grammar for the syntax category `index`. syntax ident "|" term : index syntax ident ":" term : index syntax ident ":" term "|" term : index -- And new rules macro_rules | `(_big [$op, $idx] ($i:ident : $type) $F) => `(bigop $idx (Enumerable.elems $type) (fun $i:ident => ($i:ident, $op, true, $F))) | `(_big [$op, $idx] ($i:ident : $type | $p) $F) => `(bigop $idx (Enumerable.elems $type) (fun $i:ident => ($i:ident, $op, $p, $F))) | `(_big [$op, $idx] ($i:ident | $p) $F) => `(bigop $idx (Enumerable.elems _) (fun $i:ident => ($i:ident, $op, $p, $F))) -- The new syntax is immediately available for all big operators that we have defined def myPred (x : Fin 10) : Bool := true #check Sum (i : Fin 10) i+1 #check Sum (i : Fin 10 | i != 2) i+1 #check Sum (i | myPred i) i+i #check Prod (i : Fin 10) i+1 #check Prod (i : Fin 10 | i != 2) i+1 #check Prod (i | myPred i) i+i -- We can easily create alternative syntax for any big operator. syntax "Σ" index "=>" term : term macro_rules `(Σ $idx:index => $F:term) => `(Prod ($idx:index) $F) #check Σ 10 ≤ i < 20 => i+1 -- Now, we create command for automating the generation of big operators. syntax "def_bigop" str term:max term:max : command macro_rules | `(def_bigop $head:strLit $op $unit) => `(macro $head:strLit "(" idx:index ")" F:term : term => `(_big [$op, $unit] ($$idx:index) $$F)) def_bigop "SUM" Nat.add 0 #check SUM (i <- [0, 1, 2]) i+1
7b2d13515ecdab4784eaed0773b8a5a53b7a7f44
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/clifford_algebra/fold.lean
353aed894e0f35ca266902d150874677a5957bb7
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
9,268
lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import linear_algebra.clifford_algebra.conjugation /-! # Recursive computation rules for the Clifford algebra > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides API for a special case `clifford_algebra.foldr` of the universal property `clifford_algebra.lift` with `A = module.End R N` for some arbitrary module `N`. This specialization resembles the `list.foldr` operation, allowing a bilinear map to be "folded" along the generators. For convenience, this file also provides `clifford_algebra.foldl`, implemented via `clifford_algebra.reverse` ## Main definitions * `clifford_algebra.foldr`: a computation rule for building linear maps out of the clifford algebra starting on the right, analogous to using `list.foldr` on the generators. * `clifford_algebra.foldl`: a computation rule for building linear maps out of the clifford algebra starting on the left, analogous to using `list.foldl` on the generators. ## Main statements * `clifford_algebra.right_induction`: an induction rule that adds generators from the right. * `clifford_algebra.left_induction`: an induction rule that adds generators from the left. -/ universes u1 u2 u3 variables {R M N : Type*} variables [comm_ring R] [add_comm_group M] [add_comm_group N] variables [module R M] [module R N] variables (Q : quadratic_form R M) namespace clifford_algebra section foldr /-- Fold a bilinear map along the generators of a term of the clifford algebra, with the rule given by `foldr Q f hf n (ι Q m * x) = f m (foldr Q f hf n x)`. For example, `foldr f hf n (r • ι R u + ι R v * ι R w) = r • f u n + f v (f w n)`. -/ def foldr (f : M →ₗ[R] N →ₗ[R] N) (hf : ∀ m x, f m (f m x) = Q m • x) : N →ₗ[R] clifford_algebra Q →ₗ[R] N := (clifford_algebra.lift Q ⟨f, λ v, linear_map.ext $ hf v⟩).to_linear_map.flip @[simp] lemma foldr_ι (f : M →ₗ[R] N →ₗ[R] N) (hf) (n : N) (m : M) : foldr Q f hf n (ι Q m) = f m n := linear_map.congr_fun (lift_ι_apply _ _ _) n @[simp] lemma foldr_algebra_map (f : M →ₗ[R] N →ₗ[R] N) (hf) (n : N) (r : R) : foldr Q f hf n (algebra_map R _ r) = r • n := linear_map.congr_fun (alg_hom.commutes _ r) n @[simp] lemma foldr_one (f : M →ₗ[R] N →ₗ[R] N) (hf) (n : N) : foldr Q f hf n 1 = n := linear_map.congr_fun (alg_hom.map_one _) n @[simp] lemma foldr_mul (f : M →ₗ[R] N →ₗ[R] N) (hf) (n : N) (a b : clifford_algebra Q) : foldr Q f hf n (a * b) = foldr Q f hf (foldr Q f hf n b) a := linear_map.congr_fun (alg_hom.map_mul _ _ _) n /-- This lemma demonstrates the origin of the `foldr` name. -/ lemma foldr_prod_map_ι (l : list M) (f : M →ₗ[R] N →ₗ[R] N) (hf) (n : N): foldr Q f hf n (l.map $ ι Q).prod = list.foldr (λ m n, f m n) n l := begin induction l with hd tl ih, { rw [list.map_nil, list.prod_nil, list.foldr_nil, foldr_one] }, { rw [list.map_cons, list.prod_cons, list.foldr_cons, foldr_mul, foldr_ι, ih] }, end end foldr section foldl /-- Fold a bilinear map along the generators of a term of the clifford algebra, with the rule given by `foldl Q f hf n (ι Q m * x) = f m (foldl Q f hf n x)`. For example, `foldl f hf n (r • ι R u + ι R v * ι R w) = r • f u n + f v (f w n)`. -/ def foldl (f : M →ₗ[R] N →ₗ[R] N) (hf : ∀ m x, f m (f m x) = Q m • x) : N →ₗ[R] clifford_algebra Q →ₗ[R] N := linear_map.compl₂ (foldr Q f hf) reverse @[simp] lemma foldl_reverse (f : M →ₗ[R] N →ₗ[R] N) (hf) (n : N) (x : clifford_algebra Q) : foldl Q f hf n (reverse x) = foldr Q f hf n x := fun_like.congr_arg (foldr Q f hf n) $ reverse_reverse _ @[simp] lemma foldr_reverse (f : M →ₗ[R] N →ₗ[R] N) (hf) (n : N) (x : clifford_algebra Q) : foldr Q f hf n (reverse x) = foldl Q f hf n x := rfl @[simp] lemma foldl_ι (f : M →ₗ[R] N →ₗ[R] N) (hf) (n : N) (m : M) : foldl Q f hf n (ι Q m) = f m n := by rw [←foldr_reverse, reverse_ι, foldr_ι] @[simp] lemma foldl_algebra_map (f : M →ₗ[R] N →ₗ[R] N) (hf) (n : N) (r : R) : foldl Q f hf n (algebra_map R _ r) = r • n := by rw [←foldr_reverse, reverse.commutes, foldr_algebra_map] @[simp] lemma foldl_one (f : M →ₗ[R] N →ₗ[R] N) (hf) (n : N) : foldl Q f hf n 1 = n := by rw [←foldr_reverse, reverse.map_one, foldr_one] @[simp] lemma foldl_mul (f : M →ₗ[R] N →ₗ[R] N) (hf) (n : N) (a b : clifford_algebra Q) : foldl Q f hf n (a * b) = foldl Q f hf (foldl Q f hf n a) b := by rw [←foldr_reverse, ←foldr_reverse, ←foldr_reverse, reverse.map_mul, foldr_mul] /-- This lemma demonstrates the origin of the `foldl` name. -/ lemma foldl_prod_map_ι (l : list M) (f : M →ₗ[R] N →ₗ[R] N) (hf) (n : N): foldl Q f hf n (l.map $ ι Q).prod = list.foldl (λ m n, f n m) n l := by rw [←foldr_reverse, reverse_prod_map_ι, ←list.map_reverse, foldr_prod_map_ι, list.foldr_reverse] end foldl lemma right_induction {P : clifford_algebra Q → Prop} (hr : ∀ r : R, P (algebra_map _ _ r)) (h_add : ∀ x y, P x → P y → P (x + y)) (h_ι_mul : ∀ m x, P x → P (x * ι Q m)) : ∀ x, P x := begin /- It would be neat if we could prove this via `foldr` like how we prove `clifford_algebra.induction`, but going via the grading seems easier. -/ intro x, have : x ∈ ⊤ := submodule.mem_top, rw ←supr_ι_range_eq_top at this, apply submodule.supr_induction _ this (λ i x hx, _) _ h_add, { refine submodule.pow_induction_on_right _ hr h_add (λ x px m, _) hx, rintro ⟨m, rfl⟩, exact h_ι_mul _ _ px }, { simpa only [map_zero] using hr 0} end lemma left_induction {P : clifford_algebra Q → Prop} (hr : ∀ r : R, P (algebra_map _ _ r)) (h_add : ∀ x y, P x → P y → P (x + y)) (h_mul_ι : ∀ x m, P x → P (ι Q m * x)) : ∀ x, P x := begin refine reverse_involutive.surjective.forall.2 _, intro x, induction x using clifford_algebra.right_induction with r x y hx hy m x hx, { simpa only [reverse.commutes] using hr r }, { simpa only [map_add] using h_add _ _ hx hy }, { simpa only [reverse.map_mul, reverse_ι] using h_mul_ι _ _ hx }, end /-! ### Versions with extra state -/ /-- Auxiliary definition for `clifford_algebra.foldr'` -/ def foldr'_aux (f : M →ₗ[R] clifford_algebra Q × N →ₗ[R] N) : M →ₗ[R] module.End R (clifford_algebra Q × N) := begin have v_mul := (algebra.lmul R (clifford_algebra Q)).to_linear_map ∘ₗ (ι Q), have l := v_mul.compl₂ (linear_map.fst _ _ N), exact { to_fun := λ m, (l m).prod (f m), map_add' := λ v₂ v₂, linear_map.ext $ λ x, prod.ext (linear_map.congr_fun (l.map_add _ _) x) (linear_map.congr_fun (f.map_add _ _) x), map_smul' := λ c v, linear_map.ext $ λ x, prod.ext (linear_map.congr_fun (l.map_smul _ _) x) (linear_map.congr_fun (f.map_smul _ _) x), }, end lemma foldr'_aux_apply_apply (f : M →ₗ[R] clifford_algebra Q × N →ₗ[R] N) (m : M) (x_fx) : foldr'_aux Q f m x_fx = (ι Q m * x_fx.1, f m x_fx) := rfl lemma foldr'_aux_foldr'_aux (f : M →ₗ[R] clifford_algebra Q × N →ₗ[R] N) (hf : ∀ m x fx, f m (ι Q m * x, f m (x, fx)) = Q m • fx) (v : M) (x_fx) : foldr'_aux Q f v (foldr'_aux Q f v x_fx) = Q v • x_fx := begin cases x_fx with x fx, simp only [foldr'_aux_apply_apply], rw [←mul_assoc, ι_sq_scalar, ← algebra.smul_def, hf, prod.smul_mk], end /-- Fold a bilinear map along the generators of a term of the clifford algebra, with the rule given by `foldr' Q f hf n (ι Q m * x) = f m (x, foldr' Q f hf n x)`. Note this is like `clifford_algebra.foldr`, but with an extra `x` argument. Implement the recursion scheme `F[n0](m * x) = f(m, (x, F[n0](x)))`. -/ def foldr' (f : M →ₗ[R] clifford_algebra Q × N →ₗ[R] N) (hf : ∀ m x fx, f m (ι Q m * x, f m (x, fx)) = Q m • fx) (n : N) : clifford_algebra Q →ₗ[R] N := linear_map.snd _ _ _ ∘ₗ foldr Q (foldr'_aux Q f) (foldr'_aux_foldr'_aux Q _ hf) (1, n) lemma foldr'_algebra_map (f : M →ₗ[R] clifford_algebra Q × N →ₗ[R] N) (hf : ∀ m x fx, f m (ι Q m * x, f m (x, fx)) = Q m • fx) (n r) : foldr' Q f hf n (algebra_map R _ r) = r • n := congr_arg prod.snd (foldr_algebra_map _ _ _ _ _) lemma foldr'_ι (f : M →ₗ[R] clifford_algebra Q × N →ₗ[R] N) (hf : ∀ m x fx, f m (ι Q m * x, f m (x, fx)) = Q m • fx) (n m) : foldr' Q f hf n (ι Q m) = f m (1, n) := congr_arg prod.snd (foldr_ι _ _ _ _ _) lemma foldr'_ι_mul (f : M →ₗ[R] clifford_algebra Q × N →ₗ[R] N) (hf : ∀ m x fx, f m (ι Q m * x, f m (x, fx)) = Q m • fx) (n m) (x) : foldr' Q f hf n (ι Q m * x) = f m (x, foldr' Q f hf n x) := begin dsimp [foldr'], rw [foldr_mul, foldr_ι, foldr'_aux_apply_apply], refine congr_arg (f m) (prod.mk.eta.symm.trans _), congr' 1, induction x using clifford_algebra.left_induction with r x y hx hy m x hx, { simp_rw [foldr_algebra_map, prod.smul_mk, algebra.algebra_map_eq_smul_one] }, { rw [map_add, prod.fst_add, hx, hy] }, { rw [foldr_mul, foldr_ι, foldr'_aux_apply_apply, hx], }, end end clifford_algebra
ee8eada229036fcc532a3681cd586f5de29aefe2
aa2345b30d710f7e75f13157a35845ee6d48c017
/linear_algebra/basis.lean
f668b2b1c05bcd161cd207a44267e0c46dabfe7d
[ "Apache-2.0" ]
permissive
CohenCyril/mathlib
5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe
a12d5a192f5923016752f638d19fc1a51610f163
refs/heads/master
1,586,031,957,957
1,541,432,824,000
1,541,432,824,000
156,246,337
0
0
Apache-2.0
1,541,434,514,000
1,541,434,513,000
null
UTF-8
Lean
false
false
23,630
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 Linear independence and basis sets in a module or vector space. This file is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. We define the following concepts: * `linear_independent s`: states that `s` are linear independent * `linear_independent.repr s b`: choose the linear combination representing `b` on the linear independent vectors `s`. `b` should be in `span b` (uses classical choice) * `is_basis s`: if `s` is a basis, i.e. linear independent and spans the entire space * `is_basis.repr s b`: like `linear_independent.repr` but as a `linear_map` * `is_basis.constr s g`: constructs a `linear_map` by extending `g` from the basis `s` -/ import linear_algebra.lc noncomputable theory open function lattice set submodule local attribute [instance] classical.prop_decidable variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section module variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] variables [module α β] [module α γ] [module α δ] variables {a b : α} {s t : set β} {x y : β} include α /-- Linearly independent set of vectors -/ def linear_independent (s : set β) : Prop := disjoint (lc.supported s) (lc.total β).ker theorem linear_independent_iff : linear_independent s ↔ ∀l ∈ lc.supported s, lc.total β l = 0 → l = 0 := by simp [linear_independent, linear_map.disjoint_ker] theorem linear_independent_iff_total_on : linear_independent s ↔ (lc.total_on s).ker = ⊥ := by rw [lc.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent_empty : linear_independent (∅ : set β) := by simp [linear_independent] lemma linear_independent.mono (h : t ⊆ s) : linear_independent s → linear_independent t := disjoint_mono_left (lc.supported_mono h) lemma linear_independent.unique (hs : linear_independent s) {l₁ l₂ : lc α β} : l₁ ∈ lc.supported s → l₂ ∈ lc.supported s → lc.total β l₁ = lc.total β l₂ → l₁ = l₂ := linear_map.disjoint_ker'.1 hs _ _ lemma zero_not_mem_of_linear_independent (ne : 0 ≠ (1:α)) (hs : linear_independent s) : (0:β) ∉ s := λ h, ne $ eq.symm begin suffices : (finsupp.single 0 1 : lc α β) 0 = 0, {simpa}, rw disjoint_def.1 hs _ (lc.single_mem_supported 1 h), {refl}, {simp} end lemma linear_independent_union {s t : set β} (hs : linear_independent s) (ht : linear_independent t) (hst : disjoint (span s) (span t)) : linear_independent (s ∪ t) := begin rw [linear_independent, disjoint_def, lc.supported_union], intros l h₁ h₂, rw mem_sup at h₁, rcases h₁ with ⟨ls, hls, lt, hlt, rfl⟩, rw [span_eq_map_lc, span_eq_map_lc] at hst, have : lc.total β ls ∈ map (lc.total β) (lc.supported t), { apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hlt)).1, rw [← linear_map.map_add, linear_map.mem_ker.1 h₂], apply zero_mem }, have ls0 := disjoint_def.1 hs _ hls (linear_map.mem_ker.2 $ disjoint_def.1 hst _ (mem_image_of_mem _ hls) this), subst ls0, simp [-linear_map.mem_ker] at this h₂ ⊢, exact disjoint_def.1 ht _ hlt h₂ end lemma linear_independent_of_finite (H : ∀ t ⊆ s, finite t → linear_independent t) : linear_independent s := linear_independent_iff.2 $ λ l hl, linear_independent_iff.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {ι : Type*} {s : ι → set β} (hs : directed (⊆) s) (h : ∀ i, linear_independent (s i)) : linear_independent (⋃ i, s i) := begin by_cases hι : nonempty ι, { refine linear_independent_of_finite (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le hι fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine linear_independent_empty.mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hι ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set β)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent a) : linear_independent (⋃₀ s) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_bUnion_of_directed {ι} {s : set ι} {t : ι → set β} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent (t a)) : linear_independent (⋃a∈s, t a) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_comp _ _ _).2 $ (directed_on_iff_directed _).1 hs) (by simpa using h) section repr variables (hs : linear_independent s) def linear_independent.total_equiv : lc.supported s ≃ₗ span s := linear_equiv.of_bijective (lc.total_on s) (linear_independent_iff_total_on.1 hs) (lc.total_on_range _) def linear_independent.repr : span s →ₗ lc α β := (submodule.subtype _).comp (hs.total_equiv.symm : span s →ₗ lc.supported s) lemma linear_independent.total_repr (x) : lc.total β (hs.repr x) = x := subtype.ext.1 $ hs.total_equiv.right_inv x lemma linear_independent.total_comp_repr : (lc.total β).comp hs.repr = submodule.subtype _ := linear_map.ext $ hs.total_repr lemma linear_independent.repr_ker : hs.repr.ker = ⊥ := by rw [linear_independent.repr, linear_map.ker_comp, ker_subtype, comap_bot, linear_equiv.ker] lemma linear_independent.repr_range : hs.repr.range = lc.supported s := by rw [linear_independent.repr, linear_map.range_comp, linear_equiv.range, map_top, range_subtype] lemma linear_independent.repr_eq {l : lc α β} (h : l ∈ lc.supported s) {x} (eq : lc.total β l = ↑x) : hs.repr x = l := by rw ← (subtype.eq' eq : (lc.total_on s : lc.supported s →ₗ span s) ⟨l, h⟩ = x); exact subtype.ext.1 (hs.total_equiv.left_inv ⟨l, h⟩) lemma linear_independent.repr_eq_single (x) (hx : ↑x ∈ s) : hs.repr x = finsupp.single x 1 := hs.repr_eq (lc.single_mem_supported _ hx) (by simp) lemma linear_independent.repr_supported (x) : hs.repr x ∈ lc.supported s := ((hs.total_equiv.symm : span s →ₗ lc.supported s) x).2 lemma linear_independent.repr_eq_repr_of_subset (h : t ⊆ s) (x y) (e : (↑x:β) = ↑y) : (hs.mono h).repr x = hs.repr y := eq.symm $ hs.repr_eq (lc.supported_mono h $ (hs.mono h).repr_supported _) (by rw [← e, (hs.mono h).total_repr]). lemma linear_independent_iff_not_smul_mem_span : linear_independent s ↔ (∀ (x ∈ s) (a : α), a • x ∈ span (s \ {x}) → a = 0) := ⟨λ hs x hx a ha, begin rw [span_eq_map_lc, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, have := (lc.supported s).sub_mem (lc.supported_mono (diff_subset _ _) hl) (lc.single_mem_supported a hx), rw [sub_eq_zero.1 (linear_independent_iff.1 hs _ this $ by simp [e])] at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _) end, λ H, linear_independent_iff.2 $ λ l ls l0, begin ext x, simp, by_contra hn, have xs : x ∈ s := ls (finsupp.mem_support_iff.2 hn), refine hn (H _ xs _ _), refine mem_span_iff_lc.2 ⟨finsupp.single x (l x) - l, _, _⟩, { have : finsupp.single x (l x) - l ∈ lc.supported s := sub_mem _ (lc.single_mem_supported _ xs) ls, refine λ y hy, ⟨this hy, λ e, _⟩, simp at e hy, apply hy, simp [e] }, { simp [l0] } end⟩ end repr lemma eq_of_linear_independent_of_span (nz : (1 : α) ≠ 0) (hs : linear_independent s) (h : t ⊆ s) (hst : s ⊆ span t) : s = t := begin refine subset.antisymm (λ b hb, _) h, have : (hs.mono h).repr ⟨b, hst hb⟩ = finsupp.single b 1 := (hs.repr_eq_repr_of_subset h ⟨b, hst hb⟩ ⟨b, subset_span hb⟩ rfl).trans (hs.repr_eq_single ⟨b, _⟩ hb), have ss := (hs.mono h).repr_supported _, rw this at ss, exact ss (by simp [nz]), end section variables {f : β →ₗ γ} (hs : linear_independent (f '' s)) (hf_inj : ∀ a b ∈ s, f a = f b → a = b) include hs hf_inj open linear_map lemma linear_independent.supported_disjoint_ker : disjoint (lc.supported s) (ker (f.comp (lc.total β))) := begin refine le_trans (le_inf inf_le_left _) (lc.map_disjoint_ker f hf_inj), rw [linear_independent, disjoint_iff, ← lc.map_supported f] at hs, rw [← lc.map_total, le_ker_iff_map], refine eq_bot_mono (le_inf (map_mono inf_le_left) _) hs, rw [map_le_iff_le_comap, ← ker_comp], exact inf_le_right end lemma linear_independent.of_image : linear_independent s := disjoint_mono_right (ker_le_ker_comp _ _) (hs.supported_disjoint_ker hf_inj) lemma linear_independent.disjoint_ker : disjoint (span s) f.ker := by rw [span_eq_map_lc, disjoint_iff, map_inf_eq_map_inf_comap, ← ker_comp, disjoint_iff.1 (hs.supported_disjoint_ker hf_inj), map_bot] end lemma linear_independent.inj_span_iff_inj {s : set β} {f : β →ₗ γ} (hfs : linear_independent (f '' s)) : disjoint (span s) f.ker ↔ (∀a b ∈ s, f a = f b → a = b) := ⟨linear_map.inj_of_disjoint_ker subset_span, hfs.disjoint_ker⟩ open linear_map lemma linear_independent.image {s : set β} {f : β →ₗ γ} (hs : linear_independent s) (hf_inj : disjoint (span s) f.ker) : linear_independent (f '' s) := by rw [disjoint, span_eq_map_lc, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot] at hf_inj; rw [linear_independent, disjoint, ← lc.map_supported f, map_inf_eq_map_inf_comap, map_le_iff_le_comap, ← ker_comp, lc.map_total, ker_comp]; exact le_trans (le_inf inf_le_left hf_inj) (le_trans hs bot_le) lemma linear_map.linear_independent_image_iff {s : set β} {f : β →ₗ γ} (hf_inj : disjoint (span s) f.ker) : linear_independent (f '' s) ↔ linear_independent s := ⟨λ hs, hs.of_image (linear_map.inj_of_disjoint_ker subset_span hf_inj), λ hs, hs.image hf_inj⟩ lemma linear_independent_inl_union_inr {s : set β} {t : set γ} (hs : linear_independent s) (ht : linear_independent t) : linear_independent (inl β γ '' s ∪ inr β γ '' t) := linear_independent_union (hs.image $ by simp) (ht.image $ by simp) $ by rw [span_image, span_image]; simp [disjoint_iff, prod_inf_prod] /-- A set of vectors is a basis if it is linearly independent and all vectors are in the span -/ def is_basis (s : set β) := linear_independent s ∧ span s = ⊤ section is_basis variables (hs : is_basis s) lemma is_basis.mem_span (hs : is_basis s) : ∀ x, x ∈ span s := eq_top_iff'.1 hs.2 def is_basis.repr : β →ₗ lc α β := (hs.1.repr).comp (linear_map.id.cod_restrict _ hs.mem_span) lemma is_basis.total_repr (x) : lc.total β (hs.repr x) = x := hs.1.total_repr ⟨x, _⟩ lemma is_basis.total_comp_repr : (lc.total β).comp hs.repr = linear_map.id := linear_map.ext hs.total_repr lemma is_basis.repr_ker : hs.repr.ker = ⊥ := linear_map.ker_eq_bot.2 $ injective_of_left_inverse hs.total_repr lemma is_basis.repr_range : hs.repr.range = lc.supported s := by rw [is_basis.repr, linear_map.range, submodule.map_comp, linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hs.1.repr_range] lemma is_basis.repr_supported (x) : hs.repr x ∈ lc.supported s := hs.1.repr_supported ⟨x, _⟩ lemma is_basis.repr_eq_single {x} : x ∈ s → hs.repr x = finsupp.single x 1 := hs.1.repr_eq_single ⟨x, _⟩ /-- Construct a linear map given the value at the basis. -/ def is_basis.constr (f : β → γ) : β →ₗ γ := (lc.total γ).comp $ (lc.map f).comp hs.repr theorem is_basis.constr_apply (f : β → γ) (x : β) : (hs.constr f : β → γ) x = (hs.repr x).sum (λb a, a • f b) := by dsimp [is_basis.constr]; rw [lc.total_apply, finsupp.sum_map_domain_index]; simp [add_smul] lemma is_basis.ext {f g : β →ₗ γ} (hs : is_basis s) (h : ∀x∈s, f x = g x) : f = g := linear_map.ext $ λ x, linear_eq_on h (hs.mem_span x) lemma constr_congr {f g : β → γ} {x : β} (hs : is_basis s) (h : ∀x∈s, f x = g x) : hs.constr f = hs.constr g := by ext y; simp [is_basis.constr_apply]; exact finset.sum_congr rfl (λ x hx, by simp [h x (hs.repr_supported _ hx)]) lemma constr_basis {f : β → γ} {b : β} (hs : is_basis s) (hb : b ∈ s) : (hs.constr f : β → γ) b = f b := by simp [is_basis.constr_apply, hs.repr_eq_single hb, finsupp.sum_single_index] lemma constr_eq {g : β → γ} {f : β →ₗ γ} (hs : is_basis s) (h : ∀x∈s, g x = f x) : hs.constr g = f := hs.ext $ λ x hx, (constr_basis hs hx).trans (h _ hx) lemma constr_self (f : β →ₗ γ) : hs.constr f = f := constr_eq hs $ λ x hx, rfl lemma constr_zero (hs : is_basis s) : hs.constr (λb, (0 : γ)) = 0 := constr_eq hs $ λ x hx, rfl lemma constr_add {g f : β → γ} (hs : is_basis s) : hs.constr (λb, f b + g b) = hs.constr f + hs.constr g := constr_eq hs $ by simp [constr_basis hs] {contextual := tt} lemma constr_neg {f : β → γ} (hs : is_basis s) : hs.constr (λb, - f b) = - hs.constr f := constr_eq hs $ by simp [constr_basis hs] {contextual := tt} lemma constr_sub {g f : β → γ} (hs : is_basis s) : hs.constr (λb, f b - g b) = hs.constr f - hs.constr g := by simp [constr_add, constr_neg] -- this only works on functions if `α` is a commutative ring lemma constr_smul {α β γ} [comm_ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] {f : β → γ} {a : α} {s : set β} (hs : is_basis s) {b : β} : hs.constr (λb, a • f b) = a • hs.constr f := constr_eq hs $ by simp [constr_basis hs] {contextual := tt} lemma constr_range (hs : is_basis s) {f : β → γ} : (hs.constr f).range = span (f '' s) := by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range, lc.map_supported, span_eq_map_lc] def module_equiv_lc (hs : is_basis s) : β ≃ₗ lc.supported s := (hs.1.total_equiv.trans (linear_equiv.of_top _ hs.2)).symm def equiv_of_is_basis {s : set β} {t : set γ} {f : β → γ} {g : γ → β} (hs : is_basis s) (ht : is_basis t) (hf : ∀b∈s, f b ∈ t) (hg : ∀c∈t, g c ∈ s) (hgf : ∀b∈s, g (f b) = b) (hfg : ∀c∈t, f (g c) = c) : β ≃ₗ γ := { inv_fun := ht.constr g, left_inv := have (ht.constr g).comp (hs.constr f) = linear_map.id, from hs.ext $ by simp [constr_basis, hs, ht, hf, hgf, (∘)] {contextual := tt}, λ x, congr_arg (λ h:β →ₗ β, h x) this, right_inv := have (hs.constr f).comp (ht.constr g) = linear_map.id, from ht.ext $ by simp [constr_basis, hs, ht, hg, hfg, (∘)] {contextual := tt}, λ y, congr_arg (λ h:γ →ₗ γ, h y) this, ..hs.constr f } lemma is_basis_inl_union_inr {s : set β} {t : set γ} (hs : is_basis s) (ht : is_basis t) : is_basis (inl β γ '' s ∪ inr β γ '' t) := ⟨linear_independent_inl_union_inr hs.1 ht.1, by rw [span_union, span_image, span_image]; simp [hs.2, ht.2]⟩ end is_basis lemma linear_equiv.is_basis {s : set β} (hs : is_basis s) (f : β ≃ₗ γ) : is_basis (f '' s) := show is_basis ((f : β →ₗ γ) '' s), from ⟨hs.1.image $ by simp, by rw [span_image, hs.2, map_top, f.range]⟩ end module section vector_space variables [discrete_field α] [add_comm_group β] [add_comm_group γ] [vector_space α β] [vector_space α γ] {s t : set β} {x y z : β} include α open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type classs) -/ lemma mem_span_insert_exchange : x ∈ span (insert y s) → x ∉ span s → y ∈ span (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end lemma linear_independent_iff_not_mem_span : linear_independent s ↔ (∀x∈s, x ∉ span (s \ {x})) := linear_independent_iff_not_smul_mem_span.trans ⟨λ H x xs hx, one_ne_zero (H x xs 1 $ by simpa), λ H x xs a hx, classical.by_contradiction $ λ a0, H x xs ((smul_mem_iff _ a0).1 hx)⟩ lemma linear_independent_singleton {x : β} (hx : x ≠ 0) : linear_independent ({x} : set β) := linear_independent_iff_not_mem_span.mpr $ by simp [hx] {contextual := tt} lemma disjoint_span_singleton {p : submodule α β} {x : β} (x0 : x ≠ 0) : disjoint p (span {x}) ↔ x ∉ p := ⟨λ H xp, x0 (disjoint_def.1 H _ xp (singleton_subset_iff.1 subset_span:_)), begin simp [disjoint_def, mem_span_singleton], rintro xp y yp a rfl, by_cases a0 : a = 0, {simp [a0]}, exact xp.elim ((smul_mem_iff p a0).1 yp), end⟩ lemma linear_independent.insert (hs : linear_independent s) (hx : x ∉ span s) : linear_independent (insert x s) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, exact linear_independent_union hs (linear_independent_singleton x0) ((disjoint_span_singleton x0).2 hx) end lemma exists_linear_independent (hs : linear_independent s) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span b ∧ linear_independent b := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent b} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end lemma exists_subset_is_basis (hs : linear_independent s) : ∃b, s ⊆ b ∧ is_basis b := let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨b, hx, hb₃, eq_top_iff.2 hb₂⟩ variable (β) lemma exists_is_basis : ∃b : set β, is_basis b := let ⟨b, _, hb⟩ := exists_subset_is_basis linear_independent_empty in ⟨b, hb⟩ variable {β} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset β} (hs : linear_independent s) (hst : s ⊆ (span ↑t : submodule α β)) : ∃t':finset β, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset β), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span ↑(s' ∪ t) : submodule α β) → ∃t':finset β, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span one_ne_zero hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span ↑(s' ∪ t) : submodule α β), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span ↑(s' ∪ t) : submodule α β), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span ↑(insert b₂ s' ∪ t) : submodule α β), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set β), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span (insert b₁ (insert b₂ ↑(s' ∪ t) : set β)), from span_mono this (hss' hb₃), have s ⊆ (span (insert b₁ ↑(s' ∪ t)) : submodule α β), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by rw [finset.union_comm] at hb₂t'; simp [eq, hb₂t', hb₁t, hb₁s']⟩)), have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, from finset.ext.mpr $ assume x, by by_cases x ∈ s; simp *, let ⟨u, h₁, h₂, h⟩ := this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq]) in ⟨u, subset.trans h₁ (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h₂, by rwa [eq] at h⟩ lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent s) (hst : s ⊆ span t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span ↑(ht.to_finset) : submodule α β), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from finite_subset u.finite_to_set hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ lemma exists_left_inverse_linear_map_of_injective {f : β →ₗ γ} (hf_inj : f.ker = ⊥) : ∃g:γ →ₗ β, g.comp f = linear_map.id := begin rcases exists_is_basis β with ⟨B, hB⟩, have : linear_independent (f '' B) := hB.1.image (by simp [hf_inj]), rcases exists_subset_is_basis this with ⟨C, BC, hC⟩, haveI : inhabited β := ⟨0⟩, refine ⟨hC.constr (inv_fun f), hB.ext $ λ b bB, _⟩, rw image_subset_iff at BC, simp [constr_basis hC (BC bB)], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _ end lemma exists_right_inverse_linear_map_of_surjective {f : β →ₗ γ} (hf_surj : f.range = ⊤) : ∃g:γ →ₗ β, f.comp g = linear_map.id := begin rcases exists_is_basis γ with ⟨C, hC⟩, haveI : inhabited β := ⟨0⟩, refine ⟨hC.constr (inv_fun f), hC.ext $ λ c cC, _⟩, simp [constr_basis hC cC], exact right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) _ end open submodule linear_map theorem quotient_prod_linear_equiv (p : submodule α β) : nonempty ((p.quotient × p) ≃ₗ β) := begin rcases exists_right_inverse_linear_map_of_surjective p.range_mkq with ⟨f, hf⟩, have mkf : ∀ x, submodule.quotient.mk (f x) = x := linear_map.ext_iff.1 hf, have fp : ∀ x, x - f (p.mkq x) ∈ p := λ x, (submodule.quotient.eq p).1 (mkf (p.mkq x)).symm, refine ⟨linear_equiv.of_linear (f.copair p.subtype) (p.mkq.pair (cod_restrict p (linear_map.id - f.comp p.mkq) fp)) (by ext; simp) _⟩, ext ⟨⟨x⟩, y, hy⟩; simp, { apply (submodule.quotient.eq p).2, simpa using sub_mem p hy (fp x) }, { refine subtype.coe_ext.2 _, simp [mkf, (submodule.quotient.mk_eq_zero p).2 hy] } end. end vector_space
4696cdc3bb6b89a6aa36b398fa89d10cf273055e
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/topology/continuous_on.lean
25ae8cdd6c613b648cad759294cf1c592593f1b5
[ "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
24,949
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.constructions /-! # Neighborhoods and continuity relative to a subset This file defines relative versions `nhds_within` of `nhds` `continuous_on` of `continuous` `continuous_within_at` of `continuous_at` and proves their basic properties, including the relationships between these restricted notions and the corresponding notions for the subtype equipped with the subspace topology. -/ open set filter open_locale topological_space filter variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] /-- The "neighborhood within" filter. Elements of `nhds_within a s` are sets containing the intersection of `s` and a neighborhood of `a`. -/ def nhds_within (a : α) (s : set α) : filter α := 𝓝 a ⊓ 𝓟 s theorem nhds_within_eq (a : α) (s : set α) : nhds_within a s = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, 𝓟 (t ∩ s) := have set.univ ∈ {s : set α | a ∈ s ∧ is_open s}, from ⟨set.mem_univ _, is_open_univ⟩, begin rw [nhds_within, nhds, binfi_inf]; try { exact this }, simp only [inf_principal] end theorem nhds_within_univ (a : α) : nhds_within a set.univ = 𝓝 a := by rw [nhds_within, principal_univ, inf_top_eq] lemma nhds_within_has_basis {p : β → Prop} {s : β → set α} {a : α} (h : (𝓝 a).has_basis p s) (t : set α) : (nhds_within a t).has_basis p (λ i, s i ∩ t) := h.inf_principal t lemma nhds_within_basis_open (a : α) (t : set α) : (nhds_within a t).has_basis (λ u, a ∈ u ∧ is_open u) (λ u, u ∩ t) := nhds_within_has_basis (nhds_basis_opens a) t theorem mem_nhds_within {t : set α} {a : α} {s : set α} : t ∈ nhds_within a s ↔ ∃ u, is_open u ∧ a ∈ u ∧ u ∩ s ⊆ t := by simpa only [exists_prop, and_assoc, and_comm] using (nhds_within_basis_open a s).mem_iff lemma mem_nhds_within_iff_exists_mem_nhds_inter {t : set α} {a : α} {s : set α} : t ∈ nhds_within a s ↔ ∃ u ∈ 𝓝 a, u ∩ s ⊆ t := (nhds_within_has_basis (𝓝 a).basis_sets s).mem_iff lemma nhds_of_nhds_within_of_nhds {s t : set α} {a : α} (h1 : s ∈ 𝓝 a) (h2 : t ∈ nhds_within a s) : (t ∈ 𝓝 a) := begin rcases mem_nhds_within_iff_exists_mem_nhds_inter.mp h2 with ⟨_, Hw, hw⟩, exact (nhds a).sets_of_superset ((nhds a).inter_sets Hw h1) hw, end lemma mem_nhds_within_of_mem_nhds {s t : set α} {a : α} (h : s ∈ 𝓝 a) : s ∈ nhds_within a t := mem_inf_sets_of_left h theorem self_mem_nhds_within {a : α} {s : set α} : s ∈ nhds_within a s := mem_inf_sets_of_right (mem_principal_self s) theorem inter_mem_nhds_within (s : set α) {t : set α} {a : α} (h : t ∈ 𝓝 a) : s ∩ t ∈ nhds_within a s := inter_mem_sets (mem_inf_sets_of_right (mem_principal_self s)) (mem_inf_sets_of_left h) theorem nhds_within_mono (a : α) {s t : set α} (h : s ⊆ t) : nhds_within a s ≤ nhds_within a t := inf_le_inf_left _ (principal_mono.mpr h) lemma mem_of_mem_nhds_within {a : α} {s t : set α} (ha : a ∈ s) (ht : t ∈ nhds_within a s) : a ∈ t := let ⟨u, hu, H⟩ := mem_nhds_within.1 ht in H.2 ⟨H.1, ha⟩ lemma filter.eventually.self_of_nhds_within {p : α → Prop} {s : set α} {x : α} (h : ∀ᶠ y in nhds_within x s, p y) (hx : x ∈ s) : p x := mem_of_mem_nhds_within hx h theorem nhds_within_restrict'' {a : α} (s : set α) {t : set α} (h : t ∈ nhds_within a s) : nhds_within a s = nhds_within a (s ∩ t) := le_antisymm (le_inf inf_le_left (le_principal_iff.mpr (inter_mem_sets self_mem_nhds_within h))) (inf_le_inf_left _ (principal_mono.mpr (set.inter_subset_left _ _))) theorem nhds_within_restrict' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝 a) : nhds_within a s = nhds_within a (s ∩ t) := nhds_within_restrict'' s $ mem_inf_sets_of_left h theorem nhds_within_restrict {a : α} (s : set α) {t : set α} (h₀ : a ∈ t) (h₁ : is_open t) : nhds_within a s = nhds_within a (s ∩ t) := nhds_within_restrict' s (mem_nhds_sets h₁ h₀) theorem nhds_within_le_of_mem {a : α} {s t : set α} (h : s ∈ nhds_within a t) : nhds_within a t ≤ nhds_within a s := begin rcases mem_nhds_within.1 h with ⟨u, u_open, au, uts⟩, have : nhds_within a t = nhds_within a (t ∩ u) := nhds_within_restrict _ au u_open, rw [this, inter_comm], exact nhds_within_mono _ uts end theorem nhds_within_eq_nhds_within {a : α} {s t u : set α} (h₀ : a ∈ s) (h₁ : is_open s) (h₂ : t ∩ s = u ∩ s) : nhds_within a t = nhds_within a u := by rw [nhds_within_restrict t h₀ h₁, nhds_within_restrict u h₀ h₁, h₂] theorem nhds_within_eq_of_open {a : α} {s : set α} (h₀ : a ∈ s) (h₁ : is_open s) : nhds_within a s = 𝓝 a := by rw [←nhds_within_univ]; apply nhds_within_eq_nhds_within h₀ h₁; rw [set.univ_inter, set.inter_self] @[simp] theorem nhds_within_empty (a : α) : nhds_within a {} = ⊥ := by rw [nhds_within, principal_empty, inf_bot_eq] theorem nhds_within_union (a : α) (s t : set α) : nhds_within a (s ∪ t) = nhds_within a s ⊔ nhds_within a t := by unfold nhds_within; rw [←inf_sup_left, sup_principal] theorem nhds_within_inter (a : α) (s t : set α) : nhds_within a (s ∩ t) = nhds_within a s ⊓ nhds_within a t := by unfold nhds_within; rw [inf_left_comm, inf_assoc, inf_principal, ←inf_assoc, inf_idem] theorem nhds_within_inter' (a : α) (s t : set α) : nhds_within a (s ∩ t) = (nhds_within a s) ⊓ 𝓟 t := by { unfold nhds_within, rw [←inf_principal, inf_assoc] } lemma nhds_within_prod_eq {α : Type*} [topological_space α] {β : Type*} [topological_space β] (a : α) (b : β) (s : set α) (t : set β) : nhds_within (a, b) (s.prod t) = (nhds_within a s).prod (nhds_within b t) := by { unfold nhds_within, rw [nhds_prod_eq, ←filter.prod_inf_prod, filter.prod_principal_principal] } theorem tendsto_if_nhds_within {f g : α → β} {p : α → Prop} [decidable_pred p] {a : α} {s : set α} {l : filter β} (h₀ : tendsto f (nhds_within a (s ∩ p)) l) (h₁ : tendsto g (nhds_within a (s ∩ {x | ¬ p x})) l) : tendsto (λ x, if p x then f x else g x) (nhds_within a s) l := by apply tendsto_if; rw [←nhds_within_inter']; assumption lemma map_nhds_within (f : α → β) (a : α) (s : set α) : map f (nhds_within a s) = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, 𝓟 (set.image f (t ∩ s)) := ((nhds_within_basis_open a s).map f).eq_binfi theorem tendsto_nhds_within_mono_left {f : α → β} {a : α} {s t : set α} {l : filter β} (hst : s ⊆ t) (h : tendsto f (nhds_within a t) l) : tendsto f (nhds_within a s) l := tendsto_le_left (nhds_within_mono a hst) h theorem tendsto_nhds_within_mono_right {f : β → α} {l : filter β} {a : α} {s t : set α} (hst : s ⊆ t) (h : tendsto f l (nhds_within a s)) : tendsto f l (nhds_within a t) := tendsto_le_right (nhds_within_mono a hst) h theorem tendsto_nhds_within_of_tendsto_nhds {f : α → β} {a : α} {s : set α} {l : filter β} (h : tendsto f (𝓝 a) l) : tendsto f (nhds_within a s) l := by rw [←nhds_within_univ] at h; exact tendsto_nhds_within_mono_left (set.subset_univ _) h theorem principal_subtype {α : Type*} (s : set α) (t : set {x // x ∈ s}) : 𝓟 t = comap coe (𝓟 ((coe : s → α) '' t)) := by rw comap_principal; rw set.preimage_image_eq; apply subtype.coe_injective lemma mem_closure_iff_nhds_within_ne_bot {s : set α} {x : α} : x ∈ closure s ↔ nhds_within x s ≠ ⊥ := mem_closure_iff_nhds.trans (nhds_within_has_basis (𝓝 x).basis_sets s).forall_nonempty_iff_ne_bot lemma nhds_within_ne_bot_of_mem {s : set α} {x : α} (hx : x ∈ s) : nhds_within x s ≠ ⊥ := mem_closure_iff_nhds_within_ne_bot.1 $ subset_closure hx lemma is_closed.mem_of_nhds_within_ne_bot {s : set α} (hs : is_closed s) {x : α} (hx : nhds_within x s ≠ ⊥) : x ∈ s := by simpa only [hs.closure_eq] using mem_closure_iff_nhds_within_ne_bot.2 hx /- nhds_within and subtypes -/ theorem mem_nhds_within_subtype (s : set α) (a : {x // x ∈ s}) (t u : set {x // x ∈ s}) : t ∈ nhds_within a u ↔ t ∈ comap (coe : s → α) (nhds_within a (coe '' u)) := by rw [nhds_within, nhds_subtype, principal_subtype, ←comap_inf, ←nhds_within] theorem nhds_within_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : nhds_within a t = comap (coe : s → α) (nhds_within a (coe '' t)) := filter_eq $ by ext u; rw mem_nhds_within_subtype theorem nhds_within_eq_map_subtype_coe {s : set α} {a : α} (h : a ∈ s) : nhds_within a s = map (coe : s → α) (𝓝 ⟨a, h⟩) := have h₀ : s ∈ nhds_within a s, by { rw [mem_nhds_within], existsi set.univ, simp [set.diff_eq] }, have h₁ : ∀ y ∈ s, ∃ x : s, ↑x = y, from λ y h, ⟨⟨y, h⟩, rfl⟩, begin rw [←nhds_within_univ, nhds_within_subtype, subtype.coe_image_univ], exact (map_comap_of_surjective' h₀ h₁).symm, end theorem tendsto_nhds_within_iff_subtype {s : set α} {a : α} (h : a ∈ s) (f : α → β) (l : filter β) : tendsto f (nhds_within a s) l ↔ tendsto (s.restrict f) (𝓝 ⟨a, h⟩) l := by { simp only [tendsto, nhds_within_eq_map_subtype_coe h, filter.map_map], refl } variables [topological_space β] [topological_space γ] [topological_space δ] /-- A function between topological spaces is continuous at a point `x₀` within a subset `s` if `f x` tends to `f x₀` when `x` tends to `x₀` while staying within `s`. -/ def continuous_within_at (f : α → β) (s : set α) (x : α) : Prop := tendsto f (nhds_within x s) (𝓝 (f x)) /-- If a function is continuous within `s` at `x`, then it tends to `f x` within `s` by definition. We register this fact for use with the dot notation, especially to use `tendsto.comp` as `continuous_within_at.comp` will have a different meaning. -/ lemma continuous_within_at.tendsto {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) : tendsto f (nhds_within x s) (𝓝 (f x)) := h /-- A function between topological spaces is continuous on a subset `s` when it's continuous at every point of `s` within `s`. -/ def continuous_on (f : α → β) (s : set α) : Prop := ∀ x ∈ s, continuous_within_at f s x lemma continuous_on.continuous_within_at {f : α → β} {s : set α} {x : α} (hf : continuous_on f s) (hx : x ∈ s) : continuous_within_at f s x := hf x hx theorem continuous_within_at_univ (f : α → β) (x : α) : continuous_within_at f set.univ x ↔ continuous_at f x := by rw [continuous_at, continuous_within_at, nhds_within_univ] theorem continuous_within_at_iff_continuous_at_restrict (f : α → β) {x : α} {s : set α} (h : x ∈ s) : continuous_within_at f s x ↔ continuous_at (s.restrict f) ⟨x, h⟩ := tendsto_nhds_within_iff_subtype h f _ theorem continuous_within_at.tendsto_nhds_within_image {f : α → β} {x : α} {s : set α} (h : continuous_within_at f s x) : tendsto f (nhds_within x s) (nhds_within (f x) (f '' s)) := tendsto_inf.2 ⟨h, tendsto_principal.2 $ mem_inf_sets_of_right $ mem_principal_sets.2 $ λ x, mem_image_of_mem _⟩ lemma continuous_within_at.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β} {x : α} {y : β} (hf : continuous_within_at f s x) (hg : continuous_within_at g t y) : continuous_within_at (prod.map f g) (s.prod t) (x, y) := begin unfold continuous_within_at at *, rw [nhds_within_prod_eq, prod.map, nhds_prod_eq], exact hf.prod_map hg, end theorem continuous_on_iff {f : α → β} {s : set α} : continuous_on f s ↔ ∀ x ∈ s, ∀ t : set β, is_open t → f x ∈ t → ∃ u, is_open u ∧ x ∈ u ∧ u ∩ s ⊆ f ⁻¹' t := by simp only [continuous_on, continuous_within_at, tendsto_nhds, mem_nhds_within] theorem continuous_on_iff_continuous_restrict {f : α → β} {s : set α} : continuous_on f s ↔ continuous (s.restrict f) := begin rw [continuous_on, continuous_iff_continuous_at], split, { rintros h ⟨x, xs⟩, exact (continuous_within_at_iff_continuous_at_restrict f xs).mp (h x xs) }, intros h x xs, exact (continuous_within_at_iff_continuous_at_restrict f xs).mpr (h ⟨x, xs⟩) end theorem continuous_on_iff' {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_open t → ∃ u, is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_open (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_open_induced_iff, set.restrict_eq, set.preimage_comp], simp only [subtype.preimage_coe_eq_preimage_coe_iff], split; { rintros ⟨u, ou, useq⟩, exact ⟨u, ou, useq.symm⟩ } end, by rw [continuous_on_iff_continuous_restrict, continuous]; simp only [this] theorem continuous_on_iff_is_closed {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_closed t → ∃ u, is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_closed (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_closed_induced_iff, set.restrict_eq, set.preimage_comp], simp only [subtype.preimage_coe_eq_preimage_coe_iff] end, by rw [continuous_on_iff_continuous_restrict, continuous_iff_is_closed]; simp only [this] lemma continuous_on.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β} (hf : continuous_on f s) (hg : continuous_on g t) : continuous_on (prod.map f g) (s.prod t) := λ ⟨x, y⟩ ⟨hx, hy⟩, continuous_within_at.prod_map (hf x hx) (hg y hy) lemma continuous_on_empty (f : α → β) : continuous_on f ∅ := λ x, false.elim theorem nhds_within_le_comap {x : α} {s : set α} {f : α → β} (ctsf : continuous_within_at f s x) : nhds_within x s ≤ comap f (nhds_within (f x) (f '' s)) := map_le_iff_le_comap.1 ctsf.tendsto_nhds_within_image theorem continuous_within_at_iff_ptendsto_res (f : α → β) {x : α} {s : set α} : continuous_within_at f s x ↔ ptendsto (pfun.res f s) (𝓝 x) (𝓝 (f x)) := tendsto_iff_ptendsto _ _ _ _ lemma continuous_iff_continuous_on_univ {f : α → β} : continuous f ↔ continuous_on f univ := by simp [continuous_iff_continuous_at, continuous_on, continuous_at, continuous_within_at, nhds_within_univ] lemma continuous_within_at.mono {f : α → β} {s t : set α} {x : α} (h : continuous_within_at f t x) (hs : s ⊆ t) : continuous_within_at f s x := tendsto_le_left (nhds_within_mono x hs) h lemma continuous_within_at_inter' {f : α → β} {s t : set α} {x : α} (h : t ∈ nhds_within x s) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict'' s h] lemma continuous_within_at_inter {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝 x) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict' s h] lemma continuous_within_at.union {f : α → β} {s t : set α} {x : α} (hs : continuous_within_at f s x) (ht : continuous_within_at f t x) : continuous_within_at f (s ∪ t) x := by simp only [continuous_within_at, nhds_within_union, tendsto, map_sup, sup_le_iff.2 ⟨hs, ht⟩] lemma continuous_within_at.mem_closure_image {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := mem_closure_of_tendsto (mem_closure_iff_nhds_within_ne_bot.1 hx) h $ mem_sets_of_superset self_mem_nhds_within (subset_preimage_image f s) lemma continuous_within_at.mem_closure {f : α → β} {s : set α} {x : α} {A : set β} (h : continuous_within_at f s x) (hx : x ∈ closure s) (hA : s ⊆ f⁻¹' A) : f x ∈ closure A := closure_mono (image_subset_iff.2 hA) (h.mem_closure_image hx) lemma continuous_within_at.image_closure {f : α → β} {s : set α} (hf : ∀ x ∈ closure s, continuous_within_at f s x) : f '' (closure s) ⊆ closure (f '' s) := begin rintros _ ⟨x, hx, rfl⟩, exact (hf x hx).mem_closure_image hx end theorem is_open_map.continuous_on_image_of_left_inv_on {f : α → β} {s : set α} (h : is_open_map (s.restrict f)) {finv : β → α} (hleft : left_inv_on finv f s) : continuous_on finv (f '' s) := begin rintros _ ⟨x, xs, rfl⟩ t ht, rw [hleft xs] at ht, replace h := h.nhds_le ⟨x, xs⟩, apply mem_nhds_within_of_mem_nhds, apply h, erw [map_compose.symm, function.comp, mem_map, ← nhds_within_eq_map_subtype_coe], apply mem_sets_of_superset (inter_mem_nhds_within _ ht), assume y hy, rw [mem_set_of_eq, mem_preimage, hleft hy.1], exact hy.2 end theorem is_open_map.continuous_on_range_of_left_inverse {f : α → β} (hf : is_open_map f) {finv : β → α} (hleft : function.left_inverse finv f) : continuous_on finv (range f) := begin rw [← image_univ], exact (hf.restrict is_open_univ).continuous_on_image_of_left_inv_on (λ x _, hleft x) end lemma continuous_on.congr_mono {f g : α → β} {s s₁ : set α} (h : continuous_on f s) (h' : eq_on g f s₁) (h₁ : s₁ ⊆ s) : continuous_on g s₁ := begin assume x hx, unfold continuous_within_at, have A := (h x (h₁ hx)).mono h₁, unfold continuous_within_at at A, rw ← h' hx at A, have : (g =ᶠ[nhds_within x s₁] f) := mem_inf_sets_of_right h', exact A.congr' this.symm end lemma continuous_on.congr {f g : α → β} {s : set α} (h : continuous_on f s) (h' : eq_on g f s) : continuous_on g s := h.congr_mono h' (subset.refl _) lemma continuous_on_congr {f g : α → β} {s : set α} (h' : eq_on g f s) : continuous_on g s ↔ continuous_on f s := ⟨λ h, continuous_on.congr h h'.symm, λ h, h.congr h'⟩ lemma continuous_at.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous_at f x) : continuous_within_at f s x := continuous_within_at.mono ((continuous_within_at_univ f x).2 h) (subset_univ _) lemma continuous_within_at.continuous_at {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hs : s ∈ 𝓝 x) : continuous_at f x := begin have : s = univ ∩ s, by rw univ_inter, rwa [this, continuous_within_at_inter hs, continuous_within_at_univ] at h end lemma continuous_on.continuous_at {f : α → β} {s : set α} {x : α} (h : continuous_on f s) (hx : s ∈ 𝓝 x) : continuous_at f x := (h x (mem_of_nhds hx)).continuous_at hx lemma continuous_within_at.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α} (hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) (h : s ⊆ f ⁻¹' t) : continuous_within_at (g ∘ f) s x := begin have : tendsto f (𝓟 s) (𝓟 t), by { rw tendsto_principal_principal, exact λx hx, h hx }, have : tendsto f (nhds_within x s) (𝓟 t) := tendsto_le_left inf_le_right this, have : tendsto f (nhds_within x s) (nhds_within (f x) t) := tendsto_inf.2 ⟨hf, this⟩, exact tendsto.comp hg this end lemma continuous_on.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : continuous_on g t) (hf : continuous_on f s) (h : s ⊆ f ⁻¹' t) : continuous_on (g ∘ f) s := λx hx, continuous_within_at.comp (hg _ (h hx)) (hf x hx) h lemma continuous_on.mono {f : α → β} {s t : set α} (hf : continuous_on f s) (h : t ⊆ s) : continuous_on f t := λx hx, tendsto_le_left (nhds_within_mono _ h) (hf x (h hx)) lemma continuous.continuous_on {f : α → β} {s : set α} (h : continuous f) : continuous_on f s := begin rw continuous_iff_continuous_on_univ at h, exact h.mono (subset_univ _) end lemma continuous.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous f) : continuous_within_at f s x := tendsto_le_left inf_le_left (h.tendsto x) lemma continuous.comp_continuous_on {g : β → γ} {f : α → β} {s : set α} (hg : continuous g) (hf : continuous_on f s) : continuous_on (g ∘ f) s := hg.continuous_on.comp hf subset_preimage_univ lemma continuous_within_at.preimage_mem_nhds_within {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ nhds_within x s := h ht lemma continuous_within_at.preimage_mem_nhds_within' {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ nhds_within (f x) (f '' s)) : f ⁻¹' t ∈ nhds_within x s := begin rw mem_nhds_within at ht, rcases ht with ⟨u, u_open, fxu, hu⟩, have : f ⁻¹' u ∩ s ∈ nhds_within x s := filter.inter_mem_sets (h (mem_nhds_sets u_open fxu)) self_mem_nhds_within, apply mem_sets_of_superset this, calc f ⁻¹' u ∩ s ⊆ f ⁻¹' u ∩ f ⁻¹' (f '' s) : inter_subset_inter_right _ (subset_preimage_image f s) ... = f ⁻¹' (u ∩ f '' s) : rfl ... ⊆ f ⁻¹' t : preimage_mono hu end lemma continuous_within_at.congr_of_mem_nhds_within {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : f₁ =ᶠ[nhds_within x s] f) (hx : f₁ x = f x) : continuous_within_at f₁ s x := by rwa [continuous_within_at, filter.tendsto, hx, filter.map_congr h₁] lemma continuous_within_at.congr {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : continuous_within_at f₁ s x := h.congr_of_mem_nhds_within (mem_sets_of_superset self_mem_nhds_within h₁) hx lemma continuous_on_const {s : set α} {c : β} : continuous_on (λx, c) s := continuous_const.continuous_on lemma continuous_within_at_const {b : β} {s : set α} {x : α} : continuous_within_at (λ _:α, b) s x := continuous_const.continuous_within_at lemma continuous_on_id {s : set α} : continuous_on id s := continuous_id.continuous_on lemma continuous_within_at_id {s : set α} {x : α} : continuous_within_at id s x := continuous_id.continuous_within_at lemma continuous_on_open_iff {f : α → β} {s : set α} (hs : is_open s) : continuous_on f s ↔ (∀t, is_open t → is_open (s ∩ f⁻¹' t)) := begin rw continuous_on_iff', split, { assume h t ht, rcases h t ht with ⟨u, u_open, hu⟩, rw [inter_comm, hu], apply is_open_inter u_open hs }, { assume h t ht, refine ⟨s ∩ f ⁻¹' t, h t ht, _⟩, rw [@inter_comm _ s (f ⁻¹' t), inter_assoc, inter_self] } end lemma continuous_on.preimage_open_of_open {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) (ht : is_open t) : is_open (s ∩ f⁻¹' t) := (continuous_on_open_iff hs).1 hf t ht lemma continuous_on.preimage_closed_of_closed {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_closed s) (ht : is_closed t) : is_closed (s ∩ f⁻¹' t) := begin rcases continuous_on_iff_is_closed.1 hf t ht with ⟨u, hu⟩, rw [inter_comm, hu.2], apply is_closed_inter hu.1 hs end lemma continuous_on.preimage_interior_subset_interior_preimage {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) : s ∩ f⁻¹' (interior t) ⊆ s ∩ interior (f⁻¹' t) := calc s ∩ f ⁻¹' (interior t) ⊆ interior (s ∩ f ⁻¹' t) : interior_maximal (inter_subset_inter (subset.refl _) (preimage_mono interior_subset)) (hf.preimage_open_of_open hs is_open_interior) ... = s ∩ interior (f ⁻¹' t) : by rw [interior_inter, interior_eq_of_open hs] lemma continuous_on_of_locally_continuous_on {f : α → β} {s : set α} (h : ∀x∈s, ∃t, is_open t ∧ x ∈ t ∧ continuous_on f (s ∩ t)) : continuous_on f s := begin assume x xs, rcases h x xs with ⟨t, open_t, xt, ct⟩, have := ct x ⟨xs, xt⟩, rwa [continuous_within_at, ← nhds_within_restrict _ xt open_t] at this end lemma continuous_on_open_of_generate_from {β : Type*} {s : set α} {T : set (set β)} {f : α → β} (hs : is_open s) (h : ∀t ∈ T, is_open (s ∩ f⁻¹' t)) : @continuous_on α β _ (topological_space.generate_from T) f s := begin rw continuous_on_open_iff, assume t ht, induction ht with u hu u v Tu Tv hu hv U hU hU', { exact h u hu }, { simp only [preimage_univ, inter_univ], exact hs }, { have : s ∩ f ⁻¹' (u ∩ v) = (s ∩ f ⁻¹' u) ∩ (s ∩ f ⁻¹' v), by { ext x, simp, split, finish, finish }, rw this, exact is_open_inter hu hv }, { rw [preimage_sUnion, inter_bUnion], exact is_open_bUnion hU' }, { exact hs } end lemma continuous_within_at.prod {f : α → β} {g : α → γ} {s : set α} {x : α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, (f x, g x)) s x := hf.prod_mk_nhds hg lemma continuous_on.prod {f : α → β} {g : α → γ} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, (f x, g x)) s := λx hx, continuous_within_at.prod (hf x hx) (hg x hx)
44c1a20632925ee496480a67d187a38a6bcf9089
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/match1.lean
e84d9a3c145d7af264af5f25cf1d725eb8ce670a
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
3,443
lean
def f (xs : List Nat) : List Bool := xs.map fun | 0 => true | _ => false #eval f [1, 2, 0, 2] theorem ex1 : f [1, 0, 2] = [false, true, false] := rfl #check f set_option pp.raw true set_option pp.raw.maxDepth 10 set_option trace.Elab.step true in def g (xs : List Nat) : List Bool := xs.map <| by { intro | 0 => exact true | _ => exact false } theorem ex2 : g [1, 0, 2] = [false, true, false] := rfl theorem ex3 {p q r : Prop} : p ∨ q → r → (q ∧ r) ∨ (p ∧ r) := by intro | Or.inl hp, h => { apply Or.inr; apply And.intro; assumption; assumption } | Or.inr hq, h => { apply Or.inl; exact ⟨hq, h⟩ } inductive C | mk₁ : Nat → C | mk₂ : Nat → Nat → C def C.x : C → Nat | C.mk₁ x => x | C.mk₂ x _ => x def head : {α : Type} → List α → Option α | _, a::as => some a | _, _ => none theorem ex4 : head [1, 2] = some 1 := rfl def head2 : {α : Type} → List α → Option α := @fun | _, a::as => some a | _, _ => none theorem ex5 : head2 [1, 2] = some 1 := rfl def head3 {α : Type} (xs : List α) : Option α := let rec aux : {α : Type} → List α → Option α | _, a::as => some a | _, _ => none; aux xs theorem ex6 : head3 [1, 2] = some 1 := rfl inductive Vec.{u} (α : Type u) : Nat → Type u | nil : Vec α 0 | cons {n} (head : α) (tail : Vec α n) : Vec α (n+1) def Vec.mapHead1 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ | _, nil, nil, f => none | _, cons a as, cons b bs, f => some (f a b) def Vec.mapHead2 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ | _, nil, nil, f => none | _, @cons _ n a as, cons b bs, f => some (f a b) def Vec.mapHead3 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ | _, nil, nil, f => none | _, cons (tail := as) (head := a), cons b bs, f => some (f a b) inductive Foo | mk₁ (x y z w : Nat) | mk₂ (x y z w : Nat) def Foo.z : Foo → Nat | mk₁ (z := z) .. => z | mk₂ (z := z) .. => z #eval (Foo.mk₁ 10 20 30 40).z theorem ex7 : (Foo.mk₁ 10 20 30 40).z = 30 := rfl def Foo.addY? : Foo × Foo → Option Nat | (mk₁ (y := y₁) .., mk₁ (y := y₂) ..) => some (y₁ + y₂) | _ => none #eval Foo.addY? (Foo.mk₁ 1 2 3 4, Foo.mk₁ 10 20 30 40) theorem ex8 : Foo.addY? (Foo.mk₁ 1 2 3 4, Foo.mk₁ 10 20 30 40) = some 22 := rfl instance {α} : Inhabited (Sigma fun m => Vec α m) := ⟨⟨0, Vec.nil⟩⟩ partial def filter {α} (p : α → Bool) : {n : Nat} → Vec α n → Sigma fun m => Vec α m | _, Vec.nil => ⟨0, Vec.nil⟩ | _, Vec.cons x xs => match p x, filter p xs with | true, ⟨_, ys⟩ => ⟨_, Vec.cons x ys⟩ | false, ys => ys inductive Bla | ofNat (x : Nat) | ofBool (x : Bool) def Bla.optional? : Bla → Option Nat | ofNat x => some x | ofBool _ => none def Bla.isNat? (b : Bla) : Option { x : Nat // optional? b = some x } := match b.optional? with | some y => some ⟨y, rfl⟩ | none => none def foo (b : Bla) : Option Nat := b.optional? theorem fooEq (b : Bla) : foo b = b.optional? := rfl def Bla.isNat2? (b : Bla) : Option { x : Nat // optional? b = some x } := match h:foo b with | some y => some ⟨y, Eq.trans (fooEq b).symm h⟩ | none => none def foo2 (x : Nat) : Nat := match x, rfl : (y : Nat) → x = y → Nat with | 0, h => 0 | x+1, h => 1
0f70646cc2b480992a0004fa637ae18e830b3eb5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group/with_one_auto.lean
c4a152be9ca7d46d6123a1384961a226c1882d17
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
7,572
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.ring.basic import Mathlib.data.equiv.basic import Mathlib.PostPort universes u_1 u v namespace Mathlib /-- Add an extra element `1` to a type -/ def with_one (α : Type u_1) := Option α namespace with_one protected instance Mathlib.with_zero.monad : Monad with_zero := option.monad protected instance has_one {α : Type u} : HasOne (with_one α) := { one := none } protected instance Mathlib.with_zero.inhabited {α : Type u} : Inhabited (with_zero α) := { default := 0 } protected instance Mathlib.with_zero.nontrivial {α : Type u} [Nonempty α] : nontrivial (with_zero α) := option.nontrivial protected instance Mathlib.with_zero.has_coe_t {α : Type u} : has_coe_t α (with_zero α) := has_coe_t.mk some theorem Mathlib.with_zero.some_eq_coe {α : Type u} {a : α} : some a = ↑a := rfl @[simp] theorem coe_ne_one {α : Type u} {a : α} : ↑a ≠ 1 := option.some_ne_none a @[simp] theorem one_ne_coe {α : Type u} {a : α} : 1 ≠ ↑a := ne.symm coe_ne_one theorem Mathlib.with_zero.ne_zero_iff_exists {α : Type u} {x : with_zero α} : x ≠ 0 ↔ ∃ (a : α), ↑a = x := option.ne_none_iff_exists -- `to_additive` fails to generate some meta info around eqn lemmas, so `lift` doesn't work -- unless we explicitly define this instance protected instance can_lift {α : Type u} : can_lift (with_one α) α := can_lift.mk coe (fun (a : with_one α) => a ≠ 1) sorry @[simp] theorem Mathlib.with_zero.coe_inj {α : Type u} {a : α} {b : α} : ↑a = ↑b ↔ a = b := option.some_inj protected theorem Mathlib.with_zero.cases_on {α : Type u} {P : with_zero α → Prop} (x : with_zero α) : P 0 → (∀ (a : α), P ↑a) → P x := option.cases_on protected instance Mathlib.with_zero.has_add {α : Type u} [Add α] : Add (with_zero α) := { add := option.lift_or_get Add.add } protected instance monoid {α : Type u} [semigroup α] : monoid (with_one α) := monoid.mk Mul.mul sorry 1 sorry sorry protected instance Mathlib.with_zero.add_comm_monoid {α : Type u} [add_comm_semigroup α] : add_comm_monoid (with_zero α) := add_comm_monoid.mk add_monoid.add sorry add_monoid.zero sorry sorry sorry /-- `coe` as a bundled morphism -/ def coe_mul_hom {α : Type u} [Mul α] : mul_hom α (with_one α) := mul_hom.mk coe sorry /-- Lift a semigroup homomorphism `f` to a bundled monoid homorphism. -/ def Mathlib.with_zero.lift {α : Type u} [add_semigroup α] {β : Type v} [add_monoid β] : add_hom α β ≃ (with_zero α →+ β) := equiv.mk (fun (f : add_hom α β) => add_monoid_hom.mk (fun (x : with_zero α) => option.cases_on x 0 ⇑f) sorry sorry) (fun (F : with_zero α →+ β) => add_hom.comp (add_monoid_hom.to_add_hom F) with_zero.coe_add_hom) sorry sorry @[simp] theorem Mathlib.with_zero.lift_coe {α : Type u} [add_semigroup α] {β : Type v} [add_monoid β] (f : add_hom α β) (x : α) : coe_fn (coe_fn with_zero.lift f) ↑x = coe_fn f x := rfl @[simp] theorem lift_one {α : Type u} [semigroup α] {β : Type v} [monoid β] (f : mul_hom α β) : coe_fn (coe_fn lift f) 1 = 1 := rfl theorem Mathlib.with_zero.lift_unique {α : Type u} [add_semigroup α] {β : Type v} [add_monoid β] (f : with_zero α →+ β) : f = coe_fn with_zero.lift (add_hom.comp (add_monoid_hom.to_add_hom f) with_zero.coe_add_hom) := Eq.symm (equiv.apply_symm_apply with_zero.lift f) /-- Given a multiplicative map from `α → β` returns a monoid homomorphism from `with_one α` to `with_one β` -/ def Mathlib.with_zero.map {α : Type u} {β : Type v} [add_semigroup α] [add_semigroup β] (f : add_hom α β) : with_zero α →+ with_zero β := coe_fn with_zero.lift (add_hom.comp with_zero.coe_add_hom f) @[simp] theorem Mathlib.with_zero.coe_add {α : Type u} [Add α] (a : α) (b : α) : ↑(a + b) = ↑a + ↑b := rfl end with_one namespace with_zero -- `to_additive` fails to generate some meta info around eqn lemmas, so `lift` doesn't work -- unless we explicitly define this instance protected instance can_lift {α : Type u} : can_lift (with_zero α) α := can_lift.mk coe (fun (a : with_zero α) => a ≠ 0) sorry protected instance has_one {α : Type u} [one : HasOne α] : HasOne (with_zero α) := { one := ↑1 } @[simp] theorem coe_one {α : Type u} [HasOne α] : ↑1 = 1 := rfl protected instance mul_zero_class {α : Type u} [Mul α] : mul_zero_class (with_zero α) := mul_zero_class.mk (fun (o₁ o₂ : with_zero α) => option.bind o₁ fun (a : α) => option.map (fun (b : α) => a * b) o₂) 0 sorry sorry @[simp] theorem coe_mul {α : Type u} [Mul α] {a : α} {b : α} : ↑(a * b) = ↑a * ↑b := rfl @[simp] theorem zero_mul {α : Type u} [Mul α] (a : with_zero α) : 0 * a = 0 := rfl @[simp] theorem mul_zero {α : Type u} [Mul α] (a : with_zero α) : a * 0 = 0 := option.cases_on a (Eq.refl (none * 0)) fun (a : α) => Eq.refl (some a * 0) protected instance semigroup {α : Type u} [semigroup α] : semigroup (with_zero α) := semigroup.mk mul_zero_class.mul sorry protected instance comm_semigroup {α : Type u} [comm_semigroup α] : comm_semigroup (with_zero α) := comm_semigroup.mk semigroup.mul sorry sorry protected instance monoid_with_zero {α : Type u} [monoid α] : monoid_with_zero (with_zero α) := monoid_with_zero.mk mul_zero_class.mul sorry 1 sorry sorry mul_zero_class.zero sorry sorry protected instance comm_monoid_with_zero {α : Type u} [comm_monoid α] : comm_monoid_with_zero (with_zero α) := comm_monoid_with_zero.mk monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry sorry monoid_with_zero.zero sorry sorry /-- Given an inverse operation on `α` there is an inverse operation on `with_zero α` sending `0` to `0`-/ def inv {α : Type u} [has_inv α] (x : with_zero α) : with_zero α := do let a ← x return (a⁻¹) protected instance has_inv {α : Type u} [has_inv α] : has_inv (with_zero α) := has_inv.mk inv @[simp] theorem coe_inv {α : Type u} [has_inv α] (a : α) : ↑(a⁻¹) = (↑a⁻¹) := rfl @[simp] theorem inv_zero {α : Type u} [has_inv α] : 0⁻¹ = 0 := rfl @[simp] theorem inv_one {α : Type u} [group α] : 1⁻¹ = 1 := sorry /-- if `G` is a group then `with_zero G` is a group with zero. -/ protected instance group_with_zero {α : Type u} [group α] : group_with_zero (with_zero α) := group_with_zero.mk monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry monoid_with_zero.zero sorry sorry has_inv.inv (div_inv_monoid.div._default monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry has_inv.inv) sorry sorry sorry theorem div_coe {α : Type u} [group α] (a : α) (b : α) : ↑a / ↑b = ↑(a * (b⁻¹)) := rfl protected instance comm_group_with_zero {α : Type u} [comm_group α] : comm_group_with_zero (with_zero α) := comm_group_with_zero.mk group_with_zero.mul sorry group_with_zero.one sorry sorry sorry group_with_zero.zero sorry sorry group_with_zero.inv group_with_zero.div sorry sorry sorry protected instance semiring {α : Type u} [semiring α] : semiring (with_zero α) := semiring.mk add_comm_monoid.add sorry add_comm_monoid.zero sorry sorry sorry mul_zero_class.mul sorry monoid_with_zero.one sorry sorry sorry sorry sorry sorry end Mathlib
97146e2e5a27833ea0525a599ef3584e798046d4
43390109ab88557e6090f3245c47479c123ee500
/src/M1F/problem_bank/0107/0107Q.lean
700cb3b63ab79ad6ea59c0531201bc9a104a7005
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,223
lean
-- real numbers import data.real.basic -- useful lemmas import xenalib.M1F.help_for_0107 noncomputable theory def A : set ℝ := { x | x^2 < 3} def B : set ℝ := { x | x^2 < 3 ∧ ∃ y : ℤ, x = y} def C : set ℝ := { x | x^3 < 3} definition real_half := (1 / 2 : ℝ) -- useful lemmas definition B_is_minus_one_zero_one : ∀ {x : ℝ}, x ∈ B ↔ x = -1 ∨ x = 0 ∨ x = 1 := Q0107.B_is_minus_one_zero_one definition real_half_not_in_B : real_half ∉ B := Q0107.real_half_not_in_B -- For each part x, prove exactly one of part_x_true and -- part_x_false, and comment out the other one! theorem part_a_true : (1/2 : ℝ) ∈ A ∩ B := sorry theorem part_a_false : ¬ (1/2 : ℝ) ∈ A ∩ B := sorry theorem part_b_true : (1/2 : ℝ) ∈ A ∪ B := sorry theorem part_b_false : ¬ (1/2 : ℝ) ∈ A ∪ B := sorry theorem part_c_true : A ⊆ C := sorry theorem part_c_false : ¬ A ⊆ C := sorry theorem part_d_true : B ⊆ C := sorry theorem part_d_false : ¬ B ⊆ C := sorry theorem part_e_true : C ⊆ A ∪ B := sorry theorem part_e_false : ¬ C ⊆ A ∪ B := sorry theorem part_f_true : (A ∩ B) ∪ C = (A ∪ B) ∩ C := sorry theorem part_f_false : ¬ (A ∩ B) ∪ C = (A ∪ B) ∩ C := sorry
b70f9c03fc1986ca7dd3f75bc5d55570f02f36cb
90edd5cdcf93124fe15627f7304069fdce3442dd
/src/Lean/Aesop/RuleTac.lean
7c998df30f97ddb10df8616164c4c8a6196c7fd1
[ "Apache-2.0" ]
permissive
JLimperg/lean4-aesop
8a9d9cd3ee484a8e67fda2dd9822d76708098712
5c4b9a3e05c32f69a4357c3047c274f4b94f9c71
refs/heads/master
1,689,415,944,104
1,627,383,284,000
1,627,383,284,000
377,536,770
0
0
null
null
null
null
UTF-8
Lean
false
false
2,574
lean
/- Copyright (c) 2021 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import Lean.Elab open Lean.Elab.Tactic open Lean.Meta namespace Lean.Aesop -- A `RuleTacDescr` is a 'recipe' for constructing the tactic used by a rule. -- When we serialise the rule set to an olean file, we serialise `RuleTacDescr`s -- because we can't (currently?) serialise the actual tactics. inductive RuleTacDescr | applyConst (decl : Name) | tactic (decl : Name) deriving Inhabited, BEq -- A `RuleTac` bundles a `RuleTacDescr` and the tactic that was computed from -- the description. Local rules do not have descriptions since we never -- serialise them. structure RuleTac where tac : TacticM Unit descr : Option RuleTacDescr deriving Inhabited namespace RuleTacBuilder /- Convenience for evalTacticUnsafe. -/ private abbrev TacticType := TacticM Unit def checkTacticM (decl : Name) : MetaM Unit := do let info ← getConstInfo decl unless (← isDefEq info.type (mkConst ``TacticType)) do throwError "aesop: {decl} was expected to have type\n TacticM Unit\nbut has type\n {info.type}" unsafe def evalTacticConstUnsafe (decl : Name) : TacticM Unit := do checkTacticM decl -- TODO Maybe we can elide the above check. We already check the type -- when we register the tactic. let tac ← evalConst TacticType decl tac @[implementedBy evalTacticConstUnsafe] constant evalTacticConst : Name → TacticM Unit -- I think the above use of `evalConst` is safe because we call it at a concrete -- type, making sure that the constant actually has that type. def tactic (decl : Name) : MetaM RuleTac := do checkTacticM decl return { tac := evalTacticConst decl, descr := RuleTacDescr.tactic decl } def apply (decl : Name) : MetaM RuleTac := return { tac := liftMetaTactic λ goal => do Lean.Meta.apply goal (← mkConstWithFreshMVarLevels decl) -- TODO Go via apply tactic syntax to ensure intuitive behaviour? descr := RuleTacDescr.applyConst decl } def applyFVar (userName : Name) : MetaM RuleTac := do let _ ← getLocalDeclFromUserName userName return { tac := liftMetaTactic λ goal => do let decl ← getLocalDeclFromUserName userName Lean.Meta.apply goal (mkFVar decl.fvarId) descr := none } end RuleTacBuilder namespace RuleTacDescr def toRuleTac : RuleTacDescr → MetaM RuleTac | applyConst decl => RuleTacBuilder.apply decl | tactic decl => RuleTacBuilder.tactic decl end RuleTacDescr end Lean.Aesop
d9564f6320ca15383433c010af33271a711cbb09
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/list/sort.lean
8c5c7cac0449207922fb0c48dd4ed51f82a446e7
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
10,340
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Insertion sort and merge sort. -/ import data.list.perm open list.perm namespace list section sorted universe variable uu variables {α : Type uu} {r : α → α → Prop} /-- `sorted r l` is the same as `pairwise r l`, preferred in the case that `r` is a `<` or `≤`-like relation (transitive and antisymmetric or asymmetric) -/ def sorted := @pairwise @[simp] theorem sorted_nil : sorted r [] := pairwise.nil @[simp] theorem sorted_singleton (a : α) : sorted r [a] := pairwise_singleton _ _ theorem sorted_of_sorted_cons {a : α} {l : list α} : sorted r (a :: l) → sorted r l := pairwise_of_pairwise_cons theorem rel_of_sorted_cons {a : α} {l : list α} : sorted r (a :: l) → ∀ b ∈ l, r a b := rel_of_pairwise_cons @[simp] theorem sorted_cons {a : α} {l : list α} : sorted r (a :: l) ↔ (∀ b ∈ l, r a b) ∧ sorted r l := pairwise_cons theorem eq_of_sorted_of_perm [is_antisymm α r] {l₁ l₂ : list α} (p : l₁ ~ l₂) (s₁ : sorted r l₁) (s₂ : sorted r l₂) : l₁ = l₂ := begin induction s₁ with a l₁ h₁ s₁ IH generalizing l₂, { rw eq_nil_of_perm_nil p }, { have : a ∈ l₂ := perm_subset p (mem_cons_self _ _), rcases mem_split this with ⟨u₂, v₂, rfl⟩, have p' := (perm_cons a).1 (p.trans perm_middle), have := IH p' (pairwise_of_sublist (by simp) s₂), subst l₁, change a::u₂ ++ v₂ = u₂ ++ ([a] ++ v₂), rw ← append_assoc, congr, have : ∀ (x : α) (h : x ∈ u₂), x = a := λ x m, antisymm ((pairwise_append.1 s₂).2.2 _ m a (mem_cons_self _ _)) (h₁ _ (by simp [m])), rw [(@eq_repeat _ a (length u₂ + 1) (a::u₂)).2, (@eq_repeat _ a (length u₂ + 1) (u₂++[a])).2]; split; simp [iff_true_intro this, or_comm] } end end sorted /- sorting procedures -/ section sort universe variable uu parameters {α : Type uu} (r : α → α → Prop) [decidable_rel r] local infix ` ≼ ` : 50 := r /- insertion sort -/ section insertion_sort /-- `ordered_insert a l` inserts `a` into `l` at such that `ordered_insert a l` is sorted if `l` is. -/ @[simp] def ordered_insert (a : α) : list α → list α | [] := [a] | (b :: l) := if a ≼ b then a :: b :: l else b :: ordered_insert l /-- `insertion_sort l` returns `l` sorted using the insertion sort algorithm. -/ @[simp] def insertion_sort : list α → list α | [] := [] | (b :: l) := ordered_insert b (insertion_sort l) section correctness open perm theorem perm_ordered_insert (a) : ∀ l : list α, ordered_insert a l ~ a :: l | [] := perm.refl _ | (b :: l) := by by_cases a ≼ b; [simp [ordered_insert, h], simpa [ordered_insert, h] using (perm.skip _ (perm_ordered_insert l)).trans (perm.swap _ _ _)] theorem perm_insertion_sort : ∀ l : list α, insertion_sort l ~ l | [] := perm.nil | (b :: l) := by simpa [insertion_sort] using (perm_ordered_insert _ _ _).trans (perm.skip b (perm_insertion_sort l)) section total_and_transitive variables [is_total α r] [is_trans α r] theorem sorted_ordered_insert (a : α) : ∀ l, sorted r l → sorted r (ordered_insert a l) | [] h := sorted_singleton a | (b :: l) h := begin by_cases h' : a ≼ b, { simpa [ordered_insert, h', h] using λ b' bm, trans h' (rel_of_sorted_cons h _ bm) }, { suffices : ∀ (b' : α), b' ∈ ordered_insert r a l → r b b', { simpa [ordered_insert, h', sorted_ordered_insert l (sorted_of_sorted_cons h)] }, intros b' bm, cases (show b' = a ∨ b' ∈ l, by simpa using perm_subset (perm_ordered_insert _ _ _) bm) with be bm, { subst b', exact (total_of r _ _).resolve_left h' }, { exact rel_of_sorted_cons h _ bm } } end theorem sorted_insertion_sort : ∀ l, sorted r (insertion_sort l) | [] := sorted_nil | (a :: l) := sorted_ordered_insert a _ (sorted_insertion_sort l) end total_and_transitive end correctness end insertion_sort /- merge sort -/ section merge_sort -- TODO(Jeremy): observation: if instead we write (a :: (split l).1, b :: (split l).2), the -- equation compiler can't prove the third equation /-- Split `l` into two lists of approximately equal length. split [1, 2, 3, 4, 5] = ([1, 3, 5], [2, 4]) -/ @[simp] def split : list α → list α × list α | [] := ([], []) | (a :: l) := let (l₁, l₂) := split l in (a :: l₂, l₁) theorem split_cons_of_eq (a : α) {l l₁ l₂ : list α} (h : split l = (l₁, l₂)) : split (a :: l) = (a :: l₂, l₁) := by rw [split, h]; refl theorem length_split_le : ∀ {l l₁ l₂ : list α}, split l = (l₁, l₂) → length l₁ ≤ length l ∧ length l₂ ≤ length l | [] ._ ._ rfl := ⟨nat.le_refl 0, nat.le_refl 0⟩ | (a::l) l₁' l₂' h := begin cases e : split l with l₁ l₂, injection (split_cons_of_eq _ e).symm.trans h, substs l₁' l₂', cases length_split_le e with h₁ h₂, exact ⟨nat.succ_le_succ h₂, nat.le_succ_of_le h₁⟩ end theorem length_split_lt {a b} {l l₁ l₂ : list α} (h : split (a::b::l) = (l₁, l₂)) : length l₁ < length (a::b::l) ∧ length l₂ < length (a::b::l) := begin cases e : split l with l₁' l₂', injection (split_cons_of_eq _ (split_cons_of_eq _ e)).symm.trans h, substs l₁ l₂, cases length_split_le e with h₁ h₂, exact ⟨nat.succ_le_succ (nat.succ_le_succ h₁), nat.succ_le_succ (nat.succ_le_succ h₂)⟩ end theorem perm_split : ∀ {l l₁ l₂ : list α}, split l = (l₁, l₂) → l ~ l₁ ++ l₂ | [] ._ ._ rfl := perm.refl _ | (a::l) l₁' l₂' h := begin cases e : split l with l₁ l₂, injection (split_cons_of_eq _ e).symm.trans h, substs l₁' l₂', exact perm.skip a ((perm_split e).trans perm_app_comm), end /-- Merge two sorted lists into one in linear time. merge [1, 2, 4, 5] [0, 1, 3, 4] = [0, 1, 1, 2, 3, 4, 4, 5] -/ def merge : list α → list α → list α | [] l' := l' | l [] := l | (a :: l) (b :: l') := if a ≼ b then a :: merge l (b :: l') else b :: merge (a :: l) l' include r /-- Implementation of a merge sort algorithm to sort a list. -/ def merge_sort : list α → list α | [] := [] | [a] := [a] | (a::b::l) := begin cases e : split (a::b::l) with l₁ l₂, cases length_split_lt e with h₁ h₂, exact merge r (merge_sort l₁) (merge_sort l₂) end using_well_founded { rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩], dec_tac := tactic.assumption } theorem merge_sort_cons_cons {a b} {l l₁ l₂ : list α} (h : split (a::b::l) = (l₁, l₂)) : merge_sort (a::b::l) = merge (merge_sort l₁) (merge_sort l₂) := begin suffices : ∀ (L : list α) h1, @@and.rec (λ a a (_ : length l₁ < length l + 1 + 1 ∧ length l₂ < length l + 1 + 1), L) h1 h1 = L, { simp [merge_sort, h], apply this }, intros, cases h1, refl end section correctness theorem perm_merge : ∀ (l l' : list α), merge l l' ~ l ++ l' | [] [] := perm.nil | [] (b :: l') := by simp [merge] | (a :: l) [] := by simp [merge] | (a :: l) (b :: l') := begin by_cases a ≼ b, { simpa [merge, h] using skip _ (perm_merge _ _) }, { suffices : b :: merge r (a :: l) l' ~ a :: (l ++ b :: l'), {simpa [merge, h]}, exact (skip _ (perm_merge _ _)).trans ((swap _ _ _).trans (skip _ perm_middle.symm)) } end theorem perm_merge_sort : ∀ l : list α, merge_sort l ~ l | [] := perm.refl _ | [a] := perm.refl _ | (a::b::l) := begin cases e : split (a::b::l) with l₁ l₂, cases length_split_lt e with h₁ h₂, rw [merge_sort_cons_cons r e], apply (perm_merge r _ _).trans, exact (perm_app (perm_merge_sort l₁) (perm_merge_sort l₂)).trans (perm_split e).symm end using_well_founded { rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩], dec_tac := tactic.assumption } @[simp] lemma length_merge_sort (l : list α) : (merge_sort l).length = l.length := perm_length (perm_merge_sort _) section total_and_transitive variables [is_total α r] [is_trans α r] theorem sorted_merge : ∀ {l l' : list α}, sorted r l → sorted r l' → sorted r (merge l l') | [] [] h₁ h₂ := sorted_nil | [] (b :: l') h₁ h₂ := by simpa [merge] using h₂ | (a :: l) [] h₁ h₂ := by simpa [merge] using h₁ | (a :: l) (b :: l') h₁ h₂ := begin by_cases a ≼ b, { suffices : ∀ (b' : α) (_ : b' ∈ merge r l (b :: l')), r a b', { simpa [merge, h, sorted_merge (sorted_of_sorted_cons h₁) h₂] }, intros b' bm, rcases (show b' = b ∨ b' ∈ l ∨ b' ∈ l', by simpa [or.left_comm] using perm_subset (perm_merge _ _ _) bm) with be | bl | bl', { subst b', assumption }, { exact rel_of_sorted_cons h₁ _ bl }, { exact trans h (rel_of_sorted_cons h₂ _ bl') } }, { suffices : ∀ (b' : α) (_ : b' ∈ merge r (a :: l) l'), r b b', { simpa [merge, h, sorted_merge h₁ (sorted_of_sorted_cons h₂)] }, intros b' bm, have ba : b ≼ a := (total_of r _ _).resolve_left h, rcases (show b' = a ∨ b' ∈ l ∨ b' ∈ l', by simpa using perm_subset (perm_merge _ _ _) bm) with be | bl | bl', { subst b', assumption }, { exact trans ba (rel_of_sorted_cons h₁ _ bl) }, { exact rel_of_sorted_cons h₂ _ bl' } } end theorem sorted_merge_sort : ∀ l : list α, sorted r (merge_sort l) | [] := sorted_nil | [a] := sorted_singleton _ | (a::b::l) := begin cases e : split (a::b::l) with l₁ l₂, cases length_split_lt e with h₁ h₂, rw [merge_sort_cons_cons r e], exact sorted_merge r (sorted_merge_sort l₁) (sorted_merge_sort l₂) end using_well_founded { rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩], dec_tac := tactic.assumption } theorem merge_sort_eq_self [is_antisymm α r] {l : list α} : sorted r l → merge_sort l = l := eq_of_sorted_of_perm (perm_merge_sort _) (sorted_merge_sort _) end total_and_transitive end correctness end merge_sort end sort /- try them out! -/ --#eval insertion_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] --#eval merge_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] end list
5fef8671d83599db4a41612c55943fe98324e6df
9028d228ac200bbefe3a711342514dd4e4458bff
/src/algebra/char_p.lean
702b690c99d7389c547ef688398f4285f6acab30
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,447
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau, Joey van Langen, Casper Putz -/ import data.fintype.basic import data.nat.choose import data.int.modeq import algebra.module.basic import algebra.iterate_hom import group_theory.order_of_element import algebra.group.type_tags /-! # Characteristic of semirings -/ universes u v /-- The generator of the kernel of the unique homomorphism ℕ → α for a semiring α -/ class char_p (α : Type u) [semiring α] (p : ℕ) : Prop := (cast_eq_zero_iff [] : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x) theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 := (char_p.cast_eq_zero_iff α p p).2 (dvd_refl p) @[simp] lemma char_p.cast_card_eq_zero (R : Type*) [ring R] [fintype R] : (fintype.card R : R) = 0 := begin have : fintype.card R •ℕ (1 : R) = 0 := @pow_card_eq_one (multiplicative R) _ _ (multiplicative.of_add 1), simpa only [mul_one, nsmul_eq_mul] end lemma char_p.int_cast_eq_zero_iff (R : Type u) [ring R] (p : ℕ) [char_p R p] (a : ℤ) : (a : R) = 0 ↔ (p:ℤ) ∣ a := begin rcases lt_trichotomy a 0 with h|rfl|h, { rw [← neg_eq_zero, ← int.cast_neg, ← dvd_neg], lift -a to ℕ using neg_nonneg.mpr (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] }, { simp only [int.cast_zero, eq_self_iff_true, dvd_zero] }, { lift a to ℕ using (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] } end lemma char_p.int_coe_eq_int_coe_iff (R : Type*) [ring R] (p : ℕ) [char_p R p] (a b : ℤ) : (a : R) = (b : R) ↔ a ≡ b [ZMOD p] := by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub, char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd] theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q := nat.dvd_antisymm ((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _)) ((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _)) instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 := ⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩ theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p := by letI := classical.dec_eq α; exact classical.by_cases (assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0, ⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩) (λ H, ⟨nat.find (not_forall.1 H), ⟨λ x, ⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2, nat.find_min (not_forall.1 H) (nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $ nat.find_spec (not_forall.1 H)) (not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (not_forall.1 H)), nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (not_forall.1 H)), zero_mul, add_zero] at H1, H2⟩)), λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (not_forall.1 H)), zero_mul]⟩⟩⟩) theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p := let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩ /-- Noncomputable function that outputs the unique characteristic of a semiring. -/ noncomputable def ring_char (α : Type u) [semiring α] : ℕ := classical.some (char_p.exists_unique α) theorem ring_char.spec (α : Type u) [semiring α] : ∀ x:ℕ, (x:α) = 0 ↔ ring_char α ∣ x := by letI := (classical.some_spec (char_p.exists_unique α)).1; unfold ring_char; exact char_p.cast_eq_zero_iff α (ring_char α) theorem ring_char.eq (α : Type u) [semiring α] {p : ℕ} (C : char_p α p) : p = ring_char α := (classical.some_spec (char_p.exists_unique α)).2 p C theorem add_pow_char_of_commute (R : Type u) [ring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) (h : commute x y) : (x + y)^p = x^p + y^p := begin rw [commute.add_pow h, finset.sum_range_succ, nat.sub_self, pow_zero, nat.choose_self], rw [nat.cast_one, mul_one, mul_one, add_right_inj], convert finset.sum_eq_single 0 _ _, { simp }, swap, { intro h1, contrapose! h1, rw finset.mem_range, apply nat.prime.pos, assumption }, intros b h1 h2, suffices : (p.choose b : R) = 0, { rw this, simp }, rw char_p.cast_eq_zero_iff R p, apply nat.prime.dvd_choose_self, assumption', { omega }, rwa ← finset.mem_range end theorem add_pow_char_pow_of_commute (R : Type u) [ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) (h : commute x y) : (x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) := begin induction n, { simp, }, rw [pow_succ', pow_mul, pow_mul, pow_mul, n_ih], apply add_pow_char_of_commute, apply commute.pow_pow h, end theorem sub_pow_char_of_commute (R : Type u) [ring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) (h : commute x y) : (x - y)^p = x^p - y^p := begin rw [eq_sub_iff_add_eq, ← add_pow_char_of_commute _ _ _ (commute.sub_left h rfl)], simp, repeat {apply_instance}, end theorem sub_pow_char_pow_of_commute (R : Type u) [ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) (h : commute x y) : (x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) := begin induction n, { simp, }, rw [pow_succ', pow_mul, pow_mul, pow_mul, n_ih], apply sub_pow_char_of_commute, apply commute.pow_pow h, end theorem add_pow_char (α : Type u) [comm_ring α] {p : ℕ} [fact p.prime] [char_p α p] (x y : α) : (x + y)^p = x^p + y^p := add_pow_char_of_commute _ _ _ (commute.all _ _) theorem add_pow_char_pow (R : Type u) [comm_ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) : (x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) := add_pow_char_pow_of_commute _ _ _ (commute.all _ _) theorem sub_pow_char (α : Type u) [comm_ring α] {p : ℕ} [fact p.prime] [char_p α p] (x y : α) : (x - y)^p = x^p - y^p := sub_pow_char_of_commute _ _ _ (commute.all _ _) theorem sub_pow_char_pow (R : Type u) [comm_ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) : (x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) := sub_pow_char_pow_of_commute _ _ _ (commute.all _ _) lemma eq_iff_modeq_int (R : Type*) [ring R] (p : ℕ) [char_p R p] (a b : ℤ) : (a : R) = b ↔ a ≡ b [ZMOD p] := by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub, char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd] lemma char_p.neg_one_ne_one (R : Type*) [ring R] (p : ℕ) [char_p R p] [fact (2 < p)] : (-1 : R) ≠ (1 : R) := begin suffices : (2 : R) ≠ 0, { symmetry, rw [ne.def, ← sub_eq_zero, sub_neg_eq_add], exact this }, assume h, rw [show (2 : R) = (2 : ℕ), by norm_cast] at h, have := (char_p.cast_eq_zero_iff R p 2).mp h, have := nat.le_of_dvd dec_trivial this, rw fact at *, linarith, end lemma ring_hom.char_p_iff_char_p {K L : Type*} [field K] [field L] (f : K →+* L) (p : ℕ) : char_p K p ↔ char_p L p := begin split; { introI _c, constructor, intro n, rw [← @char_p.cast_eq_zero_iff _ _ p _c n, ← f.injective.eq_iff, f.map_nat_cast, f.map_zero] } end section frobenius variables (R : Type u) [comm_ring R] {S : Type v} [comm_ring S] (f : R →* S) (g : R →+* S) (p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R) /-- The frobenius map that sends x to x^p -/ def frobenius : R →+* R := { to_fun := λ x, x^p, map_one' := one_pow p, map_mul' := λ x y, mul_pow x y p, map_zero' := zero_pow (lt_trans zero_lt_one ‹nat.prime p›.one_lt), map_add' := add_pow_char R } variable {R} theorem frobenius_def : frobenius R p x = x ^ p := rfl theorem iterate_frobenius (n : ℕ) : (frobenius R p)^[n] x = x ^ p ^ n := begin induction n, {simp}, rw [function.iterate_succ', pow_succ', pow_mul, function.comp_apply, frobenius_def, n_ih] end theorem frobenius_mul : frobenius R p (x * y) = frobenius R p x * frobenius R p y := (frobenius R p).map_mul x y theorem frobenius_one : frobenius R p 1 = 1 := one_pow _ variable {R} theorem monoid_hom.map_frobenius : f (frobenius R p x) = frobenius S p (f x) := f.map_pow x p theorem ring_hom.map_frobenius : g (frobenius R p x) = frobenius S p (g x) := g.map_pow x p theorem monoid_hom.map_iterate_frobenius (n : ℕ) : f (frobenius R p^[n] x) = (frobenius S p^[n] (f x)) := function.semiconj.iterate_right (f.map_frobenius p) n x theorem ring_hom.map_iterate_frobenius (n : ℕ) : g (frobenius R p^[n] x) = (frobenius S p^[n] (g x)) := g.to_monoid_hom.map_iterate_frobenius p x n theorem monoid_hom.iterate_map_frobenius (f : R →* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ theorem ring_hom.iterate_map_frobenius (f : R →+* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ variable (R) theorem frobenius_zero : frobenius R p 0 = 0 := (frobenius R p).map_zero theorem frobenius_add : frobenius R p (x + y) = frobenius R p x + frobenius R p y := (frobenius R p).map_add x y theorem frobenius_neg : frobenius R p (-x) = -frobenius R p x := (frobenius R p).map_neg x theorem frobenius_sub : frobenius R p (x - y) = frobenius R p x - frobenius R p y := (frobenius R p).map_sub x y theorem frobenius_nat_cast (n : ℕ) : frobenius R p n = n := (frobenius R p).map_nat_cast n end frobenius theorem frobenius_inj (α : Type u) [integral_domain α] (p : ℕ) [fact p.prime] [char_p α p] : function.injective (frobenius α p) := λ x h H, by { rw ← sub_eq_zero at H ⊢, rw ← frobenius_sub at H, exact pow_eq_zero H } namespace char_p section variables (α : Type u) [ring α] lemma char_p_to_char_zero [char_p α 0] : char_zero α := char_zero_of_inj_zero $ λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff α 0 n).mp h0) lemma cast_eq_mod (p : ℕ) [char_p α p] (k : ℕ) : (k : α) = (k % p : ℕ) := calc (k : α) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div] ... = ↑(k % p) : by simp[cast_eq_zero] theorem char_ne_zero_of_fintype (p : ℕ) [hc : char_p α p] [fintype α] : p ≠ 0 := assume h : p = 0, have char_zero α := @char_p_to_char_zero α _ (h ▸ hc), absurd (@nat.cast_injective α _ _ this) (not_injective_infinite_fintype coe) end section integral_domain open nat variables (α : Type u) [integral_domain α] theorem char_ne_one (p : ℕ) [hc : char_p α p] : p ≠ 1 := assume hp : p = 1, have ( 1 : α) = 0, by simpa using (cast_eq_zero_iff α p 1).mpr (hp ▸ dvd_refl p), absurd this one_ne_zero theorem char_is_prime_of_two_le (p : ℕ) [hc : char_p α p] (hp : 2 ≤ p) : nat.prime p := suffices ∀d ∣ p, d = 1 ∨ d = p, from ⟨hp, this⟩, assume (d : ℕ) (hdvd : ∃ e, p = d * e), let ⟨e, hmul⟩ := hdvd in have (p : α) = 0, from (cast_eq_zero_iff α p p).mpr (dvd_refl p), have (d : α) * e = 0, from (@cast_mul α _ d e) ▸ (hmul ▸ this), or.elim (eq_zero_or_eq_zero_of_mul_eq_zero this) (assume hd : (d : α) = 0, have p ∣ d, from (cast_eq_zero_iff α p d).mp hd, show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this)) (assume he : (e : α) = 0, have p ∣ e, from (cast_eq_zero_iff α p e).mp he, have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul), have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›, have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1), have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul, show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this)) theorem char_is_prime_or_zero (p : ℕ) [hc : char_p α p] : nat.prime p ∨ p = 0 := match p, hc with | 0, _ := or.inr rfl | 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one α _ (1 : ℕ) hc) | (m+2), hc := or.inl (@char_is_prime_of_two_le α _ (m+2) hc (nat.le_add_left 2 m)) end lemma char_is_prime_of_pos (p : ℕ) [h : fact (0 < p)] [char_p α p] : fact p.prime := (char_p.char_is_prime_or_zero α _).resolve_right (nat.pos_iff_ne_zero.1 h) theorem char_is_prime [fintype α] (p : ℕ) [char_p α p] : p.prime := or.resolve_right (char_is_prime_or_zero α p) (char_ne_zero_of_fintype α p) end integral_domain section char_one variables {R : Type*} @[priority 100] -- see Note [lower instance priority] instance [semiring R] [char_p R 1] : subsingleton R := subsingleton.intro $ suffices ∀ (r : R), r = 0, from assume a b, show a = b, by rw [this a, this b], assume r, calc r = 1 * r : by rw one_mul ... = (1 : ℕ) * r : by rw nat.cast_one ... = 0 * r : by rw char_p.cast_eq_zero ... = 0 : by rw zero_mul lemma false_of_nontrivial_of_char_one [semiring R] [nontrivial R] [char_p R 1] : false := false_of_nontrivial_of_subsingleton R lemma ring_char_ne_one [semiring R] [nontrivial R] : ring_char R ≠ 1 := by { intros h, apply @zero_ne_one R, symmetry, rw [←nat.cast_one, ring_char.spec, h], } lemma nontrivial_of_char_ne_one {v : ℕ} (hv : v ≠ 1) {R : Type*} [semiring R] [hr : char_p R v] : nontrivial R := ⟨⟨(1 : ℕ), 0, λ h, hv $ by rwa [char_p.cast_eq_zero_iff _ v, nat.dvd_one] at h; assumption ⟩⟩ end char_one end char_p section variables (n : ℕ) (R : Type*) [comm_ring R] [fintype R] lemma char_p_of_ne_zero (hn : fintype.card R = n) (hR : ∀ i < n, (i : R) = 0 → i = 0) : char_p R n := { cast_eq_zero_iff := begin have H : (n : R) = 0, by { rw [← hn, char_p.cast_card_eq_zero] }, intro k, split, { intro h, rw [← nat.mod_add_div k n, nat.cast_add, nat.cast_mul, H, zero_mul, add_zero] at h, rw nat.dvd_iff_mod_eq_zero, apply hR _ (nat.mod_lt _ _) h, rw [← hn, gt, fintype.card_pos_iff], exact ⟨0⟩, }, { rintro ⟨k, rfl⟩, rw [nat.cast_mul, H, zero_mul] } end } lemma char_p_of_prime_pow_injective (p : ℕ) [hp : fact p.prime] (n : ℕ) (hn : fintype.card R = p ^ n) (hR : ∀ i ≤ n, (p ^ i : R) = 0 → i = n) : char_p R (p ^ n) := begin obtain ⟨c, hc⟩ := char_p.exists R, resetI, have hcpn : c ∣ p ^ n, { rw [← char_p.cast_eq_zero_iff R c, ← hn, char_p.cast_card_eq_zero], }, obtain ⟨i, hi, hc⟩ : ∃ i ≤ n, c = p ^ i, by rwa nat.dvd_prime_pow hp at hcpn, obtain rfl : i = n, { apply hR i hi, rw [← nat.cast_pow, ← hc, char_p.cast_eq_zero] }, rwa ← hc end end
3d6e8d0ac8cdf61f039e2f8d893f88716cd1c5bb
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/20170218-monoidal-category-of-types.lean
ffdc01b846667fff0bfea258d4f1902d47665610
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
15,872
lean
open tactic open smt_tactic def pointwise_attribute : user_attribute := { name := `pointwise, descr := "A lemma that proves things are equal using the fact they are pointwise equal." } run_command attribute.register `pointwise_attribute /- Try to apply one of the given lemas, it succeeds if one of them succeeds. -/ meta def any_apply : list name → tactic unit | [] := failed | (c::cs) := (mk_const c >>= fapply) <|> any_apply cs meta def smt_simp : tactic unit := using_smt $ intros >> try simp meta def smt_eblast : tactic unit := using_smt $ intros >> try simp >> try eblast meta def smt_ematch : tactic unit := using_smt $ intros >> add_lemmas_from_facts >> try ematch meta def pointwise (and_then : tactic unit) : tactic unit := do cs ← attribute.get_instances `pointwise, try (seq (any_apply cs) and_then) attribute [pointwise] funext meta def blast : tactic unit := smt_eblast >> pointwise blast -- In a timing test on 2017-02-18, I found that using `abstract { blast }` instead of just `blast` resulted in a 5x speed-up! notation `♮` := by abstract { blast } @[pointwise] lemma {u v} pair_equality {α : Type u} {β : Type v} { X: α × β }: (X^.fst, X^.snd) = X := begin induction X, blast end @[pointwise] lemma {u v} pair_equality_1 {α : Type u} {β : Type v} { X: α × β } { A : α } ( p : A = X^.fst ) : (A, X^.snd) = X := begin induction X, blast end @[pointwise] lemma {u v} pair_equality_2 {α : Type u} {β : Type v} { X: α × β } { B : β } ( p : B = X^.snd ) : (X^.fst, B) = X := begin induction X, blast end attribute [pointwise] subtype.eq def {u} auto_cast {α β : Type u} {h : α = β} (a : α) := cast h a @[simp] lemma {u} auto_cast_identity {α : Type u} (a : α) : @auto_cast α α (by smt_ematch) a = a := ♮ notation `⟦` p `⟧` := @auto_cast _ _ (by smt_ematch) p universe variables u v structure Category := (Obj : Type u) (Hom : Obj → Obj → Type v) (identity : Π X : Obj, Hom X X) (compose : Π { X Y Z : Obj }, Hom X Y → Hom Y Z → Hom X Z) (left_identity : ∀ { X Y : Obj } (f : Hom X Y), compose (identity _) f = f) (right_identity : ∀ { X Y : Obj } (f : Hom X Y), compose f (identity _) = f) (associativity : ∀ { W X Y Z : Obj } (f : Hom W X) (g : Hom X Y) (h : Hom Y Z), compose (compose f g) h = compose f (compose g h)) attribute [simp] Category.left_identity attribute [simp] Category.right_identity attribute [ematch] Category.associativity definition CategoryOfTypes : Category := { Obj := Type u, Hom := λ a b, a → b, identity := λ a, id, compose := λ _ _ _ f g, g ∘ f, left_identity := ♮, right_identity := ♮, associativity := ♮ } universe variables u1 v1 u2 v2 u3 v3 structure Functor (C : Category.{ u1 v1 }) (D : Category.{ u2 v2 }) := (onObjects : C^.Obj → D^.Obj) (onMorphisms : Π { X Y : C^.Obj }, C^.Hom X Y → D^.Hom (onObjects X) (onObjects Y)) (identities : ∀ (X : C^.Obj), onMorphisms (C^.identity X) = D^.identity (onObjects X)) (functoriality : ∀ { X Y Z : C^.Obj } (f : C^.Hom X Y) (g : C^.Hom Y Z), onMorphisms (C^.compose f g) = D^.compose (onMorphisms f) (onMorphisms g)) attribute [simp] Functor.identities attribute [simp] Functor.functoriality attribute [ematch] Functor.functoriality -- We define a coercion so that we can write `F X` for the functor `F` applied to the object `X`. -- One can still write out `onObjects F X` when needed. instance Functor_to_onObjects { C D : Category }: has_coe_to_fun (Functor C D) := { F := λ f, C^.Obj -> D^.Obj, coe := Functor.onObjects } definition IdentityFunctor ( C: Category ) : Functor C C := { onObjects := id, onMorphisms := λ _ _ f, f, identities := ♮, functoriality := ♮ } definition FunctorComposition { C D E : Category } ( F : Functor C D ) ( G : Functor D E ) : Functor C E := { onObjects := λ X, G (F X), onMorphisms := λ _ _ f, G^.onMorphisms (F^.onMorphisms f), identities := ♮, functoriality := ♮ } -- namespace Functor -- notation F `∘` G := FunctorComposition F G -- end Functor structure NaturalTransformation { C D : Category } ( F G : Functor C D ) := (components: Π X : C^.Obj, D^.Hom (F X) (G X)) (naturality: ∀ { X Y : C^.Obj } (f : C^.Hom X Y), D^.compose (F^.onMorphisms f) (components Y) = D^.compose (components X) (G^.onMorphisms f)) attribute [ematch] NaturalTransformation.naturality -- This defines a coercion so we can write `α X` for `components α X`. instance NaturalTransformation_to_components { C D : Category } { F G : Functor C D } : has_coe_to_fun (NaturalTransformation F G) := { F := λ f, Π X : C^.Obj, D^.Hom (F X) (G X), coe := NaturalTransformation.components } -- We'll want to be able to prove that two natural transformations are equal if they are componentwise equal. @[pointwise] lemma NaturalTransformations_componentwise_equal { C D : Category } { F G : Functor C D } ( α β : NaturalTransformation F G ) ( w : ∀ X : C^.Obj, α X = β X ) : α = β := begin induction α with αc, induction β with βc, have hc : αc = βc, from funext w, by subst hc end definition IdentityNaturalTransformation { C D : Category } (F : Functor C D) : NaturalTransformation F F := { components := λ X, D^.identity (F X), naturality := ♮ } definition vertical_composition_of_NaturalTransformations { C D : Category } { F G H : Functor C D } ( α : NaturalTransformation F G ) ( β : NaturalTransformation G H ) : NaturalTransformation F H := { components := λ X, D^.compose (α X) (β X), naturality := ♮ } definition horizontal_composition_of_NaturalTransformations { C D E : Category } { F G : Functor C D } { H I : Functor D E } ( α : NaturalTransformation F G ) ( β : NaturalTransformation H I ) : NaturalTransformation (FunctorComposition F H) (FunctorComposition G I) := { components := λ X : C^.Obj, E^.compose (β (F X)) (I^.onMorphisms (α X)), naturality := begin blast, unfold FunctorComposition, blast end } definition whisker_on_left { C D E : Category } ( F : Functor C D ) { G H : Functor D E } ( α : NaturalTransformation G H ) : NaturalTransformation (FunctorComposition F G) (FunctorComposition F H) := horizontal_composition_of_NaturalTransformations (IdentityNaturalTransformation F) α definition whisker_on_right { C D E : Category } { F G : Functor C D } ( α : NaturalTransformation F G ) ( H : Functor D E ) : NaturalTransformation (FunctorComposition F H) (FunctorComposition G H) := horizontal_composition_of_NaturalTransformations α (IdentityNaturalTransformation H) definition ProductCategory (C : Category.{u1 v1}) (D : Category.{u2 v2}) : Category := { Obj := C^.Obj × D^.Obj, Hom := (λ X Y : C^.Obj × D^.Obj, C^.Hom (X^.fst) (Y^.fst) × D^.Hom (X^.snd) (Y^.snd)), identity := λ X, (C^.identity (X^.fst), D^.identity (X^.snd)), compose := λ _ _ _ f g, (C^.compose (f^.fst) (g^.fst), D^.compose (f^.snd) (g^.snd)), left_identity := ♮, right_identity := ♮, associativity := ♮ } namespace ProductCategory notation C `×` D := ProductCategory C D end ProductCategory definition ProductFunctor { A B C D : Category } ( F : Functor A B ) ( G : Functor C D ) : Functor (A × C) (B × D) := { onObjects := λ X, (F X^.fst, G X^.snd), onMorphisms := λ _ _ f, (F^.onMorphisms f^.fst, G^.onMorphisms f^.snd), identities := begin blast, unfold ProductCategory, blast, end, functoriality := begin blast, unfold ProductCategory, blast end } namespace ProductFunctor notation F `×` G := ProductFunctor F G end ProductFunctor definition ProductNaturalTransformation { A B C D : Category } { F G : Functor A B } { H I : Functor C D } (α : NaturalTransformation F G) (β : NaturalTransformation H I) : NaturalTransformation (F × H) (G × I) := { components := λ X, (α X^.fst, β X^.snd), naturality := begin blast, unfold ProductFunctor, blast, unfold ProductCategory, blast end } namespace ProductNaturalTransformation notation α `×` β := ProductNaturalTransformation α β end ProductNaturalTransformation definition ProductCategoryAssociator ( C : Category.{ u1 v1 } ) ( D : Category.{ u2 v2 } ) ( E : Category.{ u3 v3 } ) : Functor ((C × D) × E) (C × (D × E)) := { onObjects := λ X, (X^.fst^.fst, (X^.fst^.snd, X^.snd)), onMorphisms := λ _ _ f, (f^.fst^.fst, (f^.fst^.snd, f^.snd)), identities := ♮, functoriality := ♮ } @[reducible] definition TensorProduct ( C: Category ) := Functor ( C × C ) C definition left_associated_triple_tensor ( C : Category.{ u v } ) ( tensor : TensorProduct C ) : Functor ((C × C) × C) C := FunctorComposition (tensor × IdentityFunctor C) tensor definition right_associated_triple_tensor ( C : Category.{ u v } ) ( tensor : TensorProduct C ) : Functor (C × (C × C)) C := FunctorComposition (IdentityFunctor C × tensor) tensor @[reducible] definition Associator { C : Category.{ u v } } ( tensor : TensorProduct C ) := NaturalTransformation (left_associated_triple_tensor C tensor) (FunctorComposition (ProductCategoryAssociator C C C) (right_associated_triple_tensor C tensor)) definition Pentagon { C : Category } { tensor : TensorProduct C } ( associator : Associator tensor ) := let α ( X Y Z : C^.Obj ) := associator ((X, Y), Z) in let tensorObjects ( X Y : C^.Obj ) := tensor^.onObjects (X, Y) in let tensorMorphisms { W X Y Z : C^.Obj } ( f : C^.Hom W X ) ( g : C^.Hom Y Z ) : C^.Hom (tensorObjects W Y) (tensorObjects X Z) := tensor^.onMorphisms (f, g) in ∀ W X Y Z : C^.Obj, C^.compose (α (tensorObjects W X) Y Z) (α W X (tensorObjects Y Z)) = C^.compose (C^.compose (tensorMorphisms (α W X Y) (C^.identity Z)) (α W (tensorObjects X Y) Z)) (tensorMorphisms (C^.identity W) (α X Y Z)) structure MonoidalCategory extends carrier : Category := (tensor : TensorProduct carrier) (associator_transformation : Associator tensor) (pentagon : Pentagon associator_transformation) instance MonoidalCategory_coercion : has_coe MonoidalCategory.{u v} Category.{u v} := ⟨MonoidalCategory.to_Category⟩ @[reducible] definition MonoidalCategory.tensorObjects ( C : MonoidalCategory ) ( X Y : C^.Obj ) : C^.Obj := C^.tensor (X, Y) @[reducible] definition MonoidalCategory.tensorMorphisms ( C : MonoidalCategory ) { W X Y Z : C^.Obj } ( f : C^.Hom W X ) ( g : C^.Hom Y Z ) : C^.Hom (C^.tensor (W, Y)) (C^.tensor (X, Z)) := C^.tensor^.onMorphisms (f, g) @[ematch] definition MonoidalCategory.interchange ( C : MonoidalCategory ) { U V W X Y Z: C^.Obj } ( f : C^.Hom U V )( g : C^.Hom V W )( h : C^.Hom X Y )( k : C^.Hom Y Z ) : @Functor.onMorphisms _ _ C^.tensor (U, X) (W, Z) ((C^.compose f g), (C^.compose h k)) = C^.compose (@Functor.onMorphisms _ _ C^.tensor (U, X) (V, Y) (f, h)) (@Functor.onMorphisms _ _ C^.tensor (V, Y) (W, Z) (g, k)) := @Functor.functoriality (C × C) C C^.tensor (U, X) (V, Y) (W, Z) (f, h) (g, k) definition TensorProductOfTypes : TensorProduct CategoryOfTypes := { onObjects := λ p, prod p.1 p.2, onMorphisms := λ _ _ p, λ q, (p.1 q.1, p.2 q.2), identities := ♮, functoriality := ♮ } definition MonoidalCategoryOfTypes : MonoidalCategory := { CategoryOfTypes with tensor := TensorProductOfTypes, associator_transformation := { components := λ p, λ t, (t.1.1,(t.1.2, t.2)), naturality := ♮ }, pentagon := begin blast, unfold Pentagon, blast end } local attribute [reducible] lift_t coe_t coe_b @[simp] lemma bifunctor_identities { C D E : Category } ( X : C^.Obj ) ( Y : D^.Obj ) ( F : Functor (C × D) E ) : @Functor.onMorphisms _ _ F (X, Y) (X, Y) (C^.identity X, D^.identity Y) = E^.identity (F^.onObjects (X, Y)) := begin blast, assert p : (C^.identity X, D^.identity Y) = (C × D)^.identity (X, Y), blast, rewrite p, blast end set_option pp.implicit true definition tensor_on_left { C: MonoidalCategory.{u v} } ( Z: C^.Obj ) : Functor.{u v u v} C C := { onObjects := λ X, C^.tensorObjects Z X, onMorphisms := λ X Y f, C^.tensorMorphisms (C^.identity Z) f, identities := ♮, functoriality := begin blast, -- TODO I'd hope the blast could just do these steps: interchange has [ematch], and left_identity has [simp]. rewrite - C^.interchange, rewrite C^.left_identity end } -- @[reducible] definition pentagon_3step_1 ( C : MonoidalCategory.{ u v } ) := -- let α := C^.associator_transformation in -- whisker_on_right -- (α × IdentityNaturalTransformation (IdentityFunctor C)) -- C^.tensor -- @[reducible] definition pentagon_3step_2 ( C : MonoidalCategory.{ u v } ) := -- let α := C^.associator_transformation in -- whisker_on_left -- (FunctorComposition -- (ProductCategoryAssociator C C C × IdentityFunctor C) -- ((IdentityFunctor C × C^.tensor) × IdentityFunctor C)) -- α -- @[reducible] definition pentagon_3step_3 ( C : MonoidalCategory.{ u v } ) := -- let α := C^.associator_transformation in -- whisker_on_left -- (FunctorComposition -- (ProductCategoryAssociator C C C × IdentityFunctor C) -- (ProductCategoryAssociator C (C × C) C)) -- (whisker_on_right -- (IdentityNaturalTransformation (IdentityFunctor C) × α) -- C^.tensor) -- @[reducible] definition pentagon_3step ( C : MonoidalCategory.{ u v } ) := -- vertical_composition_of_NaturalTransformations -- (vertical_composition_of_NaturalTransformations -- (pentagon_3step_1 C) -- (pentagon_3step_2 C)) -- (pentagon_3step_3 C) -- @[reducible] definition pentagon_2step_1 ( C : MonoidalCategory.{ u v } ) := -- let α := C^.associator_transformation in -- whisker_on_left -- ((C^.tensor × IdentityFunctor C) × IdentityFunctor C) -- α -- @[reducible] definition pentagon_2step_2 ( C : MonoidalCategory.{ u v } ) := -- let α := C^.associator_transformation in -- whisker_on_left -- (FunctorComposition -- (ProductCategoryAssociator (C × C) C C) -- (IdentityFunctor (C × C) × C^.tensor)) -- α -- @[reducible] definition pentagon_2step ( C : MonoidalCategory.{ u v } ) := -- vertical_composition_of_NaturalTransformations -- (pentagon_2step_1 C) -- (pentagon_2step_2 C) -- -- adding these attributes increased compile time from 1.5 minutes to 13 minutes. :-( -- -- attribute [simp] MonoidalCategory.left_identity -- -- attribute [simp] MonoidalCategory.right_identity -- lemma pentagon_in_terms_of_natural_transformations -- ( C : MonoidalCategory ) : -- pentagon_2step C = pentagon_3step C := -- begin -- blast, -- induction X with PQR S, -- induction PQR with PQ R, -- induction PQ with P Q, -- pose p := C^.pentagon P Q R S, -- -- notice that the hypothesis p is gross, until we blast! -- blast, -- -- I don't understand why this isn't being done by blast automatically: Functor.identities has [simp]. -- -- Moreover, I don't understand why `rewrite bifunctor_identities` doesn't apply here. -- repeat { rewrite C^.tensor^.identities <|> rewrite C^.left_identity <|> rewrite C^.right_identity }, -- blast -- end
bbe2b3b5460059ba64ae690b348c0df95433ee90
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/json_auto.lean
f3313b94cb64dc63b9b6380143315667c3d615b0
[]
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
280
lean
/- Copyright (c) E.W.Ayers 2020. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: E.W.Ayers -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.default import Mathlib.Lean3Lib.init.meta.float namespace Mathlib end Mathlib
bca009c5e889df231a102012c2e3d1de6d20ad25
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/tests/lean/run/u_eq_max_u_v.lean
7cb20d7105c2823d3a677ba3f02eabffe3483e1a
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,039
lean
universe variables u v u1 u2 v1 v2 set_option pp.universes true open smt_tactic meta def blast : tactic unit := using_smt $ intros >> add_lemmas_from_facts >> repeat_at_most 3 ematch notation `♮` := by blast structure semigroup_morphism { α β : Type u } ( s : semigroup α ) ( t: semigroup β ) := (map: α → β) (multiplicative : ∀ x y : α, map(x * y) = map(x) * map(y)) attribute [simp] semigroup_morphism.multiplicative instance semigroup_morphism_to_map { α β : Type u } { s : semigroup α } { t: semigroup β } : has_coe_to_fun (semigroup_morphism s t) := { F := λ f, Π x : α, β, coe := semigroup_morphism.map } @[reducible] definition semigroup_identity { α : Type u } ( s: semigroup α ) : semigroup_morphism s s := ⟨ id, ♮ ⟩ @[reducible] definition semigroup_morphism_composition { α β γ : Type u } { s: semigroup α } { t: semigroup β } { u: semigroup γ} ( f: semigroup_morphism s t ) ( g: semigroup_morphism t u ) : semigroup_morphism s u := { map := λ x, g (f x), multiplicative := begin blast, simp end } @[reducible] definition semigroup_product { α β : Type u } ( s : semigroup α ) ( t: semigroup β ) : semigroup (α × β) := { mul := λ p q, (p^.fst * q^.fst, p^.snd * q^.snd), mul_assoc := begin intros, simp [@mul.equations._eqn_1 (α × β)] end } definition semigroup_morphism_product { α β γ δ : Type u } { s_f : semigroup α } { s_g: semigroup β } { t_f : semigroup γ} { t_g: semigroup δ } ( f : semigroup_morphism s_f t_f ) ( g : semigroup_morphism s_g t_g ) : semigroup_morphism (semigroup_product s_f s_g) (semigroup_product t_f t_g) := { map := λ p, (f p.1, g p.2), multiplicative := begin -- cf https://groups.google.com/d/msg/lean-user/bVs5FdjClp4/tfHiVjLIBAAJ intros, unfold mul has_mul.mul, dsimp, simp end } structure Category := (Obj : Type u) (Hom : Obj → Obj → Type v) structure Functor (C : Category.{ u1 v1 }) (D : Category.{ u2 v2 }) := (onObjects : C^.Obj → D^.Obj) (onMorphisms : Π { X Y : C^.Obj }, C^.Hom X Y → D^.Hom (onObjects X) (onObjects Y)) @[reducible] definition ProductCategory (C : Category) (D : Category) : Category := { Obj := C^.Obj × D^.Obj, Hom := (λ X Y : C^.Obj × D^.Obj, C^.Hom (X^.fst) (Y^.fst) × D^.Hom (X^.snd) (Y^.snd)) } namespace ProductCategory notation C `×` D := ProductCategory C D end ProductCategory structure PreMonoidalCategory extends carrier : Category := (tensor : Functor (carrier × carrier) carrier) definition CategoryOfSemigroups : Category := { Obj := Σ α : Type u, semigroup α, Hom := λ s t, semigroup_morphism s.2 t.2 } definition PreMonoidalCategoryOfSemigroups : PreMonoidalCategory := { CategoryOfSemigroups with tensor := { onObjects := λ p, sigma.mk (p.1.1 × p.2.1) (semigroup_product p.1.2 p.2.2), onMorphisms := λ s t f, semigroup_morphism_product f.1 f.2 } }
c4a86a336edbf9284de64b929ac831b7ba6baf69
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_cc_heq9.lean
bf3818592b1fbb7b606c55569bbcf90a813ea511
[ "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
486
lean
open subtype set_option blast.strategy "cc" example (f g : Π {A : Type₁}, A → A → A) (h : nat → nat) (a b : nat) : h = f a → h b = f a b := by blast example (f g : Π {A : Type₁}, A → A → A) (h : nat → nat) (a b : nat) : h = f a → h b = f a b := by blast example (f g : Π {A : Type₁} (a b : A), {x : A | x ≠ b}) (h : Π (b : nat), {x : nat | x ≠ b}) (a b₁ b₂ : nat) : h = f a → b₁ = b₂ → h b₁ == f a b₂ := by blast
6ea519230817e40affb528f44cc13b295e46ad3a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Tactic/Rename.lean
ce92193ab341698778622833250158c93813908e
[ "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
868
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Util namespace Lean.Meta /-- Rename the user-face naming for the free variable `fvarId` at `mvarId`. -/ def _root_.Lean.MVarId.rename (mvarId : MVarId) (fvarId : FVarId) (userNameNew : Name) : MetaM MVarId := mvarId.withContext do mvarId.checkNotAssigned `rename let lctxNew := (← getLCtx).setUserName fvarId userNameNew let mvarNew ← mkFreshExprMVarAt lctxNew (← getLocalInstances) (← mvarId.getType) MetavarKind.syntheticOpaque (← mvarId.getTag) mvarId.assign mvarNew return mvarNew.mvarId! @[deprecated MVarId.rename] def rename (mvarId : MVarId) (fvarId : FVarId) (newUserName : Name) : MetaM MVarId := mvarId.rename fvarId newUserName end Lean.Meta
cc367e9ef66ee12bdec4b00c67ab63c0717926fb
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Elab/Tactic/Injection.lean
e27ac153640c0d983586e307c6b2e1c288dbab70
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
1,591
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Injection import Lean.Elab.Tactic.ElabTerm namespace Lean.Elab.Tactic -- optional (" with " >> many1 ident') private def getInjectionNewIds (stx : Syntax) : List Name := if stx.isNone then [] else stx[1].getArgs.toList.map getNameOfIdent' private def checkUnusedIds (tacticName : Name) (mvarId : MVarId) (unusedIds : List Name) : MetaM Unit := unless unusedIds.isEmpty do Meta.throwTacticEx tacticName mvarId m!"too many identifiers provided, unused: {unusedIds}" @[builtinTactic «injection»] def evalInjection : Tactic := fun stx => do -- leading_parser nonReservedSymbol "injection " >> termParser >> withIds let fvarId ← elabAsFVar stx[1] let ids := getInjectionNewIds stx[2] liftMetaTactic fun mvarId => do match (← Meta.injection mvarId fvarId ids) with | .solved => checkUnusedIds `injection mvarId ids; return [] | .subgoal mvarId' _ unusedIds => checkUnusedIds `injection mvarId unusedIds; return [mvarId'] @[builtinTactic «injections»] def evalInjections : Tactic := fun stx => do let ids := stx[1].getArgs.toList.map getNameOfIdent' liftMetaTactic fun mvarId => do match (← Meta.injections mvarId ids) with | .solved => checkUnusedIds `injections mvarId ids; return [] | .subgoal mvarId' unusedIds => checkUnusedIds `injections mvarId unusedIds; return [mvarId'] end Lean.Elab.Tactic
7f41809465bf6e2950a94dad4ffd51e7274a17f5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/derive_inhabited.lean
3ebcb756f891962544b7c77d2198d7a1d49451cc
[ "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,365
lean
/- Copyright (c) 2020 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import logic.basic import data.rbmap.basic /-! # Derive handler for `inhabited` instances This file introduces a derive handler to automatically generate `inhabited` instances for structures and inductives. We also add various `inhabited` instances for types in the core library. -/ namespace tactic /-- Tries to derive an `inhabited` instance for inductives and structures. For example: ``` @[derive inhabited] structure foo := (a : ℕ := 42) (b : list ℕ) ``` Here, `@[derive inhabited]` adds the instance `foo.inhabited`, which is defined as `⟨⟨42, default⟩⟩`. For inductives, the default value is the first constructor. If the structure/inductive has a type parameter `α`, then the generated instance will have an argument `inhabited α`, even if it is not used. (This is due to the implementation using `instance_derive_handler`.) -/ @[derive_handler] meta def inhabited_instance : derive_handler := instance_derive_handler ``inhabited $ do applyc ``inhabited.mk, `[refine {..}] <|> (constructor >> skip), all_goals' $ do applyc ``default <|> (do s ← read, fail $ to_fmt "could not find inhabited instance for:\n" ++ to_fmt s) end tactic attribute [derive inhabited] vm_decl_kind vm_obj_kind tactic.new_goals tactic.transparency tactic.apply_cfg smt_pre_config ematch_config cc_config smt_config rsimp.config tactic.dunfold_config tactic.dsimp_config tactic.unfold_proj_config tactic.simp_intros_config tactic.delta_config tactic.simp_config tactic.rewrite_cfg interactive.loc tactic.unfold_config param_info subsingleton_info fun_info format.color pos environment.projection_info reducibility_hints congr_arg_kind ulift plift string_imp string.iterator_imp rbnode.color ordering unification_constraint pprod unification_hint doc_category tactic_doc_entry instance {α} : inhabited (bin_tree α) := ⟨bin_tree.empty⟩ instance : inhabited unsigned := ⟨0⟩ instance : inhabited string.iterator := string.iterator_imp.inhabited instance {α} : inhabited (rbnode α) := ⟨rbnode.leaf⟩ instance {α lt} : inhabited (rbtree α lt) := ⟨mk_rbtree _ _⟩ instance {α β lt} : inhabited (rbmap α β lt) := ⟨mk_rbmap _ _ _⟩
134be8008bccbde3d10570ce49ebca301e51bf4b
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/fin/default.lean
e4c86974d43fb38a70a3cf606459d6e849eb6222
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,608
lean
import galois.tactic galois.nat.simplify_le def nat_to_fin_option (k n : ℕ) : option (fin k) := if H : n < k then some ⟨ _, H ⟩ else none namespace fin lemma fin_0_empty (x : fin 0) : false := begin induction x, apply nat.lt_irrefl, apply lt_of_le_of_lt, tactic.swap, assumption, apply nat.zero_le, end lemma val_inj {n : ℕ} (i j : fin n) (H : i.val = j.val) : i = j := begin induction i, induction j, dsimp at H, induction H, reflexivity, end lemma succ_pred_id {k : ℕ} (i : fin k.succ) (H : i ≠ 0) : fin.succ (fin.pred i H) = i := begin induction i, dsimp [fin.pred, fin.succ], cases val, exfalso, apply H, unfold has_zero.zero, dsimp [nat.pred], reflexivity, end lemma succ_pred_equiv {k : ℕ} (i : fin k.succ) (H : i ≠ 0) (n : ℕ) : (i.val = nat.succ n) ↔ ((fin.pred i H).val = n) := begin induction i, dsimp [fin.pred], cases val, exfalso, apply H, unfold has_zero.zero, dsimp [nat.pred], split; intros H', injection H', subst H', end end fin lemma nat_to_fin_option_pred_none {n i : ℕ} : nat_to_fin_option n.succ i.succ = none → nat_to_fin_option n i = none := begin unfold nat_to_fin_option, apply (if Hlt : i.succ < n.succ then _ else _), { rw (dif_pos Hlt), intros H, contradiction, }, { rw (dif_neg Hlt), intros H', clear H', have H : ¬ (i < n), intros contra, apply Hlt, apply nat.succ_lt_succ, assumption, rw (dif_neg H), } end lemma nat_to_fin_option_succ_nz {n k : ℕ} {i : fin n.succ} : nat_to_fin_option n.succ k.succ = some i → i ≠ 0 := begin dsimp [nat_to_fin_option], apply (if H : (nat.succ k < nat.succ n) then _ else _), { rw (dif_pos H), intros H', injection H' with H'', clear H', intros contra, subst i, injection contra, injection h_1, }, { rw (dif_neg H), intros contra, contradiction, } end lemma nat_to_fin_option_pred_some {n k : ℕ} (i : fin n.succ) : ∀ H : nat_to_fin_option n.succ k.succ = some i , nat_to_fin_option n k = some (i.pred (nat_to_fin_option_succ_nz H)) := begin dsimp [nat_to_fin_option], intros H, apply (if H' : (nat.succ k < nat.succ n) then _ else _), { rw (dif_pos H') at H, injection H with H2, clear H, rw nat.succ_lt_succ_iff at H', rename H' H'1, rw (dif_pos H'1), f_equal, subst i, dsimp [fin.pred], reflexivity, }, { rw (dif_neg H') at H, contradiction, } end lemma nat_to_fin_option_val {n k : ℕ} {i : fin n} (H : nat_to_fin_option n k = some i) : i.val = k := begin dsimp [nat_to_fin_option] at H, apply (if H' : k < n then _ else _), { rw (dif_pos H') at H, injection H with H2, clear H, subst i, }, { rw (dif_neg H') at H, contradiction } end
c1af855efc036668d01ad49b3bd369d2a491016a
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/list/of_fn.lean
5197f8bb9c1b6d8d8d74a4f56d4f6687e5fc746d
[ "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
6,109
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.fin.basic import data.list.basic import data.list.join /-! # Lists from functions Theorems and lemmas for dealing with `list.of_fn`, which converts a function on `fin n` to a list of length `n`. ## Main Statements The main statements pertain to lists generated using `of_fn` - `list.length_of_fn`, which tells us the length of such a list - `list.nth_of_fn`, which tells us the nth element of such a list - `list.array_eq_of_fn`, which interprets the list form of an array as such a list. -/ universes u variables {α : Type u} open nat namespace list lemma length_of_fn_aux {n} (f : fin n → α) : ∀ m h l, length (of_fn_aux f m h l) = length l + m | 0 h l := rfl | (succ m) h l := (length_of_fn_aux m _ _).trans (succ_add _ _) /-- The length of a list converted from a function is the size of the domain. -/ @[simp] theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n := (length_of_fn_aux f _ _ _).trans (zero_add _) lemma nth_of_fn_aux {n} (f : fin n → α) (i) : ∀ m h l, (∀ i, nth l i = of_fn_nth_val f (i + m)) → nth (of_fn_aux f m h l) i = of_fn_nth_val f i | 0 h l H := H i | (succ m) h l H := nth_of_fn_aux m _ _ begin intro j, cases j with j, { simp only [nth, of_fn_nth_val, zero_add, dif_pos (show m < n, from h)] }, { simp only [nth, H, add_succ, succ_add] } end /-- The `n`th element of a list -/ @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = of_fn_nth_val f i := nth_of_fn_aux f _ _ _ _ $ λ i, by simp only [of_fn_nth_val, dif_neg (not_lt.2 (nat.le_add_left n i))]; refl theorem nth_le_of_fn {n} (f : fin n → α) (i : fin n) : nth_le (of_fn f) i ((length_of_fn f).symm ▸ i.2) = f i := option.some.inj $ by rw [← nth_le_nth]; simp only [list.nth_of_fn, of_fn_nth_val, fin.eta, dif_pos i.is_lt] @[simp] theorem nth_le_of_fn' {n} (f : fin n → α) {i : ℕ} (h : i < (of_fn f).length) : nth_le (of_fn f) i h = f ⟨i, ((length_of_fn f) ▸ h)⟩ := nth_le_of_fn f ⟨i, ((length_of_fn f) ▸ h)⟩ @[simp] lemma map_of_fn {β : Type*} {n : ℕ} (f : fin n → α) (g : α → β) : map g (of_fn f) = of_fn (g ∘ f) := ext_le (by simp) (λ i h h', by simp) /-- Arrays converted to lists are the same as `of_fn` on the indexing function of the array. -/ theorem array_eq_of_fn {n} (a : array n α) : a.to_list = of_fn a.read := suffices ∀ {m h l}, d_array.rev_iterate_aux a (λ i, cons) m h l = of_fn_aux (d_array.read a) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, simp only [d_array.rev_iterate_aux, of_fn_aux, IH] end @[congr] theorem of_fn_congr {m n : ℕ} (h : m = n) (f : fin m → α) : of_fn f = of_fn (λ i : fin n, f (fin.cast h.symm i)) := begin subst h, simp_rw [fin.cast_refl, order_iso.refl_apply], end /-- `of_fn` on an empty domain is the empty list. -/ @[simp] theorem of_fn_zero (f : fin 0 → α) : of_fn f = [] := rfl @[simp] theorem of_fn_succ {n} (f : fin (succ n) → α) : of_fn f = f 0 :: of_fn (λ i, f i.succ) := suffices ∀ {m h l}, of_fn_aux f (succ m) (succ_le_succ h) l = f 0 :: of_fn_aux (λ i, f i.succ) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, rw [of_fn_aux, IH], refl end theorem of_fn_succ' {n} (f : fin (succ n) → α) : of_fn f = (of_fn (λ i, f i.cast_succ)).concat (f (fin.last _)) := begin induction n with n IH, { rw [of_fn_zero, concat_nil, of_fn_succ, of_fn_zero], refl }, { rw [of_fn_succ, IH, of_fn_succ, concat_cons, fin.cast_succ_zero], congr' 3, simp_rw [fin.cast_succ_fin_succ], } end /-- Note this matches the convention of `list.of_fn_succ'`, putting the `fin m` elements first. -/ theorem of_fn_add {m n} (f : fin (m + n) → α) : list.of_fn f = list.of_fn (λ i, f (fin.cast_add n i)) ++ list.of_fn (λ j, f (fin.nat_add m j)) := begin induction n with n IH, { rw [of_fn_zero, append_nil, fin.cast_add_zero, fin.cast_refl], refl }, { rw [of_fn_succ', of_fn_succ', IH, append_concat], refl, }, end /-- This breaks a list of `m*n` items into `m` groups each containing `n` elements. -/ theorem of_fn_mul {m n} (f : fin (m * n) → α) : list.of_fn f = list.join (list.of_fn $ λ i : fin m, list.of_fn $ λ j : fin n, f ⟨i * n + j, calc ↑i * n + j < (i + 1) *n : (add_lt_add_left j.prop _).trans_eq (add_one_mul _ _).symm ... ≤ _ : nat.mul_le_mul_right _ i.prop⟩) := begin induction m with m IH, { simp_rw [of_fn_zero, zero_mul, of_fn_zero, join], }, { simp_rw [of_fn_succ', succ_mul, join_concat, of_fn_add, IH], refl, }, end /-- This breaks a list of `m*n` items into `n` groups each containing `m` elements. -/ theorem of_fn_mul' {m n} (f : fin (m * n) → α) : list.of_fn f = list.join (list.of_fn $ λ i : fin n, list.of_fn $ λ j : fin m, f ⟨m * i + j, calc m * i + j < m * (i + 1) : (add_lt_add_left j.prop _).trans_eq (mul_add_one _ _).symm ... ≤ _ : nat.mul_le_mul_left _ i.prop⟩) := by simp_rw [mul_comm m n, mul_comm m, of_fn_mul, fin.cast_mk] theorem of_fn_nth_le : ∀ l : list α, of_fn (λ i, nth_le l i i.2) = l | [] := rfl | (a::l) := by { rw of_fn_succ, congr, simp only [fin.coe_succ], exact of_fn_nth_le l } -- not registered as a simp lemma, as otherwise it fires before `forall_mem_of_fn_iff` which -- is much more useful lemma mem_of_fn {n} (f : fin n → α) (a : α) : a ∈ of_fn f ↔ a ∈ set.range f := begin simp only [mem_iff_nth_le, set.mem_range, nth_le_of_fn'], exact ⟨λ ⟨i, hi, h⟩, ⟨_, h⟩, λ ⟨i, hi⟩, ⟨i.1, (length_of_fn f).symm ▸ i.2, by simpa using hi⟩⟩ end @[simp] lemma forall_mem_of_fn_iff {n : ℕ} {f : fin n → α} {P : α → Prop} : (∀ i ∈ of_fn f, P i) ↔ ∀ j : fin n, P (f j) := by simp only [mem_of_fn, set.forall_range_iff] @[simp] lemma of_fn_const (n : ℕ) (c : α) : of_fn (λ i : fin n, c) = repeat c n := nat.rec_on n (by simp) $ λ n ihn, by simp [ihn] end list
4b38978e04631a147a62e21e9bd35c64d5d9ec23
94e33a31faa76775069b071adea97e86e218a8ee
/src/order/lattice_intervals.lean
47257e7c0cc237825aab36ae6e4bd990feec51cb
[ "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
4,942
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.bounds /-! # Intervals in Lattices In this file, we provide instances of lattice structures on intervals within lattices. Some of them depend on the order of the endpoints of the interval, and thus are not made global instances. These are probably not all of the lattice instances that could be placed on these intervals, but more can be added easily along the same lines when needed. ## Main definitions In the following, `*` can represent either `c`, `o`, or `i`. * `set.Ic*.order_bot` * `set.Ii*.semillatice_inf` * `set.I*c.order_top` * `set.I*c.semillatice_inf` * `set.I**.lattice` * `set.Iic.bounded_order`, within an `order_bot` * `set.Ici.bounded_order`, within an `order_top` -/ variable {α : Type*} namespace set namespace Ico instance [semilattice_inf α] {a b : α} : semilattice_inf (Ico a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, lt_of_le_of_lt inf_le_left hx.2⟩) /-- `Ico a b` has a bottom element whenever `a < b`. -/ @[reducible] protected def order_bot [partial_order α] {a b : α} (h : a < b) : order_bot (Ico a b) := (is_least_Ico h).order_bot end Ico namespace Iio instance [semilattice_inf α] {a : α} : semilattice_inf (Iio a) := subtype.semilattice_inf (λ x y hx hy, lt_of_le_of_lt inf_le_left hx) end Iio namespace Ioc instance [semilattice_sup α] {a b : α} : semilattice_sup (Ioc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨lt_of_lt_of_le hx.1 le_sup_left, sup_le hx.2 hy.2⟩) /-- `Ioc a b` has a top element whenever `a < b`. -/ @[reducible] protected def order_top [partial_order α] {a b : α} (h : a < b) : order_top (Ioc a b) := (is_greatest_Ioc h).order_top end Ioc namespace Ioi instance [semilattice_sup α] {a : α} : semilattice_sup (Ioi a) := subtype.semilattice_sup (λ x y hx hy, lt_of_lt_of_le hx le_sup_left) end Ioi namespace Iic instance [semilattice_inf α] {a : α} : semilattice_inf (Iic a) := subtype.semilattice_inf (λ x y hx hy, le_trans inf_le_left hx) instance [semilattice_sup α] {a : α} : semilattice_sup (Iic a) := subtype.semilattice_sup (λ x y hx hy, sup_le hx hy) instance [lattice α] {a : α} : lattice (Iic a) := { .. Iic.semilattice_inf, .. Iic.semilattice_sup } instance [preorder α] {a : α} : order_top (Iic a) := { top := ⟨a, le_refl a⟩, le_top := λ x, x.prop } @[simp] lemma coe_top [preorder α] {a : α} : ↑(⊤ : Iic a) = a := rfl instance [preorder α] [order_bot α] {a : α} : order_bot (Iic a) := { bot := ⟨⊥, bot_le⟩, bot_le := λ ⟨_,_⟩, subtype.mk_le_mk.2 bot_le } @[simp] lemma coe_bot [preorder α] [order_bot α] {a : α} : ↑(⊥ : Iic a) = (⊥ : α) := rfl instance [preorder α] [order_bot α] {a : α} : bounded_order (Iic a) := { .. Iic.order_top, .. Iic.order_bot } end Iic namespace Ici instance [semilattice_inf α] {a : α}: semilattice_inf (Ici a) := subtype.semilattice_inf (λ x y hx hy, le_inf hx hy) instance [semilattice_sup α] {a : α} : semilattice_sup (Ici a) := subtype.semilattice_sup (λ x y hx hy, le_trans hx le_sup_left) instance [lattice α] {a : α} : lattice (Ici a) := { .. Ici.semilattice_inf, .. Ici.semilattice_sup } instance [preorder α] {a : α} : order_bot (Ici a) := { bot := ⟨a, le_refl a⟩, bot_le := λ x, x.prop } @[simp] lemma coe_bot [preorder α] {a : α} : ↑(⊥ : Ici a) = a := rfl instance [preorder α] [order_top α] {a : α}: order_top (Ici a) := { top := ⟨⊤, le_top⟩, le_top := λ ⟨_,_⟩, subtype.mk_le_mk.2 le_top } @[simp] lemma coe_top [preorder α] [order_top α] {a : α} : ↑(⊤ : Ici a) = (⊤ : α) := rfl instance [preorder α] [order_top α] {a : α}: bounded_order (Ici a) := { .. Ici.order_top, .. Ici.order_bot } end Ici namespace Icc instance [semilattice_inf α] {a b : α} : semilattice_inf (Icc a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, le_trans inf_le_left hx.2⟩) instance [semilattice_sup α] {a b : α} : semilattice_sup (Icc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨le_trans hx.1 le_sup_left, sup_le hx.2 hy.2⟩) instance [lattice α] {a b : α} : lattice (Icc a b) := { .. Icc.semilattice_inf, .. Icc.semilattice_sup } /-- `Icc a b` has a bottom element whenever `a ≤ b`. -/ @[reducible] protected def order_bot [preorder α] {a b : α} (h : a ≤ b) : order_bot (Icc a b) := (is_least_Icc h).order_bot /-- `Icc a b` has a top element whenever `a ≤ b`. -/ @[reducible] protected def order_top [preorder α] {a b : α} (h : a ≤ b) : order_top (Icc a b) := (is_greatest_Icc h).order_top /-- `Icc a b` is a `bounded_order` whenever `a ≤ b`. -/ @[reducible] protected def bounded_order [preorder α] {a b : α} (h : a ≤ b) : bounded_order (Icc a b) := { .. Icc.order_top h, .. Icc.order_bot h } end Icc end set
251d453f386d22696e87db898c8849b9ff7381b7
1fd908b06e3f9c1252cb2285ada1102623a67f72
/types/pullback.lean
faa2a8bcce00aa19fa553b5674a6e084bd07b604
[ "Apache-2.0" ]
permissive
avigad/hott3
609a002849182721e7c7ae536d9f1e2956d6d4d3
f64750cd2de7a81e87d4828246d1369d59f16f43
refs/heads/master
1,629,027,243,322
1,510,946,717,000
1,510,946,717,000
103,570,461
0
0
null
1,505,415,620,000
1,505,415,620,000
null
UTF-8
Lean
false
false
6,304
lean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about pullbacks -/ import cubical.square universes u v w hott_theory namespace hott open hott.eq hott.equiv hott.is_equiv function hott.prod unit is_trunc hott.sigma variables {A₀₀ : Type _} {A₂₀ : Type _} {A₄₀ : Type _} {A₀₂ : Type _} {A₂₂ : Type _} {A₄₂ : Type _} (f₁₀ : A₀₀ → A₂₀) (f₃₀ : A₂₀ → A₄₀) (f₀₁ : A₀₀ → A₀₂) (f₂₁ : A₂₀ → A₂₂) (f₄₁ : A₄₀ → A₄₂) (f₁₂ : A₀₂ → A₂₂) (f₃₂ : A₂₂ → A₄₂) structure pullback (f₂₁ : A₂₀ → A₂₂) (f₁₂ : A₀₂ → A₂₂) := (fst : A₂₀) (snd : A₀₂) (fst_snd : f₂₁ fst = f₁₂ snd) namespace pullback @[hott] protected def sigma_char : pullback f₂₁ f₁₂ ≃ Σ(a₂₀ : A₂₀) (a₀₂ : A₀₂), f₂₁ a₂₀ = f₁₂ a₀₂ := begin fapply equiv.MK, { intro x, induction x with a₂₀ a₀₂ p, exact ⟨a₂₀, a₀₂, p⟩}, { intro x, induction x with a₂₀ y, induction y with a₀₂ p, exact pullback.mk a₂₀ a₀₂ p}, { intro x, induction x with a₂₀ y, induction y with a₀₂ p, reflexivity}, { intro x, induction x with a₂₀ a₀₂ p, reflexivity}, end variables {f₁₀ f₃₀ f₀₁ f₂₁ f₄₁ f₁₂ f₃₂} @[hott] def pullback_corec (p : Πa, f₂₁ (f₁₀ a) = f₁₂ (f₀₁ a)) (a : A₀₀) : pullback f₂₁ f₁₂ := pullback.mk (f₁₀ a) (f₀₁ a) (p a) @[hott] def pullback_eq {x y : pullback f₂₁ f₁₂} (p1 : fst x = fst y) (p2 : snd x = snd y) (r : square (fst_snd x) (fst_snd y) (ap f₂₁ p1) (ap f₁₂ p2)) : x = y := begin induction y, induction x, dsimp at *, induction p1, induction p2, exact ap (pullback.mk _ _) (eq_of_vdeg_square r) end @[hott] def pullback_comm_equiv : pullback f₁₂ f₂₁ ≃ pullback f₂₁ f₁₂ := begin fapply equiv.MK, { intro v, induction v with x y p, exact pullback.mk y x p⁻¹}, { intro v, induction v with x y p, exact pullback.mk y x p⁻¹}, { intro v, induction v, dsimp, exact ap _ (inv_inv _)}, { intro v, induction v, dsimp, exact ap _ (inv_inv _)}, end @[hott] def pullback_unit_equiv : pullback (λ(x : A₀₂), star) (λ(x : A₂₀), star) ≃ A₀₂ × A₂₀ := begin fapply equiv.MK, { intro v, induction v with x y p, exact (x, y)}, { intro v, induction v with x y, exact pullback.mk x y idp}, { intro v, induction v, reflexivity}, { intro v, induction v, dsimp, apply ap _ (is_prop.elim _ _), apply_instance }, end @[hott] def pullback_along {f : A₂₀ → A₂₂} (g : A₀₂ → A₂₂) : pullback f g → A₂₀ := fst postfix `^*`:(max+1) := pullback_along variables (f₁₀ f₃₀ f₀₁ f₂₁ f₄₁ f₁₂ f₃₂) structure pullback_square (f₁₀ : A₀₀ → A₂₀) (f₁₂ : A₀₂ → A₂₂) (f₀₁ : A₀₀ → A₀₂) (f₂₁ : A₂₀ → A₂₂) := (comm : Πa, f₂₁ (f₁₀ a) = f₁₂ (f₀₁ a)) (is_pullback : is_equiv (pullback_corec comm : A₀₀ → pullback f₂₁ f₁₂)) attribute [instance] pullback_square.is_pullback @[hott] def pbs_comm := @pullback_square.comm @[hott] def pullback_square_pullback : pullback_square (fst : pullback f₂₁ f₁₂ → A₂₀) f₁₂ snd f₂₁ := pullback_square.mk fst_snd (adjointify _ (λf, f) (λf, by induction f; reflexivity) (λg, by induction g; reflexivity)) variables {f₁₀ f₃₀ f₀₁ f₂₁ f₄₁ f₁₂ f₃₂} @[hott] def pullback_square_equiv (s : pullback_square f₁₀ f₁₂ f₀₁ f₂₁) : A₀₀ ≃ pullback f₂₁ f₁₂ := equiv.mk _ (pullback_square.is_pullback s) @[hott] def of_pullback (s : pullback_square f₁₀ f₁₂ f₀₁ f₂₁) (x : pullback f₂₁ f₁₂) : A₀₀ := inv (pullback_square_equiv s) x @[hott] def right_of_pullback (s : pullback_square f₁₀ f₁₂ f₀₁ f₂₁) (x : pullback f₂₁ f₁₂) : f₁₀ (of_pullback s x) = fst x := ap fst (to_right_inv (pullback_square_equiv s) x) @[hott] def down_of_pullback (s : pullback_square f₁₀ f₁₂ f₀₁ f₂₁) (x : pullback f₂₁ f₁₂) : f₀₁ (of_pullback s x) = snd x := ap snd (to_right_inv (pullback_square_equiv s) x) -- @[hott] def pullback_square_compose_inverse (s : pullback_square f₁₀ f₁₂ f₀₁ f₂₁) -- (t : pullback_square f₃₀ f₃₂ f₂₁ f₄₁) (x : pullback f₄₁ (f₃₂ ∘ f₁₂)) : A₀₀ := -- let a₂₀' : pullback f₄₁ f₃₂ := -- pullback.mk (fst x) (f₁₂ (snd x)) (fst_snd x) in -- let a₂₀ : A₂₀ := -- of_pullback t a₂₀' in -- have a₀₀' : pullback f₂₁ f₁₂, -- from pullback.mk a₂₀ (snd x) !down_of_pullback, -- show A₀₀, -- from of_pullback s a₀₀' -- local attribute pullback_square_compose_inverse [reducible] -- @[hott] def down_psci (s : pullback_square f₁₀ f₁₂ f₀₁ f₂₁) -- (t : pullback_square f₃₀ f₃₂ f₂₁ f₄₁) (x : pullback f₄₁ (f₃₂ ∘ f₁₂)) : -- f₀₁ (pullback_square_compose_inverse s t x) = snd x := -- by apply down_of_pullback -- @[hott] def pullback_square_compose (s : pullback_square f₁₀ f₁₂ f₀₁ f₂₁) -- (t : pullback_square f₃₀ f₃₂ f₂₁ f₄₁) : pullback_square (f₃₀ ∘ f₁₀) (f₃₂ ∘ f₁₂) f₀₁ f₄₁ := -- pullback_square.mk -- (λa, pbs_comm t (f₁₀ a) ⬝ ap f₃₂ (pbs_comm s a)) -- (adjointify _ -- (pullback_square_compose_inverse s t) -- begin -- intro x, induction x with x y p, esimp, -- fapply pullback_eq: esimp, -- { exact ap f₃₀ !right_of_pullback ⬝ !right_of_pullback}, -- { apply down_of_pullback}, -- { esimp, exact sorry } -- end -- begin -- intro x, esimp, exact sorry -- end) end pullback end hott
0525110b2fcfa23ed1919e4cc6e5b484b1bf6b44
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Meta/Tactic/Simp/SimpTheorems.lean
dcc99c5cdf914528c58955c14a89974dec2470db
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
19,971
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.ScopedEnvExtension import Lean.Util.Recognizers import Lean.Meta.DiscrTree import Lean.Meta.AppBuilder import Lean.Meta.Eqns import Lean.Meta.Tactic.AuxLemma import Lean.DocString namespace Lean.Meta /-- An `Origin` is an identifier for simp theorems which indicates roughly what action the user took which lead to this theorem existing in the simp set. -/ inductive Origin where /-- A global declaration in the environment. -/ | decl (declName : Name) /-- A local hypothesis. When `contextual := true` is enabled, this fvar may exist in an extension of the current local context; it will not be used for rewriting by simp once it is out of scope but it may end up in the `usedSimps` trace. -/ | fvar (fvarId : FVarId) /-- A proof term provided directly to a call to `simp [ref, ...]` where `ref` is the provided simp argument (of kind `Parser.Tactic.simpLemma`). The `id` is a unique identifier for the call. -/ | stx (id : Name) (ref : Syntax) /-- Some other origin. `name` should not collide with the other types for erasure to work correctly, and simp trace will ignore this lemma. The other origins should be preferred if possible. -/ | other (name : Name) deriving Inhabited, Repr /-- A unique identifier corresponding to the origin. -/ def Origin.key : Origin → Name | .decl declName => declName | .fvar fvarId => fvarId.name | .stx id _ => id | .other name => name instance : BEq Origin := ⟨(·.key == ·.key)⟩ instance : Hashable Origin := ⟨(hash ·.key)⟩ /-- The fields `levelParams` and `proof` are used to encode the proof of the simp theorem. If the `proof` is a global declaration `c`, we store `Expr.const c []` at `proof` without the universe levels, and `levelParams` is set to `#[]` When using the lemma, we create fresh universe metavariables. Motivation: most simp theorems are global declarations, and this approach is faster and saves memory. The field `levelParams` is not empty only when we elaborate an expression provided by the user, and it contains universe metavariables. Then, we use `abstractMVars` to abstract the universe metavariables and create new fresh universe parameters that are stored at the field `levelParams`. -/ structure SimpTheorem where keys : Array DiscrTree.Key := #[] /-- It stores universe parameter names for universe polymorphic proofs. Recall that it is non-empty only when we elaborate an expression provided by the user. When `proof` is just a constant, we can use the universe parameter names stored in the declaration. -/ levelParams : Array Name := #[] proof : Expr priority : Nat := eval_prio default post : Bool := true /-- `perm` is true if lhs and rhs are identical modulo permutation of variables. -/ perm : Bool := false /-- `origin` is mainly relevant for producing trace messages. It is also viewed an `id` used to "erase" `simp` theorems from `SimpTheorems`. -/ origin : Origin /-- `rfl` is true if `proof` is by `Eq.refl` or `rfl`. -/ rfl : Bool deriving Inhabited mutual partial def isRflProofCore (type : Expr) (proof : Expr) : CoreM Bool := do match type with | .forallE _ _ type _ => if let .lam _ _ proof _ := proof then isRflProofCore type proof else return false | _ => if type.isAppOfArity ``Eq 3 then if proof.isAppOfArity ``Eq.refl 2 || proof.isAppOfArity ``rfl 2 then return true else if proof.isAppOfArity ``Eq.symm 4 then -- `Eq.symm` of rfl theorem is a rfl theorem isRflProofCore type proof.appArg! -- small hack: we don't need to set the exact type else if proof.isApp && proof.getAppFn.isConst then -- The application of a `rfl` theorem is a `rfl` theorem isRflTheorem proof.getAppFn.constName! else return false else return false partial def isRflTheorem (declName : Name) : CoreM Bool := do let .thmInfo info ← getConstInfo declName | return false isRflProofCore info.type info.value end def isRflProof (proof : Expr) : MetaM Bool := do if let .const declName .. := proof then isRflTheorem declName else isRflProofCore (← inferType proof) proof instance : ToFormat SimpTheorem where format s := let perm := if s.perm then ":perm" else "" let name := format s.origin.key let prio := f!":{s.priority}" name ++ prio ++ perm def ppOrigin [Monad m] [MonadEnv m] [MonadError m] : Origin → m MessageData | .decl n => mkConstWithLevelParams n | .fvar n => return mkFVar n | .stx _ ref => return ref | .other n => return n def ppSimpTheorem [Monad m] [MonadLiftT IO m] [MonadEnv m] [MonadError m] (s : SimpTheorem) : m MessageData := do let perm := if s.perm then ":perm" else "" let name ← ppOrigin s.origin let prio := m!":{s.priority}" return name ++ prio ++ perm instance : BEq SimpTheorem where beq e₁ e₂ := e₁.proof == e₂.proof structure SimpTheorems where pre : DiscrTree SimpTheorem := DiscrTree.empty post : DiscrTree SimpTheorem := DiscrTree.empty lemmaNames : PHashSet Origin := {} toUnfold : PHashSet Name := {} erased : PHashSet Origin := {} toUnfoldThms : PHashMap Name (Array Name) := {} deriving Inhabited def addSimpTheoremEntry (d : SimpTheorems) (e : SimpTheorem) : SimpTheorems := if e.post then { d with post := d.post.insertCore e.keys e, lemmaNames := updateLemmaNames d.lemmaNames } else { d with pre := d.pre.insertCore e.keys e, lemmaNames := updateLemmaNames d.lemmaNames } where updateLemmaNames (s : PHashSet Origin) : PHashSet Origin := s.insert e.origin def SimpTheorems.addDeclToUnfoldCore (d : SimpTheorems) (declName : Name) : SimpTheorems := { d with toUnfold := d.toUnfold.insert declName } /-- Return `true` if `declName` is tagged to be unfolded using `unfoldDefinition?` (i.e., without using equational theorems). -/ def SimpTheorems.isDeclToUnfold (d : SimpTheorems) (declName : Name) : Bool := d.toUnfold.contains declName def SimpTheorems.isLemma (d : SimpTheorems) (thmId : Origin) : Bool := d.lemmaNames.contains thmId /-- Register the equational theorems for the given definition. -/ def SimpTheorems.registerDeclToUnfoldThms (d : SimpTheorems) (declName : Name) (eqThms : Array Name) : SimpTheorems := { d with toUnfoldThms := d.toUnfoldThms.insert declName eqThms } partial def SimpTheorems.eraseCore (d : SimpTheorems) (thmId : Origin) : SimpTheorems := let d := { d with erased := d.erased.insert thmId, lemmaNames := d.lemmaNames.erase thmId } if let .decl declName := thmId then let d := { d with toUnfold := d.toUnfold.erase declName } if let some thms := d.toUnfoldThms.find? declName then thms.foldl (init := d) (eraseCore · <| .decl ·) else d else d def SimpTheorems.erase [Monad m] [MonadError m] (d : SimpTheorems) (thmId : Origin) : m SimpTheorems := do unless d.isLemma thmId || match thmId with | .decl declName => d.isDeclToUnfold declName || d.toUnfoldThms.contains declName | _ => false do throwError "'{thmId.key}' does not have [simp] attribute" return d.eraseCore thmId private partial def isPerm : Expr → Expr → MetaM Bool | Expr.app f₁ a₁, Expr.app f₂ a₂ => isPerm f₁ f₂ <&&> isPerm a₁ a₂ | Expr.mdata _ s, t => isPerm s t | s, Expr.mdata _ t => isPerm s t | s@(Expr.mvar ..), t@(Expr.mvar ..) => isDefEq s t | Expr.forallE n₁ d₁ b₁ _, Expr.forallE _ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x) | Expr.lam n₁ d₁ b₁ _, Expr.lam _ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x) | Expr.letE n₁ t₁ v₁ b₁ _, Expr.letE _ t₂ v₂ b₂ _ => isPerm t₁ t₂ <&&> isPerm v₁ v₂ <&&> withLetDecl n₁ t₁ v₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x) | Expr.proj _ i₁ b₁, Expr.proj _ i₂ b₂ => pure (i₁ == i₂) <&&> isPerm b₁ b₂ | s, t => return s == t private def checkBadRewrite (lhs rhs : Expr) : MetaM Unit := do let lhs ← DiscrTree.whnfDT lhs (root := true) if lhs == rhs && lhs.isFVar then throwError "invalid `simp` theorem, equation is equivalent to{indentExpr (← mkEq lhs rhs)}" private partial def shouldPreprocess (type : Expr) : MetaM Bool := forallTelescopeReducing type fun _ result => do if let some (_, lhs, rhs) := result.eq? then checkBadRewrite lhs rhs return false else return true private partial def preprocess (e type : Expr) (inv : Bool) (isGlobal : Bool) : MetaM (List (Expr × Expr)) := go e type where go (e type : Expr) : MetaM (List (Expr × Expr)) := do let type ← whnf type if type.isForall then forallTelescopeReducing type fun xs type => do let e := mkAppN e xs let ps ← go e type ps.mapM fun (e, type) => return (← mkLambdaFVars xs e, ← mkForallFVars xs type) else if let some (_, lhs, rhs) := type.eq? then if isGlobal then checkBadRewrite lhs rhs if inv then let type ← mkEq rhs lhs let e ← mkEqSymm e return [(e, type)] else return [(e, type)] else if let some (lhs, rhs) := type.iff? then if isGlobal then checkBadRewrite lhs rhs if inv then let type ← mkEq rhs lhs let e ← mkEqSymm (← mkPropExt e) return [(e, type)] else let type ← mkEq lhs rhs let e ← mkPropExt e return [(e, type)] else if let some (_, lhs, rhs) := type.ne? then if inv then throwError "invalid '←' modifier in rewrite rule to 'False'" if rhs.isConstOf ``Bool.true then return [(← mkAppM ``Bool.of_not_eq_true #[e], ← mkEq lhs (mkConst ``Bool.false))] else if rhs.isConstOf ``Bool.false then return [(← mkAppM ``Bool.of_not_eq_false #[e], ← mkEq lhs (mkConst ``Bool.true))] let type ← mkEq (← mkEq lhs rhs) (mkConst ``False) let e ← mkEqFalse e return [(e, type)] else if let some p := type.not? then if inv then throwError "invalid '←' modifier in rewrite rule to 'False'" if let some (_, lhs, rhs) := p.eq? then if rhs.isConstOf ``Bool.true then return [(← mkAppM ``Bool.of_not_eq_true #[e], ← mkEq lhs (mkConst ``Bool.false))] else if rhs.isConstOf ``Bool.false then return [(← mkAppM ``Bool.of_not_eq_false #[e], ← mkEq lhs (mkConst ``Bool.true))] let type ← mkEq p (mkConst ``False) let e ← mkEqFalse e return [(e, type)] else if let some (type₁, type₂) := type.and? then let e₁ := mkProj ``And 0 e let e₂ := mkProj ``And 1 e return (← go e₁ type₁) ++ (← go e₂ type₂) else if inv then throwError "invalid '←' modifier in rewrite rule to 'True'" let type ← mkEq type (mkConst ``True) let e ← mkEqTrue e return [(e, type)] private def checkTypeIsProp (type : Expr) : MetaM Unit := unless (← isProp type) do throwError "invalid 'simp', proposition expected{indentExpr type}" private def mkSimpTheoremCore (origin : Origin) (e : Expr) (levelParams : Array Name) (proof : Expr) (post : Bool) (prio : Nat) : MetaM SimpTheorem := do assert! origin != .fvar ⟨.anonymous⟩ let type ← instantiateMVars (← inferType e) withNewMCtxDepth do let (_, _, type) ← withReducible <| forallMetaTelescopeReducing type let type ← whnfR type let (keys, perm) ← match type.eq? with | some (_, lhs, rhs) => pure (← DiscrTree.mkPath lhs, ← isPerm lhs rhs) | none => throwError "unexpected kind of 'simp' theorem{indentExpr type}" return { origin, keys, perm, post, levelParams, proof, priority := prio, rfl := (← isRflProof proof) } private def mkSimpTheoremsFromConst (declName : Name) (post : Bool) (inv : Bool) (prio : Nat) : MetaM (Array SimpTheorem) := do let cinfo ← getConstInfo declName let val := mkConst declName (cinfo.levelParams.map mkLevelParam) withReducible do let type ← inferType val checkTypeIsProp type if inv || (← shouldPreprocess type) then let mut r := #[] for (val, type) in (← preprocess val type inv (isGlobal := true)) do let auxName ← mkAuxLemma cinfo.levelParams type val r := r.push <| (← mkSimpTheoremCore (.decl declName) (mkConst auxName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst auxName) post prio) return r else return #[← mkSimpTheoremCore (.decl declName) (mkConst declName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst declName) post prio] inductive SimpEntry where | thm : SimpTheorem → SimpEntry | toUnfold : Name → SimpEntry | toUnfoldThms : Name → Array Name → SimpEntry deriving Inhabited abbrev SimpExtension := SimpleScopedEnvExtension SimpEntry SimpTheorems def SimpExtension.getTheorems (ext : SimpExtension) : CoreM SimpTheorems := return ext.getState (← getEnv) def addSimpTheorem (ext : SimpExtension) (declName : Name) (post : Bool) (inv : Bool) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do let simpThms ← mkSimpTheoremsFromConst declName post inv prio for simpThm in simpThms do ext.add (SimpEntry.thm simpThm) attrKind def mkSimpAttr (attrName : Name) (attrDescr : String) (ext : SimpExtension) (ref : Name := by exact decl_name%) : IO Unit := registerBuiltinAttribute { ref := ref name := attrName descr := attrDescr applicationTime := AttributeApplicationTime.afterCompilation add := fun declName stx attrKind => let go : MetaM Unit := do let info ← getConstInfo declName let post := if stx[1].isNone then true else stx[1][0].getKind == ``Lean.Parser.Tactic.simpPost let prio ← getAttrParamOptPrio stx[2] if (← isProp info.type) then addSimpTheorem ext declName post (inv := false) attrKind prio else if info.hasValue then if let some eqns ← getEqnsFor? declName then for eqn in eqns do addSimpTheorem ext eqn post (inv := false) attrKind prio ext.add (SimpEntry.toUnfoldThms declName eqns) attrKind if hasSmartUnfoldingDecl (← getEnv) declName then ext.add (SimpEntry.toUnfold declName) attrKind else ext.add (SimpEntry.toUnfold declName) attrKind else throwError "invalid 'simp', it is not a proposition nor a definition (to unfold)" discard <| go.run {} {} erase := fun declName => do let s := ext.getState (← getEnv) let s ← s.erase (.decl declName) modifyEnv fun env => ext.modifyState env fun _ => s } def mkSimpExt (extName : Name) : IO SimpExtension := registerSimpleScopedEnvExtension { name := extName initial := {} addEntry := fun d e => match e with | SimpEntry.thm e => addSimpTheoremEntry d e | SimpEntry.toUnfold n => d.addDeclToUnfoldCore n | SimpEntry.toUnfoldThms n thms => d.registerDeclToUnfoldThms n thms } abbrev SimpExtensionMap := HashMap Name SimpExtension builtin_initialize simpExtensionMapRef : IO.Ref SimpExtensionMap ← IO.mkRef {} def registerSimpAttr (attrName : Name) (attrDescr : String) (ref : Name := by exact decl_name%) (extName : Name := attrName.appendAfter "Ext") : IO SimpExtension := do let ext ← mkSimpExt extName mkSimpAttr attrName attrDescr ext ref -- Remark: it will fail if it is not performed during initialization simpExtensionMapRef.modify fun map => map.insert attrName ext return ext builtin_initialize simpExtension : SimpExtension ← registerSimpAttr `simp "simplification theorem" def getSimpExtension? (attrName : Name) : IO (Option SimpExtension) := return (← simpExtensionMapRef.get).find? attrName def getSimpTheorems : CoreM SimpTheorems := simpExtension.getTheorems /-- Auxiliary method for adding a global declaration to a `SimpTheorems` datastructure. -/ def SimpTheorems.addConst (s : SimpTheorems) (declName : Name) (post := true) (inv := false) (prio : Nat := eval_prio default) : MetaM SimpTheorems := do let s := { s with erased := s.erased.erase (.decl declName) } let simpThms ← mkSimpTheoremsFromConst declName post inv prio return simpThms.foldl addSimpTheoremEntry s def SimpTheorem.getValue (simpThm : SimpTheorem) : MetaM Expr := do if simpThm.proof.isConst && simpThm.levelParams.isEmpty then let info ← getConstInfo simpThm.proof.constName! if info.levelParams.isEmpty then return simpThm.proof else return simpThm.proof.updateConst! (← info.levelParams.mapM (fun _ => mkFreshLevelMVar)) else let us ← simpThm.levelParams.mapM fun _ => mkFreshLevelMVar return simpThm.proof.instantiateLevelParamsArray simpThm.levelParams us private def preprocessProof (val : Expr) (inv : Bool) : MetaM (Array Expr) := do let type ← inferType val checkTypeIsProp type let ps ← preprocess val type inv (isGlobal := false) return ps.toArray.map fun (val, _) => val /-- Auxiliary method for creating simp theorems from a proof term `val`. -/ def mkSimpTheorems (id : Origin) (levelParams : Array Name) (proof : Expr) (post := true) (inv := false) (prio : Nat := eval_prio default) : MetaM (Array SimpTheorem) := withReducible do (← preprocessProof proof inv).mapM fun val => mkSimpTheoremCore id val levelParams val post prio /-- Auxiliary method for adding a local simp theorem to a `SimpTheorems` datastructure. -/ def SimpTheorems.add (s : SimpTheorems) (id : Origin) (levelParams : Array Name) (proof : Expr) (inv := false) (post := true) (prio : Nat := eval_prio default) : MetaM SimpTheorems := do if proof.isConst then s.addConst proof.constName! post inv prio else let simpThms ← mkSimpTheorems id levelParams proof post inv prio return simpThms.foldl addSimpTheoremEntry s def SimpTheorems.addDeclToUnfold (d : SimpTheorems) (declName : Name) : MetaM SimpTheorems := do if let some eqns ← getEqnsFor? declName then let mut d := d for eqn in eqns do d ← SimpTheorems.addConst d eqn if hasSmartUnfoldingDecl (← getEnv) declName then d := d.addDeclToUnfoldCore declName return d else return d.addDeclToUnfoldCore declName abbrev SimpTheoremsArray := Array SimpTheorems def SimpTheoremsArray.addTheorem (thmsArray : SimpTheoremsArray) (id : Origin) (h : Expr) : MetaM SimpTheoremsArray := if thmsArray.isEmpty then let thms : SimpTheorems := {} return #[ (← thms.add id #[] h) ] else thmsArray.modifyM 0 fun thms => thms.add id #[] h def SimpTheoremsArray.eraseTheorem (thmsArray : SimpTheoremsArray) (thmId : Origin) : SimpTheoremsArray := thmsArray.map fun thms => thms.eraseCore thmId def SimpTheoremsArray.isErased (thmsArray : SimpTheoremsArray) (thmId : Origin) : Bool := thmsArray.any fun thms => thms.erased.contains thmId def SimpTheoremsArray.isDeclToUnfold (thmsArray : SimpTheoremsArray) (declName : Name) : Bool := thmsArray.any fun thms => thms.isDeclToUnfold declName macro (name := _root_.Lean.Parser.Command.registerSimpAttr) doc:docComment "register_simp_attr" id:ident : command => do let str := id.getId.toString let idParser := mkIdentFrom id (`Parser.Attr ++ id.getId) let descr := quote (removeLeadingSpaces doc.getDocString) `($doc:docComment initialize ext : SimpExtension ← registerSimpAttr $(quote id.getId) $descr $(quote id.getId) $doc:docComment syntax (name := $idParser:ident) $(quote str):str (Parser.Tactic.simpPre <|> Parser.Tactic.simpPost)? (prio)? : attr) end Meta end Lean
8f9162c0c0ba3d26ed82c232ab7efb1864794d28
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/field_theory/adjoin.lean
d009d4d6c66493e9dd5aa95ded60b9e863989dbf
[ "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
33,065
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import field_theory.intermediate_field import field_theory.splitting_field import field_theory.separable import ring_theory.adjoin_root import ring_theory.power_basis /-! # Adjoining Elements to Fields In this file we introduce the notion of adjoining elements to fields. This isn't quite the same as adjoining elements to rings. For example, `algebra.adjoin K {x}` might not include `x⁻¹`. ## Main results - `adjoin_adjoin_left`: adjoining S and then T is the same as adjoining `S ∪ T`. - `bot_eq_top_of_dim_adjoin_eq_one`: if `F⟮x⟯` has dimension `1` over `F` for every `x` in `E` then `F = E` ## Notation - `F⟮α⟯`: adjoin a single element `α` to `F`. -/ open finite_dimensional polynomial open_locale classical namespace intermediate_field section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) /-- `adjoin F S` extends a field `F` by adjoining a set `S ⊆ E`. -/ def adjoin : intermediate_field F E := { algebra_map_mem' := λ x, subfield.subset_closure (or.inl (set.mem_range_self x)), ..subfield.closure (set.range (algebra_map F E) ∪ S) } end adjoin_def section lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] @[simp] lemma adjoin_le_iff {S : set E} {T : intermediate_field F E} : adjoin F S ≤ T ↔ S ≤ T := ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subfield.subset_closure) H, λ H, (@subfield.closure_le E _ (set.range (algebra_map F E) ∪ S) T.to_subfield).mpr (set.union_subset (intermediate_field.set_range_subset T) H)⟩ lemma gc : galois_connection (adjoin F : set E → intermediate_field F E) coe := λ _ _, adjoin_le_iff /-- Galois insertion between `adjoin` and `coe`. -/ def gi : galois_insertion (adjoin F : set E → intermediate_field F E) coe := { choice := λ S _, adjoin F S, gc := intermediate_field.gc, le_l_u := λ S, (intermediate_field.gc (S : set E) (adjoin F S)).1 $ le_refl _, choice_eq := λ _ _, rfl } instance : complete_lattice (intermediate_field F E) := galois_insertion.lift_complete_lattice intermediate_field.gi instance : inhabited (intermediate_field F E) := ⟨⊤⟩ lemma mem_bot {x : E} : x ∈ (⊥ : intermediate_field F E) ↔ x ∈ set.range (algebra_map F E) := begin suffices : set.range (algebra_map F E) = (⊥ : intermediate_field F E), { rw this, refl }, { change set.range (algebra_map F E) = subfield.closure (set.range (algebra_map F E) ∪ ∅), simp [←set.image_univ, ←ring_hom.map_field_closure] } end lemma mem_top {x : E} : x ∈ (⊤ : intermediate_field F E) := subfield.subset_closure $ or.inr trivial @[simp] lemma bot_to_subalgebra : (⊥ : intermediate_field F E).to_subalgebra = ⊥ := by { ext, rw [mem_to_subalgebra, algebra.mem_bot, mem_bot] } @[simp] lemma top_to_subalgebra : (⊤ : intermediate_field F E).to_subalgebra = ⊤ := by { ext, rw [mem_to_subalgebra, iff_true_right algebra.mem_top], exact mem_top } /-- Construct an algebra isomorphism from an equality of subalgebras -/ def subalgebra.equiv_of_eq {X Y : subalgebra F E} (h : X = Y) : X ≃ₐ[F] Y := by refine { to_fun := λ x, ⟨x, _⟩, inv_fun := λ x, ⟨x, _⟩, .. }; tidy variables (F E) /-- The bottom intermediate_field is isomorphic to the field. -/ noncomputable def bot_equiv : (⊥ : intermediate_field F E) ≃ₐ[F] F := (subalgebra.equiv_of_eq bot_to_subalgebra).trans (algebra.bot_equiv F E) variables {F E} @[simp] lemma bot_equiv_def (x : F) : bot_equiv F E (algebra_map F (⊥ : intermediate_field F E) x) = x := alg_equiv.commutes (bot_equiv F E) x noncomputable instance algebra_over_bot : algebra (⊥ : intermediate_field F E) F := (intermediate_field.bot_equiv F E).to_alg_hom.to_ring_hom.to_algebra instance is_scalar_tower_over_bot : is_scalar_tower (⊥ : intermediate_field F E) F E := is_scalar_tower.of_algebra_map_eq begin intro x, let ϕ := algebra.of_id F (⊥ : subalgebra F E), let ψ := alg_equiv.of_bijective ϕ ((algebra.bot_equiv F E).symm.bijective), change (↑x : E) = ↑(ψ (ψ.symm ⟨x, _⟩)), rw alg_equiv.apply_symm_apply ψ ⟨x, _⟩, refl end /-- The top intermediate_field is isomorphic to the field. -/ noncomputable def top_equiv : (⊤ : intermediate_field F E) ≃ₐ[F] E := (subalgebra.equiv_of_eq top_to_subalgebra).trans algebra.top_equiv @[simp] lemma top_equiv_def (x : (⊤ : intermediate_field F E)) : top_equiv x = ↑x := begin suffices : algebra.to_top (top_equiv x) = algebra.to_top (x : E), { rwa subtype.ext_iff at this }, exact alg_equiv.apply_symm_apply (alg_equiv.of_bijective algebra.to_top ⟨λ _ _, subtype.mk.inj, λ x, ⟨x.val, by { ext, refl }⟩⟩ : E ≃ₐ[F] (⊤ : subalgebra F E)) (subalgebra.equiv_of_eq top_to_subalgebra x), end @[simp] lemma coe_bot_eq_self (K : intermediate_field F E) : ↑(⊥ : intermediate_field K E) = K := by { ext, rw [mem_lift2, mem_bot], exact set.ext_iff.mp subtype.range_coe x } @[simp] lemma coe_top_eq_top (K : intermediate_field F E) : ↑(⊤ : intermediate_field K E) = (⊤ : intermediate_field F E) := set_like.ext_iff.mpr $ λ _, mem_lift2.trans (iff_of_true mem_top mem_top) end lattice section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) lemma adjoin_eq_range_algebra_map_adjoin : (adjoin F S : set E) = set.range (algebra_map (adjoin F S) E) := (subtype.range_coe).symm lemma adjoin.algebra_map_mem (x : F) : algebra_map F E x ∈ adjoin F S := intermediate_field.algebra_map_mem (adjoin F S) x lemma adjoin.range_algebra_map_subset : set.range (algebra_map F E) ⊆ adjoin F S := begin intros x hx, cases hx with f hf, rw ← hf, exact adjoin.algebra_map_mem F S f, end instance adjoin.field_coe : has_coe_t F (adjoin F S) := {coe := λ x, ⟨algebra_map F E x, adjoin.algebra_map_mem F S x⟩} lemma subset_adjoin : S ⊆ adjoin F S := λ x hx, subfield.subset_closure (or.inr hx) instance adjoin.set_coe : has_coe_t S (adjoin F S) := {coe := λ x, ⟨x,subset_adjoin F S (subtype.mem x)⟩} @[mono] lemma adjoin.mono (T : set E) (h : S ⊆ T) : adjoin F S ≤ adjoin F T := galois_connection.monotone_l gc h lemma adjoin_contains_field_as_subfield (F : subfield E) : (F : set E) ⊆ adjoin F S := λ x hx, adjoin.algebra_map_mem F S ⟨x, hx⟩ lemma subset_adjoin_of_subset_left {F : subfield E} {T : set E} (HT : T ⊆ F) : T ⊆ adjoin F S := λ x hx, (adjoin F S).algebra_map_mem ⟨x, HT hx⟩ lemma subset_adjoin_of_subset_right {T : set E} (H : T ⊆ S) : T ⊆ adjoin F S := λ x hx, subset_adjoin F S (H hx) @[simp] lemma adjoin_empty (F E : Type*) [field F] [field E] [algebra F E] : adjoin F (∅ : set E) = ⊥ := eq_bot_iff.mpr (adjoin_le_iff.mpr (set.empty_subset _)) /-- If `K` is a field with `F ⊆ K` and `S ⊆ K` then `adjoin F S ≤ K`. -/ lemma adjoin_le_subfield {K : subfield E} (HF : set.range (algebra_map F E) ⊆ K) (HS : S ⊆ K) : (adjoin F S).to_subfield ≤ K := begin apply subfield.closure_le.mpr, rw set.union_subset_iff, exact ⟨HF, HS⟩, end lemma adjoin_subset_adjoin_iff {F' : Type*} [field F'] [algebra F' E] {S S' : set E} : (adjoin F S : set E) ⊆ adjoin F' S' ↔ set.range (algebra_map F E) ⊆ adjoin F' S' ∧ S ⊆ adjoin F' S' := ⟨λ h, ⟨trans (adjoin.range_algebra_map_subset _ _) h, trans (subset_adjoin _ _) h⟩, λ ⟨hF, hS⟩, subfield.closure_le.mpr (set.union_subset hF hS)⟩ /-- `F[S][T] = F[S ∪ T]` -/ lemma adjoin_adjoin_left (T : set E) : ↑(adjoin (adjoin F S) T) = adjoin F (S ∪ T) := begin rw set_like.ext'_iff, change ↑(adjoin (adjoin F S) T) = _, apply set.eq_of_subset_of_subset; rw adjoin_subset_adjoin_iff; split, { rintros _ ⟨⟨x, hx⟩, rfl⟩, exact adjoin.mono _ _ _ (set.subset_union_left _ _) hx }, { exact subset_adjoin_of_subset_right _ _ (set.subset_union_right _ _) }, { exact subset_adjoin_of_subset_left _ (adjoin.range_algebra_map_subset _ _) }, { exact set.union_subset (subset_adjoin_of_subset_left _ (subset_adjoin _ _)) (subset_adjoin _ _) }, end @[simp] lemma adjoin_insert_adjoin (x : E) : adjoin F (insert x (adjoin F S : set E)) = adjoin F (insert x S) := le_antisymm (adjoin_le_iff.mpr (set.insert_subset.mpr ⟨subset_adjoin _ _ (set.mem_insert _ _), adjoin_le_iff.mpr (subset_adjoin_of_subset_right _ _ (set.subset_insert _ _))⟩)) (adjoin.mono _ _ _ (set.insert_subset_insert (subset_adjoin _ _))) /-- `F[S][T] = F[T][S]` -/ lemma adjoin_adjoin_comm (T : set E) : ↑(adjoin (adjoin F S) T) = (↑(adjoin (adjoin F T) S) : (intermediate_field F E)) := by rw [adjoin_adjoin_left, adjoin_adjoin_left, set.union_comm] lemma adjoin_map {E' : Type*} [field E'] [algebra F E'] (f : E →ₐ[F] E') : (adjoin F S).map f = adjoin F (f '' S) := begin ext x, show x ∈ (subfield.closure (set.range (algebra_map F E) ∪ S)).map (f : E →+* E') ↔ x ∈ subfield.closure (set.range (algebra_map F E') ∪ f '' S), rw [ring_hom.map_field_closure, set.image_union, ← set.range_comp, ← ring_hom.coe_comp, f.comp_algebra_map], refl, end lemma algebra_adjoin_le_adjoin : algebra.adjoin F S ≤ (adjoin F S).to_subalgebra := algebra.adjoin_le (subset_adjoin _ _) lemma adjoin_eq_algebra_adjoin (inv_mem : ∀ x ∈ algebra.adjoin F S, x⁻¹ ∈ algebra.adjoin F S) : (adjoin F S).to_subalgebra = algebra.adjoin F S := le_antisymm (show adjoin F S ≤ { neg_mem' := λ x, (algebra.adjoin F S).neg_mem, inv_mem' := inv_mem, .. algebra.adjoin F S}, from adjoin_le_iff.mpr (algebra.subset_adjoin)) (algebra_adjoin_le_adjoin _ _) lemma eq_adjoin_of_eq_algebra_adjoin (K : intermediate_field F E) (h : K.to_subalgebra = algebra.adjoin F S) : K = adjoin F S := begin apply to_subalgebra_injective, rw h, refine (adjoin_eq_algebra_adjoin _ _ _).symm, intros x, convert K.inv_mem, rw ← h, refl end @[elab_as_eliminator] lemma adjoin_induction {s : set E} {p : E → Prop} {x} (h : x ∈ adjoin F s) (Hs : ∀ x ∈ s, p x) (Hmap : ∀ x, p (algebra_map F E x)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ x, p x → p (-x)) (Hinv : ∀ x, p x → p x⁻¹) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := subfield.closure_induction h (λ x hx, or.cases_on hx (λ ⟨x, hx⟩, hx ▸ Hmap x) (Hs x)) ((algebra_map F E).map_one ▸ Hmap 1) Hadd Hneg Hinv Hmul /-- Variation on `set.insert` to enable good notation for adjoining elements to fields. Used to preferentially use `singleton` rather than `insert` when adjoining one element. -/ --this definition of notation is courtesy of Kyle Miller on zulip class insert {α : Type*} (s : set α) := (insert : α → set α) @[priority 1000] instance insert_empty {α : Type*} : insert (∅ : set α) := { insert := λ x, @singleton _ _ set.has_singleton x } @[priority 900] instance insert_nonempty {α : Type*} (s : set α) : insert s := { insert := λ x, set.insert x s } notation K`⟮`:std.prec.max_plus l:(foldr `, ` (h t, insert.insert t h) ∅) `⟯` := adjoin K l section adjoin_simple variables (α : E) lemma mem_adjoin_simple_self : α ∈ F⟮α⟯ := subset_adjoin F {α} (set.mem_singleton α) /-- generator of `F⟮α⟯` -/ def adjoin_simple.gen : F⟮α⟯ := ⟨α, mem_adjoin_simple_self F α⟩ @[simp] lemma adjoin_simple.algebra_map_gen : algebra_map F⟮α⟯ E (adjoin_simple.gen F α) = α := rfl lemma adjoin_simple_adjoin_simple (β : E) : ↑F⟮α⟯⟮β⟯ = F⟮α, β⟯ := adjoin_adjoin_left _ _ _ lemma adjoin_simple_comm (β : E) : ↑F⟮α⟯⟮β⟯ = (↑F⟮β⟯⟮α⟯ : intermediate_field F E) := adjoin_adjoin_comm _ _ _ -- TODO: develop the API for `subalgebra.is_field_of_algebraic` so it can be used here lemma adjoin_simple_to_subalgebra_of_integral (hα : is_integral F α) : (F⟮α⟯).to_subalgebra = algebra.adjoin F {α} := begin apply adjoin_eq_algebra_adjoin, intros x hx, by_cases x = 0, { rw [h, inv_zero], exact subalgebra.zero_mem (algebra.adjoin F {α}) }, let ϕ := alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly F α, haveI := minpoly.irreducible hα, suffices : ϕ ⟨x, hx⟩ * (ϕ ⟨x, hx⟩)⁻¹ = 1, { convert subtype.mem (ϕ.symm (ϕ ⟨x, hx⟩)⁻¹), refine (eq_inv_of_mul_right_eq_one _).symm, apply_fun ϕ.symm at this, rw [alg_equiv.map_one, alg_equiv.map_mul, alg_equiv.symm_apply_apply] at this, rw [←subsemiring.coe_one, ←this, subsemiring.coe_mul, subtype.coe_mk] }, rw mul_inv_cancel (mt (λ key, _) h), rw ← ϕ.map_zero at key, change ↑(⟨x, hx⟩ : algebra.adjoin F {α}) = _, rw [ϕ.injective key, subalgebra.coe_zero] end end adjoin_simple end adjoin_def section adjoin_intermediate_field_lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} {S : set E} @[simp] lemma adjoin_eq_bot_iff : adjoin F S = ⊥ ↔ S ⊆ (⊥ : intermediate_field F E) := by { rw [eq_bot_iff, adjoin_le_iff], refl, } @[simp] lemma adjoin_simple_eq_bot_iff : F⟮α⟯ = ⊥ ↔ α ∈ (⊥ : intermediate_field F E) := by { rw adjoin_eq_bot_iff, exact set.singleton_subset_iff } @[simp] lemma adjoin_zero : F⟮(0 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (zero_mem ⊥) @[simp] lemma adjoin_one : F⟮(1 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (one_mem ⊥) @[simp] lemma adjoin_int (n : ℤ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n) @[simp] lemma adjoin_nat (n : ℕ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n) section adjoin_dim open finite_dimensional module variables {K L : intermediate_field F E} @[simp] lemma dim_eq_one_iff : module.rank F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← dim_eq_dim_subalgebra, subalgebra.dim_eq_one_iff, bot_to_subalgebra] @[simp] lemma finrank_eq_one_iff : finrank F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← finrank_eq_finrank_subalgebra, subalgebra.finrank_eq_one_iff, bot_to_subalgebra] lemma dim_adjoin_eq_one_iff : module.rank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans dim_eq_one_iff adjoin_eq_bot_iff lemma dim_adjoin_simple_eq_one_iff : module.rank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw dim_adjoin_eq_one_iff, exact set.singleton_subset_iff } lemma finrank_adjoin_eq_one_iff : finrank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans finrank_eq_one_iff adjoin_eq_bot_iff lemma finrank_adjoin_simple_eq_one_iff : finrank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw [finrank_adjoin_eq_one_iff], exact set.singleton_subset_iff } /-- If `F⟮x⟯` has dimension `1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact dim_adjoin_simple_eq_one_iff.mp (h x), end lemma bot_eq_top_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact finrank_adjoin_simple_eq_one_iff.mp (h x), end lemma subsingleton_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_dim_adjoin_eq_one h) lemma subsingleton_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_eq_one h) /-- If `F⟮x⟯` has dimension `≤1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_finrank_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : (⊥ : intermediate_field F E) = ⊤ := begin apply bot_eq_top_of_finrank_adjoin_eq_one, exact λ x, by linarith [h x, show 0 < finrank F F⟮x⟯, from finrank_pos], end lemma subsingleton_of_finrank_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_le_one h) end adjoin_dim end adjoin_intermediate_field_lattice section adjoin_integral_element variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] {α : E} variables {K : Type*} [field K] [algebra F K] lemma aeval_gen_minpoly (α : E) : aeval (adjoin_simple.gen F α) (minpoly F α) = 0 := begin ext, convert minpoly.aeval F α, conv in (aeval α) { rw [← adjoin_simple.algebra_map_gen F α] }, exact is_scalar_tower.algebra_map_aeval F F⟮α⟯ E _ _ end /-- algebra isomorphism between `adjoin_root` and `F⟮α⟯` -/ noncomputable def adjoin_root_equiv_adjoin (h : is_integral F α) : adjoin_root (minpoly F α) ≃ₐ[F] F⟮α⟯ := alg_equiv.of_bijective (alg_hom.mk (adjoin_root.lift (algebra_map F F⟮α⟯) (adjoin_simple.gen F α) (aeval_gen_minpoly F α)) (ring_hom.map_one _) (λ x y, ring_hom.map_mul _ x y) (ring_hom.map_zero _) (λ x y, ring_hom.map_add _ x y) (by { exact λ _, adjoin_root.lift_of })) (begin set f := adjoin_root.lift _ _ (aeval_gen_minpoly F α : _), haveI := minpoly.irreducible h, split, { exact ring_hom.injective f }, { suffices : F⟮α⟯.to_subfield ≤ ring_hom.field_range ((F⟮α⟯.to_subfield.subtype).comp f), { exact λ x, Exists.cases_on (this (subtype.mem x)) (λ y hy, ⟨y, subtype.ext hy⟩) }, exact subfield.closure_le.mpr (set.union_subset (λ x hx, Exists.cases_on hx (λ y hy, ⟨y, by { rw [ring_hom.comp_apply, adjoin_root.lift_of], exact hy }⟩)) (set.singleton_subset_iff.mpr ⟨adjoin_root.root (minpoly F α), by { rw [ring_hom.comp_apply, adjoin_root.lift_root], refl }⟩)) } end) lemma adjoin_root_equiv_adjoin_apply_root (h : is_integral F α) : adjoin_root_equiv_adjoin F h (adjoin_root.root (minpoly F α)) = adjoin_simple.gen F α := begin refine adjoin_root.lift_root, { exact minpoly F α }, { exact aeval_gen_minpoly F α } end /-- Algebra homomorphism `F⟮α⟯ →ₐ[F] K` are in bijection with the set of roots of `minpoly α` in `K`. -/ noncomputable def alg_hom_adjoin_integral_equiv (h : is_integral F α) : (F⟮α⟯ →ₐ[F] K) ≃ {x // x ∈ ((minpoly F α).map (algebra_map F K)).roots} := let ϕ := adjoin_root_equiv_adjoin F h, swap1 : (F⟮α⟯ →ₐ[F] K) ≃ (adjoin_root (minpoly F α) →ₐ[F] K) := { to_fun := λ f, f.comp ϕ.to_alg_hom, inv_fun := λ f, f.comp ϕ.symm.to_alg_hom, left_inv := λ _, by { ext, simp only [alg_equiv.coe_alg_hom, alg_equiv.to_alg_hom_eq_coe, alg_hom.comp_apply, alg_equiv.apply_symm_apply] }, right_inv := λ _, by { ext, simp only [alg_equiv.symm_apply_apply, alg_equiv.coe_alg_hom, alg_equiv.to_alg_hom_eq_coe, alg_hom.comp_apply] } }, swap2 := adjoin_root.equiv F K (minpoly F α) (minpoly.ne_zero h) in swap1.trans swap2 /-- Fintype of algebra homomorphism `F⟮α⟯ →ₐ[F] K` -/ noncomputable def fintype_of_alg_hom_adjoin_integral (h : is_integral F α) : fintype (F⟮α⟯ →ₐ[F] K) := fintype.of_equiv _ (alg_hom_adjoin_integral_equiv F h).symm lemma card_alg_hom_adjoin_integral (h : is_integral F α) (h_sep : (minpoly F α).separable) (h_splits : (minpoly F α).splits (algebra_map F K)) : @fintype.card (F⟮α⟯ →ₐ[F] K) (fintype_of_alg_hom_adjoin_integral F h) = (minpoly F α).nat_degree := begin let s := ((minpoly F α).map (algebra_map F K)).roots.to_finset, have H := λ x, multiset.mem_to_finset, rw [fintype.card_congr (alg_hom_adjoin_integral_equiv F h), fintype.card_of_subtype s H, nat_degree_eq_card_roots h_splits, multiset.to_finset_card_of_nodup], exact nodup_roots ((separable_map (algebra_map F K)).mpr h_sep), end end adjoin_integral_element section induction variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] /-- An intermediate field `S` is finitely generated if there exists `t : finset E` such that `intermediate_field.adjoin F t = S`. -/ def fg (S : intermediate_field F E) : Prop := ∃ (t : finset E), adjoin F ↑t = S lemma fg_adjoin_finset (t : finset E) : (adjoin F (↑t : set E)).fg := ⟨t, rfl⟩ theorem fg_def {S : intermediate_field F E} : S.fg ↔ ∃ t : set E, set.finite t ∧ adjoin F t = S := ⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩, λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩ theorem fg_bot : (⊥ : intermediate_field F E).fg := ⟨∅, adjoin_empty F E⟩ lemma fg_of_fg_to_subalgebra (S : intermediate_field F E) (h : S.to_subalgebra.fg) : S.fg := begin cases h with t ht, exact ⟨t, (eq_adjoin_of_eq_algebra_adjoin _ _ _ ht.symm).symm⟩ end lemma fg_of_noetherian (S : intermediate_field F E) [is_noetherian F E] : S.fg := S.fg_of_fg_to_subalgebra S.to_subalgebra.fg_of_noetherian lemma induction_on_adjoin_finset (S : finset E) (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x ∈ S), P K → P ↑K⟮x⟯) : P (adjoin F ↑S) := begin apply finset.induction_on' S, { exact base }, { intros a s h1 _ _ h4, rw [finset.coe_insert, set.insert_eq, set.union_comm, ←adjoin_adjoin_left], exact ih (adjoin F s) a h1 h4 } end lemma induction_on_adjoin_fg (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯) (K : intermediate_field F E) (hK : K.fg) : P K := begin obtain ⟨S, rfl⟩ := hK, exact induction_on_adjoin_finset S P base (λ K x _ hK, ih K x hK), end lemma induction_on_adjoin [fd : finite_dimensional F E] (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯) (K : intermediate_field F E) : P K := induction_on_adjoin_fg P base ih K K.fg_of_noetherian end induction section alg_hom_mk_adjoin_splits variables (F E K : Type*) [field F] [field E] [field K] [algebra F E] [algebra F K] {S : set E} /-- Lifts `L → K` of `F → K` -/ def lifts := Σ (L : intermediate_field F E), (L →ₐ[F] K) variables {F E K} noncomputable instance : order_bot (lifts F E K) := { le := λ x y, x.1 ≤ y.1 ∧ (∀ (s : x.1) (t : y.1), (s : E) = t → x.2 s = y.2 t), le_refl := λ x, ⟨le_refl x.1, λ s t hst, congr_arg x.2 (subtype.ext hst)⟩, le_trans := λ x y z hxy hyz, ⟨le_trans hxy.1 hyz.1, λ s u hsu, eq.trans (hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl) (hyz.2 ⟨s, hxy.1 s.mem⟩ u hsu)⟩, le_antisymm := begin rintros ⟨x1, x2⟩ ⟨y1, y2⟩ ⟨hxy1, hxy2⟩ ⟨hyx1, hyx2⟩, have : x1 = y1 := le_antisymm hxy1 hyx1, subst this, congr, exact alg_hom.ext (λ s, hxy2 s s rfl), end, bot := ⟨⊥, (algebra.of_id F K).comp (bot_equiv F E).to_alg_hom⟩, bot_le := λ x, ⟨bot_le, λ s t hst, begin cases intermediate_field.mem_bot.mp s.mem with u hu, rw [show s = (algebra_map F _) u, from subtype.ext hu.symm, alg_hom.commutes], rw [show t = (algebra_map F _) u, from subtype.ext (eq.trans hu hst).symm, alg_hom.commutes], end⟩ } noncomputable instance : inhabited (lifts F E K) := ⟨⊥⟩ lemma lifts.eq_of_le {x y : lifts F E K} (hxy : x ≤ y) (s : x.1) : x.2 s = y.2 ⟨s, hxy.1 s.mem⟩ := hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl lemma lifts.exists_max_two {c : set (lifts F E K)} {x y : lifts F E K} (hc : zorn.chain (≤) c) (hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) : ∃ z : lifts F E K, z ∈ set.insert ⊥ c ∧ x ≤ z ∧ y ≤ z := begin cases (zorn.chain_insert hc (λ _ _ _, or.inl bot_le)).total_of_refl hx hy with hxy hyx, { exact ⟨y, hy, hxy, le_refl y⟩ }, { exact ⟨x, hx, le_refl x, hyx⟩ }, end lemma lifts.exists_max_three {c : set (lifts F E K)} {x y z : lifts F E K} (hc : zorn.chain (≤) c) (hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) (hz : z ∈ set.insert ⊥ c) : ∃ w : lifts F E K, w ∈ set.insert ⊥ c ∧ x ≤ w ∧ y ≤ w ∧ z ≤ w := begin obtain ⟨v, hv, hxv, hyv⟩ := lifts.exists_max_two hc hx hy, obtain ⟨w, hw, hzw, hvw⟩ := lifts.exists_max_two hc hz hv, exact ⟨w, hw, le_trans hxv hvw, le_trans hyv hvw, hzw⟩, end /-- An upper bound on a chain of lifts -/ def lifts.upper_bound_intermediate_field {c : set (lifts F E K)} (hc : zorn.chain (≤) c) : intermediate_field F E := { carrier := λ s, ∃ x : (lifts F E K), x ∈ set.insert ⊥ c ∧ (s ∈ x.1 : Prop), zero_mem' := ⟨⊥, set.mem_insert ⊥ c, zero_mem ⊥⟩, one_mem' := ⟨⊥, set.mem_insert ⊥ c, one_mem ⊥⟩, neg_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.neg_mem h⟩⟩ }, inv_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.inv_mem h⟩⟩ }, add_mem' := by { rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy, exact ⟨z, hz, z.1.add_mem (hxz.1 ha) (hyz.1 hb)⟩ }, mul_mem' := by { rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy, exact ⟨z, hz, z.1.mul_mem (hxz.1 ha) (hyz.1 hb)⟩ }, algebra_map_mem' := λ s, ⟨⊥, set.mem_insert ⊥ c, algebra_map_mem ⊥ s⟩ } /-- The lift on the upper bound on a chain of lifts -/ noncomputable def lifts.upper_bound_alg_hom {c : set (lifts F E K)} (hc : zorn.chain (≤) c) : lifts.upper_bound_intermediate_field hc →ₐ[F] K := { to_fun := λ s, (classical.some s.mem).2 ⟨s, (classical.some_spec s.mem).2⟩, map_zero' := alg_hom.map_zero _, map_one' := alg_hom.map_one _, map_add' := λ s t, begin obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc (classical.some_spec s.mem).1 (classical.some_spec t.mem).1 (classical.some_spec (s + t).mem).1, rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_add], refl, end, map_mul' := λ s t, begin obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc (classical.some_spec s.mem).1 (classical.some_spec t.mem).1 (classical.some_spec (s * t).mem).1, rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_mul], refl, end, commutes' := λ _, alg_hom.commutes _ _ } /-- An upper bound on a chain of lifts -/ noncomputable def lifts.upper_bound {c : set (lifts F E K)} (hc : zorn.chain (≤) c) : lifts F E K := ⟨lifts.upper_bound_intermediate_field hc, lifts.upper_bound_alg_hom hc⟩ lemma lifts.exists_upper_bound (c : set (lifts F E K)) (hc : zorn.chain (≤) c) : ∃ ub, ∀ a ∈ c, a ≤ ub := ⟨lifts.upper_bound hc, begin intros x hx, split, { exact λ s hs, ⟨x, set.mem_insert_of_mem ⊥ hx, hs⟩ }, { intros s t hst, change x.2 s = (classical.some t.mem).2 ⟨t, (classical.some_spec t.mem).2⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc (set.mem_insert_of_mem ⊥ hx) (classical.some_spec t.mem).1, rw [lifts.eq_of_le hxz, lifts.eq_of_le hyz], exact congr_arg z.2 (subtype.ext hst) }, end⟩ /-- Extend a lift `x : lifts F E K` to an element `s : E` whose conjugates are all in `K` -/ noncomputable def lifts.lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : lifts F E K := let h3 : is_integral x.1 s := is_integral_of_is_scalar_tower s h1 in let key : (minpoly x.1 s).splits x.2.to_ring_hom := splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero h1)) ((splits_map_iff _ _).mpr (by {convert h2, exact ring_hom.ext (λ y, x.2.commutes y)})) (minpoly.dvd_map_of_is_scalar_tower _ _ _) in ⟨↑x.1⟮s⟯, (@alg_hom_equiv_sigma F x.1 (↑x.1⟮s⟯ : intermediate_field F E) K _ _ _ _ _ _ _ (intermediate_field.algebra x.1⟮s⟯) (is_scalar_tower.of_algebra_map_eq (λ _, rfl))).inv_fun ⟨x.2, (@alg_hom_adjoin_integral_equiv x.1 _ E _ _ s K _ x.2.to_ring_hom.to_algebra h3).inv_fun ⟨root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)), by { simp_rw [mem_roots (map_ne_zero (minpoly.ne_zero h3)), is_root, ←eval₂_eq_eval_map], exact map_root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)) }⟩⟩⟩ lemma lifts.le_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : x ≤ x.lift_of_splits h1 h2 := ⟨λ z hz, algebra_map_mem x.1⟮s⟯ ⟨z, hz⟩, λ t u htu, eq.symm begin rw [←(show algebra_map x.1 x.1⟮s⟯ t = u, from subtype.ext htu)], letI : algebra x.1 K := x.2.to_ring_hom.to_algebra, exact (alg_hom.commutes _ t), end⟩ lemma lifts.mem_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : s ∈ (x.lift_of_splits h1 h2).1 := mem_adjoin_simple_self x.1 s lemma lifts.exists_lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : ∃ y, x ≤ y ∧ s ∈ y.1 := ⟨x.lift_of_splits h1 h2, x.le_lifts_of_splits h1 h2, x.mem_lifts_of_splits h1 h2⟩ lemma alg_hom_mk_adjoin_splits (hK : ∀ s ∈ S, is_integral F (s : E) ∧ (minpoly F s).splits (algebra_map F K)) : nonempty (adjoin F S →ₐ[F] K) := begin obtain ⟨x : lifts F E K, hx⟩ := zorn.zorn_partial_order lifts.exists_upper_bound, refine ⟨alg_hom.mk (λ s, x.2 ⟨s, adjoin_le_iff.mpr (λ s hs, _) s.mem⟩) x.2.map_one (λ s t, x.2.map_mul ⟨s, _⟩ ⟨t, _⟩) x.2.map_zero (λ s t, x.2.map_add ⟨s, _⟩ ⟨t, _⟩) x.2.commutes⟩, rcases (x.exists_lift_of_splits (hK s hs).1 (hK s hs).2) with ⟨y, h1, h2⟩, rwa hx y h1 at h2 end lemma alg_hom_mk_adjoin_splits' (hS : adjoin F S = ⊤) (hK : ∀ x ∈ S, is_integral F (x : E) ∧ (minpoly F x).splits (algebra_map F K)) : nonempty (E →ₐ[F] K) := begin cases alg_hom_mk_adjoin_splits hK with ϕ, rw hS at ϕ, exact ⟨ϕ.comp top_equiv.symm.to_alg_hom⟩, end end alg_hom_mk_adjoin_splits end intermediate_field section power_basis variables {K L : Type*} [field K] [field L] [algebra K L] namespace intermediate_field /-- The elements `1, x, ..., x ^ (d - 1)` form a basis for `K⟮x⟯`, where `d` is the degree of the minimal polynomial of `x`. -/ noncomputable def power_basis_aux {x : L} (hx : is_integral K x) : basis (fin (minpoly K x).nat_degree) K K⟮x⟯ := (adjoin_root.power_basis (minpoly.ne_zero hx)).basis.map (adjoin_root_equiv_adjoin K hx).to_linear_equiv /-- The power basis `1, x, ..., x ^ (d - 1)` for `K⟮x⟯`, where `d` is the degree of the minimal polynomial of `x`. -/ noncomputable def adjoin.power_basis {x : L} (hx : is_integral K x) : power_basis K K⟮x⟯ := { gen := adjoin_simple.gen K x, dim := (minpoly K x).nat_degree, basis := power_basis_aux hx, basis_eq_pow := λ i, by rw [power_basis_aux, basis.map_apply, power_basis.basis_eq_pow, alg_equiv.to_linear_equiv_apply, alg_equiv.map_pow, adjoin_root.power_basis_gen, adjoin_root_equiv_adjoin_apply_root] } @[simp] lemma adjoin.power_basis.gen_eq {x : L} (hx : is_integral K x) : (adjoin.power_basis hx).gen = adjoin_simple.gen K x := rfl lemma adjoin.finite_dimensional {x : L} (hx : is_integral K x) : finite_dimensional K K⟮x⟯ := power_basis.finite_dimensional (adjoin.power_basis hx) lemma adjoin.finrank {x : L} (hx : is_integral K x) : finite_dimensional.finrank K K⟮x⟯ = (minpoly K x).nat_degree := begin rw power_basis.finrank (adjoin.power_basis hx : _), refl end end intermediate_field namespace power_basis open intermediate_field /-- `pb.equiv_adjoin_simple` is the equivalence between `K⟮pb.gen⟯` and `L` itself. -/ noncomputable def equiv_adjoin_simple (pb : power_basis K L) : K⟮pb.gen⟯ ≃ₐ[K] L := (adjoin.power_basis pb.is_integral_gen).equiv pb (minpoly.eq_of_algebra_map_eq (algebra_map K⟮pb.gen⟯ L).injective (adjoin.power_basis pb.is_integral_gen).is_integral_gen (by rw [adjoin.power_basis.gen_eq, adjoin_simple.algebra_map_gen])) @[simp] lemma equiv_adjoin_simple_aeval (pb : power_basis K L) (f : polynomial K) : pb.equiv_adjoin_simple (aeval (adjoin_simple.gen K pb.gen) f) = aeval pb.gen f := equiv_aeval _ pb _ f @[simp] lemma equiv_adjoin_simple_gen (pb : power_basis K L) : pb.equiv_adjoin_simple (adjoin_simple.gen K pb.gen) = pb.gen := equiv_gen _ pb _ @[simp] lemma equiv_adjoin_simple_symm_aeval (pb : power_basis K L) (f : polynomial K) : pb.equiv_adjoin_simple.symm (aeval pb.gen f) = aeval (adjoin_simple.gen K pb.gen) f := by rw [equiv_adjoin_simple, equiv_symm, equiv_aeval, adjoin.power_basis.gen_eq] @[simp] lemma equiv_adjoin_simple_symm_gen (pb : power_basis K L) : pb.equiv_adjoin_simple.symm pb.gen = (adjoin_simple.gen K pb.gen) := by rw [equiv_adjoin_simple, equiv_symm, equiv_gen, adjoin.power_basis.gen_eq] end power_basis end power_basis
60caa8c0a3bd57d3a70c1225cf83899b6a8fc67e
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/category_theory/limits/shapes/zero.lean
b8d27264c9ef9d28ad25673858ecec819a140105
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
8,473
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.terminal import category_theory.limits.shapes.binary_products import category_theory.epi_mono import category_theory.punit import category_theory.pempty /-! # Zero morphisms and zero objects A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space, and compositions of zero morphisms with anything give the zero morphism. (Notice this is extra structure, not merely a property.) A category "has a zero object" if it has an object which is both initial and terminal. Having a zero object provides zero morphisms, as the unique morphisms factoring through the zero object. ## References * https://en.wikipedia.org/wiki/Zero_morphism * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ universes v u open category_theory namespace category_theory.limits variables (C : Type u) [𝒞 : category.{v} C] include 𝒞 /-- A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space, and compositions of zero morphisms with anything give the zero morphism. -/ class has_zero_morphisms := [has_zero : Π X Y : C, has_zero (X ⟶ Y)] (comp_zero' : ∀ {X Y : C} (f : X ⟶ Y) (Z : C), f ≫ (0 : Y ⟶ Z) = (0 : X ⟶ Z) . obviously) (zero_comp' : ∀ (X : C) {Y Z : C} (f : Y ⟶ Z), (0 : X ⟶ Y) ≫ f = (0 : X ⟶ Z) . obviously) attribute [instance] has_zero_morphisms.has_zero restate_axiom has_zero_morphisms.comp_zero' attribute [simp] has_zero_morphisms.comp_zero restate_axiom has_zero_morphisms.zero_comp' attribute [simp, reassoc] has_zero_morphisms.zero_comp section omit 𝒞 instance has_zero_morphisms_pempty : has_zero_morphisms.{v} pempty.{v+1} := { has_zero := by tidy } instance has_zero_morphisms_punit : has_zero_morphisms.{v} punit.{v+1} := { has_zero := λ X Y, { zero := punit.star, } } end namespace has_zero_morphisms variables {C} /-- This lemma will be immediately superseded by `ext`, below. -/ private lemma ext_aux (I J : has_zero_morphisms.{v} C) (w : ∀ X Y : C, (@has_zero_morphisms.has_zero.{v} _ _ I X Y).zero = (@has_zero_morphisms.has_zero.{v} _ _ J X Y).zero) : I = J := begin resetI, cases I, cases J, congr, { ext X Y, exact w X Y }, { apply proof_irrel_heq, }, { apply proof_irrel_heq, } end /-- If you're tempted to use this lemma "in the wild", you should probably carefully consider whether you've made a mistake in allowing two instances of `has_zero_morphisms` to exist at all. See, particularly, the note on `zero_morphisms_of_zero_object` below. -/ lemma ext (I J : has_zero_morphisms.{v} C) : I = J := begin apply ext_aux, intros X Y, rw ←@has_zero_morphisms.comp_zero _ _ I X X (@has_zero_morphisms.has_zero _ _ J X X).zero, rw @has_zero_morphisms.zero_comp _ _ J, end instance : subsingleton (has_zero_morphisms.{v} C) := ⟨ext⟩ end has_zero_morphisms open has_zero_morphisms section variables {C} [has_zero_morphisms.{v} C] lemma zero_of_comp_mono {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [mono g] (h : f ≫ g = 0) : f = 0 := by { rw [←zero_comp.{v} C X g, cancel_mono] at h, exact h } lemma zero_of_comp_epi {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [epi f] (h : f ≫ g = 0) : g = 0 := by { rw [←comp_zero.{v} C f Z, cancel_epi] at h, exact h } end section universes v' u' variables (D : Type u') [𝒟 : category.{v'} D] include 𝒟 variables [has_zero_morphisms.{v} C] [has_zero_morphisms.{v'} D] @[simp] lemma equivalence_preserves_zero_morphisms (F : C ≌ D) (X Y : C) : F.functor.map (0 : X ⟶ Y) = (0 : F.functor.obj X ⟶ F.functor.obj Y) := begin have t : F.functor.map (0 : X ⟶ Y) = F.functor.map (0 : X ⟶ Y) ≫ (0 : F.functor.obj Y ⟶ F.functor.obj Y), { apply faithful.injectivity (F.inverse), rw [functor.map_comp, equivalence.inv_fun_map], dsimp, rw [zero_comp, comp_zero, zero_comp], }, exact t.trans (by simp) end end /-- A category "has a zero object" if it has an object which is both initial and terminal. -/ class has_zero_object := (zero : C) (unique_to : Π X : C, unique (zero ⟶ X)) (unique_from : Π X : C, unique (X ⟶ zero)) section omit 𝒞 instance has_zero_object_punit : has_zero_object.{v} punit.{v+1} := { zero := punit.star, unique_to := by tidy, unique_from := by tidy, } end variables {C} namespace has_zero_object variables [has_zero_object.{v} C] /-- Construct a `has_zero C` for a category with a zero object. This can not be a global instance as it will trigger for every `has_zero C` typeclass search. -/ protected def has_zero : has_zero C := { zero := has_zero_object.zero.{v} C } local attribute [instance] has_zero_object.has_zero local attribute [instance] has_zero_object.unique_to has_zero_object.unique_from /-- A category with a zero object has zero morphisms. It is rarely a good idea to use this. Many categories that have a zero object have zero morphisms for some other reason, for example from additivity. Library code that uses `zero_morphisms_of_zero_object` will then be incompatible with these categories because the `has_zero_morphisms` instances will not be definitionally equal. For this reason library code should generally ask for an instance of `has_zero_morphisms` separately, even if it already asks for an instance of `has_zero_objects`. -/ def zero_morphisms_of_zero_object : has_zero_morphisms.{v} C := { has_zero := λ X Y, { zero := inhabited.default (X ⟶ 0) ≫ inhabited.default (0 ⟶ Y) }, zero_comp' := λ X Y Z f, by { dunfold has_zero.zero, rw category.assoc, congr, }, comp_zero' := λ X Y Z f, by { dunfold has_zero.zero, rw ←category.assoc, congr, }} section variable [has_zero_morphisms.{v} C] /-- An arrow ending in the zero object is zero -/ @[ext] lemma zero_of_to_zero {X : C} (f : X ⟶ 0) : f = 0 := begin rw (has_zero_object.unique_from.{v} X).uniq f, rw (has_zero_object.unique_from.{v} X).uniq (0 : X ⟶ 0) end /-- An arrow starting at the zero object is zero -/ @[ext] lemma zero_of_from_zero {X : C} (f : 0 ⟶ X) : f = 0 := begin rw (has_zero_object.unique_to.{v} X).uniq f, rw (has_zero_object.unique_to.{v} X).uniq (0 : 0 ⟶ X) end end /-- A zero object is in particular initial. -/ def has_initial_of_has_zero_object : has_initial.{v} C := has_initial_of_unique 0 /-- A zero object is in particular terminal. -/ def has_terminal_of_has_zero_object : has_terminal.{v} C := has_terminal_of_unique 0 end has_zero_object /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_sigma_ι {β : Type v} [decidable_eq β] [has_zero_morphisms.{v} C] (f : β → C) [has_colimit (functor.of_function f)] (b : β) : split_mono (sigma.ι f b) := { retraction := sigma.desc (λ b', if h : b' = b then eq_to_hom (congr_arg f h) else 0), } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_pi_π {β : Type v} [decidable_eq β] [has_zero_morphisms.{v} C] (f : β → C) [has_limit (functor.of_function f)] (b : β) : split_epi (pi.π f b) := { section_ := pi.lift (λ b', if h : b = b' then eq_to_hom (congr_arg f h) else 0), } /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_coprod_inl [has_zero_morphisms.{v} C] {X Y : C} [has_colimit (pair X Y)] : split_mono (coprod.inl : X ⟶ X ⨿ Y) := { retraction := coprod.desc (𝟙 X) 0, } /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_coprod_inr [has_zero_morphisms.{v} C] {X Y : C} [has_colimit (pair X Y)] : split_mono (coprod.inr : Y ⟶ X ⨿ Y) := { retraction := coprod.desc 0 (𝟙 Y), } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_prod_fst [has_zero_morphisms.{v} C] {X Y : C} [has_limit (pair X Y)] : split_epi (prod.fst : X ⨯ Y ⟶ X) := { section_ := prod.lift (𝟙 X) 0, } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_prod_snd [has_zero_morphisms.{v} C] {X Y : C} [has_limit (pair X Y)] : split_epi (prod.snd : X ⨯ Y ⟶ Y) := { section_ := prod.lift 0 (𝟙 Y), } end category_theory.limits
491415f2dbd147aead136a24fce3da32eb8b7034
9028d228ac200bbefe3a711342514dd4e4458bff
/src/tactic/derive_fintype.lean
be34264d71c4b288b305db61523776bc48635e94
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,349
lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import logic.basic import data.fintype.basic /-! # Derive handler for `fintype` instances This file introduces a derive handler to automatically generate `fintype` instances for structures and inductives. ## Implementation notes To construct a fintype instance, we need 3 things: 1. A list `l` of elements 2. A proof that `l` has no duplicates 3. A proof that every element in the type is in `l` Now fintype is defined as a finset which enumerates all elements, so steps (1) and (2) are bundled together. It is possible to use finset operations that remove duplicates to avoid the need to prove (2), but this adds unnecessary functions to the constructed term, which makes it more expensive to compute the list, and it also adds a dependence on decidable equality for the type, which we want to avoid. Because we will rely on fintype instances for constructor arguments, we can't actually build a list directly, so (1) and (2) are necessarily somewhat intertwined. The inductive types we will be proving instances for look something like this: ``` @[derive fintype] inductive foo | zero : foo | one : bool → foo | two : ∀ x : fin 3, bar x → foo ``` The list of elements that we generate is ``` {foo.zero} ∪ (finset.univ : bool).map (λ b, finset.one b) ∪ (finset.univ : Σ' x : fin 3, bar x).map (λ ⟨x, y⟩, finset.two x y) ``` except that instead of `∪`, that is `finset.union`, we use `finset.disj_union` which doesn't require any deduplication, but does require a proof that the two parts of the union are disjoint. We use `finset.cons` to append singletons like `foo.zero`. The proofs of disjointness would be somewhat expensive since there are quadratically many of them, so instead we use a "discriminant" function. Essentially, we define ``` def foo.enum : foo → ℕ | foo.zero := 0 | (foo.one _) := 1 | (foo.two _ _) := 2 ``` and now the existence of this function implies that foo.zero is not foo.two and so on because they map to different natural numbers. We can prove that sets of natural numbers are mutually disjoint more easily because they have a linear order: `0 < 1 < 2` so `0 ≠ 2`. To package this argument up, we define `finset_above foo foo.enum n` to be a finset `s` together with a proof that all elements `a ∈ s` have `n ≤ enum a`. Now we only have to prove that `enum foo.zero = 0`, `enum (foo.one _) = 1`, etc. (linearly many proofs, all `rfl`) in order to prove that all variants are mutually distinct. We mirror the `finset.cons` and `finset.disj_union` functions into `finset_above.cons` and `finset_above.union`, and this forms the main part of the finset construction. This only handles distinguishing variants of a finset. Now we must enumerate the elements of a variant, for example `{foo.one ff, foo.one tt}`, while at the same time proving that all these elements have discriminant `1` in this case. To do that, we use the `finset_in` type, which is a finset satisfying a property `P`, here `λ a, foo.enum a = 1`. We could use `finset.bind` many times to construct the finset but it turns out to be somewhat complicated to get good side goals for a naturally nodup version of `finset.bind` in the same way as we did with `finset.cons` and `finset.union`. Instead, we tuple up all arguments into one type, leveraging the `fintype` instance on `psigma`, and then define a map from this type to the inductive type that untuples them and applies the constructor. The injectivity property of the constructor ensures that this function is injective, so we can use `finset.map` to apply it. This is the content of the constructor `finset_in.mk`. That completes the proofs of (1) and (2). To prove (3), we perform one case analysis over the inductive type, proving theorems like ``` foo.one a ∈ {foo.zero} ∪ (finset.univ : bool).map (λ b, finset.one b) ∪ (finset.univ : Σ' x : fin 3, bar x).map (λ ⟨x, y⟩, finset.two x y) ``` by seeking to the relevant disjunct and then supplying the constructor arguments. This part of the proof is quadratic, but quite simple. (We could do it in `O(n log n)` if we used a balanced tree for the unions.) The tactics perform the following parts of this proof scheme: * `mk_sigma` constructs the type `Γ` in `finset_in.mk` * `mk_sigma_elim` constructs the function `f` in `finset_in.mk` * `mk_sigma_elim_inj` proves that `f` is injective * `mk_sigma_elim_eq` proves that `∀ a, enum (f a) = k` * `mk_finset` constructs the finset `S = {foo.zero} ∪ ...` by recursion on the variants * `mk_finset_total` constructs the proof `|- foo.zero ∈ S; |- foo.one a ∈ S; |- foo.two a b ∈ S` by recursion on the subgoals coming out of the initial `cases` * `mk_fintype_instance` puts it all together to produce a proof of `fintype foo`. The construction of `foo.enum` is also done in this function. -/ namespace derive_fintype /-- A step in the construction of `finset.univ` for a finite inductive type. We will set `enum` to the discriminant of the inductive type, so a `finset_above` represents a finset that enumerates all elements in a tail of the constructor list. -/ def finset_above (α) (enum : α → ℕ) (n : ℕ) := {s : finset α // ∀ x ∈ s, n ≤ enum x} /-- Construct a fintype instance from a completed `finset_above`. -/ def mk_fintype {α} (enum : α → ℕ) (s : finset_above α enum 0) (H : ∀ x, x ∈ s.1) : fintype α := ⟨s.1, H⟩ /-- This is the case for a simple variant (no arguments) in an inductive type. -/ def finset_above.cons {α} {enum : α → ℕ} (n) (a : α) (h : enum a = n) (s : finset_above α enum (n+1)) : finset_above α enum n := begin refine ⟨finset.cons a s.1 _, _⟩, { intro h', have := s.2 _ h', rw h at this, exact nat.not_succ_le_self n this }, { intros x h', rcases finset.mem_cons.1 h' with rfl | h', { exact ge_of_eq h }, { exact nat.le_of_succ_le (s.2 _ h') } } end theorem finset_above.mem_cons_self {α} {enum : α → ℕ} {n a h s} : a ∈ (@finset_above.cons α enum n a h s).1 := multiset.mem_cons_self _ _ theorem finset_above.mem_cons_of_mem {α} {enum : α → ℕ} {n a h s b} : b ∈ (s : finset_above _ _ _).1 → b ∈ (@finset_above.cons α enum n a h s).1 := multiset.mem_cons_of_mem /-- The base case is when we run out of variants; we just put an empty finset at the end. -/ def finset_above.nil {α} {enum : α → ℕ} (n) : finset_above α enum n := ⟨∅, by rintro _ ⟨⟩⟩ instance (α enum n) : inhabited (finset_above α enum n) := ⟨finset_above.nil _⟩ /-- This is a finset covering a nontrivial variant (with one or more constructor arguments). The property `P` here is `λ a, enum a = n` where `n` is the discriminant for the current variant. -/ @[nolint has_inhabited_instance] def finset_in {α} (P : α → Prop) := {s : finset α // ∀ x ∈ s, P x} /-- To construct the finset, we use an injective map from the type `Γ`, which will be the sigma over all constructor arguments. We use sigma instances and existing fintype instances to prove that `Γ` is a fintype, and construct the function `f` that maps `⟨a, b, c, ...⟩` to `C_n a b c ...` where `C_n` is the nth constructor, and `mem` asserts `enum (C_n a b c ...) = n`. -/ def finset_in.mk {α} {P : α → Prop} (Γ) [fintype Γ] (f : Γ → α) (inj : function.injective f) (mem : ∀ x, P (f x)) : finset_in P := ⟨finset.univ.map ⟨f, inj⟩, λ x h, by rcases finset.mem_map.1 h with ⟨x, _, rfl⟩; exact mem x⟩ theorem finset_in.mem_mk {α} {P : α → Prop} {Γ} {s : fintype Γ} {f : Γ → α} {inj mem a} (b) (H : f b = a) : a ∈ (@finset_in.mk α P Γ s f inj mem).1 := finset.mem_map.2 ⟨_, finset.mem_univ _, H⟩ /-- For nontrivial variants, we split the constructor list into a `finset_in` component for the current constructor and a `finset_above` for the rest. -/ def finset_above.union {α} {enum : α → ℕ} (n) (s : finset_in (λ a, enum a = n)) (t : finset_above α enum (n+1)) : finset_above α enum n := begin refine ⟨finset.disj_union s.1 t.1 _, _⟩, { intros a hs ht, have := t.2 _ ht, rw s.2 _ hs at this, exact nat.not_succ_le_self n this }, { intros x h', rcases finset.mem_disj_union.1 h' with h' | h', { exact ge_of_eq (s.2 _ h') }, { exact nat.le_of_succ_le (t.2 _ h') } } end theorem finset_above.mem_union_left {α} {enum : α → ℕ} {n s t a} (H : a ∈ (s : finset_in _).1) : a ∈ (@finset_above.union α enum n s t).1 := multiset.mem_add.2 (or.inl H) theorem finset_above.mem_union_right {α} {enum : α → ℕ} {n s t a} (H : a ∈ (t : finset_above _ _ _).1) : a ∈ (@finset_above.union α enum n s t).1 := multiset.mem_add.2 (or.inr H) end derive_fintype namespace tactic open derive_fintype tactic expr namespace derive_fintype /-- Construct the term `Σ' (a:A) (b:B a), C a b` from `Π (a:A) (b:B a), C a b → T` (the type of a constructor). -/ meta def mk_sigma : expr → tactic expr | (expr.pi n bi d b@(expr.pi _ _ _ _)) := do p ← mk_local' n bi d, e ← mk_sigma (expr.instantiate_var b p), tactic.mk_app ``psigma [d, bind_lambda e p] | (expr.pi n bi d b) := pure d | _ := failed /-- Prove the goal `(Σ' (a:A) (b:B a), C a b) → T` (this is the function `f` in `finset_in.mk`) using recursive `psigma.elim`, finishing with the constructor. The two arguments are the type of the constructor, and the constructor term itself; as we recurse we add arguments to the constructor application and destructure the pi type of the constructor. We return the number of `psigma.elim` applications constructed, which is one less than the number of constructor arguments. -/ meta def mk_sigma_elim : expr → expr → tactic ℕ | (expr.pi n bi d b@(expr.pi _ _ _ _)) c := do refine ``(@psigma.elim %%d _ _ _), i ← intro_fresh n, (+ 1) <$> mk_sigma_elim (expr.instantiate_var b i) (c i) | (expr.pi n bi d b) c := do i ← intro_fresh n, exact (c i) $> 0 | _ c := failed /-- Prove the goal `a, b |- f a = f b → g a = g b` where `f` is the function we constructed in `mk_sigma_elim`, and `g` is some other term that gets built up and eventually closed by reflexivity. Here `a` and `b` have sigma types so the proof approach is to case on `a` and `b` until the goal reduces to `C_n a1 ... am = C_n b1 ... bm → ⟨a1, ..., am⟩ = ⟨b1, ..., bm⟩`, at which point cases on the equality reduces the problem to reflexivity. The arguments are the number `m` returned from `mk_sigma_elim`, and the hypotheses `a,b` that we need to case on. -/ meta def mk_sigma_elim_inj : ℕ → expr → expr → tactic unit | (m+1) x y := do [(_, [x1, x2])] ← cases x, [(_, [y1, y2])] ← cases y, mk_sigma_elim_inj m x2 y2 | 0 x y := do intro1 >>= cases, reflexivity /-- Prove the goal `a |- enum (f a) = n`, where `f` is the function constructed in `mk_sigma_elim`, and `enum` is a function that reduces to `n` on the constructor `C_n`. Here we just have to case on `a` `m` times, and then `reflexivity` finishes the proof. -/ meta def mk_sigma_elim_eq : ℕ → expr → tactic unit | (n+1) x := do [(_, [x1, x2])] ← cases x, mk_sigma_elim_eq n x2 | 0 x := reflexivity /-- Prove the goal `|- finset_above T enum k`, where `T` is the inductive type and `enum` is the discriminant function. The arguments are `args`, the parameters to the inductive type (and all constructors), `k`, the index of the current variant, and `cs`, the list of constructor names. This uses `finset_above.cons` for basic variants and `finset_above.union` for variants with arguments, using the auxiliary functions `mk_sigma`, `mk_sigma_elim`, `mk_sigma_elim_inj`, `mk_sigma_elim_eq` to close subgoals. -/ meta def mk_finset (args : list expr) : ℕ → list name → tactic unit | k (c::cs) := do e ← mk_const c, let e := e.mk_app args, t ← infer_type e, if is_pi t then do to_expr ``(finset_above.union %%(reflect k)) tt ff >>= (λ c, apply c {new_goals := new_goals.all}), Γ ← mk_sigma t, to_expr ``(finset_in.mk %%Γ) tt ff >>= (λ c, apply c {new_goals := new_goals.all}), n ← mk_sigma_elim t e, intro1 >>= (λ x, intro1 >>= mk_sigma_elim_inj n x), intro1 >>= mk_sigma_elim_eq n, mk_finset (k+1) cs else do c ← to_expr ``(finset_above.cons %%(reflect k) %%e) tt ff, apply c {new_goals := new_goals.all}, reflexivity, mk_finset (k+1) cs | k [] := applyc ``finset_above.nil /-- Prove the goal `|- Σ' (a:A) (b: B a), C a b` given a list of terms `a, b, c`. -/ meta def mk_sigma_mem : list expr → tactic unit | [x] := exact x | (x::xs) := constructor >> exact x >> mk_sigma_mem xs | [] := failed /-- This function is called to prove `a : T |- a ∈ S.1` where `S` is the `finset_above` constructed by `mk_finset`, after the initial cases on `a : T`, producing a list of subgoals. For each case, we have to navigate past all the variants that don't apply (which is what the `tac` input tactic does), and then call either `finset_above.mem_cons_self` for trivial variants or `finset_above.mem_union_left` and `finset_in.mem_mk` for nontrivial variants. Either way the proof is quite simple. -/ meta def mk_finset_total : tactic unit → list (name × list expr) → tactic unit | tac [] := done | tac ((_, xs) :: gs) := do tac, b ← succeeds (applyc ``finset_above.mem_cons_self), if b then mk_finset_total (tac >> applyc ``finset_above.mem_cons_of_mem) gs else do applyc ``finset_above.mem_union_left, applyc ``finset_in.mem_mk {new_goals := new_goals.all}, mk_sigma_mem xs, reflexivity, mk_finset_total (tac >> applyc ``finset_above.mem_union_right) gs end derive_fintype open tactic.derive_fintype /-- Proves `|- fintype T` where `T` is a non-recursive inductive type with no indices, where all arguments to all constructors are fintypes. -/ meta def mk_fintype_instance : tactic unit := do intros, `(fintype %%e) ← target >>= whnf, (const I ls, args) ← pure (get_app_fn_args e), env ← get_env, let cs := env.constructors_of I, guard (env.inductive_num_indices I = 0) <|> fail "@[derive fintype]: inductive indices are not supported", guard (¬ env.is_recursive I) <|> fail ("@[derive fintype]: recursive inductive types are " ++ "not supported (they are also usually infinite)"), applyc ``mk_fintype {new_goals := new_goals.all}, intro1 >>= cases >>= (λ gs, gs.enum.mmap' $ λ ⟨i, _⟩, exact (reflect i)), mk_finset args 0 cs, intro1 >>= cases >>= mk_finset_total skip /-- Tries to derive a `fintype` instance for inductives and structures. For example: ``` @[derive fintype] inductive foo (n m : ℕ) | zero : foo | one : bool → foo | two : fin n → fin m → foo ``` Here, `@[derive fintype]` adds the instance `foo.fintype`. The underlying finset definitionally unfolds to a list that enumerates the elements of the inductive in lexicographic order. If the structure/inductive has a type parameter `α`, then the generated instance will have an argument `fintype α`, even if it is not used. (This is due to the implementation using `instance_derive_handler`.) -/ @[derive_handler] meta def fintype_instance : derive_handler := instance_derive_handler ``fintype mk_fintype_instance end tactic
8e8d9fdb61bec8a22a69e94f3ee7addffd44847c
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/360_1.lean
b03955981673fa193fe5b877e8744d7adfc6993b
[ "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
171
lean
structure is_tr [class] (A : Type) : Type := (x : A) theorem foo (B : Type) [H : is_tr B] : B := sorry theorem bar (A : Type) (H : is_tr A) : A := begin apply foo end
373695a5faab8975ab8f137cb3cbbaa5c0ffbbdc
e030b0259b777fedcdf73dd966f3f1556d392178
/library/init/meta/default.lean
3e64ddbfc4858ce9668fb5d4ce048f23d862efaf
[ "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
856
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.name init.meta.options init.meta.format init.meta.rb_map import init.meta.level init.meta.expr init.meta.environment init.meta.attribute import init.meta.tactic init.meta.contradiction_tactic init.meta.constructor_tactic import init.meta.injection_tactic init.meta.relation_tactics init.meta.fun_info import init.meta.congr_lemma init.meta.match_tactic init.meta.ac_tactics import init.meta.backward init.meta.rewrite_tactic import init.meta.mk_dec_eq_instance init.meta.mk_inhabited_instance import init.meta.simp_tactic init.meta.set_get_option_tactics import init.meta.interactive init.meta.converter init.meta.vm import init.meta.comp_value_tactics init.meta.smt
edc0e4f9bfab27898825bdcad50fbf1aede20fd8
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/computability/partrec_code.lean
dbc39ca2fb078c29066c3dc7a41ed731b14e76ca
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
37,518
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Godel numbering for partial recursive functions. -/ import computability.partrec open encodable denumerable namespace nat.partrec open nat (mkpair) theorem rfind' {f} (hf : nat.partrec f) : nat.partrec (nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + m)))).map (+ m))) := partrec₂.unpaired'.2 $ begin refine partrec.map ((@partrec₂.unpaired' (λ (a b : ℕ), nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + b))))).1 _) (primrec.nat_add.comp primrec.snd $ primrec.snd.comp primrec.fst).to_comp.to₂, have := rfind (partrec₂.unpaired'.2 ((partrec.nat_iff.2 hf).comp (primrec₂.mkpair.comp (primrec.fst.comp $ primrec.unpair.comp primrec.fst) (primrec.nat_add.comp primrec.snd (primrec.snd.comp $ primrec.unpair.comp primrec.fst))).to_comp).to₂), simp at this, exact this end inductive code : Type | zero : code | succ : code | left : code | right : code | pair : code → code → code | comp : code → code → code | prec : code → code → code | rfind' : code → code end nat.partrec namespace nat.partrec.code open nat (mkpair unpair) open nat.partrec (code) protected def const : ℕ → code | 0 := zero | (n+1) := comp succ (const n) protected def id : code := pair left right def curry (c : code) (n : ℕ) : code := comp c (pair (code.const n) code.id) def encode_code : code → ℕ | zero := 0 | succ := 1 | left := 2 | right := 3 | (pair cf cg) := bit0 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (comp cf cg) := bit0 (bit1 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (prec cf cg) := bit1 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (rfind' cf) := bit1 (bit1 $ encode_code cf) + 4 def of_nat_code : ℕ → code | 0 := zero | 1 := succ | 2 := left | 3 := right | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, match n.bodd, n.div2.bodd with | ff, ff := pair (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | ff, tt := comp (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, ff := prec (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, tt := rfind' (of_nat_code m) end private theorem encode_of_nat_code : ∀ n, encode_code (of_nat_code n) = n | 0 := rfl | 1 := rfl | 2 := rfl | 3 := rfl | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, have IH : _ := encode_of_nat_code m, have IH1 : _ := encode_of_nat_code m.unpair.1, have IH2 : _ := encode_of_nat_code m.unpair.2, begin transitivity, swap, rw [← nat.bit_decomp n, ← nat.bit_decomp n.div2], simp [encode_code, of_nat_code, -add_comm], cases n.bodd; cases n.div2.bodd; simp [encode_code, of_nat_code, -add_comm, IH, IH1, IH2, m, nat.bit] end instance : denumerable code := mk' ⟨encode_code, of_nat_code, λ c, by induction c; try {refl}; simp [ encode_code, of_nat_code, -add_comm, *], encode_of_nat_code⟩ theorem encode_code_eq : encode = encode_code := rfl theorem of_nat_code_eq : of_nat code = of_nat_code := rfl theorem encode_lt_pair (cf cg) : encode cf < encode (pair cf cg) ∧ encode cg < encode (pair cf cg) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, have := lt_of_le_of_lt this (lt_add_of_pos_right _ (dec_trivial:0<4)), exact ⟨ lt_of_le_of_lt (nat.le_mkpair_left _ _) this, lt_of_le_of_lt (nat.le_mkpair_right _ _) this⟩ end theorem encode_lt_comp (cf cg) : encode cf < encode (comp cf cg) ∧ encode cg < encode (comp cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code, -add_comm], exact nat.bit0_lt (nat.lt_succ_self _), end theorem encode_lt_prec (cf cg) : encode cf < encode (prec cf cg) ∧ encode cg < encode (prec cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code, -add_comm], exact nat.lt_succ_self _, end theorem encode_lt_rfind' (cf) : encode cf < encode (rfind' cf) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, refine lt_of_le_of_lt (le_trans this _) (lt_add_of_pos_right _ (dec_trivial:0<4)), exact le_of_lt (nat.bit0_lt_bit1 $ le_of_lt $ nat.bit0_lt_bit1 $ le_refl _), end section open primrec theorem pair_prim : primrec₂ pair := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem comp_prim : primrec₂ comp := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit1.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem prec_prim : primrec₂ prec := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem rfind_prim : primrec rfind' := of_nat_iff.2 $ encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit1.comp $ encode_iff.2 $ primrec.of_nat code) (const 4) theorem rec_prim' {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code × code × σ × σ → σ} (hpr : primrec₂ pr) {co : α → code × code × σ × σ → σ} (hco : primrec₂ co) {pc : α → code × code × σ × σ → σ} (hpc : primrec₂ pc) {rf : α → code × σ → σ} (hrf : primrec₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a c) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in primrec (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((primrec.of_nat code).comp m).pair s)) (hpc.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end theorem rec_prim {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code → code → σ → σ → σ} (hpr : primrec (λ a : α × code × code × σ × σ, pr a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {co : α → code → code → σ → σ → σ} (hco : primrec (λ a : α × code × code × σ × σ, co a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {pc : α → code → code → σ → σ → σ} (hpc : primrec (λ a : α × code × code × σ × σ, pc a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {rf : α → code → σ → σ} (hrf : primrec (λ a : α × code × σ, rf a.1 a.2.1 a.2.2)) : let F (a c) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (pr a) (co a) (pc a) (rf a) in primrec (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m) s) (pc a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)) (cond n.div2.bodd (co a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂) (pr a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp $ a.pair (((primrec.of_nat code).comp m).pair s)) (hpc.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end section open computable /- TODO(Mario): less copy-paste from previous proof -/ theorem rec_computable {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : computable c) {z : α → σ} (hz : computable z) {s : α → σ} (hs : computable s) {l : α → σ} (hl : computable l) {r : α → σ} (hr : computable r) {pr : α → code × code × σ × σ → σ} (hpr : computable₂ pr) {co : α → code × code × σ × σ → σ} (hco : computable₂ co) {pc : α → code × code × σ × σ → σ} (hpc : computable₂ pc) {rf : α → code × σ → σ} (hrf : computable₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a c) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in computable (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : computable G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ computable.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ computable.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (computable.unpair.comp m), have m₂ := snd.comp (computable.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((computable.of_nat code).comp m).pair s)) (hpc.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) (computable.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : computable₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp computable.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end def eval : code → ℕ →. ℕ | zero := pure 0 | succ := nat.succ | left := λ n, n.unpair.1 | right := λ n, n.unpair.2 | (pair cf cg) := λ n, mkpair <$> eval cf n <*> eval cg n | (comp cf cg) := λ n, eval cg n >>= eval cf | (prec cf cg) := nat.unpaired (λ a n, n.elim (eval cf a) (λ y IH, do i ← IH, eval cg (mkpair a (mkpair y i)))) | (rfind' cf) := nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> eval cf (mkpair a (n + m)))).map (+ m)) instance : has_mem (ℕ →. ℕ) code := ⟨λ f c, eval c = f⟩ @[simp] theorem eval_const : ∀ n m, eval (code.const n) m = roption.some n | 0 m := rfl | (n+1) m := by simp! * @[simp] theorem eval_id (n) : eval code.id n = roption.some n := by simp! [(<*>)] @[simp] theorem eval_curry (c n x) : eval (curry c n) x = eval c (mkpair n x) := by simp! [(<*>)] theorem const_prim : primrec code.const := (primrec.id.nat_iterate (primrec.const zero) (comp_prim.comp (primrec.const succ) primrec.snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, code.const, nat.iterate_succ'] theorem curry_prim : primrec₂ curry := comp_prim.comp primrec.fst $ pair_prim.comp (const_prim.comp primrec.snd) (primrec.const code.id) theorem exists_code {f : ℕ →. ℕ} : nat.partrec f ↔ ∃ c : code, eval c = f := ⟨λ h, begin induction h, case nat.partrec.zero { exact ⟨zero, rfl⟩ }, case nat.partrec.succ { exact ⟨succ, rfl⟩ }, case nat.partrec.left { exact ⟨left, rfl⟩ }, case nat.partrec.right { exact ⟨right, rfl⟩ }, case nat.partrec.pair : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨pair cf cg, rfl⟩ }, case nat.partrec.comp : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨comp cf cg, rfl⟩ }, case nat.partrec.prec : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨prec cf cg, rfl⟩ }, case nat.partrec.rfind : f pf hf { rcases hf with ⟨cf, rfl⟩, refine ⟨comp (rfind' cf) (pair code.id zero), _⟩, simp [eval, (<*>), pure, pfun.pure, roption.map_id'] }, end, λ h, begin rcases h with ⟨c, rfl⟩, induction c, case nat.partrec.code.zero { exact nat.partrec.zero }, case nat.partrec.code.succ { exact nat.partrec.succ }, case nat.partrec.code.left { exact nat.partrec.left }, case nat.partrec.code.right { exact nat.partrec.right }, case nat.partrec.code.pair : cf cg pf pg { exact pf.pair pg }, case nat.partrec.code.comp : cf cg pf pg { exact pf.comp pg }, case nat.partrec.code.prec : cf cg pf pg { exact pf.prec pg }, case nat.partrec.code.rfind' : cf pf { exact pf.rfind' }, end⟩ def evaln : ∀ k : ℕ, code → ℕ → option ℕ | 0 _ := λ m, none | (k+1) zero := λ n, guard (n ≤ k) >> pure 0 | (k+1) succ := λ n, guard (n ≤ k) >> pure (nat.succ n) | (k+1) left := λ n, guard (n ≤ k) >> pure n.unpair.1 | (k+1) right := λ n, guard (n ≤ k) >> pure n.unpair.2 | (k+1) (pair cf cg) := λ n, guard (n ≤ k) >> mkpair <$> evaln (k+1) cf n <*> evaln (k+1) cg n | (k+1) (comp cf cg) := λ n, guard (n ≤ k) >> do x ← evaln (k+1) cg n, evaln (k+1) cf x | (k+1) (prec cf cg) := λ n, guard (n ≤ k) >> n.unpaired (λ a n, n.cases (evaln (k+1) cf a) $ λ y, do i ← evaln k (prec cf cg) (mkpair a y), evaln (k+1) cg (mkpair a (mkpair y i))) | (k+1) (rfind' cf) := λ n, guard (n ≤ k) >> n.unpaired (λ a m, do x ← evaln (k+1) cf (mkpair a m), if x = 0 then pure m else evaln k (rfind' cf) (mkpair a (m+1))) theorem evaln_bound : ∀ {k c n x}, x ∈ evaln k c n → n < k | 0 c n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin suffices : ∀ {o : option ℕ}, x ∈ guard (n ≤ k) >> o → n < k + 1, { cases c; rw [evaln] at h; exact this h }, simp [(>>)], exact λ _ h _, nat.lt_succ_of_le h end theorem evaln_mono : ∀ {k₁ k₂ c n x}, k₁ ≤ k₂ → x ∈ evaln k₁ c n → x ∈ evaln k₂ c n | 0 k₂ c n x hl h := by simp [evaln] at h; cases h | (k+1) (k₂+1) c n x hl h := begin have hl' := nat.le_of_succ_le_succ hl, have : ∀ {k k₂ n x : ℕ} {o₁ o₂ : option ℕ}, k ≤ k₂ → (x ∈ o₁ → x ∈ o₂) → x ∈ guard (n ≤ k) >> o₁ → x ∈ guard (n ≤ k₂) >> o₂, { simp [(>>)], introv h h₁ h₂ h₃, exact ⟨le_trans h₂ h, h₁ h₃⟩ }, simp at h ⊢, induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; rw [evaln] at h ⊢; refine this hl' (λ h, _) h, iterate 4 {exact h}, { -- pair cf cg simp [(<*>)] at h ⊢, exact h.imp (λ a, and.imp (Exists.imp (λ b, and.imp_left (hf _ _))) (Exists.imp (λ b, and.imp_left (hg _ _)))) }, { -- comp cf cg simp at h ⊢, exact h.imp (λ a, and.imp (hg _ _) (hf _ _)) }, { -- prec cf cg revert h, simp, induction n.unpair.2; simp, { apply hf }, { exact λ y h₁ h₂, ⟨y, evaln_mono hl' h₁, hg _ _ h₂⟩ } }, { -- rfind' cf simp at h ⊢, refine h.imp (λ x, and.imp (hf _ _) _), by_cases x0 : x = 0; simp [x0], exact evaln_mono hl' } end theorem evaln_sound : ∀ {k c n x}, x ∈ evaln k c n → x ∈ eval c n | 0 _ n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; simp [eval, evaln, (>>), (<*>)] at h ⊢; cases h with _ h, iterate 4 {simpa [pure, pfun.pure, eq_comm] using h}, { -- pair cf cg rcases h with ⟨_, ⟨y, ef, rfl⟩, z, eg, rfl⟩, exact ⟨_, hf _ _ ef, _, hg _ _ eg, rfl⟩ }, { --comp hf hg rcases h with ⟨y, eg, ef⟩, exact ⟨_, hg _ _ eg, hf _ _ ef⟩ }, { -- prec cf cg revert h, induction n.unpair.2 with m IH generalizing x; simp, { apply hf }, { refine λ y h₁ h₂, ⟨y, IH _ _, _⟩, { have := evaln_mono k.le_succ h₁, simp [evaln, (>>)] at this, exact this.2 }, { exact hg _ _ h₂ } } }, { -- rfind' cf rcases h with ⟨m, h₁, h₂⟩, by_cases m0 : m = 0; simp [m0] at h₂, { exact ⟨0, ⟨by simpa [m0] using hf _ _ h₁, λ m, (nat.not_lt_zero _).elim⟩, by injection h₂ with h₂; simp [h₂]⟩ }, { have := evaln_sound h₂, simp [eval] at this, rcases this with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, refine ⟨y+1, ⟨by simpa using hy₁, λ i im, _⟩, by simp⟩, cases i with i, { exact ⟨m, by simpa using hf _ _ h₁, m0⟩ }, { rcases hy₂ (nat.lt_of_succ_lt_succ im) with ⟨z, hz, z0⟩, exact ⟨z, by simpa [nat.succ_eq_add_one] using hz, z0⟩ } } } end theorem evaln_complete {c n x} : x ∈ eval c n ↔ ∃ k, x ∈ evaln k c n := ⟨λ h, begin suffices : ∃ k, x ∈ evaln (k+1) c n, { exact let ⟨k, h⟩ := this in ⟨k+1, h⟩ }, induction c generalizing n x; simp [eval, evaln, pure, pfun.pure, (<*>), (>>)] at h ⊢, iterate 4 { exact ⟨⟨_, le_refl _⟩, h.symm⟩ }, case nat.partrec.code.pair : cf cg hf hg { rcases h with ⟨x, hx, y, hy, rfl⟩, rcases hf hx with ⟨k₁, hk₁⟩, rcases hg hy with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, exact ⟨le_max_left_of_le $ nat.le_of_lt_succ $ evaln_bound hk₁, _, ⟨_, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, rfl⟩, _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂, rfl⟩ }, case nat.partrec.code.comp : cf cg hf hg { rcases h with ⟨y, hy, hx⟩, rcases hg hy with ⟨k₁, hk₁⟩, rcases hf hx with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, exact ⟨le_max_left_of_le $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂⟩ }, case nat.partrec.code.prec : cf cg hf hg { revert h, generalize : n.unpair.1 = n₁, generalize : n.unpair.2 = n₂, induction n₂ with m IH generalizing x n; simp, { intro, rcases hf h with ⟨k, hk⟩, exact ⟨_, le_max_left _ _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk⟩ }, { intros y hy hx, rcases IH hy with ⟨k₁, nk₁, hk₁⟩, rcases hg hx with ⟨k₂, hk₂⟩, refine ⟨(max k₁ k₂).succ, nat.le_succ_of_le $ le_max_left_of_le $ le_trans (le_max_left _ (mkpair n₁ m)) nk₁, y, evaln_mono (nat.succ_le_succ $ le_max_left _ _) _, evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_right _ _) hk₂⟩, simp [evaln, (>>)], exact ⟨le_trans (le_max_right _ _) nk₁, hk₁⟩ } }, case nat.partrec.code.rfind' : cf hf { rcases h with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, suffices : ∃ k, y + n.unpair.2 ∈ evaln (k+1) (rfind' cf) (mkpair n.unpair.1 n.unpair.2), {simpa [evaln, (>>)]}, revert hy₁ hy₂, generalize : n.unpair.2 = m, intros, induction y with y IH generalizing m; simp [evaln, (>>)], { simp at hy₁, rcases hf hy₁ with ⟨k, hk⟩, exact ⟨_, nat.le_of_lt_succ $ evaln_bound hk, _, hk, by simp; refl⟩ }, { rcases hy₂ (nat.succ_pos _) with ⟨a, ha, a0⟩, rcases hf ha with ⟨k₁, hk₁⟩, rcases IH m.succ (by simpa [nat.succ_eq_add_one] using hy₁) (λ i hi, by simpa [nat.succ_eq_add_one] using hy₂ (nat.succ_lt_succ hi)) with ⟨k₂, hk₂⟩, simp at hk₁, exact ⟨(max k₁ k₂).succ, nat.le_succ_of_le $ le_max_left_of_le $ nat.le_of_lt_succ $ evaln_bound hk₁, a, evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_left _ _) hk₁, by simpa [nat.succ_eq_add_one, a0, -max_eq_left, -max_eq_right] using evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂⟩ } } end, λ ⟨k, h⟩, evaln_sound h⟩ section open primrec private def lup (L : list (list (option ℕ))) (p : ℕ × code) (n : ℕ) := do l ← L.nth (encode p), o ← l.nth n, o private lemma hlup : primrec (λ p:_×(_×_)×_, lup p.1 p.2.1 p.2.2) := option_bind (list_nth.comp fst (primrec.encode.comp $ fst.comp snd)) (option_bind (list_nth.comp snd $ snd.comp $ snd.comp fst) snd) private def G (L : list (list (option ℕ))) : option (list (option ℕ)) := option.some $ let a := of_nat (ℕ × code) L.length, k := a.1, c := a.2 in (list.range k).map (λ n, k.cases none $ λ k', nat.partrec.code.rec_on c (some 0) -- zero (some (nat.succ n)) (some n.unpair.1) (some n.unpair.2) (λ cf cg _ _, do x ← lup L (k, cf) n, y ← lup L (k, cg) n, some (mkpair x y)) (λ cf cg _ _, do x ← lup L (k, cg) n, lup L (k, cf) x) (λ cf cg _ _, let z := n.unpair.1 in n.unpair.2.cases (lup L (k, cf) z) (λ y, do i ← lup L (k', c) (mkpair z y), lup L (k, cg) (mkpair z (mkpair y i)))) (λ cf _, let z := n.unpair.1, m := n.unpair.2 in do x ← lup L (k, cf) (mkpair z m), x.cases (some m) (λ _, lup L (k', c) (mkpair z (m+1))))) private lemma hG : primrec G := begin have a := (primrec.of_nat (ℕ × code)).comp list_length, have k := fst.comp a, refine option_some.comp (list_map (list_range.comp k) (_ : primrec _)), replace k := k.comp fst, have n := snd, refine nat_cases k (const none) (_ : primrec _), have k := k.comp fst, have n := n.comp fst, have k' := snd, have c := snd.comp (a.comp $ fst.comp fst), apply rec_prim c (const (some 0)) (option_some.comp (primrec.succ.comp n)) (option_some.comp (fst.comp $ primrec.unpair.comp n)) (option_some.comp (snd.comp $ primrec.unpair.comp n)), { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cf).pair n) (option_map ((hlup.comp $ L.pair $ (k.pair cg).pair n).comp fst) (primrec₂.mkpair.comp (snd.comp fst) snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cg).pair n) (hlup.comp ((L.comp fst).pair $ ((k.pair cf).comp fst).pair snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, have z := fst.comp (primrec.unpair.comp n), refine nat_cases (snd.comp (primrec.unpair.comp n)) (hlup.comp $ L.pair $ (k.pair cf).pair z) (_ : primrec _), have L := L.comp fst, have z := z.comp fst, have y := snd, refine option_bind (hlup.comp $ L.pair $ (((k'.pair c).comp fst).comp fst).pair (primrec₂.mkpair.comp z y)) (_ : primrec _), have z := z.comp fst, have y := y.comp fst, have i := snd, exact hlup.comp ((L.comp fst).pair $ ((k.pair cg).comp $ fst.comp fst).pair $ primrec₂.mkpair.comp z $ primrec₂.mkpair.comp y i) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have z := fst.comp (primrec.unpair.comp n), have m := snd.comp (primrec.unpair.comp n), refine option_bind (hlup.comp $ L.pair $ (k.pair cf).pair (primrec₂.mkpair.comp z m)) (_ : primrec _), have m := m.comp fst, exact nat_cases snd (option_some.comp m) ((hlup.comp ((L.comp fst).pair $ ((k'.pair c).comp $ fst.comp fst).pair (primrec₂.mkpair.comp (z.comp fst) (primrec.succ.comp m)))).comp fst) } end private lemma evaln_map (k c n) : (((list.range k).nth n).map (evaln k c)).bind (λ b, b) = evaln k c n := begin by_cases kn : n < k, { simp [list.nth_range kn] }, { rw list.nth_ge_len, { cases e : evaln k c n, {refl}, exact kn.elim (evaln_bound e) }, simpa using kn } end theorem evaln_prim : primrec (λ (a : (ℕ × code) × ℕ), evaln a.1.1 a.1.2 a.2) := have primrec₂ (λ (_:unit) (n : ℕ), let a := of_nat (ℕ × code) n in (list.range a.1).map (evaln a.1 a.2)), from primrec.nat_strong_rec _ (hG.comp snd).to₂ $ λ _ p, begin simp [G], rw (_ : (of_nat (ℕ × code) _).snd = of_nat code p.unpair.2), swap, {simp}, apply list.map_congr (λ n, _), rw (by simp : list.range p = list.range (mkpair p.unpair.1 (encode (of_nat code p.unpair.2)))), generalize : p.unpair.1 = k, generalize : of_nat code p.unpair.2 = c, intro nk, cases k with k', {simp [evaln]}, let k := k'+1, change k'.succ with k, simp [nat.lt_succ_iff] at nk, have hg : ∀ {k' c' n}, mkpair k' (encode c') < mkpair k (encode c) → lup ((list.range (mkpair k (encode c))).map (λ n, (list.range n.unpair.1).map (evaln n.unpair.1 (of_nat code n.unpair.2)))) (k', c') n = evaln k' c' n, { intros k₁ c₁ n₁ hl, simp [lup, list.nth_range hl, evaln_map, (>>=)] }, cases c with cf cg cf cg cf cg cf; simp [evaln, nk, (>>), (>>=), (<$>), (<*>), pure], { cases encode_lt_pair cf cg with lf lg, rw [hg (nat.mkpair_lt_mkpair_right _ lf), hg (nat.mkpair_lt_mkpair_right _ lg)], cases evaln k cf n, {refl}, cases evaln k cg n; refl }, { cases encode_lt_comp cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lg), cases evaln k cg n, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lf)] }, { cases encode_lt_prec cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases n.unpair.2, {refl}, simp, rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self), cases evaln k' _ _, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lg)] }, { have lf := encode_lt_rfind' cf, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases evaln k cf n with x, {refl}, simp, cases x; simp [nat.succ_ne_zero], rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self) } end, (option_bind (list_nth.comp (this.comp (const ()) (encode_iff.2 fst)) snd) snd.to₂).of_eq $ λ ⟨⟨k, c⟩, n⟩, by simp [evaln_map] end section open partrec computable theorem eval_eq_rfind_opt (c n) : eval c n = nat.rfind_opt (λ k, evaln k c n) := roption.ext $ λ x, begin refine evaln_complete.trans (nat.rfind_opt_mono _).symm, intros a m n hl, apply evaln_mono hl, end theorem eval_part : partrec₂ eval := (rfind_opt (evaln_prim.to_comp.comp ((snd.pair (fst.comp fst)).pair (snd.comp fst))).to₂).of_eq $ λ a, by simp [eval_eq_rfind_opt] theorem fixed_point {f : code → code} (hf : computable f) : ∃ c : code, eval (f c) = eval c := begin let g : ℕ → ℕ →. ℕ := λ x y, roption.bind (eval (of_nat code x) x) (λ b, eval (of_nat code b) y), have : partrec₂ g := (eval_part.comp ((computable.of_nat _).comp fst) fst).bind (eval_part.comp ((computable.of_nat _).comp snd) (snd.comp fst)).to₂, rcases exists_code.1 this with ⟨cg, eg⟩, have := hf.comp (curry_prim.comp (primrec.const cg) primrec.id).to_comp, rcases exists_code.1 this with ⟨cF, eF⟩, refine ⟨curry cg (encode cF), funext $ λ n, _⟩, have := congr_fun eF (encode cF), simp at this, simp [eg, this, roption.map_id', g] end theorem fixed_point₂ {f : code → ℕ →. ℕ} (hf : partrec₂ f) : ∃ c : code, eval c = f c := let ⟨cf, ef⟩ := exists_code.1 hf in (fixed_point (curry_prim.comp (primrec.const cf) primrec.encode).to_comp).imp $ λ c e, funext $ λ n, by simp [e.symm, ef, roption.map_id'] end end nat.partrec.code
fb9518b5c8febe4ffa6be0ec0d22bdc3d1229963
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/idempotents/karoubi_karoubi.lean
12d9e69c2588bf1a3a541b23dfad31e2fdf3a729
[ "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,804
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.idempotents.karoubi /-! # Idempotence of the Karoubi envelope In this file, we construct the equivalence of categories `karoubi_karoubi.equivalence C : karoubi C ≌ karoubi (karoubi C)` for any category `C`. -/ open category_theory.category open category_theory.idempotents.karoubi namespace category_theory namespace idempotents namespace karoubi_karoubi variables (C : Type*) [category C] /-- The canonical functor `karoubi (karoubi C) ⥤ karoubi C` -/ @[simps] def inverse : karoubi (karoubi C) ⥤ karoubi C := { obj := λ P, ⟨P.X.X, P.p.f, by simpa only [hom_ext] using P.idem⟩, map := λ P Q f, ⟨f.f.f, by simpa only [hom_ext] using f.comm⟩, } instance [preadditive C] : functor.additive (inverse C) := { } /-- The unit isomorphism of the equivalence -/ @[simps] def unit_iso : 𝟭 (karoubi C) ≅ to_karoubi (karoubi C) ⋙ inverse C := eq_to_iso (functor.ext (by tidy) (by tidy)) /-- The counit isomorphism of the equivalence -/ @[simps] def counit_iso : inverse C ⋙ to_karoubi (karoubi C) ≅ 𝟭 (karoubi (karoubi C)) := { hom := { app := λ P, { f := { f := P.p.1, comm := begin have h := P.idem, simp only [hom_ext, comp_f] at h, erw [← assoc, h, comp_p], end, }, comm := begin have h := P.idem, simp only [hom_ext, comp_f] at h ⊢, erw [h, h], end, }, naturality' := λ P Q f, by simpa only [hom_ext] using (p_comm f).symm, }, inv := { app := λ P, { f := { f := P.p.1, comm := begin have h := P.idem, simp only [hom_ext, comp_f] at h, erw [h, p_comp], end, }, comm := begin have h := P.idem, simp only [hom_ext, comp_f] at h ⊢, erw [h, h], end, }, naturality' := λ P Q f, by simpa only [hom_ext] using (p_comm f).symm, }, hom_inv_id' := by { ext P, simpa only [hom_ext, id_eq] using P.idem, }, inv_hom_id' := by { ext P, simpa only [hom_ext, id_eq] using P.idem, }, } /-- The equivalence `karoubi C ≌ karoubi (karoubi C)` -/ @[simps] def equivalence : karoubi C ≌ karoubi (karoubi C) := { functor := to_karoubi (karoubi C), inverse := karoubi_karoubi.inverse C, unit_iso := karoubi_karoubi.unit_iso C, counit_iso := karoubi_karoubi.counit_iso C, } instance equivalence.additive_functor [preadditive C] : functor.additive (equivalence C).functor := by { dsimp, apply_instance, } instance equivalence.additive_inverse [preadditive C] : functor.additive (equivalence C).inverse := by { dsimp, apply_instance, } end karoubi_karoubi end idempotents end category_theory
e09d20beab0b48067b61085ac577ecc9c8f27fe7
6e41ee3ac9b96e8980a16295cc21f131e731884f
/library/data/nat/comm_semiring.lean
5474db55ab10001f46c7eb95cb9e51958d4928db
[ "Apache-2.0" ]
permissive
EgbertRijke/lean
3426cfa0e5b3d35d12fc3fd7318b35574cb67dc3
4f2e0c6d7fc9274d953cfa1c37ab2f3e799ab183
refs/heads/master
1,610,834,871,476
1,422,159,801,000
1,422,159,801,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,420
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.nat.comm_semiring Author: Jeremy Avigad ℕ is a comm_semiring. -/ import data.nat.basic algebra.binary algebra.ring open binary namespace nat section open [classes] algebra protected definition comm_semiring [instance] : algebra.comm_semiring nat := algebra.comm_semiring.mk add add.assoc zero zero_add add_zero add.comm mul mul.assoc (succ zero) one_mul mul_one mul.left_distrib mul.right_distrib zero_mul mul_zero (ne.symm (succ_ne_zero zero)) mul.comm end section port_algebra theorem mul.left_comm : ∀a b c : ℕ, a * (b * c) = b * (a * c) := algebra.mul.left_comm theorem mul.right_comm : ∀a b c : ℕ, (a * b) * c = (a * c) * b := algebra.mul.right_comm definition dvd (a b : ℕ) : Prop := algebra.dvd a b infix `|` := dvd theorem dvd.intro : ∀{a b c : ℕ} (H : a * b = c), a | c := @algebra.dvd.intro _ _ theorem dvd.ex : ∀{a b : ℕ} (H : a | b), ∃c, a * c = b := @algebra.dvd.ex _ _ theorem dvd.elim : ∀{P : Prop} {a b : ℕ} (H₁ : a | b) (H₂ : ∀c, a * c = b → P), P := @algebra.dvd.elim _ _ theorem dvd.refl : ∀a : ℕ, a | a := algebra.dvd.refl theorem dvd.trans : ∀{a b c : ℕ} (H₁ : a | b) (H₂ : b | c), a | c := @algebra.dvd.trans _ _ theorem eq_zero_of_zero_dvd : ∀{a : ℕ} (H : 0 | a), a = 0 := @algebra.eq_zero_of_zero_dvd _ _ theorem dvd_zero : ∀a : ℕ, a | 0 := algebra.dvd_zero theorem one_dvd : ∀a : ℕ, 1 | a := algebra.one_dvd theorem dvd_mul_right : ∀a b : ℕ, a | a * b := algebra.dvd_mul_right theorem dvd_mul_left : ∀a b : ℕ, a | b * a := algebra.dvd_mul_left theorem dvd_mul_of_dvd_left : ∀{a b : ℕ} (H : a | b) (c : ℕ), a | b * c := @algebra.dvd_mul_of_dvd_left _ _ theorem dvd_mul_of_dvd_right : ∀{a b : ℕ} (H : a | b) (c : ℕ), a | c * b := @algebra.dvd_mul_of_dvd_right _ _ theorem mul_dvd_mul : ∀{a b c d : ℕ}, a | b → c | d → a * c | b * d := @algebra.mul_dvd_mul _ _ theorem dvd_of_mul_right_dvd : ∀{a b c : ℕ}, a * b | c → a | c := @algebra.dvd_of_mul_right_dvd _ _ theorem dvd_of_mul_left_dvd : ∀{a b c : ℕ}, a * b | c → b | c := @algebra.dvd_of_mul_left_dvd _ _ theorem dvd_add : ∀{a b c : ℕ}, a | b → a | c → a | b + c := @algebra.dvd_add _ _ end port_algebra end nat
d0406416c2be06dc0f0395098a553d429e787595
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/hott/homotopy/smash.hlean
839847b0fab1299af2a1e4087159e77ecdef235a
[ "Apache-2.0" ]
permissive
tectronics/lean
ab977ba6be0fcd46047ddbb3c8e16e7c26710701
f38af35e0616f89c6e9d7e3eb1d48e47ee666efe
refs/heads/master
1,532,358,526,384
1,456,276,623,000
1,456,276,623,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,358
hlean
/- Copyright (c) 2016 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer The Smash Product of Types -/ import hit.pushout .wedge .cofiber .susp .sphere open eq pushout prod pointed pType is_trunc definition product_of_wedge [constructor] (A B : Type*) : pwedge A B →* A ×* B := begin fconstructor, intro x, induction x with [a, b], exact (a, point B), exact (point A, b), do 2 reflexivity end definition psmash (A B : Type*) := pcofiber (product_of_wedge A B) open sphere susp unit namespace smash protected definition prec {X Y : Type*} {P : psmash X Y → Type} (pxy : Π x y, P (inr (x, y))) (ps : P (inl ⋆)) (px : Π x, pathover P ps (glue (inl x)) (pxy x (point Y))) (py : Π y, pathover P ps (glue (inr y)) (pxy (point X) y)) (pg : pathover (λ x, pathover P ps (glue x) (@prod.rec X Y (λ x, P (inr x)) pxy (pushout.elim (λ a, (a, Point Y)) (pair (Point X)) (λ x, idp) x))) (px (Point X)) (glue ⋆) (py (Point Y))) : Π s, P s := begin intro s, induction s, induction x, exact ps, induction x with [x, y], exact pxy x y, induction x with [x, y, u], exact px x, exact py y, induction u, exact pg, end protected definition prec_on {X Y : Type*} {P : psmash X Y → Type} (s : psmash X Y) (pxy : Π x y, P (inr (x, y))) (ps : P (inl ⋆)) (px : Π x, pathover P ps (glue (inl x)) (pxy x (point Y))) (py : Π y, pathover P ps (glue (inr y)) (pxy (point X) y)) (pg : pathover (λ x, pathover P ps (glue x) (@prod.rec X Y (λ x, P (inr x)) pxy (pushout.elim (λ a, (a, Point Y)) (pair (Point X)) (λ x, idp) x))) (px (Point X)) (glue ⋆) (py (Point Y))) : P s := smash.prec pxy ps px py pg s /- definition smash_bool (X : Type*) : psmash X pbool ≃* X := begin fconstructor, { fconstructor, { intro x, fapply cofiber.pelim_on x, clear x, exact point X, intro p, cases p with [x', b], cases b with [x, x'], exact point X, exact x', clear x, intro w, induction w with [y, b], reflexivity, cases b, reflexivity, reflexivity, esimp, apply eq_pathover, refine !ap_constant ⬝ph _, cases x, esimp, apply hdeg_square, apply inverse, apply concat, apply ap_compose (λ a, prod.cases_on a _), apply concat, apply ap _ !elim_glue, reflexivity }, reflexivity }, { fapply is_equiv.adjointify, { intro x, apply inr, exact pair x bool.tt }, { intro x, reflexivity }, { intro s, esimp, induction s, { cases x, apply (glue (inr bool.tt))⁻¹ }, { cases x with [x, b], cases b, apply inverse, apply concat, apply (glue (inl x))⁻¹, apply (glue (inr bool.tt)), reflexivity }, { esimp, apply eq_pathover, induction x, esimp, apply hinverse, krewrite ap_id, apply move_bot_of_left, krewrite con.right_inv, refine _ ⬝hp !(ap_compose (λ a, inr (pair a _)))⁻¹, apply transpose, apply square_of_eq_bot, rewrite [con_idp, con.left_inv], apply inverse, apply concat, apply ap (ap _), } } } definition susp_equiv_circle_smash (X : Type*) : psusp X ≃* psmash (psphere 1) X := begin fconstructor, { fconstructor, intro x, induction x, }, end-/ end smash
55d6ddfa636ca42838bd15ea5f5e8791e1f4fa5d
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/tactic/aesop/percent.lean
a4a98f8b45fa30f305e255950d3e8e940be9f52d
[ "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
1,381
lean
/- Copyright (c) 2021 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import tactic.core namespace tactic.aesop /- Invariant: between 0 and 100 -/ @[derive has_reflect] structure percent := (to_nat : ℕ) namespace percent protected def of_nat (n : ℕ) : option percent := if n <= 100 then some ⟨n⟩ else none protected def mul (p q : percent) : percent := ⟨max 1 ((p.to_nat * q.to_nat) / 100)⟩ instance : has_mul percent := ⟨percent.mul⟩ protected def lt (p q : percent) : Prop := p.to_nat < q.to_nat instance : has_lt percent := ⟨percent.lt⟩ instance : decidable_rel ((<) : percent → percent → Prop) := λ p q, (infer_instance : decidable (p.to_nat < q.to_nat)) protected def to_string (p : percent) : string := to_string p.to_nat ++ "%" instance : has_to_string percent := ⟨percent.to_string⟩ protected meta def to_fmt (p : percent) : format := p.to_string meta instance : has_to_format percent := ⟨percent.to_fmt⟩ open lean open lean.parser meta def parser : parser percent := do n ← small_nat <|> interaction_monad.fail "expected number between 0 and 100", match percent.of_nat n with | some p := pure p | none := interaction_monad.fail $ format! "expected number between 0 and 100 but got: {n}" end end percent end tactic.aesop
c06608dc2811680ba814672e8e1d5ba53d39e731
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/list/chain.lean
98a10e2b667ca0403d033b660b97ef5fdd030f68
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
12,552
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, Yury Kudryashov -/ import data.list.pairwise import logic.relation universes u v open nat variables {α : Type u} {β : Type v} namespace list /- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/ mk_iff_of_inductive_prop list.chain list.chain_iff variable {R : α → α → Prop} theorem rel_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : R a b := (chain_cons.1 p).1 theorem chain_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : chain R b l := (chain_cons.1 p).2 theorem chain.imp' {S : α → α → Prop} (HRS : ∀ ⦃a b⦄, R a b → S a b) {a b : α} (Hab : ∀ ⦃c⦄, R a c → S b c) {l : list α} (p : chain R a l) : chain S b l := by induction p with _ a c l r p IH generalizing b; constructor; [exact Hab r, exact IH (@HRS _)] theorem chain.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l := p.imp' H (H a) theorem chain.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l := ⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩ theorem chain.iff_mem {a : α} {l : list α} : chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l := ⟨λ p, by induction p with _ a b l r p IH; constructor; [exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩, exact IH.imp (λ a b ⟨am, bm, h⟩, ⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)], chain.imp (λ a b h, h.2.2)⟩ theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b := by simp only [chain_cons, chain.nil, and_true] theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔ chain R a (l₁++[b]) ∧ chain R b l₂ := by induction l₁ with x l₁ IH generalizing a; simp only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, and_assoc] theorem chain_map (f : β → α) {b : β} {l : list β} : chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l := by induction l generalizing b; simp only [map, chain.nil, chain_cons, *] theorem chain_of_chain_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α} (p : chain S (f a) (map f l)) : chain R a l := ((chain_map f).1 p).imp H theorem chain_map_of_chain {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α} (p : chain R a l) : chain S (f a) (map f l) := (chain_map f).2 $ p.imp H theorem chain_pmap_of_chain {S : β → β → Prop} {p : α → Prop} {f : Π a, p a → β} (H : ∀ a b ha hb, R a b → S (f a ha) (f b hb)) {a : α} {l : list α} (hl₁ : chain R a l) (ha : p a) (hl₂ : ∀ a ∈ l, p a) : chain S (f a ha) (list.pmap f l hl₂) := begin induction l with lh lt l_ih generalizing a, { simp }, { simp [H _ _ _ _ (rel_of_chain_cons hl₁), l_ih _ (chain_of_chain_cons hl₁)] } end theorem chain_of_chain_pmap {S : β → β → Prop} {p : α → Prop} (f : Π a, p a → β) {l : list α} (hl₁ : ∀ a ∈ l, p a) {a : α} (ha : p a) (hl₂ : chain S (f a ha) (list.pmap f l hl₁)) (H : ∀ a b ha hb, S (f a ha) (f b hb) → R a b) : chain R a l := begin induction l with lh lt l_ih generalizing a, { simp }, { simp [H _ _ _ _ (rel_of_chain_cons hl₂), l_ih _ _ (chain_of_chain_cons hl₂)] } end theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l := begin cases pairwise_cons.1 p with r p', clear p, induction p' with b l r' p IH generalizing a, {exact chain.nil}, simp only [chain_cons, forall_mem_cons] at r, exact chain_cons.2 ⟨r.1, IH r'⟩ end theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} : chain R a l ↔ pairwise R (a::l) := ⟨λ c, begin induction c with b b c l r p IH, {exact pairwise_singleton _ _}, apply IH.cons _, simp only [mem_cons_iff, forall_eq_or_imp, r, true_and], show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)), end, chain_of_pairwise⟩ theorem chain_iff_nth_le {R} : ∀ {a : α} {l : list α}, chain R a l ↔ (∀ h : 0 < length l, R a (nth_le l 0 h)) ∧ (∀ i (h : i < length l - 1), R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h))) | a [] := by simp | a (b :: t) := begin rw [chain_cons, chain_iff_nth_le], split, { rintros ⟨R, ⟨h0, h⟩⟩, split, { intro w, exact R, }, { intros i w, cases i, { apply h0, }, { convert h i _ using 1, simp only [succ_eq_add_one, add_succ_sub_one, add_zero, length, add_lt_add_iff_right] at w, exact lt_pred_iff.mpr w, } } }, { rintros ⟨h0, h⟩, split, { apply h0, simp, }, { split, { apply h 0, }, { intros i w, convert h (i+1) _, exact lt_pred_iff.mp w, } } }, end theorem chain'.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} (p : chain' R l) : chain' S l := by cases l; [trivial, exact p.imp H] theorem chain'.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : chain' R l ↔ chain' S l := ⟨chain'.imp (λ a b, (H a b).1), chain'.imp (λ a b, (H a b).2)⟩ theorem chain'.iff_mem : ∀ {l : list α}, chain' R l ↔ chain' (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l | [] := iff.rfl | (x::l) := ⟨λ h, (chain.iff_mem.1 h).imp $ λ a b ⟨h₁, h₂, h₃⟩, ⟨h₁, or.inr h₂, h₃⟩, chain'.imp $ λ a b h, h.2.2⟩ @[simp] theorem chain'_nil : chain' R [] := trivial @[simp] theorem chain'_singleton (a : α) : chain' R [a] := chain.nil theorem chain'_split {a : α} : ∀ {l₁ l₂ : list α}, chain' R (l₁++a::l₂) ↔ chain' R (l₁++[a]) ∧ chain' R (a::l₂) | [] l₂ := (and_iff_right (chain'_singleton a)).symm | (b::l₁) l₂ := chain_split theorem chain'_map (f : β → α) {l : list β} : chain' R (map f l) ↔ chain' (λ a b : β, R (f a) (f b)) l := by cases l; [refl, exact chain_map _] theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : chain' S (map f l)) : chain' R l := ((chain'_map f).1 p).imp H theorem chain'_map_of_chain' {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : chain' R l) : chain' S (map f l) := (chain'_map f).2 $ p.imp H theorem pairwise.chain' : ∀ {l : list α}, pairwise R l → chain' R l | [] _ := trivial | (a::l) h := chain_of_pairwise h theorem chain'_iff_pairwise (tr : transitive R) : ∀ {l : list α}, chain' R l ↔ pairwise R l | [] := (iff_true_intro pairwise.nil).symm | (a::l) := chain_iff_pairwise tr @[simp] theorem chain'_cons {x y l} : chain' R (x :: y :: l) ↔ R x y ∧ chain' R (y :: l) := chain_cons theorem chain'.cons {x y l} (h₁ : R x y) (h₂ : chain' R (y :: l)) : chain' R (x :: y :: l) := chain'_cons.2 ⟨h₁, h₂⟩ theorem chain'.tail : ∀ {l} (h : chain' R l), chain' R l.tail | [] _ := trivial | [x] _ := trivial | (x :: y :: l) h := (chain'_cons.mp h).right theorem chain'.rel_head {x y l} (h : chain' R (x :: y :: l)) : R x y := rel_of_chain_cons h theorem chain'.rel_head' {x l} (h : chain' R (x :: l)) ⦃y⦄ (hy : y ∈ head' l) : R x y := by { rw ← cons_head'_tail hy at h, exact h.rel_head } theorem chain'.cons' {x} : ∀ {l : list α}, chain' R l → (∀ y ∈ l.head', R x y) → chain' R (x :: l) | [] _ _ := chain'_singleton x | (a :: l) hl H := hl.cons $ H _ rfl theorem chain'_cons' {x l} : chain' R (x :: l) ↔ (∀ y ∈ head' l, R x y) ∧ chain' R l := ⟨λ h, ⟨h.rel_head', h.tail⟩, λ ⟨h₁, h₂⟩, h₂.cons' h₁⟩ theorem chain'.append : ∀ {l₁ l₂ : list α} (h₁ : chain' R l₁) (h₂ : chain' R l₂) (h : ∀ (x ∈ l₁.last') (y ∈ l₂.head'), R x y), chain' R (l₁ ++ l₂) | [] l₂ h₁ h₂ h := h₂ | [a] l₂ h₁ h₂ h := h₂.cons' $ h _ rfl | (a::b::l) l₂ h₁ h₂ h := begin simp only [last'] at h, have : chain' R (b::l) := h₁.tail, exact (this.append h₂ h).cons h₁.rel_head end theorem chain'_pair {x y} : chain' R [x, y] ↔ R x y := by simp only [chain'_singleton, chain'_cons, and_true] theorem chain'.imp_head {x y} (h : ∀ {z}, R x z → R y z) {l} (hl : chain' R (x :: l)) : chain' R (y :: l) := hl.tail.cons' $ λ z hz, h $ hl.rel_head' hz theorem chain'_reverse : ∀ {l}, chain' R (reverse l) ↔ chain' (flip R) l | [] := iff.rfl | [a] := by simp only [chain'_singleton, reverse_singleton] | (a :: b :: l) := by rw [chain'_cons, reverse_cons, reverse_cons, append_assoc, cons_append, nil_append, chain'_split, ← reverse_cons, @chain'_reverse (b :: l), and_comm, chain'_pair, flip] theorem chain'_iff_nth_le {R} : ∀ {l : list α}, chain' R l ↔ ∀ i (h : i < length l - 1), R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h)) | [] := by simp | (a :: nil) := by simp | (a :: b :: t) := begin rw [chain'_cons, chain'_iff_nth_le], split, { rintros ⟨R, h⟩ i w, cases i, { exact R, }, { convert h i _ using 1, simp only [succ_eq_add_one, add_succ_sub_one, add_zero, length, add_lt_add_iff_right] at w, simpa using w, }, }, { rintros h, split, { apply h 0, simp, }, { intros i w, convert h (i+1) _, simp only [add_zero, length, add_succ_sub_one] at w, simpa using w, } }, end /-- If `l₁ l₂` and `l₃` are lists and `l₁ ++ l₂` and `l₂ ++ l₃` both satisfy `chain' R`, then so does `l₁ ++ l₂ ++ l₃` provided `l₂ ≠ []` -/ lemma chain'.append_overlap : ∀ {l₁ l₂ l₃ : list α} (h₁ : chain' R (l₁ ++ l₂)) (h₂ : chain' R (l₂ ++ l₃)) (hn : l₂ ≠ []), chain' R (l₁ ++ l₂ ++ l₃) | [] l₂ l₃ h₁ h₂ hn := h₂ | l₁ [] l₃ h₁ h₂ hn := (hn rfl).elim | [a] (b::l₂) l₃ h₁ h₂ hn := by { simp at *, tauto } | (a::b::l₁) (c::l₂) l₃ h₁ h₂ hn := begin simp only [cons_append, chain'_cons] at h₁ h₂ ⊢, simp only [← cons_append] at h₁ h₂ ⊢, exact ⟨h₁.1, chain'.append_overlap h₁.2 h₂ (cons_ne_nil _ _)⟩ end variables {r : α → α → Prop} {a b : α} /-- If `a` and `b` are related by the reflexive transitive closure of `r`, then there is a `r`-chain starting from `a` and ending on `b`. The converse of `relation_refl_trans_gen_of_exists_chain`. -/ lemma exists_chain_of_relation_refl_trans_gen (h : relation.refl_trans_gen r a b) : ∃ l, chain r a l ∧ last (a :: l) (cons_ne_nil _ _) = b := begin apply relation.refl_trans_gen.head_induction_on h, { exact ⟨[], chain.nil, rfl⟩ }, { intros c d e t ih, obtain ⟨l, hl₁, hl₂⟩ := ih, refine ⟨d :: l, chain.cons e hl₁, _⟩, rwa last_cons_cons } end /-- Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y → p y → p x` then the predicate is true everywhere in the chain and at `a`. That is, we can propagate the predicate up the chain. -/ lemma chain.induction (p : α → Prop) (l : list α) (h : chain r a l) (hb : last (a :: l) (cons_ne_nil _ _) = b) (carries : ∀ ⦃x y : α⦄, r x y → p y → p x) (final : p b) : ∀ i ∈ a :: l, p i := begin induction l generalizing a, { cases hb, simp [final] }, { rw chain_cons at h, rintro _ (rfl | _), apply carries h.1 (l_ih h.2 hb _ (or.inl rfl)), apply l_ih h.2 hb _ H } end /-- Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y → p y → p x` then the predicate is true at `a`. That is, we can propagate the predicate all the way up the chain. -/ @[elab_as_eliminator] lemma chain.induction_head (p : α → Prop) (l : list α) (h : chain r a l) (hb : last (a :: l) (cons_ne_nil _ _) = b) (carries : ∀ ⦃x y : α⦄, r x y → p y → p x) (final : p b) : p a := (chain.induction p l h hb carries final) _ (mem_cons_self _ _) /-- If there is an `r`-chain starting from `a` and ending at `b`, then `a` and `b` are related by the reflexive transitive closure of `r`. The converse of `exists_chain_of_relation_refl_trans_gen`. -/ lemma relation_refl_trans_gen_of_exists_chain (l) (hl₁ : chain r a l) (hl₂ : last (a :: l) (cons_ne_nil _ _) = b) : relation.refl_trans_gen r a b := chain.induction_head _ l hl₁ hl₂ (λ x y, relation.refl_trans_gen.head) relation.refl_trans_gen.refl end list
98dc62577561283ae1211c3746572c8ee093c9ed
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/field/canonical/basic.lean
90e5f56e0bb7df177eda94c80d0ffa23b998ba5c
[ "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
709
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Mario Carneiro, Floris van Doorn -/ import algebra.order.field.canonical.defs /-! # Lemmas about canonically ordered semifields. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α : Type*} section canonically_linear_ordered_semifield variables [canonically_linear_ordered_semifield α] [has_sub α] [has_ordered_sub α] lemma tsub_div (a b c : α) : (a - b) / c = a / c - b / c := by simp_rw [div_eq_mul_inv, tsub_mul] end canonically_linear_ordered_semifield
51ef04fc290cbb634363c54735f9ad5de29fff42
2cf781335f4a6706b7452ab07ce323201e2e101f
/lean/deps/sexpr/src/galois/sexpr.lean
dbbc6ac1bd7205f16ce7f4a768406e8165f47533
[ "Apache-2.0" ]
permissive
simonjwinwood/reopt-vcg
697cdd5e68366b5aa3298845eebc34fc97ccfbe2
6aca24e759bff4f2230bb58270bac6746c13665e
refs/heads/master
1,586,353,878,347
1,549,667,148,000
1,549,667,148,000
159,409,828
0
0
null
1,543,358,444,000
1,543,358,444,000
null
UTF-8
Lean
false
false
5,935
lean
/- This declares an s-expression datatype for generating expressions and reasoning about their interpretation. -/ import system.io import data.array.lemmas -- from mathlib import galois.category.except import galois.data.array import galois.data.buffer import galois.data.list import galois.data.nat import .char_reader universes u v w namespace sexpr class is_atom (α : Type _) := (to_char_buffer : α → char_buffer) (read {m} [char_reader string m] (n:ℕ) : m α) end sexpr /-- Data-structure for representing s-expressions. The internal types are strictly general than what one may ordinarily expect of s-expressions to allow arbitrary strings to be converted into s-expressions, and concatenating two s-expressions. We do add a decidable_eq instance for s-expressions, but it is structural and two s expressions may be distinct, but render to the same string. The intent is to allow one to efficiently generate s-expressions, do lightweight pattern matching on them, and write them to handles. -/ inductive sexpr (α:Type) | atom : α -> sexpr | parens : list sexpr -> sexpr namespace sexpr protected def mk_atom {α:Type} (c:α) : sexpr α := sexpr.atom c protected def nil {α:Type} : sexpr α := sexpr.parens [] /-- Render s-expression as a string -/ mutual def render, list_render {α:Type} [h : is_atom α] {β} [has_append β] (rend : char_buffer → β) with render : sexpr α -> β | (atom s) := rend (@is_atom.to_char_buffer _ h s) | (parens []) := rend "()".to_char_buffer | (parens (h::t)) := rend "(".to_char_buffer ++ render h ++ list_render t with list_render : list (sexpr α) -> β | [] := rend ")".to_char_buffer | (s :: ss) := rend " ".to_char_buffer ++ render s ++ list_render ss /-- Render s-expression as a string -/ def repr {α:Type} [h : is_atom α] : sexpr α -> string := render buffer.to_string instance {α} [is_atom α] : has_repr (sexpr α) := { repr := sexpr.repr } /-- Construct an s-expression from a list of s-expressions -/ protected def of_list {α} : list (sexpr α) → sexpr α := sexpr.parens /-- A frame represents the first part of an s-expression that started with a open-paren -/ structure frame (α:Type) := (exprs : list (sexpr α)) namespace frame /-- Create an empty frame -/ def nil {α} : frame α := ⟨[]⟩ /-- Close a frame by appending close paren -/ def close {α} (f:frame α) : sexpr α := sexpr.parens f.exprs.reverse /-- This adds the partial token as an sexpression if the token is non-empty -/ def append_sexpr {α} (f:frame α) (t:sexpr α) : frame α := ⟨ t :: f.exprs⟩ /-- This adds the partial token as an sexpression if the token is non-empty -/ def append_frame {α} (f:frame α) (t:frame α) : frame α := append_sexpr f t.close end frame section open char_reader /-- The character after an atom should be empty or a close paren or whitespace. -/ def check_atom_term {m} [char_reader string m] : m unit := do mc ← peek_char, match mc with | option.none := pure () | (option.some c) := do when (c ∉ ['(', ')'] ∧ ¬c.is_whitespace) (throw ("Unexpected character "++ c.repr)), consume_char end /-- Read the s-expression from the handle/ -/ def read_core {α:Type} [is_atom α] {m} [char_reader string m] : ℕ → list (frame α) → m (sexpr α) | nat.zero frames := do throw "out of gas" | (nat.succ n) frames := (do mc ← peek_char, match mc with | option.none := throw "Unexpected end of expression." | option.some '(' := do consume_char *> read_core n (frame.nil :: frames) | option.some ')' := do match frames with | [] := throw "unexpected close paren" | (top_frame::lower_frames) := do consume_char, match lower_frames with | [] := do pure top_frame.close | (return_frame::rest_frames) := read_core n (frame.append_frame return_frame top_frame :: rest_frames) end end | option.some c := if c.is_whitespace then do consume_char, read_core n frames else do a ← sexpr.mk_atom <$> is_atom.read α n, check_atom_term, match frames with | [] := pure a | (top_frame::lower_frames) := do read_core n (top_frame.append_sexpr a :: lower_frames) end end) /-- Read the s-expression from the handle/ -/ def read (α:Type) [i:is_atom α] {m} [char_reader string m] (gas : ℕ) : m (sexpr α) := @read_core α i _ _ gas [] end local attribute [instance] char_reader.handle_char_reader.string_is_char_reader /-- Read the s-expression from the handle/ -/ def read_from_handle {α} [i:is_atom α] (h:io.handle) : io (except string (sexpr α)) := do let gas : ℕ := 2^64-1 in char_reader.read_from_handle h (@sexpr.read α i _ _ gas) --local attribute [instance] string_char_reader.string_is_char_reader /-- Parse the string as an s-expression -/ def parse {α:Type} [i:is_atom α] (s:string) : except string (sexpr α) := let gas : ℕ := 2^64-1 in char_reader.read_from_string s (@sexpr.read α i _ _ gas) /-- Write the s-expression to the handle. -/ def write {α} [is_atom α] (h:io.handle) (s:sexpr α) : io unit := @sexpr.render α _ (io unit) {append := λx y, x >> y} (io.fs.write h) s local infixr `<+>`:50 := sexpr.append -- Create an operation applied to some argumen ts. def app {α} (op:sexpr α) (args : list (sexpr α)) : sexpr α := sexpr.parens (op :: args) /-- Apply an binary operation to two sexpressions. -/ def bin_app {α} (op:sexpr α) (x y : sexpr α) : sexpr α := sexpr.parens [op, x,y] instance (α) [decidable_eq α] : decidable_eq (sexpr α) := by tactic.mk_dec_eq_instance meta def exact_trivial_tac : tactic unit := `[exact trivial] /- Construct an atom from a string literal. -/ def of_string {α} [i:is_atom α] (nm:string) (p : except.is_ok (char_reader.read_from_string nm (@sexpr.read α i _ _ 1024)) . exact_trivial_tac) : sexpr α := p.value end sexpr
4d1992c58b998fecf298fa1f286dbc4d12f51a61
d3aa99b88d7159fbbb8ab10d699374ab7be89e03
/src/measure_theory/integration.lean
4fe02af799a08573bfeb837ccea0cb5986b53027
[ "Apache-2.0" ]
permissive
mzinkevi/mathlib
62e0920edaf743f7fc53aaf42a08e372954af298
c718a22925872db4cb5f64c36ed6e6a07bdf647c
refs/heads/master
1,599,359,590,404
1,573,098,221,000
1,573,098,221,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
46,318
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl Lebesgue integral on `ennreal`. We define simple functions and show that each Borel measurable function on `ennreal` can be approximated by a sequence of simple functions. -/ import algebra.pi_instances measure_theory.measure_space measure_theory.borel_space noncomputable theory open lattice set filter open_locale classical section sequence_of_directed variables {α : Type*} {β : Type*} [encodable α] [inhabited α] open encodable noncomputable def sequence_of_directed (r : β → β → Prop) (f : α → β) (hf : directed r f) : ℕ → α | 0 := default α | (n + 1) := let p := sequence_of_directed n in match decode α n with | none := p | (some a) := classical.some (hf p a) end lemma monotone_sequence_of_directed [partial_order β] (f : α → β) (hf : directed (≤) f) : monotone (f ∘ sequence_of_directed (≤) f hf) := monotone_of_monotone_nat $ assume n, begin dsimp [sequence_of_directed], generalize eq : sequence_of_directed (≤) f hf n = p, cases h : decode α n with a, { refl }, { exact (classical.some_spec (hf p a)).1 } end lemma le_sequence_of_directed [partial_order β] (f : α → β) (hf : directed (≤) f) (a : α) : f a ≤ f (sequence_of_directed (≤) f hf (encode a + 1)) := begin simp [sequence_of_directed, -add_comm, encodek], exact (classical.some_spec (hf _ a)).2 end end sequence_of_directed namespace measure_theory variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) := (to_fun : α → β) (measurable_sn : ∀ x, is_measurable (to_fun ⁻¹' {x})) (finite : (set.range to_fun).finite) local infixr ` →ₛ `:25 := simple_func namespace simple_func section measurable variables [measurable_space α] instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) := ⟨_, to_fun⟩ @[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g := by cases f; cases g; congr; exact funext H protected def range (f : α →ₛ β) := f.finite.to_finset @[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ ∃ a, f a = b := finite.mem_to_finset def const (α) {β} [measurable_space α] (b : β) : α →ₛ β := ⟨λ a, b, λ x, is_measurable.const _, finite_subset (set.finite_singleton b) $ by rintro _ ⟨a, rfl⟩; simp⟩ @[simp] theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl lemma range_const (α) [measurable_space α] [ne : nonempty α] (b : β) : (const α b).range = {b} := begin ext b', simp [mem_range], exact ⟨assume ⟨_, h⟩, h.symm, assume h, ne.elim $ λa, ⟨a, h.symm⟩⟩ end lemma is_measurable_cut (p : α → β → Prop) (f : α →ₛ β) (h : ∀b, is_measurable {a | p a b}) : is_measurable {a | p a (f a)} := begin rw (_ : {a | p a (f a)} = ⋃ b ∈ set.range f, {a | p a b} ∩ f ⁻¹' {b}), { exact is_measurable.bUnion (countable_finite f.finite) (λ b _, is_measurable.inter (h b) (f.measurable_sn _)) }, ext a, simp, exact ⟨λ h, ⟨_, ⟨a, rfl⟩, h, rfl⟩, λ ⟨_, ⟨a', rfl⟩, h', e⟩, e.symm ▸ h'⟩ end theorem preimage_measurable (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) := is_measurable_cut (λ _ b, b ∈ s) f (λ b, by simp [is_measurable.const]) theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f := λ s _, preimage_measurable f s def ite {s : set α} (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β := ⟨λ a, if a ∈ s then f a else g a, λ x, by letI : measurable_space β := ⊤; exact measurable.if hs f.measurable g.measurable _ trivial, finite_subset (finite_union f.finite g.finite) begin rintro _ ⟨a, rfl⟩, by_cases a ∈ s; simp [h], exacts [or.inl ⟨_, rfl⟩, or.inr ⟨_, rfl⟩] end⟩ @[simp] theorem ite_apply {s : set α} (hs : is_measurable s) (f g : α →ₛ β) (a) : ite hs f g a = if a ∈ s then f a else g a := rfl def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ := ⟨λa, g (f a) a, λ c, is_measurable_cut (λa b, g b a ∈ ({c} : set γ)) f (λ b, (g b).measurable_sn c), finite_subset (finite_bUnion f.finite (λ b, (g b).finite)) $ by rintro _ ⟨a, rfl⟩; simp; exact ⟨_, ⟨a, rfl⟩, _, rfl⟩⟩ @[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) : f.bind g a = g (f a) a := rfl def restrict [has_zero β] (f : α →ₛ β) (s : set α) : α →ₛ β := if hs : is_measurable s then ite hs f (const α 0) else const α 0 @[simp] theorem restrict_apply [has_zero β] (f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) : restrict f s a = if a ∈ s then f a else 0 := by unfold_coes; simp [restrict, hs]; apply ite_apply hs theorem restrict_preimage [has_zero β] (f : α →ₛ β) {s : set α} (hs : is_measurable s) {t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by ext a; dsimp [preimage]; rw [restrict_apply]; by_cases a ∈ s; simp [h, hs, ht] def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g) @[simp] theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl @[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) : (f.map g).range = f.range.image g := begin ext c, simp [mem_range], split, { rintros ⟨a, rfl⟩, exact ⟨f a, ⟨_, rfl⟩, rfl⟩ }, { rintros ⟨_, ⟨a, rfl⟩, rfl⟩, exact ⟨_, rfl⟩ } end def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f) def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g @[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩ instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩ instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩ instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩ instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩ instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩ @[simp] lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl @[simp] lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl lemma add_apply [has_add β] (f g : α →ₛ β) (a : α) : (f + g) a = f a + g a := rfl lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) := rfl lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) := rfl lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl instance [add_monoid β] : add_monoid (α →ₛ β) := { add := (+), zero := 0, add_assoc := assume f g h, ext (assume a, add_assoc _ _ _), zero_add := assume f, ext (assume a, zero_add _), add_zero := assume f, ext (assume a, add_zero _) } instance [semiring β] [add_monoid β] : has_scalar β (α →ₛ β) := ⟨λb f, f.map (λa, b * a)⟩ instance [preorder β] : preorder (α →ₛ β) := { le_refl := λf a, le_refl _, le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a), .. simple_func.has_le } instance [partial_order β] : partial_order (α →ₛ β) := { le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a), .. simple_func.preorder } instance [order_bot β] : order_bot (α →ₛ β) := { bot := const α ⊥, bot_le := λf a, bot_le, .. simple_func.partial_order } instance [order_top β] : order_top (α →ₛ β) := { top := const α⊤, le_top := λf a, le_top, .. simple_func.partial_order } instance [semilattice_inf β] : semilattice_inf (α →ₛ β) := { inf := (⊓), inf_le_left := assume f g a, inf_le_left, inf_le_right := assume f g a, inf_le_right, le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup β] : semilattice_sup (α →ₛ β) := { sup := (⊔), le_sup_left := assume f g a, le_sup_left, le_sup_right := assume f g a, le_sup_right, sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup_bot β] : semilattice_sup_bot (α →ₛ β) := { .. simple_func.lattice.semilattice_sup,.. simple_func.lattice.order_bot } instance [lattice β] : lattice (α →ₛ β) := { .. simple_func.lattice.semilattice_sup,.. simple_func.lattice.semilattice_inf } instance [bounded_lattice β] : bounded_lattice (α →ₛ β) := { .. simple_func.lattice.lattice, .. simple_func.lattice.order_bot, .. simple_func.lattice.order_top } lemma finset_sup_apply [semilattice_sup_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) : s.sup f a = s.sup (λc, f c a) := begin refine finset.induction_on s rfl _, assume a s hs ih, rw [finset.sup_insert, finset.sup_insert, sup_apply, ih] end section approx section variables [topological_space β] [semilattice_sup_bot β] [has_zero β] def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β := (finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a}) lemma approx_apply [ordered_topology β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : _root_.measurable f) : (approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) := begin dsimp only [approx], rw [finset_sup_apply], congr, funext k, rw [restrict_apply], refl, exact (hf.preimage $ is_measurable_of_is_closed $ is_closed_ge' _) end lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) := assume n m h, finset.sup_mono $ finset.range_subset.2 h lemma approx_comp [ordered_topology β] [measurable_space γ] {i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α) (hf : _root_.measurable f) (hg : _root_.measurable g) : (approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) := by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)] end lemma supr_approx_apply [topological_space β] [complete_lattice β] [ordered_topology β] [has_zero β] (i : ℕ → β) (f : α → β) (a : α) (hf : _root_.measurable f) (h_zero : (0 : β) = ⊥) : (⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) := begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _), { rw [approx_apply a hf, h_zero], refine finset.sup_le (assume k hk, _), split_ifs, exact le_supr_of_le k (le_supr _ h), exact bot_le }, { refine le_supr_of_le (k+1) _, rw [approx_apply a hf], have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _), refine le_trans (le_of_eq _) (finset.le_sup this), rw [if_pos hk] } end end approx section eapprox def ennreal_rat_embed (n : ℕ) : ennreal := nnreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ)) lemma ennreal_rat_embed_encode (q : ℚ) (hq : 0 ≤ q) : ennreal_rat_embed (encodable.encode q) = nnreal.of_real q := by rw [ennreal_rat_embed, encodable.encodek]; refl def eapprox : (α → ennreal) → ℕ → α →ₛ ennreal := approx ennreal_rat_embed lemma monotone_eapprox (f : α → ennreal) : monotone (eapprox f) := monotone_approx _ f lemma supr_eapprox_apply (f : α → ennreal) (hf : _root_.measurable f) (a : α) : (⨆n, (eapprox f n : α →ₛ ennreal) a) = f a := begin rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl], refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _), assume h, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩, have : (nnreal.of_real q : ennreal) ≤ (⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k), { refine le_supr_of_le (encodable.encode q) _, rw [ennreal_rat_embed_encode q hq], refine le_supr_of_le (le_of_lt q_lt) _, exact le_refl _ }, exact lt_irrefl _ (lt_of_le_of_lt this lt_q) end lemma eapprox_comp [measurable_space γ] {f : γ → ennreal} {g : α → γ} {n : ℕ} (hf : _root_.measurable f) (hg : _root_.measurable g) : (eapprox (f ∘ g) n : α → ennreal) = (eapprox f n : γ →ₛ ennreal) ∘ g := funext $ assume a, approx_comp a hf hg end eapprox end measurable section measure variables [measure_space α] def integral (f : α →ₛ ennreal) : ennreal := f.range.sum (λ x, x * volume (f ⁻¹' {x})) -- TODO: slow simp proofs lemma map_integral (g : β → ennreal) (f : α →ₛ β) : (f.map g).integral = f.range.sum (λ x, g x * volume (f ⁻¹' {x})) := begin simp only [integral, coe_map, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, let s' := f.range.filter (λb, g b = g (f a)), have : g ∘ ⇑f ⁻¹' {g (f a)} = (⋃b∈s', ⇑f ⁻¹' {b}), { ext a', simp, split, { assume eq, exact ⟨⟨_, rfl⟩, eq⟩ }, { rintros ⟨_, eq⟩, exact eq } }, calc g (f a) * volume (g ∘ ⇑f ⁻¹' {g (f a)}) = g (f a) * volume (⋃b∈s', ⇑f ⁻¹' {b}) : by rw [this] ... = g (f a) * s'.sum (λb, volume (f ⁻¹' {b})) : begin rw [volume_bUnion_finset], { simp [pairwise_on, (on)], rintros b a₀ rfl eq₀ b a₁ rfl eq₁ ne a ⟨h₁, h₂⟩, simp at h₁ h₂, rw [← h₁, h₂] at ne, exact ne rfl }, exact assume a ha, preimage_measurable _ _ end ... = s'.sum (λb, g (f a) * volume (f ⁻¹' {b})) : by rw [finset.mul_sum] ... = s'.sum (λb, g b * volume (f ⁻¹' {b})) : finset.sum_congr rfl $ by simp {contextual := tt} end lemma zero_integral : (0 : α →ₛ ennreal).integral = 0 := begin refine (finset.sum_eq_zero_iff_of_nonneg $ assume _ _, zero_le _).2 _, assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩, exact zero_mul _ end lemma add_integral (f g : α →ₛ ennreal) : (f + g).integral = f.integral + g.integral := calc (f + g).integral = (pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x}) + x.2 * volume (pair f g ⁻¹' {x})) : by rw [add_eq_map₂, map_integral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _) ... = (pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x})) + (pair f g).range.sum (λx, x.2 * volume (pair f g ⁻¹' {x})) : by rw [finset.sum_add_distrib] ... = ((pair f g).map prod.fst).integral + ((pair f g).map prod.snd).integral : by rw [map_integral, map_integral] ... = integral f + integral g : rfl lemma const_mul_integral (f : α →ₛ ennreal) (x : ennreal) : (const α x * f).integral = x * f.integral := calc (f.map (λa, x * a)).integral = f.range.sum (λr, x * r * volume (f ⁻¹' {r})) : by rw [map_integral] ... = f.range.sum (λr, x * (r * volume (f ⁻¹' {r}))) : finset.sum_congr rfl (assume a ha, mul_assoc _ _ _) ... = x * f.integral : finset.mul_sum.symm lemma mem_restrict_range [has_zero β] {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) : r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (∃a∈s, f a = r) := begin simp only [mem_range, restrict_apply, hs], split, { rintros ⟨a, ha⟩, split_ifs at ha, { exact or.inr ⟨a, h, ha⟩ }, { exact or.inl ⟨ha.symm, assume eq, h $ eq.symm ▸ trivial⟩ } }, { rintros (⟨rfl, h⟩ | ⟨a, ha, rfl⟩), { have : ¬ ∀a, a ∈ s := assume this, h $ eq_univ_of_forall this, rcases not_forall.1 this with ⟨a, ha⟩, refine ⟨a, _⟩, rw [if_neg ha] }, { refine ⟨a, _⟩, rw [if_pos ha] } } end lemma restrict_preimage' {r : ennreal} {s : set α} (f : α →ₛ ennreal) (hs : is_measurable s) (hr : r ≠ 0) : (restrict f s) ⁻¹' {r} = (f ⁻¹' {r} ∩ s) := begin ext a, by_cases a ∈ s; simp [hs, h, hr.symm] end lemma restrict_integral (f : α →ₛ ennreal) (s : set α) (hs : is_measurable s) : (restrict f s).integral = f.range.sum (λr, r * volume (f ⁻¹' {r} ∩ s)) := begin refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _, { assume r hr, rcases (mem_restrict_range hs).1 hr with ⟨rfl, h⟩ | ⟨a, ha, rfl⟩, { simp }, { assume _, exact mem_range.2 ⟨a, rfl⟩ } }, { assume a b _ _ _ _ h, exact h }, { assume r hr, by_cases r0 : r = 0, { simp [r0] }, assume h0, rcases mem_range.1 hr with ⟨a, rfl⟩, have : f ⁻¹' {f a} ∩ s ≠ ∅, { assume h, simpa [h] using h0 }, rcases ne_empty_iff_exists_mem.1 this with ⟨a', eq', ha'⟩, refine ⟨_, (mem_restrict_range hs).2 (or.inr ⟨a', ha', _⟩), _, rfl⟩, { simpa using eq' }, { rwa [restrict_preimage' _ hs r0] } }, { assume r hr ne, by_cases r = 0, { simp [h] }, rw [restrict_preimage' _ hs h] } end lemma restrict_const_integral (c : ennreal) (s : set α) (hs : is_measurable s) : (restrict (const α c) s).integral = c * volume s := have (@const α ennreal _ c) ⁻¹' {c} = univ, begin refine eq_univ_of_forall (assume a, _), simp, end, calc (restrict (const α c) s).integral = c * volume ((const α c) ⁻¹' {c} ∩ s) : begin rw [restrict_integral (const α c) s hs], refine finset.sum_eq_single c _ _, { assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩, contradiction }, { by_cases nonempty α, { assume ne, rcases h with ⟨a⟩, exfalso, exact ne (mem_range.2 ⟨a, rfl⟩) }, { assume empty, have : (@const α ennreal _ c) ⁻¹' {c} ∩ s = ∅, { ext a, exfalso, exact h ⟨a⟩ }, simp only [this, volume_empty, mul_zero] } } end ... = c * volume s : by rw [this, univ_inter] lemma integral_sup_le (f g : α →ₛ ennreal) : f.integral ⊔ g.integral ≤ (f ⊔ g).integral := calc f.integral ⊔ g.integral = ((pair f g).map prod.fst).integral ⊔ ((pair f g).map prod.snd).integral : rfl ... ≤ (pair f g).range.sum (λx, (x.1 ⊔ x.2) * volume (pair f g ⁻¹' {x})) : begin rw [map_integral, map_integral], refine sup_le _ _; refine finset.sum_le_sum (λ a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)), exact le_sup_left, exact le_sup_right end ... = (f ⊔ g).integral : by rw [sup_eq_map₂, map_integral] lemma integral_le_integral (f g : α →ₛ ennreal) (h : f ≤ g) : f.integral ≤ g.integral := calc f.integral ≤ f.integral ⊔ g.integral : le_sup_left ... ≤ (f ⊔ g).integral : integral_sup_le _ _ ... = g.integral : by rw [sup_of_le_right h] lemma integral_congr (f g : α →ₛ ennreal) (h : {a | f a = g a} ∈ (@measure_space.μ α _).a_e) : f.integral = g.integral := show ((pair f g).map prod.fst).integral = ((pair f g).map prod.snd).integral, from begin rw [map_integral, map_integral], refine finset.sum_congr rfl (assume p hp, _), rcases mem_range.1 hp with ⟨a, rfl⟩, by_cases eq : f a = g a, { dsimp only [pair_apply], rw eq }, { have : volume ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine volume_mono_null (assume a' ha', _) h, simp at ha', show f a' ≠ g a', rwa [ha'.1, ha'.2] }, simp [this] } end lemma integral_map {β} [measure_space β] (f : α →ₛ ennreal) (g : β →ₛ ennreal) (m : α → β) (hm : _root_.measurable m) (eq : ∀a:α, f a = g (m a)) (h : ∀s:set β, is_measurable s → volume s = volume (m ⁻¹' s)) : f.integral = g.integral := have f_eq : (f : α → ennreal) = g ∘ m := funext eq, have vol_f : ∀r, volume (f ⁻¹' {r}) = volume (g ⁻¹' {r}), by { assume r, rw [h, f_eq, preimage_comp], exact measurable_sn _ _ }, begin simp [integral, vol_f], refine finset.sum_subset _ _, { simp [finset.subset_iff, f_eq], rintros r a rfl, exact ⟨_, rfl⟩ }, { assume r hrg hrf, rw [simple_func.mem_range, not_exists] at hrf, have : f ⁻¹' {r} = ∅ := set.eq_empty_of_subset_empty (assume a, by simpa using hrf a), simp [(vol_f _).symm, this] } end end measure end simple_func section lintegral open simple_func variable [measure_space α] /-- The lower Lebesgue integral -/ def lintegral (f : α → ennreal) : ennreal := ⨆ (s : α →ₛ ennreal) (hf : f ≥ s), s.integral notation `∫⁻` binders `, ` r:(scoped f, lintegral f) := r theorem simple_func.lintegral_eq_integral (f : α →ₛ ennreal) : (∫⁻ a, f a) = f.integral := le_antisymm (supr_le $ assume s, supr_le $ assume hs, integral_le_integral _ _ hs) (le_supr_of_le f $ le_supr_of_le (le_refl f) $ le_refl _) lemma lintegral_le_lintegral (f g : α → ennreal) (h : f ≤ g) : (∫⁻ a, f a) ≤ (∫⁻ a, g a) := supr_le_supr $ assume s, supr_le $ assume hs, le_supr_of_le (le_trans hs h) (le_refl _) lemma lintegral_eq_nnreal (f : α → ennreal) : (∫⁻ a, f a) = (⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map (coe : nnreal → ennreal)), (s.map (coe : nnreal → ennreal)).integral) := begin let c : nnreal → ennreal := coe, refine le_antisymm (supr_le $ assume s, supr_le $ assume hs, _) (supr_le $ assume s, supr_le $ assume hs, le_supr_of_le (s.map c) $ le_supr _ hs), by_cases {a | s a ≠ ⊤} ∈ (@measure_space.μ α _).a_e, { have : f ≥ (s.map ennreal.to_nnreal).map c := le_trans (assume a, ennreal.coe_to_nnreal_le_self) hs, refine le_supr_of_le (s.map ennreal.to_nnreal) (le_supr_of_le this (le_of_eq $ integral_congr _ _ _)), exact filter.mem_sets_of_superset h (assume a ha, (ennreal.coe_to_nnreal ha).symm) }, { have h_vol_s : volume {a : α | s a = ⊤} ≠ 0, { simp [measure.a_e, set.compl_set_of] at h, assumption }, let n : ℕ → (α →ₛ nnreal) := λn, restrict (const α (n : nnreal)) (s ⁻¹' {⊤}), have n_le_s : ∀i, (n i).map c ≤ s, { assume i a, dsimp [n, c], rw [restrict_apply _ (s.preimage_measurable _)], split_ifs with ha, { simp at ha, exact ha.symm ▸ le_top }, { exact zero_le _ } }, have approx_s : ∀ (i : ℕ), ↑i * volume {a : α | s a = ⊤} ≤ integral (map c (n i)), { assume i, have : {a : α | s a = ⊤} = s ⁻¹' {⊤}, { ext a, simp }, rw [this, ← restrict_const_integral _ _ (s.preimage_measurable _)], { refine integral_le_integral _ _ (assume a, le_of_eq _), simp [n, c, restrict_apply, s.preimage_measurable], split_ifs; simp [ennreal.coe_nat] }, }, calc s.integral ≤ ⊤ : le_top ... = (⨆i:ℕ, (i : ennreal) * volume {a | s a = ⊤}) : by rw [← ennreal.supr_mul, ennreal.supr_coe_nat, ennreal.top_mul, if_neg h_vol_s] ... ≤ (⨆i, ((n i).map c).integral) : supr_le_supr approx_s ... ≤ ⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map c), (s.map c).integral : have ∀i, ((n i).map c : α → ennreal) ≤ f := assume i, le_trans (n_le_s i) hs, (supr_le $ assume i, le_supr_of_le (n i) (le_supr (λh, ((n i).map c).integral) (this i))) } end /-- Monotone convergence theorem -- somtimes called Beppo-Levi convergence. See `lintegral_supr_directed` for a more general form. -/ theorem lintegral_supr {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : monotone f) : (∫⁻ a, ⨆n, f n a) = (⨆n, ∫⁻ a, f n a) := let c : nnreal → ennreal := coe in let F (a:α) := ⨆n, f n a in have hF : measurable F := measurable.supr hf, show (∫⁻ a, F a) = (⨆n, ∫⁻ a, f n a), begin refine le_antisymm _ _, { rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_lt (assume a ha, _), rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩, have ha : r < 1 := ennreal.coe_lt_coe.1 ha, let rs := s.map (λa, r * a), have eq_rs : (const α r : α →ₛ ennreal) * map c s = rs.map c, { ext1 a, exact ennreal.coe_mul.symm }, have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}), { assume p, rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]}, refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _), by_cases p_eq : p = 0, { simp [p_eq] }, simp at hx, subst hx, have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] }, have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] }, have : (rs.map c) x < ⨆ (n : ℕ), f n x, { refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x), suffices : r * s x < 1 * s x, simpa [rs], exact mul_lt_mul_of_pos_right ha (zero_lt_iff_ne_zero.2 this) }, rcases lt_supr_iff.1 this with ⟨i, hi⟩, exact mem_Union.2 ⟨i, le_of_lt hi⟩ }, have mono : ∀r:ennreal, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}), { assume r i j h, refine inter_subset_inter (subset.refl _) _, assume x hx, exact le_trans hx (h_mono h x) }, have h_meas : ∀n, is_measurable {a : α | ⇑(map c rs) a ≤ f n a} := assume n, measurable_le (simple_func.measurable _) (hf n), calc (r:ennreal) * integral (s.map c) = (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r})) : by rw [← const_mul_integral, integral, eq_rs] ... ≤ (rs.map c).range.sum (λr, r * volume (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq) ... ≤ (rs.map c).range.sum (λr, (⨆n, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}))) : le_of_eq (finset.sum_congr rfl $ assume x hx, begin rw [volume, measure_Union_eq_supr_nat _ (mono x), ennreal.mul_supr], { assume i, refine is_measurable.inter ((rs.map c).preimage_measurable _) _, refine (hf i).preimage _, exact is_measurable_of_is_closed (is_closed_ge' _) } end) ... ≤ ⨆n, (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : begin refine le_of_eq _, rw [ennreal.finset_sum_supr_nat], assume p i j h, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (volume_mono $ mono p h) end ... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).integral) : begin refine supr_le_supr (assume n, _), rw [restrict_integral _ _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2, ext a, refine and_congr_right _, simp {contextual := tt} } end ... ≤ (⨆n, ∫⁻ a, f n a) : begin refine supr_le_supr (assume n, _), rw [← simple_func.lintegral_eq_integral], refine lintegral_le_lintegral _ _ (assume a, _), dsimp, rw [restrict_apply], split_ifs; simp, simpa using h, exact h_meas n end }, { exact supr_le (assume n, lintegral_le_lintegral _ _ $ assume a, le_supr _ n) } end lemma lintegral_eq_supr_eapprox_integral {f : α → ennreal} (hf : measurable f) : (∫⁻ a, f a) = (⨆n, (eapprox f n).integral) := calc (∫⁻ a, f a) = (∫⁻ a, ⨆n, (eapprox f n : α → ennreal) a) : by congr; ext a; rw [supr_eapprox_apply f hf] ... = (⨆n, ∫⁻ a, (eapprox f n : α → ennreal) a) : begin rw [lintegral_supr], { assume n, exact (eapprox f n).measurable }, { assume i j h, exact (monotone_eapprox f h) } end ... = (⨆n, (eapprox f n).integral) : by congr; ext n; rw [(eapprox f n).lintegral_eq_integral] lemma lintegral_add {f g : α → ennreal} (hf : measurable f) (hg : measurable g) : (∫⁻ a, f a + g a) = (∫⁻ a, f a) + (∫⁻ a, g a) := calc (∫⁻ a, f a + g a) = (∫⁻ a, (⨆n, (eapprox f n : α → ennreal) a) + (⨆n, (eapprox g n : α → ennreal) a)) : by congr; funext a; rw [supr_eapprox_apply f hf, supr_eapprox_apply g hg] ... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ennreal) a)) : begin congr, funext a, rw [ennreal.supr_add_supr_of_monotone], { refl }, { assume i j h, exact monotone_eapprox _ h a }, { assume i j h, exact monotone_eapprox _ h a }, end ... = (⨆n, (eapprox f n).integral + (eapprox g n).integral) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_integral, ← simple_func.lintegral_eq_integral], refl }, { assume n, exact measurable_add (eapprox f n).measurable (eapprox g n).measurable }, { assume i j h a, exact add_le_add' (monotone_eapprox _ h _) (monotone_eapprox _ h _) } end ... = (⨆n, (eapprox f n).integral) + (⨆n, (eapprox g n).integral) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.integral_le_integral _ _ (monotone_eapprox _ h) } ... = (∫⁻ a, f a) + (∫⁻ a, g a) : by rw [lintegral_eq_supr_eapprox_integral hf, lintegral_eq_supr_eapprox_integral hg] @[simp] lemma lintegral_zero : (∫⁻ a:α, 0) = 0 := show (∫⁻ a:α, (0 : α →ₛ ennreal) a) = 0, by rw [simple_func.lintegral_eq_integral, zero_integral] lemma lintegral_finset_sum (s : finset β) {f : β → α → ennreal} (hf : ∀b, measurable (f b)) : (∫⁻ a, s.sum (λb, f b a)) = s.sum (λb, ∫⁻ a, f b a) := begin refine finset.induction_on s _ _, { simp }, { assume a s has ih, simp [has], rw [lintegral_add (hf _) (measurable_finset_sum s hf), ih] } end lemma lintegral_const_mul (r : ennreal) {f : α → ennreal} (hf : measurable f) : (∫⁻ a, r * f a) = r * (∫⁻ a, f a) := calc (∫⁻ a, r * f a) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a)) : by congr; funext a; rw [← supr_eapprox_apply f hf, ennreal.mul_supr]; refl ... = (⨆n, r * (eapprox f n).integral) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_integral, ← simple_func.lintegral_eq_integral] }, { assume n, exact simple_func.measurable _ }, { assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (monotone_eapprox _ h _) } end ... = r * (∫⁻ a, f a) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_integral hf] lemma lintegral_supr_const (r : ennreal) {s : set α} (hs : is_measurable s) : (∫⁻ a, ⨆(h : a ∈ s), r) = r * volume s := begin rw [← restrict_const_integral r s hs, ← (restrict (const α r) s).lintegral_eq_integral], congr; ext a; by_cases a ∈ s; simp [h, hs] end lemma lintegral_le_lintegral_ae {f g : α → ennreal} (h : ∀ₘ a, f a ≤ g a) : (∫⁻ a, f a) ≤ (∫⁻ a, g a) := begin rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t, hts, ht, ht0⟩, have : - t ∈ (@measure_space.μ α _).a_e, { rw [measure.mem_a_e_iff, lattice.neg_neg, ht0] }, refine (supr_le $ assume s, supr_le $ assume hfs, le_supr_of_le (s.restrict (- t)) $ le_supr_of_le _ _), { assume a, by_cases a ∈ t; simp [h, simple_func.restrict_apply, ht.compl], exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) }, { refine le_of_eq (s.integral_congr _ _), filter_upwards [this], refine assume a hnt, _, by_cases hat : a ∈ t; simp [hat, ht.compl], exact (hnt hat).elim } end lemma lintegral_congr_ae {f g : α → ennreal} (h : ∀ₘ a, f a = g a) : (∫⁻ a, f a) = (∫⁻ a, g a) := le_antisymm (lintegral_le_lintegral_ae $ by filter_upwards [h] assume a h, le_of_eq h) (lintegral_le_lintegral_ae $ by filter_upwards [h] assume a h, le_of_eq h.symm) lemma lintegral_eq_zero_iff {f : α → ennreal} (hf : measurable f) : lintegral f = 0 ↔ (∀ₘ a, f a = 0) := begin refine iff.intro (assume h, _) (assume h, _), { have : ∀n:ℕ, ∀ₘ a, f a < n⁻¹, { assume n, have : is_measurable {a : α | f a ≥ n⁻¹ }, { exact hf _ (is_measurable_of_is_closed $ is_closed_ge' _) }, have : (n : ennreal)⁻¹ * volume {a | f a ≥ n⁻¹ } = 0, { rw [← simple_func.restrict_const_integral _ _ this, ← le_zero_iff_eq, ← simple_func.lintegral_eq_integral], refine le_trans (lintegral_le_lintegral _ _ _) (le_of_eq h), assume a, by_cases h : (n : ennreal)⁻¹ ≤ f a; simp [h, (≥), this] }, rw [ennreal.mul_eq_zero, ennreal.inv_eq_zero] at this, simpa [ennreal.nat_ne_top, all_ae_iff] using this }, filter_upwards [all_ae_all_iff.2 this], dsimp, assume a ha, by_contradiction h, rcases ennreal.exists_inv_nat_lt h with ⟨n, hn⟩, exact (lt_irrefl _ $ lt_trans hn $ ha n).elim }, { calc lintegral f = lintegral (λa:α, 0) : lintegral_congr_ae h ... = 0 : lintegral_zero } end /-- Weaker version of the monotone convergence theorem-/ lemma lintegral_supr_ae {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : ∀n, ∀ₘ a, f n a ≤ f n.succ a) : (∫⁻ a, ⨆n, f n a) = (⨆n, ∫⁻ a, f n a) := let ⟨s, hs⟩ := exists_is_measurable_superset_of_measure_eq_zero (all_ae_iff.1 (all_ae_all_iff.2 h_mono)) in let g := λ n a, if a ∈ s then 0 else f n a in have g_eq_f : ∀ₘ a, ∀n, g n a = f n a, begin have := hs.2.2, rw [← compl_compl s] at this, filter_upwards [(measure.mem_a_e_iff (-s)).2 this] assume a ha n, if_neg ha end, calc (∫⁻ a, ⨆n, f n a) = (∫⁻ a, ⨆n, g n a) : lintegral_congr_ae begin filter_upwards [g_eq_f], assume a ha, congr, funext, exact (ha n).symm end ... = ⨆n, (∫⁻ a, g n a) : lintegral_supr (assume n, measurable.if hs.2.1 measurable_const (hf n)) (monotone_of_monotone_nat $ assume n a, classical.by_cases (assume h : a ∈ s, by simp [g, if_pos h]) (assume h : a ∉ s, begin simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h, simp only [not_not, mem_set_of_eq] at this, exact this n end)) ... = ⨆n, (∫⁻ a, f n a) : begin congr, funext, apply lintegral_congr_ae, filter_upwards [g_eq_f] assume a ha, ha n end lemma lintegral_sub {f g : α → ennreal} (hf : measurable f) (hg : measurable g) (hg_fin : lintegral g < ⊤) (h_le : ∀ₘ a, g a ≤ f a) : (∫⁻ a, f a - g a) = (∫⁻ a, f a) - (∫⁻ a, g a) := begin rw [← ennreal.add_right_inj hg_fin, ennreal.sub_add_cancel_of_le (lintegral_le_lintegral_ae h_le), ← lintegral_add (ennreal.measurable_sub hf hg) hg], show (∫⁻ (a : α), f a - g a + g a) = ∫⁻ (a : α), f a, apply lintegral_congr_ae, filter_upwards [h_le], simp only [add_comm, mem_set_of_eq], assume a ha, exact ennreal.add_sub_cancel_of_le ha end /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi_ae {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) (h_mono : ∀n:ℕ, ∀ₘ a, f n.succ a ≤ f n a) (h_fin : lintegral (f 0) < ⊤) : (∫⁻ a, ⨅n, f n a) = (⨅n, ∫⁻ a, f n a) := have fn_le_f0 : (∫⁻ a, ⨅n, f n a) ≤ lintegral (f 0), from lintegral_le_lintegral _ _ (assume a, infi_le_of_le 0 (le_refl _)), have fn_le_f0' : (⨅n, ∫⁻ a, f n a) ≤ lintegral (f 0), from infi_le_of_le 0 (le_refl _), (ennreal.sub_left_inj h_fin fn_le_f0 fn_le_f0').1 $ show lintegral (f 0) - (∫⁻ a, ⨅n, f n a) = lintegral (f 0) - (⨅n, ∫⁻ a, f n a), from calc lintegral (f 0) - (∫⁻ a, ⨅n, f n a) = ∫⁻ a, f 0 a - ⨅n, f n a : (lintegral_sub (h_meas 0) (measurable.infi h_meas) (calc (∫⁻ a, ⨅n, f n a) ≤ lintegral (f 0) : lintegral_le_lintegral _ _ (assume a, infi_le _ _) ... < ⊤ : h_fin ) (all_ae_of_all $ assume a, infi_le _ _)).symm ... = ∫⁻ a, ⨆n, f 0 a - f n a : congr rfl (funext (assume a, ennreal.sub_infi)) ... = ⨆n, ∫⁻ a, f 0 a - f n a : lintegral_supr_ae (assume n, ennreal.measurable_sub (h_meas 0) (h_meas n)) (assume n, by filter_upwards [h_mono n] assume a ha, ennreal.sub_le_sub (le_refl _) ha) ... = ⨆n, lintegral (f 0) - ∫⁻ a, f n a : have h_mono : ∀ₘ a, ∀n:ℕ, f n.succ a ≤ f n a := all_ae_all_iff.2 h_mono, have h_mono : ∀n, ∀ₘa, f n a ≤ f 0 a := assume n, begin filter_upwards [h_mono], simp only [mem_set_of_eq], assume a, assume h, induction n with n ih, {exact le_refl _}, {exact le_trans (h n) ih} end, congr rfl (funext $ assume n, lintegral_sub (h_meas _) (h_meas _) (calc (∫⁻ a, f n a) ≤ ∫⁻ a, f 0 a : lintegral_le_lintegral_ae $ h_mono n ... < ⊤ : h_fin) (h_mono n)) ... = lintegral (f 0) - (⨅n, ∫⁻ a, f n a) : ennreal.sub_infi.symm section priority -- for some reason the next proof fails without changing the priority of this instance local attribute [instance, priority 1000] classical.prop_decidable /-- Known as Fatou's lemma -/ lemma lintegral_liminf_le {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) : (∫⁻ a, liminf at_top (λ n, f n a)) ≤ liminf at_top (λ n, lintegral (f n)) := calc (∫⁻ a, liminf at_top (λ n, f n a)) = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a : congr rfl (funext (assume a, liminf_eq_supr_infi_of_nat)) ... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a : lintegral_supr begin assume n, apply measurable.infi, assume i, by_cases h : i ≥ n, {convert h_meas i, simp [h]}, {convert measurable_const, simp [h]} end begin assume n m hnm a, simp only [le_infi_iff], assume i hi, refine infi_le_of_le i (infi_le_of_le (le_trans hnm hi) (le_refl _)) end ... ≤ ⨆n:ℕ, ⨅i≥n, lintegral (f i) : supr_le_supr $ assume n, le_infi $ assume i, le_infi $ assume hi, lintegral_le_lintegral _ _ $ assume a, infi_le_of_le i $ infi_le_of_le hi $ le_refl _ ... = liminf at_top (λ n, lintegral (f n)) : liminf_eq_supr_infi_of_nat.symm end priority lemma limsup_lintegral_le {f : ℕ → α → ennreal} {g : α → ennreal} (hf_meas : ∀ n, measurable (f n)) (hg_meas : measurable g) (h_bound : ∀n, ∀ₘa, f n a ≤ g a) (h_fin : lintegral g < ⊤) : limsup at_top (λn, lintegral (f n)) ≤ ∫⁻ a, limsup at_top (λn, f n a) := calc limsup at_top (λn, lintegral (f n)) = ⨅n:ℕ, ⨆i≥n, lintegral (f i) : limsup_eq_infi_supr_of_nat ... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a : infi_le_infi $ assume n, supr_le $ assume i, supr_le $ assume hi, lintegral_le_lintegral _ _ $ assume a, le_supr_of_le i $ le_supr_of_le hi (le_refl _) ... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a : (lintegral_infi_ae (assume n, @measurable.supr _ _ _ _ _ _ _ _ _ (λ i a, supr (λ (h : i ≥ n), f i a)) (assume i, measurable.supr_Prop (hf_meas i))) (assume n, all_ae_of_all $ assume a, begin simp only [supr_le_iff], assume i hi, refine le_supr_of_le i _, rw [supr_pos _], exact le_refl _, exact nat.le_of_succ_le hi end ) (lt_of_le_of_lt (lintegral_le_lintegral_ae begin filter_upwards [all_ae_all_iff.2 h_bound], simp only [supr_le_iff, mem_set_of_eq], assume a ha i hi, exact ha i end ) h_fin)).symm ... = ∫⁻ a, limsup at_top (λn, f n a) : lintegral_congr_ae $ all_ae_of_all $ assume a, limsup_eq_infi_supr_of_nat.symm /-- Dominated convergence theorem for nonnegative functions -/ lemma dominated_convergence_nn {F : ℕ → α → ennreal} {f : α → ennreal} {g : α → ennreal} (hF_meas : ∀n, measurable (F n)) (hf_meas : measurable f) (hg_meas : measurable g) (h_bound : ∀n, ∀ₘ a, F n a ≤ g a) (h_fin : lintegral g < ⊤) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (nhds (f a))) : tendsto (λn, lintegral (F n)) at_top (nhds (lintegral f)) := begin have limsup_le_lintegral := calc limsup at_top (λ (n : ℕ), lintegral (F n)) ≤ ∫⁻ (a : α), limsup at_top (λn, F n a) : limsup_lintegral_le hF_meas hg_meas h_bound h_fin ... = lintegral f : lintegral_congr_ae $ by filter_upwards [h_lim] assume a h, limsup_eq_of_tendsto at_top_ne_bot h, have lintegral_le_liminf := calc lintegral f = ∫⁻ (a : α), liminf at_top (λ (n : ℕ), F n a) : lintegral_congr_ae $ by filter_upwards [h_lim] assume a h, (liminf_eq_of_tendsto at_top_ne_bot h).symm ... ≤ liminf at_top (λ n, lintegral (F n)) : lintegral_liminf_le hF_meas, have liminf_eq_limsup := le_antisymm (liminf_le_limsup (map_ne_bot at_top_ne_bot)) (le_trans limsup_le_lintegral lintegral_le_liminf), have liminf_eq_lintegral : liminf at_top (λ n, lintegral (F n)) = lintegral f := le_antisymm (by convert limsup_le_lintegral) lintegral_le_liminf, have limsup_eq_lintegral : limsup at_top (λ n, lintegral (F n)) = lintegral f := le_antisymm limsup_le_lintegral begin convert lintegral_le_liminf, exact liminf_eq_limsup.symm end, exact tendsto_of_liminf_eq_limsup ⟨liminf_eq_lintegral, limsup_eq_lintegral⟩ end section open encodable /-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/ theorem lintegral_supr_directed [encodable β] {f : β → α → ennreal} (hf : ∀b, measurable (f b)) (h_directed : directed (≤) f) : (∫⁻ a, ⨆b, f b a) = (⨆b, ∫⁻ a, f b a) := begin by_cases hβ : ¬ nonempty β, { have : ∀f : β → ennreal, (⨆(b : β), f b) = 0 := assume f, supr_eq_bot.2 (assume b, (hβ ⟨b⟩).elim), simp [this] }, cases of_not_not hβ with b, haveI iβ : inhabited β := ⟨b⟩, clear hβ b, have : ∀a, (⨆ b, f b a) = (⨆ n, f (sequence_of_directed (≤) f h_directed n) a), { assume a, refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _), exact le_supr_of_le (encode b + 1) (le_sequence_of_directed f h_directed b a) }, calc (∫⁻ a, ⨆ b, f b a) = (∫⁻ a, ⨆ n, f (sequence_of_directed (≤) f h_directed n) a) : by simp only [this] ... = (⨆ n, ∫⁻ a, f (sequence_of_directed (≤) f h_directed n) a) : lintegral_supr (assume n, hf _) (monotone_sequence_of_directed f h_directed) ... = (⨆ b, ∫⁻ a, f b a) : begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _), { exact le_supr (λb, lintegral (f b)) _ }, { exact le_supr_of_le (encode b + 1) (lintegral_le_lintegral _ _ $ le_sequence_of_directed f h_directed b) } end end end lemma lintegral_tsum [encodable β] {f : β → α → ennreal} (hf : ∀i, measurable (f i)) : (∫⁻ a, ∑ i, f i a) = (∑ i, ∫⁻ a, f i a) := begin simp only [ennreal.tsum_eq_supr_sum], rw [lintegral_supr_directed], { simp [lintegral_finset_sum _ hf] }, { assume b, exact measurable_finset_sum _ hf }, { assume s t, use [s ∪ t], split, exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _), exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) } end end lintegral namespace measure def integral [measurable_space α] (m : measure α) (f : α → ennreal) : ennreal := @lintegral α { μ := m } f variables [measurable_space α] {m : measure α} @[simp] lemma integral_zero : m.integral (λa, 0) = 0 := @lintegral_zero α { μ := m } lemma integral_map [measurable_space β] {f : β → ennreal} {g : α → β} (hf : measurable f) (hg : measurable g) : (map g m).integral f = m.integral (f ∘ g) := begin rw [integral, integral, lintegral_eq_supr_eapprox_integral, lintegral_eq_supr_eapprox_integral], { congr, funext n, symmetry, apply simple_func.integral_map, { exact hg }, { assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a }, { assume s hs, exact map_apply hg hs } }, exact hf.comp hg, assumption end lemma integral_dirac (a : α) {f : α → ennreal} (hf : measurable f) : (dirac a).integral f = f a := have ∀f:α →ₛ ennreal, @simple_func.integral α {μ := dirac a} f = f a, begin assume f, have : ∀r, @volume α { μ := dirac a } (⇑f ⁻¹' {r}) = ⨆ h : f a = r, 1, { assume r, transitivity, apply dirac_apply, apply simple_func.measurable_sn, refine supr_congr_Prop _ _; simp }, transitivity, apply finset.sum_eq_single (f a), { assume b hb h, simp [this, ne.symm h], }, { assume h, simp at h, exact (h a rfl).elim }, { rw [this], simp } end, begin rw [integral, lintegral_eq_supr_eapprox_integral], { simp [this, simple_func.supr_eapprox_apply f hf] }, assumption end def with_density (m : measure α) (f : α → ennreal) : measure α := if hf : measurable f then measure.of_measurable (λs hs, m.integral (λa, ⨆(h : a ∈ s), f a)) (by simp) begin assume s hs hd, have : ∀a, (⨆ (h : a ∈ ⋃i, s i), f a) = (∑i, (⨆ (h : a ∈ s i), f a)), { assume a, by_cases ha : ∃j, a ∈ s j, { rcases ha with ⟨j, haj⟩, have : ∀i, a ∈ s i ↔ j = i := assume i, iff.intro (assume hai, by_contradiction $ assume hij, hd j i hij ⟨haj, hai⟩) (by rintros rfl; assumption), simp [this, ennreal.tsum_supr_eq] }, { have : ∀i, ¬ a ∈ s i, { simpa using ha }, simp [this] } }, simp only [this], apply lintegral_tsum, { assume i, simp [supr_eq_if], exact measurable.if (hs i) hf measurable_const } end else 0 lemma with_density_apply {m : measure α} {f : α → ennreal} {s : set α} (hf : measurable f) (hs : is_measurable s) : m.with_density f s = m.integral (λa, ⨆(h : a ∈ s), f a) := by rw [with_density, dif_pos hf]; exact measure.of_measurable_apply s hs end measure end measure_theory
4f10c4c48ba91b54e6bcecceb2fea3675a48baa6
ebf7140a9ea507409ff4c994124fa36e79b4ae35
/src/solutions/tuesday/numbers.lean
4fc06ca13c132ccc28f4b68b860e750ba2f9fa4c
[]
no_license
fundou/lftcm2020
3e88d58a92755ea5dd49f19c36239c35286ecf5e
99d11bf3bcd71ffeaef0250caa08ecc46e69b55b
refs/heads/master
1,685,610,799,304
1,624,070,416,000
1,624,070,416,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,018
lean
import tactic import data.real.basic import data.int.gcd import number_theory.padics /-! ## Exercises about numbers and casts -/ /-! ## First exercises These first examples are just to get you comfortable with `norm_num`, `norm_cast`, and friends. -/ example : 12345 < 67890 := begin norm_num end example {α : Type} [linear_ordered_field α] : 123 + 45 < 67890/3 := begin norm_num end example : nat.prime 17 := begin norm_num end -- prove either this or its negation! example : ¬ 7/3 > 2 := begin norm_num end example (x : ℝ) (hx : x < 50*50) : x < 25*100 := begin norm_num at hx ⊢, assumption end example (x : ℤ) (hx : (x : ℝ) < 25*100) : x < 25*100 := begin assumption_mod_cast end example (x : ℤ) (hx : (x : ℝ) < 2500) : x < 25*100 := begin norm_num, assumption_mod_cast end example (p q r : ℕ) (h : r < p - q) (hpq : q ≤ p) : (r : ℝ) < p - q := begin exact_mod_cast h, end example (p q r : ℕ) (hr : r < p + 2 - p) : (r : ℤ) < 5 := begin have : p ≤ p + 2, by linarith, zify [this] at hr, linarith end /-! ## Exercise 2 This comes from the development of the p-adic numbers. `norm_cast` is very useful here, since we need to talk about values in ℕ, ℤ, ℚ, ℚ_p, and ℤ_p. We've done some work to get you started. You might look for the lemmas: -/ open padic_val_rat #check fpow_le_of_le #check fpow_nonneg #check padic_val_rat_of_int example {p n : ℕ} (hp : p.prime) {z : ℤ} (hd : ↑(p^n) ∣ z) : padic_norm p z ≤ ↑p ^ (-n : ℤ) := begin -- this lemma will be useful later in the proof. -- ignore the "inst" argument; just use `apply aux_lemma` when you need it! have aux_lemma : ∀ inst, (n : ℤ) ≤ (multiplicity ↑p z).get inst, { intro, norm_cast, rw [← enat.coe_le_coe, enat.coe_get], apply multiplicity.le_multiplicity_of_pow_dvd, assumption_mod_cast }, unfold padic_norm, split_ifs with hz hz, { apply fpow_nonneg, exact_mod_cast le_of_lt hp.pos }, { apply fpow_le_of_le, exact_mod_cast le_of_lt hp.one_lt, apply neg_le_neg, rw padic_val_rat_of_int _ hp.ne_one _, { apply aux_lemma }, { assumption_mod_cast } } end /-! ## Exercise 3 This seems like a very natural way to write the theorem "If `a` and `b` are coprime, then there are coefficients `u` and `v` such that `u*a + v*b = 1`." But I've made a mistake! What did I do wrong? Correct the statement of the theorem and prove it. I've started you off with a lemma that will be useful. You might find the `specialize` tactic to be handy as well: if you have `h : ∀ (x y : T), R x y` and `a, b : T` in the context, then `specialize h a b` will change the type of `h` to `R a b`. If you want to peek at the definition of coprime, you can use `unfold nat.coprime at h`. -/ -- notice that I've changed the existential to be over ℤ! example (p q : ℕ) (h : nat.coprime p q) : ∃ u v : ℤ, u*p+v*q = 1 := begin have := nat.gcd_eq_gcd_ab, specialize this p q, unfold nat.coprime at h, rw h at this, norm_cast at this, use [p.gcd_a q, p.gcd_b q], rw this, ring end /-! ## Exercise 4 We did an example together that was similar to this. This one takes a bit more arithmetic work. To save you some time, here are some lemmas that may be useful! (You may not need all of them, depending on how you approach it.) Remember you can also use `library_search` to try to find useful lemmas. A hint: you might find it helpful to do this once you've introduced `n`. ``` have n_pos: 0 < n, { ... } ``` -/ #check sub_le_iff_le_add #check add_le_add_iff_left #check div_le_iff #check mul_one_div_cancel #check mul_le_mul_left notation `|`x`|` := abs x def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε example : seq_limit (λ n : ℕ, (n+1)/n) 1 := begin -- we start like before intros ε ε_pos, dsimp, -- the witness to the existential must be a nat: use `nat_ceil` instead of `ceil`! use nat_ceil (1/ε), intros n hn, -- this proof is used a few times below, so we separate it as an assumption have n_pos : 0 < n, -- I've written the proofs of the calc block separately, but you could inline them { calc 0 < nat_ceil (1/ε) : _ ... ≤ n : _, { rw lt_nat_ceil, simp, assumption }, { assumption } }, -- this chain of rewrites generates some side conditions that we get rid of below rw [abs_of_nonneg, sub_le_iff_le_add, div_le_iff, add_mul, one_mul, add_comm _ (n : ℝ), add_le_add_iff_left], -- this calc proof finishes the "main goal" { calc 1 = ε * (1/ε) : _ ... ≤ ε * nat_ceil (1/ε) : _ ... ≤ ε * n : _, { symmetry, apply mul_one_div_cancel, linarith }, { rw mul_le_mul_left ε_pos, apply le_nat_ceil }, { rw mul_le_mul_left ε_pos, exact_mod_cast hn } }, -- we try to discharge the side conditions with as little work as possible { assumption_mod_cast }, { field_simp, rw one_le_div; norm_cast; linarith } end
275945816c52d8fb0a433e0ddca26701678cc485
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Runtime.lean
611434c7dd6238f4ba22a3bbe724230532b21309
[ "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
458
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 -/ namespace Lean @[extern "lean_closure_max_args"] constant closureMaxArgsFn : Unit → Nat := arbitrary _ @[extern "lean_max_small_nat"] constant maxSmallNatFn : Unit → Nat := arbitrary _ def closureMaxArgs : Nat := closureMaxArgsFn () def maxSmallNat : Nat := maxSmallNatFn () end Lean
84528985657c85af849fa584afb735e7204fc9f4
f5373ccdc976e6390397d9f4220a74c76f706f4a
/src/examples/main_entry.lean
ae2e0ed1b71b7214c00493745258081ae057ea8a
[]
no_license
jasonrute/lean_gym_prototype
fcd91fdc454f9e351bbe258c765f50276407547e
ab29624d14e4e069e15afe0b1d90248b5b394b86
refs/heads/master
1,682,628,526,780
1,590,539,315,000
1,590,539,315,000
264,938,525
3
0
null
null
null
null
UTF-8
Lean
false
false
394
lean
import lean_gym.server -- set up server meta def json_config : json_server lean_server_request lean_server_response := { read_write := io_streams.stdin_stdout_streams, get_json := json_server.get_custom_json, -- use custom format since faster put_json := json_server.put_standard_json, -- use standard format } meta def main : io unit := lean_gym.run_server_from_io json_config
3427ee15a15c25a04fd45687a6d3535e6f9f3882
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/zsqrtd/basic.lean
2fc118a957dd4201f14571fd50917187351922c5
[ "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
31,664
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.associated import tactic.ring /-- The ring of integers adjoined with a square root of `d`. These have the form `a + b √d` where `a b : ℤ`. The components are called `re` and `im` by analogy to the negative `d` case. -/ structure zsqrtd (d : ℤ) := (re : ℤ) (im : ℤ) prefix `ℤ√`:100 := zsqrtd namespace zsqrtd section parameters {d : ℤ} instance : decidable_eq ℤ√d := by tactic.mk_dec_eq_instance theorem ext : ∀ {z w : ℤ√d}, z = w ↔ z.re = w.re ∧ z.im = w.im | ⟨x, y⟩ ⟨x', y'⟩ := ⟨λ h, by injection h; split; assumption, λ ⟨h₁, h₂⟩, by congr; assumption⟩ /-- Convert an integer to a `ℤ√d` -/ def of_int (n : ℤ) : ℤ√d := ⟨n, 0⟩ theorem of_int_re (n : ℤ) : (of_int n).re = n := rfl theorem of_int_im (n : ℤ) : (of_int n).im = 0 := rfl /-- The zero of the ring -/ def zero : ℤ√d := of_int 0 instance : has_zero ℤ√d := ⟨zsqrtd.zero⟩ @[simp] theorem zero_re : (0 : ℤ√d).re = 0 := rfl @[simp] theorem zero_im : (0 : ℤ√d).im = 0 := rfl instance : inhabited ℤ√d := ⟨0⟩ /-- The one of the ring -/ def one : ℤ√d := of_int 1 instance : has_one ℤ√d := ⟨zsqrtd.one⟩ @[simp] theorem one_re : (1 : ℤ√d).re = 1 := rfl @[simp] theorem one_im : (1 : ℤ√d).im = 0 := rfl /-- The representative of `√d` in the ring -/ def sqrtd : ℤ√d := ⟨0, 1⟩ @[simp] theorem sqrtd_re : (sqrtd : ℤ√d).re = 0 := rfl @[simp] theorem sqrtd_im : (sqrtd : ℤ√d).im = 1 := rfl /-- Addition of elements of `ℤ√d` -/ def add : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x + x', y + y'⟩ instance : has_add ℤ√d := ⟨zsqrtd.add⟩ @[simp] theorem add_def (x y x' y' : ℤ) : (⟨x, y⟩ + ⟨x', y'⟩ : ℤ√d) = ⟨x + x', y + y'⟩ := rfl @[simp] theorem add_re : ∀ z w : ℤ√d, (z + w).re = z.re + w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem add_im : ∀ z w : ℤ√d, (z + w).im = z.im + w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem bit0_re (z) : (bit0 z : ℤ√d).re = bit0 z.re := add_re _ _ @[simp] theorem bit0_im (z) : (bit0 z : ℤ√d).im = bit0 z.im := add_im _ _ @[simp] theorem bit1_re (z) : (bit1 z : ℤ√d).re = bit1 z.re := by simp [bit1] @[simp] theorem bit1_im (z) : (bit1 z : ℤ√d).im = bit0 z.im := by simp [bit1] /-- Negation in `ℤ√d` -/ def neg : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨-x, -y⟩ instance : has_neg ℤ√d := ⟨zsqrtd.neg⟩ @[simp] theorem neg_re : ∀ z : ℤ√d, (-z).re = -z.re | ⟨x, y⟩ := rfl @[simp] theorem neg_im : ∀ z : ℤ√d, (-z).im = -z.im | ⟨x, y⟩ := rfl /-- Multiplication in `ℤ√d` -/ def mul : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x * x' + d * y * y', x * y' + y * x'⟩ instance : has_mul ℤ√d := ⟨zsqrtd.mul⟩ @[simp] theorem mul_re : ∀ z w : ℤ√d, (z * w).re = z.re * w.re + d * z.im * w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem mul_im : ∀ z w : ℤ√d, (z * w).im = z.re * w.im + z.im * w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl instance : comm_ring ℤ√d := by refine_struct { add := (+), zero := (0 : ℤ√d), neg := has_neg.neg, mul := (*), sub := λ a b, a + -b, one := 1, npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec _ ⟨0⟩ ⟨(+)⟩, gsmul := @gsmul_rec _ ⟨0⟩ ⟨(+)⟩ ⟨zsqrtd.neg⟩ }; intros; try { refl }; simp [ext, add_mul, mul_add, add_comm, add_left_comm, mul_comm, mul_left_comm] instance : add_comm_monoid ℤ√d := by apply_instance instance : add_monoid ℤ√d := by apply_instance instance : monoid ℤ√d := by apply_instance instance : comm_monoid ℤ√d := by apply_instance instance : comm_semigroup ℤ√d := by apply_instance instance : semigroup ℤ√d := by apply_instance instance : add_comm_semigroup ℤ√d := by apply_instance instance : add_semigroup ℤ√d := by apply_instance instance : comm_semiring ℤ√d := by apply_instance instance : semiring ℤ√d := by apply_instance instance : ring ℤ√d := by apply_instance instance : distrib ℤ√d := by apply_instance /-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/ def conj : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨x, -y⟩ @[simp] theorem conj_re : ∀ z : ℤ√d, (conj z).re = z.re | ⟨x, y⟩ := rfl @[simp] theorem conj_im : ∀ z : ℤ√d, (conj z).im = -z.im | ⟨x, y⟩ := rfl /-- `conj` as an `add_monoid_hom`. -/ def conj_hom : ℤ√d →+ ℤ√d := { to_fun := conj, map_add' := λ ⟨a, ai⟩ ⟨b, bi⟩, ext.mpr ⟨rfl, neg_add _ _⟩, map_zero' := ext.mpr ⟨rfl, neg_zero⟩ } @[simp] lemma conj_zero : conj (0 : ℤ√d) = 0 := conj_hom.map_zero @[simp] lemma conj_one : conj (1 : ℤ√d) = 1 := by simp only [zsqrtd.ext, zsqrtd.conj_re, zsqrtd.conj_im, zsqrtd.one_im, neg_zero, eq_self_iff_true, and_self] @[simp] lemma conj_neg (x : ℤ√d) : (-x).conj = -x.conj := conj_hom.map_neg x @[simp] lemma conj_add (x y : ℤ√d) : (x + y).conj = x.conj + y.conj := conj_hom.map_add x y @[simp] lemma conj_sub (x y : ℤ√d) : (x - y).conj = x.conj - y.conj := conj_hom.map_sub x y @[simp] lemma conj_conj {d : ℤ} (x : ℤ√d) : x.conj.conj = x := by simp only [ext, true_and, conj_re, eq_self_iff_true, neg_neg, conj_im] instance : nontrivial ℤ√d := ⟨⟨0, 1, dec_trivial⟩⟩ @[simp] theorem coe_nat_re (n : ℕ) : (n : ℤ√d).re = n := by induction n; simp * @[simp] theorem coe_nat_im (n : ℕ) : (n : ℤ√d).im = 0 := by induction n; simp * theorem coe_nat_val (n : ℕ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] @[simp] theorem coe_int_re (n : ℤ) : (n : ℤ√d).re = n := by cases n; simp [*, int.of_nat_eq_coe, int.neg_succ_of_nat_eq] @[simp] theorem coe_int_im (n : ℤ) : (n : ℤ√d).im = 0 := by cases n; simp * theorem coe_int_val (n : ℤ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] instance : char_zero ℤ√d := { cast_injective := λ m n, by simp [ext] } @[simp] theorem of_int_eq_coe (n : ℤ) : (of_int n : ℤ√d) = n := by simp [ext, of_int_re, of_int_im] @[simp] theorem smul_val (n x y : ℤ) : (n : ℤ√d) * ⟨x, y⟩ = ⟨n * x, n * y⟩ := by simp [ext] @[simp] theorem muld_val (x y : ℤ) : sqrtd * ⟨x, y⟩ = ⟨d * y, x⟩ := by simp [ext] @[simp] theorem dmuld : sqrtd * sqrtd = d := by simp [ext] @[simp] theorem smuld_val (n x y : ℤ) : sqrtd * (n : ℤ√d) * ⟨x, y⟩ = ⟨d * n * y, n * x⟩ := by simp [ext] theorem decompose {x y : ℤ} : (⟨x, y⟩ : ℤ√d) = x + sqrtd * y := by simp [ext] theorem mul_conj {x y : ℤ} : (⟨x, y⟩ * conj ⟨x, y⟩ : ℤ√d) = x * x - d * y * y := by simp [ext, sub_eq_add_neg, mul_comm] theorem conj_mul {a b : ℤ√d} : conj (a * b) = conj a * conj b := by { simp [ext], ring } protected lemma coe_int_add (m n : ℤ) : (↑(m + n) : ℤ√d) = ↑m + ↑n := (int.cast_ring_hom _).map_add _ _ protected lemma coe_int_sub (m n : ℤ) : (↑(m - n) : ℤ√d) = ↑m - ↑n := (int.cast_ring_hom _).map_sub _ _ protected lemma coe_int_mul (m n : ℤ) : (↑(m * n) : ℤ√d) = ↑m * ↑n := (int.cast_ring_hom _).map_mul _ _ protected lemma coe_int_inj {m n : ℤ} (h : (↑m : ℤ√d) = ↑n) : m = n := by simpa using congr_arg re h lemma coe_int_dvd_iff {d : ℤ} (z : ℤ) (a : ℤ√d) : ↑z ∣ a ↔ z ∣ a.re ∧ z ∣ a.im := begin split, { rintro ⟨x, rfl⟩, simp only [add_zero, coe_int_re, zero_mul, mul_im, dvd_mul_right, and_self, mul_re, mul_zero, coe_int_im] }, { rintro ⟨⟨r, hr⟩, ⟨i, hi⟩⟩, use ⟨r, i⟩, rw [smul_val, ext], exact ⟨hr, hi⟩ }, end /-- Read `sq_le a c b d` as `a √c ≤ b √d` -/ def sq_le (a c b d : ℕ) : Prop := c*a*a ≤ d*b*b theorem sq_le_of_le {c d x y z w : ℕ} (xz : z ≤ x) (yw : y ≤ w) (xy : sq_le x c y d) : sq_le z c w d := le_trans (mul_le_mul (nat.mul_le_mul_left _ xz) xz (nat.zero_le _) (nat.zero_le _)) $ le_trans xy (mul_le_mul (nat.mul_le_mul_left _ yw) yw (nat.zero_le _) (nat.zero_le _)) theorem sq_le_add_mixed {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : c * (x * z) ≤ d * (y * w) := nat.mul_self_le_mul_self_iff.2 $ by simpa [mul_comm, mul_left_comm] using mul_le_mul xy zw (nat.zero_le _) (nat.zero_le _) theorem sq_le_add {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : sq_le (x + z) c (y + w) d := begin have xz := sq_le_add_mixed xy zw, simp [sq_le, mul_assoc] at xy zw, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_le_add, *] end theorem sq_le_cancel {c d x y z w : ℕ} (zw : sq_le y d x c) (h : sq_le (x + z) c (y + w) d) : sq_le z c w d := begin apply le_of_not_gt, intro l, refine not_le_of_gt _ h, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_assoc], have hm := sq_le_add_mixed zw (le_of_lt l), simp [sq_le, mul_assoc] at l zw, exact lt_of_le_of_lt (add_le_add_right zw _) (add_lt_add_left (add_lt_add_of_le_of_lt hm (add_lt_add_of_le_of_lt hm l)) _) end theorem sq_le_smul {c d x y : ℕ} (n : ℕ) (xy : sq_le x c y d) : sq_le (n * x) c (n * y) d := by simpa [sq_le, mul_left_comm, mul_assoc] using nat.mul_le_mul_left (n * n) xy theorem sq_le_mul {d x y z w : ℕ} : (sq_le x 1 y d → sq_le z 1 w d → sq_le (x * w + y * z) d (x * z + d * y * w) 1) ∧ (sq_le x 1 y d → sq_le w d z 1 → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le z 1 w d → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le w d z 1 → sq_le (x * w + y * z) d (x * z + d * y * w) 1) := by refine ⟨_, _, _, _⟩; { intros xy zw, have := int.mul_nonneg (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le xy)) (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le zw)), refine int.le_of_coe_nat_le_coe_nat (le_of_sub_nonneg _), convert this, simp only [one_mul, int.coe_nat_add, int.coe_nat_mul], ring } /-- "Generalized" `nonneg`. `nonnegg c d x y` means `a √c + b √d ≥ 0`; we are interested in the case `c = 1` but this is more symmetric -/ def nonnegg (c d : ℕ) : ℤ → ℤ → Prop | (a : ℕ) (b : ℕ) := true | (a : ℕ) -[1+ b] := sq_le (b+1) c a d | -[1+ a] (b : ℕ) := sq_le (a+1) d b c | -[1+ a] -[1+ b] := false theorem nonnegg_comm {c d : ℕ} {x y : ℤ} : nonnegg c d x y = nonnegg d c y x := by induction x; induction y; refl theorem nonnegg_neg_pos {c d} : Π {a b : ℕ}, nonnegg c d (-a) b ↔ sq_le a d b c | 0 b := ⟨by simp [sq_le, nat.zero_le], λa, trivial⟩ | (a+1) b := by rw ← int.neg_succ_of_nat_coe; refl theorem nonnegg_pos_neg {c d} {a b : ℕ} : nonnegg c d a (-b) ↔ sq_le b c a d := by rw nonnegg_comm; exact nonnegg_neg_pos theorem nonnegg_cases_right {c d} {a : ℕ} : Π {b : ℤ}, (Π x : ℕ, b = -x → sq_le x c a d) → nonnegg c d a b | (b:nat) h := trivial | -[1+ b] h := h (b+1) rfl theorem nonnegg_cases_left {c d} {b : ℕ} {a : ℤ} (h : Π x : ℕ, a = -x → sq_le x d b c) : nonnegg c d a b := cast nonnegg_comm (nonnegg_cases_right h) section norm def norm (n : ℤ√d) : ℤ := n.re * n.re - d * n.im * n.im lemma norm_def (n : ℤ√d) : n.norm = n.re * n.re - d * n.im * n.im := rfl @[simp] lemma norm_zero : norm 0 = 0 := by simp [norm] @[simp] lemma norm_one : norm 1 = 1 := by simp [norm] @[simp] lemma norm_int_cast (n : ℤ) : norm n = n * n := by simp [norm] @[simp] lemma norm_nat_cast (n : ℕ) : norm n = n * n := norm_int_cast n @[simp] lemma norm_mul (n m : ℤ√d) : norm (n * m) = norm n * norm m := by { simp only [norm, mul_im, mul_re], ring } /-- `norm` as a `monoid_hom`. -/ def norm_monoid_hom : ℤ√d →* ℤ := { to_fun := norm, map_mul' := norm_mul, map_one' := norm_one } lemma norm_eq_mul_conj (n : ℤ√d) : (norm n : ℤ√d) = n * n.conj := by cases n; simp [norm, conj, zsqrtd.ext, mul_comm, sub_eq_add_neg] @[simp] lemma norm_neg (x : ℤ√d) : (-x).norm = x.norm := coe_int_inj $ by simp only [norm_eq_mul_conj, conj_neg, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, neg_neg] @[simp] lemma norm_conj (x : ℤ√d) : x.conj.norm = x.norm := coe_int_inj $ by simp only [norm_eq_mul_conj, conj_conj, mul_comm] instance : is_monoid_hom norm := { map_one := norm_one, map_mul := norm_mul } lemma norm_nonneg (hd : d ≤ 0) (n : ℤ√d) : 0 ≤ n.norm := add_nonneg (mul_self_nonneg _) (by rw [mul_assoc, neg_mul_eq_neg_mul]; exact (mul_nonneg (neg_nonneg.2 hd) (mul_self_nonneg _))) lemma norm_eq_one_iff {x : ℤ√d} : x.norm.nat_abs = 1 ↔ is_unit x := ⟨λ h, is_unit_iff_dvd_one.2 $ (le_total 0 (norm x)).cases_on (λ hx, show x ∣ 1, from ⟨x.conj, by rwa [← int.coe_nat_inj', int.nat_abs_of_nonneg hx, ← @int.cast_inj (ℤ√d) _ _, norm_eq_mul_conj, eq_comm] at h⟩) (λ hx, show x ∣ 1, from ⟨- x.conj, by rwa [← int.coe_nat_inj', int.of_nat_nat_abs_of_nonpos hx, ← @int.cast_inj (ℤ√d) _ _, int.cast_neg, norm_eq_mul_conj, neg_mul_eq_mul_neg, eq_comm] at h⟩), λ h, let ⟨y, hy⟩ := is_unit_iff_dvd_one.1 h in begin have := congr_arg (int.nat_abs ∘ norm) hy, rw [function.comp_app, function.comp_app, norm_mul, int.nat_abs_mul, norm_one, int.nat_abs_one, eq_comm, nat.mul_eq_one_iff] at this, exact this.1 end⟩ lemma is_unit_iff_norm_is_unit {d : ℤ} (z : ℤ√d) : is_unit z ↔ is_unit z.norm := by rw [int.is_unit_iff_nat_abs_eq, norm_eq_one_iff] lemma norm_eq_one_iff' {d : ℤ} (hd : d ≤ 0) (z : ℤ√d) : z.norm = 1 ↔ is_unit z := by rw [←norm_eq_one_iff, ←int.coe_nat_inj', int.nat_abs_of_nonneg (norm_nonneg hd z), int.coe_nat_one] lemma norm_eq_zero_iff {d : ℤ} (hd : d < 0) (z : ℤ√d) : z.norm = 0 ↔ z = 0 := begin split, { intro h, rw [ext, zero_re, zero_im], rw [norm_def, sub_eq_add_neg, mul_assoc] at h, have left := mul_self_nonneg z.re, have right := neg_nonneg.mpr (mul_nonpos_of_nonpos_of_nonneg hd.le (mul_self_nonneg z.im)), obtain ⟨ha, hb⟩ := (add_eq_zero_iff_eq_zero_of_nonneg left right).mp h, split; apply eq_zero_of_mul_self_eq_zero, { exact ha }, { rw [neg_eq_zero, mul_eq_zero] at hb, exact hb.resolve_left hd.ne } }, { rintro rfl, exact norm_zero } end lemma norm_eq_of_associated {d : ℤ} (hd : d ≤ 0) {x y : ℤ√d} (h : associated x y) : x.norm = y.norm := begin obtain ⟨u, rfl⟩ := h, rw [norm_mul, (norm_eq_one_iff' hd _).mpr u.is_unit, mul_one], end end norm end section parameter {d : ℕ} /-- Nonnegativity of an element of `ℤ√d`. -/ def nonneg : ℤ√d → Prop | ⟨a, b⟩ := nonnegg d 1 a b protected def le (a b : ℤ√d) : Prop := nonneg (b - a) instance : has_le ℤ√d := ⟨zsqrtd.le⟩ protected def lt (a b : ℤ√d) : Prop := ¬(b ≤ a) instance : has_lt ℤ√d := ⟨zsqrtd.lt⟩ instance decidable_nonnegg (c d a b) : decidable (nonnegg c d a b) := by cases a; cases b; repeat {rw int.of_nat_eq_coe}; unfold nonnegg sq_le; apply_instance instance decidable_nonneg : Π (a : ℤ√d), decidable (nonneg a) | ⟨a, b⟩ := zsqrtd.decidable_nonnegg _ _ _ _ instance decidable_le (a b : ℤ√d) : decidable (a ≤ b) := decidable_nonneg _ theorem nonneg_cases : Π {a : ℤ√d}, nonneg a → ∃ x y : ℕ, a = ⟨x, y⟩ ∨ a = ⟨x, -y⟩ ∨ a = ⟨-x, y⟩ | ⟨(x : ℕ), (y : ℕ)⟩ h := ⟨x, y, or.inl rfl⟩ | ⟨(x : ℕ), -[1+ y]⟩ h := ⟨x, y+1, or.inr $ or.inl rfl⟩ | ⟨-[1+ x], (y : ℕ)⟩ h := ⟨x+1, y, or.inr $ or.inr rfl⟩ | ⟨-[1+ x], -[1+ y]⟩ h := false.elim h lemma nonneg_add_lem {x y z w : ℕ} (xy : nonneg ⟨x, -y⟩) (zw : nonneg ⟨-z, w⟩) : nonneg (⟨x, -y⟩ + ⟨-z, w⟩) := have nonneg ⟨int.sub_nat_nat x z, int.sub_nat_nat w y⟩, from int.sub_nat_nat_elim x z (λm n i, sq_le y d m 1 → sq_le n 1 w d → nonneg ⟨i, int.sub_nat_nat w y⟩) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d (k + j) 1 → sq_le k 1 m d → nonneg ⟨int.of_nat j, i⟩) (λm n xy zw, trivial) (λm n xy zw, sq_le_cancel zw xy)) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d k 1 → sq_le (k + j + 1) 1 m d → nonneg ⟨-[1+ j], i⟩) (λm n xy zw, sq_le_cancel xy zw) (λm n xy zw, let t := nat.le_trans zw (sq_le_of_le (nat.le_add_right n (m+1)) (le_refl _) xy) in have k + j + 1 ≤ k, from nat.mul_self_le_mul_self_iff.2 (by repeat{rw one_mul at t}; exact t), absurd this (not_le_of_gt $ nat.succ_le_succ $ nat.le_add_right _ _))) (nonnegg_pos_neg.1 xy) (nonnegg_neg_pos.1 zw), show nonneg ⟨_, _⟩, by rw [neg_add_eq_sub]; rwa [int.sub_nat_nat_eq_coe,int.sub_nat_nat_eq_coe] at this theorem nonneg_add {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a + b) := begin rcases nonneg_cases ha with ⟨x, y, rfl|rfl|rfl⟩; rcases nonneg_cases hb with ⟨z, w, rfl|rfl|rfl⟩; dsimp [add, nonneg] at ha hb ⊢, { trivial }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ y (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ x (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ w (by simp *))) }, { apply nat.le_add_right } }, { simpa [add_comm] using nonnegg_pos_neg.2 (sq_le_add (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) }, { exact nonneg_add_lem ha hb }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ z (by simp *))) }, { apply nat.le_add_right } }, { rw [add_comm, add_comm ↑y], exact nonneg_add_lem hb ha }, { simpa [add_comm] using nonnegg_neg_pos.2 (sq_le_add (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) }, end theorem le_refl (a : ℤ√d) : a ≤ a := show nonneg (a - a), by simp protected theorem le_trans {a b c : ℤ√d} (ab : a ≤ b) (bc : b ≤ c) : a ≤ c := have nonneg (b - a + (c - b)), from nonneg_add ab bc, by simpa [sub_add_sub_cancel'] theorem nonneg_iff_zero_le {a : ℤ√d} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem le_of_le_le {x y z w : ℤ} (xz : x ≤ z) (yw : y ≤ w) : (⟨x, y⟩ : ℤ√d) ≤ ⟨z, w⟩ := show nonneg ⟨z - x, w - y⟩, from match z - x, w - y, int.le.dest_sub xz, int.le.dest_sub yw with ._, ._, ⟨a, rfl⟩, ⟨b, rfl⟩ := trivial end theorem le_arch (a : ℤ√d) : ∃n : ℕ, a ≤ n := let ⟨x, y, (h : a ≤ ⟨x, y⟩)⟩ := show ∃x y : ℕ, nonneg (⟨x, y⟩ + -a), from match -a with | ⟨int.of_nat x, int.of_nat y⟩ := ⟨0, 0, trivial⟩ | ⟨int.of_nat x, -[1+ y]⟩ := ⟨0, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], int.of_nat y⟩ := ⟨x+1, 0, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], -[1+ y]⟩ := ⟨x+1, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ end in begin refine ⟨x + d*y, zsqrtd.le_trans h _⟩, rw [← int.cast_coe_nat, ← of_int_eq_coe], change nonneg ⟨(↑x + d*y) - ↑x, 0-↑y⟩, cases y with y, { simp }, have h : ∀y, sq_le y d (d * y) 1 := λ y, by simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_right (y * y) (nat.le_mul_self d), rw [show (x:ℤ) + d * nat.succ y - x = d * nat.succ y, by simp], exact h (y+1) end protected theorem nonneg_total : Π (a : ℤ√d), nonneg a ∨ nonneg (-a) | ⟨(x : ℕ), (y : ℕ)⟩ := or.inl trivial | ⟨-[1+ x], -[1+ y]⟩ := or.inr trivial | ⟨0, -[1+ y]⟩ := or.inr trivial | ⟨-[1+ x], 0⟩ := or.inr trivial | ⟨(x+1:ℕ), -[1+ y]⟩ := nat.le_total | ⟨-[1+ x], (y+1:ℕ)⟩ := nat.le_total protected theorem le_total (a b : ℤ√d) : a ≤ b ∨ b ≤ a := let t := nonneg_total (b - a) in by rw [show -(b-a) = a-b, from neg_sub b a] at t; exact t instance : preorder ℤ√d := { le := zsqrtd.le, le_refl := zsqrtd.le_refl, le_trans := @zsqrtd.le_trans, lt := zsqrtd.lt, lt_iff_le_not_le := λ a b, (and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm } protected theorem add_le_add_left (a b : ℤ√d) (ab : a ≤ b) (c : ℤ√d) : c + a ≤ c + b := show nonneg _, by rw add_sub_add_left_eq_sub; exact ab protected theorem le_of_add_le_add_left (a b c : ℤ√d) (h : c + a ≤ c + b) : a ≤ b := by simpa using zsqrtd.add_le_add_left _ _ h (-c) protected theorem add_lt_add_left (a b : ℤ√d) (h : a < b) (c) : c + a < c + b := λ h', h (zsqrtd.le_of_add_le_add_left _ _ _ h') theorem nonneg_smul {a : ℤ√d} {n : ℕ} (ha : nonneg a) : nonneg (n * a) := by rw ← int.cast_coe_nat; exact match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := by rw smul_val; trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by rw smul_val; simpa using nonnegg_pos_neg.2 (sq_le_smul n $ nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by rw smul_val; simpa using nonnegg_neg_pos.2 (sq_le_smul n $ nonnegg_neg_pos.1 ha) end theorem nonneg_muld {a : ℤ√d} (ha : nonneg a) : nonneg (sqrtd * a) := by refine match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by simp; apply nonnegg_neg_pos.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by simp; apply nonnegg_pos_neg.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_neg_pos.1 ha) end theorem nonneg_mul_lem {x y : ℕ} {a : ℤ√d} (ha : nonneg a) : nonneg (⟨x, y⟩ * a) := have (⟨x, y⟩ * a : ℤ√d) = x * a + sqrtd * (y * a), by rw [decompose, right_distrib, mul_assoc]; refl, by rw this; exact nonneg_add (nonneg_smul ha) (nonneg_muld $ nonneg_smul ha) theorem nonneg_mul {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a * b) := match a, b, nonneg_cases ha, nonneg_cases hb, ha, hb with | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := trivial | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.left (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.left (nonnegg_neg_pos.1 ha) (nonnegg_pos_neg.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.right.left (nonnegg_pos_neg.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.right.right.right (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) end protected theorem mul_nonneg (a b : ℤ√d) : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by repeat {rw ← nonneg_iff_zero_le}; exact nonneg_mul theorem not_sq_le_succ (c d y) (h : 0 < c) : ¬sq_le (y + 1) c 0 d := not_le_of_gt $ mul_pos (mul_pos h $ nat.succ_pos _) $ nat.succ_pos _ /-- A nonsquare is a natural number that is not equal to the square of an integer. This is implemented as a typeclass because it's a necessary condition for much of the Pell equation theory. -/ class nonsquare (x : ℕ) : Prop := (ns [] : ∀n : ℕ, x ≠ n*n) parameter [dnsq : nonsquare d] include dnsq theorem d_pos : 0 < d := lt_of_le_of_ne (nat.zero_le _) $ ne.symm $ (nonsquare.ns d 0) theorem divides_sq_eq_zero {x y} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := let g := x.gcd y in or.elim g.eq_zero_or_pos (λH, ⟨nat.eq_zero_of_gcd_eq_zero_left H, nat.eq_zero_of_gcd_eq_zero_right H⟩) (λgpos, false.elim $ let ⟨m, n, co, (hx : x = m * g), (hy : y = n * g)⟩ := nat.exists_coprime gpos in begin rw [hx, hy] at h, have : m * m = d * (n * n) := nat.eq_of_mul_eq_mul_left (mul_pos gpos gpos) (by simpa [mul_comm, mul_left_comm] using h), have co2 := let co1 := co.mul_right co in co1.mul co1, exact nonsquare.ns d m (nat.dvd_antisymm (by rw this; apply dvd_mul_right) $ co2.dvd_of_dvd_mul_right $ by simp [this]) end) theorem divides_sq_eq_zero_z {x y : ℤ} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := by rw [mul_assoc, ← int.nat_abs_mul_self, ← int.nat_abs_mul_self, ← int.coe_nat_mul, ← mul_assoc] at h; exact let ⟨h1, h2⟩ := divides_sq_eq_zero (int.coe_nat_inj h) in ⟨int.eq_zero_of_nat_abs_eq_zero h1, int.eq_zero_of_nat_abs_eq_zero h2⟩ theorem not_divides_sq (x y) : (x + 1) * (x + 1) ≠ d * (y + 1) * (y + 1) := λe, by have t := (divides_sq_eq_zero e).left; contradiction theorem nonneg_antisymm : Π {a : ℤ√d}, nonneg a → nonneg (-a) → a = 0 | ⟨0, 0⟩ xy yx := rfl | ⟨-[1+ x], -[1+ y]⟩ xy yx := false.elim xy | ⟨(x+1:nat), (y+1:nat)⟩ xy yx := false.elim yx | ⟨-[1+ x], 0⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ dec_trivial) | ⟨(x+1:nat), 0⟩ xy yx := absurd yx (not_sq_le_succ _ _ _ dec_trivial) | ⟨0, -[1+ y]⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ d_pos) | ⟨0, (y+1:nat)⟩ _ yx := absurd yx (not_sq_le_succ _ _ _ d_pos) | ⟨(x+1:nat), -[1+ y]⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm yx xy in by rw[one_mul] at t; exact absurd t (not_divides_sq _ _) | ⟨-[1+ x], (y+1:nat)⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm xy yx in by rw[one_mul] at t; exact absurd t (not_divides_sq _ _) theorem le_antisymm {a b : ℤ√d} (ab : a ≤ b) (ba : b ≤ a) : a = b := eq_of_sub_eq_zero $ nonneg_antisymm ba (by rw neg_sub; exact ab) instance : linear_order ℤ√d := { le_antisymm := @zsqrtd.le_antisymm, le_total := zsqrtd.le_total, decidable_le := zsqrtd.decidable_le, ..zsqrtd.preorder } protected theorem eq_zero_or_eq_zero_of_mul_eq_zero : Π {a b : ℤ√d}, a * b = 0 → a = 0 ∨ b = 0 | ⟨x, y⟩ ⟨z, w⟩ h := by injection h with h1 h2; exact have h1 : x*z = -(d*y*w), from eq_neg_of_add_eq_zero h1, have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero h2, have fin : x*x = d*y*y → (⟨x, y⟩:ℤ√d) = 0, from λe, match x, y, divides_sq_eq_zero_z e with ._, ._, ⟨rfl, rfl⟩ := rfl end, if z0 : z = 0 then if w0 : w = 0 then or.inr (match z, w, z0, w0 with ._, ._, rfl, rfl := rfl end) else or.inl $ fin $ mul_right_cancel' w0 $ calc x * x * w = -y * (x * z) : by simp [h2, mul_assoc, mul_left_comm] ... = d * y * y * w : by simp [h1, mul_assoc, mul_left_comm] else or.inl $ fin $ mul_right_cancel' z0 $ calc x * x * z = d * -y * (x * w) : by simp [h1, mul_assoc, mul_left_comm] ... = d * y * y * z : by simp [h2, mul_assoc, mul_left_comm] instance : integral_domain ℤ√d := { eq_zero_or_eq_zero_of_mul_eq_zero := @zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero, .. zsqrtd.comm_ring, .. zsqrtd.nontrivial } protected theorem mul_pos (a b : ℤ√d) (a0 : 0 < a) (b0 : 0 < b) : 0 < a * b := λab, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero (le_antisymm ab (mul_nonneg _ _ (le_of_lt a0) (le_of_lt b0)))) (λe, ne_of_gt a0 e) (λe, ne_of_gt b0 e) instance : linear_ordered_comm_ring ℤ√d := { add_le_add_left := @zsqrtd.add_le_add_left, mul_pos := @zsqrtd.mul_pos, zero_le_one := dec_trivial, .. zsqrtd.comm_ring, .. zsqrtd.linear_order, .. zsqrtd.nontrivial } instance : linear_ordered_semiring ℤ√d := by apply_instance instance : ordered_semiring ℤ√d := by apply_instance end lemma norm_eq_zero {d : ℤ} (h_nonsquare : ∀ n : ℤ, d ≠ n*n) (a : ℤ√d) : norm a = 0 ↔ a = 0 := begin refine ⟨λ ha, ext.mpr _, λ h, by rw [h, norm_zero]⟩, delta norm at ha, rw sub_eq_zero at ha, by_cases h : 0 ≤ d, { obtain ⟨d', rfl⟩ := int.eq_coe_of_zero_le h, haveI : nonsquare d' := ⟨λ n h, h_nonsquare n $ by exact_mod_cast h⟩, exact divides_sq_eq_zero_z ha, }, { push_neg at h, suffices : a.re * a.re = 0, { rw eq_zero_of_mul_self_eq_zero this at ha ⊢, simpa only [true_and, or_self_right, zero_re, zero_im, eq_self_iff_true, zero_eq_mul, mul_zero, mul_eq_zero, h.ne, false_or, or_self] using ha }, apply _root_.le_antisymm _ (mul_self_nonneg _), rw [ha, mul_assoc], exact mul_nonpos_of_nonpos_of_nonneg h.le (mul_self_nonneg _) } end variables {R : Type} [comm_ring R] @[ext] lemma hom_ext {d : ℤ} (f g : ℤ√d →+* R) (h : f sqrtd = g sqrtd) : f = g := begin ext ⟨x_re, x_im⟩, simp [decompose, h], end /-- The unique `ring_hom` from `ℤ√d` to a ring `R`, constructed by replacing `√d` with the provided root. Conversely, this associates to every mapping `ℤ√d →+* R` a value of `√d` in `R`. -/ @[simps] def lift {d : ℤ} : {r : R // r * r = ↑d} ≃ (ℤ√d →+* R) := { to_fun := λ r, { to_fun := λ a, a.1 + a.2*(r : R), map_zero' := by simp, map_add' := λ a b, by { simp, ring, }, map_one' := by simp, map_mul' := λ a b, by { have : (a.re + a.im * r : R) * (b.re + b.im * r) = a.re * b.re + (a.re * b.im + a.im * b.re) * r + a.im * b.im * (r * r) := by ring, simp [this, r.prop], ring, } }, inv_fun := λ f, ⟨f sqrtd, by rw [←f.map_mul, dmuld, ring_hom.map_int_cast]⟩, left_inv := λ r, by { ext, simp }, right_inv := λ f, by { ext, simp } } /-- `lift r` is injective if `d` is non-square, and R has characteristic zero (that is, the map from `ℤ` into `R` is injective). -/ lemma lift_injective [char_zero R] {d : ℤ} (r : {r : R // r * r = ↑d}) (hd : ∀ n : ℤ, d ≠ n*n) : function.injective (lift r) := (lift r).injective_iff.mpr $ λ a ha, begin have h_inj : function.injective (coe : ℤ → R) := int.cast_injective, suffices : lift r a.norm = 0, { simp only [coe_int_re, add_zero, lift_apply_apply, coe_int_im, int.cast_zero, zero_mul] at this, rwa [← int.cast_zero, h_inj.eq_iff, norm_eq_zero hd] at this }, rw [norm_eq_mul_conj, ring_hom.map_mul, ha, zero_mul] end end zsqrtd
654485eb572a2838bdfddf9290d4a028a19a638a
64874bd1010548c7f5a6e3e8902efa63baaff785
/hott/init/types/empty.hlean
fea08e5b5118a1cad3a1d3435f19817a6c1bbbf9
[ "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
494
hlean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Jeremy Avigad, Floris van Doorn, Jakob von Raumer prelude import ..datatypes ..logic -- Empty type -- ---------- namespace empty protected theorem elim (A : Type) (H : empty) : A := rec (λe, A) H end empty protected definition empty.has_decidable_eq [instance] : decidable_eq empty := take (a b : empty), decidable.inl (!empty.elim a)
6a1cf8a87453ce4c2e96387d18d5988c35da3dbe
b04370a335fa89c708a3d43678d79c1f61aa24c7
/library/init/data/list/instances.lean
4680964724a3d983a1a0fd10d86dcae5b7d88faa
[ "Apache-2.0" ]
permissive
jalex-stark/lean
9b97cd8b0eb970ab0d4cdbc7b4dd57645f33a92c
85ba44431d77c8222342c7616f0bfa98fba88368
refs/heads/master
1,664,328,815,754
1,590,514,885,000
1,590,514,885,000
267,196,280
0
0
null
1,590,544,752,000
1,590,544,752,000
null
UTF-8
Lean
false
false
1,794
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.list.lemmas open list universes u v local attribute [simp] join list.ret instance : monad list := { pure := @list.ret, map := @list.map, bind := @list.bind } instance : is_lawful_monad list := { bind_pure_comp_eq_map := by intros; induction x; simp [*, (<$>), pure] at *, id_map := @list.map_id, pure_bind := by intros; simp [pure], bind_assoc := by intros; induction x; simp * } instance : alternative list := { failure := @list.nil, orelse := @list.append, ..list.monad } namespace list variables {α β : Type u} (p : α → Prop) [decidable_pred p] instance bin_tree_to_list : has_coe (bin_tree α) (list α) := ⟨bin_tree.to_list⟩ instance decidable_bex : ∀ (l : list α), decidable (∃ x ∈ l, p x) | [] := is_false (by simp) | (x::xs) := if h₁ : p x then is_true ⟨x, mem_cons_self _ _, h₁⟩ else match decidable_bex xs with | is_true h₂ := is_true begin cases h₂ with y h, cases h with hm hp, exact ⟨y, mem_cons_of_mem _ hm, hp⟩ end | is_false h₂ := is_false begin intro h, cases h with y h, cases h with hm hp, cases eq_or_mem_of_mem_cons hm, { rw [h] at hp, contradiction }, { refine absurd _ h₂, exact ⟨y, h, hp⟩ } end end instance decidable_ball (l : list α) : decidable (∀ x ∈ l, p x) := if h : ∃ x ∈ l, ¬ p x then is_false $ let ⟨x, h, np⟩ := h in λ al, np (al x h) else is_true $ λ x hx, if h' : p x then h' else false.elim $ h ⟨x, hx, h'⟩ end list
c56c6720d13872aed40563d2da537fd3729da116
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast8.lean
c7879746f61cc60e4c4d36789725e9a233c7890d
[ "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
451
lean
open nat set_option blast.strategy "preprocess" lemma l1 (a : nat) : zero = succ a → a = a → false := by blast lemma l2 (p : Prop) (a : nat) : zero = succ a → a = a → p := by blast lemma l3 (a b : nat) : succ (succ a) = succ (succ b) → a = b := by blast lemma l4 (a b : nat) : succ a = succ b → a = b := by blast lemma l5 (a b c : nat) : succ (succ a) = succ (succ b) → c = c := by blast reveal l3 l4 l5 print l3 print l4 print l5
c485bde31bdaedcbf04aaf1acb3e0c2f94ad2176
b32d3853770e6eaf06817a1b8c52064baaed0ef1
/test/lpo.lean
08b8e4f50bdf6c7b784ac1ca63e6c4975de67d6c
[]
no_license
gebner/super2
4d58b7477b6f7d945d5d866502982466db33ab0b
9bc5256c31750021ab97d6b59b7387773e54b384
refs/heads/master
1,635,021,682,021
1,634,886,326,000
1,634,886,326,000
225,600,688
4
2
null
1,598,209,306,000
1,575,371,550,000
Lean
UTF-8
Lean
false
false
468
lean
import super.lpo open tactic expr super example (x : ℕ) : true := by do x ← get_local `x, let gt := mk_lpo [``eq, x.local_uniq_name, ``has_add.add, ``has_zero.zero], let d (x y : pexpr) := (do x ← to_expr x, y ← to_expr y, trace (x,y,gt x y)), d ```(x + x) ```(x), d ```(x + 0) ```(x), d ```(x) ```(x + 0), d ```(x = x + 0) ```(x + 0 = x), m ← mk_meta_var `(ℕ), d ```(%%m + 0 = %%m) ```(%%m = %%m + 0), d ```(%%m + 0) ```(%%m), unify m `(0), triv
fbff5968b1fb7d9aa5c351ee5e5cd5bbb72c39e5
f20db13587f4dd28a4b1fbd31953afd491691fa0
/library/init/native/result.lean
dd3088fd26e10160966e0b12e1fc3d67abe7a8cc
[ "Apache-2.0" ]
permissive
AHartNtkn/lean
9a971edfc6857c63edcbf96bea6841b9a84cf916
0d83a74b26541421fc1aa33044c35b03759710ed
refs/heads/master
1,620,592,591,236
1,516,749,881,000
1,516,749,881,000
118,697,288
1
0
null
1,516,759,470,000
1,516,759,470,000
null
UTF-8
Lean
false
false
2,189
lean
/- Copyright (c) 2016 Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jared Roesch -/ prelude import init.meta.interactive namespace native inductive result (E : Type) (R : Type) : Type | err {} : E → result | ok {} : R → result def unwrap_or {E T : Type} : result E T → T → T | (result.err _) default := default | (result.ok t) _ := t def result.and_then {E T U : Type} : result E T → (T → result E U) → result E U | (result.err e) _ := result.err e | (result.ok t) f := f t local attribute [simp] result.and_then instance result_monad (E : Type) : monad (result E) := {pure := @result.ok E, bind := @result.and_then E, id_map := by intros; cases x; simp; refl, pure_bind := by intros; apply rfl, bind_assoc := by intros; cases x; simp} inductive resultT (M : Type → Type) (E : Type) (A : Type) : Type | run : M (result E A) → resultT section resultT variable {M : Type → Type} def resultT.pure [monad : monad M] {E A : Type} (x : A) : resultT M E A := resultT.run $ pure (result.ok x) def resultT.and_then [monad : monad M] {E A B : Type} : resultT M E A → (A → resultT M E B) → resultT M E B | (resultT.run action) f := resultT.run (do res_a ← action, -- a little ugly with this match match res_a with | result.err e := pure (result.err e) | result.ok a := let (resultT.run actionB) := f a in actionB end) local attribute [simp] resultT.and_then monad.bind_pure monad.pure_bind instance resultT_monad [m : monad M] (E : Type) : monad (resultT M E) := {pure := @resultT.pure M m E, bind := @resultT.and_then M m E, id_map := begin intros, cases x, simp [function.comp], have : @resultT.and_then._match_1 _ m E α _ resultT.pure = pure, { funext x, cases x; simp [resultT.pure] }, simp [this] end, pure_bind := begin intros, simp [resultT.pure], cases f x, simp [resultT.and_then] end, bind_assoc := begin intros, cases x, simp, rw [monad.bind_assoc], apply congr_arg, funext, cases x with e a; simp, { cases f a, refl }, end} end resultT end native
131b3fe0a9dae9235aba5922715447c401346407
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/list/forall2.lean
c91f13f1964beb2bd7addac50f246c7fe9933d6e
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
10,063
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl -/ import data.list.basic universes u v w z open nat function variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type z} namespace list /- forall₂ -/ variables {r : α → β → Prop} {p : γ → δ → Prop} open relator mk_iff_of_inductive_prop list.forall₂ list.forall₂_iff @[simp] theorem forall₂_cons {R : α → β → Prop} {a b l₁ l₂} : forall₂ R (a::l₁) (b::l₂) ↔ R a b ∧ forall₂ R l₁ l₂ := ⟨λ h, by cases h with h₁ h₂; split; assumption, λ ⟨h₁, h₂⟩, forall₂.cons h₁ h₂⟩ theorem forall₂.imp {R S : α → β → Prop} (H : ∀ a b, R a b → S a b) {l₁ l₂} (h : forall₂ R l₁ l₂) : forall₂ S l₁ l₂ := by induction h; constructor; solve_by_elim lemma forall₂.mp {r q s : α → β → Prop} (h : ∀a b, r a b → q a b → s a b) : ∀{l₁ l₂}, forall₂ r l₁ l₂ → forall₂ q l₁ l₂ → forall₂ s l₁ l₂ | [] [] forall₂.nil forall₂.nil := forall₂.nil | (a::l₁) (b::l₂) (forall₂.cons hr hrs) (forall₂.cons hq hqs) := forall₂.cons (h a b hr hq) (forall₂.mp hrs hqs) lemma forall₂.flip : ∀{a b}, forall₂ (flip r) b a → forall₂ r a b | _ _ forall₂.nil := forall₂.nil | (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons h₁ h₂.flip lemma forall₂_same {r : α → α → Prop} : ∀{l}, (∀x∈l, r x x) → forall₂ r l l | [] _ := forall₂.nil | (a::as) h := forall₂.cons (h _ (mem_cons_self _ _)) (forall₂_same $ assume a ha, h a $ mem_cons_of_mem _ ha) lemma forall₂_refl {r} [is_refl α r] (l : list α) : forall₂ r l l := forall₂_same $ assume a h, is_refl.refl _ lemma forall₂_eq_eq_eq : forall₂ ((=) : α → α → Prop) = (=) := begin funext a b, apply propext, split, { assume h, induction h, {refl}, simp only [*]; split; refl }, { assume h, subst h, exact forall₂_refl _ } end @[simp, priority 900] lemma forall₂_nil_left_iff {l} : forall₂ r nil l ↔ l = nil := ⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩ @[simp, priority 900] lemma forall₂_nil_right_iff {l} : forall₂ r l nil ↔ l = nil := ⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩ lemma forall₂_cons_left_iff {a l u} : forall₂ r (a::l) u ↔ (∃b u', r a b ∧ forall₂ r l u' ∧ u = b :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_cons_right_iff {b l u} : forall₂ r u (b::l) ↔ (∃a u', r a b ∧ forall₂ r u' l ∧ u = a :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_and_left {r : α → β → Prop} {p : α → Prop} : ∀l u, forall₂ (λa b, p a ∧ r a b) l u ↔ (∀a∈l, p a) ∧ forall₂ r l u | [] u := by simp only [forall₂_nil_left_iff, forall_prop_of_false (not_mem_nil _), imp_true_iff, true_and] | (a::l) u := by simp only [forall₂_and_left l, forall₂_cons_left_iff, forall_mem_cons, and_assoc, and_comm, and.left_comm, exists_and_distrib_left.symm] @[simp] lemma forall₂_map_left_iff {f : γ → α} : ∀{l u}, forall₂ r (map f l) u ↔ forall₂ (λc b, r (f c) b) l u | [] _ := by simp only [map, forall₂_nil_left_iff] | (a::l) _ := by simp only [map, forall₂_cons_left_iff, forall₂_map_left_iff] @[simp] lemma forall₂_map_right_iff {f : γ → β} : ∀{l u}, forall₂ r l (map f u) ↔ forall₂ (λa c, r a (f c)) l u | _ [] := by simp only [map, forall₂_nil_right_iff] | _ (b::u) := by simp only [map, forall₂_cons_right_iff, forall₂_map_right_iff] lemma left_unique_forall₂ (hr : left_unique r) : left_unique (forall₂ r) | a₀ nil a₁ forall₂.nil forall₂.nil := rfl | (a₀::l₀) (b::l) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ left_unique_forall₂ h₀ h₁ ▸ rfl lemma right_unique_forall₂ (hr : right_unique r) : right_unique (forall₂ r) | nil a₀ a₁ forall₂.nil forall₂.nil := rfl | (b::l) (a₀::l₀) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ right_unique_forall₂ h₀ h₁ ▸ rfl lemma bi_unique_forall₂ (hr : bi_unique r) : bi_unique (forall₂ r) := ⟨assume a b c, left_unique_forall₂ hr.1, assume a b c, right_unique_forall₂ hr.2⟩ theorem forall₂_length_eq {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → length l₁ = length l₂ | _ _ forall₂.nil := rfl | _ _ (forall₂.cons h₁ h₂) := congr_arg succ (forall₂_length_eq h₂) theorem forall₂_zip {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b | _ _ (forall₂.cons h₁ h₂) x y (or.inl rfl) := h₁ | _ _ (forall₂.cons h₁ h₂) x y (or.inr h₃) := forall₂_zip h₂ h₃ theorem forall₂_iff_zip {R : α → β → Prop} {l₁ l₂} : forall₂ R l₁ l₂ ↔ length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b := ⟨λ h, ⟨forall₂_length_eq h, @forall₂_zip _ _ _ _ _ h⟩, λ h, begin cases h with h₁ h₂, induction l₁ with a l₁ IH generalizing l₂, { cases length_eq_zero.1 h₁.symm, constructor }, { cases l₂ with b l₂; injection h₁ with h₁, exact forall₂.cons (h₂ $ or.inl rfl) (IH h₁ $ λ a b h, h₂ $ or.inr h) } end⟩ theorem forall₂_take {R : α → β → Prop} : ∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (take n l₁) (take n l₂) | 0 _ _ _ := by simp only [forall₂.nil, take] | (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, take] | (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_take n] theorem forall₂_drop {R : α → β → Prop} : ∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (drop n l₁) (drop n l₂) | 0 _ _ h := by simp only [drop, h] | (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, drop] | (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_drop n] theorem forall₂_take_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.take (length l₁) l) l₁ := have h': forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂)), from forall₂_take (length l₁) h, by rwa [take_left] at h' theorem forall₂_drop_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.drop (length l₁) l) l₂ := have h': forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂)), from forall₂_drop (length l₁) h, by rwa [drop_left] at h' lemma rel_mem (hr : bi_unique r) : (r ⇒ forall₂ r ⇒ iff) (∈) (∈) | a b h [] [] forall₂.nil := by simp only [not_mem_nil] | a b h (a'::as) (b'::bs) (forall₂.cons h₁ h₂) := rel_or (rel_eq hr h h₁) (rel_mem h h₂) lemma rel_map : ((r ⇒ p) ⇒ forall₂ r ⇒ forall₂ p) map map | f g h [] [] forall₂.nil := forall₂.nil | f g h (a::as) (b::bs) (forall₂.cons h₁ h₂) := forall₂.cons (h h₁) (rel_map @h h₂) lemma rel_append : (forall₂ r ⇒ forall₂ r ⇒ forall₂ r) append append | [] [] h l₁ l₂ hl := hl | (a::as) (b::bs) (forall₂.cons h₁ h₂) l₁ l₂ hl := forall₂.cons h₁ (rel_append h₂ hl) lemma rel_join : (forall₂ (forall₂ r) ⇒ forall₂ r) join join | [] [] forall₂.nil := forall₂.nil | (a::as) (b::bs) (forall₂.cons h₁ h₂) := rel_append h₁ (rel_join h₂) lemma rel_bind : (forall₂ r ⇒ (r ⇒ forall₂ p) ⇒ forall₂ p) list.bind list.bind := assume a b h₁ f g h₂, rel_join (rel_map @h₂ h₁) lemma rel_foldl : ((p ⇒ r ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldl foldl | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := rel_foldl @hfg (hfg hxy hab) hs lemma rel_foldr : ((r ⇒ p ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldr foldr | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := hfg hab (rel_foldr @hfg hxy hs) lemma rel_filter {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q] (hpq : (r ⇒ (↔)) p q) : (forall₂ r ⇒ forall₂ r) (filter p) (filter q) | _ _ forall₂.nil := forall₂.nil | (a::as) (b::bs) (forall₂.cons h₁ h₂) := begin by_cases p a, { have : q b, { rwa [← hpq h₁] }, simp only [filter_cons_of_pos _ h, filter_cons_of_pos _ this, forall₂_cons, h₁, rel_filter h₂, and_true], }, { have : ¬ q b, { rwa [← hpq h₁] }, simp only [filter_cons_of_neg _ h, filter_cons_of_neg _ this, rel_filter h₂], }, end theorem filter_map_cons (f : α → option β) (a : α) (l : list α) : filter_map f (a :: l) = option.cases_on (f a) (filter_map f l) (λb, b :: filter_map f l) := begin generalize eq : f a = b, cases b, { rw filter_map_cons_none _ _ eq }, { rw filter_map_cons_some _ _ _ eq }, end lemma rel_filter_map : ((r ⇒ option.rel p) ⇒ forall₂ r ⇒ forall₂ p) filter_map filter_map | f g hfg _ _ forall₂.nil := forall₂.nil | f g hfg (a::as) (b::bs) (forall₂.cons h₁ h₂) := by rw [filter_map_cons, filter_map_cons]; from match f a, g b, hfg h₁ with | _, _, option.rel.none := rel_filter_map @hfg h₂ | _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂) end @[to_additive] lemma rel_prod [monoid α] [monoid β] (h : r 1 1) (hf : (r ⇒ r ⇒ r) (*) (*)) : (forall₂ r ⇒ r) prod prod := rel_foldl hf h end list
af357efdf8346075db996b41ca8a8a5917aa83fa
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/data/list/zip.lean
c739b575ba971a55f43120d7e6ffc4b301364a64
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
11,373
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.basic universes u v w z variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type z} open nat namespace list /- zip & unzip -/ @[simp] theorem zip_with_cons_cons (f : α → β → γ) (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip_with f (a :: l₁) (b :: l₂) = f a b :: zip_with f l₁ l₂ := rfl @[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl @[simp] theorem zip_with_nil_left (f : α → β → γ) (l) : zip_with f [] l = [] := rfl @[simp] theorem zip_with_nil_right (f : α → β → γ) (l) : zip_with f l [] = [] := by cases l; refl @[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl @[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] := zip_with_nil_right _ l @[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β), (zip l₁ l₂).map prod.swap = zip l₂ l₁ | [] l₂ := (zip_nil_right _).symm | l₁ [] := by rw zip_nil_right; refl | (a::l₁) (b::l₂) := by simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, prod.swap_prod_mk]; split; refl @[simp] theorem length_zip_with (f : α → β → γ) : ∀ (l₁ : list α) (l₂ : list β), length (zip_with f l₁ l₂) = min (length l₁) (length l₂) | [] l₂ := rfl | l₁ [] := by simp only [length, min_zero, zip_with_nil_right] | (a::l₁) (b::l₂) := by by simp [length, zip_cons_cons, length_zip_with l₁ l₂, min_add_add_right] @[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β), length (zip l₁ l₂) = min (length l₁) (length l₂) := length_zip_with _ lemma lt_length_left_of_zip_with {f : α → β → γ} {i : ℕ} {l : list α} {l' : list β} (h : i < (zip_with f l l').length) : i < l.length := by { rw [length_zip_with, lt_min_iff] at h, exact h.left } lemma lt_length_right_of_zip_with {f : α → β → γ} {i : ℕ} {l : list α} {l' : list β} (h : i < (zip_with f l l').length) : i < l'.length := by { rw [length_zip_with, lt_min_iff] at h, exact h.right } lemma lt_length_left_of_zip {i : ℕ} {l : list α} {l' : list β} (h : i < (zip l l').length) : i < l.length := lt_length_left_of_zip_with h lemma lt_length_right_of_zip {i : ℕ} {l : list α} {l' : list β} (h : i < (zip l l').length) : i < l'.length := lt_length_right_of_zip_with h theorem zip_append : ∀ {l₁ r₁ : list α} {l₂ r₂ : list β} (h : length l₁ = length l₂), zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂ | [] r₁ l₂ r₂ h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl | l₁ r₁ [] r₂ h := by simp only [eq_nil_of_length_eq_zero h]; refl | (a::l₁) r₁ (b::l₂) r₂ h := by simp only [cons_append, zip_cons_cons, zip_append (succ.inj h)]; split; refl theorem zip_map (f : α → γ) (g : β → δ) : ∀ (l₁ : list α) (l₂ : list β), zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (prod.map f g) | [] l₂ := rfl | l₁ [] := by simp only [map, zip_nil_right] | (a::l₁) (b::l₂) := by simp only [map, zip_cons_cons, zip_map l₁ l₂, prod.map]; split; refl theorem zip_map_left (f : α → γ) (l₁ : list α) (l₂ : list β) : zip (l₁.map f) l₂ = (zip l₁ l₂).map (prod.map f id) := by rw [← zip_map, map_id] theorem zip_map_right (f : β → γ) (l₁ : list α) (l₂ : list β) : zip l₁ (l₂.map f) = (zip l₁ l₂).map (prod.map id f) := by rw [← zip_map, map_id] @[simp] lemma zip_with_map {μ} (f : γ → δ → μ) (g : α → γ) (h : β → δ) (as : list α) (bs : list β) : zip_with f (as.map g) (bs.map h) = zip_with (λ a b, f (g a) (h b)) as bs := begin induction as generalizing bs, { simp }, { cases bs; simp * } end lemma zip_with_map_left (f : α → β → γ) (g : δ → α) (l : list δ) (l' : list β) : zip_with f (l.map g) l' = zip_with (f ∘ g) l l' := by { convert (zip_with_map f g id l l'), exact eq.symm (list.map_id _) } lemma zip_with_map_right (f : α → β → γ) (l : list α) (g : δ → β) (l' : list δ) : zip_with f l (l'.map g) = zip_with (λ x, f x ∘ g) l l' := by { convert (list.zip_with_map f id g l l'), exact eq.symm (list.map_id _) } theorem zip_map' (f : α → β) (g : α → γ) : ∀ (l : list α), zip (l.map f) (l.map g) = l.map (λ a, (f a, g a)) | [] := rfl | (a::l) := by simp only [map, zip_cons_cons, zip_map' l]; split; refl theorem mem_zip {a b} : ∀ {l₁ : list α} {l₂ : list β}, (a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂ | (_::l₁) (_::l₂) (or.inl rfl) := ⟨or.inl rfl, or.inl rfl⟩ | (a'::l₁) (b'::l₂) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h] theorem map_fst_zip : ∀ (l₁ : list α) (l₂ : list β), l₁.length ≤ l₂.length → map prod.fst (zip l₁ l₂) = l₁ | [] bs _ := rfl | (a :: as) (b :: bs) h := by { simp at h, simp! * } | (a :: as) [] h := by { simp at h, contradiction } theorem map_snd_zip : ∀ (l₁ : list α) (l₂ : list β), l₂.length ≤ l₁.length → map prod.snd (zip l₁ l₂) = l₂ | _ [] _ := by { rw zip_nil_right, refl } | [] (b :: bs) h := by { simp at h, contradiction } | (a :: as) (b :: bs) h := by { simp at h, simp! * } @[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl @[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) : unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) := by rw unzip; cases unzip l; refl theorem unzip_eq_map : ∀ (l : list (α × β)), unzip l = (l.map prod.fst, l.map prod.snd) | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, map_cons, unzip_eq_map l] theorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst := by simp only [unzip_eq_map] theorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd := by simp only [unzip_eq_map] theorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap := by simp only [unzip_eq_map, map_map]; split; refl theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, zip_cons_cons, zip_unzip l]; split; refl theorem unzip_zip_left : ∀ {l₁ : list α} {l₂ : list β}, length l₁ ≤ length l₂ → (unzip (zip l₁ l₂)).1 = l₁ | [] l₂ h := rfl | l₁ [] h := by rw eq_nil_of_length_eq_zero (eq_zero_of_le_zero h); refl | (a::l₁) (b::l₂) h := by simp only [zip_cons_cons, unzip_cons, unzip_zip_left (le_of_succ_le_succ h)]; split; refl theorem unzip_zip_right {l₁ : list α} {l₂ : list β} (h : length l₂ ≤ length l₁) : (unzip (zip l₁ l₂)).2 = l₂ := by rw [← zip_swap, unzip_swap]; exact unzip_zip_left h theorem unzip_zip {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂) : unzip (zip l₁ l₂) = (l₁, l₂) := by rw [← @prod.mk.eta _ _ (unzip (zip l₁ l₂)), unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)] lemma zip_of_prod {l : list α} {l' : list β} {lp : list (α × β)} (hl : lp.map prod.fst = l) (hr : lp.map prod.snd = l') : lp = l.zip l' := by rw [←hl, ←hr, ←zip_unzip lp, ←unzip_left, ←unzip_right, zip_unzip, zip_unzip] lemma map_prod_left_eq_zip {l : list α} (f : α → β) : l.map (λ x, (x, f x)) = l.zip (l.map f) := by { rw ←zip_map', congr, exact map_id _ } lemma map_prod_right_eq_zip {l : list α} (f : α → β) : l.map (λ x, (f x, x)) = (l.map f).zip l := by { rw ←zip_map', congr, exact map_id _ } @[simp] theorem length_revzip (l : list α) : length (revzip l) = length l := by simp only [revzip, length_zip, length_reverse, min_self] @[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) := unzip_zip (length_reverse l).symm @[simp] theorem revzip_map_fst (l : list α) : (revzip l).map prod.fst = l := by rw [← unzip_left, unzip_revzip] @[simp] theorem revzip_map_snd (l : list α) : (revzip l).map prod.snd = l.reverse := by rw [← unzip_right, unzip_revzip] theorem reverse_revzip (l : list α) : reverse l.revzip = revzip l.reverse := by rw [← zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip] theorem revzip_swap (l : list α) : (revzip l).map prod.swap = revzip l.reverse := by simp [revzip] lemma nth_zip_with {α β γ} (f : α → β → γ) (l₁ : list α) (l₂ : list β) (i : ℕ) : (zip_with f l₁ l₂).nth i = f <$> l₁.nth i <*> l₂.nth i := begin induction l₁ generalizing l₂ i, { simp [zip_with, (<*>)] }, { cases l₂; simp only [zip_with, has_seq.seq, functor.map, nth, option.map_none'], { cases ((l₁_hd :: l₁_tl).nth i); refl }, { cases i; simp only [option.map_some', nth, option.some_bind', *], refl } }, end lemma nth_zip_with_eq_some {α β γ} (f : α → β → γ) (l₁ : list α) (l₂ : list β) (z : γ) (i : ℕ) : (zip_with f l₁ l₂).nth i = some z ↔ ∃ x y, l₁.nth i = some x ∧ l₂.nth i = some y ∧ f x y = z := begin induction l₁ generalizing l₂ i, { simp [zip_with] }, { cases l₂; simp only [zip_with, nth, exists_false, and_false, false_and], cases i; simp *, }, end lemma nth_zip_eq_some (l₁ : list α) (l₂ : list β) (z : α × β) (i : ℕ) : (zip l₁ l₂).nth i = some z ↔ l₁.nth i = some z.1 ∧ l₂.nth i = some z.2 := begin cases z, rw [zip, nth_zip_with_eq_some], split, { rintro ⟨x, y, h₀, h₁, h₂⟩, cc }, { rintro ⟨h₀, h₁⟩, exact ⟨_,_,h₀,h₁,rfl⟩ } end @[simp] lemma nth_le_zip_with {f : α → β → γ} {l : list α} {l' : list β} {i : ℕ} {h : i < (zip_with f l l').length} : (zip_with f l l').nth_le i h = f (l.nth_le i (lt_length_left_of_zip_with h)) (l'.nth_le i (lt_length_right_of_zip_with h)) := begin rw [←option.some_inj, ←nth_le_nth, nth_zip_with_eq_some], refine ⟨l.nth_le i (lt_length_left_of_zip_with h), l'.nth_le i (lt_length_right_of_zip_with h), nth_le_nth _, _⟩, simp only [←nth_le_nth, eq_self_iff_true, and_self] end @[simp] lemma nth_le_zip {l : list α} {l' : list β} {i : ℕ} {h : i < (zip l l').length} : (zip l l').nth_le i h = (l.nth_le i (lt_length_left_of_zip h), l'.nth_le i (lt_length_right_of_zip h)) := nth_le_zip_with lemma mem_zip_inits_tails {l : list α} {init tail : list α} : (init, tail) ∈ zip l.inits l.tails ↔ init ++ tail = l := begin induction l generalizing init tail; simp_rw [tails, inits, zip_cons_cons], { simp }, { split; rw [mem_cons_iff, zip_map_left, mem_map, prod.exists], { rintros (⟨rfl, rfl⟩ | ⟨_, _, h, rfl, rfl⟩), { simp }, { simp [l_ih.mp h], }, }, { cases init, { simp }, { intro h, right, use [init_tl, tail], simp * at *, }, }, }, end lemma map_uncurry_zip_eq_zip_with (f : α → β → γ) (l : list α) (l' : list β) : map (function.uncurry f) (l.zip l') = zip_with f l l' := begin induction l with hd tl hl generalizing l', { simp }, { cases l' with hd' tl', { simp }, { simp [hl] } } end end list
5934883327a39f6300dbbd26986b3d773a131833
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/hott/function.hlean
2ac85a9e4ae4ce7739cfdc78abcb85884d7e8ece
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,035
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about embeddings and surjections -/ import hit.trunc types.equiv cubical.square open equiv sigma sigma.ops eq trunc is_trunc pi is_equiv fiber prod variables {A B : Type} (f : A → B) {b : B} definition is_embedding [class] (f : A → B) := Π(a a' : A), is_equiv (ap f : a = a' → f a = f a') definition is_surjective [class] (f : A → B) := Π(b : B), ∥ fiber f b ∥ definition is_split_surjective [class] (f : A → B) := Π(b : B), fiber f b structure is_retraction [class] (f : A → B) := (sect : B → A) (right_inverse : Π(b : B), f (sect b) = b) structure is_section [class] (f : A → B) := (retr : B → A) (left_inverse : Π(a : A), retr (f a) = a) definition is_weakly_constant [class] (f : A → B) := Π(a a' : A), f a = f a' structure is_constant [class] (f : A → B) := (pt : B) (eq : Π(a : A), f a = pt) structure is_conditionally_constant [class] (f : A → B) := (g : ∥A∥ → B) (eq : Π(a : A), f a = g (tr a)) -- structure is_retract (g : A → B) := -- (X Y : Type) -- (f : X → Y) -- (s : A → X) -- (r : X → A) -- (s' : B → Y) -- (r' : Y → B) -- (R : Πa, r (s a) = a) -- (R' : Πb, r' (s' b) = b) -- (L : Πa, f (s a) = s' (g a)) -- (K : Πx, g (r x) = r' (f x)) -- (H : Πa, square (K (s a)) (R' (g a))⁻¹ (ap g (R a)) (ap r' (L a))) namespace function abbreviation sect [unfold 4] := @is_retraction.sect abbreviation right_inverse [unfold 4] := @is_retraction.right_inverse abbreviation retr [unfold 4] := @is_section.retr abbreviation left_inverse [unfold 4] := @is_section.left_inverse definition is_equiv_ap_of_embedding [instance] [H : is_embedding f] (a a' : A) : is_equiv (ap f : a = a' → f a = f a') := H a a' definition ap_inv_idp {a : A} {H : is_equiv (ap f : a = a → f a = f a)} : (ap f)⁻¹ᶠ idp = idp :> a = a := !left_inv variable {f} definition is_injective_of_is_embedding [reducible] [H : is_embedding f] {a a' : A} : f a = f a' → a = a' := (ap f)⁻¹ definition is_embedding_of_is_injective [HA : is_hset A] [HB : is_hset B] (H : Π(a a' : A), f a = f a' → a = a') : is_embedding f := begin intro a a', fapply adjointify, {exact (H a a')}, {intro p, apply is_hset.elim}, {intro p, apply is_hset.elim} end variable (f) definition is_hprop_is_embedding [instance] : is_hprop (is_embedding f) := by unfold is_embedding; exact _ definition is_embedding_equiv_is_injective [HA : is_hset A] [HB : is_hset B] : is_embedding f ≃ (Π(a a' : A), f a = f a' → a = a') := begin fapply equiv.MK, { apply @is_injective_of_is_embedding}, { apply is_embedding_of_is_injective}, { intro H, apply is_hprop.elim}, { intro H, apply is_hprop.elim, } end definition is_hprop_fiber_of_is_embedding [H : is_embedding f] (b : B) : is_hprop (fiber f b) := begin apply is_hprop.mk, intro v w, induction v with a p, induction w with a' q, induction q, fapply fiber_eq, { esimp, apply is_injective_of_is_embedding p}, { esimp [is_injective_of_is_embedding], symmetry, apply right_inv} end definition is_hprop_fun_of_is_embedding [H : is_embedding f] : is_trunc_fun -1 f := is_hprop_fiber_of_is_embedding f definition is_embedding_of_is_hprop_fun [constructor] [H : is_trunc_fun -1 f] : is_embedding f := begin intro a a', fapply adjointify, { intro p, exact ap point (@is_hprop.elim (fiber f (f a')) _ (fiber.mk a p) (fiber.mk a' idp))}, { intro p, rewrite [-ap_compose], esimp, apply ap_con_eq (@point_eq _ _ f (f a'))}, { intro p, induction p, apply ap (ap point), apply is_hprop_elim_self} end variable {f} definition is_surjective_rec_on {P : Type} (H : is_surjective f) (b : B) [Pt : is_hprop P] (IH : fiber f b → P) : P := trunc.rec_on (H b) IH variable (f) definition is_surjective_of_is_split_surjective [instance] [H : is_split_surjective f] : is_surjective f := λb, tr (H b) definition is_hprop_is_surjective [instance] : is_hprop (is_surjective f) := by unfold is_surjective; exact _ definition is_weakly_constant_ap [instance] [H : is_weakly_constant f] (a a' : A) : is_weakly_constant (ap f : a = a' → f a = f a') := take p q : a = a', have Π{b c : A} {r : b = c}, (H a b)⁻¹ ⬝ H a c = ap f r, from (λb c r, eq.rec_on r !con.left_inv), this⁻¹ ⬝ this definition is_constant_ap [unfold 4] [instance] [H : is_constant f] (a a' : A) : is_constant (ap f : a = a' → f a = f a') := begin induction H with b q, fapply is_constant.mk, { exact q a ⬝ (q a')⁻¹}, { intro p, induction p, exact !con.right_inv⁻¹} end definition is_contr_is_retraction [instance] [H : is_equiv f] : is_contr (is_retraction f) := begin have H2 : (Σ(g : B → A), Πb, f (g b) = b) ≃ is_retraction f, begin fapply equiv.MK, {intro x, induction x with g p, constructor, exact p}, {intro h, induction h, apply sigma.mk, assumption}, {intro h, induction h, reflexivity}, {intro x, induction x, reflexivity}, end, apply is_trunc_equiv_closed, exact H2, apply is_equiv.is_contr_right_inverse end definition is_contr_is_section [instance] [H : is_equiv f] : is_contr (is_section f) := begin have H2 : (Σ(g : B → A), Πa, g (f a) = a) ≃ is_section f, begin fapply equiv.MK, {intro x, induction x with g p, constructor, exact p}, {intro h, induction h, apply sigma.mk, assumption}, {intro h, induction h, reflexivity}, {intro x, induction x, reflexivity}, end, apply is_trunc_equiv_closed, exact H2, fapply is_trunc_equiv_closed, {apply sigma_equiv_sigma_id, intro g, apply eq_equiv_homotopy}, fapply is_trunc_equiv_closed, {apply fiber.sigma_char}, fapply is_contr_fiber_of_is_equiv, exact to_is_equiv (arrow_equiv_arrow_left_rev A (equiv.mk f H)), end definition is_embedding_of_is_equiv [instance] [H : is_equiv f] : is_embedding f := λa a', _ definition is_equiv_of_is_surjective_of_is_embedding [H : is_embedding f] [H' : is_surjective f] : is_equiv f := @is_equiv_of_is_contr_fun _ _ _ (λb, is_surjective_rec_on H' b (λa, is_contr.mk a (λa', fiber_eq ((ap f)⁻¹ ((point_eq a) ⬝ (point_eq a')⁻¹)) (by rewrite (right_inv (ap f)); rewrite inv_con_cancel_right)))) definition is_split_surjective_of_is_retraction [H : is_retraction f] : is_split_surjective f := λb, fiber.mk (sect f b) (right_inverse f b) definition is_constant_compose_point [constructor] [instance] (b : B) : is_constant (f ∘ point : fiber f b → B) := is_constant.mk b (λv, by induction v with a p;exact p) definition is_embedding_of_is_hprop_fiber [H : Π(b : B), is_hprop (fiber f b)] : is_embedding f := begin intro a a', fapply adjointify, { intro p, exact ap point (is_hprop.elim (fiber.mk a p) (fiber.mk a' idp))}, { exact abstract begin intro p, rewrite [-ap_compose], apply @is_constant.eq _ _ _ (is_constant_ap (f ∘ point) (fiber.mk a p) (fiber.mk a' idp)) end end }, { intro p, induction p, rewrite [▸*,is_hprop_elim_self]}, end -- definition is_embedding_of_is_section_inv' [H : is_section f] {a : A} {b : B} (p : f a = b) : -- a = retr f b := -- (left_inverse f a)⁻¹ ⬝ ap (retr f) p -- definition is_embedding_of_is_section_inv [H : is_section f] {a a' : A} (p : f a = f a') : -- a = a' := -- is_embedding_of_is_section_inv' f p ⬝ left_inverse f a' -- definition is_embedding_of_is_section [constructor] [instance] [H : is_section f] -- : is_embedding f := -- begin -- intro a a', -- fapply adjointify, -- { exact is_embedding_of_is_section_inv f}, -- { exact abstract begin -- assert H2 : Π {b : B} (p : f a = b), ap f (is_embedding_of_is_section_inv' f p) = p ⬝ _, -- { } -- -- intro p, rewrite [+ap_con,-ap_compose], -- -- check_expr natural_square (left_inverse f), -- -- induction H with g q, esimp, -- end end }, -- { intro p, induction p, esimp, apply con.left_inv}, -- end definition is_retraction_of_is_equiv [instance] [H : is_equiv f] : is_retraction f := is_retraction.mk f⁻¹ (right_inv f) definition is_section_of_is_equiv [instance] [H : is_equiv f] : is_section f := is_section.mk f⁻¹ (left_inv f) definition is_equiv_of_is_section_of_is_retraction [H1 : is_retraction f] [H2 : is_section f] : is_equiv f := let g := sect f in let h := retr f in adjointify f g (right_inverse f) (λa, calc g (f a) = h (f (g (f a))) : left_inverse ... = h (f a) : right_inverse f ... = a : left_inverse) section local attribute is_equiv_of_is_section_of_is_retraction [instance] [priority 10000] local attribute trunctype.struct [instance] [priority 1] -- remove after #842 is closed variable (f) definition is_hprop_is_retraction_prod_is_section : is_hprop (is_retraction f × is_section f) := begin apply is_hprop_of_imp_is_contr, intro H, induction H with H1 H2, exact _, end end definition is_retraction_trunc_functor [instance] (r : A → B) [H : is_retraction r] (n : trunc_index) : is_retraction (trunc_functor n r) := is_retraction.mk (trunc_functor n (sect r)) (λb, ((trunc_functor_compose n (sect r) r) b)⁻¹ ⬝ trunc_homotopy n (right_inverse r) b ⬝ trunc_functor_id B n b) -- Lemma 3.11.7 definition is_contr_retract (r : A → B) [H : is_retraction r] : is_contr A → is_contr B := begin intro CA, apply is_contr.mk (r (center A)), intro b, exact ap r (center_eq (is_retraction.sect r b)) ⬝ (is_retraction.right_inverse r b) end local attribute is_hprop_is_retraction_prod_is_section [instance] definition is_retraction_prod_is_section_equiv_is_equiv [constructor] : (is_retraction f × is_section f) ≃ is_equiv f := begin apply equiv_of_is_hprop, intro H, induction H, apply is_equiv_of_is_section_of_is_retraction, intro H, split, repeat exact _ end definition is_retraction_equiv_is_split_surjective : is_retraction f ≃ is_split_surjective f := begin fapply equiv.MK, { intro H, induction H with g p, intro b, constructor, exact p b}, { intro H, constructor, intro b, exact point_eq (H b)}, { intro H, esimp, apply eq_of_homotopy, intro b, esimp, induction H b, reflexivity}, { intro H, induction H with g p, reflexivity}, end /- The definitions is_surjective_of_is_equiv is_equiv_equiv_is_embedding_times_is_surjective are in types.trunc -/ end function
e54645d14b1d0bdd525c0edf94b9796a939e1d2c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Build/Targets.lean
ceef5fa2bbca68cb2e5354668487d35ec0cefd11
[ "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,792
lean
/- Copyright (c) 2023 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lake.Build.Monad /-! # Build Target Fetching Utilities for fetching package, library, module, and executable targets and facets. -/ namespace Lake /-! ## Package Facets & Targets -/ /-- Fetch the build job of the specified package target. -/ def Package.fetchTargetJob (self : Package) (target : Name) : IndexBuildM (BuildJob Unit) := do let some config := self.findTargetConfig? target | error s!"package '{self.name}' has no target '{target}'" return config.getJob (← fetch <| self.target target) /-- Fetch the build result of a target. -/ protected def TargetDecl.fetch (self : TargetDecl) [FamilyOut CustomData (self.pkg, self.name) α] : IndexBuildM α := do let some pkg ← findPackage? self.pkg | error s!"package '{self.pkg}' of target '{self.name}' does not exist in workspace" fetch <| pkg.target self.name /-- Fetch the build job of the target. -/ def TargetDecl.fetchJob (self : TargetDecl) : IndexBuildM (BuildJob Unit) := do let some pkg ← findPackage? self.pkg | error s!"package '{self.pkg}' of target '{self.name}' does not exist in workspace" return self.config.getJob (← fetch <| pkg.target self.name) /-- Fetch the build result of a package facet. -/ @[inline] protected def PackageFacetDecl.fetch (pkg : Package) (self : PackageFacetDecl) [FamilyOut PackageData self.name α] : IndexBuildM α := do fetch <| pkg.facet self.name /-- Fetch the build job of a package facet. -/ def PackageFacetConfig.fetchJob (pkg : Package) (self : PackageFacetConfig name) : IndexBuildM (BuildJob Unit) := do let some getJob := self.getJob? | error s!"package facet '{name}' has no associated build job" return getJob <| ← fetch <| pkg.facet self.name /-- Fetch the build job of a library facet. -/ def Package.fetchFacetJob (name : Name) (self : Package) : IndexBuildM (BuildJob Unit) := do let some config := (← getWorkspace).packageFacetConfigs.find? name | error s!"package facet '{name}' does not exist in workspace" inline <| config.fetchJob self /-! ## Module Facets -/ /-- Fetch the build result of a module facet. -/ @[inline] protected def ModuleFacetDecl.fetch (mod : Module) (self : ModuleFacetDecl) [FamilyOut ModuleData self.name α] : IndexBuildM α := do fetch <| mod.facet self.name /-- Fetch the build job of a module facet. -/ def ModuleFacetConfig.fetchJob (mod : Module) (self : ModuleFacetConfig name) : IndexBuildM (BuildJob Unit) := do let some getJob := self.getJob? | error "module facet '{self.name}' has no associated build job" return getJob <| ← fetch <| mod.facet self.name /-- Fetch the build job of a module facet. -/ def Module.fetchFacetJob (name : Name) (self : Module) : IndexBuildM (BuildJob Unit) := do let some config := (← getWorkspace).moduleFacetConfigs.find? name | error "library facet '{name}' does not exist in workspace" inline <| config.fetchJob self /-! ## Lean Library Facets -/ /-- Get the Lean library in the workspace with the configuration's name. -/ @[inline] def LeanLibConfig.get (self : LeanLibConfig) [Monad m] [MonadError m] [MonadLake m] : m LeanLib := do let some lib ← findLeanLib? self.name | error "Lean library '{self.name}' does not exist in the workspace" return lib /-- Fetch the build result of a library facet. -/ @[inline] protected def LibraryFacetDecl.fetch (lib : LeanLib) (self : LibraryFacetDecl) [FamilyOut LibraryData self.name α] : IndexBuildM α := do fetch <| lib.facet self.name /-- Fetch the build job of a library facet. -/ def LibraryFacetConfig.fetchJob (lib : LeanLib) (self : LibraryFacetConfig name) : IndexBuildM (BuildJob Unit) := do let some getJob := self.getJob? | error "library facet '{self.name}' has no associated build job" return getJob <| ← fetch <| lib.facet self.name /-- Fetch the build job of a library facet. -/ def LeanLib.fetchFacetJob (name : Name) (self : LeanLib) : IndexBuildM (BuildJob Unit) := do let some config := (← getWorkspace).libraryFacetConfigs.find? name | error "library facet '{name}' does not exist in workspace" inline <| config.fetchJob self /-! ## Lean Executable Target -/ /-- Get the Lean executable in the workspace with the configuration's name. -/ @[inline] def LeanExeConfig.get (self : LeanExeConfig) [Monad m] [MonadError m] [MonadLake m] : m LeanExe := do let some exe ← findLeanExe? self.name | error "Lean executable '{self.name}' does not exist in the workspace" return exe /-- Fetch the build of the Lean executable. -/ @[inline] def LeanExeConfig.fetch (self : LeanExeConfig) : IndexBuildM (BuildJob FilePath) := do (← self.get).exe.fetch
8ff735836c60e9303146af43a927202494e70026
367134ba5a65885e863bdc4507601606690974c1
/src/linear_algebra/invariant_basis_number.lean
b7a9c01f8db022cd969c0fb228e6746db304c8d2
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
5,601
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import linear_algebra.finite_dimensional import ring_theory.ideal.basic /-! # Invariant basis number property We say that a ring `R` satisfies the invariant basis number property if there is a well-defined notion of the rank of a finitely generated free (left) `R`-module. Since a finitely generated free module with a basis consisting of `n` elements is linearly equivalent to `fin n → R`, it is sufficient that `(fin n → R) ≃ₗ[R] (fin m → R)` implies `n = m`. ## Main definitions `invariant_basis_number R` is a type class stating that `R` has the invariant basis number property. ## Main results We show that every nontrivial commutative ring has the invariant basis number property. ## Future work So far, there is no API at all for the `invariant_basis_number` class. There are several natural ways to formulate that a module `M` is finitely generated and free, for example `M ≃ₗ[R] (fin n → R)`, `M ≃ₗ[R] (ι → R)`, where `ι` is a fintype, or prividing a basis indexed by a finite type. There should be lemmas applying the invariant basis number property to each situation. The finite version of the invariant basis number property implies the infinite analogue, i.e., that `(ι →₀ R) ≃ₗ[R] (ι' →₀ R)` implies that `cardinal.mk ι = cardinal.mk ι'`. This fact (and its variants) should be formalized. ## References * https://en.wikipedia.org/wiki/Invariant_basis_number ## Tags free module, rank, invariant basis number, IBN -/ noncomputable theory open_locale classical big_operators universes u v w section variables (R : Type u) [ring R] /-- We say that `R` has the invariant basis number property if `(fin n → R) ≃ₗ[R] (fin m → R)` implies `n = m`. This gives rise to a well-defined notion of rank of a finitely generated free module. -/ class invariant_basis_number : Prop := (eq_of_fin_equiv : ∀ {n m : ℕ}, ((fin n → R) ≃ₗ[R] (fin m → R)) → n = m) end section variables (R : Type u) [ring R] [invariant_basis_number R] lemma eq_of_fin_equiv {n m : ℕ} : ((fin n → R) ≃ₗ[R] (fin m → R)) → n = m := invariant_basis_number.eq_of_fin_equiv lemma nontrivial_of_invariant_basis_number : nontrivial R := begin by_contra h, refine zero_ne_one (eq_of_fin_equiv R _), haveI := not_nontrivial_iff_subsingleton.1 h, haveI : subsingleton (fin 1 → R) := ⟨λ a b, funext $ λ x, subsingleton.elim _ _⟩, refine { .. }; { intros, exact 0 } <|> tidy end end section open finite_dimensional /-- A field has invariant basis number. This will be superseded below by the fact that any nonzero commutative ring has invariant basis number. -/ lemma invariant_basis_number_field {K : Type u} [field K] : invariant_basis_number K := ⟨λ n m e, calc n = fintype.card (fin n) : eq.symm $ fintype.card_fin n ... = findim K (fin n → K) : eq.symm $ findim_eq_card_basis (pi.is_basis_fun K (fin n)) ... = findim K (fin m → K) : linear_equiv.findim_eq e ... = fintype.card (fin m) : findim_eq_card_basis (pi.is_basis_fun K (fin m)) ... = m : fintype.card_fin m⟩ end /-! We want to show that nontrivial commutative rings have invariant basis number. The idea is to take a maximal ideal `I` of `R` and use an isomorphism `R^n ≃ R^m` of `R` modules to produce an isomorphism `(R/I)^n ≃ (R/I)^m` of `R/I`-modules, which will imply `n = m` since `R/I` is a field and we know that fields have invariant basis number. We construct the isomorphism in two steps: 1. We construct the ring `R^n/I^n`, show that it is an `R/I`-module and show that there is an isomorphism of `R/I`-modules `R^n/I^n ≃ (R/I)^n`. This isomorphism is called `ideal.pi_quot_equiv` and is located in the file `ring_theory/ideals.lean`. 2. We construct an isomorphism of `R/I`-modules `R^n/I^n ≃ R^m/I^m` using the isomorphism `R^n ≃ R^m`. -/ section variables {R : Type u} [comm_ring R] (I : ideal R) {ι : Type v} [fintype ι] {ι' : Type w} /-- An `R`-linear map `R^n → R^m` induces a function `R^n/I^n → R^m/I^m`. -/ private def induced_map (I : ideal R) (e : (ι → R) →ₗ[R] (ι' → R)) : (I.pi ι).quotient → (I.pi ι').quotient := λ x, quotient.lift_on' x (λ y, ideal.quotient.mk _ (e y)) begin refine λ a b hab, ideal.quotient.eq.2 (λ h, _), rw ←linear_map.map_sub, exact ideal.map_pi _ _ hab e h, end /-- An isomorphism of `R`-modules `R^n ≃ R^m` induces an isomorphism `R/I`-modules `R^n/I^n ≃ R^m/I^m`. -/ private def induced_equiv [fintype ι'] (I : ideal R) (e : (ι → R) ≃ₗ[R] (ι' → R)) : (I.pi ι).quotient ≃ₗ[I.quotient] (I.pi ι').quotient := begin refine { to_fun := induced_map I e, inv_fun := induced_map I e.symm, .. }, all_goals { rintro ⟨a⟩ ⟨b⟩ <|> rintro ⟨a⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr, simp } end end section local attribute [instance] invariant_basis_number_field local attribute [instance, priority 1] ideal.quotient.field /-- Nontrivial commutative rings have the invariant basis number property. -/ @[priority 100] instance invariant_basis_number_of_nontrivial_of_comm_ring {R : Type u} [comm_ring R] [nontrivial R] : invariant_basis_number R := ⟨λ n m e, let ⟨I, hI⟩ := ideal.exists_maximal R in by exactI eq_of_fin_equiv I.quotient ((ideal.pi_quot_equiv _ _).symm.trans ((induced_equiv _ e).trans (ideal.pi_quot_equiv _ _)))⟩ end
76657fd686b4a41ba5e0abd7c28ec30bc4b70694
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/nat/digits.lean
8cb8a404477427b6d2d2eabdd15994bada81a0b7
[ "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
23,231
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Shing Tak Lam, Mario Carneiro -/ import data.int.modeq import data.nat.bits import data.nat.log import data.list.indexes import data.list.palindrome import algebra.parity import tactic.interval_cases import tactic.linarith /-! # Digits of a natural number This provides a basic API for extracting the digits of a natural number in a given base, and reconstructing numbers from their digits. We also prove some divisibility tests based on digits, in particular completing Theorem #85 from https://www.cs.ru.nl/~freek/100/. A basic `norm_digits` tactic is also provided for proving goals of the form `nat.digits a b = l` where `a` and `b` are numerals. -/ namespace nat variables {n : ℕ} /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_0 : ℕ → list ℕ | 0 := [] | (n+1) := [n+1] /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_1 (n : ℕ) : list ℕ := list.repeat 1 n /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux (b : ℕ) (h : 2 ≤ b) : ℕ → list ℕ | 0 := [] | (n+1) := have (n+1)/b < n+1 := nat.div_lt_self (nat.succ_pos _) h, (n+1) % b :: digits_aux ((n+1)/b) @[simp] lemma digits_aux_zero (b : ℕ) (h : 2 ≤ b) : digits_aux b h 0 = [] := by rw digits_aux lemma digits_aux_def (b : ℕ) (h : 2 ≤ b) (n : ℕ) (w : 0 < n) : digits_aux b h n = n % b :: digits_aux b h (n/b) := begin cases n, { cases w, }, { rw [digits_aux], } end /-- `digits b n` gives the digits, in little-endian order, of a natural number `n` in a specified base `b`. In any base, we have `of_digits b L = L.foldr (λ x y, x + b * y) 0`. * For any `2 ≤ b`, we have `l < b` for any `l ∈ digits b n`, and the last digit is not zero. This uniquely specifies the behaviour of `digits b`. * For `b = 1`, we define `digits 1 n = list.repeat 1 n`. * For `b = 0`, we define `digits 0 n = [n]`, except `digits 0 0 = []`. Note this differs from the existing `nat.to_digits` in core, which is used for printing numerals. In particular, `nat.to_digits b 0 = [0]`, while `digits b 0 = []`. -/ def digits : ℕ → ℕ → list ℕ | 0 := digits_aux_0 | 1 := digits_aux_1 | (b+2) := digits_aux (b+2) (by norm_num) @[simp] lemma digits_zero (b : ℕ) : digits b 0 = [] := by rcases b with _|⟨_|⟨_⟩⟩; simp [digits, digits_aux_0, digits_aux_1] @[simp] lemma digits_zero_zero : digits 0 0 = [] := rfl @[simp] lemma digits_zero_succ (n : ℕ) : digits 0 (n.succ) = [n+1] := rfl theorem digits_zero_succ' : ∀ {n : ℕ} (w : 0 < n), digits 0 n = [n] | 0 h := absurd h dec_trivial | (n+1) _ := rfl @[simp] lemma digits_one (n : ℕ) : digits 1 n = list.repeat 1 n := rfl @[simp] lemma digits_one_succ (n : ℕ) : digits 1 (n + 1) = 1 :: digits 1 n := rfl @[simp] lemma digits_add_two_add_one (b n : ℕ) : digits (b+2) (n+1) = (((n+1) % (b+2)) :: digits (b+2) ((n+1) / (b+2))) := by { rw [digits, digits_aux_def], exact succ_pos n } theorem digits_def' : ∀ {b : ℕ} (h : 2 ≤ b) {n : ℕ} (w : 0 < n), digits b n = n % b :: digits b (n/b) | 0 h := absurd h dec_trivial | 1 h := absurd h dec_trivial | (b+2) h := digits_aux_def _ _ @[simp] lemma digits_of_lt (b x : ℕ) (w₁ : 0 < x) (w₂ : x < b) : digits b x = [x] := begin cases b, { cases w₂ }, { cases b, { interval_cases x, }, { cases x, { cases w₁, }, { rw [digits_add_two_add_one, nat.div_eq_of_lt w₂, digits_zero, nat.mod_eq_of_lt w₂] } } } end lemma digits_add (b : ℕ) (h : 2 ≤ b) (x y : ℕ) (w : x < b) (w' : 0 < x ∨ 0 < y) : digits b (x + b * y) = x :: digits b y := begin cases b, { cases h, }, { cases b, { norm_num at h, }, { cases y, { norm_num at w', simp [w, w'], }, dsimp [digits], rw digits_aux_def, { congr, { simp [nat.add_mod, nat.mod_eq_of_lt w], }, { simp [mul_comm (b+2), nat.add_mul_div_right, nat.div_eq_of_lt w], } }, { apply nat.succ_pos, }, }, }, end /-- `of_digits b L` takes a list `L` of natural numbers, and interprets them as a number in semiring, as the little-endian digits in base `b`. -/ -- If we had a function converting a list into a polynomial, -- and appropriate lemmas about that function, -- we could rewrite this in terms of that. def of_digits {α : Type*} [semiring α] (b : α) : list ℕ → α | [] := 0 | (h :: t) := h + b * of_digits t lemma of_digits_eq_foldr {α : Type*} [semiring α] (b : α) (L : list ℕ) : of_digits b L = L.foldr (λ x y, x + b * y) 0 := begin induction L with d L ih, { refl, }, { dsimp [of_digits], rw ih, }, end lemma of_digits_eq_sum_map_with_index_aux (b : ℕ) (l : list ℕ) : ((list.range l.length).zip_with ((λ (i a : ℕ), a * b ^ i) ∘ succ) l).sum = b * ((list.range l.length).zip_with (λ i a, a * b ^ i) l).sum := begin suffices : (list.range l.length).zip_with (((λ (i a : ℕ), a * b ^ i) ∘ succ)) l = (list.range l.length).zip_with (λ i a, b * (a * b ^ i)) l, { simp [this] }, congr, ext, simp [pow_succ], ring end lemma of_digits_eq_sum_map_with_index (b : ℕ) (L : list ℕ): of_digits b L = (L.map_with_index (λ i a, a * b ^ i)).sum := begin rw [list.map_with_index_eq_enum_map, list.enum_eq_zip_range, list.map_uncurry_zip_eq_zip_with, of_digits_eq_foldr], induction L with hd tl hl, { simp }, { simpa [list.range_succ_eq_map, list.zip_with_map_left, of_digits_eq_sum_map_with_index_aux] using or.inl hl } end @[simp] lemma of_digits_singleton {b n : ℕ} : of_digits b [n] = n := by simp [of_digits] @[simp] lemma of_digits_one_cons {α : Type*} [semiring α] (h : ℕ) (L : list ℕ) : of_digits (1 : α) (h :: L) = h + of_digits 1 L := by simp [of_digits] lemma of_digits_append {b : ℕ} {l1 l2 : list ℕ} : of_digits b (l1 ++ l2) = of_digits b l1 + b^(l1.length) * of_digits b l2 := begin induction l1 with hd tl IH, { simp [of_digits] }, { rw [of_digits, list.cons_append, of_digits, IH, list.length_cons, pow_succ'], ring } end @[norm_cast] lemma coe_of_digits (α : Type*) [semiring α] (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : α) = of_digits (b : α) L := begin induction L with d L ih, { simp [of_digits], }, { dsimp [of_digits], push_cast, rw ih, } end @[norm_cast] lemma coe_int_of_digits (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : ℤ) = of_digits (b : ℤ) L := begin induction L with d L ih, { refl, }, { dsimp [of_digits], push_cast } end lemma digits_zero_of_eq_zero {b : ℕ} (h : 1 ≤ b) {L : list ℕ} (w : of_digits b L = 0) : ∀ l ∈ L, l = 0 := begin induction L with d L ih, { intros l m, cases m, }, { intros l m, dsimp [of_digits] at w, rcases m with ⟨rfl⟩, { apply nat.eq_zero_of_add_eq_zero_right w }, { exact ih (mul_right_injective₀ (pos_iff_ne_zero.1 h) (nat.eq_zero_of_add_eq_zero_left w)) _ m, }, } end lemma digits_of_digits (b : ℕ) (h : 2 ≤ b) (L : list ℕ) (w₁ : ∀ l ∈ L, l < b) (w₂ : ∀ (h : L ≠ []), L.last h ≠ 0) : digits b (of_digits b L) = L := begin induction L with d L ih, { dsimp [of_digits], simp }, { dsimp [of_digits], replace w₂ := w₂ (by simp), rw digits_add b h, { rw ih, { intros l m, apply w₁, exact list.mem_cons_of_mem _ m, }, { intro h, { rw [list.last_cons h] at w₂, convert w₂, }}}, { exact w₁ d (list.mem_cons_self _ _) }, { by_cases h' : L = [], { rcases h' with rfl, simp at w₂, left, apply nat.pos_of_ne_zero, exact w₂ }, { right, apply nat.pos_of_ne_zero, contrapose! w₂, apply digits_zero_of_eq_zero _ w₂, { rw list.last_cons h', exact list.last_mem h', }, { exact le_of_lt h, }, }, }, }, end lemma of_digits_digits (b n : ℕ) : of_digits b (digits b n) = n := begin cases b with b, { cases n with n, { refl, }, { change of_digits 0 [n+1] = n+1, dsimp [of_digits], simp, } }, { cases b with b, { induction n with n ih, { refl, }, { simp only [ih, add_comm 1, of_digits_one_cons, nat.cast_id, digits_one_succ], } }, { apply nat.strong_induction_on n _, clear n, intros n h, cases n, { rw digits_zero, refl, }, { simp only [nat.succ_eq_add_one, digits_add_two_add_one], dsimp [of_digits], rw h _ (nat.div_lt_self' n b), rw [nat.mod_add_div], }, }, }, end lemma of_digits_one (L : list ℕ) : of_digits 1 L = L.sum := begin induction L with d L ih, { refl, }, { simp [of_digits, list.sum_cons, ih], } end /-! ### Properties This section contains various lemmas of properties relating to `digits` and `of_digits`. -/ lemma digits_eq_nil_iff_eq_zero {b n : ℕ} : digits b n = [] ↔ n = 0 := begin split, { intro h, have : of_digits b (digits b n) = of_digits b [], by rw h, convert this, rw of_digits_digits }, { rintro rfl, simp } end lemma digits_ne_nil_iff_ne_zero {b n : ℕ} : digits b n ≠ [] ↔ n ≠ 0 := not_congr digits_eq_nil_iff_eq_zero lemma digits_eq_cons_digits_div {b n : ℕ} (h : 2 ≤ b) (w : 0 < n) : digits b n = ((n % b) :: digits b (n / b)) := begin rcases b with _|_|b, { rw [digits_zero_succ' w, nat.mod_zero, nat.div_zero, nat.digits_zero_zero] }, { norm_num at h }, rcases n with _|n, { norm_num at w }, simp, end lemma digits_last {b : ℕ} (m : ℕ) (h : 2 ≤ b) (p q) : (digits b m).last p = (digits b (m/b)).last q := begin by_cases hm : m = 0, { simp [hm], }, simp only [digits_eq_cons_digits_div h (nat.pos_of_ne_zero hm)], rw list.last_cons, end lemma digits.injective (b : ℕ) : function.injective b.digits := function.left_inverse.injective (of_digits_digits b) @[simp] lemma digits_inj_iff {b n m : ℕ} : b.digits n = b.digits m ↔ n = m := (digits.injective b).eq_iff lemma digits_len (b n : ℕ) (hb : 2 ≤ b) (hn : 0 < n) : (b.digits n).length = b.log n + 1 := begin induction n using nat.strong_induction_on with n IH, rw [digits_eq_cons_digits_div hb hn, list.length], cases (n / b).eq_zero_or_pos with h h, { have posb : 0 < b := zero_lt_two.trans_le hb, simp [h, log_eq_zero_iff, ←nat.div_eq_zero_iff posb] }, { have hb' : 1 < b := one_lt_two.trans_le hb, have : n / b < n := div_lt_self hn hb', rw [IH _ this h, log_div_base, tsub_add_cancel_of_le], rw [succ_le_iff], refine log_pos hb' _, contrapose! h, rw div_eq_of_lt h } end lemma last_digit_ne_zero (b : ℕ) {m : ℕ} (hm : m ≠ 0) : (digits b m).last (digits_ne_nil_iff_ne_zero.mpr hm) ≠ 0 := begin rcases b with _|_|b, { cases m, { cases hm rfl }, { simp } }, { cases m, { cases hm rfl }, simp_rw [digits_one, list.last_repeat_succ 1 m], norm_num }, revert hm, apply nat.strong_induction_on m, intros n IH hn, have hnpos : 0 < n := nat.pos_of_ne_zero hn, by_cases hnb : n < b + 2, { simp_rw [digits_of_lt b.succ.succ n hnpos hnb], exact pos_iff_ne_zero.mp hnpos }, { rw digits_last n (show 2 ≤ b + 2, from dec_trivial), refine IH _ (nat.div_lt_self hnpos dec_trivial) _, { rw ←pos_iff_ne_zero, exact nat.div_pos (le_of_not_lt hnb) dec_trivial } }, end /-- The digits in the base b+2 expansion of n are all less than b+2 -/ lemma digits_lt_base' {b m : ℕ} : ∀ {d}, d ∈ digits (b+2) m → d < b+2 := begin apply nat.strong_induction_on m, intros n IH d hd, cases n with n, { rw digits_zero at hd, cases hd }, -- base b+2 expansion of 0 has no digits rw digits_add_two_add_one at hd, cases hd, { rw hd, exact n.succ.mod_lt (by linarith) }, { exact IH _ (nat.div_lt_self (nat.succ_pos _) (by linarith)) hd } end /-- The digits in the base b expansion of n are all less than b, if b ≥ 2 -/ lemma digits_lt_base {b m d : ℕ} (hb : 2 ≤ b) (hd : d ∈ digits b m) : d < b := begin rcases b with _ | _ | b; try {linarith}, exact digits_lt_base' hd, end /-- an n-digit number in base b + 2 is less than (b + 2)^n -/ lemma of_digits_lt_base_pow_length' {b : ℕ} {l : list ℕ} (hl : ∀ x ∈ l, x < b+2) : of_digits (b+2) l < (b+2)^(l.length) := begin induction l with hd tl IH, { simp [of_digits], }, { rw [of_digits, list.length_cons, pow_succ], have : (of_digits (b + 2) tl + 1) * (b+2) ≤ (b + 2) ^ tl.length * (b+2) := mul_le_mul (IH (λ x hx, hl _ (list.mem_cons_of_mem _ hx))) (by refl) dec_trivial (nat.zero_le _), suffices : ↑hd < b + 2, { linarith }, norm_cast, exact hl hd (list.mem_cons_self _ _) } end /-- an n-digit number in base b is less than b^n if b ≥ 2 -/ lemma of_digits_lt_base_pow_length {b : ℕ} {l : list ℕ} (hb : 2 ≤ b) (hl : ∀ x ∈ l, x < b) : of_digits b l < b^l.length := begin rcases b with _ | _ | b; try { linarith }, exact of_digits_lt_base_pow_length' hl, end /-- Any number m is less than (b+2)^(number of digits in the base b + 2 representation of m) -/ lemma lt_base_pow_length_digits' {b m : ℕ} : m < (b + 2) ^ (digits (b + 2) m).length := begin convert of_digits_lt_base_pow_length' (λ _, digits_lt_base'), rw of_digits_digits (b+2) m, end /-- Any number m is less than b^(number of digits in the base b representation of m) -/ lemma lt_base_pow_length_digits {b m : ℕ} (hb : 2 ≤ b) : m < b^(digits b m).length := begin rcases b with _ | _ | b; try { linarith }, exact lt_base_pow_length_digits', end lemma of_digits_digits_append_digits {b m n : ℕ} : of_digits b (digits b n ++ digits b m) = n + b ^ (digits b n).length * m:= by rw [of_digits_append, of_digits_digits, of_digits_digits] lemma digits_len_le_digits_len_succ (b n : ℕ) : (digits b n).length ≤ (digits b (n + 1)).length := begin rcases n.eq_zero_or_pos with rfl|hn, { simp }, cases lt_or_le b 2 with hb hb, { rcases b with _|_|b, { simp [digits_zero_succ', hn] }, { simp, }, { simpa [succ_lt_succ_iff] using hb } }, simpa [digits_len, hb, hn] using log_mono_right (le_succ _) end lemma le_digits_len_le (b n m : ℕ) (h : n ≤ m) : (digits b n).length ≤ (digits b m).length := monotone_nat_of_le_succ (digits_len_le_digits_len_succ b) h lemma pow_length_le_mul_of_digits {b : ℕ} {l : list ℕ} (hl : l ≠ []) (hl2 : l.last hl ≠ 0): (b + 2) ^ l.length ≤ (b + 2) * of_digits (b+2) l := begin rw [←list.init_append_last hl], simp only [list.length_append, list.length, zero_add, list.length_init, of_digits_append, list.length_init, of_digits_singleton, add_comm (l.length - 1), pow_add, pow_one], apply nat.mul_le_mul_left, refine le_trans _ (nat.le_add_left _ _), have : 0 < l.last hl, { rwa [pos_iff_ne_zero] }, convert nat.mul_le_mul_left _ this, rw [mul_one] end /-- Any non-zero natural number `m` is greater than (b+2)^((number of digits in the base (b+2) representation of m) - 1) -/ lemma base_pow_length_digits_le' (b m : ℕ) (hm : m ≠ 0) : (b + 2) ^ ((digits (b + 2) m).length) ≤ (b + 2) * m := begin have : digits (b + 2) m ≠ [], from digits_ne_nil_iff_ne_zero.mpr hm, convert pow_length_le_mul_of_digits this (last_digit_ne_zero _ hm), rwa of_digits_digits, end /-- Any non-zero natural number `m` is greater than b^((number of digits in the base b representation of m) - 1) -/ lemma base_pow_length_digits_le (b m : ℕ) (hb : 2 ≤ b): m ≠ 0 → b ^ ((digits b m).length) ≤ b * m := begin rcases b with _ | _ | b; try { linarith }, exact base_pow_length_digits_le' b m, end /-! ### Binary -/ lemma digits_two_eq_bits (n : ℕ) : digits 2 n = n.bits.map (λ b, cond b 1 0) := begin induction n using nat.binary_rec_from_one with b n h ih, { simp, }, { simp, }, rw bits_append_bit _ _ (λ hn, absurd hn h), cases b, { rw digits_def' (le_refl 2), { simpa [nat.bit, nat.bit0_val n], }, { simpa [pos_iff_ne_zero, bit_eq_zero_iff], }, }, { simpa [nat.bit, nat.bit1_val n, add_comm, digits_add 2 le_rfl 1 n (by norm_num) (by norm_num)] }, end /-! ### Modular Arithmetic -/ -- This is really a theorem about polynomials. lemma dvd_of_digits_sub_of_digits {α : Type*} [comm_ring α] {a b k : α} (h : k ∣ a - b) (L : list ℕ) : k ∣ of_digits a L - of_digits b L := begin induction L with d L ih, { change k ∣ 0 - 0, simp, }, { simp only [of_digits, add_sub_add_left_eq_sub], exact dvd_mul_sub_mul h ih, } end lemma of_digits_modeq' (b b' : ℕ) (k : ℕ) (h : b ≡ b' [MOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [MOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [nat.modeq] at *, conv_lhs { rw [nat.add_mod, nat.mul_mod, h, ih], }, conv_rhs { rw [nat.add_mod, nat.mul_mod], }, } end lemma of_digits_modeq (b k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [MOD k] := of_digits_modeq' b (b % k) k (b.mod_modeq k).symm L lemma of_digits_mod (b k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_modeq b k L lemma of_digits_zmodeq' (b b' : ℤ) (k : ℕ) (h : b ≡ b' [ZMOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [ZMOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [int.modeq] at *, conv_lhs { rw [int.add_mod, int.mul_mod, h, ih], }, conv_rhs { rw [int.add_mod, int.mul_mod], }, } end lemma of_digits_zmodeq (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [ZMOD k] := of_digits_zmodeq' b (b % k) k (b.mod_modeq ↑k).symm L lemma of_digits_zmod (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_zmodeq b k L lemma modeq_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : n ≡ (digits b' n).sum [MOD b] := begin rw ←of_digits_one, conv { congr, skip, rw ←(of_digits_digits b' n) }, convert of_digits_modeq _ _ _, exact h.symm, end lemma modeq_three_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 3] := modeq_digits_sum 3 10 (by norm_num) n lemma modeq_nine_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 9] := modeq_digits_sum 9 10 (by norm_num) n lemma zmodeq_of_digits_digits (b b' : ℕ) (c : ℤ) (h : b' ≡ c [ZMOD b]) (n : ℕ) : n ≡ of_digits c (digits b' n) [ZMOD b] := begin conv { congr, skip, rw ←(of_digits_digits b' n) }, rw coe_int_of_digits, apply of_digits_zmodeq' _ _ _ h, end lemma of_digits_neg_one : Π (L : list ℕ), of_digits (-1 : ℤ) L = (L.map (λ n : ℕ, (n : ℤ))).alternating_sum | [] := rfl | [n] := by simp [of_digits, list.alternating_sum] | (a :: b :: t) := begin simp only [of_digits, list.alternating_sum, list.map_cons, of_digits_neg_one t], ring, end lemma modeq_eleven_digits_sum (n : ℕ) : n ≡ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum [ZMOD 11] := begin have t := zmodeq_of_digits_digits 11 10 (-1 : ℤ) (by unfold int.modeq; norm_num) n, rwa of_digits_neg_one at t end /-! ## Divisibility -/ lemma dvd_iff_dvd_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : b ∣ n ↔ b ∣ (digits b' n).sum := begin rw ←of_digits_one, conv_lhs { rw ←(of_digits_digits b' n) }, rw [nat.dvd_iff_mod_eq_zero, nat.dvd_iff_mod_eq_zero, of_digits_mod, h], end /-- **Divisibility by 3 Rule** -/ lemma three_dvd_iff (n : ℕ) : 3 ∣ n ↔ 3 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 3 10 (by norm_num) n lemma nine_dvd_iff (n : ℕ) : 9 ∣ n ↔ 9 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 9 10 (by norm_num) n lemma dvd_iff_dvd_of_digits (b b' : ℕ) (c : ℤ) (h : (b : ℤ) ∣ (b' : ℤ) - c) (n : ℕ) : b ∣ n ↔ (b : ℤ) ∣ of_digits c (digits b' n) := begin rw ←int.coe_nat_dvd, exact dvd_iff_dvd_of_dvd_sub (zmodeq_of_digits_digits b b' c (int.modeq_iff_dvd.2 h).symm _).symm.dvd, end lemma eleven_dvd_iff : 11 ∣ n ↔ (11 : ℤ) ∣ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum := begin have t := dvd_iff_dvd_of_digits 11 10 (-1 : ℤ) (by norm_num) n, rw of_digits_neg_one at t, exact t, end lemma eleven_dvd_of_palindrome (p : (digits 10 n).palindrome) (h : even (digits 10 n).length) : 11 ∣ n := begin let dig := (digits 10 n).map (coe : ℕ → ℤ), replace h : even dig.length := by rwa list.length_map, refine eleven_dvd_iff.2 ⟨0, (_ : dig.alternating_sum = 0)⟩, have := dig.alternating_sum_reverse, rw [(p.map _).reverse_eq, pow_succ, h.neg_one_pow, mul_one, neg_one_zsmul] at this, exact eq_zero_of_neg_eq this.symm, end /-! ### `norm_digits` tactic -/ namespace norm_digits theorem digits_succ (b n m r l) (e : r + b * m = n) (hr : r < b) (h : nat.digits b m = l ∧ 2 ≤ b ∧ 0 < m) : nat.digits b n = r :: l ∧ 2 ≤ b ∧ 0 < n := begin rcases h with ⟨h, b2, m0⟩, have b0 : 0 < b := by linarith, have n0 : 0 < n := by linarith [mul_pos b0 m0], refine ⟨_, b2, n0⟩, obtain ⟨rfl, rfl⟩ := (nat.div_mod_unique b0).2 ⟨e, hr⟩, subst h, exact nat.digits_def' b2 n0, end theorem digits_one (b n) (n0 : 0 < n) (nb : n < b) : nat.digits b n = [n] ∧ 2 ≤ b ∧ 0 < n := begin have b2 : 2 ≤ b := by linarith, refine ⟨_, b2, n0⟩, rw [nat.digits_def' b2 n0, nat.mod_eq_of_lt nb, (nat.div_eq_zero_iff (by linarith : 0 < b)).2 nb, nat.digits_zero], end open tactic /-- Helper function for the `norm_digits` tactic. -/ meta def eval_aux (eb : expr) (b : ℕ) : expr → ℕ → instance_cache → tactic (instance_cache × expr × expr) | en n ic := do let m := n / b, let r := n % b, (ic, er) ← ic.of_nat r, (ic, pr) ← norm_num.prove_lt_nat ic er eb, if m = 0 then do (_, pn0) ← norm_num.prove_pos ic en, return (ic, `([%%en] : list nat), `(digits_one %%eb %%en %%pn0 %%pr)) else do em ← expr.of_nat `(ℕ) m, (_, pe) ← norm_num.derive `(%%er + %%eb * %%em : ℕ), (ic, el, p) ← eval_aux em m ic, return (ic, `(@list.cons ℕ %%er %%el), `(digits_succ %%eb %%en %%em %%er %%el %%pe %%pr %%p)) /-- A tactic for normalizing expressions of the form `nat.digits a b = l` where `a` and `b` are numerals. ``` example : nat.digits 10 123 = [3,2,1] := by norm_num ``` -/ @[norm_num] meta def eval : expr → tactic (expr × expr) | `(nat.digits %%eb %%en) := do b ← expr.to_nat eb, n ← expr.to_nat en, if n = 0 then return (`([] : list ℕ), `(nat.digits_zero %%eb)) else if b = 0 then do ic ← mk_instance_cache `(ℕ), (_, pn0) ← norm_num.prove_pos ic en, return (`([%%en] : list ℕ), `(@nat.digits_zero_succ' %%en %%pn0)) else if b = 1 then do ic ← mk_instance_cache `(ℕ), (_, pn0) ← norm_num.prove_pos ic en, s ← simp_lemmas.add_simp simp_lemmas.mk `list.repeat, (rhs, p2, _) ← simplify s [] `(list.repeat 1 %%en), p ← mk_eq_trans `(nat.digits_one %%en) p2, return (rhs, p) else do ic ← mk_instance_cache `(ℕ), (_, l, p) ← eval_aux eb b en n ic, p ← mk_app ``and.left [p], return (l, p) | _ := failed end norm_digits end nat
6c1042a5a3ba8ac2e6c5b6e40f44ceee4c3d7a49
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/category_theory/preadditive/default.lean
46e4fa03aa06adbfa1c9b3fbee2d67c63733e08f
[ "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
8,585
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import algebra.group.hom import category_theory.limits.shapes.kernels import algebra.big_operators.basic import category_theory.endomorphism /-! # Preadditive categories A preadditive category is a category in which `X ⟶ Y` is an abelian group in such a way that composition of morphisms is linear in both variables. This file contains a definition of preadditive category that directly encodes the definition given above. The definition could also be phrased as follows: A preadditive category is a category enriched over the category of Abelian groups. Once the general framework to state this in Lean is available, the contents of this file should become obsolete. ## Main results * Definition of preadditive categories and basic properties * In a preadditive category, `f : Q ⟶ R` is mono if and only if `g ≫ f = 0 → g = 0` for all composable `g`. * A preadditive category with kernels has equalizers. ## Implementation notes The simp normal form for negation and composition is to push negations as far as possible to the outside. For example, `f ≫ (-g)` and `(-f) ≫ g` both become `-(f ≫ g)`, and `(-f) ≫ (-g)` is simplified to `f ≫ g`. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] ## Tags additive, preadditive, Hom group, Ab-category, Ab-enriched -/ universes v u open category_theory.limits open add_monoid_hom namespace category_theory variables (C : Type u) [category.{v} C] /-- A category is called preadditive if `P ⟶ Q` is an abelian group such that composition is linear in both variables. -/ class preadditive := (hom_group : Π P Q : C, add_comm_group (P ⟶ Q) . tactic.apply_instance) (add_comp' : ∀ (P Q R : C) (f f' : P ⟶ Q) (g : Q ⟶ R), (f + f') ≫ g = f ≫ g + f' ≫ g . obviously) (comp_add' : ∀ (P Q R : C) (f : P ⟶ Q) (g g' : Q ⟶ R), f ≫ (g + g') = f ≫ g + f ≫ g' . obviously) attribute [instance] preadditive.hom_group restate_axiom preadditive.add_comp' restate_axiom preadditive.comp_add' attribute [simp,reassoc] preadditive.add_comp attribute [reassoc] preadditive.comp_add -- (the linter doesn't like `simp` on this lemma) attribute [simp] preadditive.comp_add end category_theory open category_theory namespace category_theory.preadditive section preadditive variables {C : Type u} [category.{v} C] [preadditive C] section induced_category universes u' variables {C} {D : Type u'} (F : D → C) instance induced_category.category : preadditive.{v} (induced_category C F) := { hom_group := λ P Q, @preadditive.hom_group C _ _ (F P) (F Q), add_comp' := λ P Q R f f' g, add_comp' _ _ _ _ _ _, comp_add' := λ P Q R f g g', comp_add' _ _ _ _ _ _, } end induced_category instance (X : C) : add_comm_group (End X) := by { dsimp [End], apply_instance, } instance (X : C) : ring (End X) := { left_distrib := λ f g h, preadditive.add_comp X X X g h f, right_distrib := λ f g h, preadditive.comp_add X X X h f g, ..(infer_instance : add_comm_group (End X)), ..(infer_instance : monoid (End X)) } /-- Composition by a fixed left argument as a group homomorphism -/ def left_comp {P Q : C} (R : C) (f : P ⟶ Q) : (Q ⟶ R) →+ (P ⟶ R) := mk' (λ g, f ≫ g) $ λ g g', by simp /-- Composition by a fixed right argument as a group homomorphism -/ def right_comp (P : C) {Q R : C} (g : Q ⟶ R) : (P ⟶ Q) →+ (P ⟶ R) := mk' (λ f, f ≫ g) $ λ f f', by simp @[simp, reassoc] lemma sub_comp {P Q R : C} (f f' : P ⟶ Q) (g : Q ⟶ R) : (f - f') ≫ g = f ≫ g - f' ≫ g := map_sub (right_comp P g) f f' -- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma comp_sub {P Q R : C} (f : P ⟶ Q) (g g' : Q ⟶ R) : f ≫ (g - g') = f ≫ g - f ≫ g' := map_sub (left_comp R f) g g' @[simp, reassoc] lemma neg_comp {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) : (-f) ≫ g = -(f ≫ g) := map_neg (right_comp _ _) _ /- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. -/ @[reassoc, simp] lemma comp_neg {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) : f ≫ (-g) = -(f ≫ g) := map_neg (left_comp _ _) _ @[reassoc] lemma neg_comp_neg {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) : (-f) ≫ (-g) = f ≫ g := by simp section big_operators open_locale big_operators @[reassoc] lemma comp_sum {P Q R : C} {J : Type*} {s : finset J} (f : P ⟶ Q) (g : J → (Q ⟶ R)) : f ≫ ∑ j in s, g j = ∑ j in s, f ≫ g j := begin change left_comp R f _ = _, rw [add_monoid_hom.map_sum], refl, end @[reassoc] lemma sum_comp {P Q R : C} {J : Type*} {s : finset J} (f : J → (P ⟶ Q)) (g : Q ⟶ R) : (∑ j in s, f j) ≫ g = ∑ j in s, f j ≫ g := begin change right_comp P g _ = _, rw [add_monoid_hom.map_sum], refl, end end big_operators instance {P Q : C} {f : P ⟶ Q} [epi f] : epi (-f) := ⟨λ R g g' H, by rwa [neg_comp, neg_comp, ←comp_neg, ←comp_neg, cancel_epi, neg_inj] at H⟩ instance {P Q : C} {f : P ⟶ Q} [mono f] : mono (-f) := ⟨λ R g g' H, by rwa [comp_neg, comp_neg, ←neg_comp, ←neg_comp, cancel_mono, neg_inj] at H⟩ @[priority 100] instance preadditive_has_zero_morphisms : has_zero_morphisms C := { has_zero := infer_instance, comp_zero' := λ P Q f R, map_zero $ left_comp R f, zero_comp' := λ P Q R f, map_zero $ right_comp P f } lemma mono_of_cancel_zero {Q R : C} (f : Q ⟶ R) (h : ∀ {P : C} (g : P ⟶ Q), g ≫ f = 0 → g = 0) : mono f := ⟨λ P g g' hg, sub_eq_zero.1 $ h _ $ (map_sub (right_comp P f) g g').trans $ sub_eq_zero.2 hg⟩ lemma mono_iff_cancel_zero {Q R : C} (f : Q ⟶ R) : mono f ↔ ∀ (P : C) (g : P ⟶ Q), g ≫ f = 0 → g = 0 := ⟨λ m P g, by exactI zero_of_comp_mono _, mono_of_cancel_zero f⟩ lemma mono_of_kernel_zero {X Y : C} {f : X ⟶ Y} [has_limit (parallel_pair f 0)] (w : kernel.ι f = 0) : mono f := mono_of_cancel_zero f (λ P g h, by rw [←kernel.lift_ι f g h, w, limits.comp_zero]) lemma epi_of_cancel_zero {P Q : C} (f : P ⟶ Q) (h : ∀ {R : C} (g : Q ⟶ R), f ≫ g = 0 → g = 0) : epi f := ⟨λ R g g' hg, sub_eq_zero.1 $ h _ $ (map_sub (left_comp R f) g g').trans $ sub_eq_zero.2 hg⟩ lemma epi_iff_cancel_zero {P Q : C} (f : P ⟶ Q) : epi f ↔ ∀ (R : C) (g : Q ⟶ R), f ≫ g = 0 → g = 0 := ⟨λ e R g, by exactI zero_of_epi_comp _, epi_of_cancel_zero f⟩ lemma epi_of_cokernel_zero {X Y : C} (f : X ⟶ Y) [has_colimit (parallel_pair f 0 )] (w : cokernel.π f = 0) : epi f := epi_of_cancel_zero f (λ P g h, by rw [←cokernel.π_desc f g h, w, limits.zero_comp]) end preadditive section equalizers variables {C : Type u} [category.{v} C] [preadditive C] section variables {X Y : C} (f : X ⟶ Y) (g : X ⟶ Y) /-- A kernel of `f - g` is an equalizer of `f` and `g`. -/ lemma has_limit_parallel_pair [has_kernel (f - g)] : has_limit (parallel_pair f g) := has_limit.mk { cone := fork.of_ι (kernel.ι (f - g)) (sub_eq_zero.1 $ by { rw ←comp_sub, exact kernel.condition _ }), is_limit := fork.is_limit.mk _ (λ s, kernel.lift (f - g) (fork.ι s) $ by { rw comp_sub, apply sub_eq_zero.2, exact fork.condition _ }) (λ s, by simp) (λ s m h, by { ext, simpa using h walking_parallel_pair.zero }) } end section /-- If a preadditive category has all kernels, then it also has all equalizers. -/ lemma has_equalizers_of_has_kernels [has_kernels C] : has_equalizers C := @has_equalizers_of_has_limit_parallel_pair _ _ (λ _ _ f g, has_limit_parallel_pair f g) end section variables {X Y : C} (f : X ⟶ Y) (g : X ⟶ Y) /-- A cokernel of `f - g` is a coequalizer of `f` and `g`. -/ lemma has_colimit_parallel_pair [has_cokernel (f - g)] : has_colimit (parallel_pair f g) := has_colimit.mk { cocone := cofork.of_π (cokernel.π (f - g)) (sub_eq_zero.1 $ by { rw ←sub_comp, exact cokernel.condition _ }), is_colimit := cofork.is_colimit.mk _ (λ s, cokernel.desc (f - g) (cofork.π s) $ by { rw sub_comp, apply sub_eq_zero.2, exact cofork.condition _ }) (λ s, by simp) (λ s m h, by { ext, simpa using h walking_parallel_pair.one }) } end section /-- If a preadditive category has all cokernels, then it also has all coequalizers. -/ lemma has_coequalizers_of_has_cokernels [has_cokernels C] : has_coequalizers C := @has_coequalizers_of_has_colimit_parallel_pair _ _ (λ _ _ f g, has_colimit_parallel_pair f g) end end equalizers end category_theory.preadditive
ede3fbad8c708256760f099ff69de772903500a6
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/algebra/order/basic.lean
442c1e88eba917032f7b78137d36222b93169671
[ "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
139,592
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, Yury Kudryashov -/ import algebra.group_with_zero.power import data.set.intervals.pi import order.filter.interval import topology.algebra.field import topology.algebra.order.left_right import tactic.linarith import tactic.tfae import tactic.positivity /-! # Theory of topology on ordered spaces ## Main definitions The order topology on an ordered space is the topology generated by all open intervals (or equivalently by those of the form `(-∞, a)` and `(b, +∞)`). We define it as `preorder.topology α`. However, we do *not* register it as an instance (as many existing ordered types already have topologies, which would be equal but not definitionally equal to `preorder.topology α`). Instead, we introduce a class `order_topology α` (which is a `Prop`, also known as a mixin) saying that on the type `α` having already a topological space structure and a preorder structure, the topological structure is equal to the order topology. We also introduce another (mixin) class `order_closed_topology α` saying that the set of points `(x, y)` with `x ≤ y` is closed in the product space. This is automatically satisfied on a linear order with the order topology. We prove many basic properties of such topologies. ## Main statements This file contains the proofs of the following facts. For exact requirements (`order_closed_topology` vs `order_topology`, `preorder` vs `partial_order` vs `linear_order` etc) see their statements. ### Open / closed sets * `is_open_lt` : if `f` and `g` are continuous functions, then `{x | f x < g x}` is open; * `is_open_Iio`, `is_open_Ioi`, `is_open_Ioo` : open intervals are open; * `is_closed_le` : if `f` and `g` are continuous functions, then `{x | f x ≤ g x}` is closed; * `is_closed_Iic`, `is_closed_Ici`, `is_closed_Icc` : closed intervals are closed; * `frontier_le_subset_eq`, `frontier_lt_subset_eq` : frontiers of both `{x | f x ≤ g x}` and `{x | f x < g x}` are included by `{x | f x = g x}`; * `exists_Ioc_subset_of_mem_nhds`, `exists_Ico_subset_of_mem_nhds` : if `x < y`, then any neighborhood of `x` includes an interval `[x, z)` for some `z ∈ (x, y]`, and any neighborhood of `y` includes an interval `(z, y]` for some `z ∈ [x, y)`. ### Convergence and inequalities * `le_of_tendsto_of_tendsto` : if `f` converges to `a`, `g` converges to `b`, and eventually `f x ≤ g x`, then `a ≤ b` * `le_of_tendsto`, `ge_of_tendsto` : if `f` converges to `a` and eventually `f x ≤ b` (resp., `b ≤ f x`), then `a ≤ b` (resp., `b ≤ a); we also provide primed versions that assume the inequalities to hold for all `x`. ### Min, max, `Sup` and `Inf` * `continuous.min`, `continuous.max`: pointwise `min`/`max` of two continuous functions is continuous. * `tendsto.min`, `tendsto.max` : if `f` tends to `a` and `g` tends to `b`, then their pointwise `min`/`max` tend to `min a b` and `max a b`, respectively. * `tendsto_of_tendsto_of_tendsto_of_le_of_le` : theorem known as squeeze theorem, sandwich theorem, theorem of Carabinieri, and two policemen (and a drunk) theorem; if `g` and `h` both converge to `a`, and eventually `g x ≤ f x ≤ h x`, then `f` converges to `a`. ## Implementation notes We do _not_ register the order topology as an instance on a preorder (or even on a linear order). Indeed, on many such spaces, a topology has already been constructed in a different way (think of the discrete spaces `ℕ` or `ℤ`, or `ℝ` that could inherit a topology as the completion of `ℚ`), and is in general not defeq to the one generated by the intervals. We make it available as a definition `preorder.topology α` though, that can be registered as an instance when necessary, or for specific types. -/ open set filter topological_space open function open order_dual (to_dual of_dual) open_locale topological_space classical filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- A topology on a set which is both a topological space and a preorder is _order-closed_ if the set of points `(x, y)` with `x ≤ y` is closed in the product space. We introduce this as a mixin. This property is satisfied for the order topology on a linear order, but it can be satisfied more generally, and suffices to derive many interesting properties relating order and topology. -/ class order_closed_topology (α : Type*) [topological_space α] [preorder α] : Prop := (is_closed_le' : is_closed {p:α×α | p.1 ≤ p.2}) instance [topological_space α] [h : first_countable_topology α] : first_countable_topology αᵒᵈ := h instance [topological_space α] [h : second_countable_topology α] : second_countable_topology αᵒᵈ := h @[to_additive] instance [topological_space α] [has_mul α] [h : has_continuous_mul α] : has_continuous_mul αᵒᵈ := h lemma dense.order_dual [topological_space α] {s : set α} (hs : dense s) : dense (order_dual.of_dual ⁻¹' s) := hs section order_closed_topology section preorder variables [topological_space α] [preorder α] [t : order_closed_topology α] include t namespace subtype instance {p : α → Prop} : order_closed_topology (subtype p) := have this : continuous (λ (p : (subtype p) × (subtype p)), ((p.fst : α), (p.snd : α))) := (continuous_subtype_coe.comp continuous_fst).prod_mk (continuous_subtype_coe.comp continuous_snd), order_closed_topology.mk (t.is_closed_le'.preimage this) end subtype lemma is_closed_le_prod : is_closed {p : α × α | p.1 ≤ p.2} := t.is_closed_le' lemma is_closed_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {b | f b ≤ g b} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_le_prod lemma is_closed_le' (a : α) : is_closed {b | b ≤ a} := is_closed_le continuous_id continuous_const lemma is_closed_Iic {a : α} : is_closed (Iic a) := is_closed_le' a lemma is_closed_ge' (a : α) : is_closed {b | a ≤ b} := is_closed_le continuous_const continuous_id lemma is_closed_Ici {a : α} : is_closed (Ici a) := is_closed_ge' a instance : order_closed_topology αᵒᵈ := ⟨(@order_closed_topology.is_closed_le' α _ _ _).preimage continuous_swap⟩ lemma is_closed_Icc {a b : α} : is_closed (Icc a b) := is_closed.inter is_closed_Ici is_closed_Iic @[simp] lemma closure_Icc (a b : α) : closure (Icc a b) = Icc a b := is_closed_Icc.closure_eq @[simp] lemma closure_Iic (a : α) : closure (Iic a) = Iic a := is_closed_Iic.closure_eq @[simp] lemma closure_Ici (a : α) : closure (Ici a) = Ici a := is_closed_Ici.closure_eq lemma le_of_tendsto_of_tendsto {f g : β → α} {b : filter β} {a₁ a₂ : α} [ne_bot b] (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : f ≤ᶠ[b] g) : a₁ ≤ a₂ := have tendsto (λb, (f b, g b)) b (𝓝 (a₁, a₂)), by rw [nhds_prod_eq]; exact hf.prod_mk hg, show (a₁, a₂) ∈ {p:α×α | p.1 ≤ p.2}, from t.is_closed_le'.mem_of_tendsto this h alias le_of_tendsto_of_tendsto ← tendsto_le_of_eventually_le lemma le_of_tendsto_of_tendsto' {f g : β → α} {b : filter β} {a₁ a₂ : α} [ne_bot b] (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : ∀ x, f x ≤ g x) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto hf hg (eventually_of_forall h) lemma le_of_tendsto {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, f c ≤ b) : a ≤ b := le_of_tendsto_of_tendsto lim tendsto_const_nhds h lemma le_of_tendsto' {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ c, f c ≤ b) : a ≤ b := le_of_tendsto lim (eventually_of_forall h) lemma ge_of_tendsto {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, b ≤ f c) : b ≤ a := le_of_tendsto_of_tendsto tendsto_const_nhds lim h lemma ge_of_tendsto' {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ c, b ≤ f c) : b ≤ a := ge_of_tendsto lim (eventually_of_forall h) @[simp] lemma closure_le_eq [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b ≤ g b} = {b | f b ≤ g b} := (is_closed_le hf hg).closure_eq lemma closure_lt_subset_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b < g b} ⊆ {b | f b ≤ g b} := closure_minimal (λ x, le_of_lt) $ is_closed_le hf hg lemma continuous_within_at.closure_le [topological_space β] {f g : β → α} {s : set β} {x : β} (hx : x ∈ closure s) (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) (h : ∀ y ∈ s, f y ≤ g y) : f x ≤ g x := show (f x, g x) ∈ {p : α × α | p.1 ≤ p.2}, from order_closed_topology.is_closed_le'.closure_subset ((hf.prod hg).mem_closure hx h) /-- If `s` is a closed set and two functions `f` and `g` are continuous on `s`, then the set `{x ∈ s | f x ≤ g x}` is a closed set. -/ lemma is_closed.is_closed_le [topological_space β] {f g : β → α} {s : set β} (hs : is_closed s) (hf : continuous_on f s) (hg : continuous_on g s) : is_closed {x ∈ s | f x ≤ g x} := (hf.prod hg).preimage_closed_of_closed hs order_closed_topology.is_closed_le' lemma le_on_closure [topological_space β] {f g : β → α} {s : set β} (h : ∀ x ∈ s, f x ≤ g x) (hf : continuous_on f (closure s)) (hg : continuous_on g (closure s)) ⦃x⦄ (hx : x ∈ closure s) : f x ≤ g x := have s ⊆ {y ∈ closure s | f y ≤ g y}, from λ y hy, ⟨subset_closure hy, h y hy⟩, (closure_minimal this (is_closed_closure.is_closed_le hf hg) hx).2 lemma is_closed.epigraph [topological_space β] {f : β → α} {s : set β} (hs : is_closed s) (hf : continuous_on f s) : is_closed {p : β × α | p.1 ∈ s ∧ f p.1 ≤ p.2} := (hs.preimage continuous_fst).is_closed_le (hf.comp continuous_on_fst subset.rfl) continuous_on_snd lemma is_closed.hypograph [topological_space β] {f : β → α} {s : set β} (hs : is_closed s) (hf : continuous_on f s) : is_closed {p : β × α | p.1 ∈ s ∧ p.2 ≤ f p.1} := (hs.preimage continuous_fst).is_closed_le continuous_on_snd (hf.comp continuous_on_fst subset.rfl) omit t lemma nhds_within_Ici_ne_bot {a b : α} (H₂ : a ≤ b) : ne_bot (𝓝[Ici a] b) := nhds_within_ne_bot_of_mem H₂ @[instance] lemma nhds_within_Ici_self_ne_bot (a : α) : ne_bot (𝓝[≥] a) := nhds_within_Ici_ne_bot (le_refl a) lemma nhds_within_Iic_ne_bot {a b : α} (H : a ≤ b) : ne_bot (𝓝[Iic b] a) := nhds_within_ne_bot_of_mem H @[instance] lemma nhds_within_Iic_self_ne_bot (a : α) : ne_bot (𝓝[≤] a) := nhds_within_Iic_ne_bot (le_refl a) end preorder section partial_order variables [topological_space α] [partial_order α] [t : order_closed_topology α] include t @[priority 90] -- see Note [lower instance priority] instance order_closed_topology.to_t2_space : t2_space α := t2_iff_is_closed_diagonal.2 $ by simpa only [diagonal, le_antisymm_iff] using t.is_closed_le'.inter (is_closed_le continuous_snd continuous_fst) end partial_order section linear_order variables [topological_space α] [linear_order α] [order_closed_topology α] lemma is_open_lt_prod : is_open {p : α × α | p.1 < p.2} := by { simp_rw [← is_closed_compl_iff, compl_set_of, not_lt], exact is_closed_le continuous_snd continuous_fst } lemma is_open_lt [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_open {b | f b < g b} := by simp [lt_iff_not_ge, -not_le]; exact (is_closed_le hg hf).is_open_compl variables {a b : α} lemma is_open_Iio : is_open (Iio a) := is_open_lt continuous_id continuous_const lemma is_open_Ioi : is_open (Ioi a) := is_open_lt continuous_const continuous_id lemma is_open_Ioo : is_open (Ioo a b) := is_open.inter is_open_Ioi is_open_Iio @[simp] lemma interior_Ioi : interior (Ioi a) = Ioi a := is_open_Ioi.interior_eq @[simp] lemma interior_Iio : interior (Iio a) = Iio a := is_open_Iio.interior_eq @[simp] lemma interior_Ioo : interior (Ioo a b) = Ioo a b := is_open_Ioo.interior_eq lemma Ioo_subset_closure_interior : Ioo a b ⊆ closure (interior (Ioo a b)) := by simp only [interior_Ioo, subset_closure] lemma Iio_mem_nhds {a b : α} (h : a < b) : Iio b ∈ 𝓝 a := is_open.mem_nhds is_open_Iio h lemma Ioi_mem_nhds {a b : α} (h : a < b) : Ioi a ∈ 𝓝 b := is_open.mem_nhds is_open_Ioi h lemma Iic_mem_nhds {a b : α} (h : a < b) : Iic b ∈ 𝓝 a := mem_of_superset (Iio_mem_nhds h) Iio_subset_Iic_self lemma Ici_mem_nhds {a b : α} (h : a < b) : Ici a ∈ 𝓝 b := mem_of_superset (Ioi_mem_nhds h) Ioi_subset_Ici_self lemma Ioo_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Ioo a b ∈ 𝓝 x := is_open.mem_nhds is_open_Ioo ⟨ha, hb⟩ lemma Ioc_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Ioc a b ∈ 𝓝 x := mem_of_superset (Ioo_mem_nhds ha hb) Ioo_subset_Ioc_self lemma Ico_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Ico a b ∈ 𝓝 x := mem_of_superset (Ioo_mem_nhds ha hb) Ioo_subset_Ico_self lemma Icc_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Icc a b ∈ 𝓝 x := mem_of_superset (Ioo_mem_nhds ha hb) Ioo_subset_Icc_self lemma eventually_lt_of_tendsto_lt {l : filter γ} {f : γ → α} {u v : α} (hv : v < u) (h : filter.tendsto f l (𝓝 v)) : ∀ᶠ a in l, f a < u := tendsto_nhds.1 h (< u) is_open_Iio hv lemma eventually_gt_of_tendsto_gt {l : filter γ} {f : γ → α} {u v : α} (hv : u < v) (h : filter.tendsto f l (𝓝 v)) : ∀ᶠ a in l, u < f a := tendsto_nhds.1 h (> u) is_open_Ioi hv lemma eventually_le_of_tendsto_lt {l : filter γ} {f : γ → α} {u v : α} (hv : v < u) (h : tendsto f l (𝓝 v)) : ∀ᶠ a in l, f a ≤ u := (eventually_lt_of_tendsto_lt hv h).mono (λ v, le_of_lt) lemma eventually_ge_of_tendsto_gt {l : filter γ} {f : γ → α} {u v : α} (hv : u < v) (h : tendsto f l (𝓝 v)) : ∀ᶠ a in l, u ≤ f a := (eventually_gt_of_tendsto_gt hv h).mono (λ v, le_of_lt) variables [topological_space γ] /-! ### Neighborhoods to the left and to the right on an `order_closed_topology` Limits to the left and to the right of real functions are defined in terms of neighborhoods to the left and to the right, either open or closed, i.e., members of `𝓝[>] a` and `𝓝[≥] a` on the right, and similarly on the left. Here we simply prove that all right-neighborhoods of a point are equal, and we'll prove later other useful characterizations which require the stronger hypothesis `order_topology α` -/ /-! #### Right neighborhoods, point excluded -/ lemma Ioo_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Ioo a c ∈ 𝓝[>] b := mem_nhds_within.2 ⟨Iio c, is_open_Iio, H.2, by rw [inter_comm, Ioi_inter_Iio]; exact Ioo_subset_Ioo_left H.1⟩ lemma Ioc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Ioc a c ∈ 𝓝[>] b := mem_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ioc_self lemma Ico_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Ico a c ∈ 𝓝[>] b := mem_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ico_self lemma Icc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Icc a c ∈ 𝓝[>] b := mem_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Icc_self @[simp] lemma nhds_within_Ioc_eq_nhds_within_Ioi {a b : α} (h : a < b) : 𝓝[Ioc a b] a = 𝓝[>] a := le_antisymm (nhds_within_mono _ Ioc_subset_Ioi_self) $ nhds_within_le_of_mem $ Ioc_mem_nhds_within_Ioi $ left_mem_Ico.2 h @[simp] lemma nhds_within_Ioo_eq_nhds_within_Ioi {a b : α} (h : a < b) : 𝓝[Ioo a b] a = 𝓝[>] a := le_antisymm (nhds_within_mono _ Ioo_subset_Ioi_self) $ nhds_within_le_of_mem $ Ioo_mem_nhds_within_Ioi $ left_mem_Ico.2 h @[simp] lemma continuous_within_at_Ioc_iff_Ioi [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioc a b) a ↔ continuous_within_at f (Ioi a) a := by simp only [continuous_within_at, nhds_within_Ioc_eq_nhds_within_Ioi h] @[simp] lemma continuous_within_at_Ioo_iff_Ioi [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioo a b) a ↔ continuous_within_at f (Ioi a) a := by simp only [continuous_within_at, nhds_within_Ioo_eq_nhds_within_Ioi h] /-! #### Left neighborhoods, point excluded -/ lemma Ioo_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Ioo a c ∈ 𝓝[<] b := by simpa only [dual_Ioo] using Ioo_mem_nhds_within_Ioi (show to_dual b ∈ Ico (to_dual c) (to_dual a), from H.symm) lemma Ico_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Ico a c ∈ 𝓝[<] b := mem_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Ico_self lemma Ioc_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Ioc a c ∈ 𝓝[<] b := mem_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Ioc_self lemma Icc_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Icc a c ∈ 𝓝[<] b := mem_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Icc_self @[simp] lemma nhds_within_Ico_eq_nhds_within_Iio {a b : α} (h : a < b) : 𝓝[Ico a b] b = 𝓝[<] b := by simpa only [dual_Ioc] using nhds_within_Ioc_eq_nhds_within_Ioi h.dual @[simp] lemma nhds_within_Ioo_eq_nhds_within_Iio {a b : α} (h : a < b) : 𝓝[Ioo a b] b = 𝓝[<] b := by simpa only [dual_Ioo] using nhds_within_Ioo_eq_nhds_within_Ioi h.dual @[simp] lemma continuous_within_at_Ico_iff_Iio {a b : α} {f : α → γ} (h : a < b) : continuous_within_at f (Ico a b) b ↔ continuous_within_at f (Iio b) b := by simp only [continuous_within_at, nhds_within_Ico_eq_nhds_within_Iio h] @[simp] lemma continuous_within_at_Ioo_iff_Iio {a b : α} {f : α → γ} (h : a < b) : continuous_within_at f (Ioo a b) b ↔ continuous_within_at f (Iio b) b := by simp only [continuous_within_at, nhds_within_Ioo_eq_nhds_within_Iio h] /-! #### Right neighborhoods, point included -/ lemma Ioo_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ioo a c) : Ioo a c ∈ 𝓝[≥] b := mem_nhds_within_of_mem_nhds $ is_open.mem_nhds is_open_Ioo H lemma Ioc_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ioo a c) : Ioc a c ∈ 𝓝[≥] b := mem_of_superset (Ioo_mem_nhds_within_Ici H) Ioo_subset_Ioc_self lemma Ico_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ico a c) : Ico a c ∈ 𝓝[≥] b := mem_nhds_within.2 ⟨Iio c, is_open_Iio, H.2, by simp only [inter_comm, Ici_inter_Iio, Ico_subset_Ico_left H.1]⟩ lemma Icc_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ico a c) : Icc a c ∈ 𝓝[≥] b := mem_of_superset (Ico_mem_nhds_within_Ici H) Ico_subset_Icc_self @[simp] lemma nhds_within_Icc_eq_nhds_within_Ici {a b : α} (h : a < b) : 𝓝[Icc a b] a = 𝓝[≥] a := le_antisymm (nhds_within_mono _ Icc_subset_Ici_self) $ nhds_within_le_of_mem $ Icc_mem_nhds_within_Ici $ left_mem_Ico.2 h @[simp] lemma nhds_within_Ico_eq_nhds_within_Ici {a b : α} (h : a < b) : 𝓝[Ico a b] a = 𝓝[≥] a := le_antisymm (nhds_within_mono _ (λ x, and.left)) $ nhds_within_le_of_mem $ Ico_mem_nhds_within_Ici $ left_mem_Ico.2 h @[simp] lemma continuous_within_at_Icc_iff_Ici [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Icc a b) a ↔ continuous_within_at f (Ici a) a := by simp only [continuous_within_at, nhds_within_Icc_eq_nhds_within_Ici h] @[simp] lemma continuous_within_at_Ico_iff_Ici [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ico a b) a ↔ continuous_within_at f (Ici a) a := by simp only [continuous_within_at, nhds_within_Ico_eq_nhds_within_Ici h] /-! #### Left neighborhoods, point included -/ lemma Ioo_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioo a c) : Ioo a c ∈ 𝓝[≤] b := mem_nhds_within_of_mem_nhds $ is_open.mem_nhds is_open_Ioo H lemma Ico_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioo a c) : Ico a c ∈ 𝓝[≤] b := mem_of_superset (Ioo_mem_nhds_within_Iic H) Ioo_subset_Ico_self lemma Ioc_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioc a c) : Ioc a c ∈ 𝓝[≤] b := by simpa only [dual_Ico] using Ico_mem_nhds_within_Ici (show to_dual b ∈ Ico (to_dual c) (to_dual a), from H.symm) lemma Icc_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioc a c) : Icc a c ∈ 𝓝[≤] b := mem_of_superset (Ioc_mem_nhds_within_Iic H) Ioc_subset_Icc_self @[simp] lemma nhds_within_Icc_eq_nhds_within_Iic {a b : α} (h : a < b) : 𝓝[Icc a b] b = 𝓝[≤] b := by simpa only [dual_Icc] using nhds_within_Icc_eq_nhds_within_Ici h.dual @[simp] lemma nhds_within_Ioc_eq_nhds_within_Iic {a b : α} (h : a < b) : 𝓝[Ioc a b] b = 𝓝[≤] b := by simpa only [dual_Ico] using nhds_within_Ico_eq_nhds_within_Ici h.dual @[simp] lemma continuous_within_at_Icc_iff_Iic [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Icc a b) b ↔ continuous_within_at f (Iic b) b := by simp only [continuous_within_at, nhds_within_Icc_eq_nhds_within_Iic h] @[simp] lemma continuous_within_at_Ioc_iff_Iic [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioc a b) b ↔ continuous_within_at f (Iic b) b := by simp only [continuous_within_at, nhds_within_Ioc_eq_nhds_within_Iic h] end linear_order section linear_order variables [topological_space α] [linear_order α] [order_closed_topology α] {f g : β → α} section variables [topological_space β] lemma lt_subset_interior_le (hf : continuous f) (hg : continuous g) : {b | f b < g b} ⊆ interior {b | f b ≤ g b} := interior_maximal (λ p, le_of_lt) $ is_open_lt hf hg lemma frontier_le_subset_eq (hf : continuous f) (hg : continuous g) : frontier {b | f b ≤ g b} ⊆ {b | f b = g b} := begin rw [frontier_eq_closure_inter_closure, closure_le_eq hf hg], rintros b ⟨hb₁, hb₂⟩, refine le_antisymm hb₁ (closure_lt_subset_le hg hf _), convert hb₂ using 2, simp only [not_le.symm], refl end lemma frontier_Iic_subset (a : α) : frontier (Iic a) ⊆ {a} := frontier_le_subset_eq (@continuous_id α _) continuous_const lemma frontier_Ici_subset (a : α) : frontier (Ici a) ⊆ {a} := @frontier_Iic_subset αᵒᵈ _ _ _ _ lemma frontier_lt_subset_eq (hf : continuous f) (hg : continuous g) : frontier {b | f b < g b} ⊆ {b | f b = g b} := by rw ← frontier_compl; convert frontier_le_subset_eq hg hf; simp [ext_iff, eq_comm] lemma continuous_if_le [topological_space γ] [Π x, decidable (f x ≤ g x)] {f' g' : β → γ} (hf : continuous f) (hg : continuous g) (hf' : continuous_on f' {x | f x ≤ g x}) (hg' : continuous_on g' {x | g x ≤ f x}) (hfg : ∀ x, f x = g x → f' x = g' x) : continuous (λ x, if f x ≤ g x then f' x else g' x) := begin refine continuous_if (λ a ha, hfg _ (frontier_le_subset_eq hf hg ha)) _ (hg'.mono _), { rwa [(is_closed_le hf hg).closure_eq] }, { simp only [not_le], exact closure_lt_subset_le hg hf } end lemma continuous.if_le [topological_space γ] [Π x, decidable (f x ≤ g x)] {f' g' : β → γ} (hf' : continuous f') (hg' : continuous g') (hf : continuous f) (hg : continuous g) (hfg : ∀ x, f x = g x → f' x = g' x) : continuous (λ x, if f x ≤ g x then f' x else g' x) := continuous_if_le hf hg hf'.continuous_on hg'.continuous_on hfg lemma tendsto.eventually_lt {l : filter γ} {f g : γ → α} {y z : α} (hf : tendsto f l (𝓝 y)) (hg : tendsto g l (𝓝 z)) (hyz : y < z) : ∀ᶠ x in l, f x < g x := begin by_cases h : y ⋖ z, { filter_upwards [hf (Iio_mem_nhds hyz), hg (Ioi_mem_nhds hyz)], rw [h.Iio_eq], exact λ x hfx hgx, lt_of_le_of_lt hfx hgx }, { obtain ⟨w, hyw, hwz⟩ := (not_covby_iff hyz).mp h, filter_upwards [hf (Iio_mem_nhds hyw), hg (Ioi_mem_nhds hwz)], exact λ x, lt_trans }, end lemma continuous_at.eventually_lt {x₀ : β} (hf : continuous_at f x₀) (hg : continuous_at g x₀) (hfg : f x₀ < g x₀) : ∀ᶠ x in 𝓝 x₀, f x < g x := tendsto.eventually_lt hf hg hfg @[continuity] lemma continuous.min (hf : continuous f) (hg : continuous g) : continuous (λb, min (f b) (g b)) := by { simp only [min_def], exact hf.if_le hg hf hg (λ x, id) } @[continuity] lemma continuous.max (hf : continuous f) (hg : continuous g) : continuous (λb, max (f b) (g b)) := @continuous.min αᵒᵈ _ _ _ _ _ _ _ hf hg end lemma continuous_min : continuous (λ p : α × α, min p.1 p.2) := continuous_fst.min continuous_snd lemma continuous_max : continuous (λ p : α × α, max p.1 p.2) := continuous_fst.max continuous_snd lemma filter.tendsto.max {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) : tendsto (λb, max (f b) (g b)) b (𝓝 (max a₁ a₂)) := (continuous_max.tendsto (a₁, a₂)).comp (hf.prod_mk_nhds hg) lemma filter.tendsto.min {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) : tendsto (λb, min (f b) (g b)) b (𝓝 (min a₁ a₂)) := (continuous_min.tendsto (a₁, a₂)).comp (hf.prod_mk_nhds hg) lemma dense.exists_lt [no_min_order α] {s : set α} (hs : dense s) (x : α) : ∃ y ∈ s, y < x := hs.exists_mem_open is_open_Iio (exists_lt x) lemma dense.exists_gt [no_max_order α] {s : set α} (hs : dense s) (x : α) : ∃ y ∈ s, x < y := hs.order_dual.exists_lt x lemma dense.exists_le [no_min_order α] {s : set α} (hs : dense s) (x : α) : ∃ y ∈ s, y ≤ x := (hs.exists_lt x).imp $ λ y hy, ⟨hy.fst, hy.snd.le⟩ lemma dense.exists_ge [no_max_order α] {s : set α} (hs : dense s) (x : α) : ∃ y ∈ s, x ≤ y := hs.order_dual.exists_le x lemma dense.exists_le' {s : set α} (hs : dense s) (hbot : ∀ x, is_bot x → x ∈ s) (x : α) : ∃ y ∈ s, y ≤ x := begin by_cases hx : is_bot x, { exact ⟨x, hbot x hx, le_rfl⟩ }, { simp only [is_bot, not_forall, not_le] at hx, rcases hs.exists_mem_open is_open_Iio hx with ⟨y, hys, hy : y < x⟩, exact ⟨y, hys, hy.le⟩ } end lemma dense.exists_ge' {s : set α} (hs : dense s) (htop : ∀ x, is_top x → x ∈ s) (x : α) : ∃ y ∈ s, x ≤ y := hs.order_dual.exists_le' htop x lemma dense.exists_between [densely_ordered α] {s : set α} (hs : dense s) {x y : α} (h : x < y) : ∃ z ∈ s, z ∈ Ioo x y := hs.exists_mem_open is_open_Ioo (nonempty_Ioo.2 h) variables [nonempty α] [topological_space β] /-- A compact set is bounded below -/ lemma is_compact.bdd_below {s : set α} (hs : is_compact s) : bdd_below s := begin by_contra H, rcases hs.elim_finite_subcover_image (λ x (_ : x ∈ s), @is_open_Ioi _ _ _ _ x) _ with ⟨t, st, ft, ht⟩, { refine H (ft.bdd_below.imp $ λ C hC y hy, _), rcases mem_Union₂.1 (ht hy) with ⟨x, hx, xy⟩, exact le_trans (hC hx) (le_of_lt xy) }, { refine λ x hx, mem_Union₂.2 (not_imp_comm.1 _ H), exact λ h, ⟨x, λ y hy, le_of_not_lt (h.imp $ λ ys, ⟨_, hy, ys⟩)⟩ } end /-- A compact set is bounded above -/ lemma is_compact.bdd_above {s : set α} (hs : is_compact s) : bdd_above s := @is_compact.bdd_below αᵒᵈ _ _ _ _ _ hs /-- A continuous function is bounded below on a compact set. -/ lemma is_compact.bdd_below_image {f : β → α} {K : set β} (hK : is_compact K) (hf : continuous_on f K) : bdd_below (f '' K) := (hK.image_of_continuous_on hf).bdd_below /-- A continuous function is bounded above on a compact set. -/ lemma is_compact.bdd_above_image {f : β → α} {K : set β} (hK : is_compact K) (hf : continuous_on f K) : bdd_above (f '' K) := @is_compact.bdd_below_image αᵒᵈ _ _ _ _ _ _ _ _ hK hf /-- A continuous function with compact support is bounded below. -/ @[to_additive /-" A continuous function with compact support is bounded below. "-/] lemma continuous.bdd_below_range_of_has_compact_mul_support [has_one α] {f : β → α} (hf : continuous f) (h : has_compact_mul_support f) : bdd_below (range f) := (h.is_compact_range hf).bdd_below /-- A continuous function with compact support is bounded above. -/ @[to_additive /-" A continuous function with compact support is bounded above. "-/] lemma continuous.bdd_above_range_of_has_compact_mul_support [has_one α] {f : β → α} (hf : continuous f) (h : has_compact_mul_support f) : bdd_above (range f) := @continuous.bdd_below_range_of_has_compact_mul_support αᵒᵈ _ _ _ _ _ _ _ _ hf h end linear_order end order_closed_topology instance [preorder α] [topological_space α] [order_closed_topology α] [preorder β] [topological_space β] [order_closed_topology β] : order_closed_topology (α × β) := ⟨(is_closed_le (continuous_fst.comp continuous_fst) (continuous_fst.comp continuous_snd)).inter (is_closed_le (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd))⟩ instance {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] [Π i, topological_space (α i)] [Π i, order_closed_topology (α i)] : order_closed_topology (Π i, α i) := begin constructor, simp only [pi.le_def, set_of_forall], exact is_closed_Inter (λ i, is_closed_le ((continuous_apply i).comp continuous_fst) ((continuous_apply i).comp continuous_snd)) end instance pi.order_closed_topology' [preorder β] [topological_space β] [order_closed_topology β] : order_closed_topology (α → β) := pi.order_closed_topology /-- The order topology on an ordered type is the topology generated by open intervals. We register it on a preorder, but it is mostly interesting in linear orders, where it is also order-closed. We define it as a mixin. If you want to introduce the order topology on a preorder, use `preorder.topology`. -/ class order_topology (α : Type*) [t : topological_space α] [preorder α] : Prop := (topology_eq_generate_intervals : t = generate_from {s | ∃a, s = Ioi a ∨ s = Iio a}) /-- (Order) topology on a partial order `α` generated by the subbase of open intervals `(a, ∞) = { x ∣ a < x }, (-∞ , b) = {x ∣ x < b}` for all `a, b` in `α`. We do not register it as an instance as many ordered sets are already endowed with the same topology, most often in a non-defeq way though. Register as a local instance when necessary. -/ def preorder.topology (α : Type*) [preorder α] : topological_space α := generate_from {s : set α | ∃ (a : α), s = {b : α | a < b} ∨ s = {b : α | b < a}} section order_topology instance {α : Type*} [topological_space α] [partial_order α] [order_topology α] : order_topology αᵒᵈ := ⟨by convert @order_topology.topology_eq_generate_intervals α _ _ _; conv in (_ ∨ _) { rw or.comm }; refl⟩ section partial_order variables [topological_space α] [partial_order α] [t : order_topology α] include t lemma is_open_iff_generate_intervals {s : set α} : is_open s ↔ generate_open {s | ∃a, s = Ioi a ∨ s = Iio a} s := by rw [t.topology_eq_generate_intervals]; refl lemma is_open_lt' (a : α) : is_open {b:α | a < b} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inl rfl⟩ lemma is_open_gt' (a : α) : is_open {b:α | b < a} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inr rfl⟩ lemma lt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a < x := is_open.mem_nhds (is_open_lt' _) h lemma le_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a ≤ x := (𝓝 b).sets_of_superset (lt_mem_nhds h) $ assume b hb, le_of_lt hb lemma gt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x < b := is_open.mem_nhds (is_open_gt' _) h lemma ge_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x ≤ b := (𝓝 a).sets_of_superset (gt_mem_nhds h) $ assume b hb, le_of_lt hb lemma nhds_eq_order (a : α) : 𝓝 a = (⨅b ∈ Iio a, 𝓟 (Ioi b)) ⊓ (⨅b ∈ Ioi a, 𝓟 (Iio b)) := by rw [t.topology_eq_generate_intervals, nhds_generate_from]; from le_antisymm (le_inf (le_infi₂ $ assume b hb, infi_le_of_le {c : α | b < c} $ infi_le _ ⟨hb, b, or.inl rfl⟩) (le_infi₂ $ assume b hb, infi_le_of_le {c : α | c < b} $ infi_le _ ⟨hb, b, or.inr rfl⟩)) (le_infi $ assume s, le_infi $ assume ⟨ha, b, hs⟩, match s, ha, hs with | _, h, (or.inl rfl) := inf_le_of_left_le $ infi_le_of_le b $ infi_le _ h | _, h, (or.inr rfl) := inf_le_of_right_le $ infi_le_of_le b $ infi_le _ h end) lemma tendsto_order {f : β → α} {a : α} {x : filter β} : tendsto f x (𝓝 a) ↔ (∀ a' < a, ∀ᶠ b in x, a' < f b) ∧ (∀ a' > a, ∀ᶠ b in x, f b < a') := by simp [nhds_eq_order a, tendsto_inf, tendsto_infi, tendsto_principal] instance tendsto_Icc_class_nhds (a : α) : tendsto_Ixx_class Icc (𝓝 a) (𝓝 a) := begin simp only [nhds_eq_order, infi_subtype'], refine ((has_basis_infi_principal_finite _).inf (has_basis_infi_principal_finite _)).tendsto_Ixx_class (λ s hs, _), refine ((ord_connected_bInter _).inter (ord_connected_bInter _)).out; intros _ _, exacts [ord_connected_Ioi, ord_connected_Iio] end instance tendsto_Ico_class_nhds (a : α) : tendsto_Ixx_class Ico (𝓝 a) (𝓝 a) := tendsto_Ixx_class_of_subset (λ _ _, Ico_subset_Icc_self) instance tendsto_Ioc_class_nhds (a : α) : tendsto_Ixx_class Ioc (𝓝 a) (𝓝 a) := tendsto_Ixx_class_of_subset (λ _ _, Ioc_subset_Icc_self) instance tendsto_Ioo_class_nhds (a : α) : tendsto_Ixx_class Ioo (𝓝 a) (𝓝 a) := tendsto_Ixx_class_of_subset (λ _ _, Ioo_subset_Icc_self) /-- **Squeeze theorem** (also known as **sandwich theorem**). This version assumes that inequalities hold eventually for the filter. -/ lemma tendsto_of_tendsto_of_tendsto_of_le_of_le' {f g h : β → α} {b : filter β} {a : α} (hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a)) (hgf : ∀ᶠ b in b, g b ≤ f b) (hfh : ∀ᶠ b in b, f b ≤ h b) : tendsto f b (𝓝 a) := (hg.Icc hh).of_small_sets $ hgf.and hfh /-- **Squeeze theorem** (also known as **sandwich theorem**). This version assumes that inequalities hold everywhere. -/ lemma tendsto_of_tendsto_of_tendsto_of_le_of_le {f g h : β → α} {b : filter β} {a : α} (hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a)) (hgf : g ≤ f) (hfh : f ≤ h) : tendsto f b (𝓝 a) := tendsto_of_tendsto_of_tendsto_of_le_of_le' hg hh (eventually_of_forall hgf) (eventually_of_forall hfh) lemma nhds_order_unbounded {a : α} (hu : ∃u, a < u) (hl : ∃l, l < a) : 𝓝 a = (⨅l (h₂ : l < a) u (h₂ : a < u), 𝓟 (Ioo l u)) := have ∃ u, u ∈ Ioi a, from hu, have ∃ l, l ∈ Iio a, from hl, by { simp only [nhds_eq_order, inf_binfi, binfi_inf, *, inf_principal, Ioi_inter_Iio], refl } lemma tendsto_order_unbounded {f : β → α} {a : α} {x : filter β} (hu : ∃u, a < u) (hl : ∃l, l < a) (h : ∀l u, l < a → a < u → ∀ᶠ b in x, l < f b ∧ f b < u) : tendsto f x (𝓝 a) := by rw [nhds_order_unbounded hu hl]; from (tendsto_infi.2 $ assume l, tendsto_infi.2 $ assume hl, tendsto_infi.2 $ assume u, tendsto_infi.2 $ assume hu, tendsto_principal.2 $ h l u hl hu) end partial_order instance tendsto_Ixx_nhds_within {α : Type*} [preorder α] [topological_space α] (a : α) {s t : set α} {Ixx} [tendsto_Ixx_class Ixx (𝓝 a) (𝓝 a)] [tendsto_Ixx_class Ixx (𝓟 s) (𝓟 t)]: tendsto_Ixx_class Ixx (𝓝[s] a) (𝓝[t] a) := filter.tendsto_Ixx_class_inf instance tendsto_Icc_class_nhds_pi {ι : Type*} {α : ι → Type*} [Π i, partial_order (α i)] [Π i, topological_space (α i)] [∀ i, order_topology (α i)] (f : Π i, α i) : tendsto_Ixx_class Icc (𝓝 f) (𝓝 f) := begin constructor, conv in ((𝓝 f).small_sets) { rw [nhds_pi, filter.pi] }, simp only [small_sets_infi, small_sets_comap, tendsto_infi, tendsto_lift', (∘), mem_powerset_iff], intros i s hs, have : tendsto (λ g : Π i, α i, g i) (𝓝 f) (𝓝 (f i)) := ((continuous_apply i).tendsto f), refine (tendsto_lift'.1 ((this.comp tendsto_fst).Icc (this.comp tendsto_snd)) s hs).mono _, exact λ p hp g hg, hp ⟨hg.1 _, hg.2 _⟩ end theorem induced_order_topology' {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [order_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H₁ : ∀ {a x}, x < f a → ∃ b < a, x ≤ f b) (H₂ : ∀ {a x}, f a < x → ∃ b > a, f b ≤ x) : @order_topology _ (induced f ta) _ := begin letI := induced f ta, refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩, rw [nhds_induced, nhds_generate_from, nhds_eq_order (f a)], apply le_antisymm, { refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _), rcases hs with ⟨ab, b, rfl|rfl⟩, { exact mem_comap.2 ⟨{x | f b < x}, mem_inf_of_left $ mem_infi_of_mem _ $ mem_infi_of_mem (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ }, { exact mem_comap.2 ⟨{x | x < f b}, mem_inf_of_right $ mem_infi_of_mem _ $ mem_infi_of_mem (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ } }, { rw [← map_le_iff_le_comap], refine le_inf _ _; refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _); simp, { rcases H₁ h with ⟨b, ab, xb⟩, refine mem_infi_of_mem _ (mem_infi_of_mem ⟨ab, b, or.inl rfl⟩ (mem_principal.2 _)), exact λ c hc, lt_of_le_of_lt xb (hf.2 hc) }, { rcases H₂ h with ⟨b, ab, xb⟩, refine mem_infi_of_mem _ (mem_infi_of_mem ⟨ab, b, or.inr rfl⟩ (mem_principal.2 _)), exact λ c hc, lt_of_lt_of_le (hf.2 hc) xb } }, end theorem induced_order_topology {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [order_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H : ∀ {x y}, x < y → ∃ a, x < f a ∧ f a < y) : @order_topology _ (induced f ta) _ := induced_order_topology' f @hf (λ a x xa, let ⟨b, xb, ba⟩ := H xa in ⟨b, hf.1 ba, le_of_lt xb⟩) (λ a x ax, let ⟨b, ab, bx⟩ := H ax in ⟨b, hf.1 ab, le_of_lt bx⟩) /-- On an `ord_connected` subset of a linear order, the order topology for the restriction of the order is the same as the restriction to the subset of the order topology. -/ instance order_topology_of_ord_connected {α : Type u} [ta : topological_space α] [linear_order α] [order_topology α] {t : set α} [ht : ord_connected t] : order_topology t := begin letI := induced (coe : t → α) ta, refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩, rw [nhds_induced, nhds_generate_from, nhds_eq_order (a : α)], apply le_antisymm, { refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _), rcases hs with ⟨ab, b, rfl|rfl⟩, { refine ⟨Ioi b, _, λ _, id⟩, refine mem_inf_of_left (mem_infi_of_mem b _), exact mem_infi_of_mem ab (mem_principal_self (Ioi ↑b)) }, { refine ⟨Iio b, _, λ _, id⟩, refine mem_inf_of_right (mem_infi_of_mem b _), exact mem_infi_of_mem ab (mem_principal_self (Iio b)) } }, { rw [← map_le_iff_le_comap], refine le_inf _ _, { refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _), by_cases hx : x ∈ t, { refine mem_infi_of_mem (Ioi ⟨x, hx⟩) (mem_infi_of_mem ⟨h, ⟨⟨x, hx⟩, or.inl rfl⟩⟩ _), exact λ _, id }, simp only [set_coe.exists, mem_set_of_eq, mem_map'], convert univ_sets _, suffices hx' : ∀ (y : t), ↑y ∈ Ioi x, { simp [hx'] }, intros y, revert hx, contrapose!, -- here we use the `ord_connected` hypothesis exact λ hx, ht.out y.2 a.2 ⟨le_of_not_gt hx, le_of_lt h⟩ }, { refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _), by_cases hx : x ∈ t, { refine mem_infi_of_mem (Iio ⟨x, hx⟩) (mem_infi_of_mem ⟨h, ⟨⟨x, hx⟩, or.inr rfl⟩⟩ _), exact λ _, id }, simp only [set_coe.exists, mem_set_of_eq, mem_map'], convert univ_sets _, suffices hx' : ∀ (y : t), ↑y ∈ Iio x, { simp [hx'] }, intros y, revert hx, contrapose!, -- here we use the `ord_connected` hypothesis exact λ hx, ht.out a.2 y.2 ⟨le_of_lt h, le_of_not_gt hx⟩ } } end lemma nhds_within_Ici_eq'' [topological_space α] [partial_order α] [order_topology α] (a : α) : 𝓝[≥] a = (⨅ u (hu : a < u), 𝓟 (Iio u)) ⊓ 𝓟 (Ici a) := begin rw [nhds_within, nhds_eq_order], refine le_antisymm (inf_le_inf_right _ inf_le_right) (le_inf (le_inf _ inf_le_left) inf_le_right), exact inf_le_right.trans (le_infi₂ $ λ l hl, principal_mono.2 $ Ici_subset_Ioi.2 hl) end lemma nhds_within_Iic_eq'' [topological_space α] [partial_order α] [order_topology α] (a : α) : 𝓝[≤] a = (⨅ l < a, 𝓟 (Ioi l)) ⊓ 𝓟 (Iic a) := nhds_within_Ici_eq'' (to_dual a) lemma nhds_within_Ici_eq' [topological_space α] [partial_order α] [order_topology α] {a : α} (ha : ∃ u, a < u) : 𝓝[≥] a = ⨅ u (hu : a < u), 𝓟 (Ico a u) := by simp only [nhds_within_Ici_eq'', binfi_inf ha, inf_principal, Iio_inter_Ici] lemma nhds_within_Iic_eq' [topological_space α] [partial_order α] [order_topology α] {a : α} (ha : ∃ l, l < a) : 𝓝[≤] a = ⨅ l < a, 𝓟 (Ioc l a) := by simp only [nhds_within_Iic_eq'', binfi_inf ha, inf_principal, Ioi_inter_Iic] lemma nhds_within_Ici_basis' [topological_space α] [linear_order α] [order_topology α] {a : α} (ha : ∃ u, a < u) : (𝓝[≥] a).has_basis (λ u, a < u) (λ u, Ico a u) := (nhds_within_Ici_eq' ha).symm ▸ has_basis_binfi_principal (λ b hb c hc, ⟨min b c, lt_min hb hc, Ico_subset_Ico_right (min_le_left _ _), Ico_subset_Ico_right (min_le_right _ _)⟩) ha lemma nhds_within_Iic_basis' [topological_space α] [linear_order α] [order_topology α] {a : α} (ha : ∃ l, l < a) : (𝓝[≤] a).has_basis (λ l, l < a) (λ l, Ioc l a) := by { convert @nhds_within_Ici_basis' αᵒᵈ _ _ _ (to_dual a) ha, exact funext (λ x, (@dual_Ico _ _ _ _).symm) } lemma nhds_within_Ici_basis [topological_space α] [linear_order α] [order_topology α] [no_max_order α] (a : α) : (𝓝[≥] a).has_basis (λ u, a < u) (λ u, Ico a u) := nhds_within_Ici_basis' (exists_gt a) lemma nhds_within_Iic_basis [topological_space α] [linear_order α] [order_topology α] [no_min_order α] (a : α) : (𝓝[≤] a).has_basis (λ l, l < a) (λ l, Ioc l a) := nhds_within_Iic_basis' (exists_lt a) lemma nhds_top_order [topological_space α] [partial_order α] [order_top α] [order_topology α] : 𝓝 (⊤:α) = (⨅l (h₂ : l < ⊤), 𝓟 (Ioi l)) := by simp [nhds_eq_order (⊤:α)] lemma nhds_bot_order [topological_space α] [partial_order α] [order_bot α] [order_topology α] : 𝓝 (⊥:α) = (⨅l (h₂ : ⊥ < l), 𝓟 (Iio l)) := by simp [nhds_eq_order (⊥:α)] lemma nhds_top_basis [topological_space α] [linear_order α] [order_top α] [order_topology α] [nontrivial α] : (𝓝 ⊤).has_basis (λ a : α, a < ⊤) (λ a : α, Ioi a) := have ∃ x : α, x < ⊤, from (exists_ne ⊤).imp $ λ x hx, hx.lt_top, by simpa only [Iic_top, nhds_within_univ, Ioc_top] using nhds_within_Iic_basis' this lemma nhds_bot_basis [topological_space α] [linear_order α] [order_bot α] [order_topology α] [nontrivial α] : (𝓝 ⊥).has_basis (λ a : α, ⊥ < a) (λ a : α, Iio a) := @nhds_top_basis αᵒᵈ _ _ _ _ _ lemma nhds_top_basis_Ici [topological_space α] [linear_order α] [order_top α] [order_topology α] [nontrivial α] [densely_ordered α] : (𝓝 ⊤).has_basis (λ a : α, a < ⊤) Ici := nhds_top_basis.to_has_basis (λ a ha, let ⟨b, hab, hb⟩ := exists_between ha in ⟨b, hb, Ici_subset_Ioi.mpr hab⟩) (λ a ha, ⟨a, ha, Ioi_subset_Ici_self⟩) lemma nhds_bot_basis_Iic [topological_space α] [linear_order α] [order_bot α] [order_topology α] [nontrivial α] [densely_ordered α] : (𝓝 ⊥).has_basis (λ a : α, ⊥ < a) Iic := @nhds_top_basis_Ici αᵒᵈ _ _ _ _ _ _ lemma tendsto_nhds_top_mono [topological_space β] [partial_order β] [order_top β] [order_topology β] {l : filter α} {f g : α → β} (hf : tendsto f l (𝓝 ⊤)) (hg : f ≤ᶠ[l] g) : tendsto g l (𝓝 ⊤) := begin simp only [nhds_top_order, tendsto_infi, tendsto_principal] at hf ⊢, intros x hx, filter_upwards [hf x hx, hg] with _ using lt_of_lt_of_le, end lemma tendsto_nhds_bot_mono [topological_space β] [partial_order β] [order_bot β] [order_topology β] {l : filter α} {f g : α → β} (hf : tendsto f l (𝓝 ⊥)) (hg : g ≤ᶠ[l] f) : tendsto g l (𝓝 ⊥) := @tendsto_nhds_top_mono α βᵒᵈ _ _ _ _ _ _ _ hf hg lemma tendsto_nhds_top_mono' [topological_space β] [partial_order β] [order_top β] [order_topology β] {l : filter α} {f g : α → β} (hf : tendsto f l (𝓝 ⊤)) (hg : f ≤ g) : tendsto g l (𝓝 ⊤) := tendsto_nhds_top_mono hf (eventually_of_forall hg) lemma tendsto_nhds_bot_mono' [topological_space β] [partial_order β] [order_bot β] [order_topology β] {l : filter α} {f g : α → β} (hf : tendsto f l (𝓝 ⊥)) (hg : g ≤ f) : tendsto g l (𝓝 ⊥) := tendsto_nhds_bot_mono hf (eventually_of_forall hg) section linear_order variables [topological_space α] [linear_order α] section order_closed_topology variables [order_closed_topology α] {a b : α} lemma eventually_le_nhds (hab : a < b) : ∀ᶠ x in 𝓝 a, x ≤ b := eventually_iff.mpr (mem_nhds_iff.mpr ⟨Iio b, Iio_subset_Iic_self, is_open_Iio, hab⟩) lemma eventually_lt_nhds (hab : a < b) : ∀ᶠ x in 𝓝 a, x < b := eventually_iff.mpr (mem_nhds_iff.mpr ⟨Iio b, rfl.subset, is_open_Iio, hab⟩) lemma eventually_ge_nhds (hab : b < a) : ∀ᶠ x in 𝓝 a, b ≤ x := eventually_iff.mpr (mem_nhds_iff.mpr ⟨Ioi b, Ioi_subset_Ici_self, is_open_Ioi, hab⟩) lemma eventually_gt_nhds (hab : b < a) : ∀ᶠ x in 𝓝 a, b < x := eventually_iff.mpr (mem_nhds_iff.mpr ⟨Ioi b, rfl.subset, is_open_Ioi, hab⟩) end order_closed_topology section order_topology variables [order_topology α] lemma order_separated {a₁ a₂ : α} (h : a₁ < a₂) : ∃u v : set α, is_open u ∧ is_open v ∧ a₁ ∈ u ∧ a₂ ∈ v ∧ (∀b₁∈u, ∀b₂∈v, b₁ < b₂) := match dense_or_discrete a₁ a₂ with | or.inl ⟨a, ha₁, ha₂⟩ := ⟨{a' | a' < a}, {a' | a < a'}, is_open_gt' a, is_open_lt' a, ha₁, ha₂, assume b₁ h₁ b₂ h₂, lt_trans h₁ h₂⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a | a < a₂}, {a | a₁ < a}, is_open_gt' a₂, is_open_lt' a₁, h, h, assume b₁ hb₁ b₂ hb₂, calc b₁ ≤ a₁ : h₂ _ hb₁ ... < a₂ : h ... ≤ b₂ : h₁ _ hb₂⟩ end @[priority 100] -- see Note [lower instance priority] instance order_topology.to_order_closed_topology : order_closed_topology α := { is_closed_le' := is_open_compl_iff.1 $ is_open_prod_iff.mpr $ assume a₁ a₂ (h : ¬ a₁ ≤ a₂), have h : a₂ < a₁, from lt_of_not_ge h, let ⟨u, v, hu, hv, ha₁, ha₂, h⟩ := order_separated h in ⟨v, u, hv, hu, ha₂, ha₁, assume ⟨b₁, b₂⟩ ⟨h₁, h₂⟩, not_le_of_gt $ h b₂ h₂ b₁ h₁⟩ } lemma exists_Ioc_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ l, l < a) : ∃ l < a, Ioc l a ⊆ s := (nhds_within_Iic_basis' h).mem_iff.mp (nhds_within_le_nhds hs) lemma exists_Ioc_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {l : α} (hl : l < a) : ∃ l' ∈ Ico l a, Ioc l' a ⊆ s := let ⟨l', hl'a, hl's⟩ := exists_Ioc_subset_of_mem_nhds hs ⟨l, hl⟩ in ⟨max l l', ⟨le_max_left _ _, max_lt hl hl'a⟩, (Ioc_subset_Ioc_left $ le_max_right _ _).trans hl's⟩ lemma exists_Ico_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {u : α} (hu : a < u) : ∃ u' ∈ Ioc a u, Ico a u' ⊆ s := by simpa only [order_dual.exists, exists_prop, dual_Ico, dual_Ioc] using exists_Ioc_subset_of_mem_nhds' (show of_dual ⁻¹' s ∈ 𝓝 (to_dual a), from hs) hu.dual lemma exists_Ico_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ u, a < u) : ∃ u (_ : a < u), Ico a u ⊆ s := let ⟨l', hl'⟩ := h, ⟨l, hl⟩ := exists_Ico_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.1, hl.snd⟩ lemma exists_Icc_mem_subset_of_mem_nhds_within_Ici {a : α} {s : set α} (hs : s ∈ 𝓝[≥] a) : ∃ b (_ : a ≤ b), Icc a b ∈ 𝓝[≥] a ∧ Icc a b ⊆ s := begin rcases (em (is_max a)).imp_right not_is_max_iff.mp with ha|ha, { use a, simpa [ha.Ici_eq] using hs }, { rcases (nhds_within_Ici_basis' ha).mem_iff.mp hs with ⟨b, hab, hbs⟩, rcases eq_empty_or_nonempty (Ioo a b) with H|⟨c, hac, hcb⟩, { have : Ico a b = Icc a a, { rw [← Icc_union_Ioo_eq_Ico le_rfl hab, H, union_empty] }, exact ⟨a, le_rfl, this ▸ ⟨Ico_mem_nhds_within_Ici $ left_mem_Ico.2 hab, hbs⟩⟩ }, { refine ⟨c, hac.le, Icc_mem_nhds_within_Ici $ left_mem_Ico.mpr hac, _⟩, exact (Icc_subset_Ico_right hcb).trans hbs } } end lemma exists_Icc_mem_subset_of_mem_nhds_within_Iic {a : α} {s : set α} (hs : s ∈ 𝓝[≤] a) : ∃ b ≤ a, Icc b a ∈ 𝓝[≤] a ∧ Icc b a ⊆ s := by simpa only [dual_Icc, to_dual.surjective.exists] using @exists_Icc_mem_subset_of_mem_nhds_within_Ici αᵒᵈ _ _ _ (to_dual a) _ hs lemma exists_Icc_mem_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) : ∃ b c, a ∈ Icc b c ∧ Icc b c ∈ 𝓝 a ∧ Icc b c ⊆ s := begin rcases exists_Icc_mem_subset_of_mem_nhds_within_Iic (nhds_within_le_nhds hs) with ⟨b, hba, hb_nhds, hbs⟩, rcases exists_Icc_mem_subset_of_mem_nhds_within_Ici (nhds_within_le_nhds hs) with ⟨c, hac, hc_nhds, hcs⟩, refine ⟨b, c, ⟨hba, hac⟩, _⟩, rw [← Icc_union_Icc_eq_Icc hba hac, ← nhds_left_sup_nhds_right], exact ⟨union_mem_sup hb_nhds hc_nhds, union_subset hbs hcs⟩ end lemma is_open.exists_Ioo_subset [nontrivial α] {s : set α} (hs : is_open s) (h : s.nonempty) : ∃ a b, a < b ∧ Ioo a b ⊆ s := begin obtain ⟨x, hx⟩ : ∃ x, x ∈ s := h, obtain ⟨y, hy⟩ : ∃ y, y ≠ x := exists_ne x, rcases lt_trichotomy x y with H|rfl|H, { obtain ⟨u, xu, hu⟩ : ∃ (u : α) (hu : x < u), Ico x u ⊆ s := exists_Ico_subset_of_mem_nhds (hs.mem_nhds hx) ⟨y, H⟩, exact ⟨x, u, xu, Ioo_subset_Ico_self.trans hu⟩ }, { exact (hy rfl).elim }, { obtain ⟨l, lx, hl⟩ : ∃ (l : α) (hl : l < x), Ioc l x ⊆ s := exists_Ioc_subset_of_mem_nhds (hs.mem_nhds hx) ⟨y, H⟩, exact ⟨l, x, lx, Ioo_subset_Ioc_self.trans hl⟩ } end lemma dense_of_exists_between [nontrivial α] {s : set α} (h : ∀ ⦃a b⦄, a < b → ∃ c ∈ s, a < c ∧ c < b) : dense s := begin apply dense_iff_inter_open.2 (λ U U_open U_nonempty, _), obtain ⟨a, b, hab, H⟩ : ∃ (a b : α), a < b ∧ Ioo a b ⊆ U := U_open.exists_Ioo_subset U_nonempty, obtain ⟨x, xs, hx⟩ : ∃ (x : α) (H : x ∈ s), a < x ∧ x < b := h hab, exact ⟨x, ⟨H hx, xs⟩⟩ end /-- A set in a nontrivial densely linear ordered type is dense in the sense of topology if and only if for any `a < b` there exists `c ∈ s`, `a < c < b`. Each implication requires less typeclass assumptions. -/ lemma dense_iff_exists_between [densely_ordered α] [nontrivial α] {s : set α} : dense s ↔ ∀ a b, a < b → ∃ c ∈ s, a < c ∧ c < b := ⟨λ h a b hab, h.exists_between hab, dense_of_exists_between⟩ @[priority 100] -- see Note [lower instance priority] instance order_topology.t3_space : t3_space α := begin refine ⟨λ s a hs ha, _⟩, have : sᶜ ∈ 𝓝 a, from hs.is_open_compl.mem_nhds ha, rcases exists_Icc_mem_subset_of_mem_nhds this with ⟨b, c, -, hmem, hsub⟩, refine ⟨(Icc b c)ᶜ, is_closed_Icc.is_open_compl, subset_compl_comm.2 hsub, _⟩, rwa [nhds_within, inf_principal_eq_bot, compl_compl] end /-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`, provided `a` is neither a bottom element nor a top element. -/ lemma mem_nhds_iff_exists_Ioo_subset' {a : α} {s : set α} (hl : ∃ l, l < a) (hu : ∃ u, a < u) : s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s := begin split, { assume h, rcases exists_Ico_subset_of_mem_nhds h hu with ⟨u, au, hu⟩, rcases exists_Ioc_subset_of_mem_nhds h hl with ⟨l, la, hl⟩, exact ⟨l, u, ⟨la, au⟩, Ioc_union_Ico_eq_Ioo la au ▸ union_subset hl hu⟩ }, { rintros ⟨l, u, ha, h⟩, apply mem_of_superset (Ioo_mem_nhds ha.1 ha.2) h } end /-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`. -/ lemma mem_nhds_iff_exists_Ioo_subset [no_max_order α] [no_min_order α] {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s := mem_nhds_iff_exists_Ioo_subset' (exists_lt a) (exists_gt a) lemma nhds_basis_Ioo' {a : α} (hl : ∃ l, l < a) (hu : ∃ u, a < u) : (𝓝 a).has_basis (λ b : α × α, b.1 < a ∧ a < b.2) (λ b, Ioo b.1 b.2) := ⟨λ s, (mem_nhds_iff_exists_Ioo_subset' hl hu).trans $ by simp⟩ lemma nhds_basis_Ioo [no_max_order α] [no_min_order α] (a : α) : (𝓝 a).has_basis (λ b : α × α, b.1 < a ∧ a < b.2) (λ b, Ioo b.1 b.2) := nhds_basis_Ioo' (exists_lt a) (exists_gt a) lemma filter.eventually.exists_Ioo_subset [no_max_order α] [no_min_order α] {a : α} {p : α → Prop} (hp : ∀ᶠ x in 𝓝 a, p x) : ∃ l u, a ∈ Ioo l u ∧ Ioo l u ⊆ {x | p x} := mem_nhds_iff_exists_Ioo_subset.1 hp /-- The set of points which are isolated on the right is countable when the space is second-countable. -/ lemma countable_of_isolated_right [second_countable_topology α] : set.countable {x : α | ∃ y, x < y ∧ Ioo x y = ∅} := begin nontriviality α, let s := {x : α | ∃ y, x < y ∧ Ioo x y = ∅}, have : ∀ x ∈ s, ∃ y, x < y ∧ Ioo x y = ∅ := λ x, id, choose! y hy h'y using this, have Hy : ∀ x z, x ∈ s → z < y x → z ≤ x, { assume x z xs hz, have A : Ioo x (y x) = ∅ := h'y _ xs, contrapose! A, exact ne_empty_iff_nonempty.2 ⟨z, A, hz⟩ }, suffices H : ∀ (a : set α), is_open a → set.countable {x | x ∈ s ∧ x ∈ a ∧ y x ∉ a}, { have : s ⊆ ⋃ (a ∈ countable_basis α), {x | x ∈ s ∧ x ∈ a ∧ y x ∉ a}, { assume x hx, rcases (is_basis_countable_basis α).exists_mem_of_ne (hy x hx).ne with ⟨a, ab, xa, ya⟩, simp only [mem_set_of_eq, mem_Union], exact ⟨a, ab, hx, xa, ya⟩ }, apply countable.mono this, refine countable.bUnion (countable_countable_basis α) (λ a ha, H _ _), exact is_open_of_mem_countable_basis ha }, assume a ha, suffices H : set.countable {x | x ∈ s ∧ x ∈ a ∧ y x ∉ a ∧ ¬(is_bot x)}, { have : {x | x ∈ s ∧ x ∈ a ∧ y x ∉ a} ⊆ {x | x ∈ s ∧ x ∈ a ∧ y x ∉ a ∧ ¬(is_bot x)} ∪ {x | is_bot x}, { assume x hx, by_cases h'x : is_bot x, { simp only [h'x, mem_set_of_eq, mem_union_eq, not_true, and_false, false_or] }, { simpa only [h'x, hx.2.1, hx.2.2, mem_set_of_eq, mem_union_eq, not_false_iff, and_true, or_false] using hx.left } }, exact countable.mono this (H.union (subsingleton_is_bot α).countable) }, let t := {x | x ∈ s ∧ x ∈ a ∧ y x ∉ a ∧ ¬(is_bot x)}, have : ∀ x ∈ t, ∃ z < x, Ioc z x ⊆ a, { assume x hx, apply exists_Ioc_subset_of_mem_nhds (ha.mem_nhds hx.2.1), simpa only [is_bot, not_forall, not_le] using hx.right.right.right }, choose! z hz h'z using this, have : pairwise_disjoint t (λ x, Ioc (z x) x), { assume x xt x' x't hxx', rcases lt_or_gt_of_ne hxx' with h'|h', { refine disjoint_left.2 (λ u ux ux', xt.2.2.1 _), refine h'z x' x't ⟨ux'.1.trans_le (ux.2.trans (hy x xt.1).le), _⟩, by_contra' H, exact false.elim (lt_irrefl _ ((Hy _ _ xt.1 H).trans_lt h')) }, { refine disjoint_left.2 (λ u ux ux', x't.2.2.1 _), refine h'z x xt ⟨ux.1.trans_le (ux'.2.trans (hy x' x't.1).le), _⟩, by_contra' H, exact false.elim (lt_irrefl _ ((Hy _ _ x't.1 H).trans_lt h')) } }, refine this.countable_of_is_open (λ x hx, _) (λ x hx, ⟨x, hz x hx, le_rfl⟩), suffices H : Ioc (z x) x = Ioo (z x) (y x), { rw H, exact is_open_Ioo }, exact subset.antisymm (Ioc_subset_Ioo_right (hy x hx.1)) (λ u hu, ⟨hu.1, Hy _ _ hx.1 hu.2⟩), end /-- The set of points which are isolated on the left is countable when the space is second-countable. -/ lemma countable_of_isolated_left [second_countable_topology α] : set.countable {x : α | ∃ y, y < x ∧ Ioo y x = ∅} := begin convert @countable_of_isolated_right αᵒᵈ _ _ _ _, have : ∀ (x y : α), Ioo x y = {z | z < y ∧ x < z}, { simp_rw [and_comm, Ioo], simp only [eq_self_iff_true, forall_2_true_iff] }, simp_rw [this], refl end /-- Consider a disjoint family of intervals `(x, y)` with `x < y` in a second-countable space. Then the family is countable. This is not a straightforward consequence of second-countability as some of these intervals might be empty (but in fact this can happen only for countably many of them). -/ lemma set.pairwise_disjoint.countable_of_Ioo [second_countable_topology α] {y : α → α} {s : set α} (h : pairwise_disjoint s (λ x, Ioo x (y x))) (h' : ∀ x ∈ s, x < y x) : s.countable := begin let t := {x | x ∈ s ∧ (Ioo x (y x)).nonempty}, have t_count : t.countable, { have : t ⊆ s := λ x hx, hx.1, exact (h.subset this).countable_of_is_open (λ x hx, is_open_Ioo) (λ x hx, hx.2) }, have : s ⊆ t ∪ {x : α | ∃ x', x < x' ∧ Ioo x x' = ∅}, { assume x hx, by_cases h'x : (Ioo x (y x)).nonempty, { exact or.inl ⟨hx, h'x⟩ }, { exact or.inr ⟨y x, h' x hx, not_nonempty_iff_eq_empty.1 h'x⟩ } }, exact countable.mono this (t_count.union countable_of_isolated_right), end section pi /-! ### Intervals in `Π i, π i` belong to `𝓝 x` For each lemma `pi_Ixx_mem_nhds` we add a non-dependent version `pi_Ixx_mem_nhds'` because sometimes Lean fails to unify different instances while trying to apply the dependent version to, e.g., `ι → ℝ`. -/ variables {ι : Type*} {π : ι → Type*} [finite ι] [Π i, linear_order (π i)] [Π i, topological_space (π i)] [∀ i, order_topology (π i)] {a b x : Π i, π i} {a' b' x' : ι → α} lemma pi_Iic_mem_nhds (ha : ∀ i, x i < a i) : Iic a ∈ 𝓝 x := pi_univ_Iic a ▸ set_pi_mem_nhds (set.to_finite _) (λ i _, Iic_mem_nhds (ha _)) lemma pi_Iic_mem_nhds' (ha : ∀ i, x' i < a' i) : Iic a' ∈ 𝓝 x' := pi_Iic_mem_nhds ha lemma pi_Ici_mem_nhds (ha : ∀ i, a i < x i) : Ici a ∈ 𝓝 x := pi_univ_Ici a ▸ set_pi_mem_nhds (set.to_finite _) (λ i _, Ici_mem_nhds (ha _)) lemma pi_Ici_mem_nhds' (ha : ∀ i, a' i < x' i) : Ici a' ∈ 𝓝 x' := pi_Ici_mem_nhds ha lemma pi_Icc_mem_nhds (ha : ∀ i, a i < x i) (hb : ∀ i, x i < b i) : Icc a b ∈ 𝓝 x := pi_univ_Icc a b ▸ set_pi_mem_nhds finite_univ (λ i _, Icc_mem_nhds (ha _) (hb _)) lemma pi_Icc_mem_nhds' (ha : ∀ i, a' i < x' i) (hb : ∀ i, x' i < b' i) : Icc a' b' ∈ 𝓝 x' := pi_Icc_mem_nhds ha hb variables [nonempty ι] lemma pi_Iio_mem_nhds (ha : ∀ i, x i < a i) : Iio a ∈ 𝓝 x := begin refine mem_of_superset (set_pi_mem_nhds (set.to_finite _) (λ i _, _)) (pi_univ_Iio_subset a), exact Iio_mem_nhds (ha i) end lemma pi_Iio_mem_nhds' (ha : ∀ i, x' i < a' i) : Iio a' ∈ 𝓝 x' := pi_Iio_mem_nhds ha lemma pi_Ioi_mem_nhds (ha : ∀ i, a i < x i) : Ioi a ∈ 𝓝 x := @pi_Iio_mem_nhds ι (λ i, (π i)ᵒᵈ) _ _ _ _ _ _ _ ha lemma pi_Ioi_mem_nhds' (ha : ∀ i, a' i < x' i) : Ioi a' ∈ 𝓝 x' := pi_Ioi_mem_nhds ha lemma pi_Ioc_mem_nhds (ha : ∀ i, a i < x i) (hb : ∀ i, x i < b i) : Ioc a b ∈ 𝓝 x := begin refine mem_of_superset (set_pi_mem_nhds (set.to_finite _) (λ i _, _)) (pi_univ_Ioc_subset a b), exact Ioc_mem_nhds (ha i) (hb i) end lemma pi_Ioc_mem_nhds' (ha : ∀ i, a' i < x' i) (hb : ∀ i, x' i < b' i) : Ioc a' b' ∈ 𝓝 x' := pi_Ioc_mem_nhds ha hb lemma pi_Ico_mem_nhds (ha : ∀ i, a i < x i) (hb : ∀ i, x i < b i) : Ico a b ∈ 𝓝 x := begin refine mem_of_superset (set_pi_mem_nhds (set.to_finite _) (λ i _, _)) (pi_univ_Ico_subset a b), exact Ico_mem_nhds (ha i) (hb i) end lemma pi_Ico_mem_nhds' (ha : ∀ i, a' i < x' i) (hb : ∀ i, x' i < b' i) : Ico a' b' ∈ 𝓝 x' := pi_Ico_mem_nhds ha hb lemma pi_Ioo_mem_nhds (ha : ∀ i, a i < x i) (hb : ∀ i, x i < b i) : Ioo a b ∈ 𝓝 x := begin refine mem_of_superset (set_pi_mem_nhds (set.to_finite _) (λ i _, _)) (pi_univ_Ioo_subset a b), exact Ioo_mem_nhds (ha i) (hb i) end lemma pi_Ioo_mem_nhds' (ha : ∀ i, a' i < x' i) (hb : ∀ i, x' i < b' i) : Ioo a' b' ∈ 𝓝 x' := pi_Ioo_mem_nhds ha hb end pi lemma disjoint_nhds_at_top [no_max_order α] (x : α) : disjoint (𝓝 x) at_top := begin rcases exists_gt x with ⟨y, hy : x < y⟩, refine disjoint_of_disjoint_of_mem _ (Iio_mem_nhds hy) (mem_at_top y), exact disjoint_left.mpr (λ z, not_le.2) end @[simp] lemma inf_nhds_at_top [no_max_order α] (x : α) : 𝓝 x ⊓ at_top = ⊥ := disjoint_iff.1 (disjoint_nhds_at_top x) lemma disjoint_nhds_at_bot [no_min_order α] (x : α) : disjoint (𝓝 x) at_bot := @disjoint_nhds_at_top αᵒᵈ _ _ _ _ x @[simp] lemma inf_nhds_at_bot [no_min_order α] (x : α) : 𝓝 x ⊓ at_bot = ⊥ := @inf_nhds_at_top αᵒᵈ _ _ _ _ x lemma not_tendsto_nhds_of_tendsto_at_top [no_max_order α] {F : filter β} [ne_bot F] {f : β → α} (hf : tendsto f F at_top) (x : α) : ¬ tendsto f F (𝓝 x) := hf.not_tendsto (disjoint_nhds_at_top x).symm lemma not_tendsto_at_top_of_tendsto_nhds [no_max_order α] {F : filter β} [ne_bot F] {f : β → α} {x : α} (hf : tendsto f F (𝓝 x)) : ¬ tendsto f F at_top := hf.not_tendsto (disjoint_nhds_at_top x) lemma not_tendsto_nhds_of_tendsto_at_bot [no_min_order α] {F : filter β} [ne_bot F] {f : β → α} (hf : tendsto f F at_bot) (x : α) : ¬ tendsto f F (𝓝 x) := hf.not_tendsto (disjoint_nhds_at_bot x).symm lemma not_tendsto_at_bot_of_tendsto_nhds [no_min_order α] {F : filter β} [ne_bot F] {f : β → α} {x : α} (hf : tendsto f F (𝓝 x)) : ¬ tendsto f F at_bot := hf.not_tendsto (disjoint_nhds_at_bot x) /-! ### Neighborhoods to the left and to the right on an `order_topology` We've seen some properties of left and right neighborhood of a point in an `order_closed_topology`. In an `order_topology`, such neighborhoods can be characterized as the sets containing suitable intervals to the right or to the left of `a`. We give now these characterizations. -/ -- NB: If you extend the list, append to the end please to avoid breaking the API /-- The following statements are equivalent: 0. `s` is a neighborhood of `a` within `(a, +∞)` 1. `s` is a neighborhood of `a` within `(a, b]` 2. `s` is a neighborhood of `a` within `(a, b)` 3. `s` includes `(a, u)` for some `u ∈ (a, b]` 4. `s` includes `(a, u)` for some `u > a` -/ lemma tfae_mem_nhds_within_Ioi {a b : α} (hab : a < b) (s : set α) : tfae [s ∈ 𝓝[>] a, -- 0 : `s` is a neighborhood of `a` within `(a, +∞)` s ∈ 𝓝[Ioc a b] a, -- 1 : `s` is a neighborhood of `a` within `(a, b]` s ∈ 𝓝[Ioo a b] a, -- 2 : `s` is a neighborhood of `a` within `(a, b)` ∃ u ∈ Ioc a b, Ioo a u ⊆ s, -- 3 : `s` includes `(a, u)` for some `u ∈ (a, b]` ∃ u ∈ Ioi a, Ioo a u ⊆ s] := -- 4 : `s` includes `(a, u)` for some `u > a` begin tfae_have : 1 ↔ 2, by rw [nhds_within_Ioc_eq_nhds_within_Ioi hab], tfae_have : 1 ↔ 3, by rw [nhds_within_Ioo_eq_nhds_within_Ioi hab], tfae_have : 4 → 5, from λ ⟨u, umem, hu⟩, ⟨u, umem.1, hu⟩, tfae_have : 5 → 1, { rintros ⟨u, hau, hu⟩, exact mem_of_superset (Ioo_mem_nhds_within_Ioi ⟨le_refl a, hau⟩) hu }, tfae_have : 1 → 4, { assume h, rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩, rcases exists_Ico_subset_of_mem_nhds' va hab with ⟨u, au, hu⟩, refine ⟨u, au, λx hx, _⟩, refine hv ⟨hu ⟨le_of_lt hx.1, hx.2⟩, _⟩, exact hx.1 }, tfae_finish end lemma mem_nhds_within_Ioi_iff_exists_mem_Ioc_Ioo_subset {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[>] a ↔ ∃u ∈ Ioc a u', Ioo a u ⊆ s := (tfae_mem_nhds_within_Ioi hu' s).out 0 3 /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)` with `a < u < u'`, provided `a` is not a top element. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset' {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[>] a ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s := (tfae_mem_nhds_within_Ioi hu' s).out 0 4 /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)` with `a < u`. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset [no_max_order α] {a : α} {s : set α} : s ∈ 𝓝[>] a ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s := let ⟨u', hu'⟩ := exists_gt a in mem_nhds_within_Ioi_iff_exists_Ioo_subset' hu' /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u]` with `a < u`. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioc_subset [no_max_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[>] a ↔ ∃u ∈ Ioi a, Ioc a u ⊆ s := begin rw mem_nhds_within_Ioi_iff_exists_Ioo_subset, split, { rintros ⟨u, au, as⟩, rcases exists_between au with ⟨v, hv⟩, exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ }, { rintros ⟨u, au, as⟩, exact ⟨u, au, subset.trans Ioo_subset_Ioc_self as⟩ } end /-- The following statements are equivalent: 0. `s` is a neighborhood of `b` within `(-∞, b)` 1. `s` is a neighborhood of `b` within `[a, b)` 2. `s` is a neighborhood of `b` within `(a, b)` 3. `s` includes `(l, b)` for some `l ∈ [a, b)` 4. `s` includes `(l, b)` for some `l < b` -/ lemma tfae_mem_nhds_within_Iio {a b : α} (h : a < b) (s : set α) : tfae [s ∈ 𝓝[<] b, -- 0 : `s` is a neighborhood of `b` within `(-∞, b)` s ∈ 𝓝[Ico a b] b, -- 1 : `s` is a neighborhood of `b` within `[a, b)` s ∈ 𝓝[Ioo a b] b, -- 2 : `s` is a neighborhood of `b` within `(a, b)` ∃ l ∈ Ico a b, Ioo l b ⊆ s, -- 3 : `s` includes `(l, b)` for some `l ∈ [a, b)` ∃ l ∈ Iio b, Ioo l b ⊆ s] := -- 4 : `s` includes `(l, b)` for some `l < b` by simpa only [exists_prop, order_dual.exists, dual_Ioi, dual_Ioc, dual_Ioo] using tfae_mem_nhds_within_Ioi h.dual (of_dual ⁻¹' s) lemma mem_nhds_within_Iio_iff_exists_mem_Ico_Ioo_subset {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[<] a ↔ ∃l ∈ Ico l' a, Ioo l a ⊆ s := (tfae_mem_nhds_within_Iio hl' s).out 0 3 /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)` with `l < a`, provided `a` is not a bottom element. -/ lemma mem_nhds_within_Iio_iff_exists_Ioo_subset' {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[<] a ↔ ∃l ∈ Iio a, Ioo l a ⊆ s := (tfae_mem_nhds_within_Iio hl' s).out 0 4 /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)` with `l < a`. -/ lemma mem_nhds_within_Iio_iff_exists_Ioo_subset [no_min_order α] {a : α} {s : set α} : s ∈ 𝓝[<] a ↔ ∃l ∈ Iio a, Ioo l a ⊆ s := let ⟨l', hl'⟩ := exists_lt a in mem_nhds_within_Iio_iff_exists_Ioo_subset' hl' /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `[l, a)` with `l < a`. -/ lemma mem_nhds_within_Iio_iff_exists_Ico_subset [no_min_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[<] a ↔ ∃l ∈ Iio a, Ico l a ⊆ s := begin have : of_dual ⁻¹' s ∈ 𝓝[>] (to_dual a) ↔ _ := mem_nhds_within_Ioi_iff_exists_Ioc_subset, simpa only [order_dual.exists, exists_prop, dual_Ioc] using this, end /-- The following statements are equivalent: 0. `s` is a neighborhood of `a` within `[a, +∞)` 1. `s` is a neighborhood of `a` within `[a, b]` 2. `s` is a neighborhood of `a` within `[a, b)` 3. `s` includes `[a, u)` for some `u ∈ (a, b]` 4. `s` includes `[a, u)` for some `u > a` -/ lemma tfae_mem_nhds_within_Ici {a b : α} (hab : a < b) (s : set α) : tfae [s ∈ 𝓝[≥] a, -- 0 : `s` is a neighborhood of `a` within `[a, +∞)` s ∈ 𝓝[Icc a b] a, -- 1 : `s` is a neighborhood of `a` within `[a, b]` s ∈ 𝓝[Ico a b] a, -- 2 : `s` is a neighborhood of `a` within `[a, b)` ∃ u ∈ Ioc a b, Ico a u ⊆ s, -- 3 : `s` includes `[a, u)` for some `u ∈ (a, b]` ∃ u ∈ Ioi a, Ico a u ⊆ s] := -- 4 : `s` includes `[a, u)` for some `u > a` begin tfae_have : 1 ↔ 2, by rw [nhds_within_Icc_eq_nhds_within_Ici hab], tfae_have : 1 ↔ 3, by rw [nhds_within_Ico_eq_nhds_within_Ici hab], tfae_have : 1 ↔ 5, from (nhds_within_Ici_basis' ⟨b, hab⟩).mem_iff, tfae_have : 4 → 5, from λ ⟨u, umem, hu⟩, ⟨u, umem.1, hu⟩, tfae_have : 5 → 4, { rintro ⟨u, hua, hus⟩, exact ⟨min u b, ⟨lt_min hua hab, min_le_right _ _⟩, (Ico_subset_Ico_right $ min_le_left _ _).trans hus⟩, }, tfae_finish end lemma mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[≥] a ↔ ∃u ∈ Ioc a u', Ico a u ⊆ s := (tfae_mem_nhds_within_Ici hu' s).out 0 3 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)` with `a < u < u'`, provided `a` is not a top element. -/ lemma mem_nhds_within_Ici_iff_exists_Ico_subset' {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[≥] a ↔ ∃u ∈ Ioi a, Ico a u ⊆ s := (tfae_mem_nhds_within_Ici hu' s).out 0 4 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)` with `a < u`. -/ lemma mem_nhds_within_Ici_iff_exists_Ico_subset [no_max_order α] {a : α} {s : set α} : s ∈ 𝓝[≥] a ↔ ∃u ∈ Ioi a, Ico a u ⊆ s := let ⟨u', hu'⟩ := exists_gt a in mem_nhds_within_Ici_iff_exists_Ico_subset' hu' lemma nhds_within_Ici_basis_Ico [no_max_order α] (a : α) : (𝓝[≥] a).has_basis (λ u, a < u) (Ico a) := ⟨λ s, mem_nhds_within_Ici_iff_exists_Ico_subset⟩ /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u]` with `a < u`. -/ lemma mem_nhds_within_Ici_iff_exists_Icc_subset [no_max_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[≥] a ↔ ∃ u, a < u ∧ Icc a u ⊆ s := begin rw mem_nhds_within_Ici_iff_exists_Ico_subset, split, { rintros ⟨u, au, as⟩, rcases exists_between au with ⟨v, hv⟩, exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ }, { rintros ⟨u, au, as⟩, exact ⟨u, au, subset.trans Ico_subset_Icc_self as⟩ } end /-- The following statements are equivalent: 0. `s` is a neighborhood of `b` within `(-∞, b]` 1. `s` is a neighborhood of `b` within `[a, b]` 2. `s` is a neighborhood of `b` within `(a, b]` 3. `s` includes `(l, b]` for some `l ∈ [a, b)` 4. `s` includes `(l, b]` for some `l < b` -/ lemma tfae_mem_nhds_within_Iic {a b : α} (h : a < b) (s : set α) : tfae [s ∈ 𝓝[≤] b, -- 0 : `s` is a neighborhood of `b` within `(-∞, b]` s ∈ 𝓝[Icc a b] b, -- 1 : `s` is a neighborhood of `b` within `[a, b]` s ∈ 𝓝[Ioc a b] b, -- 2 : `s` is a neighborhood of `b` within `(a, b]` ∃ l ∈ Ico a b, Ioc l b ⊆ s, -- 3 : `s` includes `(l, b]` for some `l ∈ [a, b)` ∃ l ∈ Iio b, Ioc l b ⊆ s] := -- 4 : `s` includes `(l, b]` for some `l < b` by simpa only [exists_prop, order_dual.exists, dual_Ici, dual_Ioc, dual_Icc, dual_Ico] using tfae_mem_nhds_within_Ici h.dual (of_dual ⁻¹' s) lemma mem_nhds_within_Iic_iff_exists_mem_Ico_Ioc_subset {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[≤] a ↔ ∃l ∈ Ico l' a, Ioc l a ⊆ s := (tfae_mem_nhds_within_Iic hl' s).out 0 3 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]` with `l < a`, provided `a` is not a bottom element. -/ lemma mem_nhds_within_Iic_iff_exists_Ioc_subset' {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[≤] a ↔ ∃l ∈ Iio a, Ioc l a ⊆ s := (tfae_mem_nhds_within_Iic hl' s).out 0 4 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]` with `l < a`. -/ lemma mem_nhds_within_Iic_iff_exists_Ioc_subset [no_min_order α] {a : α} {s : set α} : s ∈ 𝓝[≤] a ↔ ∃l ∈ Iio a, Ioc l a ⊆ s := let ⟨l', hl'⟩ := exists_lt a in mem_nhds_within_Iic_iff_exists_Ioc_subset' hl' /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `[l, a]` with `l < a`. -/ lemma mem_nhds_within_Iic_iff_exists_Icc_subset [no_min_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[≤] a ↔ ∃ l, l < a ∧ Icc l a ⊆ s := begin convert @mem_nhds_within_Ici_iff_exists_Icc_subset αᵒᵈ _ _ _ _ _ _ _, simp_rw (show ∀ u : αᵒᵈ, @Icc αᵒᵈ _ a u = @Icc α _ u a, from λ u, dual_Icc), refl, end end order_topology end linear_order section linear_ordered_add_comm_group variables [topological_space α] [linear_ordered_add_comm_group α] [order_topology α] variables {l : filter β} {f g : β → α} lemma nhds_eq_infi_abs_sub (a : α) : 𝓝 a = (⨅r>0, 𝓟 {b | |a - b| < r}) := begin simp only [le_antisymm_iff, nhds_eq_order, le_inf_iff, le_infi_iff, le_principal_iff, mem_Ioi, mem_Iio, abs_sub_lt_iff, @sub_lt_iff_lt_add _ _ _ _ _ _ a, @sub_lt _ _ _ _ a, set_of_and], refine ⟨_, _, _⟩, { intros ε ε0, exact inter_mem_inf (mem_infi_of_mem (a - ε) $ mem_infi_of_mem (sub_lt_self a ε0) (mem_principal_self _)) (mem_infi_of_mem (ε + a) $ mem_infi_of_mem (by simpa) (mem_principal_self _)) }, { intros b hb, exact mem_infi_of_mem (a - b) (mem_infi_of_mem (sub_pos.2 hb) (by simp [Ioi])) }, { intros b hb, exact mem_infi_of_mem (b - a) (mem_infi_of_mem (sub_pos.2 hb) (by simp [Iio])) } end lemma order_topology_of_nhds_abs {α : Type*} [topological_space α] [linear_ordered_add_comm_group α] (h_nhds : ∀a:α, 𝓝 a = (⨅r>0, 𝓟 {b | |a - b| < r})) : order_topology α := begin refine ⟨eq_of_nhds_eq_nhds $ λ a, _⟩, rw [h_nhds], letI := preorder.topology α, letI : order_topology α := ⟨rfl⟩, exact (nhds_eq_infi_abs_sub a).symm end lemma linear_ordered_add_comm_group.tendsto_nhds {x : filter β} {a : α} : tendsto f x (𝓝 a) ↔ ∀ ε > (0 : α), ∀ᶠ b in x, |f b - a| < ε := by simp [nhds_eq_infi_abs_sub, abs_sub_comm a] lemma eventually_abs_sub_lt (a : α) {ε : α} (hε : 0 < ε) : ∀ᶠ x in 𝓝 a, |x - a| < ε := (nhds_eq_infi_abs_sub a).symm ▸ mem_infi_of_mem ε (mem_infi_of_mem hε $ by simp only [abs_sub_comm, mem_principal_self]) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_add_comm_group.topological_add_group : topological_add_group α := { continuous_add := begin refine continuous_iff_continuous_at.2 _, rintro ⟨a, b⟩, refine linear_ordered_add_comm_group.tendsto_nhds.2 (λ ε ε0, _), rcases dense_or_discrete 0 ε with (⟨δ, δ0, δε⟩|⟨h₁, h₂⟩), { -- If there exists `δ ∈ (0, ε)`, then we choose `δ`-nhd of `a` and `(ε-δ)`-nhd of `b` filter_upwards [(eventually_abs_sub_lt a δ0).prod_nhds (eventually_abs_sub_lt b (sub_pos.2 δε))], rintros ⟨x, y⟩ ⟨hx : |x - a| < δ, hy : |y - b| < ε - δ⟩, rw [add_sub_add_comm], calc |x - a + (y - b)| ≤ |x - a| + |y - b| : abs_add _ _ ... < δ + (ε - δ) : add_lt_add hx hy ... = ε : add_sub_cancel'_right _ _ }, { -- Otherewise `ε`-nhd of each point `a` is `{a}` have hε : ∀ {x y}, |x - y| < ε → x = y, { intros x y h, simpa [sub_eq_zero] using h₂ _ h }, filter_upwards [(eventually_abs_sub_lt a ε0).prod_nhds (eventually_abs_sub_lt b ε0)], rintros ⟨x, y⟩ ⟨hx : |x - a| < ε, hy : |y - b| < ε⟩, simpa [hε hx, hε hy] } end, continuous_neg := continuous_iff_continuous_at.2 $ λ a, linear_ordered_add_comm_group.tendsto_nhds.2 $ λ ε ε0, (eventually_abs_sub_lt a ε0).mono $ λ x hx, by rwa [neg_sub_neg, abs_sub_comm] } @[continuity] lemma continuous_abs : continuous (abs : α → α) := continuous_id.max continuous_neg lemma filter.tendsto.abs {f : β → α} {a : α} {l : filter β} (h : tendsto f l (𝓝 a)) : tendsto (λ x, |f x|) l (𝓝 (|a|)) := (continuous_abs.tendsto _).comp h lemma tendsto_zero_iff_abs_tendsto_zero (f : β → α) {l : filter β} : tendsto f l (𝓝 0) ↔ tendsto (abs ∘ f) l (𝓝 0) := begin refine ⟨λ h, (abs_zero : |(0 : α)| = 0) ▸ h.abs, λ h, _⟩, have : tendsto (λ a, -|f a|) l (𝓝 0) := (neg_zero : -(0 : α) = 0) ▸ h.neg, exact tendsto_of_tendsto_of_tendsto_of_le_of_le this h (λ x, neg_abs_le_self $ f x) (λ x, le_abs_self $ f x), end lemma nhds_basis_Ioo_pos [no_min_order α] [no_max_order α] (a : α) : (𝓝 a).has_basis (λ ε : α, (0 : α) < ε) (λ ε, Ioo (a-ε) (a+ε)) := ⟨begin refine λ t, (nhds_basis_Ioo a).mem_iff.trans ⟨_, _⟩, { rintros ⟨⟨l, u⟩, ⟨hl : l < a, hu : a < u⟩, h' : Ioo l u ⊆ t⟩, refine ⟨min (a-l) (u-a), by apply lt_min; rwa sub_pos, _⟩, rintros x ⟨hx, hx'⟩, apply h', rw [sub_lt, lt_min_iff, sub_lt_sub_iff_left] at hx, rw [← sub_lt_iff_lt_add', lt_min_iff, sub_lt_sub_iff_right] at hx', exact ⟨hx.1, hx'.2⟩ }, { rintros ⟨ε, ε_pos, h⟩, exact ⟨(a-ε, a+ε), by simp [ε_pos], h⟩ }, end⟩ lemma nhds_basis_abs_sub_lt [no_min_order α] [no_max_order α] (a : α) : (𝓝 a).has_basis (λ ε : α, (0 : α) < ε) (λ ε, {b | |b - a| < ε}) := begin convert nhds_basis_Ioo_pos a, { ext ε, change |x - a| < ε ↔ a - ε < x ∧ x < a + ε, simp [abs_lt, sub_lt_iff_lt_add, add_comm ε a, add_comm x ε] } end variable (α) lemma nhds_basis_zero_abs_sub_lt [no_min_order α] [no_max_order α] : (𝓝 (0 : α)).has_basis (λ ε : α, (0 : α) < ε) (λ ε, {b | |b| < ε}) := by simpa using nhds_basis_abs_sub_lt (0 : α) variable {α} /-- If `a` is positive we can form a basis from only nonnegative `Ioo` intervals -/ lemma nhds_basis_Ioo_pos_of_pos [no_min_order α] [no_max_order α] {a : α} (ha : 0 < a) : (𝓝 a).has_basis (λ ε : α, (0 : α) < ε ∧ ε ≤ a) (λ ε, Ioo (a-ε) (a+ε)) := ⟨ λ t, (nhds_basis_Ioo_pos a).mem_iff.trans ⟨λ h, let ⟨i, hi, hit⟩ := h in ⟨min i a, ⟨lt_min hi ha, min_le_right i a⟩, trans (Ioo_subset_Ioo (sub_le_sub_left (min_le_left i a) a) (add_le_add_left (min_le_left i a) a)) hit⟩, λ h, let ⟨i, hi, hit⟩ := h in ⟨i, hi.1, hit⟩ ⟩ ⟩ section variables [topological_space β] {b : β} {a : α} {s : set β} lemma continuous.abs (h : continuous f) : continuous (λ x, |f x|) := continuous_abs.comp h lemma continuous_at.abs (h : continuous_at f b) : continuous_at (λ x, |f x|) b := h.abs lemma continuous_within_at.abs (h : continuous_within_at f s b) : continuous_within_at (λ x, |f x|) s b := h.abs lemma continuous_on.abs (h : continuous_on f s) : continuous_on (λ x, |f x|) s := λ x hx, (h x hx).abs lemma tendsto_abs_nhds_within_zero : tendsto (abs : α → α) (𝓝[≠] 0) (𝓝[>] 0) := (continuous_abs.tendsto' (0 : α) 0 abs_zero).inf $ tendsto_principal_principal.2 $ λ x, abs_pos.2 end /-- In a linearly ordered additive commutative group with the order topology, if `f` tends to `C` and `g` tends to `at_top` then `f + g` tends to `at_top`. -/ lemma filter.tendsto.add_at_top {C : α} (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := begin nontriviality α, obtain ⟨C', hC'⟩ : ∃ C', C' < C := exists_lt C, refine tendsto_at_top_add_left_of_le' _ C' _ hg, exact (hf.eventually (lt_mem_nhds hC')).mono (λ x, le_of_lt) end /-- In a linearly ordered additive commutative group with the order topology, if `f` tends to `C` and `g` tends to `at_bot` then `f + g` tends to `at_bot`. -/ lemma filter.tendsto.add_at_bot {C : α} (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @filter.tendsto.add_at_top αᵒᵈ _ _ _ _ _ _ _ _ hf hg /-- In a linearly ordered additive commutative group with the order topology, if `f` tends to `at_top` and `g` tends to `C` then `f + g` tends to `at_top`. -/ lemma filter.tendsto.at_top_add {C : α} (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, f x + g x) l at_top := by { conv in (_ + _) { rw add_comm }, exact hg.add_at_top hf } /-- In a linearly ordered additive commutative group with the order topology, if `f` tends to `at_bot` and `g` tends to `C` then `f + g` tends to `at_bot`. -/ lemma filter.tendsto.at_bot_add {C : α} (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, f x + g x) l at_bot := by { conv in (_ + _) { rw add_comm }, exact hg.add_at_bot hf } end linear_ordered_add_comm_group section linear_ordered_field variables [linear_ordered_field α] [topological_space α] [order_topology α] variables {l : filter β} {f g : β → α} section continuous_mul lemma mul_tendsto_nhds_zero_right (x : α) : tendsto (uncurry ((*) : α → α → α)) (𝓝 0 ×ᶠ 𝓝 x) $ 𝓝 0 := begin have hx : 0 < 2 * (1 + |x|) := by positivity, rw ((nhds_basis_zero_abs_sub_lt α).prod $ nhds_basis_abs_sub_lt x).tendsto_iff (nhds_basis_zero_abs_sub_lt α), refine λ ε ε_pos, ⟨(ε/(2 * (1 + |x|)), 1), ⟨div_pos ε_pos hx, zero_lt_one⟩, _⟩, suffices : ∀ (a b : α), |a| < ε / (2 * (1 + |x|)) → |b - x| < 1 → |a| * |b| < ε, by simpa only [and_imp, prod.forall, mem_prod, ← abs_mul], intros a b h h', refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left _ (abs_nonneg a)) ((lt_div_iff hx).1 h), calc |b| = |(b - x) + x| : by rw sub_add_cancel b x ... ≤ |b - x| + |x| : abs_add (b - x) x ... ≤ 2 * (1 + |x|) : by linarith, end lemma mul_tendsto_nhds_zero_left (x : α) : tendsto (uncurry ((*) : α → α → α)) (𝓝 x ×ᶠ 𝓝 0) $ 𝓝 0 := begin intros s hs, have := mul_tendsto_nhds_zero_right x hs, rw [filter.mem_map, mem_prod_iff] at this ⊢, obtain ⟨U, hU, V, hV, h⟩ := this, exact ⟨V, hV, U, hU, λ y hy, ((mul_comm y.2 y.1) ▸ h (⟨hy.2, hy.1⟩ : (prod.mk y.2 y.1) ∈ U ×ˢ V) : y.1 * y.2 ∈ s)⟩, end lemma nhds_eq_map_mul_left_nhds_one {x₀ : α} (hx₀ : x₀ ≠ 0) : 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1) := begin have hx₀' : 0 < |x₀| := abs_pos.2 hx₀, refine filter.ext (λ t, _), simp only [exists_prop, set_of_subset_set_of, (nhds_basis_abs_sub_lt x₀).mem_iff, (nhds_basis_abs_sub_lt (1 : α)).mem_iff, filter.mem_map'], refine ⟨λ h, _, λ h, _⟩, { obtain ⟨i, hi, hit⟩ := h, refine ⟨i / (|x₀|), div_pos hi (abs_pos.2 hx₀), λ x hx, hit _⟩, calc |x₀ * x - x₀| = |x₀ * (x - 1)| : congr_arg abs (by ring_nf) ... = |x₀| * |x - 1| : abs_mul x₀ (x - 1) ... < |x₀| * (i / |x₀|) : mul_lt_mul' le_rfl hx (by positivity) (abs_pos.2 hx₀) ... = |x₀| * i / |x₀| : by ring ... = i : mul_div_cancel_left i (λ h, hx₀ (abs_eq_zero.1 h)) }, { obtain ⟨i, hi, hit⟩ := h, refine ⟨i * |x₀|, mul_pos hi (abs_pos.2 hx₀), λ x hx, _⟩, have : |x / x₀ - 1| < i, calc |x / x₀ - 1| = |x / x₀ - x₀ / x₀| : (by rw div_self hx₀) ... = |(x - x₀) / x₀| : congr_arg abs (sub_div x x₀ x₀).symm ... = |x - x₀| / |x₀| : abs_div (x - x₀) x₀ ... < i * |x₀| / |x₀| : div_lt_div_of_lt (abs_pos.2 hx₀) hx ... = i : by rw [← mul_div_assoc', div_self (ne_of_lt $ abs_pos.2 hx₀).symm, mul_one], specialize hit (x / x₀) this, rwa [mul_div_assoc', mul_div_cancel_left x hx₀] at hit } end lemma nhds_eq_map_mul_right_nhds_one {x₀ : α} (hx₀ : x₀ ≠ 0) : 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1) := by simp_rw [mul_comm _ x₀, nhds_eq_map_mul_left_nhds_one hx₀] lemma mul_tendsto_nhds_one_nhds_one : tendsto (uncurry ((*) : α → α → α)) (𝓝 1 ×ᶠ 𝓝 1) $ 𝓝 1 := begin rw ((nhds_basis_Ioo_pos (1 : α)).prod $ nhds_basis_Ioo_pos (1 : α)).tendsto_iff (nhds_basis_Ioo_pos_of_pos (zero_lt_one : (0 : α) < 1)), intros ε hε, have hε' : 0 ≤ 1 - ε / 4 := by linarith, have ε_pos : 0 < ε / 4 := by linarith, have ε_pos' : 0 < ε / 2 := by linarith, simp only [and_imp, prod.forall, mem_Ioo, function.uncurry_apply_pair, mem_prod, prod.exists], refine ⟨ε/4, ε/4, ⟨ε_pos, ε_pos⟩, λ a b ha ha' hb hb', _⟩, have ha0 : 0 ≤ a := le_trans hε' (le_of_lt ha), have hb0 : 0 ≤ b := le_trans hε' (le_of_lt hb), refine ⟨lt_of_le_of_lt _ (mul_lt_mul'' ha hb hε' hε'), lt_of_lt_of_le (mul_lt_mul'' ha' hb' ha0 hb0) _⟩, { calc 1 - ε = 1 - ε / 2 - ε/2 : by ring_nf ... ≤ 1 - ε/2 - ε/2 + (ε/2)*(ε/2) : le_add_of_nonneg_right (by positivity) ... = (1 - ε/2) * (1 - ε/2) : by ring_nf ... ≤ (1 - ε/4) * (1 - ε/4) : mul_le_mul (by linarith) (by linarith) (by linarith) hε' }, { calc (1 + ε/4) * (1 + ε/4) = 1 + ε/2 + (ε/4)*(ε/4) : by ring_nf ... = 1 + ε/2 + (ε * ε) / 16 : by ring_nf ... ≤ 1 + ε/2 + ε/2 : add_le_add_left (div_le_div (le_of_lt hε.1) (le_trans ((mul_le_mul_left hε.1).2 hε.2) (le_of_eq $ mul_one ε)) zero_lt_two (by linarith)) (1 + ε/2) ... ≤ 1 + ε : by ring_nf } end @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.has_continuous_mul : has_continuous_mul α := ⟨begin rw continuous_iff_continuous_at, rintro ⟨x₀, y₀⟩, by_cases hx₀ : x₀ = 0, { rw [hx₀, continuous_at, zero_mul, nhds_prod_eq], exact mul_tendsto_nhds_zero_right y₀ }, by_cases hy₀ : y₀ = 0, { rw [hy₀, continuous_at, mul_zero, nhds_prod_eq], exact mul_tendsto_nhds_zero_left x₀ }, have hxy : x₀ * y₀ ≠ 0 := mul_ne_zero hx₀ hy₀, have key : (λ p : α × α, x₀ * p.1 * (p.2 * y₀)) = ((λ x, x₀*x) ∘ (λ x, x*y₀)) ∘ (uncurry (*)), { ext p, simp [uncurry, mul_assoc] }, have key₂ : (λ x, x₀*x) ∘ (λ x, y₀*x) = λ x, (x₀ *y₀)*x, { ext x, simp }, calc map (uncurry (*)) (𝓝 (x₀, y₀)) = map (uncurry (*)) (𝓝 x₀ ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : α × α), x₀ * p.1 * (p.2 * y₀)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [uncurry, nhds_eq_map_mul_left_nhds_one hx₀, nhds_eq_map_mul_right_nhds_one hy₀, prod_map_map_eq, filter.map_map] ... = map ((λ x, x₀ * x) ∘ λ x, x * y₀) (map (uncurry (*)) (𝓝 1 ×ᶠ 𝓝 1)) : by rw [key, ← filter.map_map] ... ≤ map ((λ (x : α), x₀ * x) ∘ λ x, x * y₀) (𝓝 1) : map_mono (mul_tendsto_nhds_one_nhds_one) ... = 𝓝 (x₀*y₀) : by rw [← filter.map_map, ← nhds_eq_map_mul_right_nhds_one hy₀, nhds_eq_map_mul_left_nhds_one hy₀, filter.map_map, key₂, ← nhds_eq_map_mul_left_nhds_one hxy], end⟩ end continuous_mul /-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to a positive constant `C` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.at_top_mul {C : α} (hC : 0 < C) (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_top := begin refine tendsto_at_top_mono' _ _ (hf.at_top_mul_const (half_pos hC)), filter_upwards [hg.eventually (lt_mem_nhds (half_lt_self hC)), hf.eventually (eventually_ge_at_top 0)] with x hg hf using mul_le_mul_of_nonneg_left hg.le hf, end /-- In a linearly ordered field with the order topology, if `f` tends to a positive constant `C` and `g` tends to `at_top` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.mul_at_top {C : α} (hC : 0 < C) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) : tendsto (λ x, (f x * g x)) l at_top := by simpa only [mul_comm] using hg.at_top_mul hC hf /-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to a negative constant `C` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.at_top_mul_neg {C : α} (hC : C < 0) (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_bot := by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp (hf.at_top_mul (neg_pos.2 hC) hg.neg) /-- In a linearly ordered field with the order topology, if `f` tends to a negative constant `C` and `g` tends to `at_top` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.neg_mul_at_top {C : α} (hC : C < 0) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) : tendsto (λ x, (f x * g x)) l at_bot := by simpa only [mul_comm] using hg.at_top_mul_neg hC hf /-- In a linearly ordered field with the order topology, if `f` tends to `at_bot` and `g` tends to a positive constant `C` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.at_bot_mul {C : α} (hC : 0 < C) (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_bot := by simpa [(∘)] using tendsto_neg_at_top_at_bot.comp ((tendsto_neg_at_bot_at_top.comp hf).at_top_mul hC hg) /-- In a linearly ordered field with the order topology, if `f` tends to `at_bot` and `g` tends to a negative constant `C` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.at_bot_mul_neg {C : α} (hC : C < 0) (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_top := by simpa [(∘)] using tendsto_neg_at_bot_at_top.comp ((tendsto_neg_at_bot_at_top.comp hf).at_top_mul_neg hC hg) /-- In a linearly ordered field with the order topology, if `f` tends to a positive constant `C` and `g` tends to `at_bot` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.mul_at_bot {C : α} (hC : 0 < C) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) : tendsto (λ x, (f x * g x)) l at_bot := by simpa only [mul_comm] using hg.at_bot_mul hC hf /-- In a linearly ordered field with the order topology, if `f` tends to a negative constant `C` and `g` tends to `at_bot` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.neg_mul_at_bot {C : α} (hC : C < 0) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) : tendsto (λ x, (f x * g x)) l at_top := by simpa only [mul_comm] using hg.at_bot_mul_neg hC hf /-- The function `x ↦ x⁻¹` tends to `+∞` on the right of `0`. -/ lemma tendsto_inv_zero_at_top : tendsto (λx:α, x⁻¹) (𝓝[>] (0:α)) at_top := begin refine (at_top_basis' 1).tendsto_right_iff.2 (λ b hb, _), have hb' : 0 < b := by positivity, filter_upwards [Ioc_mem_nhds_within_Ioi ⟨le_rfl, inv_pos.2 hb'⟩] with x hx using (le_inv hx.1 hb').1 hx.2, end /-- The function `r ↦ r⁻¹` tends to `0` on the right as `r → +∞`. -/ lemma tendsto_inv_at_top_zero' : tendsto (λr:α, r⁻¹) at_top (𝓝[>] (0:α)) := begin refine (has_basis.tendsto_iff at_top_basis ⟨λ s, mem_nhds_within_Ioi_iff_exists_Ioc_subset⟩).2 _, refine λ b hb, ⟨b⁻¹, trivial, λ x hx, _⟩, have : 0 < x := lt_of_lt_of_le (inv_pos.2 hb) hx, exact ⟨inv_pos.2 this, (inv_le this hb).2 hx⟩ end lemma tendsto_inv_at_top_zero : tendsto (λr:α, r⁻¹) at_top (𝓝 0) := tendsto_inv_at_top_zero'.mono_right inf_le_left lemma filter.tendsto.div_at_top [has_continuous_mul α] {f g : β → α} {l : filter β} {a : α} (h : tendsto f l (𝓝 a)) (hg : tendsto g l at_top) : tendsto (λ x, f x / g x) l (𝓝 0) := by { simp only [div_eq_mul_inv], exact mul_zero a ▸ h.mul (tendsto_inv_at_top_zero.comp hg) } lemma filter.tendsto.inv_tendsto_at_top (h : tendsto f l at_top) : tendsto (f⁻¹) l (𝓝 0) := tendsto_inv_at_top_zero.comp h lemma filter.tendsto.inv_tendsto_zero (h : tendsto f l (𝓝[>] 0)) : tendsto (f⁻¹) l at_top := tendsto_inv_zero_at_top.comp h /-- The function `x^(-n)` tends to `0` at `+∞` for any positive natural `n`. A version for positive real powers exists as `tendsto_rpow_neg_at_top`. -/ lemma tendsto_pow_neg_at_top {n : ℕ} (hn : n ≠ 0) : tendsto (λ x : α, x ^ (-(n:ℤ))) at_top (𝓝 0) := by simpa only [zpow_neg, zpow_coe_nat] using (@tendsto_pow_at_top α _ _ hn).inv_tendsto_at_top lemma tendsto_zpow_at_top_zero {n : ℤ} (hn : n < 0) : tendsto (λ x : α, x^n) at_top (𝓝 0) := begin lift -n to ℕ using le_of_lt (neg_pos.mpr hn) with N, rw [← neg_pos, ← h, nat.cast_pos] at hn, simpa only [h, neg_neg] using tendsto_pow_neg_at_top hn.ne' end lemma tendsto_const_mul_zpow_at_top_zero {n : ℤ} {c : α} (hn : n < 0) : tendsto (λ x, c * x ^ n) at_top (𝓝 0) := (mul_zero c) ▸ (filter.tendsto.const_mul c (tendsto_zpow_at_top_zero hn)) lemma tendsto_const_mul_pow_nhds_iff' {n : ℕ} {c d : α} : tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔ (c = 0 ∨ n = 0) ∧ c = d := begin rcases eq_or_ne n 0 with (rfl|hn), { simp [tendsto_const_nhds_iff] }, rcases lt_trichotomy c 0 with hc|rfl|hc, { have := tendsto_const_mul_pow_at_bot_iff.2 ⟨hn, hc⟩, simp [not_tendsto_nhds_of_tendsto_at_bot this, hc.ne, hn] }, { simp [tendsto_const_nhds_iff] }, { have := tendsto_const_mul_pow_at_top_iff.2 ⟨hn, hc⟩, simp [not_tendsto_nhds_of_tendsto_at_top this, hc.ne', hn] } end lemma tendsto_const_mul_pow_nhds_iff {n : ℕ} {c d : α} (hc : c ≠ 0) : tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔ n = 0 ∧ c = d := by simp [tendsto_const_mul_pow_nhds_iff', hc] lemma tendsto_const_mul_zpow_at_top_nhds_iff {n : ℤ} {c d : α} (hc : c ≠ 0) : tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔ (n = 0 ∧ c = d) ∨ (n < 0 ∧ d = 0) := begin refine ⟨λ h, _, λ h, _⟩, { by_cases hn : 0 ≤ n, { lift n to ℕ using hn, simp only [zpow_coe_nat] at h, rw [tendsto_const_mul_pow_nhds_iff hc, ← int.coe_nat_eq_zero] at h, exact or.inl h }, { rw not_le at hn, refine or.inr ⟨hn, tendsto_nhds_unique h (tendsto_const_mul_zpow_at_top_zero hn)⟩ } }, { cases h, { simp only [h.left, h.right, zpow_zero, mul_one], exact tendsto_const_nhds }, { exact h.2.symm ▸ tendsto_const_mul_zpow_at_top_zero h.1} } end -- TODO: With a different proof, this could be possibly generalised to only require a -- `linear_ordered_semifield` instance, which would also remove the need for the -- `nnreal` instance of `has_continuous_inv₀`. @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.to_topological_division_ring : topological_division_ring α := { continuous_at_inv₀ := begin suffices : ∀ {x : α}, 0 < x → continuous_at has_inv.inv x, { intros x hx, cases hx.symm.lt_or_lt, { exact this h }, convert (this $ neg_pos.mpr h).neg.comp continuous_neg.continuous_at, ext, simp [neg_inv] }, intros t ht, rw [continuous_at, (nhds_basis_Ioo_pos t).tendsto_iff $ nhds_basis_Ioo_pos_of_pos $ inv_pos.2 ht], rintros ε ⟨hε : ε > 0, hεt : ε ≤ t⁻¹⟩, refine ⟨min (t ^ 2 * ε / 2) (t / 2), by positivity, λ x h, _⟩, have hx : t / 2 < x, { rw [set.mem_Ioo, sub_lt, lt_min_iff] at h, nlinarith }, have hx' : 0 < x := (half_pos ht).trans hx, have aux : 0 < 2 / t ^ 2 := by positivity, rw [set.mem_Ioo, ←sub_lt_iff_lt_add', sub_lt, ←abs_sub_lt_iff] at h ⊢, rw [inv_sub_inv ht.ne' hx'.ne', abs_div, div_eq_mul_inv], suffices : |t * x|⁻¹ < 2 / t ^ 2, { rw [←abs_neg, neg_sub], refine (mul_lt_mul'' h this (by positivity) (by positivity)).trans_le _, rw [mul_comm, mul_min_of_nonneg _ _ aux.le], apply min_le_of_left_le, rw [←mul_div, ←mul_assoc, div_mul_cancel _ (sq_pos_of_pos ht).ne', mul_div_cancel' ε two_ne_zero] }, refine inv_lt_of_inv_lt aux _, rw [inv_div, abs_of_pos $ mul_pos ht hx', sq, ←mul_div_assoc'], exact mul_lt_mul_of_pos_left hx ht end } end linear_ordered_field lemma preimage_neg [add_group α] : preimage (has_neg.neg : α → α) = image (has_neg.neg : α → α) := (image_eq_preimage_of_inverse neg_neg neg_neg).symm lemma filter.map_neg_eq_comap_neg [add_group α] : map (has_neg.neg : α → α) = comap (has_neg.neg : α → α) := funext $ assume f, map_eq_comap_of_inverse (funext neg_neg) (funext neg_neg) section order_topology variables [topological_space α] [topological_space β] [linear_order α] [linear_order β] [order_topology α] [order_topology β] lemma is_lub.frequently_mem {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) : ∃ᶠ x in 𝓝[≤] a, x ∈ s := begin rcases hs with ⟨a', ha'⟩, intro h, rcases (ha.1 ha').eq_or_lt with (rfl|ha'a), { exact h.self_of_nhds_within le_rfl ha' }, { rcases (mem_nhds_within_Iic_iff_exists_Ioc_subset' ha'a).1 h with ⟨b, hba, hb⟩, rcases ha.exists_between hba with ⟨b', hb's, hb'⟩, exact hb hb' hb's }, end lemma is_lub.frequently_nhds_mem {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) : ∃ᶠ x in 𝓝 a, x ∈ s := (ha.frequently_mem hs).filter_mono inf_le_left lemma is_glb.frequently_mem {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) : ∃ᶠ x in 𝓝[≥] a, x ∈ s := @is_lub.frequently_mem αᵒᵈ _ _ _ _ _ ha hs lemma is_glb.frequently_nhds_mem {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) : ∃ᶠ x in 𝓝 a, x ∈ s := (ha.frequently_mem hs).filter_mono inf_le_left lemma is_lub.mem_closure {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) : a ∈ closure s := (ha.frequently_nhds_mem hs).mem_closure lemma is_glb.mem_closure {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) : a ∈ closure s := (ha.frequently_nhds_mem hs).mem_closure lemma is_lub.nhds_within_ne_bot {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) : ne_bot (𝓝[s] a) := mem_closure_iff_nhds_within_ne_bot.1 (ha.mem_closure hs) lemma is_glb.nhds_within_ne_bot : ∀ {a : α} {s : set α}, is_glb s a → s.nonempty → ne_bot (𝓝[s] a) := @is_lub.nhds_within_ne_bot αᵒᵈ _ _ _ lemma is_lub_of_mem_nhds {s : set α} {a : α} {f : filter α} (hsa : a ∈ upper_bounds s) (hsf : s ∈ f) [ne_bot (f ⊓ 𝓝 a)] : is_lub s a := ⟨hsa, assume b hb, not_lt.1 $ assume hba, have s ∩ {a | b < a} ∈ f ⊓ 𝓝 a, from inter_mem_inf hsf (is_open.mem_nhds (is_open_lt' _) hba), let ⟨x, ⟨hxs, hxb⟩⟩ := filter.nonempty_of_mem this in have b < b, from lt_of_lt_of_le hxb $ hb hxs, lt_irrefl b this⟩ lemma is_lub_of_mem_closure {s : set α} {a : α} (hsa : a ∈ upper_bounds s) (hsf : a ∈ closure s) : is_lub s a := begin rw [mem_closure_iff_cluster_pt, cluster_pt, inf_comm] at hsf, haveI : (𝓟 s ⊓ 𝓝 a).ne_bot := hsf, exact is_lub_of_mem_nhds hsa (mem_principal_self s), end lemma is_glb_of_mem_nhds : ∀ {s : set α} {a : α} {f : filter α}, a ∈ lower_bounds s → s ∈ f → ne_bot (f ⊓ 𝓝 a) → is_glb s a := @is_lub_of_mem_nhds αᵒᵈ _ _ _ lemma is_glb_of_mem_closure {s : set α} {a : α} (hsa : a ∈ lower_bounds s) (hsf : a ∈ closure s) : is_glb s a := @is_lub_of_mem_closure αᵒᵈ _ _ _ s a hsa hsf lemma is_lub.mem_upper_bounds_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ} (hf : monotone_on f s) (ha : is_lub s a) (hb : tendsto f (𝓝[s] a) (𝓝 b)) : b ∈ upper_bounds (f '' s) := begin rintro _ ⟨x, hx, rfl⟩, replace ha := ha.inter_Ici_of_mem hx, haveI := ha.nhds_within_ne_bot ⟨x, hx, le_rfl⟩, refine ge_of_tendsto (hb.mono_left (nhds_within_mono _ (inter_subset_left s (Ici x)))) _, exact mem_of_superset self_mem_nhds_within (λ y hy, hf hx hy.1 hy.2) end -- For a version of this theorem in which the convergence considered on the domain `α` is as `x : α` -- tends to infinity, rather than tending to a point `x` in `α`, see `is_lub_of_tendsto_at_top` lemma is_lub.is_lub_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ} (hf : monotone_on f s) (ha : is_lub s a) (hs : s.nonempty) (hb : tendsto f (𝓝[s] a) (𝓝 b)) : is_lub (f '' s) b := begin haveI := ha.nhds_within_ne_bot hs, exact ⟨ha.mem_upper_bounds_of_tendsto hf hb, λ b' hb', le_of_tendsto hb (mem_of_superset self_mem_nhds_within $ λ x hx, hb' $ mem_image_of_mem _ hx)⟩ end lemma is_glb.mem_lower_bounds_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ} (hf : monotone_on f s) (ha : is_glb s a) (hb : tendsto f (𝓝[s] a) (𝓝 b)) : b ∈ lower_bounds (f '' s) := @is_lub.mem_upper_bounds_of_tendsto αᵒᵈ γᵒᵈ _ _ _ _ _ _ _ _ _ _ hf.dual ha hb -- For a version of this theorem in which the convergence considered on the domain `α` is as -- `x : α` tends to negative infinity, rather than tending to a point `x` in `α`, see -- `is_glb_of_tendsto_at_bot` lemma is_glb.is_glb_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ} (hf : monotone_on f s) : is_glb s a → s.nonempty → tendsto f (𝓝[s] a) (𝓝 b) → is_glb (f '' s) b := @is_lub.is_lub_of_tendsto αᵒᵈ γᵒᵈ _ _ _ _ _ _ f s a b hf.dual lemma is_lub.mem_lower_bounds_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ} (hf : antitone_on f s) (ha : is_lub s a) (hb : tendsto f (𝓝[s] a) (𝓝 b)) : b ∈ lower_bounds (f '' s) := @is_lub.mem_upper_bounds_of_tendsto α γᵒᵈ _ _ _ _ _ _ _ _ _ _ hf ha hb lemma is_lub.is_glb_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] : ∀ {f : α → γ} {s : set α} {a : α} {b : γ}, (antitone_on f s) → is_lub s a → s.nonempty → tendsto f (𝓝[s] a) (𝓝 b) → is_glb (f '' s) b := @is_lub.is_lub_of_tendsto α γᵒᵈ _ _ _ _ _ _ lemma is_glb.mem_upper_bounds_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ} (hf : antitone_on f s) (ha : is_glb s a) (hb : tendsto f (𝓝[s] a) (𝓝 b)) : b ∈ upper_bounds (f '' s) := @is_glb.mem_lower_bounds_of_tendsto α γᵒᵈ _ _ _ _ _ _ _ _ _ _ hf ha hb lemma is_glb.is_lub_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] : ∀ {f : α → γ} {s : set α} {a : α} {b : γ}, (antitone_on f s) → is_glb s a → s.nonempty → tendsto f (𝓝[s] a) (𝓝 b) → is_lub (f '' s) b := @is_glb.is_glb_of_tendsto α γᵒᵈ _ _ _ _ _ _ lemma is_lub.mem_of_is_closed {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) (sc : is_closed s) : a ∈ s := sc.closure_subset $ ha.mem_closure hs alias is_lub.mem_of_is_closed ← is_closed.is_lub_mem lemma is_glb.mem_of_is_closed {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) (sc : is_closed s) : a ∈ s := sc.closure_subset $ ha.mem_closure hs alias is_glb.mem_of_is_closed ← is_closed.is_glb_mem /-! ### Existence of sequences tending to Inf or Sup of a given set -/ lemma is_lub.exists_seq_strict_mono_tendsto_of_not_mem {t : set α} {x : α} [is_countably_generated (𝓝 x)] (htx : is_lub t x) (not_mem : x ∉ t) (ht : t.nonempty) : ∃ u : ℕ → α, strict_mono u ∧ (∀ n, u n < x) ∧ tendsto u at_top (𝓝 x) ∧ (∀ n, u n ∈ t) := begin rcases ht with ⟨l, hl⟩, have hl : l < x, from (htx.1 hl).eq_or_lt.resolve_left (λ h, (not_mem $ h ▸ hl).elim), obtain ⟨s, hs⟩ : ∃ s : ℕ → set α, (𝓝 x).has_basis (λ (_x : ℕ), true) s := let ⟨s, hs⟩ := (𝓝 x).exists_antitone_basis in ⟨s, hs.to_has_basis⟩, have : ∀ n k, k < x → ∃ y, Icc y x ⊆ s n ∧ k < y ∧ y < x ∧ y ∈ t, { assume n k hk, obtain ⟨L, hL, h⟩ : ∃ (L : α) (hL : L ∈ Ico k x), Ioc L x ⊆ s n := exists_Ioc_subset_of_mem_nhds' (hs.mem_of_mem trivial) hk, obtain ⟨y, hy⟩ : ∃ (y : α), L < y ∧ y < x ∧ y ∈ t, { rcases htx.exists_between' not_mem hL.2 with ⟨y, yt, hy⟩, refine ⟨y, hy.1, hy.2, yt⟩ }, exact ⟨y, λ z hz, h ⟨hy.1.trans_le hz.1, hz.2⟩, hL.1.trans_lt hy.1, hy.2⟩ }, choose! f hf using this, let u : ℕ → α := λ n, nat.rec_on n (f 0 l) (λ n h, f n.succ h), have I : ∀ n, u n < x, { assume n, induction n with n IH, { exact (hf 0 l hl).2.2.1 }, { exact (hf n.succ _ IH).2.2.1 } }, have S : strict_mono u := strict_mono_nat_of_lt_succ (λ n, (hf n.succ _ (I n)).2.1), refine ⟨u, S, I, hs.tendsto_right_iff.2 (λ n _, _), (λ n, _)⟩, { simp only [ge_iff_le, eventually_at_top], refine ⟨n, λ p hp, _⟩, have up : u p ∈ Icc (u n) x := ⟨S.monotone hp, (I p).le⟩, have : Icc (u n) x ⊆ s n, by { cases n, { exact (hf 0 l hl).1 }, { exact (hf n.succ (u n) (I n)).1 } }, exact this up }, { cases n, { exact (hf 0 l hl).2.2.2 }, { exact (hf n.succ _ (I n)).2.2.2 } } end lemma is_lub.exists_seq_monotone_tendsto {t : set α} {x : α} [is_countably_generated (𝓝 x)] (htx : is_lub t x) (ht : t.nonempty) : ∃ u : ℕ → α, monotone u ∧ (∀ n, u n ≤ x) ∧ tendsto u at_top (𝓝 x) ∧ (∀ n, u n ∈ t) := begin by_cases h : x ∈ t, { exact ⟨λ n, x, monotone_const, λ n, le_rfl, tendsto_const_nhds, λ n, h⟩ }, { rcases htx.exists_seq_strict_mono_tendsto_of_not_mem h ht with ⟨u, hu⟩, exact ⟨u, hu.1.monotone, λ n, (hu.2.1 n).le, hu.2.2⟩ } end lemma exists_seq_strict_mono_tendsto' {α : Type*} [linear_order α] [topological_space α] [densely_ordered α] [order_topology α] [first_countable_topology α] {x y : α} (hy : y < x) : ∃ u : ℕ → α, strict_mono u ∧ (∀ n, u n ∈ Ioo y x) ∧ tendsto u at_top (𝓝 x) := begin have hx : x ∉ Ioo y x := λ h, (lt_irrefl x h.2).elim, have ht : set.nonempty (Ioo y x) := nonempty_Ioo.2 hy, rcases (is_lub_Ioo hy).exists_seq_strict_mono_tendsto_of_not_mem hx ht with ⟨u, hu⟩, exact ⟨u, hu.1, hu.2.2.symm⟩ end lemma exists_seq_strict_mono_tendsto [densely_ordered α] [no_min_order α] [first_countable_topology α] (x : α) : ∃ u : ℕ → α, strict_mono u ∧ (∀ n, u n < x) ∧ tendsto u at_top (𝓝 x) := begin obtain ⟨y, hy⟩ : ∃ y, y < x := exists_lt x, rcases exists_seq_strict_mono_tendsto' hy with ⟨u, hu_mono, hu_mem, hux⟩, exact ⟨u, hu_mono, λ n, (hu_mem n).2, hux⟩ end lemma exists_seq_tendsto_Sup {α : Type*} [conditionally_complete_linear_order α] [topological_space α] [order_topology α] [first_countable_topology α] {S : set α} (hS : S.nonempty) (hS' : bdd_above S) : ∃ (u : ℕ → α), monotone u ∧ tendsto u at_top (𝓝 (Sup S)) ∧ (∀ n, u n ∈ S) := begin rcases (is_lub_cSup hS hS').exists_seq_monotone_tendsto hS with ⟨u, hu⟩, exact ⟨u, hu.1, hu.2.2⟩, end lemma is_glb.exists_seq_strict_anti_tendsto_of_not_mem {t : set α} {x : α} [is_countably_generated (𝓝 x)] (htx : is_glb t x) (not_mem : x ∉ t) (ht : t.nonempty) : ∃ u : ℕ → α, strict_anti u ∧ (∀ n, x < u n) ∧ tendsto u at_top (𝓝 x) ∧ (∀ n, u n ∈ t) := @is_lub.exists_seq_strict_mono_tendsto_of_not_mem αᵒᵈ _ _ _ t x _ htx not_mem ht lemma is_glb.exists_seq_antitone_tendsto {t : set α} {x : α} [is_countably_generated (𝓝 x)] (htx : is_glb t x) (ht : t.nonempty) : ∃ u : ℕ → α, antitone u ∧ (∀ n, x ≤ u n) ∧ tendsto u at_top (𝓝 x) ∧ (∀ n, u n ∈ t) := @is_lub.exists_seq_monotone_tendsto αᵒᵈ _ _ _ t x _ htx ht lemma exists_seq_strict_anti_tendsto' [densely_ordered α] [first_countable_topology α] {x y : α} (hy : x < y) : ∃ u : ℕ → α, strict_anti u ∧ (∀ n, u n ∈ Ioo x y) ∧ tendsto u at_top (𝓝 x) := by simpa only [dual_Ioo] using exists_seq_strict_mono_tendsto' (order_dual.to_dual_lt_to_dual.2 hy) lemma exists_seq_strict_anti_tendsto [densely_ordered α] [no_max_order α] [first_countable_topology α] (x : α) : ∃ u : ℕ → α, strict_anti u ∧ (∀ n, x < u n) ∧ tendsto u at_top (𝓝 x) := @exists_seq_strict_mono_tendsto αᵒᵈ _ _ _ _ _ _ x lemma exists_seq_strict_anti_strict_mono_tendsto [densely_ordered α] [first_countable_topology α] {x y : α} (h : x < y) : ∃ (u v : ℕ → α), strict_anti u ∧ strict_mono v ∧ (∀ k, u k ∈ Ioo x y) ∧ (∀ l, v l ∈ Ioo x y) ∧ (∀ k l, u k < v l) ∧ tendsto u at_top (𝓝 x) ∧ tendsto v at_top (𝓝 y) := begin rcases exists_seq_strict_anti_tendsto' h with ⟨u, hu_anti, hu_mem, hux⟩, rcases exists_seq_strict_mono_tendsto' (hu_mem 0).2 with ⟨v, hv_mono, hv_mem, hvy⟩, exact ⟨u, v, hu_anti, hv_mono, hu_mem, λ l, ⟨(hu_mem 0).1.trans (hv_mem l).1, (hv_mem l).2⟩, λ k l, (hu_anti.antitone (zero_le k)).trans_lt (hv_mem l).1, hux, hvy⟩ end lemma exists_seq_tendsto_Inf {α : Type*} [conditionally_complete_linear_order α] [topological_space α] [order_topology α] [first_countable_topology α] {S : set α} (hS : S.nonempty) (hS' : bdd_below S) : ∃ (u : ℕ → α), antitone u ∧ tendsto u at_top (𝓝 (Inf S)) ∧ (∀ n, u n ∈ S) := @exists_seq_tendsto_Sup αᵒᵈ _ _ _ _ S hS hS' end order_topology section densely_ordered variables [topological_space α] [linear_order α] [order_topology α] [densely_ordered α] {a b : α} {s : set α} /-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`, unless `a` is a top element. -/ lemma closure_Ioi' {a : α} (h : (Ioi a).nonempty) : closure (Ioi a) = Ici a := begin apply subset.antisymm, { exact closure_minimal Ioi_subset_Ici_self is_closed_Ici }, { rw [← diff_subset_closure_iff, Ici_diff_Ioi_same, singleton_subset_iff], exact is_glb_Ioi.mem_closure h } end /-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`. -/ @[simp] lemma closure_Ioi (a : α) [no_max_order α] : closure (Ioi a) = Ici a := closure_Ioi' nonempty_Ioi /-- The closure of the interval `(-∞, a)` is the closed interval `(-∞, a]`, unless `a` is a bottom element. -/ lemma closure_Iio' (h : (Iio a).nonempty) : closure (Iio a) = Iic a := @closure_Ioi' αᵒᵈ _ _ _ _ _ h /-- The closure of the interval `(-∞, a)` is the interval `(-∞, a]`. -/ @[simp] lemma closure_Iio (a : α) [no_min_order α] : closure (Iio a) = Iic a := closure_Iio' nonempty_Iio /-- The closure of the open interval `(a, b)` is the closed interval `[a, b]`. -/ @[simp] lemma closure_Ioo {a b : α} (hab : a ≠ b) : closure (Ioo a b) = Icc a b := begin apply subset.antisymm, { exact closure_minimal Ioo_subset_Icc_self is_closed_Icc }, { cases hab.lt_or_lt with hab hab, { rw [← diff_subset_closure_iff, Icc_diff_Ioo_same hab.le], have hab' : (Ioo a b).nonempty, from nonempty_Ioo.2 hab, simp only [insert_subset, singleton_subset_iff], exact ⟨(is_glb_Ioo hab).mem_closure hab', (is_lub_Ioo hab).mem_closure hab'⟩ }, { rw Icc_eq_empty_of_lt hab, exact empty_subset _ } } end /-- The closure of the interval `(a, b]` is the closed interval `[a, b]`. -/ @[simp] lemma closure_Ioc {a b : α} (hab : a ≠ b) : closure (Ioc a b) = Icc a b := begin apply subset.antisymm, { exact closure_minimal Ioc_subset_Icc_self is_closed_Icc }, { apply subset.trans _ (closure_mono Ioo_subset_Ioc_self), rw closure_Ioo hab } end /-- The closure of the interval `[a, b)` is the closed interval `[a, b]`. -/ @[simp] lemma closure_Ico {a b : α} (hab : a ≠ b) : closure (Ico a b) = Icc a b := begin apply subset.antisymm, { exact closure_minimal Ico_subset_Icc_self is_closed_Icc }, { apply subset.trans _ (closure_mono Ioo_subset_Ico_self), rw closure_Ioo hab } end @[simp] lemma interior_Ici' {a : α} (ha : (Iio a).nonempty) : interior (Ici a) = Ioi a := by rw [← compl_Iio, interior_compl, closure_Iio' ha, compl_Iic] lemma interior_Ici [no_min_order α] {a : α} : interior (Ici a) = Ioi a := interior_Ici' nonempty_Iio @[simp] lemma interior_Iic' {a : α} (ha : (Ioi a).nonempty) : interior (Iic a) = Iio a := @interior_Ici' αᵒᵈ _ _ _ _ _ ha lemma interior_Iic [no_max_order α] {a : α} : interior (Iic a) = Iio a := interior_Iic' nonempty_Ioi @[simp] lemma interior_Icc [no_min_order α] [no_max_order α] {a b : α}: interior (Icc a b) = Ioo a b := by rw [← Ici_inter_Iic, interior_inter, interior_Ici, interior_Iic, Ioi_inter_Iio] @[simp] lemma interior_Ico [no_min_order α] {a b : α} : interior (Ico a b) = Ioo a b := by rw [← Ici_inter_Iio, interior_inter, interior_Ici, interior_Iio, Ioi_inter_Iio] @[simp] lemma interior_Ioc [no_max_order α] {a b : α} : interior (Ioc a b) = Ioo a b := by rw [← Ioi_inter_Iic, interior_inter, interior_Ioi, interior_Iic, Ioi_inter_Iio] lemma closure_interior_Icc {a b : α} (h : a ≠ b) : closure (interior (Icc a b)) = Icc a b := (closure_minimal interior_subset is_closed_Icc).antisymm $ calc Icc a b = closure (Ioo a b) : (closure_Ioo h).symm ... ⊆ closure (interior (Icc a b)) : closure_mono (interior_maximal Ioo_subset_Icc_self is_open_Ioo) lemma Ioc_subset_closure_interior (a b : α) : Ioc a b ⊆ closure (interior (Ioc a b)) := begin rcases eq_or_ne a b with rfl|h, { simp }, { calc Ioc a b ⊆ Icc a b : Ioc_subset_Icc_self ... = closure (Ioo a b) : (closure_Ioo h).symm ... ⊆ closure (interior (Ioc a b)) : closure_mono (interior_maximal Ioo_subset_Ioc_self is_open_Ioo) } end lemma Ico_subset_closure_interior (a b : α) : Ico a b ⊆ closure (interior (Ico a b)) := by simpa only [dual_Ioc] using Ioc_subset_closure_interior (order_dual.to_dual b) (order_dual.to_dual a) @[simp] lemma frontier_Ici' {a : α} (ha : (Iio a).nonempty) : frontier (Ici a) = {a} := by simp [frontier, ha] lemma frontier_Ici [no_min_order α] {a : α} : frontier (Ici a) = {a} := frontier_Ici' nonempty_Iio @[simp] lemma frontier_Iic' {a : α} (ha : (Ioi a).nonempty) : frontier (Iic a) = {a} := by simp [frontier, ha] lemma frontier_Iic [no_max_order α] {a : α} : frontier (Iic a) = {a} := frontier_Iic' nonempty_Ioi @[simp] lemma frontier_Ioi' {a : α} (ha : (Ioi a).nonempty) : frontier (Ioi a) = {a} := by simp [frontier, closure_Ioi' ha, Iic_diff_Iio, Icc_self] lemma frontier_Ioi [no_max_order α] {a : α} : frontier (Ioi a) = {a} := frontier_Ioi' nonempty_Ioi @[simp] lemma frontier_Iio' {a : α} (ha : (Iio a).nonempty) : frontier (Iio a) = {a} := by simp [frontier, closure_Iio' ha, Iic_diff_Iio, Icc_self] lemma frontier_Iio [no_min_order α] {a : α} : frontier (Iio a) = {a} := frontier_Iio' nonempty_Iio @[simp] lemma frontier_Icc [no_min_order α] [no_max_order α] {a b : α} (h : a < b) : frontier (Icc a b) = {a, b} := by simp [frontier, le_of_lt h, Icc_diff_Ioo_same] @[simp] lemma frontier_Ioo {a b : α} (h : a < b) : frontier (Ioo a b) = {a, b} := by rw [frontier, closure_Ioo h.ne, interior_Ioo, Icc_diff_Ioo_same h.le] @[simp] lemma frontier_Ico [no_min_order α] {a b : α} (h : a < b) : frontier (Ico a b) = {a, b} := by rw [frontier, closure_Ico h.ne, interior_Ico, Icc_diff_Ioo_same h.le] @[simp] lemma frontier_Ioc [no_max_order α] {a b : α} (h : a < b) : frontier (Ioc a b) = {a, b} := by rw [frontier, closure_Ioc h.ne, interior_Ioc, Icc_diff_Ioo_same h.le] lemma nhds_within_Ioi_ne_bot' {a b : α} (H₁ : (Ioi a).nonempty) (H₂ : a ≤ b) : ne_bot (𝓝[Ioi a] b) := mem_closure_iff_nhds_within_ne_bot.1 $ by rwa [closure_Ioi' H₁] lemma nhds_within_Ioi_ne_bot [no_max_order α] {a b : α} (H : a ≤ b) : ne_bot (𝓝[Ioi a] b) := nhds_within_Ioi_ne_bot' nonempty_Ioi H lemma nhds_within_Ioi_self_ne_bot' {a : α} (H : (Ioi a).nonempty) : ne_bot (𝓝[>] a) := nhds_within_Ioi_ne_bot' H (le_refl a) @[instance] lemma nhds_within_Ioi_self_ne_bot [no_max_order α] (a : α) : ne_bot (𝓝[>] a) := nhds_within_Ioi_ne_bot (le_refl a) lemma filter.eventually.exists_gt [no_max_order α] {a : α} {p : α → Prop} (h : ∀ᶠ x in 𝓝 a, p x) : ∃ b > a, p b := by simpa only [exists_prop, gt_iff_lt, and_comm] using ((h.filter_mono (@nhds_within_le_nhds _ _ a (Ioi a))).and self_mem_nhds_within).exists lemma nhds_within_Iio_ne_bot' {b c : α} (H₁ : (Iio c).nonempty) (H₂ : b ≤ c) : ne_bot (𝓝[Iio c] b) := mem_closure_iff_nhds_within_ne_bot.1 $ by rwa closure_Iio' H₁ lemma nhds_within_Iio_ne_bot [no_min_order α] {a b : α} (H : a ≤ b) : ne_bot (𝓝[Iio b] a) := nhds_within_Iio_ne_bot' nonempty_Iio H lemma nhds_within_Iio_self_ne_bot' {b : α} (H : (Iio b).nonempty) : ne_bot (𝓝[<] b) := nhds_within_Iio_ne_bot' H (le_refl b) @[instance] lemma nhds_within_Iio_self_ne_bot [no_min_order α] (a : α) : ne_bot (𝓝[<] a) := nhds_within_Iio_ne_bot (le_refl a) lemma filter.eventually.exists_lt [no_min_order α] {a : α} {p : α → Prop} (h : ∀ᶠ x in 𝓝 a, p x) : ∃ b < a, p b := @filter.eventually.exists_gt αᵒᵈ _ _ _ _ _ _ _ h lemma right_nhds_within_Ico_ne_bot {a b : α} (H : a < b) : ne_bot (𝓝[Ico a b] b) := (is_lub_Ico H).nhds_within_ne_bot (nonempty_Ico.2 H) lemma left_nhds_within_Ioc_ne_bot {a b : α} (H : a < b) : ne_bot (𝓝[Ioc a b] a) := (is_glb_Ioc H).nhds_within_ne_bot (nonempty_Ioc.2 H) lemma left_nhds_within_Ioo_ne_bot {a b : α} (H : a < b) : ne_bot (𝓝[Ioo a b] a) := (is_glb_Ioo H).nhds_within_ne_bot (nonempty_Ioo.2 H) lemma right_nhds_within_Ioo_ne_bot {a b : α} (H : a < b) : ne_bot (𝓝[Ioo a b] b) := (is_lub_Ioo H).nhds_within_ne_bot (nonempty_Ioo.2 H) lemma comap_coe_nhds_within_Iio_of_Ioo_subset (hb : s ⊆ Iio b) (hs : s.nonempty → ∃ a < b, Ioo a b ⊆ s) : comap (coe : s → α) (𝓝[<] b) = at_top := begin nontriviality, haveI : nonempty s := nontrivial_iff_nonempty.1 ‹_›, rcases hs (nonempty_subtype.1 ‹_›) with ⟨a, h, hs⟩, ext u, split, { rintros ⟨t, ht, hts⟩, obtain ⟨x, ⟨hxa : a ≤ x, hxb : x < b⟩, hxt : Ioo x b ⊆ t⟩ := (mem_nhds_within_Iio_iff_exists_mem_Ico_Ioo_subset h).mp ht, obtain ⟨y, hxy, hyb⟩ := exists_between hxb, refine mem_of_superset (mem_at_top ⟨y, hs ⟨hxa.trans_lt hxy, hyb⟩⟩) _, rintros ⟨z, hzs⟩ (hyz : y ≤ z), refine hts (hxt ⟨hxy.trans_le _, hb _⟩); assumption }, { intros hu, obtain ⟨x : s, hx : ∀ z, x ≤ z → z ∈ u⟩ := mem_at_top_sets.1 hu, exact ⟨Ioo x b, Ioo_mem_nhds_within_Iio (right_mem_Ioc.2 $ hb x.2), λ z hz, hx _ hz.1.le⟩ } end lemma comap_coe_nhds_within_Ioi_of_Ioo_subset (ha : s ⊆ Ioi a) (hs : s.nonempty → ∃ b > a, Ioo a b ⊆ s) : comap (coe : s → α) (𝓝[>] a) = at_bot := comap_coe_nhds_within_Iio_of_Ioo_subset (show of_dual ⁻¹' s ⊆ Iio (to_dual a), from ha) (λ h, by simpa only [order_dual.exists, dual_Ioo] using hs h) lemma map_coe_at_top_of_Ioo_subset (hb : s ⊆ Iio b) (hs : ∀ a' < b, ∃ a < b, Ioo a b ⊆ s) : map (coe : s → α) at_top = 𝓝[<] b := begin rcases eq_empty_or_nonempty (Iio b) with (hb'|⟨a, ha⟩), { rw [filter_eq_bot_of_is_empty at_top, filter.map_bot, hb', nhds_within_empty], exact ⟨λ x, hb'.subset (hb x.2)⟩ }, { rw [← comap_coe_nhds_within_Iio_of_Ioo_subset hb (λ _, hs a ha), map_comap_of_mem], rw subtype.range_coe, exact (mem_nhds_within_Iio_iff_exists_Ioo_subset' ha).2 (hs a ha) }, end lemma map_coe_at_bot_of_Ioo_subset (ha : s ⊆ Ioi a) (hs : ∀ b' > a, ∃ b > a, Ioo a b ⊆ s) : map (coe : s → α) at_bot = (𝓝[>] a) := begin -- the elaborator gets stuck without `(... : _)` refine (map_coe_at_top_of_Ioo_subset (show of_dual ⁻¹' s ⊆ Iio (to_dual a), from ha) (λ b' hb', _) : _), simpa only [order_dual.exists, dual_Ioo] using hs b' hb', end /-- The `at_top` filter for an open interval `Ioo a b` comes from the left-neighbourhoods filter at the right endpoint in the ambient order. -/ lemma comap_coe_Ioo_nhds_within_Iio (a b : α) : comap (coe : Ioo a b → α) (𝓝[<] b) = at_top := comap_coe_nhds_within_Iio_of_Ioo_subset Ioo_subset_Iio_self $ λ h, ⟨a, nonempty_Ioo.1 h, subset.refl _⟩ /-- The `at_bot` filter for an open interval `Ioo a b` comes from the right-neighbourhoods filter at the left endpoint in the ambient order. -/ lemma comap_coe_Ioo_nhds_within_Ioi (a b : α) : comap (coe : Ioo a b → α) (𝓝[>] a) = at_bot := comap_coe_nhds_within_Ioi_of_Ioo_subset Ioo_subset_Ioi_self $ λ h, ⟨b, nonempty_Ioo.1 h, subset.refl _⟩ lemma comap_coe_Ioi_nhds_within_Ioi (a : α) : comap (coe : Ioi a → α) (𝓝[>] a) = at_bot := comap_coe_nhds_within_Ioi_of_Ioo_subset (subset.refl _) $ λ ⟨x, hx⟩, ⟨x, hx, Ioo_subset_Ioi_self⟩ lemma comap_coe_Iio_nhds_within_Iio (a : α) : comap (coe : Iio a → α) (𝓝[<] a) = at_top := @comap_coe_Ioi_nhds_within_Ioi αᵒᵈ _ _ _ _ a @[simp] lemma map_coe_Ioo_at_top {a b : α} (h : a < b) : map (coe : Ioo a b → α) at_top = 𝓝[<] b := map_coe_at_top_of_Ioo_subset Ioo_subset_Iio_self $ λ _ _, ⟨_, h, subset.refl _⟩ @[simp] lemma map_coe_Ioo_at_bot {a b : α} (h : a < b) : map (coe : Ioo a b → α) at_bot = 𝓝[>] a := map_coe_at_bot_of_Ioo_subset Ioo_subset_Ioi_self $ λ _ _, ⟨_, h, subset.refl _⟩ @[simp] lemma map_coe_Ioi_at_bot (a : α) : map (coe : Ioi a → α) at_bot = 𝓝[>] a := map_coe_at_bot_of_Ioo_subset (subset.refl _) $ λ b hb, ⟨b, hb, Ioo_subset_Ioi_self⟩ @[simp] lemma map_coe_Iio_at_top (a : α) : map (coe : Iio a → α) at_top = 𝓝[<] a := @map_coe_Ioi_at_bot αᵒᵈ _ _ _ _ _ variables {l : filter β} {f : α → β} @[simp] lemma tendsto_comp_coe_Ioo_at_top (h : a < b) : tendsto (λ x : Ioo a b, f x) at_top l ↔ tendsto f (𝓝[<] b) l := by rw [← map_coe_Ioo_at_top h, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Ioo_at_bot (h : a < b) : tendsto (λ x : Ioo a b, f x) at_bot l ↔ tendsto f (𝓝[>] a) l := by rw [← map_coe_Ioo_at_bot h, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Ioi_at_bot : tendsto (λ x : Ioi a, f x) at_bot l ↔ tendsto f (𝓝[>] a) l := by rw [← map_coe_Ioi_at_bot, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Iio_at_top : tendsto (λ x : Iio a, f x) at_top l ↔ tendsto f (𝓝[<] a) l := by rw [← map_coe_Iio_at_top, tendsto_map'_iff] @[simp] lemma tendsto_Ioo_at_top {f : β → Ioo a b} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l (𝓝[<] b) := by rw [← comap_coe_Ioo_nhds_within_Iio, tendsto_comap_iff] @[simp] lemma tendsto_Ioo_at_bot {f : β → Ioo a b} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l (𝓝[>] a) := by rw [← comap_coe_Ioo_nhds_within_Ioi, tendsto_comap_iff] @[simp] lemma tendsto_Ioi_at_bot {f : β → Ioi a} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l (𝓝[>] a) := by rw [← comap_coe_Ioi_nhds_within_Ioi, tendsto_comap_iff] @[simp] lemma tendsto_Iio_at_top {f : β → Iio a} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l (𝓝[<] a) := by rw [← comap_coe_Iio_nhds_within_Iio, tendsto_comap_iff] instance (x : α) [nontrivial α] : ne_bot (𝓝[≠] x) := begin apply forall_mem_nonempty_iff_ne_bot.1 (λ s hs, _), obtain ⟨u, u_open, xu, us⟩ : ∃ (u : set α), is_open u ∧ x ∈ u ∧ u ∩ {x}ᶜ ⊆ s := mem_nhds_within.1 hs, obtain ⟨a, b, a_lt_b, hab⟩ : ∃ (a b : α), a < b ∧ Ioo a b ⊆ u := u_open.exists_Ioo_subset ⟨x, xu⟩, obtain ⟨y, hy⟩ : ∃ y, a < y ∧ y < b := exists_between a_lt_b, rcases ne_or_eq x y with xy|rfl, { exact ⟨y, us ⟨hab hy, xy.symm⟩⟩ }, obtain ⟨z, hz⟩ : ∃ z, a < z ∧ z < x := exists_between hy.1, exact ⟨z, us ⟨hab ⟨hz.1, hz.2.trans hy.2⟩, hz.2.ne⟩⟩, end /-- Let `s` be a dense set in a nontrivial dense linear order `α`. If `s` is a separable space (e.g., if `α` has a second countable topology), then there exists a countable dense subset `t ⊆ s` such that `t` does not contain bottom/top elements of `α`. -/ lemma dense.exists_countable_dense_subset_no_bot_top [nontrivial α] {s : set α} [separable_space s] (hs : dense s) : ∃ t ⊆ s, t.countable ∧ dense t ∧ (∀ x, is_bot x → x ∉ t) ∧ (∀ x, is_top x → x ∉ t) := begin rcases hs.exists_countable_dense_subset with ⟨t, hts, htc, htd⟩, refine ⟨t \ ({x | is_bot x} ∪ {x | is_top x}), _, _, _, _, _⟩, { exact (diff_subset _ _).trans hts }, { exact htc.mono (diff_subset _ _) }, { exact htd.diff_finite ((subsingleton_is_bot α).finite.union (subsingleton_is_top α).finite) }, { assume x hx, simp [hx] }, { assume x hx, simp [hx] } end variable (α) /-- If `α` is a nontrivial separable dense linear order, then there exists a countable dense set `s : set α` that contains neither top nor bottom elements of `α`. For a dense set containing both bot and top elements, see `exists_countable_dense_bot_top`. -/ lemma exists_countable_dense_no_bot_top [separable_space α] [nontrivial α] : ∃ s : set α, s.countable ∧ dense s ∧ (∀ x, is_bot x → x ∉ s) ∧ (∀ x, is_top x → x ∉ s) := by simpa using dense_univ.exists_countable_dense_subset_no_bot_top end densely_ordered section complete_linear_order variables [complete_linear_order α] [topological_space α] [order_topology α] [complete_linear_order β] [topological_space β] [order_closed_topology β] [nonempty γ] lemma Sup_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) : Sup s ∈ closure s := (is_lub_Sup s).mem_closure hs lemma Inf_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) : Inf s ∈ closure s := (is_glb_Inf s).mem_closure hs lemma is_closed.Sup_mem {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) (hc : is_closed s) : Sup s ∈ s := (is_lub_Sup s).mem_of_is_closed hs hc lemma is_closed.Inf_mem {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) (hc : is_closed s) : Inf s ∈ s := (is_glb_Inf s).mem_of_is_closed hs hc /-- A monotone function continuous at the supremum of a nonempty set sends this supremum to the supremum of the image of this set. -/ lemma monotone.map_Sup_of_continuous_at' {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Mf : monotone f) (hs : s.nonempty) : f (Sup s) = Sup (f '' s) := --This is a particular case of the more general is_lub.is_lub_of_tendsto ((is_lub_Sup _).is_lub_of_tendsto (λ x hx y hy xy, Mf xy) hs $ Cf.mono_left inf_le_left).Sup_eq.symm /-- A monotone function `f` sending `bot` to `bot` and continuous at the supremum of a set sends this supremum to the supremum of the image of this set. -/ lemma monotone.map_Sup_of_continuous_at {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Mf : monotone f) (fbot : f ⊥ = ⊥) : f (Sup s) = Sup (f '' s) := begin cases s.eq_empty_or_nonempty with h h, { simp [h, fbot] }, { exact Mf.map_Sup_of_continuous_at' Cf h } end /-- A monotone function continuous at the indexed supremum over a nonempty `Sort` sends this indexed supremum to the indexed supremum of the composition. -/ lemma monotone.map_supr_of_continuous_at' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α} (Cf : continuous_at f (supr g)) (Mf : monotone f) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, Mf.map_Sup_of_continuous_at' Cf (range_nonempty g), ← range_comp, supr] /-- If a monotone function sending `bot` to `bot` is continuous at the indexed supremum over a `Sort`, then it sends this indexed supremum to the indexed supremum of the composition. -/ lemma monotone.map_supr_of_continuous_at {ι : Sort*} {f : α → β} {g : ι → α} (Cf : continuous_at f (supr g)) (Mf : monotone f) (fbot : f ⊥ = ⊥) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, Mf.map_Sup_of_continuous_at Cf fbot, ← range_comp, supr] /-- A monotone function continuous at the infimum of a nonempty set sends this infimum to the infimum of the image of this set. -/ lemma monotone.map_Inf_of_continuous_at' {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Mf : monotone f) (hs : s.nonempty) : f (Inf s) = Inf (f '' s) := @monotone.map_Sup_of_continuous_at' αᵒᵈ βᵒᵈ _ _ _ _ _ _ f s Cf Mf.dual hs /-- A monotone function `f` sending `top` to `top` and continuous at the infimum of a set sends this infimum to the infimum of the image of this set. -/ lemma monotone.map_Inf_of_continuous_at {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Mf : monotone f) (ftop : f ⊤ = ⊤) : f (Inf s) = Inf (f '' s) := @monotone.map_Sup_of_continuous_at αᵒᵈ βᵒᵈ _ _ _ _ _ _ f s Cf Mf.dual ftop /-- A monotone function continuous at the indexed infimum over a nonempty `Sort` sends this indexed infimum to the indexed infimum of the composition. -/ lemma monotone.map_infi_of_continuous_at' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α} (Cf : continuous_at f (infi g)) (Mf : monotone f) : f (⨅ i, g i) = ⨅ i, f (g i) := @monotone.map_supr_of_continuous_at' αᵒᵈ βᵒᵈ _ _ _ _ _ _ ι _ f g Cf Mf.dual /-- If a monotone function sending `top` to `top` is continuous at the indexed infimum over a `Sort`, then it sends this indexed infimum to the indexed infimum of the composition. -/ lemma monotone.map_infi_of_continuous_at {ι : Sort*} {f : α → β} {g : ι → α} (Cf : continuous_at f (infi g)) (Mf : monotone f) (ftop : f ⊤ = ⊤) : f (infi g) = infi (f ∘ g) := @monotone.map_supr_of_continuous_at αᵒᵈ βᵒᵈ _ _ _ _ _ _ ι f g Cf Mf.dual ftop /-- An antitone function continuous at the supremum of a nonempty set sends this supremum to the infimum of the image of this set. -/ lemma antitone.map_Sup_of_continuous_at' {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Af : antitone f) (hs : s.nonempty) : f (Sup s) = Inf (f '' s) := monotone.map_Sup_of_continuous_at' (show continuous_at (order_dual.to_dual ∘ f) (Sup s), from Cf) Af hs /-- An antitone function `f` sending `bot` to `top` and continuous at the supremum of a set sends this supremum to the infimum of the image of this set. -/ lemma antitone.map_Sup_of_continuous_at {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Af : antitone f) (fbot : f ⊥ = ⊤) : f (Sup s) = Inf (f '' s) := monotone.map_Sup_of_continuous_at (show continuous_at (order_dual.to_dual ∘ f) (Sup s), from Cf) Af fbot /-- An antitone function continuous at the indexed supremum over a nonempty `Sort` sends this indexed supremum to the indexed infimum of the composition. -/ lemma antitone.map_supr_of_continuous_at' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α} (Cf : continuous_at f (supr g)) (Af : antitone f) : f (⨆ i, g i) = ⨅ i, f (g i) := monotone.map_supr_of_continuous_at' (show continuous_at (order_dual.to_dual ∘ f) (supr g), from Cf) Af /-- An antitone function sending `bot` to `top` is continuous at the indexed supremum over a `Sort`, then it sends this indexed supremum to the indexed supremum of the composition. -/ lemma antitone.map_supr_of_continuous_at {ι : Sort*} {f : α → β} {g : ι → α} (Cf : continuous_at f (supr g)) (Af : antitone f) (fbot : f ⊥ = ⊤) : f (⨆ i, g i) = ⨅ i, f (g i) := monotone.map_supr_of_continuous_at (show continuous_at (order_dual.to_dual ∘ f) (supr g), from Cf) Af fbot /-- An antitone function continuous at the infimum of a nonempty set sends this infimum to the supremum of the image of this set. -/ lemma antitone.map_Inf_of_continuous_at' {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Af : antitone f) (hs : s.nonempty) : f (Inf s) = Sup (f '' s) := monotone.map_Inf_of_continuous_at' (show continuous_at (order_dual.to_dual ∘ f) (Inf s), from Cf) Af hs /-- An antitone function `f` sending `top` to `bot` and continuous at the infimum of a set sends this infimum to the supremum of the image of this set. -/ lemma antitone.map_Inf_of_continuous_at {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Af : antitone f) (ftop : f ⊤ = ⊥) : f (Inf s) = Sup (f '' s) := monotone.map_Inf_of_continuous_at (show continuous_at (order_dual.to_dual ∘ f) (Inf s), from Cf) Af ftop /-- An antitone function continuous at the indexed infimum over a nonempty `Sort` sends this indexed infimum to the indexed supremum of the composition. -/ lemma antitone.map_infi_of_continuous_at' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α} (Cf : continuous_at f (infi g)) (Af : antitone f) : f (⨅ i, g i) = ⨆ i, f (g i) := monotone.map_infi_of_continuous_at' (show continuous_at (order_dual.to_dual ∘ f) (infi g), from Cf) Af /-- If an antitone function sending `top` to `bot` is continuous at the indexed infimum over a `Sort`, then it sends this indexed infimum to the indexed supremum of the composition. -/ lemma antitone.map_infi_of_continuous_at {ι : Sort*} {f : α → β} {g : ι → α} (Cf : continuous_at f (infi g)) (Af : antitone f) (ftop : f ⊤ = ⊥) : f (infi g) = supr (f ∘ g) := monotone.map_infi_of_continuous_at (show continuous_at (order_dual.to_dual ∘ f) (infi g), from Cf) Af ftop end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [topological_space α] [order_topology α] [conditionally_complete_linear_order β] [topological_space β] [order_closed_topology β] [nonempty γ] lemma cSup_mem_closure {s : set α} (hs : s.nonempty) (B : bdd_above s) : Sup s ∈ closure s := (is_lub_cSup hs B).mem_closure hs lemma cInf_mem_closure {s : set α} (hs : s.nonempty) (B : bdd_below s) : Inf s ∈ closure s := (is_glb_cInf hs B).mem_closure hs lemma is_closed.cSup_mem {s : set α} (hc : is_closed s) (hs : s.nonempty) (B : bdd_above s) : Sup s ∈ s := (is_lub_cSup hs B).mem_of_is_closed hs hc lemma is_closed.cInf_mem {s : set α} (hc : is_closed s) (hs : s.nonempty) (B : bdd_below s) : Inf s ∈ s := (is_glb_cInf hs B).mem_of_is_closed hs hc /-- If a monotone function is continuous at the supremum of a nonempty bounded above set `s`, then it sends this supremum to the supremum of the image of `s`. -/ lemma monotone.map_cSup_of_continuous_at {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Mf : monotone f) (ne : s.nonempty) (H : bdd_above s) : f (Sup s) = Sup (f '' s) := begin refine ((is_lub_cSup (ne.image f) (Mf.map_bdd_above H)).unique _).symm, refine (is_lub_cSup ne H).is_lub_of_tendsto (λx hx y hy xy, Mf xy) ne _, exact Cf.mono_left inf_le_left end /-- If a monotone function is continuous at the indexed supremum of a bounded function on a nonempty `Sort`, then it sends this supremum to the supremum of the composition. -/ lemma monotone.map_csupr_of_continuous_at {f : α → β} {g : γ → α} (Cf : continuous_at f (⨆ i, g i)) (Mf : monotone f) (H : bdd_above (range g)) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, Mf.map_cSup_of_continuous_at Cf (range_nonempty _) H, ← range_comp, supr] /-- If a monotone function is continuous at the infimum of a nonempty bounded below set `s`, then it sends this infimum to the infimum of the image of `s`. -/ lemma monotone.map_cInf_of_continuous_at {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Mf : monotone f) (ne : s.nonempty) (H : bdd_below s) : f (Inf s) = Inf (f '' s) := @monotone.map_cSup_of_continuous_at αᵒᵈ βᵒᵈ _ _ _ _ _ _ f s Cf Mf.dual ne H /-- A continuous monotone function sends indexed infimum to indexed infimum in conditionally complete linear order, under a boundedness assumption. -/ lemma monotone.map_cinfi_of_continuous_at {f : α → β} {g : γ → α} (Cf : continuous_at f (⨅ i, g i)) (Mf : monotone f) (H : bdd_below (range g)) : f (⨅ i, g i) = ⨅ i, f (g i) := @monotone.map_csupr_of_continuous_at αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ _ _ _ Cf Mf.dual H /-- If an antitone function is continuous at the supremum of a nonempty bounded above set `s`, then it sends this supremum to the infimum of the image of `s`. -/ lemma antitone.map_cSup_of_continuous_at {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Af : antitone f) (ne : s.nonempty) (H : bdd_above s) : f (Sup s) = Inf (f '' s) := monotone.map_cSup_of_continuous_at (show continuous_at (order_dual.to_dual ∘ f) (Sup s), from Cf) Af ne H /-- If an antitone function is continuous at the indexed supremum of a bounded function on a nonempty `Sort`, then it sends this supremum to the infimum of the composition. -/ lemma antitone.map_csupr_of_continuous_at {f : α → β} {g : γ → α} (Cf : continuous_at f (⨆ i, g i)) (Af : antitone f) (H : bdd_above (range g)) : f (⨆ i, g i) = ⨅ i, f (g i) := monotone.map_csupr_of_continuous_at (show continuous_at (order_dual.to_dual ∘ f) (⨆ i, g i), from Cf) Af H /-- If an antitone function is continuous at the infimum of a nonempty bounded below set `s`, then it sends this infimum to the supremum of the image of `s`. -/ lemma antitone.map_cInf_of_continuous_at {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Af : antitone f) (ne : s.nonempty) (H : bdd_below s) : f (Inf s) = Sup (f '' s) := monotone.map_cInf_of_continuous_at (show continuous_at (order_dual.to_dual ∘ f) (Inf s), from Cf) Af ne H /-- A continuous antitone function sends indexed infimum to indexed supremum in conditionally complete linear order, under a boundedness assumption. -/ lemma antitone.map_cinfi_of_continuous_at {f : α → β} {g : γ → α} (Cf : continuous_at f (⨅ i, g i)) (Af : antitone f) (H : bdd_below (range g)) : f (⨅ i, g i) = ⨆ i, f (g i) := monotone.map_cinfi_of_continuous_at (show continuous_at (order_dual.to_dual ∘ f) (⨅ i, g i), from Cf) Af H /-- A monotone map has a limit to the left of any point `x`, equal to `Sup (f '' (Iio x))`. -/ lemma monotone.tendsto_nhds_within_Iio {α β : Type*} [linear_order α] [topological_space α] [order_topology α] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] {f : α → β} (Mf : monotone f) (x : α) : tendsto f (𝓝[<] x) (𝓝 (Sup (f '' (Iio x)))) := begin rcases eq_empty_or_nonempty (Iio x) with h|h, { simp [h] }, refine tendsto_order.2 ⟨λ l hl, _, λ m hm, _⟩, { obtain ⟨z, zx, lz⟩ : ∃ (a : α), a < x ∧ l < f a, by simpa only [mem_image, exists_prop, exists_exists_and_eq_and] using exists_lt_of_lt_cSup (nonempty_image_iff.2 h) hl, exact (mem_nhds_within_Iio_iff_exists_Ioo_subset' zx).2 ⟨z, zx, λ y hy, lz.trans_le (Mf (hy.1.le))⟩ }, { filter_upwards [self_mem_nhds_within] with _ hy, apply lt_of_le_of_lt _ hm, exact le_cSup (Mf.map_bdd_above bdd_above_Iio) (mem_image_of_mem _ hy), }, end /-- A monotone map has a limit to the right of any point `x`, equal to `Inf (f '' (Ioi x))`. -/ lemma monotone.tendsto_nhds_within_Ioi {α β : Type*} [linear_order α] [topological_space α] [order_topology α] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] {f : α → β} (Mf : monotone f) (x : α) : tendsto f (𝓝[>] x) (𝓝 (Inf (f '' (Ioi x)))) := @monotone.tendsto_nhds_within_Iio αᵒᵈ βᵒᵈ _ _ _ _ _ _ f Mf.dual x end conditionally_complete_linear_order end order_topology
def39e86060b96b110677aa77c6778ff8b9c6319
7b66d83f3b69dae0a3dfb684d7ebe5e9e3f3c913
/src/exercises_sources/thursday/afternoon/category_theory/exercise7.lean
7ca24b0e02fe3fd9ce3998b1748c657776be5851
[]
permissive
dpochekutov/lftcm2020
58a09e10f0e638075b97884d3c2612eb90296adb
cdfbf1ac089f21058e523db73f2476c9c98ed16a
refs/heads/master
1,669,226,265,076
1,594,629,725,000
1,594,629,725,000
279,213,346
1
0
MIT
1,594,622,757,000
1,594,615,843,000
null
UTF-8
Lean
false
false
1,214
lean
import algebra.category.CommRing.basic import data.polynomial /-! Let show that taking polynomials over a ring is functor `Ring ⥤ Ring`. -/ noncomputable theory -- the default implementation of polynomials is noncomputable /-! mathlib is undergoing a transition at the moment from using "unbundled" homomorphisms (e.g. we talk about a bare function `f : R → S`, along with a typeclass `[is_semiring_hom f]`) to using "bundled" homomorphisms (e.g. a structure `f : R →+* S`, which has a coercion to a bare function). The category `Ring` uses bundled homomorphisms (and in future all of mathlib will). However at present the polynomial library hasn't been updated. You may find the `ring_hom.of` useful -- this upgrades an unbundled homomorphism to a bundled homomorphism. -/ /-! Hints: * use `polynomial.map` * use `polynomial.coeff_map` (what happens if you mark this as a `simp` lemma?) -/ def Ring.polynomial : Ring ⥤ Ring := sorry def CommRing.polynomial : CommRing ⥤ CommRing := sorry open category_theory def commutes : (forget₂ CommRing Ring) ⋙ Ring.polynomial ≅ CommRing.polynomial ⋙ (forget₂ CommRing Ring) := -- Hint: You can do this in two lines, ≤ 33 columns! sorry
31f9fe8fa80be8639710d997bc8321e05c8467f1
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/generalize_proofs.lean
0c79bd609af03a0c5ad40bbb10bef33b0b5931ce
[ "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
817
lean
import tactic.generalize_proofs example (x : ℕ) (h : x < 2) : classical.some ⟨x, h⟩ < 2 := begin generalize_proofs a, guard_hyp a : ∃ x, x < 2, guard_target classical.some a < 2, exact classical.some_spec a, end example (a : ∃ x, x < 2) : classical.some a < 2 := begin generalize_proofs, guard_target classical.some a < 2, exact classical.some_spec a, end example (x : ℕ) (h : x < 2) (a : ∃ x, x < 2) : classical.some a < 2 := begin generalize_proofs, guard_target classical.some a < 2, exact classical.some_spec a, end example (x : ℕ) (h : x < 2) (H : classical.some ⟨x, h⟩ < 2) : classical.some ⟨x, h⟩ < 2 := begin generalize_proofs a at H ⊢, guard_hyp a : ∃ x, x < 2, guard_hyp H : classical.some a < 2, guard_target classical.some a < 2, exact H, end
2c217e3d9d2042e03e2063fa66a58ecf26250bb9
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/univ_bug2.lean
3b7e3b83913f9c72174607dd4f8e72e85d6ddbba
[ "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
887
lean
---------------------------------------------------------------------------------------------------- --- Copyright (c) 2014 Microsoft Corporation. All rights reserved. --- Released under Apache 2.0 license as described in the file LICENSE. --- Author: Jeremy Avigad ---------------------------------------------------------------------------------------------------- open nat -- first define a class of homogeneous equality class inductive simplifies_to {T : Type} (t1 t2 : T) : Prop | mk : t1 = t2 → simplifies_to namespace simplifies_to theorem get_eq {T : Type} {t1 t2 : T} (C : simplifies_to t1 t2) : t1 = t2 := simplifies_to.rec (λx, x) C attribute [instance] theorem simp_app (S : Type) (T : Type) (f1 f2 : S → T) (s1 s2 : S) [C1 : simplifies_to f1 f2] [C2 : simplifies_to s1 s2] : simplifies_to (f1 s1) (f2 s2) := mk (congr (get_eq C1) (get_eq C2)) end simplifies_to
ddc7d417d610b8be1709aa6993d6fc600ce6c3a8
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/algebra/order_functions.lean
1d0092c3ed844a8b6e46b7369ac04fc75102c103
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
10,304
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.ordered_group order.lattice open lattice universes u v variables {α : Type u} {β : Type v} attribute [simp] max_eq_left max_eq_right min_eq_left min_eq_right /-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/ def strict_mono [has_lt α] [has_lt β] (f : α → β) : Prop := ∀ a b, a < b → f a < f b namespace strict_mono open ordering function section variables [linear_order α] [preorder β] {f : α → β} lemma lt_iff_lt (H : strict_mono f) {a b} : f a < f b ↔ a < b := ⟨λ h, ((lt_trichotomy b a) .resolve_left $ λ h', lt_asymm h $ H _ _ h') .resolve_left $ λ e, ne_of_gt h $ congr_arg _ e, H _ _⟩ lemma injective (H : strict_mono f) : injective f | a b e := ((lt_trichotomy a b) .resolve_left $ λ h, ne_of_lt (H _ _ h) e) .resolve_right $ λ h, ne_of_gt (H _ _ h) e theorem compares (H : strict_mono f) {a b} : ∀ {o}, compares o (f a) (f b) ↔ compares o a b | lt := H.lt_iff_lt | eq := ⟨λ h, H.injective h, congr_arg _⟩ | gt := H.lt_iff_lt lemma le_iff_le (H : strict_mono f) {a b} : f a ≤ f b ↔ a ≤ b := ⟨λ h, le_of_not_gt $ λ h', not_le_of_lt (H b a h') h, λ h, (lt_or_eq_of_le h).elim (λ h', le_of_lt (H _ _ h')) (λ h', h' ▸ le_refl _)⟩ end -- `preorder α` isn't strong enough: if the preorder on α is an equivalence relation, -- then `strict_mono f` is vacuously true. lemma monotone [partial_order α] [preorder β] {f : α → β} (H : strict_mono f) : monotone f := λ a b h, (lt_or_eq_of_le h).rec (le_of_lt ∘ (H _ _)) (by rintro rfl; refl) end strict_mono section open function variables [partial_order α] [partial_order β] {f : α → β} lemma strict_mono_of_monotone_of_injective (h₁ : monotone f) (h₂ : injective f) : strict_mono f := λ a b h, begin rw lt_iff_le_and_ne at ⊢ h, exact ⟨h₁ h.1, λ e, h.2 (h₂ e)⟩ end end section variables [decidable_linear_order α] [decidable_linear_order β] {f : α → β} {a b c d : α} -- translate from lattices to linear orders (sup → max, inf → min) @[simp] lemma le_min_iff : c ≤ min a b ↔ c ≤ a ∧ c ≤ b := le_inf_iff @[simp] lemma max_le_iff : max a b ≤ c ↔ a ≤ c ∧ b ≤ c := sup_le_iff lemma max_le_max : a ≤ c → b ≤ d → max a b ≤ max c d := sup_le_sup lemma min_le_min : a ≤ c → b ≤ d → min a b ≤ min c d := inf_le_inf lemma le_max_left_of_le : a ≤ b → a ≤ max b c := le_sup_left_of_le lemma le_max_right_of_le : a ≤ c → a ≤ max b c := le_sup_right_of_le lemma min_le_left_of_le : a ≤ c → min a b ≤ c := inf_le_left_of_le lemma min_le_right_of_le : b ≤ c → min a b ≤ c := inf_le_right_of_le lemma max_min_distrib_left : max a (min b c) = min (max a b) (max a c) := sup_inf_left lemma max_min_distrib_right : max (min a b) c = min (max a c) (max b c) := sup_inf_right lemma min_max_distrib_left : min a (max b c) = max (min a b) (min a c) := inf_sup_left lemma min_max_distrib_right : min (max a b) c = max (min a c) (min b c) := inf_sup_right instance max_idem : is_idempotent α max := by apply_instance instance min_idem : is_idempotent α min := by apply_instance @[simp] lemma min_le_iff : min a b ≤ c ↔ a ≤ c ∨ b ≤ c := have a ≤ b → (a ≤ c ∨ b ≤ c ↔ a ≤ c), from assume h, or_iff_left_of_imp $ le_trans h, have b ≤ a → (a ≤ c ∨ b ≤ c ↔ b ≤ c), from assume h, or_iff_right_of_imp $ le_trans h, by cases le_total a b; simp * @[simp] lemma le_max_iff : a ≤ max b c ↔ a ≤ b ∨ a ≤ c := have b ≤ c → (a ≤ b ∨ a ≤ c ↔ a ≤ c), from assume h, or_iff_right_of_imp $ assume h', le_trans h' h, have c ≤ b → (a ≤ b ∨ a ≤ c ↔ a ≤ b), from assume h, or_iff_left_of_imp $ assume h', le_trans h' h, by cases le_total b c; simp * @[simp] lemma max_lt_iff : max a b < c ↔ (a < c ∧ b < c) := by rw [lt_iff_not_ge]; simp [(≥), le_max_iff, not_or_distrib] @[simp] lemma lt_min_iff : a < min b c ↔ (a < b ∧ a < c) := by rw [lt_iff_not_ge]; simp [(≥), min_le_iff, not_or_distrib] @[simp] lemma lt_max_iff : a < max b c ↔ a < b ∨ a < c := by rw [lt_iff_not_ge]; simp [(≥), max_le_iff, not_and_distrib] @[simp] lemma min_lt_iff : min a b < c ↔ a < c ∨ b < c := by rw [lt_iff_not_ge]; simp [(≥), le_min_iff, not_and_distrib] lemma max_lt_max (h₁ : a < c) (h₂ : b < d) : max a b < max c d := by apply max_lt; simp [lt_max_iff, h₁, h₂] lemma min_lt_min (h₁ : a < c) (h₂ : b < d) : min a b < min c d := by apply lt_min; simp [min_lt_iff, h₁, h₂] theorem min_right_comm (a b c : α) : min (min a b) c = min (min a c) b := right_comm min min_comm min_assoc a b c theorem max.left_comm (a b c : α) : max a (max b c) = max b (max a c) := left_comm max max_comm max_assoc a b c theorem max.right_comm (a b c : α) : max (max a b) c = max (max a c) b := right_comm max max_comm max_assoc a b c lemma max_distrib_of_monotone (hf : monotone f) : f (max a b) = max (f a) (f b) := by cases le_total a b; simp [h, hf h] lemma min_distrib_of_monotone (hf : monotone f) : f (min a b) = min (f a) (f b) := by cases le_total a b; simp [h, hf h] theorem min_choice (a b : α) : min a b = a ∨ min a b = b := by by_cases h : a ≤ b; simp [min, h] theorem max_choice (a b : α) : max a b = a ∨ max a b = b := by by_cases h : a ≤ b; simp [max, h] lemma le_of_max_le_left {a b c : α} (h : max a b ≤ c) : a ≤ c := le_trans (le_max_left _ _) h lemma le_of_max_le_right {a b c : α} (h : max a b ≤ c) : b ≤ c := le_trans (le_max_right _ _) h end lemma min_add {α : Type u} [decidable_linear_ordered_comm_group α] (a b c : α) : min a b + c = min (a + c) (b + c) := if hle : a ≤ b then have a - c ≤ b - c, from sub_le_sub hle (le_refl _), by simp * at * else have b - c ≤ a - c, from sub_le_sub (le_of_lt (lt_of_not_ge hle)) (le_refl _), by simp * at * lemma min_sub {α : Type u} [decidable_linear_ordered_comm_group α] (a b c : α) : min a b - c = min (a - c) (b - c) := by simp [min_add, sub_eq_add_neg] section decidable_linear_ordered_comm_group variables [decidable_linear_ordered_comm_group α] {a b c : α} attribute [simp] abs_zero abs_neg def abs_add := @abs_add_le_abs_add_abs theorem abs_le : abs a ≤ b ↔ - b ≤ a ∧ a ≤ b := ⟨assume h, ⟨neg_le_of_neg_le $ le_trans (neg_le_abs_self _) h, le_trans (le_abs_self _) h⟩, assume ⟨h₁, h₂⟩, abs_le_of_le_of_neg_le h₂ $ neg_le_of_neg_le h₁⟩ lemma abs_lt : abs a < b ↔ - b < a ∧ a < b := ⟨assume h, ⟨neg_lt_of_neg_lt $ lt_of_le_of_lt (neg_le_abs_self _) h, lt_of_le_of_lt (le_abs_self _) h⟩, assume ⟨h₁, h₂⟩, abs_lt_of_lt_of_neg_lt h₂ $ neg_lt_of_neg_lt h₁⟩ lemma abs_sub_le_iff : abs (a - b) ≤ c ↔ a - b ≤ c ∧ b - a ≤ c := by rw [abs_le, neg_le_sub_iff_le_add, @sub_le_iff_le_add' _ _ b, and_comm] lemma abs_sub_lt_iff : abs (a - b) < c ↔ a - b < c ∧ b - a < c := by rw [abs_lt, neg_lt_sub_iff_lt_add, @sub_lt_iff_lt_add' _ _ b, and_comm] def sub_abs_le_abs_sub := @abs_sub_abs_le_abs_sub lemma abs_abs_sub_le_abs_sub (a b : α) : abs (abs a - abs b) ≤ abs (a - b) := abs_sub_le_iff.2 ⟨sub_abs_le_abs_sub _ _, by rw abs_sub; apply sub_abs_le_abs_sub⟩ lemma abs_eq (hb : b ≥ 0) : abs a = b ↔ a = b ∨ a = -b := iff.intro begin cases le_total a 0 with a_nonpos a_nonneg, { rw [abs_of_nonpos a_nonpos, neg_eq_iff_neg_eq, eq_comm], exact or.inr }, { rw [abs_of_nonneg a_nonneg, eq_comm], exact or.inl } end (by intro h; cases h; subst h; try { rw abs_neg }; exact abs_of_nonneg hb) @[simp] lemma abs_eq_zero : abs a = 0 ↔ a = 0 := ⟨eq_zero_of_abs_eq_zero, λ e, e.symm ▸ abs_zero⟩ lemma abs_pos_iff {a : α} : 0 < abs a ↔ a ≠ 0 := ⟨λ h, mt abs_eq_zero.2 (ne_of_gt h), abs_pos_of_ne_zero⟩ @[simp] lemma abs_nonpos_iff {a : α} : abs a ≤ 0 ↔ a = 0 := by rw [← not_lt, abs_pos_iff, not_not] lemma abs_le_max_abs_abs (hab : a ≤ b) (hbc : b ≤ c) : abs b ≤ max (abs a) (abs c) := abs_le_of_le_of_neg_le (by simp [le_max_iff, le_trans hbc (le_abs_self c)]) (by simp [le_max_iff, le_trans (neg_le_neg hab) (neg_le_abs_self a)]) theorem abs_le_abs {α : Type*} [decidable_linear_ordered_comm_group α] {a b : α} (h₀ : a ≤ b) (h₁ : -a ≤ b) : abs a ≤ abs b := calc abs a ≤ b : by { apply abs_le_of_le_of_neg_le; assumption } ... ≤ abs b : le_abs_self _ lemma min_le_add_of_nonneg_right {a b : α} (hb : b ≥ 0) : min a b ≤ a + b := calc min a b ≤ a : by apply min_le_left ... ≤ a + b : le_add_of_nonneg_right hb lemma min_le_add_of_nonneg_left {a b : α} (ha : a ≥ 0) : min a b ≤ a + b := calc min a b ≤ b : by apply min_le_right ... ≤ a + b : le_add_of_nonneg_left ha lemma max_le_add_of_nonneg {a b : α} (ha : a ≥ 0) (hb : b ≥ 0) : max a b ≤ a + b := max_le_iff.2 (by split; simpa) end decidable_linear_ordered_comm_group section decidable_linear_ordered_semiring variables [decidable_linear_ordered_semiring α] {a b c d : α} lemma monotone_mul_of_nonneg (ha : 0 ≤ a) : monotone (λ x, a*x) := assume b c b_le_c, mul_le_mul_of_nonneg_left b_le_c ha lemma mul_max_of_nonneg (b c : α) (ha : 0 ≤ a) : a * max b c = max (a * b) (a * c) := max_distrib_of_monotone (monotone_mul_of_nonneg ha) lemma mul_min_of_nonneg (b c : α) (ha : 0 ≤ a) : a * min b c = min (a * b) (a * c) := min_distrib_of_monotone (monotone_mul_of_nonneg ha) end decidable_linear_ordered_semiring section decidable_linear_ordered_comm_ring variables [decidable_linear_ordered_comm_ring α] {a b c d : α} @[simp] lemma abs_one : abs (1 : α) = 1 := abs_of_pos zero_lt_one lemma max_mul_mul_le_max_mul_max (b c : α) (ha : 0 ≤ a) (hd: 0 ≤ d) : max (a * b) (d * c) ≤ max a c * max d b := have ba : b * a ≤ max d b * max c a, from mul_le_mul (le_max_right d b) (le_max_right c a) ha (le_trans hd (le_max_left d b)), have cd : c * d ≤ max a c * max b d, from mul_le_mul (le_max_right a c) (le_max_right b d) hd (le_trans ha (le_max_left a c)), max_le (by simpa [mul_comm, max_comm] using ba) (by simpa [mul_comm, max_comm] using cd) end decidable_linear_ordered_comm_ring