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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
24bf8da0d585da0f47e90ac5eb3bf2fc0de7e22a | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/field_type_mismatch.lean | 6371cbb2141c3cd463086bfda2937a53ce1146e1 | [
"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 | 251 | lean | namespace test
instance : has_add nat :=
{add := nat.succ}
class semigroup (α : Type) extends has_mul α :=
(mul_assoc : ∀ x y z : α, x * y * z = x * (y * z))
instance : semigroup nat :=
{mul := nat.add,
mul_assoc := trivial }
end test
|
2189865243cee10d35902fec290840aa05d8db49 | 05b503addd423dd68145d68b8cde5cd595d74365 | /src/algebra/module.lean | 593b0b091299d570c07266bbb2c8830be137312d | [
"Apache-2.0"
] | permissive | aestriplex/mathlib | 77513ff2b176d74a3bec114f33b519069788811d | e2fa8b2b1b732d7c25119229e3cdfba8370cb00f | refs/heads/master | 1,621,969,960,692 | 1,586,279,279,000 | 1,586,279,279,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,640 | lean | /-
Copyright (c) 2015 Nathaniel Thomas. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro
Modules over a ring.
## Implementation notes
Throughout the `linear_map` section implicit `{}` brackets are often used instead of type class `[]` brackets.
This is done when the instances can be inferred because they are implicit arguments to the type `linear_map`.
When they can be inferred from the type it is faster to use this method than to use type class inference
-/
import algebra.ring algebra.big_operators group_theory.subgroup group_theory.group_action
open function
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
-- /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/
-- class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ)
-- infixr ` • `:73 := has_scalar.smul
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A semimodule is a generalization of vector spaces to a scalar semiring.
It consists of a scalar semiring `α` and an additive monoid of "vectors" `β`,
connected by a "scalar multiplication" operation `r • x : β`
(where `r : α` and `x : β`) with some natural associativity and
distributivity axioms similar to those on a ring. -/
class semimodule (α : Type u) (β : Type v) [semiring α]
[add_comm_monoid β] extends distrib_mul_action α β :=
(add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x)
(zero_smul : ∀x : β, (0 : α) • x = 0)
end prio
section semimodule
variables [R:semiring α] [add_comm_monoid β] [semimodule α β] (r s : α) (x y : β)
include R
theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x
variables (α)
@[simp] theorem zero_smul : (0 : α) • x = 0 := semimodule.zero_smul α x
variable {α}
lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : α) = 1) : x = 0 :=
by rw [←one_smul α x, ←zero_eq_one, zero_smul]
instance smul.is_add_monoid_hom (x : β) : is_add_monoid_hom (λ r:α, r • x) :=
{ map_zero := zero_smul _ x,
map_add := λ r₁ r₂, add_smul r₁ r₂ x }
lemma list.sum_smul {l : list α} {x : β} : l.sum • x = (l.map (λ r, r • x)).sum :=
show (λ r, r • x) l.sum = (l.map (λ r, r • x)).sum,
from (list.sum_hom _ _).symm
lemma multiset.sum_smul {l : multiset α} {x : β} : l.sum • x = (l.map (λ r, r • x)).sum :=
show (λ r, r • x) l.sum = (l.map (λ r, r • x)).sum,
from (multiset.sum_hom _ _).symm
lemma finset.sum_smul {f : γ → α} {s : finset γ} {x : β} :
s.sum f • x = s.sum (λ r, (f r) • x) :=
show (λ r, r • x) (s.sum f) = s.sum (λ r, (f r) • x),
from (finset.sum_hom _ _).symm
end semimodule
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A module is a generalization of vector spaces to a scalar ring.
It consists of a scalar ring `α` and an additive group of "vectors" `β`,
connected by a "scalar multiplication" operation `r • x : β`
(where `r : α` and `x : β`) with some natural associativity and
distributivity axioms similar to those on a ring. -/
class module (α : Type u) (β : Type v) [ring α] [add_comm_group β] extends semimodule α β
end prio
/--
To prove two module structures on a fixed `add_comm_group` agree,
it suffices to check the scalar multiplications agree.
-/
-- We'll later use this to show `module ℤ M` is a subsingleton.
@[ext]
lemma module_ext {R : Type*} [ring R] {M : Type*} [add_comm_group M] (P Q : module R M)
(w : ∀ (r : R) (m : M), by { haveI := P, exact r • m } = by { haveI := Q, exact r • m }) :
P = Q :=
begin
resetI,
rcases P with ⟨⟨⟨⟨⟨P⟩⟩⟩⟩⟩, rcases Q with ⟨⟨⟨⟨⟨Q⟩⟩⟩⟩⟩, congr,
funext r m,
exact w r m,
all_goals { apply proof_irrel_heq },
end
structure module.core (α β) [ring α] [add_comm_group β] extends has_scalar α β :=
(smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y)
(add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x)
(mul_smul : ∀(r s : α) (x : β), (r * s) • x = r • s • x)
(one_smul : ∀x : β, (1 : α) • x = x)
/-- Define `module` without proving `zero_smul` and `smul_zero` by using an auxiliary
structure `module.core`. -/
def module.of_core {α β} [ring α] [add_comm_group β] (M : module.core α β) : module α β :=
by letI := M.to_has_scalar; exact
{ zero_smul := λ x,
have (0 : α) • x + (0 : α) • x = (0 : α) • x + 0, by rw ← M.add_smul; simp,
add_left_cancel this,
smul_zero := λ r,
have r • (0:β) + r • 0 = r • 0 + 0, by rw ← M.smul_add; simp,
add_left_cancel this,
..M }
section module
variables [ring α] [add_comm_group β] [module α β] (r s : α) (x y : β)
@[simp] theorem neg_smul : -r • x = - (r • x) :=
eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul])
variables (α)
theorem neg_one_smul (x : β) : (-1 : α) • x = -x := by simp
variables {α}
@[simp] theorem smul_neg : r • (-x) = -(r • x) :=
by rw [← neg_one_smul α, ← mul_smul, mul_neg_one, neg_smul]
theorem smul_sub (r : α) (x y : β) : r • (x - y) = r • x - r • y :=
by simp [smul_add, sub_eq_add_neg]; rw smul_neg
theorem sub_smul (r s : α) (y : β) : (r - s) • y = r • y - s • y :=
by simp [add_smul, sub_eq_add_neg]
theorem smul_eq_zero {R E : Type*} [division_ring R] [add_comm_group E] [module R E]
{c : R} {x : E} :
c • x = 0 ↔ c = 0 ∨ x = 0 :=
⟨λ h, classical.by_cases or.inl
(λ hc, or.inr $ by rw [← one_smul R x, ← inv_mul_cancel hc, mul_smul, h, smul_zero]),
λ h, h.elim (λ hc, hc.symm ▸ zero_smul R x) (λ hx, hx.symm ▸ smul_zero c)⟩
end module
instance semiring.to_semimodule [r : semiring α] : semimodule α α :=
{ smul := (*),
smul_add := mul_add,
add_smul := add_mul,
mul_smul := mul_assoc,
one_smul := one_mul,
zero_smul := zero_mul,
smul_zero := mul_zero, ..r }
@[simp] lemma smul_eq_mul [semiring α] {a a' : α} : a • a' = a * a' := rfl
instance ring.to_module [r : ring α] : module α α :=
{ ..semiring.to_semimodule }
/-- A ring homomorphism `f : α →+* β` defines a module structure by `r • x = f r * x`. -/
def ring_hom.to_module [ring α] [ring β] (f : α →+* β) : module α β :=
module.of_core
{ smul := λ r x, f r * x,
smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add],
add_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_add, add_mul],
mul_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_mul, mul_assoc],
one_smul := λ x, show f 1 * x = _, by rw [f.map_one, one_mul] }
class is_linear_map (α : Type u) {β : Type v} {γ : Type w}
[ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ]
(f : β → γ) : Prop :=
(add : ∀x y, f (x + y) = f x + f y)
(smul : ∀(c : α) x, f (c • x) = c • f x)
structure linear_map (α : Type u) (β : Type v) (γ : Type w)
[ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] :=
(to_fun : β → γ)
(add : ∀x y, to_fun (x + y) = to_fun x + to_fun y)
(smul : ∀(c : α) x, to_fun (c • x) = c • to_fun x)
infixr ` →ₗ `:25 := linear_map _
notation β ` →ₗ[`:25 α:25 `] `:0 γ:0 := linear_map α β γ
namespace linear_map
variables {rα : ring α} {gβ : add_comm_group β} {gγ : add_comm_group γ} {gδ : add_comm_group δ}
variables {mβ : module α β} {mγ : module α γ} {mδ : module α δ}
variables (f g : β →ₗ[α] γ)
include α mβ mγ
instance : has_coe_to_fun (β →ₗ[α] γ) := ⟨_, to_fun⟩
@[simp] lemma coe_mk (f : β → γ) (h₁ h₂) :
((linear_map.mk f h₁ h₂ : β →ₗ[α] γ) : β → γ) = f := rfl
@[simp] lemma to_fun_eq_coe (f : β →ₗ[α] γ) : f.to_fun = ⇑f := rfl
theorem is_linear : is_linear_map α f := {..f}
@[ext] theorem ext {f g : β →ₗ[α] γ} (H : ∀ x, f x = g x) : f = g :=
by cases f; cases g; congr'; exact funext H
theorem ext_iff {f g : β →ₗ[α] γ} : f = g ↔ ∀ x, f x = g x :=
⟨by rintro rfl; simp, ext⟩
@[simp] lemma map_add (x y : β) : f (x + y) = f x + f y := f.add x y
@[simp] lemma map_smul (c : α) (x : β) : f (c • x) = c • f x := f.smul c x
@[simp] lemma map_zero : f 0 = 0 :=
by rw [← zero_smul α, map_smul f 0 0, zero_smul]
instance : is_add_group_hom f := { map_add := map_add f }
/-- convert a linear map to an additive map -/
def to_add_monoid_hom (f : β →ₗ[α] γ) : β →+ γ :=
{ to_fun := f,
map_zero' := f.map_zero,
map_add' := f.map_add }
@[simp] lemma to_add_monoid_hom_coe (f : β →ₗ[α] γ) :
((f.to_add_monoid_hom) : β → γ) = (f : β → γ) := rfl
@[simp] lemma map_neg (x : β) : f (- x) = - f x :=
f.to_add_monoid_hom.map_neg x
@[simp] lemma map_sub (x y : β) : f (x - y) = f x - f y :=
f.to_add_monoid_hom.map_sub x y
@[simp] lemma map_sum {ι} {t : finset ι} {g : ι → β} :
f (t.sum g) = t.sum (λi, f (g i)) :=
f.to_add_monoid_hom.map_sum _ _
include mδ
/-- Composition of two linear maps is a linear map -/
def comp (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) : β →ₗ[α] δ := ⟨f ∘ g, by simp, by simp⟩
@[simp] lemma comp_apply (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) (x : β) : f.comp g x = f (g x) := rfl
omit mγ mδ
variables [rα] [gβ] [mβ]
/-- Identity map as a `linear_map` -/
def id : β →ₗ[α] β := ⟨id, λ _ _, rfl, λ _ _, rfl⟩
@[simp] lemma id_apply (x : β) : @id α β _ _ _ x = x := rfl
end linear_map
namespace is_linear_map
variables [ring α] [add_comm_group β] [add_comm_group γ]
variables [module α β] [module α γ]
include α
/-- Convert an `is_linear_map` predicate to a `linear_map` -/
def mk' (f : β → γ) (H : is_linear_map α f) : β →ₗ γ := {to_fun := f, ..H}
@[simp] theorem mk'_apply {f : β → γ} (H : is_linear_map α f) (x : β) :
mk' f H x = f x := rfl
lemma is_linear_map_neg :
is_linear_map α (λ (z : β), -z) :=
is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm)
lemma is_linear_map_smul {α R : Type*} [add_comm_group α] [comm_ring R] [module R α] (c : R) :
is_linear_map R (λ (z : α), c • z) :=
begin
refine is_linear_map.mk (smul_add c) _,
intros _ _,
simp [smul_smul],
ac_refl
end
--TODO: move
lemma is_linear_map_smul' {α R : Type*} [add_comm_group α] [ring R] [module R α] (a : α) :
is_linear_map R (λ (c : R), c • a) :=
begin
refine is_linear_map.mk (λ x y, add_smul x y a) _,
intros _ _,
simp [smul_smul]
end
variables {f : β → γ} (lin : is_linear_map α f)
include β γ lin
lemma map_zero : f (0 : β) = (0 : γ) := (lin.mk' f).map_zero
lemma map_add : ∀ x y, f (x + y) = f x + f y := lin.add
lemma map_neg (x : β) : f (- x) = - f x := (lin.mk' f).map_neg x
lemma map_sub (x y : β) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y
lemma map_smul (c : α) (x : β) : f (c • x) = c • f x := (lin.mk' f).map_smul c x
end is_linear_map
abbreviation module.End (R : Type u) (M : Type v)
[comm_ring R] [add_comm_group M] [module R M] := M →ₗ[R] M
/-- A submodule of a module is one which is closed under vector operations.
This is a sufficient condition for the subset of vectors in the submodule
to themselves form a module. -/
structure submodule (α : Type u) (β : Type v) [ring α]
[add_comm_group β] [module α β] : Type v :=
(carrier : set β)
(zero : (0:β) ∈ carrier)
(add : ∀ {x y}, x ∈ carrier → y ∈ carrier → x + y ∈ carrier)
(smul : ∀ (c:α) {x}, x ∈ carrier → c • x ∈ carrier)
namespace submodule
variables [ring α] [add_comm_group β] [add_comm_group γ]
variables [module α β] [module α γ]
variables (p p' : submodule α β)
variables {r : α} {x y : β}
instance : has_coe (submodule α β) (set β) := ⟨submodule.carrier⟩
instance : has_mem β (submodule α β) := ⟨λ x p, x ∈ (p : set β)⟩
@[simp] theorem mem_coe : x ∈ (p : set β) ↔ x ∈ p := iff.rfl
theorem ext' {s t : submodule α β} (h : (s : set β) = t) : s = t :=
by cases s; cases t; congr'
protected theorem ext'_iff {s t : submodule α β} : (s : set β) = t ↔ s = t :=
⟨ext', λ h, h ▸ rfl⟩
@[ext] theorem ext {s t : submodule α β}
(h : ∀ x, x ∈ s ↔ x ∈ t) : s = t := ext' $ set.ext h
@[simp] lemma zero_mem : (0 : β) ∈ p := p.zero
lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add h₁ h₂
lemma smul_mem (r : α) (h : x ∈ p) : r • x ∈ p := p.smul r h
lemma neg_mem (hx : x ∈ p) : -x ∈ p := by rw ← neg_one_smul α; exact p.smul_mem _ hx
lemma sub_mem (hx : x ∈ p) (hy : y ∈ p) : x - y ∈ p := p.add_mem hx (p.neg_mem hy)
lemma neg_mem_iff : -x ∈ p ↔ x ∈ p :=
⟨λ h, by simpa using neg_mem p h, neg_mem p⟩
lemma add_mem_iff_left (h₁ : y ∈ p) : x + y ∈ p ↔ x ∈ p :=
⟨λ h₂, by simpa using sub_mem _ h₂ h₁, λ h₂, add_mem _ h₂ h₁⟩
lemma add_mem_iff_right (h₁ : x ∈ p) : x + y ∈ p ↔ y ∈ p :=
⟨λ h₂, by simpa using sub_mem _ h₂ h₁, add_mem _ h₁⟩
lemma sum_mem {ι : Type w} [decidable_eq ι] {t : finset ι} {f : ι → β} :
(∀c∈t, f c ∈ p) → t.sum f ∈ p :=
finset.induction_on t (by simp [p.zero_mem]) (by simp [p.add_mem] {contextual := tt})
lemma smul_mem_iff' (u : units α) : (u:α) • x ∈ p ↔ x ∈ p :=
⟨λ h, by simpa only [smul_smul, u.inv_mul, one_smul] using p.smul_mem ↑u⁻¹ h, p.smul_mem u⟩
instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩
instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩
instance : inhabited p := ⟨0⟩
instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩
instance : has_scalar α p := ⟨λ c x, ⟨c • x.1, smul_mem _ c x.2⟩⟩
@[simp, move_cast] lemma coe_add (x y : p) : (↑(x + y) : β) = ↑x + ↑y := rfl
@[simp, elim_cast] lemma coe_zero : ((0 : p) : β) = 0 := rfl
@[simp, move_cast] lemma coe_neg (x : p) : ((-x : p) : β) = -x := rfl
@[simp, move_cast] lemma coe_smul (r : α) (x : p) : ((r • x : p) : β) = r • ↑x := rfl
@[simp, elim_cast] lemma coe_mk (x : β) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : β) = x := rfl
@[simp] protected lemma eta (x : p) (hx : (x : β) ∈ p) : (⟨x, hx⟩ : p) = x := subtype.eta x hx
instance : add_comm_group p :=
by refine {add := (+), zero := 0, neg := has_neg.neg, ..};
{ intros, apply set_coe.ext, simp [add_comm, add_left_comm] }
instance submodule_is_add_subgroup : is_add_subgroup (p : set β) :=
{ zero_mem := p.zero,
add_mem := p.add,
neg_mem := λ _, p.neg_mem }
@[simp, move_cast] lemma coe_sub (x y : p) : (↑(x - y) : β) = ↑x - ↑y := rfl
instance : module α p :=
by refine {smul := (•), ..};
{ intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] }
protected def subtype : p →ₗ[α] β :=
by refine {to_fun := coe, ..}; simp [coe_smul]
@[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl
lemma subtype_eq_val (p : submodule α β) :
((submodule.subtype p) : p → β) = subtype.val := rfl
end submodule
@[reducible] def ideal (α : Type u) [comm_ring α] := submodule α α
namespace ideal
variables [comm_ring α] (I : ideal α) {a b : α}
protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem
protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem
lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff
lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left
lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right
protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem
lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem _
lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left h
end ideal
/--
Vector spaces are defined as an `abbreviation` for modules,
if the base ring is a field.
(A previous definition made `vector_space` a structure
defined to be `module`.)
This has as advantage that vector spaces are completely transparant
for type class inference, which means that all instances for modules
are immediately picked up for vector spaces as well.
A cosmetic disadvantage is that one can not extend vector spaces an sich,
in definitions such as `normed_space`.
The solution is to extend `module` instead.
-/
library_note "vector space definition"
/-- A vector space is the same as a module, except the scalar ring is actually
a field. (This adds commutativity of the multiplication and existence of inverses.)
This is the traditional generalization of spaces like `ℝ^n`, which have a natural
addition operation and a way to multiply them by real numbers, but no multiplication
operation between vectors. -/
abbreviation vector_space (α : Type u) (β : Type v) [field α] [add_comm_group β] :=
module α β
instance field.to_vector_space {α : Type*} [field α] : vector_space α α :=
{ .. ring.to_module }
/-- Subspace of a vector space. Defined to equal `submodule`. -/
@[reducible] def subspace (α : Type u) (β : Type v)
[field α] [add_comm_group β] [vector_space α β] : Type v :=
submodule α β
instance subspace.vector_space {α β}
{f : field α} [add_comm_group β] [vector_space α β]
(p : subspace α β) : vector_space α p := {..submodule.module p}
namespace submodule
variables {R : division_ring α} [add_comm_group β] [module α β]
variables (p : submodule α β) {r : α} {x y : β}
include R
set_option class.instance_max_depth 36
theorem smul_mem_iff (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p :=
p.smul_mem_iff' (units.mk0 r r0)
end submodule
namespace add_comm_monoid
open add_monoid
variables {M : Type*} [add_comm_monoid M]
/-- The natural ℕ-semimodule structure on any `add_comm_monoid`. -/
-- We don't make this a global instance, as it results in too many instances,
-- and confusing ambiguity in the notation `n • x` when `n : ℕ`.
def nat_semimodule : semimodule ℕ M :=
{ smul := smul,
smul_add := λ _ _ _, smul_add _ _ _,
add_smul := λ _ _ _, add_smul _ _ _,
mul_smul := λ _ _ _, mul_smul _ _ _,
one_smul := one_smul,
zero_smul := zero_smul,
smul_zero := smul_zero }
end add_comm_monoid
namespace add_comm_group
variables {M : Type*} [add_comm_group M]
/-- The natural ℤ-module structure on any `add_comm_group`. -/
-- We don't immediately make this a global instance, as it results in too many instances,
-- and confusing ambiguity in the notation `n • x` when `n : ℤ`.
-- We do turn it into a global instance, but only at the end of this file,
-- and I remain dubious whether this is a good idea.
def int_module : module ℤ M :=
{ smul := gsmul,
smul_add := λ _ _ _, gsmul_add _ _ _,
add_smul := λ _ _ _, add_gsmul _ _ _,
mul_smul := λ _ _ _, gsmul_mul _ _ _,
one_smul := one_gsmul,
zero_smul := zero_gsmul,
smul_zero := gsmul_zero }
instance : subsingleton (module ℤ M) :=
begin
split,
intros P Q,
ext,
-- isn't that lovely: `r • m = r • m`
have one_smul : by { haveI := P, exact (1 : ℤ) • m } = by { haveI := Q, exact (1 : ℤ) • m },
begin
rw [@one_smul ℤ _ _ (by { haveI := P, apply_instance, }) m],
rw [@one_smul ℤ _ _ (by { haveI := Q, apply_instance, }) m],
end,
have nat_smul : ∀ n : ℕ, by { haveI := P, exact (n : ℤ) • m } = by { haveI := Q, exact (n : ℤ) • m },
begin
intro n,
induction n with n ih,
{ erw [zero_smul, zero_smul], },
{ rw [int.coe_nat_succ, add_smul, add_smul],
erw ih,
rw [one_smul], }
end,
cases r,
{ rw [int.of_nat_eq_coe, nat_smul], },
{ rw [int.neg_succ_of_nat_coe, neg_smul, neg_smul, nat_smul], }
end
end add_comm_group
section
local attribute [instance] add_comm_monoid.nat_semimodule
lemma semimodule.smul_eq_smul (R : Type*) [semiring R]
{β : Type*} [add_comm_group β] [semimodule R β]
(n : ℕ) (b : β) : n • b = (n : R) • b :=
begin
induction n with n ih,
{ rw [nat.cast_zero, zero_smul, zero_smul] },
{ change (n + 1) • b = (n + 1 : R) • b,
rw [add_smul, add_smul, one_smul, ih, one_smul] }
end
lemma semimodule.add_monoid_smul_eq_smul (R : Type*) [semiring R] {β : Type*} [add_comm_group β]
[semimodule R β] (n : ℕ) (b : β) : add_monoid.smul n b = (n : R) • b :=
semimodule.smul_eq_smul R n b
lemma nat.smul_def {M : Type*} [add_comm_monoid M] (n : ℕ) (x : M) :
n • x = add_monoid.smul n x :=
rfl
end
section
local attribute [instance] add_comm_group.int_module
lemma gsmul_eq_smul {M : Type*} [add_comm_group M] (n : ℤ) (x : M) : gsmul n x = n • x := rfl
lemma module.gsmul_eq_smul_cast (R : Type*) [ring R] {β : Type*} [add_comm_group β] [module R β]
(n : ℤ) (b : β) : gsmul n b = (n : R) • b :=
begin
cases n,
{ apply semimodule.add_monoid_smul_eq_smul, },
{ dsimp,
rw semimodule.add_monoid_smul_eq_smul R,
push_cast,
rw neg_smul, }
end
lemma module.gsmul_eq_smul {β : Type*} [add_comm_group β] [module ℤ β]
(n : ℤ) (b : β) : gsmul n b = n • b :=
by rw [module.gsmul_eq_smul_cast ℤ, int.cast_id]
end
-- We prove this without using the `add_comm_group.int_module` instance, so the `•`s here
-- come from whatever the local `module ℤ` structure actually is.
lemma add_monoid_hom.map_int_module_smul
{α : Type*} {β : Type*} [add_comm_group α] [add_comm_group β]
[module ℤ α] [module ℤ β] (f : α →+ β) (x : ℤ) (a : α) : f (x • a) = x • f a :=
by simp only [← module.gsmul_eq_smul, f.map_gsmul]
lemma add_monoid_hom.map_int_cast_smul
{R : Type*} [ring R] {α : Type*} {β : Type*} [add_comm_group α] [add_comm_group β]
[module R α] [module R β] (f : α →+ β) (x : ℤ) (a : α) : f ((x : R) • a) = (x : R) • f a :=
by simp only [← module.gsmul_eq_smul_cast, f.map_gsmul]
lemma add_monoid_hom.map_nat_cast_smul
{R : Type*} [semiring R] {α : Type*} {β : Type*} [add_comm_group α] [add_comm_group β]
[semimodule R α] [semimodule R β] (f : α →+ β) (x : ℕ) (a : α) :
f ((x : R) • a) = (x : R) • f a :=
by simp only [← semimodule.add_monoid_smul_eq_smul, f.map_smul]
lemma add_monoid_hom.map_rat_cast_smul {R : Type*} [division_ring R] [char_zero R]
{E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F]
(f : E →+ F) (c : ℚ) (x : E) :
f ((c : R) • x) = (c : R) • f x :=
begin
have : ∀ (x : E) (n : ℕ), 0 < n → f (((n⁻¹ : ℚ) : R) • x) = ((n⁻¹ : ℚ) : R) • f x,
{ intros x n hn,
replace hn : (n : R) ≠ 0 := nat.cast_ne_zero.2 (ne_of_gt hn),
conv_rhs { congr, skip, rw [← one_smul R x, ← mul_inv_cancel hn, mul_smul] },
rw [f.map_nat_cast_smul, smul_smul, rat.cast_inv, rat.cast_coe_nat,
inv_mul_cancel hn, one_smul] },
refine c.num_denom_cases_on (λ m n hn hmn, _),
rw [rat.mk_eq_div, div_eq_mul_inv, rat.cast_mul, int.cast_coe_nat, mul_smul, mul_smul,
rat.cast_coe_int, f.map_int_cast_smul, this _ n hn]
end
lemma add_monoid_hom.map_rat_module_smul {E : Type*} [add_comm_group E] [vector_space ℚ E]
{F : Type*} [add_comm_group F] [module ℚ F] (f : E →+ F) (c : ℚ) (x : E) :
f (c • x) = c • f x :=
rat.cast_id c ▸ f.map_rat_cast_smul c x
-- We finally turn on these instances globally:
attribute [instance] add_comm_monoid.nat_semimodule add_comm_group.int_module
/-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/
def add_monoid_hom.to_int_linear_map [add_comm_group α] [add_comm_group β] (f : α →+ β) :
α →ₗ[ℤ] β :=
⟨f, f.map_add, f.map_int_module_smul⟩
/-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/
def add_monoid_hom.to_rat_linear_map [add_comm_group α] [vector_space ℚ α]
[add_comm_group β] [vector_space ℚ β] (f : α →+ β) :
α →ₗ[ℚ] β :=
⟨f, f.map_add, f.map_rat_module_smul⟩
namespace finset
lemma sum_const' {α : Type*} (R : Type*) [ring R] {β : Type*}
[add_comm_group β] [module R β] {s : finset α} (b : β) :
finset.sum s (λ (a : α), b) = (finset.card s : R) • b :=
by rw [finset.sum_const, ← semimodule.smul_eq_smul]; refl
variables {M : Type*} [decidable_linear_ordered_cancel_comm_monoid M]
{s : finset α} (f : α → M)
theorem exists_card_smul_le_sum (hs : s.nonempty) :
∃ i ∈ s, s.card • f i ≤ s.sum f :=
exists_le_of_sum_le hs $ by rw [sum_const, ← nat.smul_def, smul_sum]
theorem exists_card_smul_ge_sum (hs : s.nonempty) :
∃ i ∈ s, s.sum f ≤ s.card • f i :=
exists_le_of_sum_le hs $ by rw [sum_const, ← nat.smul_def, smul_sum]
end finset
|
c38b8d1ec81889c941c573bd1d2a2d823f78241b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/analysis/convex/cone.lean | 2844d320e217c6e5c4bb03977178aea47b440f62 | [] | 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 | 18,473 | lean | /-
Copyright (c) 2020 Yury Kudryashov All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Frédéric Dupuis
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.linear_algebra.linear_pmap
import Mathlib.analysis.convex.basic
import Mathlib.order.zorn
import Mathlib.PostPort
universes u_1 l u_2 u_3 u_4
namespace Mathlib
/-!
# Convex cones
In a vector space `E` over `ℝ`, we define a convex cone as a subset `s` such that
`a • x + b • y ∈ s` whenever `x, y ∈ s` and `a, b > 0`. We prove that convex cones form
a `complete_lattice`, and define their images (`convex_cone.map`) and preimages
(`convex_cone.comap`) under linear maps.
We define pointed, blunt, flat and salient cones, and prove the correspondence between
convex cones and ordered semimodules.
We also define `convex.to_cone` to be the minimal cone that includes a given convex set.
## Main statements
We prove two extension theorems:
* `riesz_extension`:
[M. Riesz extension theorem](https://en.wikipedia.org/wiki/M._Riesz_extension_theorem) says that
if `s` is a convex cone in a real vector space `E`, `p` is a submodule of `E`
such that `p + s = E`, and `f` is a linear function `p → ℝ` which is
nonnegative on `p ∩ s`, then there exists a globally defined linear function
`g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`.
* `exists_extension_of_le_sublinear`:
Hahn-Banach theorem: if `N : E → ℝ` is a sublinear map, `f` is a linear map
defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`,
then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x`
for all `x`
## Implementation notes
While `convex` is a predicate on sets, `convex_cone` is a bundled convex cone.
## References
* https://en.wikipedia.org/wiki/Convex_cone
## TODO
* Define the dual cone.
-/
/-!
### Definition of `convex_cone` and basic properties
-/
/-- A convex cone is a subset `s` of a vector space over `ℝ` such that `a • x + b • y ∈ s`
whenever `a, b > 0` and `x, y ∈ s`. -/
structure convex_cone (E : Type u_1) [add_comm_group E] [vector_space ℝ E]
where
carrier : set E
smul_mem' : ∀ {c : ℝ}, 0 < c → ∀ {x : E}, x ∈ carrier → c • x ∈ carrier
add_mem' : ∀ {x : E}, x ∈ carrier → ∀ {y : E}, y ∈ carrier → x + y ∈ carrier
namespace convex_cone
protected instance set.has_coe {E : Type u_1} [add_comm_group E] [vector_space ℝ E] : has_coe (convex_cone E) (set E) :=
has_coe.mk carrier
protected instance has_mem {E : Type u_1} [add_comm_group E] [vector_space ℝ E] : has_mem E (convex_cone E) :=
has_mem.mk fun (m : E) (S : convex_cone E) => m ∈ carrier S
protected instance has_le {E : Type u_1} [add_comm_group E] [vector_space ℝ E] : HasLessEq (convex_cone E) :=
{ LessEq := fun (S T : convex_cone E) => carrier S ⊆ carrier T }
protected instance has_lt {E : Type u_1} [add_comm_group E] [vector_space ℝ E] : HasLess (convex_cone E) :=
{ Less := fun (S T : convex_cone E) => carrier S ⊂ carrier T }
@[simp] theorem mem_coe {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) {x : E} : x ∈ ↑S ↔ x ∈ S :=
iff.rfl
@[simp] theorem mem_mk {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {s : set E} {h₁ : ∀ {c : ℝ}, 0 < c → ∀ {x : E}, x ∈ s → c • x ∈ s} {h₂ : ∀ {x : E}, x ∈ s → ∀ {y : E}, y ∈ s → x + y ∈ s} {x : E} : x ∈ mk s h₁ h₂ ↔ x ∈ s :=
iff.rfl
/-- Two `convex_cone`s are equal if the underlying subsets are equal. -/
theorem ext' {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {S : convex_cone E} {T : convex_cone E} (h : ↑S = ↑T) : S = T := sorry
/-- Two `convex_cone`s are equal if and only if the underlying subsets are equal. -/
protected theorem ext'_iff {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {S : convex_cone E} {T : convex_cone E} : ↑S = ↑T ↔ S = T :=
{ mp := ext', mpr := fun (h : S = T) => h ▸ rfl }
/-- Two `convex_cone`s are equal if they have the same elements. -/
theorem ext {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {S : convex_cone E} {T : convex_cone E} (h : ∀ (x : E), x ∈ S ↔ x ∈ T) : S = T :=
ext' (set.ext h)
theorem smul_mem {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) {c : ℝ} {x : E} (hc : 0 < c) (hx : x ∈ S) : c • x ∈ S :=
smul_mem' S hc hx
theorem add_mem {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) {x : E} (hx : x ∈ S) {y : E} (hy : y ∈ S) : x + y ∈ S :=
add_mem' S hx hy
theorem smul_mem_iff {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) {c : ℝ} (hc : 0 < c) {x : E} : c • x ∈ S ↔ x ∈ S := sorry
theorem convex {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) : convex ↑S :=
iff.mpr convex_iff_forall_pos
fun (x y : E) (hx : x ∈ ↑S) (hy : y ∈ ↑S) (a b : ℝ) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) =>
add_mem S (smul_mem S ha hx) (smul_mem S hb hy)
protected instance has_inf {E : Type u_1} [add_comm_group E] [vector_space ℝ E] : has_inf (convex_cone E) :=
has_inf.mk fun (S T : convex_cone E) => mk (↑S ∩ ↑T) sorry sorry
theorem coe_inf {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) (T : convex_cone E) : ↑(S ⊓ T) = ↑S ∩ ↑T :=
rfl
theorem mem_inf {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) (T : convex_cone E) {x : E} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T :=
iff.rfl
protected instance has_Inf {E : Type u_1} [add_comm_group E] [vector_space ℝ E] : has_Inf (convex_cone E) :=
has_Inf.mk
fun (S : set (convex_cone E)) => mk (set.Inter fun (s : convex_cone E) => set.Inter fun (H : s ∈ S) => ↑s) sorry sorry
theorem mem_Inf {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {x : E} {S : set (convex_cone E)} : x ∈ Inf S ↔ ∀ (s : convex_cone E), s ∈ S → x ∈ s :=
set.mem_bInter_iff
protected instance has_bot {E : Type u_1} [add_comm_group E] [vector_space ℝ E] : has_bot (convex_cone E) :=
has_bot.mk (mk ∅ sorry sorry)
theorem mem_bot {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (x : E) : x ∈ ⊥ = False :=
rfl
protected instance has_top {E : Type u_1} [add_comm_group E] [vector_space ℝ E] : has_top (convex_cone E) :=
has_top.mk (mk set.univ sorry sorry)
theorem mem_top {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (x : E) : x ∈ ⊤ :=
set.mem_univ x
protected instance complete_lattice {E : Type u_1} [add_comm_group E] [vector_space ℝ E] : complete_lattice (convex_cone E) :=
complete_lattice.mk (fun (a b : convex_cone E) => Inf (set_of fun (x : convex_cone E) => a ≤ x ∧ b ≤ x)) LessEq Less
sorry sorry sorry sorry sorry sorry has_inf.inf sorry sorry sorry ⊤ sorry ⊥ sorry
(fun (s : set (convex_cone E)) => Inf (set_of fun (T : convex_cone E) => ∀ (S : convex_cone E), S ∈ s → S ≤ T)) Inf
sorry sorry sorry sorry
protected instance inhabited {E : Type u_1} [add_comm_group E] [vector_space ℝ E] : Inhabited (convex_cone E) :=
{ default := ⊥ }
/-- The image of a convex cone under an `ℝ`-linear map is a convex cone. -/
def map {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {F : Type u_2} [add_comm_group F] [vector_space ℝ F] (f : linear_map ℝ E F) (S : convex_cone E) : convex_cone F :=
mk (⇑f '' ↑S) sorry sorry
theorem map_map {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {F : Type u_2} [add_comm_group F] [vector_space ℝ F] {G : Type u_3} [add_comm_group G] [vector_space ℝ G] (g : linear_map ℝ F G) (f : linear_map ℝ E F) (S : convex_cone E) : map g (map f S) = map (linear_map.comp g f) S :=
ext' (set.image_image ⇑g ⇑f ↑S)
@[simp] theorem map_id {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) : map linear_map.id S = S :=
ext' (set.image_id ↑S)
/-- The preimage of a convex cone under an `ℝ`-linear map is a convex cone. -/
def comap {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {F : Type u_2} [add_comm_group F] [vector_space ℝ F] (f : linear_map ℝ E F) (S : convex_cone F) : convex_cone E :=
mk (⇑f ⁻¹' ↑S) sorry sorry
@[simp] theorem comap_id {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) : comap linear_map.id S = S :=
ext' set.preimage_id
theorem comap_comap {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {F : Type u_2} [add_comm_group F] [vector_space ℝ F] {G : Type u_3} [add_comm_group G] [vector_space ℝ G] (g : linear_map ℝ F G) (f : linear_map ℝ E F) (S : convex_cone G) : comap f (comap g S) = comap (linear_map.comp g f) S :=
ext' (Eq.symm set.preimage_comp)
@[simp] theorem mem_comap {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {F : Type u_2} [add_comm_group F] [vector_space ℝ F] {f : linear_map ℝ E F} {S : convex_cone F} {x : E} : x ∈ comap f S ↔ coe_fn f x ∈ S :=
iff.rfl
/--
Constructs an ordered semimodule given an `ordered_add_comm_group`, a cone, and a proof that
the order relation is the one defined by the cone.
-/
theorem to_ordered_semimodule {M : Type u_1} [ordered_add_comm_group M] [semimodule ℝ M] (S : convex_cone M) (h : ∀ (x y : M), x ≤ y ↔ y - x ∈ S) : ordered_semimodule ℝ M := sorry
/-! ### Convex cones with extra properties -/
/-- A convex cone is pointed if it includes 0. -/
def pointed {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) :=
0 ∈ S
/-- A convex cone is blunt if it doesn't include 0. -/
def blunt {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) :=
¬0 ∈ S
/-- A convex cone is flat if it contains some nonzero vector `x` and its opposite `-x`. -/
def flat {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) :=
∃ (x : E), ∃ (H : x ∈ S), x ≠ 0 ∧ -x ∈ S
/-- A convex cone is salient if it doesn't include `x` and `-x` for any nonzero `x`. -/
def salient {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) :=
∀ (x : E), x ∈ S → x ≠ 0 → ¬-x ∈ S
theorem pointed_iff_not_blunt {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) : pointed S ↔ ¬blunt S :=
{ mp := fun (h₁ : pointed S) (h₂ : blunt S) => h₂ h₁, mpr := fun (h : ¬blunt S) => iff.mp not_not h }
theorem salient_iff_not_flat {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) : salient S ↔ ¬flat S := sorry
/-- A blunt cone (one not containing 0) is always salient. -/
theorem salient_of_blunt {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) : blunt S → salient S := sorry
/-- A pointed convex cone defines a preorder. -/
def to_preorder {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) (h₁ : pointed S) : preorder E :=
preorder.mk (fun (x y : E) => y - x ∈ S) (fun (a b : E) => b - a ∈ S ∧ ¬a - b ∈ S) sorry sorry
/-- A pointed and salient cone defines a partial order. -/
def to_partial_order {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) (h₁ : pointed S) (h₂ : salient S) : partial_order E :=
partial_order.mk preorder.le preorder.lt sorry sorry sorry
/-- A pointed and salient cone defines an `ordered_add_comm_group`. -/
def to_ordered_add_comm_group {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (S : convex_cone E) (h₁ : pointed S) (h₂ : salient S) : ordered_add_comm_group E :=
ordered_add_comm_group.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub
sorry sorry partial_order.le partial_order.lt sorry sorry sorry sorry
/-! ### Positive cone of an ordered semimodule -/
/--
The positive cone is the convex cone formed by the set of nonnegative elements in an ordered
semimodule.
-/
def positive_cone (M : Type u_4) [ordered_add_comm_group M] [semimodule ℝ M] [ordered_semimodule ℝ M] : convex_cone M :=
mk (set_of fun (x : M) => 0 ≤ x) sorry sorry
/-- The positive cone of an ordered semimodule is always salient. -/
theorem salient_of_positive_cone (M : Type u_4) [ordered_add_comm_group M] [semimodule ℝ M] [ordered_semimodule ℝ M] : salient (positive_cone M) := sorry
/-- The positive cone of an ordered semimodule is always pointed. -/
theorem pointed_of_positive_cone (M : Type u_4) [ordered_add_comm_group M] [semimodule ℝ M] [ordered_semimodule ℝ M] : pointed (positive_cone M) :=
le_refl 0
end convex_cone
/-!
### Cone over a convex set
-/
namespace convex
/-- The set of vectors proportional to those in a convex set forms a convex cone. -/
def to_cone {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (s : set E) (hs : convex s) : convex_cone E :=
convex_cone.mk (set.Union fun (c : ℝ) => set.Union fun (H : c > 0) => c • s) sorry sorry
theorem mem_to_cone {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : convex s) {x : E} : x ∈ to_cone s hs ↔ ∃ (c : ℝ), ∃ (H : c > 0), ∃ (y : E), ∃ (H : y ∈ s), c • y = x := sorry
theorem mem_to_cone' {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : convex s) {x : E} : x ∈ to_cone s hs ↔ ∃ (c : ℝ), ∃ (H : c > 0), c • x ∈ s := sorry
theorem subset_to_cone {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : convex s) : s ⊆ ↑(to_cone s hs) :=
fun (x : E) (hx : x ∈ s) =>
iff.mpr (mem_to_cone' hs)
(Exists.intro 1 (Exists.intro zero_lt_one (eq.mpr (id (Eq._oldrec (Eq.refl (1 • x ∈ s)) (one_smul ℝ x))) hx)))
/-- `hs.to_cone s` is the least cone that includes `s`. -/
theorem to_cone_is_least {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : convex s) : is_least (set_of fun (t : convex_cone E) => s ⊆ ↑t) (to_cone s hs) := sorry
theorem to_cone_eq_Inf {E : Type u_1} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : convex s) : to_cone s hs = Inf (set_of fun (t : convex_cone E) => s ⊆ ↑t) :=
Eq.symm (is_glb.Inf_eq (is_least.is_glb (to_cone_is_least hs)))
end convex
theorem convex_hull_to_cone_is_least {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (s : set E) : is_least (set_of fun (t : convex_cone E) => s ⊆ ↑t) (convex.to_cone (convex_hull s) (convex_convex_hull s)) := sorry
theorem convex_hull_to_cone_eq_Inf {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (s : set E) : convex.to_cone (convex_hull s) (convex_convex_hull s) = Inf (set_of fun (t : convex_cone E) => s ⊆ ↑t) :=
Eq.symm (is_glb.Inf_eq (is_least.is_glb (convex_hull_to_cone_is_least s)))
/-!
### M. Riesz extension theorem
Given a convex cone `s` in a vector space `E`, a submodule `p`, and a linear `f : p → ℝ`, assume
that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then there exists a globally defined linear
function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`.
We prove this theorem using Zorn's lemma. `riesz_extension.step` is the main part of the proof.
It says that if the domain `p` of `f` is not the whole space, then `f` can be extended to a larger
subspace `p ⊔ span ℝ {y}` without breaking the non-negativity condition.
In `riesz_extension.exists_top` we use Zorn's lemma to prove that we can extend `f`
to a linear map `g` on `⊤ : submodule E`. Mathematically this is the same as a linear map on `E`
but in Lean `⊤ : submodule E` is isomorphic but is not equal to `E`. In `riesz_extension`
we use this isomorphism to prove the theorem.
-/
namespace riesz_extension
/-- Induction step in M. Riesz extension theorem. Given a convex cone `s` in a vector space `E`,
a partially defined linear map `f : f.domain → ℝ`, assume that `f` is nonnegative on `f.domain ∩ p`
and `p + s = E`. If `f` is not defined on the whole `E`, then we can extend it to a larger
submodule without breaking the non-negativity condition. -/
theorem step {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (s : convex_cone E) (f : linear_pmap ℝ E ℝ) (nonneg : ∀ (x : ↥(linear_pmap.domain f)), ↑x ∈ s → 0 ≤ coe_fn f x) (dense : ∀ (y : E), ∃ (x : ↥(linear_pmap.domain f)), ↑x + y ∈ s) (hdom : linear_pmap.domain f ≠ ⊤) : ∃ (g : linear_pmap ℝ E ℝ), f < g ∧ ∀ (x : ↥(linear_pmap.domain g)), ↑x ∈ s → 0 ≤ coe_fn g x := sorry
theorem exists_top {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (s : convex_cone E) (p : linear_pmap ℝ E ℝ) (hp_nonneg : ∀ (x : ↥(linear_pmap.domain p)), ↑x ∈ s → 0 ≤ coe_fn p x) (hp_dense : ∀ (y : E), ∃ (x : ↥(linear_pmap.domain p)), ↑x + y ∈ s) : ∃ (q : linear_pmap ℝ E ℝ),
∃ (H : q ≥ p), linear_pmap.domain q = ⊤ ∧ ∀ (x : ↥(linear_pmap.domain q)), ↑x ∈ s → 0 ≤ coe_fn q x := sorry
end riesz_extension
/-- M. Riesz extension theorem: given a convex cone `s` in a vector space `E`, a submodule `p`,
and a linear `f : p → ℝ`, assume that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then
there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`,
and is nonnegative on `s`. -/
theorem riesz_extension {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (s : convex_cone E) (f : linear_pmap ℝ E ℝ) (nonneg : ∀ (x : ↥(linear_pmap.domain f)), ↑x ∈ s → 0 ≤ coe_fn f x) (dense : ∀ (y : E), ∃ (x : ↥(linear_pmap.domain f)), ↑x + y ∈ s) : ∃ (g : linear_map ℝ E ℝ),
(∀ (x : ↥(linear_pmap.domain f)), coe_fn g ↑x = coe_fn f x) ∧ ∀ (x : E), x ∈ s → 0 ≤ coe_fn g x := sorry
/-- Hahn-Banach theorem: if `N : E → ℝ` is a sublinear map, `f` is a linear map
defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`,
then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x`
for all `x`. -/
theorem exists_extension_of_le_sublinear {E : Type u_1} [add_comm_group E] [vector_space ℝ E] (f : linear_pmap ℝ E ℝ) (N : E → ℝ) (N_hom : ∀ (c : ℝ), 0 < c → ∀ (x : E), N (c • x) = c * N x) (N_add : ∀ (x y : E), N (x + y) ≤ N x + N y) (hf : ∀ (x : ↥(linear_pmap.domain f)), coe_fn f x ≤ N ↑x) : ∃ (g : linear_map ℝ E ℝ), (∀ (x : ↥(linear_pmap.domain f)), coe_fn g ↑x = coe_fn f x) ∧ ∀ (x : E), coe_fn g x ≤ N x := sorry
|
75474f89a4dca7be742b814c9d521e89d0ac1f2f | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/normed_space/add_torsor_bases.lean | 18a1c19ef60ad692bfa737a1c1e309f6c9dac63e | [
"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 | 7,429 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import analysis.normed_space.banach
import analysis.normed_space.finite_dimension
import analysis.calculus.affine_map
import analysis.convex.combination
import linear_algebra.affine_space.basis
import linear_algebra.affine_space.finite_dimensional
/-!
# Bases in normed affine spaces.
This file contains results about bases in normed affine spaces.
## Main definitions:
* `continuous_barycentric_coord`
* `is_open_map_barycentric_coord`
* `interior_convex_hull_aff_basis`
* `exists_subset_affine_independent_span_eq_top_of_open`
* `interior_convex_hull_nonempty_iff_aff_span_eq_top`
-/
section barycentric
variables {ι 𝕜 E P : Type*} [nontrivially_normed_field 𝕜] [complete_space 𝕜]
variables [normed_add_comm_group E] [normed_space 𝕜 E] [finite_dimensional 𝕜 E]
variables [metric_space P] [normed_add_torsor E P]
variables (b : affine_basis ι 𝕜 P)
@[continuity]
lemma continuous_barycentric_coord (i : ι) : continuous (b.coord i) :=
(b.coord i).continuous_of_finite_dimensional
local attribute [instance] finite_dimensional.complete
lemma is_open_map_barycentric_coord [nontrivial ι] (i : ι) :
is_open_map (b.coord i) :=
(b.coord i).is_open_map (continuous_barycentric_coord b i) (b.surjective_coord i)
lemma smooth_barycentric_coord (b : affine_basis ι 𝕜 E) (i : ι) : cont_diff 𝕜 ⊤ (b.coord i) :=
(⟨b.coord i, continuous_barycentric_coord b i⟩ : E →A[𝕜] 𝕜).cont_diff
end barycentric
open set
/-- Given a finite-dimensional normed real vector space, the interior of the convex hull of an
affine basis is the set of points whose barycentric coordinates are strictly positive with respect
to this basis.
TODO Restate this result for affine spaces (instead of vector spaces) once the definition of
convexity is generalised to this setting. -/
lemma interior_convex_hull_aff_basis {ι E : Type*} [finite ι] [normed_add_comm_group E]
[normed_space ℝ E] (b : affine_basis ι ℝ E) :
interior (convex_hull ℝ (range b.points)) = { x | ∀ i, 0 < b.coord i x } :=
begin
casesI subsingleton_or_nontrivial ι,
{ -- The zero-dimensional case.
suffices : range (b.points) = univ, { simp [this], },
refine affine_subspace.eq_univ_of_subsingleton_span_eq_top _ b.tot,
rw ← image_univ,
exact subsingleton.image subsingleton_of_subsingleton b.points, },
{ -- The positive-dimensional case.
haveI : finite_dimensional ℝ E,
{ classical,
obtain ⟨i⟩ := (infer_instance : nonempty ι),
exact finite_dimensional.of_fintype_basis (b.basis_of i), },
have : convex_hull ℝ (range b.points) = ⋂ i, (b.coord i)⁻¹' Ici 0,
{ rw convex_hull_affine_basis_eq_nonneg_barycentric b, ext, simp, },
ext,
simp only [this, interior_Inter, ← is_open_map.preimage_interior_eq_interior_preimage
(is_open_map_barycentric_coord b _) (continuous_barycentric_coord b _),
interior_Ici, mem_Inter, mem_set_of_eq, mem_Ioi, mem_preimage], },
end
variables {V P : Type*} [normed_add_comm_group V] [normed_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
open affine_map
/-- Given a set `s` of affine-independent points belonging to an open set `u`, we may extend `s` to
an affine basis, all of whose elements belong to `u`. -/
lemma exists_subset_affine_independent_span_eq_top_of_open {s u : set P} (hu : is_open u)
(hsu : s ⊆ u) (hne : s.nonempty) (h : affine_independent ℝ (coe : s → P)) :
∃ t : set P, s ⊆ t ∧ t ⊆ u ∧ affine_independent ℝ (coe : t → P) ∧ affine_span ℝ t = ⊤ :=
begin
obtain ⟨q, hq⟩ := hne,
obtain ⟨ε, hε, hεu⟩ := metric.is_open_iff.mp hu q (hsu hq),
obtain ⟨t, ht₁, ht₂, ht₃⟩ := exists_subset_affine_independent_affine_span_eq_top h,
let f : P → P := λ y, line_map q y (ε / 2 / (dist y q)),
have hf : ∀ y, f y ∈ u,
{ intros y,
apply hεu,
simp only [metric.mem_ball, f, line_map_apply, dist_vadd_left, norm_smul, real.norm_eq_abs,
dist_eq_norm_vsub V y q],
cases eq_or_ne (∥y -ᵥ q∥) 0 with hyq hyq, { rwa [hyq, mul_zero], },
rw [← norm_pos_iff, norm_norm] at hyq,
calc abs (ε / 2 / ∥y -ᵥ q∥) * ∥y -ᵥ q∥
= ε / 2 / ∥y -ᵥ q∥ * ∥y -ᵥ q∥ : by rw [abs_div, abs_of_pos (half_pos hε), abs_of_pos hyq]
... = ε / 2 : div_mul_cancel _ (ne_of_gt hyq)
... < ε : half_lt_self hε, },
have hεyq : ∀ (y ∉ s), ε / 2 / dist y q ≠ 0,
{ simp only [ne.def, div_eq_zero_iff, or_false, dist_eq_zero, bit0_eq_zero, one_ne_zero,
not_or_distrib, ne_of_gt hε, true_and, not_false_iff],
exact λ y h1 h2, h1 (h2.symm ▸ hq) },
classical,
let w : t → ℝˣ := λ p, if hp : (p : P) ∈ s then 1 else units.mk0 _ (hεyq ↑p hp),
refine ⟨set.range (λ (p : t), line_map q p (w p : ℝ)), _, _, _, _⟩,
{ intros p hp, use ⟨p, ht₁ hp⟩, simp [w, hp], },
{ intros y hy,
simp only [set.mem_range, set_coe.exists, subtype.coe_mk] at hy,
obtain ⟨p, hp, hyq⟩ := hy,
by_cases hps : p ∈ s;
simp only [w, hps, line_map_apply_one, units.coe_mk0, dif_neg, dif_pos, not_false_iff,
units.coe_one, subtype.coe_mk] at hyq;
rw ← hyq;
[exact hsu hps, exact hf p], },
{ exact (ht₂.units_line_map ⟨q, ht₁ hq⟩ w).range, },
{ rw [affine_span_eq_affine_span_line_map_units (ht₁ hq) w, ht₃], },
end
lemma interior_convex_hull_nonempty_iff_aff_span_eq_top [finite_dimensional ℝ V] {s : set V} :
(interior (convex_hull ℝ s)).nonempty ↔ affine_span ℝ s = ⊤ :=
begin
split,
{ rintros ⟨x, hx⟩,
obtain ⟨u, hu₁, hu₂, hu₃⟩ := mem_interior.mp hx,
let t : set V := {x},
obtain ⟨b, hb₁, hb₂, hb₃, hb₄⟩ := exists_subset_affine_independent_span_eq_top_of_open hu₂
(singleton_subset_iff.mpr hu₃) (singleton_nonempty x)
(affine_independent_of_subsingleton ℝ (coe : t → V)),
rw [eq_top_iff, ← hb₄, ← affine_span_convex_hull s],
mono,
exact hb₂.trans hu₁, },
{ intros h,
obtain ⟨t, hts, h_tot, h_ind⟩ := exists_affine_independent ℝ V s,
suffices : (interior (convex_hull ℝ (range (coe : t → V)))).nonempty,
{ rw [subtype.range_coe_subtype, set_of_mem_eq] at this,
apply nonempty.mono _ this,
mono* },
haveI : fintype t := fintype_of_fin_dim_affine_independent ℝ h_ind,
use finset.centroid ℝ (finset.univ : finset t) (coe : t → V),
rw [h, ← @set_of_mem_eq V t, ← subtype.range_coe_subtype] at h_tot,
let b : affine_basis t ℝ V := ⟨coe, h_ind, h_tot⟩,
rw interior_convex_hull_aff_basis b,
have htne : (finset.univ : finset t).nonempty,
{ simpa [finset.univ_nonempty_iff] using
affine_subspace.nonempty_of_affine_span_eq_top ℝ V V h_tot, },
simp [finset.centroid_def, b.coord_apply_combination_of_mem (finset.mem_univ _)
(finset.sum_centroid_weights_eq_one_of_nonempty ℝ (finset.univ : finset t) htne),
finset.centroid_weights_apply, nat.cast_pos, inv_pos, finset.card_pos.mpr htne], },
end
lemma convex.interior_nonempty_iff_affine_span_eq_top [finite_dimensional ℝ V] {s : set V}
(hs : convex ℝ s) : (interior s).nonempty ↔ affine_span ℝ s = ⊤ :=
by rw [← interior_convex_hull_nonempty_iff_aff_span_eq_top, hs.convex_hull_eq]
|
bfb9892bb7f764a352ea8ab10f0439bfb9b5976d | 592ee40978ac7604005a4e0d35bbc4b467389241 | /Library/generated/mathscheme-lean/Unital.lean | 6657f61d1d5d3c1b969a67d930345ce704dd18c6 | [] | no_license | ysharoda/Deriving-Definitions | 3e149e6641fae440badd35ac110a0bd705a49ad2 | dfecb27572022de3d4aa702cae8db19957523a59 | refs/heads/master | 1,679,127,857,700 | 1,615,939,007,000 | 1,615,939,007,000 | 229,785,731 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,502 | lean | import init.data.nat.basic
import init.data.fin.basic
import data.vector
import .Prelude
open Staged
open nat
open fin
open vector
section Unital
structure Unital (A : Type) : Type :=
(e : A)
(op : (A → (A → A)))
(lunit_e : (∀ {x : A} , (op e x) = x))
(runit_e : (∀ {x : A} , (op x e) = x))
open Unital
structure Sig (AS : Type) : Type :=
(eS : AS)
(opS : (AS → (AS → AS)))
structure Product (A : Type) : Type :=
(eP : (Prod A A))
(opP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(lunit_eP : (∀ {xP : (Prod A A)} , (opP eP xP) = xP))
(runit_eP : (∀ {xP : (Prod A A)} , (opP xP eP) = xP))
structure Hom {A1 : Type} {A2 : Type} (Un1 : (Unital A1)) (Un2 : (Unital A2)) : Type :=
(hom : (A1 → A2))
(pres_e : (hom (e Un1)) = (e Un2))
(pres_op : (∀ {x1 x2 : A1} , (hom ((op Un1) x1 x2)) = ((op Un2) (hom x1) (hom x2))))
structure RelInterp {A1 : Type} {A2 : Type} (Un1 : (Unital A1)) (Un2 : (Unital A2)) : Type 1 :=
(interp : (A1 → (A2 → Type)))
(interp_e : (interp (e Un1) (e Un2)))
(interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Un1) x1 x2) ((op Un2) y1 y2))))))
inductive UnitalTerm : Type
| eL : UnitalTerm
| opL : (UnitalTerm → (UnitalTerm → UnitalTerm))
open UnitalTerm
inductive ClUnitalTerm (A : Type) : Type
| sing : (A → ClUnitalTerm)
| eCl : ClUnitalTerm
| opCl : (ClUnitalTerm → (ClUnitalTerm → ClUnitalTerm))
open ClUnitalTerm
inductive OpUnitalTerm (n : ℕ) : Type
| v : ((fin n) → OpUnitalTerm)
| eOL : OpUnitalTerm
| opOL : (OpUnitalTerm → (OpUnitalTerm → OpUnitalTerm))
open OpUnitalTerm
inductive OpUnitalTerm2 (n : ℕ) (A : Type) : Type
| v2 : ((fin n) → OpUnitalTerm2)
| sing2 : (A → OpUnitalTerm2)
| eOL2 : OpUnitalTerm2
| opOL2 : (OpUnitalTerm2 → (OpUnitalTerm2 → OpUnitalTerm2))
open OpUnitalTerm2
def simplifyCl {A : Type} : ((ClUnitalTerm A) → (ClUnitalTerm A))
| (opCl eCl x) := x
| (opCl x eCl) := x
| eCl := eCl
| (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2))
| (sing x1) := (sing x1)
def simplifyOpB {n : ℕ} : ((OpUnitalTerm n) → (OpUnitalTerm n))
| (opOL eOL x) := x
| (opOL x eOL) := x
| eOL := eOL
| (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2))
| (v x1) := (v x1)
def simplifyOp {n : ℕ} {A : Type} : ((OpUnitalTerm2 n A) → (OpUnitalTerm2 n A))
| (opOL2 eOL2 x) := x
| (opOL2 x eOL2) := x
| eOL2 := eOL2
| (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2))
| (v2 x1) := (v2 x1)
| (sing2 x1) := (sing2 x1)
def evalB {A : Type} : ((Unital A) → (UnitalTerm → A))
| Un eL := (e Un)
| Un (opL x1 x2) := ((op Un) (evalB Un x1) (evalB Un x2))
def evalCl {A : Type} : ((Unital A) → ((ClUnitalTerm A) → A))
| Un (sing x1) := x1
| Un eCl := (e Un)
| Un (opCl x1 x2) := ((op Un) (evalCl Un x1) (evalCl Un x2))
def evalOpB {A : Type} {n : ℕ} : ((Unital A) → ((vector A n) → ((OpUnitalTerm n) → A)))
| Un vars (v x1) := (nth vars x1)
| Un vars eOL := (e Un)
| Un vars (opOL x1 x2) := ((op Un) (evalOpB Un vars x1) (evalOpB Un vars x2))
def evalOp {A : Type} {n : ℕ} : ((Unital A) → ((vector A n) → ((OpUnitalTerm2 n A) → A)))
| Un vars (v2 x1) := (nth vars x1)
| Un vars (sing2 x1) := x1
| Un vars eOL2 := (e Un)
| Un vars (opOL2 x1 x2) := ((op Un) (evalOp Un vars x1) (evalOp Un vars x2))
def inductionB {P : (UnitalTerm → Type)} : ((P eL) → ((∀ (x1 x2 : UnitalTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : UnitalTerm) , (P x))))
| pel popl eL := pel
| pel popl (opL x1 x2) := (popl _ _ (inductionB pel popl x1) (inductionB pel popl x2))
def inductionCl {A : Type} {P : ((ClUnitalTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((P eCl) → ((∀ (x1 x2 : (ClUnitalTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClUnitalTerm A)) , (P x)))))
| psing pecl popcl (sing x1) := (psing x1)
| psing pecl popcl eCl := pecl
| psing pecl popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing pecl popcl x1) (inductionCl psing pecl popcl x2))
def inductionOpB {n : ℕ} {P : ((OpUnitalTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((P eOL) → ((∀ (x1 x2 : (OpUnitalTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpUnitalTerm n)) , (P x)))))
| pv peol popol (v x1) := (pv x1)
| pv peol popol eOL := peol
| pv peol popol (opOL x1 x2) := (popol _ _ (inductionOpB pv peol popol x1) (inductionOpB pv peol popol x2))
def inductionOp {n : ℕ} {A : Type} {P : ((OpUnitalTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((P eOL2) → ((∀ (x1 x2 : (OpUnitalTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpUnitalTerm2 n A)) , (P x))))))
| pv2 psing2 peol2 popol2 (v2 x1) := (pv2 x1)
| pv2 psing2 peol2 popol2 (sing2 x1) := (psing2 x1)
| pv2 psing2 peol2 popol2 eOL2 := peol2
| pv2 psing2 peol2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 peol2 popol2 x1) (inductionOp pv2 psing2 peol2 popol2 x2))
def stageB : (UnitalTerm → (Staged UnitalTerm))
| eL := (Now eL)
| (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2))
def stageCl {A : Type} : ((ClUnitalTerm A) → (Staged (ClUnitalTerm A)))
| (sing x1) := (Now (sing x1))
| eCl := (Now eCl)
| (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2))
def stageOpB {n : ℕ} : ((OpUnitalTerm n) → (Staged (OpUnitalTerm n)))
| (v x1) := (const (code (v x1)))
| eOL := (Now eOL)
| (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2))
def stageOp {n : ℕ} {A : Type} : ((OpUnitalTerm2 n A) → (Staged (OpUnitalTerm2 n A)))
| (sing2 x1) := (Now (sing2 x1))
| (v2 x1) := (const (code (v2 x1)))
| eOL2 := (Now eOL2)
| (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2))
structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type :=
(eT : (Repr A))
(opT : ((Repr A) → ((Repr A) → (Repr A))))
end Unital |
4305d96da9a317106eedc0528b315a6da7b6d2a3 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/category_theory/limits/preserves/shapes/terminal.lean | 3b3b9fd2059fc416154a87172e642e01f9679a35 | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,604 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.limits.preserves.limits
import category_theory.limits.shapes.terminal
/-!
# Preserving terminal object
Constructions to relate the notions of preserving terminal objects and reflecting terminal objects
to concrete objects.
In particular, we show that `terminal_comparison G` is an isomorphism iff `G` preserves terminal
objects.
-/
universes v u₁ u₂
noncomputable theory
open category_theory category_theory.category category_theory.limits
variables {C : Type u₁} [category.{v} C]
variables {D : Type u₂} [category.{v} D]
variables (G : C ⥤ D)
namespace category_theory.limits
variables (X : C)
section terminal
/--
The map of an empty cone is a limit iff the mapped object is terminal.
-/
def is_limit_map_cone_empty_cone_equiv :
is_limit (G.map_cone (as_empty_cone X)) ≃ is_terminal (G.obj X) :=
(is_limit.postcompose_hom_equiv (functor.empty_ext _ _) _).symm.trans
(is_limit.equiv_iso_limit (cones.ext (iso.refl _) (by tidy)))
/-- The property of preserving terminal objects expressed in terms of `is_terminal`. -/
def is_terminal.is_terminal_obj [preserves_limit (functor.empty C) G]
(l : is_terminal X) : is_terminal (G.obj X) :=
is_limit_map_cone_empty_cone_equiv G X (preserves_limit.preserves l)
/-- The property of reflecting terminal objects expressed in terms of `is_terminal`. -/
def is_terminal.is_terminal_of_obj [reflects_limit (functor.empty C) G]
(l : is_terminal (G.obj X)) : is_terminal X :=
reflects_limit.reflects ((is_limit_map_cone_empty_cone_equiv G X).symm l)
variables [has_terminal C]
/--
If `G` preserves the terminal object and `C` has a terminal object, then the image of the terminal
object is terminal.
-/
def is_limit_of_has_terminal_of_preserves_limit [preserves_limit (functor.empty C) G] :
is_terminal (G.obj (⊤_ C)) :=
terminal_is_terminal.is_terminal_obj G (⊤_ C)
/--
If `C` has a terminal object and `G` preserves terminal objects, then `D` has a terminal object
also.
Note this property is somewhat unique to (co)limits of the empty diagram: for general `J`, if `C`
has limits of shape `J` and `G` preserves them, then `D` does not necessarily have limits of shape
`J`.
-/
lemma has_terminal_of_has_terminal_of_preserves_limit [preserves_limit (functor.empty C) G] :
has_terminal D :=
⟨λ F,
begin
haveI := has_limit.mk ⟨_, is_limit_of_has_terminal_of_preserves_limit G⟩,
apply has_limit_of_iso F.unique_from_empty.symm,
end⟩
variable [has_terminal D]
/--
If the terminal comparison map for `G` is an isomorphism, then `G` preserves terminal objects.
-/
def preserves_terminal.of_iso_comparison
[i : is_iso (terminal_comparison G)] : preserves_limit (functor.empty C) G :=
begin
apply preserves_limit_of_preserves_limit_cone terminal_is_terminal,
apply (is_limit_map_cone_empty_cone_equiv _ _).symm _,
apply is_limit.of_point_iso (limit.is_limit (functor.empty D)),
apply i,
end
/-- If there is any isomorphism `G.obj ⊤ ⟶ ⊤`, then `G` preserves terminal objects. -/
def preserves_terminal_of_is_iso
(f : G.obj (⊤_ C) ⟶ ⊤_ D) [i : is_iso f] : preserves_limit (functor.empty C) G :=
begin
rw subsingleton.elim f (terminal_comparison G) at i,
exactI preserves_terminal.of_iso_comparison G,
end
/-- If there is any isomorphism `G.obj ⊤ ≅ ⊤`, then `G` preserves terminal objects. -/
def preserves_terminal_of_iso
(f : G.obj (⊤_ C) ≅ ⊤_ D) : preserves_limit (functor.empty C) G :=
preserves_terminal_of_is_iso G f.hom
variables [preserves_limit (functor.empty C) G]
/--
If `G` preserves terminal objects, then the terminal comparison map for `G` is an isomorphism.
-/
def preserves_terminal.iso : G.obj (⊤_ C) ≅ ⊤_ D :=
(is_limit_of_has_terminal_of_preserves_limit G).cone_point_unique_up_to_iso (limit.is_limit _)
@[simp]
lemma preserves_terminal.iso_hom : (preserves_terminal.iso G).hom = terminal_comparison G :=
rfl
instance : is_iso (terminal_comparison G) :=
begin
rw ← preserves_terminal.iso_hom,
apply_instance,
end
end terminal
section initial
/--
The map of an empty cocone is a colimit iff the mapped object is initial.
-/
def is_colimit_map_cocone_empty_cocone_equiv :
is_colimit (G.map_cocone (as_empty_cocone X)) ≃ is_initial (G.obj X) :=
(is_colimit.precompose_hom_equiv (functor.empty_ext _ _) _).symm.trans
(is_colimit.equiv_iso_colimit (cocones.ext (iso.refl _) (by tidy)))
/-- The property of preserving initial objects expressed in terms of `is_initial`. -/
def is_initial.is_initial_obj [preserves_colimit (functor.empty C) G]
(l : is_initial X) : is_initial (G.obj X) :=
is_colimit_map_cocone_empty_cocone_equiv G X (preserves_colimit.preserves l)
/-- The property of reflecting initial objects expressed in terms of `is_initial`. -/
def is_initial.is_initial_of_obj [reflects_colimit (functor.empty C) G]
(l : is_initial (G.obj X)) : is_initial X :=
reflects_colimit.reflects ((is_colimit_map_cocone_empty_cocone_equiv G X).symm l)
variables [has_initial C]
/--
If `G` preserves the initial object and `C` has a initial object, then the image of the initial
object is initial.
-/
def is_colimit_of_has_initial_of_preserves_colimit [preserves_colimit (functor.empty C) G] :
is_initial (G.obj (⊥_ C)) :=
initial_is_initial.is_initial_obj G (⊥_ C)
/--
If `C` has a initial object and `G` preserves initial objects, then `D` has a initial object
also.
Note this property is somewhat unique to colimits of the empty diagram: for general `J`, if `C`
has colimits of shape `J` and `G` preserves them, then `D` does not necessarily have colimits of
shape `J`.
-/
lemma has_initial_of_has_initial_of_preserves_colimit [preserves_colimit (functor.empty C) G] :
has_initial D :=
⟨λ F,
begin
haveI := has_colimit.mk ⟨_, is_colimit_of_has_initial_of_preserves_colimit G⟩,
apply has_colimit_of_iso F.unique_from_empty,
end⟩
variable [has_initial D]
/--
If the initial comparison map for `G` is an isomorphism, then `G` preserves initial objects.
-/
def preserves_initial.of_iso_comparison
[i : is_iso (initial_comparison G)] : preserves_colimit (functor.empty C) G :=
begin
apply preserves_colimit_of_preserves_colimit_cocone initial_is_initial,
apply (is_colimit_map_cocone_empty_cocone_equiv _ _).symm _,
apply is_colimit.of_point_iso (colimit.is_colimit (functor.empty D)),
apply i,
end
/-- If there is any isomorphism `⊥ ⟶ G.obj ⊥`, then `G` preserves initial objects. -/
def preserves_initial_of_is_iso
(f : ⊥_ D ⟶ G.obj (⊥_ C)) [i : is_iso f] : preserves_colimit (functor.empty C) G :=
begin
rw subsingleton.elim f (initial_comparison G) at i,
exactI preserves_initial.of_iso_comparison G,
end
/-- If there is any isomorphism `⊥ ≅ G.obj ⊥ `, then `G` preserves initial objects. -/
def preserves_initial_of_iso
(f : ⊥_ D ≅ G.obj (⊥_ C)) : preserves_colimit (functor.empty C) G :=
preserves_initial_of_is_iso G f.hom
variables [preserves_colimit (functor.empty C) G]
/-- If `G` preserves initial objects, then the initial comparison map for `G` is an isomorphism. -/
def preserves_initial.iso : G.obj (⊥_ C) ≅ ⊥_ D :=
(is_colimit_of_has_initial_of_preserves_colimit G).cocone_point_unique_up_to_iso
(colimit.is_colimit _)
@[simp]
lemma preserves_initial.iso_hom : (preserves_initial.iso G).inv = initial_comparison G :=
rfl
instance : is_iso (initial_comparison G) :=
begin
rw ← preserves_initial.iso_hom,
apply_instance,
end
end initial
end category_theory.limits
|
99aba5f26731e89119dd9f5e78b491e8145b354f | bb31430994044506fa42fd667e2d556327e18dfe | /src/data/nat/squarefree.lean | f0ab22e538b91ecfe8a448aef9d145797aa039ac | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 22,057 | lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import algebra.squarefree
import data.nat.factorization.prime_pow
import data.nat.prime_norm_num
import ring_theory.int.basic
/-!
# Lemmas about squarefreeness of natural numbers
A number is squarefree when it is not divisible by any squares except the squares of units.
## Main Results
- `nat.squarefree_iff_nodup_factors`: A positive natural number `x` is squarefree iff
the list `factors x` has no duplicate factors.
## Tags
squarefree, multiplicity
-/
namespace nat
lemma squarefree_iff_nodup_factors {n : ℕ} (h0 : n ≠ 0) :
squarefree n ↔ n.factors.nodup :=
begin
rw [unique_factorization_monoid.squarefree_iff_nodup_normalized_factors h0, nat.factors_eq],
simp,
end
theorem squarefree_iff_prime_squarefree {n : ℕ} : squarefree n ↔ ∀ x, prime x → ¬ x * x ∣ n :=
squarefree_iff_irreducible_sq_not_dvd_of_exists_irreducible ⟨_, prime_two⟩
lemma squarefree.factorization_le_one {n : ℕ} (p : ℕ) (hn : squarefree n) :
n.factorization p ≤ 1 :=
begin
rcases eq_or_ne n 0 with rfl | hn',
{ simp },
rw [multiplicity.squarefree_iff_multiplicity_le_one] at hn,
by_cases hp : p.prime,
{ have := hn p,
simp only [multiplicity_eq_factorization hp hn', nat.is_unit_iff, hp.ne_one, or_false] at this,
exact_mod_cast this },
{ rw factorization_eq_zero_of_non_prime _ hp,
exact zero_le_one }
end
lemma squarefree_of_factorization_le_one {n : ℕ} (hn : n ≠ 0) (hn' : ∀ p, n.factorization p ≤ 1) :
squarefree n :=
begin
rw [squarefree_iff_nodup_factors hn, list.nodup_iff_count_le_one],
intro a,
rw factors_count_eq,
apply hn',
end
lemma squarefree_iff_factorization_le_one {n : ℕ} (hn : n ≠ 0) :
squarefree n ↔ ∀ p, n.factorization p ≤ 1 :=
⟨λ p hn, squarefree.factorization_le_one hn p, squarefree_of_factorization_le_one hn⟩
lemma squarefree.ext_iff {n m : ℕ} (hn : squarefree n) (hm : squarefree m) :
n = m ↔ ∀ p, prime p → (p ∣ n ↔ p ∣ m) :=
begin
refine ⟨by { rintro rfl, simp }, λ h, eq_of_factorization_eq hn.ne_zero hm.ne_zero (λ p, _)⟩,
by_cases hp : p.prime,
{ have h₁ := h _ hp,
rw [←not_iff_not, hp.dvd_iff_one_le_factorization hn.ne_zero, not_le, lt_one_iff,
hp.dvd_iff_one_le_factorization hm.ne_zero, not_le, lt_one_iff] at h₁,
have h₂ := squarefree.factorization_le_one p hn,
have h₃ := squarefree.factorization_le_one p hm,
rw [nat.le_add_one_iff, le_zero_iff] at h₂ h₃,
cases h₂,
{ rwa [h₂, eq_comm, ←h₁] },
{ rw [h₂, h₃.resolve_left],
rw [←h₁, h₂],
simp only [nat.one_ne_zero, not_false_iff] } },
rw [factorization_eq_zero_of_non_prime _ hp, factorization_eq_zero_of_non_prime _ hp],
end
lemma squarefree_pow_iff {n k : ℕ} (hn : n ≠ 1) (hk : k ≠ 0) :
squarefree (n ^ k) ↔ squarefree n ∧ k = 1 :=
begin
refine ⟨λ h, _, by { rintro ⟨hn, rfl⟩, simpa }⟩,
rcases eq_or_ne n 0 with rfl | hn₀,
{ simpa [zero_pow hk.bot_lt] using h },
refine ⟨h.squarefree_of_dvd (dvd_pow_self _ hk), by_contradiction $ λ h₁, _⟩,
have : 2 ≤ k := k.two_le_iff.mpr ⟨hk, h₁⟩,
apply hn (nat.is_unit_iff.1 (h _ _)),
rw ←sq,
exact pow_dvd_pow _ this
end
lemma squarefree_and_prime_pow_iff_prime {n : ℕ} :
squarefree n ∧ is_prime_pow n ↔ prime n :=
begin
refine iff.symm ⟨λ hn, ⟨hn.squarefree, hn.is_prime_pow⟩, _⟩,
rw is_prime_pow_nat_iff,
rintro ⟨h, p, k, hp, hk, rfl⟩,
rw squarefree_pow_iff hp.ne_one hk.ne' at h,
rwa [h.2, pow_one],
end
/-- Assuming that `n` has no factors less than `k`, returns the smallest prime `p` such that
`p^2 ∣ n`. -/
def min_sq_fac_aux : ℕ → ℕ → option ℕ
| n k :=
if h : n < k * k then none else
have nat.sqrt n + 2 - (k + 2) < nat.sqrt n + 2 - k,
by { rw nat.add_sub_add_right, exact nat.min_fac_lemma n k h },
if k ∣ n then
let n' := n / k in
have nat.sqrt n' + 2 - (k + 2) < nat.sqrt n + 2 - k, from
lt_of_le_of_lt (nat.sub_le_sub_right
(nat.add_le_add_right (nat.sqrt_le_sqrt $ nat.div_le_self _ _) _) _) this,
if k ∣ n' then some k else min_sq_fac_aux n' (k + 2)
else min_sq_fac_aux n (k + 2)
using_well_founded {rel_tac :=
λ _ _, `[exact ⟨_, measure_wf (λ ⟨n, k⟩, nat.sqrt n + 2 - k)⟩]}
/-- Returns the smallest prime factor `p` of `n` such that `p^2 ∣ n`, or `none` if there is no
such `p` (that is, `n` is squarefree). See also `squarefree_iff_min_sq_fac`. -/
def min_sq_fac (n : ℕ) : option ℕ :=
if 2 ∣ n then
let n' := n / 2 in
if 2 ∣ n' then some 2 else min_sq_fac_aux n' 3
else min_sq_fac_aux n 3
/-- The correctness property of the return value of `min_sq_fac`.
* If `none`, then `n` is squarefree;
* If `some d`, then `d` is a minimal square factor of `n` -/
def min_sq_fac_prop (n : ℕ) : option ℕ → Prop
| none := squarefree n
| (some d) := prime d ∧ d * d ∣ n ∧ ∀ p, prime p → p * p ∣ n → d ≤ p
theorem min_sq_fac_prop_div (n) {k} (pk : prime k) (dk : k ∣ n) (dkk : ¬ k * k ∣ n)
{o} (H : min_sq_fac_prop (n / k) o) : min_sq_fac_prop n o :=
begin
have : ∀ p, prime p → p*p ∣ n → k*(p*p) ∣ n := λ p pp dp,
have _ := (coprime_primes pk pp).2 (λ e, by { subst e, contradiction }),
(coprime_mul_iff_right.2 ⟨this, this⟩).mul_dvd_of_dvd_of_dvd dk dp,
cases o with d,
{ rw [min_sq_fac_prop, squarefree_iff_prime_squarefree] at H ⊢,
exact λ p pp dp, H p pp ((dvd_div_iff dk).2 (this _ pp dp)) },
{ obtain ⟨H1, H2, H3⟩ := H,
simp only [dvd_div_iff dk] at H2 H3,
exact ⟨H1, dvd_trans (dvd_mul_left _ _) H2, λ p pp dp, H3 _ pp (this _ pp dp)⟩ }
end
theorem min_sq_fac_aux_has_prop : ∀ {n : ℕ} k, 0 < n → ∀ i, k = 2*i+3 →
(∀ m, prime m → m ∣ n → k ≤ m) → min_sq_fac_prop n (min_sq_fac_aux n k)
| n k := λ n0 i e ih, begin
rw min_sq_fac_aux,
by_cases h : n < k*k; simp [h],
{ refine squarefree_iff_prime_squarefree.2 (λ p pp d, _),
have := ih p pp (dvd_trans ⟨_, rfl⟩ d),
have := nat.mul_le_mul this this,
exact not_le_of_lt h (le_trans this (le_of_dvd n0 d)) },
have k2 : 2 ≤ k, { subst e, exact dec_trivial },
have k0 : 0 < k := lt_of_lt_of_le dec_trivial k2,
have IH : ∀ n', n' ∣ n → ¬ k ∣ n' → min_sq_fac_prop n' (n'.min_sq_fac_aux (k + 2)),
{ intros n' nd' nk,
have hn' := le_of_dvd n0 nd',
refine
have nat.sqrt n' - k < nat.sqrt n + 2 - k, from
lt_of_le_of_lt (nat.sub_le_sub_right (nat.sqrt_le_sqrt hn') _) (nat.min_fac_lemma n k h),
@min_sq_fac_aux_has_prop n' (k+2) (pos_of_dvd_of_pos nd' n0)
(i+1) (by simp [e, left_distrib]) (λ m m2 d, _),
cases nat.eq_or_lt_of_le (ih m m2 (dvd_trans d nd')) with me ml,
{ subst me, contradiction },
apply (nat.eq_or_lt_of_le ml).resolve_left, intro me,
rw [← me, e] at d, change 2 * (i + 2) ∣ n' at d,
have := ih _ prime_two (dvd_trans (dvd_of_mul_right_dvd d) nd'),
rw e at this, exact absurd this dec_trivial },
have pk : k ∣ n → prime k,
{ refine λ dk, prime_def_min_fac.2 ⟨k2, le_antisymm (min_fac_le k0) _⟩,
exact ih _ (min_fac_prime (ne_of_gt k2)) (dvd_trans (min_fac_dvd _) dk) },
split_ifs with dk dkk,
{ exact ⟨pk dk, (nat.dvd_div_iff dk).1 dkk, λ p pp d, ih p pp (dvd_trans ⟨_, rfl⟩ d)⟩ },
{ specialize IH (n/k) (div_dvd_of_dvd dk) dkk,
exact min_sq_fac_prop_div _ (pk dk) dk (mt (nat.dvd_div_iff dk).2 dkk) IH },
{ exact IH n (dvd_refl _) dk }
end
using_well_founded {rel_tac :=
λ _ _, `[exact ⟨_, measure_wf (λ ⟨n, k⟩, nat.sqrt n + 2 - k)⟩]}
theorem min_sq_fac_has_prop (n : ℕ) : min_sq_fac_prop n (min_sq_fac n) :=
begin
dunfold min_sq_fac, split_ifs with d2 d4,
{ exact ⟨prime_two, (dvd_div_iff d2).1 d4, λ p pp _, pp.two_le⟩ },
{ cases nat.eq_zero_or_pos n with n0 n0, { subst n0, cases d4 dec_trivial },
refine min_sq_fac_prop_div _ prime_two d2 (mt (dvd_div_iff d2).2 d4) _,
refine min_sq_fac_aux_has_prop 3 (nat.div_pos (le_of_dvd n0 d2) dec_trivial) 0 rfl _,
refine λ p pp dp, succ_le_of_lt (lt_of_le_of_ne pp.two_le _),
rintro rfl, contradiction },
{ cases nat.eq_zero_or_pos n with n0 n0, { subst n0, cases d2 dec_trivial },
refine min_sq_fac_aux_has_prop _ n0 0 rfl _,
refine λ p pp dp, succ_le_of_lt (lt_of_le_of_ne pp.two_le _),
rintro rfl, contradiction },
end
theorem min_sq_fac_prime {n d : ℕ} (h : n.min_sq_fac = some d) : prime d :=
by { have := min_sq_fac_has_prop n, rw h at this, exact this.1 }
theorem min_sq_fac_dvd {n d : ℕ} (h : n.min_sq_fac = some d) : d * d ∣ n :=
by { have := min_sq_fac_has_prop n, rw h at this, exact this.2.1 }
theorem min_sq_fac_le_of_dvd {n d : ℕ} (h : n.min_sq_fac = some d)
{m} (m2 : 2 ≤ m) (md : m * m ∣ n) : d ≤ m :=
begin
have := min_sq_fac_has_prop n, rw h at this,
have fd := min_fac_dvd m,
exact le_trans
(this.2.2 _ (min_fac_prime $ ne_of_gt m2) (dvd_trans (mul_dvd_mul fd fd) md))
(min_fac_le $ lt_of_lt_of_le dec_trivial m2),
end
lemma squarefree_iff_min_sq_fac {n : ℕ} :
squarefree n ↔ n.min_sq_fac = none :=
begin
have := min_sq_fac_has_prop n,
split; intro H,
{ cases n.min_sq_fac with d, {refl},
cases squarefree_iff_prime_squarefree.1 H _ this.1 this.2.1 },
{ rwa H at this }
end
instance : decidable_pred (squarefree : ℕ → Prop) :=
λ n, decidable_of_iff' _ squarefree_iff_min_sq_fac
theorem squarefree_two : squarefree 2 := by rw squarefree_iff_nodup_factors; norm_num
open unique_factorization_monoid
lemma divisors_filter_squarefree {n : ℕ} (h0 : n ≠ 0) :
(n.divisors.filter squarefree).val =
(unique_factorization_monoid.normalized_factors n).to_finset.powerset.val.map
(λ x, x.val.prod) :=
begin
rw (finset.nodup _).ext ((finset.nodup _).map_on _),
{ intro a,
simp only [multiset.mem_filter, id.def, multiset.mem_map, finset.filter_val, ← finset.mem_def,
mem_divisors],
split,
{ rintro ⟨⟨an, h0⟩, hsq⟩,
use (unique_factorization_monoid.normalized_factors a).to_finset,
simp only [id.def, finset.mem_powerset],
rcases an with ⟨b, rfl⟩,
rw mul_ne_zero_iff at h0,
rw unique_factorization_monoid.squarefree_iff_nodup_normalized_factors h0.1 at hsq,
rw [multiset.to_finset_subset, multiset.to_finset_val, hsq.dedup, ← associated_iff_eq,
normalized_factors_mul h0.1 h0.2],
exact ⟨multiset.subset_of_le (multiset.le_add_right _ _), normalized_factors_prod h0.1⟩ },
{ rintro ⟨s, hs, rfl⟩,
rw [finset.mem_powerset, ← finset.val_le_iff, multiset.to_finset_val] at hs,
have hs0 : s.val.prod ≠ 0,
{ rw [ne.def, multiset.prod_eq_zero_iff],
simp only [exists_prop, id.def, exists_eq_right],
intro con,
apply not_irreducible_zero (irreducible_of_normalized_factor 0
(multiset.mem_dedup.1 (multiset.mem_of_le hs con))) },
rw (normalized_factors_prod h0).symm.dvd_iff_dvd_right,
refine ⟨⟨multiset.prod_dvd_prod_of_le (le_trans hs (multiset.dedup_le _)), h0⟩, _⟩,
have h := unique_factorization_monoid.factors_unique irreducible_of_normalized_factor
(λ x hx, irreducible_of_normalized_factor x (multiset.mem_of_le
(le_trans hs (multiset.dedup_le _)) hx)) (normalized_factors_prod hs0),
rw [associated_eq_eq, multiset.rel_eq] at h,
rw [unique_factorization_monoid.squarefree_iff_nodup_normalized_factors hs0, h],
apply s.nodup } },
{ intros x hx y hy h,
rw [← finset.val_inj, ← multiset.rel_eq, ← associated_eq_eq],
rw [← finset.mem_def, finset.mem_powerset] at hx hy,
apply unique_factorization_monoid.factors_unique _ _ (associated_iff_eq.2 h),
{ intros z hz,
apply irreducible_of_normalized_factor z,
rw ← multiset.mem_to_finset,
apply hx hz },
{ intros z hz,
apply irreducible_of_normalized_factor z,
rw ← multiset.mem_to_finset,
apply hy hz } }
end
open_locale big_operators
lemma sum_divisors_filter_squarefree {n : ℕ} (h0 : n ≠ 0)
{α : Type*} [add_comm_monoid α] {f : ℕ → α} :
∑ i in (n.divisors.filter squarefree), f i =
∑ i in (unique_factorization_monoid.normalized_factors n).to_finset.powerset, f (i.val.prod) :=
by rw [finset.sum_eq_multiset_sum, divisors_filter_squarefree h0, multiset.map_map,
finset.sum_eq_multiset_sum]
lemma sq_mul_squarefree_of_pos {n : ℕ} (hn : 0 < n) :
∃ a b : ℕ, 0 < a ∧ 0 < b ∧ b ^ 2 * a = n ∧ squarefree a :=
begin
let S := {s ∈ finset.range (n + 1) | s ∣ n ∧ ∃ x, s = x ^ 2},
have hSne : S.nonempty,
{ use 1,
have h1 : 0 < n ∧ ∃ (x : ℕ), 1 = x ^ 2 := ⟨hn, ⟨1, (one_pow 2).symm⟩⟩,
simpa [S] },
let s := finset.max' S hSne,
have hs : s ∈ S := finset.max'_mem S hSne,
simp only [finset.sep_def, S, finset.mem_filter, finset.mem_range] at hs,
obtain ⟨hsn1, ⟨a, hsa⟩, ⟨b, hsb⟩⟩ := hs,
rw hsa at hn,
obtain ⟨hlts, hlta⟩ := canonically_ordered_comm_semiring.mul_pos.mp hn,
rw hsb at hsa hn hlts,
refine ⟨a, b, hlta, (pow_pos_iff zero_lt_two).mp hlts, hsa.symm, _⟩,
rintro x ⟨y, hy⟩,
rw nat.is_unit_iff,
by_contra hx,
refine lt_le_antisymm _ (finset.le_max' S ((b * x) ^ 2) _),
{ simp_rw [S, hsa, finset.sep_def, finset.mem_filter, finset.mem_range],
refine ⟨lt_succ_iff.mpr (le_of_dvd hn _), _, ⟨b * x, rfl⟩⟩; use y; rw hy; ring },
{ convert lt_mul_of_one_lt_right hlts
(one_lt_pow 2 x zero_lt_two (one_lt_iff_ne_zero_and_ne_one.mpr ⟨λ h, by simp * at *, hx⟩)),
rw mul_pow },
end
lemma sq_mul_squarefree_of_pos' {n : ℕ} (h : 0 < n) :
∃ a b : ℕ, (b + 1) ^ 2 * (a + 1) = n ∧ squarefree (a + 1) :=
begin
obtain ⟨a₁, b₁, ha₁, hb₁, hab₁, hab₂⟩ := sq_mul_squarefree_of_pos h,
refine ⟨a₁.pred, b₁.pred, _, _⟩;
simpa only [add_one, succ_pred_eq_of_pos, ha₁, hb₁],
end
lemma sq_mul_squarefree (n : ℕ) : ∃ a b : ℕ, b ^ 2 * a = n ∧ squarefree a :=
begin
cases n,
{ exact ⟨1, 0, (by simp), squarefree_one⟩ },
{ obtain ⟨a, b, -, -, h₁, h₂⟩ := sq_mul_squarefree_of_pos (succ_pos n),
exact ⟨a, b, h₁, h₂⟩ },
end
/-- `squarefree` is multiplicative. Note that the → direction does not require `hmn`
and generalizes to arbitrary commutative monoids. See `squarefree.of_mul_left` and
`squarefree.of_mul_right` above for auxiliary lemmas. -/
lemma squarefree_mul {m n : ℕ} (hmn : m.coprime n) :
squarefree (m * n) ↔ squarefree m ∧ squarefree n :=
begin
simp only [squarefree_iff_prime_squarefree, ←sq, ←forall_and_distrib],
refine ball_congr (λ p hp, _),
simp only [hmn.is_prime_pow_dvd_mul (hp.is_prime_pow.pow two_ne_zero), not_or_distrib],
end
end nat
/-! ### Square-free prover -/
open norm_num
namespace tactic
namespace norm_num
/-- A predicate representing partial progress in a proof of `squarefree`. -/
def squarefree_helper (n k : ℕ) : Prop :=
0 < k → (∀ m, nat.prime m → m ∣ bit1 n → bit1 k ≤ m) → squarefree (bit1 n)
lemma squarefree_bit10 (n : ℕ) (h : squarefree_helper n 1) :
squarefree (bit0 (bit1 n)) :=
begin
refine @nat.min_sq_fac_prop_div _ _ nat.prime_two two_dvd_bit0 _ none _,
{ rw [bit0_eq_two_mul (bit1 n), mul_dvd_mul_iff_left (two_ne_zero' ℕ)],
exact nat.not_two_dvd_bit1 _ },
{ rw [bit0_eq_two_mul, nat.mul_div_right _ (dec_trivial:0<2)],
refine h dec_trivial (λ p pp dp, nat.succ_le_of_lt (lt_of_le_of_ne pp.two_le _)),
rintro rfl, exact nat.not_two_dvd_bit1 _ dp }
end
lemma squarefree_bit1 (n : ℕ) (h : squarefree_helper n 1) :
squarefree (bit1 n) :=
begin
refine h dec_trivial (λ p pp dp, nat.succ_le_of_lt (lt_of_le_of_ne pp.two_le _)),
rintro rfl, exact nat.not_two_dvd_bit1 _ dp
end
lemma squarefree_helper_0 {k} (k0 : 0 < k)
{p : ℕ} (pp : nat.prime p) (h : bit1 k ≤ p) : bit1 (k + 1) ≤ p ∨ bit1 k = p :=
begin
rcases lt_or_eq_of_le h with (hp:_+1≤_) | hp,
{ rw [bit1, bit0_eq_two_mul] at hp, change 2*(_+1) ≤ _ at hp,
rw [bit1, bit0_eq_two_mul],
refine or.inl (lt_of_le_of_ne hp _), unfreezingI { rintro rfl },
exact nat.not_prime_mul dec_trivial (lt_add_of_pos_left _ k0) pp },
{ exact or.inr hp }
end
lemma squarefree_helper_1 (n k k' : ℕ) (e : k + 1 = k')
(hk : nat.prime (bit1 k) → ¬ bit1 k ∣ bit1 n)
(H : squarefree_helper n k') : squarefree_helper n k :=
λ k0 ih, begin
subst e,
refine H (nat.succ_pos _) (λ p pp dp, _),
refine (squarefree_helper_0 k0 pp (ih p pp dp)).resolve_right (λ hp, _),
subst hp, cases hk pp dp
end
lemma squarefree_helper_2 (n k k' c : ℕ) (e : k + 1 = k')
(hc : bit1 n % bit1 k = c) (c0 : 0 < c)
(h : squarefree_helper n k') : squarefree_helper n k :=
begin
refine squarefree_helper_1 _ _ _ e (λ _, _) h,
refine mt _ (ne_of_gt c0), intro e₁,
rwa [← hc, ← nat.dvd_iff_mod_eq_zero],
end
lemma squarefree_helper_3 (n n' k k' c : ℕ) (e : k + 1 = k')
(hn' : bit1 n' * bit1 k = bit1 n)
(hc : bit1 n' % bit1 k = c) (c0 : 0 < c)
(H : squarefree_helper n' k') : squarefree_helper n k :=
λ k0 ih, begin
subst e,
have k0' : 0 < bit1 k := bit1_pos (nat.zero_le _),
have dn' : bit1 n' ∣ bit1 n := ⟨_, hn'.symm⟩,
have dk : bit1 k ∣ bit1 n := ⟨_, ((mul_comm _ _).trans hn').symm⟩,
have : bit1 n / bit1 k = bit1 n',
{ rw [← hn', nat.mul_div_cancel _ k0'] },
have k2 : 2 ≤ bit1 k := nat.succ_le_succ (bit0_pos k0),
have pk : (bit1 k).prime,
{ refine nat.prime_def_min_fac.2 ⟨k2, le_antisymm (nat.min_fac_le k0') _⟩,
exact ih _ (nat.min_fac_prime (ne_of_gt k2)) (dvd_trans (nat.min_fac_dvd _) dk) },
have dkk' : ¬ bit1 k ∣ bit1 n', {rw [nat.dvd_iff_mod_eq_zero, hc], exact ne_of_gt c0},
have dkk : ¬ bit1 k * bit1 k ∣ bit1 n, {rwa [← nat.dvd_div_iff dk, this]},
refine @nat.min_sq_fac_prop_div _ _ pk dk dkk none _,
rw this, refine H (nat.succ_pos _) (λ p pp dp, _),
refine (squarefree_helper_0 k0 pp (ih p pp $ dvd_trans dp dn')).resolve_right (λ e, _),
subst e, contradiction
end
lemma squarefree_helper_4 (n k k' : ℕ) (e : bit1 k * bit1 k = k')
(hd : bit1 n < k') : squarefree_helper n k :=
begin
cases nat.eq_zero_or_pos n with h h,
{ subst n, exact λ _ _, squarefree_one },
subst e,
refine λ k0 ih, irreducible.squarefree (nat.prime_def_le_sqrt.2 ⟨bit1_lt_bit1.2 h, _⟩),
intros m m2 hm md,
obtain ⟨p, pp, hp⟩ := nat.exists_prime_and_dvd (ne_of_gt m2),
have := (ih p pp (dvd_trans hp md)).trans
(le_trans (nat.le_of_dvd (lt_of_lt_of_le dec_trivial m2) hp) hm),
rw nat.le_sqrt at this,
exact not_le_of_lt hd this
end
lemma not_squarefree_mul (a aa b n : ℕ) (ha : a * a = aa) (hb : aa * b = n)
(h₁ : 1 < a) : ¬ squarefree n :=
by { rw [← hb, ← ha], exact λ H, ne_of_gt h₁ (nat.is_unit_iff.1 $ H _ ⟨_, rfl⟩) }
/-- Given `e` a natural numeral and `a : nat` with `a^2 ∣ n`, return `⊢ ¬ squarefree e`. -/
meta def prove_non_squarefree (e : expr) (n a : ℕ) : tactic expr := do
let ea := reflect a,
let eaa := reflect (a*a),
c ← mk_instance_cache `(nat),
(c, p₁) ← prove_lt_nat c `(1) ea,
let b := n / (a*a), let eb := reflect b,
(c, eaa, pa) ← prove_mul_nat c ea ea,
(c, e', pb) ← prove_mul_nat c eaa eb,
guard (e' =ₐ e),
return $ `(@not_squarefree_mul).mk_app [ea, eaa, eb, e, pa, pb, p₁]
/-- Given `en`,`en1 := bit1 en`, `n1` the value of `en1`, `ek`,
returns `⊢ squarefree_helper en ek`. -/
meta def prove_squarefree_aux : ∀ (ic : instance_cache) (en en1 : expr) (n1 : ℕ)
(ek : expr) (k : ℕ), tactic expr
| ic en en1 n1 ek k := do
let k1 := bit1 k,
let ek1 := `(bit1:ℕ→ℕ).mk_app [ek],
if n1 < k1*k1 then do
(ic, ek', p₁) ← prove_mul_nat ic ek1 ek1,
(ic, p₂) ← prove_lt_nat ic en1 ek',
pure $ `(squarefree_helper_4).mk_app [en, ek, ek', p₁, p₂]
else do
let c := n1 % k1,
let k' := k+1, let ek' := reflect k',
(ic, p₁) ← prove_succ ic ek ek',
if c = 0 then do
let n1' := n1 / k1,
let n' := n1' / 2, let en' := reflect n',
let en1' := `(bit1:ℕ→ℕ).mk_app [en'],
(ic, _, pn') ← prove_mul_nat ic en1' ek1,
let c := n1' % k1,
guard (c ≠ 0),
(ic, ec, pc) ← prove_div_mod ic en1' ek1 tt,
(ic, p₀) ← prove_pos ic ec,
p₂ ← prove_squarefree_aux ic en' en1' n1' ek' k',
pure $ `(squarefree_helper_3).mk_app [en, en', ek, ek', ec, p₁, pn', pc, p₀, p₂]
else do
(ic, ec, pc) ← prove_div_mod ic en1 ek1 tt,
(ic, p₀) ← prove_pos ic ec,
p₂ ← prove_squarefree_aux ic en en1 n1 ek' k',
pure $ `(squarefree_helper_2).mk_app [en, ek, ek', ec, p₁, pc, p₀, p₂]
/-- Given `n > 0` a squarefree natural numeral, returns `⊢ squarefree n`. -/
meta def prove_squarefree (en : expr) (n : ℕ) : tactic expr :=
match match_numeral en with
| match_numeral_result.one := pure `(@squarefree_one ℕ _)
| match_numeral_result.bit0 en1 := match match_numeral en1 with
| match_numeral_result.one := pure `(nat.squarefree_two)
| match_numeral_result.bit1 en := do
ic ← mk_instance_cache `(ℕ),
p ← prove_squarefree_aux ic en en1 (n / 2) `(1:ℕ) 1,
pure $ `(squarefree_bit10).mk_app [en, p]
| _ := failed
end
| match_numeral_result.bit1 en' := do
ic ← mk_instance_cache `(ℕ),
p ← prove_squarefree_aux ic en' en n `(1:ℕ) 1,
pure $ `(squarefree_bit1).mk_app [en', p]
| _ := failed
end
/-- Evaluates the `squarefree` predicate on naturals. -/
@[norm_num] meta def eval_squarefree : expr → tactic (expr × expr)
| `(squarefree (%%e : ℕ)) := do
n ← e.to_nat,
match n with
| 0 := false_intro `(@not_squarefree_zero ℕ _ _)
| 1 := true_intro `(@squarefree_one ℕ _)
| _ := match n.min_sq_fac with
| some d := prove_non_squarefree e n d >>= false_intro
| none := prove_squarefree e n >>= true_intro
end
end
| _ := failed
end norm_num
end tactic
|
1563a54d403023c3913aebb78dd1ebdbe1e6897e | 8f67b34bba98f894155dedf263bc8d61c31e89cd | /2ltt/fibrantlimits_aux.lean | 0fe3b0698b281142e9332bbc2f2fd08009e0032e | [] | no_license | 5HT/two-level | 3b1523db242cba819681b862fbc8f490d9571a66 | 370f5a91311db3b463b10a31891370721e2476e2 | refs/heads/master | 1,648,254,367,420 | 1,576,269,550,000 | 1,576,269,550,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,096 | lean | import .fibrant .matching .inverse algebra.category
.limit .pullbacks .finite .matching_facts
import data.fin
open invcat category functor matching_object Fib
sigma.ops fincat natural_transformation eq
universe variable u
variables {C : Category.{1 1}}
{D : Category}
open subcat_obj reedy
open sum nat fin function equiv
definition max_fun_to_ℕ (φ : C → ℕ) {n : ℕ} [ψ : objects C ≃ₛ fin (nat.succ n)] :
Σ z, (Π c, φ c ≤ φ z) :=
begin
generalize φ, clear φ, generalize ψ, clear ψ, generalize C, clear C,
induction n with [n', IHn],
intros,
{ cases ψ with [f,g,l,r], esimp at *,
existsi g (fin.zero 0),
intro, assert H : f c = zero, apply eq_of_veq, cases (f c) with [v, Hlt], esimp, cases v,
reflexivity, cases Hlt with [a, Hle], exfalso,
rewrite -(succ_le_zero_iff_false (succ a)), apply Hle, rewrite -l, rewrite H },
{ intros,
have H : Σ z, @to_fun _ (fin (succ (nat.succ n'))) ψ z = maxi, from ⟨(inv_fun C maxi), !right_inv⟩,
cases H with [z'', max_z],
have ψ' : C_without_z z'' ≃ fin (succ n'), from (@C_without_z_is_obj_finite _ _ z'' _),
have H : Π (φ : C_without_z z'' → ℕ),
Σ (z : C_without_z z''), (Π c, φ c ≤ φ z),
from IHn _ ψ',
cases H (φ ∘ obj) with [z', Hmax],
cases (@decidable_le (φ z'') (φ z')) with [z_le, z_ne_le],
existsi z', intros,
cases (@fincat.has_decidable_eq _ ⟨succ (succ n'), ψ⟩ c z'') with [c_eq_z, c_ne_z],
{ rewrite c_eq_z, assumption },
{ apply Hmax (mk _ c_ne_z) },
existsi z'', intro, apply nat.le_of_eq_or_lt,
cases (@fincat.has_decidable_eq _ ⟨succ (succ n'), ψ⟩ c z'') with [c_eq_z, c_ne_z],
left, rewrite c_eq_z, right,
have Hmax_c' : φ (obj (mk c c_ne_z)) ≤ φ (obj z'), from Hmax (mk c c_ne_z), esimp at *,
have Hlt : φ z' < φ z'', from iff.elim_right (gt_iff_not_le _ _) z_ne_le,
apply lt_of_le_of_lt Hmax_c' Hlt }
end
open invcat
definition Functor_from_C'_eq (X : C ⇒ U) (z : C) (x' : C_without_z z) :
X (@obj _ _ x') = (object (Functor_from_C' z X) x') :=
begin esimp end
open poly_unit
open reduced_coslice
open reduced_coslice.red_coslice_obs
-- for any object "a" from z//C (which is an arrow z⟶y with extra property) we show that codomain y cannot be z
-- we show it using the definition of reduced coslice and the fact that C is an inverse category
definition reduced_coslice_ne (z : C) (a : z//C) [invC : invcat C] : to a ≠ z :=
begin
cases a with [y, f, non_id_f], esimp at *,
intro p, cases p,
apply non_id_f rfl,
cases invC, cases reflecting_id_ℕop,
apply (reflecting_id f ⟨rfl,rfl⟩).2
end
definition Functor_from_C'_reedy_fibrant (z : C) (X : C ⇒ U) [invC : invcat C]
{φ : C ⇒ ℕop} {max_rank : ∀ x, φ x ≤ φ z} {reflecting_id : id_reflect φ}
[rfibX : is_reedy_fibrant X] [finC : is_obj_finite C]
: is_reedy_fibrant (Functor_from_C' z X) :=
begin
let C' := C_without_z z,
let X' := Functor_from_C' z X,
unfold is_reedy_fibrant at *,
unfold is_fibration at *,
intros x b,
let Hequiv := (@MO_equiv C z x φ reflecting_id max_rank _ _ X),
let MO := @to_fun _ _ Hequiv b,
assert isfibX' : is_fibrant (fibreₛ (matching_obj_map X (obj x)) (@to_fun _ _ Hequiv b)), begin apply (rfibX x MO) end,
assert Hfeq': (fibreₛ (matching_obj_map X (obj x)) MO) ≃ₛ (fibreₛ (matching_obj_map (Functor_from_C' z X) x) b),
begin
unfold fibreₛ, apply @sigma_congr₂, intros, esimp,
apply iff_impl_equiv, refine iff.intro _ _,
{ intros p,
calc
matching_obj_map X' x a
= @inv_fun _ _ Hequiv (matching_obj_map X (obj x) a) :
begin refine nat_trans_eq, apply funext, intro y, apply funext, intro uu,
cases y, cases uu, esimp end
... = @inv_fun _ _ Hequiv (@to_fun _ _ Hequiv b) : ap _ p
... = b : @left_inv _ _ _
},
{ intros p,
calc
matching_obj_map X (obj x) a
= Hequiv ∙ (matching_obj_map X' x a) :
begin
unfold fn, refine nat_trans_eq, apply funext, intro y, apply funext, intro uu,
cases uu, esimp at *,
assert H : morphism X (hom_to y) a =
natural_map ((@MO'_to_MO_map _ _ _ _ reflecting_id max_rank _ _ X)
(matching_obj_map (Functor_from_C' z X) x a)) y star, unfold MO'_to_MO_map,
rewrite natural_map_proj, cases y, esimp, cases x, esimp,
apply H end
... = Hequiv ∙ b : ap _ p }
end,
apply equiv_is_fibrant Hfeq'
end
-- map from limit of X restricted to C'
definition map_L_to_Mz (z : C) (X : C ⇒ U) [invC : invcat C]
(L : cone_with_tip (Functor_from_C' z X) poly_unit) : matching_object X z :=
by cases L with [η, NatSq]; refine natural_transformation.mk
(λ a u, η (mk (to a) (reduced_coslice_ne z a)) poly_unit.star)
(λ a b f, begin apply funext, intro, cases x, refine happly (NatSq _) poly_unit.star end)
-- explicit representation of the limit of X restricted to category C without z
definition lim_restricted [reducible] (X : C ⇒ U) (z : C) [invC : invcat C]
:= Σ (c : Π y, (Functor_from_C' z X) y),
Π (y y' : C_without_z z) (f : @hom (subcat_obj C _) _ y y'),
((Functor_from_C' z X) f) (c y) = c y'
-- map from the limit of X restricted to C' where we use explicit representation of limit L
definition map_L_to_Mz_alt (z : C) (X : C ⇒ U.{u}) [invC : invcat C]
(L : lim_restricted X z) : matching_object X z :=
match L with
| ⟨η, NatSq⟩ :=
by refine natural_transformation.mk
(λ a u, η (mk _ (reduced_coslice_ne z a)))
(λ a b f, funext (λ u, NatSq _ _ _))
end
open eq.ops
definition lift_to_rc [reducible] {z : C} (y : C_without_z z) (f : z ⟶ obj y): z//C :=
red_coslice_obs.mk (obj y) f (λ p a, prop y p⁻¹)
definition singleton_contr_fiberₛ {E B : Type} {p : E → B} : (Σ b, fibreₛ p b) ≃ₛ E :=
begin
refine equiv.mk (λ (p' : (Σ b, fibreₛ p b)), p'.2.1) (λ e, ⟨p e, ⟨e,rfl⟩⟩) _ (λx, rfl),
unfold function.left_inverse, intros, cases x with [p1, p2], cases p2 with [p21,p22],
esimp, induction p22 using eq.drec, congruence
end
definition two_piece_limit_pullback_p_q_equiv [invC : invcat C] (X : C ⇒ U.{u}) (z : C) :
(Σ (c_z : X z) (c : (Π y : C_without_z z, X y)),
(Π (y : C_without_z z) (f : z ⟶ obj y ), X f c_z = c y) ×
(Π (y y' : C_without_z z) (f : @hom (subcat_obj _ _) _ y y'), (Functor_from_C' z X) f (c y) = c y'))
≃ₛ
(Σ (c_z : X z) d, !map_L_to_Mz_alt d = !matching_obj_map c_z)
:=
begin
refine @sigma_congr₂ _ _ _ _, intro c_z,
refine equiv.mk _ _ _ _,
{ intro w, refine ⟨_,_⟩, refine ⟨w.1, prod.pr2 w.2⟩,
unfold map_L_to_Mz_alt, refine nat_trans_eq, unfold natural_map,
apply funext, intro y, apply funext, intro u, unfold matching_obj_map,
esimp, cases w with [c,p2], cases p2 with [p_l, p_r], esimp at *, symmetry,
apply (p_l (subcat_obj.mk (to y) (reduced_coslice_ne z y)) (hom_to y)) },
{ intro w,
cases w with [d, Heq], unfold lim_restricted at d, cases d with [c, Heq'], existsi c,
split,
{ intros,
assert H: natural_map (!map_L_to_Mz_alt ⟨c, Heq'⟩) (lift_to_rc y f) star =
natural_map (!matching_obj_map c_z) (lift_to_rc y f) star, begin rewrite Heq end,
assert lemma1 : natural_map (map_L_to_Mz_alt z X ⟨c,Heq'⟩) (lift_to_rc y f) star = c y,
begin unfold map_L_to_Mz_alt, unfold natural_map, cases y, esimp end,
have lemma2 : (natural_map (matching_obj_map X z c_z)) (lift_to_rc y f) star = X f c_z, from rfl,
symmetry,
apply #eq.ops lemma1⁻¹ ⬝ H ⬝ lemma2 },
{ apply Heq'}},
{ intro w, cases w with [c, H], cases H with [p1,p2], apply sigma_eq_congr, existsi rfl, apply apd },
{ intro w, cases w with [c, H], apply sigma_eq_congr, refine ⟨_,_⟩, cases c with [p1,p2],
apply sigma_eq_congr, existsi rfl, refine apd _ _, apply p2, reflexivity, apply proof_irrel }
end
definition lim_two_pieces_eq
{ X : C ⇒ U}
{ z : C }
{ c_z : X z}
{ c : Π y, X (obj y) }
{a b : (Π (y : C_without_z z) (f : z ⟶ obj y ), X f c_z = c y) ×
(Π (y y' : C_without_z z) (f : @hom (subcat_obj _ _) _ y y'), (Functor_from_C' z X) f (c y) = c y')} : a = b :=
begin cases a, cases b, congruence end
definition limit_two_piece_limit_equiv [invC : invcat C] {n' : ℕ}
(ψ : C ≃ₛ fin (succ n'))
{z : C}
{φ : C ⇒ ℕop}
(reflecting_id : id_reflect φ)
(max_rank : Πy, φ y ≤ φ z)
(X : C ⇒ U.{u}) :
(Σ (c : Π y, X y), Π y y' f, morphism X f (c y) = c y')
≃ₛ
(Σ (c_z : X z) (c : (Π y : C_without_z z, X y)),
(Π (y : C_without_z z) (f : z ⟶ obj y ), X f c_z = c y) ×
(Π (y y' : C_without_z z) (f : @hom (subcat_obj _ _) _ y y'), (Functor_from_C' z X) f (c y) = c y'))
:= begin
refine equiv.mk _ _ _ _,
{ intro, cases a with [p1, p2], refine ⟨p1 z, ⟨λ y, p1 y,(λ y' f, p2 z y' f, λ y y' f, p2 y y' f)⟩⟩ },
{ intro, cases a with [c_z, p'], cases p' with [p2, p3], cases p3 with [l_z, l_y], refine ⟨_,λ y y' f, _⟩, intro y'',
have Heq : decidable (y'' = z), from @fincat.has_decidable_eq _ (⟨_,ψ⟩) _ _,
cases Heq with [y_eq_z, y_ne_z],
{ rewrite y_eq_z, assumption },
{ refine p2 (mk y'' _), assumption },
intros,
-- now, we have 4 cases to consider: y=z, y≠z, y'=z, y'≠z
generalize (@fincat.has_decidable_eq C ⟨_,ψ⟩ y z),
generalize (@fincat.has_decidable_eq C ⟨_,ψ⟩ y' z),
intros deq_y deq_y',
cases deq_y' with [y_eq_z, y_ne_z]:
cases deq_y with [y'_eq_z, y'_ne_z],
{ cases y_eq_z, cases y'_eq_z, esimp, rewrite (endomorphism_is_id f), refine happly (respect_id _ _) _},
{ cases y_eq_z, esimp, apply l_z},
{ cases y'_eq_z, esimp, exfalso, apply (@no_incoming_non_id_arrows _ z φ max_rank _), existsi y, existsi f, assumption },
{ esimp, apply l_y },
},
{ unfold left_inverse, esimp, intros, cases x with [x, H], esimp, congruence, apply funext, intro y,
cases @fincat.has_decidable_eq C (⟨_,ψ⟩) y z with [y_eq_z, y_ne_z],
{ cases y_eq_z, esimp }, {esimp }},
{ unfold right_inverse, unfold left_inverse, esimp, intro y, cases y with [c_z, Hs],
esimp, cases Hs with [p1, p2], esimp, cases p2, esimp,
cases (@has_decidable_eq C ⟨succ n', ψ⟩ z z) with [y_eq_z, y_ne_z], esimp, congruence,
apply sigma_eq_congr,
refine ⟨_,lim_two_pieces_eq⟩,
{ intros, apply reflecting_id, assumption },
{ apply funext, intro y',
cases @fincat.has_decidable_eq C (⟨_,ψ⟩) y' z with [y'_eq_z, y'_ne_z], esimp,
cases y' with [y'', p'], esimp at *, exfalso, apply p', apply y'_eq_z,
esimp, cases y', congruence },
exfalso, apply y_ne_z, reflexivity
}
end
definition fibration_domain_is_fibrant {E : Type} {B : Fib} (p : E → B) [isfibr_p : is_fibration p]:
is_fibrant E := @equiv_is_fibrant (Σ b x, p x = b) _ singleton_contr_fiberₛ _
definition fincat_0_limit_unit_equiv [φ : C ≃ₛ fin 0 ] (X : C ⇒ U) : Nat(𝟙,X) ≃ₛ poly_unit :=
begin
cases φ with [f,g,l,r],
refine equiv.mk (λ x, star) _ _ _,
{ intros, esimp, refine mk _ _, intros x, exfalso, apply (false_of_fin_zero (f x)),
intros a b u, exfalso, apply (false_of_fin_zero (f a))},
{ unfold left_inverse, intro L, cases L, congruence, apply funext, intro x, exfalso, apply (false_of_fin_zero (f x))},
{ unfold right_inverse, unfold left_inverse, intro x, cases x, reflexivity }
end
|
9da61fa2d227a37fd978b82b777d9ac05843e45b | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/order/complete_lattice.lean | eeab9b77a60254a1478126af5fc6fe06fb230cbb | [
"Apache-2.0"
] | permissive | ntzwq/mathlib | ca50b21079b0a7c6781c34b62199a396dd00cee2 | 36eec1a98f22df82eaccd354a758ef8576af2a7f | refs/heads/master | 1,675,193,391,478 | 1,607,822,996,000 | 1,607,822,996,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 39,252 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import order.bounds
/-!
# Theory of complete lattices
## Main definitions
* `Sup` and `Inf` are the supremum and the infimum of a set;
* `supr (f : ι → α)` and `infi (f : ι → α)` are indexed supremum and infimum of a function,
defined as `Sup` and `Inf` of the range of this function;
* `class complete_lattice`: a bounded lattice such that `Sup s` is always the least upper boundary
of `s` and `Inf s` is always the greatest lower boundary of `s`;
* `class complete_linear_order`: a linear ordered complete lattice.
## Naming conventions
We use `Sup`/`Inf`/`supr`/`infi` for the corresponding functions in the statement. Sometimes we
also use `bsupr`/`binfi` for "bounded` supremum or infimum, i.e. one of `⨆ i ∈ s, f i`,
`⨆ i (hi : p i), f i`, or more generally `⨆ i (hi : p i), f i hi`.
## Notation
* `⨆ i, f i` : `supr f`, the supremum of the range of `f`;
* `⨅ i, f i` : `infi f`, the infimum of the range of `f`.
-/
set_option old_structure_cmd true
open set
variables {α β β₂ : Type*} {ι ι₂ : Sort*}
/-- class for the `Sup` operator -/
class has_Sup (α : Type*) := (Sup : set α → α)
/-- class for the `Inf` operator -/
class has_Inf (α : Type*) := (Inf : set α → α)
export has_Sup (Sup) has_Inf (Inf)
/-- Supremum of a set -/
add_decl_doc has_Sup.Sup
/-- Infimum of a set -/
add_decl_doc has_Inf.Inf
/-- Indexed supremum -/
def supr [has_Sup α] {ι} (s : ι → α) : α := Sup (range s)
/-- Indexed infimum -/
def infi [has_Inf α] {ι} (s : ι → α) : α := Inf (range s)
@[priority 50] instance has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩
@[priority 50] instance has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩
notation `⨆` binders `, ` r:(scoped f, supr f) := r
notation `⨅` binders `, ` r:(scoped f, infi f) := r
instance (α) [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩
instance (α) [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩
/-- A complete lattice is a bounded lattice which
has suprema and infima for every subset. -/
class complete_lattice (α : Type*) extends bounded_lattice α, has_Sup α, has_Inf α :=
(le_Sup : ∀s, ∀a∈s, a ≤ Sup s)
(Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a)
(Inf_le : ∀s, ∀a∈s, Inf s ≤ a)
(le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s)
/-- Create a `complete_lattice` from a `partial_order` and `Inf` function
that returns the greatest lower bound of a set. Usually this constructor provides
poor definitional equalities. If other fields are known explicitly, they should be
provided; for example, if `inf` is known explicitly, construct the `complete_lattice`
instance as
```
instance : complete_lattice my_T :=
{ inf := better_inf,
le_inf := ...,
inf_le_right := ...,
inf_le_left := ...
-- don't care to fix sup, Sup, bot, top
..complete_lattice_of_Inf my_T _ }
```
-/
def complete_lattice_of_Inf (α : Type*) [H1 : partial_order α]
[H2 : has_Inf α] (is_glb_Inf : ∀ s : set α, is_glb s (Inf s)) :
complete_lattice α :=
{ bot := Inf univ,
bot_le := λ x, (is_glb_Inf univ).1 trivial,
top := Inf ∅,
le_top := λ a, (is_glb_Inf ∅).2 $ by simp,
sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x},
inf := λ a b, Inf {a, b},
le_inf := λ a b c hab hac, by { apply (is_glb_Inf _).2, simp [*] },
inf_le_right := λ a b, (is_glb_Inf _).1 $ mem_insert_of_mem _ $ mem_singleton _,
inf_le_left := λ a b, (is_glb_Inf _).1 $ mem_insert _ _,
sup_le := λ a b c hac hbc, (is_glb_Inf _).1 $ by simp [*],
le_sup_left := λ a b, (is_glb_Inf _).2 $ λ x, and.left,
le_sup_right := λ a b, (is_glb_Inf _).2 $ λ x, and.right,
le_Inf := λ s a ha, (is_glb_Inf s).2 ha,
Inf_le := λ s a ha, (is_glb_Inf s).1 ha,
Sup := λ s, Inf (upper_bounds s),
le_Sup := λ s a ha, (is_glb_Inf (upper_bounds s)).2 $ λ b hb, hb ha,
Sup_le := λ s a ha, (is_glb_Inf (upper_bounds s)).1 ha,
.. H1, .. H2 }
/-- Create a `complete_lattice` from a `partial_order` and `Sup` function
that returns the least upper bound of a set. Usually this constructor provides
poor definitional equalities. If other fields are known explicitly, they should be
provided; for example, if `inf` is known explicitly, construct the `complete_lattice`
instance as
```
instance : complete_lattice my_T :=
{ inf := better_inf,
le_inf := ...,
inf_le_right := ...,
inf_le_left := ...
-- don't care to fix sup, Inf, bot, top
..complete_lattice_of_Sup my_T _ }
```
-/
def complete_lattice_of_Sup (α : Type*) [H1 : partial_order α]
[H2 : has_Sup α] (is_lub_Sup : ∀ s : set α, is_lub s (Sup s)) :
complete_lattice α :=
{ top := Sup univ,
le_top := λ x, (is_lub_Sup univ).1 trivial,
bot := Sup ∅,
bot_le := λ x, (is_lub_Sup ∅).2 $ by simp,
sup := λ a b, Sup {a, b},
sup_le := λ a b c hac hbc, (is_lub_Sup _).2 (by simp [*]),
le_sup_left := λ a b, (is_lub_Sup _).1 $ mem_insert _ _,
le_sup_right := λ a b, (is_lub_Sup _).1 $ mem_insert_of_mem _ $ mem_singleton _,
inf := λ a b, Sup {x | x ≤ a ∧ x ≤ b},
le_inf := λ a b c hab hac, (is_lub_Sup _).1 $ by simp [*],
inf_le_left := λ a b, (is_lub_Sup _).2 (λ x, and.left),
inf_le_right := λ a b, (is_lub_Sup _).2 (λ x, and.right),
Inf := λ s, Sup (lower_bounds s),
Sup_le := λ s a ha, (is_lub_Sup s).2 ha,
le_Sup := λ s a ha, (is_lub_Sup s).1 ha,
Inf_le := λ s a ha, (is_lub_Sup (lower_bounds s)).2 (λ b hb, hb ha),
le_Inf := λ s a ha, (is_lub_Sup (lower_bounds s)).1 ha,
.. H1, .. H2 }
/-- A complete linear order is a linear order whose lattice structure is complete. -/
class complete_linear_order (α : Type*) extends complete_lattice α, linear_order α
namespace order_dual
variable (α)
instance [complete_lattice α] : complete_lattice (order_dual α) :=
{ le_Sup := @complete_lattice.Inf_le α _,
Sup_le := @complete_lattice.le_Inf α _,
Inf_le := @complete_lattice.le_Sup α _,
le_Inf := @complete_lattice.Sup_le α _,
.. order_dual.bounded_lattice α, ..order_dual.has_Sup α, ..order_dual.has_Inf α }
instance [complete_linear_order α] : complete_linear_order (order_dual α) :=
{ .. order_dual.complete_lattice α, .. order_dual.linear_order α }
end order_dual
section
variables [complete_lattice α] {s t : set α} {a b : α}
@[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a
theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a
@[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a
theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a
lemma is_lub_Sup (s : set α) : is_lub s (Sup s) := ⟨assume x, le_Sup, assume x, Sup_le⟩
lemma is_lub.Sup_eq (h : is_lub s a) : Sup s = a := (is_lub_Sup s).unique h
lemma is_glb_Inf (s : set α) : is_glb s (Inf s) := ⟨assume a, Inf_le, assume a, le_Inf⟩
lemma is_glb.Inf_eq (h : is_glb s a) : Inf s = a := (is_glb_Inf s).unique h
theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s :=
le_trans h (le_Sup hb)
theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a :=
le_trans (Inf_le hb) h
theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t :=
(is_lub_Sup s).mono (is_lub_Sup t) h
theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s :=
(is_glb_Inf s).mono (is_glb_Inf t) h
@[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) :=
is_lub_le_iff (is_lub_Sup s)
@[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) :=
le_is_glb_iff (is_glb_Inf s)
theorem Sup_le_Sup_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, x ≤ y) : Sup s ≤ Sup t :=
le_of_forall_le' (by simp only [Sup_le_iff]; introv h₀ h₁; rcases h _ h₁ with ⟨y,hy,hy'⟩; solve_by_elim [le_trans hy'])
theorem Inf_le_Inf_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, y ≤ x) : Inf t ≤ Inf s :=
le_of_forall_le (by simp only [le_Inf_iff]; introv h₀ h₁; rcases h _ h₁ with ⟨y,hy,hy'⟩; solve_by_elim [le_trans _ hy'])
theorem Inf_le_Sup (hs : s.nonempty) : Inf s ≤ Sup s :=
is_glb_le_is_lub (is_glb_Inf s) (is_lub_Sup s) hs
-- TODO: it is weird that we have to add union_def
theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t :=
((is_lub_Sup s).union (is_lub_Sup t)).Sup_eq
theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t :=
by finish
/-
Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t))
-/
theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t :=
((is_glb_Inf s).union (is_glb_Inf t)).Inf_eq
theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) :=
@Sup_inter_le (order_dual α) _ _ _
@[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) :=
is_lub_empty.Sup_eq
@[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) :=
(@is_glb_empty α _).Inf_eq
@[simp] theorem Sup_univ : Sup univ = (⊤ : α) :=
(@is_lub_univ α _).Sup_eq
@[simp] theorem Inf_univ : Inf univ = (⊥ : α) :=
is_glb_univ.Inf_eq
-- TODO(Jeremy): get this automatically
@[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s :=
((is_lub_Sup s).insert a).Sup_eq
@[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s :=
((is_glb_Inf s).insert a).Inf_eq
theorem Sup_le_Sup_of_subset_instert_bot (h : s ⊆ insert ⊥ t) : Sup s ≤ Sup t :=
le_trans (Sup_le_Sup h) (le_of_eq (trans Sup_insert bot_sup_eq))
theorem Inf_le_Inf_of_subset_insert_top (h : s ⊆ insert ⊤ t) : Inf t ≤ Inf s :=
le_trans (le_of_eq (trans top_inf_eq.symm Inf_insert.symm)) (Inf_le_Inf h)
-- We will generalize this to conditionally complete lattices in `cSup_singleton`.
theorem Sup_singleton {a : α} : Sup {a} = a :=
is_lub_singleton.Sup_eq
-- We will generalize this to conditionally complete lattices in `cInf_singleton`.
theorem Inf_singleton {a : α} : Inf {a} = a :=
is_glb_singleton.Inf_eq
theorem Sup_pair {a b : α} : Sup {a, b} = a ⊔ b :=
(@is_lub_pair α _ a b).Sup_eq
theorem Inf_pair {a b : α} : Inf {a, b} = a ⊓ b :=
(@is_glb_pair α _ a b).Inf_eq
@[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) :=
iff.intro
(assume h a ha, top_unique $ h ▸ Inf_le ha)
(assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha)
@[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) :=
@Inf_eq_top (order_dual α) _ _
end
section complete_linear_order
variables [complete_linear_order α] {s t : set α} {a b : α}
lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) :=
is_glb_lt_iff (is_glb_Inf s)
lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) :=
lt_is_lub_iff (is_lub_Sup s)
lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) :=
iff.intro
(assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb)
(assume h, top_unique $ le_of_not_gt $ assume h',
let ⟨a, ha, h⟩ := h _ h' in
lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h)
lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) :=
@Sup_eq_top (order_dual α) _ _
lemma lt_supr_iff {f : ι → α} : a < supr f ↔ (∃i, a < f i) :=
lt_Sup_iff.trans exists_range_iff
lemma infi_lt_iff {f : ι → α} : infi f < a ↔ (∃i, f i < a) :=
Inf_lt_iff.trans exists_range_iff
end complete_linear_order
/-
### supr & infi
-/
section
variables [complete_lattice α] {s t : ι → α} {a b : α}
-- TODO: this declaration gives error when starting smt state
--@[ematch]
theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s :=
le_Sup ⟨i, rfl⟩
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) :=
le_Sup ⟨i, rfl⟩
/- TODO: this version would be more powerful, but, alas, the pattern matcher
doesn't accept it.
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) :=
le_Sup ⟨i, rfl⟩
-/
lemma is_lub_supr : is_lub (range s) (⨆j, s j) := is_lub_Sup _
lemma is_lub.supr_eq (h : is_lub (range s) a) : (⨆j, s j) = a := h.Sup_eq
lemma is_glb_infi : is_glb (range s) (⨅j, s j) := is_glb_Inf _
lemma is_glb.infi_eq (h : is_glb (range s) a) : (⨅j, s j) = a := h.Inf_eq
theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s :=
le_trans h (le_supr _ i)
theorem le_bsupr {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) :
f i hi ≤ ⨆ i hi, f i hi :=
le_supr_of_le i $ le_supr (f i) hi
theorem le_bsupr_of_le {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) (h : a ≤ f i hi) :
a ≤ ⨆ i hi, f i hi :=
le_trans h (le_bsupr i hi)
theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a :=
Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i
theorem bsupr_le {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ a) :
(⨆ i (hi : p i), f i hi) ≤ a :=
supr_le $ λ i, supr_le $ h i
theorem bsupr_le_supr (p : ι → Prop) (f : ι → α) : (⨆ i (H : p i), f i) ≤ ⨆ i, f i :=
bsupr_le (λ i hi, le_supr f i)
theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t :=
supr_le $ assume i, le_supr_of_le i (h i)
theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t :=
supr_le $ assume j, exists.elim (h j) le_supr_of_le
theorem bsupr_le_bsupr {p : ι → Prop} {f g : Π i (hi : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) :
(⨆ i hi, f i hi) ≤ ⨆ i hi, g i hi :=
bsupr_le $ λ i hi, le_trans (h i hi) (le_bsupr i hi)
theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) :=
supr_le $ le_supr _ ∘ h
@[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) :=
(is_lub_le_iff is_lub_supr).trans forall_range_iff
theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) :=
le_antisymm
(Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h)
(supr_le $ assume b, supr_le $ assume h, le_Sup h)
lemma le_supr_iff : (a ≤ supr s) ↔ (∀ b, (∀ i, s i ≤ b) → a ≤ b) :=
⟨λ h b hb, le_trans h (supr_le hb), λ h, h _ $ λ i, le_supr s i⟩
lemma monotone.le_map_supr [complete_lattice β] {f : α → β} (hf : monotone f) :
(⨆ i, f (s i)) ≤ f (supr s) :=
supr_le $ λ i, hf $ le_supr _ _
lemma monotone.le_map_supr2 [complete_lattice β] {f : α → β} (hf : monotone f)
{ι' : ι → Sort*} (s : Π i, ι' i → α) :
(⨆ i (h : ι' i), f (s i h)) ≤ f (⨆ i (h : ι' i), s i h) :=
calc (⨆ i h, f (s i h)) ≤ (⨆ i, f (⨆ h, s i h)) :
supr_le_supr $ λ i, hf.le_map_supr
... ≤ f (⨆ i (h : ι' i), s i h) : hf.le_map_supr
lemma monotone.le_map_Sup [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) :
(⨆a∈s, f a) ≤ f (Sup s) :=
by rw [Sup_eq_supr]; exact hf.le_map_supr2 _
lemma supr_comp_le {ι' : Sort*} (f : ι' → α) (g : ι → ι') :
(⨆ x, f (g x)) ≤ ⨆ y, f y :=
supr_le_supr2 $ λ x, ⟨_, le_refl _⟩
lemma monotone.supr_comp_eq [preorder β] {f : β → α} (hf : monotone f)
{s : ι → β} (hs : ∀ x, ∃ i, x ≤ s i) :
(⨆ x, f (s x)) = ⨆ y, f y :=
le_antisymm (supr_comp_le _ _) (supr_le_supr2 $ λ x, (hs x).imp $ λ i hi, hf hi)
lemma function.surjective.supr_comp {α : Type*} [has_Sup α] {f : ι → ι₂}
(hf : function.surjective f) (g : ι₂ → α) :
(⨆ x, g (f x)) = ⨆ y, g y :=
by simp only [supr, hf.range_comp]
lemma supr_congr {α : Type*} [has_Sup α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂)
(h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨆ x, f x) = ⨆ y, g y :=
by { convert h1.supr_comp g, exact (funext h2).symm }
-- TODO: finish doesn't do well here.
@[congr] theorem supr_congr_Prop {α : Type*} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ :=
begin
have : f₁ ∘ pq.mpr = f₂ := funext f,
rw [← this],
refine (function.surjective.supr_comp (λ h, ⟨pq.1 h, _⟩) f₁).symm,
refl
end
theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i :=
Inf_le ⟨i, rfl⟩
@[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) :=
Inf_le ⟨i, rfl⟩
theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a :=
le_trans (infi_le _ i) h
theorem binfi_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) :
(⨅ i hi, f i hi) ≤ f i hi :=
infi_le_of_le i $ infi_le (f i) hi
theorem binfi_le_of_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) (h : f i hi ≤ a) :
(⨅ i hi, f i hi) ≤ a :=
le_trans (binfi_le i hi) h
theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s :=
le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i
theorem le_binfi {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, a ≤ f i hi) :
a ≤ ⨅ i hi, f i hi :=
le_infi $ λ i, le_infi $ h i
theorem infi_le_binfi (p : ι → Prop) (f : ι → α) : (⨅ i, f i) ≤ ⨅ i (H : p i), f i :=
le_binfi (λ i hi, infi_le f i)
theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t :=
le_infi $ assume i, infi_le_of_le i (h i)
theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t :=
le_infi $ assume j, exists.elim (h j) infi_le_of_le
theorem binfi_le_binfi {p : ι → Prop} {f g : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) :
(⨅ i hi, f i hi) ≤ ⨅ i hi, g i hi :=
le_binfi $ λ i hi, le_trans (binfi_le i hi) (h i hi)
theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) :=
le_infi $ infi_le _ ∘ h
@[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) :=
⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩
theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) :=
@Sup_eq_supr (order_dual α) _ _
lemma monotone.map_infi_le [complete_lattice β] {f : α → β} (hf : monotone f) :
f (infi s) ≤ (⨅ i, f (s i)) :=
le_infi $ λ i, hf $ infi_le _ _
lemma monotone.map_infi2_le [complete_lattice β] {f : α → β} (hf : monotone f)
{ι' : ι → Sort*} (s : Π i, ι' i → α) :
f (⨅ i (h : ι' i), s i h) ≤ (⨅ i (h : ι' i), f (s i h)) :=
@monotone.le_map_supr2 (order_dual α) (order_dual β) _ _ _ f hf.order_dual _ _
lemma monotone.map_Inf_le [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) :
f (Inf s) ≤ ⨅ a∈s, f a :=
by rw [Inf_eq_infi]; exact hf.map_infi2_le _
lemma le_infi_comp {ι' : Sort*} (f : ι' → α) (g : ι → ι') :
(⨅ y, f y) ≤ ⨅ x, f (g x) :=
infi_le_infi2 $ λ x, ⟨_, le_refl _⟩
lemma monotone.infi_comp_eq [preorder β] {f : β → α} (hf : monotone f)
{s : ι → β} (hs : ∀ x, ∃ i, s i ≤ x) :
(⨅ x, f (s x)) = ⨅ y, f y :=
le_antisymm (infi_le_infi2 $ λ x, (hs x).imp $ λ i hi, hf hi) (le_infi_comp _ _)
lemma function.surjective.infi_comp {α : Type*} [has_Inf α] {f : ι → ι₂}
(hf : function.surjective f) (g : ι₂ → α) :
(⨅ x, g (f x)) = ⨅ y, g y :=
@function.surjective.supr_comp _ _ (order_dual α) _ f hf g
lemma infi_congr {α : Type*} [has_Inf α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂)
(h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨅ x, f x) = ⨅ y, g y :=
@supr_congr _ _ (order_dual α) _ _ _ h h1 h2
@[congr] theorem infi_congr_Prop {α : Type*} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ :=
@supr_congr_Prop (order_dual α) _ p q f₁ f₂ pq f
lemma supr_const_le {x : α} : (⨆ (h : ι), x) ≤ x :=
supr_le (λ _, le_rfl)
lemma le_infi_const {x : α} : x ≤ (⨅ (h : ι), x) :=
le_infi (λ _, le_rfl)
-- We will generalize this to conditionally complete lattices in `cinfi_const`.
theorem infi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a :=
by rw [infi, range_const, Inf_singleton]
-- We will generalize this to conditionally complete lattices in `csupr_const`.
theorem supr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a :=
@infi_const (order_dual α) _ _ _ _
@[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ :=
top_unique $ le_infi $ assume i, le_refl _
@[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ :=
@infi_top (order_dual α) _ _
@[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) :=
Inf_eq_top.trans forall_range_iff
@[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) :=
Sup_eq_bot.trans forall_range_iff
@[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp :=
le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _)
@[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ :=
le_antisymm le_top $ le_infi $ assume h, (hp h).elim
@[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp :=
le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _)
@[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ :=
le_antisymm (supr_le $ assume h, (hp h).elim) bot_le
lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) :
(⨆h:p, a h) = (if h : p then a h else ⊥) :=
by by_cases p; simp [h]
lemma supr_eq_if {p : Prop} [decidable p] (a : α) :
(⨆h:p, a) = (if p then a else ⊥) :=
supr_eq_dif (λ _, a)
lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) :
(⨅h:p, a h) = (if h : p then a h else ⊤) :=
@supr_eq_dif (order_dual α) _ _ _ _
lemma infi_eq_if {p : Prop} [decidable p] (a : α) :
(⨅h:p, a) = (if p then a else ⊤) :=
infi_eq_dif (λ _, a)
-- TODO: should this be @[simp]?
theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i)
(le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j)
/- TODO: this is strange. In the proof below, we get exactly the desired
among the equalities, but close does not get it.
begin
apply @le_antisymm,
simp, intros,
begin [smt]
ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i),
trace_state, close
end
end
-/
-- TODO: should this be @[simp]?
theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) :=
@infi_comm (order_dual α) _ _ _ _
@[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} :
(⨅x, ⨅h:x = b, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} :
(⨅x, ⨅h:b = x, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} :
(⨆x, ⨆h : x = b, f x h) = f b rfl :=
@infi_infi_eq_left (order_dual α) _ _ _ _
@[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} :
(⨆x, ⨆h : b = x, f x h) = f b rfl :=
@infi_infi_eq_right (order_dual α) _ _ _ _
attribute [ematch] le_refl
theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
lemma infi_subtype' {p : ι → Prop} {f : ∀ i, p i → α} :
(⨅ i (h : p i), f i h) = (⨅ x : subtype p, f x x.property) :=
(@infi_subtype _ _ _ p (λ x, f x.val x.property)).symm
lemma infi_subtype'' {ι} (s : set ι) (f : ι → α) :
(⨅ i : s, f i) = ⨅ (t : ι) (H : t ∈ s), f t :=
infi_subtype
theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) :=
le_antisymm
(le_inf
(le_infi $ assume i, infi_le_of_le i inf_le_left)
(le_infi $ assume i, infi_le_of_le i inf_le_right))
(le_infi $ assume i, le_inf
(inf_le_left_of_le $ infi_le _ _)
(inf_le_right_of_le $ infi_le _ _))
/- TODO: here is another example where more flexible pattern matching
might help.
begin
apply @le_antisymm,
safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end
end
-/
lemma infi_inf [h : nonempty ι] {f : ι → α} {a : α} : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) :=
by rw [infi_inf_eq, infi_const]
lemma inf_infi [nonempty ι] {f : ι → α} {a : α} : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) :=
by rw [inf_comm, infi_inf]; simp [inf_comm]
lemma binfi_inf {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) :
(⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) :=
by haveI : nonempty {i // p i} := (let ⟨i, hi⟩ := h in ⟨⟨i, hi⟩⟩);
rw [infi_subtype', infi_subtype', infi_inf]
theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) :=
@infi_inf_eq (order_dual α) β _ _ _
/- supr and infi under Prop -/
@[simp] theorem infi_false {s : false → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, false.elim i)
@[simp] theorem supr_false {s : false → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, false.elim i) bot_le
@[simp] theorem infi_true {s : true → α} : infi s = s trivial :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_true {s : true → α} : supr s = s trivial :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
@[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} :
(⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
@[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} :
(⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) :=
@infi_exists (order_dual α) _ _ _ _
theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
/-- The symmetric case of `infi_and`, useful for rewriting into a infimum over a conjunction -/
lemma infi_and' {p q : Prop} {s : p → q → α} :
(⨅ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨅ (h : p ∧ q), s h.1 h.2 :=
by { symmetry, exact infi_and }
theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) :=
@infi_and (order_dual α) _ _ _ _
/-- The symmetric case of `supr_and`, useful for rewriting into a supremum over a conjunction -/
lemma supr_and' {p q : Prop} {s : p → q → α} :
(⨆ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨆ (h : p ∧ q), s h.1 h.2 :=
by { symmetry, exact supr_and }
theorem infi_or {p q : Prop} {s : p ∨ q → α} :
infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume i, match i with
| or.inl i := inf_le_left_of_le $ infi_le _ _
| or.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_or {p q : Prop} {s : p ∨ q → α} :
(⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) :=
@infi_or (order_dual α) _ _ _ _
lemma Sup_range {α : Type*} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl
lemma Inf_range {α : Type*} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl
lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) :=
le_antisymm
(supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i)
(supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _))
lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) :=
@supr_range (order_dual α) _ _ _ _ _
theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) :=
by rw [← infi_subtype'', infi, range_comp, subtype.range_coe]
theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) :=
@Inf_image (order_dual α) _ _ _ _
/-
### supr and infi under set constructions
-/
theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ :=
by simp
theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ :=
by simp
theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) :=
by simp
theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) :=
by simp
theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) :=
by simp only [← infi_inf_eq, infi_or]
lemma infi_split (f : β → α) (p : β → Prop) :
(⨅ i, f i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), f i) :=
by simpa [classical.em] using @infi_union _ _ _ f {i | p i} {i | ¬ p i}
lemma infi_split_single (f : β → α) (i₀ : β) :
(⨅ i, f i) = f i₀ ⊓ (⨅ i (h : i ≠ i₀), f i) :=
by convert infi_split _ _; simp
theorem infi_le_infi_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) :
(⨅ x ∈ t, f x) ≤ (⨅ x ∈ s, f x) :=
by rw [(union_eq_self_of_subset_left h).symm, infi_union]; exact inf_le_left
theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) :=
@infi_union (order_dual α) _ _ _ _ _
lemma supr_split (f : β → α) (p : β → Prop) :
(⨆ i, f i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), f i) :=
@infi_split (order_dual α) _ _ _ _
lemma supr_split_single (f : β → α) (i₀ : β) :
(⨆ i, f i) = f i₀ ⊔ (⨆ i (h : i ≠ i₀), f i) :=
@infi_split_single (order_dual α) _ _ _ _
theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) :
(⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) :=
@infi_le_infi_of_subset (order_dual α) _ _ _ _ _ h
theorem infi_insert {f : β → α} {s : set β} {b : β} :
(⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) :=
eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left
theorem supr_insert {f : β → α} {s : set β} {b : β} :
(⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) :=
eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left
theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b :=
by simp
theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b :=
by rw [infi_insert, infi_singleton]
theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b :=
@infi_singleton (order_dual α) _ _ _ _
theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b :=
by rw [supr_insert, supr_singleton]
lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} :
(⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) :=
by rw [← Inf_image, ← Inf_image, ← image_comp]
lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} :
(⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) :=
@infi_image (order_dual α) _ _ _ _ _ _
/-!
### `supr` and `infi` under `Type`
-/
theorem infi_of_empty' (h : ι → false) {s : ι → α} : infi s = ⊤ :=
top_unique (le_infi $ assume i, (h i).elim)
theorem supr_of_empty' (h : ι → false) {s : ι → α} : supr s = ⊥ :=
bot_unique (supr_le $ assume i, (h i).elim)
theorem infi_of_empty (h : ¬nonempty ι) {s : ι → α} : infi s = ⊤ :=
infi_of_empty' (λ i, h ⟨i⟩)
theorem supr_of_empty (h : ¬nonempty ι) {s : ι → α} : supr s = ⊥ :=
supr_of_empty' (λ i, h ⟨i⟩)
@[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ :=
infi_of_empty nonempty_empty
@[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ :=
supr_of_empty nonempty_empty
@[simp] theorem infi_unit {f : unit → α} : (⨅ x, f x) = f () :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_unit {f : unit → α} : (⨆ x, f x) = f () :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff :=
le_antisymm
(supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end)
(sup_le (le_supr _ _) (le_supr _ _))
lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff :=
@supr_bool_eq (order_dual α) _ _
lemma is_glb_binfi {s : set β} {f : β → α} : is_glb (f '' s) (⨅ x ∈ s, f x) :=
by simpa only [range_comp, subtype.range_coe, infi_subtype'] using @is_glb_infi α s _ (f ∘ coe)
theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
@infi_subtype (order_dual α) _ _ _ _
lemma supr_subtype' {p : ι → Prop} {f : ∀ i, p i → α} :
(⨆ i (h : p i), f i h) = (⨆ x : subtype p, f x x.property) :=
(@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm
lemma Sup_eq_supr' {s : set α} : Sup s = ⨆ x : s, (x : α) :=
by rw [Sup_eq_supr, supr_subtype']; refl
lemma is_lub_bsupr {s : set β} {f : β → α} : is_lub (f '' s) (⨆ x ∈ s, f x) :=
by simpa only [range_comp, subtype.range_coe, supr_subtype'] using @is_lub_supr α s _ (f ∘ coe)
theorem infi_sigma {p : β → Type*} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_sigma {p : β → Type*} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
@infi_sigma (order_dual α) _ _ _ _
theorem infi_prod {γ : Type*} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_prod {γ : Type*} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) :=
@infi_prod (order_dual α) _ _ _ _
theorem infi_sum {γ : Type*} {f : β ⊕ γ → α} :
(⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume i, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume s, match s with
| sum.inl i := inf_le_left_of_le $ infi_le _ _
| sum.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_sum {γ : Type*} {f : β ⊕ γ → α} :
(⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) :=
@infi_sum (order_dual α) _ _ _ _
/-!
### `supr` and `infi` under `ℕ`
-/
lemma supr_ge_eq_supr_nat_add {u : ℕ → α} (n : ℕ) : (⨆ i ≥ n, u i) = ⨆ i, u (i + n) :=
begin
apply le_antisymm;
simp only [supr_le_iff],
{ exact λ i hi, le_Sup ⟨i - n, by { dsimp only, rw nat.sub_add_cancel hi }⟩ },
{ exact λ i, le_Sup ⟨i + n, supr_pos (nat.le_add_left _ _)⟩ }
end
lemma infi_ge_eq_infi_nat_add {u : ℕ → α} (n : ℕ) : (⨅ i ≥ n, u i) = ⨅ i, u (i + n) :=
@supr_ge_eq_supr_nat_add (order_dual α) _ _ _
end
section complete_linear_order
variables [complete_linear_order α]
lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) :=
by simp only [← Sup_range, Sup_eq_top, set.exists_range_iff]
lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, f i < b) :=
by simp only [← Inf_range, Inf_eq_bot, set.exists_range_iff]
end complete_linear_order
/-!
### Instances
-/
instance complete_lattice_Prop : complete_lattice Prop :=
{ Sup := λs, ∃a∈s, a,
le_Sup := assume s a h p, ⟨a, h, p⟩,
Sup_le := assume s a h ⟨b, h', p⟩, h b h' p,
Inf := λs, ∀a:Prop, a∈s → a,
Inf_le := assume s a h p, p a h,
le_Inf := assume s a h p b hb, h b hb p,
.. bounded_distrib_lattice_Prop }
lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl
lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl
lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) :=
le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i)
lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) :=
le_antisymm (λ ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (λ ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩)
instance pi.has_Sup {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] : has_Sup (Π i, β i) :=
⟨λ s i, ⨆ f : s, (f : Π i, β i) i⟩
instance pi.has_Inf {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] : has_Inf (Π i, β i) :=
⟨λ s i, ⨅ f : s, (f : Π i, β i) i⟩
instance pi.complete_lattice {α : Type*} {β : α → Type*} [∀ i, complete_lattice (β i)] :
complete_lattice (Π i, β i) :=
{ Sup := Sup,
Inf := Inf,
le_Sup := λ s f hf i, le_supr (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩,
Inf_le := λ s f hf i, infi_le (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩,
Sup_le := λ s f hf i, supr_le $ λ g, hf g g.2 i,
le_Inf := λ s f hf i, le_infi $ λ g, hf g g.2 i,
.. pi.bounded_lattice }
lemma Inf_apply {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)]
{s : set (Πa, β a)} {a : α} :
(Inf s) a = (⨅ f : s, (f : Πa, β a) a) :=
rfl
lemma infi_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Inf (β i)]
{f : ι → Πa, β a} {a : α} :
(⨅i, f i) a = (⨅i, f i a) :=
by rw [infi, Inf_apply, infi, infi, ← image_eq_range (λ f : Π i, β i, f a) (range f), ← range_comp]
lemma Sup_apply {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] {s : set (Πa, β a)} {a : α} :
(Sup s) a = (⨆f:s, (f : Πa, β a) a) :=
rfl
lemma supr_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Sup (β i)] {f : ι → Πa, β a}
{a : α} :
(⨆i, f i) a = (⨆i, f i a) :=
@infi_apply α (λ i, order_dual (β i)) _ _ f a
section complete_lattice
variables [preorder α] [complete_lattice β]
theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) :=
assume x y h, supr_le $ λ f, le_supr_of_le f $ m_s f f.2 h
theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) :=
assume x y h, le_infi $ λ f, infi_le_of_le f $ m_s f f.2 h
end complete_lattice
namespace prod
variables (α β)
instance [has_Inf α] [has_Inf β] : has_Inf (α × β) :=
⟨λs, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩
instance [has_Sup α] [has_Sup β] : has_Sup (α × β) :=
⟨λs, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩
instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) :=
{ le_Sup := assume s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩,
Sup_le := assume s p h,
⟨ Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).1,
Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).2⟩,
Inf_le := assume s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩,
le_Inf := assume s p h,
⟨ le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).1,
le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).2⟩,
.. prod.bounded_lattice α β,
.. prod.has_Sup α β,
.. prod.has_Inf α β }
end prod
|
1be292d4175d965f65940836a53d7dbfc06c9adc | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/concrete_category/bundled.lean | 824b25cadc1b2d7487f4652da432328dbb272d3b | [] | 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,469 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.category.default
import Mathlib.PostPort
universes u v l
namespace Mathlib
/-!
# Bundled types
`bundled c` provides a uniform structure for bundling a type equipped with a type class.
We provide `category` instances for these in `category_theory/unbundled_hom.lean`
(for categories with unbundled homs, e.g. topological spaces)
and in `category_theory/bundled_hom.lean` (for categories with bundled homs, e.g. monoids).
-/
namespace category_theory
/-- `bundled` is a type bundled with a type class instance for that type. Only
the type class is exposed as a parameter. -/
structure bundled (c : Type u → Type v)
where
α : Type u
str : autoParam (c α)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.apply_instance")
(Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "apply_instance") [])
namespace bundled
/-- A generic function for lifting a type equipped with an instance to a bundled object. -/
-- Usually explicit instances will provide their own version of this, e.g. `Mon.of` and `Top.of`.
def of {c : Type u → Type v} (α : Type u) [str : c α] : bundled c :=
mk α
protected instance has_coe_to_sort {c : Type u → Type v} : has_coe_to_sort (bundled c) :=
has_coe_to_sort.mk (Type u) α
@[simp] theorem coe_mk {c : Type u → Type v} (α : Type u) (str : autoParam (c α)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.apply_instance")
(Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "apply_instance") [])) : ↥(mk α) = α :=
rfl
/-
`bundled.map` is reducible so that, if we define a category
def Ring : Type (u+1) := induced_category SemiRing (bundled.map @ring.to_semiring)
instance search is able to "see" that a morphism R ⟶ S in Ring is really
a (semi)ring homomorphism from R.α to S.α, and not merely from
`(bundled.map @ring.to_semiring R).α` to `(bundled.map @ring.to_semiring S).α`.
-/
/-- Map over the bundled structure -/
def map {c : Type u → Type v} {d : Type u → Type v} (f : {α : Type u} → c α → d α) (b : bundled c) : bundled d :=
mk ↥b
|
6ea7016a25c26ae691f92d596f69e256fed3098b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/direct_sum/algebra.lean | e08cc480379f0feedf09b8a6a85f38e3b65a350f | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 5,895 | 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 algebra.algebra.basic
import algebra.direct_sum.module
import algebra.direct_sum.ring
/-! # Additively-graded algebra structures on `⨁ i, A i`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file provides `R`-algebra structures on external direct sums of `R`-modules.
Recall that if `A i` are a family of `add_comm_monoid`s indexed by an `add_monoid`, then an instance
of `direct_sum.gmonoid A` is a multiplication `A i → A j → A (i + j)` giving `⨁ i, A i` the
structure of a semiring. In this file, we introduce the `direct_sum.galgebra R A` class for the case
where all `A i` are `R`-modules. This is the extra structure needed to promote `⨁ i, A i` to an
`R`-algebra.
## Main definitions
* `direct_sum.galgebra R A`, the typeclass.
* `direct_sum.galgebra.of_submodules`, for creating the above instance from a collection of
submodules.
* `direct_sum.to_algebra` extends `direct_sum.to_semiring` to produce an `alg_hom`.
-/
universes uι uR uA uB
variables {ι : Type uι}
namespace direct_sum
open_locale direct_sum
variables (R : Type uR) (A : ι → Type uA) {B : Type uB} [decidable_eq ι]
variables [comm_semiring R] [Π i, add_comm_monoid (A i)] [Π i, module R (A i)]
variables [add_monoid ι] [gsemiring A]
section
/-- A graded version of `algebra`. An instance of `direct_sum.galgebra R A` endows `(⨁ i, A i)`
with an `R`-algebra structure. -/
class galgebra :=
(to_fun : R →+ A 0)
(map_one : to_fun 1 = graded_monoid.ghas_one.one)
(map_mul : ∀ r s,
graded_monoid.mk _ (to_fun (r * s)) = ⟨_, graded_monoid.ghas_mul.mul (to_fun r) (to_fun s)⟩)
(commutes : ∀ r x, graded_monoid.mk _ (to_fun r) * x = x * ⟨_, to_fun r⟩)
(smul_def : ∀ r (x : graded_monoid A), graded_monoid.mk x.1 (r • x.2) = ⟨_, to_fun (r)⟩ * x)
end
variables [semiring B] [galgebra R A] [algebra R B]
instance : algebra R (⨁ i, A i) :=
{ to_fun := (direct_sum.of A 0).comp galgebra.to_fun,
map_zero' := add_monoid_hom.map_zero _,
map_add' := add_monoid_hom.map_add _,
map_one' := (direct_sum.of A 0).congr_arg galgebra.map_one,
map_mul' := λ a b, begin
simp only [add_monoid_hom.comp_apply],
rw of_mul_of,
apply dfinsupp.single_eq_of_sigma_eq (galgebra.map_mul a b),
end,
commutes' := λ r x, begin
change add_monoid_hom.mul (direct_sum.of _ _ _) x =
add_monoid_hom.mul.flip (direct_sum.of _ _ _) x,
apply add_monoid_hom.congr_fun _ x,
ext i xi : 2,
dsimp only [add_monoid_hom.comp_apply, add_monoid_hom.mul_apply, add_monoid_hom.flip_apply],
rw [of_mul_of, of_mul_of],
apply dfinsupp.single_eq_of_sigma_eq (galgebra.commutes r ⟨i, xi⟩),
end,
smul_def' := λ r x, begin
change distrib_mul_action.to_add_monoid_hom _ r x = add_monoid_hom.mul (direct_sum.of _ _ _) x,
apply add_monoid_hom.congr_fun _ x,
ext i xi : 2,
dsimp only [add_monoid_hom.comp_apply, distrib_mul_action.to_add_monoid_hom_apply,
add_monoid_hom.mul_apply],
rw [direct_sum.of_mul_of, ←of_smul],
apply dfinsupp.single_eq_of_sigma_eq (galgebra.smul_def r ⟨i, xi⟩),
end }
lemma algebra_map_apply (r : R) :
algebra_map R (⨁ i, A i) r = direct_sum.of A 0 (galgebra.to_fun r) := rfl
lemma algebra_map_to_add_monoid_hom :
↑(algebra_map R (⨁ i, A i)) = (direct_sum.of A 0).comp (galgebra.to_fun : R →+ A 0) := rfl
/-- A family of `linear_map`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul`
describes an `alg_hom` on `⨁ i, A i`. This is a stronger version of `direct_sum.to_semiring`.
Of particular interest is the case when `A i` are bundled subojects, `f` is the family of
coercions such as `submodule.subtype (A i)`, and the `[gmonoid A]` structure originates from
`direct_sum.gmonoid.of_add_submodules`, in which case the proofs about `ghas_one` and `ghas_mul`
can be discharged by `rfl`. -/
@[simps]
def to_algebra
(f : Π i, A i →ₗ[R] B) (hone : f _ (graded_monoid.ghas_one.one) = 1)
(hmul : ∀ {i j} (ai : A i) (aj : A j), f _ (graded_monoid.ghas_mul.mul ai aj) = f _ ai * f _ aj)
(hcommutes : ∀ r, (f 0) (galgebra.to_fun r) = (algebra_map R B) r) :
(⨁ i, A i) →ₐ[R] B :=
{ to_fun := to_semiring (λ i, (f i).to_add_monoid_hom) hone @hmul,
commutes' := λ r, (direct_sum.to_semiring_of _ _ _ _ _).trans (hcommutes r),
.. to_semiring (λ i, (f i).to_add_monoid_hom) hone @hmul}
/-- Two `alg_hom`s out of a direct sum are equal if they agree on the generators.
See note [partially-applied ext lemmas]. -/
@[ext]
lemma alg_hom_ext' ⦃f g : (⨁ i, A i) →ₐ[R] B⦄
(h : ∀ i, f.to_linear_map.comp (lof _ _ A i) = g.to_linear_map.comp (lof _ _ A i)) : f = g :=
alg_hom.to_linear_map_injective $ direct_sum.linear_map_ext _ h
lemma alg_hom_ext ⦃f g : (⨁ i, A i) →ₐ[R] B⦄ (h : ∀ i x, f (of A i x) = g (of A i x)) : f = g :=
alg_hom_ext' R A $ λ i, linear_map.ext $ h i
end direct_sum
/-! ### Concrete instances -/
/-- A direct sum of copies of a `algebra` inherits the algebra structure.
-/
@[simps]
instance algebra.direct_sum_galgebra {R A : Type*} [decidable_eq ι]
[add_monoid ι] [comm_semiring R] [semiring A] [algebra R A] :
direct_sum.galgebra R (λ i : ι, A) :=
{ to_fun := (algebra_map R A).to_add_monoid_hom,
map_one := (algebra_map R A).map_one,
map_mul := λ a b, sigma.ext (zero_add _).symm (heq_of_eq $ (algebra_map R A).map_mul a b),
commutes := λ r ⟨ai, a⟩, sigma.ext ((zero_add _).trans (add_zero _).symm)
(heq_of_eq $ algebra.commutes _ _),
smul_def := λ r ⟨ai, a⟩, sigma.ext (zero_add _).symm (heq_of_eq $ algebra.smul_def _ _) }
namespace submodule
variables {R A : Type*} [comm_semiring R]
end submodule
|
180f5f62ae1abd52f7db3b4c7b0edd21497f1d8b | 05b503addd423dd68145d68b8cde5cd595d74365 | /src/ring_theory/algebra.lean | f50fe43d4f78935db678985b6cda2f0f6f0bb5ca | [
"Apache-2.0"
] | permissive | aestriplex/mathlib | 77513ff2b176d74a3bec114f33b519069788811d | e2fa8b2b1b732d7c25119229e3cdfba8370cb00f | refs/heads/master | 1,621,969,960,692 | 1,586,279,279,000 | 1,586,279,279,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,355 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
Algebra over Commutative Ring (under category)
-/
import data.complex.basic
import data.matrix.basic
import linear_algebra.tensor_product
import ring_theory.subring
import algebra.commute
noncomputable theory
universes u v w u₁ v₁
open_locale tensor_product
section prio
-- We set this priority to 0 later in this file
set_option default_priority 200 -- see Note [default priority]
/-- The category of R-algebras where R is a commutative
ring is the under category R ↓ CRing. In the categorical
setting we have a forgetful functor R-Alg ⥤ R-Mod.
However here it extends module in order to preserve
definitional equality in certain cases. -/
class algebra (R : Type u) (A : Type v) [comm_ring R] [ring A] extends has_scalar R A :=
(to_fun : R → A) [hom : is_ring_hom to_fun]
(commutes' : ∀ r x, x * to_fun r = to_fun r * x)
(smul_def' : ∀ r x, r • x = to_fun r * x)
end prio
def algebra_map {R : Type u} (A : Type v) [comm_ring R] [ring A] [algebra R A] (x : R) : A :=
algebra.to_fun A x
namespace algebra
variables {R : Type u} {S : Type v} {A : Type w}
variables [comm_ring R] [comm_ring S] [ring A] [algebra R A]
instance : is_ring_hom (algebra_map A : R → A) := algebra.hom _ A
variables (A)
@[simp] lemma map_add (r s : R) : algebra_map A (r + s) = algebra_map A r + algebra_map A s :=
is_ring_hom.map_add _
@[simp] lemma map_neg (r : R) : algebra_map A (-r) = -algebra_map A r :=
is_ring_hom.map_neg _
@[simp] lemma map_sub (r s : R) : algebra_map A (r - s) = algebra_map A r - algebra_map A s :=
is_ring_hom.map_sub _
@[simp] lemma map_mul (r s : R) : algebra_map A (r * s) = algebra_map A r * algebra_map A s :=
is_ring_hom.map_mul _
variables (R)
@[simp] lemma map_zero : algebra_map A (0 : R) = 0 :=
is_ring_hom.map_zero _
@[simp] lemma map_one : algebra_map A (1 : R) = 1 :=
is_ring_hom.map_one _
variables {R A}
/-- Creating an algebra from a morphism in CRing. -/
def of_ring_hom (i : R → S) (hom : is_ring_hom i) : algebra R S :=
{ smul := λ c x, i c * x,
to_fun := i,
commutes' := λ _ _, mul_comm _ _,
smul_def' := λ c x, rfl }
lemma smul_def'' (r : R) (x : A) : r • x = algebra_map A r * x :=
algebra.smul_def' r x
@[priority 200] -- see Note [lower instance priority]
instance to_module : module R A :=
{ one_smul := by simp [smul_def''],
mul_smul := by simp [smul_def'', mul_assoc],
smul_add := by simp [smul_def'', mul_add],
smul_zero := by simp [smul_def''],
add_smul := by simp [smul_def'', add_mul],
zero_smul := by simp [smul_def''] }
-- from now on, we don't want to use the following instance anymore
attribute [instance, priority 0] algebra.to_has_scalar
lemma smul_def (r : R) (x : A) : r • x = algebra_map A r * x :=
algebra.smul_def' r x
theorem commutes (r : R) (x : A) : x * algebra_map A r = algebra_map A r * x :=
algebra.commutes' r x
theorem left_comm (r : R) (x y : A) : x * (algebra_map A r * y) = algebra_map A r * (x * y) :=
by rw [← mul_assoc, commutes, mul_assoc]
@[simp] lemma mul_smul_comm (s : R) (x y : A) :
x * (s • y) = s • (x * y) :=
by rw [smul_def, smul_def, left_comm]
@[simp] lemma smul_mul_assoc (r : R) (x y : A) :
(r • x) * y = r • (x * y) :=
by rw [smul_def, smul_def, mul_assoc]
/-- Creating an algebra from a subring. This is the dual of ring extension. -/
instance of_subring (S : set R) [is_subring S] : algebra S R :=
of_ring_hom subtype.val ⟨rfl, λ _ _, rfl, λ _ _, rfl⟩
variables (R A)
/-- The multiplication in an algebra is a bilinear map. -/
def lmul : A →ₗ A →ₗ A :=
linear_map.mk₂ R (*)
(λ x y z, add_mul x y z)
(λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y])
(λ x y z, mul_add x y z)
(λ c x y, by rw [smul_def, smul_def, left_comm])
def lmul_left (r : A) : A →ₗ A :=
lmul R A r
def lmul_right (r : A) : A →ₗ A :=
(lmul R A).flip r
variables {R A}
@[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl
@[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl
@[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl
end algebra
instance module.endomorphism_algebra (R : Type u) (M : Type v)
[comm_ring R] [add_comm_group M] [module R M] : algebra R (M →ₗ[R] M) :=
{ to_fun := (λ r, r • linear_map.id),
hom := by apply is_ring_hom.mk; intros; ext; simp [mul_smul, add_smul],
commutes' := by intros; ext; simp,
smul_def' := by intros; ext; simp }
set_option class.instance_max_depth 40
instance matrix_algebra (n : Type u) (R : Type v)
[fintype n] [decidable_eq n] [comm_ring R] : algebra R (matrix n n R) :=
{ to_fun := (λ r, r • 1),
hom := { map_one := by { ext, simp, },
map_mul := by { intros, ext, simp [mul_assoc], },
map_add := by { intros, simp [add_smul], } },
commutes' := by { intros, simp },
smul_def' := by { intros, simp } }
set_option old_structure_cmd true
/-- Defining the homomorphism in the category R-Alg. -/
structure alg_hom (R : Type u) (A : Type v) (B : Type w)
[comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] extends ring_hom A B :=
(commutes' : ∀ r : R, to_fun (algebra_map A r) = algebra_map B r)
infixr ` →ₐ `:25 := alg_hom _
notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁}
variables {rR : comm_ring R} {rA : ring A} {rB : ring B} {rC : ring C} {rD : ring D}
variables {aA : algebra R A} {aB : algebra R B} {aC : algebra R C} {aD : algebra R D}
include R rR rA rB aA aB
instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩
instance : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩
variables (φ : A →ₐ[R] B)
instance : is_ring_hom ⇑φ := ring_hom.is_ring_hom φ.to_ring_hom
@[ext]
theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ :=
by cases φ₁; cases φ₂; congr' 1; ext; apply H
theorem commutes (r : R) : φ (algebra_map A r) = algebra_map B r := φ.commutes' r
@[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s :=
is_ring_hom.map_add _
@[simp] lemma map_zero : φ 0 = 0 :=
is_ring_hom.map_zero _
@[simp] lemma map_neg (x) : φ (-x) = -φ x :=
is_ring_hom.map_neg _
@[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y :=
is_ring_hom.map_sub _
@[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y :=
is_ring_hom.map_mul _
@[simp] lemma map_one : φ 1 = 1 :=
is_ring_hom.map_one _
/-- R-Alg ⥤ R-Mod -/
def to_linear_map : A →ₗ B :=
{ to_fun := φ,
add := φ.map_add,
smul := λ (c : R) x, by rw [algebra.smul_def, φ.map_mul, φ.commutes c, algebra.smul_def] }
@[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl
theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ :=
ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H
variables (R A)
omit rB aB
variables [rR] [rA] [aA]
protected def id : A →ₐ[R] A :=
{ commutes' := λ _, rfl,
..ring_hom.id A }
variables {R A rR rA aA}
@[simp] lemma id_to_linear_map :
(alg_hom.id R A).to_linear_map = @linear_map.id R A _ _ _ := rfl
@[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl
include rB rC aB aC
def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C :=
{ commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl,
.. φ₁.to_ring_hom.comp ↑φ₂ }
@[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) :
(g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl
@[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) :
φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl
omit rC aC
@[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ :=
ext $ λ x, rfl
@[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ :=
ext $ λ x, rfl
include rC aC rD aD
theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) :
(φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) :=
ext $ λ x, rfl
end alg_hom
namespace algebra
variables (R : Type u) (S : Type v) (A : Type w)
include R S A
/-- `comap R S A` is a type alias for `A`, and has an R-algebra structure defined on it
when `algebra R S` and `algebra S A`. -/
/- This is done to avoid a type class search with meta-variables `algebra R ?m_1` and
`algebra ?m_1 A -/
/- The `nolint` attribute is added because it has unused arguments `R` and `S`, but these are necessary for synthesizing the
appropriate type classes -/
@[nolint unused_arguments] def comap : Type w := A
def comap.to_comap : A → comap R S A := id
def comap.of_comap : comap R S A → A := id
omit R S A
variables [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A]
instance comap.ring : ring (comap R S A) := _inst_3
instance comap.comm_ring (R : Type u) (S : Type v) (A : Type w)
[comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] :
comm_ring (comap R S A) := _inst_8
instance comap.module : module S (comap R S A) := show module S A, by apply_instance
instance comap.has_scalar : has_scalar S (comap R S A) := show has_scalar S A, by apply_instance
set_option class.instance_max_depth 40
/-- R ⟶ S induces S-Alg ⥤ R-Alg -/
instance comap.algebra : algebra R (comap R S A) :=
{ smul := λ r x, (algebra_map S r • x : A),
to_fun := (algebra_map A : S → A) ∘ algebra_map S,
hom := @is_ring_hom.comp _ _ _ _ _ _ _ _ _ _inst_5.hom,
commutes' := λ r x, algebra.commutes _ _,
smul_def' := λ _ _, algebra.smul_def _ _ }
def to_comap : S →ₐ[R] comap R S A :=
{ commutes' := λ r, rfl,
..ring_hom.of (algebra_map A : S → A) }
theorem to_comap_apply (x) : to_comap R S A x = (algebra_map A : S → A) x := rfl
end algebra
namespace alg_hom
variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁}
variables [comm_ring R] [comm_ring S] [ring A] [ring B]
variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B)
include R
/-- R ⟶ S induces S-Alg ⥤ R-Alg -/
def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B :=
{ commutes' := λ r, φ.commutes (algebra_map S r)
..φ }
end alg_hom
namespace rat
instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α :=
{ smul := λ r x, (r : α) * x,
to_fun := coe,
hom := (rat.cast_hom α).is_ring_hom,
commutes' := λ r x, (commute.cast_int_right x r.1).div_right (commute.cast_nat_right x r.2),
smul_def' := λ _ _, rfl }
end rat
namespace complex
instance algebra_over_reals : algebra ℝ ℂ :=
algebra.of_ring_hom coe $ by constructor; intros; simp [one_re]
instance : has_scalar ℝ ℂ := { smul := λ r c, ↑r * c}
end complex
structure subalgebra (R : Type u) (A : Type v)
[comm_ring R] [ring A] [algebra R A] : Type v :=
(carrier : set A) [subring : is_subring carrier]
(range_le' : set.range (algebra_map A : R → A) ≤ carrier)
namespace subalgebra
variables {R : Type u} {A : Type v}
variables [comm_ring R] [ring A] [algebra R A]
include R
instance : has_coe (subalgebra R A) (set A) :=
⟨λ S, S.carrier⟩
lemma range_le (S : subalgebra R A) : set.range (algebra_map A : R → A) ≤ S := S.range_le'
instance : has_mem A (subalgebra R A) :=
⟨λ x S, x ∈ (S : set A)⟩
variables {A}
theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s :=
iff.rfl
@[ext] theorem ext {S T : subalgebra R A}
(h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T :=
by cases S; cases T; congr; ext x; exact h x
theorem ext_iff {S T : subalgebra R A} : S = T ↔ ∀ x : A, x ∈ S ↔ x ∈ T :=
⟨λ h x, by rw h, ext⟩
variables (S : subalgebra R A)
instance : is_subring (S : set A) := S.subring
instance : ring S := @@subtype.ring _ S.is_subring
instance : inhabited S := ⟨0⟩
instance (R : Type u) (A : Type v) {rR : comm_ring R} [comm_ring A]
{aA : algebra R A} (S : subalgebra R A) : comm_ring S := @@subtype.comm_ring _ S.is_subring
instance algebra : algebra R S :=
{ smul := λ (c:R) x, ⟨c • x.1,
by rw algebra.smul_def; exact @@is_submonoid.mul_mem _ S.2.2 (S.3 ⟨c, rfl⟩) x.2⟩,
to_fun := λ r, ⟨algebra_map A r, S.range_le ⟨r, rfl⟩⟩,
hom := ⟨subtype.eq $ algebra.map_one R A, λ x y, subtype.eq $ algebra.map_mul A x y,
λ x y, subtype.eq $ algebra.map_add A x y⟩,
commutes' := λ c x, subtype.eq $ by apply _inst_3.4,
smul_def' := λ c x, subtype.eq $ by apply _inst_3.5 }
instance to_algebra (R : Type u) (A : Type v) [comm_ring R] [comm_ring A]
[algebra R A] (S : subalgebra R A) : algebra S A :=
algebra.of_subring _
def val : S →ₐ[R] A :=
by refine_struct { to_fun := subtype.val }; intros; refl
def to_submodule : submodule R A :=
{ carrier := S,
zero := (0:S).2,
add := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2,
smul := λ c x hx, (algebra.smul_def c x).symm ▸ (⟨algebra_map A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 }
instance coe_to_submodule : has_coe (subalgebra R A) (submodule R A) :=
⟨to_submodule⟩
instance to_submodule.is_subring : is_subring ((S : submodule R A) : set A) := S.2
instance : partial_order (subalgebra R A) :=
{ le := λ S T, (S : set A) ≤ (T : set A),
le_refl := λ _, le_refl _,
le_trans := λ _ _ _, le_trans,
le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ }
def comap {R : Type u} {S : Type v} {A : Type w}
[comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A]
(iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) :=
{ carrier := (iSB : set A),
subring := iSB.is_subring,
range_le' := λ a ⟨r, hr⟩, hr ▸ iSB.range_le ⟨_, rfl⟩ }
def under {R : Type u} {A : Type v} [comm_ring R] [comm_ring A]
{i : algebra R A} (S : subalgebra R A)
(T : subalgebra S A) : subalgebra R A :=
{ carrier := T,
range_le' := (λ a ⟨r, hr⟩, hr ▸ T.range_le ⟨⟨algebra_map A r, S.range_le ⟨r, rfl⟩⟩, rfl⟩) }
end subalgebra
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B]
variables (φ : A →ₐ[R] B)
protected def range : subalgebra R B :=
{ carrier := set.range φ,
subring :=
{ one_mem := ⟨1, φ.map_one⟩,
mul_mem := λ y₁ y₂ ⟨x₁, hx₁⟩ ⟨x₂, hx₂⟩, ⟨x₁ * x₂, hx₁ ▸ hx₂ ▸ φ.map_mul x₁ x₂⟩ },
range_le' := λ y ⟨r, hr⟩, ⟨algebra_map A r, hr ▸ φ.commutes r⟩ }
end alg_hom
namespace algebra
variables {R : Type u} (A : Type v)
variables [comm_ring R] [ring A] [algebra R A]
include R
variables (R)
instance id : algebra R R :=
algebra.of_ring_hom id $ by apply_instance
namespace id
@[simp] lemma map_eq_self (x : R) : algebra_map R x = x := rfl
@[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl
end id
def of_id : R →ₐ A :=
{ commutes' := λ _, rfl, .. ring_hom.of (algebra_map A) }
variables {R}
theorem of_id_apply (r) : of_id R A r = algebra_map A r := rfl
variables (R) {A}
def adjoin (s : set A) : subalgebra R A :=
{ carrier := ring.closure (set.range (algebra_map A : R → A) ∪ s),
range_le' := le_trans (set.subset_union_left _ _) ring.subset_closure }
variables {R}
protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe :=
λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) ring.subset_closure) H,
λ H, ring.closure_subset $ set.union_subset S.range_le H⟩
protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe :=
{ choice := λ s hs, adjoin R s,
gc := algebra.gc,
le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _,
choice_eq := λ _ _, rfl }
instance : complete_lattice (subalgebra R A) :=
galois_insertion.lift_complete_lattice algebra.gi
instance : inhabited (subalgebra R A) := ⟨⊥⟩
theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map A : R → A) :=
suffices (⊥ : subalgebra R A) = (of_id R A).range, by rw this; refl,
le_antisymm bot_le $ subalgebra.range_le _
theorem mem_top {x : A} : x ∈ (⊤ : subalgebra R A) :=
ring.mem_closure $ or.inr trivial
theorem eq_top_iff {S : subalgebra R A} :
S = ⊤ ↔ ∀ x : A, x ∈ S :=
⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩
def to_top : A →ₐ[R] (⊤ : subalgebra R A) :=
by refine_struct { to_fun := λ x, (⟨x, mem_top⟩ : (⊤ : subalgebra R A)) }; intros; refl
end algebra
section int
variables (R : Type*) [comm_ring R]
/-- CRing ⥤ ℤ-Alg -/
def alg_hom_int
{R : Type u} [comm_ring R] [algebra ℤ R]
{S : Type v} [comm_ring S] [algebra ℤ S]
(f : R → S) [is_ring_hom f] : R →ₐ[ℤ] S :=
{ commutes' := λ i, by change (ring_hom.of f).to_fun with f; exact
int.induction_on i (by rw [algebra.map_zero, algebra.map_zero, is_ring_hom.map_zero f])
(λ i ih, by rw [algebra.map_add, algebra.map_add, algebra.map_one, algebra.map_one];
rw [is_ring_hom.map_add f, is_ring_hom.map_one f, ih])
(λ i ih, by rw [algebra.map_sub, algebra.map_sub, algebra.map_one, algebra.map_one];
rw [is_ring_hom.map_sub f, is_ring_hom.map_one f, ih]),
..ring_hom.of f }
/-- CRing ⥤ ℤ-Alg -/
instance algebra_int : algebra ℤ R :=
{ to_fun := int.cast_ring_hom R,
commutes' := λ _ _, mul_comm _ _,
smul_def' := λ _ _, gsmul_eq_mul _ _ }
variables {R}
/-- CRing ⥤ ℤ-Alg -/
def subalgebra_of_subring (S : set R) [is_subring S] : subalgebra ℤ R :=
{ carrier := S, range_le' := λ x ⟨i, h⟩, h ▸ int.induction_on i
(by rw algebra.map_zero; exact is_add_submonoid.zero_mem _)
(λ i hi, by rw [algebra.map_add, algebra.map_one]; exact is_add_submonoid.add_mem hi (is_submonoid.one_mem _))
(λ i hi, by rw [algebra.map_sub, algebra.map_one]; exact is_add_subgroup.sub_mem _ _ _ hi (is_submonoid.one_mem _)) }
@[simp] lemma mem_subalgebra_of_subring {x : R} {S : set R} [is_subring S] :
x ∈ subalgebra_of_subring S ↔ x ∈ S :=
iff.rfl
section span_int
open submodule
lemma span_int_eq_add_group_closure (s : set R) :
↑(span ℤ s) = add_group.closure s :=
set.subset.antisymm (λ x hx, span_induction hx
(λ _, add_group.mem_closure)
(is_add_submonoid.zero_mem _)
(λ a b ha hb, is_add_submonoid.add_mem ha hb)
(λ n a ha, by { exact is_add_subgroup.gsmul_mem ha }))
(add_group.closure_subset subset_span)
@[simp] lemma span_int_eq (s : set R) [is_add_subgroup s] :
(↑(span ℤ s) : set R) = s :=
by rw [span_int_eq_add_group_closure, add_group.closure_add_subgroup]
end span_int
end int
section restrict_scalars
/- In this section, we describe restriction of scalars: if `S` is an algebra over `R`, then
`S`-modules are also `R`-modules. -/
variables (R : Type*) [comm_ring R] (S : Type*) [ring S] [algebra R S]
(E : Type*) [add_comm_group E] [module S E] {F : Type*} [add_comm_group F] [module S F]
/-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a
module structure over `R`, called `module.restrict S R E`.
Not registered as an instance as `S` can not be inferred. -/
def module.restrict_scalars : module R E :=
{ smul := λc x, (algebra_map S c) • x,
one_smul := by simp,
mul_smul := by simp [mul_smul],
smul_add := by simp [smul_add],
smul_zero := by simp [smul_zero],
add_smul := by simp [add_smul],
zero_smul := by simp [zero_smul] }
variables {S E}
local attribute [instance] module.restrict_scalars
/-- The `R`-linear map induced by an `S`-linear map when `S` is an algebra over `R`. -/
def linear_map.restrict_scalars (f : E →ₗ[S] F) : E →ₗ[R] F :=
{ to_fun := f.to_fun,
add := λx y, f.map_add x y,
smul := λc x, f.map_smul (algebra_map S c) x }
@[simp, squash_cast] lemma linear_map.coe_restrict_scalars_eq_coe (f : E →ₗ[S] F) :
(f.restrict_scalars R : E → F) = f := rfl
/- Register as an instance (with low priority) the fact that a complex vector space is also a real
vector space. -/
instance module.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] : module ℝ E :=
module.restrict_scalars ℝ ℂ E
attribute [instance, priority 900] module.complex_to_real
end restrict_scalars
|
0321af5f1ea5a32f21ae1135015968ae892663fd | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/tactic/solve_by_elim.lean | 399a6e67ee550f20e056c9ffc44e59efce920567 | [
"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 | 12,153 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Scott Morrison
-/
import tactic.core
/-!
# solve_by_elim
A depth-first search backwards reasoner.
`solve_by_elim` takes a list of lemmas, and repeating tries to `apply` these against
the goals, recursively acting on any generated subgoals.
It accepts a variety of configuration options described below, enabling
* backtracking across multiple goals,
* pruning the search tree, and
* invoking other tactics before or after trying to apply lemmas.
At present it has no "premise selection", and simply tries the supplied lemmas in order
at each step of the search.
-/
namespace tactic
namespace solve_by_elim
/--
`mk_assumption_set` builds a collection of lemmas for use in the backtracking search in `solve_by_elim`.
* By default, it includes all local hypotheses, along with `rfl`, `trivial`, `congr_fun` and
`congr_arg`.
* The flag `no_dflt` removes these.
* The argument `hs` is a list of `simp_arg_type`s,
and can be used to add, or remove, lemmas or expressions from the set.
* The argument `attr : list name` adds all lemmas tagged with one of a specified list of attributes.
`mk_assumption_set` returns not a `list expr`, but a `list (tactic expr)`.
The problem here is that we may generate lemmas that have as yet unspecified implicit arguments,
and these implicit arguments would be filled in by metavariables if we created the actual `expr`
objects now.
As an example, we have `def rfl : ∀ {α : Sort u} {a : α}, a = a`, which on elaboration will become
`@rfl ?m_1 ?m_2`.
Because `solve_by_elim` works by repeated application of lemmas against subgoals,
the first time such a lemma is successfully applied,
those metavariables will be unified, and thereafter have fixed values.
This would make it impossible to apply the lemma
a second time with different values of the metavariables.
See https://github.com/leanprover-community/mathlib/issues/2269
As an optimisation, after we build the list of `tactic expr`s, we actually run them, and replace any
that do not in fact produce metavariables with a simple `return` tactic.
-/
meta def mk_assumption_set (no_dflt : bool) (hs : list simp_arg_type) (attr : list name) :
tactic (list (tactic expr)) :=
-- We lock the tactic state so that any spurious goals generated during
-- elaboration of pre-expressions are discarded
lock_tactic_state $
do
-- `hs` are expressions specified explicitly,
-- `hex` are exceptions (specified via `solve_by_elim [-h]`) referring to local hypotheses,
-- `gex` are the other exceptions
(hs, gex, hex, all_hyps) ← decode_simp_arg_list hs,
-- Recall, per the discussion above, we produce `tactic expr` thunks rather than actual `expr`s.
-- Note that while we evaluate these thunks on two occasions below while preparing the list,
-- this is a one-time cost during `mk_assumption_set`, rather than a cost proportional to the
-- length of the search `solve_by_elim` executes.
let hs := hs.map (λ h, i_to_expr_for_apply h),
l ← attr.mmap $ λ a, attribute.get_instances a,
let l := l.join,
let m := l.map (λ h, mk_const h),
-- In order to remove the expressions we need to evaluate the thunks.
hs ← (hs ++ m).mfilter $ λ h, (do h ← h, return $ expr.const_name h ∉ gex),
let hs := if no_dflt then hs else
([`rfl, `trivial, `congr_fun, `congr_arg].map (λ n, (mk_const n))) ++ hs,
hs ← if ¬ no_dflt ∨ all_hyps then do
ctx ← local_context,
-- Remove local exceptions specified in `hex`:
return $ hs.append ((ctx.filter (λ h : expr, h.local_uniq_name ∉ hex)).map return)
else return hs,
-- Finally, run all of the tactics: any that return an expression without metavariables can safely
-- be replaced by a `return` tactic.
hs.mmap (λ h, do e ← h, if e.has_meta_var then return h else return (return e))
/--
Configuration options for `solve_by_elim`.
* `accept : list expr → tactic unit` determines whether the current branch should be explored.
At each step, before the lemmas are applied,
`accept` is passed the proof terms for the original goals,
as reported by `get_goals` when `solve_by_elim` started.
These proof terms may be metavariables (if no progress has been made on that goal)
or may contain metavariables at some leaf nodes
(if the goal has been partially solved by previous `apply` steps).
If the `accept` tactic fails `solve_by_elim` aborts searching this branch and backtracks.
By default `accept := λ _, skip` always succeeds.
(There is an example usage in `tests/solve_by_elim.lean`.)
* `pre_apply : tactic unit` specifies an additional tactic to run before each round of `apply`.
* `discharger : tactic unit` specifies an additional tactic to apply on subgoals
for which no lemma applies.
If that tactic succeeds, `solve_by_elim` will continue applying lemmas on resulting goals.
-/
meta structure basic_opt extends apply_any_opt :=
(accept : list expr → tactic unit := λ _, skip)
(pre_apply : tactic unit := skip)
(discharger : tactic unit := failed)
/--
The internal implementation of `solve_by_elim`, with a limiting counter.
-/
meta def solve_by_elim_aux (opt : basic_opt)
(original_goals : list expr) (lemmas : list (tactic expr)) : ℕ → tactic unit
| n := do
-- First, check that progress so far is `accept`able.
lock_tactic_state (original_goals.mmap instantiate_mvars >>= opt.accept) >>
-- Then check if we've finished.
(done <|>
-- Otherwise, if there's more time left,
guard (n > 0) >>
-- run the `pre_apply` tactic, then
opt.pre_apply >>
-- try either applying a lemma and recursing, or
((apply_any_thunk lemmas opt.to_apply_any_opt $ solve_by_elim_aux (n-1)) <|>
-- if that doesn't work, run the discharger and recurse.
(opt.discharger >> solve_by_elim_aux (n-1))))
/--
Arguments for `solve_by_elim`:
* By default `solve_by_elim` operates only on the first goal,
but with `backtrack_all_goals := true`, it operates on all goals at once,
backtracking across goals as needed,
and only succeeds if it discharges all goals.
* `lemmas` specifies the list of lemmas to use in the backtracking search.
If `none`, `solve_by_elim` uses the local hypotheses,
along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`.
* `lemma_thunks` provides the lemmas as a list of `tactic expr`,
which are used to regenerate the `expr` objects to avoid binding metavariables.
(If both `lemmas` and `lemma_thunks` are specified, only `lemma_thunks` is used.)
* `max_depth` bounds the depth of the search.
-/
meta structure opt extends basic_opt :=
(backtrack_all_goals : bool := ff)
(lemmas : option (list expr) := none)
(lemma_thunks : option (list (tactic expr)) := lemmas.map (λ l, l.map return))
(max_depth : ℕ := 3)
/--
If no lemmas have been specified, generate the default set
(local hypotheses, along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`).
-/
meta def opt.get_lemma_thunks (opt : opt) : tactic (list (tactic expr)) :=
match opt.lemma_thunks with
| none := mk_assumption_set ff [] []
| some lemma_thunks := return lemma_thunks
end
end solve_by_elim
open solve_by_elim
/--
`solve_by_elim` repeatedly tries `apply`ing a lemma
from the list of assumptions (passed via the `opt` argument),
recursively operating on any generated subgoals.
It succeeds only if it discharges the first goal
(or with `backtrack_all_goals := tt`, if it discharges all goals.)
If passed an empty list of assumptions, `solve_by_elim` builds a default set
as per the interactive tactic, using the `local_context` along with
`rfl`, `trivial`, `congr_arg`, and `congr_fun`.
To pass a particular list of assumptions, use the `lemmas` field
in the configuration argument. This expects an `option (list (tactic expr))`.
We provide lemmas as `tactic expr` thunks to allow for regenerating metavariables
for each application.
-/
meta def solve_by_elim (opt : opt := { }) : tactic unit :=
do
tactic.fail_if_no_goals,
lemmas ← opt.get_lemma_thunks,
(if opt.backtrack_all_goals then id else focus1) $ (do
gs ← get_goals,
solve_by_elim_aux opt.to_basic_opt gs lemmas opt.max_depth)
open interactive lean.parser interactive.types
local postfix `?`:9001 := optional
namespace interactive
/--
`apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head`
where `head` matches the current goal.
If this fails, `apply_assumption` will call `symmetry` and try again.
If this also fails, `apply_assumption` will call `exfalso` and try again,
so that if there is an assumption of the form `P → ¬ Q`, the new tactic state
will have two goals, `P` and `Q`.
Optional arguments:
- `lemmas`: a list of expressions to apply, instead of the local constants
- `tac`: a tactic to run on each subgoal after applying an assumption; if
this tactic fails, the corresponding assumption will be rejected and
the next one will be attempted.
-/
meta def apply_assumption
(lemmas : option (list expr) := none)
(opt : apply_any_opt := {})
(tac : tactic unit := skip) : tactic unit :=
do
lemmas ← match lemmas with
| none := local_context
| some lemmas := return lemmas
end,
tactic.apply_any lemmas opt tac
add_tactic_doc
{ name := "apply_assumption",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply_assumption],
tags := ["context management", "lemma application"] }
/--
`solve_by_elim` calls `apply` on the main goal to find an assumption whose head matches
and then repeatedly calls `apply` on the generated subgoals until no subgoals remain,
performing at most `max_depth` recursive steps.
`solve_by_elim` discharges the current goal or fails.
`solve_by_elim` performs back-tracking if subgoals can not be solved.
By default, the assumptions passed to `apply` are the local context, `rfl`, `trivial`,
`congr_fun` and `congr_arg`.
The assumptions can be modified with similar syntax as for `simp`:
* `solve_by_elim [h₁, h₂, ..., hᵣ]` also applies the named lemmas.
* `solve_by_elim with attr₁ ... attrᵣ` also applies all lemmas tagged with the specified attributes.
* `solve_by_elim only [h₁, h₂, ..., hᵣ]` does not include the local context,
`rfl`, `trivial`, `congr_fun`, or `congr_arg` unless they are explicitly included.
* `solve_by_elim [-id_1, ... -id_n]` uses the default assumptions, removing the specified ones.
`solve_by_elim*` tries to solve all goals together, using backtracking if a solution for one goal
makes other goals impossible.
optional arguments passed via a configuration argument as `solve_by_elim { ... }`
- max_depth: number of attempts at discharging generated sub-goals
- discharger: a subsidiary tactic to try at each step when no lemmas apply (e.g. `cc` may be helpful).
- pre_apply: a subsidiary tactic to run at each step before applying lemmas (e.g. `intros`).
- accept: a subsidiary tactic `list expr → tactic unit` that at each step,
before any lemmas are applied, is passed the original proof terms
as reported by `get_goals` when `solve_by_elim` started
(but which may by now have been partially solved by previous `apply` steps).
If the `accept` tactic fails,
`solve_by_elim` will abort searching the current branch and backtrack.
This may be used to filter results, either at every step of the search,
or filtering complete results
(by testing for the absence of metavariables, and then the filtering condition).
-/
meta def solve_by_elim (all_goals : parse $ (tk "*")?) (no_dflt : parse only_flag)
(hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : solve_by_elim.opt := { }) :
tactic unit :=
do lemma_thunks ← mk_assumption_set no_dflt hs attr_names,
tactic.solve_by_elim
{ backtrack_all_goals := all_goals.is_some ∨ opt.backtrack_all_goals,
lemma_thunks := some lemma_thunks,
..opt }
add_tactic_doc
{ name := "solve_by_elim",
category := doc_category.tactic,
decl_names := [`tactic.interactive.solve_by_elim],
tags := ["search"] }
end interactive
end tactic
|
2b9fde8069664ee08a5bf37bac75dff705ef543f | 92b50235facfbc08dfe7f334827d47281471333b | /library/logic/eq.lean | d42f7f5d4ea7cb940b92b87f7a47c90ccbffb189 | [
"Apache-2.0"
] | permissive | htzh/lean | 24f6ed7510ab637379ec31af406d12584d31792c | d70c79f4e30aafecdfc4a60b5d3512199200ab6e | refs/heads/master | 1,607,677,731,270 | 1,437,089,952,000 | 1,437,089,952,000 | 37,078,816 | 0 | 0 | null | 1,433,780,956,000 | 1,433,780,955,000 | null | UTF-8 | Lean | false | false | 3,899 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn
Additional declarations/theorems about equality. See also init.datatypes and init.logic.
-/
open eq.ops
namespace eq
variables {A B : Type} {a a' a₁ a₂ a₃ a₄ : A}
theorem irrel (H₁ H₂ : a = a') : H₁ = H₂ :=
!proof_irrel
theorem id_refl (H₁ : a = a) : H₁ = (eq.refl a) :=
rfl
theorem rec_on_id {B : A → Type} (H : a = a) (b : B a) : eq.rec_on H b = b :=
rfl
theorem rec_on_constant (H : a = a') {B : Type} (b : B) : eq.rec_on H b = b :=
eq.drec_on H rfl
theorem rec_on_constant2 (H₁ : a₁ = a₂) (H₂ : a₃ = a₄) (b : B) : eq.rec_on H₁ b = eq.rec_on H₂ b :=
rec_on_constant H₁ b ⬝ (rec_on_constant H₂ b)⁻¹
theorem rec_on_irrel_arg {f : A → B} {D : B → Type} (H : a = a') (H' : f a = f a') (b : D (f a)) :
eq.rec_on H b = eq.rec_on H' b :=
eq.drec_on H (λ(H' : f a = f a), !rec_on_id⁻¹) H'
theorem rec_on_irrel {a a' : A} {D : A → Type} (H H' : a = a') (b : D a) :
eq.drec_on H b = eq.drec_on H' b :=
proof_irrel H H' ▸ rfl
theorem rec_on_compose {a b c : A} {P : A → Type} (H₁ : a = b) (H₂ : b = c)
(u : P a) : eq.rec_on H₂ (eq.rec_on H₁ u) = eq.rec_on (trans H₁ H₂) u :=
(show ∀ H₂ : b = c, eq.rec_on H₂ (eq.rec_on H₁ u) = eq.rec_on (trans H₁ H₂) u,
from eq.drec_on H₂ (take (H₂ : b = b), rec_on_id H₂ _))
H₂
end eq
open eq
section
variables {A B C D E F : Type}
variables {a a' : A} {b b' : B} {c c' : C} {d d' : D} {e e' : E}
theorem congr_arg2 (f : A → B → C) (Ha : a = a') (Hb : b = b') : f a b = f a' b' :=
by substvars
theorem congr_arg3 (f : A → B → C → D) (Ha : a = a') (Hb : b = b') (Hc : c = c')
: f a b c = f a' b' c' :=
by substvars
theorem congr_arg4 (f : A → B → C → D → E) (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d')
: f a b c d = f a' b' c' d' :=
by substvars
theorem congr_arg5 (f : A → B → C → D → E → F)
(Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') (He : e = e')
: f a b c d e = f a' b' c' d' e' :=
by substvars
theorem congr2 (f f' : A → B → C) (Hf : f = f') (Ha : a = a') (Hb : b = b') : f a b = f' a' b' :=
by substvars
theorem congr3 (f f' : A → B → C → D) (Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c')
: f a b c = f' a' b' c' :=
by substvars
theorem congr4 (f f' : A → B → C → D → E)
(Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d')
: f a b c d = f' a' b' c' d' :=
by substvars
theorem congr5 (f f' : A → B → C → D → E → F)
(Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') (He : e = e')
: f a b c d e = f' a' b' c' d' e' :=
by substvars
end
theorem equal_f {A : Type} {B : A → Type} {f g : Π x, B x} (H : f = g) : ∀x, f x = g x :=
take x, congr_fun H x
section
variables {a b c : Prop}
theorem eqmp (H₁ : a = b) (H₂ : a) : b :=
H₁ ▸ H₂
theorem eqmpr (H₁ : a = b) (H₂ : b) : a :=
H₁⁻¹ ▸ H₂
theorem imp_trans (H₁ : a → b) (H₂ : b → c) : a → c :=
assume Ha, H₂ (H₁ Ha)
theorem imp_eq_trans (H₁ : a → b) (H₂ : b = c) : a → c :=
assume Ha, H₂ ▸ (H₁ Ha)
theorem eq_imp_trans (H₁ : a = b) (H₂ : b → c) : a → c :=
assume Ha, H₂ (H₁ ▸ Ha)
end
section
variables {p : Prop}
theorem p_ne_false : p → p ≠ false :=
assume (Hp : p) (Heq : p = false), Heq ▸ Hp
theorem p_ne_true : ¬p → p ≠ true :=
assume (Hnp : ¬p) (Heq : p = true), absurd trivial (Heq ▸ Hnp)
end
theorem true_ne_false : ¬true = false :=
assume H : true = false,
H ▸ trivial
|
8af89a9bc3c491db2d2447a53cb8b576d6e83384 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/control/option_auto.lean | 1b8dfd273eb8fa30d92c26cad20b0d8efcf354cb | [] | 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,891 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.control.alternative
import Mathlib.Lean3Lib.init.control.lift
import Mathlib.Lean3Lib.init.control.except
universes u v l u_1 u_2
namespace Mathlib
structure option_t (m : Type u → Type v) (α : Type u) where
run : m (Option α)
namespace option_t
protected def bind_cont {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u}
(f : α → option_t m β) : Option α → m (Option β) :=
sorry
protected def bind {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} (ma : option_t m α)
(f : α → option_t m β) : option_t m β :=
mk (run ma >>= option_t.bind_cont f)
protected def pure {m : Type u → Type v} [Monad m] {α : Type u} (a : α) : option_t m α :=
mk (pure (some a))
protected instance monad {m : Type u → Type v} [Monad m] : Monad (option_t m) := sorry
protected def orelse {m : Type u → Type v} [Monad m] {α : Type u} (ma : option_t m α)
(mb : option_t m α) : option_t m α :=
mk
do
run ma
sorry
protected def fail {m : Type u → Type v} [Monad m] {α : Type u} : option_t m α := mk (pure none)
def of_option {m : Type u → Type v} [Monad m] {α : Type u} : Option α → option_t m α := sorry
protected instance alternative {m : Type u → Type v} [Monad m] : alternative (option_t m) :=
alternative.mk option_t.fail
protected def lift {m : Type u → Type v} [Monad m] {α : Type u} (ma : m α) : option_t m α :=
mk (some <$> ma)
protected instance has_monad_lift {m : Type u → Type v} [Monad m] : has_monad_lift m (option_t m) :=
has_monad_lift.mk option_t.lift
protected def monad_map {m : Type u → Type v} [Monad m] {m' : Type u → Type u_1} [Monad m']
{α : Type u} (f : {α : Type u} → m α → m' α) : option_t m α → option_t m' α :=
fun (x : option_t m α) => mk (f (run x))
protected instance monad_functor {m : Type u → Type v} [Monad m] (m' : Type u → Type v) [Monad m'] :
monad_functor m m' (option_t m) (option_t m') :=
monad_functor.mk fun (α : Type u) => option_t.monad_map
protected def catch {m : Type u → Type v} [Monad m] {α : Type u} (ma : option_t m α)
(handle : Unit → option_t m α) : option_t m α :=
mk
do
run ma
sorry
protected instance monad_except {m : Type u → Type v} [Monad m] : monad_except Unit (option_t m) :=
monad_except.mk (fun (_x : Type u) (_x_1 : Unit) => option_t.fail) option_t.catch
protected instance monad_run (m : Type u_1 → Type u_2) (out : outParam (Type u_1 → Type u_2))
[monad_run out m] : monad_run (fun (α : Type u_1) => out (Option α)) (option_t m) :=
monad_run.mk fun (α : Type u_1) => run ∘ run
end Mathlib |
45cf07dfb4fb81ab01d9389adf898377255531b5 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/set_theory/ordinal_arithmetic.lean | fc19de9ebab8747efc929ed9a2a366da9985172f | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 69,933 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import set_theory.ordinal
/-!
# Ordinal arithmetic
Ordinals have an addition (corresponding to disjoint union) that turns them into an additive
monoid, and a multiplication (corresponding to the lexicographic order on the product) that turns
them into a monoid. One can also define correspondingly a subtraction, a division, a successor
function, a power function and a logarithm function.
We also define limit ordinals and prove the basic induction principle on ordinals separating
successor ordinals and limit ordinals, in `limit_rec_on`.
## Main definitions and results
* `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that
every element of `o₁` is smaller than every element of `o₂`.
* `o₁ - o₂` is the unique ordinal `o` such that `o₂ + o = o₁`, when `o₂ ≤ o₁`.
* `o₁ * o₂` is the lexicographic order on `o₂ × o₁`.
* `o₁ / o₂` is the ordinal `o` such that `o₁ = o₂ * o + o'` with `o' < o₂`. We also define the
divisibility predicate, and a modulo operation.
* `succ o = o + 1` is the successor of `o`.
* `pred o` if the predecessor of `o`. If `o` is not a successor, we set `pred o = o`.
We also define the power function and the logarithm function on ordinals, and discuss the properties
of casts of natural numbers of and of `omega` with respect to these operations.
Some properties of the operations are also used to discuss general tools on ordinals:
* `is_limit o`: an ordinal is a limit ordinal if it is neither `0` nor a successor.
* `limit_rec_on` is the main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals.
* `is_normal`: a function `f : ordinal → ordinal` satisfies `is_normal` if it is strictly increasing
and order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`.
* `nfp f a`: the next fixed point of a function `f` on ordinals, above `a`. It behaves well
for normal functions.
* `CNF b o` is the Cantor normal form of the ordinal `o` in base `b`.
* `sup`: the supremum of an indexed family of ordinals in `Type u`, as an ordinal in `Type u`.
* `bsup`: the supremum of a set of ordinals indexed by ordinals less than a given ordinal `o`.
-/
noncomputable theory
open function cardinal set equiv
open_locale classical cardinal
universes u v w
variables {α : Type*} {β : Type*} {γ : Type*}
{r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
namespace ordinal
/-! ### Further properties of addition on ordinals -/
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans
(rel_iso.sum_lex_congr (rel_iso.preimage equiv.ulift _)
(rel_iso.preimage equiv.ulift _)).symm⟩
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
by unfold succ; simp only [lift_add, lift_one]
theorem add_le_add_iff_left (a) {b c : ordinal} : a + b ≤ a + c ↔ b ≤ c :=
⟨induction_on a $ λ α r hr, induction_on b $ λ β₁ s₁ hs₁, induction_on c $ λ β₂ s₂ hs₂ ⟨f⟩, ⟨
have fl : ∀ a, f (sum.inl a) = sum.inl a := λ a,
by simpa only [initial_seg.trans_apply, initial_seg.le_add_apply]
using @initial_seg.eq _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr hs₂)
((initial_seg.le_add r s₁).trans f) (initial_seg.le_add r s₂) a,
have ∀ b, {b' // f (sum.inr b) = sum.inr b'}, begin
intro b, cases e : f (sum.inr b),
{ rw ← fl at e, have := f.inj' e, contradiction },
{ exact ⟨_, rfl⟩ }
end,
let g (b) := (this b).1 in
have fr : ∀ b, f (sum.inr b) = sum.inr (g b), from λ b, (this b).2,
⟨⟨⟨g, λ x y h, by injection f.inj'
(by rw [fr, fr, h] : f (sum.inr x) = f (sum.inr y))⟩,
λ a b, by simpa only [sum.lex_inr_inr, fr, rel_embedding.coe_fn_to_embedding,
initial_seg.coe_fn_to_rel_embedding, function.embedding.coe_fn_mk]
using @rel_embedding.map_rel_iff _ _ _ _ f.to_rel_embedding (sum.inr a) (sum.inr b)⟩,
λ a b H, begin
rcases f.init' (by rw fr; exact sum.lex_inr_inr.2 H) with ⟨a'|a', h⟩,
{ rw fl at h, cases h },
{ rw fr at h, exact ⟨a', sum.inr.inj h⟩ }
end⟩⟩,
λ h, add_le_add_left h _⟩
theorem add_succ (o₁ o₂ : ordinal) : o₁ + succ o₂ = succ (o₁ + o₂) :=
(add_assoc _ _ _).symm
@[simp] theorem succ_zero : succ 0 = 1 := zero_add _
theorem one_le_iff_pos {o : ordinal} : 1 ≤ o ↔ 0 < o :=
by rw [← succ_zero, succ_le]
theorem one_le_iff_ne_zero {o : ordinal} : 1 ≤ o ↔ o ≠ 0 :=
by rw [one_le_iff_pos, pos_iff_ne_zero]
theorem succ_pos (o : ordinal) : 0 < succ o :=
lt_of_le_of_lt (zero_le _) (lt_succ_self _)
theorem succ_ne_zero (o : ordinal) : succ o ≠ 0 :=
ne_of_gt $ succ_pos o
@[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 :=
by simp only [succ, card_add, card_one]
theorem nat_cast_succ (n : ℕ) : (succ n : ordinal) = n.succ := rfl
theorem add_left_cancel (a) {b c : ordinal} : a + b = a + c ↔ b = c :=
by simp only [le_antisymm_iff, add_le_add_iff_left]
theorem lt_succ {a b : ordinal} : a < succ b ↔ a ≤ b :=
by rw [← not_le, succ_le, not_lt]
theorem add_lt_add_iff_left (a) {b c : ordinal} : a + b < a + c ↔ b < c :=
by rw [← not_le, ← not_le, add_le_add_iff_left]
theorem lt_of_add_lt_add_right {a b c : ordinal} : a + b < c + b → a < c :=
lt_imp_lt_of_le_imp_le (λ h, add_le_add_right h _)
@[simp] theorem succ_lt_succ {a b : ordinal} : succ a < succ b ↔ a < b :=
by rw [lt_succ, succ_le]
@[simp] theorem succ_le_succ {a b : ordinal} : succ a ≤ succ b ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 succ_lt_succ
theorem succ_inj {a b : ordinal} : succ a = succ b ↔ a = b :=
by simp only [le_antisymm_iff, succ_le_succ]
theorem add_le_add_iff_right {a b : ordinal} (n : ℕ) : a + n ≤ b + n ↔ a ≤ b :=
by induction n with n ih; [rw [nat.cast_zero, add_zero, add_zero],
rw [← nat_cast_succ, add_succ, add_succ, succ_le_succ, ih]]
theorem add_right_cancel {a b : ordinal} (n : ℕ) : a + n = b + n ↔ a = b :=
by simp only [le_antisymm_iff, add_le_add_iff_right]
/-! ### The zero ordinal -/
@[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 :=
⟨induction_on o $ λ α r _ h, begin
refine le_antisymm (le_of_not_lt $
λ hn, ne_zero_iff_nonempty.2 _ h) (zero_le _),
rw [← succ_le, succ_zero] at hn, cases hn with f,
exact ⟨f punit.star⟩
end, λ e, by simp only [e, card_zero]⟩
theorem type_ne_zero_iff_nonempty [is_well_order α r] : type r ≠ 0 ↔ nonempty α :=
(not_congr (@card_eq_zero (type r))).symm.trans ne_zero_iff_nonempty
@[simp] theorem type_eq_zero_iff_empty [is_well_order α r] : type r = 0 ↔ ¬ nonempty α :=
(not_iff_comm.1 type_ne_zero_iff_nonempty).symm
protected lemma one_ne_zero : (1 : ordinal) ≠ 0 :=
type_ne_zero_iff_nonempty.2 ⟨punit.star⟩
instance : nontrivial ordinal.{u} :=
⟨⟨1, 0, ordinal.one_ne_zero⟩⟩
theorem zero_lt_one : (0 : ordinal) < 1 :=
lt_iff_le_and_ne.2 ⟨zero_le _, ne.symm $ ordinal.one_ne_zero⟩
/-! ### The predecessor of an ordinal -/
/-- The ordinal predecessor of `o` is `o'` if `o = succ o'`,
and `o` otherwise. -/
def pred (o : ordinal.{u}) : ordinal.{u} :=
if h : ∃ a, o = succ a then classical.some h else o
@[simp] theorem pred_succ (o) : pred (succ o) = o :=
by have h : ∃ a, succ o = succ a := ⟨_, rfl⟩;
simpa only [pred, dif_pos h] using (succ_inj.1 $ classical.some_spec h).symm
theorem pred_le_self (o) : pred o ≤ o :=
if h : ∃ a, o = succ a then let ⟨a, e⟩ := h in
by rw [e, pred_succ]; exact le_of_lt (lt_succ_self _)
else by rw [pred, dif_neg h]
theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬ ∃ a, o = succ a :=
⟨λ e ⟨a, e'⟩, by rw [e', pred_succ] at e; exact ne_of_lt (lt_succ_self _) e,
λ h, dif_neg h⟩
theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a :=
iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le])
(iff_not_comm.1 pred_eq_iff_not_succ).symm
theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a :=
⟨λ e, ⟨_, e.symm⟩, λ ⟨a, e⟩, by simp only [e, pred_succ]⟩
theorem succ_lt_of_not_succ {o} (h : ¬ ∃ a, o = succ a) {b} : succ b < o ↔ b < o :=
⟨lt_trans (lt_succ_self _), λ l,
lt_of_le_of_ne (succ_le.2 l) (λ e, h ⟨_, e.symm⟩)⟩
theorem lt_pred {a b} : a < pred b ↔ succ a < b :=
if h : ∃ a, b = succ a then let ⟨c, e⟩ := h in
by rw [e, pred_succ, succ_lt_succ]
else by simp only [pred, dif_neg h, succ_lt_of_not_succ h]
theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b :=
le_iff_le_iff_lt_iff_lt.2 lt_pred
@[simp] theorem lift_is_succ {o} : (∃ a, lift o = succ a) ↔ (∃ a, o = succ a) :=
⟨λ ⟨a, h⟩,
let ⟨b, e⟩ := lift_down $ show a ≤ lift o, from le_of_lt $
h.symm ▸ lt_succ_self _ in
⟨b, lift_inj.1 $ by rw [h, ← e, lift_succ]⟩,
λ ⟨a, h⟩, ⟨lift a, by simp only [h, lift_succ]⟩⟩
@[simp] theorem lift_pred (o) : lift (pred o) = pred (lift o) :=
if h : ∃ a, o = succ a then
by cases h with a e; simp only [e, pred_succ, lift_succ]
else by rw [pred_eq_iff_not_succ.2 h,
pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)]
/-! ### Limit ordinals -/
/-- A limit ordinal is an ordinal which is not zero and not a successor. -/
def is_limit (o : ordinal) : Prop := o ≠ 0 ∧ ∀ a < o, succ a < o
theorem not_zero_is_limit : ¬ is_limit 0
| ⟨h, _⟩ := h rfl
theorem not_succ_is_limit (o) : ¬ is_limit (succ o)
| ⟨_, h⟩ := lt_irrefl _ (h _ (lt_succ_self _))
theorem not_succ_of_is_limit {o} (h : is_limit o) : ¬ ∃ a, o = succ a
| ⟨a, e⟩ := not_succ_is_limit a (e ▸ h)
theorem succ_lt_of_is_limit {o} (h : is_limit o) {a} : succ a < o ↔ a < o :=
⟨lt_trans (lt_succ_self _), h.2 _⟩
theorem le_succ_of_is_limit {o} (h : is_limit o) {a} : o ≤ succ a ↔ o ≤ a :=
le_iff_le_iff_lt_iff_lt.2 $ succ_lt_of_is_limit h
theorem limit_le {o} (h : is_limit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a :=
⟨λ h x l, le_trans (le_of_lt l) h,
λ H, (le_succ_of_is_limit h).1 $ le_of_not_lt $ λ hn,
not_lt_of_le (H _ hn) (lt_succ_self _)⟩
theorem lt_limit {o} (h : is_limit o) {a} : a < o ↔ ∃ x < o, a < x :=
by simpa only [not_ball, not_le] using not_congr (@limit_le _ h a)
@[simp] theorem lift_is_limit (o) : is_limit (lift o) ↔ is_limit o :=
and_congr (not_congr $ by simpa only [lift_zero] using @lift_inj o 0)
⟨λ H a h, lift_lt.1 $ by simpa only [lift_succ] using H _ (lift_lt.2 h),
λ H a h, let ⟨a', e⟩ := lift_down (le_of_lt h) in
by rw [← e, ← lift_succ, lift_lt];
rw [← e, lift_lt] at h; exact H a' h⟩
theorem is_limit.pos {o : ordinal} (h : is_limit o) : 0 < o :=
lt_of_le_of_ne (zero_le _) h.1.symm
theorem is_limit.one_lt {o : ordinal} (h : is_limit o) : 1 < o :=
by simpa only [succ_zero] using h.2 _ h.pos
theorem is_limit.nat_lt {o : ordinal} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o
| 0 := h.pos
| (n+1) := h.2 _ (is_limit.nat_lt n)
theorem zero_or_succ_or_limit (o : ordinal) :
o = 0 ∨ (∃ a, o = succ a) ∨ is_limit o :=
if o0 : o = 0 then or.inl o0 else
if h : ∃ a, o = succ a then or.inr (or.inl h) else
or.inr $ or.inr ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩
/-- Main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals. -/
@[elab_as_eliminator] def limit_rec_on {C : ordinal → Sort*}
(o : ordinal) (H₁ : C 0) (H₂ : ∀ o, C o → C (succ o))
(H₃ : ∀ o, is_limit o → (∀ o' < o, C o') → C o) : C o :=
wf.fix (λ o IH,
if o0 : o = 0 then by rw o0; exact H₁ else
if h : ∃ a, o = succ a then
by rw ← succ_pred_iff_is_succ.2 h; exact
H₂ _ (IH _ $ pred_lt_iff_is_succ.2 h)
else H₃ _ ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ IH) o
@[simp] theorem limit_rec_on_zero {C} (H₁ H₂ H₃) : @limit_rec_on C 0 H₁ H₂ H₃ = H₁ :=
by rw [limit_rec_on, well_founded.fix_eq, dif_pos rfl]; refl
@[simp] theorem limit_rec_on_succ {C} (o H₁ H₂ H₃) :
@limit_rec_on C (succ o) H₁ H₂ H₃ = H₂ o (@limit_rec_on C o H₁ H₂ H₃) :=
begin
have h : ∃ a, succ o = succ a := ⟨_, rfl⟩,
rw [limit_rec_on, well_founded.fix_eq,
dif_neg (succ_ne_zero o), dif_pos h],
generalize : limit_rec_on._proof_2 (succ o) h = h₂,
generalize : limit_rec_on._proof_3 (succ o) h = h₃,
revert h₂ h₃, generalize e : pred (succ o) = o', intros,
rw pred_succ at e, subst o', refl
end
@[simp] theorem limit_rec_on_limit {C} (o H₁ H₂ H₃ h) :
@limit_rec_on C o H₁ H₂ H₃ = H₃ o h (λ x h, @limit_rec_on C x H₁ H₂ H₃) :=
by rw [limit_rec_on, well_founded.fix_eq,
dif_neg h.1, dif_neg (not_succ_of_is_limit h)]; refl
lemma has_succ_of_is_limit {α} {r : α → α → Prop} [wo : is_well_order α r]
(h : (type r).is_limit) (x : α) : ∃y, r x y :=
begin
use enum r (typein r x).succ (h.2 _ (typein_lt_type r x)),
convert (enum_lt (typein_lt_type r x) _).mpr (lt_succ_self _), rw [enum_typein]
end
lemma type_subrel_lt (o : ordinal.{u}) :
type (subrel (<) {o' : ordinal | o' < o}) = ordinal.lift.{u u+1} o :=
begin
refine quotient.induction_on o _,
rintro ⟨α, r, wo⟩, resetI, apply quotient.sound,
constructor, symmetry, refine (rel_iso.preimage equiv.ulift r).trans (typein_iso r)
end
lemma mk_initial_seg (o : ordinal.{u}) :
#{o' : ordinal | o' < o} = cardinal.lift.{u u+1} o.card :=
by rw [lift_card, ←type_subrel_lt, card_type]
/-! ### Normal ordinal functions -/
/-- A normal ordinal function is a strictly increasing function which is
order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`. -/
def is_normal (f : ordinal → ordinal) : Prop :=
(∀ o, f o < f (succ o)) ∧ ∀ o, is_limit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a
theorem is_normal.limit_le {f} (H : is_normal f) : ∀ {o}, is_limit o →
∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a := H.2
theorem is_normal.limit_lt {f} (H : is_normal f) {o} (h : is_limit o) {a} :
a < f o ↔ ∃ b < o, a < f b :=
not_iff_not.1 $ by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a
theorem is_normal.lt_iff {f} (H : is_normal f) {a b} : f a < f b ↔ a < b :=
strict_mono.lt_iff_lt $ λ a b,
limit_rec_on b (not.elim (not_lt_of_le $ zero_le _))
(λ b IH h, (lt_or_eq_of_le (lt_succ.1 h)).elim
(λ h, lt_trans (IH h) (H.1 _))
(λ e, e ▸ H.1 _))
(λ b l IH h, lt_of_lt_of_le (H.1 a)
((H.2 _ l _).1 (le_refl _) _ (l.2 _ h)))
theorem is_normal.le_iff {f} (H : is_normal f) {a b} : f a ≤ f b ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 H.lt_iff
theorem is_normal.inj {f} (H : is_normal f) {a b} : f a = f b ↔ a = b :=
by simp only [le_antisymm_iff, H.le_iff]
theorem is_normal.le_self {f} (H : is_normal f) (a) : a ≤ f a :=
limit_rec_on a (zero_le _)
(λ a IH, succ_le.2 $ lt_of_le_of_lt IH (H.1 _))
(λ a l IH, (limit_le l).2 $ λ b h,
le_trans (IH b h) $ H.le_iff.2 $ le_of_lt h)
theorem is_normal.le_set {f} (H : is_normal f) (p : ordinal → Prop)
(p0 : ∃ x, p x) (S)
(H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → a ≤ o) {o} :
f S ≤ o ↔ ∀ a, p a → f a ≤ o :=
⟨λ h a pa, le_trans (H.le_iff.2 ((H₂ _).1 (le_refl _) _ pa)) h,
λ h, begin
revert H₂, apply limit_rec_on S,
{ intro H₂,
cases p0 with x px,
have := le_zero.1 ((H₂ _).1 (zero_le _) _ px),
rw this at px, exact h _ px },
{ intros S _ H₂,
rcases not_ball.1 (mt (H₂ S).2 $ not_le_of_lt $ lt_succ_self _) with ⟨a, h₁, h₂⟩,
exact le_trans (H.le_iff.2 $ succ_le.2 $ not_le.1 h₂) (h _ h₁) },
{ intros S L _ H₂, apply (H.2 _ L _).2, intros a h',
rcases not_ball.1 (mt (H₂ a).2 (not_le.2 h')) with ⟨b, h₁, h₂⟩,
exact le_trans (H.le_iff.2 $ le_of_lt $ not_le.1 h₂) (h _ h₁) }
end⟩
theorem is_normal.le_set' {f} (H : is_normal f) (p : α → Prop) (g : α → ordinal)
(p0 : ∃ x, p x) (S)
(H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → g a ≤ o) {o} :
f S ≤ o ↔ ∀ a, p a → f (g a) ≤ o :=
(H.le_set (λ x, ∃ y, p y ∧ x = g y)
(let ⟨x, px⟩ := p0 in ⟨_, _, px, rfl⟩) _
(λ o, (H₂ o).trans ⟨λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1,
λ H a h1, H (g a) ⟨a, h1, rfl⟩⟩)).trans
⟨λ H a h, H (g a) ⟨a, h, rfl⟩, λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1⟩
theorem is_normal.refl : is_normal id :=
⟨λ x, lt_succ_self _, λ o l a, limit_le l⟩
theorem is_normal.trans {f g} (H₁ : is_normal f) (H₂ : is_normal g) :
is_normal (λ x, f (g x)) :=
⟨λ x, H₁.lt_iff.2 (H₂.1 _),
λ o l a, H₁.le_set' (< o) g ⟨_, l.pos⟩ _ (λ c, H₂.2 _ l _)⟩
theorem is_normal.is_limit {f} (H : is_normal f) {o} (l : is_limit o) :
is_limit (f o) :=
⟨ne_of_gt $ lt_of_le_of_lt (zero_le _) $ H.lt_iff.2 l.pos,
λ a h, let ⟨b, h₁, h₂⟩ := (H.limit_lt l).1 h in
lt_of_le_of_lt (succ_le.2 h₂) (H.lt_iff.2 h₁)⟩
theorem add_le_of_limit {a b c : ordinal.{u}}
(h : is_limit b) : a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c :=
⟨λ h b' l, le_trans (add_le_add_left (le_of_lt l) _) h,
λ H, le_of_not_lt $
induction_on a (λ α r _, induction_on b $ λ β s _ h H l, begin
resetI,
suffices : ∀ x : β, sum.lex r s (sum.inr x) (enum _ _ l),
{ cases enum _ _ l with x x,
{ cases this (enum s 0 h.pos) },
{ exact irrefl _ (this _) } },
intros x,
rw [← typein_lt_typein (sum.lex r s), typein_enum],
have := H _ (h.2 _ (typein_lt_type s x)),
rw [add_succ, succ_le] at this,
refine lt_of_le_of_lt (type_le'.2
⟨rel_embedding.of_monotone (λ a, _) (λ a b, _)⟩) this,
{ rcases a with ⟨a | b, h⟩,
{ exact sum.inl a },
{ exact sum.inr ⟨b, by cases h; assumption⟩ } },
{ rcases a with ⟨a | a, h₁⟩; rcases b with ⟨b | b, h₂⟩; cases h₁; cases h₂;
rintro ⟨⟩; constructor; assumption }
end) h H⟩
theorem add_is_normal (a : ordinal) : is_normal ((+) a) :=
⟨λ b, (add_lt_add_iff_left a).2 (lt_succ_self _),
λ b l c, add_le_of_limit l⟩
theorem add_is_limit (a) {b} : is_limit b → is_limit (a + b) :=
(add_is_normal a).is_limit
/-! ### Subtraction on ordinals-/
/-- `a - b` is the unique ordinal satisfying
`b + (a - b) = a` when `b ≤ a`. -/
def sub (a b : ordinal.{u}) : ordinal.{u} :=
omin {o | a ≤ b+o} ⟨a, le_add_left _ _⟩
instance : has_sub ordinal := ⟨sub⟩
theorem le_add_sub (a b : ordinal) : a ≤ b + (a - b) :=
omin_mem {o | a ≤ b+o} _
theorem sub_le {a b c : ordinal} : a - b ≤ c ↔ a ≤ b + c :=
⟨λ h, le_trans (le_add_sub a b) (add_le_add_left h _),
λ h, omin_le h⟩
theorem lt_sub {a b c : ordinal} : a < b - c ↔ c + a < b :=
lt_iff_lt_of_le_iff_le sub_le
theorem add_sub_cancel (a b : ordinal) : a + b - a = b :=
le_antisymm (sub_le.2 $ le_refl _)
((add_le_add_iff_left a).1 $ le_add_sub _ _)
theorem sub_eq_of_add_eq {a b c : ordinal} (h : a + b = c) : c - a = b :=
h ▸ add_sub_cancel _ _
theorem sub_le_self (a b : ordinal) : a - b ≤ a :=
sub_le.2 $ le_add_left _ _
theorem add_sub_cancel_of_le {a b : ordinal} (h : b ≤ a) : b + (a - b) = a :=
le_antisymm begin
rcases zero_or_succ_or_limit (a-b) with e|⟨c,e⟩|l,
{ simp only [e, add_zero, h] },
{ rw [e, add_succ, succ_le, ← lt_sub, e], apply lt_succ_self },
{ exact (add_le_of_limit l).2 (λ c l, le_of_lt (lt_sub.1 l)) }
end (le_add_sub _ _)
@[simp] theorem sub_zero (a : ordinal) : a - 0 = a :=
by simpa only [zero_add] using add_sub_cancel 0 a
@[simp] theorem zero_sub (a : ordinal) : 0 - a = 0 :=
by rw ← le_zero; apply sub_le_self
@[simp] theorem sub_self (a : ordinal) : a - a = 0 :=
by simpa only [add_zero] using add_sub_cancel a 0
theorem sub_eq_zero_iff_le {a b : ordinal} : a - b = 0 ↔ a ≤ b :=
⟨λ h, by simpa only [h, add_zero] using le_add_sub a b,
λ h, by rwa [← le_zero, sub_le, add_zero]⟩
theorem sub_sub (a b c : ordinal) : a - b - c = a - (b + c) :=
eq_of_forall_ge_iff $ λ d, by rw [sub_le, sub_le, sub_le, add_assoc]
theorem add_sub_add_cancel (a b c : ordinal) : a + b - (a + c) = b - c :=
by rw [← sub_sub, add_sub_cancel]
theorem sub_is_limit {a b} (l : is_limit a) (h : b < a) : is_limit (a - b) :=
⟨ne_of_gt $ lt_sub.2 $ by rwa add_zero,
λ c h, by rw [lt_sub, add_succ]; exact l.2 _ (lt_sub.1 h)⟩
@[simp] theorem one_add_omega : 1 + omega.{u} = omega :=
begin
refine le_antisymm _ (le_add_left _ _),
rw [omega, one_eq_lift_type_unit, ← lift_add, lift_le, type_add],
have : is_well_order unit empty_relation := by apply_instance,
refine ⟨rel_embedding.collapse (rel_embedding.of_monotone _ _)⟩,
{ apply sum.rec, exact λ _, 0, exact nat.succ },
{ intros a b, cases a; cases b; intro H; cases H with _ _ H _ _ H;
[cases H, exact nat.succ_pos _, exact nat.succ_lt_succ H] }
end
@[simp, priority 990]
theorem one_add_of_omega_le {o} (h : omega ≤ o) : 1 + o = o :=
by rw [← add_sub_cancel_of_le h, ← add_assoc, one_add_omega]
/-! ### Multiplication of ordinals-/
/-- The multiplication of ordinals `o₁` and `o₂` is the (well founded) lexicographic order on
`o₂ × o₁`. -/
instance : monoid ordinal.{u} :=
{ mul := λ a b, quotient.lift_on₂ a b
(λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨β × α, prod.lex s r, by exactI prod.lex.is_well_order⟩⟧
: Well_order → Well_order → ordinal) $
λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩,
quot.sound ⟨rel_iso.prod_lex_congr g f⟩,
one := 1,
mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩,
eq.symm $ quotient.sound ⟨⟨prod_assoc _ _ _, λ a b, begin
rcases a with ⟨⟨a₁, a₂⟩, a₃⟩,
rcases b with ⟨⟨b₁, b₂⟩, b₃⟩,
simp [prod.lex_def, and_or_distrib_left, or_assoc, and_assoc]
end⟩⟩,
mul_one := λ a, induction_on a $ λ α r _, quotient.sound
⟨⟨punit_prod _, λ a b, by rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩;
simp only [prod.lex_def, empty_relation, false_or];
simp only [eq_self_iff_true, true_and]; refl⟩⟩,
one_mul := λ a, induction_on a $ λ α r _, quotient.sound
⟨⟨prod_punit _, λ a b, by rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩;
simp only [prod.lex_def, empty_relation, and_false, or_false]; refl⟩⟩ }
@[simp] theorem type_mul {α β : Type u} (r : α → α → Prop) (s : β → β → Prop)
[is_well_order α r] [is_well_order β s] : type r * type s = type (prod.lex s r) := rfl
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans
(rel_iso.prod_lex_congr (rel_iso.preimage equiv.ulift _)
(rel_iso.preimage equiv.ulift _)).symm⟩
@[simp] theorem card_mul (a b) : card (a * b) = card a * card b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
mul_comm (mk β) (mk α)
@[simp] theorem mul_zero (a : ordinal) : a * 0 = 0 :=
induction_on a $ λ α _ _, by exactI
type_eq_zero_iff_empty.2 (λ ⟨⟨e, _⟩⟩, e.elim)
@[simp] theorem zero_mul (a : ordinal) : 0 * a = 0 :=
induction_on a $ λ α _ _, by exactI
type_eq_zero_iff_empty.2 (λ ⟨⟨_, e⟩⟩, e.elim)
theorem mul_add (a b c : ordinal) : a * (b + c) = a * b + a * c :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩,
quotient.sound ⟨⟨sum_prod_distrib _ _ _, begin
rintro ⟨a₁|a₁, a₂⟩ ⟨b₁|b₁, b₂⟩; simp only [prod.lex_def,
sum.lex_inl_inl, sum.lex.sep, sum.lex_inr_inl, sum.lex_inr_inr,
sum_prod_distrib_apply_left, sum_prod_distrib_apply_right];
simp only [sum.inl.inj_iff, true_or, false_and, false_or]
end⟩⟩
@[simp] theorem mul_add_one (a b : ordinal) : a * (b + 1) = a * b + a :=
by simp only [mul_add, mul_one]
@[simp] theorem mul_succ (a b : ordinal) : a * succ b = a * b + a := mul_add_one _ _
theorem mul_le_mul_left {a b} (c : ordinal) : a ≤ b → c * a ≤ c * b :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin
resetI,
refine type_le'.2 ⟨rel_embedding.of_monotone
(λ a, (f a.1, a.2))
(λ a b h, _)⟩, clear_,
cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h',
{ exact prod.lex.left _ _ (f.to_rel_embedding.map_rel_iff.1 h') },
{ exact prod.lex.right _ h' }
end
theorem mul_le_mul_right {a b} (c : ordinal) : a ≤ b → a * c ≤ b * c :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin
resetI,
refine type_le'.2 ⟨rel_embedding.of_monotone
(λ a, (a.1, f a.2))
(λ a b h, _)⟩,
cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h',
{ exact prod.lex.left _ _ h' },
{ exact prod.lex.right _ (f.to_rel_embedding.map_rel_iff.1 h') }
end
theorem mul_le_mul {a b c d : ordinal} (h₁ : a ≤ c) (h₂ : b ≤ d) : a * b ≤ c * d :=
le_trans (mul_le_mul_left _ h₂) (mul_le_mul_right _ h₁)
private lemma mul_le_of_limit_aux {α β r s} [is_well_order α r] [is_well_order β s]
{c} (h : is_limit (type s)) (H : ∀ b' < type s, type r * b' ≤ c)
(l : c < type r * type s) : false :=
begin
suffices : ∀ a b, prod.lex s r (b, a) (enum _ _ l),
{ cases enum _ _ l with b a, exact irrefl _ (this _ _) },
intros a b,
rw [← typein_lt_typein (prod.lex s r), typein_enum],
have := H _ (h.2 _ (typein_lt_type s b)),
rw [mul_succ] at this,
have := lt_of_lt_of_le ((add_lt_add_iff_left _).2
(typein_lt_type _ a)) this,
refine lt_of_le_of_lt _ this,
refine (type_le'.2 _),
constructor,
refine rel_embedding.of_monotone (λ a, _) (λ a b, _),
{ rcases a with ⟨⟨b', a'⟩, h⟩,
by_cases e : b = b',
{ refine sum.inr ⟨a', _⟩,
subst e, cases h with _ _ _ _ h _ _ _ h,
{ exact (irrefl _ h).elim },
{ exact h } },
{ refine sum.inl (⟨b', _⟩, a'),
cases h with _ _ _ _ h _ _ _ h,
{ exact h }, { exact (e rfl).elim } } },
{ rcases a with ⟨⟨b₁, a₁⟩, h₁⟩,
rcases b with ⟨⟨b₂, a₂⟩, h₂⟩,
intro h, by_cases e₁ : b = b₁; by_cases e₂ : b = b₂,
{ substs b₁ b₂,
simpa only [subrel_val, prod.lex_def, @irrefl _ s _ b, true_and, false_or, eq_self_iff_true,
dif_pos, sum.lex_inr_inr] using h },
{ subst b₁,
simp only [subrel_val, prod.lex_def, e₂, prod.lex_def, dif_pos, subrel_val, eq_self_iff_true,
or_false, dif_neg, not_false_iff, sum.lex_inr_inl, false_and] at h ⊢,
cases h₂; [exact asymm h h₂_h, exact e₂ rfl] },
{ simp only [e₂, dif_pos, eq_self_iff_true, dif_neg e₁, not_false_iff, sum.lex.sep] },
{ simpa only [dif_neg e₁, dif_neg e₂, prod.lex_def, subrel_val, subtype.mk_eq_mk,
sum.lex_inl_inl] using h } }
end
theorem mul_le_of_limit {a b c : ordinal.{u}}
(h : is_limit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c :=
⟨λ h b' l, le_trans (mul_le_mul_left _ (le_of_lt l)) h,
λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _,
by exactI mul_le_of_limit_aux) h H⟩
theorem mul_is_normal {a : ordinal} (h : 0 < a) : is_normal ((*) a) :=
⟨λ b, by rw mul_succ; simpa only [add_zero] using (add_lt_add_iff_left (a*b)).2 h,
λ b l c, mul_le_of_limit l⟩
theorem lt_mul_of_limit {a b c : ordinal.{u}}
(h : is_limit c) : a < b * c ↔ ∃ c' < c, a < b * c' :=
by simpa only [not_ball, not_le] using not_congr (@mul_le_of_limit b c a h)
theorem mul_lt_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c :=
(mul_is_normal a0).lt_iff
theorem mul_le_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c :=
(mul_is_normal a0).le_iff
theorem mul_lt_mul_of_pos_left {a b c : ordinal}
(h : a < b) (c0 : 0 < c) : c * a < c * b :=
(mul_lt_mul_iff_left c0).2 h
theorem mul_pos {a b : ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b :=
by simpa only [mul_zero] using mul_lt_mul_of_pos_left h₂ h₁
theorem mul_ne_zero {a b : ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 :=
by simpa only [pos_iff_ne_zero] using mul_pos
theorem le_of_mul_le_mul_left {a b c : ordinal}
(h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b :=
le_imp_le_of_lt_imp_lt (λ h', mul_lt_mul_of_pos_left h' h0) h
theorem mul_right_inj {a b c : ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c :=
(mul_is_normal a0).inj
theorem mul_is_limit {a b : ordinal}
(a0 : 0 < a) : is_limit b → is_limit (a * b) :=
(mul_is_normal a0).is_limit
theorem mul_is_limit_left {a b : ordinal}
(l : is_limit a) (b0 : 0 < b) : is_limit (a * b) :=
begin
rcases zero_or_succ_or_limit b with rfl|⟨b,rfl⟩|lb,
{ exact (lt_irrefl _).elim b0 },
{ rw mul_succ, exact add_is_limit _ l },
{ exact mul_is_limit l.pos lb }
end
/-! ### Division on ordinals -/
protected lemma div_aux (a b : ordinal.{u}) (h : b ≠ 0) : set.nonempty {o | a < b * succ o} :=
⟨a, succ_le.1 $
by simpa only [succ_zero, one_mul]
using mul_le_mul_right (succ a) (succ_le.2 (pos_iff_ne_zero.2 h))⟩
/-- `a / b` is the unique ordinal `o` satisfying
`a = b * o + o'` with `o' < b`. -/
protected def div (a b : ordinal.{u}) : ordinal.{u} :=
if h : b = 0 then 0 else omin {o | a < b * succ o} (ordinal.div_aux a b h)
instance : has_div ordinal := ⟨ordinal.div⟩
@[simp] theorem div_zero (a : ordinal) : a / 0 = 0 := dif_pos rfl
lemma div_def (a) {b : ordinal} (h : b ≠ 0) :
a / b = omin {o | a < b * succ o} (ordinal.div_aux a b h) := dif_neg h
theorem lt_mul_succ_div (a) {b : ordinal} (h : b ≠ 0) : a < b * succ (a / b) :=
by rw div_def a h; exact omin_mem {o | a < b * succ o} _
theorem lt_mul_div_add (a) {b : ordinal} (h : b ≠ 0) : a < b * (a / b) + b :=
by simpa only [mul_succ] using lt_mul_succ_div a h
theorem div_le {a b c : ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c :=
⟨λ h, lt_of_lt_of_le (lt_mul_succ_div a b0) (mul_le_mul_left _ $ succ_le_succ.2 h),
λ h, by rw div_def a b0; exact omin_le h⟩
theorem lt_div {a b c : ordinal} (c0 : c ≠ 0) : a < b / c ↔ c * succ a ≤ b :=
by rw [← not_le, div_le c0, not_lt]
theorem le_div {a b c : ordinal} (c0 : c ≠ 0) :
a ≤ b / c ↔ c * a ≤ b :=
begin
apply limit_rec_on a,
{ simp only [mul_zero, zero_le] },
{ intros, rw [succ_le, lt_div c0] },
{ simp only [mul_le_of_limit, limit_le, iff_self, forall_true_iff] {contextual := tt} }
end
theorem div_lt {a b c : ordinal} (b0 : b ≠ 0) :
a / b < c ↔ a < b * c :=
lt_iff_lt_of_le_iff_le $ le_div b0
theorem div_le_of_le_mul {a b c : ordinal} (h : a ≤ b * c) : a / b ≤ c :=
if b0 : b = 0 then by simp only [b0, div_zero, zero_le] else
(div_le b0).2 $ lt_of_le_of_lt h $
mul_lt_mul_of_pos_left (lt_succ_self _) (pos_iff_ne_zero.2 b0)
theorem mul_lt_of_lt_div {a b c : ordinal} : a < b / c → c * a < b :=
lt_imp_lt_of_le_imp_le div_le_of_le_mul
@[simp] theorem zero_div (a : ordinal) : 0 / a = 0 :=
le_zero.1 $ div_le_of_le_mul $ zero_le _
theorem mul_div_le (a b : ordinal) : b * (a / b) ≤ a :=
if b0 : b = 0 then by simp only [b0, zero_mul, zero_le] else (le_div b0).1 (le_refl _)
theorem mul_add_div (a) {b : ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b :=
begin
apply le_antisymm,
{ apply (div_le b0).2,
rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left],
apply lt_mul_div_add _ b0 },
{ rw [le_div b0, mul_add, add_le_add_iff_left],
apply mul_div_le }
end
theorem div_eq_zero_of_lt {a b : ordinal} (h : a < b) : a / b = 0 :=
by rw [← le_zero, div_le $ pos_iff_ne_zero.1 $ lt_of_le_of_lt (zero_le _) h];
simpa only [succ_zero, mul_one] using h
@[simp] theorem mul_div_cancel (a) {b : ordinal} (b0 : b ≠ 0) : b * a / b = a :=
by simpa only [add_zero, zero_div] using mul_add_div a b0 0
@[simp] theorem div_one (a : ordinal) : a / 1 = a :=
by simpa only [one_mul] using mul_div_cancel a ordinal.one_ne_zero
@[simp] theorem div_self {a : ordinal} (h : a ≠ 0) : a / a = 1 :=
by simpa only [mul_one] using mul_div_cancel 1 h
theorem mul_sub (a b c : ordinal) : a * (b - c) = a * b - a * c :=
if a0 : a = 0 then by simp only [a0, zero_mul, sub_self] else
eq_of_forall_ge_iff $ λ d,
by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0]
theorem is_limit_add_iff {a b} : is_limit (a + b) ↔ is_limit b ∨ (b = 0 ∧ is_limit a) :=
begin
split; intro h,
{ by_cases h' : b = 0,
{ rw [h', add_zero] at h, right, exact ⟨h', h⟩ },
left, rw [←add_sub_cancel a b], apply sub_is_limit h,
suffices : a + 0 < a + b, simpa only [add_zero],
rwa [add_lt_add_iff_left, pos_iff_ne_zero] },
rcases h with h|⟨rfl, h⟩, exact add_is_limit a h, simpa only [add_zero]
end
theorem dvd_add_iff : ∀ {a b c : ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c)
| a _ c ⟨b, rfl⟩ :=
⟨λ ⟨d, e⟩, ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩,
λ ⟨d, e⟩, by { rw [e, ← mul_add], apply dvd_mul_right }⟩
theorem dvd_add {a b c : ordinal} (h₁ : a ∣ b) : a ∣ c → a ∣ b + c :=
(dvd_add_iff h₁).2
theorem dvd_zero (a : ordinal) : a ∣ 0 := ⟨_, (mul_zero _).symm⟩
theorem zero_dvd {a : ordinal} : 0 ∣ a ↔ a = 0 :=
⟨λ ⟨h, e⟩, by simp only [e, zero_mul], λ e, e.symm ▸ dvd_zero _⟩
theorem one_dvd (a : ordinal) : 1 ∣ a := ⟨a, (one_mul _).symm⟩
theorem div_mul_cancel : ∀ {a b : ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b
| a _ a0 ⟨b, rfl⟩ := by rw [mul_div_cancel _ a0]
theorem le_of_dvd : ∀ {a b : ordinal}, b ≠ 0 → a ∣ b → a ≤ b
| a _ b0 ⟨b, rfl⟩ := by simpa only [mul_one] using mul_le_mul_left a
(one_le_iff_ne_zero.2 (λ h : b = 0, by simpa only [h, mul_zero] using b0))
theorem dvd_antisymm {a b : ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b :=
if a0 : a = 0 then by subst a; exact (zero_dvd.1 h₁).symm else
if b0 : b = 0 then by subst b; exact zero_dvd.1 h₂ else
le_antisymm (le_of_dvd b0 h₁) (le_of_dvd a0 h₂)
/-- `a % b` is the unique ordinal `o'` satisfying
`a = b * o + o'` with `o' < b`. -/
instance : has_mod ordinal := ⟨λ a b, a - b * (a / b)⟩
theorem mod_def (a b : ordinal) : a % b = a - b * (a / b) := rfl
@[simp] theorem mod_zero (a : ordinal) : a % 0 = a :=
by simp only [mod_def, div_zero, zero_mul, sub_zero]
theorem mod_eq_of_lt {a b : ordinal} (h : a < b) : a % b = a :=
by simp only [mod_def, div_eq_zero_of_lt h, mul_zero, sub_zero]
@[simp] theorem zero_mod (b : ordinal) : 0 % b = 0 :=
by simp only [mod_def, zero_div, mul_zero, sub_self]
theorem div_add_mod (a b : ordinal) : b * (a / b) + a % b = a :=
add_sub_cancel_of_le $ mul_div_le _ _
theorem mod_lt (a) {b : ordinal} (h : b ≠ 0) : a % b < b :=
(add_lt_add_iff_left (b * (a / b))).1 $
by rw div_add_mod; exact lt_mul_div_add a h
@[simp] theorem mod_self (a : ordinal) : a % a = 0 :=
if a0 : a = 0 then by simp only [a0, zero_mod] else
by simp only [mod_def, div_self a0, mul_one, sub_self]
@[simp] theorem mod_one (a : ordinal) : a % 1 = 0 :=
by simp only [mod_def, div_one, one_mul, sub_self]
/-! ### Supremum of a family of ordinals -/
/-- The supremum of a family of ordinals -/
def sup {ι} (f : ι → ordinal) : ordinal :=
omin {c | ∀ i, f i ≤ c}
⟨(sup (cardinal.succ ∘ card ∘ f)).ord, λ i, le_of_lt $
cardinal.lt_ord.2 (lt_of_lt_of_le (cardinal.lt_succ_self _) (le_sup _ _))⟩
theorem le_sup {ι} (f : ι → ordinal) : ∀ i, f i ≤ sup f :=
omin_mem {c | ∀ i, f i ≤ c} _
theorem sup_le {ι} {f : ι → ordinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a :=
⟨λ h i, le_trans (le_sup _ _) h, λ h, omin_le h⟩
theorem lt_sup {ι} {f : ι → ordinal} {a} : a < sup f ↔ ∃ i, a < f i :=
by simpa only [not_forall, not_le] using not_congr (@sup_le _ f a)
theorem is_normal.sup {f} (H : is_normal f)
{ι} {g : ι → ordinal} (h : nonempty ι) : f (sup g) = sup (f ∘ g) :=
eq_of_forall_ge_iff $ λ a,
by rw [sup_le, comp, H.le_set' (λ_:ι, true) g (let ⟨i⟩ := h in ⟨i, ⟨⟩⟩)];
intros; simp only [sup_le, true_implies_iff]
theorem sup_ord {ι} (f : ι → cardinal) : sup (λ i, (f i).ord) = (cardinal.sup f).ord :=
eq_of_forall_ge_iff $ λ a, by simp only [sup_le, cardinal.ord_le, cardinal.sup_le]
lemma sup_succ {ι} (f : ι → ordinal) : sup (λ i, succ (f i)) ≤ succ (sup f) :=
by { rw [ordinal.sup_le], intro i, rw ordinal.succ_le_succ, apply ordinal.le_sup }
lemma unbounded_range_of_sup_ge {α β : Type u} (r : α → α → Prop) [is_well_order α r] (f : β → α)
(h : type r ≤ sup.{u u} (typein r ∘ f)) : unbounded r (range f) :=
begin
apply (not_bounded_iff _).mp, rintro ⟨x, hx⟩, apply not_lt_of_ge h,
refine lt_of_le_of_lt _ (typein_lt_type r x), rw [sup_le], intro y,
apply le_of_lt, rw typein_lt_typein, apply hx, apply mem_range_self
end
/-- The supremum of a family of ordinals indexed by the set
of ordinals less than some `o : ordinal.{u}`.
(This is not a special case of `sup` over the subtype,
because `{a // a < o} : Type (u+1)` and `sup` only works over
families in `Type u`.) -/
def bsup (o : ordinal.{u}) : (Π a < o, ordinal.{max u v}) → ordinal.{max u v} :=
match o, o.out, o.out_eq with
| _, ⟨α, r, _⟩, rfl, f := by exactI sup (λ a, f (typein r a) (typein_lt_type _ _))
end
theorem bsup_le {o f a} : bsup.{u v} o f ≤ a ↔ ∀ i h, f i h ≤ a :=
match o, o.out, o.out_eq, f :
∀ o w (e : ⟦w⟧ = o) (f : Π (a : ordinal.{u}), a < o → ordinal.{(max u v)}),
bsup._match_1 o w e f ≤ a ↔ ∀ i h, f i h ≤ a with
| _, ⟨α, r, _⟩, rfl, f := by rw [bsup._match_1, sup_le]; exactI
⟨λ H i h, by simpa only [typein_enum] using H (enum r i h), λ H b, H _ _⟩
end
theorem bsup_type (r : α → α → Prop) [is_well_order α r] (f) :
bsup (type r) f = sup (λ a, f (typein r a) (typein_lt_type _ _)) :=
eq_of_forall_ge_iff $ λ o,
by rw [bsup_le, sup_le]; exact
⟨λ H b, H _ _, λ H i h, by simpa only [typein_enum] using H (enum r i h)⟩
theorem le_bsup {o} (f : Π a < o, ordinal) (i h) : f i h ≤ bsup o f :=
bsup_le.1 (le_refl _) _ _
theorem lt_bsup {o : ordinal} {f : Π a < o, ordinal}
(hf : ∀{a a'} (ha : a < o) (ha' : a' < o), a < a' → f a ha < f a' ha')
(ho : o.is_limit) (i h) : f i h < bsup o f :=
lt_of_lt_of_le (hf _ _ $ lt_succ_self i) (le_bsup f i.succ $ ho.2 _ h)
theorem bsup_id {o} (ho : is_limit o) : bsup.{u u} o (λ x _, x) = o :=
begin
apply le_antisymm, rw [bsup_le], intro i, apply le_of_lt,
rw [←not_lt], intro h, apply lt_irrefl (bsup.{u u} o (λ x _, x)),
apply lt_of_le_of_lt _ (lt_bsup _ ho _ h), refl, intros, assumption
end
theorem is_normal.bsup {f} (H : is_normal f)
{o : ordinal} : ∀ (g : Π a < o, ordinal) (h : o ≠ 0),
f (bsup o g) = bsup o (λ a h, f (g a h)) :=
induction_on o $ λ α r _ g h,
by resetI; rw [bsup_type,
H.sup (type_ne_zero_iff_nonempty.1 h), bsup_type]
theorem is_normal.bsup_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) :
bsup.{u} o (λx _, f x) = f o :=
by { rw [←is_normal.bsup.{u u} H (λ x _, x) h.1, bsup_id h] }
/-! ### Ordinal exponential -/
/-- The ordinal exponential, defined by transfinite recursion. -/
def power (a b : ordinal) : ordinal :=
if a = 0 then 1 - b else
limit_rec_on b 1 (λ _ IH, IH * a) (λ b _, bsup.{u u} b)
instance : has_pow ordinal ordinal := ⟨power⟩
local infixr ^ := @pow ordinal ordinal ordinal.has_pow
theorem zero_power' (a : ordinal) : 0 ^ a = 1 - a :=
by simp only [pow, power, if_pos rfl]
@[simp] theorem zero_power {a : ordinal} (a0 : a ≠ 0) : 0 ^ a = 0 :=
by rwa [zero_power', sub_eq_zero_iff_le, one_le_iff_ne_zero]
@[simp] theorem power_zero (a : ordinal) : a ^ 0 = 1 :=
by by_cases a = 0; [simp only [pow, power, if_pos h, sub_zero],
simp only [pow, power, if_neg h, limit_rec_on_zero]]
@[simp] theorem power_succ (a b : ordinal) : a ^ succ b = a ^ b * a :=
if h : a = 0 then by subst a; simp only [zero_power (succ_ne_zero _), mul_zero]
else by simp only [pow, power, limit_rec_on_succ, if_neg h]
theorem power_limit {a b : ordinal} (a0 : a ≠ 0) (h : is_limit b) :
a ^ b = bsup.{u u} b (λ c _, a ^ c) :=
by simp only [pow, power, if_neg a0]; rw limit_rec_on_limit _ _ _ _ h; refl
theorem power_le_of_limit {a b c : ordinal} (a0 : a ≠ 0) (h : is_limit b) :
a ^ b ≤ c ↔ ∀ b' < b, a ^ b' ≤ c :=
by rw [power_limit a0 h, bsup_le]
theorem lt_power_of_limit {a b c : ordinal} (b0 : b ≠ 0) (h : is_limit c) :
a < b ^ c ↔ ∃ c' < c, a < b ^ c' :=
by rw [← not_iff_not, not_exists]; simp only [not_lt, power_le_of_limit b0 h, exists_prop, not_and]
@[simp] theorem power_one (a : ordinal) : a ^ 1 = a :=
by rw [← succ_zero, power_succ]; simp only [power_zero, one_mul]
@[simp] theorem one_power (a : ordinal) : 1 ^ a = 1 :=
begin
apply limit_rec_on a,
{ simp only [power_zero] },
{ intros _ ih, simp only [power_succ, ih, mul_one] },
refine λ b l IH, eq_of_forall_ge_iff (λ c, _),
rw [power_le_of_limit ordinal.one_ne_zero l],
exact ⟨λ H, by simpa only [power_zero] using H 0 l.pos,
λ H b' h, by rwa IH _ h⟩,
end
theorem power_pos {a : ordinal} (b)
(a0 : 0 < a) : 0 < a ^ b :=
begin
have h0 : 0 < a ^ 0, {simp only [power_zero, zero_lt_one]},
apply limit_rec_on b,
{ exact h0 },
{ intros b IH, rw [power_succ],
exact mul_pos IH a0 },
{ exact λ b l _, (lt_power_of_limit (pos_iff_ne_zero.1 a0) l).2
⟨0, l.pos, h0⟩ },
end
theorem power_ne_zero {a : ordinal} (b)
(a0 : a ≠ 0) : a ^ b ≠ 0 :=
pos_iff_ne_zero.1 $ power_pos b $ pos_iff_ne_zero.2 a0
theorem power_is_normal {a : ordinal} (h : 1 < a) : is_normal ((^) a) :=
have a0 : 0 < a, from lt_trans zero_lt_one h,
⟨λ b, by simpa only [mul_one, power_succ] using
(mul_lt_mul_iff_left (power_pos b a0)).2 h,
λ b l c, power_le_of_limit (ne_of_gt a0) l⟩
theorem power_lt_power_iff_right {a b c : ordinal}
(a1 : 1 < a) : a ^ b < a ^ c ↔ b < c :=
(power_is_normal a1).lt_iff
theorem power_le_power_iff_right {a b c : ordinal}
(a1 : 1 < a) : a ^ b ≤ a ^ c ↔ b ≤ c :=
(power_is_normal a1).le_iff
theorem power_right_inj {a b c : ordinal}
(a1 : 1 < a) : a ^ b = a ^ c ↔ b = c :=
(power_is_normal a1).inj
theorem power_is_limit {a b : ordinal}
(a1 : 1 < a) : is_limit b → is_limit (a ^ b) :=
(power_is_normal a1).is_limit
theorem power_is_limit_left {a b : ordinal}
(l : is_limit a) (hb : b ≠ 0) : is_limit (a ^ b) :=
begin
rcases zero_or_succ_or_limit b with e|⟨b,rfl⟩|l',
{ exact absurd e hb },
{ rw power_succ,
exact mul_is_limit (power_pos _ l.pos) l },
{ exact power_is_limit l.one_lt l' }
end
theorem power_le_power_right {a b c : ordinal}
(h₁ : 0 < a) (h₂ : b ≤ c) : a ^ b ≤ a ^ c :=
begin
cases lt_or_eq_of_le (one_le_iff_pos.2 h₁) with h₁ h₁,
{ exact (power_le_power_iff_right h₁).2 h₂ },
{ subst a, simp only [one_power] }
end
theorem power_le_power_left {a b : ordinal} (c)
(ab : a ≤ b) : a ^ c ≤ b ^ c :=
begin
by_cases a0 : a = 0,
{ subst a, by_cases c0 : c = 0,
{ subst c, simp only [power_zero] },
{ simp only [zero_power c0, zero_le] } },
{ apply limit_rec_on c,
{ simp only [power_zero] },
{ intros c IH, simpa only [power_succ] using mul_le_mul IH ab },
{ exact λ c l IH, (power_le_of_limit a0 l).2
(λ b' h, le_trans (IH _ h) (power_le_power_right
(lt_of_lt_of_le (pos_iff_ne_zero.2 a0) ab) (le_of_lt h))) } }
end
theorem le_power_self {a : ordinal} (b) (a1 : 1 < a) : b ≤ a ^ b :=
(power_is_normal a1).le_self _
theorem power_lt_power_left_of_succ {a b c : ordinal}
(ab : a < b) : a ^ succ c < b ^ succ c :=
by rw [power_succ, power_succ]; exact
lt_of_le_of_lt
(mul_le_mul_right _ $ power_le_power_left _ $ le_of_lt ab)
(mul_lt_mul_of_pos_left ab (power_pos _ (lt_of_le_of_lt (zero_le _) ab)))
theorem power_add (a b c : ordinal) : a ^ (b + c) = a ^ b * a ^ c :=
begin
by_cases a0 : a = 0,
{ subst a,
by_cases c0 : c = 0, {simp only [c0, add_zero, power_zero, mul_one]},
have : b+c ≠ 0 := ne_of_gt (lt_of_lt_of_le
(pos_iff_ne_zero.2 c0) (le_add_left _ _)),
simp only [zero_power c0, zero_power this, mul_zero] },
cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1,
{ subst a1, simp only [one_power, mul_one] },
apply limit_rec_on c,
{ simp only [add_zero, power_zero, mul_one] },
{ intros c IH,
rw [add_succ, power_succ, IH, power_succ, mul_assoc] },
{ intros c l IH,
refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans
(add_is_normal b)).limit_le l).trans _),
simp only [IH] {contextual := tt},
exact (((mul_is_normal $ power_pos b (pos_iff_ne_zero.2 a0)).trans
(power_is_normal a1)).limit_le l).symm }
end
theorem power_dvd_power (a) {b c : ordinal}
(h : b ≤ c) : a ^ b ∣ a ^ c :=
by { rw [← add_sub_cancel_of_le h, power_add], apply dvd_mul_right }
theorem power_dvd_power_iff {a b c : ordinal}
(a1 : 1 < a) : a ^ b ∣ a ^ c ↔ b ≤ c :=
⟨λ h, le_of_not_lt $ λ hn,
not_le_of_lt ((power_lt_power_iff_right a1).2 hn) $
le_of_dvd (power_ne_zero _ $ one_le_iff_ne_zero.1 $ le_of_lt a1) h,
power_dvd_power _⟩
theorem power_mul (a b c : ordinal) : a ^ (b * c) = (a ^ b) ^ c :=
begin
by_cases b0 : b = 0, {simp only [b0, zero_mul, power_zero, one_power]},
by_cases a0 : a = 0,
{ subst a,
by_cases c0 : c = 0, {simp only [c0, mul_zero, power_zero]},
simp only [zero_power b0, zero_power c0, zero_power (mul_ne_zero b0 c0)] },
cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1,
{ subst a1, simp only [one_power] },
apply limit_rec_on c,
{ simp only [mul_zero, power_zero] },
{ intros c IH,
rw [mul_succ, power_add, IH, power_succ] },
{ intros c l IH,
refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans
(mul_is_normal (pos_iff_ne_zero.2 b0))).limit_le l).trans _),
simp only [IH] {contextual := tt},
exact (power_le_of_limit (power_ne_zero _ a0) l).symm }
end
/-! ### Ordinal logarithm -/
/-- The ordinal logarithm is the solution `u` to the equation
`x = b ^ u * v + w` where `v < b` and `w < b`. -/
def log (b : ordinal) (x : ordinal) : ordinal :=
if h : 1 < b then pred $
omin {o | x < b^o} ⟨succ x, succ_le.1 (le_power_self _ h)⟩
else 0
@[simp] theorem log_not_one_lt {b : ordinal} (b1 : ¬ 1 < b) (x : ordinal) : log b x = 0 :=
by simp only [log, dif_neg b1]
theorem log_def {b : ordinal} (b1 : 1 < b) (x : ordinal) : log b x =
pred (omin {o | x < b^o} (log._proof_1 b x b1)) :=
by simp only [log, dif_pos b1]
@[simp] theorem log_zero (b : ordinal) : log b 0 = 0 :=
if b1 : 1 < b then
by rw [log_def b1, ← le_zero, pred_le];
apply omin_le; change 0<b^succ 0;
rw [succ_zero, power_one];
exact lt_trans zero_lt_one b1
else by simp only [log_not_one_lt b1]
theorem succ_log_def {b x : ordinal} (b1 : 1 < b) (x0 : 0 < x) : succ (log b x) =
omin {o | x < b^o} (log._proof_1 b x b1) :=
begin
let t := omin {o | x < b^o} (log._proof_1 b x b1),
have : x < b ^ t := omin_mem {o | x < b^o} _,
rcases zero_or_succ_or_limit t with h|h|h,
{ refine (not_lt_of_le (one_le_iff_pos.2 x0) _).elim,
simpa only [h, power_zero] },
{ rw [show log b x = pred t, from log_def b1 x,
succ_pred_iff_is_succ.2 h] },
{ rcases (lt_power_of_limit (ne_of_gt $ lt_trans zero_lt_one b1) h).1 this with ⟨a, h₁, h₂⟩,
exact (not_le_of_lt h₁).elim (le_omin.1 (le_refl t) a h₂) }
end
theorem lt_power_succ_log {b : ordinal} (b1 : 1 < b) (x : ordinal) :
x < b ^ succ (log b x) :=
begin
cases lt_or_eq_of_le (zero_le x) with x0 x0,
{ rw [succ_log_def b1 x0], exact omin_mem {o | x < b^o} _ },
{ subst x, apply power_pos _ (lt_trans zero_lt_one b1) }
end
theorem power_log_le (b) {x : ordinal} (x0 : 0 < x) :
b ^ log b x ≤ x :=
begin
by_cases b0 : b = 0,
{ rw [b0, zero_power'],
refine le_trans (sub_le_self _ _) (one_le_iff_pos.2 x0) },
cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1,
{ refine le_of_not_lt (λ h, not_le_of_lt (lt_succ_self (log b x)) _),
have := @omin_le {o | x < b^o} _ _ h,
rwa ← succ_log_def b1 x0 at this },
{ rw [← b1, one_power], exact one_le_iff_pos.2 x0 }
end
theorem le_log {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) :
c ≤ log b x ↔ b ^ c ≤ x :=
⟨λ h, le_trans ((power_le_power_iff_right b1).2 h) (power_log_le b x0),
λ h, le_of_not_lt $ λ hn,
not_le_of_lt (lt_power_succ_log b1 x) $
le_trans ((power_le_power_iff_right b1).2 (succ_le.2 hn)) h⟩
theorem log_lt {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) :
log b x < c ↔ x < b ^ c :=
lt_iff_lt_of_le_iff_le (le_log b1 x0)
theorem log_le_log (b) {x y : ordinal} (xy : x ≤ y) :
log b x ≤ log b y :=
if x0 : x = 0 then by simp only [x0, log_zero, zero_le] else
have x0 : 0 < x, from pos_iff_ne_zero.2 x0,
if b1 : 1 < b then
(le_log b1 (lt_of_lt_of_le x0 xy)).2 $ le_trans (power_log_le _ x0) xy
else by simp only [log_not_one_lt b1, zero_le]
theorem log_le_self (b x : ordinal) : log b x ≤ x :=
if x0 : x = 0 then by simp only [x0, log_zero, zero_le] else
if b1 : 1 < b then
le_trans (le_power_self _ b1) (power_log_le b (pos_iff_ne_zero.2 x0))
else by simp only [log_not_one_lt b1, zero_le]
/-! ### The Cantor normal form -/
theorem CNF_aux {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) :
o % b ^ log b o < o :=
lt_of_lt_of_le
(mod_lt _ $ power_ne_zero _ b0)
(power_log_le _ $ pos_iff_ne_zero.2 o0)
/-- Proving properties of ordinals by induction over their Cantor normal form. -/
@[elab_as_eliminator] noncomputable def CNF_rec {b : ordinal} (b0 : b ≠ 0)
{C : ordinal → Sort*}
(H0 : C 0)
(H : ∀ o, o ≠ 0 → o % b ^ log b o < o → C (o % b ^ log b o) → C o)
: ∀ o, C o
| o :=
if o0 : o = 0 then by rw o0; exact H0 else
have _, from CNF_aux b0 o0,
H o o0 this (CNF_rec (o % b ^ log b o))
using_well_founded {dec_tac := `[assumption]}
@[simp] theorem CNF_rec_zero {b} (b0) {C H0 H} : @CNF_rec b b0 C H0 H 0 = H0 :=
by rw [CNF_rec, dif_pos rfl]; refl
@[simp] theorem CNF_rec_ne_zero {b} (b0) {C H0 H o} (o0) :
@CNF_rec b b0 C H0 H o = H o o0 (CNF_aux b0 o0) (@CNF_rec b b0 C H0 H _) :=
by rw [CNF_rec, dif_neg o0]
/-- The Cantor normal form of an ordinal is the list of coefficients
in the base-`b` expansion of `o`.
CNF b (b ^ u₁ * v₁ + b ^ u₂ * v₂) = [(u₁, v₁), (u₂, v₂)] -/
noncomputable def CNF (b := omega) (o : ordinal) : list (ordinal × ordinal) :=
if b0 : b = 0 then [] else
CNF_rec b0 [] (λ o o0 h IH, (log b o, o / b ^ log b o) :: IH) o
@[simp] theorem zero_CNF (o) : CNF 0 o = [] :=
dif_pos rfl
@[simp] theorem CNF_zero (b) : CNF b 0 = [] :=
if b0 : b = 0 then dif_pos b0 else
(dif_neg b0).trans $ CNF_rec_zero _
theorem CNF_ne_zero {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) :
CNF b o = (log b o, o / b ^ log b o) :: CNF b (o % b ^ log b o) :=
by unfold CNF; rw [dif_neg b0, dif_neg b0, CNF_rec_ne_zero b0 o0]
theorem one_CNF {o : ordinal} (o0 : o ≠ 0) :
CNF 1 o = [(0, o)] :=
by rw [CNF_ne_zero ordinal.one_ne_zero o0, log_not_one_lt (lt_irrefl _), power_zero, mod_one,
CNF_zero, div_one]
theorem CNF_foldr {b : ordinal} (b0 : b ≠ 0) (o) :
(CNF b o).foldr (λ p r, b ^ p.1 * p.2 + r) 0 = o :=
CNF_rec b0 (by rw CNF_zero; refl)
(λ o o0 h IH, by rw [CNF_ne_zero b0 o0, list.foldr_cons, IH, div_add_mod]) o
theorem CNF_pairwise_aux (b := omega) (o) :
(∀ p ∈ CNF b o, prod.fst p ≤ log b o) ∧
(CNF b o).pairwise (λ p q, q.1 < p.1) :=
begin
by_cases b0 : b = 0,
{ simp only [b0, zero_CNF, list.pairwise.nil, and_true], exact λ _, false.elim },
cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1,
{ refine CNF_rec b0 _ _ o,
{ simp only [CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim },
intros o o0 H IH, cases IH with IH₁ IH₂,
simp only [CNF_ne_zero b0 o0, list.forall_mem_cons, list.pairwise_cons, IH₂, and_true],
refine ⟨⟨le_refl _, λ p m, _⟩, λ p m, _⟩,
{ exact le_trans (IH₁ p m) (log_le_log _ $ le_of_lt H) },
{ refine lt_of_le_of_lt (IH₁ p m) ((log_lt b1 _).2 _),
{ rw pos_iff_ne_zero, intro e,
rw e at m, simpa only [CNF_zero] using m },
{ exact mod_lt _ (power_ne_zero _ b0) } } },
{ by_cases o0 : o = 0,
{ simp only [o0, CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim },
rw [← b1, one_CNF o0],
simp only [list.mem_singleton, log_not_one_lt (lt_irrefl _), forall_eq, le_refl, true_and, list.pairwise_singleton] }
end
theorem CNF_pairwise (b := omega) (o) :
(CNF b o).pairwise (λ p q, prod.fst q < p.1) :=
(CNF_pairwise_aux _ _).2
theorem CNF_fst_le_log (b := omega) (o) :
∀ p ∈ CNF b o, prod.fst p ≤ log b o :=
(CNF_pairwise_aux _ _).1
theorem CNF_fst_le (b := omega) (o) (p ∈ CNF b o) : prod.fst p ≤ o :=
le_trans (CNF_fst_le_log _ _ p H) (log_le_self _ _)
theorem CNF_snd_lt {b : ordinal} (b1 : 1 < b) (o) :
∀ p ∈ CNF b o, prod.snd p < b :=
begin
have b0 := ne_of_gt (lt_trans zero_lt_one b1),
refine CNF_rec b0 (λ _, by rw [CNF_zero]; exact false.elim) _ o,
intros o o0 H IH,
simp only [CNF_ne_zero b0 o0, list.mem_cons_iff, list.forall_mem_cons', iff_true_intro IH, and_true],
rw [div_lt (power_ne_zero _ b0), ← power_succ],
exact lt_power_succ_log b1 _,
end
theorem CNF_sorted (b := omega) (o) :
((CNF b o).map prod.fst).sorted (>) :=
by rw [list.sorted, list.pairwise_map]; exact CNF_pairwise b o
/-! ### Casting naturals into ordinals, compatibility with operations -/
@[simp] theorem nat_cast_mul {m n : ℕ} : ((m * n : ℕ) : ordinal) = m * n :=
by induction n with n IH; [simp only [nat.cast_zero, nat.mul_zero, mul_zero],
rw [nat.mul_succ, nat.cast_add, IH, nat.cast_succ, mul_add_one]]
@[simp] theorem nat_cast_power {m n : ℕ} : ((pow m n : ℕ) : ordinal) = m ^ n :=
by induction n with n IH; [simp only [nat.pow_zero, nat.cast_zero, power_zero, nat.cast_one],
rw [nat.pow_succ, nat_cast_mul, IH, nat.cast_succ, ← succ_eq_add_one, power_succ]]
@[simp] theorem nat_cast_le {m n : ℕ} : (m : ordinal) ≤ n ↔ m ≤ n :=
by rw [← cardinal.ord_nat, ← cardinal.ord_nat,
cardinal.ord_le_ord, cardinal.nat_cast_le]
@[simp] theorem nat_cast_lt {m n : ℕ} : (m : ordinal) < n ↔ m < n :=
by simp only [lt_iff_le_not_le, nat_cast_le]
@[simp] theorem nat_cast_inj {m n : ℕ} : (m : ordinal) = n ↔ m = n :=
by simp only [le_antisymm_iff, nat_cast_le]
@[simp] theorem nat_cast_eq_zero {n : ℕ} : (n : ordinal) = 0 ↔ n = 0 :=
@nat_cast_inj n 0
theorem nat_cast_ne_zero {n : ℕ} : (n : ordinal) ≠ 0 ↔ n ≠ 0 :=
not_congr nat_cast_eq_zero
@[simp] theorem nat_cast_pos {n : ℕ} : (0 : ordinal) < n ↔ 0 < n :=
@nat_cast_lt 0 n
@[simp] theorem nat_cast_sub {m n : ℕ} : ((m - n : ℕ) : ordinal) = m - n :=
(_root_.le_total m n).elim
(λ h, by rw [nat.sub_eq_zero_iff_le.2 h, sub_eq_zero_iff_le.2 (nat_cast_le.2 h)]; refl)
(λ h, (add_left_cancel n).1 $ by rw [← nat.cast_add,
nat.add_sub_cancel' h, add_sub_cancel_of_le (nat_cast_le.2 h)])
@[simp] theorem nat_cast_div {m n : ℕ} : ((m / n : ℕ) : ordinal) = m / n :=
if n0 : n = 0 then by simp only [n0, nat.div_zero, nat.cast_zero, div_zero] else
have n0':_, from nat_cast_ne_zero.2 n0,
le_antisymm
(by rw [le_div n0', ← nat_cast_mul, nat_cast_le, mul_comm];
apply nat.div_mul_le_self)
(by rw [div_le n0', succ, ← nat.cast_succ, ← nat_cast_mul,
nat_cast_lt, mul_comm, ← nat.div_lt_iff_lt_mul _ _ (nat.pos_of_ne_zero n0)];
apply nat.lt_succ_self)
@[simp] theorem nat_cast_mod {m n : ℕ} : ((m % n : ℕ) : ordinal) = m % n :=
by rw [← add_left_cancel (n*(m/n)), div_add_mod, ← nat_cast_div, ← nat_cast_mul, ← nat.cast_add,
add_comm, nat.mod_add_div]
@[simp] theorem nat_le_card {o} {n : ℕ} : (n : cardinal) ≤ card o ↔ (n : ordinal) ≤ o :=
⟨λ h, by rwa [← cardinal.ord_le, cardinal.ord_nat] at h,
λ h, card_nat n ▸ card_le_card h⟩
@[simp] theorem nat_lt_card {o} {n : ℕ} : (n : cardinal) < card o ↔ (n : ordinal) < o :=
by rw [← succ_le, ← cardinal.succ_le, ← cardinal.nat_succ, nat_le_card]; refl
@[simp] theorem card_lt_nat {o} {n : ℕ} : card o < n ↔ o < n :=
lt_iff_lt_of_le_iff_le nat_le_card
@[simp] theorem card_le_nat {o} {n : ℕ} : card o ≤ n ↔ o ≤ n :=
le_iff_le_iff_lt_iff_lt.2 nat_lt_card
@[simp] theorem card_eq_nat {o} {n : ℕ} : card o = n ↔ o = n :=
by simp only [le_antisymm_iff, card_le_nat, nat_le_card]
@[simp] theorem type_fin (n : ℕ) : @type (fin n) (<) _ = n :=
by rw [← card_eq_nat, card_type, mk_fin]
@[simp] theorem lift_nat_cast (n : ℕ) : lift n = n :=
by induction n with n ih; [simp only [nat.cast_zero, lift_zero],
simp only [nat.cast_succ, lift_add, ih, lift_one]]
theorem lift_type_fin (n : ℕ) : lift (@type (fin n) (<) _) = n :=
by simp only [type_fin, lift_nat_cast]
theorem fintype_card (r : α → α → Prop) [is_well_order α r] [fintype α] : type r = fintype.card α :=
by rw [← card_eq_nat, card_type, fintype_card]
end ordinal
/-! ### Properties of `omega` -/
namespace cardinal
open ordinal
@[simp] theorem ord_omega : ord.{u} omega = ordinal.omega :=
le_antisymm (ord_le.2 $ le_refl _) $
le_of_forall_lt $ λ o h, begin
rcases ordinal.lt_lift_iff.1 h with ⟨o, rfl, h'⟩,
rw [lt_ord, ← lift_card, ← lift_omega.{0 u},
lift_lt, ← typein_enum (<) h'],
exact lt_omega_iff_fintype.2 ⟨set.fintype_lt_nat _⟩
end
@[simp] theorem add_one_of_omega_le {c} (h : omega ≤ c) : c + 1 = c :=
by rw [add_comm, ← card_ord c, ← card_one,
← card_add, one_add_of_omega_le];
rwa [← ord_omega, ord_le_ord]
end cardinal
namespace ordinal
theorem lt_omega {o : ordinal.{u}} : o < omega ↔ ∃ n : ℕ, o = n :=
by rw [← cardinal.ord_omega, cardinal.lt_ord, lt_omega]; simp only [card_eq_nat]
theorem nat_lt_omega (n : ℕ) : (n : ordinal) < omega :=
lt_omega.2 ⟨_, rfl⟩
theorem omega_pos : 0 < omega := nat_lt_omega 0
theorem omega_ne_zero : omega ≠ 0 := ne_of_gt omega_pos
theorem one_lt_omega : 1 < omega := by simpa only [nat.cast_one] using nat_lt_omega 1
theorem omega_is_limit : is_limit omega :=
⟨omega_ne_zero, λ o h,
let ⟨n, e⟩ := lt_omega.1 h in
by rw [e]; exact nat_lt_omega (n+1)⟩
theorem omega_le {o : ordinal.{u}} : omega ≤ o ↔ ∀ n : ℕ, (n : ordinal) ≤ o :=
⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h,
λ H, le_of_forall_lt $ λ a h,
let ⟨n, e⟩ := lt_omega.1 h in
by rw [e, ← succ_le]; exact H (n+1)⟩
theorem nat_lt_limit {o} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o
| 0 := lt_of_le_of_ne (zero_le o) h.1.symm
| (n+1) := h.2 _ (nat_lt_limit n)
theorem omega_le_of_is_limit {o} (h : is_limit o) : omega ≤ o :=
omega_le.2 $ λ n, le_of_lt $ nat_lt_limit h n
theorem add_omega {a : ordinal} (h : a < omega) : a + omega = omega :=
begin
rcases lt_omega.1 h with ⟨n, rfl⟩,
clear h, induction n with n IH,
{ rw [nat.cast_zero, zero_add] },
{ rw [nat.cast_succ, add_assoc, one_add_of_omega_le (le_refl _), IH] }
end
theorem add_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a + b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega
end
theorem mul_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a * b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_mul]; apply nat_lt_omega
end
theorem is_limit_iff_omega_dvd {a : ordinal} : is_limit a ↔ a ≠ 0 ∧ omega ∣ a :=
begin
refine ⟨λ l, ⟨l.1, ⟨a / omega, le_antisymm _ (mul_div_le _ _)⟩⟩, λ h, _⟩,
{ refine (limit_le l).2 (λ x hx, le_of_lt _),
rw [← div_lt omega_ne_zero, ← succ_le, le_div omega_ne_zero,
mul_succ, add_le_of_limit omega_is_limit],
intros b hb,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
exact le_trans (add_le_add_right (mul_div_le _ _) _)
(le_of_lt $ lt_sub.1 $ nat_lt_limit (sub_is_limit l hx) _) },
{ rcases h with ⟨a0, b, rfl⟩,
refine mul_is_limit_left omega_is_limit
(pos_iff_ne_zero.2 $ mt _ a0),
intro e, simp only [e, mul_zero] }
end
local infixr ^ := @pow ordinal ordinal ordinal.has_pow
theorem power_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_power]; apply nat_lt_omega
end
theorem add_omega_power {a b : ordinal} (h : a < omega ^ b) : a + omega ^ b = omega ^ b :=
begin
refine le_antisymm _ (le_add_left _ _),
revert h, apply limit_rec_on b,
{ intro h, rw [power_zero, ← succ_zero, lt_succ, le_zero] at h,
rw [h, zero_add] },
{ intros b _ h, rw [power_succ] at h,
rcases (lt_mul_of_limit omega_is_limit).1 h with ⟨x, xo, ax⟩,
refine le_trans (add_le_add_right (le_of_lt ax) _) _,
rw [power_succ, ← mul_add, add_omega xo] },
{ intros b l IH h, rcases (lt_power_of_limit omega_ne_zero l).1 h with ⟨x, xb, ax⟩,
refine (((add_is_normal a).trans (power_is_normal one_lt_omega))
.limit_le l).2 (λ y yb, _),
let z := max x y,
have := IH z (max_lt xb yb)
(lt_of_lt_of_le ax $ power_le_power_right omega_pos (le_max_left _ _)),
exact le_trans (add_le_add_left (power_le_power_right omega_pos (le_max_right _ _)) _)
(le_trans this (power_le_power_right omega_pos $ le_of_lt $ max_lt xb yb)) }
end
theorem add_lt_omega_power {a b c : ordinal} (h₁ : a < omega ^ c) (h₂ : b < omega ^ c) :
a + b < omega ^ c :=
by rwa [← add_omega_power h₁, add_lt_add_iff_left]
theorem add_absorp {a b c : ordinal} (h₁ : a < omega ^ b) (h₂ : omega ^ b ≤ c) : a + c = c :=
by rw [← add_sub_cancel_of_le h₂, ← add_assoc, add_omega_power h₁]
theorem add_absorp_iff {o : ordinal} (o0 : 0 < o) : (∀ a < o, a + o = o) ↔ ∃ a, o = omega ^ a :=
⟨λ H, ⟨log omega o, begin
refine ((lt_or_eq_of_le (power_log_le _ o0))
.resolve_left $ λ h, _).symm,
have := H _ h,
have := lt_power_succ_log one_lt_omega o,
rw [power_succ, lt_mul_of_limit omega_is_limit] at this,
rcases this with ⟨a, ao, h'⟩,
rcases lt_omega.1 ao with ⟨n, rfl⟩, clear ao,
revert h', apply not_lt_of_le,
suffices e : omega ^ log omega o * ↑n + o = o,
{ simpa only [e] using le_add_right (omega ^ log omega o * ↑n) o },
induction n with n IH, {simp only [nat.cast_zero, mul_zero, zero_add]},
simp only [nat.cast_succ, mul_add_one, add_assoc, this, IH]
end⟩,
λ ⟨b, e⟩, e.symm ▸ λ a, add_omega_power⟩
theorem add_mul_limit_aux {a b c : ordinal} (ba : b + a = a)
(l : is_limit c)
(IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) :
(a + b) * c = a * c :=
le_antisymm
((mul_le_of_limit l).2 $ λ c' h, begin
apply le_trans (mul_le_mul_left _ (le_of_lt $ lt_succ_self _)),
rw IH _ h,
apply le_trans (add_le_add_left _ _),
{ rw ← mul_succ, exact mul_le_mul_left _ (succ_le.2 $ l.2 _ h) },
{ rw ← ba, exact le_add_right _ _ }
end)
(mul_le_mul_right _ (le_add_right _ _))
theorem add_mul_succ {a b : ordinal} (c) (ba : b + a = a) :
(a + b) * succ c = a * succ c + b :=
begin
apply limit_rec_on c,
{ simp only [succ_zero, mul_one] },
{ intros c IH,
rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ] },
{ intros c l IH,
have := add_mul_limit_aux ba l IH,
rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc] }
end
theorem add_mul_limit {a b c : ordinal} (ba : b + a = a)
(l : is_limit c) : (a + b) * c = a * c :=
add_mul_limit_aux ba l (λ c' _, add_mul_succ c' ba)
theorem mul_omega {a : ordinal} (a0 : 0 < a) (ha : a < omega) : a * omega = omega :=
le_antisymm
((mul_le_of_limit omega_is_limit).2 $ λ b hb, le_of_lt (mul_lt_omega ha hb))
(by simpa only [one_mul] using mul_le_mul_right omega (one_le_iff_pos.2 a0))
theorem mul_lt_omega_power {a b c : ordinal}
(c0 : 0 < c) (ha : a < omega ^ c) (hb : b < omega) : a * b < omega ^ c :=
if b0 : b = 0 then by simp only [b0, mul_zero, power_pos _ omega_pos] else begin
rcases zero_or_succ_or_limit c with rfl|⟨c,rfl⟩|l,
{ exact (lt_irrefl _).elim c0 },
{ rw power_succ at ha,
rcases ((mul_is_normal $ power_pos _ omega_pos).limit_lt
omega_is_limit).1 ha with ⟨n, hn, an⟩,
refine lt_of_le_of_lt (mul_le_mul_right _ (le_of_lt an)) _,
rw [power_succ, mul_assoc, mul_lt_mul_iff_left (power_pos _ omega_pos)],
exact mul_lt_omega hn hb },
{ rcases ((power_is_normal one_lt_omega).limit_lt l).1 ha with ⟨x, hx, ax⟩,
refine lt_of_le_of_lt (mul_le_mul (le_of_lt ax) (le_of_lt hb)) _,
rw [← power_succ, power_lt_power_iff_right one_lt_omega],
exact l.2 _ hx }
end
theorem mul_omega_dvd {a : ordinal}
(a0 : 0 < a) (ha : a < omega) : ∀ {b}, omega ∣ b → a * b = b
| _ ⟨b, rfl⟩ := by rw [← mul_assoc, mul_omega a0 ha]
theorem mul_omega_power_power {a b : ordinal} (a0 : 0 < a) (h : a < omega ^ omega ^ b) :
a * omega ^ omega ^ b = omega ^ omega ^ b :=
begin
by_cases b0 : b = 0, {rw [b0, power_zero, power_one] at h ⊢, exact mul_omega a0 h},
refine le_antisymm _ (by simpa only [one_mul] using mul_le_mul_right (omega^omega^b) (one_le_iff_pos.2 a0)),
rcases (lt_power_of_limit omega_ne_zero (power_is_limit_left omega_is_limit b0)).1 h
with ⟨x, xb, ax⟩,
refine le_trans (mul_le_mul_right _ (le_of_lt ax)) _,
rw [← power_add, add_omega_power xb]
end
theorem power_omega {a : ordinal} (a1 : 1 < a) (h : a < omega) : a ^ omega = omega :=
le_antisymm
((power_le_of_limit (one_le_iff_ne_zero.1 $ le_of_lt a1) omega_is_limit).2
(λ b hb, le_of_lt (power_lt_omega h hb)))
(le_power_self _ a1)
/-! ### Fixed points of normal functions -/
/-- The next fixed point function, the least fixed point of the
normal function `f` above `a`. -/
def nfp (f : ordinal → ordinal) (a : ordinal) :=
sup (λ n : ℕ, f^[n] a)
theorem iterate_le_nfp (f a n) : f^[n] a ≤ nfp f a :=
le_sup _ n
theorem le_nfp_self (f a) : a ≤ nfp f a :=
iterate_le_nfp f a 0
theorem is_normal.lt_nfp {f} (H : is_normal f) {a b} :
f b < nfp f a ↔ b < nfp f a :=
lt_sup.trans $ iff.trans
(by exact
⟨λ ⟨n, h⟩, ⟨n, lt_of_le_of_lt (H.le_self _) h⟩,
λ ⟨n, h⟩, ⟨n+1, by rw iterate_succ'; exact H.lt_iff.2 h⟩⟩)
lt_sup.symm
theorem is_normal.nfp_le {f} (H : is_normal f) {a b} :
nfp f a ≤ f b ↔ nfp f a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 H.lt_nfp
theorem is_normal.nfp_le_fp {f} (H : is_normal f) {a b}
(ab : a ≤ b) (h : f b ≤ b) : nfp f a ≤ b :=
sup_le.2 $ λ i, begin
induction i with i IH generalizing a, {exact ab},
exact IH (le_trans (H.le_iff.2 ab) h),
end
theorem is_normal.nfp_fp {f} (H : is_normal f) (a) : f (nfp f a) = nfp f a :=
begin
refine le_antisymm _ (H.le_self _),
cases le_or_lt (f a) a with aa aa,
{ rwa le_antisymm (H.nfp_le_fp (le_refl _) aa) (le_nfp_self _ _) },
rcases zero_or_succ_or_limit (nfp f a) with e|⟨b, e⟩|l,
{ refine @le_trans _ _ _ (f a) _ (H.le_iff.2 _) (iterate_le_nfp f a 1),
simp only [e, zero_le] },
{ have : f b < nfp f a := H.lt_nfp.2 (by simp only [e, lt_succ_self]),
rw [e, lt_succ] at this,
have ab : a ≤ b,
{ rw [← lt_succ, ← e],
exact lt_of_lt_of_le aa (iterate_le_nfp f a 1) },
refine le_trans (H.le_iff.2 (H.nfp_le_fp ab this))
(le_trans this (le_of_lt _)),
simp only [e, lt_succ_self] },
{ exact (H.2 _ l _).2 (λ b h, le_of_lt (H.lt_nfp.2 h)) }
end
theorem is_normal.le_nfp {f} (H : is_normal f) {a b} :
f b ≤ nfp f a ↔ b ≤ nfp f a :=
⟨le_trans (H.le_self _), λ h,
by simpa only [H.nfp_fp] using H.le_iff.2 h⟩
theorem nfp_eq_self {f : ordinal → ordinal} {a} (h : f a = a) : nfp f a = a :=
le_antisymm (sup_le.mpr $ λ i, by rw [iterate_fixed h]) (le_nfp_self f a)
/-- The derivative of a normal function `f` is
the sequence of fixed points of `f`. -/
def deriv (f : ordinal → ordinal) (o : ordinal) : ordinal :=
limit_rec_on o (nfp f 0)
(λ a IH, nfp f (succ IH))
(λ a l, bsup.{u u} a)
@[simp] theorem deriv_zero (f) : deriv f 0 = nfp f 0 := limit_rec_on_zero _ _ _
@[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) :=
limit_rec_on_succ _ _ _ _
theorem deriv_limit (f) {o} : is_limit o →
deriv f o = bsup.{u u} o (λ a _, deriv f a) :=
limit_rec_on_limit _ _ _ _
theorem deriv_is_normal (f) : is_normal (deriv f) :=
⟨λ o, by rw [deriv_succ, ← succ_le]; apply le_nfp_self,
λ o l a, by rw [deriv_limit _ l, bsup_le]⟩
theorem is_normal.deriv_fp {f} (H : is_normal f) (o) : f (deriv.{u} f o) = deriv f o :=
begin
apply limit_rec_on o,
{ rw [deriv_zero, H.nfp_fp] },
{ intros o ih, rw [deriv_succ, H.nfp_fp] },
intros o l IH,
rw [deriv_limit _ l, is_normal.bsup.{u u u} H _ l.1],
refine eq_of_forall_ge_iff (λ c, _),
simp only [bsup_le, IH] {contextual:=tt}
end
theorem is_normal.fp_iff_deriv {f} (H : is_normal f)
{a} : f a ≤ a ↔ ∃ o, a = deriv f o :=
⟨λ ha, begin
suffices : ∀ o (_:a ≤ deriv f o), ∃ o, a = deriv f o,
from this a ((deriv_is_normal _).le_self _),
intro o, apply limit_rec_on o,
{ intros h₁,
refine ⟨0, le_antisymm h₁ _⟩,
rw deriv_zero,
exact H.nfp_le_fp (zero_le _) ha },
{ intros o IH h₁,
cases le_or_lt a (deriv f o), {exact IH h},
refine ⟨succ o, le_antisymm h₁ _⟩,
rw deriv_succ,
exact H.nfp_le_fp (succ_le.2 h) ha },
{ intros o l IH h₁,
cases eq_or_lt_of_le h₁, {exact ⟨_, h⟩},
rw [deriv_limit _ l, ← not_le, bsup_le, not_ball] at h,
exact let ⟨o', h, hl⟩ := h in IH o' h (le_of_not_le hl) }
end, λ ⟨o, e⟩, e.symm ▸ le_of_eq (H.deriv_fp _)⟩
end ordinal
|
a80ef6d1a2e034a2cd51c56f780cbd973c9e3ec9 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/combinatorics/simple_graph/matching.lean | 97e3a11465b27a9bbc38412b63c02bd37a315050 | [] | 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,353 | lean | /-
Copyright (c) 2020 Alena Gusakov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Alena Gusakov.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.fintype.basic
import Mathlib.data.sym2
import Mathlib.combinatorics.simple_graph.basic
import Mathlib.PostPort
universes u l
namespace Mathlib
/-!
# Matchings
## Main definitions
* a `matching` on a simple graph is a subset of its edge set such that
no two edges share an endpoint.
* a `perfect_matching` on a simple graph is a matching in which every
vertex belongs to an edge.
TODO:
- Lemma stating that the existence of a perfect matching on `G` implies that
the cardinality of `V` is even (assuming it's finite)
- Hall's Marriage Theorem
- Tutte's Theorem
- consider coercions instead of type definition for `matching`:
https://github.com/leanprover-community/mathlib/pull/5156#discussion_r532935457
- consider expressing `matching_verts` as union:
https://github.com/leanprover-community/mathlib/pull/5156#discussion_r532906131
TODO: Tutte and Hall require a definition of subgraphs.
-/
namespace simple_graph
/--
A matching on `G` is a subset of its edges such that no two edges share a vertex.
-/
structure matching {V : Type u} (G : simple_graph V)
where
edges : set (sym2 V)
sub_edges : edges ⊆ edge_set G
disjoint : ∀ (x y : sym2 V), x ∈ edges → y ∈ edges → ∀ (v : V), v ∈ x ∧ v ∈ y → x = y
protected instance matching.inhabited {V : Type u} (G : simple_graph V) : Inhabited (matching G) :=
{ default := matching.mk ∅ sorry sorry }
/--
`M.support` is the set of vertices of `G` that are
contained in some edge of matching `M`
-/
def matching.support {V : Type u} {G : simple_graph V} (M : matching G) : set V :=
set_of fun (v : V) => ∃ (x : sym2 V), ∃ (H : x ∈ matching.edges M), v ∈ x
/--
A perfect matching `M` on graph `G` is a matching such that
every vertex is contained in an edge of `M`.
-/
def matching.is_perfect {V : Type u} {G : simple_graph V} (M : matching G) :=
matching.support M = set.univ
theorem matching.is_perfect_iff {V : Type u} {G : simple_graph V} (M : matching G) : matching.is_perfect M ↔ ∀ (v : V), ∃ (e : sym2 V), ∃ (H : e ∈ matching.edges M), v ∈ e :=
set.eq_univ_iff_forall
|
c48185897fc9734c915d6bbb350e448767030edd | 4fa161becb8ce7378a709f5992a594764699e268 | /src/measure_theory/ae_eq_fun.lean | c69b9abfff2eed53b947c88cd220cc1d4ccb3228 | [
"Apache-2.0"
] | permissive | laughinggas/mathlib | e4aa4565ae34e46e834434284cb26bd9d67bc373 | 86dcd5cda7a5017c8b3c8876c89a510a19d49aad | refs/heads/master | 1,669,496,232,688 | 1,592,831,995,000 | 1,592,831,995,000 | 274,155,979 | 0 | 0 | Apache-2.0 | 1,592,835,190,000 | 1,592,835,189,000 | null | UTF-8 | Lean | false | false | 21,597 | lean | /-
Copyright (c) 2019 Johannes Hölzl, Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Zhouhang Zhou
-/
import measure_theory.integration
/-!
# Almost everywhere equal functions
Two measurable functions are treated as identical if they are almost everywhere equal. We form the
set of equivalence classes under the relation of being almost everywhere equal, which is sometimes
known as the `L⁰` space.
See `l1_space.lean` for `L¹` space.
## Notation
* `α →ₘ β` is the type of `L⁰` space, where `α` is a measure space and `β` is a measurable space.
`f : α →ₘ β` is a "function" in `L⁰`. In comments, `[f]` is also used to denote an `L⁰` function.
`ₘ` can be typed as `\_m`. Sometimes it is shown as a box if font is missing.
## Main statements
* The linear structure of `L⁰` :
Addition and scalar multiplication are defined on `L⁰` in the natural way, i.e.,
`[f] + [g] := [f + g]`, `c • [f] := [c • f]`. So defined, `α →ₘ β` inherits the linear structure
of `β`. For example, if `β` is a module, then `α →ₘ β` is a module over the same ring.
See `mk_add_mk`, `neg_mk`, `mk_sub_mk`, `smul_mk`,
`add_to_fun`, `neg_to_fun`, `sub_to_fun`, `smul_to_fun`
* The order structure of `L⁰` :
`≤` can be defined in a similar way: `[f] ≤ [g]` if `f a ≤ g a` for almost all `a` in domain.
And `α →ₘ β` inherits the preorder and partial order of `β`.
TODO: Define `sup` and `inf` on `L⁰` so that it forms a lattice. It seems that `β` must be a
linear order, since otherwise `f ⊔ g` may not be a measurable function.
* Emetric on `L⁰` :
If `β` is an `emetric_space`, then `L⁰` can be made into an `emetric_space`, where
`edist [f] [g]` is defined to be `∫⁻ a, edist (f a) (g a)`.
The integral used here is `lintegral : (α → ennreal) → ennreal`, which is defined in the file
`integration.lean`.
See `edist_mk_mk` and `edist_to_fun`.
## Implementation notes
* `f.to_fun` : To find a representative of `f : α →ₘ β`, use `f.to_fun`.
For each operation `op` in `L⁰`, there is a lemma called `op_to_fun`, characterizing,
say, `(f op g).to_fun`.
* `ae_eq_fun.mk` : To constructs an `L⁰` function `α →ₘ β` from a measurable function `f : α → β`,
use `ae_eq_fun.mk`
* `comp` : Use `comp g f` to get `[g ∘ f]` from `g : β → γ` and `[f] : α →ₘ γ`
* `comp₂` : Use `comp₂ g f₁ f₂ to get `[λa, g (f₁ a) (f₂ a)]`.
For example, `[f + g]` is `comp₂ (+)`
## Tags
function space, almost everywhere equal, `L⁰`, ae_eq_fun
-/
noncomputable theory
open_locale classical
namespace measure_theory
open set filter topological_space
universes u v
variables {α : Type u} {β : Type v} [measure_space α]
section measurable_space
variables [measurable_space β]
variables (α β)
/-- The equivalence relation of being almost everywhere equal -/
instance ae_eq_fun.setoid : setoid { f : α → β // measurable f } :=
⟨λf g, ∀ₘ a, f.1 a = g.1 a, λ f, ae_eq_refl f, λ f g, ae_eq_symm, λ f g h, ae_eq_trans⟩
/-- The space of equivalence classes of measurable functions, where two measurable functions are
equivalent if they agree almost everywhere, i.e., they differ on a set of measure `0`. -/
def ae_eq_fun : Type (max u v) := quotient (ae_eq_fun.setoid α β)
variables {α β}
infixr ` →ₘ `:25 := ae_eq_fun
end measurable_space
namespace ae_eq_fun
variables [measurable_space β]
/-- Construct the equivalence class `[f]` of a measurable function `f`, based on the equivalence
relation of being almost everywhere equal. -/
def mk (f : α → β) (hf : measurable f) : α →ₘ β := quotient.mk ⟨f, hf⟩
/-- A representative of an `ae_eq_fun` [f] -/
protected def to_fun (f : α →ₘ β) : α → β := @quotient.out _ (ae_eq_fun.setoid α β) f
protected lemma measurable (f : α →ₘ β) : measurable f.to_fun :=
(@quotient.out _ (ae_eq_fun.setoid α β) f).2
instance : has_coe (α →ₘ β) (α → β) := ⟨λf, f.to_fun⟩
@[simp] lemma quot_mk_eq_mk (f : {f : α → β // measurable f}) : quot.mk setoid.r f = mk f.1 f.2 :=
by cases f; refl
@[simp] lemma mk_eq_mk (f g : α → β) (hf hg) :
mk f hf = mk g hg ↔ (∀ₘ a, f a = g a) :=
⟨quotient.exact, assume h, quotient.sound h⟩
@[ext] lemma ext (f g : α →ₘ β) (f' g' : α → β) (hf' hg') (hf : mk f' hf' = f)
(hg : mk g' hg' = g) (h : ∀ₘ a, f' a = g' a) : f = g :=
by { rw [← hf, ← hg], rw mk_eq_mk, assumption }
lemma self_eq_mk (f : α →ₘ β) : f = mk (f.to_fun) f.measurable :=
by simp [mk, ae_eq_fun.to_fun]
lemma all_ae_mk_to_fun (f : α → β) (hf) : ∀ₘ a, (mk f hf).to_fun a = f a :=
by rw [← mk_eq_mk _ f _ hf, ← self_eq_mk (mk f hf)]
/-- Given a measurable function `g : β → γ`, and an almost everywhere equal function `[f] : α →ₘ β`,
return the equivalence class of `g ∘ f`, i.e., the almost everywhere equal function
`[g ∘ f] : α →ₘ γ`. -/
def comp {γ : Type*} [measurable_space γ] (g : β → γ) (hg : measurable g) (f : α →ₘ β) : α →ₘ γ :=
quotient.lift_on f (λf, mk (g ∘ f.1) (measurable.comp hg f.2)) $ assume f₁ f₂ eq,
by refine quotient.sound _; filter_upwards [eq] assume a, congr_arg g
@[simp] lemma comp_mk {γ : Type*} [measurable_space γ] (g : β → γ) (hg : measurable g)
(f : α → β) (hf) : comp g hg (mk f hf) = mk (g ∘ f) (measurable.comp hg hf) :=
rfl
lemma comp_eq_mk_to_fun {γ : Type*} [measurable_space γ] (g : β → γ) (hg : measurable g) (f : α →ₘ β) :
comp g hg f = mk (g ∘ f.to_fun) (hg.comp f.measurable) :=
by conv_lhs { rw [self_eq_mk f, comp_mk] }
lemma comp_to_fun {γ : Type*} [measurable_space γ] (g : β → γ) (hg : measurable g) (f : α →ₘ β) :
∀ₘ a, (comp g hg f).to_fun a = (g ∘ f.to_fun) a :=
by { rw comp_eq_mk_to_fun, apply all_ae_mk_to_fun }
/-- Given a measurable function `g : β → γ → δ`, and almost everywhere equal functions
`[f₁] : α →ₘ β` and `[f₂] : α →ₘ γ`, return the equivalence class of the function
`λa, g (f₁ a) (f₂ a)`, i.e., the almost everywhere equal function
`[λa, g (f₁ a) (f₂ a)] : α →ₘ γ` -/
def comp₂ {γ δ : Type*} [measurable_space γ] [measurable_space δ]
(g : β → γ → δ) (hg : measurable (λp:β×γ, g p.1 p.2)) (f₁ : α →ₘ β) (f₂ : α →ₘ γ) : α →ₘ δ :=
begin
refine quotient.lift_on₂ f₁ f₂ (λf₁ f₂, mk (λa, g (f₁.1 a) (f₂.1 a)) $ _) _,
{ exact measurable.comp hg (measurable.prod_mk f₁.2 f₂.2) },
{ rintros ⟨f₁, hf₁⟩ ⟨f₂, hf₂⟩ ⟨g₁, hg₁⟩ ⟨g₂, hg₂⟩ h₁ h₂,
refine quotient.sound _,
filter_upwards [h₁, h₂],
simp {contextual := tt} }
end
@[simp] lemma comp₂_mk_mk {γ δ : Type*} [measurable_space γ] [measurable_space δ]
(g : β → γ → δ) (hg : measurable (λp:β×γ, g p.1 p.2)) (f₁ : α → β) (f₂ : α → γ) (hf₁ hf₂) :
comp₂ g hg (mk f₁ hf₁) (mk f₂ hf₂) =
mk (λa, g (f₁ a) (f₂ a)) (measurable.comp hg (measurable.prod_mk hf₁ hf₂)) :=
rfl
lemma comp₂_eq_mk_to_fun {γ δ : Type*} [measurable_space γ] [measurable_space δ]
(g : β → γ → δ) (hg : measurable (λp:β×γ, g p.1 p.2)) (f₁ : α →ₘ β) (f₂ : α →ₘ γ) :
comp₂ g hg f₁ f₂ = mk (λa, g (f₁.to_fun a) (f₂.to_fun a))
(hg.comp (measurable.prod_mk f₁.measurable f₂.measurable)) :=
by conv_lhs { rw [self_eq_mk f₁, self_eq_mk f₂, comp₂_mk_mk] }
lemma comp₂_to_fun {γ δ : Type*} [measurable_space γ] [measurable_space δ]
(g : β → γ → δ) (hg : measurable (λp:β×γ, g p.1 p.2)) (f₁ : α →ₘ β) (f₂ : α →ₘ γ) :
∀ₘ a, (comp₂ g hg f₁ f₂).to_fun a = g (f₁.to_fun a) (f₂.to_fun a) :=
by { rw comp₂_eq_mk_to_fun, apply all_ae_mk_to_fun }
/-- Given a predicate `p` and an equivalence class `[f]`, return true if `p` holds of `f a`
for almost all `a` -/
def lift_pred (p : β → Prop) (f : α →ₘ β) : Prop :=
quotient.lift_on f (λf, ∀ₘ a, p (f.1 a))
begin
assume f g h, dsimp, refine propext (eventually_congr _),
filter_upwards [h], simp {contextual := tt}
end
/-- Given a relation `r` and equivalence class `[f]` and `[g]`, return true if `r` holds of
`(f a, g a)` for almost all `a` -/
def lift_rel {γ : Type*} [measurable_space γ] (r : β → γ → Prop) (f : α →ₘ β) (g : α →ₘ γ) : Prop :=
lift_pred (λp:β×γ, r p.1 p.2)
(comp₂ prod.mk (measurable.prod_mk
(measurable.fst measurable_id) (measurable.snd measurable_id)) f g)
lemma lift_rel_mk_mk {γ : Type*} [measurable_space γ] (r : β → γ → Prop)
(f : α → β) (g : α → γ) (hf hg) : lift_rel r (mk f hf) (mk g hg) ↔ ∀ₘ a, r (f a) (g a) :=
iff.rfl
lemma lift_rel_iff_to_fun {γ : Type*} [measurable_space γ] (r : β → γ → Prop) (f : α →ₘ β)
(g : α →ₘ γ) : lift_rel r f g ↔ ∀ₘ a, r (f.to_fun a) (g.to_fun a) :=
by conv_lhs { rw [self_eq_mk f, self_eq_mk g, lift_rel_mk_mk] }
section order
instance [preorder β] : preorder (α →ₘ β) :=
{ le := lift_rel (≤),
le_refl := by rintros ⟨⟨f, hf⟩⟩; exact univ_mem_sets' (assume a, le_refl _),
le_trans :=
begin
rintros ⟨⟨f, hf⟩⟩ ⟨⟨g, hg⟩⟩ ⟨⟨h, hh⟩⟩ hfg hgh,
filter_upwards [hfg, hgh] assume a, le_trans
end }
lemma mk_le_mk [preorder β] {f g : α → β} (hf hg) : mk f hf ≤ mk g hg ↔ ∀ₘ a, f a ≤ g a :=
iff.rfl
lemma le_iff_to_fun_le [preorder β] {f g : α →ₘ β} : f ≤ g ↔ ∀ₘ a, f.to_fun a ≤ g.to_fun a :=
lift_rel_iff_to_fun _ _ _
instance [partial_order β] : partial_order (α →ₘ β) :=
{ le_antisymm :=
begin
rintros ⟨⟨f, hf⟩⟩ ⟨⟨g, hg⟩⟩ hfg hgf,
refine quotient.sound _,
filter_upwards [hfg, hgf] assume a, le_antisymm
end,
.. ae_eq_fun.preorder }
/- TODO: Prove `L⁰` space is a lattice if β is linear order.
What if β is only a lattice? -/
-- instance [linear_order β] : semilattice_sup (α →ₘ β) :=
-- { sup := comp₂ (⊔) (_),
-- .. ae_eq_fun.partial_order }
end order
variable (α)
/-- The equivalence class of a constant function: `[λa:α, b]`, based on the equivalence relation of
being almost everywhere equal -/
def const (b : β) : α →ₘ β := mk (λa:α, b) measurable_const
lemma const_to_fun (b : β) : ∀ₘ a, (const α b).to_fun a = b := all_ae_mk_to_fun _ _
variable {α}
instance [inhabited β] : inhabited (α →ₘ β) := ⟨const _ (default _)⟩
instance [has_zero β] : has_zero (α →ₘ β) := ⟨const α 0⟩
lemma zero_def [has_zero β] : (0 : α →ₘ β) = mk (λa:α, 0) measurable_const := rfl
lemma zero_to_fun [has_zero β] : ∀ₘ a, (0 : α →ₘ β).to_fun a = 0 := const_to_fun _ _
instance [has_one β] : has_one (α →ₘ β) := ⟨const α 1⟩
lemma one_def [has_one β] : (1 : α →ₘ β) = mk (λa:α, 1) measurable_const := rfl
lemma one_to_fun [has_one β] : ∀ₘ a, (1 : α →ₘ β).to_fun a = 1 := const_to_fun _ _
section add_monoid
variables {γ : Type*}
[topological_space γ] [second_countable_topology γ] [measurable_space γ] [borel_space γ]
[add_monoid γ] [topological_add_monoid γ]
instance : has_add (α →ₘ γ) := ⟨comp₂ (+) measurable_add⟩
@[simp] lemma mk_add_mk (f g : α → γ) (hf hg) :
(mk f hf) + (mk g hg) = mk (f + g) (measurable.add hf hg) := rfl
lemma add_to_fun (f g : α →ₘ γ) : ∀ₘ a, (f + g).to_fun a = f.to_fun a + g.to_fun a :=
comp₂_to_fun _ _ _ _
instance : add_monoid (α →ₘ γ) :=
{ zero := 0,
add := (+),
add_zero := by rintros ⟨a⟩; exact quotient.sound (ae_of_all _ $ assume a, add_zero _),
zero_add := by rintros ⟨a⟩; exact quotient.sound (ae_of_all _ $ assume a, zero_add _),
add_assoc :=
by rintros ⟨a⟩ ⟨b⟩ ⟨c⟩; exact quotient.sound (ae_of_all _ $ assume a, add_assoc _ _ _) }
end add_monoid
section add_comm_monoid
variables {γ : Type*}
[topological_space γ] [second_countable_topology γ] [measurable_space γ] [borel_space γ]
[add_comm_monoid γ] [topological_add_monoid γ]
instance add_comm_monoid : add_comm_monoid (α →ₘ γ) :=
{ add_comm := by rintros ⟨a⟩ ⟨b⟩; exact quotient.sound (univ_mem_sets' $ assume a, add_comm _ _),
.. ae_eq_fun.add_monoid }
end add_comm_monoid
section add_group
variables {γ : Type*} [topological_space γ] [measurable_space γ] [borel_space γ]
[add_group γ] [topological_add_group γ]
instance : has_neg (α →ₘ γ) := ⟨comp has_neg.neg measurable_id.neg⟩
@[simp] lemma neg_mk (f : α → γ) (hf) : -(mk f hf) = mk (-f) (measurable.neg hf) := rfl
lemma neg_to_fun (f : α →ₘ γ) : ∀ₘ a, (-f).to_fun a = - f.to_fun a := comp_to_fun _ _ _
variables [second_countable_topology γ]
instance : add_group (α →ₘ γ) :=
{ neg := has_neg.neg,
add_left_neg := by rintros ⟨a⟩; exact quotient.sound (ae_of_all _ $ assume a, add_left_neg _),
.. ae_eq_fun.add_monoid }
@[simp] lemma mk_sub_mk (f g : α → γ) (hf hg) :
(mk f hf) - (mk g hg) = mk (λa, (f a) - (g a)) (measurable.sub hf hg) := rfl
lemma sub_to_fun (f g : α →ₘ γ) : ∀ₘ a, (f - g).to_fun a = f.to_fun a - g.to_fun a :=
begin
rw sub_eq_add_neg,
filter_upwards [add_to_fun f (-g), neg_to_fun g],
assume a,
simp only [mem_set_of_eq],
repeat {assume h, rw h},
refl
end
end add_group
section add_comm_group
variables {γ : Type*}
[topological_space γ] [second_countable_topology γ] [measurable_space γ] [borel_space γ]
[add_comm_group γ] [topological_add_group γ]
instance : add_comm_group (α →ₘ γ) :=
{ .. ae_eq_fun.add_group, .. ae_eq_fun.add_comm_monoid }
end add_comm_group
section semimodule
variables {𝕜 : Type*} [semiring 𝕜] [topological_space 𝕜]
variables {γ : Type*} [topological_space γ] [measurable_space γ] [borel_space γ]
[add_comm_monoid γ] [semimodule 𝕜 γ] [topological_semimodule 𝕜 γ]
instance : has_scalar 𝕜 (α →ₘ γ) :=
⟨λ c f, comp (has_scalar.smul c) (measurable_id.const_smul _) f⟩
@[simp] lemma smul_mk (c : 𝕜) (f : α → γ) (hf) :
c • (mk f hf) = mk (c • f) (hf.const_smul _) :=
rfl
lemma smul_to_fun (c : 𝕜) (f : α →ₘ γ) : ∀ₘ a, (c • f).to_fun a = c • f.to_fun a :=
comp_to_fun _ _ _
variables [second_countable_topology γ] [topological_add_monoid γ]
instance : semimodule 𝕜 (α →ₘ γ) :=
{ one_smul := by { rintros ⟨f, hf⟩, simp only [quot_mk_eq_mk, smul_mk, one_smul] },
mul_smul :=
by { rintros x y ⟨f, hf⟩, simp only [quot_mk_eq_mk, smul_mk, mul_action.mul_smul x y f], refl },
smul_add :=
begin
rintros x ⟨f, hf⟩ ⟨g, hg⟩, simp only [quot_mk_eq_mk, smul_mk, mk_add_mk],
congr, exact smul_add x f g
end,
smul_zero := by { intro x, simp only [zero_def, smul_mk], congr, exact smul_zero x },
add_smul :=
begin
intros x y, rintro ⟨f, hf⟩, simp only [quot_mk_eq_mk, smul_mk, mk_add_mk], congr,
exact add_smul x y f
end,
zero_smul :=
by { rintro ⟨f, hf⟩, simp only [quot_mk_eq_mk, smul_mk, zero_def], congr, exact zero_smul 𝕜 f }}
instance : mul_action 𝕜 (α →ₘ γ) := by apply_instance
end semimodule
/- TODO : Prove that `L⁰` is a complete space if the codomain is complete. -/
/- TODO : Multiplicative structure of `L⁰` if useful -/
open ennreal
/-- For `f : α → ennreal`, Define `∫ [f]` to be `∫ f` -/
def eintegral (f : α →ₘ ennreal) : ennreal :=
quotient.lift_on f (λf, lintegral f.1) (assume ⟨f, hf⟩ ⟨g, hg⟩ eq, lintegral_congr_ae eq)
@[simp] lemma eintegral_mk (f : α → ennreal) (hf) : eintegral (mk f hf) = lintegral f := rfl
lemma eintegral_to_fun (f : α →ₘ ennreal) : eintegral f = lintegral (f.to_fun) :=
by conv_lhs { rw [self_eq_mk f, eintegral_mk] }
@[simp] lemma eintegral_zero : eintegral (0 : α →ₘ ennreal) = 0 := lintegral_zero
@[simp] lemma eintegral_eq_zero_iff (f : α →ₘ ennreal) : eintegral f = 0 ↔ f = 0 :=
begin
rcases f with ⟨f, hf⟩,
refine iff.trans (lintegral_eq_zero_iff hf) ⟨_, _⟩,
{ assume h, exact quotient.sound h },
{ assume h, exact quotient.exact h }
end
lemma eintegral_add : ∀(f g : α →ₘ ennreal), eintegral (f + g) = eintegral f + eintegral g :=
by { rintros ⟨f⟩ ⟨g⟩, simp only [quot_mk_eq_mk, mk_add_mk, eintegral_mk], exact lintegral_add f.2 g.2 }
lemma eintegral_le_eintegral {f g : α →ₘ ennreal} (h : f ≤ g) : eintegral f ≤ eintegral g :=
begin
rcases f with ⟨f, hf⟩, rcases g with ⟨g, hg⟩,
simp only [quot_mk_eq_mk, eintegral_mk, mk_le_mk] at *,
refine lintegral_le_lintegral_ae _,
filter_upwards [h], simp
end
section
variables {γ : Type*} [emetric_space γ] [second_countable_topology γ] [measurable_space γ]
[opens_measurable_space γ]
/-- `comp_edist [f] [g] a` will return `edist (f a) (g a) -/
def comp_edist (f g : α →ₘ γ) : α →ₘ ennreal := comp₂ edist measurable_edist f g
lemma comp_edist_to_fun (f g : α →ₘ γ) :
∀ₘ a, (comp_edist f g).to_fun a = edist (f.to_fun a) (g.to_fun a) :=
comp₂_to_fun _ _ _ _
lemma comp_edist_self : ∀ (f : α →ₘ γ), comp_edist f f = 0 :=
by rintro ⟨f⟩; refine quotient.sound _; simp only [edist_self]
/-- Almost everywhere equal functions form an `emetric_space`, with the emetric defined as
`edist f g = ∫⁻ a, edist (f a) (g a)`. -/
instance : emetric_space (α →ₘ γ) :=
{ edist := λf g, eintegral (comp_edist f g),
edist_self := assume f, (eintegral_eq_zero_iff _).2 (comp_edist_self _),
edist_comm :=
by rintros ⟨f⟩ ⟨g⟩; simp only [comp_edist, quot_mk_eq_mk, comp₂_mk_mk, edist_comm],
edist_triangle :=
begin
rintros ⟨f⟩ ⟨g⟩ ⟨h⟩,
simp only [comp_edist, quot_mk_eq_mk, comp₂_mk_mk, (eintegral_add _ _).symm],
exact lintegral_mono (assume a, edist_triangle _ _ _)
end,
eq_of_edist_eq_zero :=
begin
rintros ⟨f⟩ ⟨g⟩,
simp only [edist, comp_edist, quot_mk_eq_mk, comp₂_mk_mk, eintegral_eq_zero_iff],
simp only [zero_def, mk_eq_mk, edist_eq_zero],
assume h, assumption
end }
lemma edist_mk_mk {f g : α → γ} (hf hg) : edist (mk f hf) (mk g hg) = ∫⁻ x, edist (f x) (g x) := rfl
lemma edist_to_fun (f g : α →ₘ γ) : edist f g = ∫⁻ x, edist (f.to_fun x) (g.to_fun x) :=
by conv_lhs { rw [self_eq_mk f, self_eq_mk g, edist_mk_mk] }
lemma edist_zero_to_fun [has_zero γ] (f : α →ₘ γ) : edist f 0 = ∫⁻ x, edist (f.to_fun x) 0 :=
begin
rw edist_to_fun,
apply lintegral_congr_ae,
have : ∀ₘ a:α, (0 : α →ₘ γ).to_fun a = 0 := zero_to_fun,
filter_upwards [this],
assume a h,
simp only [mem_set_of_eq] at *,
rw h
end
end
section metric
variables {γ : Type*} [metric_space γ] [second_countable_topology γ] [measurable_space γ]
[opens_measurable_space γ]
lemma edist_mk_mk' {f g : α → γ} (hf hg) :
edist (mk f hf) (mk g hg) = ∫⁻ x, nndist (f x) (g x) :=
show (∫⁻ x, edist (f x) (g x)) = ∫⁻ x, nndist (f x) (g x), from
lintegral_congr_ae $ ae_of_all _ $ assume a, edist_nndist _ _
lemma edist_to_fun' (f g : α →ₘ γ) : edist f g = ∫⁻ x, nndist (f.to_fun x) (g.to_fun x) :=
by conv_lhs { rw [self_eq_mk f, self_eq_mk g, edist_mk_mk'] }
end metric
section normed_group
variables {γ : Type*} [normed_group γ] [second_countable_topology γ] [measurable_space γ]
[borel_space γ]
lemma edist_eq_add_add : ∀ {f g h : α →ₘ γ}, edist f g = edist (f + h) (g + h) :=
begin
rintros ⟨f⟩ ⟨g⟩ ⟨h⟩,
simp only [quot_mk_eq_mk, mk_add_mk, edist_mk_mk'],
apply lintegral_congr_ae,
filter_upwards [], simp [nndist_eq_nnnorm]
end
end normed_group
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜]
variables {γ : Type*} [normed_group γ] [second_countable_topology γ] [normed_space 𝕜 γ]
[measurable_space γ] [borel_space γ]
lemma edist_smul (x : 𝕜) : ∀ f : α →ₘ γ, edist (x • f) 0 = (ennreal.of_real ∥x∥) * edist f 0 :=
begin
rintros ⟨f, hf⟩, simp only [zero_def, edist_mk_mk', quot_mk_eq_mk, smul_mk],
exact calc
(∫⁻ (a : α), nndist (x • f a) 0) = (∫⁻ (a : α), (nnnorm x) * nnnorm (f a)) :
lintegral_congr_ae $ by { filter_upwards [], assume a, simp [nndist_eq_nnnorm, nnnorm_smul] }
... = _ : lintegral_const_mul _ hf.ennnorm
... = _ :
begin
convert rfl,
{ rw ← coe_nnnorm, rw [ennreal.of_real], congr, exact nnreal.of_real_coe },
{ funext, simp [nndist_eq_nnnorm] }
end,
end
end normed_space
section pos_part
variables {γ : Type*} [topological_space γ] [decidable_linear_order γ] [order_closed_topology γ]
[second_countable_topology γ] [has_zero γ] [measurable_space γ] [opens_measurable_space γ]
/-- Positive part of an `ae_eq_fun`. -/
def pos_part (f : α →ₘ γ) : α →ₘ γ :=
comp₂ max (measurable_id.fst.max measurable_id.snd) f 0
lemma pos_part_to_fun (f : α →ₘ γ) : ∀ₘ a, (pos_part f).to_fun a = max (f.to_fun a) (0:γ) :=
begin
filter_upwards [comp₂_to_fun max (measurable_id.fst.max measurable_id.snd) f 0,
@ae_eq_fun.zero_to_fun α γ],
simp only [mem_set_of_eq],
assume a h₁ h₂,
rw [pos_part, h₁, h₂]
end
end pos_part
end ae_eq_fun
end measure_theory
|
c9941e9ff6d84b3786a1550c6aa12c9b24db5791 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/set_theory/ordinal_arithmetic.lean | a4f9f5128fb7c46dc603810ae8f39b50ae8a0a7c | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 70,433 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn
-/
import set_theory.ordinal
/-!
# Ordinal arithmetic
Ordinals have an addition (corresponding to disjoint union) that turns them into an additive
monoid, and a multiplication (corresponding to the lexicographic order on the product) that turns
them into a monoid. One can also define correspondingly a subtraction, a division, a successor
function, a power function and a logarithm function.
We also define limit ordinals and prove the basic induction principle on ordinals separating
successor ordinals and limit ordinals, in `limit_rec_on`.
## Main definitions and results
* `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that
every element of `o₁` is smaller than every element of `o₂`.
* `o₁ - o₂` is the unique ordinal `o` such that `o₂ + o = o₁`, when `o₂ ≤ o₁`.
* `o₁ * o₂` is the lexicographic order on `o₂ × o₁`.
* `o₁ / o₂` is the ordinal `o` such that `o₁ = o₂ * o + o'` with `o' < o₂`. We also define the
divisibility predicate, and a modulo operation.
* `succ o = o + 1` is the successor of `o`.
* `pred o` if the predecessor of `o`. If `o` is not a successor, we set `pred o = o`.
We also define the power function and the logarithm function on ordinals, and discuss the properties
of casts of natural numbers of and of `omega` with respect to these operations.
Some properties of the operations are also used to discuss general tools on ordinals:
* `is_limit o`: an ordinal is a limit ordinal if it is neither `0` nor a successor.
* `limit_rec_on` is the main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals.
* `is_normal`: a function `f : ordinal → ordinal` satisfies `is_normal` if it is strictly increasing
and order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`.
* `nfp f a`: the next fixed point of a function `f` on ordinals, above `a`. It behaves well
for normal functions.
* `CNF b o` is the Cantor normal form of the ordinal `o` in base `b`.
* `sup`: the supremum of an indexed family of ordinals in `Type u`, as an ordinal in `Type u`.
* `bsup`: the supremum of a set of ordinals indexed by ordinals less than a given ordinal `o`.
-/
noncomputable theory
open function cardinal set equiv
open_locale classical cardinal
universes u v w
variables {α : Type*} {β : Type*} {γ : Type*}
{r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
namespace ordinal
/-! ### Further properties of addition on ordinals -/
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans
(rel_iso.sum_lex_congr (rel_iso.preimage equiv.ulift _)
(rel_iso.preimage equiv.ulift _)).symm⟩
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
by unfold succ; simp only [lift_add, lift_one]
theorem add_le_add_iff_left (a) {b c : ordinal} : a + b ≤ a + c ↔ b ≤ c :=
⟨induction_on a $ λ α r hr, induction_on b $ λ β₁ s₁ hs₁, induction_on c $ λ β₂ s₂ hs₂ ⟨f⟩, ⟨
have fl : ∀ a, f (sum.inl a) = sum.inl a := λ a,
by simpa only [initial_seg.trans_apply, initial_seg.le_add_apply]
using @initial_seg.eq _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr hs₂)
((initial_seg.le_add r s₁).trans f) (initial_seg.le_add r s₂) a,
have ∀ b, {b' // f (sum.inr b) = sum.inr b'}, begin
intro b, cases e : f (sum.inr b),
{ rw ← fl at e, have := f.inj' e, contradiction },
{ exact ⟨_, rfl⟩ }
end,
let g (b) := (this b).1 in
have fr : ∀ b, f (sum.inr b) = sum.inr (g b), from λ b, (this b).2,
⟨⟨⟨g, λ x y h, by injection f.inj'
(by rw [fr, fr, h] : f (sum.inr x) = f (sum.inr y))⟩,
λ a b, by simpa only [sum.lex_inr_inr, fr, rel_embedding.coe_fn_to_embedding,
initial_seg.coe_fn_to_rel_embedding, function.embedding.coe_fn_mk]
using @rel_embedding.map_rel_iff _ _ _ _ f.to_rel_embedding (sum.inr a) (sum.inr b)⟩,
λ a b H, begin
rcases f.init' (by rw fr; exact sum.lex_inr_inr.2 H) with ⟨a'|a', h⟩,
{ rw fl at h, cases h },
{ rw fr at h, exact ⟨a', sum.inr.inj h⟩ }
end⟩⟩,
λ h, add_le_add_left h _⟩
theorem add_succ (o₁ o₂ : ordinal) : o₁ + succ o₂ = succ (o₁ + o₂) :=
(add_assoc _ _ _).symm
@[simp] theorem succ_zero : succ 0 = 1 := zero_add _
theorem one_le_iff_pos {o : ordinal} : 1 ≤ o ↔ 0 < o :=
by rw [← succ_zero, succ_le]
theorem one_le_iff_ne_zero {o : ordinal} : 1 ≤ o ↔ o ≠ 0 :=
by rw [one_le_iff_pos, ordinal.pos_iff_ne_zero]
theorem succ_pos (o : ordinal) : 0 < succ o :=
lt_of_le_of_lt (ordinal.zero_le _) (lt_succ_self _)
theorem succ_ne_zero (o : ordinal) : succ o ≠ 0 :=
ne_of_gt $ succ_pos o
@[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 :=
by simp only [succ, card_add, card_one]
theorem nat_cast_succ (n : ℕ) : (succ n : ordinal) = n.succ := rfl
theorem add_left_cancel (a) {b c : ordinal} : a + b = a + c ↔ b = c :=
by simp only [le_antisymm_iff, add_le_add_iff_left]
theorem lt_succ {a b : ordinal} : a < succ b ↔ a ≤ b :=
by rw [← not_le, succ_le, not_lt]
theorem add_lt_add_iff_left (a) {b c : ordinal} : a + b < a + c ↔ b < c :=
by rw [← not_le, ← not_le, add_le_add_iff_left]
theorem lt_of_add_lt_add_right {a b c : ordinal} : a + b < c + b → a < c :=
lt_imp_lt_of_le_imp_le (λ h, add_le_add_right h _)
@[simp] theorem succ_lt_succ {a b : ordinal} : succ a < succ b ↔ a < b :=
by rw [lt_succ, succ_le]
@[simp] theorem succ_le_succ {a b : ordinal} : succ a ≤ succ b ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 succ_lt_succ
theorem succ_inj {a b : ordinal} : succ a = succ b ↔ a = b :=
by simp only [le_antisymm_iff, succ_le_succ]
theorem add_le_add_iff_right {a b : ordinal} (n : ℕ) : a + n ≤ b + n ↔ a ≤ b :=
by induction n with n ih; [rw [nat.cast_zero, add_zero, add_zero],
rw [← nat_cast_succ, add_succ, add_succ, succ_le_succ, ih]]
theorem add_right_cancel {a b : ordinal} (n : ℕ) : a + n = b + n ↔ a = b :=
by simp only [le_antisymm_iff, add_le_add_iff_right]
/-! ### The zero ordinal -/
@[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 :=
⟨induction_on o $ λ α r _ h, begin
refine le_antisymm (le_of_not_lt $
λ hn, ne_zero_iff_nonempty.2 _ h) (ordinal.zero_le _),
rw [← succ_le, succ_zero] at hn, cases hn with f,
exact ⟨f punit.star⟩
end, λ e, by simp only [e, card_zero]⟩
@[simp] theorem type_eq_zero_of_empty [is_well_order α r] [is_empty α] : type r = 0 :=
card_eq_zero.symm.mpr eq_zero_of_is_empty
@[simp] theorem type_eq_zero_iff_is_empty [is_well_order α r] : type r = 0 ↔ is_empty α :=
(@card_eq_zero (type r)).symm.trans eq_zero_iff_is_empty
theorem type_ne_zero_iff_nonempty [is_well_order α r] : type r ≠ 0 ↔ nonempty α :=
(not_congr (@card_eq_zero (type r))).symm.trans ne_zero_iff_nonempty
protected lemma one_ne_zero : (1 : ordinal) ≠ 0 :=
type_ne_zero_iff_nonempty.2 ⟨punit.star⟩
instance : nontrivial ordinal.{u} :=
⟨⟨1, 0, ordinal.one_ne_zero⟩⟩
theorem zero_lt_one : (0 : ordinal) < 1 :=
lt_iff_le_and_ne.2 ⟨ordinal.zero_le _, ne.symm $ ordinal.one_ne_zero⟩
/-! ### The predecessor of an ordinal -/
/-- The ordinal predecessor of `o` is `o'` if `o = succ o'`,
and `o` otherwise. -/
def pred (o : ordinal.{u}) : ordinal.{u} :=
if h : ∃ a, o = succ a then classical.some h else o
@[simp] theorem pred_succ (o) : pred (succ o) = o :=
by have h : ∃ a, succ o = succ a := ⟨_, rfl⟩;
simpa only [pred, dif_pos h] using (succ_inj.1 $ classical.some_spec h).symm
theorem pred_le_self (o) : pred o ≤ o :=
if h : ∃ a, o = succ a then let ⟨a, e⟩ := h in
by rw [e, pred_succ]; exact le_of_lt (lt_succ_self _)
else by rw [pred, dif_neg h]
theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬ ∃ a, o = succ a :=
⟨λ e ⟨a, e'⟩, by rw [e', pred_succ] at e; exact ne_of_lt (lt_succ_self _) e,
λ h, dif_neg h⟩
theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a :=
iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le])
(iff_not_comm.1 pred_eq_iff_not_succ).symm
theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a :=
⟨λ e, ⟨_, e.symm⟩, λ ⟨a, e⟩, by simp only [e, pred_succ]⟩
theorem succ_lt_of_not_succ {o} (h : ¬ ∃ a, o = succ a) {b} : succ b < o ↔ b < o :=
⟨lt_trans (lt_succ_self _), λ l,
lt_of_le_of_ne (succ_le.2 l) (λ e, h ⟨_, e.symm⟩)⟩
theorem lt_pred {a b} : a < pred b ↔ succ a < b :=
if h : ∃ a, b = succ a then let ⟨c, e⟩ := h in
by rw [e, pred_succ, succ_lt_succ]
else by simp only [pred, dif_neg h, succ_lt_of_not_succ h]
theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b :=
le_iff_le_iff_lt_iff_lt.2 lt_pred
@[simp] theorem lift_is_succ {o} : (∃ a, lift o = succ a) ↔ (∃ a, o = succ a) :=
⟨λ ⟨a, h⟩,
let ⟨b, e⟩ := lift_down $ show a ≤ lift o, from le_of_lt $
h.symm ▸ lt_succ_self _ in
⟨b, lift_inj.1 $ by rw [h, ← e, lift_succ]⟩,
λ ⟨a, h⟩, ⟨lift a, by simp only [h, lift_succ]⟩⟩
@[simp] theorem lift_pred (o) : lift (pred o) = pred (lift o) :=
if h : ∃ a, o = succ a then
by cases h with a e; simp only [e, pred_succ, lift_succ]
else by rw [pred_eq_iff_not_succ.2 h,
pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)]
/-! ### Limit ordinals -/
/-- A limit ordinal is an ordinal which is not zero and not a successor. -/
def is_limit (o : ordinal) : Prop := o ≠ 0 ∧ ∀ a < o, succ a < o
theorem not_zero_is_limit : ¬ is_limit 0
| ⟨h, _⟩ := h rfl
theorem not_succ_is_limit (o) : ¬ is_limit (succ o)
| ⟨_, h⟩ := lt_irrefl _ (h _ (lt_succ_self _))
theorem not_succ_of_is_limit {o} (h : is_limit o) : ¬ ∃ a, o = succ a
| ⟨a, e⟩ := not_succ_is_limit a (e ▸ h)
theorem succ_lt_of_is_limit {o} (h : is_limit o) {a} : succ a < o ↔ a < o :=
⟨lt_trans (lt_succ_self _), h.2 _⟩
theorem le_succ_of_is_limit {o} (h : is_limit o) {a} : o ≤ succ a ↔ o ≤ a :=
le_iff_le_iff_lt_iff_lt.2 $ succ_lt_of_is_limit h
theorem limit_le {o} (h : is_limit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a :=
⟨λ h x l, le_trans (le_of_lt l) h,
λ H, (le_succ_of_is_limit h).1 $ le_of_not_lt $ λ hn,
not_lt_of_le (H _ hn) (lt_succ_self _)⟩
theorem lt_limit {o} (h : is_limit o) {a} : a < o ↔ ∃ x < o, a < x :=
by simpa only [not_ball, not_le] using not_congr (@limit_le _ h a)
@[simp] theorem lift_is_limit (o) : is_limit (lift o) ↔ is_limit o :=
and_congr (not_congr $ by simpa only [lift_zero] using @lift_inj o 0)
⟨λ H a h, lift_lt.1 $ by simpa only [lift_succ] using H _ (lift_lt.2 h),
λ H a h, let ⟨a', e⟩ := lift_down (le_of_lt h) in
by rw [← e, ← lift_succ, lift_lt];
rw [← e, lift_lt] at h; exact H a' h⟩
theorem is_limit.pos {o : ordinal} (h : is_limit o) : 0 < o :=
lt_of_le_of_ne (ordinal.zero_le _) h.1.symm
theorem is_limit.one_lt {o : ordinal} (h : is_limit o) : 1 < o :=
by simpa only [succ_zero] using h.2 _ h.pos
theorem is_limit.nat_lt {o : ordinal} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o
| 0 := h.pos
| (n+1) := h.2 _ (is_limit.nat_lt n)
theorem zero_or_succ_or_limit (o : ordinal) :
o = 0 ∨ (∃ a, o = succ a) ∨ is_limit o :=
if o0 : o = 0 then or.inl o0 else
if h : ∃ a, o = succ a then or.inr (or.inl h) else
or.inr $ or.inr ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩
/-- Main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals. -/
@[elab_as_eliminator] def limit_rec_on {C : ordinal → Sort*}
(o : ordinal) (H₁ : C 0) (H₂ : ∀ o, C o → C (succ o))
(H₃ : ∀ o, is_limit o → (∀ o' < o, C o') → C o) : C o :=
wf.fix (λ o IH,
if o0 : o = 0 then by rw o0; exact H₁ else
if h : ∃ a, o = succ a then
by rw ← succ_pred_iff_is_succ.2 h; exact
H₂ _ (IH _ $ pred_lt_iff_is_succ.2 h)
else H₃ _ ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ IH) o
@[simp] theorem limit_rec_on_zero {C} (H₁ H₂ H₃) : @limit_rec_on C 0 H₁ H₂ H₃ = H₁ :=
by rw [limit_rec_on, well_founded.fix_eq, dif_pos rfl]; refl
@[simp] theorem limit_rec_on_succ {C} (o H₁ H₂ H₃) :
@limit_rec_on C (succ o) H₁ H₂ H₃ = H₂ o (@limit_rec_on C o H₁ H₂ H₃) :=
begin
have h : ∃ a, succ o = succ a := ⟨_, rfl⟩,
rw [limit_rec_on, well_founded.fix_eq,
dif_neg (succ_ne_zero o), dif_pos h],
generalize : limit_rec_on._proof_2 (succ o) h = h₂,
generalize : limit_rec_on._proof_3 (succ o) h = h₃,
revert h₂ h₃, generalize e : pred (succ o) = o', intros,
rw pred_succ at e, subst o', refl
end
@[simp] theorem limit_rec_on_limit {C} (o H₁ H₂ H₃ h) :
@limit_rec_on C o H₁ H₂ H₃ = H₃ o h (λ x h, @limit_rec_on C x H₁ H₂ H₃) :=
by rw [limit_rec_on, well_founded.fix_eq,
dif_neg h.1, dif_neg (not_succ_of_is_limit h)]; refl
lemma has_succ_of_is_limit {α} {r : α → α → Prop} [wo : is_well_order α r]
(h : (type r).is_limit) (x : α) : ∃y, r x y :=
begin
use enum r (typein r x).succ (h.2 _ (typein_lt_type r x)),
convert (enum_lt (typein_lt_type r x) _).mpr (lt_succ_self _), rw [enum_typein]
end
lemma type_subrel_lt (o : ordinal.{u}) :
type (subrel (<) {o' : ordinal | o' < o}) = ordinal.lift.{u u+1} o :=
begin
refine quotient.induction_on o _,
rintro ⟨α, r, wo⟩, resetI, apply quotient.sound,
constructor, symmetry, refine (rel_iso.preimage equiv.ulift r).trans (typein_iso r)
end
lemma mk_initial_seg (o : ordinal.{u}) :
#{o' : ordinal | o' < o} = cardinal.lift.{u u+1} o.card :=
by rw [lift_card, ←type_subrel_lt, card_type]
/-! ### Normal ordinal functions -/
/-- A normal ordinal function is a strictly increasing function which is
order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`. -/
def is_normal (f : ordinal → ordinal) : Prop :=
(∀ o, f o < f (succ o)) ∧ ∀ o, is_limit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a
theorem is_normal.limit_le {f} (H : is_normal f) : ∀ {o}, is_limit o →
∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a := H.2
theorem is_normal.limit_lt {f} (H : is_normal f) {o} (h : is_limit o) {a} :
a < f o ↔ ∃ b < o, a < f b :=
not_iff_not.1 $ by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a
theorem is_normal.lt_iff {f} (H : is_normal f) {a b} : f a < f b ↔ a < b :=
strict_mono.lt_iff_lt $ λ a b,
limit_rec_on b (not.elim (not_lt_of_le $ ordinal.zero_le _))
(λ b IH h, (lt_or_eq_of_le (lt_succ.1 h)).elim
(λ h, lt_trans (IH h) (H.1 _))
(λ e, e ▸ H.1 _))
(λ b l IH h, lt_of_lt_of_le (H.1 a)
((H.2 _ l _).1 (le_refl _) _ (l.2 _ h)))
theorem is_normal.le_iff {f} (H : is_normal f) {a b} : f a ≤ f b ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 H.lt_iff
theorem is_normal.inj {f} (H : is_normal f) {a b} : f a = f b ↔ a = b :=
by simp only [le_antisymm_iff, H.le_iff]
theorem is_normal.le_self {f} (H : is_normal f) (a) : a ≤ f a :=
limit_rec_on a (ordinal.zero_le _)
(λ a IH, succ_le.2 $ lt_of_le_of_lt IH (H.1 _))
(λ a l IH, (limit_le l).2 $ λ b h,
le_trans (IH b h) $ H.le_iff.2 $ le_of_lt h)
theorem is_normal.le_set {f} (H : is_normal f) (p : ordinal → Prop)
(p0 : ∃ x, p x) (S)
(H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → a ≤ o) {o} :
f S ≤ o ↔ ∀ a, p a → f a ≤ o :=
⟨λ h a pa, le_trans (H.le_iff.2 ((H₂ _).1 (le_refl _) _ pa)) h,
λ h, begin
revert H₂, apply limit_rec_on S,
{ intro H₂,
cases p0 with x px,
have := ordinal.le_zero.1 ((H₂ _).1 (ordinal.zero_le _) _ px),
rw this at px, exact h _ px },
{ intros S _ H₂,
rcases not_ball.1 (mt (H₂ S).2 $ not_le_of_lt $ lt_succ_self _) with ⟨a, h₁, h₂⟩,
exact le_trans (H.le_iff.2 $ succ_le.2 $ not_le.1 h₂) (h _ h₁) },
{ intros S L _ H₂, apply (H.2 _ L _).2, intros a h',
rcases not_ball.1 (mt (H₂ a).2 (not_le.2 h')) with ⟨b, h₁, h₂⟩,
exact le_trans (H.le_iff.2 $ le_of_lt $ not_le.1 h₂) (h _ h₁) }
end⟩
theorem is_normal.le_set' {f} (H : is_normal f) (p : α → Prop) (g : α → ordinal)
(p0 : ∃ x, p x) (S)
(H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → g a ≤ o) {o} :
f S ≤ o ↔ ∀ a, p a → f (g a) ≤ o :=
(H.le_set (λ x, ∃ y, p y ∧ x = g y)
(let ⟨x, px⟩ := p0 in ⟨_, _, px, rfl⟩) _
(λ o, (H₂ o).trans ⟨λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1,
λ H a h1, H (g a) ⟨a, h1, rfl⟩⟩)).trans
⟨λ H a h, H (g a) ⟨a, h, rfl⟩, λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1⟩
theorem is_normal.refl : is_normal id :=
⟨λ x, lt_succ_self _, λ o l a, limit_le l⟩
theorem is_normal.trans {f g} (H₁ : is_normal f) (H₂ : is_normal g) :
is_normal (λ x, f (g x)) :=
⟨λ x, H₁.lt_iff.2 (H₂.1 _),
λ o l a, H₁.le_set' (< o) g ⟨_, l.pos⟩ _ (λ c, H₂.2 _ l _)⟩
theorem is_normal.is_limit {f} (H : is_normal f) {o} (l : is_limit o) :
is_limit (f o) :=
⟨ne_of_gt $ lt_of_le_of_lt (ordinal.zero_le _) $ H.lt_iff.2 l.pos,
λ a h, let ⟨b, h₁, h₂⟩ := (H.limit_lt l).1 h in
lt_of_le_of_lt (succ_le.2 h₂) (H.lt_iff.2 h₁)⟩
theorem add_le_of_limit {a b c : ordinal.{u}}
(h : is_limit b) : a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c :=
⟨λ h b' l, le_trans (add_le_add_left (le_of_lt l) _) h,
λ H, le_of_not_lt $
induction_on a (λ α r _, induction_on b $ λ β s _ h H l, begin
resetI,
suffices : ∀ x : β, sum.lex r s (sum.inr x) (enum _ _ l),
{ cases enum _ _ l with x x,
{ cases this (enum s 0 h.pos) },
{ exact irrefl _ (this _) } },
intros x,
rw [← typein_lt_typein (sum.lex r s), typein_enum],
have := H _ (h.2 _ (typein_lt_type s x)),
rw [add_succ, succ_le] at this,
refine lt_of_le_of_lt (type_le'.2
⟨rel_embedding.of_monotone (λ a, _) (λ a b, _)⟩) this,
{ rcases a with ⟨a | b, h⟩,
{ exact sum.inl a },
{ exact sum.inr ⟨b, by cases h; assumption⟩ } },
{ rcases a with ⟨a | a, h₁⟩; rcases b with ⟨b | b, h₂⟩; cases h₁; cases h₂;
rintro ⟨⟩; constructor; assumption }
end) h H⟩
theorem add_is_normal (a : ordinal) : is_normal ((+) a) :=
⟨λ b, (add_lt_add_iff_left a).2 (lt_succ_self _),
λ b l c, add_le_of_limit l⟩
theorem add_is_limit (a) {b} : is_limit b → is_limit (a + b) :=
(add_is_normal a).is_limit
/-! ### Subtraction on ordinals-/
/-- `a - b` is the unique ordinal satisfying
`b + (a - b) = a` when `b ≤ a`. -/
def sub (a b : ordinal.{u}) : ordinal.{u} :=
omin {o | a ≤ b+o} ⟨a, le_add_left _ _⟩
instance : has_sub ordinal := ⟨sub⟩
theorem le_add_sub (a b : ordinal) : a ≤ b + (a - b) :=
omin_mem {o | a ≤ b+o} _
theorem sub_le {a b c : ordinal} : a - b ≤ c ↔ a ≤ b + c :=
⟨λ h, le_trans (le_add_sub a b) (add_le_add_left h _),
λ h, omin_le h⟩
theorem lt_sub {a b c : ordinal} : a < b - c ↔ c + a < b :=
lt_iff_lt_of_le_iff_le sub_le
theorem add_sub_cancel (a b : ordinal) : a + b - a = b :=
le_antisymm (sub_le.2 $ le_refl _)
((add_le_add_iff_left a).1 $ le_add_sub _ _)
theorem sub_eq_of_add_eq {a b c : ordinal} (h : a + b = c) : c - a = b :=
h ▸ add_sub_cancel _ _
theorem sub_le_self (a b : ordinal) : a - b ≤ a :=
sub_le.2 $ le_add_left _ _
theorem add_sub_cancel_of_le {a b : ordinal} (h : b ≤ a) : b + (a - b) = a :=
le_antisymm begin
rcases zero_or_succ_or_limit (a-b) with e|⟨c,e⟩|l,
{ simp only [e, add_zero, h] },
{ rw [e, add_succ, succ_le, ← lt_sub, e], apply lt_succ_self },
{ exact (add_le_of_limit l).2 (λ c l, le_of_lt (lt_sub.1 l)) }
end (le_add_sub _ _)
@[simp] theorem sub_zero (a : ordinal) : a - 0 = a :=
by simpa only [zero_add] using add_sub_cancel 0 a
@[simp] theorem zero_sub (a : ordinal) : 0 - a = 0 :=
by rw ← ordinal.le_zero; apply sub_le_self
@[simp] theorem sub_self (a : ordinal) : a - a = 0 :=
by simpa only [add_zero] using add_sub_cancel a 0
protected theorem sub_eq_zero_iff_le {a b : ordinal} : a - b = 0 ↔ a ≤ b :=
⟨λ h, by simpa only [h, add_zero] using le_add_sub a b,
λ h, by rwa [← ordinal.le_zero, sub_le, add_zero]⟩
theorem sub_sub (a b c : ordinal) : a - b - c = a - (b + c) :=
eq_of_forall_ge_iff $ λ d, by rw [sub_le, sub_le, sub_le, add_assoc]
theorem add_sub_add_cancel (a b c : ordinal) : a + b - (a + c) = b - c :=
by rw [← sub_sub, add_sub_cancel]
theorem sub_is_limit {a b} (l : is_limit a) (h : b < a) : is_limit (a - b) :=
⟨ne_of_gt $ lt_sub.2 $ by rwa add_zero,
λ c h, by rw [lt_sub, add_succ]; exact l.2 _ (lt_sub.1 h)⟩
@[simp] theorem one_add_omega : 1 + omega.{u} = omega :=
begin
refine le_antisymm _ (le_add_left _ _),
rw [omega, one_eq_lift_type_unit, ← lift_add, lift_le, type_add],
have : is_well_order unit empty_relation := by apply_instance,
refine ⟨rel_embedding.collapse (rel_embedding.of_monotone _ _)⟩,
{ apply sum.rec, exact λ _, 0, exact nat.succ },
{ intros a b, cases a; cases b; intro H; cases H with _ _ H _ _ H;
[cases H, exact nat.succ_pos _, exact nat.succ_lt_succ H] }
end
@[simp, priority 990]
theorem one_add_of_omega_le {o} (h : omega ≤ o) : 1 + o = o :=
by rw [← add_sub_cancel_of_le h, ← add_assoc, one_add_omega]
/-! ### Multiplication of ordinals-/
/-- The multiplication of ordinals `o₁` and `o₂` is the (well founded) lexicographic order on
`o₂ × o₁`. -/
instance : monoid ordinal.{u} :=
{ mul := λ a b, quotient.lift_on₂ a b
(λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨β × α, prod.lex s r, by exactI prod.lex.is_well_order⟩⟧
: Well_order → Well_order → ordinal) $
λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩,
quot.sound ⟨rel_iso.prod_lex_congr g f⟩,
one := 1,
mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩,
eq.symm $ quotient.sound ⟨⟨prod_assoc _ _ _, λ a b, begin
rcases a with ⟨⟨a₁, a₂⟩, a₃⟩,
rcases b with ⟨⟨b₁, b₂⟩, b₃⟩,
simp [prod.lex_def, and_or_distrib_left, or_assoc, and_assoc]
end⟩⟩,
mul_one := λ a, induction_on a $ λ α r _, quotient.sound
⟨⟨punit_prod _, λ a b, by rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩;
simp only [prod.lex_def, empty_relation, false_or];
simp only [eq_self_iff_true, true_and]; refl⟩⟩,
one_mul := λ a, induction_on a $ λ α r _, quotient.sound
⟨⟨prod_punit _, λ a b, by rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩;
simp only [prod.lex_def, empty_relation, and_false, or_false]; refl⟩⟩ }
@[simp] theorem type_mul {α β : Type u} (r : α → α → Prop) (s : β → β → Prop)
[is_well_order α r] [is_well_order β s] : type r * type s = type (prod.lex s r) := rfl
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans
(rel_iso.prod_lex_congr (rel_iso.preimage equiv.ulift _)
(rel_iso.preimage equiv.ulift _)).symm⟩
@[simp] theorem card_mul (a b) : card (a * b) = card a * card b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
mul_comm (mk β) (mk α)
@[simp] theorem mul_zero (a : ordinal) : a * 0 = 0 :=
induction_on a $ λ α _ _, by exactI type_eq_zero_of_empty
@[simp] theorem zero_mul (a : ordinal) : 0 * a = 0 :=
induction_on a $ λ α _ _, by exactI type_eq_zero_of_empty
theorem mul_add (a b c : ordinal) : a * (b + c) = a * b + a * c :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩,
quotient.sound ⟨⟨sum_prod_distrib _ _ _, begin
rintro ⟨a₁|a₁, a₂⟩ ⟨b₁|b₁, b₂⟩; simp only [prod.lex_def,
sum.lex_inl_inl, sum.lex.sep, sum.lex_inr_inl, sum.lex_inr_inr,
sum_prod_distrib_apply_left, sum_prod_distrib_apply_right];
simp only [sum.inl.inj_iff, true_or, false_and, false_or]
end⟩⟩
@[simp] theorem mul_add_one (a b : ordinal) : a * (b + 1) = a * b + a :=
by simp only [mul_add, mul_one]
@[simp] theorem mul_succ (a b : ordinal) : a * succ b = a * b + a := mul_add_one _ _
theorem mul_le_mul_left {a b} (c : ordinal) : a ≤ b → c * a ≤ c * b :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin
resetI,
refine type_le'.2 ⟨rel_embedding.of_monotone
(λ a, (f a.1, a.2))
(λ a b h, _)⟩, clear_,
cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h',
{ exact prod.lex.left _ _ (f.to_rel_embedding.map_rel_iff.2 h') },
{ exact prod.lex.right _ h' }
end
theorem mul_le_mul_right {a b} (c : ordinal) : a ≤ b → a * c ≤ b * c :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin
resetI,
refine type_le'.2 ⟨rel_embedding.of_monotone
(λ a, (a.1, f a.2))
(λ a b h, _)⟩,
cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h',
{ exact prod.lex.left _ _ h' },
{ exact prod.lex.right _ (f.to_rel_embedding.map_rel_iff.2 h') }
end
theorem mul_le_mul {a b c d : ordinal} (h₁ : a ≤ c) (h₂ : b ≤ d) : a * b ≤ c * d :=
le_trans (mul_le_mul_left _ h₂) (mul_le_mul_right _ h₁)
private lemma mul_le_of_limit_aux {α β r s} [is_well_order α r] [is_well_order β s]
{c} (h : is_limit (type s)) (H : ∀ b' < type s, type r * b' ≤ c)
(l : c < type r * type s) : false :=
begin
suffices : ∀ a b, prod.lex s r (b, a) (enum _ _ l),
{ cases enum _ _ l with b a, exact irrefl _ (this _ _) },
intros a b,
rw [← typein_lt_typein (prod.lex s r), typein_enum],
have := H _ (h.2 _ (typein_lt_type s b)),
rw [mul_succ] at this,
have := lt_of_lt_of_le ((add_lt_add_iff_left _).2
(typein_lt_type _ a)) this,
refine lt_of_le_of_lt _ this,
refine (type_le'.2 _),
constructor,
refine rel_embedding.of_monotone (λ a, _) (λ a b, _),
{ rcases a with ⟨⟨b', a'⟩, h⟩,
by_cases e : b = b',
{ refine sum.inr ⟨a', _⟩,
subst e, cases h with _ _ _ _ h _ _ _ h,
{ exact (irrefl _ h).elim },
{ exact h } },
{ refine sum.inl (⟨b', _⟩, a'),
cases h with _ _ _ _ h _ _ _ h,
{ exact h }, { exact (e rfl).elim } } },
{ rcases a with ⟨⟨b₁, a₁⟩, h₁⟩,
rcases b with ⟨⟨b₂, a₂⟩, h₂⟩,
intro h, by_cases e₁ : b = b₁; by_cases e₂ : b = b₂,
{ substs b₁ b₂,
simpa only [subrel_val, prod.lex_def, @irrefl _ s _ b, true_and, false_or, eq_self_iff_true,
dif_pos, sum.lex_inr_inr] using h },
{ subst b₁,
simp only [subrel_val, prod.lex_def, e₂, prod.lex_def, dif_pos, subrel_val, eq_self_iff_true,
or_false, dif_neg, not_false_iff, sum.lex_inr_inl, false_and] at h ⊢,
cases h₂; [exact asymm h h₂_h, exact e₂ rfl] },
{ simp only [e₂, dif_pos, eq_self_iff_true, dif_neg e₁, not_false_iff, sum.lex.sep] },
{ simpa only [dif_neg e₁, dif_neg e₂, prod.lex_def, subrel_val, subtype.mk_eq_mk,
sum.lex_inl_inl] using h } }
end
theorem mul_le_of_limit {a b c : ordinal.{u}}
(h : is_limit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c :=
⟨λ h b' l, le_trans (mul_le_mul_left _ (le_of_lt l)) h,
λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _,
by exactI mul_le_of_limit_aux) h H⟩
theorem mul_is_normal {a : ordinal} (h : 0 < a) : is_normal ((*) a) :=
⟨λ b, by rw mul_succ; simpa only [add_zero] using (add_lt_add_iff_left (a*b)).2 h,
λ b l c, mul_le_of_limit l⟩
theorem lt_mul_of_limit {a b c : ordinal.{u}}
(h : is_limit c) : a < b * c ↔ ∃ c' < c, a < b * c' :=
by simpa only [not_ball, not_le] using not_congr (@mul_le_of_limit b c a h)
theorem mul_lt_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c :=
(mul_is_normal a0).lt_iff
theorem mul_le_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c :=
(mul_is_normal a0).le_iff
theorem mul_lt_mul_of_pos_left {a b c : ordinal}
(h : a < b) (c0 : 0 < c) : c * a < c * b :=
(mul_lt_mul_iff_left c0).2 h
theorem mul_pos {a b : ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b :=
by simpa only [mul_zero] using mul_lt_mul_of_pos_left h₂ h₁
theorem mul_ne_zero {a b : ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 :=
by simpa only [ordinal.pos_iff_ne_zero] using mul_pos
theorem le_of_mul_le_mul_left {a b c : ordinal}
(h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b :=
le_imp_le_of_lt_imp_lt (λ h', mul_lt_mul_of_pos_left h' h0) h
theorem mul_right_inj {a b c : ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c :=
(mul_is_normal a0).inj
theorem mul_is_limit {a b : ordinal}
(a0 : 0 < a) : is_limit b → is_limit (a * b) :=
(mul_is_normal a0).is_limit
theorem mul_is_limit_left {a b : ordinal}
(l : is_limit a) (b0 : 0 < b) : is_limit (a * b) :=
begin
rcases zero_or_succ_or_limit b with rfl|⟨b,rfl⟩|lb,
{ exact (lt_irrefl _).elim b0 },
{ rw mul_succ, exact add_is_limit _ l },
{ exact mul_is_limit l.pos lb }
end
/-! ### Division on ordinals -/
protected lemma div_aux (a b : ordinal.{u}) (h : b ≠ 0) : set.nonempty {o | a < b * succ o} :=
⟨a, succ_le.1 $
by simpa only [succ_zero, one_mul]
using mul_le_mul_right (succ a) (succ_le.2 (ordinal.pos_iff_ne_zero.2 h))⟩
/-- `a / b` is the unique ordinal `o` satisfying
`a = b * o + o'` with `o' < b`. -/
protected def div (a b : ordinal.{u}) : ordinal.{u} :=
if h : b = 0 then 0 else omin {o | a < b * succ o} (ordinal.div_aux a b h)
instance : has_div ordinal := ⟨ordinal.div⟩
@[simp] theorem div_zero (a : ordinal) : a / 0 = 0 := dif_pos rfl
lemma div_def (a) {b : ordinal} (h : b ≠ 0) :
a / b = omin {o | a < b * succ o} (ordinal.div_aux a b h) := dif_neg h
theorem lt_mul_succ_div (a) {b : ordinal} (h : b ≠ 0) : a < b * succ (a / b) :=
by rw div_def a h; exact omin_mem {o | a < b * succ o} _
theorem lt_mul_div_add (a) {b : ordinal} (h : b ≠ 0) : a < b * (a / b) + b :=
by simpa only [mul_succ] using lt_mul_succ_div a h
theorem div_le {a b c : ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c :=
⟨λ h, lt_of_lt_of_le (lt_mul_succ_div a b0) (mul_le_mul_left _ $ succ_le_succ.2 h),
λ h, by rw div_def a b0; exact omin_le h⟩
theorem lt_div {a b c : ordinal} (c0 : c ≠ 0) : a < b / c ↔ c * succ a ≤ b :=
by rw [← not_le, div_le c0, not_lt]
theorem le_div {a b c : ordinal} (c0 : c ≠ 0) :
a ≤ b / c ↔ c * a ≤ b :=
begin
apply limit_rec_on a,
{ simp only [mul_zero, ordinal.zero_le] },
{ intros, rw [succ_le, lt_div c0] },
{ simp only [mul_le_of_limit, limit_le, iff_self, forall_true_iff] {contextual := tt} }
end
theorem div_lt {a b c : ordinal} (b0 : b ≠ 0) :
a / b < c ↔ a < b * c :=
lt_iff_lt_of_le_iff_le $ le_div b0
theorem div_le_of_le_mul {a b c : ordinal} (h : a ≤ b * c) : a / b ≤ c :=
if b0 : b = 0 then by simp only [b0, div_zero, ordinal.zero_le] else
(div_le b0).2 $ lt_of_le_of_lt h $
mul_lt_mul_of_pos_left (lt_succ_self _) (ordinal.pos_iff_ne_zero.2 b0)
theorem mul_lt_of_lt_div {a b c : ordinal} : a < b / c → c * a < b :=
lt_imp_lt_of_le_imp_le div_le_of_le_mul
@[simp] theorem zero_div (a : ordinal) : 0 / a = 0 :=
ordinal.le_zero.1 $ div_le_of_le_mul $ ordinal.zero_le _
theorem mul_div_le (a b : ordinal) : b * (a / b) ≤ a :=
if b0 : b = 0 then by simp only [b0, zero_mul, ordinal.zero_le] else (le_div b0).1 (le_refl _)
theorem mul_add_div (a) {b : ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b :=
begin
apply le_antisymm,
{ apply (div_le b0).2,
rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left],
apply lt_mul_div_add _ b0 },
{ rw [le_div b0, mul_add, add_le_add_iff_left],
apply mul_div_le }
end
theorem div_eq_zero_of_lt {a b : ordinal} (h : a < b) : a / b = 0 :=
begin
rw [← ordinal.le_zero, div_le $ ordinal.pos_iff_ne_zero.1 $ lt_of_le_of_lt (ordinal.zero_le _) h],
simpa only [succ_zero, mul_one] using h
end
@[simp] theorem mul_div_cancel (a) {b : ordinal} (b0 : b ≠ 0) : b * a / b = a :=
by simpa only [add_zero, zero_div] using mul_add_div a b0 0
@[simp] theorem div_one (a : ordinal) : a / 1 = a :=
by simpa only [one_mul] using mul_div_cancel a ordinal.one_ne_zero
@[simp] theorem div_self {a : ordinal} (h : a ≠ 0) : a / a = 1 :=
by simpa only [mul_one] using mul_div_cancel 1 h
theorem mul_sub (a b c : ordinal) : a * (b - c) = a * b - a * c :=
if a0 : a = 0 then by simp only [a0, zero_mul, sub_self] else
eq_of_forall_ge_iff $ λ d,
by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0]
theorem is_limit_add_iff {a b} : is_limit (a + b) ↔ is_limit b ∨ (b = 0 ∧ is_limit a) :=
begin
split; intro h,
{ by_cases h' : b = 0,
{ rw [h', add_zero] at h, right, exact ⟨h', h⟩ },
left, rw [←add_sub_cancel a b], apply sub_is_limit h,
suffices : a + 0 < a + b, simpa only [add_zero],
rwa [add_lt_add_iff_left, ordinal.pos_iff_ne_zero] },
rcases h with h|⟨rfl, h⟩, exact add_is_limit a h, simpa only [add_zero]
end
theorem dvd_add_iff : ∀ {a b c : ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c)
| a _ c ⟨b, rfl⟩ :=
⟨λ ⟨d, e⟩, ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩,
λ ⟨d, e⟩, by { rw [e, ← mul_add], apply dvd_mul_right }⟩
theorem dvd_add {a b c : ordinal} (h₁ : a ∣ b) : a ∣ c → a ∣ b + c :=
(dvd_add_iff h₁).2
theorem dvd_zero (a : ordinal) : a ∣ 0 := ⟨_, (mul_zero _).symm⟩
theorem zero_dvd {a : ordinal} : 0 ∣ a ↔ a = 0 :=
⟨λ ⟨h, e⟩, by simp only [e, zero_mul], λ e, e.symm ▸ dvd_zero _⟩
theorem one_dvd (a : ordinal) : 1 ∣ a := ⟨a, (one_mul _).symm⟩
theorem div_mul_cancel : ∀ {a b : ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b
| a _ a0 ⟨b, rfl⟩ := by rw [mul_div_cancel _ a0]
theorem le_of_dvd : ∀ {a b : ordinal}, b ≠ 0 → a ∣ b → a ≤ b
| a _ b0 ⟨b, rfl⟩ := by simpa only [mul_one] using mul_le_mul_left a
(one_le_iff_ne_zero.2 (λ h : b = 0, by simpa only [h, mul_zero] using b0))
theorem dvd_antisymm {a b : ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b :=
if a0 : a = 0 then by subst a; exact (zero_dvd.1 h₁).symm else
if b0 : b = 0 then by subst b; exact zero_dvd.1 h₂ else
le_antisymm (le_of_dvd b0 h₁) (le_of_dvd a0 h₂)
/-- `a % b` is the unique ordinal `o'` satisfying
`a = b * o + o'` with `o' < b`. -/
instance : has_mod ordinal := ⟨λ a b, a - b * (a / b)⟩
theorem mod_def (a b : ordinal) : a % b = a - b * (a / b) := rfl
@[simp] theorem mod_zero (a : ordinal) : a % 0 = a :=
by simp only [mod_def, div_zero, zero_mul, sub_zero]
theorem mod_eq_of_lt {a b : ordinal} (h : a < b) : a % b = a :=
by simp only [mod_def, div_eq_zero_of_lt h, mul_zero, sub_zero]
@[simp] theorem zero_mod (b : ordinal) : 0 % b = 0 :=
by simp only [mod_def, zero_div, mul_zero, sub_self]
theorem div_add_mod (a b : ordinal) : b * (a / b) + a % b = a :=
add_sub_cancel_of_le $ mul_div_le _ _
theorem mod_lt (a) {b : ordinal} (h : b ≠ 0) : a % b < b :=
(add_lt_add_iff_left (b * (a / b))).1 $
by rw div_add_mod; exact lt_mul_div_add a h
@[simp] theorem mod_self (a : ordinal) : a % a = 0 :=
if a0 : a = 0 then by simp only [a0, zero_mod] else
by simp only [mod_def, div_self a0, mul_one, sub_self]
@[simp] theorem mod_one (a : ordinal) : a % 1 = 0 :=
by simp only [mod_def, div_one, one_mul, sub_self]
/-! ### Supremum of a family of ordinals -/
/-- The supremum of a family of ordinals -/
def sup {ι} (f : ι → ordinal) : ordinal :=
omin {c | ∀ i, f i ≤ c}
⟨(sup (cardinal.succ ∘ card ∘ f)).ord, λ i, le_of_lt $
cardinal.lt_ord.2 (lt_of_lt_of_le (cardinal.lt_succ_self _) (le_sup _ _))⟩
theorem le_sup {ι} (f : ι → ordinal) : ∀ i, f i ≤ sup f :=
omin_mem {c | ∀ i, f i ≤ c} _
theorem sup_le {ι} {f : ι → ordinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a :=
⟨λ h i, le_trans (le_sup _ _) h, λ h, omin_le h⟩
theorem lt_sup {ι} {f : ι → ordinal} {a} : a < sup f ↔ ∃ i, a < f i :=
by simpa only [not_forall, not_le] using not_congr (@sup_le _ f a)
theorem is_normal.sup {f} (H : is_normal f)
{ι} {g : ι → ordinal} (h : nonempty ι) : f (sup g) = sup (f ∘ g) :=
eq_of_forall_ge_iff $ λ a,
by rw [sup_le, comp, H.le_set' (λ_:ι, true) g (let ⟨i⟩ := h in ⟨i, ⟨⟩⟩)];
intros; simp only [sup_le, true_implies_iff]
theorem sup_ord {ι} (f : ι → cardinal) : sup (λ i, (f i).ord) = (cardinal.sup f).ord :=
eq_of_forall_ge_iff $ λ a, by simp only [sup_le, cardinal.ord_le, cardinal.sup_le]
lemma sup_succ {ι} (f : ι → ordinal) : sup (λ i, succ (f i)) ≤ succ (sup f) :=
by { rw [ordinal.sup_le], intro i, rw ordinal.succ_le_succ, apply ordinal.le_sup }
lemma unbounded_range_of_sup_ge {α β : Type u} (r : α → α → Prop) [is_well_order α r] (f : β → α)
(h : type r ≤ sup.{u u} (typein r ∘ f)) : unbounded r (range f) :=
begin
apply (not_bounded_iff _).mp, rintro ⟨x, hx⟩, apply not_lt_of_ge h,
refine lt_of_le_of_lt _ (typein_lt_type r x), rw [sup_le], intro y,
apply le_of_lt, rw typein_lt_typein, apply hx, apply mem_range_self
end
/-- The supremum of a family of ordinals indexed by the set
of ordinals less than some `o : ordinal.{u}`.
(This is not a special case of `sup` over the subtype,
because `{a // a < o} : Type (u+1)` and `sup` only works over
families in `Type u`.) -/
def bsup (o : ordinal.{u}) : (Π a < o, ordinal.{max u v}) → ordinal.{max u v} :=
match o, o.out, o.out_eq with
| _, ⟨α, r, _⟩, rfl, f := by exactI sup (λ a, f (typein r a) (typein_lt_type _ _))
end
theorem bsup_le {o f a} : bsup.{u v} o f ≤ a ↔ ∀ i h, f i h ≤ a :=
match o, o.out, o.out_eq, f :
∀ o w (e : ⟦w⟧ = o) (f : Π (a : ordinal.{u}), a < o → ordinal.{(max u v)}),
bsup._match_1 o w e f ≤ a ↔ ∀ i h, f i h ≤ a with
| _, ⟨α, r, _⟩, rfl, f := by rw [bsup._match_1, sup_le]; exactI
⟨λ H i h, by simpa only [typein_enum] using H (enum r i h), λ H b, H _ _⟩
end
theorem bsup_type (r : α → α → Prop) [is_well_order α r] (f) :
bsup (type r) f = sup (λ a, f (typein r a) (typein_lt_type _ _)) :=
eq_of_forall_ge_iff $ λ o,
by rw [bsup_le, sup_le]; exact
⟨λ H b, H _ _, λ H i h, by simpa only [typein_enum] using H (enum r i h)⟩
theorem le_bsup {o} (f : Π a < o, ordinal) (i h) : f i h ≤ bsup o f :=
bsup_le.1 (le_refl _) _ _
theorem lt_bsup {o : ordinal} {f : Π a < o, ordinal}
(hf : ∀{a a'} (ha : a < o) (ha' : a' < o), a < a' → f a ha < f a' ha')
(ho : o.is_limit) (i h) : f i h < bsup o f :=
lt_of_lt_of_le (hf _ _ $ lt_succ_self i) (le_bsup f i.succ $ ho.2 _ h)
theorem bsup_id {o} (ho : is_limit o) : bsup.{u u} o (λ x _, x) = o :=
begin
apply le_antisymm, rw [bsup_le], intro i, apply le_of_lt,
rw [←not_lt], intro h, apply lt_irrefl (bsup.{u u} o (λ x _, x)),
apply lt_of_le_of_lt _ (lt_bsup _ ho _ h), refl, intros, assumption
end
theorem is_normal.bsup {f} (H : is_normal f)
{o : ordinal} : ∀ (g : Π a < o, ordinal) (h : o ≠ 0),
f (bsup o g) = bsup o (λ a h, f (g a h)) :=
induction_on o $ λ α r _ g h,
by resetI; rw [bsup_type,
H.sup (type_ne_zero_iff_nonempty.1 h), bsup_type]
theorem is_normal.bsup_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) :
bsup.{u} o (λx _, f x) = f o :=
by { rw [←is_normal.bsup.{u u} H (λ x _, x) h.1, bsup_id h] }
/-! ### Ordinal exponential -/
/-- The ordinal exponential, defined by transfinite recursion. -/
def power (a b : ordinal) : ordinal :=
if a = 0 then 1 - b else
limit_rec_on b 1 (λ _ IH, IH * a) (λ b _, bsup.{u u} b)
instance : has_pow ordinal ordinal := ⟨power⟩
local infixr ^ := @pow ordinal ordinal ordinal.has_pow
theorem zero_power' (a : ordinal) : 0 ^ a = 1 - a :=
by simp only [pow, power, if_pos rfl]
@[simp] theorem zero_power {a : ordinal} (a0 : a ≠ 0) : 0 ^ a = 0 :=
by rwa [zero_power', ordinal.sub_eq_zero_iff_le, one_le_iff_ne_zero]
@[simp] theorem power_zero (a : ordinal) : a ^ 0 = 1 :=
by by_cases a = 0; [simp only [pow, power, if_pos h, sub_zero],
simp only [pow, power, if_neg h, limit_rec_on_zero]]
@[simp] theorem power_succ (a b : ordinal) : a ^ succ b = a ^ b * a :=
if h : a = 0 then by subst a; simp only [zero_power (succ_ne_zero _), mul_zero]
else by simp only [pow, power, limit_rec_on_succ, if_neg h]
theorem power_limit {a b : ordinal} (a0 : a ≠ 0) (h : is_limit b) :
a ^ b = bsup.{u u} b (λ c _, a ^ c) :=
by simp only [pow, power, if_neg a0]; rw limit_rec_on_limit _ _ _ _ h; refl
theorem power_le_of_limit {a b c : ordinal} (a0 : a ≠ 0) (h : is_limit b) :
a ^ b ≤ c ↔ ∀ b' < b, a ^ b' ≤ c :=
by rw [power_limit a0 h, bsup_le]
theorem lt_power_of_limit {a b c : ordinal} (b0 : b ≠ 0) (h : is_limit c) :
a < b ^ c ↔ ∃ c' < c, a < b ^ c' :=
by rw [← not_iff_not, not_exists]; simp only [not_lt, power_le_of_limit b0 h, exists_prop, not_and]
@[simp] theorem power_one (a : ordinal) : a ^ 1 = a :=
by rw [← succ_zero, power_succ]; simp only [power_zero, one_mul]
@[simp] theorem one_power (a : ordinal) : 1 ^ a = 1 :=
begin
apply limit_rec_on a,
{ simp only [power_zero] },
{ intros _ ih, simp only [power_succ, ih, mul_one] },
refine λ b l IH, eq_of_forall_ge_iff (λ c, _),
rw [power_le_of_limit ordinal.one_ne_zero l],
exact ⟨λ H, by simpa only [power_zero] using H 0 l.pos,
λ H b' h, by rwa IH _ h⟩,
end
theorem power_pos {a : ordinal} (b)
(a0 : 0 < a) : 0 < a ^ b :=
begin
have h0 : 0 < a ^ 0, {simp only [power_zero, zero_lt_one]},
apply limit_rec_on b,
{ exact h0 },
{ intros b IH, rw [power_succ],
exact mul_pos IH a0 },
{ exact λ b l _, (lt_power_of_limit (ordinal.pos_iff_ne_zero.1 a0) l).2
⟨0, l.pos, h0⟩ },
end
theorem power_ne_zero {a : ordinal} (b)
(a0 : a ≠ 0) : a ^ b ≠ 0 :=
ordinal.pos_iff_ne_zero.1 $ power_pos b $ ordinal.pos_iff_ne_zero.2 a0
theorem power_is_normal {a : ordinal} (h : 1 < a) : is_normal ((^) a) :=
have a0 : 0 < a, from lt_trans zero_lt_one h,
⟨λ b, by simpa only [mul_one, power_succ] using
(mul_lt_mul_iff_left (power_pos b a0)).2 h,
λ b l c, power_le_of_limit (ne_of_gt a0) l⟩
theorem power_lt_power_iff_right {a b c : ordinal}
(a1 : 1 < a) : a ^ b < a ^ c ↔ b < c :=
(power_is_normal a1).lt_iff
theorem power_le_power_iff_right {a b c : ordinal}
(a1 : 1 < a) : a ^ b ≤ a ^ c ↔ b ≤ c :=
(power_is_normal a1).le_iff
theorem power_right_inj {a b c : ordinal}
(a1 : 1 < a) : a ^ b = a ^ c ↔ b = c :=
(power_is_normal a1).inj
theorem power_is_limit {a b : ordinal}
(a1 : 1 < a) : is_limit b → is_limit (a ^ b) :=
(power_is_normal a1).is_limit
theorem power_is_limit_left {a b : ordinal}
(l : is_limit a) (hb : b ≠ 0) : is_limit (a ^ b) :=
begin
rcases zero_or_succ_or_limit b with e|⟨b,rfl⟩|l',
{ exact absurd e hb },
{ rw power_succ,
exact mul_is_limit (power_pos _ l.pos) l },
{ exact power_is_limit l.one_lt l' }
end
theorem power_le_power_right {a b c : ordinal}
(h₁ : 0 < a) (h₂ : b ≤ c) : a ^ b ≤ a ^ c :=
begin
cases lt_or_eq_of_le (one_le_iff_pos.2 h₁) with h₁ h₁,
{ exact (power_le_power_iff_right h₁).2 h₂ },
{ subst a, simp only [one_power] }
end
theorem power_le_power_left {a b : ordinal} (c)
(ab : a ≤ b) : a ^ c ≤ b ^ c :=
begin
by_cases a0 : a = 0,
{ subst a, by_cases c0 : c = 0,
{ subst c, simp only [power_zero] },
{ simp only [zero_power c0, ordinal.zero_le] } },
{ apply limit_rec_on c,
{ simp only [power_zero] },
{ intros c IH, simpa only [power_succ] using mul_le_mul IH ab },
{ exact λ c l IH, (power_le_of_limit a0 l).2
(λ b' h, le_trans (IH _ h) (power_le_power_right
(lt_of_lt_of_le (ordinal.pos_iff_ne_zero.2 a0) ab) (le_of_lt h))) } }
end
theorem le_power_self {a : ordinal} (b) (a1 : 1 < a) : b ≤ a ^ b :=
(power_is_normal a1).le_self _
theorem power_lt_power_left_of_succ {a b c : ordinal}
(ab : a < b) : a ^ succ c < b ^ succ c :=
by rw [power_succ, power_succ]; exact
lt_of_le_of_lt
(mul_le_mul_right _ $ power_le_power_left _ $ le_of_lt ab)
(mul_lt_mul_of_pos_left ab (power_pos _ (lt_of_le_of_lt (ordinal.zero_le _) ab)))
theorem power_add (a b c : ordinal) : a ^ (b + c) = a ^ b * a ^ c :=
begin
by_cases a0 : a = 0,
{ subst a,
by_cases c0 : c = 0, {simp only [c0, add_zero, power_zero, mul_one]},
have : b+c ≠ 0 := ne_of_gt (lt_of_lt_of_le
(ordinal.pos_iff_ne_zero.2 c0) (le_add_left _ _)),
simp only [zero_power c0, zero_power this, mul_zero] },
cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1,
{ subst a1, simp only [one_power, mul_one] },
apply limit_rec_on c,
{ simp only [add_zero, power_zero, mul_one] },
{ intros c IH,
rw [add_succ, power_succ, IH, power_succ, mul_assoc] },
{ intros c l IH,
refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans
(add_is_normal b)).limit_le l).trans _),
simp only [IH] {contextual := tt},
exact (((mul_is_normal $ power_pos b (ordinal.pos_iff_ne_zero.2 a0)).trans
(power_is_normal a1)).limit_le l).symm }
end
theorem power_dvd_power (a) {b c : ordinal}
(h : b ≤ c) : a ^ b ∣ a ^ c :=
by { rw [← add_sub_cancel_of_le h, power_add], apply dvd_mul_right }
theorem power_dvd_power_iff {a b c : ordinal}
(a1 : 1 < a) : a ^ b ∣ a ^ c ↔ b ≤ c :=
⟨λ h, le_of_not_lt $ λ hn,
not_le_of_lt ((power_lt_power_iff_right a1).2 hn) $
le_of_dvd (power_ne_zero _ $ one_le_iff_ne_zero.1 $ le_of_lt a1) h,
power_dvd_power _⟩
theorem power_mul (a b c : ordinal) : a ^ (b * c) = (a ^ b) ^ c :=
begin
by_cases b0 : b = 0, {simp only [b0, zero_mul, power_zero, one_power]},
by_cases a0 : a = 0,
{ subst a,
by_cases c0 : c = 0, {simp only [c0, mul_zero, power_zero]},
simp only [zero_power b0, zero_power c0, zero_power (mul_ne_zero b0 c0)] },
cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1,
{ subst a1, simp only [one_power] },
apply limit_rec_on c,
{ simp only [mul_zero, power_zero] },
{ intros c IH,
rw [mul_succ, power_add, IH, power_succ] },
{ intros c l IH,
refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans
(mul_is_normal (ordinal.pos_iff_ne_zero.2 b0))).limit_le l).trans _),
simp only [IH] {contextual := tt},
exact (power_le_of_limit (power_ne_zero _ a0) l).symm }
end
/-! ### Ordinal logarithm -/
/-- The ordinal logarithm is the solution `u` to the equation
`x = b ^ u * v + w` where `v < b` and `w < b`. -/
def log (b : ordinal) (x : ordinal) : ordinal :=
if h : 1 < b then pred $
omin {o | x < b^o} ⟨succ x, succ_le.1 (le_power_self _ h)⟩
else 0
@[simp] theorem log_not_one_lt {b : ordinal} (b1 : ¬ 1 < b) (x : ordinal) : log b x = 0 :=
by simp only [log, dif_neg b1]
theorem log_def {b : ordinal} (b1 : 1 < b) (x : ordinal) : log b x =
pred (omin {o | x < b^o} (log._proof_1 b x b1)) :=
by simp only [log, dif_pos b1]
@[simp] theorem log_zero (b : ordinal) : log b 0 = 0 :=
if b1 : 1 < b then
by rw [log_def b1, ← ordinal.le_zero, pred_le];
apply omin_le; change 0<b^succ 0;
rw [succ_zero, power_one];
exact lt_trans zero_lt_one b1
else by simp only [log_not_one_lt b1]
theorem succ_log_def {b x : ordinal} (b1 : 1 < b) (x0 : 0 < x) : succ (log b x) =
omin {o | x < b^o} (log._proof_1 b x b1) :=
begin
let t := omin {o | x < b^o} (log._proof_1 b x b1),
have : x < b ^ t := omin_mem {o | x < b^o} _,
rcases zero_or_succ_or_limit t with h|h|h,
{ refine (not_lt_of_le (one_le_iff_pos.2 x0) _).elim,
simpa only [h, power_zero] },
{ rw [show log b x = pred t, from log_def b1 x,
succ_pred_iff_is_succ.2 h] },
{ rcases (lt_power_of_limit (ne_of_gt $ lt_trans zero_lt_one b1) h).1 this with ⟨a, h₁, h₂⟩,
exact (not_le_of_lt h₁).elim (le_omin.1 (le_refl t) a h₂) }
end
theorem lt_power_succ_log {b : ordinal} (b1 : 1 < b) (x : ordinal) :
x < b ^ succ (log b x) :=
begin
cases lt_or_eq_of_le (ordinal.zero_le x) with x0 x0,
{ rw [succ_log_def b1 x0], exact omin_mem {o | x < b^o} _ },
{ subst x, apply power_pos _ (lt_trans zero_lt_one b1) }
end
theorem power_log_le (b) {x : ordinal} (x0 : 0 < x) :
b ^ log b x ≤ x :=
begin
by_cases b0 : b = 0,
{ rw [b0, zero_power'],
refine le_trans (sub_le_self _ _) (one_le_iff_pos.2 x0) },
cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1,
{ refine le_of_not_lt (λ h, not_le_of_lt (lt_succ_self (log b x)) _),
have := @omin_le {o | x < b^o} _ _ h,
rwa ← succ_log_def b1 x0 at this },
{ rw [← b1, one_power], exact one_le_iff_pos.2 x0 }
end
theorem le_log {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) :
c ≤ log b x ↔ b ^ c ≤ x :=
⟨λ h, le_trans ((power_le_power_iff_right b1).2 h) (power_log_le b x0),
λ h, le_of_not_lt $ λ hn,
not_le_of_lt (lt_power_succ_log b1 x) $
le_trans ((power_le_power_iff_right b1).2 (succ_le.2 hn)) h⟩
theorem log_lt {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) :
log b x < c ↔ x < b ^ c :=
lt_iff_lt_of_le_iff_le (le_log b1 x0)
theorem log_le_log (b) {x y : ordinal} (xy : x ≤ y) :
log b x ≤ log b y :=
if x0 : x = 0 then by simp only [x0, log_zero, ordinal.zero_le] else
have x0 : 0 < x, from ordinal.pos_iff_ne_zero.2 x0,
if b1 : 1 < b then
(le_log b1 (lt_of_lt_of_le x0 xy)).2 $ le_trans (power_log_le _ x0) xy
else by simp only [log_not_one_lt b1, ordinal.zero_le]
theorem log_le_self (b x : ordinal) : log b x ≤ x :=
if x0 : x = 0 then by simp only [x0, log_zero, ordinal.zero_le] else
if b1 : 1 < b then
le_trans (le_power_self _ b1) (power_log_le b (ordinal.pos_iff_ne_zero.2 x0))
else by simp only [log_not_one_lt b1, ordinal.zero_le]
/-! ### The Cantor normal form -/
theorem CNF_aux {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) :
o % b ^ log b o < o :=
lt_of_lt_of_le
(mod_lt _ $ power_ne_zero _ b0)
(power_log_le _ $ ordinal.pos_iff_ne_zero.2 o0)
/-- Proving properties of ordinals by induction over their Cantor normal form. -/
@[elab_as_eliminator] noncomputable def CNF_rec {b : ordinal} (b0 : b ≠ 0)
{C : ordinal → Sort*}
(H0 : C 0)
(H : ∀ o, o ≠ 0 → o % b ^ log b o < o → C (o % b ^ log b o) → C o)
: ∀ o, C o
| o :=
if o0 : o = 0 then by rw o0; exact H0 else
have _, from CNF_aux b0 o0,
H o o0 this (CNF_rec (o % b ^ log b o))
using_well_founded {dec_tac := `[assumption]}
@[simp] theorem CNF_rec_zero {b} (b0) {C H0 H} : @CNF_rec b b0 C H0 H 0 = H0 :=
by rw [CNF_rec, dif_pos rfl]; refl
@[simp] theorem CNF_rec_ne_zero {b} (b0) {C H0 H o} (o0) :
@CNF_rec b b0 C H0 H o = H o o0 (CNF_aux b0 o0) (@CNF_rec b b0 C H0 H _) :=
by rw [CNF_rec, dif_neg o0]
/-- The Cantor normal form of an ordinal is the list of coefficients
in the base-`b` expansion of `o`.
CNF b (b ^ u₁ * v₁ + b ^ u₂ * v₂) = [(u₁, v₁), (u₂, v₂)] -/
noncomputable def CNF (b := omega) (o : ordinal) : list (ordinal × ordinal) :=
if b0 : b = 0 then [] else
CNF_rec b0 [] (λ o o0 h IH, (log b o, o / b ^ log b o) :: IH) o
@[simp] theorem zero_CNF (o) : CNF 0 o = [] :=
dif_pos rfl
@[simp] theorem CNF_zero (b) : CNF b 0 = [] :=
if b0 : b = 0 then dif_pos b0 else
(dif_neg b0).trans $ CNF_rec_zero _
theorem CNF_ne_zero {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) :
CNF b o = (log b o, o / b ^ log b o) :: CNF b (o % b ^ log b o) :=
by unfold CNF; rw [dif_neg b0, dif_neg b0, CNF_rec_ne_zero b0 o0]
theorem one_CNF {o : ordinal} (o0 : o ≠ 0) :
CNF 1 o = [(0, o)] :=
by rw [CNF_ne_zero ordinal.one_ne_zero o0, log_not_one_lt (lt_irrefl _), power_zero, mod_one,
CNF_zero, div_one]
theorem CNF_foldr {b : ordinal} (b0 : b ≠ 0) (o) :
(CNF b o).foldr (λ p r, b ^ p.1 * p.2 + r) 0 = o :=
CNF_rec b0 (by rw CNF_zero; refl)
(λ o o0 h IH, by rw [CNF_ne_zero b0 o0, list.foldr_cons, IH, div_add_mod]) o
theorem CNF_pairwise_aux (b := omega) (o) :
(∀ p ∈ CNF b o, prod.fst p ≤ log b o) ∧
(CNF b o).pairwise (λ p q, q.1 < p.1) :=
begin
by_cases b0 : b = 0,
{ simp only [b0, zero_CNF, list.pairwise.nil, and_true], exact λ _, false.elim },
cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1,
{ refine CNF_rec b0 _ _ o,
{ simp only [CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim },
intros o o0 H IH, cases IH with IH₁ IH₂,
simp only [CNF_ne_zero b0 o0, list.forall_mem_cons, list.pairwise_cons, IH₂, and_true],
refine ⟨⟨le_refl _, λ p m, _⟩, λ p m, _⟩,
{ exact le_trans (IH₁ p m) (log_le_log _ $ le_of_lt H) },
{ refine lt_of_le_of_lt (IH₁ p m) ((log_lt b1 _).2 _),
{ rw ordinal.pos_iff_ne_zero, intro e,
rw e at m, simpa only [CNF_zero] using m },
{ exact mod_lt _ (power_ne_zero _ b0) } } },
{ by_cases o0 : o = 0,
{ simp only [o0, CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim },
rw [← b1, one_CNF o0],
simp only [list.mem_singleton, log_not_one_lt (lt_irrefl _), forall_eq, le_refl, true_and,
list.pairwise_singleton] }
end
theorem CNF_pairwise (b := omega) (o) :
(CNF b o).pairwise (λ p q, prod.fst q < p.1) :=
(CNF_pairwise_aux _ _).2
theorem CNF_fst_le_log (b := omega) (o) :
∀ p ∈ CNF b o, prod.fst p ≤ log b o :=
(CNF_pairwise_aux _ _).1
theorem CNF_fst_le (b := omega) (o) (p ∈ CNF b o) : prod.fst p ≤ o :=
le_trans (CNF_fst_le_log _ _ p H) (log_le_self _ _)
theorem CNF_snd_lt {b : ordinal} (b1 : 1 < b) (o) :
∀ p ∈ CNF b o, prod.snd p < b :=
begin
have b0 := ne_of_gt (lt_trans zero_lt_one b1),
refine CNF_rec b0 (λ _, by rw [CNF_zero]; exact false.elim) _ o,
intros o o0 H IH,
simp only [CNF_ne_zero b0 o0, list.mem_cons_iff, forall_eq_or_imp, iff_true_intro IH, and_true],
rw [div_lt (power_ne_zero _ b0), ← power_succ],
exact lt_power_succ_log b1 _,
end
theorem CNF_sorted (b := omega) (o) :
((CNF b o).map prod.fst).sorted (>) :=
by rw [list.sorted, list.pairwise_map]; exact CNF_pairwise b o
/-! ### Casting naturals into ordinals, compatibility with operations -/
@[simp] theorem nat_cast_mul {m n : ℕ} : ((m * n : ℕ) : ordinal) = m * n :=
by induction n with n IH; [simp only [nat.cast_zero, nat.mul_zero, mul_zero],
rw [nat.mul_succ, nat.cast_add, IH, nat.cast_succ, mul_add_one]]
@[simp] theorem nat_cast_power {m n : ℕ} : ((pow m n : ℕ) : ordinal) = m ^ n :=
by induction n with n IH; [simp only [pow_zero, nat.cast_zero, power_zero, nat.cast_one],
rw [pow_succ', nat_cast_mul, IH, nat.cast_succ, ← succ_eq_add_one, power_succ]]
@[simp] theorem nat_cast_le {m n : ℕ} : (m : ordinal) ≤ n ↔ m ≤ n :=
by rw [← cardinal.ord_nat, ← cardinal.ord_nat,
cardinal.ord_le_ord, cardinal.nat_cast_le]
@[simp] theorem nat_cast_lt {m n : ℕ} : (m : ordinal) < n ↔ m < n :=
by simp only [lt_iff_le_not_le, nat_cast_le]
@[simp] theorem nat_cast_inj {m n : ℕ} : (m : ordinal) = n ↔ m = n :=
by simp only [le_antisymm_iff, nat_cast_le]
@[simp] theorem nat_cast_eq_zero {n : ℕ} : (n : ordinal) = 0 ↔ n = 0 :=
@nat_cast_inj n 0
theorem nat_cast_ne_zero {n : ℕ} : (n : ordinal) ≠ 0 ↔ n ≠ 0 :=
not_congr nat_cast_eq_zero
@[simp] theorem nat_cast_pos {n : ℕ} : (0 : ordinal) < n ↔ 0 < n :=
@nat_cast_lt 0 n
@[simp] theorem nat_cast_sub {m n : ℕ} : ((m - n : ℕ) : ordinal) = m - n :=
(_root_.le_total m n).elim
(λ h, by rw [nat.sub_eq_zero_iff_le.2 h, ordinal.sub_eq_zero_iff_le.2 (nat_cast_le.2 h)]; refl)
(λ h, (add_left_cancel n).1 $ by rw [← nat.cast_add,
nat.add_sub_cancel' h, add_sub_cancel_of_le (nat_cast_le.2 h)])
@[simp] theorem nat_cast_div {m n : ℕ} : ((m / n : ℕ) : ordinal) = m / n :=
if n0 : n = 0 then by simp only [n0, nat.div_zero, nat.cast_zero, div_zero] else
have n0':_, from nat_cast_ne_zero.2 n0,
le_antisymm
(by rw [le_div n0', ← nat_cast_mul, nat_cast_le, mul_comm];
apply nat.div_mul_le_self)
(by rw [div_le n0', succ, ← nat.cast_succ, ← nat_cast_mul,
nat_cast_lt, mul_comm, ← nat.div_lt_iff_lt_mul _ _ (nat.pos_of_ne_zero n0)];
apply nat.lt_succ_self)
@[simp] theorem nat_cast_mod {m n : ℕ} : ((m % n : ℕ) : ordinal) = m % n :=
by rw [← add_left_cancel (n*(m/n)), div_add_mod, ← nat_cast_div, ← nat_cast_mul, ← nat.cast_add,
nat.div_add_mod]
@[simp] theorem nat_le_card {o} {n : ℕ} : (n : cardinal) ≤ card o ↔ (n : ordinal) ≤ o :=
⟨λ h, by rwa [← cardinal.ord_le, cardinal.ord_nat] at h,
λ h, card_nat n ▸ card_le_card h⟩
@[simp] theorem nat_lt_card {o} {n : ℕ} : (n : cardinal) < card o ↔ (n : ordinal) < o :=
by rw [← succ_le, ← cardinal.succ_le, ← cardinal.nat_succ, nat_le_card]; refl
@[simp] theorem card_lt_nat {o} {n : ℕ} : card o < n ↔ o < n :=
lt_iff_lt_of_le_iff_le nat_le_card
@[simp] theorem card_le_nat {o} {n : ℕ} : card o ≤ n ↔ o ≤ n :=
le_iff_le_iff_lt_iff_lt.2 nat_lt_card
@[simp] theorem card_eq_nat {o} {n : ℕ} : card o = n ↔ o = n :=
by simp only [le_antisymm_iff, card_le_nat, nat_le_card]
@[simp] theorem type_fin (n : ℕ) : @type (fin n) (<) _ = n :=
by rw [← card_eq_nat, card_type, mk_fin]
@[simp] theorem lift_nat_cast (n : ℕ) : lift n = n :=
by induction n with n ih; [simp only [nat.cast_zero, lift_zero],
simp only [nat.cast_succ, lift_add, ih, lift_one]]
theorem lift_type_fin (n : ℕ) : lift (@type (fin n) (<) _) = n :=
by simp only [type_fin, lift_nat_cast]
theorem fintype_card (r : α → α → Prop) [is_well_order α r] [fintype α] : type r = fintype.card α :=
by rw [← card_eq_nat, card_type, fintype_card]
end ordinal
/-! ### Properties of `omega` -/
namespace cardinal
open ordinal
@[simp] theorem ord_omega : ord.{u} omega = ordinal.omega :=
le_antisymm (ord_le.2 $ le_refl _) $
le_of_forall_lt $ λ o h, begin
rcases ordinal.lt_lift_iff.1 h with ⟨o, rfl, h'⟩,
rw [lt_ord, ← lift_card, ← lift_omega.{0 u},
lift_lt, ← typein_enum (<) h'],
exact lt_omega_iff_fintype.2 ⟨set.fintype_lt_nat _⟩
end
@[simp] theorem add_one_of_omega_le {c} (h : omega ≤ c) : c + 1 = c :=
by rw [add_comm, ← card_ord c, ← card_one,
← card_add, one_add_of_omega_le];
rwa [← ord_omega, ord_le_ord]
end cardinal
namespace ordinal
theorem lt_omega {o : ordinal.{u}} : o < omega ↔ ∃ n : ℕ, o = n :=
by rw [← cardinal.ord_omega, cardinal.lt_ord, lt_omega]; simp only [card_eq_nat]
theorem nat_lt_omega (n : ℕ) : (n : ordinal) < omega :=
lt_omega.2 ⟨_, rfl⟩
theorem omega_pos : 0 < omega := nat_lt_omega 0
theorem omega_ne_zero : omega ≠ 0 := ne_of_gt omega_pos
theorem one_lt_omega : 1 < omega := by simpa only [nat.cast_one] using nat_lt_omega 1
theorem omega_is_limit : is_limit omega :=
⟨omega_ne_zero, λ o h,
let ⟨n, e⟩ := lt_omega.1 h in
by rw [e]; exact nat_lt_omega (n+1)⟩
theorem omega_le {o : ordinal.{u}} : omega ≤ o ↔ ∀ n : ℕ, (n : ordinal) ≤ o :=
⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h,
λ H, le_of_forall_lt $ λ a h,
let ⟨n, e⟩ := lt_omega.1 h in
by rw [e, ← succ_le]; exact H (n+1)⟩
theorem nat_lt_limit {o} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o
| 0 := lt_of_le_of_ne (ordinal.zero_le o) h.1.symm
| (n+1) := h.2 _ (nat_lt_limit n)
theorem omega_le_of_is_limit {o} (h : is_limit o) : omega ≤ o :=
omega_le.2 $ λ n, le_of_lt $ nat_lt_limit h n
theorem add_omega {a : ordinal} (h : a < omega) : a + omega = omega :=
begin
rcases lt_omega.1 h with ⟨n, rfl⟩,
clear h, induction n with n IH,
{ rw [nat.cast_zero, zero_add] },
{ rw [nat.cast_succ, add_assoc, one_add_of_omega_le (le_refl _), IH] }
end
theorem add_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a + b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega
end
theorem mul_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a * b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_mul]; apply nat_lt_omega
end
theorem is_limit_iff_omega_dvd {a : ordinal} : is_limit a ↔ a ≠ 0 ∧ omega ∣ a :=
begin
refine ⟨λ l, ⟨l.1, ⟨a / omega, le_antisymm _ (mul_div_le _ _)⟩⟩, λ h, _⟩,
{ refine (limit_le l).2 (λ x hx, le_of_lt _),
rw [← div_lt omega_ne_zero, ← succ_le, le_div omega_ne_zero,
mul_succ, add_le_of_limit omega_is_limit],
intros b hb,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
exact le_trans (add_le_add_right (mul_div_le _ _) _)
(le_of_lt $ lt_sub.1 $ nat_lt_limit (sub_is_limit l hx) _) },
{ rcases h with ⟨a0, b, rfl⟩,
refine mul_is_limit_left omega_is_limit
(ordinal.pos_iff_ne_zero.2 $ mt _ a0),
intro e, simp only [e, mul_zero] }
end
local infixr ^ := @pow ordinal ordinal ordinal.has_pow
theorem power_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_power]; apply nat_lt_omega
end
theorem add_omega_power {a b : ordinal} (h : a < omega ^ b) : a + omega ^ b = omega ^ b :=
begin
refine le_antisymm _ (le_add_left _ _),
revert h, apply limit_rec_on b,
{ intro h, rw [power_zero, ← succ_zero, lt_succ, ordinal.le_zero] at h,
rw [h, zero_add] },
{ intros b _ h, rw [power_succ] at h,
rcases (lt_mul_of_limit omega_is_limit).1 h with ⟨x, xo, ax⟩,
refine le_trans (add_le_add_right (le_of_lt ax) _) _,
rw [power_succ, ← mul_add, add_omega xo] },
{ intros b l IH h, rcases (lt_power_of_limit omega_ne_zero l).1 h with ⟨x, xb, ax⟩,
refine (((add_is_normal a).trans (power_is_normal one_lt_omega))
.limit_le l).2 (λ y yb, _),
let z := max x y,
have := IH z (max_lt xb yb)
(lt_of_lt_of_le ax $ power_le_power_right omega_pos (le_max_left _ _)),
exact le_trans (add_le_add_left (power_le_power_right omega_pos (le_max_right _ _)) _)
(le_trans this (power_le_power_right omega_pos $ le_of_lt $ max_lt xb yb)) }
end
theorem add_lt_omega_power {a b c : ordinal} (h₁ : a < omega ^ c) (h₂ : b < omega ^ c) :
a + b < omega ^ c :=
by rwa [← add_omega_power h₁, add_lt_add_iff_left]
theorem add_absorp {a b c : ordinal} (h₁ : a < omega ^ b) (h₂ : omega ^ b ≤ c) : a + c = c :=
by rw [← add_sub_cancel_of_le h₂, ← add_assoc, add_omega_power h₁]
theorem add_absorp_iff {o : ordinal} (o0 : 0 < o) : (∀ a < o, a + o = o) ↔ ∃ a, o = omega ^ a :=
⟨λ H, ⟨log omega o, begin
refine ((lt_or_eq_of_le (power_log_le _ o0))
.resolve_left $ λ h, _).symm,
have := H _ h,
have := lt_power_succ_log one_lt_omega o,
rw [power_succ, lt_mul_of_limit omega_is_limit] at this,
rcases this with ⟨a, ao, h'⟩,
rcases lt_omega.1 ao with ⟨n, rfl⟩, clear ao,
revert h', apply not_lt_of_le,
suffices e : omega ^ log omega o * ↑n + o = o,
{ simpa only [e] using le_add_right (omega ^ log omega o * ↑n) o },
induction n with n IH, {simp only [nat.cast_zero, mul_zero, zero_add]},
simp only [nat.cast_succ, mul_add_one, add_assoc, this, IH]
end⟩,
λ ⟨b, e⟩, e.symm ▸ λ a, add_omega_power⟩
theorem add_mul_limit_aux {a b c : ordinal} (ba : b + a = a)
(l : is_limit c)
(IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) :
(a + b) * c = a * c :=
le_antisymm
((mul_le_of_limit l).2 $ λ c' h, begin
apply le_trans (mul_le_mul_left _ (le_of_lt $ lt_succ_self _)),
rw IH _ h,
apply le_trans (add_le_add_left _ _),
{ rw ← mul_succ, exact mul_le_mul_left _ (succ_le.2 $ l.2 _ h) },
{ rw ← ba, exact le_add_right _ _ }
end)
(mul_le_mul_right _ (le_add_right _ _))
theorem add_mul_succ {a b : ordinal} (c) (ba : b + a = a) :
(a + b) * succ c = a * succ c + b :=
begin
apply limit_rec_on c,
{ simp only [succ_zero, mul_one] },
{ intros c IH,
rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ] },
{ intros c l IH,
have := add_mul_limit_aux ba l IH,
rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc] }
end
theorem add_mul_limit {a b c : ordinal} (ba : b + a = a)
(l : is_limit c) : (a + b) * c = a * c :=
add_mul_limit_aux ba l (λ c' _, add_mul_succ c' ba)
theorem mul_omega {a : ordinal} (a0 : 0 < a) (ha : a < omega) : a * omega = omega :=
le_antisymm
((mul_le_of_limit omega_is_limit).2 $ λ b hb, le_of_lt (mul_lt_omega ha hb))
(by simpa only [one_mul] using mul_le_mul_right omega (one_le_iff_pos.2 a0))
theorem mul_lt_omega_power {a b c : ordinal}
(c0 : 0 < c) (ha : a < omega ^ c) (hb : b < omega) : a * b < omega ^ c :=
if b0 : b = 0 then by simp only [b0, mul_zero, power_pos _ omega_pos] else begin
rcases zero_or_succ_or_limit c with rfl|⟨c,rfl⟩|l,
{ exact (lt_irrefl _).elim c0 },
{ rw power_succ at ha,
rcases ((mul_is_normal $ power_pos _ omega_pos).limit_lt
omega_is_limit).1 ha with ⟨n, hn, an⟩,
refine lt_of_le_of_lt (mul_le_mul_right _ (le_of_lt an)) _,
rw [power_succ, mul_assoc, mul_lt_mul_iff_left (power_pos _ omega_pos)],
exact mul_lt_omega hn hb },
{ rcases ((power_is_normal one_lt_omega).limit_lt l).1 ha with ⟨x, hx, ax⟩,
refine lt_of_le_of_lt (mul_le_mul (le_of_lt ax) (le_of_lt hb)) _,
rw [← power_succ, power_lt_power_iff_right one_lt_omega],
exact l.2 _ hx }
end
theorem mul_omega_dvd {a : ordinal}
(a0 : 0 < a) (ha : a < omega) : ∀ {b}, omega ∣ b → a * b = b
| _ ⟨b, rfl⟩ := by rw [← mul_assoc, mul_omega a0 ha]
theorem mul_omega_power_power {a b : ordinal} (a0 : 0 < a) (h : a < omega ^ omega ^ b) :
a * omega ^ omega ^ b = omega ^ omega ^ b :=
begin
by_cases b0 : b = 0, {rw [b0, power_zero, power_one] at h ⊢, exact mul_omega a0 h},
refine le_antisymm _
(by simpa only [one_mul] using mul_le_mul_right (omega^omega^b) (one_le_iff_pos.2 a0)),
rcases (lt_power_of_limit omega_ne_zero (power_is_limit_left omega_is_limit b0)).1 h
with ⟨x, xb, ax⟩,
refine le_trans (mul_le_mul_right _ (le_of_lt ax)) _,
rw [← power_add, add_omega_power xb]
end
theorem power_omega {a : ordinal} (a1 : 1 < a) (h : a < omega) : a ^ omega = omega :=
le_antisymm
((power_le_of_limit (one_le_iff_ne_zero.1 $ le_of_lt a1) omega_is_limit).2
(λ b hb, le_of_lt (power_lt_omega h hb)))
(le_power_self _ a1)
/-! ### Fixed points of normal functions -/
/-- The next fixed point function, the least fixed point of the
normal function `f` above `a`. -/
def nfp (f : ordinal → ordinal) (a : ordinal) :=
sup (λ n : ℕ, f^[n] a)
theorem iterate_le_nfp (f a n) : f^[n] a ≤ nfp f a :=
le_sup _ n
theorem le_nfp_self (f a) : a ≤ nfp f a :=
iterate_le_nfp f a 0
theorem is_normal.lt_nfp {f} (H : is_normal f) {a b} :
f b < nfp f a ↔ b < nfp f a :=
lt_sup.trans $ iff.trans
(by exact
⟨λ ⟨n, h⟩, ⟨n, lt_of_le_of_lt (H.le_self _) h⟩,
λ ⟨n, h⟩, ⟨n+1, by rw iterate_succ'; exact H.lt_iff.2 h⟩⟩)
lt_sup.symm
theorem is_normal.nfp_le {f} (H : is_normal f) {a b} :
nfp f a ≤ f b ↔ nfp f a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 H.lt_nfp
theorem is_normal.nfp_le_fp {f} (H : is_normal f) {a b}
(ab : a ≤ b) (h : f b ≤ b) : nfp f a ≤ b :=
sup_le.2 $ λ i, begin
induction i with i IH generalizing a, {exact ab},
exact IH (le_trans (H.le_iff.2 ab) h),
end
theorem is_normal.nfp_fp {f} (H : is_normal f) (a) : f (nfp f a) = nfp f a :=
begin
refine le_antisymm _ (H.le_self _),
cases le_or_lt (f a) a with aa aa,
{ rwa le_antisymm (H.nfp_le_fp (le_refl _) aa) (le_nfp_self _ _) },
rcases zero_or_succ_or_limit (nfp f a) with e|⟨b, e⟩|l,
{ refine @le_trans _ _ _ (f a) _ (H.le_iff.2 _) (iterate_le_nfp f a 1),
simp only [e, ordinal.zero_le] },
{ have : f b < nfp f a := H.lt_nfp.2 (by simp only [e, lt_succ_self]),
rw [e, lt_succ] at this,
have ab : a ≤ b,
{ rw [← lt_succ, ← e],
exact lt_of_lt_of_le aa (iterate_le_nfp f a 1) },
refine le_trans (H.le_iff.2 (H.nfp_le_fp ab this))
(le_trans this (le_of_lt _)),
simp only [e, lt_succ_self] },
{ exact (H.2 _ l _).2 (λ b h, le_of_lt (H.lt_nfp.2 h)) }
end
theorem is_normal.le_nfp {f} (H : is_normal f) {a b} :
f b ≤ nfp f a ↔ b ≤ nfp f a :=
⟨le_trans (H.le_self _), λ h,
by simpa only [H.nfp_fp] using H.le_iff.2 h⟩
theorem nfp_eq_self {f : ordinal → ordinal} {a} (h : f a = a) : nfp f a = a :=
le_antisymm (sup_le.mpr $ λ i, by rw [iterate_fixed h]) (le_nfp_self f a)
/-- The derivative of a normal function `f` is
the sequence of fixed points of `f`. -/
def deriv (f : ordinal → ordinal) (o : ordinal) : ordinal :=
limit_rec_on o (nfp f 0)
(λ a IH, nfp f (succ IH))
(λ a l, bsup.{u u} a)
@[simp] theorem deriv_zero (f) : deriv f 0 = nfp f 0 := limit_rec_on_zero _ _ _
@[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) :=
limit_rec_on_succ _ _ _ _
theorem deriv_limit (f) {o} : is_limit o →
deriv f o = bsup.{u u} o (λ a _, deriv f a) :=
limit_rec_on_limit _ _ _ _
theorem deriv_is_normal (f) : is_normal (deriv f) :=
⟨λ o, by rw [deriv_succ, ← succ_le]; apply le_nfp_self,
λ o l a, by rw [deriv_limit _ l, bsup_le]⟩
theorem is_normal.deriv_fp {f} (H : is_normal f) (o) : f (deriv.{u} f o) = deriv f o :=
begin
apply limit_rec_on o,
{ rw [deriv_zero, H.nfp_fp] },
{ intros o ih, rw [deriv_succ, H.nfp_fp] },
intros o l IH,
rw [deriv_limit _ l, is_normal.bsup.{u u u} H _ l.1],
refine eq_of_forall_ge_iff (λ c, _),
simp only [bsup_le, IH] {contextual:=tt}
end
theorem is_normal.fp_iff_deriv {f} (H : is_normal f)
{a} : f a ≤ a ↔ ∃ o, a = deriv f o :=
⟨λ ha, begin
suffices : ∀ o (_:a ≤ deriv f o), ∃ o, a = deriv f o,
from this a ((deriv_is_normal _).le_self _),
intro o, apply limit_rec_on o,
{ intros h₁,
refine ⟨0, le_antisymm h₁ _⟩,
rw deriv_zero,
exact H.nfp_le_fp (ordinal.zero_le _) ha },
{ intros o IH h₁,
cases le_or_lt a (deriv f o), {exact IH h},
refine ⟨succ o, le_antisymm h₁ _⟩,
rw deriv_succ,
exact H.nfp_le_fp (succ_le.2 h) ha },
{ intros o l IH h₁,
cases eq_or_lt_of_le h₁, {exact ⟨_, h⟩},
rw [deriv_limit _ l, ← not_le, bsup_le, not_ball] at h,
exact let ⟨o', h, hl⟩ := h in IH o' h (le_of_not_le hl) }
end, λ ⟨o, e⟩, e.symm ▸ le_of_eq (H.deriv_fp _)⟩
end ordinal
|
10dc622f18b235b0e6f9272e4527b10b633a2525 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/data/finset/basic.lean | cc369ee8984ad45dd1c468c863293a010608040e | [
"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 | 126,449 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro
-/
import data.int.basic
import data.multiset.finset_ops
import tactic.apply
import tactic.monotonicity
import tactic.nth_rewrite
/-!
# Finite sets
Terms of type `finset α` are one way of talking about finite subsets of `α` in mathlib.
Below, `finset α` is defined as a structure with 2 fields:
1. `val` is a `multiset α` of elements;
2. `nodup` is a proof that `val` has no duplicates.
Finsets in Lean are constructive in that they have an underlying `list` that enumerates their
elements. In particular, any function that uses the data of the underlying list cannot depend on its
ordering. This is handled on the `multiset` level by multiset API, so in most cases one needn't
worry about it explicitly.
Finsets give a basic foundation for defining finite sums and products over types:
1. `∑ i in (s : finset α), f i`;
2. `∏ i in (s : finset α), f i`.
Lean refers to these operations as `big_operator`s.
More information can be found in `algebra.big_operators.basic`.
Finsets are directly used to define fintypes in Lean.
A `fintype α` instance for a type `α` consists of
a universal `finset α` containing every term of `α`, called `univ`. See `data.fintype.basic`.
There is also `univ'`, the noncomputable partner to `univ`,
which is defined to be `α` as a finset if `α` is finite,
and the empty finset otherwise. See `data.fintype.basic`.
`finset.card`, the size of a finset is defined in `data.finset.card`. This is then used to define
`fintype.card`, the size of a type.
## Main declarations
### Main definitions
* `finset`: Defines a type for the finite subsets of `α`.
Constructing a `finset` requires two pieces of data: `val`, a `multiset α` of elements,
and `nodup`, a proof that `val` has no duplicates.
* `finset.has_mem`: Defines membership `a ∈ (s : finset α)`.
* `finset.has_coe`: Provides a coercion `s : finset α` to `s : set α`.
* `finset.has_coe_to_sort`: Coerce `s : finset α` to the type of all `x ∈ s`.
* `finset.induction_on`: Induction on finsets. To prove a proposition about an arbitrary `finset α`,
it suffices to prove it for the empty finset, and to show that if it holds for some `finset α`,
then it holds for the finset obtained by inserting a new element.
* `finset.choose`: Given a proof `h` of existence and uniqueness of a certain element
satisfying a predicate, `choose s h` returns the element of `s` satisfying that predicate.
### Finset constructions
* `singleton`: Denoted by `{a}`; the finset consisting of one element.
* `finset.empty`: Denoted by `∅`. The finset associated to any type consisting of no elements.
* `finset.range`: For any `n : ℕ`, `range n` is equal to `{0, 1, ... , n - 1} ⊆ ℕ`.
This convention is consistent with other languages and normalizes `card (range n) = n`.
Beware, `n` is not in `range n`.
* `finset.attach`: Given `s : finset α`, `attach s` forms a finset of elements of the subtype
`{a // a ∈ s}`; in other words, it attaches elements to a proof of membership in the set.
### Finsets from functions
* `finset.image`: Given a function `f : α → β`, `s.image f` is the image finset in `β`.
* `finset.map`: Given an embedding `f : α ↪ β`, `s.map f` is the image finset in `β`.
* `finset.filter`: Given a predicate `p : α → Prop`, `s.filter p` is
the finset consisting of those elements in `s` satisfying the predicate `p`.
### The lattice structure on subsets of finsets
There is a natural lattice structure on the subsets of a set.
In Lean, we use lattice notation to talk about things involving unions and intersections. See
`order.lattice`. For the lattice structure on finsets, `⊥` is called `bot` with `⊥ = ∅` and `⊤` is
called `top` with `⊤ = univ`.
* `finset.has_subset`: Lots of API about lattices, otherwise behaves exactly as one would expect.
* `finset.has_union`: Defines `s ∪ t` (or `s ⊔ t`) as the union of `s` and `t`.
See `finset.sup`/`finset.bUnion` for finite unions.
* `finset.has_inter`: Defines `s ∩ t` (or `s ⊓ t`) as the intersection of `s` and `t`.
See `finset.inf` for finite intersections.
* `finset.disj_union`: Given a hypothesis `h` which states that finsets `s` and `t` are disjoint,
`s.disj_union t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`; this does
not require decidable equality on the type `α`.
### Operations on two or more finsets
* `insert` and `finset.cons`: For any `a : α`, `insert s a` returns `s ∪ {a}`. `cons s a h`
returns the same except that it requires a hypothesis stating that `a` is not already in `s`.
This does not require decidable equality on the type `α`.
* `finset.has_union`: see "The lattice structure on subsets of finsets"
* `finset.has_inter`: see "The lattice structure on subsets of finsets"
* `finset.erase`: For any `a : α`, `erase s a` returns `s` with the element `a` removed.
* `finset.has_sdiff`: Defines the set difference `s \ t` for finsets `s` and `t`.
* `finset.product`: Given finsets of `α` and `β`, defines finsets of `α × β`.
For arbitrary dependent products, see `data.finset.pi`.
* `finset.bUnion`: Finite unions of finsets; given an indexing function `f : α → finset β` and a
`s : finset α`, `s.bUnion f` is the union of all finsets of the form `f a` for `a ∈ s`.
* `finset.bInter`: TODO: Implemement finite intersections.
### Maps constructed using finsets
* `finset.piecewise`: Given two functions `f`, `g`, `s.piecewise f g` is a function which is equal
to `f` on `s` and `g` on the complement.
### Predicates on finsets
* `disjoint`: defined via the lattice structure on finsets; two sets are disjoint if their
intersection is empty.
* `finset.nonempty`: A finset is nonempty if it has elements.
This is equivalent to saying `s ≠ ∅`. TODO: Decide on the simp normal form.
### Equivalences between finsets
* The `data.equiv` files describe a general type of equivalence, so look in there for any lemmas.
There is some API for rewriting sums and products from `s` to `t` given that `s ≃ t`.
TODO: examples
## Tags
finite sets, finset
-/
open multiset subtype nat function
universes u
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `finset α` is the type of finite sets of elements of `α`. It is implemented
as a multiset (a list up to permutation) which has no duplicate elements. -/
structure finset (α : Type*) :=
(val : multiset α)
(nodup : nodup val)
namespace finset
theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t
| ⟨s, _⟩ ⟨t, _⟩ rfl := rfl
theorem val_injective : injective (val : finset α → multiset α) := λ _ _, eq_of_veq
@[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := val_injective.eq_iff
@[simp] theorem dedup_eq_self [decidable_eq α] (s : finset α) : dedup s.1 = s.1 :=
s.2.dedup
instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α)
| s₁ s₂ := decidable_of_iff _ val_inj
/-! ### membership -/
instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩
theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl
@[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl
instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) :=
multiset.decidable_mem _ _
/-! ### set coercion -/
/-- Convert a finset to a set in the natural way. -/
instance : has_coe_t (finset α) (set α) := ⟨λ s, {x | x ∈ s}⟩
@[simp, norm_cast] lemma mem_coe {a : α} {s : finset α} : a ∈ (s : set α) ↔ a ∈ s := iff.rfl
@[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = s := rfl
@[simp] lemma coe_mem {s : finset α} (x : (s : set α)) : ↑x ∈ s := x.2
@[simp] lemma mk_coe {s : finset α} (x : (s : set α)) {h} :
(⟨x, h⟩ : (s : set α)) = x :=
subtype.coe_eta _ _
instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) :
decidable (a ∈ (s : set α)) := s.decidable_mem _
/-! ### extensionality -/
theorem ext_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ :=
val_inj.symm.trans $ s₁.nodup.ext s₂.nodup
@[ext]
theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ :=
ext_iff.2
@[simp, norm_cast] theorem coe_inj {s₁ s₂ : finset α} : (s₁ : set α) = s₂ ↔ s₁ = s₂ :=
set.ext_iff.trans ext_iff.symm
lemma coe_injective {α} : injective (coe : finset α → set α) :=
λ s t, coe_inj.1
/-! ### type coercion -/
/-- Coercion from a finset to the corresponding subtype. -/
instance {α : Type u} : has_coe_to_sort (finset α) (Type u) := ⟨λ s, {x // x ∈ s}⟩
@[simp] protected lemma forall_coe {α : Type*} (s : finset α) (p : s → Prop) :
(∀ (x : s), p x) ↔ ∀ (x : α) (h : x ∈ s), p ⟨x, h⟩ := subtype.forall
@[simp] protected lemma exists_coe {α : Type*} (s : finset α) (p : s → Prop) :
(∃ (x : s), p x) ↔ ∃ (x : α) (h : x ∈ s), p ⟨x, h⟩ := subtype.exists
instance pi_finset_coe.can_lift (ι : Type*) (α : Π i : ι, Type*) [ne : Π i, nonempty (α i)]
(s : finset ι) :
can_lift (Π i : s, α i) (Π i, α i) :=
{ coe := λ f i, f i,
.. pi_subtype.can_lift ι α (∈ s) }
instance pi_finset_coe.can_lift' (ι α : Type*) [ne : nonempty α] (s : finset ι) :
can_lift (s → α) (ι → α) :=
pi_finset_coe.can_lift ι (λ _, α) s
instance finset_coe.can_lift (s : finset α) : can_lift α s :=
{ coe := coe,
cond := λ a, a ∈ s,
prf := λ a ha, ⟨⟨a, ha⟩, rfl⟩ }
@[simp, norm_cast] lemma coe_sort_coe (s : finset α) :
((s : set α) : Sort*) = s := rfl
/-! ### Subset and strict subset relations -/
section subset
variables {s t : finset α}
instance : has_subset (finset α) := ⟨λ s t, ∀ ⦃a⦄, a ∈ s → a ∈ t⟩
instance : has_ssubset (finset α) := ⟨λ s t, s ⊆ t ∧ ¬ t ⊆ s⟩
instance : partial_order (finset α) :=
{ le := (⊆),
lt := (⊂),
le_refl := λ s a, id,
le_trans := λ s t u hst htu a ha, htu $ hst ha,
le_antisymm := λ s t hst hts, ext $ λ a, ⟨@hst _, @hts _⟩ }
instance : is_refl (finset α) (⊆) := has_le.le.is_refl
instance : is_trans (finset α) (⊆) := has_le.le.is_trans
instance : is_antisymm (finset α) (⊆) := has_le.le.is_antisymm
instance : is_irrefl (finset α) (⊂) := has_lt.lt.is_irrefl
instance : is_trans (finset α) (⊂) := has_lt.lt.is_trans
instance : is_asymm (finset α) (⊂) := has_lt.lt.is_asymm
instance : is_nonstrict_strict_order (finset α) (⊆) (⊂) := ⟨λ _ _, iff.rfl⟩
lemma subset_def : s ⊆ t ↔ s.1 ⊆ t.1 := iff.rfl
lemma ssubset_def : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := iff.rfl
@[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _
protected lemma subset.rfl {s :finset α} : s ⊆ s := subset.refl _
protected theorem subset_of_eq {s t : finset α} (h : s = t) : s ⊆ t := h ▸ subset.refl _
theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans
theorem superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ :=
λ h' h, subset.trans h h'
theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset
lemma not_mem_mono {s t : finset α} (h : s ⊆ t) {a : α} : a ∉ t → a ∉ s := mt $ @h _
theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ :=
ext $ λ a, ⟨@H₁ a, @H₂ a⟩
theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl
@[simp, norm_cast] theorem coe_subset {s₁ s₂ : finset α} :
(s₁ : set α) ⊆ s₂ ↔ s₁ ⊆ s₂ := iff.rfl
@[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2
theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ :=
le_antisymm_iff
theorem not_subset (s t : finset α) : ¬(s ⊆ t) ↔ ∃ x ∈ s, ¬(x ∈ t) :=
by simp only [←finset.coe_subset, set.not_subset, exists_prop, finset.mem_coe]
@[simp] theorem le_eq_subset : ((≤) : finset α → finset α → Prop) = (⊆) := rfl
@[simp] theorem lt_eq_subset : ((<) : finset α → finset α → Prop) = (⊂) := rfl
theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl
theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl
@[simp, norm_cast] lemma coe_ssubset {s₁ s₂ : finset α} : (s₁ : set α) ⊂ s₂ ↔ s₁ ⊂ s₂ :=
show (s₁ : set α) ⊂ s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁,
by simp only [set.ssubset_def, finset.coe_subset]
@[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ :=
and_congr val_le_iff $ not_congr val_le_iff
lemma ssubset_iff_subset_ne {s t : finset α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t :=
@lt_iff_le_and_ne _ _ s t
theorem ssubset_iff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ :=
set.ssubset_iff_of_subset h
lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) :
s₁ ⊂ s₃ :=
set.ssubset_of_ssubset_of_subset hs₁s₂ hs₂s₃
lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) :
s₁ ⊂ s₃ :=
set.ssubset_of_subset_of_ssubset hs₁s₂ hs₂s₃
lemma exists_of_ssubset {s₁ s₂ : finset α} (h : s₁ ⊂ s₂) :
∃ x ∈ s₂, x ∉ s₁ :=
set.exists_of_ssubset h
end subset
-- TODO: these should be global attributes, but this will require fixing other files
local attribute [trans] subset.trans superset.trans
/-! ### Order embedding from `finset α` to `set α` -/
/-- Coercion to `set α` as an `order_embedding`. -/
def coe_emb : finset α ↪o set α := ⟨⟨coe, coe_injective⟩, λ s t, coe_subset⟩
@[simp] lemma coe_coe_emb : ⇑(coe_emb : finset α ↪o set α) = coe := rfl
/-! ### Nonempty -/
/-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used
in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks
to the dot notation. -/
protected def nonempty (s : finset α) : Prop := ∃ x : α, x ∈ s
instance decidable_nonempty {s : finset α} : decidable s.nonempty :=
decidable_of_iff (∃ a ∈ s, true) $ by simp_rw [exists_prop, and_true, finset.nonempty]
@[simp, norm_cast] lemma coe_nonempty {s : finset α} : (s : set α).nonempty ↔ s.nonempty := iff.rfl
@[simp] lemma nonempty_coe_sort {s : finset α} : nonempty ↥s ↔ s.nonempty := nonempty_subtype
alias coe_nonempty ↔ _ nonempty.to_set
lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x : α, x ∈ s := h
lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty :=
set.nonempty.mono hst hs
lemma nonempty.forall_const {s : finset α} (h : s.nonempty) {p : Prop} : (∀ x ∈ s, p) ↔ p :=
let ⟨x, hx⟩ := h in ⟨λ h, h x hx, λ h x hx, h⟩
/-! ### empty -/
/-- The empty finset -/
protected def empty : finset α := ⟨0, nodup_zero⟩
instance : has_emptyc (finset α) := ⟨finset.empty⟩
instance inhabited_finset : inhabited (finset α) := ⟨∅⟩
@[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl
@[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id
@[simp] theorem not_nonempty_empty : ¬(∅ : finset α).nonempty :=
λ ⟨x, hx⟩, not_mem_empty x hx
@[simp] theorem mk_zero : (⟨0, nodup_zero⟩ : finset α) = ∅ := rfl
theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ :=
λ e, not_mem_empty a $ e ▸ h
theorem nonempty.ne_empty {s : finset α} (h : s.nonempty) : s ≠ ∅ :=
exists.elim h $ λ a, ne_empty_of_mem
@[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _
lemma eq_empty_of_forall_not_mem {s : finset α} (H : ∀ x, x ∉ s) : s = ∅ :=
eq_of_veq (eq_zero_of_forall_not_mem H)
lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s :=
⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩
@[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅
theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero
@[simp] lemma not_ssubset_empty (s : finset α) : ¬s ⊂ ∅ :=
λ h, let ⟨x, he, hs⟩ := exists_of_ssubset h in he
theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty :=
exists_mem_of_ne_zero (mt val_eq_zero.1 h)
theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ :=
⟨nonempty.ne_empty, nonempty_of_ne_empty⟩
@[simp] theorem not_nonempty_iff_eq_empty {s : finset α} : ¬s.nonempty ↔ s = ∅ :=
nonempty_iff_ne_empty.not.trans not_not
theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty :=
classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h))
@[simp, norm_cast] lemma coe_empty : ((∅ : finset α) : set α) = ∅ := rfl
@[simp, norm_cast] lemma coe_eq_empty {s : finset α} : (s : set α) = ∅ ↔ s = ∅ :=
by rw [← coe_empty, coe_inj]
@[simp] lemma is_empty_coe_sort {s : finset α} : is_empty ↥s ↔ s = ∅ :=
by simpa using @set.is_empty_coe_sort α s
/-- A `finset` for an empty type is empty. -/
lemma eq_empty_of_is_empty [is_empty α] (s : finset α) : s = ∅ :=
finset.eq_empty_of_forall_not_mem is_empty_elim
/-! ### singleton -/
/--
`{a} : finset a` is the set `{a}` containing `a` and nothing else.
This differs from `insert a ∅` in that it does not require a `decidable_eq` instance for `α`.
-/
instance : has_singleton α (finset α) := ⟨λ a, ⟨{a}, nodup_singleton a⟩⟩
@[simp] theorem singleton_val (a : α) : ({a} : finset α).1 = {a} := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : finset α) ↔ b = a := mem_singleton
lemma eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : finset α)) : x = y := mem_singleton.1 h
theorem not_mem_singleton {a b : α} : a ∉ ({b} : finset α) ↔ a ≠ b := not_congr mem_singleton
theorem mem_singleton_self (a : α) : a ∈ ({a} : finset α) := or.inl rfl
lemma singleton_injective : injective (singleton : α → finset α) :=
λ a b h, mem_singleton.1 (h ▸ mem_singleton_self _)
theorem singleton_inj {a b : α} : ({a} : finset α) = {b} ↔ a = b :=
singleton_injective.eq_iff
@[simp] theorem singleton_nonempty (a : α) : ({a} : finset α).nonempty := ⟨a, mem_singleton_self a⟩
@[simp] theorem singleton_ne_empty (a : α) : ({a} : finset α) ≠ ∅ := (singleton_nonempty a).ne_empty
@[simp, norm_cast] lemma coe_singleton (a : α) : (({a} : finset α) : set α) = {a} :=
by { ext, simp }
@[simp, norm_cast] lemma coe_eq_singleton {s : finset α} {a : α} : (s : set α) = {a} ↔ s = {a} :=
by rw [←coe_singleton, coe_inj]
lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} :
s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a :=
begin
split; intro t,
rw t,
refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩,
ext, rw finset.mem_singleton,
refine ⟨t.right _, λ r, r.symm ▸ t.left⟩
end
lemma eq_singleton_iff_nonempty_unique_mem {s : finset α} {a : α} :
s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a :=
begin
split,
{ rintro rfl, simp },
{ rintros ⟨hne, h_uniq⟩, rw eq_singleton_iff_unique_mem, refine ⟨_, h_uniq⟩,
rw ← h_uniq hne.some hne.some_spec, exact hne.some_spec }
end
lemma nonempty_iff_eq_singleton_default [unique α] {s : finset α} :
s.nonempty ↔ s = {default} :=
by simp [eq_singleton_iff_nonempty_unique_mem]
alias nonempty_iff_eq_singleton_default ↔ nonempty.eq_singleton_default _
lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s :=
by simp only [eq_singleton_iff_unique_mem, exists_unique]
lemma singleton_subset_set_iff {s : set α} {a : α} : ↑({a} : finset α) ⊆ s ↔ a ∈ s :=
by rw [coe_singleton, set.singleton_subset_iff]
@[simp] lemma singleton_subset_iff {s : finset α} {a : α} : {a} ⊆ s ↔ a ∈ s :=
singleton_subset_set_iff
@[simp] lemma subset_singleton_iff {s : finset α} {a : α} : s ⊆ {a} ↔ s = ∅ ∨ s = {a} :=
by rw [←coe_subset, coe_singleton, set.subset_singleton_iff_eq, coe_eq_empty, coe_eq_singleton]
protected lemma nonempty.subset_singleton_iff {s : finset α} {a : α} (h : s.nonempty) :
s ⊆ {a} ↔ s = {a} :=
subset_singleton_iff.trans $ or_iff_right h.ne_empty
lemma subset_singleton_iff' {s : finset α} {a : α} : s ⊆ {a} ↔ ∀ b ∈ s, b = a :=
forall₂_congr $ λ _ _, mem_singleton
@[simp] lemma ssubset_singleton_iff {s : finset α} {a : α} :
s ⊂ {a} ↔ s = ∅ :=
by rw [←coe_ssubset, coe_singleton, set.ssubset_singleton_iff, coe_eq_empty]
lemma eq_empty_of_ssubset_singleton {s : finset α} {x : α} (hs : s ⊂ {x}) : s = ∅ :=
ssubset_singleton_iff.1 hs
instance [nonempty α] : nontrivial (finset α) :=
‹nonempty α›.elim $ λ a, ⟨⟨{a}, ∅, singleton_ne_empty _⟩⟩
instance [is_empty α] : unique (finset α) :=
{ default := ∅,
uniq := λ s, eq_empty_of_forall_not_mem is_empty_elim }
/-! ### cons -/
section cons
variables {s t : finset α} {a b : α}
/-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as
`insert a s` when it is defined, but unlike `insert a s` it does not require `decidable_eq α`,
and the union is guaranteed to be disjoint. -/
def cons (a : α) (s : finset α) (h : a ∉ s) : finset α := ⟨a ::ₘ s.1, nodup_cons.2 ⟨h, s.2⟩⟩
@[simp] lemma mem_cons {h} : b ∈ s.cons a h ↔ b = a ∨ b ∈ s := mem_cons
@[simp] lemma mem_cons_self (a : α) (s : finset α) {h} : a ∈ cons a s h := mem_cons_self _ _
@[simp] lemma cons_val (h : a ∉ s) : (cons a s h).1 = a ::ₘ s.1 := rfl
lemma forall_mem_cons (h : a ∉ s) (p : α → Prop) :
(∀ x, x ∈ cons a s h → p x) ↔ p a ∧ ∀ x, x ∈ s → p x :=
by simp only [mem_cons, or_imp_distrib, forall_and_distrib, forall_eq]
@[simp] lemma mk_cons {s : multiset α} (h : (a ::ₘ s).nodup) :
(⟨a ::ₘ s, h⟩ : finset α) = cons a ⟨s, (nodup_cons.1 h).2⟩ (nodup_cons.1 h).1 := rfl
@[simp] lemma nonempty_cons (h : a ∉ s) : (cons a s h).nonempty := ⟨a, mem_cons.2 $ or.inl rfl⟩
@[simp] lemma nonempty_mk {m : multiset α} {hm} : (⟨m, hm⟩ : finset α).nonempty ↔ m ≠ 0 :=
by induction m using multiset.induction_on; simp
@[simp] lemma coe_cons {a s h} : (@cons α a s h : set α) = insert a s := by { ext, simp }
lemma subset_cons (h : a ∉ s) : s ⊆ s.cons a h := subset_cons _ _
lemma ssubset_cons (h : a ∉ s) : s ⊂ s.cons a h := ssubset_cons h
lemma cons_subset {h : a ∉ s} : s.cons a h ⊆ t ↔ a ∈ t ∧ s ⊆ t := cons_subset
@[simp] lemma cons_subset_cons {hs ht} : s.cons a hs ⊆ t.cons a ht ↔ s ⊆ t :=
by rwa [← coe_subset, coe_cons, coe_cons, set.insert_subset_insert_iff, coe_subset]
lemma ssubset_iff_exists_cons_subset : s ⊂ t ↔ ∃ a (h : a ∉ s), s.cons a h ⊆ t :=
begin
refine ⟨λ h, _, λ ⟨a, ha, h⟩, ssubset_of_ssubset_of_subset (ssubset_cons _) h⟩,
obtain ⟨a, hs, ht⟩ := (not_subset _ _).1 h.2,
exact ⟨a, ht, cons_subset.2 ⟨hs, h.subset⟩⟩,
end
end cons
/-! ### disjoint union -/
/-- `disj_union s t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`.
It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis
ensures that the sets are disjoint. -/
def disj_union (s t : finset α) (h : ∀ a ∈ s, a ∉ t) : finset α :=
⟨s.1 + t.1, multiset.nodup_add.2 ⟨s.2, t.2, h⟩⟩
@[simp] theorem mem_disj_union {α s t h a} :
a ∈ @disj_union α s t h ↔ a ∈ s ∨ a ∈ t :=
by rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply list.mem_append
lemma disj_union_comm (s t : finset α) (h : ∀ a ∈ s, a ∉ t) :
disj_union s t h = disj_union t s (λ a ht hs, h _ hs ht) :=
eq_of_veq $ add_comm _ _
@[simp] lemma empty_disj_union (t : finset α) (h : ∀ a' ∈ ∅, a' ∉ t := λ a h _, not_mem_empty _ h) :
disj_union ∅ t h = t :=
eq_of_veq $ zero_add _
@[simp] lemma disj_union_empty (s : finset α) (h : ∀ a' ∈ s, a' ∉ ∅ := λ a h, not_mem_empty _) :
disj_union s ∅ h = s :=
eq_of_veq $ add_zero _
lemma singleton_disj_union (a : α) (t : finset α) (h : ∀ a' ∈ {a}, a' ∉ t) :
disj_union {a} t h = cons a t (h _ $ mem_singleton_self _) :=
eq_of_veq $ multiset.singleton_add _ _
lemma disj_union_singleton (s : finset α) (a : α) (h : ∀ a' ∈ s, a' ∉ {a}) :
disj_union s {a} h = cons a s (λ ha, h _ ha $ mem_singleton_self _) :=
by rw [disj_union_comm, singleton_disj_union]
/-! ### insert -/
section decidable_eq
variables [decidable_eq α] {s t u v : finset α} {a b : α}
/-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/
instance : has_insert α (finset α) := ⟨λ a s, ⟨_, s.2.ndinsert a⟩⟩
lemma insert_def (a : α) (s : finset α) : insert a s = ⟨_, s.2.ndinsert a⟩ := rfl
@[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl
theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = dedup (a ::ₘ s.1) :=
by rw [dedup_cons, dedup_eq_self]; refl
theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a ::ₘ s.1 :=
by rw [insert_val, ndinsert_of_not_mem h]
@[simp] lemma mem_insert : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert
theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1
lemma mem_insert_of_mem (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h
lemma mem_of_mem_insert_of_ne (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left
lemma eq_of_not_mem_of_mem_insert (ha : b ∈ insert a s) (hb : b ∉ s) : b = a :=
(mem_insert.1 ha).resolve_right hb
@[simp] theorem cons_eq_insert (a s h) : @cons α a s h = insert a s := ext $ λ a, by simp
@[simp, norm_cast] lemma coe_insert (a : α) (s : finset α) :
↑(insert a s) = (insert a s : set α) :=
set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff]
lemma mem_insert_coe {s : finset α} {x y : α} : x ∈ insert y s ↔ x ∈ insert y (s : set α) :=
by simp
instance : is_lawful_singleton α (finset α) := ⟨λ a, by { ext, simp }⟩
@[simp] lemma insert_eq_of_mem (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h
@[simp] lemma insert_eq_self : insert a s = s ↔ a ∈ s :=
⟨λ h, h ▸ mem_insert_self _ _, insert_eq_of_mem⟩
lemma insert_ne_self : insert a s ≠ s ↔ a ∉ s := insert_eq_self.not
@[simp] theorem pair_eq_singleton (a : α) : ({a, a} : finset α) = {a} :=
insert_eq_of_mem $ mem_singleton_self _
theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) :=
ext $ λ x, by simp only [mem_insert, or.left_comm]
@[simp, norm_cast] lemma coe_pair {a b : α} :
(({a, b} : finset α) : set α) = {a, b} := by { ext, simp }
@[simp, norm_cast] lemma coe_eq_pair {s : finset α} {a b : α} :
(s : set α) = {a, b} ↔ s = {a, b} := by rw [←coe_pair, coe_inj]
theorem pair_comm (a b : α) : ({a, b} : finset α) = {b, a} := insert.comm a b ∅
@[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s :=
ext $ λ x, by simp only [mem_insert, or.assoc.symm, or_self]
@[simp] theorem insert_nonempty (a : α) (s : finset α) : (insert a s).nonempty :=
⟨a, mem_insert_self a s⟩
@[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ :=
(insert_nonempty a s).ne_empty
/-!
The universe annotation is required for the following instance, possibly this is a bug in Lean. See
leanprover.zulipchat.com/#narrow/stream/113488-general/topic/strange.20error.20(universe.20issue.3F)
-/
instance {α : Type u} [decidable_eq α] (i : α) (s : finset α) :
nonempty.{u + 1} ((insert i s : finset α) : set α) :=
(finset.coe_nonempty.mpr (s.insert_nonempty i)).to_subtype
lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) : s ≠ insert a t :=
by { contrapose! h, simp [h] }
lemma insert_subset : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib]
lemma subset_insert (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem
theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t :=
insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩
lemma insert_inj (ha : a ∉ s) : insert a s = insert b s ↔ a = b :=
⟨λ h, eq_of_not_mem_of_mem_insert (h.subst $ mem_insert_self _ _) ha, congr_arg _⟩
lemma insert_inj_on (s : finset α) : set.inj_on (λ a, insert a s) sᶜ := λ a h b _, (insert_inj h).1
lemma ssubset_iff : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t :=
by exact_mod_cast @set.ssubset_iff_insert α s t
lemma ssubset_insert (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.rfl⟩
@[elab_as_eliminator]
lemma cons_induction {α : Type*} {p : finset α → Prop}
(h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : ∀ s, p s
| ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin
cases nodup_cons.1 nd with m nd',
rw [← (eq_of_veq _ : cons a (finset.mk s _) m = ⟨a ::ₘ s, nd⟩)],
{ exact h₂ (by exact m) (IH nd') },
{ rw [cons_val] }
end) nd
@[elab_as_eliminator]
lemma cons_induction_on {α : Type*} {p : finset α → Prop} (s : finset α)
(h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : p s :=
cons_induction h₁ h₂ s
@[elab_as_eliminator]
protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α]
(h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s :=
cons_induction h₁ $ λ a s ha, (s.cons_eq_insert a ha).symm ▸ h₂ ha
/--
To prove a proposition about an arbitrary `finset α`,
it suffices to prove it for the empty `finset`,
and to show that if it holds for some `finset α`,
then it holds for the `finset` obtained by inserting a new element.
-/
@[elab_as_eliminator]
protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α]
(s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s :=
finset.induction h₁ h₂ s
/--
To prove a proposition about `S : finset α`,
it suffices to prove it for the empty `finset`,
and to show that if it holds for some `finset α ⊆ S`,
then it holds for the `finset` obtained by inserting a new element of `S`.
-/
@[elab_as_eliminator]
theorem induction_on' {α : Type*} {p : finset α → Prop} [decidable_eq α]
(S : finset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → p s → p (insert a s)) : p S :=
@finset.induction_on α (λ T, T ⊆ S → p T) _ S (λ _, h₁) (λ a s has hqs hs,
let ⟨hS, sS⟩ := finset.insert_subset.1 hs in h₂ hS sS has (hqs sS)) (finset.subset.refl S)
/-- To prove a proposition about a nonempty `s : finset α`, it suffices to show it holds for all
singletons and that if it holds for nonempty `t : finset α`, then it also holds for the `finset`
obtained by inserting an element in `t`. -/
@[elab_as_eliminator]
lemma nonempty.cons_induction {α : Type*} {p : Π s : finset α, s.nonempty → Prop}
(h₀ : ∀ a, p {a} (singleton_nonempty _))
(h₁ : ∀ ⦃a⦄ s (h : a ∉ s) hs, p s hs → p (finset.cons a s h) (nonempty_cons h))
{s : finset α} (hs : s.nonempty) : p s hs :=
begin
induction s using finset.cons_induction with a t ha h,
{ exact (not_nonempty_empty hs).elim },
obtain rfl | ht := t.eq_empty_or_nonempty,
{ exact h₀ a },
{ exact h₁ t ha ht (h ht) }
end
/-- Inserting an element to a finite set is equivalent to the option type. -/
def subtype_insert_equiv_option {t : finset α} {x : α} (h : x ∉ t) :
{i // i ∈ insert x t} ≃ option {i // i ∈ t} :=
begin
refine
{ to_fun := λ y, if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩,
inv_fun := λ y, y.elim ⟨x, mem_insert_self _ _⟩ $ λ z, ⟨z, mem_insert_of_mem z.2⟩,
.. },
{ intro y, by_cases h : ↑y = x,
simp only [subtype.ext_iff, h, option.elim, dif_pos, subtype.coe_mk],
simp only [h, option.elim, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] },
{ rintro (_|y), simp only [option.elim, dif_pos, subtype.coe_mk],
have : ↑y ≠ x, { rintro ⟨⟩, exact h y.2 },
simp only [this, option.elim, subtype.eta, dif_neg, not_false_iff, subtype.coe_eta,
subtype.coe_mk] },
end
/-! ### Lattice structure -/
/-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/
instance : has_union (finset α) := ⟨λ s t, ⟨_, t.2.ndunion s.1⟩⟩
/-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/
instance : has_inter (finset α) := ⟨λ s t, ⟨_, s.2.ndinter t.1⟩⟩
instance : lattice (finset α) :=
{ sup := (∪),
sup_le := λ s t u hs ht a ha, (mem_ndunion.1 ha).elim (λ h, hs h) (λ h, ht h),
le_sup_left := λ s t a h, mem_ndunion.2 $ or.inl h,
le_sup_right := λ s t a h, mem_ndunion.2 $ or.inr h,
inf := (∩),
le_inf := λ s t u ht hu a h, mem_ndinter.2 ⟨ht h, hu h⟩,
inf_le_left := λ s t a h, (mem_ndinter.1 h).1,
inf_le_right := λ s t a h, (mem_ndinter.1 h).2,
..finset.partial_order }
/-! #### union -/
@[simp] lemma sup_eq_union : ((⊔) : finset α → finset α → finset α) = (∪) := rfl
@[simp] lemma inf_eq_inter : ((⊓) : finset α → finset α → finset α) = (∩) := rfl
lemma union_val_nd (s t : finset α) : (s ∪ t).1 = ndunion s.1 t.1 := rfl
@[simp] lemma union_val (s t : finset α) : (s ∪ t).1 = s.1 ∪ t.1 := ndunion_eq_union s.2
@[simp] lemma mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := mem_ndunion
@[simp] lemma disj_union_eq_union (s t h) : @disj_union α s t h = s ∪ t := ext $ λ a, by simp
lemma mem_union_left (t : finset α) (h : a ∈ s) : a ∈ s ∪ t := mem_union.2 $ or.inl h
lemma mem_union_right (s : finset α) (h : a ∈ t) : a ∈ s ∪ t := mem_union.2 $ or.inr h
lemma forall_mem_union {p : α → Prop} : (∀ a ∈ s ∪ t, p a) ↔ (∀ a ∈ s, p a) ∧ ∀ a ∈ t, p a :=
⟨λ h, ⟨λ a, h a ∘ mem_union_left _, λ b, h b ∘ mem_union_right _⟩,
λ h ab hab, (mem_union.mp hab).elim (h.1 _) (h.2 _)⟩
lemma not_mem_union : a ∉ s ∪ t ↔ a ∉ s ∧ a ∉ t := by rw [mem_union, not_or_distrib]
@[simp, norm_cast]
lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (s₁ ∪ s₂ : set α) := set.ext $ λ x, mem_union
lemma union_subset (hs : s ⊆ u) : t ⊆ u → s ∪ t ⊆ u := sup_le $ le_iff_subset.2 hs
theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _
theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _
lemma union_subset_union (hsu : s ⊆ u) (htv : t ⊆ v) : s ∪ t ⊆ u ∪ v :=
sup_le_sup (le_iff_subset.2 hsu) htv
lemma union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := sup_comm
instance : is_commutative (finset α) (∪) := ⟨union_comm⟩
@[simp] lemma union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := sup_assoc
instance : is_associative (finset α) (∪) := ⟨union_assoc⟩
@[simp] lemma union_idempotent (s : finset α) : s ∪ s = s := sup_idem
instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩
lemma union_subset_left (h : s ∪ t ⊆ u) : s ⊆ u := (subset_union_left _ _).trans h
lemma union_subset_right {s t u : finset α} (h : s ∪ t ⊆ u) : t ⊆ u :=
subset.trans (subset_union_right _ _) h
lemma union_left_comm (s t u : finset α) : s ∪ (t ∪ u) = t ∪ (s ∪ u) :=
ext $ λ _, by simp only [mem_union, or.left_comm]
lemma union_right_comm (s t u : finset α) : (s ∪ t) ∪ u = (s ∪ u) ∪ t :=
ext $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ t)]
theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s
@[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s :=
ext $ λ x, mem_union.trans $ or_false _
@[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s :=
ext $ λ x, mem_union.trans $ false_or _
theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl
@[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) :=
by simp only [insert_eq, union_assoc]
@[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) :=
by simp only [insert_eq, union_left_comm]
lemma insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t :=
by simp only [insert_union, union_insert, insert_idem]
@[simp] lemma union_eq_left_iff_subset {s t : finset α} : s ∪ t = s ↔ t ⊆ s := sup_eq_left
@[simp] lemma left_eq_union_iff_subset {s t : finset α} : s = s ∪ t ↔ t ⊆ s :=
by rw [← union_eq_left_iff_subset, eq_comm]
@[simp] lemma union_eq_right_iff_subset {s t : finset α} : s ∪ t = t ↔ s ⊆ t := sup_eq_right
@[simp] lemma right_eq_union_iff_subset {s t : finset α} : s = t ∪ s ↔ t ⊆ s :=
by rw [← union_eq_right_iff_subset, eq_comm]
lemma union_congr_left (ht : t ⊆ s ∪ u) (hu : u ⊆ s ∪ t) : s ∪ t = s ⊔ u := sup_congr_left ht hu
lemma union_congr_right (hs : s ⊆ t ∪ u) (ht : t ⊆ s ∪ u) : s ∪ u = t ∪ u := sup_congr_right hs ht
lemma union_eq_union_iff_left : s ∪ t = s ∪ u ↔ t ⊆ s ∪ u ∧ u ⊆ s ∪ t := sup_eq_sup_iff_left
lemma union_eq_union_iff_right : s ∪ u = t ∪ u ↔ s ⊆ t ∪ u ∧ t ⊆ s ∪ u := sup_eq_sup_iff_right
/--
To prove a relation on pairs of `finset X`, it suffices to show that it is
* symmetric,
* it holds when one of the `finset`s is empty,
* it holds for pairs of singletons,
* if it holds for `[a, c]` and for `[b, c]`, then it holds for `[a ∪ b, c]`.
-/
lemma induction_on_union (P : finset α → finset α → Prop)
(symm : ∀ {a b}, P a b → P b a)
(empty_right : ∀ {a}, P a ∅)
(singletons : ∀ {a b}, P {a} {b})
(union_of : ∀ {a b c}, P a c → P b c → P (a ∪ b) c) :
∀ a b, P a b :=
begin
intros a b,
refine finset.induction_on b empty_right (λ x s xs hi, symm _),
rw finset.insert_eq,
apply union_of _ (symm hi),
refine finset.induction_on a empty_right (λ a t ta hi, symm _),
rw finset.insert_eq,
exact union_of singletons (symm hi),
end
lemma _root_.directed.exists_mem_subset_of_finset_subset_bUnion {α ι : Type*} [hn : nonempty ι]
{f : ι → set α} (h : directed (⊆) f)
{s : finset α} (hs : (s : set α) ⊆ ⋃ i, f i) : ∃ i, (s : set α) ⊆ f i :=
begin
classical,
revert hs,
apply s.induction_on,
{ refine λ _, ⟨hn.some, _⟩,
simp only [coe_empty, set.empty_subset], },
{ intros b t hbt htc hbtc,
obtain ⟨i : ι , hti : (t : set α) ⊆ f i⟩ :=
htc (set.subset.trans (t.subset_insert b) hbtc),
obtain ⟨j, hbj⟩ : ∃ j, b ∈ f j,
by simpa [set.mem_Union₂] using hbtc (t.mem_insert_self b),
rcases h j i with ⟨k, hk, hk'⟩,
use k,
rw [coe_insert, set.insert_subset],
exact ⟨hk hbj, trans hti hk'⟩ }
end
lemma _root_.directed_on.exists_mem_subset_of_finset_subset_bUnion {α ι : Type*}
{f : ι → set α} {c : set ι} (hn : c.nonempty) (hc : directed_on (λ i j, f i ⊆ f j) c)
{s : finset α} (hs : (s : set α) ⊆ ⋃ i ∈ c, f i) : ∃ i ∈ c, (s : set α) ⊆ f i :=
begin
rw set.bUnion_eq_Union at hs,
haveI := set.nonempty_coe_sort.2 hn,
obtain ⟨⟨i, hic⟩, hi⟩ :=
(directed_comp.2 hc.directed_coe).exists_mem_subset_of_finset_subset_bUnion hs,
exact ⟨i, hic, hi⟩
end
/-! #### inter -/
theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl
@[simp] lemma inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2
@[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter
theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) :
a ∈ s₁ := (mem_inter.1 h).1
theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) :
a ∈ s₂ := (mem_inter.1 h).2
theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ :=
and_imp.1 mem_inter.2
theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left
theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right
lemma subset_inter {s₁ s₂ u : finset α} : s₁ ⊆ s₂ → s₁ ⊆ u → s₁ ⊆ s₂ ∩ u :=
by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial
@[simp, norm_cast]
lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (s₁ ∩ s₂ : set α) := set.ext $ λ _, mem_inter
@[simp] theorem union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s :=
by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left]
@[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t :=
by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right]
theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ :=
ext $ λ _, by simp only [mem_inter, and_comm]
@[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) :=
ext $ λ _, by simp only [mem_inter, and_assoc]
theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
ext $ λ _, by simp only [mem_inter, and.left_comm]
theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ :=
ext $ λ _, by simp only [mem_inter, and.right_comm]
@[simp] lemma inter_self (s : finset α) : s ∩ s = s := ext $ λ _, mem_inter.trans $ and_self _
@[simp] lemma inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext $ λ _, mem_inter.trans $ and_false _
@[simp] lemma empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext $ λ _, mem_inter.trans $ false_and _
@[simp] lemma inter_union_self (s t : finset α) : s ∩ (t ∪ s) = s :=
by rw [inter_comm, union_inter_cancel_right]
@[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) :
insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) :=
ext $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h,
by simp only [mem_inter, mem_insert, or_and_distrib_left, this]
@[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) :
s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) :=
by rw [inter_comm, insert_inter_of_mem h, inter_comm]
@[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) :
insert a s₁ ∩ s₂ = s₁ ∩ s₂ :=
ext $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H,
by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or]
@[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) :
s₁ ∩ insert a s₂ = s₁ ∩ s₂ :=
by rw [inter_comm, insert_inter_of_not_mem h, inter_comm]
@[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : {a} ∩ s = {a} :=
show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter]
@[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : {a} ∩ s = ∅ :=
eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h
@[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ {a} = {a} :=
by rw [inter_comm, singleton_inter_of_mem h]
@[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ {a} = ∅ :=
by rw [inter_comm, singleton_inter_of_not_mem h]
@[mono]
lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t :=
begin
intros a a_in,
rw finset.mem_inter at a_in ⊢,
exact ⟨h a_in.1, h' a_in.2⟩
end
lemma inter_subset_inter_left (h : t ⊆ u) : s ∩ t ⊆ s ∩ u := inter_subset_inter subset.rfl h
lemma inter_subset_inter_right (h : s ⊆ t) : s ∩ u ⊆ t ∩ u := inter_subset_inter h subset.rfl
instance {α : Type u} : order_bot (finset α) :=
{ bot := ∅, bot_le := empty_subset }
@[simp] lemma bot_eq_empty {α : Type u} : (⊥ : finset α) = ∅ := rfl
instance : distrib_lattice (finset α) :=
{ le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c,
by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt};
simp only [true_or, imp_true_iff, true_and, or_true],
..finset.lattice }
@[simp] theorem union_left_idem (s t : finset α) : s ∪ (s ∪ t) = s ∪ t := sup_left_idem
@[simp] theorem union_right_idem (s t : finset α) : s ∪ t ∪ t = s ∪ t := sup_right_idem
@[simp] theorem inter_left_idem (s t : finset α) : s ∩ (s ∩ t) = s ∩ t := inf_left_idem
@[simp] theorem inter_right_idem (s t : finset α) : s ∩ t ∩ t = s ∩ t := inf_right_idem
theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left
theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right
theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left
theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right
lemma union_union_distrib_left (s t u : finset α) : s ∪ (t ∪ u) = (s ∪ t) ∪ (s ∪ u) :=
sup_sup_distrib_left _ _ _
lemma union_union_distrib_right (s t u : finset α) : (s ∪ t) ∪ u = (s ∪ u) ∪ (t ∪ u) :=
sup_sup_distrib_right _ _ _
lemma inter_inter_distrib_left (s t u : finset α) : s ∩ (t ∩ u) = (s ∩ t) ∩ (s ∩ u) :=
inf_inf_distrib_left _ _ _
lemma inter_inter_distrib_right (s t u : finset α) : (s ∩ t) ∩ u = (s ∩ u) ∩ (t ∩ u) :=
inf_inf_distrib_right _ _ _
lemma union_union_union_comm (s t u v : finset α) : (s ∪ t) ∪ (u ∪ v) = (s ∪ u) ∪ (t ∪ v) :=
sup_sup_sup_comm _ _ _ _
lemma inter_inter_inter_comm (s t u v : finset α) : (s ∩ t) ∩ (u ∩ v) = (s ∩ u) ∩ (t ∩ v) :=
inf_inf_inf_comm _ _ _ _
lemma union_eq_empty_iff (A B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ := sup_eq_bot_iff
lemma union_subset_iff : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := (sup_le_iff : s ⊔ t ≤ u ↔ s ≤ u ∧ t ≤ u)
lemma subset_inter_iff : s ⊆ t ∩ u ↔ s ⊆ t ∧ s ⊆ u := (le_inf_iff : s ≤ t ⊓ u ↔ s ≤ t ∧ s ≤ u)
lemma inter_eq_left_iff_subset (s t : finset α) : s ∩ t = s ↔ s ⊆ t := inf_eq_left
lemma inter_eq_right_iff_subset (s t : finset α) : t ∩ s = s ↔ s ⊆ t := inf_eq_right
lemma inter_congr_left (ht : s ∩ u ⊆ t) (hu : s ∩ t ⊆ u) : s ∩ t = s ∩ u := inf_congr_left ht hu
lemma inter_congr_right (hs : t ∩ u ⊆ s) (ht : s ∩ u ⊆ t) : s ∩ u = t ∩ u := inf_congr_right hs ht
lemma inter_eq_inter_iff_left : s ∩ t = s ∩ u ↔ s ∩ u ⊆ t ∧ s ∩ t ⊆ u := inf_eq_inf_iff_left
lemma inter_eq_inter_iff_right : s ∩ u = t ∩ u ↔ t ∩ u ⊆ s ∧ s ∩ u ⊆ t := inf_eq_inf_iff_right
lemma ite_subset_union (s s' : finset α) (P : Prop) [decidable P] :
ite P s s' ⊆ s ∪ s' := ite_le_sup s s' P
lemma inter_subset_ite (s s' : finset α) (P : Prop) [decidable P] :
s ∩ s' ⊆ ite P s s' := inf_le_ite s s' P
/-! ### erase -/
/-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are
not equal to `a`. -/
def erase (s : finset α) (a : α) : finset α := ⟨_, s.2.erase a⟩
@[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl
@[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s :=
s.2.mem_erase_iff
lemma not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := s.2.not_mem_erase
-- While this can be solved by `simp`, this lemma is eligible for `dsimp`
@[nolint simp_nf, simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl
@[simp] lemma erase_singleton (a : α) : ({a} : finset α).erase a = ∅ :=
begin
ext x,
rw [mem_erase, mem_singleton, not_and_self],
refl,
end
lemma ne_of_mem_erase : b ∈ erase s a → b ≠ a := λ h, (mem_erase.1 h).1
lemma mem_of_mem_erase : b ∈ erase s a → b ∈ s := mem_of_mem_erase
lemma mem_erase_of_ne_of_mem : a ≠ b → a ∈ s → a ∈ erase s b :=
by simp only [mem_erase]; exact and.intro
/-- An element of `s` that is not an element of `erase s a` must be
`a`. -/
lemma eq_of_mem_of_not_mem_erase (hs : b ∈ s) (hsa : b ∉ s.erase a) : b = a :=
begin
rw [mem_erase, not_and] at hsa,
exact not_imp_not.mp hsa hs
end
theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s :=
ext $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or];
apply and_iff_right_of_imp; rintro H rfl; exact h H
theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s :=
ext $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and];
apply or_iff_right_of_imp; rintro rfl; exact h
theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a :=
val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h
theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _
lemma subset_erase {a : α} {s t : finset α} : s ⊆ t.erase a ↔ s ⊆ t ∧ a ∉ s :=
⟨λ h, ⟨h.trans (erase_subset _ _), λ ha, not_mem_erase _ _ (h ha)⟩,
λ h b hb, mem_erase.2 ⟨ne_of_mem_of_not_mem hb h.2, h.1 hb⟩⟩
@[simp, norm_cast] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (s \ {a} : set α) :=
set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl
lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s :=
calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _
... = _ : insert_erase h
lemma ssubset_iff_exists_subset_erase {s t : finset α} : s ⊂ t ↔ ∃ a ∈ t, s ⊆ t.erase a :=
begin
refine ⟨λ h, _, λ ⟨a, ha, h⟩, ssubset_of_subset_of_ssubset h $ erase_ssubset ha⟩,
obtain ⟨a, ht, hs⟩ := (not_subset _ _).1 h.2,
exact ⟨a, ht, subset_erase.2 ⟨h.1, hs⟩⟩,
end
lemma erase_ssubset_insert (s : finset α) (a : α) : s.erase a ⊂ insert a s :=
ssubset_iff_exists_subset_erase.2 ⟨a, mem_insert_self _ _, erase_subset_erase _ $ subset_insert _ _⟩
@[simp]
theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s :=
eq_of_veq $ erase_of_not_mem h
@[simp] lemma erase_eq_self : s.erase a = s ↔ a ∉ s :=
⟨λ h, h ▸ not_mem_erase _ _, erase_eq_of_not_mem⟩
lemma erase_ne_self : s.erase a ≠ s ↔ a ∈ s := erase_eq_self.not_left
@[simp] lemma erase_insert_eq_erase (s : finset α) (a : α) :
(insert a s).erase a = s.erase a :=
by by_cases ha : a ∈ s; { simp [ha, erase_insert] }
lemma erase_cons {s : finset α} {a : α} (h : a ∉ s) : (s.cons a h).erase a = s :=
by rw [cons_eq_insert, erase_insert_eq_erase, erase_eq_of_not_mem h]
lemma erase_idem {a : α} {s : finset α} : erase (erase s a) a = erase s a :=
by simp
lemma erase_right_comm {a b : α} {s : finset α} : erase (erase s a) b = erase (erase s b) a :=
by { ext x, simp only [mem_erase, ←and_assoc], rw and_comm (x ≠ a) }
theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t :=
by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp];
exact forall_congr (λ x, forall_swap)
theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s :=
subset_insert_iff.1 $ subset.rfl
theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) :=
subset_insert_iff.2 $ subset.rfl
lemma subset_insert_iff_of_not_mem (h : a ∉ s) : s ⊆ insert a t ↔ s ⊆ t :=
by rw [subset_insert_iff, erase_eq_of_not_mem h]
lemma erase_subset_iff_of_mem (h : a ∈ t) : s.erase a ⊆ t ↔ s ⊆ t :=
by rw [←subset_insert_iff, insert_eq_of_mem h]
lemma erase_inj {x y : α} (s : finset α) (hx : x ∈ s) : s.erase x = s.erase y ↔ x = y :=
begin
refine ⟨λ h, _, congr_arg _⟩,
rw eq_of_mem_of_not_mem_erase hx,
rw ←h,
simp,
end
lemma erase_inj_on (s : finset α) : set.inj_on s.erase s := λ _ _ _ _, (erase_inj s ‹_›).mp
lemma erase_inj_on' (a : α) : {s : finset α | a ∈ s}.inj_on (λ s, erase s a) :=
λ s hs t ht (h : s.erase a = _), by rw [←insert_erase hs, ←insert_erase ht, h]
/-! ### sdiff -/
/-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/
instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le tsub_le_self s₁.2⟩⟩
@[simp] lemma sdiff_val (s₁ s₂ : finset α) : (s₁ \ s₂).val = s₁.val - s₂.val := rfl
@[simp] theorem mem_sdiff : a ∈ s \ t ↔ a ∈ s ∧ a ∉ t := mem_sub_of_nodup s.2
@[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ :=
eq_empty_of_forall_not_mem $
by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h
instance : generalized_boolean_algebra (finset α) :=
{ sup_inf_sdiff := λ x y, by { simp only [ext_iff, mem_union, mem_sdiff, inf_eq_inter, sup_eq_union,
mem_inter], tauto },
inf_inf_sdiff := λ x y, by { simp only [ext_iff, inter_sdiff_self, inter_empty, inter_assoc,
false_iff, inf_eq_inter, not_mem_empty], tauto },
..finset.has_sdiff,
..finset.distrib_lattice,
..finset.order_bot }
lemma not_mem_sdiff_of_mem_right (h : a ∈ t) : a ∉ s \ t :=
by simp only [mem_sdiff, h, not_true, not_false_iff, and_false]
lemma not_mem_sdiff_of_not_mem_left (h : a ∉ s) : a ∉ s \ t := by simpa
lemma union_sdiff_of_subset (h : s ⊆ t) : s ∪ (t \ s) = t := sup_sdiff_cancel_right h
theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ :=
(union_comm _ _).trans (union_sdiff_of_subset h)
lemma inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] }
@[simp] lemma sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := inf_sdiff_self_left
@[simp] lemma sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ := sdiff_self
lemma sdiff_inter_distrib_right (s t u : finset α) : s \ (t ∩ u) = (s \ t) ∪ (s \ u) := sdiff_inf
@[simp] lemma sdiff_inter_self_left (s t : finset α) : s \ (s ∩ t) = s \ t :=
sdiff_inf_self_left _ _
@[simp] lemma sdiff_inter_self_right (s t : finset α) : s \ (t ∩ s) = s \ t :=
sdiff_inf_self_right _ _
@[simp] lemma sdiff_empty : s \ ∅ = s := sdiff_bot
@[mono] lemma sdiff_subset_sdiff (hst : s ⊆ t) (hvu : v ⊆ u) : s \ u ⊆ t \ v :=
sdiff_le_sdiff ‹s ≤ t› ‹v ≤ u›
@[simp, norm_cast] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (s₁ \ s₂ : set α) :=
set.ext $ λ _, mem_sdiff
@[simp] lemma union_sdiff_self_eq_union : s ∪ t \ s = s ∪ t := sup_sdiff_self_right _ _
@[simp] lemma sdiff_union_self_eq_union : s \ t ∪ t = s ∪ t := sup_sdiff_self_left _ _
lemma union_sdiff_left (s t : finset α) : (s ∪ t) \ s = t \ s := sup_sdiff_left_self
lemma union_sdiff_right (s t : finset α) : (s ∪ t) \ t = s \ t := sup_sdiff_right_self
lemma union_sdiff_symm : s ∪ (t \ s) = t ∪ (s \ t) := by simp [union_comm]
lemma sdiff_union_inter (s t : finset α) : (s \ t) ∪ (s ∩ t) = s := sup_sdiff_inf _ _
@[simp] lemma sdiff_idem (s t : finset α) : s \ t \ t = s \ t := sdiff_idem
lemma sdiff_eq_empty_iff_subset : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff
lemma sdiff_nonempty : (s \ t).nonempty ↔ ¬ s ⊆ t :=
nonempty_iff_ne_empty.trans sdiff_eq_empty_iff_subset.not
@[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ := bot_sdiff
lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) :
(insert x s) \ t = insert x (s \ t) :=
begin
rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert],
exact set.insert_diff_of_not_mem s h
end
lemma insert_sdiff_of_mem (s : finset α) {x : α} (h : x ∈ t) : (insert x s) \ t = s \ t :=
begin
rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert],
exact set.insert_diff_of_mem s h
end
@[simp] lemma insert_sdiff_insert (s t : finset α) (x : α) :
(insert x s) \ (insert x t) = s \ insert x t :=
insert_sdiff_of_mem _ (mem_insert_self _ _)
lemma sdiff_insert_of_not_mem {x : α} (h : x ∉ s) (t : finset α) : s \ (insert x t) = s \ t :=
begin
refine subset.antisymm (sdiff_subset_sdiff (subset.refl _) (subset_insert _ _)) (λ y hy, _),
simp only [mem_sdiff, mem_insert, not_or_distrib] at hy ⊢,
exact ⟨hy.1, λ hxy, h $ hxy ▸ hy.1, hy.2⟩
end
@[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le
lemma sdiff_ssubset (h : t ⊆ s) (ht : t.nonempty) : s \ t ⊂ s := sdiff_lt ‹t ≤ s› ht.ne_empty
lemma union_sdiff_distrib (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t := sup_sdiff
lemma sdiff_union_distrib (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) := sdiff_sup
lemma union_sdiff_self (s t : finset α) : (s ∪ t) \ t = s \ t := sup_sdiff_right_self
lemma sdiff_singleton_eq_erase (a : α) (s : finset α) : s \ singleton a = erase s a :=
by { ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto }
@[simp] lemma sdiff_singleton_not_mem_eq_self (s : finset α) {a : α} (ha : a ∉ s) : s \ {a} = s :=
by simp only [sdiff_singleton_eq_erase, ha, erase_eq_of_not_mem, not_false_iff]
lemma sdiff_sdiff_left' (s t u : finset α) :
(s \ t) \ u = (s \ t) ∩ (s \ u) := sdiff_sdiff_left'
lemma sdiff_insert (s t : finset α) (x : α) :
s \ insert x t = (s \ t).erase x :=
by simp_rw [← sdiff_singleton_eq_erase, insert_eq,
sdiff_sdiff_left', sdiff_union_distrib, inter_comm]
lemma sdiff_insert_insert_of_mem_of_not_mem {s t : finset α} {x : α} (hxs : x ∈ s) (hxt : x ∉ t) :
insert x (s \ insert x t) = s \ t :=
by rw [sdiff_insert, insert_erase (mem_sdiff.mpr ⟨hxs, hxt⟩)]
lemma sdiff_erase {x : α} (hx : x ∈ s) : s \ s.erase x = {x} :=
begin
rw [← sdiff_singleton_eq_erase, sdiff_sdiff_right_self],
exact inf_eq_right.2 (singleton_subset_iff.2 hx),
end
lemma sdiff_sdiff_self_left (s t : finset α) : s \ (s \ t) = s ∩ t := sdiff_sdiff_right_self
lemma sdiff_sdiff_eq_self (h : t ⊆ s) : s \ (s \ t) = t := sdiff_sdiff_eq_self h
lemma sdiff_eq_sdiff_iff_inter_eq_inter {s t₁ t₂ : finset α} : s \ t₁ = s \ t₂ ↔ s ∩ t₁ = s ∩ t₂ :=
sdiff_eq_sdiff_iff_inf_eq_inf
lemma union_eq_sdiff_union_sdiff_union_inter (s t : finset α) :
s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) :=
sup_eq_sdiff_sup_sdiff_sup_inf
lemma erase_eq_empty_iff (s : finset α) (a : α) : s.erase a = ∅ ↔ s = ∅ ∨ s = {a} :=
by rw [←sdiff_singleton_eq_erase, sdiff_eq_empty_iff_subset, subset_singleton_iff]
/-! ### Symmetric difference -/
lemma mem_symm_diff : a ∈ s ∆ t ↔ a ∈ s ∧ a ∉ t ∨ a ∈ t ∧ a ∉ s :=
by simp_rw [symm_diff, sup_eq_union, mem_union, mem_sdiff]
@[simp, norm_cast] lemma coe_symm_diff : (↑(s ∆ t) : set α) = s ∆ t := set.ext $ λ _, mem_symm_diff
end decidable_eq
/-! ### attach -/
/-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype
`{x // x ∈ s}`. -/
def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩
theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : finset α} (hx : x ∈ s) :
sizeof x < sizeof s := by
{ cases s, dsimp [sizeof, has_sizeof.sizeof, finset.sizeof],
apply lt_add_left, exact multiset.sizeof_lt_sizeof_of_mem hx }
@[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl
@[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _
@[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl
@[simp] lemma attach_nonempty_iff (s : finset α) : s.attach.nonempty ↔ s.nonempty :=
by simp [finset.nonempty]
@[simp] lemma attach_eq_empty_iff (s : finset α) : s.attach = ∅ ↔ s = ∅ :=
by simpa [eq_empty_iff_forall_not_mem]
/-! ### piecewise -/
section piecewise
/-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its
complement. -/
def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Π i, δ i) [Π j, decidable (j ∈ s)] :
Π i, δ i :=
λi, if i ∈ s then f i else g i
variables {δ : α → Sort*} (s : finset α) (f g : Π i, δ i)
@[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀ i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g j = f j :=
by simp [piecewise]
@[simp] lemma piecewise_empty [Π i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g :=
by { ext i, simp [piecewise] }
variable [Π j, decidable (j ∈ s)]
-- TODO: fix this in norm_cast
@[norm_cast move] lemma piecewise_coe [∀ j, decidable (j ∈ (s : set α))] :
(s : set α).piecewise f g = s.piecewise f g :=
by { ext, congr }
@[simp, priority 980]
lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi]
@[simp, priority 980]
lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i :=
by simp [piecewise, hi]
lemma piecewise_congr {f f' g g' : Π i, δ i} (hf : ∀ i ∈ s, f i = f' i) (hg : ∀ i ∉ s, g i = g' i) :
s.piecewise f g = s.piecewise f' g' :=
funext $ λ i, if_ctx_congr iff.rfl (hf i) (hg i)
@[simp, priority 990]
lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀ i, decidable (i ∈ insert j s)]
(h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i :=
by simp [piecewise, h]
lemma piecewise_insert [decidable_eq α] (j : α) [∀ i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g = update (s.piecewise f g) j (f j) :=
by { classical, simp only [← piecewise_coe, coe_insert, ← set.piecewise_insert] }
lemma piecewise_cases {i} (p : δ i → Prop) (hf : p (f i)) (hg : p (g i)) : p (s.piecewise f g i) :=
by by_cases hi : i ∈ s; simpa [hi]
lemma piecewise_mem_set_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)}
{f g} (hf : f ∈ set.pi t t') (hg : g ∈ set.pi t t') : s.piecewise f g ∈ set.pi t t' :=
by { classical, rw ← piecewise_coe, exact set.piecewise_mem_pi ↑s hf hg }
lemma piecewise_singleton [decidable_eq α] (i : α) :
piecewise {i} f g = update g i (f i) :=
by rw [← insert_emptyc_eq, piecewise_insert, piecewise_empty]
lemma piecewise_piecewise_of_subset_left {s t : finset α} [Π i, decidable (i ∈ s)]
[Π i, decidable (i ∈ t)] (h : s ⊆ t) (f₁ f₂ g : Π a, δ a) :
s.piecewise (t.piecewise f₁ f₂) g = s.piecewise f₁ g :=
s.piecewise_congr (λ i hi, piecewise_eq_of_mem _ _ _ (h hi)) (λ _ _, rfl)
@[simp] lemma piecewise_idem_left (f₁ f₂ g : Π a, δ a) :
s.piecewise (s.piecewise f₁ f₂) g = s.piecewise f₁ g :=
piecewise_piecewise_of_subset_left (subset.refl _) _ _ _
lemma piecewise_piecewise_of_subset_right {s t : finset α} [Π i, decidable (i ∈ s)]
[Π i, decidable (i ∈ t)] (h : t ⊆ s) (f g₁ g₂ : Π a, δ a) :
s.piecewise f (t.piecewise g₁ g₂) = s.piecewise f g₂ :=
s.piecewise_congr (λ _ _, rfl) (λ i hi, t.piecewise_eq_of_not_mem _ _ (mt (@h _) hi))
@[simp] lemma piecewise_idem_right (f g₁ g₂ : Π a, δ a) :
s.piecewise f (s.piecewise g₁ g₂) = s.piecewise f g₂ :=
piecewise_piecewise_of_subset_right (subset.refl _) f g₁ g₂
lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) :
update f i v = piecewise (singleton i) (λj, v) f :=
(piecewise_singleton _ _ _).symm
lemma update_piecewise [decidable_eq α] (i : α) (v : δ i) :
update (s.piecewise f g) i v = s.piecewise (update f i v) (update g i v) :=
begin
ext j,
rcases em (j = i) with (rfl|hj); by_cases hs : j ∈ s; simp *
end
lemma update_piecewise_of_mem [decidable_eq α] {i : α} (hi : i ∈ s) (v : δ i) :
update (s.piecewise f g) i v = s.piecewise (update f i v) g :=
begin
rw update_piecewise,
refine s.piecewise_congr (λ _ _, rfl) (λ j hj, update_noteq _ _ _),
exact λ h, hj (h.symm ▸ hi)
end
lemma update_piecewise_of_not_mem [decidable_eq α] {i : α} (hi : i ∉ s) (v : δ i) :
update (s.piecewise f g) i v = s.piecewise f (update g i v) :=
begin
rw update_piecewise,
refine s.piecewise_congr (λ j hj, update_noteq _ _ _) (λ _ _, rfl),
exact λ h, hi (h ▸ hj)
end
lemma piecewise_le_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i}
(Hf : f ≤ h) (Hg : g ≤ h) : s.piecewise f g ≤ h :=
λ x, piecewise_cases s f g (≤ h x) (Hf x) (Hg x)
lemma le_piecewise_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i}
(Hf : h ≤ f) (Hg : h ≤ g) : h ≤ s.piecewise f g :=
λ x, piecewise_cases s f g (λ y, h x ≤ y) (Hf x) (Hg x)
lemma piecewise_le_piecewise' {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i}
(Hf : ∀ x ∈ s, f x ≤ f' x) (Hg : ∀ x ∉ s, g x ≤ g' x) : s.piecewise f g ≤ s.piecewise f' g' :=
λ x, by { by_cases hx : x ∈ s; simp [hx, *] }
lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i}
(Hf : f ≤ f') (Hg : g ≤ g') : s.piecewise f g ≤ s.piecewise f' g' :=
s.piecewise_le_piecewise' (λ x _, Hf x) (λ x _, Hg x)
lemma piecewise_mem_Icc_of_mem_of_mem {δ : α → Type*} [Π i, preorder (δ i)] {f f₁ g g₁ : Π i, δ i}
(hf : f ∈ set.Icc f₁ g₁) (hg : g ∈ set.Icc f₁ g₁) :
s.piecewise f g ∈ set.Icc f₁ g₁ :=
⟨le_piecewise_of_le_of_le _ hf.1 hg.1, piecewise_le_of_le_of_le _ hf.2 hg.2⟩
lemma piecewise_mem_Icc {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : f ≤ g) :
s.piecewise f g ∈ set.Icc f g :=
piecewise_mem_Icc_of_mem_of_mem _ (set.left_mem_Icc.2 h) (set.right_mem_Icc.2 h)
lemma piecewise_mem_Icc' {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : g ≤ f) :
s.piecewise f g ∈ set.Icc g f :=
piecewise_mem_Icc_of_mem_of_mem _ (set.right_mem_Icc.2 h) (set.left_mem_Icc.2 h)
end piecewise
section decidable_pi_exists
variables {s : finset α}
instance decidable_dforall_finset {p : Π a ∈ s, Prop} [hp : ∀ a (h : a ∈ s), decidable (p a h)] :
decidable (∀ a (h : a ∈ s), p a h) :=
multiset.decidable_dforall_multiset
/-- decidable equality for functions whose domain is bounded by finsets -/
instance decidable_eq_pi_finset {β : α → Type*} [h : ∀ a, decidable_eq (β a)] :
decidable_eq (Π a ∈ s, β a) :=
multiset.decidable_eq_pi_multiset
instance decidable_dexists_finset {p : Π a ∈ s, Prop} [hp : ∀ a (h : a ∈ s), decidable (p a h)] :
decidable (∃ a (h : a ∈ s), p a h) :=
multiset.decidable_dexists_multiset
end decidable_pi_exists
/-! ### filter -/
section filter
variables (p q : α → Prop) [decidable_pred p] [decidable_pred q]
/-- `filter p s` is the set of elements of `s` that satisfy `p`. -/
def filter (s : finset α) : finset α := ⟨_, s.2.filter p⟩
@[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl
@[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ _
variable {p}
@[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter
lemma mem_of_mem_filter {s : finset α} (x : α) (h : x ∈ s.filter p) : x ∈ s :=
mem_of_mem_filter h
theorem filter_ssubset {s : finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬ p x :=
⟨λ h, let ⟨x, hs, hp⟩ := set.exists_of_ssubset h in ⟨x, hs, mt (λ hp, mem_filter.2 ⟨hs, hp⟩) hp⟩,
λ ⟨x, hs, hp⟩, ⟨s.filter_subset _, λ h, hp (mem_filter.1 (h hs)).2⟩⟩
variable (p)
theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) :=
ext $ assume a, by simp only [mem_filter, and_comm, and.left_comm]
lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] :
@finset.filter α (λ _, true) h s = s :=
by ext; simp
@[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ :=
ext $ assume a, by simp only [mem_filter, and_false]; refl
variables {p q}
lemma filter_eq_self (s : finset α) :
s.filter p = s ↔ ∀ x ∈ s, p x :=
by simp [finset.ext_iff]
/-- If all elements of a `finset` satisfy the predicate `p`, `s.filter p` is `s`. -/
@[simp] lemma filter_true_of_mem {s : finset α} (h : ∀ x ∈ s, p x) : s.filter p = s :=
(filter_eq_self s).mpr h
/-- If all elements of a `finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/
lemma filter_false_of_mem {s : finset α} (h : ∀ x ∈ s, ¬ p x) : s.filter p = ∅ :=
eq_empty_of_forall_not_mem (by simpa)
lemma filter_eq_empty_iff (s : finset α) :
(s.filter p = ∅) ↔ ∀ x ∈ s, ¬ p x :=
begin
refine ⟨_, filter_false_of_mem⟩,
intros hs,
injection hs with hs',
rwa filter_eq_nil at hs'
end
lemma filter_nonempty_iff {s : finset α} : (s.filter p).nonempty ↔ ∃ a ∈ s, p a :=
by simp only [nonempty_iff_ne_empty, ne.def, filter_eq_empty_iff, not_not, not_forall]
lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s :=
eq_of_veq $ filter_congr H
variables (p q)
lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ _
lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p :=
assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩
lemma monotone_filter_left : monotone (filter p) :=
λ _ _, filter_subset_filter p
lemma monotone_filter_right (s : finset α) ⦃p q : α → Prop⦄
[decidable_pred p] [decidable_pred q] (h : p ≤ q) :
s.filter p ≤ s.filter q :=
multiset.subset_of_le (multiset.monotone_filter_right s.val h)
@[simp, norm_cast] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) :=
set.ext $ λ _, mem_filter
lemma subset_coe_filter_of_subset_forall (s : finset α) {t : set α}
(h₁ : t ⊆ s) (h₂ : ∀ x ∈ t, p x) : t ⊆ s.filter p :=
λ x hx, (s.coe_filter p).symm ▸ ⟨h₁ hx, h₂ x hx⟩
theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ :=
by { classical, ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] }
theorem filter_cons_of_pos (a : α) (s : finset α) (ha : a ∉ s) (hp : p a):
filter p (cons a s ha) = cons a (filter p s) (mem_filter.not.mpr $ mt and.left ha) :=
eq_of_veq $ multiset.filter_cons_of_pos s.val hp
theorem filter_cons_of_neg (a : α) (s : finset α) (ha : a ∉ s) (hp : ¬p a):
filter p (cons a s ha) = filter p s :=
eq_of_veq $ multiset.filter_cons_of_neg s.val hp
theorem filter_disj_union (s : finset α) (t : finset α) (h : ∀ (a : α), a ∈ s → a ∉ t) :
filter p (disj_union s t h) = (filter p s).disj_union (filter p t)
(λ a hs ht, h a (mem_of_mem_filter _ hs) (mem_of_mem_filter _ ht)) :=
eq_of_veq $ multiset.filter_add _ _ _
theorem filter_cons {a : α} (s : finset α) (ha : a ∉ s) :
filter p (cons a s ha) = (if p a then {a} else ∅ : finset α).disj_union (filter p s) (λ b hb, by
{ split_ifs at hb,
{ rw finset.mem_singleton.mp hb,
exact (mem_filter.not.mpr $ mt and.left ha) },
{ cases hb } }) :=
begin
split_ifs with h,
{ rw [filter_cons_of_pos _ _ _ ha h, singleton_disj_union] },
{ rw [filter_cons_of_neg _ _ _ ha h, empty_disj_union] },
end
variable [decidable_eq α]
theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p :=
ext $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right]
theorem filter_union_right (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) :=
ext $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm]
lemma filter_mem_eq_inter {s t : finset α} [Π i, decidable (i ∈ t)] :
s.filter (λ i, i ∈ t) = s ∩ t :=
ext $ λ i, by rw [mem_filter, mem_inter]
lemma filter_inter_distrib (s t : finset α) : (s ∩ t).filter p = s.filter p ∩ t.filter p :=
by { ext, simp only [mem_filter, mem_inter], exact and_and_distrib_right _ _ _ }
theorem filter_inter (s t : finset α) : filter p s ∩ t = filter p (s ∩ t) :=
by { ext, simp only [mem_inter, mem_filter, and.right_comm] }
theorem inter_filter (s t : finset α) : s ∩ filter p t = filter p (s ∩ t) :=
by rw [inter_comm, filter_inter, inter_comm]
theorem filter_insert (a : α) (s : finset α) :
filter p (insert a s) = if p a then insert a (filter p s) else filter p s :=
by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] }
theorem filter_erase (a : α) (s : finset α) : filter p (erase s a) = erase (filter p s) a :=
by { ext x, simp only [and_assoc, mem_filter, iff_self, mem_erase] }
theorem filter_or [decidable_pred (λ a, p a ∨ q a)] (s : finset α) :
s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q :=
ext $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left]
theorem filter_and [decidable_pred (λ a, p a ∧ q a)] (s : finset α) :
s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q :=
ext $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self]
theorem filter_not [decidable_pred (λ a, ¬ p a)] (s : finset α) :
s.filter (λ a, ¬ p a) = s \ s.filter p :=
ext $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $
λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm
theorem sdiff_eq_filter (s₁ s₂ : finset α) :
s₁ \ s₂ = filter (∉ s₂) s₁ := ext $ λ _, by simp only [mem_sdiff, mem_filter]
lemma sdiff_eq_self (s₁ s₂ : finset α) : s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ :=
by { simp [subset.antisymm_iff],
split; intro h,
{ transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp },
{ calc s₁ \ s₂
⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)]
... ⊇ s₁ \ ∅ : by mono using [(⊇)]
... ⊇ s₁ : by simp [(⊇)] } }
theorem filter_union_filter_neg_eq [decidable_pred (λ a, ¬ p a)]
(s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s :=
by simp only [filter_not, union_sdiff_of_subset (filter_subset p s)]
theorem filter_inter_filter_neg_eq [decidable_pred (λ a, ¬ p a)]
(s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ :=
by simp only [filter_not, inter_sdiff_self]
lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) :
∃ s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ :=
begin
classical,
refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩,
{ simp [filter_union_right, em] },
{ intro x, simp },
{ intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ }
end
/- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/
@[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p)
[decidable_pred p] : @filter α p h s = s.filter p :=
by congr
section classical
open_locale classical
/-- The following instance allows us to write `{x ∈ s | p x}` for `finset.filter p s`.
Since the former notation requires us to define this for all propositions `p`, and `finset.filter`
only works for decidable propositions, the notation `{x ∈ s | p x}` is only compatible with
classical logic because it uses `classical.prop_decidable`.
We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp`
unfolds the notation `{x ∈ s | p x}` to `finset.filter p s`. If `p` happens to be decidable, the
simp-lemma `finset.filter_congr_decidable` will make sure that `finset.filter` uses the right
instance for decidability.
-/
noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩
@[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl
end classical
/--
After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq'` with the equality the other way.
-/
-- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing
-- on, e.g. `x ∈ s.filter(eq b)`.
lemma filter_eq [decidable_eq β] (s : finset β) (b : β) : s.filter (eq b) = ite (b ∈ s) {b} ∅ :=
begin
split_ifs,
{ ext,
simp only [mem_filter, mem_singleton],
exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩ }⟩ },
{ ext,
simp only [mem_filter, not_and, iff_false, not_mem_empty],
rintro m ⟨e⟩, exact h m }
end
/--
After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq` with the equality the other way.
-/
lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) :
s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ :=
trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b)
lemma filter_ne [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, b ≠ a) = s.erase b :=
by { ext, simp only [mem_filter, mem_erase, ne.def], tauto }
lemma filter_ne' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a ≠ b) = s.erase b :=
trans (filter_congr (λ _ _, ⟨ne.symm, ne.symm⟩)) (filter_ne s b)
end filter
/-! ### range -/
section range
variables {n m l : ℕ}
/-- `range n` is the set of natural numbers less than `n`. -/
def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩
@[simp] theorem range_coe (n : ℕ) : (range n).1 = multiset.range n := rfl
@[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range
@[simp] theorem range_zero : range 0 = ∅ := rfl
@[simp] theorem range_one : range 1 = {0} := rfl
theorem range_succ : range (succ n) = insert n (range n) :=
eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm
lemma range_add_one : range (n + 1) = insert n (range n) := range_succ
@[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self
@[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := multiset.self_mem_range_succ n
@[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset
theorem range_mono : monotone range := λ _ _, range_subset.2
lemma mem_range_succ_iff {a b : ℕ} : a ∈ finset.range b.succ ↔ a ≤ b :=
finset.mem_range.trans nat.lt_succ_iff
lemma mem_range_le {n x : ℕ} (hx : x ∈ range n) : x ≤ n := (mem_range.1 hx).le
lemma mem_range_sub_ne_zero {n x : ℕ} (hx : x ∈ range n) : n - x ≠ 0 :=
ne_of_gt $ tsub_pos_of_lt $ mem_range.1 hx
@[simp] lemma nonempty_range_iff : (range n).nonempty ↔ n ≠ 0 :=
⟨λ ⟨k, hk⟩, ((zero_le k).trans_lt $ mem_range.1 hk).ne',
λ h, ⟨0, mem_range.2 $ pos_iff_ne_zero.2 h⟩⟩
@[simp] lemma range_eq_empty_iff : range n = ∅ ↔ n = 0 :=
by rw [← not_nonempty_iff_eq_empty, nonempty_range_iff, not_not]
lemma nonempty_range_succ : (range $ n + 1).nonempty :=
nonempty_range_iff.2 n.succ_ne_zero
end range
/- useful rules for calculations with quantifiers -/
theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false :=
by simp only [not_mem_empty, false_and, exists_false]
lemma exists_mem_insert [decidable_eq α] (a : α) (s : finset α) (p : α → Prop) :
(∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ ∃ x, x ∈ s ∧ p x :=
by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left]
theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true :=
iff_true_intro $ λ _, false.elim
lemma forall_mem_insert [decidable_eq α] (a : α) (s : finset α) (p : α → Prop) :
(∀ x, x ∈ insert a s → p x) ↔ p a ∧ ∀ x, x ∈ s → p x :=
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
end finset
/-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/
def not_mem_range_equiv (k : ℕ) : {n // n ∉ range k} ≃ ℕ :=
{ to_fun := λ i, i.1 - k,
inv_fun := λ j, ⟨j + k, by simp⟩,
left_inv := λ j,
begin
rw subtype.ext_iff_val,
apply tsub_add_cancel_of_le,
simpa using j.2
end,
right_inv := λ j, add_tsub_cancel_right _ _ }
@[simp] lemma coe_not_mem_range_equiv (k : ℕ) :
(not_mem_range_equiv k : {n // n ∉ range k} → ℕ) = (λ i, i - k) := rfl
@[simp] lemma coe_not_mem_range_equiv_symm (k : ℕ) :
((not_mem_range_equiv k).symm : ℕ → {n // n ∉ range k}) = λ j, ⟨j + k, by simp⟩ := rfl
/-! ### dedup on list and multiset -/
namespace multiset
variable [decidable_eq α]
/-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/
def to_finset (s : multiset α) : finset α := ⟨_, nodup_dedup s⟩
@[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.dedup := rfl
theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset :=
finset.val_inj.1 n.dedup.symm
lemma nodup.to_finset_inj {l l' : multiset α} (hl : nodup l) (hl' : nodup l')
(h : l.to_finset = l'.to_finset) : l = l' :=
by simpa [←to_finset_eq hl, ←to_finset_eq hl'] using h
@[simp] lemma mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_dedup
@[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl
@[simp] lemma to_finset_cons (a : α) (s : multiset α) :
to_finset (a ::ₘ s) = insert a (to_finset s) :=
finset.eq_of_veq dedup_cons
@[simp] lemma to_finset_singleton (a : α) : to_finset ({a} : multiset α) = {a} :=
by rw [←cons_zero, to_finset_cons, to_finset_zero, is_lawful_singleton.insert_emptyc_eq]
@[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t :=
finset.ext $ by simp
@[simp] lemma to_finset_nsmul (s : multiset α) :
∀ (n : ℕ) (hn : n ≠ 0), (n • s).to_finset = s.to_finset
| 0 h := by contradiction
| (n+1) h :=
begin
by_cases n = 0,
{ rw [h, zero_add, one_nsmul] },
{ rw [add_nsmul, to_finset_add, one_nsmul, to_finset_nsmul n h, finset.union_idempotent] }
end
@[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t :=
finset.ext $ by simp
@[simp] lemma to_finset_union (s t : multiset α) : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset :=
by ext; simp
@[simp] theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 :=
finset.val_inj.symm.trans multiset.dedup_eq_zero
@[simp] lemma to_finset_subset (s t : multiset α) : s.to_finset ⊆ t.to_finset ↔ s ⊆ t :=
by simp only [finset.subset_iff, multiset.subset_iff, multiset.mem_to_finset]
end multiset
namespace finset
@[simp] lemma val_to_finset [decidable_eq α] (s : finset α) : s.val.to_finset = s :=
by { ext, rw [multiset.mem_to_finset, ←mem_def] }
lemma val_le_iff_val_subset {a : finset α} {b : multiset α} : a.val ≤ b ↔ a.val ⊆ b :=
multiset.le_iff_subset a.nodup
end finset
namespace list
variables [decidable_eq α] {l l' : list α} {a : α}
/-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/
def to_finset (l : list α) : finset α := multiset.to_finset l
@[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.dedup : multiset α) := rfl
@[simp] theorem to_finset_coe (l : list α) : (l : multiset α).to_finset = l.to_finset := rfl
lemma to_finset_eq (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n
@[simp] lemma mem_to_finset : a ∈ l.to_finset ↔ a ∈ l := mem_dedup
@[simp] lemma to_finset_nil : to_finset (@nil α) = ∅ := rfl
@[simp] lemma to_finset_cons : to_finset (a :: l) = insert a (to_finset l) :=
finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.dedup_cons, h]
lemma to_finset_surj_on : set.surj_on to_finset {l : list α | l.nodup} set.univ :=
by { rintro ⟨⟨l⟩, hl⟩ _, exact ⟨l, hl, (to_finset_eq hl).symm⟩ }
theorem to_finset_surjective : surjective (to_finset : list α → finset α) :=
λ s, let ⟨l, _, hls⟩ := to_finset_surj_on (set.mem_univ s) in ⟨l, hls⟩
lemma to_finset_eq_iff_perm_dedup : l.to_finset = l'.to_finset ↔ l.dedup ~ l'.dedup :=
by simp [finset.ext_iff, perm_ext (nodup_dedup _) (nodup_dedup _)]
lemma to_finset.ext_iff {a b : list α} : a.to_finset = b.to_finset ↔ ∀ x, x ∈ a ↔ x ∈ b :=
by simp only [finset.ext_iff, mem_to_finset]
lemma to_finset.ext : (∀ x, x ∈ l ↔ x ∈ l') → l.to_finset = l'.to_finset := to_finset.ext_iff.mpr
lemma to_finset_eq_of_perm (l l' : list α) (h : l ~ l') : l.to_finset = l'.to_finset :=
to_finset_eq_iff_perm_dedup.mpr h.dedup
lemma perm_of_nodup_nodup_to_finset_eq (hl : nodup l) (hl' : nodup l')
(h : l.to_finset = l'.to_finset) : l ~ l' :=
by { rw ←multiset.coe_eq_coe, exact multiset.nodup.to_finset_inj hl hl' h }
@[simp] lemma to_finset_append : to_finset (l ++ l') = l.to_finset ∪ l'.to_finset :=
begin
induction l with hd tl hl,
{ simp },
{ simp [hl] }
end
@[simp] lemma to_finset_reverse {l : list α} : to_finset l.reverse = l.to_finset :=
to_finset_eq_of_perm _ _ (reverse_perm l)
lemma to_finset_repeat_of_ne_zero {n : ℕ} (hn : n ≠ 0) : (list.repeat a n).to_finset = {a} :=
by { ext x, simp [hn, list.mem_repeat] }
@[simp] lemma to_finset_union (l l' : list α) : (l ∪ l').to_finset = l.to_finset ∪ l'.to_finset :=
by { ext, simp }
@[simp] lemma to_finset_inter (l l' : list α) : (l ∩ l').to_finset = l.to_finset ∩ l'.to_finset :=
by { ext, simp }
@[simp] lemma to_finset_eq_empty_iff (l : list α) : l.to_finset = ∅ ↔ l = nil := by cases l; simp
end list
namespace finset
/-! ### map -/
section map
open function
/-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image
finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/
def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, s.2.map f.2⟩
@[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl
@[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl
variables {f : α ↪ β} {s : finset α}
@[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b :=
mem_map.trans $ by simp only [exists_prop]; refl
@[simp] lemma mem_map_equiv {f : α ≃ β} {b : β} : b ∈ s.map f.to_embedding ↔ f.symm b ∈ s :=
by { rw mem_map, exact ⟨by { rintro ⟨a, H, rfl⟩, simpa }, λ h, ⟨_, h, by simp⟩⟩ }
lemma mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_injective f.2
lemma mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2
lemma forall_mem_map {f : α ↪ β} {s : finset α} {p : Π a, a ∈ s.map f → Prop} :
(∀ y ∈ s.map f, p y H) ↔ ∀ x ∈ s, p (f x) (mem_map_of_mem _ H) :=
⟨λ h y hy, h (f y) (mem_map_of_mem _ hy), λ h x hx,
by { obtain ⟨y, hy, rfl⟩ := mem_map.1 hx, exact h _ hy }⟩
lemma apply_coe_mem_map (f : α ↪ β) (s : finset α) (x : s) : f x ∈ s.map f :=
mem_map_of_mem f x.prop
@[simp, norm_cast] theorem coe_map (f : α ↪ β) (s : finset α) : (s.map f : set β) = f '' s :=
set.ext $ λ x, mem_map.trans set.mem_image_iff_bex.symm
theorem coe_map_subset_range (f : α ↪ β) (s : finset α) : (s.map f : set β) ⊆ set.range f :=
calc ↑(s.map f) = f '' s : coe_map f s
... ⊆ set.range f : set.image_subset_range f ↑s
/-- If the only elements outside `s` are those left fixed by `σ`, then mapping by `σ` has no effect.
-/
lemma map_perm {σ : equiv.perm α} (hs : {a | σ a ≠ a} ⊆ s) : s.map (σ : α ↪ α) = s :=
coe_injective $ (coe_map _ _).trans $ set.image_perm hs
theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} :
s.to_finset.map f = (s.map f).to_finset :=
ext $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset]
@[simp] theorem map_refl : s.map (embedding.refl _) = s :=
ext $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right
@[simp] theorem map_cast_heq {α β} (h : α = β) (s : finset α) :
s.map (equiv.cast h).to_embedding == s :=
by { subst h, simp }
theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) :=
eq_of_veq $ by simp only [map_val, multiset.map_map]; refl
lemma map_comm {β'} {f : β ↪ γ} {g : α ↪ β} {f' : α ↪ β'} {g' : β' ↪ γ}
(h_comm : ∀ a, f (g a) = g' (f' a)) :
(s.map g).map f = (s.map f').map g' :=
by simp_rw [map_map, embedding.trans, function.comp, h_comm]
lemma _root_.function.semiconj.finset_map {f : α ↪ β} {ga : α ↪ α} {gb : β ↪ β}
(h : function.semiconj f ga gb) :
function.semiconj (map f) (map ga) (map gb) :=
λ s, map_comm h
lemma _root_.function.commute.finset_map {f g : α ↪ α} (h : function.commute f g) :
function.commute (map f) (map g) :=
h.finset_map
@[simp] theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ :=
⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs,
λ h, by simp [subset_def, map_subset_map h]⟩
/-- Associate to an embedding `f` from `α` to `β` the order embedding that maps a finset to its
image under `f`. -/
def map_embedding (f : α ↪ β) : finset α ↪o finset β :=
order_embedding.of_map_le_iff (map f) (λ _ _, map_subset_map)
@[simp] theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ :=
(map_embedding f).injective.eq_iff
lemma map_injective (f : α ↪ β) : injective (map f) := (map_embedding f).injective
@[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl
theorem map_filter {p : β → Prop} [decidable_pred p] :
(s.map f).filter p = (s.filter (p ∘ f)).map f :=
eq_of_veq (map_filter _ _ _)
/-- A helper lemma to produce a default proof for `finset.map_disj_union`. -/
theorem map_disj_union_aux {f : α ↪ β} {s₁ s₂ : finset α} :
(∀ a, a ∈ s₁ → a ∉ s₂) ↔ ∀ a, a ∈ map f s₁ → a ∉ map f s₂ :=
by simp_rw [forall_mem_map, mem_map']
theorem map_disj_union {f : α ↪ β} (s₁ s₂ : finset α) (h) (h' := map_disj_union_aux.1 h) :
(s₁.disj_union s₂ h).map f = (s₁.map f).disj_union (s₂.map f) h' :=
eq_of_veq $ multiset.map_add _ _ _
/-- A version of `finset.map_disj_union` for writing in the other direction. -/
theorem map_disj_union' {f : α ↪ β} (s₁ s₂ : finset α) (h') (h := map_disj_union_aux.2 h') :
(s₁.disj_union s₂ h).map f = (s₁.map f).disj_union (s₂.map f) h' :=
map_disj_union _ _ _
theorem map_union [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f :=
coe_injective $ by simp only [coe_map, coe_union, set.image_union]
theorem map_inter [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f :=
coe_injective $ by simp only [coe_map, coe_inter, set.image_inter f.injective]
@[simp] theorem map_singleton (f : α ↪ β) (a : α) : map f {a} = {f a} :=
coe_injective $ by simp only [coe_map, coe_singleton, set.image_singleton]
@[simp] lemma map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) :
(insert a s).map f = insert (f a) (s.map f) :=
by simp only [insert_eq, map_union, map_singleton]
@[simp] lemma map_cons (f : α ↪ β) (a : α) (s : finset α) (ha : a ∉ s) :
(cons a s ha).map f = cons (f a) (s.map f) (by simpa using ha) :=
eq_of_veq $ multiset.map_cons f a s.val
@[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
@[simp] lemma map_nonempty : (s.map f).nonempty ↔ s.nonempty :=
by rw [nonempty_iff_ne_empty, nonempty_iff_ne_empty, ne.def, map_eq_empty]
alias map_nonempty ↔ _ nonempty.map
lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s :=
eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _
lemma disjoint_range_add_left_embedding (a b : ℕ) :
disjoint (range a) (map (add_left_embedding a) (range b)) :=
begin
intros k hk,
simp only [exists_prop, mem_range, inf_eq_inter, mem_map, add_left_embedding_apply,
mem_inter] at hk,
obtain ⟨a, haQ, ha⟩ := hk.2,
simpa [← ha] using hk.1,
end
lemma disjoint_range_add_right_embedding (a b : ℕ) :
disjoint (range a) (map (add_right_embedding a) (range b)) :=
begin
intros k hk,
simp only [exists_prop, mem_range, inf_eq_inter, mem_map, add_left_embedding_apply,
mem_inter] at hk,
obtain ⟨a, haQ, ha⟩ := hk.2,
simpa [← ha] using hk.1,
end
end map
lemma range_add_one' (n : ℕ) :
range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ.inj⟩) :=
by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n]
/-! ### image -/
section image
variables [decidable_eq β]
/-- `image f s` is the forward image of `s` under `f`. -/
def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset
@[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).dedup := rfl
@[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl
variables {f g : α → β} {s : finset α} {t : finset β} {a : α} {b c : β}
@[simp] lemma mem_image : b ∈ s.image f ↔ ∃ a ∈ s, f a = b :=
by simp only [mem_def, image_val, mem_dedup, multiset.mem_map, exists_prop]
lemma mem_image_of_mem (f : α → β) {a} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩
@[simp] lemma mem_image_const : c ∈ s.image (const α b) ↔ s.nonempty ∧ b = c :=
by { rw mem_image, simp only [exists_prop, const_apply, exists_and_distrib_right], refl }
lemma mem_image_const_self : b ∈ s.image (const α b) ↔ s.nonempty :=
mem_image_const.trans $ and_iff_left rfl
instance [can_lift β α] : can_lift (finset β) (finset α) :=
{ cond := λ s, ∀ x ∈ s, can_lift.cond α x,
coe := image can_lift.coe,
prf :=
begin
rintro ⟨⟨l⟩, hd : l.nodup⟩ hl,
lift l to list α using hl,
exact ⟨⟨l, hd.of_map _⟩, ext $ λ a, by simp⟩,
end }
lemma image_congr (h : (s : set α).eq_on f g) : finset.image f s = finset.image g s :=
by { ext, simp_rw mem_image, exact bex_congr (λ x hx, by rw h hx) }
lemma _root_.function.injective.mem_finset_image (hf : injective f) : f a ∈ s.image f ↔ a ∈ s :=
begin
refine ⟨λ h, _, finset.mem_image_of_mem f⟩,
obtain ⟨y, hy, heq⟩ := mem_image.1 h,
exact hf heq ▸ hy,
end
lemma filter_mem_image_eq_image (f : α → β) (s : finset α) (t : finset β) (h : ∀ x ∈ s, f x ∈ t) :
t.filter (λ y, y ∈ s.image f) = s.image f :=
by { ext, rw [mem_filter, mem_image],
simp only [and_imp, exists_prop, and_iff_right_iff_imp, exists_imp_distrib],
rintros x xel rfl, exact h _ xel }
lemma fiber_nonempty_iff_mem_image (f : α → β) (s : finset α) (y : β) :
(s.filter (λ x, f x = y)).nonempty ↔ y ∈ s.image f :=
by simp [finset.nonempty]
@[simp, norm_cast] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s :=
set.ext $ λ _, mem_image.trans set.mem_image_iff_bex.symm
protected lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty :=
let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩
@[simp] lemma nonempty.image_iff (f : α → β) : (s.image f).nonempty ↔ s.nonempty :=
⟨λ ⟨y, hy⟩, let ⟨x, hx, _⟩ := mem_image.mp hy in ⟨x, hx⟩, λ h, h.image f⟩
theorem image_to_finset [decidable_eq α] {s : multiset α} :
s.to_finset.image f = (s.map f).to_finset :=
ext $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map]
lemma image_val_of_inj_on (H : set.inj_on f s) : (image f s).1 = s.1.map f := (s.2.map_on H).dedup
@[simp] lemma image_id [decidable_eq α] : s.image id = s :=
ext $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right]
@[simp] theorem image_id' [decidable_eq α] : s.image (λ x, x) = s := image_id
theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) :=
eq_of_veq $ by simp only [image_val, dedup_map_dedup_eq, multiset.map_map]
lemma image_comm {β'} [decidable_eq β'] [decidable_eq γ] {f : β → γ} {g : α → β}
{f' : α → β'} {g' : β' → γ} (h_comm : ∀ a, f (g a) = g' (f' a)) :
(s.image g).image f = (s.image f').image g' :=
by simp_rw [image_image, comp, h_comm]
lemma _root_.function.semiconj.finset_image [decidable_eq α] {f : α → β} {ga : α → α} {gb : β → β}
(h : function.semiconj f ga gb) :
function.semiconj (image f) (image ga) (image gb) :=
λ s, image_comm h
lemma _root_.function.commute.finset_image [decidable_eq α] {f g : α → α}
(h : function.commute f g) :
function.commute (image f) (image g) :=
h.finset_image
theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f :=
by simp only [subset_def, image_val, subset_dedup', dedup_subset',
multiset.map_subset_map h]
lemma image_subset_iff : s.image f ⊆ t ↔ ∀ x ∈ s, f x ∈ t :=
calc s.image f ⊆ t ↔ f '' ↑s ⊆ ↑t : by norm_cast
... ↔ _ : set.image_subset_iff
theorem image_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image
lemma image_subset_image_iff {t : finset α} (hf : injective f) : s.image f ⊆ t.image f ↔ s ⊆ t :=
by { simp_rw ←coe_subset, push_cast, exact set.image_subset_image_iff hf }
theorem coe_image_subset_range : ↑(s.image f) ⊆ set.range f :=
calc ↑(s.image f) = f '' ↑s : coe_image
... ⊆ set.range f : set.image_subset_range f ↑s
theorem image_filter {p : β → Prop} [decidable_pred p] :
(s.image f).filter p = (s.filter (p ∘ f)).image f :=
ext $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact
⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩,
by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩
theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) :
(s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f :=
ext $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right,
exists_or_distrib]
lemma image_inter_subset [decidable_eq α] (f : α → β) (s t : finset α) :
(s ∩ t).image f ⊆ s.image f ∩ t.image f :=
subset_inter (image_subset_image $ inter_subset_left _ _) $
image_subset_image $ inter_subset_right _ _
lemma image_inter_of_inj_on [decidable_eq α] {f : α → β} (s t : finset α)
(hf : set.inj_on f (s ∪ t)) :
(s ∩ t).image f = s.image f ∩ t.image f :=
(image_inter_subset _ _ _).antisymm $ λ x, begin
simp only [mem_inter, mem_image],
rintro ⟨⟨a, ha, rfl⟩, b, hb, h⟩,
exact ⟨a, ⟨ha, by rwa ←hf (or.inr hb) (or.inl ha) h⟩, rfl⟩,
end
lemma image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : injective f) :
(s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f :=
image_inter_of_inj_on _ _ $ hf.inj_on _
@[simp] theorem image_singleton (f : α → β) (a : α) : image f {a} = {f a} :=
ext $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm
@[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) :
(insert a s).image f = insert (f a) (s.image f) :=
by simp only [insert_eq, image_singleton, image_union]
lemma erase_image_subset_image_erase [decidable_eq α] (f : α → β) (s : finset α) (a : α) :
(s.image f).erase (f a) ⊆ (s.erase a).image f :=
begin
simp only [subset_iff, and_imp, exists_prop, mem_image, exists_imp_distrib, mem_erase],
rintro b hb x hx rfl,
exact ⟨_, ⟨ne_of_apply_ne f hb, hx⟩, rfl⟩,
end
@[simp] lemma image_erase [decidable_eq α] {f : α → β} (hf : injective f) (s : finset α) (a : α) :
(s.erase a).image f = (s.image f).erase (f a) :=
begin
refine (erase_image_subset_image_erase _ _ _).antisymm' (λ b, _),
simp only [mem_image, exists_prop, mem_erase],
rintro ⟨a', ⟨haa', ha'⟩, rfl⟩,
exact ⟨hf.ne haa', a', ha', rfl⟩,
end
@[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma mem_range_iff_mem_finset_range_of_mod_eq' [decidable_eq α] {f : ℕ → α} {a : α} {n : ℕ}
(hn : 0 < n) (h : ∀ i, f (i % n) = f i) :
a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) :=
begin
split,
{ rintros ⟨i, hi⟩,
simp only [mem_image, exists_prop, mem_range],
exact ⟨i % n, nat.mod_lt i hn, (rfl.congr hi).mp (h i)⟩ },
{ rintro h,
simp only [mem_image, exists_prop, set.mem_range, mem_range] at *,
rcases h with ⟨i, hi, ha⟩,
exact ⟨i, ha⟩ }
end
lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ}
(hn : 0 < n) (h : ∀ i, f (i % n) = f i) :
a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) :=
suffices (∃ i, f (i % n) = a) ↔ ∃ i, i < n ∧ f ↑i = a, by simpa [h],
have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn,
iff.intro
(assume ⟨i, hi⟩,
have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'),
⟨int.to_nat (i % n),
by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩)
(assume ⟨i, hi, ha⟩,
⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩)
lemma range_add (a b : ℕ) : range (a + b) = range a ∪ (range b).map (add_left_embedding a) :=
by { rw [←val_inj, union_val], exact multiset.range_add_eq_union a b }
@[simp] lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s :=
eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, dedup_eq_self]
@[simp] lemma attach_image_coe [decidable_eq α] {s : finset α} : s.attach.image coe = s :=
finset.attach_image_val
@[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} :
attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s})
((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) :=
ext $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx)
(λ h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h)
(λ h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩),
λ _, finset.mem_attach _ _⟩
theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f :=
eq_of_veq (s.map f).2.dedup.symm
lemma image_const {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b :=
ext $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right,
h.bex, true_and, mem_singleton, eq_comm]
@[simp] lemma map_erase [decidable_eq α] (f : α ↪ β) (s : finset α) (a : α) :
(s.erase a).map f = (s.map f).erase (f a) :=
by { simp_rw map_eq_image, exact s.image_erase f.2 a }
/-! ### Subtype -/
/-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose
elements belong to `s`. -/
protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) :=
(s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩,
λ x y H, subtype.eq $ subtype.mk.inj H⟩
@[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} :
∀ {a : subtype p}, a ∈ s.subtype p ↔ (a : α) ∈ s
| ⟨a, ha⟩ := by simp [finset.subtype, ha]
lemma subtype_eq_empty {p : α → Prop} [decidable_pred p] {s : finset α} :
s.subtype p = ∅ ↔ ∀ x, p x → x ∉ s :=
by simp [ext_iff, subtype.forall, subtype.coe_mk]; refl
@[mono] lemma subtype_mono {p : α → Prop} [decidable_pred p] : monotone (finset.subtype p) :=
λ s t h x hx, mem_subtype.2 $ h $ mem_subtype.1 hx
/-- `s.subtype p` converts back to `s.filter p` with
`embedding.subtype`. -/
@[simp] lemma subtype_map (p : α → Prop) [decidable_pred p] :
(s.subtype p).map (embedding.subtype _) = s.filter p :=
begin
ext x,
simp [and_comm _ (_ = _), @and.left_comm _ (_ = _), and_comm (p x) (x ∈ s)]
end
/-- If all elements of a `finset` satisfy the predicate `p`,
`s.subtype p` converts back to `s` with `embedding.subtype`. -/
lemma subtype_map_of_mem {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) :
(s.subtype p).map (embedding.subtype _) = s :=
by rw [subtype_map, filter_true_of_mem h]
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, all elements of the result have the property of
the subtype. -/
lemma property_of_mem_map_subtype {p : α → Prop} (s : finset {x // p x}) {a : α}
(h : a ∈ s.map (embedding.subtype _)) : p a :=
begin
rcases mem_map.1 h with ⟨x, hx, rfl⟩,
exact x.2
end
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, the result does not contain any value that does
not satisfy the property of the subtype. -/
lemma not_mem_map_subtype_of_not_property {p : α → Prop} (s : finset {x // p x})
{a : α} (h : ¬ p a) : a ∉ (s.map (embedding.subtype _)) :=
mt s.property_of_mem_map_subtype h
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, the result is a subset of the set giving the
subtype. -/
lemma map_subtype_subset {t : set α} (s : finset t) : ↑(s.map (embedding.subtype _)) ⊆ t :=
begin
intros a ha,
rw mem_coe at ha,
convert property_of_mem_map_subtype s ha
end
/-! ### Fin -/
/--
Given a finset `s` of natural numbers and a bound `n`,
`s.fin n` is the finset of all elements of `s` less than `n`.
-/
protected def fin (n : ℕ) (s : finset ℕ) : finset (fin n) :=
(s.subtype _).map fin.equiv_subtype.symm.to_embedding
@[simp] lemma mem_fin {n} {s : finset ℕ} :
∀ a : fin n, a ∈ s.fin n ↔ (a : ℕ) ∈ s
| ⟨a, ha⟩ := by simp [finset.fin]
@[mono] lemma fin_mono {n} : monotone (finset.fin n) :=
λ s t h x, by simpa using @h x
@[simp] lemma fin_map {n} {s : finset ℕ} : (s.fin n).map fin.coe_embedding = s.filter (< n) :=
by simp [finset.fin, finset.map_map]
lemma subset_image_iff {s : set α} : ↑t ⊆ f '' s ↔ ∃ s' : finset α, ↑s' ⊆ s ∧ s'.image f = t :=
begin
split, swap,
{ rintro ⟨t, ht, rfl⟩, rw [coe_image], exact set.image_subset f ht },
intro h,
letI : can_lift β s := ⟨f ∘ coe, λ y, y ∈ f '' s, λ y ⟨x, hxt, hy⟩, ⟨⟨x, hxt⟩, hy⟩⟩,
lift t to finset s using h,
refine ⟨t.map (embedding.subtype _), map_subtype_subset _, _⟩,
ext y, simp
end
lemma range_sdiff_zero {n : ℕ} : range (n + 1) \ {0} = (range n).image nat.succ :=
begin
induction n with k hk,
{ simp },
nth_rewrite 1 range_succ,
rw [range_succ, image_insert, ←hk, insert_sdiff_of_not_mem],
simp
end
end image
lemma _root_.multiset.to_finset_map [decidable_eq α] [decidable_eq β] (f : α → β) (m : multiset α) :
(m.map f).to_finset = m.to_finset.image f :=
finset.val_inj.1 (multiset.dedup_map_dedup_eq _ _).symm
section to_list
/-- Produce a list of the elements in the finite set using choice. -/
noncomputable def to_list (s : finset α) : list α := s.1.to_list
lemma nodup_to_list (s : finset α) : s.to_list.nodup :=
by { rw [to_list, ←multiset.coe_nodup, multiset.coe_to_list], exact s.nodup }
@[simp] lemma mem_to_list {a : α} {s : finset α} : a ∈ s.to_list ↔ a ∈ s := mem_to_list
@[simp] lemma to_list_eq_nil {s : finset α} : s.to_list = [] ↔ s = ∅ :=
to_list_eq_nil.trans val_eq_zero
@[simp] lemma empty_to_list {s : finset α} : s.to_list.empty ↔ s = ∅ :=
list.empty_iff_eq_nil.trans to_list_eq_nil
@[simp] lemma to_list_empty : (∅ : finset α).to_list = [] := to_list_eq_nil.mpr rfl
lemma nonempty.to_list_ne_nil {s : finset α} (hs : s.nonempty) : s.to_list ≠ [] :=
mt to_list_eq_nil.mp hs.ne_empty
lemma nonempty.not_empty_to_list {s : finset α} (hs : s.nonempty) : ¬s.to_list.empty :=
mt empty_to_list.mp hs.ne_empty
@[simp, norm_cast]
lemma coe_to_list (s : finset α) : (s.to_list : multiset α) = s.val := s.val.coe_to_list
@[simp] lemma to_list_to_finset [decidable_eq α] (s : finset α) : s.to_list.to_finset = s :=
by { ext, simp }
lemma exists_list_nodup_eq [decidable_eq α] (s : finset α) :
∃ (l : list α), l.nodup ∧ l.to_finset = s :=
⟨s.to_list, s.nodup_to_list, s.to_list_to_finset⟩
lemma to_list_cons {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).to_list ~ a :: s.to_list :=
(list.perm_ext (nodup_to_list _) (by simp [h, nodup_to_list s])).2 $
λ x, by simp only [list.mem_cons_iff, finset.mem_to_list, finset.mem_cons]
lemma to_list_insert [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) :
(insert a s).to_list ~ a :: s.to_list :=
cons_eq_insert _ _ h ▸ to_list_cons _
end to_list
section bUnion
/-!
### bUnion
This section is about the bounded union of an indexed family `t : α → finset β` of finite sets
over a finite set `s : finset α`.
-/
variables [decidable_eq β] {s s₁ s₂ : finset α} {t t₁ t₂ : α → finset β}
/-- `bUnion s t` is the union of `t x` over `x ∈ s`.
(This was formerly `bind` due to the monad structure on types with `decidable_eq`.) -/
protected def bUnion (s : finset α) (t : α → finset β) : finset β :=
(s.1.bind (λ a, (t a).1)).to_finset
@[simp] theorem bUnion_val (s : finset α) (t : α → finset β) :
(s.bUnion t).1 = (s.1.bind (λ a, (t a).1)).dedup := rfl
@[simp] theorem bUnion_empty : finset.bUnion ∅ t = ∅ := rfl
@[simp] lemma mem_bUnion {b : β} : b ∈ s.bUnion t ↔ ∃ a ∈ s, b ∈ t a :=
by simp only [mem_def, bUnion_val, mem_dedup, mem_bind, exists_prop]
@[simp, norm_cast] lemma coe_bUnion : (s.bUnion t : set β) = ⋃ x ∈ (s : set α), t x :=
by simp only [set.ext_iff, mem_bUnion, set.mem_Union, iff_self, mem_coe, implies_true_iff]
@[simp] theorem bUnion_insert [decidable_eq α] {a : α} : (insert a s).bUnion t = t a ∪ s.bUnion t :=
ext $ λ x, by simp only [mem_bUnion, exists_prop, mem_union, mem_insert,
or_and_distrib_right, exists_or_distrib, exists_eq_left]
-- ext $ λ x, by simp [or_and_distrib_right, exists_or_distrib]
lemma bUnion_congr (hs : s₁ = s₂) (ht : ∀ a ∈ s₁, t₁ a = t₂ a) : s₁.bUnion t₁ = s₂.bUnion t₂ :=
ext $ λ x, by simp [hs, ht] { contextual := tt }
theorem bUnion_subset {s' : finset β} : s.bUnion t ⊆ s' ↔ ∀ x ∈ s, t x ⊆ s' :=
by simp only [subset_iff, mem_bUnion]; exact
⟨λ H a ha b hb, H ⟨a, ha, hb⟩, λ H b ⟨a, ha, hb⟩, H a ha hb⟩
@[simp] lemma singleton_bUnion {a : α} : finset.bUnion {a} t = t a :=
by { classical, rw [← insert_emptyc_eq, bUnion_insert, bUnion_empty, union_empty] }
theorem bUnion_inter (s : finset α) (f : α → finset β) (t : finset β) :
s.bUnion f ∩ t = s.bUnion (λ x, f x ∩ t) :=
begin
ext x,
simp only [mem_bUnion, mem_inter],
tauto
end
theorem inter_bUnion (t : finset β) (s : finset α) (f : α → finset β) :
t ∩ s.bUnion f = s.bUnion (λ x, t ∩ f x) :=
by rw [inter_comm, bUnion_inter]; simp [inter_comm]
theorem image_bUnion [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} :
(s.image f).bUnion t = s.bUnion (λa, t (f a)) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [image_insert, bUnion_insert, ih])
theorem bUnion_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} :
(s.bUnion t).image f = s.bUnion (λa, (t a).image f) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [bUnion_insert, image_union, ih])
lemma bUnion_bUnion [decidable_eq γ] (s : finset α) (f : α → finset β) (g : β → finset γ) :
(s.bUnion f).bUnion g = s.bUnion (λ a, (f a).bUnion g) :=
begin
ext,
simp only [finset.mem_bUnion, exists_prop],
simp_rw [←exists_and_distrib_right, ←exists_and_distrib_left, and_assoc],
rw exists_comm,
end
theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) :
(s.bind t).to_finset = s.to_finset.bUnion (λa, (t a).to_finset) :=
ext $ λ x, by simp only [multiset.mem_to_finset, mem_bUnion, multiset.mem_bind, exists_prop]
lemma bUnion_mono (h : ∀ a ∈ s, t₁ a ⊆ t₂ a) : s.bUnion t₁ ⊆ s.bUnion t₂ :=
have ∀ b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a),
from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩,
by simpa only [subset_iff, mem_bUnion, exists_imp_distrib, and_imp, exists_prop]
lemma bUnion_subset_bUnion_of_subset_left (t : α → finset β) (h : s₁ ⊆ s₂) :
s₁.bUnion t ⊆ s₂.bUnion t :=
begin
intro x,
simp only [and_imp, mem_bUnion, exists_prop],
exact Exists.imp (λ a ha, ⟨h ha.1, ha.2⟩)
end
lemma subset_bUnion_of_mem (u : α → finset β) {x : α} (xs : x ∈ s) : u x ⊆ s.bUnion u :=
singleton_bUnion.superset.trans $ bUnion_subset_bUnion_of_subset_left u $ singleton_subset_iff.2 xs
@[simp] lemma bUnion_subset_iff_forall_subset {α β : Type*} [decidable_eq β]
{s : finset α} {t : finset β} {f : α → finset β} : s.bUnion f ⊆ t ↔ ∀ x ∈ s, f x ⊆ t :=
⟨λ h x hx, (subset_bUnion_of_mem f hx).trans h,
λ h x hx, let ⟨a, ha₁, ha₂⟩ := mem_bUnion.mp hx in h _ ha₁ ha₂⟩
lemma bUnion_singleton {f : α → β} : s.bUnion (λa, {f a}) = s.image f :=
ext $ λ x, by simp only [mem_bUnion, mem_image, mem_singleton, eq_comm]
@[simp] lemma bUnion_singleton_eq_self [decidable_eq α] : s.bUnion (singleton : α → finset α) = s :=
by { rw bUnion_singleton, exact image_id }
lemma filter_bUnion (s : finset α) (f : α → finset β) (p : β → Prop) [decidable_pred p] :
(s.bUnion f).filter p = s.bUnion (λ a, (f a).filter p) :=
begin
ext b,
simp only [mem_bUnion, exists_prop, mem_filter],
split,
{ rintro ⟨⟨a, ha, hba⟩, hb⟩,
exact ⟨a, ha, hba, hb⟩ },
{ rintro ⟨a, ha, hba, hb⟩,
exact ⟨⟨a, ha, hba⟩, hb⟩ }
end
lemma bUnion_filter_eq_of_maps_to [decidable_eq α] {s : finset α} {t : finset β} {f : α → β}
(h : ∀ x ∈ s, f x ∈ t) :
t.bUnion (λa, s.filter $ (λc, f c = a)) = s :=
ext $ λ b, by simpa using h b
lemma image_bUnion_filter_eq [decidable_eq α] (s : finset β) (g : β → α) :
(s.image g).bUnion (λa, s.filter $ (λc, g c = a)) = s :=
bUnion_filter_eq_of_maps_to (λ x, mem_image_of_mem g)
lemma erase_bUnion (f : α → finset β) (s : finset α) (b : β) :
(s.bUnion f).erase b = s.bUnion (λ x, (f x).erase b) :=
by { ext, simp only [finset.mem_bUnion, iff_self, exists_and_distrib_left, finset.mem_erase] }
@[simp] lemma bUnion_nonempty : (s.bUnion t).nonempty ↔ ∃ x ∈ s, (t x).nonempty :=
by simp [finset.nonempty, ← exists_and_distrib_left, @exists_swap α]
lemma nonempty.bUnion (hs : s.nonempty) (ht : ∀ x ∈ s, (t x).nonempty) : (s.bUnion t).nonempty :=
bUnion_nonempty.2 $ hs.imp $ λ x hx, ⟨hx, ht x hx⟩
end bUnion
/-! ### disjoint -/
--TODO@Yaël: Kill lemmas duplicate with `boolean_algebra`
section disjoint
variables [decidable_eq α] [decidable_eq β] {f : α → β} {s t u : finset α} {a b : α}
lemma disjoint_left : disjoint s t ↔ ∀ ⦃a⦄, a ∈ s → a ∉ t :=
by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and,
and_imp]; refl
lemma disjoint_val : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left
lemma disjoint_iff_inter_eq_empty : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff
instance decidable_disjoint (U V : finset α) : decidable (disjoint U V) :=
decidable_of_decidable_of_iff (by apply_instance) eq_bot_iff
lemma disjoint_right : disjoint s t ↔ ∀ ⦃a⦄, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left]
lemma disjoint_iff_ne : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
lemma _root_.disjoint.forall_ne_finset (h : disjoint s t) (ha : a ∈ s) (hb : b ∈ t) : a ≠ b :=
disjoint_iff_ne.1 h _ ha _ hb
lemma not_disjoint_iff : ¬ disjoint s t ↔ ∃ a, a ∈ s ∧ a ∈ t :=
not_forall.trans $ exists_congr $ λ a, not_not.trans mem_inter
lemma disjoint_of_subset_left (h : s ⊆ u) (d : disjoint u t) : disjoint s t :=
disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁))
lemma disjoint_of_subset_right (h : t ⊆ u) (d : disjoint s u) : disjoint s t :=
disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁))
@[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left
@[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right
@[simp] lemma disjoint_singleton_left : disjoint (singleton a) s ↔ a ∉ s :=
by simp only [disjoint_left, mem_singleton, forall_eq]
@[simp] lemma disjoint_singleton_right : disjoint s (singleton a) ↔ a ∉ s :=
disjoint.comm.trans disjoint_singleton_left
@[simp] lemma disjoint_singleton : disjoint ({a} : finset α) {b} ↔ a ≠ b :=
by rw [disjoint_singleton_left, mem_singleton]
@[simp] lemma disjoint_insert_left : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t :=
by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
@[simp] lemma disjoint_insert_right : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t :=
disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm]
@[simp] lemma disjoint_union_left : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib]
@[simp] lemma disjoint_union_right : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib]
lemma sdiff_disjoint : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2
lemma disjoint_sdiff : disjoint s (t \ s) := sdiff_disjoint.symm
lemma disjoint_sdiff_inter (s t : finset α) : disjoint (s \ t) (s ∩ t) :=
disjoint_of_subset_right (inter_subset_right _ _) sdiff_disjoint
lemma sdiff_eq_self_iff_disjoint : s \ t = s ↔ disjoint s t := sdiff_eq_self_iff_disjoint'
lemma sdiff_eq_self_of_disjoint (h : disjoint s t) : s \ t = s := sdiff_eq_self_iff_disjoint.2 h
lemma disjoint_self_iff_empty (s : finset α) : disjoint s s ↔ s = ∅ := disjoint_self
lemma disjoint_bUnion_left {ι : Type*} (s : finset ι) (f : ι → finset α) (t : finset α) :
disjoint (s.bUnion f) t ↔ (∀ i ∈ s, disjoint (f i) t) :=
begin
classical,
refine s.induction _ _,
{ simp only [forall_mem_empty_iff, bUnion_empty, disjoint_empty_left] },
{ assume i s his ih,
simp only [disjoint_union_left, bUnion_insert, his, forall_mem_insert, ih] }
end
lemma disjoint_bUnion_right {ι : Type*} (s : finset α) (t : finset ι) (f : ι → finset α) :
disjoint s (t.bUnion f) ↔ ∀ i ∈ t, disjoint s (f i) :=
by simpa only [disjoint.comm] using disjoint_bUnion_left t f s
lemma disjoint_filter {p q : α → Prop} [decidable_pred p] [decidable_pred q] :
disjoint (s.filter p) (s.filter q) ↔ ∀ x ∈ s, p x → ¬ q x :=
by split; simp [disjoint_left] {contextual := tt}
lemma disjoint_filter_filter {p q : α → Prop} [decidable_pred p] [decidable_pred q] :
(disjoint s t) → disjoint (s.filter p) (t.filter q) :=
disjoint.mono (filter_subset _ _) (filter_subset _ _)
lemma disjoint_filter_filter_neg (s : finset α) (p : α → Prop) [decidable_pred p] :
disjoint (s.filter p) (s.filter $ λ a, ¬ p a) :=
(disjoint_filter.2 $ λ a _, id).symm
@[simp, norm_cast] lemma disjoint_coe : disjoint (s : set α) t ↔ disjoint s t :=
by { rw [finset.disjoint_left, set.disjoint_left], refl }
@[simp, norm_cast] lemma pairwise_disjoint_coe {ι : Type*} {s : set ι} {f : ι → finset α} :
s.pairwise_disjoint (λ i, f i : ι → set α) ↔ s.pairwise_disjoint f :=
forall₅_congr $ λ _ _ _ _ _, disjoint_coe
@[simp] lemma _root_.disjoint.of_image_finset (h : disjoint (s.image f) (t.image f)) :
disjoint s t :=
disjoint_iff_ne.2 $ λ a ha b hb, ne_of_apply_ne f $ h.forall_ne_finset
(mem_image_of_mem _ ha) (mem_image_of_mem _ hb)
@[simp] lemma disjoint_image {f : α → β} (hf : injective f) :
disjoint (s.image f) (t.image f) ↔ disjoint s t :=
begin
simp only [disjoint_iff_ne, mem_image, exists_prop, exists_imp_distrib, and_imp],
refine ⟨λ h a ha b hb hab, h _ _ ha rfl _ _ hb rfl $ congr_arg _ hab, _⟩,
rintro h _ a ha rfl _ b hb rfl,
exact hf.ne (h _ ha _ hb),
end
@[simp] lemma disjoint_map {f : α ↪ β} : disjoint (s.map f) (t.map f) ↔ disjoint s t :=
by { simp_rw map_eq_image, exact disjoint_image f.injective }
end disjoint
/-! ### choose -/
section choose
variables (p : α → Prop) [decidable_pred p] (l : finset α)
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the corresponding subtype. -/
def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } :=
multiset.choose_x p l.val hp
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the ambient type. -/
def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp
lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
section pairwise
variables {s : finset α}
lemma pairwise_subtype_iff_pairwise_finset' (r : β → β → Prop) (f : α → β) :
pairwise (r on λ x : s, f x) ↔ (s : set α).pairwise (r on f) :=
begin
refine ⟨λ h x hx y hy hxy, h ⟨x, hx⟩ ⟨y, hy⟩ (by simpa only [subtype.mk_eq_mk, ne.def]), _⟩,
rintros h ⟨x, hx⟩ ⟨y, hy⟩ hxy,
exact h hx hy (subtype.mk_eq_mk.not.mp hxy)
end
lemma pairwise_subtype_iff_pairwise_finset (r : α → α → Prop) :
pairwise (r on λ x : s, x) ↔ (s : set α).pairwise r :=
pairwise_subtype_iff_pairwise_finset' r id
lemma pairwise_cons' {a : α} (ha : a ∉ s) (r : β → β → Prop) (f : α → β) :
pairwise (r on λ a : s.cons a ha, f a) ↔
pairwise (r on λ a : s, f a) ∧ ∀ b ∈ s, r (f a) (f b) ∧ r (f b) (f a) :=
begin
simp only [pairwise_subtype_iff_pairwise_finset', finset.coe_cons, set.pairwise_insert,
finset.mem_coe, and.congr_right_iff],
exact λ hsr, ⟨λ h b hb, h b hb $ by { rintro rfl, contradiction }, λ h b hb _, h b hb⟩,
end
lemma pairwise_cons {a : α} (ha : a ∉ s) (r : α → α → Prop) :
pairwise (r on λ a : s.cons a ha, a) ↔ pairwise (r on λ a : s, a) ∧ ∀ b ∈ s, r a b ∧ r b a :=
pairwise_cons' ha r id
end pairwise
end finset
namespace equiv
/-- Given an equivalence `α` to `β`, produce an equivalence between `finset α` and `finset β`. -/
protected def finset_congr (e : α ≃ β) : finset α ≃ finset β :=
{ to_fun := λ s, s.map e.to_embedding,
inv_fun := λ s, s.map e.symm.to_embedding,
left_inv := λ s, by simp [finset.map_map],
right_inv := λ s, by simp [finset.map_map] }
@[simp] lemma finset_congr_apply (e : α ≃ β) (s : finset α) :
e.finset_congr s = s.map e.to_embedding :=
rfl
@[simp] lemma finset_congr_refl : (equiv.refl α).finset_congr = equiv.refl _ := by { ext, simp }
@[simp] lemma finset_congr_symm (e : α ≃ β) : e.finset_congr.symm = e.symm.finset_congr := rfl
@[simp] lemma finset_congr_trans (e : α ≃ β) (e' : β ≃ γ) :
e.finset_congr.trans (e'.finset_congr) = (e.trans e').finset_congr :=
by { ext, simp [-finset.mem_map, -equiv.trans_to_embedding] }
lemma finset_congr_to_embedding (e : α ≃ β) :
e.finset_congr.to_embedding = (finset.map_embedding e.to_embedding).to_embedding := rfl
/--
Inhabited types are equivalent to `option β` for some `β` by identifying `default α` with `none`.
-/
def sigma_equiv_option_of_inhabited (α : Type u) [inhabited α] [decidable_eq α] :
Σ (β : Type u), α ≃ option β :=
⟨{x : α // x ≠ default},
{ to_fun := λ (x : α), if h : x = default then none else some ⟨x, h⟩,
inv_fun := option.elim default coe,
left_inv := λ x, by { dsimp only, split_ifs; simp [*] },
right_inv := begin
rintro (_|⟨x,h⟩),
{ simp },
{ dsimp only,
split_ifs with hi,
{ simpa [h] using hi },
{ simp } }
end }⟩
end equiv
namespace multiset
variable [decidable_eq α]
lemma disjoint_to_finset {m1 m2 : multiset α} :
_root_.disjoint m1.to_finset m2.to_finset ↔ m1.disjoint m2 :=
begin
rw finset.disjoint_iff_ne,
refine ⟨λ h a ha1 ha2, _, _⟩,
{ rw ← multiset.mem_to_finset at ha1 ha2,
exact h _ ha1 _ ha2 rfl },
{ rintros h a ha b hb rfl,
rw multiset.mem_to_finset at ha hb,
exact h ha hb }
end
end multiset
namespace list
variables [decidable_eq α] {l l' : list α}
lemma disjoint_to_finset_iff_disjoint : _root_.disjoint l.to_finset l'.to_finset ↔ l.disjoint l' :=
multiset.disjoint_to_finset
end list
|
f396d26be64216067062b6c55dc03ad8ec2c56dc | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/number_theory/sum_two_squares.lean | 9c066fcc1793dc3776e918034568161901bb796b | [
"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 | 776 | 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 data.zsqrtd.gaussian_int
/-!
# Sums of two squares
Proof of Fermat's theorem on the sum of two squares. Every prime congruent to 1 mod 4 is the sum
of two squares
-/
open gaussian_int principal_ideal_domain
namespace nat
namespace prime
/-- Fermat's theorem on the sum of two squares. Every prime congruent to 1 mod 4 is the sum
of two squares -/
lemma sum_two_squares {p : ℕ} (hp : p.prime) (hp1 : p % 4 = 1) :
∃ a b : ℕ, a ^ 2 + b ^ 2 = p :=
sum_two_squares_of_nat_prime_of_not_irreducible hp
(by rw [irreducible_iff_prime, prime_iff_mod_four_eq_three_of_nat_prime hp, hp1]; norm_num)
end prime
end nat
|
c4f16c5efc533213a10954472db07452d8b26d1b | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/topology/uniform_space/basic.lean | 5aad3035aa56cd20ed5c26698703f047de3c3a1b | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 80,776 | 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, Patrick Massot
-/
import order.filter.small_sets
import topology.subset_properties
/-!
# Uniform spaces
Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly
generalize to uniform spaces, e.g.
* uniform continuity (in this file)
* completeness (in `cauchy.lean`)
* extension of uniform continuous functions to complete spaces (in `uniform_embedding.lean`)
* totally bounded sets (in `cauchy.lean`)
* totally bounded complete sets are compact (in `cauchy.lean`)
A uniform structure on a type `X` is a filter `𝓤 X` on `X × X` satisfying some conditions
which makes it reasonable to say that `∀ᶠ (p : X × X) in 𝓤 X, ...` means
"for all p.1 and p.2 in X close enough, ...". Elements of this filter are called entourages
of `X`. The two main examples are:
* If `X` is a metric space, `V ∈ 𝓤 X ↔ ∃ ε > 0, { p | dist p.1 p.2 < ε } ⊆ V`
* If `G` is an additive topological group, `V ∈ 𝓤 G ↔ ∃ U ∈ 𝓝 (0 : G), {p | p.2 - p.1 ∈ U} ⊆ V`
Those examples are generalizations in two different directions of the elementary example where
`X = ℝ` and `V ∈ 𝓤 ℝ ↔ ∃ ε > 0, { p | |p.2 - p.1| < ε } ⊆ V` which features both the topological
group structure on `ℝ` and its metric space structure.
Each uniform structure on `X` induces a topology on `X` characterized by
> `nhds_eq_comap_uniformity : ∀ {x : X}, 𝓝 x = comap (prod.mk x) (𝓤 X)`
where `prod.mk x : X → X × X := (λ y, (x, y))` is the partial evaluation of the product
constructor.
The dictionary with metric spaces includes:
* an upper bound for `dist x y` translates into `(x, y) ∈ V` for some `V ∈ 𝓤 X`
* a ball `ball x r` roughly corresponds to `uniform_space.ball x V := {y | (x, y) ∈ V}`
for some `V ∈ 𝓤 X`, but the later is more general (it includes in
particular both open and closed balls for suitable `V`).
In particular we have:
`is_open_iff_ball_subset {s : set X} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 X, ball x V ⊆ s`
The triangle inequality is abstracted to a statement involving the composition of relations in `X`.
First note that the triangle inequality in a metric space is equivalent to
`∀ (x y z : X) (r r' : ℝ), dist x y ≤ r → dist y z ≤ r' → dist x z ≤ r + r'`.
Then, for any `V` and `W` with type `set (X × X)`, the composition `V ○ W : set (X × X)` is
defined as `{ p : X × X | ∃ z, (p.1, z) ∈ V ∧ (z, p.2) ∈ W }`.
In the metric space case, if `V = { p | dist p.1 p.2 ≤ r }` and `W = { p | dist p.1 p.2 ≤ r' }`
then the triangle inequality, as reformulated above, says `V ○ W` is contained in
`{p | dist p.1 p.2 ≤ r + r'}` which is the entourage associated to the radius `r + r'`.
In general we have `mem_ball_comp (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W)`.
Note that this discussion does not depend on any axiom imposed on the uniformity filter,
it is simply captured by the definition of composition.
The uniform space axioms ask the filter `𝓤 X` to satisfy the following:
* every `V ∈ 𝓤 X` contains the diagonal `id_rel = { p | p.1 = p.2 }`. This abstracts the fact
that `dist x x ≤ r` for every non-negative radius `r` in the metric space case and also that
`x - x` belongs to every neighborhood of zero in the topological group case.
* `V ∈ 𝓤 X → prod.swap '' V ∈ 𝓤 X`. This is tightly related the fact that `dist x y = dist y x`
in a metric space, and to continuity of negation in the topological group case.
* `∀ V ∈ 𝓤 X, ∃ W ∈ 𝓤 X, W ○ W ⊆ V`. In the metric space case, it corresponds
to cutting the radius of a ball in half and applying the triangle inequality.
In the topological group case, it comes from continuity of addition at `(0, 0)`.
These three axioms are stated more abstractly in the definition below, in terms of
operations on filters, without directly manipulating entourages.
## Main definitions
* `uniform_space X` is a uniform space structure on a type `X`
* `uniform_continuous f` is a predicate saying a function `f : α → β` between uniform spaces
is uniformly continuous : `∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r`
In this file we also define a complete lattice structure on the type `uniform_space X`
of uniform structures on `X`, as well as the pullback (`uniform_space.comap`) of uniform structures
coming from the pullback of filters.
Like distance functions, uniform structures cannot be pushed forward in general.
## Notations
Localized in `uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`,
and `○` for composition of relations, seen as terms with type `set (X × X)`.
## Implementation notes
There is already a theory of relations in `data/rel.lean` where the main definition is
`def rel (α β : Type*) := α → β → Prop`.
The relations used in the current file involve only one type, but this is not the reason why
we don't reuse `data/rel.lean`. We use `set (α × α)`
instead of `rel α α` because we really need sets to use the filter library, and elements
of filters on `α × α` have type `set (α × α)`.
The structure `uniform_space X` bundles a uniform structure on `X`, a topology on `X` and
an assumption saying those are compatible. This may not seem mathematically reasonable at first,
but is in fact an instance of the forgetful inheritance pattern. See Note [forgetful inheritance]
below.
## References
The formalization uses the books:
* [N. Bourbaki, *General Topology*][bourbaki1966]
* [I. M. James, *Topologies and Uniformities*][james1999]
But it makes a more systematic use of the filter library.
-/
open set filter classical
open_locale classical topological_space filter
set_option eqn_compiler.zeta true
universes u
/-!
### Relations, seen as `set (α × α)`
-/
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*}
/-- The identity relation, or the graph of the identity function -/
def id_rel {α : Type*} := {p : α × α | p.1 = p.2}
@[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl
@[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s :=
by simp [subset_def]; exact forall_congr (λ a, by simp)
/-- The composition of relations -/
def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂}
localized "infix ` ○ `:55 := comp_rel" in uniformity
@[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)}
{x y : α} : (x, y) ∈ r₁ ○ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl
@[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α :=
set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm
theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)}
(hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ○ (g x)) :=
assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩
@[mono]
lemma comp_rel_mono {f g h k: set (α×α)} (h₁ : f ⊆ h) (h₂ : g ⊆ k) : f ○ g ⊆ h ○ k :=
λ ⟨x, y⟩ ⟨z, h, h'⟩, ⟨z, h₁ h, h₂ h'⟩
lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) :
(a, b) ∈ s ○ t :=
⟨c, h₁, h₂⟩
@[simp] lemma id_comp_rel {r : set (α×α)} : id_rel ○ r = r :=
set.ext $ assume ⟨a, b⟩, by simp
lemma comp_rel_assoc {r s t : set (α×α)} :
(r ○ s) ○ t = r ○ (s ○ t) :=
by ext p; cases p; simp only [mem_comp_rel]; tauto
lemma left_subset_comp_rel {s t : set (α × α)} (h : id_rel ⊆ t) : s ⊆ s ○ t :=
λ ⟨x, y⟩ xy_in, ⟨y, xy_in, h $ by exact rfl⟩
lemma right_subset_comp_rel {s t : set (α × α)} (h : id_rel ⊆ s) : t ⊆ s ○ t :=
λ ⟨x, y⟩ xy_in, ⟨x, h $ by exact rfl, xy_in⟩
lemma subset_comp_self {s : set (α × α)} (h : id_rel ⊆ s) : s ⊆ s ○ s :=
left_subset_comp_rel h
lemma subset_iterate_comp_rel {s t : set (α × α)} (h : id_rel ⊆ s) (n : ℕ) :
t ⊆ (((○) s) ^[n] t) :=
begin
induction n with n ihn generalizing t,
exacts [subset.rfl, (right_subset_comp_rel h).trans ihn]
end
/-- The relation is invariant under swapping factors. -/
def symmetric_rel (V : set (α × α)) : Prop := prod.swap ⁻¹' V = V
/-- The maximal symmetric relation contained in a given relation. -/
def symmetrize_rel (V : set (α × α)) : set (α × α) := V ∩ prod.swap ⁻¹' V
lemma symmetric_symmetrize_rel (V : set (α × α)) : symmetric_rel (symmetrize_rel V) :=
by simp [symmetric_rel, symmetrize_rel, preimage_inter, inter_comm, ← preimage_comp]
lemma symmetrize_rel_subset_self (V : set (α × α)) : symmetrize_rel V ⊆ V :=
sep_subset _ _
@[mono]
lemma symmetrize_mono {V W: set (α × α)} (h : V ⊆ W) : symmetrize_rel V ⊆ symmetrize_rel W :=
inter_subset_inter h $ preimage_mono h
lemma symmetric_rel.mk_mem_comm {V : set (α × α)} (hV : symmetric_rel V) {x y : α} :
(x, y) ∈ V ↔ (y, x) ∈ V :=
set.ext_iff.1 hV (y, x)
lemma symmetric_rel.eq {U : set (α × α)} (hU : symmetric_rel U) : prod.swap ⁻¹' U = U := hU
lemma symmetric_rel.inter {U V : set (α × α)} (hU : symmetric_rel U) (hV : symmetric_rel V) :
symmetric_rel (U ∩ V) :=
by rw [symmetric_rel, preimage_inter, hU.eq, hV.eq]
/-- This core description of a uniform space is outside of the type class hierarchy. It is useful
for constructions of uniform spaces, when the topology is derived from the uniform space. -/
structure uniform_space.core (α : Type u) :=
(uniformity : filter (α × α))
(refl : 𝓟 id_rel ≤ uniformity)
(symm : tendsto prod.swap uniformity uniformity)
(comp : uniformity.lift' (λs, s ○ s) ≤ uniformity)
/-- An alternative constructor for `uniform_space.core`. This version unfolds various
`filter`-related definitions. -/
def uniform_space.core.mk' {α : Type u} (U : filter (α × α))
(refl : ∀ (r ∈ U) x, (x, x) ∈ r)
(symm : ∀ r ∈ U, prod.swap ⁻¹' r ∈ U)
(comp : ∀ r ∈ U, ∃ t ∈ U, t ○ t ⊆ r) : uniform_space.core α :=
⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm,
begin
intros r ru,
rw [mem_lift'_sets],
exact comp _ ru,
apply monotone_comp_rel; exact monotone_id,
end⟩
/-- Defining an `uniform_space.core` from a filter basis satisfying some uniformity-like axioms. -/
def uniform_space.core.mk_of_basis {α : Type u} (B : filter_basis (α × α))
(refl : ∀ (r ∈ B) x, (x, x) ∈ r)
(symm : ∀ r ∈ B, ∃ t ∈ B, t ⊆ prod.swap ⁻¹' r)
(comp : ∀ r ∈ B, ∃ t ∈ B, t ○ t ⊆ r) : uniform_space.core α :=
{ uniformity := B.filter,
refl := B.has_basis.ge_iff.mpr (λ r ru, id_rel_subset.2 $ refl _ ru),
symm := (B.has_basis.tendsto_iff B.has_basis).mpr symm,
comp := (has_basis.le_basis_iff (B.has_basis.lift' (monotone_comp_rel monotone_id monotone_id))
B.has_basis).mpr comp }
/-- A uniform space generates a topological space -/
def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) :
topological_space α :=
{ is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity,
is_open_univ := by simp; intro; exact univ_mem,
is_open_inter :=
assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt},
is_open_sUnion :=
assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] with p ph h using ⟨t, ts, ph h⟩ }
lemma uniform_space.core_eq :
∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂
| ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := by { congr, exact h }
-- the topological structure is embedded in the uniform structure
-- to avoid instance diamond issues. See Note [forgetful inheritance].
/-- A uniform space is a generalization of the "uniform" topological aspects of a
metric space. It consists of a filter on `α × α` called the "uniformity", which
satisfies properties analogous to the reflexivity, symmetry, and triangle properties
of a metric.
A metric space has a natural uniformity, and a uniform space has a natural topology.
A topological group also has a natural uniformity, even when it is not metrizable. -/
class uniform_space (α : Type u) extends topological_space α, uniform_space.core α :=
(is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity))
/-- Alternative constructor for `uniform_space α` when a topology is already given. -/
@[pattern] def uniform_space.mk' {α} (t : topological_space α)
(c : uniform_space.core α)
(is_open_uniformity : ∀s:set α, t.is_open s ↔
(∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) :
uniform_space α := ⟨c, is_open_uniformity⟩
/-- Construct a `uniform_space` from a `uniform_space.core`. -/
def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α :=
{ to_core := u,
to_topological_space := u.to_topological_space,
is_open_uniformity := assume a, iff.rfl }
/-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure
that is equal to `u.to_topological_space`. -/
def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α)
(h : t = u.to_topological_space) : uniform_space α :=
{ to_core := u,
to_topological_space := t,
is_open_uniformity := assume a, h.symm ▸ iff.rfl }
lemma uniform_space.to_core_to_topological_space (u : uniform_space α) :
u.to_core.to_topological_space = u.to_topological_space :=
topological_space_eq $ funext $ assume s,
by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity]
@[ext]
lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂
| (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h :=
have u₁ = u₂, from uniform_space.core_eq h,
have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this],
by simp [*]
lemma uniform_space.of_core_eq_to_core
(u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) :
uniform_space.of_core_eq u.to_core t h = u :=
uniform_space_eq rfl
/-- Replace topology in a `uniform_space` instance with a propositionally (but possibly not
definitionally) equal one. -/
@[reducible] def uniform_space.replace_topology {α : Type*} [i : topological_space α]
(u : uniform_space α) (h : i = u.to_topological_space) : uniform_space α :=
uniform_space.of_core_eq u.to_core i $ h.trans u.to_core_to_topological_space.symm
lemma uniform_space.replace_topology_eq {α : Type*} [i : topological_space α] (u : uniform_space α)
(h : i = u.to_topological_space) : u.replace_topology h = u :=
u.of_core_eq_to_core _ _
section uniform_space
variables [uniform_space α]
/-- The uniformity is a filter on α × α (inferred from an ambient uniform space
structure on α). -/
def uniformity (α : Type u) [uniform_space α] : filter (α × α) :=
(@uniform_space.to_core α _).uniformity
localized "notation `𝓤` := uniformity" in uniformity
lemma is_open_uniformity {s : set α} :
is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) :=
uniform_space.is_open_uniformity s
lemma refl_le_uniformity : 𝓟 id_rel ≤ 𝓤 α :=
(@uniform_space.to_core α _).refl
instance uniformity.ne_bot [nonempty α] : ne_bot (𝓤 α) :=
begin
inhabit α,
refine (principal_ne_bot_iff.2 _).mono refl_le_uniformity,
exact ⟨(default, default), rfl⟩
end
lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) :
(x, x) ∈ s :=
refl_le_uniformity h rfl
lemma mem_uniformity_of_eq {x y : α} {s : set (α × α)} (h : s ∈ 𝓤 α) (hx : x = y) :
(x, y) ∈ s :=
hx ▸ refl_mem_uniformity h
lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) :=
(@uniform_space.to_core α _).symm
lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), s ○ s) ≤ 𝓤 α :=
(@uniform_space.to_core α _).comp
lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) :=
symm_le_uniformity
lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, t ○ t ⊆ s :=
have s ∈ (𝓤 α).lift' (λt:set (α×α), t ○ t),
from comp_le_uniformity hs,
(mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this
/-- If `s ∈ 𝓤 α`, then for any natural `n`, for a subset `t` of a sufficiently small set in `𝓤 α`,
we have `t ○ t ○ ... ○ t ⊆ s` (`n` compositions). -/
lemma eventually_uniformity_iterate_comp_subset {s : set (α × α)} (hs : s ∈ 𝓤 α) (n : ℕ) :
∀ᶠ t in (𝓤 α).small_sets, ((○) t) ^[n] t ⊆ s :=
begin
suffices : ∀ᶠ t in (𝓤 α).small_sets, t ⊆ s ∧ (((○) t) ^[n] t ⊆ s),
from (eventually_and.1 this).2,
induction n with n ihn generalizing s, { simpa },
rcases comp_mem_uniformity_sets hs with ⟨t, htU, hts⟩,
refine (ihn htU).mono (λ U hU, _),
rw [function.iterate_succ_apply'],
exact ⟨hU.1.trans $ (subset_comp_self $ refl_le_uniformity htU).trans hts,
(comp_rel_mono hU.1 hU.2).trans hts⟩
end
/-- If `s ∈ 𝓤 α`, then for any natural `n`, for a subset `t` of a sufficiently small set in `𝓤 α`,
we have `t ○ t ⊆ s`. -/
lemma eventually_uniformity_comp_subset {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∀ᶠ t in (𝓤 α).small_sets, t ○ t ⊆ s :=
eventually_uniformity_iterate_comp_subset hs 1
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/
lemma filter.tendsto.uniformity_trans {l : filter β} {f₁ f₂ f₃ : β → α}
(h₁₂ : tendsto (λ x, (f₁ x, f₂ x)) l (𝓤 α)) (h₂₃ : tendsto (λ x, (f₂ x, f₃ x)) l (𝓤 α)) :
tendsto (λ x, (f₁ x, f₃ x)) l (𝓤 α) :=
begin
refine le_trans (le_lift' $ λ s hs, mem_map.2 _) comp_le_uniformity,
filter_upwards [h₁₂ hs, h₂₃ hs] with x hx₁₂ hx₂₃ using ⟨_, hx₁₂, hx₂₃⟩,
end
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/
lemma filter.tendsto.uniformity_symm {l : filter β} {f : β → α × α}
(h : tendsto f l (𝓤 α)) :
tendsto (λ x, ((f x).2, (f x).1)) l (𝓤 α) :=
tendsto_swap_uniformity.comp h
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/
lemma tendsto_diag_uniformity (f : β → α) (l : filter β) :
tendsto (λ x, (f x, f x)) l (𝓤 α) :=
assume s hs, mem_map.2 $ univ_mem' $ λ x, refl_mem_uniformity hs
lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) :=
tendsto_diag_uniformity (λ _, a) f
lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s :=
have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs,
⟨s ∩ preimage prod.swap s, inter_mem hs this, λ a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩
lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ t ○ t ⊆ s :=
let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in
let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in
⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩
lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α :=
by rw [map_swap_eq_comap_swap];
from map_le_iff_le_comap.1 tendsto_swap_uniformity
lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α :=
le_antisymm uniformity_le_symm symm_le_uniformity
@[simp] lemma comap_swap_uniformity : comap (@prod.swap α α) (𝓤 α) = 𝓤 α :=
(congr_arg _ uniformity_eq_symm).trans $ comap_map prod.swap_injective
lemma symmetrize_mem_uniformity {V : set (α × α)} (h : V ∈ 𝓤 α) : symmetrize_rel V ∈ 𝓤 α :=
begin
apply (𝓤 α).inter_sets h,
rw [← image_swap_eq_preimage_swap, uniformity_eq_symm],
exact image_mem_map h,
end
/-- Symmetric entourages form a basis of `𝓤 α` -/
lemma uniform_space.has_basis_symmetric :
(𝓤 α).has_basis (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) id :=
has_basis_self.2 $ λ t t_in, ⟨symmetrize_rel t, symmetrize_mem_uniformity t_in,
symmetric_symmetrize_rel t, symmetrize_rel_subset_self t⟩
theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g)
(h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f :=
calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g :
lift_mono uniformity_le_symm le_rfl
... ≤ _ :
by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h
lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) :
(𝓤 α).lift (λs, f (s ○ s)) ≤ (𝓤 α).lift f :=
calc (𝓤 α).lift (λs, f (s ○ s)) =
((𝓤 α).lift' (λs:set (α×α), s ○ s)).lift f :
begin
rw [lift_lift'_assoc],
exact monotone_comp_rel monotone_id monotone_id,
exact h
end
... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity le_rfl
lemma comp_le_uniformity3 :
(𝓤 α).lift' (λs:set (α×α), s ○ (s ○ s)) ≤ (𝓤 α) :=
calc (𝓤 α).lift' (λd, d ○ (d ○ d)) =
(𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ (t ○ t))) :
begin
rw [lift_lift'_same_eq_lift'],
exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id),
exact (assume x, monotone_comp_rel monotone_id monotone_const),
end
... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ t)) :
lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (𝓟 ∘ (○) s) $
monotone_principal.comp (monotone_comp_rel monotone_const monotone_id)
... = (𝓤 α).lift' (λs:set(α×α), s ○ s) :
lift_lift'_same_eq_lift'
(assume s, monotone_comp_rel monotone_const monotone_id)
(assume s, monotone_comp_rel monotone_id monotone_const)
... ≤ (𝓤 α) : comp_le_uniformity
/-- See also `comp_open_symm_mem_uniformity_sets`. -/
lemma comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ⊆ s :=
begin
obtain ⟨w, w_in, w_sub⟩ : ∃ w ∈ 𝓤 α, w ○ w ⊆ s := comp_mem_uniformity_sets hs,
use [symmetrize_rel w, symmetrize_mem_uniformity w_in, symmetric_symmetrize_rel w],
have : symmetrize_rel w ⊆ w := symmetrize_rel_subset_self w,
calc symmetrize_rel w ○ symmetrize_rel w ⊆ w ○ w : by mono
... ⊆ s : w_sub,
end
lemma subset_comp_self_of_mem_uniformity {s : set (α × α)} (h : s ∈ 𝓤 α) : s ⊆ s ○ s :=
subset_comp_self (refl_le_uniformity h)
lemma comp_comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ○ t ⊆ s :=
begin
rcases comp_symm_mem_uniformity_sets hs with ⟨w, w_in, w_symm, w_sub⟩,
rcases comp_symm_mem_uniformity_sets w_in with ⟨t, t_in, t_symm, t_sub⟩,
use [t, t_in, t_symm],
have : t ⊆ t ○ t := subset_comp_self_of_mem_uniformity t_in,
calc
t ○ t ○ t ⊆ w ○ t : by mono
... ⊆ w ○ (t ○ t) : by mono
... ⊆ w ○ w : by mono
... ⊆ s : w_sub,
end
/-!
### Balls in uniform spaces
-/
/-- The ball around `(x : β)` with respect to `(V : set (β × β))`. Intended to be
used for `V ∈ 𝓤 β`, but this is not needed for the definition. Recovers the
notions of metric space ball when `V = {p | dist p.1 p.2 < r }`. -/
def uniform_space.ball (x : β) (V : set (β × β)) : set β := (prod.mk x) ⁻¹' V
open uniform_space (ball)
lemma uniform_space.mem_ball_self (x : α) {V : set (α × α)} (hV : V ∈ 𝓤 α) :
x ∈ ball x V :=
refl_mem_uniformity hV
/-- The triangle inequality for `uniform_space.ball` -/
lemma mem_ball_comp {V W : set (β × β)} {x y z} (h : y ∈ ball x V) (h' : z ∈ ball y W) :
z ∈ ball x (V ○ W) :=
prod_mk_mem_comp_rel h h'
lemma ball_subset_of_comp_subset {V W : set (β × β)} {x y} (h : x ∈ ball y W) (h' : W ○ W ⊆ V) :
ball x W ⊆ ball y V :=
λ z z_in, h' (mem_ball_comp h z_in)
lemma ball_mono {V W : set (β × β)} (h : V ⊆ W) (x : β) : ball x V ⊆ ball x W :=
preimage_mono h
lemma ball_inter (x : β) (V W : set (β × β)) : ball x (V ∩ W) = ball x V ∩ ball x W :=
preimage_inter
lemma ball_inter_left (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x V :=
ball_mono (inter_subset_left V W) x
lemma ball_inter_right (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x W :=
ball_mono (inter_subset_right V W) x
lemma mem_ball_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x y} :
x ∈ ball y V ↔ y ∈ ball x V :=
show (x, y) ∈ prod.swap ⁻¹' V ↔ (x, y) ∈ V, by { unfold symmetric_rel at hV, rw hV }
lemma ball_eq_of_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x} :
ball x V = {y | (y, x) ∈ V} :=
by { ext y, rw mem_ball_symmetry hV, exact iff.rfl }
lemma mem_comp_of_mem_ball {V W : set (β × β)} {x y z : β} (hV : symmetric_rel V)
(hx : x ∈ ball z V) (hy : y ∈ ball z W) : (x, y) ∈ V ○ W :=
begin
rw mem_ball_symmetry hV at hx,
exact ⟨z, hx, hy⟩
end
lemma uniform_space.is_open_ball (x : α) {V : set (α × α)} (hV : is_open V) :
is_open (ball x V) :=
hV.preimage $ continuous_const.prod_mk continuous_id
lemma mem_comp_comp {V W M : set (β × β)} (hW' : symmetric_rel W) {p : β × β} :
p ∈ V ○ M ○ W ↔ ((ball p.1 V ×ˢ ball p.2 W) ∩ M).nonempty :=
begin
cases p with x y,
split,
{ rintros ⟨z, ⟨w, hpw, hwz⟩, hzy⟩,
exact ⟨(w, z), ⟨hpw, by rwa mem_ball_symmetry hW'⟩, hwz⟩, },
{ rintro ⟨⟨w, z⟩, ⟨w_in, z_in⟩, hwz⟩,
rwa mem_ball_symmetry hW' at z_in,
use [z, w] ; tauto },
end
/-!
### Neighborhoods in uniform spaces
-/
lemma mem_nhds_uniformity_iff_right {x : α} {s : set α} :
s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α :=
begin
refine ⟨_, λ hs, _⟩,
{ simp only [mem_nhds_iff, is_open_uniformity, and_imp, exists_imp_distrib],
intros t ts ht xt,
filter_upwards [ht x xt] using λ y h eq, ts (h eq) },
{ refine mem_nhds_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, _, _, hs⟩,
{ exact λ y hy, refl_mem_uniformity hy rfl },
{ refine is_open_uniformity.mpr (λ y hy, _),
rcases comp_mem_uniformity_sets hy with ⟨t, ht, tr⟩,
filter_upwards [ht], rintro ⟨a, b⟩ hp' rfl,
filter_upwards [ht], rintro ⟨a', b'⟩ hp'' rfl,
exact @tr (a, b') ⟨a', hp', hp''⟩ rfl } }
end
lemma mem_nhds_uniformity_iff_left {x : α} {s : set α} :
s ∈ 𝓝 x ↔ {p : α × α | p.2 = x → p.1 ∈ s} ∈ 𝓤 α :=
by { rw [uniformity_eq_symm, mem_nhds_uniformity_iff_right], refl }
lemma nhds_eq_comap_uniformity_aux {α : Type u} {x : α} {s : set α} {F : filter (α × α)} :
{p : α × α | p.fst = x → p.snd ∈ s} ∈ F ↔ s ∈ comap (prod.mk x) F :=
by rw mem_comap ; from iff.intro
(assume hs, ⟨_, hs, assume x hx, hx rfl⟩)
(assume ⟨t, h, ht⟩, F.sets_of_superset h $
assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp])
lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) :=
by { ext s, rw [mem_nhds_uniformity_iff_right], exact nhds_eq_comap_uniformity_aux }
/-- See also `is_open_iff_open_ball_subset`. -/
lemma is_open_iff_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, ball x V ⊆ s :=
begin
simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity],
exact iff.rfl,
end
lemma nhds_basis_uniformity' {p : ι → Prop} {s : ι → set (α × α)} (h : (𝓤 α).has_basis p s)
{x : α} :
(𝓝 x).has_basis p (λ i, ball x (s i)) :=
by { rw [nhds_eq_comap_uniformity], exact h.comap (prod.mk x) }
lemma nhds_basis_uniformity {p : ι → Prop} {s : ι → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} :
(𝓝 x).has_basis p (λ i, {y | (y, x) ∈ s i}) :=
begin
replace h := h.comap prod.swap,
rw [← map_swap_eq_comap_swap, ← uniformity_eq_symm] at h,
exact nhds_basis_uniformity' h
end
lemma uniform_space.mem_nhds_iff {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, ball x V ⊆ s :=
begin
rw [nhds_eq_comap_uniformity, mem_comap],
exact iff.rfl,
end
lemma uniform_space.ball_mem_nhds (x : α) ⦃V : set (α × α)⦄ (V_in : V ∈ 𝓤 α) : ball x V ∈ 𝓝 x :=
begin
rw uniform_space.mem_nhds_iff,
exact ⟨V, V_in, subset.refl _⟩
end
lemma uniform_space.mem_nhds_iff_symm {x : α} {s : set α} :
s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, symmetric_rel V ∧ ball x V ⊆ s :=
begin
rw uniform_space.mem_nhds_iff,
split,
{ rintros ⟨V, V_in, V_sub⟩,
use [symmetrize_rel V, symmetrize_mem_uniformity V_in, symmetric_symmetrize_rel V],
exact subset.trans (ball_mono (symmetrize_rel_subset_self V) x) V_sub },
{ rintros ⟨V, V_in, V_symm, V_sub⟩,
exact ⟨V, V_in, V_sub⟩ }
end
lemma uniform_space.has_basis_nhds (x : α) :
has_basis (𝓝 x) (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) (λ s, ball x s) :=
⟨λ t, by simp [uniform_space.mem_nhds_iff_symm, and_assoc]⟩
open uniform_space
lemma uniform_space.mem_closure_iff_symm_ball {s : set α} {x} :
x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → symmetric_rel V → (s ∩ ball x V).nonempty :=
by simp [mem_closure_iff_nhds_basis (has_basis_nhds x), set.nonempty]
lemma uniform_space.mem_closure_iff_ball {s : set α} {x} :
x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → (ball x V ∩ s).nonempty :=
by simp [mem_closure_iff_nhds_basis' (nhds_basis_uniformity' (𝓤 α).basis_sets)]
lemma uniform_space.has_basis_nhds_prod (x y : α) :
has_basis (𝓝 (x, y)) (λ s, s ∈ 𝓤 α ∧ symmetric_rel s) $ λ s, ball x s ×ˢ ball y s :=
begin
rw nhds_prod_eq,
apply (has_basis_nhds x).prod_same_index (has_basis_nhds y),
rintro U V ⟨U_in, U_symm⟩ ⟨V_in, V_symm⟩,
exact ⟨U ∩ V, ⟨(𝓤 α).inter_sets U_in V_in, U_symm.inter V_symm⟩,
ball_inter_left x U V, ball_inter_right y U V⟩,
end
lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (ball x) :=
(nhds_basis_uniformity' (𝓤 α).basis_sets).eq_binfi
lemma nhds_eq_uniformity' {x : α} : 𝓝 x = (𝓤 α).lift' (λ s, {y | (y, x) ∈ s}) :=
(nhds_basis_uniformity (𝓤 α).basis_sets).eq_binfi
lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) :
{y : α | (x, y) ∈ s} ∈ 𝓝 x :=
ball_mem_nhds x h
lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) :
{x : α | (x, y) ∈ s} ∈ 𝓝 y :=
mem_nhds_left _ (symm_le_uniformity h)
lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) :=
assume s, mem_nhds_right a
lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) :=
assume s, mem_nhds_left a
lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) :
(𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) :=
eq.trans
begin
rw [nhds_eq_uniformity],
exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage )
end
(congr_arg _ $ funext $ assume s, filter.lift_principal hg)
lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) :
(𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) :=
calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg
... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) :
by rw [←uniformity_eq_symm]
... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) :
map_lift_eq2 $ hg.comp monotone_preimage
... = _ : by simp [image_swap_eq_preimage_swap]
lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} :
𝓝 a ×ᶠ 𝓝 b =
(𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α),
{y : α | (y, a) ∈ s} ×ˢ {y : α | (b, y) ∈ t})) :=
begin
rw [nhds_eq_uniformity', nhds_eq_uniformity, prod_lift'_lift'],
{ refl },
{ exact monotone_preimage },
{ exact monotone_preimage },
end
lemma nhds_eq_uniformity_prod {a b : α} :
𝓝 (a, b) =
(𝓤 α).lift' (λs:set (α×α), {y : α | (y, a) ∈ s} ×ˢ {y : α | (b, y) ∈ s}) :=
begin
rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'],
{ intro s, exact monotone_const.set_prod monotone_preimage },
{ intro t, exact monotone_preimage.set_prod monotone_const }
end
lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) :
∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} :=
let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in
have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from
assume ⟨x, y⟩ hp, _root_.mem_nhds_iff.mp $
show cl_d ∈ 𝓝 (x, y),
begin
rw [nhds_eq_uniformity_prod, mem_lift'_sets],
exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩,
exact monotone_preimage.set_prod monotone_preimage
end,
have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)),
∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h,
by simp [classical.skolem] at this; simp; assumption,
match this with
| ⟨t, ht⟩ :=
⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)),
is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left,
assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end,
Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩
end
/-- Entourages are neighborhoods of the diagonal. -/
lemma nhds_le_uniformity (x : α) : 𝓝 (x, x) ≤ 𝓤 α :=
begin
intros V V_in,
rcases comp_symm_mem_uniformity_sets V_in with ⟨w, w_in, w_symm, w_sub⟩,
have : ball x w ×ˢ ball x w ∈ 𝓝 (x, x),
{ rw nhds_prod_eq,
exact prod_mem_prod (ball_mem_nhds x w_in) (ball_mem_nhds x w_in) },
apply mem_of_superset this,
rintros ⟨u, v⟩ ⟨u_in, v_in⟩,
exact w_sub (mem_comp_of_mem_ball w_symm u_in v_in)
end
/-- Entourages are neighborhoods of the diagonal. -/
lemma supr_nhds_le_uniformity : (⨆ x : α, 𝓝 (x, x)) ≤ 𝓤 α :=
supr_le nhds_le_uniformity
/-!
### Closure and interior in uniform spaces
-/
lemma closure_eq_uniformity (s : set $ α × α) :
closure s = ⋂ V ∈ {V | V ∈ 𝓤 α ∧ symmetric_rel V}, V ○ s ○ V :=
begin
ext ⟨x, y⟩,
simp only [mem_closure_iff_nhds_basis (uniform_space.has_basis_nhds_prod x y), mem_Inter,
mem_set_of_eq, and_imp, mem_comp_comp, exists_prop, ← mem_inter_eq, inter_comm, set.nonempty]
{ contextual := tt }
end
lemma uniformity_has_basis_closed : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_closed V) id :=
begin
refine filter.has_basis_self.2 (λ t h, _),
rcases comp_comp_symm_mem_uniformity_sets h with ⟨w, w_in, w_symm, r⟩,
refine ⟨closure w, mem_of_superset w_in subset_closure, is_closed_closure, _⟩,
refine subset.trans _ r,
rw closure_eq_uniformity,
apply Inter_subset_of_subset,
apply Inter_subset,
exact ⟨w_in, w_symm⟩
end
lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure :=
eq.symm $ uniformity_has_basis_closed.lift'_closure_eq_self $ λ _, and.right
lemma filter.has_basis.uniformity_closure {p : ι → Prop} {U : ι → set (α × α)}
(h : (𝓤 α).has_basis p U) : (𝓤 α).has_basis p (λ i, closure (U i)) :=
(@uniformity_eq_uniformity_closure α _).symm ▸ h.lift'_closure
/-- Closed entourages form a basis of the uniformity filter. -/
lemma uniformity_has_basis_closure : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α) closure :=
(𝓤 α).basis_sets.uniformity_closure
lemma closure_eq_inter_uniformity {t : set (α×α)} :
closure t = (⋂ d ∈ 𝓤 α, d ○ (t ○ d)) :=
calc closure t = ⋂ V (hV : V ∈ 𝓤 α ∧ symmetric_rel V), V ○ t ○ V : closure_eq_uniformity t
... = ⋂ V ∈ 𝓤 α, V ○ t ○ V : eq.symm $ uniform_space.has_basis_symmetric.bInter_mem $
λ V₁ V₂ hV, comp_rel_mono (comp_rel_mono hV subset.rfl) hV
... = ⋂ V ∈ 𝓤 α, V ○ (t ○ V) : by simp only [comp_rel_assoc]
lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior :=
le_antisymm
(le_infi $ assume d, le_infi $ assume hd,
let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $
monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp
(comp_le_uniformity3 hd) in
let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in
have s ⊆ interior d, from
calc s ⊆ t : hst
... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $
λ x (hx : x ∈ t), let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp hx in hs_comp ⟨x, h₁, y, h₂, h₃⟩,
have interior d ∈ 𝓤 α, by filter_upwards [hs] using this,
by simp [this])
(assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset)
lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
interior s ∈ 𝓤 α :=
by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs
lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) :
∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s :=
let ⟨t, ⟨ht_mem, htc⟩, hts⟩ := uniformity_has_basis_closed.mem_iff.1 h in
⟨t, ht_mem, htc, hts⟩
lemma is_open_iff_open_ball_subset {s : set α} :
is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, is_open V ∧ ball x V ⊆ s :=
begin
rw is_open_iff_ball_subset,
split; intros h x hx,
{ obtain ⟨V, hV, hV'⟩ := h x hx,
exact ⟨interior V, interior_mem_uniformity hV, is_open_interior,
(ball_mono interior_subset x).trans hV'⟩, },
{ obtain ⟨V, hV, -, hV'⟩ := h x hx,
exact ⟨V, hV, hV'⟩, },
end
/-- The uniform neighborhoods of all points of a dense set cover the whole space. -/
lemma dense.bUnion_uniformity_ball {s : set α} {U : set (α × α)} (hs : dense s) (hU : U ∈ 𝓤 α) :
(⋃ x ∈ s, ball x U) = univ :=
begin
refine Union₂_eq_univ_iff.2 (λ y, _),
rcases hs.inter_nhds_nonempty (mem_nhds_right y hU) with ⟨x, hxs, hxy : (x, y) ∈ U⟩,
exact ⟨x, hxs, hxy⟩
end
/-!
### Uniformity bases
-/
/-- Open elements of `𝓤 α` form a basis of `𝓤 α`. -/
lemma uniformity_has_basis_open : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V) id :=
has_basis_self.2 $ λ s hs,
⟨interior s, interior_mem_uniformity hs, is_open_interior, interior_subset⟩
lemma filter.has_basis.mem_uniformity_iff {p : β → Prop} {s : β → set (α×α)}
(h : (𝓤 α).has_basis p s) {t : set (α × α)} :
t ∈ 𝓤 α ↔ ∃ i (hi : p i), ∀ a b, (a, b) ∈ s i → (a, b) ∈ t :=
h.mem_iff.trans $ by simp only [prod.forall, subset_def]
/-- Open elements `s : set (α × α)` of `𝓤 α` such that `(x, y) ∈ s ↔ (y, x) ∈ s` form a basis
of `𝓤 α`. -/
lemma uniformity_has_basis_open_symmetric :
has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V ∧ symmetric_rel V) id :=
begin
simp only [← and_assoc],
refine uniformity_has_basis_open.restrict (λ s hs, ⟨symmetrize_rel s, _⟩),
exact ⟨⟨symmetrize_mem_uniformity hs.1, is_open.inter hs.2 (hs.2.preimage continuous_swap)⟩,
symmetric_symmetrize_rel s, symmetrize_rel_subset_self s⟩
end
lemma comp_open_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, is_open t ∧ symmetric_rel t ∧ t ○ t ⊆ s :=
begin
obtain ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs,
obtain ⟨u, ⟨hu₁, hu₂, hu₃⟩, hu₄ : u ⊆ t⟩ := uniformity_has_basis_open_symmetric.mem_iff.mp ht₁,
exact ⟨u, hu₁, hu₂, hu₃, (comp_rel_mono hu₄ hu₄).trans ht₂⟩,
end
section
variable (α)
lemma uniform_space.has_seq_basis [is_countably_generated $ 𝓤 α] :
∃ V : ℕ → set (α × α), has_antitone_basis (𝓤 α) V ∧ ∀ n, symmetric_rel (V n) :=
let ⟨U, hsym, hbasis⟩ := uniform_space.has_basis_symmetric.exists_antitone_subbasis
in ⟨U, hbasis, λ n, (hsym n).2⟩
end
lemma filter.has_basis.bInter_bUnion_ball {p : ι → Prop} {U : ι → set (α × α)}
(h : has_basis (𝓤 α) p U) (s : set α) :
(⋂ i (hi : p i), ⋃ x ∈ s, ball x (U i)) = closure s :=
begin
ext x,
simp [mem_closure_iff_nhds_basis (nhds_basis_uniformity h), ball]
end
/-! ### Uniform continuity -/
/-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal
as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then
`f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/
def uniform_continuous [uniform_space β] (f : α → β) :=
tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β)
/-- A function `f : α → β` is *uniformly continuous* on `s : set α` if `(f x, f y)` tends to
the diagonal as `(x, y)` tends to the diagonal while remaining in `s ×ˢ s`.
In other words, if `x` is sufficiently close to `y`, then `f x` is close to
`f y` no matter where `x` and `y` are located in `s`.-/
def uniform_continuous_on [uniform_space β] (f : α → β) (s : set α) : Prop :=
tendsto (λ x : α × α, (f x.1, f x.2)) (𝓤 α ⊓ principal (s ×ˢ s)) (𝓤 β)
theorem uniform_continuous_def [uniform_space β] {f : α → β} :
uniform_continuous f ↔ ∀ r ∈ 𝓤 β, { x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α :=
iff.rfl
theorem uniform_continuous_iff_eventually [uniform_space β] {f : α → β} :
uniform_continuous f ↔ ∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r :=
iff.rfl
theorem uniform_continuous_on_univ [uniform_space β] {f : α → β} :
uniform_continuous_on f univ ↔ uniform_continuous f :=
by rw [uniform_continuous_on, uniform_continuous, univ_prod_univ, principal_univ, inf_top_eq]
lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) :
uniform_continuous c :=
have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from
eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b,
le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem]) refl_le_uniformity
lemma uniform_continuous_id : uniform_continuous (@id α) :=
by simp [uniform_continuous]; exact tendsto_id
lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) :=
uniform_continuous_of_const $ λ _ _, rfl
lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β}
(hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) :=
hg.comp hf
lemma filter.has_basis.uniform_continuous_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)}
(ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t)
{f : α → β} :
uniform_continuous f ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y, (x, y) ∈ s j → (f x, f y) ∈ t i :=
(ha.tendsto_iff hb).trans $ by simp only [prod.forall]
lemma filter.has_basis.uniform_continuous_on_iff [uniform_space β] {p : γ → Prop}
{s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)}
(hb : (𝓤 β).has_basis q t) {f : α → β} {S : set α} :
uniform_continuous_on f S ↔
∀ i (hi : q i), ∃ j (hj : p j), ∀ x y ∈ S, (x, y) ∈ s j → (f x, f y) ∈ t i :=
((ha.inf_principal (S ×ˢ S)).tendsto_iff hb).trans $
by simp [prod.forall, set.inter_comm (s _), ball_mem_comm]
end uniform_space
open_locale uniformity
section constructions
instance : partial_order (uniform_space α) :=
{ le := λt s, t.uniformity ≤ s.uniformity,
le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂,
le_refl := assume t, le_rfl,
le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ }
instance : has_Inf (uniform_space α) :=
⟨assume s, uniform_space.of_core
{ uniformity := (⨅u∈s, @uniformity α u),
refl := le_infi $ assume u, le_infi $ assume hu, u.refl,
symm := le_infi $ assume u, le_infi $ assume hu,
le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm,
comp := le_infi $ assume u, le_infi $ assume hu,
le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_rfl) u.comp }⟩
private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) :
Inf tt ≤ t :=
show (⨅u∈tt, @uniformity α u) ≤ t.uniformity,
from infi_le_of_le t $ infi_le _ h
private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') :
t ≤ Inf tt :=
show t.uniformity ≤ (⨅u∈tt, @uniformity α u),
from le_infi $ assume t', le_infi $ assume ht', h t' ht'
instance : has_top (uniform_space α) :=
⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩
instance : has_bot (uniform_space α) :=
⟨{ to_topological_space := ⊥,
uniformity := 𝓟 id_rel,
refl := le_rfl,
symm := by simp [tendsto]; apply subset.refl,
comp :=
begin
rw [lift'_principal], {simp},
exact monotone_comp_rel monotone_id monotone_id
end,
is_open_uniformity :=
assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩
instance : has_inf (uniform_space α) :=
⟨λ u₁ u₂,
@uniform_space.replace_topology _
(u₁.to_topological_space ⊓ u₂.to_topological_space) (uniform_space.of_core
{ uniformity := u₁.uniformity ⊓ u₂.uniformity,
refl := le_inf u₁.refl u₂.refl,
symm := u₁.symm.inf u₂.symm,
comp := (lift'_inf_le _ _ _).trans $ inf_le_inf u₁.comp u₂.comp }) $
eq_of_nhds_eq_nhds $ λ a,
by simpa only [nhds_inf, nhds_eq_comap_uniformity] using comap_inf.symm⟩
instance : complete_lattice (uniform_space α) :=
{ sup := λa b, Inf {x | a ≤ x ∧ b ≤ x},
le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h),
le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h),
sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩,
inf := (⊓),
le_inf := λ a b c h₁ h₂, show a.uniformity ≤ _, from le_inf h₁ h₂,
inf_le_left := λ a b, show _ ≤ a.uniformity, from inf_le_left,
inf_le_right := λ a b, show _ ≤ b.uniformity, from inf_le_right,
top := ⊤,
le_top := λ a, show a.uniformity ≤ ⊤, from le_top,
bot := ⊥,
bot_le := λ u, u.refl,
Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t},
le_Sup := λ s u h, le_Inf (λ u' h', h' u h),
Sup_le := λ s u h, Inf_le h,
Inf := Inf,
le_Inf := λ s a hs, le_Inf hs,
Inf_le := λ s a ha, Inf_le ha,
..uniform_space.partial_order }
lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} :
(infi u).uniformity = (⨅i, (u i).uniformity) :=
show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from
le_antisymm
(le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩)
(le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _)
lemma infi_uniformity' {ι : Sort*} {u : ι → uniform_space α} :
@uniformity α (infi u) = (⨅i, @uniformity α (u i)) :=
infi_uniformity
lemma inf_uniformity {u v : uniform_space α} :
(u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity :=
rfl
lemma inf_uniformity' {u v : uniform_space α} :
@uniformity α (u ⊓ v) = @uniformity α u ⊓ @uniformity α v :=
rfl
instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩
instance inhabited_uniform_space_core : inhabited (uniform_space.core α) :=
⟨@uniform_space.to_core _ default⟩
/-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f`
is the inverse image in the filter sense of the induced function `α × α → β × β`. -/
def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α :=
{ uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)),
to_topological_space := u.to_topological_space.induced f,
refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl),
symm := by simp [tendsto_comap_iff, prod.swap, (∘)];
exact tendsto_swap_uniformity.comp tendsto_comap,
comp := le_trans
begin
rw [comap_lift'_eq, comap_lift'_eq2],
exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩),
exact monotone_comp_rel monotone_id monotone_id
end
(comap_mono u.comp),
is_open_uniformity := λ s, begin
change (@is_open α (u.to_topological_space.induced f) s ↔ _),
simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff_right, filter.comap, and_comm],
refine ball_congr (λ x hx, ⟨_, _⟩),
{ rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩,
rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) },
{ rintro ⟨t, ht, hts⟩,
exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl,
mem_nhds_uniformity_iff_right.1 $ mem_nhds_left _ ht⟩ }
end }
lemma uniformity_comap [uniform_space α] [uniform_space β] {f : α → β}
(h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) :
𝓤 α = comap (prod.map f f) (𝓤 β) :=
by { rw h, refl }
lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id :=
by ext u ; dsimp only [uniform_space.comap, id] ; rw [prod.id_prod, filter.comap_id]
lemma uniform_space.comap_comap {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} :
uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) :=
by ext ; dsimp only [uniform_space.comap] ; rw filter.comap_comap
lemma uniform_space.comap_inf {α γ} {u₁ u₂ : uniform_space γ} {f : α → γ} :
(u₁ ⊓ u₂).comap f = u₁.comap f ⊓ u₂.comap f :=
uniform_space_eq comap_inf
lemma uniform_space.comap_infi {ι α γ} {u : ι → uniform_space γ} {f : α → γ} :
(⨅ i, u i).comap f = ⨅ i, (u i).comap f :=
begin
ext : 1,
change (𝓤 _) = (𝓤 _),
simp [uniformity_comap rfl, infi_uniformity']
end
lemma uniform_space.comap_mono {α γ} {f : α → γ} :
monotone (λ u : uniform_space γ, u.comap f) :=
begin
intros u₁ u₂ hu,
change (𝓤 _) ≤ (𝓤 _),
rw uniformity_comap rfl,
exact comap_mono hu
end
lemma uniform_continuous_iff {α β} {uα : uniform_space α} {uβ : uniform_space β} {f : α → β} :
uniform_continuous f ↔ uα ≤ uβ.comap f :=
filter.map_le_iff_le_comap
lemma le_iff_uniform_continuous_id {u v : uniform_space α} :
u ≤ v ↔ @uniform_continuous _ _ u v id :=
by rw [uniform_continuous_iff, uniform_space_comap_id, id]
lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] :
@uniform_continuous α β (uniform_space.comap f u) u f :=
tendsto_comap
theorem to_topological_space_comap {f : α → β} {u : uniform_space β} :
@uniform_space.to_topological_space _ (uniform_space.comap f u) =
topological_space.induced f (@uniform_space.to_topological_space β u) := rfl
lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α]
(h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g :=
tendsto_comap_iff.2 h
lemma to_nhds_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) (a : α) :
@nhds _ (@uniform_space.to_topological_space _ u₁) a ≤
@nhds _ (@uniform_space.to_topological_space _ u₂) a :=
by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h le_rfl)
lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) :
@uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ :=
le_of_nhds_le_nhds $ to_nhds_mono h
lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β}
(hf : uniform_continuous f) : continuous f :=
continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf
lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl
lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ :=
top_unique $ assume s hs, s.eq_empty_or_nonempty.elim
(assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤)
(assume ⟨x, hx⟩,
have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl,
this.symm ▸ @is_open_univ _ ⊤)
lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} :
(infi u).to_topological_space = ⨅i, (u i).to_topological_space :=
begin
refine (eq_of_nhds_eq_nhds $ assume a, _),
rw [nhds_infi, nhds_eq_uniformity],
change (infi u).uniformity.lift' (preimage $ prod.mk a) = _,
rw [infi_uniformity, lift'_infi_of_map_univ _ preimage_univ],
{ simp only [nhds_eq_uniformity], refl },
{ exact ball_inter _ }
end
lemma to_topological_space_Inf {s : set (uniform_space α)} :
(Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) :=
begin
rw [Inf_eq_infi],
simp only [← to_topological_space_infi],
end
lemma to_topological_space_inf {u v : uniform_space α} :
(u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space :=
rfl
section uniform_continuous_infi
lemma uniform_continuous_inf_rng {f : α → β} {u₁ : uniform_space α} {u₂ u₃ : uniform_space β}
(h₁ : @@uniform_continuous u₁ u₂ f) (h₂ : @@uniform_continuous u₁ u₃ f) :
@@uniform_continuous u₁ (u₂ ⊓ u₃) f :=
tendsto_inf.mpr ⟨h₁, h₂⟩
lemma uniform_continuous_inf_dom_left {f : α → β} {u₁ u₂ : uniform_space α} {u₃ : uniform_space β}
(hf : @@uniform_continuous u₁ u₃ f) : @@uniform_continuous (u₁ ⊓ u₂) u₃ f :=
tendsto_inf_left hf
lemma uniform_continuous_inf_dom_right {f : α → β} {u₁ u₂ : uniform_space α} {u₃ : uniform_space β}
(hf : @@uniform_continuous u₂ u₃ f) : @@uniform_continuous (u₁ ⊓ u₂) u₃ f :=
tendsto_inf_right hf
lemma uniform_continuous_Inf_dom {f : α → β} {u₁ : set (uniform_space α)} {u₂ : uniform_space β}
{u : uniform_space α} (h₁ : u ∈ u₁) (hf : @@uniform_continuous u u₂ f) :
@@uniform_continuous (Inf u₁) u₂ f :=
begin
rw [uniform_continuous, Inf_eq_infi', infi_uniformity'],
exact tendsto_infi' ⟨u, h₁⟩ hf
end
lemma uniform_continuous_Inf_rng {f : α → β} {u₁ : uniform_space α} {u₂ : set (uniform_space β)}
(h : ∀u∈u₂, @@uniform_continuous u₁ u f) : @@uniform_continuous u₁ (Inf u₂) f :=
begin
rw [uniform_continuous, Inf_eq_infi', infi_uniformity'],
exact tendsto_infi.mpr (λ ⟨u, hu⟩, h u hu)
end
lemma uniform_continuous_infi_dom {f : α → β} {u₁ : ι → uniform_space α} {u₂ : uniform_space β}
{i : ι} (hf : @@uniform_continuous (u₁ i) u₂ f) : @@uniform_continuous (infi u₁) u₂ f :=
begin
rw [uniform_continuous, infi_uniformity'],
exact tendsto_infi' i hf
end
lemma uniform_continuous_infi_rng {f : α → β} {u₁ : uniform_space α} {u₂ : ι → uniform_space β}
(h : ∀i, @@uniform_continuous u₁ (u₂ i) f) : @@uniform_continuous u₁ (infi u₂) f :=
by rwa [uniform_continuous, infi_uniformity', tendsto_infi]
end uniform_continuous_infi
/-- A uniform space with the discrete uniformity has the discrete topology. -/
lemma discrete_topology_of_discrete_uniformity [hα : uniform_space α]
(h : uniformity α = 𝓟 id_rel) :
discrete_topology α :=
⟨(uniform_space_eq h.symm : ⊥ = hα) ▸ rfl⟩
instance : uniform_space empty := ⊥
instance : uniform_space punit := ⊥
instance : uniform_space bool := ⊥
instance : uniform_space ℕ := ⊥
instance : uniform_space ℤ := ⊥
section
variables [uniform_space α]
open additive multiplicative
instance : uniform_space (additive α) := ‹uniform_space α›
instance : uniform_space (multiplicative α) := ‹uniform_space α›
lemma uniform_continuous_of_mul : uniform_continuous (of_mul : α → additive α) :=
uniform_continuous_id
lemma uniform_continuous_to_mul : uniform_continuous (to_mul : additive α → α) :=
uniform_continuous_id
lemma uniform_continuous_of_add : uniform_continuous (of_add : α → multiplicative α) :=
uniform_continuous_id
lemma uniform_continuous_to_add : uniform_continuous (to_add : multiplicative α → α) :=
uniform_continuous_id
lemma uniformity_additive : 𝓤 (additive α) = (𝓤 α).map (prod.map of_mul of_mul) :=
by { convert map_id.symm, exact prod.map_id }
lemma uniformity_multiplicative : 𝓤 (multiplicative α) = (𝓤 α).map (prod.map of_add of_add) :=
by { convert map_id.symm, exact prod.map_id }
end
instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) :=
uniform_space.comap subtype.val t
lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] :
𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) :=
rfl
lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] :
uniform_continuous (subtype.val : {a : α // p a} → α) :=
uniform_continuous_comap
lemma uniform_continuous_subtype_coe {p : α → Prop} [uniform_space α] :
uniform_continuous (coe : {a : α // p a} → α) :=
uniform_continuous_subtype_val
lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β]
{f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) :
uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) :=
uniform_continuous_comap' hf
lemma uniform_continuous_on_iff_restrict [uniform_space α] [uniform_space β] {f : α → β}
{s : set α} :
uniform_continuous_on f s ↔ uniform_continuous (s.restrict f) :=
begin
unfold uniform_continuous_on set.restrict uniform_continuous tendsto,
rw [show (λ x : s × s, (f x.1, f x.2)) = prod.map f f ∘ coe, by ext x; cases x; refl,
uniformity_comap rfl,
show prod.map subtype.val subtype.val = (coe : s × s → α × α), by ext x; cases x; refl],
conv in (map _ (comap _ _)) { rw ← filter.map_map },
rw subtype_coe_map_comap_prod, refl,
end
lemma tendsto_of_uniform_continuous_subtype
[uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α}
(hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) :
tendsto f (𝓝 a) (𝓝 (f a)) :=
by rw [(@map_nhds_subtype_coe_eq α _ s a (mem_of_mem_nhds ha) ha).symm]; exact
tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _)
lemma uniform_continuous_on.continuous_on [uniform_space α] [uniform_space β] {f : α → β}
{s : set α} (h : uniform_continuous_on f s) : continuous_on f s :=
begin
rw uniform_continuous_on_iff_restrict at h,
rw continuous_on_iff_continuous_restrict,
exact h.continuous
end
@[to_additive]
instance [uniform_space α] : uniform_space (αᵐᵒᵖ) :=
uniform_space.comap mul_opposite.unop ‹_›
@[to_additive]
lemma uniformity_mul_opposite [uniform_space α] :
𝓤 (αᵐᵒᵖ) = comap (λ q : αᵐᵒᵖ × αᵐᵒᵖ, (q.1.unop, q.2.unop)) (𝓤 α) :=
rfl
@[simp, to_additive] lemma comap_uniformity_mul_opposite [uniform_space α] :
comap (λ p : α × α, (mul_opposite.op p.1, mul_opposite.op p.2)) (𝓤 αᵐᵒᵖ) = 𝓤 α :=
by simpa [uniformity_mul_opposite, comap_comap, (∘)] using comap_id
namespace mul_opposite
@[to_additive]
lemma uniform_continuous_unop [uniform_space α] : uniform_continuous (unop : αᵐᵒᵖ → α) :=
uniform_continuous_comap
@[to_additive]
lemma uniform_continuous_op [uniform_space α] : uniform_continuous (op : α → αᵐᵒᵖ) :=
uniform_continuous_comap' uniform_continuous_id
end mul_opposite
section prod
/- a similar product space is possible on the function space (uniformity of pointwise convergence),
but we want to have the uniformity of uniform convergence on function spaces -/
instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) :=
u₁.comap prod.fst ⊓ u₂.comap prod.snd
-- check the above produces no diamond
example [u₁ : uniform_space α] [u₂ : uniform_space β] :
(prod.topological_space : topological_space (α × β)) = uniform_space.to_topological_space :=
rfl
theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) =
(𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓
(𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) :=
rfl
lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] :
𝓤 (α × β) = map (λ p : (α × α) × (β × β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ᶠ 𝓤 β) :=
by rw [map_swap4_eq_comap, uniformity_prod, filter.prod, comap_inf, comap_comap, comap_comap]
lemma mem_map_iff_exists_image' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} :
t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) :=
mem_map_iff_exists_image
lemma mem_uniformity_of_uniform_continuous_invariant [uniform_space α] {s:set (α×α)} {f : α → α → α}
(hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) :
∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s :=
begin
rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf,
rcases mem_map_iff_exists_image'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf,
rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht,
refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩,
exact hab,
exact refl_mem_uniformity hv,
refl
end
lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)}
{b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) :
{p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) :=
by rw [uniformity_prod]; exact inter_mem_inf (preimage_mem_comap ha) (preimage_mem_comap hb)
lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] :
tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) :=
le_trans (map_mono inf_le_left) map_comap_le
lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] :
tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) :=
le_trans (map_mono inf_le_right) map_comap_le
lemma uniform_continuous_fst [uniform_space α] [uniform_space β] :
uniform_continuous (λp:α×β, p.1) :=
tendsto_prod_uniformity_fst
lemma uniform_continuous_snd [uniform_space α] [uniform_space β] :
uniform_continuous (λp:α×β, p.2) :=
tendsto_prod_uniformity_snd
variables [uniform_space α] [uniform_space β] [uniform_space γ]
lemma uniform_continuous.prod_mk
{f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) :
uniform_continuous (λa, (f₁ a, f₂ a)) :=
by rw [uniform_continuous, uniformity_prod]; exact
tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩
lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) :
uniform_continuous (λ a, f (a,b)) :=
h.comp (uniform_continuous_id.prod_mk uniform_continuous_const)
lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) :
uniform_continuous (λ b, f (a,b)) :=
h.comp (uniform_continuous_const.prod_mk uniform_continuous_id)
lemma uniform_continuous.prod_map [uniform_space δ] {f : α → γ} {g : β → δ}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
uniform_continuous (prod.map f g) :=
(hf.comp uniform_continuous_fst).prod_mk (hg.comp uniform_continuous_snd)
lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] :
@uniform_space.to_topological_space (α × β) prod.uniform_space =
@prod.topological_space α β u.to_topological_space v.to_topological_space := rfl
/-- A version of `uniform_continuous_inf_dom_left` for binary functions -/
lemma uniform_continuous_inf_dom_left₂ {α β γ} {f : α → β → γ}
{ua1 ua2 : uniform_space α} {ub1 ub2 : uniform_space β} {uc1 : uniform_space γ}
(h : by haveI := ua1; haveI := ub1; exact uniform_continuous (λ p : α × β, f p.1 p.2)) :
by haveI := ua1 ⊓ ua2; haveI := ub1 ⊓ ub2; exact uniform_continuous (λ p : α × β, f p.1 p.2) :=
begin
-- proof essentially copied from ``continuous_inf_dom_left₂`
have ha := @uniform_continuous_inf_dom_left _ _ id ua1 ua2 ua1 (@uniform_continuous_id _ (id _)),
have hb := @uniform_continuous_inf_dom_left _ _ id ub1 ub2 ub1 (@uniform_continuous_id _ (id _)),
have h_unif_cont_id := @uniform_continuous.prod_map _ _ _ _ (
ua1 ⊓ ua2) (ub1 ⊓ ub2) ua1 ub1 _ _ ha hb,
exact @uniform_continuous.comp _ _ _ (id _) (id _) _ _ _ h h_unif_cont_id,
end
/-- A version of `uniform_continuous_inf_dom_right` for binary functions -/
lemma uniform_continuous_inf_dom_right₂ {α β γ} {f : α → β → γ}
{ua1 ua2 : uniform_space α} {ub1 ub2 : uniform_space β} {uc1 : uniform_space γ}
(h : by haveI := ua2; haveI := ub2; exact uniform_continuous (λ p : α × β, f p.1 p.2)) :
by haveI := ua1 ⊓ ua2; haveI := ub1 ⊓ ub2; exact uniform_continuous (λ p : α × β, f p.1 p.2) :=
begin
-- proof essentially copied from ``continuous_inf_dom_right₂`
have ha := @uniform_continuous_inf_dom_right _ _ id ua1 ua2 ua2 (@uniform_continuous_id _ (id _)),
have hb := @uniform_continuous_inf_dom_right _ _ id ub1 ub2 ub2 (@uniform_continuous_id _ (id _)),
have h_unif_cont_id := @uniform_continuous.prod_map _ _ _ _
(ua1 ⊓ ua2) (ub1 ⊓ ub2) ua2 ub2 _ _ ha hb,
exact @uniform_continuous.comp _ _ _ (id _) (id _) _ _ _ h h_unif_cont_id,
end
/-- A version of `uniform_continuous_Inf_dom` for binary functions -/
lemma uniform_continuous_Inf_dom₂ {α β γ} {f : α → β → γ}
{uas : set (uniform_space α)} {ubs : set (uniform_space β)}
{ua : uniform_space α} {ub : uniform_space β} {uc : uniform_space γ}
(ha : ua ∈ uas) (hb : ub ∈ ubs)
(hf : uniform_continuous (λ p : α × β, f p.1 p.2)):
by haveI := Inf uas; haveI := Inf ubs;
exact @uniform_continuous _ _ _ uc (λ p : α × β, f p.1 p.2) :=
begin
-- proof essentially copied from ``continuous_Inf_dom`
let t : uniform_space (α × β) := prod.uniform_space,
have ha := uniform_continuous_Inf_dom ha uniform_continuous_id,
have hb := uniform_continuous_Inf_dom hb uniform_continuous_id,
have h_unif_cont_id := @uniform_continuous.prod_map _ _ _ _ (Inf uas) (Inf ubs) ua ub _ _ ha hb,
exact @uniform_continuous.comp _ _ _ (id _) (id _) _ _ _ hf h_unif_cont_id,
end
end prod
section
open uniform_space function
variables {δ' : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ]
[uniform_space δ']
local notation f `∘₂` g := function.bicompr f g
/-- Uniform continuity for functions of two variables. -/
def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry f)
lemma uniform_continuous₂_def (f : α → β → γ) :
uniform_continuous₂ f ↔ uniform_continuous (uncurry f) := iff.rfl
lemma uniform_continuous₂.uniform_continuous {f : α → β → γ} (h : uniform_continuous₂ f) :
uniform_continuous (uncurry f) := h
lemma uniform_continuous₂_curry (f : α × β → γ) :
uniform_continuous₂ (function.curry f) ↔ uniform_continuous f :=
by rw [uniform_continuous₂, uncurry_curry]
lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ}
(hg : uniform_continuous g) (hf : uniform_continuous₂ f) :
uniform_continuous₂ (g ∘₂ f) :=
hg.comp hf
lemma uniform_continuous₂.bicompl {f : α → β → γ} {ga : δ → α} {gb : δ' → β}
(hf : uniform_continuous₂ f) (hga : uniform_continuous ga) (hgb : uniform_continuous gb) :
uniform_continuous₂ (bicompl f ga gb) :=
hf.uniform_continuous.comp (hga.prod_map hgb)
end
lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} :
@uniform_space.to_topological_space (subtype p) subtype.uniform_space =
@subtype.topological_space α p u.to_topological_space := rfl
section sum
variables [uniform_space α] [uniform_space β]
open sum
/-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained
by taking independently an entourage of the diagonal in the first part, and an entourage of
the diagonal in the second part. -/
def uniform_space.core.sum : uniform_space.core (α ⊕ β) :=
uniform_space.core.mk'
(map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β))
(λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂])
(λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩)
(λ r ⟨Hrα, Hrβ⟩, begin
rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩,
rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩,
refine ⟨_,
⟨mem_map_iff_exists_image.2 ⟨tα, htα, subset_union_left _ _⟩,
mem_map_iff_exists_image.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩,
rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩,
⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩,
{ have A : (a, c) ∈ tα ○ tα := ⟨b, hab, hbc⟩,
exact Htα A },
{ have A : (a, c) ∈ tβ ○ tβ := ⟨b, hab, hbc⟩,
exact Htβ A }
end)
/-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage
of the diagonal. -/
lemma union_mem_uniformity_sum
{a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) :
((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈
(@uniform_space.core.sum α β _ _).uniformity :=
⟨mem_map_iff_exists_image.2 ⟨_, ha, subset_union_left _ _⟩,
mem_map_iff_exists_image.2 ⟨_, hb, subset_union_right _ _⟩⟩
/- To prove that the topology defined by the uniform structure on the disjoint union coincides with
the disjoint union topology, we need two lemmas saying that open sets can be characterized by
the uniform structure -/
lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) :
{ p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity :=
begin
cases x,
{ refine mem_of_superset
(union_mem_uniformity_sum (mem_nhds_uniformity_iff_right.1 (is_open.mem_nhds hs.1 xs))
univ_mem)
(union_subset _ _);
rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩,
exact h rfl },
{ refine mem_of_superset
(union_mem_uniformity_sum univ_mem (mem_nhds_uniformity_iff_right.1
(is_open.mem_nhds hs.2 xs)))
(union_subset _ _);
rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩,
exact h rfl },
end
lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)}
(hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈
(@uniform_space.core.sum α β _ _).uniformity) :
is_open s :=
begin
split,
{ refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff_right.2 _),
rcases mem_map_iff_exists_image.1 (hs _ ha).1 with ⟨t, ht, st⟩,
refine mem_of_superset ht _,
rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl },
{ refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff_right.2 _),
rcases mem_map_iff_exists_image.1 (hs _ hb).2 with ⟨t, ht, st⟩,
refine mem_of_superset ht _,
rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }
end
/- We can now define the uniform structure on the disjoint union -/
instance sum.uniform_space : uniform_space (α ⊕ β) :=
{ to_core := uniform_space.core.sum,
is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ }
lemma sum.uniformity : 𝓤 (α ⊕ β) =
map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔
map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl
end sum
end constructions
-- For a version of the Lebesgue number lemma assuming only a sequentially compact space,
-- see topology/sequences.lean
/-- Let `c : ι → set α` be an open cover of a compact set `s`. Then there exists an entourage
`n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `c i`. -/
lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α}
(hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i :=
begin
let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ m ○ n} ⊆ c i},
have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n),
{ refine λ n hn, is_open_uniformity.2 _,
rintro x ⟨i, m, hm, h⟩,
rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩,
apply (𝓤 α).sets_of_superset hm',
rintros ⟨x, y⟩ hp rfl,
refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩,
dsimp [-mem_comp_rel] at hz ⊢, rw comp_rel_assoc,
exact ⟨y, hp, hz⟩ },
have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n,
{ intros x hx,
rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩,
rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩,
exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ },
rcases hs.elim_finite_subcover_image hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩,
refine ⟨_, (bInter_mem b_fin).2 bu, λ x hx, _⟩,
rcases mem_Union₂.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩,
refine ⟨i, λ y hy, h _⟩,
exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy)
end
/-- Let `c : set (set α)` be an open cover of a compact set `s`. Then there exists an entourage
`n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `t ∈ c`. -/
lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)}
(hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma hs (by simpa) hc₂
/-- A useful consequence of the Lebesgue number lemma: given any compact set `K` contained in an
open set `U`, we can find an (open) entourage `V` such that the ball of size `V` about any point of
`K` is contained in `U`. -/
lemma lebesgue_number_of_compact_open [uniform_space α]
{K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) :
∃ V ∈ 𝓤 α, is_open V ∧ ∀ x ∈ K, uniform_space.ball x V ⊆ U :=
begin
let W : K → set (α × α) := λ k, classical.some $ is_open_iff_open_ball_subset.mp hU k.1 $ hKU k.2,
have hW : ∀ k, W k ∈ 𝓤 α ∧ is_open (W k) ∧ uniform_space.ball k.1 (W k) ⊆ U,
{ intros k,
obtain ⟨h₁, h₂, h₃⟩ := classical.some_spec (is_open_iff_open_ball_subset.mp hU k.1 (hKU k.2)),
exact ⟨h₁, h₂, h₃⟩, },
let c : K → set α := λ k, uniform_space.ball k.1 (W k),
have hc₁ : ∀ k, is_open (c k), { exact λ k, uniform_space.is_open_ball k.1 (hW k).2.1, },
have hc₂ : K ⊆ ⋃ i, c i,
{ intros k hk,
simp only [mem_Union, set_coe.exists],
exact ⟨k, hk, uniform_space.mem_ball_self k (hW ⟨k, hk⟩).1⟩, },
have hc₃ : ∀ k, c k ⊆ U, { exact λ k, (hW k).2.2, },
obtain ⟨V, hV, hV'⟩ := lebesgue_number_lemma hK hc₁ hc₂,
refine ⟨interior V, interior_mem_uniformity hV, is_open_interior, _⟩,
intros k hk,
obtain ⟨k', hk'⟩ := hV' k hk,
exact ((ball_mono interior_subset k).trans hk').trans (hc₃ k'),
end
/-!
### Expressing continuity properties in uniform spaces
We reformulate the various continuity properties of functions taking values in a uniform space
in terms of the uniformity in the target. Since the same lemmas (essentially with the same names)
also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or
the edistance in the target), we put them in a namespace `uniform` here.
In the metric and emetric space setting, there are also similar lemmas where one assumes that
both the source and the target are metric spaces, reformulating things in terms of the distance
on both sides. These lemmas are generally written without primes, and the versions where only
the target is a metric space is primed. We follow the same convention here, thus giving lemmas
with primes.
-/
namespace uniform
variables [uniform_space α]
theorem tendsto_nhds_right {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ tendsto (λ x, (a, u x)) f (𝓤 α) :=
⟨λ H, tendsto_left_nhds_uniformity.comp H,
λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_right.1 hs)⟩
theorem tendsto_nhds_left {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ tendsto (λ x, (u x, a)) f (𝓤 α) :=
⟨λ H, tendsto_right_nhds_uniformity.comp H,
λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_left.1 hs)⟩
theorem continuous_at_iff'_right [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) :=
by rw [continuous_at, tendsto_nhds_right]
theorem continuous_at_iff'_left [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) :=
by rw [continuous_at, tendsto_nhds_left]
theorem continuous_at_iff_prod [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ tendsto (λ x : β × β, (f x.1, f x.2)) (𝓝 (b, b)) (𝓤 α) :=
⟨λ H, le_trans (H.prod_map' H) (nhds_le_uniformity _),
λ H, continuous_at_iff'_left.2 $ H.comp $ tendsto_id.prod_mk_nhds tendsto_const_nhds⟩
theorem continuous_within_at_iff'_right [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔ tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) :=
by rw [continuous_within_at, tendsto_nhds_right]
theorem continuous_within_at_iff'_left [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔ tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) :=
by rw [continuous_within_at, tendsto_nhds_left]
theorem continuous_on_iff'_right [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) :=
by simp [continuous_on, continuous_within_at_iff'_right]
theorem continuous_on_iff'_left [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) :=
by simp [continuous_on, continuous_within_at_iff'_left]
theorem continuous_iff'_right [topological_space β] {f : β → α} :
continuous f ↔ ∀ b, tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_right
theorem continuous_iff'_left [topological_space β] {f : β → α} :
continuous f ↔ ∀ b, tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_left
end uniform
lemma filter.tendsto.congr_uniformity {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β}
(hf : tendsto f l (𝓝 b)) (hg : tendsto (λ x, (f x, g x)) l (𝓤 β)) :
tendsto g l (𝓝 b) :=
uniform.tendsto_nhds_right.2 $ (uniform.tendsto_nhds_right.1 hf).uniformity_trans hg
lemma uniform.tendsto_congr {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β}
(hfg : tendsto (λ x, (f x, g x)) l (𝓤 β)) :
tendsto f l (𝓝 b) ↔ tendsto g l (𝓝 b) :=
⟨λ h, h.congr_uniformity hfg, λ h, h.congr_uniformity hfg.uniformity_symm⟩
|
522d810480dcccdab0e4d47b9c113bc5d272ac3c | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /library/init/num.lean | 9a56aa0e75853cf5094a0743cb49207352626d28 | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,284 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: init.num
Authors: Leonardo de Moura
-/
prelude
import init.logic init.bool
open bool
definition pos_num.is_inhabited [instance] : inhabited pos_num :=
inhabited.mk pos_num.one
namespace pos_num
definition is_one (a : pos_num) : bool :=
pos_num.rec_on a tt (λn r, ff) (λn r, ff)
definition pred (a : pos_num) : pos_num :=
pos_num.rec_on a one (λn r, bit0 n) (λn r, cond (is_one n) one (bit1 r))
definition size (a : pos_num) : pos_num :=
pos_num.rec_on a one (λn r, succ r) (λn r, succ r)
definition add (a b : pos_num) : pos_num :=
pos_num.rec_on a
succ
(λn f b, pos_num.rec_on b
(succ (bit1 n))
(λm r, succ (bit1 (f m)))
(λm r, bit1 (f m)))
(λn f b, pos_num.rec_on b
(bit1 n)
(λm r, bit1 (f m))
(λm r, bit0 (f m)))
b
notation a + b := add a b
definition mul (a b : pos_num) : pos_num :=
pos_num.rec_on a
b
(λn r, bit0 r + b)
(λn r, bit0 r)
notation a * b := mul a b
definition lt (a b : pos_num) : bool :=
pos_num.rec_on a
(λ b, pos_num.cases_on b
ff
(λm, tt)
(λm, tt))
(λn f b, pos_num.cases_on b
ff
(λm, f m)
(λm, f m))
(λn f b, pos_num.cases_on b
ff
(λm, f (succ m))
(λm, f m))
b
definition le (a b : pos_num) : bool :=
lt a (succ b)
end pos_num
definition num.is_inhabited [instance] : inhabited num :=
inhabited.mk num.zero
namespace num
open pos_num
definition pred (a : num) : num :=
num.rec_on a zero (λp, cond (is_one p) zero (pos (pred p)))
definition size (a : num) : num :=
num.rec_on a (pos one) (λp, pos (size p))
definition add (a b : num) : num :=
num.rec_on a b (λpa, num.rec_on b (pos pa) (λpb, pos (pos_num.add pa pb)))
definition mul (a b : num) : num :=
num.rec_on a zero (λpa, num.rec_on b zero (λpb, pos (pos_num.mul pa pb)))
notation a + b := add a b
notation a * b := mul a b
definition le (a b : num) : bool :=
num.rec_on a tt (λpa, num.rec_on b ff (λpb, pos_num.le pa pb))
private definition psub (a b : pos_num) : num :=
pos_num.rec_on a
(λb, zero)
(λn f b,
cond (pos_num.le (bit1 n) b)
zero
(pos_num.cases_on b
(pos (bit0 n))
(λm, 2 * f m)
(λm, 2 * f m + 1)))
(λn f b,
cond (pos_num.le (bit0 n) b)
zero
(pos_num.cases_on b
(pos (pos_num.pred (bit0 n)))
(λm, pred (2 * f m))
(λm, 2 * f m)))
b
definition sub (a b : num) : num :=
num.rec_on a zero (λpa, num.rec_on b a (λpb, psub pa pb))
notation a ≤ b := le a b
notation a - b := sub a b
end num
-- the coercion from num to nat is defined here,
-- so that it can already be used in init.tactic
namespace nat
definition add (a b : nat) : nat :=
nat.rec_on b a (λ b₁ r, succ r)
notation a + b := add a b
definition of_num [coercion] (n : num) : nat :=
num.rec zero
(λ n, pos_num.rec (succ zero) (λ n r, r + r + (succ zero)) (λ n r, r + r) n) n
end nat
attribute nat.of_num [reducible] -- of_num is also reducible if namespace "nat" is not opened
|
8777a2f77c73a5b921580e5c04857fc9974e8d99 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/complex/phragmen_lindelof.lean | 4ed88cff0bf7b914343fb03fb81fb18ac44f9fb2 | [
"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 | 49,550 | lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.complex.abs_max
import analysis.asymptotics.superpolynomial_decay
/-!
# Phragmen-Lindelöf principle
In this file we prove several versions of the Phragmen-Lindelöf principle, a version of the maximum
modulus principle for an unbounded domain.
## Main statements
* `phragmen_lindelof.horizontal_strip`: the Phragmen-Lindelöf principle in a horizontal strip
`{z : ℂ | a < complex.im z < b}`;
* `phragmen_lindelof.eq_zero_on_horizontal_strip`, `phragmen_lindelof.eq_on_horizontal_strip`:
extensionality lemmas based on the Phragmen-Lindelöf principle in a horizontal strip;
* `phragmen_lindelof.vertical_strip`: the Phragmen-Lindelöf principle in a vertical strip
`{z : ℂ | a < complex.re z < b}`;
* `phragmen_lindelof.eq_zero_on_vertical_strip`, `phragmen_lindelof.eq_on_vertical_strip`:
extensionality lemmas based on the Phragmen-Lindelöf principle in a vertical strip;
* `phragmen_lindelof.quadrant_I`, `phragmen_lindelof.quadrant_II`, `phragmen_lindelof.quadrant_III`,
`phragmen_lindelof.quadrant_IV`: the Phragmen-Lindelöf principle in the coordinate quadrants;
* `phragmen_lindelof.right_half_plane_of_tendsto_zero_on_real`,
`phragmen_lindelof.right_half_plane_of_bounded_on_real`: two versions of the Phragmen-Lindelöf
principle in the right half-plane;
* `phragmen_lindelof.eq_zero_on_right_half_plane_of_superexponential_decay`,
`phragmen_lindelof.eq_on_right_half_plane_of_superexponential_decay`: extensionality lemmas based
on the Phragmen-Lindelöf principle in the right half-plane.
In the case of the right half-plane, we prove a version of the Phragmen-Lindelöf principle that is
useful for Ilyashenko's proof of the individual finiteness theorem (a polynomial vector field on the
real plane has only finitely many limit cycles).
-/
open set function filter asymptotics metric complex
open_locale topological_space filter real
local notation `expR` := real.exp
namespace phragmen_lindelof
/-!
### Auxiliary lemmas
-/
variables {E : Type*} [normed_add_comm_group E]
/-- An auxiliary lemma that combines two double exponential estimates into a similar estimate
on the difference of the functions. -/
lemma is_O_sub_exp_exp {a : ℝ} {f g : ℂ → E} {l : filter ℂ} {u : ℂ → ℝ}
(hBf : ∃ (c < a) B, f =O[l] (λ z, expR (B * expR (c * |u z|))))
(hBg : ∃ (c < a) B, g =O[l] (λ z, expR (B * expR (c * |u z|)))) :
∃ (c < a) B, (f - g) =O[l] (λ z, expR (B * expR (c * |u z|))) :=
begin
have : ∀ {c₁ c₂ B₁ B₂}, c₁ ≤ c₂ → 0 ≤ B₂ → B₁ ≤ B₂ → ∀ z,
‖expR (B₁ * expR (c₁ * |u z|))‖ ≤ ‖expR (B₂ * expR (c₂ * |u z|))‖,
{ intros c₁ c₂ B₁ B₂ hc hB₀ hB z,
rw [real.norm_eq_abs, real.norm_eq_abs, real.abs_exp, real.abs_exp, real.exp_le_exp],
exact mul_le_mul hB (real.exp_le_exp.2 $ mul_le_mul_of_nonneg_right hc $ abs_nonneg _)
(real.exp_pos _).le hB₀ },
rcases hBf with ⟨cf, hcf, Bf, hOf⟩, rcases hBg with ⟨cg, hcg, Bg, hOg⟩,
refine ⟨max cf cg, max_lt hcf hcg, max 0 (max Bf Bg), _⟩,
refine (hOf.trans_le $ this _ _ _).sub (hOg.trans_le $ this _ _ _),
exacts [le_max_left _ _, le_max_left _ _, (le_max_left _ _).trans (le_max_right _ _),
le_max_right _ _, le_max_left _ _, (le_max_right _ _).trans (le_max_right _ _)]
end
/-- An auxiliary lemma that combines two “exponential of a power” estimates into a similar estimate
on the difference of the functions. -/
lemma is_O_sub_exp_rpow {a : ℝ} {f g : ℂ → E} {l : filter ℂ}
(hBf : ∃ (c < a) B, f =O[comap complex.abs at_top ⊓ l] (λ z, expR (B * (abs z) ^ c)))
(hBg : ∃ (c < a) B, g =O[comap complex.abs at_top ⊓ l] (λ z, expR (B * (abs z) ^ c))) :
∃ (c < a) B, (f - g) =O[comap complex.abs at_top ⊓ l] (λ z, expR (B * (abs z) ^ c)) :=
begin
have : ∀ {c₁ c₂ B₁ B₂ : ℝ}, c₁ ≤ c₂ → 0 ≤ B₂ → B₁ ≤ B₂ →
(λ z : ℂ, expR (B₁ * (abs z) ^ c₁)) =O[comap complex.abs at_top ⊓ l]
(λ z, expR (B₂ * (abs z) ^ c₂)),
{ have : ∀ᶠ z : ℂ in comap complex.abs at_top ⊓ l, 1 ≤ abs z,
from ((eventually_ge_at_top 1).comap _).filter_mono inf_le_left,
refine λ c₁ c₂ B₁ B₂ hc hB₀ hB, is_O.of_bound 1 (this.mono $ λ z hz, _),
rw [one_mul, real.norm_eq_abs, real.norm_eq_abs, real.abs_exp, real.abs_exp, real.exp_le_exp],
exact mul_le_mul hB (real.rpow_le_rpow_of_exponent_le hz hc)
(real.rpow_nonneg_of_nonneg (complex.abs.nonneg _) _) hB₀ },
rcases hBf with ⟨cf, hcf, Bf, hOf⟩, rcases hBg with ⟨cg, hcg, Bg, hOg⟩,
refine ⟨max cf cg, max_lt hcf hcg, max 0 (max Bf Bg), _⟩,
refine (hOf.trans $ this _ _ _).sub (hOg.trans $ this _ _ _),
exacts [le_max_left _ _, le_max_left _ _, (le_max_left _ _).trans (le_max_right _ _),
le_max_right _ _, le_max_left _ _, (le_max_right _ _).trans (le_max_right _ _)]
end
variables [normed_space ℂ E] {a b C : ℝ} {f g : ℂ → E} {z : ℂ}
/-!
### Phragmen-Lindelöf principle in a horizontal strip
-/
/-- **Phragmen-Lindelöf principle** in a strip `U = {z : ℂ | a < im z < b}`.
Let `f : ℂ → E` be a function such that
* `f` is differentiable on `U` and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * exp(c * |re z|))` on `U` for some `c < π / (b - a)`;
* `‖f z‖` is bounded from above by a constant `C` on the boundary of `U`.
Then `‖f z‖` is bounded by the same constant on the closed strip
`{z : ℂ | a ≤ im z ≤ b}`. Moreover, it suffices to verify the second assumption
only for sufficiently large values of `|re z|`.
-/
lemma horizontal_strip (hfd : diff_cont_on_cl ℂ f (im ⁻¹' Ioo a b))
(hB : ∃ (c < π / (b - a)) B, f =O[comap (has_abs.abs ∘ re) at_top ⊓ 𝓟 (im ⁻¹' Ioo a b)]
(λ z, expR (B * expR (c * |z.re|))))
(hle_a : ∀ z : ℂ, im z = a → ‖f z‖ ≤ C) (hle_b : ∀ z, im z = b → ‖f z‖ ≤ C)
(hza : a ≤ im z) (hzb : im z ≤ b) :
‖f z‖ ≤ C :=
begin
-- If `im z = a` or `im z = b`, then we apply `hle_a` or `hle_b`, otherwise `im z ∈ Ioo a b`.
rw le_iff_eq_or_lt at hza hzb,
cases hza with hza hza, { exact hle_a _ hza.symm },
cases hzb with hzb hzb, { exact hle_b _ hzb },
-- WLOG, `0 < C`.
suffices : ∀ C' : ℝ, 0 < C' → (∀ w : ℂ, im w = a → ‖f w‖ ≤ C') →
(∀ w : ℂ, im w = b → ‖f w‖ ≤ C') → ‖f z‖ ≤ C',
{ refine le_of_forall_le_of_dense (λ C' hC', this C' _ (λ w hw, _) (λ w hw, _)),
{ refine ((norm_nonneg (f (a * I))).trans (hle_a _ _)).trans_lt hC',
rw [mul_I_im, of_real_re] },
exacts [(hle_a _ hw).trans hC'.le, (hle_b _ hw).trans hC'.le] },
clear_dependent C, intros C hC₀ hle_a hle_b,
-- After a change of variables, we deal with the strip `a - b < im z < a + b` instead
-- of `a < im z < b`
obtain ⟨a, b, rfl, rfl⟩ : ∃ a' b', a = a' - b' ∧ b = a' + b' :=
⟨(a + b) / 2, (b - a) / 2, by ring, by ring⟩,
have hab : a - b < a + b, from hza.trans hzb,
have hb : 0 < b,
by simpa only [sub_eq_add_neg, add_lt_add_iff_left, neg_lt_self_iff] using hab,
rw [add_sub_sub_cancel, ← two_mul, div_mul_eq_div_div] at hB,
have hπb : 0 < π / 2 / b, from div_pos real.pi_div_two_pos hb,
-- Choose some `c B : ℝ` satisfying `hB`, then choose `max c 0 < d < π / 2 / b`.
rcases hB with ⟨c, hc, B, hO⟩,
obtain ⟨d, ⟨hcd, hd₀⟩, hd⟩ : ∃ d, (c < d ∧ 0 < d) ∧ d < π / 2 / b,
by simpa only [max_lt_iff] using exists_between (max_lt hc hπb),
have hb' : d * b < π / 2, from (lt_div_iff hb).1 hd,
set aff : ℂ → ℂ := λ w, d * (w - a * I),
set g : ℝ → ℂ → ℂ := λ ε w, exp (ε * (exp (aff w) + exp (-aff w))),
/- Since `g ε z → 1` as `ε → 0⁻`, it suffices to prove that `‖g ε z • f z‖ ≤ C`
for all negative `ε`. -/
suffices : ∀ᶠ ε : ℝ in 𝓝[<] 0, ‖g ε z • f z‖ ≤ C,
{ refine le_of_tendsto (tendsto.mono_left _ nhds_within_le_nhds) this,
apply ((continuous_of_real.mul continuous_const).cexp.smul continuous_const).norm.tendsto',
simp, apply_instance },
filter_upwards [self_mem_nhds_within] with ε ε₀, change ε < 0 at ε₀,
-- An upper estimate on `‖g ε w‖` that will be used in two branches of the proof.
obtain ⟨δ, δ₀, hδ⟩ : ∃ δ : ℝ, δ < 0 ∧ ∀ ⦃w⦄, im w ∈ Icc (a - b) (a + b) →
abs (g ε w) ≤ expR (δ * expR (d * |re w|)),
{ refine ⟨ε * real.cos (d * b), mul_neg_of_neg_of_pos ε₀ (real.cos_pos_of_mem_Ioo $ abs_lt.1 $
(abs_of_pos (mul_pos hd₀ hb)).symm ▸ hb'), λ w hw, _⟩,
replace hw : |im (aff w)| ≤ d * b,
{ rw [← real.closed_ball_eq_Icc] at hw,
rwa [of_real_mul_im, sub_im, mul_I_im, of_real_re, _root_.abs_mul, abs_of_pos hd₀,
mul_le_mul_left hd₀] },
simpa only [of_real_mul_re, _root_.abs_mul, abs_of_pos hd₀, sub_re, mul_I_re, of_real_im,
zero_mul, neg_zero, sub_zero]
using abs_exp_mul_exp_add_exp_neg_le_of_abs_im_le ε₀.le hw hb'.le },
-- `abs (g ε w) ≤ 1` on the lines `w.im = a ± b` (actually, it holds everywhere in the strip)
have hg₁ : ∀ w, (im w = a - b ∨ im w = a + b) → abs (g ε w) ≤ 1,
{ refine λ w hw, (hδ $ hw.by_cases _ _).trans (real.exp_le_one_iff.2 _),
exacts [λ h, h.symm ▸ left_mem_Icc.2 hab.le, λ h, h.symm ▸ right_mem_Icc.2 hab.le,
mul_nonpos_of_nonpos_of_nonneg δ₀.le (real.exp_pos _).le] },
/- Our apriori estimate on `f` implies that `g ε w • f w → 0` as `|w.re| → ∞` along the strip. In
particular, its norm is less than or equal to `C` for sufficiently large `|w.re|`. -/
obtain ⟨R, hzR, hR⟩ : ∃ R : ℝ, |z.re| < R ∧ ∀ w, |re w| = R → im w ∈ Ioo (a - b) (a + b) →
‖g ε w • f w‖ ≤ C,
{ refine ((eventually_gt_at_top _).and _).exists,
rcases hO.exists_pos with ⟨A, hA₀, hA⟩,
simp only [is_O_with_iff, eventually_inf_principal, eventually_comap, mem_Ioo, ← abs_lt,
mem_preimage, (∘), real.norm_eq_abs, abs_of_pos (real.exp_pos _)] at hA,
suffices : tendsto (λ R, expR (δ * expR (d * R) + B * expR (c * R) + real.log A)) at_top (𝓝 0),
{ filter_upwards [this.eventually (ge_mem_nhds hC₀), hA] with R hR Hle w hre him,
calc ‖g ε w • f w‖ ≤ expR (δ * expR (d * R) + B * expR (c * R) + real.log A) : _
... ≤ C : hR,
rw [norm_smul, real.exp_add, ← hre, real.exp_add, real.exp_log hA₀, mul_assoc, mul_comm _ A],
exact mul_le_mul (hδ $ Ioo_subset_Icc_self him) (Hle _ hre him) (norm_nonneg _)
(real.exp_pos _).le },
refine real.tendsto_exp_at_bot.comp _,
suffices H : tendsto (λ R, δ + B * (expR ((d - c) * R))⁻¹) at_top (𝓝 (δ + B * 0)),
{ rw [mul_zero, add_zero] at H,
refine tendsto.at_bot_add _ tendsto_const_nhds,
simpa only [id, (∘), add_mul, mul_assoc, ← div_eq_inv_mul, ← real.exp_sub,
← sub_mul, sub_sub_cancel]
using H.neg_mul_at_top δ₀ (real.tendsto_exp_at_top.comp $
tendsto_const_nhds.mul_at_top hd₀ tendsto_id) },
refine tendsto_const_nhds.add (tendsto_const_nhds.mul _),
exact tendsto_inv_at_top_zero.comp (real.tendsto_exp_at_top.comp $
tendsto_const_nhds.mul_at_top (sub_pos.2 hcd) tendsto_id) },
have hR₀ : 0 < R, from (_root_.abs_nonneg _).trans_lt hzR,
/- Finally, we apply the bounded version of the maximum modulus principle to the rectangle
`(-R, R) × (a - b, a + b)`. The function is bounded by `C` on the horizontal sides by assumption
(and because `‖g ε w‖ ≤ 1`) and on the vertical sides by the choice of `R`. -/
have hgd : differentiable ℂ (g ε),
from ((((differentiable_id.sub_const _).const_mul _).cexp.add
((differentiable_id.sub_const _).const_mul _).neg.cexp).const_mul _).cexp,
replace hd : diff_cont_on_cl ℂ (λ w, g ε w • f w) (Ioo (-R) R ×ℂ Ioo (a - b) (a + b)),
from (hgd.diff_cont_on_cl.smul hfd).mono (inter_subset_right _ _),
convert norm_le_of_forall_mem_frontier_norm_le ((bounded_Ioo _ _).re_prod_im (bounded_Ioo _ _))
hd (λ w hw, _) _,
{ have hwc := frontier_subset_closure hw,
rw [frontier_re_prod_im, closure_Ioo (neg_lt_self hR₀).ne, frontier_Ioo hab,
closure_Ioo hab.ne, frontier_Ioo (neg_lt_self hR₀)] at hw,
by_cases him : w.im = a - b ∨ w.im = a + b,
{ rw [closure_re_prod_im, closure_Ioo (neg_lt_self hR₀).ne] at hwc,
rw [norm_smul, ← one_mul C],
exact mul_le_mul (hg₁ _ him) (him.by_cases (hle_a _) (hle_b _)) (norm_nonneg _) zero_le_one },
{ replace hw : w ∈ {-R, R} ×ℂ Icc (a - b) (a + b), from hw.resolve_left (λ h, him h.2),
have hw' := eq_endpoints_or_mem_Ioo_of_mem_Icc hw.2, rw ← or.assoc at hw',
exact hR _ ((abs_eq hR₀.le).2 hw.1.symm) (hw'.resolve_left him) } },
{ rw [closure_re_prod_im, closure_Ioo hab.ne, closure_Ioo (neg_lt_self hR₀).ne],
exact ⟨abs_le.1 hzR.le, ⟨hza.le, hzb.le⟩⟩ }
end
/-- **Phragmen-Lindelöf principle** in a strip `U = {z : ℂ | a < im z < b}`.
Let `f : ℂ → E` be a function such that
* `f` is differentiable on `U` and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * exp(c * |re z|))` on `U` for some `c < π / (b - a)`;
* `f z = 0` on the boundary of `U`.
Then `f` is equal to zero on the closed strip `{z : ℂ | a ≤ im z ≤ b}`.
-/
lemma eq_zero_on_horizontal_strip (hd : diff_cont_on_cl ℂ f (im ⁻¹' Ioo a b))
(hB : ∃ (c < π / (b - a)) B, f =O[comap (has_abs.abs ∘ re) at_top ⊓ 𝓟 (im ⁻¹' Ioo a b)]
(λ z, expR (B * expR (c * |z.re|))))
(ha : ∀ z : ℂ, z.im = a → f z = 0) (hb : ∀ z : ℂ, z.im = b → f z = 0) :
eq_on f 0 (im ⁻¹' Icc a b) :=
λ z hz, norm_le_zero_iff.1 $ horizontal_strip hd hB
(λ z hz, (ha z hz).symm ▸ norm_zero.le) (λ z hz, (hb z hz).symm ▸ norm_zero.le) hz.1 hz.2
/-- **Phragmen-Lindelöf principle** in a strip `U = {z : ℂ | a < im z < b}`.
Let `f g : ℂ → E` be functions such that
* `f` and `g` are differentiable on `U` and are continuous on its closure;
* `‖f z‖` and `‖g z‖` are bounded from above by `A * exp(B * exp(c * |re z|))` on `U` for some
`c < π / (b - a)`;
* `f z = g z` on the boundary of `U`.
Then `f` is equal to `g` on the closed strip `{z : ℂ | a ≤ im z ≤ b}`.
-/
lemma eq_on_horizontal_strip {g : ℂ → E} (hdf : diff_cont_on_cl ℂ f (im ⁻¹' Ioo a b))
(hBf : ∃ (c < π / (b - a)) B, f =O[comap (has_abs.abs ∘ re) at_top ⊓ 𝓟 (im ⁻¹' Ioo a b)]
(λ z, expR (B * expR (c * |z.re|))))
(hdg : diff_cont_on_cl ℂ g (im ⁻¹' Ioo a b))
(hBg : ∃ (c < π / (b - a)) B, g =O[comap (has_abs.abs ∘ re) at_top ⊓ 𝓟 (im ⁻¹' Ioo a b)]
(λ z, expR (B * expR (c * |z.re|))))
(ha : ∀ z : ℂ, z.im = a → f z = g z) (hb : ∀ z : ℂ, z.im = b → f z = g z) :
eq_on f g (im ⁻¹' Icc a b) :=
λ z hz, sub_eq_zero.1 (eq_zero_on_horizontal_strip (hdf.sub hdg) (is_O_sub_exp_exp hBf hBg)
(λ w hw, sub_eq_zero.2 (ha w hw)) (λ w hw, sub_eq_zero.2 (hb w hw)) hz)
/-!
### Phragmen-Lindelöf principle in a vertical strip
-/
/-- **Phragmen-Lindelöf principle** in a strip `U = {z : ℂ | a < re z < b}`.
Let `f : ℂ → E` be a function such that
* `f` is differentiable on `U` and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * exp(c * |im z|))` on `U` for some `c < π / (b - a)`;
* `‖f z‖` is bounded from above by a constant `C` on the boundary of `U`.
Then `‖f z‖` is bounded by the same constant on the closed strip
`{z : ℂ | a ≤ re z ≤ b}`. Moreover, it suffices to verify the second assumption
only for sufficiently large values of `|im z|`.
-/
lemma vertical_strip (hfd : diff_cont_on_cl ℂ f (re ⁻¹' Ioo a b))
(hB : ∃ (c < π / (b - a)) B, f =O[comap (has_abs.abs ∘ im) at_top ⊓ 𝓟 (re ⁻¹' Ioo a b)]
(λ z, expR (B * expR (c * |z.im|))))
(hle_a : ∀ z : ℂ, re z = a → ‖f z‖ ≤ C) (hle_b : ∀ z, re z = b → ‖f z‖ ≤ C)
(hza : a ≤ re z) (hzb : re z ≤ b) :
‖f z‖ ≤ C :=
begin
suffices : ‖(λ z, f (z * (-I))) (z * I)‖ ≤ C, by simpa [mul_assoc] using this,
have H : maps_to (λ z, z * (-I)) (im ⁻¹' Ioo a b) (re ⁻¹' Ioo a b),
{ intros z hz, simpa using hz },
refine horizontal_strip (hfd.comp (differentiable_id.mul_const _).diff_cont_on_cl H)
_ (λ z hz, hle_a _ _) (λ z hz, hle_b _ _) _ _,
{ refine Exists₃.imp (λ c hc B hO, _) hB,
have : tendsto (λ z, z * (-I)) (comap (has_abs.abs ∘ re) at_top ⊓ 𝓟 (im ⁻¹' Ioo a b))
(comap (has_abs.abs ∘ im) at_top ⊓ 𝓟 (re ⁻¹' Ioo a b)),
{ refine (tendsto_comap_iff.2 _).inf H.tendsto,
simpa [(∘)] using tendsto_comap },
simpa [(∘)] using hO.comp_tendsto this },
all_goals { simpa }
end
/-- **Phragmen-Lindelöf principle** in a strip `U = {z : ℂ | a < re z < b}`.
Let `f : ℂ → E` be a function such that
* `f` is differentiable on `U` and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * exp(c * |im z|))` on `U` for some `c < π / (b - a)`;
* `f z = 0` on the boundary of `U`.
Then `f` is equal to zero on the closed strip `{z : ℂ | a ≤ re z ≤ b}`.
-/
lemma eq_zero_on_vertical_strip (hd : diff_cont_on_cl ℂ f (re ⁻¹' Ioo a b))
(hB : ∃ (c < π / (b - a)) B, f =O[comap (has_abs.abs ∘ im) at_top ⊓ 𝓟 (re ⁻¹' Ioo a b)]
(λ z, expR (B * expR (c * |z.im|))))
(ha : ∀ z : ℂ, re z = a → f z = 0) (hb : ∀ z : ℂ, re z = b → f z = 0) :
eq_on f 0 (re ⁻¹' Icc a b) :=
λ z hz, norm_le_zero_iff.1 $ vertical_strip hd hB
(λ z hz, (ha z hz).symm ▸ norm_zero.le) (λ z hz, (hb z hz).symm ▸ norm_zero.le) hz.1 hz.2
/-- **Phragmen-Lindelöf principle** in a strip `U = {z : ℂ | a < re z < b}`.
Let `f g : ℂ → E` be functions such that
* `f` and `g` are differentiable on `U` and are continuous on its closure;
* `‖f z‖` and `‖g z‖` are bounded from above by `A * exp(B * exp(c * |im z|))` on `U` for some
`c < π / (b - a)`;
* `f z = g z` on the boundary of `U`.
Then `f` is equal to `g` on the closed strip `{z : ℂ | a ≤ re z ≤ b}`.
-/
lemma eq_on_vertical_strip {g : ℂ → E} (hdf : diff_cont_on_cl ℂ f (re ⁻¹' Ioo a b))
(hBf : ∃ (c < π / (b - a)) B, f =O[comap (has_abs.abs ∘ im) at_top ⊓ 𝓟 (re ⁻¹' Ioo a b)]
(λ z, expR (B * expR (c * |z.im|))))
(hdg : diff_cont_on_cl ℂ g (re ⁻¹' Ioo a b))
(hBg : ∃ (c < π / (b - a)) B, g =O[comap (has_abs.abs ∘ im) at_top ⊓ 𝓟 (re ⁻¹' Ioo a b)]
(λ z, expR (B * expR (c * |z.im|))))
(ha : ∀ z : ℂ, re z = a → f z = g z) (hb : ∀ z : ℂ, re z = b → f z = g z) :
eq_on f g (re ⁻¹' Icc a b) :=
λ z hz, sub_eq_zero.1 (eq_zero_on_vertical_strip (hdf.sub hdg) (is_O_sub_exp_exp hBf hBg)
(λ w hw, sub_eq_zero.2 (ha w hw)) (λ w hw, sub_eq_zero.2 (hb w hw)) hz)
/-!
### Phragmen-Lindelöf principle in coordinate quadrants
-/
/-- **Phragmen-Lindelöf principle** in the first quadrant. Let `f : ℂ → E` be a function such that
* `f` is differentiable in the open first quadrant and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * (abs z) ^ c)` on the open first quadrant
for some `c < 2`;
* `‖f z‖` is bounded from above by a constant `C` on the boundary of the first quadrant.
Then `‖f z‖` is bounded from above by the same constant on the closed first quadrant. -/
lemma quadrant_I (hd : diff_cont_on_cl ℂ f (Ioi 0 ×ℂ Ioi 0))
(hB : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 (Ioi 0 ×ℂ Ioi 0)]
(λ z, expR (B * (abs z) ^ c)))
(hre : ∀ x : ℝ, 0 ≤ x → ‖f x‖ ≤ C) (him : ∀ x : ℝ, 0 ≤ x → ‖f (x * I)‖ ≤ C)
(hz_re : 0 ≤ z.re) (hz_im : 0 ≤ z.im) :
‖f z‖ ≤ C :=
begin
-- The case `z = 0` is trivial.
rcases eq_or_ne z 0 with rfl|hzne, { exact hre 0 le_rfl },
-- Otherwise, `z = e ^ ζ` for some `ζ : ℂ`, `0 < Im ζ < π / 2`.
obtain ⟨ζ, hζ, rfl⟩ : ∃ ζ : ℂ, ζ.im ∈ Icc 0 (π / 2) ∧ exp ζ = z,
{ refine ⟨log z, _, exp_log hzne⟩,
rw log_im,
exact ⟨arg_nonneg_iff.2 hz_im, arg_le_pi_div_two_iff.2 (or.inl hz_re)⟩ },
clear hz_re hz_im hzne,
-- We are going to apply `phragmen_lindelof.horizontal_strip` to `f ∘ complex.exp` and `ζ`.
change ‖(f ∘ exp) ζ‖ ≤ C,
have H : maps_to exp (im ⁻¹' Ioo 0 (π / 2)) (Ioi 0 ×ℂ Ioi 0),
{ intros z hz,
rw [mem_re_prod_im, exp_re, exp_im, mem_Ioi, mem_Ioi],
refine ⟨mul_pos (real.exp_pos _)
(real.cos_pos_of_mem_Ioo ⟨(neg_lt_zero.2 $ div_pos real.pi_pos two_pos).trans hz.1, hz.2⟩),
mul_pos (real.exp_pos _)
(real.sin_pos_of_mem_Ioo ⟨hz.1, hz.2.trans (half_lt_self real.pi_pos)⟩)⟩ },
refine horizontal_strip (hd.comp differentiable_exp.diff_cont_on_cl H) _ _ _ hζ.1 hζ.2;
clear hζ ζ,
{ -- The estimate `hB` on `f` implies the required estimate on
-- `f ∘ exp` with the same `c` and `B' = max B 0`.
rw [sub_zero, div_div_cancel' real.pi_pos.ne'],
rcases hB with ⟨c, hc, B, hO⟩,
refine ⟨c, hc, max B 0, _⟩,
rw [← comap_comap, comap_abs_at_top, comap_sup, inf_sup_right],
-- We prove separately the estimates as `ζ.re → ∞` and as `ζ.re → -∞`
refine is_O.sup _ ((hO.comp_tendsto $ tendsto_exp_comap_re_at_top.inf H.tendsto).trans $
is_O.of_bound 1 _),
{ -- For the estimate as `ζ.re → -∞`, note that `f` is continuous within the first quadrant at
-- zero, hence `f (exp ζ)` has a limit as `ζ.re → -∞`, `0 < ζ.im < π / 2`.
have hc : continuous_within_at f (Ioi 0 ×ℂ Ioi 0) 0,
{ refine (hd.continuous_on _ _).mono subset_closure,
simp [closure_re_prod_im, mem_re_prod_im] },
refine ((hc.tendsto.comp $ tendsto_exp_comap_re_at_bot.inf
H.tendsto).is_O_one ℝ).trans (is_O_of_le _ (λ w, _)),
rw [norm_one, real.norm_of_nonneg (real.exp_pos _).le, real.one_le_exp_iff],
exact mul_nonneg (le_max_right _ _) (real.exp_pos _).le },
{ -- For the estimate as `ζ.re → ∞`, we reuse the uppoer estimate on `f`
simp only [eventually_inf_principal, eventually_comap, comp_app, one_mul,
real.norm_of_nonneg (real.exp_pos _).le, abs_exp, ← real.exp_mul, real.exp_le_exp],
refine (eventually_ge_at_top 0).mono (λ x hx z hz hz', _),
rw [hz, _root_.abs_of_nonneg hx, mul_comm _ c],
exact mul_le_mul_of_nonneg_right (le_max_left _ _) (real.exp_pos _).le } },
{ -- If `ζ.im = 0`, then `complex.exp ζ` is a positive real number
intros ζ hζ, lift ζ to ℝ using hζ,
rw [comp_app, ← of_real_exp],
exact hre _ (real.exp_pos _).le },
{ -- If `ζ.im = π / 2`, then `complex.exp ζ` is a purely imaginary number with positive `im`
intros ζ hζ,
rw [← re_add_im ζ, hζ, comp_app, exp_add_mul_I, ← of_real_cos, ← of_real_sin,
real.cos_pi_div_two, real.sin_pi_div_two, of_real_zero, of_real_one, one_mul, zero_add,
← of_real_exp],
exact him _ (real.exp_pos _).le }
end
/-- **Phragmen-Lindelöf principle** in the first quadrant. Let `f : ℂ → E` be a function such that
* `f` is differentiable in the open first quadrant and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * (abs z) ^ c)` on the open first quadrant
for some `A`, `B`, and `c < 2`;
* `f` is equal to zero on the boundary of the first quadrant.
Then `f` is equal to zero on the closed first quadrant. -/
lemma eq_zero_on_quadrant_I (hd : diff_cont_on_cl ℂ f (Ioi 0 ×ℂ Ioi 0))
(hB : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 (Ioi 0 ×ℂ Ioi 0)]
(λ z, expR (B * (abs z) ^ c)))
(hre : ∀ x : ℝ, 0 ≤ x → f x = 0) (him : ∀ x : ℝ, 0 ≤ x → f (x * I) = 0) :
eq_on f 0 {z | 0 ≤ z.re ∧ 0 ≤ z.im} :=
λ z hz, norm_le_zero_iff.1 $ quadrant_I hd hB (λ x hx, norm_le_zero_iff.2 $ hre x hx)
(λ x hx, norm_le_zero_iff.2 $ him x hx) hz.1 hz.2
/-- **Phragmen-Lindelöf principle** in the first quadrant. Let `f g : ℂ → E` be functions such that
* `f` and `g` are differentiable in the open first quadrant and are continuous on its closure;
* `‖f z‖` and `‖g z‖` are bounded from above by `A * exp(B * (abs z) ^ c)` on the open first
quadrant for some `A`, `B`, and `c < 2`;
* `f` is equal to `g` on the boundary of the first quadrant.
Then `f` is equal to `g` on the closed first quadrant. -/
lemma eq_on_quadrant_I (hdf : diff_cont_on_cl ℂ f (Ioi 0 ×ℂ Ioi 0))
(hBf : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 (Ioi 0 ×ℂ Ioi 0)]
(λ z, expR (B * (abs z) ^ c)))
(hdg : diff_cont_on_cl ℂ g (Ioi 0 ×ℂ Ioi 0))
(hBg : ∃ (c < (2 : ℝ)) B, g =O[comap complex.abs at_top ⊓ 𝓟 (Ioi 0 ×ℂ Ioi 0)]
(λ z, expR (B * (abs z) ^ c)))
(hre : ∀ x : ℝ, 0 ≤ x → f x = g x) (him : ∀ x : ℝ, 0 ≤ x → f (x * I) = g (x * I)) :
eq_on f g {z | 0 ≤ z.re ∧ 0 ≤ z.im} :=
λ z hz, sub_eq_zero.1 $ eq_zero_on_quadrant_I (hdf.sub hdg) (is_O_sub_exp_rpow hBf hBg)
(λ x hx, sub_eq_zero.2 $ hre x hx) (λ x hx, sub_eq_zero.2 $ him x hx) hz
/-- **Phragmen-Lindelöf principle** in the second quadrant. Let `f : ℂ → E` be a function such that
* `f` is differentiable in the open second quadrant and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * (abs z) ^ c)` on the open second quadrant
for some `c < 2`;
* `‖f z‖` is bounded from above by a constant `C` on the boundary of the second quadrant.
Then `‖f z‖` is bounded from above by the same constant on the closed second quadrant. -/
lemma quadrant_II (hd : diff_cont_on_cl ℂ f (Iio 0 ×ℂ Ioi 0))
(hB : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 (Iio 0 ×ℂ Ioi 0)]
(λ z, expR (B * (abs z) ^ c)))
(hre : ∀ x : ℝ, x ≤ 0 → ‖f x‖ ≤ C) (him : ∀ x : ℝ, 0 ≤ x → ‖f (x * I)‖ ≤ C)
(hz_re : z.re ≤ 0) (hz_im : 0 ≤ z.im) :
‖f z‖ ≤ C :=
begin
obtain ⟨z, rfl⟩ : ∃ z', z' * I = z, from ⟨z / I, div_mul_cancel _ I_ne_zero⟩,
simp only [mul_I_re, mul_I_im, neg_nonpos] at hz_re hz_im,
change ‖(f ∘ (* I)) z‖ ≤ C,
have H : maps_to (* I) (Ioi 0 ×ℂ Ioi 0) (Iio 0 ×ℂ Ioi 0),
{ intros w hw,
simpa only [mem_re_prod_im, mul_I_re, mul_I_im, neg_lt_zero, mem_Iio] using hw.symm },
refine quadrant_I (hd.comp (differentiable_id.mul_const _).diff_cont_on_cl H)
(Exists₃.imp (λ c hc B hO, _) hB) him (λ x hx, _) hz_im hz_re,
{ simpa only [(∘), map_mul, abs_I, mul_one]
using hO.comp_tendsto ((tendsto_mul_right_cobounded I_ne_zero).inf H.tendsto) },
{ rw [comp_app, mul_assoc, I_mul_I, mul_neg_one, ← of_real_neg],
exact hre _ (neg_nonpos.2 hx) }
end
/-- **Phragmen-Lindelöf principle** in the second quadrant. Let `f : ℂ → E` be a function such that
* `f` is differentiable in the open second quadrant and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * (abs z) ^ c)` on the open second quadrant
for some `A`, `B`, and `c < 2`;
* `f` is equal to zero on the boundary of the second quadrant.
Then `f` is equal to zero on the closed second quadrant. -/
lemma eq_zero_on_quadrant_II (hd : diff_cont_on_cl ℂ f (Iio 0 ×ℂ Ioi 0))
(hB : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 (Iio 0 ×ℂ Ioi 0)]
(λ z, expR (B * (abs z) ^ c)))
(hre : ∀ x : ℝ, x ≤ 0 → f x = 0) (him : ∀ x : ℝ, 0 ≤ x → f (x * I) = 0) :
eq_on f 0 {z | z.re ≤ 0 ∧ 0 ≤ z.im} :=
λ z hz, norm_le_zero_iff.1 $ quadrant_II hd hB (λ x hx, norm_le_zero_iff.2 $ hre x hx)
(λ x hx, norm_le_zero_iff.2 $ him x hx) hz.1 hz.2
/-- **Phragmen-Lindelöf principle** in the second quadrant. Let `f g : ℂ → E` be functions such that
* `f` and `g` are differentiable in the open second quadrant and are continuous on its closure;
* `‖f z‖` and `‖g z‖` are bounded from above by `A * exp(B * (abs z) ^ c)` on the open second
quadrant for some `A`, `B`, and `c < 2`;
* `f` is equal to `g` on the boundary of the second quadrant.
Then `f` is equal to `g` on the closed second quadrant. -/
lemma eq_on_quadrant_II (hdf : diff_cont_on_cl ℂ f (Iio 0 ×ℂ Ioi 0))
(hBf : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 (Iio 0 ×ℂ Ioi 0)]
(λ z, expR (B * (abs z) ^ c)))
(hdg : diff_cont_on_cl ℂ g (Iio 0 ×ℂ Ioi 0))
(hBg : ∃ (c < (2 : ℝ)) B, g =O[comap complex.abs at_top ⊓ 𝓟 (Iio 0 ×ℂ Ioi 0)]
(λ z, expR (B * (abs z) ^ c)))
(hre : ∀ x : ℝ, x ≤ 0 → f x = g x) (him : ∀ x : ℝ, 0 ≤ x → f (x * I) = g (x * I)) :
eq_on f g {z | z.re ≤ 0 ∧ 0 ≤ z.im} :=
λ z hz, sub_eq_zero.1 $ eq_zero_on_quadrant_II (hdf.sub hdg) (is_O_sub_exp_rpow hBf hBg)
(λ x hx, sub_eq_zero.2 $ hre x hx) (λ x hx, sub_eq_zero.2 $ him x hx) hz
/-- **Phragmen-Lindelöf principle** in the third quadrant. Let `f : ℂ → E` be a function such that
* `f` is differentiable in the open third quadrant and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp (B * (abs z) ^ c)` on the open third quadrant
for some `c < 2`;
* `‖f z‖` is bounded from above by a constant `C` on the boundary of the third quadrant.
Then `‖f z‖` is bounded from above by the same constant on the closed third quadrant. -/
lemma quadrant_III (hd : diff_cont_on_cl ℂ f (Iio 0 ×ℂ Iio 0))
(hB : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 (Iio 0 ×ℂ Iio 0)]
(λ z, expR (B * (abs z) ^ c)))
(hre : ∀ x : ℝ, x ≤ 0 → ‖f x‖ ≤ C) (him : ∀ x : ℝ, x ≤ 0 → ‖f (x * I)‖ ≤ C)
(hz_re : z.re ≤ 0) (hz_im : z.im ≤ 0) :
‖f z‖ ≤ C :=
begin
obtain ⟨z, rfl⟩ : ∃ z', -z' = z, from ⟨-z, neg_neg z⟩,
simp only [neg_re, neg_im, neg_nonpos] at hz_re hz_im,
change ‖(f ∘ has_neg.neg) z‖ ≤ C,
have H : maps_to has_neg.neg (Ioi 0 ×ℂ Ioi 0) (Iio 0 ×ℂ Iio 0),
{ intros w hw,
simpa only [mem_re_prod_im, neg_re, neg_im, neg_lt_zero, mem_Iio] using hw },
refine quadrant_I (hd.comp differentiable_neg.diff_cont_on_cl H) _ (λ x hx, _) (λ x hx, _)
hz_re hz_im,
{ refine Exists₃.imp (λ c hc B hO, _) hB,
simpa only [(∘), complex.abs.map_neg]
using hO.comp_tendsto (tendsto_neg_cobounded.inf H.tendsto) },
{ rw [comp_app, ← of_real_neg],
exact hre (-x) (neg_nonpos.2 hx) },
{ rw [comp_app, ← neg_mul, ← of_real_neg],
exact him (-x) (neg_nonpos.2 hx) }
end
/-- **Phragmen-Lindelöf principle** in the third quadrant. Let `f : ℂ → E` be a function such that
* `f` is differentiable in the open third quadrant and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * (abs z) ^ c)` on the open third quadrant
for some `A`, `B`, and `c < 2`;
* `f` is equal to zero on the boundary of the third quadrant.
Then `f` is equal to zero on the closed third quadrant. -/
lemma eq_zero_on_quadrant_III (hd : diff_cont_on_cl ℂ f (Iio 0 ×ℂ Iio 0))
(hB : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 (Iio 0 ×ℂ Iio 0)]
(λ z, expR (B * (abs z) ^ c)))
(hre : ∀ x : ℝ, x ≤ 0 → f x = 0) (him : ∀ x : ℝ, x ≤ 0 → f (x * I) = 0) :
eq_on f 0 {z | z.re ≤ 0 ∧ z.im ≤ 0} :=
λ z hz, norm_le_zero_iff.1 $ quadrant_III hd hB (λ x hx, norm_le_zero_iff.2 $ hre x hx)
(λ x hx, norm_le_zero_iff.2 $ him x hx) hz.1 hz.2
/-- **Phragmen-Lindelöf principle** in the third quadrant. Let `f g : ℂ → E` be functions such that
* `f` and `g` are differentiable in the open third quadrant and are continuous on its closure;
* `‖f z‖` and `‖g z‖` are bounded from above by `A * exp(B * (abs z) ^ c)` on the open third
quadrant for some `A`, `B`, and `c < 2`;
* `f` is equal to `g` on the boundary of the third quadrant.
Then `f` is equal to `g` on the closed third quadrant. -/
lemma eq_on_quadrant_III (hdf : diff_cont_on_cl ℂ f (Iio 0 ×ℂ Iio 0))
(hBf : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 (Iio 0 ×ℂ Iio 0)]
(λ z, expR (B * (abs z) ^ c)))
(hdg : diff_cont_on_cl ℂ g (Iio 0 ×ℂ Iio 0))
(hBg : ∃ (c < (2 : ℝ)) B, g =O[comap complex.abs at_top ⊓ 𝓟 (Iio 0 ×ℂ Iio 0)]
(λ z, expR (B * (abs z) ^ c)))
(hre : ∀ x : ℝ, x ≤ 0 → f x = g x) (him : ∀ x : ℝ, x ≤ 0 → f (x * I) = g (x * I)) :
eq_on f g {z | z.re ≤ 0 ∧ z.im ≤ 0} :=
λ z hz, sub_eq_zero.1 $ eq_zero_on_quadrant_III (hdf.sub hdg) (is_O_sub_exp_rpow hBf hBg)
(λ x hx, sub_eq_zero.2 $ hre x hx) (λ x hx, sub_eq_zero.2 $ him x hx) hz
/-- **Phragmen-Lindelöf principle** in the fourth quadrant. Let `f : ℂ → E` be a function such that
* `f` is differentiable in the open fourth quadrant and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * (abs z) ^ c)` on the open fourth quadrant
for some `c < 2`;
* `‖f z‖` is bounded from above by a constant `C` on the boundary of the fourth quadrant.
Then `‖f z‖` is bounded from above by the same constant on the closed fourth quadrant. -/
lemma quadrant_IV (hd : diff_cont_on_cl ℂ f (Ioi 0 ×ℂ Iio 0))
(hB : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 (Ioi 0 ×ℂ Iio 0)]
(λ z, expR (B * (abs z) ^ c)))
(hre : ∀ x : ℝ, 0 ≤ x → ‖f x‖ ≤ C) (him : ∀ x : ℝ, x ≤ 0 → ‖f (x * I)‖ ≤ C)
(hz_re : 0 ≤ z.re) (hz_im : z.im ≤ 0) :
‖f z‖ ≤ C :=
begin
obtain ⟨z, rfl⟩ : ∃ z', -z' = z, from ⟨-z, neg_neg z⟩,
simp only [neg_re, neg_im, neg_nonpos, neg_nonneg] at hz_re hz_im,
change ‖(f ∘ has_neg.neg) z‖ ≤ C,
have H : maps_to has_neg.neg (Iio 0 ×ℂ Ioi 0) (Ioi 0 ×ℂ Iio 0),
{ intros w hw,
simpa only [mem_re_prod_im, neg_re, neg_im, neg_lt_zero, neg_pos, mem_Ioi, mem_Iio] using hw },
refine quadrant_II (hd.comp differentiable_neg.diff_cont_on_cl H) _ (λ x hx, _) (λ x hx, _)
hz_re hz_im,
{ refine Exists₃.imp (λ c hc B hO, _) hB,
simpa only [(∘), complex.abs.map_neg]
using hO.comp_tendsto (tendsto_neg_cobounded.inf H.tendsto) },
{ rw [comp_app, ← of_real_neg],
exact hre (-x) (neg_nonneg.2 hx) },
{ rw [comp_app, ← neg_mul, ← of_real_neg],
exact him (-x) (neg_nonpos.2 hx) }
end
/-- **Phragmen-Lindelöf principle** in the fourth quadrant. Let `f : ℂ → E` be a function such that
* `f` is differentiable in the open fourth quadrant and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * (abs z) ^ c)` on the open fourth quadrant
for some `A`, `B`, and `c < 2`;
* `f` is equal to zero on the boundary of the fourth quadrant.
Then `f` is equal to zero on the closed fourth quadrant. -/
lemma eq_zero_on_quadrant_IV (hd : diff_cont_on_cl ℂ f (Ioi 0 ×ℂ Iio 0))
(hB : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 (Ioi 0 ×ℂ Iio 0)]
(λ z, expR (B * (abs z) ^ c)))
(hre : ∀ x : ℝ, 0 ≤ x → f x = 0) (him : ∀ x : ℝ, x ≤ 0 → f (x * I) = 0) :
eq_on f 0 {z | 0 ≤ z.re ∧ z.im ≤ 0} :=
λ z hz, norm_le_zero_iff.1 $ quadrant_IV hd hB (λ x hx, norm_le_zero_iff.2 $ hre x hx)
(λ x hx, norm_le_zero_iff.2 $ him x hx) hz.1 hz.2
/-- **Phragmen-Lindelöf principle** in the fourth quadrant. Let `f g : ℂ → E` be functions such that
* `f` and `g` are differentiable in the open fourth quadrant and are continuous on its closure;
* `‖f z‖` and `‖g z‖` are bounded from above by `A * exp(B * (abs z) ^ c)` on the open fourth
quadrant for some `A`, `B`, and `c < 2`;
* `f` is equal to `g` on the boundary of the fourth quadrant.
Then `f` is equal to `g` on the closed fourth quadrant. -/
lemma eq_on_quadrant_IV (hdf : diff_cont_on_cl ℂ f (Ioi 0 ×ℂ Iio 0))
(hBf : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 (Ioi 0 ×ℂ Iio 0)]
(λ z, expR (B * (abs z) ^ c)))
(hdg : diff_cont_on_cl ℂ g (Ioi 0 ×ℂ Iio 0))
(hBg : ∃ (c < (2 : ℝ)) B, g =O[comap complex.abs at_top ⊓ 𝓟 (Ioi 0 ×ℂ Iio 0)]
(λ z, expR (B * (abs z) ^ c)))
(hre : ∀ x : ℝ, 0 ≤ x → f x = g x) (him : ∀ x : ℝ, x ≤ 0 → f (x * I) = g (x * I)) :
eq_on f g {z | 0 ≤ z.re ∧ z.im ≤ 0} :=
λ z hz, sub_eq_zero.1 $ eq_zero_on_quadrant_IV (hdf.sub hdg) (is_O_sub_exp_rpow hBf hBg)
(λ x hx, sub_eq_zero.2 $ hre x hx) (λ x hx, sub_eq_zero.2 $ him x hx) hz
/-!
### Phragmen-Lindelöf principle in the right half-plane
-/
/-- **Phragmen-Lindelöf principle** in the right half-plane. Let `f : ℂ → E` be a function such that
* `f` is differentiable in the open right half-plane and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * (abs z) ^ c)` on the open right half-plane
for some `c < 2`;
* `‖f z‖` is bounded from above by a constant `C` on the imaginary axis;
* `f x → 0` as `x : ℝ` tends to infinity.
Then `‖f z‖` is bounded from above by the same constant on the closed right half-plane.
See also `phragmen_lindelof.right_half_plane_of_bounded_on_real` for a stronger version. -/
lemma right_half_plane_of_tendsto_zero_on_real (hd : diff_cont_on_cl ℂ f {z | 0 < z.re})
(hexp : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 {z | 0 < z.re}]
(λ z, expR (B * (abs z) ^ c)))
(hre : tendsto (λ x : ℝ, f x) at_top (𝓝 0)) (him : ∀ x : ℝ, ‖f (x * I)‖ ≤ C) (hz : 0 ≤ z.re) :
‖f z‖ ≤ C :=
begin
/- We are going to apply the Phragmen-Lindelöf principle in the first and fourth quadrants.
The lemmas immediately imply that for any upper estimate `C'` on `‖f x‖`, `x : ℝ`, `0 ≤ x`,
the number `max C C'` is an upper estimate on `f` in the whole right half-plane. -/
revert z,
have hle : ∀ C', (∀ x : ℝ, 0 ≤ x → ‖f x‖ ≤ C') → ∀ z : ℂ, 0 ≤ z.re → ‖f z‖ ≤ max C C',
{ intros C' hC' z hz,
cases le_total z.im 0,
{ refine quadrant_IV (hd.mono $ λ _, and.left) (Exists₃.imp (λ c hc B hO, _) hexp)
(λ x hx, (hC' x hx).trans $ le_max_right _ _) (λ x hx, (him x).trans (le_max_left _ _))
hz h,
exact hO.mono (inf_le_inf_left _ $ principal_mono.2 $ λ _, and.left) },
{ refine quadrant_I (hd.mono $ λ _, and.left) (Exists₃.imp (λ c hc B hO, _) hexp)
(λ x hx, (hC' x hx).trans $ le_max_right _ _) (λ x hx, (him x).trans (le_max_left _ _))
hz h,
exact hO.mono (inf_le_inf_left _ $ principal_mono.2 $ λ _, and.left) } },
-- Since `f` is continuous on `Ici 0` and `‖f x‖` tends to zero as `x → ∞`,
-- the norm `‖f x‖` takes its maximum value at some `x₀ : ℝ`.
obtain ⟨x₀, hx₀, hmax⟩ : ∃ x : ℝ, 0 ≤ x ∧ ∀ y : ℝ, 0 ≤ y → ‖f y‖ ≤ ‖f x‖,
{ have hfc : continuous_on (λ x : ℝ, f x) (Ici 0),
{ refine hd.continuous_on.comp continuous_of_real.continuous_on (λ x hx, _),
rwa closure_set_of_lt_re },
by_cases h₀ : ∀ x : ℝ, 0 ≤ x → f x = 0,
{ refine ⟨0, le_rfl, λ y hy, _⟩, rw [h₀ y hy, h₀ 0 le_rfl] },
push_neg at h₀,
rcases h₀ with ⟨x₀, hx₀, hne⟩,
have hlt : ‖(0 : E)‖ < ‖f x₀‖, by rwa [norm_zero, norm_pos_iff],
suffices : ∀ᶠ x : ℝ in cocompact ℝ ⊓ 𝓟 (Ici 0), ‖f x‖ ≤ ‖f x₀‖,
by simpa only [exists_prop] using hfc.norm.exists_forall_ge' is_closed_Ici hx₀ this,
rw [real.cocompact_eq, inf_sup_right, (disjoint_at_bot_principal_Ici (0 : ℝ)).eq_bot,
bot_sup_eq],
exact (hre.norm.eventually $ ge_mem_nhds hlt).filter_mono inf_le_left },
cases le_or_lt (‖f x₀‖) C,
{ -- If `‖f x₀‖ ≤ C`, then `hle` implies the required estimate
simpa only [max_eq_left h] using hle _ hmax },
{ -- Otherwise, `‖f z‖ ≤ ‖f x₀‖` for all `z` in the right half-plane due to `hle`.
replace hmax : is_max_on (norm ∘ f) {z | 0 < z.re} x₀,
{ rintros z (hz : 0 < z.re),
simpa [max_eq_right h.le] using hle _ hmax _ hz.le },
-- Due to the maximum modulus principle applied to the closed ball of radius `x₀.re`,
-- `‖f 0‖ = ‖f x₀‖`.
have : ‖f 0‖ = ‖f x₀‖,
{ apply norm_eq_norm_of_is_max_on_of_ball_subset hd hmax,
-- move to a lemma?
intros z hz,
rw [mem_ball, dist_zero_left, dist_eq, norm_eq_abs, complex.abs_of_nonneg hx₀] at hz,
rw mem_set_of_eq,
contrapose! hz,
calc x₀ ≤ x₀ - z.re : (le_sub_self_iff _).2 hz
... ≤ |x₀ - z.re| : le_abs_self _
... = |(z - x₀).re| : by rw [sub_re, of_real_re, _root_.abs_sub_comm]
... ≤ abs (z - x₀) : abs_re_le_abs _ },
-- Thus we have `C < ‖f x₀‖ = ‖f 0‖ ≤ C`. Contradiction completes the proof.
refine (h.not_le $ this ▸ _).elim,
simpa using him 0 }
end
/-- **Phragmen-Lindelöf principle** in the right half-plane. Let `f : ℂ → E` be a function such that
* `f` is differentiable in the open right half-plane and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * (abs z) ^ c)` on the open right half-plane
for some `c < 2`;
* `‖f z‖` is bounded from above by a constant `C` on the imaginary axis;
* `‖f x‖` is bounded from above by a constant for large real values of `x`.
Then `‖f z‖` is bounded from above by `C` on the closed right half-plane.
See also `phragmen_lindelof.right_half_plane_of_tendsto_zero_on_real` for a weaker version. -/
lemma right_half_plane_of_bounded_on_real (hd : diff_cont_on_cl ℂ f {z | 0 < z.re})
(hexp : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 {z | 0 < z.re}]
(λ z, expR (B * (abs z) ^ c)))
(hre : is_bounded_under (≤) at_top (λ x : ℝ, ‖f x‖))
(him : ∀ x : ℝ, ‖f (x * I)‖ ≤ C) (hz : 0 ≤ z.re) :
‖f z‖ ≤ C :=
begin
-- For each `ε < 0`, the function `λ z, exp (ε * z) • f z` satisfies assumptions of
-- `right_half_plane_of_tendsto_zero_on_real`, hence `‖exp (ε * z) • f z‖ ≤ C` for all `ε < 0`.
-- Taking the limit as `ε → 0`, we obtain the required inequality.
suffices : ∀ᶠ ε : ℝ in 𝓝[<] 0, ‖exp (ε * z) • f z‖ ≤ C,
{ refine le_of_tendsto (tendsto.mono_left _ nhds_within_le_nhds) this,
apply ((continuous_of_real.mul continuous_const).cexp.smul continuous_const).norm.tendsto',
simp, apply_instance },
filter_upwards [self_mem_nhds_within] with ε ε₀, change ε < 0 at ε₀,
set g : ℂ → E := λ z, exp (ε * z) • f z, change ‖g z‖ ≤ C,
replace hd : diff_cont_on_cl ℂ g {z : ℂ | 0 < z.re},
from (differentiable_id.const_mul _).cexp.diff_cont_on_cl.smul hd,
have hgn : ∀ z, ‖g z‖ = expR (ε * z.re) * ‖f z‖,
{ intro z, rw [norm_smul, norm_eq_abs, abs_exp, of_real_mul_re] },
refine right_half_plane_of_tendsto_zero_on_real hd _ _ (λ y, _) hz,
{ refine Exists₃.imp (λ c hc B hO, (is_O.of_bound 1 _).trans hO) hexp,
refine (eventually_inf_principal.2 $ eventually_of_forall $ λ z hz, _),
rw [hgn, one_mul],
refine mul_le_of_le_one_left (norm_nonneg _) (real.exp_le_one_iff.2 _),
exact mul_nonpos_of_nonpos_of_nonneg ε₀.le (le_of_lt hz) },
{ simp_rw [g, ← of_real_mul, ← of_real_exp, coe_smul],
have h₀ : tendsto (λ x : ℝ, expR (ε * x)) at_top (𝓝 0),
from real.tendsto_exp_at_bot.comp (tendsto_const_nhds.neg_mul_at_top ε₀ tendsto_id),
exact h₀.zero_smul_is_bounded_under_le hre },
{ rw [hgn, of_real_mul_re, I_re, mul_zero, mul_zero, real.exp_zero, one_mul],
exact him y }
end
/-- **Phragmen-Lindelöf principle** in the right half-plane. Let `f : ℂ → E` be a function such that
* `f` is differentiable in the open right half-plane and is continuous on its closure;
* `‖f z‖` is bounded from above by `A * exp(B * (abs z) ^ c)` on the open right half-plane
for some `c < 2`;
* `‖f z‖` is bounded from above by a constant on the imaginary axis;
* `f x`, `x : ℝ`, tends to zero superexponentially fast as `x → ∞`:
for any natural `n`, `exp (n * x) * ‖f x‖` tends to zero as `x → ∞`.
Then `f` is equal to zero on the closed right half-plane. -/
lemma eq_zero_on_right_half_plane_of_superexponential_decay
(hd : diff_cont_on_cl ℂ f {z | 0 < z.re})
(hexp : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 {z | 0 < z.re}]
(λ z, expR (B * (abs z) ^ c)))
(hre : superpolynomial_decay at_top expR (λ x, ‖f x‖))
(him : ∃ C, ∀ x : ℝ, ‖f (x * I)‖ ≤ C) :
eq_on f 0 {z : ℂ | 0 ≤ z.re} :=
begin
rcases him with ⟨C, hC⟩,
-- Due to continuity, it suffices to prove the equality on the open right half-plane.
suffices : ∀ z : ℂ, 0 < z.re → f z = 0,
{ simpa only [closure_set_of_lt_re] using eq_on.of_subset_closure this hd.continuous_on
continuous_on_const subset_closure subset.rfl },
-- Consider $g_n(z)=e^{nz}f(z)$.
set g : ℕ → ℂ → E := λ n z, (exp z) ^ n • f z,
have hg : ∀ n z, ‖g n z‖ = (expR z.re) ^ n * ‖f z‖,
{ intros n z, simp only [norm_smul, norm_eq_abs, complex.abs_pow, abs_exp] },
intros z hz,
-- Since `e^{nz} → ∞` as `n → ∞`, it suffices to show that each `g_n` is bounded from above by `C`
suffices H : ∀ n : ℕ, ‖g n z‖ ≤ C,
{ contrapose! H,
simp only [hg],
exact (((tendsto_pow_at_top_at_top_of_one_lt (real.one_lt_exp_iff.2 hz)).at_top_mul
(norm_pos_iff.2 H) tendsto_const_nhds).eventually (eventually_gt_at_top C)).exists },
intro n,
-- This estimate follows from the Phragmen-Lindelöf principle in the right half-plane.
refine right_half_plane_of_tendsto_zero_on_real
((differentiable_exp.pow n).diff_cont_on_cl.smul hd) _ _ (λ y, _) hz.le,
{ rcases hexp with ⟨c, hc, B, hO⟩,
refine ⟨max c 1, max_lt hc one_lt_two, n + max B 0, is_O.of_norm_left _⟩,
simp only [hg],
refine ((is_O_refl (λ z : ℂ, expR z.re ^ n) _).mul hO.norm_left).trans (is_O.of_bound 1 _),
simp only [← real.exp_nat_mul, ← real.exp_add, real.norm_of_nonneg (real.exp_pos _).le,
real.exp_le_exp, add_mul, eventually_inf_principal, eventually_comap, one_mul],
filter_upwards [eventually_ge_at_top (1 : ℝ)] with r hr z hzr hre, subst r,
refine add_le_add (mul_le_mul_of_nonneg_left _ n.cast_nonneg) _,
{ calc z.re ≤ abs z : re_le_abs _
... = abs z ^ (1 : ℝ) : (real.rpow_one _).symm
... ≤ abs z ^ (max c 1) : real.rpow_le_rpow_of_exponent_le hr (le_max_right _ _) },
{ exact mul_le_mul (le_max_left _ _) (real.rpow_le_rpow_of_exponent_le hr (le_max_left _ _))
(real.rpow_nonneg_of_nonneg (complex.abs.nonneg _) _) (le_max_right _ _) } },
{ rw tendsto_zero_iff_norm_tendsto_zero, simp only [hg],
exact hre n },
{ rw [hg, of_real_mul_re, I_re, mul_zero, real.exp_zero, one_pow, one_mul],
exact hC y }
end
/-- **Phragmen-Lindelöf principle** in the right half-plane. Let `f g : ℂ → E` be functions such
that
* `f` and `g` are differentiable in the open right half-plane and are continuous on its closure;
* `‖f z‖` and `‖g z‖` are bounded from above by `A * exp(B * (abs z) ^ c)` on the open right
half-plane for some `c < 2`;
* `‖f z‖` and `‖g z‖` are bounded from above by constants on the imaginary axis;
* `f x - g x`, `x : ℝ`, tends to zero superexponentially fast as `x → ∞`:
for any natural `n`, `exp (n * x) * ‖f x - g x‖` tends to zero as `x → ∞`.
Then `f` is equal to `g` on the closed right half-plane. -/
lemma eq_on_right_half_plane_of_superexponential_decay {g : ℂ → E}
(hfd : diff_cont_on_cl ℂ f {z | 0 < z.re}) (hgd : diff_cont_on_cl ℂ g {z | 0 < z.re})
(hfexp : ∃ (c < (2 : ℝ)) B, f =O[comap complex.abs at_top ⊓ 𝓟 {z | 0 < z.re}]
(λ z, expR (B * (abs z) ^ c)))
(hgexp : ∃ (c < (2 : ℝ)) B, g =O[comap complex.abs at_top ⊓ 𝓟 {z | 0 < z.re}]
(λ z, expR (B * (abs z) ^ c)))
(hre : superpolynomial_decay at_top expR (λ x, ‖f x - g x‖))
(hfim : ∃ C, ∀ x : ℝ, ‖f (x * I)‖ ≤ C) (hgim : ∃ C, ∀ x : ℝ, ‖g (x * I)‖ ≤ C) :
eq_on f g {z : ℂ | 0 ≤ z.re} :=
begin
suffices : eq_on (f - g) 0 {z : ℂ | 0 ≤ z.re},
by simpa only [eq_on, pi.sub_apply, pi.zero_apply, sub_eq_zero] using this,
refine eq_zero_on_right_half_plane_of_superexponential_decay (hfd.sub hgd) _ hre _,
{ set l : filter ℂ := comap complex.abs at_top ⊓ 𝓟 {z : ℂ | 0 < z.re},
suffices : ∀ {c₁ c₂ B₁ B₂ : ℝ}, c₁ ≤ c₂ → B₁ ≤ B₂ → 0 ≤ B₂ →
(λ z, expR (B₁ * abs z ^ c₁)) =O[l] (λ z, expR (B₂ * abs z ^ c₂)),
{ rcases hfexp with ⟨cf, hcf, Bf, hOf⟩, rcases hgexp with ⟨cg, hcg, Bg, hOg⟩,
refine ⟨max cf cg, max_lt hcf hcg, max 0 (max Bf Bg), _⟩,
refine is_O.sub (hOf.trans $ this _ _ _) (hOg.trans $ this _ _ _); simp },
intros c₁ c₂ B₁ B₂ hc hB hB₂,
have : ∀ᶠ z : ℂ in l, 1 ≤ abs z,
from ((eventually_ge_at_top 1).comap _).filter_mono inf_le_left,
refine is_O.of_bound 1 (this.mono $ λ z hz, _),
simp only [real.norm_of_nonneg (real.exp_pos _).le, real.exp_le_exp, one_mul],
exact mul_le_mul hB (real.rpow_le_rpow_of_exponent_le hz hc)
(real.rpow_nonneg_of_nonneg (complex.abs.nonneg _) _) hB₂ },
{ rcases hfim with ⟨Cf, hCf⟩, rcases hgim with ⟨Cg, hCg⟩,
exact ⟨Cf + Cg, λ x, norm_sub_le_of_le (hCf x) (hCg x)⟩ }
end
end phragmen_lindelof
|
b86223e9a99626bfc7a3a4f0f5a7669ec3a36ce2 | 9db059bff49b1090a86ec0050ac6c577eb16ac67 | /src/exercises/order.lean | 878a5c2c5e371b8cad53801938c3164541015626 | [] | no_license | fpvandoorn/Harvard-tutoring | d64cd75c4c529009ee562c30e9cb245fe237e760 | a8846c08e32cdc7b91a7e28adfa5d9b2810088b0 | refs/heads/master | 1,680,870,428,641 | 1,617,022,194,000 | 1,617,022,194,000 | 330,297,467 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,743 | lean | /-
# Orders
Groups, rings, fields, modules etc are in the "algebra hierarchy".
Metric and topological spaces are in the "topology hierarchy".
The other important hierarchy is the "order hierarchy".
It starts with partially ordered sets, and then goes on to lattices.
Because I like algebra, let's demonstrate the order hierarchy by
making an algebraic type, namely the type of subgroups of a group G,
and then working up the order hierarchy with it. Subgroups of a group
are ordered by inclusion, and this is where we shall start. We will
then define infs and sups, and bot and top, and go on from there.
-/
import tactic
-- We will be using all of the theory of subsets of a type
-- without further comment (e.g. `inter_subset_left A B : A ∩ B ⊆ A`)
-- so let's open the `set` namespace.
open set
-- The type of subgroups of a group G is called `subgroup G` in Lean.
-- It already has a lattice structure in Lean.
-- So let's just redo the entire theory and call it `my_subgroup G`.
/-- The type of subgroups of a group `G`. -/
structure my_subgroup (G : Type) [group G] :=
-- A subgroup of G is a sub*set* of G, called `carrier`
(carrier : set G)
-- and then axioms saying it's closed under the group structure (i.e. *, 1, ⁻¹)
(mul_mem {a b : G} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier)
(one_mem : (1 : G) ∈ carrier)
(inv_mem {a : G} : a ∈ carrier → a⁻¹ ∈ carrier)
namespace my_subgroup
/-
Note in particular that we have a function `my_subgroup.carrier : my_subgroup G → set G`,
sending a subgroup of `G` to the underlying subset (`set G` is the type
of subsets of G).
-/
-- Let G be a group, let H,J,K be subgroups of G, and let a,b,c be elements of G.
variables {G : Type} [group G] (H J K : my_subgroup G) (a b c : G)
/- # Extensionality
One of the first things you should consider proving about a newly-defined
type is an extensionality lemma: a sensible criterion to check that
two terms are equal. When are two subgroups of `G` equal? A subgroup
is defined by four things: a subset, and three proofs. But two proofs
of a proposition `P` are equal by definition in Lean, so two subgroups
of `G` are equal iff their underlying subsets are equal, which is
true iff their underlying subsets have the same elements. Let's give
names to these basic results because they'll show up everywhere.
Let's start by showing that two subgroups are equal if their
underlying subsets are equal. This is precisely the statement that
`∀ H J : my_subgroup G, H.carrier = J.carrier → H = J`, and a good name
for this would be `carrier_injective`. We adopt the Lean tradition
of putting as many things to the left of the `:` as we can; it
doesn't change the statement of the theorem.
-/
lemma carrier_injective (H J : my_subgroup G) (h : H.carrier = J.carrier) : H = J :=
begin
-- take H and J apart
cases H, cases J,
-- and note that they are the same set, and then a bunch of proofs
-- which are equal by definition, so it's obvious
simp * at *,
end
-- Now let's prove that two subgroups are equal iff they have the same elements.
-- This is the most useful "extensionality lemma" so we tag it `@[ext]`.
@[ext] theorem ext {H J : my_subgroup G} (h : ∀ (x : G), x ∈ H.carrier ↔ x ∈ J.carrier) :
H = J :=
begin
-- it suffices to prove the subsets are equal
apply carrier_injective,
-- Now let's use extensionality for subsets
ext x,
exact h x,
end
-- We also want the `iff` version of this.
theorem ext_iff {H J : my_subgroup G} : H = J ↔ ∀ (x : G), x ∈ H.carrier ↔ x ∈ J.carrier :=
begin
sorry
end
/-
## Partial orders
-/
-- These are familiar to most mathematicians. We will put a partial order
-- structure on `my_subgroup G`. In other words, we will create a term of
-- type `partial_order (my_subgroup G)`.
-- Let's define `H ≤ J` to mean `H.carrier ⊆ J.carrier`, using the `has_le` notation typeclass
instance : has_le (my_subgroup G) := ⟨λ H J, H.carrier ⊆ J.carrier⟩
-- "tidy" is a one-size-fits-all tactic which solves certain kinds of "follow your nose" goals.
instance : partial_order (my_subgroup G) :=
{ le := (≤),
le_refl := by tidy,
le_trans := by tidy,
le_antisymm := by tidy }
/- Here is a second proof. If X → Y is injective, and Y is partially ordered,
then X inherits a partial order. This construction (it's not a theorem, because
it involves data) is called `partial_order.lift`. Applying it to the injection
`my_subgroup.carrier` and the fact that Lean already knows that `set G` is partially
ordered, turns into this second construction, (which I won't call an `instance`
because if I did then I would have committed the sin of making two terms of
type `partial_order (my_subgroup G)`, and `partial_order (my_subgroup G)` is a class so
should have at most one instance):
-/
-- partial_order.lift is the function which pulls a partial order back along an injection.
example : partial_order (my_subgroup G) := partial_order.lift my_subgroup.carrier carrier_injective
/- Note that we magically just inherited `<` notatation, because
`#check partial_order` tells you that `partial_order` extends `preorder`,
which extends `has_lt`, which is a notation typeclass. In other words,
`#check (H < J)` makes sense, and is a `Prop`. In fact `H < J` is
defined to mean `H ≤ J ∧ ¬ (J ≤ H)`.
# From partial orders to lattices.
Let's now prove that `my_subgroup G` is a `semilattice_inf_top`. This is a class
which extends `partial_order` -- it is a partial order equipped with a top element,
and a function `inf : my_subgroup G → my_subgroup G → my_subgroup G` (called "inf" or "meet"
or "greatest lower bound", satisfying some axioms. In our case, `top`
will be the subgroup `G` of `G` (or more precisely `univ`), and `inf` will
just be intersection. The work we need to do is to check that these are
subgroups, and to prove the axioms for a `semilattice_inf_top`, which
we'll come to later.
First let's define `top` -- the biggest subgroup. The underlying carrier
is `univ : set G`, i.e. the subset `G` of `G`. I'll leave it to you to prove
that the subgroup axioms hold!
The useful piece of interface for `univ` you'll need is `mem_univ g : g ∈ univ`.
-/
def top : my_subgroup G :=
{ carrier := set.univ,
mul_mem := begin
sorry
end,
one_mem := begin
sorry
end,
inv_mem := begin
sorry
end }
-- Add the `⊤` notation (typed with `\top`) for this subgroup:
instance : has_top (my_subgroup G) := ⟨top⟩
-- Now `#check (⊤ : my_subgroup G)` works
/-
We'll now prove the theorem that the intersection of
two subgroups is a subgroup. This is a *definition* in Lean,
indeed it is a construction which given two subgroups `H` and `K` of `G`
produces a third subgroup `H ⊓ K` (Lean's notation for `inf H K`).
The part of the interface for `∩` you'll need is that `a ∈ B ∩ C` is
definitionally equal to `a ∈ B ∧ a ∈ C`, so you can use `split`
if you have a goal `⊢ a ∈ B ∩ C`, and you can use `cases h` if you
have a hypothesis `h : a ∈ B ∩ C`. Don't forget `mul_mem H`, `one_mem H`
and `inv_mem H`, the axioms for `H` if `H : my_subgroup G`.
-/
/-- "Theorem" : intersection of two my_subgroups is a my_subgroup -/
definition inf (H K : my_subgroup G) : my_subgroup G :=
{ carrier := H.carrier ∩ K.carrier,
mul_mem := begin
sorry
end,
one_mem := begin
sorry
end,
inv_mem := begin
sorry
end }
-- Add the `⊓` notation (type with `\inf`) for the intersection (inf) of two subgroups:
instance : has_inf (my_subgroup G) := ⟨inf⟩
-- We now check the four axioms for a semilattice_inf_top.
-- They are called `le_top`, `inf_le_left`, `inf_le_right` and `le_inf`.
-- You might be able to guess the statementss of the axioms
-- from their names.
lemma le_top (H : my_subgroup G) : H ≤ ⊤ :=
begin
sorry
end
lemma inf_le_left (H K : my_subgroup G) : H ⊓ K ≤ H :=
begin
-- by definition this says `H.carrier ∩ K.carrier ⊆ H.carrier`
change H.carrier ∩ K.carrier ⊆ H.carrier,
-- now try `library_search`, to find that this is called `inter_subset_left
apply inter_subset_left,
end
lemma inf_le_right (H K : my_subgroup G) : H ⊓ K ≤ K :=
begin
sorry
end
-- Can you use `library_search`, or other methods, to find the name of the
-- statement that if `A B C : set G` then `A ⊆ B → A ⊆ C → A ⊆ (B ∩ C)`?
lemma le_inf (H J K : my_subgroup G) (h1 : H ≤ J) (h2 : H ≤ K) : H ≤ J ⊓ K :=
begin
sorry
end
-- Now we're ready to make the instance.
instance : semilattice_inf_top (my_subgroup G) :=
{ top := top,
le_top := le_top,
inf := inf,
inf_le_left := inf_le_left,
inf_le_right := inf_le_right,
le_inf := le_inf,
.. my_subgroup.partial_order } -- don't forget to inlude the partial order
/- The logic behind `semilattice_inf_top` is that it is the simplest class
which is closed under all finite "meet"s. The meet of 0 subgroups
is `top`, the meet of one subgroup is the subgroup, the meet of two
subgroups is their inf, and for three or more you proceed by induction.
We could now go on to make a `semilattice_sup_bot` structure, and then
a lattice structure. But let's jump straight to the strongest type
in the order hierarchy -- a `complete_lattice`. This has arbitrary `Inf` and `Sup`s.
So let's first note that we can do better than finite intersections -- we can take
arbitrary intersections! Let's now define the `Inf` of an arbitrary
set of subgroups of `G`.
The part of the interface for sets you'll need to know here is that if `S` is a
set of subsets of `G`, then `⋂₀ S` is notation for their intersection, and
to work with it you'll need to know
`set.mem_sInter : g ∈ ⋂₀ S ↔ ∀ (U : set G), U ∈ S → g ∈ U`.
-/
def Inf (S : set (my_subgroup G)) : my_subgroup G :=
{ carrier := Inf (my_subgroup.carrier '' S),
mul_mem := begin
sorry
end,
one_mem := begin
sorry
end,
inv_mem := begin
sorry
end }
-- We now equip `my_subgroup G` with an Inf. I think the notation is `⨅`, or `\Inf`,
-- but I find it hard to use, and `#print notation ⨅` returns garbage.
instance : has_Inf (my_subgroup G) := ⟨Inf⟩
/- # Complete lattices
Let's jump straight from `semilattice_inf_bot` to `complete_lattice`.
A complete lattice has arbitrary Infs and arbitrary Sups, and satisfies
some other axioms which you can probably imagine. Our next goal
is to make `my_subgroup G` into a complete lattice. We will do it in two ways.
The first way is to show that if our `Inf` satisfies
`(∀ (S : set (my_subgroup G)), is_glb S (Inf S))` then we can build a complete
lattice from this, using `complete_lattice_of_Inf`.
-/
instance : complete_lattice (my_subgroup G) := complete_lattice_of_Inf _ begin
-- ⊢ ∀ (s : set (my_subgroup G)), is_glb s (has_Inf.Inf s)
-- See if you can figure out what this says, and how to prove it.
-- You might find the function `is_glb.of_image` useful.
sorry
end
/- Now let me show you another way to do this.
# Galois connections
A Galois conection is a pair of adjoint functors between two
partially ordered sets, considered as categories whose hom sets Hom(H,J) have
size 1 if H ≤ J and size 0 otherwise. In other words, a Galois
connection between two partial orders α and β is a pair of monotone functions
`l : α → β` and `u : β → α` such that `∀ (a : α) (b : β), l a ≤ b ↔ a ≤ u b`.
There is an example coming from Galois theory (between subfields and subgroups),
and an example coming from classical algebraic geometry (between affine
varieties and ideals); note that in both cases you have to use the opposite
partial order on one side to make everything covariant.
The examples we want to keep in mind here are:
1) α = subsets of G, β = subgroups of G, l = "subgroup generated by", u = `carrier`
2) X : Type, α := set (set X), β := topologies on X,
l = topology generated by a collection of open sets, u = the open sets regarded as subsets.
As you can imagine, there are a bunch of abstract theorems with simple proofs
proved for Galois connections. You can see them by `#check galois_connection`,
jumping to the definition, and reading the next 150 lines of the mathlib file
after the definition. Examples of theorems you might recognise from contexts
where you have seen this before:
lemma le_u_l (a : α) : a ≤ u (l a) := ...
lemma l_u_le (b : β) : l (u b) ≤ b := ...
lemma u_l_u_eq_u : u ∘ l ∘ u = u := ...
lemma l_u_l_eq_l : l ∘ u ∘ l = l := ...
# Galois insertions
A particularly cool kind of Galois connection is a Galois insertion, which
is a Galois connection such that `l ∘ u = id`. This is true for both
the examples we're keeping in mind (the subgroup of `G` generated
by a subgroup is the same subgroup; the topology on `X` generated by a
topology is the same topology).
Our new goal: let's make subgroups of a group into a complete lattice,
using the fact that `carrier` is part of a Galois insertion.
-/
-- The adjoint functor to the `carrier` functor is the `span` functor
-- from subsets to my_subgroups. Here we will CHEAT by using `Inf` to
-- define `span`. We could have built `span` directly with
-- an inductive definition.
def span (S : set G) : my_subgroup G := Inf {H : my_subgroup G | S ⊆ H.carrier}
-- Here are some theorems about it.
lemma monotone_carrier : monotone (my_subgroup.carrier : my_subgroup G → set G) :=
begin
sorry
end
lemma monotone_span : monotone (span : set G → my_subgroup G) :=
begin
sorry
end
lemma subset_span (S : set G) : S ≤ (span S).carrier :=
begin
sorry
end
lemma span_my_subgroup (H : my_subgroup G) : span H.carrier = H :=
begin
sorry
end
-- We have proved all the things we need to show that `span` and `carrier`
-- form a Galois insertion, using `galois_insertion.monotone_intro`.
def gi_my_subgroup : galois_insertion (span : set G → my_subgroup G) (my_subgroup.carrier : my_subgroup G → set G) :=
galois_insertion.monotone_intro monotone_carrier monotone_span subset_span span_my_subgroup
-- Note that `set G` is already a complete lattice:
example : complete_lattice (set G) := by apply_instance
-- and now `my_subgroup G` can also be made into a complete lattice, by
-- a theorem about Galois insertions. Again, I don't use `instance`
-- because we already made the instance above.
example : complete_lattice (my_subgroup G) := galois_insertion.lift_complete_lattice gi_my_subgroup
end my_subgroup
-- Because Alex defined the topology generated by a collection of subsets
-- yesterday, I'll show you how you can use Galois insertions to prove
-- that if `X : Type` then the type of topological space structures on `X`
-- is a complete lattice. We use the topology generated by a collection
-- of subsets, which is a functor adjoint to the forgetful functor.
-- We start by literally copying some stuff from Alex' talk.
open set
@[ext]
class topological_space (X : Type) :=
(is_open : set X → Prop) -- why set X → Prop not set (set X)? former plays
-- nicer with typeclasses later
(univ_mem : is_open univ)
(union : ∀ (B : set (set X)) (h : ∀ b ∈ B, is_open b), is_open (⋃₀ B))
(inter : ∀ (A B : set X) (hA : is_open A) (hB : is_open B), is_open (A ∩ B))
namespace topological_space
def forget {X : Type} : topological_space X → set (set X) := @is_open X
/-- The open sets of the least topology containing a collection of basic sets. -/
inductive generated_open (X : Type) (g : set (set X)) : set X → Prop
| basic : ∀ s ∈ g, generated_open s
| univ : generated_open univ
| inter : ∀s t, generated_open s → generated_open t → generated_open (s ∩ t)
| sUnion : ∀k, (∀ s ∈ k, generated_open s) → generated_open (⋃₀ k)
/-- The smallest topological space containing the collection `g` of basic sets -/
def generate_from {X : Type} (g : set (set X)) : topological_space X :=
{ is_open := generated_open X g,
univ_mem := sorry,
inter := sorry,
union := sorry }
-- Recall that `topological_space X` is the type of topological space structures
-- on `X`. Our Galois insertion will use the adjoint functors
-- `generate_from` and `is_open`.
-- We'd better start by giving the collection of topological space structures on X
-- a partial order:
instance (X : Type) : partial_order (topological_space X) :=
partial_order.lift (forget)
begin
-- need to show that a top space is determined by its open sets
intros τ₁ τ₂ h,
cases τ₁, cases τ₂,
simp [forget, *] at *,
end
-- Exercise (LONG): First, show that we have a Galois insertion.
lemma monotone_is_open {X : Type} :
monotone (forget : topological_space X → set (set X)) :=
begin
sorry
end
lemma monotone_span {X : Type} :
monotone (generate_from : set (set X) → topological_space X) :=
begin
sorry
end
lemma subset_forget {X : Type} (Us : set (set X)) :
Us ≤ forget (generate_from Us) :=
begin
sorry
end
lemma generate_forget {X : Type} (τ : topological_space X) :
generate_from (forget τ) = τ :=
begin
sorry
end
def gi_top (X : Type) :
galois_insertion (generate_from : set (set X) → topological_space X)
(forget : topological_space X → set (set X)) :=
galois_insertion.monotone_intro monotone_is_open monotone_span subset_forget generate_forget
/-
Then deduce that the type of topological space structures on X
is a complete lattice, i.e. that there is a good definition of
arbitrary Infs and Sups of topological space structures on a type, and
they satisfy all the correct properties of Infs and Sups. In
other words,
-/
example (X : Type) : complete_lattice (topological_space X) :=
galois_insertion.lift_complete_lattice (gi_top X)
end topological_space
|
ac17993e649a04e19260bfbac55e12680317c2d3 | a7dd8b83f933e72c40845fd168dde330f050b1c9 | /src/category_theory/instances/Mon/colimits.lean | ca5da8d9ebe50953e7327d6dcc3e765849ff6ef6 | [
"Apache-2.0"
] | permissive | NeilStrickland/mathlib | 10420e92ee5cb7aba1163c9a01dea2f04652ed67 | 3efbd6f6dff0fb9b0946849b43b39948560a1ffe | refs/heads/master | 1,589,043,046,346 | 1,558,938,706,000 | 1,558,938,706,000 | 181,285,984 | 0 | 0 | Apache-2.0 | 1,568,941,848,000 | 1,555,233,833,000 | Lean | UTF-8 | Lean | false | false | 6,628 | lean | import category_theory.instances.Mon.basic
import category_theory.limits.limits
universes v
open category_theory
open category_theory.instances
open category_theory.limits
/-
We build colimits of monoids.
We do so knowing nothing about monoids.
In particular, I want to claim that this file could be produced by a python script
that just looks at the output of `#print monoid`:
-- structure monoid : Type u → Type u
-- fields:
-- monoid.mul : Π {α : Type u} [c : monoid α], α → α → α
-- monoid.mul_assoc : ∀ {α : Type u} [c : monoid α] (a b c_1 : α), a * b * c_1 = a * (b * c_1)
-- monoid.one : Π (α : Type u) [c : monoid α], α
-- monoid.one_mul : ∀ {α : Type u} [c : monoid α] (a : α), 1 * a = a
-- monoid.mul_one : ∀ {α : Type u} [c : monoid α] (a : α), a * 1 = a
and if we'd fed it the output of `#print comm_ring`, this file would instead build
colimits of commutative rings.
A slightly bolder claim is that we could do this with tactics, as well.
-/
namespace category_theory.instances.Mon.colimits
variables {J : Type v} [small_category J] (F : J ⥤ Mon.{v})
inductive prequotient
-- There's always `of`
| of : Π (j : J) (x : (F.obj j).α), prequotient
-- Then one generator for each operation
| one {} : prequotient
| mul : prequotient → prequotient → prequotient
open prequotient
inductive relation : prequotient F → prequotient F → Prop
-- Make it an equivalence relation:
| refl : Π (x), relation x x
| symm : Π (x y) (h : relation x y), relation y x
| trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z
-- There's always a `map` relation
| map : Π (j j' : J) (f : j ⟶ j') (x : (F.obj j).α), relation (of j' ((F.map f) x)) (of j x)
-- Then one relation per operation, describing the interaction with `of`
| mul : Π (j) (x y : (F.obj j).α), relation (of j (x * y)) (mul (of j x) (of j y))
| one : Π (j), relation (of j 1) one
-- Then one relation per argument of each operation
| mul_1 : Π (x x' y) (r : relation x x'), relation (mul x y) (mul x' y)
| mul_2 : Π (x y y') (r : relation y y'), relation (mul x y) (mul x y')
-- And one relation per axiom
| mul_assoc : Π (x y z), relation (mul (mul x y) z) (mul x (mul y z))
| one_mul : Π (x), relation (mul one x) x
| mul_one : Π (x), relation (mul x one) x
def colimit_setoid : setoid (prequotient F) :=
{ r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ }
attribute [instance] colimit_setoid
def colimit_type : Type v := quotient (colimit_setoid F)
instance monoid_colimit_type : monoid (colimit_type F) :=
{ mul :=
begin
fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)),
{ intro x,
fapply @quot.lift,
{ intro y,
exact quot.mk _ (mul x y) },
{ intros y y' r,
apply quot.sound,
exact relation.mul_2 _ _ _ r } },
{ intros x x' r,
funext y,
induction y,
dsimp,
apply quot.sound,
{ exact relation.mul_1 _ _ _ r },
{ refl } },
end,
one :=
begin
exact quot.mk _ one
end,
mul_assoc := λ x y z,
begin
induction x,
induction y,
induction z,
dsimp,
apply quot.sound,
apply relation.mul_assoc,
refl,
refl,
refl,
end,
one_mul := λ x,
begin
induction x,
dsimp,
apply quot.sound,
apply relation.one_mul,
refl,
end,
mul_one := λ x,
begin
induction x,
dsimp,
apply quot.sound,
apply relation.mul_one,
refl,
end }
@[simp] lemma quot_one : quot.mk setoid.r one = (1 : colimit_type F) := rfl
@[simp] lemma quot_mul (x y) : quot.mk setoid.r (mul x y) = ((quot.mk setoid.r x) * (quot.mk setoid.r y) : colimit_type F) := rfl
def colimit : Mon := ⟨colimit_type F, by apply_instance⟩
def cocone_fun (j : J) (x : (F.obj j).α) : colimit_type F :=
quot.mk _ (of j x)
instance cocone_is_hom (j : J) : is_monoid_hom (cocone_fun F j) :=
{ map_one :=
begin
apply quot.sound,
apply relation.one,
end,
map_mul := λ x y,
begin
apply quot.sound,
apply relation.mul,
end }
def cocone_morphism (j : J) : F.obj j ⟶ colimit F :=
{ val := cocone_fun F j,
property := by apply_instance }
@[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') :
F.map f ≫ (cocone_morphism F j') = cocone_morphism F j :=
begin
ext,
apply quot.sound,
apply relation.map,
end
@[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j):
(F.map f ≫ (cocone_morphism F j')) x = (cocone_morphism F j) x :=
by rw cocone_naturality
def colimit_cocone : cocone F :=
{ X := colimit F,
ι :=
{ app := cocone_morphism F, } }.
@[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X
| (of j x) := (s.ι.app j) x
| one := 1
| (mul x y) := desc_fun_lift x * desc_fun_lift y
def desc_fun (s : cocone F) : colimit_type F → s.X :=
begin
fapply quot.lift,
{ exact desc_fun_lift F s },
{ intros x y r,
induction r; try { dsimp },
-- refl
{ refl },
-- symm
{ exact r_ih.symm },
-- trans
{ exact eq.trans r_ih_h r_ih_k },
-- map
{ rw cocone.naturality_bundled, },
-- mul
{ rw is_monoid_hom.map_mul ⇑((s.ι).app r_j) },
-- one
{ erw is_monoid_hom.map_one ⇑((s.ι).app r), refl },
-- mul_1
{ rw r_ih, },
-- mul_2
{ rw r_ih, },
-- mul_assoc
{ rw mul_assoc, },
-- one_mul
{ rw one_mul, },
-- mul_one
{ rw mul_one, } }
end
instance desc_fun_is_morphism (s : cocone F) : is_monoid_hom (desc_fun F s) :=
{ map_one := rfl,
map_mul := λ x y,
begin
induction x, induction y,
refl,
refl,
refl,
end, }
@[simp] def desc_morphism (s : cocone F) : colimit F ⟶ s.X :=
{ val := desc_fun F s,
property := by apply_instance }
def colimit_is_colimit : is_colimit (colimit_cocone F) :=
{ desc := λ s, desc_morphism F s,
uniq' := λ s m w,
begin
ext,
induction x,
induction x,
{ have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x,
erw w',
refl, },
{ simp only [desc_morphism, quot_one],
erw is_monoid_hom.map_one ⇑m,
refl, },
{ simp only [desc_morphism, quot_mul],
erw is_monoid_hom.map_mul ⇑m,
rw [x_ih_a, x_ih_a_1],
refl, },
refl
end }.
-- FIXME why is this infer_instance needed!?
instance has_colimits_Mon : @has_colimits Mon.{v} infer_instance :=
{ has_colimits_of_shape := λ J 𝒥,
{ has_colimit := λ F, by resetI; exact
{ cocone := colimit_cocone F,
is_colimit := colimit_is_colimit F } } }
end category_theory.instances.Mon.colimits
|
36e9bda1f7fc4d0d0f92423d6db1b0cffcc8d3fd | f57749ca63d6416f807b770f67559503fdb21001 | /library/theories/group_theory/cyclic.lean | ce3c7b36eab3ee140ae3ed0069ac934e65d0b806 | [
"Apache-2.0"
] | permissive | aliassaf/lean | bd54e85bed07b1ff6f01396551867b2677cbc6ac | f9b069b6a50756588b309b3d716c447004203152 | refs/heads/master | 1,610,982,152,948 | 1,438,916,029,000 | 1,438,916,029,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,758 | lean | /-
Copyright (c) 2015 Haitao Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Haitao Zhang
-/
import data algebra.group algebra.group_power .finsubg .hom .perm
open function algebra finset
open eq.ops
namespace group
section cyclic
open nat fin list
local attribute madd [reducible]
variable {A : Type}
variable [ambG : group A]
include ambG
lemma pow_mod {a : A} {n m : nat} : a ^ m = 1 → a ^ n = a ^ (n mod m) :=
assume Pid,
assert a ^ (n div m * m) = 1, from calc
a ^ (n div m * m) = a ^ (m * (n div m)) : by rewrite (mul.comm (n div m) m)
... = (a ^ m) ^ (n div m) : by rewrite pow_mul
... = 1 ^ (n div m) : by rewrite Pid
... = 1 : one_pow (n div m),
calc a ^ n = a ^ (n div m * m + n mod m) : by rewrite -(eq_div_mul_add_mod n m)
... = a ^ (n div m * m) * a ^ (n mod m) : by rewrite pow_add
... = 1 * a ^ (n mod m) : by rewrite this
... = a ^ (n mod m) : by rewrite one_mul
lemma pow_sub_eq_one_of_pow_eq {a : A} {i j : nat} :
a^i = a^j → a^(i - j) = 1 :=
assume Pe, or.elim (lt_or_ge i j)
(assume Piltj, begin rewrite [sub_eq_zero_of_le (nat.le_of_lt Piltj)] end)
(assume Pigej, begin rewrite [pow_sub a Pigej, Pe, mul.right_inv] end)
lemma pow_dist_eq_one_of_pow_eq {a : A} {i j : nat} :
a^i = a^j → a^(dist i j) = 1 :=
assume Pe, or.elim (lt_or_ge i j)
(suppose i < j, by rewrite [dist_eq_sub_of_lt this]; exact pow_sub_eq_one_of_pow_eq (eq.symm Pe))
(suppose i ≥ j, by rewrite [dist_eq_sub_of_ge this]; exact pow_sub_eq_one_of_pow_eq Pe)
lemma pow_madd {a : A} {n : nat} {i j : fin (succ n)} :
a^(succ n) = 1 → a^(val (i + j)) = a^i * a^j :=
assume Pe, calc
a^(val (i + j)) = a^((i + j) mod (succ n)) : rfl
... = a^(i + j) : by rewrite [-pow_mod Pe]
... = a^i * a^j : by rewrite pow_add
lemma mk_pow_mod {a : A} {n m : nat} : a ^ (succ m) = 1 → a ^ n = a ^ (mk_mod m n) :=
assume Pe, pow_mod Pe
variable [finA : fintype A]
include finA
open fintype
variable [deceqA : decidable_eq A]
include deceqA
lemma exists_pow_eq_one (a : A) : ∃ n, n < card A ∧ a ^ (succ n) = 1 :=
let f := (λ i : fin (succ (card A)), a ^ i) in
assert Pninj : ¬(injective f), from assume Pinj,
absurd (card_le_of_inj _ _ (exists.intro f Pinj))
(begin rewrite [card_fin], apply not_succ_le_self end),
obtain i₁ P₁, from exists_not_of_not_forall Pninj,
obtain i₂ P₂, from exists_not_of_not_forall P₁,
obtain Pfe Pne, from iff.elim_left not_implies_iff_and_not P₂,
assert Pvne : val i₁ ≠ val i₂, from assume Pveq, absurd (eq_of_veq Pveq) Pne,
exists.intro (pred (dist i₁ i₂)) (begin
rewrite [succ_pred_of_pos (dist_pos_of_ne Pvne)], apply and.intro,
apply lt_of_succ_lt_succ,
rewrite [succ_pred_of_pos (dist_pos_of_ne Pvne)],
apply nat.lt_of_le_of_lt dist_le_max (max_lt i₁ i₂),
apply pow_dist_eq_one_of_pow_eq Pfe
end)
-- Another possibility is to generate a list of powers and use find to get the first
-- unity.
-- The bound on bex is arbitrary as long as it is large enough (at least card A). Making
-- it larger simplifies some proofs, such as a ∈ cyc a.
definition cyc (a : A) : finset A := {x ∈ univ | bex (succ (card A)) (λ n, a ^ n = x)}
definition order (a : A) := card (cyc a)
definition pow_fin (a : A) (n : nat) (i : fin (order a)) := pow a (i + n)
definition cyc_pow_fin (a : A) (n : nat) : finset A := image (pow_fin a n) univ
lemma order_le_group_order {a : A} : order a ≤ card A :=
card_le_card_of_subset !subset_univ
lemma cyc_has_one (a : A) : 1 ∈ cyc a :=
begin
apply mem_filter_of_mem !mem_univ,
existsi 0, apply and.intro,
apply zero_lt_succ,
apply pow_zero
end
lemma order_pos (a : A) : 0 < order a :=
length_pos_of_mem (cyc_has_one a)
lemma cyc_mul_closed (a : A) : finset_mul_closed_on (cyc a) :=
take g h, assume Pgin Phin,
obtain n Plt Pe, from exists_pow_eq_one a,
obtain i Pilt Pig, from of_mem_filter Pgin,
obtain j Pjlt Pjh, from of_mem_filter Phin,
begin
rewrite [-Pig, -Pjh, -pow_add, pow_mod Pe],
apply mem_filter_of_mem !mem_univ,
existsi ((i + j) mod (succ n)), apply and.intro,
apply nat.lt.trans (mod_lt (i+j) !zero_lt_succ) (succ_lt_succ Plt),
apply rfl
end
lemma cyc_has_inv (a : A) : finset_has_inv (cyc a) :=
take g, assume Pgin,
obtain n Plt Pe, from exists_pow_eq_one a,
obtain i Pilt Pig, from of_mem_filter Pgin,
let ni := -(mk_mod n i) in
assert Pinv : g*a^ni = 1, by
rewrite [-Pig, mk_pow_mod Pe, -(pow_madd Pe), add.right_inv],
begin
rewrite [inv_eq_of_mul_eq_one Pinv],
apply mem_filter_of_mem !mem_univ,
existsi ni, apply and.intro,
apply nat.lt.trans (is_lt ni) (succ_lt_succ Plt),
apply rfl
end
lemma self_mem_cyc (a : A) : a ∈ cyc a :=
mem_filter_of_mem !mem_univ
(exists.intro (1 : nat) (and.intro (succ_lt_succ card_pos) !pow_one))
lemma mem_cyc (a : A) : ∀ {n : nat}, a^n ∈ cyc a
| 0 := cyc_has_one a
| (succ n) :=
begin rewrite pow_succ, apply cyc_mul_closed a, exact mem_cyc, apply self_mem_cyc end
lemma order_le {a : A} {n : nat} : a^(succ n) = 1 → order a ≤ succ n :=
assume Pe, let s := image (pow a) (upto (succ n)) in
assert Psub: cyc a ⊆ s, from subset_of_forall
(take g, assume Pgin, obtain i Pilt Pig, from of_mem_filter Pgin, begin
rewrite [-Pig, pow_mod Pe],
apply mem_image,
apply mem_upto_of_lt (mod_lt i !zero_lt_succ),
exact rfl end),
#nat calc order a ≤ card s : card_le_card_of_subset Psub
... ≤ card (upto (succ n)) : !card_image_le
... = succ n : card_upto (succ n)
lemma pow_ne_of_lt_order {a : A} {n : nat} : succ n < order a → a^(succ n) ≠ 1 :=
assume Plt, not_imp_not_of_imp order_le (nat.not_le_of_gt Plt)
lemma eq_zero_of_pow_eq_one {a : A} : ∀ {n : nat}, a^n = 1 → n < order a → n = 0
| 0 := assume Pe Plt, rfl
| (succ n) := assume Pe Plt, absurd Pe (pow_ne_of_lt_order Plt)
lemma pow_fin_inj (a : A) (n : nat) : injective (pow_fin a n) :=
take i j,
suppose a^(i + n) = a^(j + n),
have a^(dist i j) = 1, begin apply !dist_add_add_right ▸ (pow_dist_eq_one_of_pow_eq this) end,
have dist i j = 0, from
eq_zero_of_pow_eq_one this (nat.lt_of_le_of_lt dist_le_max (max_lt i j)),
eq_of_veq (eq_of_dist_eq_zero this)
lemma cyc_eq_cyc (a : A) (n : nat) : cyc_pow_fin a n = cyc a :=
assert Psub : cyc_pow_fin a n ⊆ cyc a, from subset_of_forall
(take g, assume Pgin,
obtain i Pin Pig, from exists_of_mem_image Pgin, by rewrite [-Pig]; apply mem_cyc),
eq_of_card_eq_of_subset (begin apply eq.trans,
apply card_image_eq_of_inj_on,
rewrite [to_set_univ, -set.injective_iff_inj_on_univ], exact pow_fin_inj a n,
rewrite [card_fin] end) Psub
lemma pow_order (a : A) : a^(order a) = 1 :=
obtain i Pin Pone, from exists_of_mem_image (eq.symm (cyc_eq_cyc a 1) ▸ cyc_has_one a),
or.elim (eq_or_lt_of_le (succ_le_of_lt (is_lt i)))
(assume P, P ▸ Pone) (assume P, absurd Pone (pow_ne_of_lt_order P))
lemma eq_one_of_order_eq_one {a : A} : order a = 1 → a = 1 :=
assume Porder,
calc a = a^1 : by rewrite (pow_one a)
... = a^(order a) : by rewrite Porder
... = 1 : by rewrite pow_order
lemma order_of_min_pow {a : A} {n : nat}
(Pone : a^(succ n) = 1) (Pmin : ∀ i, i < n → a^(succ i) ≠ 1) : order a = succ n :=
or.elim (eq_or_lt_of_le (order_le Pone)) (λ P, P)
(λ P : order a < succ n, begin
assert Pn : a^(order a) ≠ 1,
rewrite [-(succ_pred_of_pos (order_pos a))],
apply Pmin, apply nat.lt_of_succ_lt_succ,
rewrite [succ_pred_of_pos !order_pos], assumption,
exact absurd (pow_order a) Pn end)
lemma order_dvd_of_pow_eq_one {a : A} {n : nat} (Pone : a^n = 1) : order a ∣ n :=
assert Pe : a^(n mod order a) = 1, from
begin
revert Pone,
rewrite [eq_div_mul_add_mod n (order a) at {1}, pow_add, mul.comm _ (order a), pow_mul, pow_order, one_pow, one_mul],
intros, assumption
end,
dvd_of_mod_eq_zero (eq_zero_of_pow_eq_one Pe (mod_lt n !order_pos))
definition cyc_is_finsubg [instance] (a : A) : is_finsubg (cyc a) :=
is_finsubg.mk (cyc_has_one a) (cyc_mul_closed a) (cyc_has_inv a)
lemma order_dvd_group_order (a : A) : order a ∣ card A :=
dvd.intro (eq.symm (!mul.comm ▸ lagrange_theorem (subset_univ (cyc a))))
definition pow_fin' (a : A) (i : fin (succ (pred (order a)))) := pow a i
local attribute group_of_add_group [instance]
lemma pow_fin_hom (a : A) : homomorphic (pow_fin' a) :=
take i j,
begin
rewrite [↑pow_fin'],
apply pow_madd,
rewrite [succ_pred_of_pos !order_pos],
exact pow_order a
end
definition pow_fin_is_iso (a : A) : is_iso_class (pow_fin' a) :=
is_iso_class.mk (pow_fin_hom a)
(begin rewrite [↑pow_fin', succ_pred_of_pos !order_pos], exact pow_fin_inj a 0 end)
end cyclic
section rot
open nat list
open fin fintype list
section
local attribute group_of_add_group [instance]
local infix ^ := algebra.pow
lemma pow_eq_mul {n : nat} {i : fin (succ n)} : ∀ {k : nat}, i^k = mk_mod n (i*k)
| 0 := by rewrite [pow_zero]
| (succ k) := begin
assert Psucc : i^(succ k) = madd (i^k) i, apply pow_succ,
rewrite [Psucc, pow_eq_mul],
apply eq_of_veq,
rewrite [mul_succ, val_madd, ↑mk_mod, mod_add_mod]
end
end
definition rotl : ∀ {n : nat} m : nat, fin n → fin n
| 0 := take m i, elim0 i
| (succ n) := take m, madd (mk_mod n (n*m))
definition rotr : ∀ {n : nat} m : nat, fin n → fin n
| (0:nat) := take m i, elim0 i
| (nat.succ n) := take m, madd (-(mk_mod n (n*m)))
lemma rotl_succ' {n m : nat} : rotl m = madd (mk_mod n (n*m)) := rfl
lemma rotl_zero : ∀ {n : nat}, @rotl n 0 = id
| 0 := funext take i, elim0 i
| (succ n) := funext take i, zero_add i
lemma rotl_id : ∀ {n : nat}, @rotl n n = id
| 0 := funext take i, elim0 i
| (succ n) :=
assert P : mk_mod n (n * succ n) = mk_mod n 0,
from eq_of_veq !mul_mod_left,
begin rewrite [rotl_succ', P], apply rotl_zero end
lemma rotl_to_zero {n i : nat} : rotl i (mk_mod n i) = zero n :=
eq_of_veq begin rewrite [↑rotl, val_madd], esimp [mk_mod], rewrite [ mod_add_mod, add_mod_mod, -succ_mul, mul_mod_right] end
lemma rotl_compose : ∀ {n : nat} {j k : nat}, (@rotl n j) ∘ (rotl k) = rotl (j + k)
| 0 := take j k, funext take i, elim0 i
| (succ n) := take j k, funext take i, eq.symm begin
rewrite [*rotl_succ', mul.left_distrib, -(@madd_mk_mod n (n*j)), madd_assoc],
end
lemma rotr_rotl : ∀ {n : nat} (m : nat) {i : fin n}, rotr m (rotl m i) = i
| 0 := take m i, elim0 i
| (nat.succ n) := take m i, calc (-(mk_mod n (n*m))) + ((mk_mod n (n*m)) + i) = i : by rewrite neg_add_cancel_left
lemma rotl_rotr : ∀ {n : nat} (m : nat), (@rotl n m) ∘ (rotr m) = id
| 0 := take m, funext take i, elim0 i
| (nat.succ n) := take m, funext take i, calc (mk_mod n (n*m)) + (-(mk_mod n (n*m)) + i) = i : add_neg_cancel_left
lemma rotl_succ {n : nat} : (rotl 1) ∘ (@succ n) = lift_succ :=
funext (take i, eq_of_veq (begin rewrite [↑compose, ↑rotl, ↑madd, mul_one n, ↑mk_mod, mod_add_mod, ↑lift_succ, val_succ, -succ_add_eq_succ_add, add_mod_self_left, mod_eq_of_lt (lt.trans (is_lt i) !lt_succ_self), -val_lift] end))
definition list.rotl {A : Type} : ∀ l : list A, list A
| [] := []
| (a::l) := l++[a]
lemma rotl_cons {A : Type} {a : A} {l} : list.rotl (a::l) = l++[a] := rfl
lemma rotl_map {A B : Type} {f : A → B} : ∀ {l : list A}, list.rotl (map f l) = map f (list.rotl l)
| [] := rfl
| (a::l) := begin rewrite [map_cons, *rotl_cons, map_append] end
lemma rotl_eq_rotl : ∀ {n : nat}, map (rotl 1) (upto n) = list.rotl (upto n)
| 0 := rfl
| (succ n) := begin
rewrite [upto_step at {1}, upto_succ, rotl_cons, map_append],
congruence,
rewrite [map_map], congruence, exact rotl_succ,
rewrite [map_singleton], congruence, rewrite [↑rotl, mul_one n, ↑mk_mod, ↑zero, ↑maxi, ↑madd],
congruence, rewrite [ mod_add_mod, nat.add_zero, mod_eq_of_lt !lt_succ_self ]
end
definition seq [reducible] (A : Type) (n : nat) := fin n → A
variable {A : Type}
definition rotl_fun {n : nat} (m : nat) (f : seq A n) : seq A n := f ∘ (rotl m)
definition rotr_fun {n : nat} (m : nat) (f : seq A n) : seq A n := f ∘ (rotr m)
lemma rotl_seq_zero {n : nat} : rotl_fun 0 = @id (seq A n) :=
funext take f, begin rewrite [↑rotl_fun, rotl_zero] end
lemma rotl_seq_ne_id : ∀ {n : nat}, (∃ a b : A, a ≠ b) → ∀ i, i < n → rotl_fun (succ i) ≠ (@id (seq A (succ n)))
| 0 := assume Pex, take i, assume Piltn, absurd Piltn !not_lt_zero
| (succ n) := assume Pex, obtain a b Pne, from Pex, take i, assume Pilt,
let f := (λ j : fin (succ (succ n)), if j = zero (succ n) then a else b),
fi := mk_mod (succ n) (succ i) in
have Pfne : rotl_fun (succ i) f fi ≠ f fi,
from begin rewrite [↑rotl_fun, rotl_to_zero, mk_mod_of_lt (succ_lt_succ Pilt), if_pos rfl, if_neg mk_succ_ne_zero], assumption end,
have P : rotl_fun (succ i) f ≠ f, from
assume Peq, absurd (congr_fun Peq fi) Pfne,
assume Peq, absurd (congr_fun Peq f) P
lemma rotr_rotl_fun {n : nat} (m : nat) (f : seq A n) : rotr_fun m (rotl_fun m f) = f :=
calc f ∘ (rotl m) ∘ (rotr m) = f ∘ ((rotl m) ∘ (rotr m)) : by rewrite -compose.assoc
... = f ∘ id : by rewrite (rotl_rotr m)
lemma rotl_fun_inj {n : nat} {m : nat} : @injective (seq A n) (seq A n) (rotl_fun m) :=
injective_of_has_left_inverse (exists.intro (rotr_fun m) (rotr_rotl_fun m))
lemma seq_rotl_eq_list_rotl {n : nat} (f : seq A n) :
fun_to_list (rotl_fun 1 f) = list.rotl (fun_to_list f) :=
begin
rewrite [↑fun_to_list, ↑rotl_fun, -map_map, rotl_map],
congruence, exact rotl_eq_rotl
end
end rot
section rotg
open nat fin fintype
definition rotl_perm [reducible] (A : Type) [finA : fintype A] [deceqA : decidable_eq A] (n : nat) (m : nat) : perm (seq A n) :=
perm.mk (rotl_fun m) rotl_fun_inj
variable {A : Type}
variable [finA : fintype A]
variable [deceqA : decidable_eq A]
variable {n : nat}
include finA deceqA
lemma rotl_perm_mul {i j : nat} : (rotl_perm A n i) * (rotl_perm A n j) = rotl_perm A n (j+i) :=
eq_of_feq (funext take f, calc
f ∘ (rotl j) ∘ (rotl i) = f ∘ ((rotl j) ∘ (rotl i)) : by rewrite -compose.assoc
... = f ∘ (rotl (j+i)) : by rewrite rotl_compose)
lemma rotl_perm_pow_eq : ∀ {i : nat}, (rotl_perm A n 1) ^ i = rotl_perm A n i
| 0 := begin rewrite [pow_zero, ↑rotl_perm, perm_one, -eq_iff_feq], esimp, rewrite rotl_seq_zero end
| (succ i) := begin rewrite [pow_succ, rotl_perm_pow_eq, rotl_perm_mul, one_add] end
lemma rotl_perm_pow_eq_one : (rotl_perm A n 1) ^ n = 1 :=
eq.trans rotl_perm_pow_eq (eq_of_feq begin esimp [rotl_perm], rewrite [↑rotl_fun, rotl_id] end)
lemma rotl_perm_mod {i : nat} : rotl_perm A n i = rotl_perm A n (i mod n) :=
calc rotl_perm A n i = (rotl_perm A n 1) ^ i : by rewrite rotl_perm_pow_eq
... = (rotl_perm A n 1) ^ (i mod n) : by rewrite (pow_mod rotl_perm_pow_eq_one)
... = rotl_perm A n (i mod n) : by rewrite rotl_perm_pow_eq
-- needs A to have at least two elements!
lemma rotl_perm_pow_ne_one (Pex : ∃ a b : A, a ≠ b) : ∀ i, i < n → (rotl_perm A (succ n) 1)^(succ i) ≠ 1 :=
take i, assume Piltn, begin
intro P, revert P, rewrite [rotl_perm_pow_eq, -eq_iff_feq, perm_one, *perm.f_mk],
intro P, exact absurd P (rotl_seq_ne_id Pex i Piltn)
end
lemma rotl_perm_order (Pex : ∃ a b : A, a ≠ b) : order (rotl_perm A (succ n) 1) = (succ n) :=
order_of_min_pow rotl_perm_pow_eq_one (rotl_perm_pow_ne_one Pex)
end rotg
end group
|
dbfcc3cd8342336ee96e609ed2495608f74d3f54 | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/basics/unnamed_1097.lean | 28acec8fccf7c9e03401ed92855524d3636fa8e0 | [] | no_license | jamescheuk91/mathematics_in_lean | 09f1f87d2b0dce53464ff0cbe592c568ff59cf5e | 4452499264e2975bca2f42565c0925506ba5dda3 | refs/heads/master | 1,679,716,410,967 | 1,613,957,947,000 | 1,613,957,947,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 175 | lean | import data.real.basic
variables a b c : ℝ
-- BEGIN
example (a b c d e : ℝ) (h₀ : a ≤ b) (h₁ : b < c) (h₂ : c ≤ d)
(h₃ : d < e) :
a < e :=
sorry
-- END |
08628bb160c683e5b0c924bde34c99ee8e01bfef | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Init/Data/OfScientific.lean | 772ce0b0f986681fe2e900359c4bb61eb58df4ae | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,665 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Meta
import Init.Data.Float
import Init.Data.Nat
/-- For decimal and scientific numbers (e.g., `1.23`, `3.12e10`).
Examples:
- `OfScientific.ofScientific 123 true 2` represents `1.23`
- `OfScientific.ofScientific 121 false 100` represents `121e100`
-/
class OfScientific (α : Type u) where
ofScientific (mantissa : Nat) (exponentSign : Bool) (decimalExponent : Nat) : α
/-- Computes `m * 2^e`. -/
def Float.ofBinaryScientific (m : Nat) (e : Int) : Float :=
let s := m.log2 - 63
let m := (m >>> s).toUInt64
let e := e + s
m.toFloat.scaleB e
protected opaque Float.ofScientific (m : Nat) (s : Bool) (e : Nat) : Float :=
if s then
let s := 64 - m.log2 -- ensure we have 64 bits of mantissa left after division
let m := (m <<< (3 * e + s)) / 5^e
Float.ofBinaryScientific m (-4 * e - s)
else
Float.ofBinaryScientific (m * 5^e) e
/--
The `OfScientific Float` must have priority higher than `mid` since
the default instance `Neg Int` has `mid` priority.
```
#check -42.0 -- must be Float
```
-/
@[default_instance mid+1]
instance : OfScientific Float where
ofScientific := Float.ofScientific
@[export lean_float_of_nat]
def Float.ofNat (n : Nat) : Float :=
OfScientific.ofScientific n false 0
def Float.ofInt : Int → Float
| Int.ofNat n => Float.ofNat n
| Int.negSucc n => Float.neg (Float.ofNat (Nat.succ n))
instance : OfNat Float n := ⟨Float.ofNat n⟩
abbrev Nat.toFloat (n : Nat) : Float :=
Float.ofNat n
|
cc5c1969d0c3eaa8ad3bd4b1bb64f5369219911e | a7dd8b83f933e72c40845fd168dde330f050b1c9 | /src/category_theory/instances/CommRing/adjunctions.lean | 8ed386e4a5361693ca209407be12ad2b68bd5e0a | [
"Apache-2.0"
] | permissive | NeilStrickland/mathlib | 10420e92ee5cb7aba1163c9a01dea2f04652ed67 | 3efbd6f6dff0fb9b0946849b43b39948560a1ffe | refs/heads/master | 1,589,043,046,346 | 1,558,938,706,000 | 1,558,938,706,000 | 181,285,984 | 0 | 0 | Apache-2.0 | 1,568,941,848,000 | 1,555,233,833,000 | Lean | UTF-8 | Lean | false | false | 1,588 | lean | /- Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Johannes Hölzl
Multivariable polynomials on a type is the left adjoint of the
forgetful functor from commutative rings to types.
-/
import category_theory.instances.CommRing.basic
import category_theory.adjunction.basic
import data.mv_polynomial
universe u
open mv_polynomial
open category_theory
open category_theory.instances
namespace category_theory.instances.CommRing
local attribute [instance, priority 0] classical.prop_decidable
noncomputable def polynomial_ring : Type u ⥤ CommRing.{u} :=
{ obj := λ α, ⟨mv_polynomial α ℤ, by apply_instance⟩,
map := λ α β f, ⟨rename f, by apply_instance⟩ }
@[simp] lemma polynomial_ring_obj_α {α : Type u} :
(polynomial_ring.obj α).α = mv_polynomial α ℤ := rfl
@[simp] lemma polynomial_ring_map_val {α β : Type u} {f : α → β} :
(polynomial_ring.map f).val = rename f := rfl
noncomputable def adj : polynomial_ring ⊣ (forget : CommRing.{u} ⥤ Type u) :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ α R,
{ to_fun := λ f, f ∘ X,
inv_fun := λ f, ⟨eval₂ (λ n : ℤ, (n : R)) f, by { unfold_coes, apply_instance }⟩,
left_inv := λ f, CommRing.hom.ext $ @eval₂_hom_X _ _ _ _ _ _ f _,
right_inv := λ x, by { ext1, unfold_coes, simp only [function.comp_app, eval₂_X] } },
hom_equiv_naturality_left_symm' :=
λ X X' Y f g, by { ext1, dsimp, apply eval₂_cast_comp }
}.
end category_theory.instances.CommRing
|
dbdb9ec2b1d0d9c5aaf94b5ad9729bd8aca86cc2 | e4a7c8ab8b68ca0e53d2c21397320ea590fa01c6 | /src/data/polya/field/pterm.lean | bbf7e6ce803b7c78534adae243da18d2df1a7de3 | [] | no_license | lean-forward/field | 3ff5dc5f43de40f35481b375f8c871cd0a07c766 | 7e2127ad485aec25e58a1b9c82a6bb74a599467a | refs/heads/master | 1,590,947,010,909 | 1,563,811,881,000 | 1,563,811,881,000 | 190,415,651 | 1 | 0 | null | 1,563,643,371,000 | 1,559,746,688,000 | Lean | UTF-8 | Lean | false | false | 10,758 | lean | import .basic
namespace polya.field
open nterm
--@[derive decidable_eq]
structure xterm (γ : Type) [const_space γ] : Type :=
(term : nterm γ)
(exp : znum)
namespace xterm
variables {α : Type} [discrete_field α]
variables {γ : Type} [const_space γ]
variables [morph γ α] {ρ : dict α}
def to_nterm (x : xterm γ) : nterm γ :=
if x.exp = 0 then x.term / x.term
else if x.exp = 1 then x.term
else x.term ^ x.exp
def eval (ρ : dict α) (x : xterm γ) : α :=
let a := nterm.eval ρ x.term in
if a = 0 then 0 else a ^ (x.exp : ℤ)
def eval_to_nterm {x : xterm γ} :
nterm.eval ρ x.to_nterm = xterm.eval ρ x :=
begin
by_cases hx : nterm.eval ρ x.term = 0;
{ by_cases h1 : x.exp = 0,
{ simp [hx, h1, nterm.eval, xterm.eval, to_nterm] },
{ have : (x.exp : ℤ) ≠ 0, by {rw ← znum.cast_zero, exact_mod_cast h1 },
by_cases h2 : x.exp = 1;
simp [hx, h1, h2, nterm.eval, xterm.eval, to_nterm, zero_fpow, this] }}
end
theorem eval_to_nterm' :
nterm.eval ρ ∘ @xterm.to_nterm γ _ = xterm.eval ρ :=
begin
unfold function.comp,
simp [eval_to_nterm]
end
theorem eval_def {x : nterm γ} {n : znum} :
xterm.eval ρ ⟨x, n⟩ =
if nterm.eval ρ x = 0 then 0
else nterm.eval ρ x ^ (n : ℤ) :=
rfl
theorem eval_add {x : nterm γ} {n m : znum} :
xterm.eval ρ ⟨x, n + m⟩ = xterm.eval ρ ⟨x, n⟩ * xterm.eval ρ ⟨x, m⟩ :=
begin
by_cases hx : nterm.eval ρ x = 0;
simp [xterm.eval, fpow_add, hx]
end
def pmerge : list (xterm γ) → list (xterm γ) → list (xterm γ)
| (x::xs) (y::ys) :=
if x.term = y.term then
⟨x.term, x.exp + y.exp⟩ :: pmerge xs ys
else if x.term < y.term then
x :: pmerge xs (y::ys)
else
y :: pmerge (x::xs) ys
| xs [] := xs
| [] ys := ys
lemma pmerge_nil_left {ys : list (xterm γ)} :
pmerge [] ys = ys :=
begin
induction ys with y ys ih,
{ unfold pmerge },
{ unfold pmerge }
end
lemma pmerge_nil_right {xs : list (xterm γ)} :
pmerge xs [] = xs :=
begin
induction xs with x xs ih,
{ unfold pmerge },
{ unfold pmerge }
end
lemma pmerge_def1 {x y : xterm γ} {xs ys : list (xterm γ)} :
x.term = y.term →
pmerge (x::xs) (y::ys) = ⟨x.term, x.exp + y.exp⟩ :: pmerge xs ys :=
by intro h; simp [pmerge, h]
lemma pmerge_def2 {x y : xterm γ} {xs ys : list (xterm γ)} :
x.term ≠ y.term → x.term < y.term →
pmerge (x::xs) (y::ys) = x :: pmerge xs (y :: ys) :=
by intros h1 h2; simp [pmerge, h1, h2]
lemma pmerge_def3 {x y : xterm γ} {xs ys : list (xterm γ)} :
x.term ≠ y.term → ¬ x.term < y.term →
pmerge (x::xs) (y::ys) = y :: pmerge (x::xs) ys :=
by intros h1 h2; simp [pmerge, h1, h2]
theorem eval_pmerge (xs ys : list (xterm γ)) :
list.prod (list.map (xterm.eval ρ) (pmerge xs ys))
= list.prod (list.map (xterm.eval ρ) xs)
* list.prod (list.map (xterm.eval ρ) ys) :=
begin
revert ys,
induction xs with x xs ihx,
{ intro ys, simp [pmerge_nil_left] },
{ intro ys, induction ys with y ys ihy,
{ simp [pmerge_nil_right] },
{ by_cases h1 : x.term = y.term,
{ rw pmerge_def1 h1,
cases x with x n, cases y with y m,
simp only [] at h1, rw h1 at *,
repeat {rw [list.map_cons, list.prod_cons]},
rw [eval_add, ihx ys], ring },
{ by_cases h2 : x.term < y.term,
{ rw pmerge_def2 h1 h2,
repeat {rw [list.map_cons, list.prod_cons]},
rw [ihx (y::ys), list.map_cons, list.prod_cons],
ring},
{ rw pmerge_def3 h1 h2,
repeat {rw [list.map_cons, list.prod_cons]},
rw [ihy, list.map_cons, list.prod_cons],
ring }}}}
end
theorem eval_pow {x : xterm γ} {n : znum} :
n ≠ 0 → xterm.eval ρ ⟨x.term, x.exp * n⟩ = xterm.eval ρ x ^ (n : ℤ) :=
begin
intro h0,
have h1 : (n : ℤ) ≠ 0, by {rw ← znum.cast_zero, exact_mod_cast h0},
by_cases hx : nterm.eval ρ x.term = 0,
{ simp [hx, xterm.eval, zero_fpow, h1] },
{ simp [hx, xterm.eval, fpow_mul] }
end
theorem eval_prod_pow {xs : list (xterm γ)} {n : znum} :
n ≠ 0 → list.prod (list.map (xterm.eval ρ) xs) ^ (n : ℤ)
= list.prod (list.map (λ x : xterm γ, xterm.eval ρ ⟨x.term, x.exp * n⟩) xs) :=
begin
intro hn,
induction xs with x xs ih,
{ simp },
{ repeat {rw [list.map_cons, list.prod_cons]},
rw [eval_pow hn, mul_fpow, ih] }
end
end xterm
structure pterm (γ : Type) [const_space γ] : Type :=
(terms : list (xterm γ))
(coeff : γ)
namespace pterm
variables {α : Type} [discrete_field α]
variables {γ : Type} [const_space γ]
variables [morph γ α] {ρ : dict α}
def of_const (a : γ) : pterm γ :=
{ terms := [], coeff := a, }
def singleton (x : nterm γ) : pterm γ :=
{ terms := [⟨x, 1⟩], coeff := 1 }
def eval (ρ : dict α) (P : pterm γ) : α :=
list.prod (P.terms.map (xterm.eval ρ)) * ↑P.coeff
theorem eval_of_const (a : γ) :
pterm.eval ρ (of_const a) = ↑a :=
by simp [of_const, pterm.eval, xterm.eval]
theorem eval_singleton (x : nterm γ) :
pterm.eval ρ (singleton x) = nterm.eval ρ x :=
begin
by_cases hx : nterm.eval ρ x = 0,
repeat {simp [singleton, pterm.eval, xterm.eval, hx]}
end
def mul (P1 P2 : pterm γ) : pterm γ :=
if P1.coeff = 0 ∨ P2.coeff = 0 then
{ terms := [],
coeff := 0,
}
else
{ terms := xterm.pmerge P1.terms P2.terms,
coeff := P1.coeff * P2.coeff,
}
def pow (P : pterm γ) (n : znum) : pterm γ :=
if n = 0 then
of_const 1
else
{ terms := P.terms.map (λ x, ⟨x.term, x.exp * n⟩),
coeff := P.coeff ^ (n : ℤ),
}
instance : has_mul (pterm γ) := ⟨mul⟩
instance : has_pow (pterm γ) znum := ⟨pow⟩
theorem mul_terms {P Q : pterm γ} :
P.coeff ≠ 0 ∧ Q.coeff ≠ 0 →
(P * Q).terms = xterm.pmerge P.terms Q.terms :=
begin
intro h,
simp [has_mul.mul, mul, h]
end
theorem mul_terms' {P Q : pterm γ} :
P.coeff = 0 ∨ Q.coeff = 0 →
(P * Q).terms = [] :=
begin
intro h,
simp [has_mul.mul, mul, h]
end
theorem mul_coeff {P Q : pterm γ} :
(P * Q).coeff = P.coeff * Q.coeff :=
begin
by_cases h : P.coeff = 0 ∨ Q.coeff = 0,
{ apply eq.trans,
{ show (P * Q).coeff = 0, simp [has_mul.mul, mul, h] },
{ simp [h] }},
{ simp [has_mul.mul, mul, h] }
end
theorem eval_mul {P Q : pterm γ} :
pterm.eval ρ (P * Q) = pterm.eval ρ P * pterm.eval ρ Q :=
begin
unfold pterm.eval, rw mul_coeff,
by_cases h0 : P.coeff = 0 ∨ Q.coeff = 0,
{ cases h0; simp [h0, morph.morph_zero'] },
{ have : P.coeff ≠ 0 ∧ Q.coeff ≠ 0,
from (decidable.not_or_iff_and_not _ _).mp h0,
rw [mul_terms this, xterm.eval_pmerge, morph.morph_mul],
ring }
end
theorem pow_def {P : pterm γ} {n : znum} :
n ≠ 0 → pterm.eval ρ (P.pow n) =
list.prod (list.map (λ x : xterm γ, xterm.eval ρ ⟨x.term, x.exp * n⟩) P.terms) * ↑P.coeff ^ (n : ℤ) :=
begin
intro hn,
rw [← morph.morph_pow],
simp [has_pow.pow, pow, hn, pterm.eval]
end
theorem eval_pow {P : pterm γ} {n : znum} :
pterm.eval ρ (P ^ n) = pterm.eval ρ P ^ (n : ℤ) :=
begin
by_cases hn : n = 0,
{ rw [hn, znum.cast_zero, fpow_zero],
simp [has_pow.pow, pow, of_const, pterm.eval] },
{ cases P with xs c,
simp only [pterm.eval],
rw [mul_fpow, ← morph.morph_pow],
congr,
{ rw xterm.eval_prod_pow hn,
simp [has_pow.pow, pow, hn] },
{ simp [has_pow.pow, pow, hn] }}
end
def to_nterm (P : pterm γ) : nterm γ :=
prod (P.terms.map xterm.to_nterm) * P.coeff
theorem eval_to_nterm {P : pterm γ} :
pterm.eval ρ P = nterm.eval ρ P.to_nterm :=
begin
--cases P with xs c,
--by_cases h1 : xs.empty = ff,
--{ by_cases h2 : c = 1,
-- { rw h2, simp [pterm.eval, to_nterm, h1, eval_prod, xterm.eval_to_nterm'] },
-- { suffices : list.prod (list.map (xterm.eval ρ) xs) * ↑c =
-- nterm.eval ρ (prod (list.map xterm.to_nterm xs)) * ↑c,
-- by { simp [to_nterm, pterm.eval, this, h1, h2] },
-- rw [eval_prod, list.map_map],
-- rw xterm.eval_to_nterm' }},
----this is silly TODO
--{ have h1' : xs.empty = tt, by { cases xs,
-- { refl },
-- { by_contradiction, apply h1, unfold list.empty }},
-- cases xs,
-- { simp [pterm.eval, nterm.eval, to_nterm, h1'] },
-- { by_contradiction, apply h1, unfold list.empty }
--}
cases P with xs c,
suffices : list.prod (list.map (xterm.eval ρ) xs) * ↑c =
nterm.eval ρ (prod (list.map xterm.to_nterm xs)) * ↑c,
by { simp [to_nterm, pterm.eval, this] },
rw [eval_prod, list.map_map],
rw xterm.eval_to_nterm'
end
def reduce (P : pterm γ) : pterm γ :=
{ terms := P.terms.filter (λ x, x.exp ≠ 0),
coeff := P.coeff
}
def reduce_hyps (P : pterm γ) : list (nterm γ) :=
list.map xterm.term (P.terms.filter (λ x, x.exp = 0))
private lemma lemma_eval_reduce {x : xterm γ} :
x.exp = 0 ∧ nterm.eval ρ x.term ≠ 0 →
xterm.eval ρ x = 1 :=
begin
cases x with x n,
simp only [],
intro h, cases h with hn hx,
simp [xterm.eval, hn, hx]
end
theorem eval_reduce {P : pterm γ} :
nonzero ρ P.reduce_hyps →
pterm.eval ρ P = pterm.eval ρ P.reduce :=
begin
intro H,
have H1 : ∀ x : xterm γ, x ∈ P.terms → x.exp = 0 → nterm.eval ρ (x.term) ≠ 0,
by { intros x h1 h2, apply H, simp [reduce_hyps], existsi x, simp [h1, h2] },
have H2 : ∀ x : xterm γ, x ∈ P.terms.filter (λ x, x.exp = 0) → nterm.eval ρ (x.term) ≠ 0,
by { intros x hx, have : x ∈ P.terms ∧ x.exp = 0, from list.mem_filter.mp hx,
cases this, apply H1; assumption },
have : P.terms ~ P.terms.filter (λ x, x.exp = 0) ++ P.terms.filter (λ x, x.exp ≠ 0),
from list.filter_perm,
unfold pterm.eval,
rw list.prod_eq_of_perm (list.perm_map _ this),
rw [list.map_append, list.prod_append],
have : ∀ x ∈ P.terms.filter (λ x, x.exp = 0), xterm.eval ρ x = 1,
by {
intros x hx,
apply lemma_eval_reduce,
split,
{ exact (list.mem_filter.mp hx).right },
{ apply H2, exact hx }},
have : ∀ a ∈ (list.map (xterm.eval ρ) (P.terms.filter (λ x, x.exp = 0))), a = 1,
by { intros a ha, rw list.mem_map at ha,
cases ha with x hx,
cases hx with hx ha,
rw ← ha, apply this,
assumption },
simp [reduce, list.prod_ones this]
end
def of_nterm : nterm γ → pterm γ
| (nterm.mul x y) := of_nterm x * of_nterm y
| (nterm.pow x n) := of_nterm x ^ n
| (nterm.const a) := of_const a
| x := singleton x
theorem eval_of_nterm {x : nterm γ} :
pterm.eval ρ (of_nterm x) = nterm.eval ρ x :=
begin
induction x with i c x y ihx ihy x y ihx ihy x n ihx,
{ simp [of_nterm, eval_singleton] },
{ simp [of_nterm, eval_of_const, nterm.eval] },
{ simp [of_nterm, eval_singleton] },
{ simp [of_nterm, eval_mul, nterm.eval, ihx, ihy] },
{ simp [of_nterm, eval_pow, nterm.eval, ihx] }
end
end pterm
end polya.field
|
9b37b4693780580d4351a02f6ecdd0a40716f13e | 367134ba5a65885e863bdc4507601606690974c1 | /src/topology/shrinking_lemma.lean | c004f3055f44a7d57c2d2cda3142acc075da9736 | [
"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 | 10,812 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Reid Barton
-/
import topology.separation
/-!
# The shrinking lemma
In this file we prove a few versions of the shrinking lemma. The lemma says that in a normal
topological space a point finite open covering can be “shrunk”: for a point finite open covering
`u : ι → set X` there exists a refinement `v : ι → set X` such that `closure (v i) ⊆ u i`.
For finite or countable coverings this lemma can be proved without the axiom of choice, see
[ncatlab](https://ncatlab.org/nlab/show/shrinking+lemma) for details. We only formalize the most
general result that works for any covering but needs the axiom of choice.
We prove two versions of the lemma:
* `exists_subset_Union_closure_subset` deals with a covering of a closed set in a normal space;
* `exists_Union_eq_closure_subset` deals with a covering of the whole space.
## Tags
normal space, shrinking lemma
-/
open set zorn function
open_locale classical
noncomputable theory
variables {ι X : Type*} [topological_space X] [normal_space X]
namespace shrinking_lemma
/-- Auxiliary definition for the proof of `shrinking_lemma`. A partial refinement of a covering
`⋃ i, u i` of a set `s` is a map `v : ι → set X` and a set `carrier : set ι` such that
* `s ⊆ ⋃ i, v i`;
* all `v i` are open;
* if `i ∈ carrier v`, then `closure (v i) ⊆ u i`;
* if `i ∉ carrier`, then `v i = u i`.
This type is equipped with the folowing partial order: `v ≤ v'` if `v.carrier ⊆ v'.carrier`
and `v i = v' i` for `i ∈ v.carrier`. We will use Zorn's lemma to prove that this type has
a maximal element, then show that the maximal element must have `carrier = univ`. -/
@[nolint has_inhabited_instance] -- the trivial refinement needs `u` to be a covering
structure partial_refinement (u : ι → set X) (s : set X) :=
(to_fun : ι → set X)
(carrier : set ι)
(is_open' : ∀ i, is_open (to_fun i))
(subset_Union' : s ⊆ ⋃ i, to_fun i)
(closure_subset' : ∀ i ∈ carrier, closure (to_fun i) ⊆ (u i))
(apply_eq' : ∀ i ∉ carrier, to_fun i = u i)
namespace partial_refinement
variables {u : ι → set X} {s : set X}
instance : has_coe_to_fun (partial_refinement u s) := ⟨_, to_fun⟩
lemma subset_Union (v : partial_refinement u s) : s ⊆ ⋃ i, v i := v.subset_Union'
lemma closure_subset (v : partial_refinement u s) {i : ι} (hi : i ∈ v.carrier) :
closure (v i) ⊆ (u i) :=
v.closure_subset' i hi
lemma apply_eq (v : partial_refinement u s) {i : ι} (hi : i ∉ v.carrier) : v i = u i :=
v.apply_eq' i hi
protected lemma is_open (v : partial_refinement u s) (i : ι) : is_open (v i) := v.is_open' i
protected lemma subset (v : partial_refinement u s) (i : ι) : v i ⊆ u i :=
if h : i ∈ v.carrier then subset.trans subset_closure (v.closure_subset h)
else (v.apply_eq h).le
attribute [ext] partial_refinement
instance : partial_order (partial_refinement u s) :=
{ le := λ v₁ v₂, v₁.carrier ⊆ v₂.carrier ∧ ∀ i ∈ v₁.carrier, v₁ i = v₂ i,
le_refl := λ v, ⟨subset.refl _, λ _ _, rfl⟩,
le_trans := λ v₁ v₂ v₃ h₁₂ h₂₃,
⟨subset.trans h₁₂.1 h₂₃.1, λ i hi, (h₁₂.2 i hi).trans (h₂₃.2 i $ h₁₂.1 hi)⟩,
le_antisymm := λ v₁ v₂ h₁₂ h₂₁,
have hc : v₁.carrier = v₂.carrier, from subset.antisymm h₁₂.1 h₂₁.1,
ext _ _ (funext $ λ x,
if hx : x ∈ v₁.carrier then h₁₂.2 _ hx
else (v₁.apply_eq hx).trans (eq.symm $ v₂.apply_eq $ hc ▸ hx)) hc }
/-- If two partial refinements `v₁`, `v₂` belong to a chain (hence, they are comparable)
and `i` belongs to the carriers of both partial refinements, then `v₁ i = v₂ i`. -/
lemma apply_eq_of_chain {c : set (partial_refinement u s)} (hc : chain (≤) c) {v₁ v₂}
(h₁ : v₁ ∈ c) (h₂ : v₂ ∈ c) {i} (hi₁ : i ∈ v₁.carrier) (hi₂ : i ∈ v₂.carrier) :
v₁ i = v₂ i :=
begin
wlog hle : v₁ ≤ v₂ := hc.total_of_refl h₁ h₂ using [v₁ v₂, v₂ v₁],
exact hle.2 _ hi₁,
end
/-- The carrier of the least upper bound of a non-empty chain of partial refinements
is the union of their carriers. -/
def chain_Sup_carrier (c : set (partial_refinement u s)) : set ι :=
⋃ v ∈ c, carrier v
/-- Choice of an element of a nonempty chain of partial refinements. If `i` belongs to one of
`carrier v`, `v ∈ c`, then `find c ne i` is one of these partial refinements. -/
def find (c : set (partial_refinement u s)) (ne : c.nonempty) (i : ι) :
partial_refinement u s :=
if hi : ∃ v ∈ c, i ∈ carrier v then hi.some else ne.some
lemma find_mem {c : set (partial_refinement u s)} (i : ι) (ne : c.nonempty) :
find c ne i ∈ c :=
by { rw find, split_ifs, exacts [h.some_spec.fst, ne.some_spec] }
lemma mem_find_carrier_iff {c : set (partial_refinement u s)} {i : ι} (ne : c.nonempty) :
i ∈ (find c ne i).carrier ↔ i ∈ chain_Sup_carrier c :=
begin
rw find,
split_ifs,
{ have : i ∈ h.some.carrier ∧ i ∈ chain_Sup_carrier c,
from ⟨h.some_spec.snd, mem_bUnion_iff.2 h⟩,
simp only [this] },
{ have : i ∉ ne.some.carrier ∧ i ∉ chain_Sup_carrier c,
from ⟨λ hi, h ⟨_, ne.some_spec, hi⟩, mt mem_bUnion_iff.1 h⟩,
simp only [this] }
end
lemma find_apply_of_mem {c : set (partial_refinement u s)} (hc : chain (≤) c) (ne : c.nonempty)
{i v} (hv : v ∈ c) (hi : i ∈ carrier v) :
find c ne i i = v i :=
apply_eq_of_chain hc (find_mem _ _) hv
((mem_find_carrier_iff _).2 $ mem_bUnion_iff.2 ⟨v, hv, hi⟩) hi
/-- Least upper bound of a nonempty chain of partial refinements. -/
def chain_Sup (c : set (partial_refinement u s)) (hc : chain (≤) c)
(ne : c.nonempty) (hfin : ∀ x ∈ s, finite {i | x ∈ u i}) (hU : s ⊆ ⋃ i, u i) :
partial_refinement u s :=
begin
refine ⟨λ i, find c ne i i, chain_Sup_carrier c,
λ i, (find _ _ _).is_open i,
λ x hxs, mem_Union.2 _,
λ i hi, (find c ne i).closure_subset ((mem_find_carrier_iff _).2 hi),
λ i hi, (find c ne i).apply_eq (mt (mem_find_carrier_iff _).1 hi)⟩,
rcases em (∃ i ∉ chain_Sup_carrier c, x ∈ u i) with ⟨i, hi, hxi⟩|hx,
{ use i,
rwa (find c ne i).apply_eq (mt (mem_find_carrier_iff _).1 hi) },
{ simp_rw [not_exists, not_imp_not, chain_Sup_carrier, mem_bUnion_iff] at hx,
haveI : nonempty (partial_refinement u s) := ⟨ne.some⟩,
choose! v hvc hiv using hx,
rcases (hfin x hxs).exists_maximal_wrt v _ (mem_Union.1 (hU hxs))
with ⟨i, hxi : x ∈ u i, hmax : ∀ j, x ∈ u j → v i ≤ v j → v i = v j⟩,
rcases mem_Union.1 ((v i).subset_Union hxs) with ⟨j, hj⟩,
use j,
have hj' : x ∈ u j := (v i).subset _ hj,
have : v j ≤ v i,
from (hc.total_of_refl (hvc _ hxi) (hvc _ hj')).elim (λ h, (hmax j hj' h).ge) id,
rwa find_apply_of_mem hc ne (hvc _ hxi) (this.1 $ hiv _ hj') }
end
/-- `chain_Sup hu c hc ne hfin hU` is an upper bound of the chain `c`. -/
lemma le_chain_Sup {c : set (partial_refinement u s)} (hc : chain (≤) c)
(ne : c.nonempty) (hfin : ∀ x ∈ s, finite {i | x ∈ u i}) (hU : s ⊆ ⋃ i, u i)
{v} (hv : v ∈ c) :
v ≤ chain_Sup c hc ne hfin hU :=
⟨λ i hi, mem_bUnion hv hi, λ i hi, (find_apply_of_mem hc _ hv hi).symm⟩
/-- If `s` is a closed set, `v` is a partial refinement, and `i` is an index such that
`i ∉ v.carrier`, then there exists a partial refinement that is strictly greater than `v`. -/
lemma exists_gt (v : partial_refinement u s) (hs : is_closed s) (i : ι) (hi : i ∉ v.carrier) :
∃ v' : partial_refinement u s, v < v' :=
begin
have I : s ∩ (⋂ j ≠ i, (v j)ᶜ) ⊆ v i,
{ simp only [subset_def, mem_inter_eq, mem_Inter, and_imp],
intros x hxs H,
rcases mem_Union.1 (v.subset_Union hxs) with ⟨j, hj⟩,
exact (em (j = i)).elim (λ h, h ▸ hj) (λ h, (H j h hj).elim) },
have C : is_closed (s ∩ (⋂ j ≠ i, (v j)ᶜ)),
from is_closed_inter hs (is_closed_bInter $ λ _ _, is_closed_compl_iff.2 $ v.is_open _),
rcases normal_exists_closure_subset C (v.is_open i) I with ⟨vi, ovi, hvi, cvi⟩,
refine ⟨⟨update v i vi, insert i v.carrier, _, _, _, _⟩, _, _⟩,
{ intro j, by_cases h : j = i; simp [h, ovi, v.is_open] },
{ refine λ x hx, mem_Union.2 _,
rcases em (∃ j ≠ i, x ∈ v j) with ⟨j, hji, hj⟩|h,
{ use j, rwa update_noteq hji },
{ push_neg at h, use i, rw update_same, exact hvi ⟨hx, mem_bInter h⟩ } },
{ rintro j (rfl|hj),
{ rwa [update_same, ← v.apply_eq hi] },
{ rw update_noteq (ne_of_mem_of_not_mem hj hi), exact v.closure_subset hj } },
{ intros j hj,
rw [mem_insert_iff, not_or_distrib] at hj,
rw [update_noteq hj.1, v.apply_eq hj.2] },
{ refine ⟨subset_insert _ _, λ j hj, _⟩,
exact (update_noteq (ne_of_mem_of_not_mem hj hi) _ _).symm },
{ exact λ hle, hi (hle.1 $ mem_insert _ _) }
end
end partial_refinement
end shrinking_lemma
open shrinking_lemma
variables {u : ι → set X} {s : set X}
/-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk"
to a new open cover so that the closure of each new open set is contained in the corresponding
original open set. -/
lemma exists_subset_Union_closure_subset (hs : is_closed s) (uo : ∀ i, is_open (u i))
(uf : ∀ x ∈ s, finite {i | x ∈ u i}) (us : s ⊆ ⋃ i, u i) :
∃ v : ι → set X, s ⊆ Union v ∧ ∀ i, is_open (v i) ∧ closure (v i) ⊆ u i :=
begin
classical,
haveI : nonempty (partial_refinement u s) := ⟨⟨u, ∅, uo, us, λ _, false.elim, λ _ _, rfl⟩⟩,
have : ∀ c : set (partial_refinement u s), chain (≤) c → c.nonempty → ∃ ub, ∀ v ∈ c, v ≤ ub,
from λ c hc ne, ⟨partial_refinement.chain_Sup c hc ne uf us,
λ v hv, partial_refinement.le_chain_Sup _ _ _ _ hv⟩,
rcases zorn_nonempty_partial_order this with ⟨v, hv⟩,
suffices : ∀ i, i ∈ v.carrier,
from ⟨v, v.subset_Union, λ i, ⟨v.is_open _, v.closure_subset (this i)⟩⟩,
contrapose! hv,
rcases hv with ⟨i, hi⟩,
rcases v.exists_gt hs i hi with ⟨v', hlt⟩,
exact ⟨v', hlt.le, hlt.ne'⟩
end
/-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk"
to a new open cover so that the closure of each new open set is contained in the corresponding
original open set. -/
lemma exists_Union_eq_closure_subset (uo : ∀ i, is_open (u i)) (uf : ∀ x, finite {i | x ∈ u i})
(uU : (⋃ i, u i) = univ) :
∃ v : ι → set X, Union v = univ ∧ ∀ i, is_open (v i) ∧ closure (v i) ⊆ u i :=
let ⟨v, vU, hv⟩ := exists_subset_Union_closure_subset is_closed_univ uo (λ x _, uf x) uU.ge
in ⟨v, univ_subset_iff.1 vU, hv⟩
|
f51fc5e622c8c7ab361db8bf8f117e895c40c3a6 | 5749d8999a76f3a8fddceca1f6941981e33aaa96 | /src/ring_theory/localization.lean | fc612f58f95d043049f88876b5954605b77b9f2d | [
"Apache-2.0"
] | permissive | jdsalchow/mathlib | 13ab43ef0d0515a17e550b16d09bd14b76125276 | 497e692b946d93906900bb33a51fd243e7649406 | refs/heads/master | 1,585,819,143,348 | 1,580,072,892,000 | 1,580,072,892,000 | 154,287,128 | 0 | 0 | Apache-2.0 | 1,540,281,610,000 | 1,540,281,609,000 | null | UTF-8 | Lean | false | false | 24,520 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Johan Commelin
-/
import tactic.ring data.quot data.equiv.algebra ring_theory.ideal_operations group_theory.submonoid
universes u v
namespace localization
variables (α : Type u) [comm_ring α] (S : set α) [is_submonoid S]
def r (x y : α × S) : Prop :=
∃ t ∈ S, ((x.2 : α) * y.1 - y.2 * x.1) * t = 0
local infix ≈ := r α S
section
variables {α S}
theorem r_of_eq {a₀ a₁ : α × S} (h : (a₀.2 : α) * a₁.1 = a₁.2 * a₀.1) : a₀ ≈ a₁ :=
⟨1, is_submonoid.one_mem S, by rw [h, sub_self, mul_one]⟩
end
theorem refl (x : α × S) : x ≈ x := r_of_eq rfl
theorem symm (x y : α × S) : x ≈ y → y ≈ x :=
λ ⟨t, hts, ht⟩, ⟨t, hts, by rw [← neg_sub, ← neg_mul_eq_neg_mul, ht, neg_zero]⟩
theorem trans : ∀ (x y z : α × S), x ≈ y → y ≈ z → x ≈ z :=
λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨t, hts, ht⟩ ⟨t', hts', ht'⟩,
⟨s₂ * t' * t, is_submonoid.mul_mem (is_submonoid.mul_mem hs₂ hts') hts,
calc (s₁ * r₃ - s₃ * r₁) * (s₂ * t' * t) =
t' * s₃ * ((s₁ * r₂ - s₂ * r₁) * t) + t * s₁ * ((s₂ * r₃ - s₃ * r₂) * t') :
by simp [mul_left_comm, mul_add, mul_comm]
... = 0 : by simp only [subtype.coe_mk] at ht ht'; rw [ht, ht']; simp⟩
instance : setoid (α × S) :=
⟨r α S, refl α S, symm α S, trans α S⟩
end localization
/-- The localization of a ring at a submonoid:
the elements of the submonoid become invertible in the localization.-/
def localization (α : Type u) [comm_ring α] (S : set α) [is_submonoid S] :=
quotient $ localization.setoid α S
namespace localization
variables (α : Type u) [comm_ring α] (S : set α) [is_submonoid S]
instance : has_add (localization α S) :=
⟨quotient.lift₂
(λ x y : α × S, (⟦⟨x.2 * y.1 + y.2 * x.1, x.2 * y.2⟩⟧ : localization α S)) $
λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩,
quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅,
calc (s₁ * s₂ * (s₃ * r₄ + s₄ * r₃) - s₃ * s₄ * (s₁ * r₂ + s₂ * r₁)) * (t₆ * t₅) =
s₁ * s₃ * ((s₂ * r₄ - s₄ * r₂) * t₆) * t₅ + s₂ * s₄ * ((s₁ * r₃ - s₃ * r₁) * t₅) * t₆ : by ring
... = 0 : by simp only [subtype.coe_mk] at ht₅ ht₆; rw [ht₆, ht₅]; simp⟩⟩
instance : has_neg (localization α S) :=
⟨quotient.lift (λ x : α × S, (⟦⟨-x.1, x.2⟩⟧ : localization α S)) $
λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩,
quotient.sound ⟨t, hts,
calc (s₁ * -r₂ - s₂ * -r₁) * t = -((s₁ * r₂ - s₂ * r₁) * t) : by ring
... = 0 : by simp only [subtype.coe_mk] at ht; rw ht; simp⟩⟩
instance : has_mul (localization α S) :=
⟨quotient.lift₂
(λ x y : α × S, (⟦⟨x.1 * y.1, x.2 * y.2⟩⟧ : localization α S)) $
λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩,
quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅,
calc ((s₁ * s₂) * (r₃ * r₄) - (s₃ * s₄) * (r₁ * r₂)) * (t₆ * t₅) =
t₆ * ((s₁ * r₃ - s₃ * r₁) * t₅) * r₂ * s₄ + t₅ * ((s₂ * r₄ - s₄ * r₂) * t₆) * r₃ * s₁ :
by simp [mul_left_comm, mul_add, mul_comm]
... = 0 : by simp only [subtype.coe_mk] at ht₅ ht₆; rw [ht₅, ht₆]; simp⟩⟩
variables {α S}
def mk (r : α) (s : S) : localization α S := ⟦(r, s)⟧
/-- The natural map from the ring to the localization.-/
def of (r : α) : localization α S := mk r 1
instance : comm_ring (localization α S) :=
by refine
{ add := has_add.add,
add_assoc := λ m n k, quotient.induction_on₃ m n k _,
zero := of 0,
zero_add := quotient.ind _,
add_zero := quotient.ind _,
neg := has_neg.neg,
add_left_neg := quotient.ind _,
add_comm := quotient.ind₂ _,
mul := has_mul.mul,
mul_assoc := λ m n k, quotient.induction_on₃ m n k _,
one := of 1,
one_mul := quotient.ind _,
mul_one := quotient.ind _,
left_distrib := λ m n k, quotient.induction_on₃ m n k _,
right_distrib := λ m n k, quotient.induction_on₃ m n k _,
mul_comm := quotient.ind₂ _ };
{ intros,
try {rcases a with ⟨r₁, s₁, hs₁⟩},
try {rcases b with ⟨r₂, s₂, hs₂⟩},
try {rcases c with ⟨r₃, s₃, hs₃⟩},
refine (quotient.sound $ r_of_eq _),
simp [mul_left_comm, mul_add, mul_comm] }
instance of.is_ring_hom : is_ring_hom (of : α → localization α S) :=
{ map_add := λ x y, quotient.sound $ by simp,
map_mul := λ x y, quotient.sound $ by simp,
map_one := rfl }
variables {S}
instance : has_coe_t α (localization α S) := ⟨of⟩ -- note [use has_coe_t]
instance coe.is_ring_hom : is_ring_hom (coe : α → localization α S) :=
localization.of.is_ring_hom
/-- The natural map from the submonoid to the unit group of the localization.-/
def to_units (s : S) : units (localization α S) :=
{ val := s,
inv := mk 1 s,
val_inv := quotient.sound $ r_of_eq $ mul_assoc _ _ _,
inv_val := quotient.sound $ r_of_eq $ show s.val * 1 * 1 = 1 * (1 * s.val), by simp }
@[simp] lemma to_units_coe (s : S) : ((to_units s) : localization α S) = s := rfl
section
variables (α S) (x y : α) (n : ℕ)
@[simp] lemma of_zero : (of 0 : localization α S) = 0 := rfl
@[simp] lemma of_one : (of 1 : localization α S) = 1 := rfl
@[simp] lemma of_add : (of (x + y) : localization α S) = of x + of y :=
by apply is_ring_hom.map_add
@[simp] lemma of_sub : (of (x - y) : localization α S) = of x - of y :=
by apply is_ring_hom.map_sub
@[simp] lemma of_mul : (of (x * y) : localization α S) = of x * of y :=
by apply is_ring_hom.map_mul
@[simp] lemma of_neg : (of (-x) : localization α S) = -of x :=
by apply is_ring_hom.map_neg
@[simp] lemma of_pow : (of (x ^ n) : localization α S) = (of x) ^ n :=
by apply is_semiring_hom.map_pow
@[simp] lemma of_is_unit (s : S) : is_unit (of s : localization α S) :=
is_unit_unit $ to_units s
@[simp] lemma of_is_unit' (s ∈ S) : is_unit (of s : localization α S) :=
is_unit_unit $ to_units ⟨s, ‹s ∈ S›⟩
@[simp] lemma coe_zero : ((0 : α) : localization α S) = 0 := rfl
@[simp] lemma coe_one : ((1 : α) : localization α S) = 1 := rfl
@[simp] lemma coe_add : (↑(x + y) : localization α S) = x + y := of_add _ _ _ _
@[simp] lemma coe_sub : (↑(x - y) : localization α S) = x - y := of_sub _ _ _ _
@[simp] lemma coe_mul : (↑(x * y) : localization α S) = x * y := of_mul _ _ _ _
@[simp] lemma coe_neg : (↑(-x) : localization α S) = -x := of_neg _ _ _
@[simp] lemma coe_pow : (↑(x ^ n) : localization α S) = x ^ n := of_pow _ _ _ _
@[simp] lemma coe_is_unit (s : S) : is_unit (s : localization α S) := of_is_unit _ _ _
@[simp] lemma coe_is_unit' (s ∈ S) : is_unit (s : localization α S) := of_is_unit' _ _ _ ‹s ∈ S›
end
@[simp] lemma mk_self {x : α} {hx : x ∈ S} :
(mk x ⟨x, hx⟩ : localization α S) = 1 :=
quotient.sound ⟨1, is_submonoid.one_mem S,
by simp only [subtype.coe_mk, is_submonoid.coe_one, mul_one, one_mul, sub_self]⟩
@[simp] lemma mk_self' {s : S} :
(mk s s : localization α S) = 1 :=
by cases s; exact mk_self
@[simp] lemma mk_self'' {s : S} :
(mk s.1 s : localization α S) = 1 :=
mk_self'
@[simp] lemma coe_mul_mk (x y : α) (s : S) :
↑x * mk y s = mk (x * y) s :=
quotient.sound $ r_of_eq $ by rw one_mul
lemma mk_eq_mul_mk_one (r : α) (s : S) :
mk r s = r * mk 1 s :=
by rw [coe_mul_mk, mul_one]
@[simp] lemma mk_mul_mk (x y : α) (s t : S) :
mk x s * mk y t = mk (x * y) (s * t) := rfl
@[simp] lemma mk_mul_cancel_left (r : α) (s : S) :
mk (↑s * r) s = r :=
by rw [mk_eq_mul_mk_one, mul_comm ↑s, coe_mul,
mul_assoc, ← mk_eq_mul_mk_one, mk_self', mul_one]
@[simp] lemma mk_mul_cancel_right (r : α) (s : S) :
mk (r * s) s = r :=
by rw [mul_comm, mk_mul_cancel_left]
@[simp] lemma mk_eq (r : α) (s : S) :
mk r s = r * ((to_units s)⁻¹ : units _) :=
quotient.sound $ by simp
@[elab_as_eliminator]
protected theorem induction_on {C : localization α S → Prop} (x : localization α S)
(ih : ∀ r s, C (mk r s : localization α S)) : C x :=
by rcases x with ⟨r, s⟩; exact ih r s
section
variables {β : Type v} [comm_ring β] {T : set β} [is_submonoid T] (f : α → β) [is_ring_hom f]
@[elab_with_expected_type]
def lift' (g : S → units β) (hg : ∀ s, (g s : β) = f s) (x : localization α S) : β :=
quotient.lift_on x (λ p, f p.1 * ((g p.2)⁻¹ : units β)) $ λ ⟨r₁, s₁⟩ ⟨r₂, s₂⟩ ⟨t, hts, ht⟩,
show f r₁ * ↑(g s₁)⁻¹ = f r₂ * ↑(g s₂)⁻¹, from
calc f r₁ * ↑(g s₁)⁻¹
= (f r₁ * g s₂ + ((g s₁ * f r₂ - g s₂ * f r₁) * g ⟨t, hts⟩) * ↑(g ⟨t, hts⟩)⁻¹)
* ↑(g s₁)⁻¹ * ↑(g s₂)⁻¹ :
by simp only [hg, subtype.coe_mk, (is_ring_hom.map_mul f).symm, (is_ring_hom.map_sub f).symm,
ht, is_ring_hom.map_zero f, zero_mul, add_zero];
rw [is_ring_hom.map_mul f, ← hg, mul_right_comm,
mul_assoc (f r₁), ← units.coe_mul, mul_inv_self];
rw [units.coe_one, mul_one]
... = f r₂ * ↑(g s₂)⁻¹ :
by rw [mul_assoc, mul_assoc, ← units.coe_mul, mul_inv_self, units.coe_one,
mul_one, mul_comm ↑(g s₂), add_sub_cancel'_right];
rw [mul_comm ↑(g s₁), ← mul_assoc, mul_assoc (f r₂), ← units.coe_mul,
mul_inv_self, units.coe_one, mul_one]
instance lift'.is_ring_hom (g : S → units β) (hg : ∀ s, (g s : β) = f s) :
is_ring_hom (localization.lift' f g hg) :=
{ map_one := have g 1 = 1, from units.ext (by rw hg; exact is_ring_hom.map_one f),
show f 1 * ↑(g 1)⁻¹ = 1, by rw [this, one_inv, units.coe_one, mul_one, is_ring_hom.map_one f],
map_mul := λ x y, localization.induction_on x $ λ r₁ s₁,
localization.induction_on y $ λ r₂ s₂,
have g (s₁ * s₂) = g s₁ * g s₂,
from units.ext (by simp only [hg, units.coe_mul]; exact is_ring_hom.map_mul f),
show _ * ↑(g (_ * _))⁻¹ = (_ * _) * (_ * _),
by simp only [subtype.coe_mk, mul_one, one_mul, subtype.coe_eta, this, mul_inv_rev];
rw [is_ring_hom.map_mul f, units.coe_mul, ← mul_assoc, ← mul_assoc];
simp only [mul_right_comm],
map_add := λ x y, localization.induction_on x $ λ r₁ s₁,
localization.induction_on y $ λ r₂ s₂,
have g (s₁ * s₂) = g s₁ * g s₂,
from units.ext (by simp only [hg, units.coe_mul]; exact is_ring_hom.map_mul f),
show _ * ↑(g (_ * _))⁻¹ = _ * _ + _ * _,
by simp only [subtype.coe_mk, mul_one, one_mul, subtype.coe_eta, this, mul_inv_rev];
simp only [is_ring_hom.map_mul f, is_ring_hom.map_add f, add_mul, (hg _).symm];
simp only [mul_assoc, mul_comm, mul_left_comm, (units.coe_mul _ _).symm];
rw [mul_inv_cancel_left, mul_left_comm, ← mul_assoc, mul_inv_cancel_right, add_comm] }
noncomputable def lift (h : ∀ s ∈ S, is_unit (f s)) :
localization α S → β :=
localization.lift' f (λ s, classical.some $ h s.1 s.2)
(λ s, by rw [← classical.some_spec (h s.1 s.2)]; refl)
instance lift.is_ring_hom (h : ∀ s ∈ S, is_unit (f s)) :
is_ring_hom (lift f h) :=
lift'.is_ring_hom _ _ _
@[simp] lemma lift'_mk (g : S → units β) (hg : ∀ s, (g s : β) = f s) (r : α) (s : S) :
lift' f g hg (mk r s) = f r * ↑(g s)⁻¹ := rfl
@[simp] lemma lift'_of (g : S → units β) (hg : ∀ s, (g s : β) = f s) (a : α) :
lift' f g hg (of a) = f a :=
have g 1 = 1, from units.ext_iff.2 $ by simp [hg, is_ring_hom.map_one f],
by simp [lift', quotient.lift_on_beta, of, mk, this]
@[simp] lemma lift'_coe (g : S → units β) (hg : ∀ s, (g s : β) = f s) (a : α) :
lift' f g hg a = f a := lift'_of _ _ _ _
@[simp] lemma lift_of (h : ∀ s ∈ S, is_unit (f s)) (a : α) :
lift f h (of a) = f a := lift'_of _ _ _ _
@[simp] lemma lift_coe (h : ∀ s ∈ S, is_unit (f s)) (a : α) :
lift f h a = f a := lift'_of _ _ _ _
@[simp] lemma lift'_comp_of (g : S → units β) (hg : ∀ s, (g s : β) = f s) :
lift' f g hg ∘ of = f := funext $ λ a, lift'_of _ _ _ a
@[simp] lemma lift_comp_of (h : ∀ s ∈ S, is_unit (f s)) :
lift f h ∘ of = f := lift'_comp_of _ _ _
@[simp] lemma lift'_apply_coe (f : localization α S → β) [is_ring_hom f]
(g : S → units β) (hg : ∀ s, (g s : β) = f s) :
lift' (λ a : α, f a) g hg = f :=
have g = (λ s, (units.map' f : units (localization α S) → units β) (to_units s)),
from funext $ λ x, units.ext $ (hg x).symm ▸ rfl,
funext $ λ x, localization.induction_on x
(λ r s, by subst this; rw [lift'_mk, ← (units.map' f).map_inv, units.coe_map'];
simp [is_ring_hom.map_mul f])
@[simp] lemma lift_apply_coe (f : localization α S → β) [is_ring_hom f] :
lift (λ a : α, f a)
(λ s hs, is_unit.map' f (is_unit_unit (to_units ⟨s, hs⟩))) = f :=
by rw [lift, lift'_apply_coe]
/-- Function extensionality for localisations:
two functions are equal if they agree on elements that are coercions.-/
protected lemma funext (f g : localization α S → β) [is_ring_hom f] [is_ring_hom g]
(h : ∀ a : α, f a = g a) : f = g :=
begin
rw [← lift_apply_coe f, ← lift_apply_coe g],
congr' 1,
exact funext h
end
variables {α S T}
def map (hf : ∀ s ∈ S, f s ∈ T) : localization α S → localization β T :=
lift' (of ∘ f) (to_units ∘ subtype.map f hf) (λ s, rfl)
instance map.is_ring_hom (hf : ∀ s ∈ S, f s ∈ T) : is_ring_hom (map f hf) :=
lift'.is_ring_hom _ _ _
@[simp] lemma map_of (hf : ∀ s ∈ S, f s ∈ T) (a : α) :
map f hf (of a) = of (f a) := lift'_of _ _ _ _
@[simp] lemma map_coe (hf : ∀ s ∈ S, f s ∈ T) (a : α) :
map f hf a = (f a) := lift'_of _ _ _ _
@[simp] lemma map_comp_of (hf : ∀ s ∈ S, f s ∈ T) :
map f hf ∘ of = of ∘ f := funext $ λ a, map_of _ _ _
@[simp] lemma map_id : map id (λ s (hs : s ∈ S), hs) = id :=
localization.funext _ _ $ map_coe _ _
lemma map_comp_map {γ : Type*} [comm_ring γ] (hf : ∀ s ∈ S, f s ∈ T) (U : set γ)
[is_submonoid U] (g : β → γ) [is_ring_hom g] (hg : ∀ t ∈ T, g t ∈ U) :
map g hg ∘ map f hf = map (λ x, g (f x)) (λ s hs, hg _ (hf _ hs)) :=
localization.funext _ _ $ by simp
lemma map_map {γ : Type*} [comm_ring γ] (hf : ∀ s ∈ S, f s ∈ T) (U : set γ)
[is_submonoid U] (g : β → γ) [is_ring_hom g] (hg : ∀ t ∈ T, g t ∈ U) (x) :
map g hg (map f hf x) = map (λ x, g (f x)) (λ s hs, hg _ (hf _ hs)) x :=
congr_fun (map_comp_map _ _ _ _ _) x
def equiv_of_equiv (h₁ : α ≃+* β) (h₂ : h₁ '' S = T) :
localization α S ≃+* localization β T :=
{ to_fun := map h₁ $ λ s hs, h₂ ▸ set.mem_image_of_mem _ hs,
inv_fun := map h₁.symm $ λ t ht,
by simp [h₁.image_eq_preimage, set.preimage, set.ext_iff, *] at *,
left_inv := λ _, by simp only [map_map, h₁.symm_apply_apply]; erw map_id; refl,
right_inv := λ _, by simp only [map_map, h₁.apply_symm_apply]; erw map_id; refl,
map_mul' := λ _ _, is_ring_hom.map_mul _,
map_add' := λ _ _, is_ring_hom.map_add _ }
end
section away
variables {β : Type v} [comm_ring β] (f : α → β) [is_ring_hom f]
@[reducible] def away (x : α) := localization α (powers x)
@[simp] def away.inv_self (x : α) : away x :=
mk 1 ⟨x, 1, pow_one x⟩
@[elab_with_expected_type]
noncomputable def away.lift {x : α} (hfx : is_unit (f x)) : away x → β :=
localization.lift' f (λ s, classical.some hfx ^ classical.some s.2) $ λ s,
by rw [units.coe_pow, ← classical.some_spec hfx,
← is_semiring_hom.map_pow f, classical.some_spec s.2]; refl
instance away.lift.is_ring_hom {x : α} (hfx : is_unit (f x)) :
is_ring_hom (localization.away.lift f hfx) :=
lift'.is_ring_hom _ _ _
@[simp] lemma away.lift_of {x : α} (hfx : is_unit (f x)) (a : α) :
away.lift f hfx (of a) = f a := lift'_of _ _ _ _
@[simp] lemma away.lift_coe {x : α} (hfx : is_unit (f x)) (a : α) :
away.lift f hfx a = f a := lift'_of _ _ _ _
@[simp] lemma away.lift_comp_of {x : α} (hfx : is_unit (f x)) :
away.lift f hfx ∘ of = f := lift'_comp_of _ _ _
noncomputable def away_to_away_right (x y : α) : away x → away (x * y) :=
localization.away.lift coe $
is_unit_of_mul_one x (y * away.inv_self (x * y)) $
by rw [away.inv_self, coe_mul_mk, coe_mul_mk, mul_one, mk_self]
instance away_to_away_right.is_ring_hom (x y : α) :
is_ring_hom (away_to_away_right x y) :=
away.lift.is_ring_hom _ _
end away
section at_prime
variables (P : ideal α) [hp : ideal.is_prime P]
include hp
instance prime.is_submonoid :
is_submonoid (-P : set α) :=
{ one_mem := P.ne_top_iff_one.1 hp.1,
mul_mem := λ x y hnx hny hxy, or.cases_on (hp.2 hxy) hnx hny }
@[reducible] def at_prime := localization α (-P)
instance at_prime.local_ring : local_ring (at_prime P) :=
local_of_nonunits_ideal
(λ hze,
let ⟨t, hts, ht⟩ := quotient.exact hze in
hts $ have htz : t = 0, by simpa using ht,
suffices (0:α) ∈ P, by rwa htz,
P.zero_mem)
(begin
rintro ⟨⟨r₁, s₁, hs₁⟩⟩ ⟨⟨r₂, s₂, hs₂⟩⟩ hx hy hu,
rcases is_unit_iff_exists_inv.1 hu with ⟨⟨⟨r₃, s₃, hs₃⟩⟩, hz⟩,
rcases quotient.exact hz with ⟨t, hts, ht⟩,
simp at ht,
have : ∀ {r s hs}, (⟦⟨r, s, hs⟩⟧ : at_prime P) ∈ nonunits (at_prime P) → r ∈ P,
{ haveI := classical.dec,
exact λ r s hs, not_imp_comm.1 (λ nr,
is_unit_iff_exists_inv.2 ⟨⟦⟨s, r, nr⟩⟧,
quotient.sound $ r_of_eq $ by simp [mul_comm]⟩) },
have hr₃ := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right hts,
have := (ideal.add_mem_iff_left _ _).1 hr₃,
{ exact not_or (mt hp.mem_or_mem (not_or hs₁ hs₂)) hs₃ (hp.mem_or_mem this) },
{ exact P.neg_mem (P.mul_mem_right
(P.add_mem (P.mul_mem_left (this hy)) (P.mul_mem_left (this hx)))) }
end)
end at_prime
variable (α)
def non_zero_divisors : set α := {x | ∀ z, z * x = 0 → z = 0}
instance non_zero_divisors.is_submonoid : is_submonoid (non_zero_divisors α) :=
{ one_mem := λ z hz, by rwa mul_one at hz,
mul_mem := λ x₁ x₂ hx₁ hx₂ z hz,
have z * x₁ * x₂ = 0, by rwa mul_assoc,
hx₁ z $ hx₂ (z * x₁) this }
@[simp] lemma non_zero_divisors_one_val : (1 : non_zero_divisors α).val = 1 := rfl
/-- The field of fractions of an integral domain.-/
@[reducible] def fraction_ring := localization α (non_zero_divisors α)
namespace fraction_ring
open function
variables {β : Type u} [integral_domain β] [decidable_eq β]
lemma eq_zero_of_ne_zero_of_mul_eq_zero {x y : β} :
x ≠ 0 → y * x = 0 → y = 0 :=
λ hnx hxy, or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx
lemma mem_non_zero_divisors_iff_ne_zero {x : β} :
x ∈ non_zero_divisors β ↔ x ≠ 0 :=
⟨λ hm hz, zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm,
λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx⟩
variable (β)
def inv_aux (x : β × (non_zero_divisors β)) : fraction_ring β :=
if h : x.1 = 0 then 0 else ⟦⟨x.2, x.1, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧
instance : has_inv (fraction_ring β) :=
⟨quotient.lift (inv_aux β) $
λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩,
begin
have hrs : s₁ * r₂ = 0 + s₂ * r₁,
from sub_eq_iff_eq_add.1 (hts _ ht),
by_cases hr₁ : r₁ = 0;
by_cases hr₂ : r₂ = 0;
simp [hr₁, hr₂] at hrs;
simp only [inv_aux, hr₁, hr₂, dif_pos, dif_neg, not_false_iff, subtype.coe_mk, quotient.eq],
{ exfalso,
exact mem_non_zero_divisors_iff_ne_zero.mp hs₁ hrs },
{ exfalso,
exact mem_non_zero_divisors_iff_ne_zero.mp hs₂ hrs },
{ apply r_of_eq,
simpa [mul_comm] using hrs.symm }
end⟩
lemma mk_inv {r s} :
(mk r s : fraction_ring β)⁻¹ =
if h : r = 0 then 0 else ⟦⟨s, r, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧ := rfl
lemma mk_inv' :
∀ (x : β × (non_zero_divisors β)), (⟦x⟧⁻¹ : fraction_ring β) =
if h : x.1 = 0 then 0 else ⟦⟨x.2.val, x.1, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧
| ⟨r,s,hs⟩ := rfl
instance : decidable_eq (fraction_ring β) :=
@quotient.decidable_eq (β × non_zero_divisors β) (localization.setoid β (non_zero_divisors β)) $
λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩, show decidable (∃ t ∈ non_zero_divisors β, (s₁ * r₂ - s₂ * r₁) * t = 0),
from decidable_of_iff (s₁ * r₂ - s₂ * r₁ = 0)
⟨λ H, ⟨1, λ y, (mul_one y).symm ▸ id, H.symm ▸ zero_mul _⟩,
λ ⟨t, ht1, ht2⟩, or.resolve_right (mul_eq_zero.1 ht2) $ λ ht,
one_ne_zero (ht1 1 ((one_mul t).symm ▸ ht))⟩
instance : discrete_field (fraction_ring β) :=
by refine
{ inv := has_inv.inv,
zero_ne_one := λ hzo,
let ⟨t, hts, ht⟩ := quotient.exact hzo in
zero_ne_one (by simpa using hts _ ht : 0 = 1),
mul_inv_cancel := quotient.ind _,
inv_mul_cancel := quotient.ind _,
has_decidable_eq := fraction_ring.decidable_eq β,
inv_zero := dif_pos rfl,
.. localization.comm_ring };
{ intros x hnx,
rcases x with ⟨x, z, hz⟩,
have : x ≠ 0,
from assume hx, hnx (quotient.sound $ r_of_eq $ by simp [hx]),
simp only [has_inv.inv, inv_aux, quotient.lift_beta, dif_neg this],
exact (quotient.sound $ r_of_eq $ by simp [mul_comm]) }
@[simp] lemma mk_eq_div {r s} : (mk r s : fraction_ring β) = (r / s : fraction_ring β) :=
show _ = _ * dite (s.1 = 0) _ _, by rw [dif_neg (mem_non_zero_divisors_iff_ne_zero.mp s.2)];
exact localization.mk_eq_mul_mk_one _ _
variables {β}
@[simp] lemma mk_eq_div' (x : β × (non_zero_divisors β)) :
(⟦x⟧ : fraction_ring β) = ((x.1) / ((x.2).val) : fraction_ring β) :=
by erw ← mk_eq_div; cases x; refl
lemma eq_zero_of (x : β) (h : (of x : fraction_ring β) = 0) : x = 0 :=
begin
rcases quotient.exact h with ⟨t, ht, ht'⟩,
simpa [mem_non_zero_divisors_iff_ne_zero.mp ht] using ht'
end
lemma of.injective : function.injective (of : β → fraction_ring β) :=
(is_add_group_hom.injective_iff _).mpr eq_zero_of
section map
open function is_ring_hom
variables {A : Type u} [integral_domain A] [decidable_eq A]
variables {B : Type v} [integral_domain B] [decidable_eq B]
variables (f : A → B) [is_ring_hom f]
def map (hf : injective f) : fraction_ring A → fraction_ring B :=
localization.map f $ λ s h,
by rw [mem_non_zero_divisors_iff_ne_zero, ← map_zero f, ne.def, hf.eq_iff];
exact mem_non_zero_divisors_iff_ne_zero.1 h
@[simp] lemma map_of (hf : injective f) (a : A) : map f hf (of a) = of (f a) :=
localization.map_of _ _ _
@[simp] lemma map_coe (hf : injective f) (a : A) : map f hf a = f a :=
localization.map_coe _ _ _
@[simp] lemma map_comp_of (hf : injective f) :
map f hf ∘ (of : A → fraction_ring A) = (of : B → fraction_ring B) ∘ f :=
localization.map_comp_of _ _
instance map.is_ring_hom (hf : injective f) : is_ring_hom (map f hf) :=
localization.map.is_ring_hom _ _
def equiv_of_equiv (h : A ≃+* B) : fraction_ring A ≃+* fraction_ring B :=
localization.equiv_of_equiv h
begin
ext b,
rw [h.image_eq_preimage, set.preimage, set.mem_set_of_eq,
mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero, ne.def],
exact h.symm.map_ne_zero_iff
end
end map
end fraction_ring
section ideals
theorem map_comap (J : ideal (localization α S)) :
ideal.map coe (ideal.comap (coe : α → localization α S) J) = J :=
le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x,
localization.induction_on x $ λ r s hJ, (submodule.mem_coe _).2 $
mul_one r ▸ coe_mul_mk r 1 s ▸ (ideal.mul_mem_right _ $ ideal.mem_map_of_mem $
have _ := @ideal.mul_mem_left (localization α S) _ _ s _ hJ,
by rwa [coe_coe, coe_mul_mk, mk_mul_cancel_left] at this)
def le_order_embedding :
((≤) : ideal (localization α S) → ideal (localization α S) → Prop) ≼o
((≤) : ideal α → ideal α → Prop) :=
{ to_fun := λ J, ideal.comap coe J,
inj := function.injective_of_left_inverse (map_comap α),
ord := λ J₁ J₂, ⟨ideal.comap_mono, λ hJ,
map_comap α J₁ ▸ map_comap α J₂ ▸ ideal.map_mono hJ⟩ }
end ideals
end localization
|
d26d1cc71f1886061bca2aa92b082b46bf702ec2 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /archive/imo/imo1998_q2.lean | 559b381b4c9345664f8b490b0abfac2da663af95 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 9,503 | lean | /-
Copyright (c) 2020 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import data.fintype.basic
import data.int.parity
import algebra.big_operators.order
import tactic.ring
import tactic.noncomm_ring
/-!
# IMO 1998 Q2
In a competition, there are `a` contestants and `b` judges, where `b ≥ 3` is an odd integer. Each
judge rates each contestant as either "pass" or "fail". Suppose `k` is a number such that, for any
two judges, their ratings coincide for at most `k` contestants. Prove that `k / a ≥ (b - 1) / (2b)`.
## Solution
The problem asks us to think about triples consisting of a contestant and two judges whose ratings
agree for that contestant. We thus consider the subset `A ⊆ C × JJ` of all such incidences of
agreement, where `C` and `J` are the sets of contestants and judges, and `JJ = J × J - {(j, j)}`. We
have natural maps: `left : A → C` and `right: A → JJ`. We count the elements of `A` in two ways: as
the sum of the cardinalities of the fibres of `left` and as the sum of the cardinalities of the
fibres of `right`. We obtain an upper bound on the cardinality of `A` from the count for `right`,
and a lower bound from the count for `left`. These two bounds combine to the required result.
First consider the map `right : A → JJ`. Since the size of any fibre over a point in JJ is bounded
by `k` and since `|JJ| = b^2 - b`, we obtain the upper bound: `|A| ≤ k(b^2-b)`.
Now consider the map `left : A → C`. The fibre over a given contestant `c ∈ C` is the set of
ordered pairs of (distinct) judges who agree about `c`. We seek to bound the cardinality of this
fibre from below. Minimum agreement for a contestant occurs when the judges' ratings are split as
evenly as possible. Since `b` is odd, this occurs when they are divided into groups of size
`(b-1)/2` and `(b+1)/2`. This corresponds to a fibre of cardinality `(b-1)^2/2` and so we obtain
the lower bound: `a(b-1)^2/2 ≤ |A|`.
Rearranging gives the result.
-/
open_locale classical
noncomputable theory
/-- An ordered pair of judges. -/
abbreviation judge_pair (J : Type*) := J × J
/-- A triple consisting of contestant together with an ordered pair of judges. -/
abbreviation agreed_triple (C J : Type*) := C × (judge_pair J)
variables {C J : Type*} (r : C → J → Prop)
/-- The first judge from an ordered pair of judges. -/
abbreviation judge_pair.judge₁ : judge_pair J → J := prod.fst
/-- The second judge from an ordered pair of judges. -/
abbreviation judge_pair.judge₂ : judge_pair J → J := prod.snd
/-- The proposition that the judges in an ordered pair are distinct. -/
abbreviation judge_pair.distinct (p : judge_pair J) := p.judge₁ ≠ p.judge₂
/-- The proposition that the judges in an ordered pair agree about a contestant's rating. -/
abbreviation judge_pair.agree (p : judge_pair J) (c : C) := r c p.judge₁ ↔ r c p.judge₂
/-- The contestant from the triple consisting of a contestant and an ordered pair of judges. -/
abbreviation agreed_triple.contestant : agreed_triple C J → C := prod.fst
/-- The ordered pair of judges from the triple consisting of a contestant and an ordered pair of
judges. -/
abbreviation agreed_triple.judge_pair : agreed_triple C J → judge_pair J := prod.snd
@[simp] lemma judge_pair.agree_iff_same_rating (p : judge_pair J) (c : C) :
p.agree r c ↔ (r c p.judge₁ ↔ r c p.judge₂) := iff.rfl
/-- The set of contestants on which two judges agree. -/
def agreed_contestants [fintype C] (p : judge_pair J) : finset C :=
finset.univ.filter (λ c, p.agree r c)
section
variables [fintype J] [fintype C]
/-- All incidences of agreement. -/
def A : finset (agreed_triple C J) := finset.univ.filter (λ (a : agreed_triple C J),
a.judge_pair.agree r a.contestant ∧ a.judge_pair.distinct)
lemma A_maps_to_off_diag_judge_pair (a : agreed_triple C J) :
a ∈ A r → a.judge_pair ∈ finset.off_diag (@finset.univ J _) :=
by simp [A, finset.mem_off_diag]
lemma A_fibre_over_contestant (c : C) :
finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct) =
((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).image prod.snd :=
begin
ext p,
simp only [A, finset.mem_univ, finset.mem_filter, finset.mem_image, true_and, exists_prop],
split,
{ rintros ⟨h₁, h₂⟩, refine ⟨(c, p), _⟩, finish, },
{ intros h, finish, },
end
lemma A_fibre_over_contestant_card (c : C) :
(finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card =
((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).card :=
by { rw A_fibre_over_contestant r, apply finset.card_image_of_inj_on, tidy, }
lemma A_fibre_over_judge_pair {p : judge_pair J} (h : p.distinct) :
agreed_contestants r p =
((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).image agreed_triple.contestant :=
begin
dunfold A agreed_contestants, ext c, split; intros h,
{ rw finset.mem_image, refine ⟨⟨c, p⟩, _⟩, finish, },
{ finish, },
end
lemma A_fibre_over_judge_pair_card {p : judge_pair J} (h : p.distinct) :
(agreed_contestants r p).card =
((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).card :=
by { rw A_fibre_over_judge_pair r h, apply finset.card_image_of_inj_on, tidy, }
lemma A_card_upper_bound
{k : ℕ} (hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) :
(A r).card ≤ k * ((fintype.card J) * (fintype.card J) - (fintype.card J)) :=
begin
change _ ≤ k * ((finset.card _ ) * (finset.card _ ) - (finset.card _ )),
rw ← finset.off_diag_card,
apply finset.card_le_mul_card_image_of_maps_to (A_maps_to_off_diag_judge_pair r),
intros p hp,
have hp' : p.distinct, { simp [finset.mem_off_diag] at hp, exact hp, },
rw ← A_fibre_over_judge_pair_card r hp', apply hk, exact hp',
end
end
lemma add_sq_add_sq_sub {α : Type*} [ring α] (x y : α) :
(x + y) * (x + y) + (x - y) * (x - y) = 2*x*x + 2*y*y :=
by noncomm_ring
lemma norm_bound_of_odd_sum {x y z : ℤ} (h : x + y = 2*z + 1) :
2*z*z + 2*z + 1 ≤ x*x + y*y :=
begin
suffices : 4*z*z + 4*z + 1 + 1 ≤ 2*x*x + 2*y*y,
{ rw ← mul_le_mul_left (zero_lt_two' ℤ), convert this; ring, },
have h' : (x + y) * (x + y) = 4*z*z + 4*z + 1, { rw h, ring, },
rw [← add_sq_add_sq_sub, h', add_le_add_iff_left],
suffices : 0 < (x - y) * (x - y), { apply int.add_one_le_of_lt this, },
rw [mul_self_pos, sub_ne_zero], apply int.ne_of_odd_add ⟨z, h⟩,
end
section
variables [fintype J]
lemma judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) :
2*z*z + 2*z + 1 ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card :=
begin
let x := (finset.univ.filter (λ j, r c j)).card,
let y := (finset.univ.filter (λ j, ¬ r c j)).card,
have h : (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card = x*x + y*y,
{ simp [← finset.filter_product_card], },
rw h, apply int.le_of_coe_nat_le_coe_nat, simp only [int.coe_nat_add, int.coe_nat_mul],
apply norm_bound_of_odd_sum,
suffices : x + y = 2*z + 1, { simp [← int.coe_nat_add, this], },
rw [finset.filter_card_add_filter_neg_card_eq_card, ← hJ], refl,
end
lemma distinct_judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) :
2*z*z ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card :=
begin
let s := finset.univ.filter (λ (p : judge_pair J), p.agree r c),
let t := finset.univ.filter (λ (p : judge_pair J), p.distinct),
have hs : 2*z*z + 2*z + 1 ≤ s.card, { exact judge_pairs_card_lower_bound r hJ c, },
have hst : s \ t = finset.univ.diag,
{ ext p, split; intros,
{ finish, },
{ suffices : p.judge₁ = p.judge₂, { simp [this], }, finish, }, },
have hst' : (s \ t).card = 2*z + 1, { rw [hst, finset.diag_card, ← hJ], refl, },
rw [finset.filter_and, ← finset.sdiff_sdiff_self_left s t, finset.card_sdiff],
{ rw hst', rw add_assoc at hs, apply le_tsub_of_add_le_right hs, },
{ apply finset.sdiff_subset, },
end
lemma A_card_lower_bound [fintype C] {z : ℕ} (hJ : fintype.card J = 2*z + 1) :
2*z*z * (fintype.card C) ≤ (A r).card :=
begin
have h : ∀ a, a ∈ A r → prod.fst a ∈ @finset.univ C _, { intros, apply finset.mem_univ, },
apply finset.mul_card_image_le_card_of_maps_to h,
intros c hc,
rw ← A_fibre_over_contestant_card,
apply distinct_judge_pairs_card_lower_bound r hJ,
end
end
lemma clear_denominators {a b k : ℕ} (ha : 0 < a) (hb : 0 < b) :
(b - 1 : ℚ) / (2 * b) ≤ k / a ↔ (b - 1) * a ≤ k * (2 * b) :=
by rw div_le_div_iff; norm_cast; simp [ha, hb]
theorem imo1998_q2 [fintype J] [fintype C]
(a b k : ℕ) (hC : fintype.card C = a) (hJ : fintype.card J = b) (ha : 0 < a) (hb : odd b)
(hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) :
(b - 1 : ℚ) / (2 * b) ≤ k / a :=
begin
rw clear_denominators ha hb.pos,
obtain ⟨z, hz⟩ := hb, rw hz at hJ, rw hz,
have h := le_trans (A_card_lower_bound r hJ) (A_card_upper_bound r hk),
rw [hC, hJ] at h,
-- We are now essentially done; we just need to bash `h` into exactly the right shape.
have hl : k * ((2 * z + 1) * (2 * z + 1) - (2 * z + 1)) = (k * (2 * (2 * z + 1))) * z,
{ simp only [add_mul, two_mul, mul_comm, mul_assoc], finish, },
have hr : 2 * z * z * a = 2 * z * a * z, { ring, },
rw [hl, hr] at h,
cases z,
{ simp, },
{ exact le_of_mul_le_mul_right h z.succ_pos, },
end
|
d486d2b7ae2976b94ff83f219c6840d7ad33ca89 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/nateq.lean | ac5723e07b2ceffc3aeea8a81cb2fb2bbfc87e22 | [
"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 | 421 | lean | open bool nat
definition is_eq (a b : nat) : bool :=
nat.rec_on a
(λ b, nat.cases_on b tt (λb₁, ff))
(λ a₁ r₁ b, nat.cases_on b ff (λb₁, r₁ b₁))
b
example : is_eq 3 3 = tt :=
rfl
example : is_eq 3 5 = ff :=
rfl
theorem eq.to_is_eq (a b : nat) (H : a = b) : is_eq a b = tt :=
have aux : is_eq a a = tt, from
nat.rec_on a
rfl
(λ (a₁ : nat) (ih : is_eq a₁ a₁ = tt), ih),
H ▸ aux
|
effdd2a075f50a328ca2df0bae13a1f1a304a589 | d9ed0fce1c218297bcba93e046cb4e79c83c3af8 | /library/init/data/nat/basic.lean | a2d2d7b0a3f10a8ab30a019db6881dfbed0137a6 | [
"Apache-2.0"
] | permissive | leodemoura/lean_clone | 005c63aa892a6492f2d4741ee3c2cb07a6be9d7f | cc077554b584d39bab55c360bc12a6fe7957afe6 | refs/heads/master | 1,610,506,475,484 | 1,482,348,354,000 | 1,482,348,543,000 | 77,091,586 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,197 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Leonardo de Moura
-/
prelude
import init.logic init.data.num.basic
notation `ℕ` := nat
namespace nat
inductive less_than (a : ℕ) : ℕ → Prop
| refl : less_than a
| step : Π {b}, less_than b → less_than (succ b)
instance : has_le ℕ :=
⟨nat.less_than⟩
@[reducible] protected def le (n m : ℕ) := nat.less_than n m
@[reducible] protected def lt (n m : ℕ) := nat.less_than (succ n) m
instance : has_lt ℕ :=
⟨nat.lt⟩
def pred : ℕ → ℕ
| 0 := 0
| (a+1) := a
protected def sub : ℕ → ℕ → ℕ
| a 0 := a
| a (b+1) := pred (sub a b)
protected def mul : nat → nat → nat
| a 0 := 0
| a (b+1) := (mul a b) + a
instance : has_sub ℕ :=
⟨nat.sub⟩
instance : has_mul ℕ :=
⟨nat.mul⟩
instance : decidable_eq ℕ
| zero zero := is_true rfl
| (succ x) zero := is_false (λ h, nat.no_confusion h)
| zero (succ y) := is_false (λ h, nat.no_confusion h)
| (succ x) (succ y) :=
match decidable_eq x y with
| is_true xeqy := is_true (xeqy ▸ eq.refl (succ x))
| is_false xney := is_false (λ h, nat.no_confusion h (λ xeqy, absurd xeqy xney))
end
def {u} repeat {α : Type u} (f : ℕ → α → α) : ℕ → α → α
| 0 a := a
| (succ n) a := f n (repeat n a)
instance : inhabited ℕ :=
⟨nat.zero⟩
@[simp] lemma nat_zero_eq_zero : nat.zero = 0 :=
rfl
/- properties of inequality -/
@[refl] protected def le_refl : ∀ a : ℕ, a ≤ a :=
less_than.refl
lemma le_succ (n : ℕ) : n ≤ succ n :=
less_than.step (nat.le_refl n)
lemma succ_le_succ {n m : ℕ} : n ≤ m → succ n ≤ succ m :=
λ h, less_than.rec (nat.le_refl (succ n)) (λ a b, less_than.step) h
lemma zero_le : ∀ (n : ℕ), 0 ≤ n
| 0 := nat.le_refl 0
| (n+1) := less_than.step (zero_le n)
lemma zero_lt_succ (n : ℕ) : 0 < succ n :=
succ_le_succ (zero_le n)
def succ_pos := zero_lt_succ
lemma not_succ_le_zero : ∀ (n : ℕ), succ n ≤ 0 → false
.
lemma not_lt_zero (a : ℕ) : ¬ a < 0 := not_succ_le_zero a
lemma pred_le_pred {n m : ℕ} : n ≤ m → pred n ≤ pred m :=
λ h, less_than.rec_on h
(nat.le_refl (pred n))
(λ n, nat.rec (λ a b, b) (λ a b c, less_than.step) n)
lemma le_of_succ_le_succ {n m : ℕ} : succ n ≤ succ m → n ≤ m :=
pred_le_pred
instance decidable_le : ∀ a b : ℕ, decidable (a ≤ b)
| 0 b := is_true (zero_le b)
| (a+1) 0 := is_false (not_succ_le_zero a)
| (a+1) (b+1) :=
match decidable_le a b with
| is_true h := is_true (succ_le_succ h)
| is_false h := is_false (λ a, h (le_of_succ_le_succ a))
end
instance decidable_lt : ∀ a b : ℕ, decidable (a < b) :=
λ a b, nat.decidable_le (succ a) b
protected lemma eq_or_lt_of_le {a b : ℕ} (h : a ≤ b) : a = b ∨ a < b :=
less_than.cases_on h (or.inl rfl) (λ n h, or.inr (succ_le_succ h))
lemma lt_succ_of_le {a b : ℕ} : a ≤ b → a < succ b :=
succ_le_succ
@[simp] lemma succ_sub_succ_eq_sub (a b : ℕ) : succ a - succ b = a - b :=
nat.rec_on b
(show succ a - succ zero = a - zero, from (eq.refl (succ a - succ zero)))
(λ b, congr_arg pred)
lemma not_succ_le_self : ∀ n : ℕ, ¬succ n ≤ n :=
λ n, nat.rec (not_succ_le_zero 0) (λ a b c, b (le_of_succ_le_succ c)) n
protected lemma lt_irrefl (n : ℕ) : ¬n < n :=
not_succ_le_self n
protected lemma le_trans {n m k : ℕ} (h1 : n ≤ m) : m ≤ k → n ≤ k :=
less_than.rec h1 (λ p h2, less_than.step)
lemma pred_le : ∀ (n : ℕ), pred n ≤ n
| 0 := less_than.refl 0
| (succ a) := less_than.step (less_than.refl a)
lemma sub_le (a b : ℕ) : a - b ≤ a :=
nat.rec_on b (nat.le_refl (a - 0)) (λ b₁, nat.le_trans (pred_le (a - b₁)))
lemma sub_lt : ∀ {a b : ℕ}, 0 < a → 0 < b → a - b < a
| 0 b h1 h2 := absurd h1 (nat.lt_irrefl 0)
| (a+1) 0 h1 h2 := absurd h2 (nat.lt_irrefl 0)
| (a+1) (b+1) h1 h2 :=
eq.symm (succ_sub_succ_eq_sub a b) ▸
show a - b < succ a, from
lt_succ_of_le (sub_le a b)
protected lemma lt_of_lt_of_le {n m k : ℕ} : n < m → m ≤ k → n < k :=
nat.le_trans
end nat
|
253c20802e5a61fd13c3fa2415602a86df163cd6 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/linear_algebra/finsupp.lean | 3ec06577d567a03580bf5bb75cb4cc01e567e39d | [
"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 | 16,370 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Linear structures on function with finite support `α →₀ β`.
-/
import data.finsupp linear_algebra.basic
noncomputable theory
open lattice set linear_map submodule
namespace finsupp
variables {α : Type*} {β : Type*} {γ : Type*}
variables [decidable_eq α] [decidable_eq β] [ring γ] [add_comm_group β] [module γ β]
def lsingle (a : α) : β →ₗ[γ] (α →₀ β) :=
⟨single a, assume a b, single_add, assume c b, (smul_single _ _ _).symm⟩
def lapply (a : α) : (α →₀ β) →ₗ[γ] β := ⟨λg, g a, assume a b, rfl, assume a b, rfl⟩
section lsubtype_domain
variables (s : set α) [decidable_pred (λx, x ∈ s)]
def lsubtype_domain : (α →₀ β) →ₗ[γ] (s →₀ β) :=
⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩
lemma lsubtype_domain_apply (f : α →₀ β) :
(lsubtype_domain s : (α →₀ β) →ₗ[γ] (s →₀ β)) f = subtype_domain (λx, x ∈ s) f := rfl
end lsubtype_domain
@[simp] lemma lsingle_apply (a : α) (b : β) : (lsingle a : β →ₗ[γ] (α →₀ β)) b = single a b :=
rfl
@[simp] lemma lapply_apply (a : α) (f : α →₀ β) : (lapply a : (α →₀ β) →ₗ[γ] β) f = f a :=
rfl
@[simp] lemma ker_lsingle (a : α) : (lsingle a : β →ₗ[γ] (α →₀ β)).ker = ⊥ :=
ker_eq_bot.2 (injective_single a)
lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) :
(⨆a∈s, (lsingle a : β →ₗ[γ] (α →₀ β)).range) ≤ (⨅a∈t, ker (lapply a)) :=
begin
refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _),
simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi],
assume b hb a₂ h₂,
have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩,
exact single_eq_of_ne this
end
lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ β) →ₗ[γ] β)) ≤ ⊥ :=
begin
simp only [le_def', mem_infi, mem_ker, mem_bot, lapply_apply],
exact assume a h, finsupp.ext h
end
lemma supr_lsingle_range : (⨆a, (lsingle a : β →ₗ[γ] (α →₀ β)).range) = ⊤ :=
begin
refine (eq_top_iff.2 $ le_def'.2 $ assume f _, _),
rw [← sum_single f],
refine sum_mem _ (assume a ha, submodule.mem_supr_of_mem _ a $ set.mem_image_of_mem _ trivial)
end
lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) :
disjoint (⨆a∈s, (lsingle a : β →ₗ[γ] (α →₀ β)).range) (⨆a∈t, (lsingle a).range) :=
begin
refine disjoint_mono
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl s)
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl t)
(le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot),
classical,
by_cases his : i ∈ s,
{ by_cases hit : i ∈ t,
{ exact (hs ⟨his, hit⟩).elim },
exact inf_le_right_of_le (infi_le_of_le i $ infi_le _ hit) },
exact inf_le_left_of_le (infi_le_of_le i $ infi_le _ his)
end
lemma span_single_image (s : set β) (a : α) :
submodule.span γ (single a '' s) = (submodule.span γ s).map (lsingle a) :=
by rw ← span_image; refl
variables (β γ)
def supported (s : set α) : submodule γ (α →₀ β) :=
begin
refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩,
{ simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply],
assume h ha, exact (ha rfl).elim },
{ assume p q hp hq,
refine subset.trans
(subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq),
rw [finset.coe_union] },
{ assume a p hp,
refine subset.trans (finset.coe_subset.2 support_smul) hp }
end
variables {β}
lemma mem_supported {s : set α} (p : α →₀ β) : p ∈ (supported β γ s) ↔ ↑p.support ⊆ s :=
iff.rfl
lemma mem_supported' {s : set α} (p : α →₀ β) :
p ∈ supported β γ s ↔ ∀ x ∉ s, p x = 0 :=
by haveI := classical.dec_pred (λ (x : α), x ∈ s);
simp [mem_supported, set.subset_def, not_imp_comm]
lemma single_mem_supported {s : set α} {a : α} (b : β) (h : a ∈ s) :
single a b ∈ supported β γ s :=
set.subset.trans support_single_subset (set.singleton_subset_iff.2 h)
lemma supported_eq_span_single [decidable_eq γ] [has_one β] (s : set α) :
supported γ γ s = span γ ((λ i, single i 1) '' s) :=
begin
refine (span_eq_of_le _ _ (le_def'.2 $ λ l hl, _)).symm,
{ rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported γ 1 hp },
{ rw ← l.sum_single,
refine sum_mem _ (λ i il, _),
convert @smul_mem γ (α →₀ γ) _ _ _ _ (single i 1) (l i) _,
{ simp },
apply subset_span,
apply set.mem_image_of_mem _ (hl il) }
end
variables (β γ)
def restrict_dom (s : set α) [decidable_pred (λ x, x ∈ s)]: (α →₀ β) →ₗ supported β γ s :=
linear_map.cod_restrict _
{ to_fun := filter (∈ s),
add := λ l₁ l₂, filter_add,
smul := λ a l, filter_smul }
(λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l)
variables {β γ}
section
set_option class.instance_max_depth 50
@[simp] theorem restrict_dom_apply (s : set α) [decidable_pred (λ x, x ∈ s)] (l : α →₀ β) :
((restrict_dom β γ s : (α →₀ β) →ₗ supported β γ s) l : α →₀ β) = finsupp.filter (∈ s) l := rfl
end
theorem restrict_dom_comp_subtype (s : set α) [decidable_pred (λ x, x ∈ s)] :
(restrict_dom β γ s).comp (submodule.subtype _) = linear_map.id :=
begin
ext l,
apply subtype.coe_ext.2,
simp,
ext a,
by_cases a ∈ s,
{ simp [h] },
{ rw [filter_apply_neg (λ x, x ∈ s) _ h],
exact ((mem_supported' γ l.1).1 l.2 a h).symm }
end
theorem range_restrict_dom (s : set α) [decidable_pred (λ x, x ∈ s)] :
(restrict_dom β γ s).range = ⊤ :=
begin
have := linear_map.range_comp (submodule.subtype _) (restrict_dom β γ s),
rw [restrict_dom_comp_subtype, linear_map.range_id] at this,
exact eq_top_mono (submodule.map_mono le_top) this.symm
end
theorem supported_mono {s t : set α} (st : s ⊆ t) :
supported β γ s ≤ supported β γ t :=
λ l h, set.subset.trans h st
@[simp] theorem supported_empty : supported β γ (∅ : set α) = ⊥ :=
eq_bot_iff.2 $ λ l h, (submodule.mem_bot γ).2 $
by ext; simp [*, mem_supported'] at *
@[simp] theorem supported_univ : supported β γ (set.univ : set α) = ⊤ :=
eq_top_iff.2 $ λ l _, set.subset_univ _
theorem supported_Union {δ : Type*} (s : δ → set α) :
supported β γ (⋃ i, s i) = ⨆ i, supported β γ (s i) :=
begin
refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _),
haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)),
suffices : ((submodule.subtype _).comp (restrict_dom β γ (⋃ i, s i))).range ≤ ⨆ i, supported β γ (s i),
{ rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this },
rw [range_le_iff_comap, eq_top_iff],
rintro l ⟨⟩, rw mem_coe,
apply finsupp.induction l, {exact zero_mem _},
refine λ x a l hl a0, add_mem _ _,
haveI := classical.dec_pred (λ x, ∃ i, x ∈ s i),
by_cases (∃ i, x ∈ s i); simp [h],
{ cases h with i hi,
exact le_supr (λ i, supported β γ (s i)) i (single_mem_supported γ _ hi) },
{ rw filter_single_of_neg,
{ simp },
{ exact h } }
end
theorem supported_union (s t : set α) :
supported β γ (s ∪ t) = supported β γ s ⊔ supported β γ t :=
by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl
theorem supported_Inter {ι : Type*} (s : ι → set α) :
supported β γ (⋂ i, s i) = ⨅ i, supported β γ (s i) :=
begin
refine le_antisymm (le_infi $ λ i, supported_mono $ set.Inter_subset _ _) _,
simp [le_def, infi_coe, set.subset_def],
exact λ l, set.subset_Inter
end
section
set_option class.instance_max_depth 37
def supported_equiv_finsupp (s : set α) [decidable_pred (λ (x : α), x ∈ s)] :
(supported β γ s) ≃ₗ[γ] (s →₀ β) :=
(restrict_support_equiv s).to_linear_equiv
begin
show is_linear_map γ ((lsubtype_domain s : (α →₀ β) →ₗ[γ] (s →₀ β)).comp
(submodule.subtype (supported β γ s))),
exact linear_map.is_linear _
end
end
def lsum [decidable_eq γ] (f : α → γ →ₗ[γ] β) : (α →₀ γ) →ₗ[γ] β :=
⟨λ d, d.sum (λ i, f i),
assume d₁ d₂, by simp [sum_add_index],
assume a d, by simp [sum_smul_index, smul_sum, -smul_eq_mul, smul_eq_mul.symm]⟩
@[simp] theorem lsum_apply [decidable_eq γ] (f : α → γ →ₗ[γ] β) (l : α →₀ γ) :
(finsupp.lsum f : (α →₀ γ) →ₗ β) l = l.sum (λ b, f b) := rfl
section lmap_domain
variables {α' : Type*} [decidable_eq α'] {α'' : Type*} [decidable_eq α''] (β γ)
def lmap_domain (f : α → α') : (α →₀ β) →ₗ[γ] (α' →₀ β) :=
⟨map_domain f, assume a b, map_domain_add, map_domain_smul⟩
@[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ β) :
(lmap_domain β γ f : (α →₀ β) →ₗ[γ] (α' →₀ β)) l = map_domain f l := rfl
@[simp] theorem lmap_domain_id : (lmap_domain β γ id : (α →₀ β) →ₗ[γ] α →₀ β) = linear_map.id :=
linear_map.ext $ λ l, map_domain_id
theorem lmap_domain_comp (f : α → α') (g : α' → α'') :
lmap_domain β γ (g ∘ f) = (lmap_domain β γ g).comp (lmap_domain β γ f) :=
linear_map.ext $ λ l, map_domain_comp
theorem supported_comap_lmap_domain (f : α → α') (s : set α') :
supported β γ (f ⁻¹' s) ≤ (supported β γ s).comap (lmap_domain β γ f) :=
λ l (hl : ↑l.support ⊆ f ⁻¹' s),
show ↑(map_domain f l).support ⊆ s, begin
rw [← set.image_subset_iff, ← finset.coe_image] at hl,
exact set.subset.trans map_domain_support hl
end
theorem lmap_domain_supported [inhabited α] (f : α → α') (s : set α) :
(supported β γ s).map (lmap_domain β γ f) = supported β γ (f '' s) :=
begin
refine le_antisymm (map_le_iff_le_comap.2 $
le_trans (supported_mono $ set.subset_preimage_image _ _)
(supported_comap_lmap_domain _ _ _ _)) _,
intros l hl,
refine ⟨(lmap_domain β γ (function.inv_fun_on f s) : (α' →₀ β) →ₗ α →₀ β) l, λ x hx, _, _⟩,
{ rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩,
exact function.inv_fun_on_mem (by simpa using hl hc) },
{ rw [← linear_map.comp_apply, ← lmap_domain_comp],
refine (map_domain_congr $ λ c hc, _).trans map_domain_id,
exact function.inv_fun_on_eq (by simpa using hl hc) }
end
theorem lmap_domain_disjoint_ker (f : α → α') {s : set α}
(H : ∀ a b ∈ s, f a = f b → a = b) :
disjoint (supported β γ s) (lmap_domain β γ f).ker :=
begin
rintro l ⟨h₁, h₂⟩,
rw [mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂,
simp, ext x,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases xs : x ∈ s,
{ have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl},
rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this,
{ simpa [finsupp.single_apply] },
{ intros y hy xy, simp [mt (H _ _ (h₁ hy) xs) xy] },
{ simp {contextual := tt} } },
{ by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) }
end
end lmap_domain
section total
variables (α) {α' : Type*} (β) {β' : Type*} (γ)
[decidable_eq α'] [decidable_eq β'] [add_comm_group β'] [decidable_eq γ] [module γ β']
(v : α → β) {v' : α' → β'}
/-- Interprets (l : α →₀ γ) as linear combination of the elements in the family (v : α → β) and
evaluates this linear combination. -/
protected def total : (α →₀ γ) →ₗ β := finsupp.lsum (λ i, linear_map.id.smul_right (v i))
variables {α β v}
theorem total_apply (l : α →₀ γ) :
finsupp.total α β γ v l = l.sum (λ i a, a • v i) := rfl
@[simp] theorem total_single (c : γ) (a : α) :
finsupp.total α β γ v (single a c) = c • (v a) :=
by simp [total_apply, sum_single_index]
theorem total_range (h : function.surjective v) : (finsupp.total α β γ v).range = ⊤ :=
begin
apply range_eq_top.2,
intros x,
apply exists.elim (h x),
exact λ i hi, ⟨single i 1, by simp [hi]⟩
end
lemma range_total : (finsupp.total α β γ v).range = span γ (range v) :=
begin
ext x,
split,
{ intros hx,
rw [linear_map.mem_range] at hx,
rcases hx with ⟨l, hl⟩,
rw ← hl,
rw finsupp.total_apply,
unfold finsupp.sum,
apply sum_mem (span γ (range v)),
{ exact λ i hi, submodule.smul _ _ (subset_span (mem_range_self i)) },
apply_instance },
{ apply span_le.2,
intros x hx,
rcases hx with ⟨i, hi⟩,
rw [mem_coe, linear_map.mem_range],
use finsupp.single i 1,
simp [hi] }
end
theorem lmap_domain_total (f : α → α') (g : β →ₗ[γ] β') (h : ∀ i, g (v i) = v' (f i)) :
(finsupp.total α' β' γ v').comp (lmap_domain γ γ f) = g.comp (finsupp.total α β γ v) :=
by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h]
theorem total_emb_domain (f : α ↪ α') (l : α →₀ γ) :
(finsupp.total α' β' γ v') (emb_domain f l) = (finsupp.total α β' γ (v' ∘ f)) l :=
by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply]
theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ γ) :
(finsupp.total α' β' γ v') (map_domain f l) = (finsupp.total α β' γ (v' ∘ f)) l :=
begin
have : map_domain f l = emb_domain ⟨f, hf⟩ l,
{ rw emb_domain_eq_map_domain ⟨f, hf⟩,
refl },
rw this,
apply total_emb_domain γ ⟨f, hf⟩ l
end
theorem span_eq_map_total (s : set α):
span γ (v '' s) = submodule.map (finsupp.total α β γ v) (supported γ γ s) :=
begin
apply span_eq_of_le,
{ intros x hx,
rw set.mem_image at hx,
apply exists.elim hx,
intros i hi,
exact ⟨_, finsupp.single_mem_supported γ 1 hi.1, by simp [hi.2]⟩ },
{ refine map_le_iff_le_comap.2 (λ z hz, _),
have : ∀i, z i • v i ∈ span γ (v '' s),
{ intro c,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases c ∈ s,
{ exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) },
{ simp [(finsupp.mem_supported' γ _).1 hz _ h] } },
refine sum_mem _ _, simp [this] }
end
theorem mem_span_iff_total {s : set α} {x : β}:
x ∈ span γ (v '' s) ↔ ∃ l ∈ supported γ γ s, finsupp.total α β γ v l = x :=
by rw span_eq_map_total; simp
variables (α) (β) (v)
protected def total_on (s : set α) : supported γ γ s →ₗ[γ] span γ (v '' s) :=
linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported γ γ s))) $
λ ⟨l, hl⟩, (mem_span_iff_total _).2 ⟨l, hl, rfl⟩
variables {α} {β} {v}
theorem total_on_range (s : set α) : (finsupp.total_on α β γ v s).range = ⊤ :=
by rw [finsupp.total_on, linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap,
range_subtype, map_top, linear_map.range_comp, range_subtype]; exact le_of_eq (span_eq_map_total _ _)
theorem total_comp (f : α' → α) :
(finsupp.total α' β γ (v ∘ f)) = (finsupp.total α β γ v).comp (lmap_domain γ γ f) :=
begin
ext l,
simp [total_apply],
rw sum_map_domain_index; simp [add_smul],
end
lemma total_comap_domain
(f : α → α') (l : α' →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) :
finsupp.total α β γ v (finsupp.comap_domain f l hf) = (l.support.preimage hf).sum (λ i, (l (f i)) • (v i)) :=
by rw finsupp.total_apply; refl
end total
protected def dom_lcongr
{α₁ : Type*} {α₂ : Type*} [decidable_eq α₁] [decidable_eq α₂] (e : α₁ ≃ α₂) :
(α₁ →₀ β) ≃ₗ[γ] (α₂ →₀ β) :=
(finsupp.dom_congr e).to_linear_equiv
begin
change is_linear_map γ (lmap_domain β γ e : (α₁ →₀ β) →ₗ[γ] (α₂ →₀ β)),
exact linear_map.is_linear _
end
noncomputable def congr {α' : Type*} [decidable_eq α'] (s : set α) (t : set α') (e : s ≃ t) :
supported β γ s ≃ₗ[γ] supported β γ t :=
begin
haveI := classical.dec_pred (λ x, x ∈ s),
haveI := classical.dec_pred (λ x, x ∈ t),
refine linear_equiv.trans (finsupp.supported_equiv_finsupp s)
(linear_equiv.trans _ (finsupp.supported_equiv_finsupp t).symm),
exact finsupp.dom_lcongr e
end
end finsupp
|
64fe86186f781a87e223aef18145203775d073b6 | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/sets_functions_and_relations/unnamed_1329.lean | 2a8e20b6c60cb43130bc6c96a87854c03e578d28 | [] | no_license | jamescheuk91/mathematics_in_lean | 09f1f87d2b0dce53464ff0cbe592c568ff59cf5e | 4452499264e2975bca2f42565c0925506ba5dda3 | refs/heads/master | 1,679,716,410,967 | 1,613,957,947,000 | 1,613,957,947,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 591 | lean | import data.set.function tactic
open set function
variables {α β : Type*} [inhabited α]
noncomputable theory
open_locale classical
def inverse (f : α → β) : β → α :=
λ y : β, if h : ∃ x, f x = y then classical.some h else default α
theorem inverse_spec {f : α → β} (y : β) (h : ∃ x, f x = y) :
f (inverse f y) = y :=
begin
rw inverse, dsimp, rw dif_pos h,
exact classical.some_spec h
end
-- BEGIN
variable f : α → β
example : injective f ↔ left_inverse (inverse f) f :=
sorry
example : surjective f ↔ right_inverse (inverse f) f :=
sorry
-- END |
61c5388ccc01a1b3d5e1640a0c07a629ae8957f1 | 5719a16e23dfc08cdea7a5bf035b81690f307965 | /src/Init/Lean/Meta/Basic.lean | 61883e19f11ce43f80d692e2a357cf1aaf51c39f | [
"Apache-2.0"
] | permissive | postmasters/lean4 | 488b03969a371e1507e1e8a4df9ebf63c7cbe7ac | f3976fc53a883ac7606fc59357d43f4b51016ca7 | refs/heads/master | 1,655,582,707,480 | 1,588,682,595,000 | 1,588,682,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 33,655 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Control.Reader
import Init.Lean.Data.LOption
import Init.Lean.Environment
import Init.Lean.Class
import Init.Lean.ReducibilityAttrs
import Init.Lean.Util.Trace
import Init.Lean.Util.RecDepth
import Init.Lean.Util.Closure
import Init.Lean.Meta.Exception
import Init.Lean.Meta.DiscrTreeTypes
import Init.Lean.Eval
/-
This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks.
1- Weak head normal form computation with support for metavariables and transparency modes.
2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality).
3- Type inference.
4- Type class resolution.
They are packed into the MetaM monad.
-/
namespace Lean
namespace Meta
inductive TransparencyMode
| all | default | reducible
namespace TransparencyMode
instance : Inhabited TransparencyMode := ⟨TransparencyMode.default⟩
def beq : TransparencyMode → TransparencyMode → Bool
| all, all => true
| default, default => true
| reducible, reducible => true
| _, _ => false
instance : HasBeq TransparencyMode := ⟨beq⟩
def hash : TransparencyMode → USize
| all => 7
| default => 11
| reducible => 13
instance : Hashable TransparencyMode := ⟨hash⟩
def lt : TransparencyMode → TransparencyMode → Bool
| reducible, default => true
| reducible, all => true
| default, all => true
| _, _ => false
end TransparencyMode
structure Config :=
(opts : Options := {})
(foApprox : Bool := false)
(ctxApprox : Bool := false)
(quasiPatternApprox : Bool := false)
/- When `constApprox` is set to true,
we solve `?m t =?= c` using
`?m := fun _ => c`
when `?m t` is not a higher-order pattern and `c` is not an application as -/
(constApprox : Bool := false)
/-
When the following flag is set,
`isDefEq` throws the exeption `Exeption.isDefEqStuck`
whenever it encounters a constraint `?m ... =?= t` where
`?m` is read only.
This feature is useful for type class resolution where
we may want to notify the caller that the TC problem may be solveable
later after it assigns `?m`. -/
(isDefEqStuckEx : Bool := false)
(debug : Bool := false)
(transparency : TransparencyMode := TransparencyMode.default)
structure ParamInfo :=
(implicit : Bool := false)
(instImplicit : Bool := false)
(hasFwdDeps : Bool := false)
(backDeps : Array Nat := #[])
instance ParamInfo.inhabited : Inhabited ParamInfo := ⟨{}⟩
structure FunInfo :=
(paramInfo : Array ParamInfo := #[])
(resultDeps : Array Nat := #[])
structure InfoCacheKey :=
(transparency : TransparencyMode)
(expr : Expr)
(nargs? : Option Nat)
namespace InfoCacheKey
instance : Inhabited InfoCacheKey := ⟨⟨arbitrary _, arbitrary _, arbitrary _⟩⟩
instance : Hashable InfoCacheKey :=
⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) $ mixHash (hash expr) (hash nargs)⟩
instance : HasBeq InfoCacheKey :=
⟨fun ⟨t₁, e₁, n₁⟩ ⟨t₂, e₂, n₂⟩ => t₁ == t₂ && n₁ == n₂ && e₁ == e₂⟩
end InfoCacheKey
structure Cache :=
(inferType : PersistentExprStructMap Expr := {})
(funInfo : PersistentHashMap InfoCacheKey FunInfo := {})
(synthInstance : PersistentHashMap Expr (Option Expr) := {})
(whnfDefault : PersistentExprStructMap Expr := {}) -- cache for closed terms and `TransparencyMode.default`
structure Context :=
(config : Config := {})
(lctx : LocalContext := {})
(localInstances : LocalInstances := #[])
(currRecDepth : Nat)
(maxRecDepth : Nat)
structure PostponedEntry :=
(lhs : Level)
(rhs : Level)
structure State :=
(env : Environment)
(mctx : MetavarContext := {})
(cache : Cache := {})
(ngen : NameGenerator := {})
(traceState : TraceState := {})
(postponed : PersistentArray PostponedEntry := {})
abbrev MetaM := ReaderT Context (EStateM Exception State)
instance MetaM.inhabited {α} : Inhabited (MetaM α) :=
⟨fun c s => EStateM.Result.error (arbitrary _) s⟩
@[inline] def withIncRecDepth {α} (x : MetaM α) : MetaM α := do
ctx ← read;
when (ctx.currRecDepth == ctx.maxRecDepth) $ throw $ Exception.other maxRecDepthErrorMessage;
adaptReader (fun (ctx : Context) => { currRecDepth := ctx.currRecDepth + 1, .. ctx }) x
@[inline] def getLCtx : MetaM LocalContext := do
ctx ← read; pure ctx.lctx
@[inline] def getLocalInstances : MetaM LocalInstances := do
ctx ← read; pure ctx.localInstances
@[inline] def getConfig : MetaM Config := do
ctx ← read; pure ctx.config
@[inline] def getMCtx : MetaM MetavarContext := do
s ← get; pure s.mctx
@[inline] def getEnv : MetaM Environment := do
s ← get; pure s.env
@[inline] def setEnv (env : Environment) : MetaM Unit := do
modify $ fun s => { env := env, .. s }
def mkWHNFRef : IO (IO.Ref (Expr → MetaM Expr)) :=
IO.mkRef $ fun _ => throw $ Exception.other "whnf implementation was not set"
@[init mkWHNFRef] def whnfRef : IO.Ref (Expr → MetaM Expr) := arbitrary _
def mkInferTypeRef : IO (IO.Ref (Expr → MetaM Expr)) :=
IO.mkRef $ fun _ => throw $ Exception.other "inferType implementation was not set"
@[init mkInferTypeRef] def inferTypeRef : IO.Ref (Expr → MetaM Expr) := arbitrary _
def mkIsExprDefEqAuxRef : IO (IO.Ref (Expr → Expr → MetaM Bool)) :=
IO.mkRef $ fun _ _ => throw $ Exception.other "isDefEq implementation was not set"
@[init mkIsExprDefEqAuxRef] def isExprDefEqAuxRef : IO.Ref (Expr → Expr → MetaM Bool) := arbitrary _
def mkSynthPendingRef : IO (IO.Ref (MVarId → MetaM Bool)) :=
IO.mkRef $ fun _ => pure false
@[init mkSynthPendingRef] def synthPendingRef : IO.Ref (MVarId → MetaM Bool) := arbitrary _
structure MetaExtState :=
(whnf : Expr → MetaM Expr)
(inferType : Expr → MetaM Expr)
(isDefEqAux : Expr → Expr → MetaM Bool)
(synthPending : MVarId → MetaM Bool)
instance MetaExtState.inhabited : Inhabited MetaExtState :=
⟨{ whnf := arbitrary _, inferType := arbitrary _, isDefEqAux := arbitrary _, synthPending := arbitrary _ }⟩
def mkMetaExtension : IO (EnvExtension MetaExtState) :=
registerEnvExtension $ do
whnf ← whnfRef.get;
inferType ← inferTypeRef.get;
isDefEqAux ← isExprDefEqAuxRef.get;
synthPending ← synthPendingRef.get;
pure { whnf := whnf, inferType := inferType, isDefEqAux := isDefEqAux, synthPending := synthPending }
@[init mkMetaExtension]
constant metaExt : EnvExtension MetaExtState := arbitrary _
def whnf (e : Expr) : MetaM Expr :=
withIncRecDepth $ do
env ← getEnv;
(metaExt.getState env).whnf e
def whnfForall (e : Expr) : MetaM Expr := do
e' ← whnf e;
if e'.isForall then pure e' else pure e
def inferType (e : Expr) : MetaM Expr :=
withIncRecDepth $ do
env ← getEnv;
(metaExt.getState env).inferType e
def isExprDefEqAux (t s : Expr) : MetaM Bool :=
withIncRecDepth $ do
env ← getEnv;
(metaExt.getState env).isDefEqAux t s
def synthPending (mvarId : MVarId) : MetaM Bool :=
withIncRecDepth $ do
env ← getEnv;
(metaExt.getState env).synthPending mvarId
def mkFreshId : MetaM Name := do
s ← get;
let id := s.ngen.curr;
modify $ fun s => { ngen := s.ngen.next, .. s };
pure id
def mkFreshExprMVarAt
(lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (userName : Name := Name.anonymous) (kind : MetavarKind := MetavarKind.natural)
: MetaM Expr := do
mvarId ← mkFreshId;
modify $ fun s => { mctx := s.mctx.addExprMVarDecl mvarId userName lctx localInsts type kind, .. s };
pure $ mkMVar mvarId
def mkFreshExprMVar (type : Expr) (userName : Name := Name.anonymous) (kind : MetavarKind := MetavarKind.natural) : MetaM Expr := do
lctx ← getLCtx;
localInsts ← getLocalInstances;
mkFreshExprMVarAt lctx localInsts type userName kind
def mkFreshLevelMVar : MetaM Level := do
mvarId ← mkFreshId;
modify $ fun s => { mctx := s.mctx.addLevelMVarDecl mvarId, .. s};
pure $ mkLevelMVar mvarId
@[inline] def throwEx {α} (f : ExceptionContext → Exception) : MetaM α := do
ctx ← read;
s ← get;
throw (f {env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts })
def throwBug {α} (b : Bug) : MetaM α :=
throwEx $ Exception.bug b
/-- Execute `x` only in debugging mode. -/
@[inline] private def whenDebugging (x : MetaM Unit) : MetaM Unit := do
ctx ← read;
when ctx.config.debug x
@[inline] def shouldReduceAll : MetaM Bool := do
ctx ← read; pure $ ctx.config.transparency == TransparencyMode.all
@[inline] def shouldReduceReducibleOnly : MetaM Bool := do
ctx ← read; pure $ ctx.config.transparency == TransparencyMode.reducible
@[inline] def getTransparency : MetaM TransparencyMode := do
ctx ← read; pure $ ctx.config.transparency
@[inline] def getOptions : MetaM Options := do
ctx ← read; pure ctx.config.opts
-- Remark: wanted to use `private`, but in C++ parser, `private` declarations do not shadow outer public ones.
-- TODO: fix this bug
@[inline] def isReducible (constName : Name) : MetaM Bool := do
env ← getEnv; pure $ isReducible env constName
@[inline] def withConfig {α} (f : Config → Config) (x : MetaM α) : MetaM α :=
adaptReader (fun (ctx : Context) => { config := f ctx.config, .. ctx }) x
/-- While executing `x`, ensure the given transparency mode is used. -/
@[inline] def withTransparency {α} (mode : TransparencyMode) (x : MetaM α) : MetaM α :=
withConfig (fun config => { transparency := mode, .. config }) x
@[inline] def withReducible {α} (x : MetaM α) : MetaM α :=
withTransparency TransparencyMode.reducible x
@[inline] def withAtLeastTransparency {α} (mode : TransparencyMode) (x : MetaM α) : MetaM α :=
withConfig
(fun config =>
let oldMode := config.transparency;
let mode := if oldMode.lt mode then mode else oldMode;
{ transparency := mode, .. config })
x
def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do
mctx ← getMCtx;
match mctx.findDecl? mvarId with
| some d => pure d
| none => throwEx $ Exception.unknownExprMVar mvarId
def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit :=
modify $ fun s => { mctx := s.mctx.setMVarKind mvarId kind, .. s}
def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do
mvarDecl ← getMVarDecl mvarId;
mctx ← getMCtx;
pure $ mvarDecl.depth != mctx.depth
def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do
mvarDecl ← getMVarDecl mvarId;
match mvarDecl.kind with
| MetavarKind.syntheticOpaque => pure true
| _ => do
mctx ← getMCtx;
pure $ mvarDecl.depth != mctx.depth
def isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do
mctx ← getMCtx;
match mctx.findLevelDepth? mvarId with
| some depth => pure $ depth != mctx.depth
| _ => throwEx $ Exception.unknownLevelMVar mvarId
def renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit :=
modify $ fun s => { mctx := s.mctx.renameMVar mvarId newUserName, .. s }
@[inline] def isExprMVarAssigned (mvarId : MVarId) : MetaM Bool := do
mctx ← getMCtx;
pure $ mctx.isExprAssigned mvarId
@[inline] def getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) := do
mctx ← getMCtx; pure (mctx.getExprAssignment? mvarId)
def assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit := do
whenDebugging $ whenM (isExprMVarAssigned mvarId) $ throwBug $ Bug.overwritingExprMVar mvarId;
modify $ fun s => { mctx := s.mctx.assignExpr mvarId val, .. s }
def isDelayedAssigned (mvarId : MVarId) : MetaM Bool := do
mctx ← getMCtx;
pure $ mctx.isDelayedAssigned mvarId
def hasAssignableMVar (e : Expr) : MetaM Bool := do
mctx ← getMCtx;
pure $ mctx.hasAssignableMVar e
def dbgTrace {α} [HasToString α] (a : α) : MetaM Unit :=
_root_.dbgTrace (toString a) $ fun _ => pure ()
@[inline] private def getTraceState : MetaM TraceState := do
s ← get; pure s.traceState
def addContext (msg : MessageData) : MetaM MessageData := do
ctx ← read;
s ← get;
pure $ MessageData.withContext { env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts } msg
instance tracer : SimpleMonadTracerAdapter MetaM :=
{ getOptions := getOptions,
getTraceState := getTraceState,
addContext := addContext,
modifyTraceState := fun f => modify $ fun s => { traceState := f s.traceState, .. s } }
def getConstAux (constName : Name) (exception? : Bool) : MetaM (Option ConstantInfo) := do
env ← getEnv;
match env.find? constName with
| some (info@(ConstantInfo.thmInfo _)) =>
condM shouldReduceAll (pure (some info)) (pure none)
| some (info@(ConstantInfo.defnInfo _)) =>
condM shouldReduceReducibleOnly
(condM (isReducible constName) (pure (some info)) (pure none))
(pure (some info))
| some info => pure (some info)
| none =>
if exception? then throwEx $ Exception.unknownConst constName
else pure none
@[inline] def getConst (constName : Name) : MetaM (Option ConstantInfo) :=
getConstAux constName true
@[inline] def getConstNoEx (constName : Name) : MetaM (Option ConstantInfo) :=
getConstAux constName false
def getConstInfo (constName : Name) : MetaM ConstantInfo := do
env ← getEnv;
match env.find? constName with
| some info => pure info
| none => throwEx $ Exception.unknownConst constName
def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do
lctx ← getLCtx;
match lctx.find? fvarId with
| some d => pure d
| none => throwEx $ Exception.unknownFVar fvarId
def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl :=
getLocalDecl fvar.fvarId!
def instantiateMVars (e : Expr) : MetaM Expr :=
if e.hasMVar then
modifyGet $ fun s =>
let (e, mctx) := s.mctx.instantiateMVars e;
(e, { mctx := mctx, .. s })
else
pure e
@[inline] private def liftMkBindingM {α} (x : MetavarContext.MkBindingM α) : MetaM α :=
fun ctx s =>
match x ctx.lctx { mctx := s.mctx, ngen := s.ngen } with
| EStateM.Result.ok e newS =>
EStateM.Result.ok e { mctx := newS.mctx, ngen := newS.ngen, .. s}
| EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS =>
EStateM.Result.error
(Exception.revertFailure toRevert decl { lctx := lctx, mctx := mctx, env := s.env, opts := ctx.config.opts })
{ mctx := newS.mctx, ngen := newS.ngen, .. s }
def mkForall (xs : Array Expr) (e : Expr) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM $ MetavarContext.mkForall xs e
def mkLambda (xs : Array Expr) (e : Expr) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM $ MetavarContext.mkLambda xs e
def mkForallUsedOnly (xs : Array Expr) (e : Expr) : MetaM (Expr × Nat) :=
if xs.isEmpty then pure (e, 0) else liftMkBindingM $ MetavarContext.mkForallUsedOnly xs e
def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM $ MetavarContext.elimMVarDeps xs e preserveOrder
/-- Save cache, execute `x`, restore cache -/
@[inline] def savingCache {α} (x : MetaM α) : MetaM α := do
s ← get;
let savedCache := s.cache;
finally x (modify $ fun s => { cache := savedCache, .. s })
def isClassQuickConst (constName : Name) : MetaM (LOption Name) := do
env ← getEnv;
if isClass env constName then
pure (LOption.some constName)
else do
cinfo? ← getConst constName;
match cinfo? with
| some _ => pure LOption.undef
| none => pure LOption.none
partial def isClassQuick : Expr → MetaM (LOption Name)
| Expr.bvar _ _ => pure LOption.none
| Expr.lit _ _ => pure LOption.none
| Expr.fvar _ _ => pure LOption.none
| Expr.sort _ _ => pure LOption.none
| Expr.lam _ _ _ _ => pure LOption.none
| Expr.letE _ _ _ _ _ => pure LOption.undef
| Expr.proj _ _ _ _ => pure LOption.undef
| Expr.forallE _ _ b _ => isClassQuick b
| Expr.mdata _ e _ => isClassQuick e
| Expr.const n _ _ => isClassQuickConst n
| Expr.mvar mvarId _ => do
val? ← getExprMVarAssignment? mvarId;
match val? with
| some val => isClassQuick val
| none => pure LOption.none
| Expr.app f _ _ =>
match f.getAppFn with
| Expr.const n _ _ => isClassQuickConst n
| Expr.lam _ _ _ _ => pure LOption.undef
| _ => pure LOption.none
| Expr.localE _ _ _ _ => unreachable!
/-- Reset `synthInstance` cache, execute `x`, and restore cache -/
@[inline] def resettingSynthInstanceCache {α} (x : MetaM α) : MetaM α := do
s ← get;
let savedSythInstance := s.cache.synthInstance;
modify $ fun s => { cache := { synthInstance := {}, .. s.cache }, .. s };
finally x (modify $ fun s => { cache := { synthInstance := savedSythInstance, .. s.cache }, .. s })
/-- Add entry `{ className := className, fvar := fvar }` to localInstances,
and then execute continuation `k`.
It resets the type class cache using `resettingSynthInstanceCache`. -/
@[inline] def withNewLocalInstance {α} (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α :=
resettingSynthInstanceCache $
adaptReader
(fun (ctx : Context) => {
localInstances := ctx.localInstances.push { className := className, fvar := fvar },
.. ctx })
k
/--
`withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances
using free variables `fvars[j] ... fvars.back`, and execute `k`.
- `isClassExpensive` is defined later.
- The type class chache is reset whenever a new local instance is found.
- `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances.
Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/
@[specialize] partial def withNewLocalInstances {α}
(isClassExpensive : Expr → MetaM (Option Name))
(fvars : Array Expr) : Nat → MetaM α → MetaM α
| i, k =>
if h : i < fvars.size then do
let fvar := fvars.get ⟨i, h⟩;
decl ← getFVarLocalDecl fvar;
c? ← isClassQuick decl.type;
match c? with
| LOption.none => withNewLocalInstances (i+1) k
| LOption.undef => do
c? ← isClassExpensive decl.type;
match c? with
| none => withNewLocalInstances (i+1) k
| some c => withNewLocalInstance c fvar $ withNewLocalInstances (i+1) k
| LOption.some c => withNewLocalInstance c fvar $ withNewLocalInstances (i+1) k
else
k
/--
`forallTelescopeAux whnf k lctx fvars j type`
Remarks:
- `lctx` is the `MetaM` local context exteded with the declaration for `fvars`.
- `type` is the type we are computing the telescope for. It contains only
dangling bound variables in the range `[j, fvars.size)`
- if `reducing? == true` and `type` is not `forallE`, we use `whnf`.
- when `type` is not a `forallE` nor it can't be reduced to one, we
excute the continuation `k`.
Here is an example that demonstrates the `reducing?`.
Suppose we have
```
abbrev StateM s a := s -> Prod a s
```
Now, assume we are trying to build the telescope for
```
forall (x : Nat), StateM Int Bool
```
if `reducing? == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`.
if `reducing? == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)`
if `maxFVars?` is `some max`, then we interrupt the telescope construction
when `fvars.size == max`
-/
@[specialize] private partial def forallTelescopeReducingAuxAux {α}
(isClassExpensive : Expr → MetaM (Option Name))
(reducing? : Bool) (maxFVars? : Option Nat)
(k : Array Expr → Expr → MetaM α)
: LocalContext → Array Expr → Nat → Expr → MetaM α
| lctx, fvars, j, type@(Expr.forallE n d b c) => do
let process : Unit → MetaM α := fun _ => do {
let d := d.instantiateRevRange j fvars.size fvars;
fvarId ← mkFreshId;
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo;
let fvar := mkFVar fvarId;
let fvars := fvars.push fvar;
forallTelescopeReducingAuxAux lctx fvars j b
};
match maxFVars? with
| none => process ()
| some maxFVars =>
if fvars.size < maxFVars then
process ()
else
let type := type.instantiateRevRange j fvars.size fvars;
adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $
withNewLocalInstances isClassExpensive fvars j $
k fvars type
| lctx, fvars, j, type =>
let type := type.instantiateRevRange j fvars.size fvars;
adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $
withNewLocalInstances isClassExpensive fvars j $
if reducing? then do
newType ← whnf type;
if newType.isForall then
forallTelescopeReducingAuxAux lctx fvars fvars.size newType
else
k fvars type
else
k fvars type
/- We need this auxiliary definition because it depends on `isClassExpensive`,
and `isClassExpensive` depends on it. -/
@[specialize] private def forallTelescopeReducingAux {α}
(isClassExpensive : Expr → MetaM (Option Name))
(type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do
newType ← whnf type;
if newType.isForall then do
lctx ← getLCtx;
forallTelescopeReducingAuxAux isClassExpensive true maxFVars? k lctx #[] 0 newType
else
k #[] type
partial def isClassExpensive : Expr → MetaM (Option Name)
| type => withReducible $ -- when testing whether a type is a type class, we only unfold reducible constants.
forallTelescopeReducingAux isClassExpensive type none $ fun xs type => do
match type.getAppFn with
| Expr.const c _ _ => do
env ← getEnv;
pure $ if isClass env c then some c else none
| _ => pure none
/--
Given `type` of the form `forall xs, A`, execute `k xs A`.
This combinator will declare local declarations, create free variables for them,
execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/
def forallTelescope {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do
lctx ← getLCtx;
forallTelescopeReducingAuxAux isClassExpensive false none k lctx #[] 0 type
/--
Similar to `forallTelescope`, but given `type` of the form `forall xs, A`,
it reduces `A` and continues bulding the telescope if it is a `forall`. -/
def forallTelescopeReducing {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux isClassExpensive type none k
/--
Similar to `forallTelescopeReducing`, stops constructing the telescope when
it reaches size `maxFVars`. -/
def forallBoundedTelescope {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux isClassExpensive type maxFVars? k
/-- Return the parameter names for the givel global declaration. -/
def getParamNames (declName : Name) : MetaM (Array Name) := do
cinfo ← getConstInfo declName;
forallTelescopeReducing cinfo.type $ fun xs _ => do
xs.mapM $ fun x => do
localDecl ← getLocalDecl x.fvarId!;
pure localDecl.userName
def isClass (type : Expr) : MetaM (Option Name) := do
c? ← isClassQuick type;
match c? with
| LOption.none => pure none
| LOption.some c => pure (some c)
| LOption.undef => isClassExpensive type
/-- Similar to `forallTelescopeAuxAux` but for lambda and let expressions. -/
private partial def lambdaTelescopeAux {α}
(k : Array Expr → Expr → MetaM α)
: LocalContext → Array Expr → Nat → Expr → MetaM α
| lctx, fvars, j, Expr.lam n d b c => do
let d := d.instantiateRevRange j fvars.size fvars;
fvarId ← mkFreshId;
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo;
let fvar := mkFVar fvarId;
lambdaTelescopeAux lctx (fvars.push fvar) j b
| lctx, fvars, j, Expr.letE n t v b _ => do
let t := t.instantiateRevRange j fvars.size fvars;
let v := v.instantiateRevRange j fvars.size fvars;
fvarId ← mkFreshId;
let lctx := lctx.mkLetDecl fvarId n t v;
let fvar := mkFVar fvarId;
lambdaTelescopeAux lctx (fvars.push fvar) j b
| lctx, fvars, j, e =>
let e := e.instantiateRevRange j fvars.size fvars;
adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $
withNewLocalInstances isClassExpensive fvars j $ do
k fvars e
/-- Similar to `forallTelescope` but for lambda and let expressions. -/
def lambdaTelescope {α} (e : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do
lctx ← getLCtx;
lambdaTelescopeAux k lctx #[] 0 e
-- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments.
private partial def forallMetaTelescopeReducingAux
(reducing? : Bool) (maxMVars? : Option Nat) (kind : MetavarKind)
: Array Expr → Array BinderInfo → Nat → Expr → MetaM (Array Expr × Array BinderInfo × Expr)
| mvars, bis, j, type@(Expr.forallE n d b c) => do
let process : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do {
let d := d.instantiateRevRange j mvars.size mvars;
let k := if c.binderInfo.isInstImplicit then MetavarKind.synthetic else kind;
mvar ← mkFreshExprMVar d n k;
let mvars := mvars.push mvar;
let bis := bis.push c.binderInfo;
forallMetaTelescopeReducingAux mvars bis j b
};
match maxMVars? with
| none => process ()
| some maxMVars =>
if mvars.size < maxMVars then
process ()
else
let type := type.instantiateRevRange j mvars.size mvars;
pure (mvars, bis, type)
| mvars, bis, j, type =>
let type := type.instantiateRevRange j mvars.size mvars;
if reducing? then do
newType ← whnf type;
if newType.isForall then
forallMetaTelescopeReducingAux mvars bis mvars.size newType
else
pure (mvars, bis, type)
else
pure (mvars, bis, type)
/-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/
def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux false none kind #[] #[] 0 e
/-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/
def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux true maxMVars? kind #[] #[] 0 e
/-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/
private partial def lambdaMetaTelescopeAux (maxMVars? : Option Nat)
: Array Expr → Array BinderInfo → Nat → Expr → MetaM (Array Expr × Array BinderInfo × Expr)
| mvars, bis, j, type => do
let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do {
let type := type.instantiateRevRange j mvars.size mvars;
pure (mvars, bis, type)
};
let process : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do {
match type with
| Expr.lam n d b c => do
let d := d.instantiateRevRange j mvars.size mvars;
mvar ← mkFreshExprMVar d;
let mvars := mvars.push mvar;
let bis := bis.push c.binderInfo;
lambdaMetaTelescopeAux mvars bis j b
| _ => finalize ()
};
match maxMVars? with
| none => process ()
| some maxMVars =>
if mvars.size < maxMVars then
process ()
else
finalize ()
/-- Similar to `forallMetaTelescope` but for lambda expressions. -/
def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) :=
lambdaMetaTelescopeAux maxMVars? #[] #[] 0 e
@[inline] def liftStateMCtx {α} (x : StateM MetavarContext α) : MetaM α :=
fun _ s =>
let (a, mctx) := x.run s.mctx;
EStateM.Result.ok a { mctx := mctx, .. s }
def instantiateLevelMVars (lvl : Level) : MetaM Level :=
liftStateMCtx $ MetavarContext.instantiateLevelMVars lvl
def assignLevelMVar (mvarId : MVarId) (lvl : Level) : MetaM Unit :=
modify $ fun s => { mctx := MetavarContext.assignLevel s.mctx mvarId lvl, .. s }
def mkFreshLevelMVarId : MetaM MVarId := do
mvarId ← mkFreshId;
modify $ fun s => { mctx := s.mctx.addLevelMVarDecl mvarId, .. s };
pure mvarId
def whnfD : Expr → MetaM Expr :=
fun e => withTransparency TransparencyMode.default $ whnf e
/-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/
@[inline] def approxDefEq {α} (x : MetaM α) : MetaM α :=
adaptReader (fun (ctx : Context) => { config := { foApprox := true, ctxApprox := true, quasiPatternApprox := true, .. ctx.config }, .. ctx })
x
/--
Similar to `approxDefEq`, but uses all available approximations.
We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code.
For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[HasPure ?m]`.
Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved
as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to
solve `[HasPure (fun _ => IO Bool)]` -/
@[inline] def fullApproxDefEq {α} (x : MetaM α) : MetaM α :=
adaptReader (fun (ctx : Context) => { config := { foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true, .. ctx.config }, .. ctx })
x
@[inline] private def withNewFVar {α} (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do
c? ← isClass fvarType;
match c? with
| none => k fvar
| some c => withNewLocalInstance c fvar $ k fvar
def withLocalDecl {α} (n : Name) (type : Expr) (bi : BinderInfo) (k : Expr → MetaM α) : MetaM α := do
fvarId ← mkFreshId;
ctx ← read;
let lctx := ctx.lctx.mkLocalDecl fvarId n type bi;
let fvar := mkFVar fvarId;
adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $
withNewFVar fvar type k
def withLocalDeclD {α} (n : Name) (type : Expr) (k : Expr → MetaM α) : MetaM α :=
withLocalDecl n type BinderInfo.default k
def withLetDecl {α} (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do
fvarId ← mkFreshId;
ctx ← read;
let lctx := ctx.lctx.mkLetDecl fvarId n type val;
let fvar := mkFVar fvarId;
adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $
withNewFVar fvar type k
/--
Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`,
and restore saved data. -/
@[inline] def withNewMCtxDepth {α} (x : MetaM α) : MetaM α := do
s ← get;
let savedMCtx := s.mctx;
modify $ fun s => { mctx := s.mctx.incDepth, .. s };
finally x (modify $ fun s => { mctx := savedMCtx, .. s })
def withLocalContext {α} (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do
localInstsCurr ← getLocalInstances;
adaptReader (fun (ctx : Context) => { lctx := lctx, localInstances := localInsts, .. ctx }) $
if localInsts == localInstsCurr then
x
else
resettingSynthInstanceCache x
/--
Execute `x` using the given metavariable `LocalContext` and `LocalInstances`.
The type class resolution cache is flushed when executing `x` if its `LocalInstances` are
different from the current ones. -/
@[inline] def withMVarContext {α} (mvarId : MVarId) (x : MetaM α) : MetaM α := do
mvarDecl ← getMVarDecl mvarId;
withLocalContext mvarDecl.lctx mvarDecl.localInstances x
@[inline] def withMCtx {α} (mctx : MetavarContext) (x : MetaM α) : MetaM α := do
mctx' ← getMCtx;
modify $ fun s => { mctx := mctx, .. s };
finally x (modify $ fun s => { mctx := mctx', .. s })
/--
Create an auxiliary definition with the given name, type and value.
The parameters `type` and `value` may contain free and meta variables.
A "closure" is computed, and a term of the form `name.{u_1 ... u_n} t_1 ... t_m` is
returned where `u_i`s are universe parameters and metavariables `type` and `value` depend on,
and `t_j`s are free and meta variables `type` and `value` depend on. -/
def mkAuxDefinition (name : Name) (type : Expr) (value : Expr) : MetaM Expr := do
env ← getEnv;
opts ← getOptions;
mctx ← getMCtx;
lctx ← getLCtx;
match Lean.mkAuxDefinition env opts mctx lctx name type value with
| Except.error ex => throw $ Exception.kernel ex opts
| Except.ok (e, env) => do setEnv env; pure e
/-- Similar to `mkAuxDefinition`, but infers the type of `value`. -/
def mkAuxDefinitionFor (name : Name) (value : Expr) : MetaM Expr := do
type ← inferType value;
let type := type.headBeta;
mkAuxDefinition name type value
@[init] private def regTraceClasses : IO Unit := do
registerTraceClass `Meta;
registerTraceClass `Meta.debug
def run {α} (env : Environment) (x : MetaM α) (maxRecDepth := 10000) : Except Exception α :=
match x { maxRecDepth := maxRecDepth, currRecDepth := 0 } { env := env } with
| EStateM.Result.ok a _ => Except.ok a
| EStateM.Result.error ex _ => Except.error ex
end Meta
export Meta (MetaM)
end Lean
open Lean
open Lean.Meta
/-- Helper function for running `MetaM` methods in attributes -/
@[inline] def IO.runMeta {α} (x : MetaM α) (env : Environment) (cfg : Config := {}) : IO (α × Environment) :=
match (x { config := cfg, currRecDepth := 0, maxRecDepth := defaultMaxRecDepth }).run { env := env } with
| EStateM.Result.ok a s => pure (a, s.env)
| EStateM.Result.error ex _ => throw (IO.userError (toString ex))
|
d8d0b7b364a019f149b2857cf51809f3b4585f46 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/monotonicity/interactive.lean | fd9ab6624ceb224988f16a0379d4736ef18c326f | [
"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 | 23,634 | lean | /-
Copyright (c) 2019 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import control.traversable.derive
import control.traversable.lemmas
import data.dlist
import tactic.monotonicity.basic
variables {a b c p : Prop}
namespace tactic.interactive
open lean lean.parser interactive
open interactive.types
open tactic
local postfix (name := parser.optional) `?`:9001 := optional
local postfix (name := parser.many) *:9001 := many
meta inductive mono_function (elab : bool := tt)
| non_assoc : expr elab → list (expr elab) → list (expr elab) → mono_function
| assoc : expr elab → option (expr elab) → option (expr elab) → mono_function
| assoc_comm : expr elab → expr elab → mono_function
meta instance : decidable_eq mono_function :=
by mk_dec_eq_instance
meta def mono_function.to_tactic_format : mono_function → tactic format
| (mono_function.non_assoc fn xs ys) := do
fn' ← pp fn,
xs' ← mmap pp xs,
ys' ← mmap pp ys,
return format!"{fn'} {xs'} _ {ys'}"
| (mono_function.assoc fn xs ys) := do
fn' ← pp fn,
xs' ← pp xs,
ys' ← pp ys,
return format!"{fn'} {xs'} _ {ys'}"
| (mono_function.assoc_comm fn xs) := do
fn' ← pp fn,
xs' ← pp xs,
return format!"{fn'} _ {xs'}"
meta instance has_to_tactic_format_mono_function : has_to_tactic_format mono_function :=
{ to_tactic_format := mono_function.to_tactic_format }
@[derive traversable]
meta structure ac_mono_ctx' (rel : Type) :=
(to_rel : rel)
(function : mono_function)
(left right rel_def : expr)
@[reducible]
meta def ac_mono_ctx := ac_mono_ctx' (option (expr → expr → expr))
@[reducible]
meta def ac_mono_ctx_ne := ac_mono_ctx' (expr → expr → expr)
meta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format :=
do fn ← pp ctx.function,
l ← pp ctx.left,
r ← pp ctx.right,
rel ← pp ctx.rel_def,
return format!"{{ function := {fn}\n, left := {l}\n, right := {r}\n, rel_def := {rel} }}"
meta instance has_to_tactic_format_mono_ctx : has_to_tactic_format ac_mono_ctx :=
{ to_tactic_format := ac_mono_ctx.to_tactic_format }
meta def as_goal (e : expr) (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
set_goals [e],
tac,
set_goals gs
open list (hiding map) functor dlist
section config
parameter opt : mono_cfg
parameter asms : list expr
meta def unify_with_instance (e : expr) : tactic unit :=
as_goal e $
apply_instance
<|>
apply_opt_param
<|>
apply_auto_param
<|>
tactic.solve_by_elim { lemmas := some asms }
<|>
reflexivity
<|>
applyc ``id
<|>
return ()
private meta def match_rule_head (p : expr)
: list expr → expr → expr → tactic expr
| vs e t :=
(unify t p >> mmap' unify_with_instance vs.reverse >> instantiate_mvars e)
<|>
do (expr.pi _ _ d b) ← return t | failed,
v ← mk_meta_var d,
match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v)
meta def pi_head : expr → tactic expr
| (expr.pi n _ t b) :=
do v ← mk_meta_var t,
pi_head (b.instantiate_var v)
| e := return e
meta def delete_expr (e : expr)
: list expr → tactic (option (list expr))
| [] := return none
| (x :: xs) :=
(compare opt e x >> return (some xs))
<|>
(map (cons x) <$> delete_expr xs)
meta def match_ac'
: list expr → list expr → tactic (list expr × list expr × list expr)
| es (x :: xs) := do
es' ← delete_expr x es,
match es' with
| (some es') := do
(c,l,r) ← match_ac' es' xs, return (x::c,l,r)
| none := do
(c,l,r) ← match_ac' es xs, return (c,l,x::r)
end
| es [] := do
return ([],es,[])
meta def match_ac (l : list expr) (r : list expr)
: tactic (list expr × list expr × list expr) :=
do (s',l',r') ← match_ac' l r,
s' ← mmap instantiate_mvars s',
l' ← mmap instantiate_mvars l',
r' ← mmap instantiate_mvars r',
return (s',l',r')
meta def match_prefix
: list expr → list expr → tactic (list expr × list expr × list expr)
| (x :: xs) (y :: ys) :=
(do compare opt x y,
prod.map ((::) x) id <$> match_prefix xs ys)
<|> return ([],x :: xs,y :: ys)
| xs ys := return ([],xs,ys)
/--
`(prefix,left,right,suffix) ← match_assoc unif l r` finds the
longest prefix and suffix common to `l` and `r` and
returns them along with the differences -/
meta def match_assoc (l : list expr) (r : list expr)
: tactic (list expr × list expr × list expr × list expr) :=
do (pre,l₁,r₁) ← match_prefix l r,
(suf,l₂,r₂) ← match_prefix (reverse l₁) (reverse r₁),
return (pre,reverse l₂,reverse r₂,reverse suf)
meta def check_ac : expr → tactic (bool × bool × option (expr × expr × expr) × expr)
| (expr.app (expr.app f x) y) :=
do t ← infer_type x,
a ← try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance,
c ← try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance,
i ← try_core (do
v ← mk_meta_var t,
l_inst_p ← to_expr ``(is_left_id %%t %%f %%v),
r_inst_p ← to_expr ``(is_right_id %%t %%f %%v),
l_v ← mk_meta_var l_inst_p,
r_v ← mk_meta_var r_inst_p ,
l_id ← mk_mapp `is_left_id.left_id [some t,f,v,some l_v],
mk_instance l_inst_p >>= unify l_v,
r_id ← mk_mapp `is_right_id.right_id [none,f,v,some r_v],
mk_instance r_inst_p >>= unify r_v,
v' ← instantiate_mvars v,
return (l_id,r_id,v')),
return (a.is_some,c.is_some,i,f)
| _ := return (ff,ff,none,expr.var 1)
meta def parse_assoc_chain' (f : expr) : expr → tactic (dlist expr)
| e :=
(do (expr.app (expr.app f' x) y) ← return e,
is_def_eq f f',
(++) <$> parse_assoc_chain' x <*> parse_assoc_chain' y)
<|> return (singleton e)
meta def parse_assoc_chain (f : expr) : expr → tactic (list expr) :=
map dlist.to_list ∘ parse_assoc_chain' f
meta def fold_assoc (op : expr) :
option (expr × expr × expr) → list expr → option (expr × list expr)
| _ (x::xs) := some (foldl (expr.app ∘ expr.app op) x xs, [])
| none [] := none
| (some (l_id,r_id,x₀)) [] := some (x₀,[l_id,r_id])
meta def fold_assoc1 (op : expr) : list expr → option expr
| (x::xs) := some $ foldl (expr.app ∘ expr.app op) x xs
| [] := none
meta def same_function_aux
: list expr → list expr → expr → expr → tactic (expr × list expr × list expr)
| xs₀ xs₁ (expr.app f₀ a₀) (expr.app f₁ a₁) :=
same_function_aux (a₀ :: xs₀) (a₁ :: xs₁) f₀ f₁
| xs₀ xs₁ e₀ e₁ := is_def_eq e₀ e₁ >> return (e₀,xs₀,xs₁)
meta def same_function : expr → expr → tactic (expr × list expr × list expr) :=
same_function_aux [] []
meta def parse_ac_mono_function (l r : expr)
: tactic (expr × expr × list expr × mono_function) :=
do (full_f,ls,rs) ← same_function l r,
(a,c,i,f) ← check_ac l,
if a
then if c
then do
(s,ls,rs) ← monad.join (match_ac
<$> parse_assoc_chain f l
<*> parse_assoc_chain f r),
(l',l_id) ← fold_assoc f i ls,
(r',r_id) ← fold_assoc f i rs,
s' ← fold_assoc1 f s,
return (l',r',l_id ++ r_id,mono_function.assoc_comm f s')
else do -- a ∧ ¬ c
(pre,ls,rs,suff) ← monad.join (match_assoc
<$> parse_assoc_chain f l
<*> parse_assoc_chain f r),
(l',l_id) ← fold_assoc f i ls,
(r',r_id) ← fold_assoc f i rs,
let pre' := fold_assoc1 f pre,
let suff' := fold_assoc1 f suff,
return (l',r',l_id ++ r_id,mono_function.assoc f pre' suff')
else do -- ¬ a
(xs₀,x₀,x₁,xs₁) ← find_one_difference opt ls rs,
return (x₀,x₁,[],mono_function.non_assoc full_f xs₀ xs₁)
meta def parse_ac_mono_function' (l r : pexpr) :=
do l' ← to_expr l,
r' ← to_expr r,
parse_ac_mono_function l' r'
meta def ac_monotonicity_goal : expr → tactic (expr × expr × list expr × ac_mono_ctx)
| `(%%e₀ → %%e₁) :=
do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,
t₀ ← infer_type e₀,
t₁ ← infer_type e₁,
rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) → (x₁ : %%t₁)),
return (e₀, e₁, id_rs,
{ function := f
, left := l, right := r
, to_rel := some $ expr.pi `x binder_info.default
, rel_def := rel_def })
| `(%%e₀ = %%e₁) :=
do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,
t₀ ← infer_type e₀,
t₁ ← infer_type e₁,
rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) = (x₁ : %%t₁)),
return (e₀, e₁, id_rs,
{ function := f
, left := l, right := r
, to_rel := none
, rel_def := rel_def })
| (expr.app (expr.app rel e₀) e₁) :=
do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,
return (e₀, e₁, id_rs,
{ function := f
, left := l, right := r
, to_rel := expr.app ∘ expr.app rel
, rel_def := rel })
| _ := fail "invalid monotonicity goal"
meta def bin_op_left (f : expr) : option expr → expr → expr
| none e := e
| (some e₀) e₁ := f.mk_app [e₀,e₁]
meta def bin_op (f a b : expr) : expr :=
f.mk_app [a,b]
meta def bin_op_right (f : expr) : expr → option expr → expr
| e none := e
| e₀ (some e₁) := f.mk_app [e₀,e₁]
meta def mk_fun_app : mono_function → expr → expr
| (mono_function.non_assoc f x y) z := f.mk_app (x ++ z :: y)
| (mono_function.assoc f x y) z := bin_op_left f x (bin_op_right f z y)
| (mono_function.assoc_comm f x) z := f.mk_app [z,x]
meta inductive mono_law
/- `assoc (l₀,r₀) (r₁,l₁)` gives first how to find rules to prove
x+(y₀+z) R x+(y₁+z);
if that fails, helps prove (x+y₀)+z R (x+y₁)+z -/
| assoc : expr × expr → expr × expr → mono_law
/- `congr r` gives the rule to prove `x = y → f x = f y` -/
| congr : expr → mono_law
| other : expr → mono_law
meta def mono_law.to_tactic_format : mono_law → tactic format
| (mono_law.other e) := do e ← pp e, return format!"other {e}"
| (mono_law.congr r) := do e ← pp r, return format!"congr {e}"
| (mono_law.assoc (x₀,x₁) (y₀,y₁)) :=
do x₀ ← pp x₀,
x₁ ← pp x₁,
y₀ ← pp y₀,
y₁ ← pp y₁,
return format!"assoc {x₀}; {x₁} | {y₀}; {y₁}"
meta instance has_to_tactic_format_mono_law : has_to_tactic_format mono_law :=
{ to_tactic_format := mono_law.to_tactic_format }
meta def mk_rel (ctx : ac_mono_ctx_ne) (f : expr → expr) : expr :=
ctx.to_rel (f ctx.left) (f ctx.right)
meta def mk_congr_args (fn : expr) (xs₀ xs₁ : list expr) (l r : expr) : tactic expr :=
do p ← mk_app `eq [fn.mk_app $ xs₀ ++ l :: xs₁,fn.mk_app $ xs₀ ++ r :: xs₁],
prod.snd <$> solve_aux p
(do iterate_exactly (xs₁.length) (applyc `congr_fun),
applyc `congr_arg)
meta def mk_congr_law (ctx : ac_mono_ctx) : tactic expr :=
match ctx.function with
| (mono_function.assoc f x₀ x₁) :=
if (x₀ <|> x₁).is_some
then mk_congr_args f x₀.to_monad x₁.to_monad ctx.left ctx.right
else failed
| (mono_function.assoc_comm f x₀) := mk_congr_args f [x₀] [] ctx.left ctx.right
| (mono_function.non_assoc f x₀ x₁) := mk_congr_args f x₀ x₁ ctx.left ctx.right
end
meta def mk_pattern (ctx : ac_mono_ctx) : tactic mono_law :=
match (sequence ctx : option (ac_mono_ctx' _)) with
| (some ctx) :=
match ctx.function with
| (mono_function.assoc f (some x) (some y)) :=
return $ mono_law.assoc
( mk_rel ctx (λ i, bin_op f x (bin_op f i y))
, mk_rel ctx (λ i, bin_op f i y))
( mk_rel ctx (λ i, bin_op f (bin_op f x i) y)
, mk_rel ctx (λ i, bin_op f x i))
| (mono_function.assoc f (some x) none) :=
return $ mono_law.other $
mk_rel ctx (λ e, mk_fun_app ctx.function e)
| (mono_function.assoc f none (some y)) :=
return $ mono_law.other $
mk_rel ctx (λ e, mk_fun_app ctx.function e)
| (mono_function.assoc f none none) :=
none
| _ :=
return $ mono_law.other $
mk_rel ctx (λ e, mk_fun_app ctx.function e)
end
| none := mono_law.congr <$> mk_congr_law ctx
end
meta def match_rule (pat : expr) (r : name) : tactic expr :=
do r' ← mk_const r,
t ← infer_type r',
t ← expr.dsimp t { fail_if_unchanged := ff } tt [] [
simp_arg_type.expr ``(monotone), simp_arg_type.expr ``(strict_mono)],
match_rule_head pat [] r' t
meta def find_lemma (pat : expr) : list name → tactic (list expr)
| [] := return []
| (r :: rs) :=
do (cons <$> match_rule pat r <|> pure id) <*> find_lemma rs
meta def match_chaining_rules (ls : list name) (x₀ x₁ : expr) : tactic (list expr) :=
do x' ← to_expr ``(%%x₁ → %%x₀),
r₀ ← find_lemma x' ls,
r₁ ← find_lemma x₁ ls,
return (expr.app <$> r₀ <*> r₁)
meta def find_rule (ls : list name) : mono_law → tactic (list expr)
| (mono_law.assoc (x₀,x₁) (y₀,y₁)) :=
(match_chaining_rules ls x₀ x₁)
<|> (match_chaining_rules ls y₀ y₁)
| (mono_law.congr r) := return [r]
| (mono_law.other p) := find_lemma p ls
universes u v
def apply_rel {α : Sort u} (R : α → α → Sort v) {x y : α}
(x' y' : α)
(h : R x y)
(hx : x = x')
(hy : y = y')
: R x' y' :=
by { rw [← hx,← hy], apply h }
meta def ac_refine (e : expr) : tactic unit :=
refine ``(eq.mp _ %%e) ; ac_refl
meta def one_line (e : expr) : tactic format :=
do lbl ← pp e,
asm ← infer_type e >>= pp,
return format!"\t{asm}\n"
meta def side_conditions (e : expr) : tactic format :=
do let vs := e.list_meta_vars,
ts ← mmap one_line vs.tail,
let r := e.get_app_fn.const_name,
return format!"{r}:\n{format.join ts}"
open monad
/-- tactic-facing function, similar to `interactive.tactic.generalize` with the
exception that meta variables -/
private meta def monotonicity.generalize' (h : name) (v : expr) (x : name) : tactic (expr × expr) :=
do tgt ← target,
t ← infer_type v,
tgt' ← do
{ ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize v x >> target),
to_expr ``(λ y : %%t, Π x, y = x → %%(tgt'.binding_body.lift_vars 0 1)) }
<|> to_expr ``(λ y : %%t, Π x, %%v = x → %%tgt),
t ← head_beta (tgt' v) >>= assert h,
swap,
r ← mk_eq_refl v,
solve1 $ tactic.exact (t v r),
prod.mk <$> tactic.intro x <*> tactic.intro h
private meta def hide_meta_vars (tac : list expr → tactic unit) : tactic unit :=
focus1 $
do tgt ← target >>= instantiate_mvars,
tactic.change tgt,
ctx ← local_context,
let vs := tgt.list_meta_vars,
vs' ← mmap (λ v,
do h ← get_unused_name `h,
x ← get_unused_name `x,
prod.snd <$> monotonicity.generalize' h v x) vs,
tac ctx;
vs'.mmap' (try ∘ tactic.subst)
meta def hide_meta_vars' (tac : itactic) : itactic :=
hide_meta_vars $ λ _, tac
end config
meta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
set_goals [v],
target >>= instantiate_mvars >>= tactic.change,
tac, done,
set_goals $ gs
def list.minimum_on {α β} [linear_order β] (f : α → β) : list α → list α
| [] := []
| (x :: xs) := prod.snd $ xs.foldl (λ ⟨k,a⟩ b,
let k' := f b in
if k < k' then (k,a)
else if k' < k then (k', [b])
else (k,b :: a)) (f x, [x])
open format mono_selection
meta def best_match {β} (xs : list expr) (tac : expr → tactic β) : tactic unit :=
do t ← target,
xs ← xs.mmap (λ x,
try_core $ prod.mk x <$> solve_aux t (tac x >> get_goals)),
let xs := xs.filter_map id,
let r := list.minimum_on (list.length ∘ prod.fst ∘ prod.snd) xs,
match r with
| [(_,gs,pr)] := tactic.exact pr >> set_goals gs
| [] := fail "no good match found"
| _ :=
do lmms ← r.mmap (λ ⟨l,gs,_⟩,
do ts ← gs.mmap infer_type,
msg ← ts.mmap pp,
pure $ foldl compose "\n\n" $
list.intersperse "\n" $ to_fmt l.get_app_fn.const_name :: msg),
let msg := foldl compose "" lmms,
fail format!("ambiguous match: {msg}\n\n" ++
"Tip: try asserting a side condition to distinguish between the lemmas")
end
meta def mono_aux (dir : parse side) :
tactic unit :=
do t ← target >>= instantiate_mvars,
ns ← get_monotonicity_lemmas t dir,
asms ← local_context,
rs ← find_lemma asms t ns,
focus1 $ () <$ best_match rs (λ law, tactic.refine $ to_pexpr law)
/--
- `mono` applies a monotonicity rule.
- `mono*` applies monotonicity rules repetitively.
- `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed
propositions. Those help to select the right monotonicity rule.
- `mono left` or `mono right` is useful when proving strict orderings:
for `x + y < w + z` could be broken down into either
- left: `x ≤ w` and `y < z` or
- right: `x < w` and `y ≤ z`
- `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono.
- The general syntax is
`mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg?`
To use it, first import `tactic.monotonicity`.
Here is an example of mono:
```lean
example (x y z k : ℤ)
(h : 3 ≤ (4 : ℤ))
(h' : z ≤ y) :
(k + 3 + x) - y ≤ (k + 4 + x) - z :=
begin
mono, -- unfold `(-)`, apply add_le_add
{ -- ⊢ k + 3 + x ≤ k + 4 + x
mono, -- apply add_le_add, refl
-- ⊢ k + 3 ≤ k + 4
mono },
{ -- ⊢ -y ≤ -z
mono /- apply neg_le_neg -/ }
end
```
More succinctly, we can prove the same goal as:
```lean
example (x y z k : ℤ)
(h : 3 ≤ (4 : ℤ))
(h' : z ≤ y) :
(k + 3 + x) - y ≤ (k + 4 + x) - z :=
by mono*
```
-/
meta def mono (many : parse (tk "*")?)
(dir : parse side)
(hyps : parse $ tk "with" *> pexpr_list_or_texpr <|> pure [])
(simp_rules : parse $ tk "using" *> simp_arg_list <|> pure []) :
tactic unit :=
do hyps ← hyps.mmap (λ p, to_expr p >>= mk_meta_var),
hyps.mmap' (λ pr, do h ← get_unused_name `h, note h none pr),
when (¬ simp_rules.empty) (simp_core { } failed tt simp_rules [] (loc.ns [none]) >> skip),
if many.is_some
then repeat $ mono_aux dir
else mono_aux dir,
gs ← get_goals,
set_goals $ hyps ++ gs
add_tactic_doc
{ name := "mono",
category := doc_category.tactic,
decl_names := [`tactic.interactive.mono],
tags := ["monotonicity"] }
/--
transforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas
marked as `monotonic`.
Special care is taken when `f` is the repeated application of an
associative operator and if the operator is commutative
-/
meta def ac_mono_aux (cfg : mono_cfg := { mono_cfg . }) :
tactic unit :=
hide_meta_vars $ λ asms,
do try `[simp only [sub_eq_add_neg]],
tgt ← target >>= instantiate_mvars,
(l,r,id_rs,g) ← ac_monotonicity_goal cfg tgt
<|> fail "monotonic context not found",
ns ← get_monotonicity_lemmas tgt both,
p ← mk_pattern g,
rules ← find_rule asms ns p <|> fail "no applicable rules found",
when (rules = []) (fail "no applicable rules found"),
err ← format.join <$> mmap side_conditions rules,
focus1 $ best_match rules (λ rule, do
t₀ ← mk_meta_var `(Prop),
v₀ ← mk_meta_var t₀,
t₁ ← mk_meta_var `(Prop),
v₁ ← mk_meta_var t₁,
tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v₀ %%v₁),
solve_mvar v₀ (try (any_of id_rs rewrite_target) >>
( done <|>
refl <|>
ac_refl <|>
`[simp only [is_associative.assoc]]) ),
solve_mvar v₁ (try (any_of id_rs rewrite_target) >>
( done <|>
refl <|>
ac_refl <|>
`[simp only [is_associative.assoc]]) ),
n ← num_goals,
iterate_exactly (n-1) (try $ solve1 $ apply_instance <|>
tactic.solve_by_elim { lemmas := some asms }))
open sum nat
/-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/
meta def repeat_until_or_at_most : nat → tactic unit → tactic unit → tactic unit
| 0 t _ := fail "too many applications"
| (succ n) t u := u <|> (t >> repeat_until_or_at_most n t u)
meta def repeat_until : tactic unit → tactic unit → tactic unit :=
repeat_until_or_at_most 100000
@[derive _root_.has_reflect, derive _root_.inhabited]
inductive rep_arity : Type
| one | exactly (n : ℕ) | many
meta def repeat_or_not : rep_arity → tactic unit → option (tactic unit) → tactic unit
| rep_arity.one tac none := tac
| rep_arity.many tac none := repeat tac
| (rep_arity.exactly n) tac none := iterate_exactly' n tac
| rep_arity.one tac (some until) := tac >> until
| rep_arity.many tac (some until) := repeat_until tac until
| (rep_arity.exactly n) tac (some until) := iterate_exactly n tac >> until
meta def assert_or_rule : lean.parser (pexpr ⊕ pexpr) :=
(tk ":=" *> inl <$> texpr <|> (tk ":" *> inr <$> texpr))
meta def arity : lean.parser rep_arity :=
tk "*" *> pure rep_arity.many <|>
rep_arity.exactly <$> (tk "^" *> small_nat) <|>
pure rep_arity.one
/--
`ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a
monotonic function `f` to `x ≺ y`.
`ac_mono*` unwraps monotonic functions until it can't.
`ac_mono^k`, for some literal number `k` applies monotonicity `k`
times.
`ac_mono := h`, with `h` a hypothesis, unwraps monotonic functions and
uses `h` to solve the remaining goal. Can be combined with `*` or `^k`:
`ac_mono* := h`
`ac_mono : p` asserts `p` and uses it to discharge the goal result
unwrapping a series of monotonic functions. Can be combined with * or
^k: `ac_mono* : p`
In the case where `f` is an associative or commutative operator,
`ac_mono` will consider any possible permutation of its arguments and
use the one the minimizes the difference between the left-hand side
and the right-hand side.
To use it, first import `tactic.monotonicity`.
`ac_mono` can be used as follows:
```lean
example (x y z k m n : ℕ)
(h₀ : z ≥ 0)
(h₁ : x ≤ y) :
(m + x + n) * z + k ≤ z * (y + n + m) + k :=
begin
ac_mono,
-- ⊢ (m + x + n) * z ≤ z * (y + n + m)
ac_mono,
-- ⊢ m + x + n ≤ y + n + m
ac_mono,
end
```
As with `mono*`, `ac_mono*` solves the goal in one go and so does
`ac_mono* := h₁`. The latter syntax becomes especially interesting in the
following example:
```lean
example (x y z k m n : ℕ)
(h₀ : z ≥ 0)
(h₁ : m + x + n ≤ y + n + m) :
(m + x + n) * z + k ≤ z * (y + n + m) + k :=
by ac_mono* := h₁.
```
By giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to
stop earlier than it would normally would.
-/
meta def ac_mono (rep : parse arity) :
parse assert_or_rule? →
opt_param mono_cfg { mono_cfg . } →
tactic unit
| none opt := focus1 $ repeat_or_not rep (ac_mono_aux opt) none
| (some (inl h)) opt :=
do focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> to_expr h >>= ac_refine)
| (some (inr t)) opt :=
do h ← i_to_expr t >>= assert `h,
tactic.swap,
focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> ac_refine h)
/-
TODO(Simon): with `ac_mono := h` and `ac_mono : p` split the remaining
gaol if the provided rule does not solve it completely.
-/
add_tactic_doc
{ name := "ac_mono",
category := doc_category.tactic,
decl_names := [`tactic.interactive.ac_mono],
tags := ["monotonicity"] }
attribute [mono] and.imp or.imp
end tactic.interactive
|
d59576786e5256b5aad584fd0188240461221233 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/set_theory/surreal.lean | 2efc64cbeccbbecac9381aad0d593c6ff49051d9 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,129 | lean | /-
Copyright (c) 2019 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Scott Morrison
-/
import set_theory.pgame
/-!
# Surreal numbers
The basic theory of surreal numbers, built on top of the theory of combinatorial (pre-)games.
A pregame is `numeric` if all the Left options are strictly smaller than all the Right options, and
all those options are themselves numeric. In terms of combinatorial games, the numeric games have
"frozen"; you can only make your position worse by playing, and Left is some definite "number" of
moves ahead (or behind) Right.
A surreal number is an equivalence class of numeric pregames.
In fact, the surreals form a complete ordered field, containing a copy of the reals (and much else
besides!) but we do not yet have a complete development.
## Order properties
Surreal numbers inherit the relations `≤` and `<` from games, and these relations satisfy the axioms
of a partial order (recall that `x < y ↔ x ≤ y ∧ ¬ y ≤ x` did not hold for games).
## Algebraic operations
At this point, we have defined addition and negation (from pregames), and shown that surreals form
an additive semigroup. It would be very little work to finish showing that the surreals form an
ordered commutative group.
We define the operations of multiplication and inverse on surreals, but do not yet establish any of
the necessary properties to show the surreals form an ordered field.
## Embeddings
It would be nice projects to define the group homomorphism `surreal → game`, and also `ℤ → surreal`,
and then the homomorphic inclusion of the dyadic rationals into surreals, and finally
via dyadic Dedekind cuts the homomorphic inclusion of the reals into the surreals.
One can also map all the ordinals into the surreals!
## References
* [Conway, *On numbers and games*][conway2001]
-/
universes u
namespace pgame
/-! Multiplicative operations can be defined at the level of pre-games, but as
they are only useful on surreal numbers, we define them here. -/
/-- The product of `x = {xL | xR}` and `y = {yL | yR}` is
`{xL*y + x*yL - xL*yL, xR*y + x*yR - xR*yR | xL*y + x*yR - xL*yR, x*yL + xR*y - xR*yL }`. -/
def mul (x y : pgame) : pgame :=
begin
induction x with xl xr xL xR IHxl IHxr generalizing y,
induction y with yl yr yL yR IHyl IHyr,
have y := mk yl yr yL yR,
refine ⟨xl × yl ⊕ xr × yr, xl × yr ⊕ xr × yl, _, _⟩; rintro (⟨i, j⟩ | ⟨i, j⟩),
{ exact IHxl i y + IHyl j - IHxl i (yL j) },
{ exact IHxr i y + IHyr j - IHxr i (yR j) },
{ exact IHxl i y + IHyr j - IHxl i (yR j) },
{ exact IHxr i y + IHyl j - IHxr i (yL j) }
end
instance : has_mul pgame := ⟨mul⟩
/-- Because the two halves of the definition of `inv` produce more elements
of each side, we have to define the two families inductively.
This is the indexing set for the function, and `inv_val` is the function part. -/
inductive inv_ty (l r : Type u) : bool → Type u
| zero : inv_ty ff
| left₁ : r → inv_ty ff → inv_ty ff
| left₂ : l → inv_ty tt → inv_ty ff
| right₁ : l → inv_ty ff → inv_ty tt
| right₂ : r → inv_ty tt → inv_ty tt
/-- Because the two halves of the definition of `inv` produce more elements
of each side, we have to define the two families inductively.
This is the function part, defined by recursion on `inv_ty`. -/
def inv_val {l r} (L : l → pgame) (R : r → pgame)
(IHl : l → pgame) (IHr : r → pgame) : ∀ {b}, inv_ty l r b → pgame
| _ inv_ty.zero := 0
| _ (inv_ty.left₁ i j) := (1 + (R i - mk l r L R) * inv_val j) * IHr i
| _ (inv_ty.left₂ i j) := (1 + (L i - mk l r L R) * inv_val j) * IHl i
| _ (inv_ty.right₁ i j) := (1 + (L i - mk l r L R) * inv_val j) * IHl i
| _ (inv_ty.right₂ i j) := (1 + (R i - mk l r L R) * inv_val j) * IHr i
/-- The inverse of a positive surreal number `x = {L | R}` is
given by `x⁻¹ = {0,
(1 + (R - x) * x⁻¹L) * R, (1 + (L - x) * x⁻¹R) * L |
(1 + (L - x) * x⁻¹L) * L, (1 + (R - x) * x⁻¹R) * R}`.
Because the two halves `x⁻¹L, x⁻¹R` of `x⁻¹` are used in their own
definition, the sets and elements are inductively generated. -/
def inv' : pgame → pgame
| ⟨l, r, L, R⟩ :=
let l' := {i // 0 < L i},
L' : l' → pgame := λ i, L i.1,
IHl' : l' → pgame := λ i, inv' (L i.1),
IHr := λ i, inv' (R i) in
⟨inv_ty l' r ff, inv_ty l' r tt,
inv_val L' R IHl' IHr, inv_val L' R IHl' IHr⟩
/-- The inverse of a surreal number in terms of the inverse on positive surreals. -/
noncomputable def inv (x : pgame) : pgame :=
by classical; exact
if x = 0 then 0 else if 0 < x then inv' x else inv' (-x)
noncomputable instance : has_inv pgame := ⟨inv⟩
noncomputable instance : has_div pgame := ⟨λ x y, x * y⁻¹⟩
/-- A pre-game is numeric if everything in the L set is less than everything in the R set,
and all the elements of L and R are also numeric. -/
def numeric : pgame → Prop
| ⟨l, r, L, R⟩ :=
(∀ i j, L i < R j) ∧ (∀ i, numeric (L i)) ∧ (∀ i, numeric (R i))
lemma numeric.move_left {x : pgame} (o : numeric x) (i : x.left_moves) :
numeric (x.move_left i) :=
begin
cases x with xl xr xL xR,
exact o.2.1 i,
end
lemma numeric.move_right {x : pgame} (o : numeric x) (j : x.right_moves) :
numeric (x.move_right j) :=
begin
cases x with xl xr xL xR,
exact o.2.2 j,
end
@[elab_as_eliminator]
theorem numeric_rec {C : pgame → Prop}
(H : ∀ l r (L : l → pgame) (R : r → pgame),
(∀ i j, L i < R j) → (∀ i, numeric (L i)) → (∀ i, numeric (R i)) →
(∀ i, C (L i)) → (∀ i, C (R i)) → C ⟨l, r, L, R⟩) :
∀ x, numeric x → C x
| ⟨l, r, L, R⟩ ⟨h, hl, hr⟩ :=
H _ _ _ _ h hl hr (λ i, numeric_rec _ (hl i)) (λ i, numeric_rec _ (hr i))
theorem lt_asymm {x y : pgame} (ox : numeric x) (oy : numeric y) : x < y → ¬ y < x :=
begin
refine numeric_rec (λ xl xr xL xR hx oxl oxr IHxl IHxr, _) x ox y oy,
refine numeric_rec (λ yl yr yL yR hy oyl oyr IHyl IHyr, _),
rw [mk_lt_mk, mk_lt_mk], rintro (⟨i, h₁⟩ | ⟨j, h₁⟩) (⟨i, h₂⟩ | ⟨j, h₂⟩),
{ exact IHxl _ _ (oyl _) (lt_of_le_mk h₁) (lt_of_le_mk h₂) },
{ exact not_lt.2 (le_trans h₂ h₁) (hy _ _) },
{ exact not_lt.2 (le_trans h₁ h₂) (hx _ _) },
{ exact IHxr _ _ (oyr _) (lt_of_mk_le h₁) (lt_of_mk_le h₂) },
end
theorem le_of_lt {x y : pgame} (ox : numeric x) (oy : numeric y) (h : x < y) : x ≤ y :=
not_lt.1 (lt_asymm ox oy h)
/-- On numeric pre-games, `<` and `≤` satisfy the axioms of a partial order (even though they
don't on all pre-games). -/
theorem lt_iff_le_not_le {x y : pgame} (ox : numeric x) (oy : numeric y) :
x < y ↔ x ≤ y ∧ ¬ y ≤ x :=
⟨λ h, ⟨le_of_lt ox oy h, not_le.2 h⟩, λ h, not_le.1 h.2⟩
theorem numeric_zero : numeric 0 :=
⟨by rintros ⟨⟩ ⟨⟩, ⟨by rintros ⟨⟩, by rintros ⟨⟩⟩⟩
theorem numeric_one : numeric 1 :=
⟨by rintros ⟨⟩ ⟨⟩, ⟨λ x, numeric_zero, by rintros ⟨⟩⟩⟩
theorem numeric_neg : Π {x : pgame} (o : numeric x), numeric (-x)
| ⟨l, r, L, R⟩ o :=
⟨λ j i, lt_iff_neg_gt.1 (o.1 i j),
⟨λ j, numeric_neg (o.2.2 j), λ i, numeric_neg (o.2.1 i)⟩⟩
theorem numeric.move_left_lt {x : pgame.{u}} (o : numeric x) (i : x.left_moves) :
x.move_left i < x :=
begin
rw lt_def_le,
left,
use i,
end
theorem numeric.move_left_le {x : pgame} (o : numeric x) (i : x.left_moves) :
x.move_left i ≤ x :=
le_of_lt (o.move_left i) o (o.move_left_lt i)
theorem numeric.lt_move_right {x : pgame} (o : numeric x) (j : x.right_moves) :
x < x.move_right j :=
begin
rw lt_def_le,
right,
use j,
end
theorem numeric.le_move_right {x : pgame} (o : numeric x) (j : x.right_moves) :
x ≤ x.move_right j :=
le_of_lt o (o.move_right j) (o.lt_move_right j)
theorem add_lt_add
{w x y z : pgame.{u}} (ow : numeric w) (ox : numeric x) (oy : numeric y) (oz : numeric z)
(hwx : w < x) (hyz : y < z) : w + y < x + z :=
begin
rw lt_def_le at *,
rcases hwx with ⟨ix, hix⟩|⟨jw, hjw⟩;
rcases hyz with ⟨iz, hiz⟩|⟨jy, hjy⟩,
{ left,
use (left_moves_add x z).symm (sum.inl ix),
simp only [add_move_left_inl],
calc w + y ≤ move_left x ix + y : add_le_add_right hix
... ≤ move_left x ix + move_left z iz : add_le_add_left hiz
... ≤ move_left x ix + z : add_le_add_left (oz.move_left_le iz) },
{ left,
use (left_moves_add x z).symm (sum.inl ix),
simp only [add_move_left_inl],
calc w + y ≤ move_left x ix + y : add_le_add_right hix
... ≤ move_left x ix + move_right y jy : add_le_add_left (oy.le_move_right jy)
... ≤ move_left x ix + z : add_le_add_left hjy },
{ right,
use (right_moves_add w y).symm (sum.inl jw),
simp only [add_move_right_inl],
calc move_right w jw + y ≤ x + y : add_le_add_right hjw
... ≤ x + move_left z iz : add_le_add_left hiz
... ≤ x + z : add_le_add_left (oz.move_left_le iz), },
{ right,
use (right_moves_add w y).symm (sum.inl jw),
simp only [add_move_right_inl],
calc move_right w jw + y ≤ x + y : add_le_add_right hjw
... ≤ x + move_right y jy : add_le_add_left (oy.le_move_right jy)
... ≤ x + z : add_le_add_left hjy, },
end
theorem numeric_add : Π {x y : pgame} (ox : numeric x) (oy : numeric y), numeric (x + y)
| ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ox oy :=
⟨begin
rintros (ix|iy) (jx|jy),
{ show xL ix + ⟨yl, yr, yL, yR⟩ < xR jx + ⟨yl, yr, yL, yR⟩,
exact add_lt_add_right (ox.1 ix jx), },
{ show xL ix + ⟨yl, yr, yL, yR⟩ < ⟨xl, xr, xL, xR⟩ + yR jy,
apply add_lt_add (ox.move_left ix) ox oy (oy.move_right jy),
apply ox.move_left_lt,
apply oy.lt_move_right },
{ -- show ⟨xl, xr, xL, xR⟩ + yL iy < xR jx + ⟨yl, yr, yL, yR⟩, -- fails?
apply add_lt_add ox (ox.move_right jx) (oy.move_left iy) oy,
apply ox.lt_move_right,
apply oy.move_left_lt, },
{ -- show ⟨xl, xr, xL, xR⟩ + yL iy < ⟨xl, xr, xL, xR⟩ + yR jy, -- fails?
exact @add_lt_add_left ⟨xl, xr, xL, xR⟩ _ _ (oy.1 iy jy), }
end,
begin
split,
{ rintros (ix|iy),
{ apply numeric_add (ox.move_left ix) oy, },
{ apply numeric_add ox (oy.move_left iy), }, },
{ rintros (jx|jy),
{ apply numeric_add (ox.move_right jx) oy, },
{ apply numeric_add ox (oy.move_right jy), }, },
end⟩
using_well_founded { dec_tac := pgame_wf_tac }
-- TODO prove
-- theorem numeric_nat (n : ℕ) : numeric n := sorry
-- theorem numeric_omega : numeric omega := sorry
end pgame
/-- The equivalence on numeric pre-games. -/
def surreal.equiv (x y : {x // pgame.numeric x}) : Prop := x.1.equiv y.1
local infix ` ≈ ` := surreal.equiv
instance surreal.setoid : setoid {x // pgame.numeric x} :=
⟨λ x y, x.1.equiv y.1,
λ x, pgame.equiv_refl _,
λ x y, pgame.equiv_symm,
λ x y z, pgame.equiv_trans⟩
/-- The type of surreal numbers. These are the numeric pre-games quotiented
by the equivalence relation `x ≈ y ↔ x ≤ y ∧ y ≤ x`. In the quotient,
the order becomes a total order. -/
def surreal := quotient surreal.setoid
namespace surreal
open pgame
/-- Construct a surreal number from a numeric pre-game. -/
def mk (x : pgame) (h : x.numeric) : surreal := quotient.mk ⟨x, h⟩
instance : has_zero surreal :=
{ zero := ⟦⟨0, numeric_zero⟩⟧ }
instance : has_one surreal :=
{ one := ⟦⟨1, numeric_one⟩⟧ }
instance : inhabited surreal := ⟨0⟩
/-- Lift an equivalence-respecting function on pre-games to surreals. -/
def lift {α} (f : ∀ x, numeric x → α)
(H : ∀ {x y} (hx : numeric x) (hy : numeric y), x.equiv y → f x hx = f y hy) : surreal → α :=
quotient.lift (λ x : {x // numeric x}, f x.1 x.2) (λ x y, H x.2 y.2)
/-- Lift a binary equivalence-respecting function on pre-games to surreals. -/
def lift₂ {α} (f : ∀ x y, numeric x → numeric y → α)
(H : ∀ {x₁ y₁ x₂ y₂} (ox₁ : numeric x₁) (oy₁ : numeric y₁) (ox₂ : numeric x₂) (oy₂ : numeric y₂),
x₁.equiv x₂ → y₁.equiv y₂ → f x₁ y₁ ox₁ oy₁ = f x₂ y₂ ox₂ oy₂) : surreal → surreal → α :=
lift (λ x ox, lift (λ y oy, f x y ox oy) (λ y₁ y₂ oy₁ oy₂ h, H _ _ _ _ (equiv_refl _) h))
(λ x₁ x₂ ox₁ ox₂ h, funext $ quotient.ind $ by exact λ ⟨y, oy⟩, H _ _ _ _ h (equiv_refl _))
/-- The relation `x ≤ y` on surreals. -/
def le : surreal → surreal → Prop :=
lift₂ (λ x y _ _, x ≤ y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (le_congr hx hy))
/-- The relation `x < y` on surreals. -/
def lt : surreal → surreal → Prop :=
lift₂ (λ x y _ _, x < y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (lt_congr hx hy))
theorem not_le : ∀ {x y : surreal}, ¬ le x y ↔ lt y x :=
by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; exact not_le
instance : preorder surreal :=
{ le := le,
lt := lt,
le_refl := by rintro ⟨⟨x, ox⟩⟩; exact le_refl _,
le_trans := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩ ⟨⟨z, oz⟩⟩; exact le_trans,
lt_iff_le_not_le := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; exact lt_iff_le_not_le ox oy }
instance : partial_order surreal :=
{ le_antisymm := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩ h₁ h₂; exact quot.sound ⟨h₁, h₂⟩,
..surreal.preorder }
noncomputable instance : linear_order surreal :=
{ le_total := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; classical; exact
or_iff_not_imp_left.2 (λ h, le_of_lt oy ox (pgame.not_le.1 h)),
decidable_le := classical.dec_rel _,
..surreal.partial_order }
/-- Addition on surreals is inherited from pre-game addition:
the sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/
def add : surreal → surreal → surreal :=
surreal.lift₂
(λ (x y : pgame) (ox) (oy), ⟦⟨x + y, numeric_add ox oy⟩⟧)
(λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, quot.sound (pgame.add_congr hx hy))
instance : has_add surreal := ⟨add⟩
theorem add_assoc : ∀ (x y z : surreal), (x + y) + z = x + (y + z) :=
begin
rintros ⟨x⟩ ⟨y⟩ ⟨z⟩,
apply quot.sound,
exact add_assoc_equiv,
end
instance : add_semigroup surreal :=
{ add_assoc := add_assoc,
..(by apply_instance : has_add surreal) }
-- We conclude with some ideas for further work on surreals; these would make fun projects.
-- TODO construct the remaining instances:
-- add_monoid, add_group, add_comm_semigroup, add_comm_group, ordered_add_comm_group,
-- as per the instances for `game`
-- TODO define the inclusion of groups `surreal → game`
-- TODO define the dyadic rationals, and show they map into the surreals via the formula
-- m / 2^n ↦ { (m-1) / 2^n | (m+1) / 2^n }
-- TODO show this is a group homomorphism, and injective
-- TODO map the reals into the surreals, using dyadic Dedekind cuts
-- TODO show this is a group homomorphism, and injective
-- TODO define the field structure on the surreals
-- TODO show the maps from the dyadic rationals and from the reals
-- into the surreals are multiplicative
end surreal
|
43835c0d7579a616941f20b27d2ed92bd0f6767d | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/algebra/module/determinant.lean | 4613a6f35a2c7e045f7adc7c8d15539355044b5d | [
"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 | 1,189 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo, Yury Kudryashov, Frédéric Dupuis,
Heather Macbeth
-/
import topology.algebra.module.basic
import linear_algebra.determinant
/-!
# The determinant of a continuous linear map.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
namespace continuous_linear_map
/-- The determinant of a continuous linear map, mainly as a convenience device to be able to
write `A.det` instead of `(A : M →ₗ[R] M).det`. -/
@[reducible] noncomputable def det {R : Type*} [comm_ring R]
{M : Type*} [topological_space M] [add_comm_group M] [module R M] (A : M →L[R] M) : R :=
linear_map.det (A : M →ₗ[R] M)
end continuous_linear_map
namespace continuous_linear_equiv
@[simp] lemma det_coe_symm {R : Type*} [field R]
{M : Type*} [topological_space M] [add_comm_group M] [module R M] (A : M ≃L[R] M) :
(A.symm : M →L[R] M).det = (A : M →L[R] M).det ⁻¹ :=
linear_equiv.det_coe_symm A.to_linear_equiv
end continuous_linear_equiv
|
74da09b29e17102e644222c85940ac9a8a1d7605 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/data/rat/denumerable.lean | e4a435c7d012b8a353ce5cfad9b8307b42b556fb | [
"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 | 1,062 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.rat
import set_theory.cardinal
namespace rat
open denumerable
instance : infinite ℚ :=
infinite.of_injective (coe : ℕ → ℚ) nat.cast_injective
private def denumerable_aux : ℚ ≃ { x : ℤ × ℕ // 0 < x.2 ∧ x.1.nat_abs.coprime x.2 } :=
{ to_fun := λ x, ⟨⟨x.1, x.2⟩, x.3, x.4⟩,
inv_fun := λ x, ⟨x.1.1, x.1.2, x.2.1, x.2.2⟩,
left_inv := λ ⟨_, _, _, _⟩, rfl,
right_inv := λ ⟨⟨_, _⟩, _, _⟩, rfl }
instance : denumerable ℚ :=
begin
let T := { x : ℤ × ℕ // 0 < x.2 ∧ x.1.nat_abs.coprime x.2 },
letI : infinite T := infinite.of_injective _ denumerable_aux.injective,
letI : encodable T := encodable.subtype,
letI : denumerable T := of_encodable_of_infinite T,
exact denumerable.of_equiv T denumerable_aux
end
end rat
namespace cardinal
lemma mk_rat : cardinal.mk ℚ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
end cardinal
|
f8e5347702053ee50a45509035d1df79e2b272bd | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/induction_generalizing_bug.lean | 33a093e9d6978c2cb2ada81337d53aeb6d4ff4cf | [
"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 | 138 | lean | open nat
example (n : nat) (h : n > 0) : succ n > 0 ∧ n = n :=
begin
split,
induction n generalizing h,
all_goals { admit },
end
|
d96f260fc406cf454c5f00aa5665c64ba922d9ac | 947b78d97130d56365ae2ec264df196ce769371a | /stage0/src/Lean/Compiler/IR/EmitC.lean | e760088496f4f667374eea67f5402568495e85ad | [
"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 | 24,581 | 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.Runtime
import Lean.Compiler.NameMangling
import Lean.Compiler.ExportAttr
import Lean.Compiler.InitAttr
import Lean.Compiler.IR.CompilerM
import Lean.Compiler.IR.EmitUtil
import Lean.Compiler.IR.NormIds
import Lean.Compiler.IR.SimpCase
import Lean.Compiler.IR.Boxing
namespace Lean
namespace IR
open ExplicitBoxing (requiresBoxedVersion mkBoxedName isBoxedName)
namespace EmitC
def leanMainFn := "_lean_main"
structure Context :=
(env : Environment)
(modName : Name)
(jpMap : JPParamsMap := {})
(mainFn : FunId := arbitrary _)
(mainParams : Array Param := #[])
abbrev M := ReaderT Context (EStateM String String)
def getEnv : M Environment := Context.env <$> read
def getModName : M Name := Context.modName <$> read
def getDecl (n : Name) : M Decl := do
env ← getEnv;
match findEnvDecl env n with
| some d => pure d
| none => throw ("unknown declaration '" ++ toString n ++ "'")
@[inline] def emit {α : Type} [HasToString α] (a : α) : M Unit :=
modify (fun out => out ++ toString a)
@[inline] def emitLn {α : Type} [HasToString α] (a : α) : M Unit :=
emit a *> emit "\n"
def emitLns {α : Type} [HasToString α] (as : List α) : M Unit :=
as.forM $ fun a => emitLn a
def argToCString (x : Arg) : String :=
match x with
| Arg.var x => toString x
| _ => "lean_box(0)"
def emitArg (x : Arg) : M Unit :=
emit (argToCString x)
def toCType : IRType → String
| IRType.float => "double"
| IRType.uint8 => "uint8_t"
| IRType.uint16 => "uint16_t"
| IRType.uint32 => "uint32_t"
| IRType.uint64 => "uint64_t"
| IRType.usize => "size_t"
| IRType.object => "lean_object*"
| IRType.tobject => "lean_object*"
| IRType.irrelevant => "lean_object*"
| IRType.struct _ _ => panic! "not implemented yet"
| IRType.union _ _ => panic! "not implemented yet"
def throwInvalidExportName {α : Type} (n : Name) : M α :=
throw ("invalid export name '" ++ toString n ++ "'")
def toCName (n : Name) : M String := do
env ← getEnv;
-- TODO: we should support simple export names only
match getExportNameFor env n with
| some (Name.str Name.anonymous s _) => pure s
| some _ => throwInvalidExportName n
| none => if n == `main then pure leanMainFn else pure n.mangle
def emitCName (n : Name) : M Unit :=
toCName n >>= emit
def toCInitName (n : Name) : M String := do
env ← getEnv;
-- TODO: we should support simple export names only
match getExportNameFor env n with
| some (Name.str Name.anonymous s _) => pure $ "_init_" ++ s
| some _ => throwInvalidExportName n
| none => pure ("_init_" ++ n.mangle)
def emitCInitName (n : Name) : M Unit :=
toCInitName n >>= emit
def emitFnDeclAux (decl : Decl) (cppBaseName : String) (addExternForConsts : Bool) : M Unit := do
let ps := decl.params;
env ← getEnv;
when (ps.isEmpty && addExternForConsts) (emit "extern ");
emit (toCType decl.resultType ++ " " ++ cppBaseName);
unless (ps.isEmpty) $ do {
emit "(";
-- We omit irrelevant parameters for extern constants
let ps := if isExternC env decl.name then ps.filter (fun p => !p.ty.isIrrelevant) else ps;
if ps.size > closureMaxArgs && isBoxedName decl.name then
emit "lean_object**"
else
ps.size.forM $ fun i => do {
when (i > 0) (emit ", ");
emit (toCType (ps.get! i).ty)
};
emit ")"
};
emitLn ";"
def emitFnDecl (decl : Decl) (addExternForConsts : Bool) : M Unit := do
cppBaseName ← toCName decl.name;
emitFnDeclAux decl cppBaseName addExternForConsts
def emitExternDeclAux (decl : Decl) (cNameStr : String) : M Unit := do
let cName := mkNameSimple cNameStr;
env ← getEnv;
let extC := isExternC env decl.name;
emitFnDeclAux decl cNameStr (!extC)
def emitFnDecls : M Unit := do
env ← getEnv;
let decls := getDecls env;
let modDecls : NameSet := decls.foldl (fun s d => s.insert d.name) {};
let usedDecls : NameSet := decls.foldl (fun s d => collectUsedDecls env d (s.insert d.name)) {};
let usedDecls := usedDecls.toList;
usedDecls.forM $ fun n => do
decl ← getDecl n;
match getExternNameFor env `c decl.name with
| some cName => emitExternDeclAux decl cName
| none => emitFnDecl decl (!modDecls.contains n)
def emitMainFn : M Unit := do
d ← getDecl `main;
match d with
| Decl.fdecl f xs t b => do
unless (xs.size == 2 || xs.size == 1) (throw "invalid main function, incorrect arity when generating code");
env ← getEnv;
let usesLeanAPI := usesModuleFrom env `Lean;
if usesLeanAPI then
emitLn "void lean_initialize();"
else
emitLn "void lean_initialize_runtime_module();";
emitLn "
#if defined(WIN32) || defined(_WIN32)
#include <windows.h>
#endif
int main(int argc, char ** argv) {
#if defined(WIN32) || defined(_WIN32)
SetErrorMode(SEM_FAILCRITICALERRORS);
#endif
lean_object* in; lean_object* res;";
if usesLeanAPI then
emitLn "lean_initialize();"
else
emitLn "lean_initialize_runtime_module();";
modName ← getModName;
emitLn ("res = " ++ mkModuleInitializationFunctionName modName ++ "(lean_io_mk_world());");
emitLns ["lean_io_mark_end_initialization();",
"if (lean_io_result_is_ok(res)) {",
"lean_dec_ref(res);",
"lean_init_task_manager();"];
if xs.size == 2 then do {
emitLns ["in = lean_box(0);",
"int i = argc;",
"while (i > 1) {",
" lean_object* n;",
" i--;",
" n = lean_alloc_ctor(1,2,0); lean_ctor_set(n, 0, lean_mk_string(argv[i])); lean_ctor_set(n, 1, in);",
" in = n;",
"}"];
emitLn ("res = " ++ leanMainFn ++ "(in, lean_io_mk_world());")
} else do {
emitLn ("res = " ++ leanMainFn ++ "(lean_io_mk_world());")
};
emitLn "}";
emitLns ["if (lean_io_result_is_ok(res)) {",
" int ret = lean_unbox(lean_io_result_get_value(res));",
" lean_dec_ref(res);",
" return ret;",
"} else {",
" lean_io_result_show_error(res);",
" lean_dec_ref(res);",
" return 1;",
"}"];
emitLn "}"
| other => throw "function declaration expected"
def hasMainFn : M Bool := do
env ← getEnv;
let decls := getDecls env;
pure $ decls.any (fun d => d.name == `main)
def emitMainFnIfNeeded : M Unit :=
whenM hasMainFn emitMainFn
def emitFileHeader : M Unit := do
env ← getEnv;
modName ← getModName;
emitLn "// Lean compiler output";
emitLn ("// Module: " ++ toString modName);
emit "// Imports:";
env.imports.forM $ fun m => emit (" " ++ toString m);
emitLn "";
emitLn "#include <lean/lean.h>";
emitLns [
"#if defined(__clang__)",
"#pragma clang diagnostic ignored \"-Wunused-parameter\"",
"#pragma clang diagnostic ignored \"-Wunused-label\"",
"#elif defined(__GNUC__) && !defined(__CLANG__)",
"#pragma GCC diagnostic ignored \"-Wunused-parameter\"",
"#pragma GCC diagnostic ignored \"-Wunused-label\"",
"#pragma GCC diagnostic ignored \"-Wunused-but-set-variable\"",
"#endif",
"#ifdef __cplusplus",
"extern \"C\" {",
"#endif"
]
def emitFileFooter : M Unit :=
emitLns [
"#ifdef __cplusplus",
"}",
"#endif"
]
def throwUnknownVar {α : Type} (x : VarId) : M α :=
throw ("unknown variable '" ++ toString x ++ "'")
def getJPParams (j : JoinPointId) : M (Array Param) := do
ctx ← read;
match ctx.jpMap.find? j with
| some ps => pure ps
| none => throw "unknown join point"
def declareVar (x : VarId) (t : IRType) : M Unit := do
emit (toCType t); emit " "; emit x; emit "; "
def declareParams (ps : Array Param) : M Unit :=
ps.forM $ fun p => declareVar p.x p.ty
partial def declareVars : FnBody → Bool → M Bool
| e@(FnBody.vdecl x t _ b), d => do
ctx ← read;
if isTailCallTo ctx.mainFn e then
pure d
else
declareVar x t *> declareVars b true
| FnBody.jdecl j xs _ b, d => declareParams xs *> declareVars b (d || xs.size > 0)
| e, d => if e.isTerminal then pure d else declareVars e.body d
def emitTag (x : VarId) (xType : IRType) : M Unit := do
if xType.isObj then do
emit "lean_obj_tag("; emit x; emit ")"
else
emit x
def isIf (alts : Array Alt) : Option (Nat × FnBody × FnBody) :=
if alts.size != 2 then none
else match alts.get! 0 with
| Alt.ctor c b => some (c.cidx, b, (alts.get! 1).body)
| _ => none
def emitIf (emitBody : FnBody → M Unit) (x : VarId) (xType : IRType) (tag : Nat) (t : FnBody) (e : FnBody) : M Unit := do
emit "if ("; emitTag x xType; emit " == "; emit tag; emitLn ")";
emitBody t;
emitLn "else";
emitBody e
def emitCase (emitBody : FnBody → M Unit) (x : VarId) (xType : IRType) (alts : Array Alt) : M Unit :=
match isIf alts with
| some (tag, t, e) => emitIf emitBody x xType tag t e
| _ => do
emit "switch ("; emitTag x xType; emitLn ") {";
let alts := ensureHasDefault alts;
alts.forM $ fun alt => match alt with
| Alt.ctor c b => emit "case " *> emit c.cidx *> emitLn ":" *> emitBody b
| Alt.default b => emitLn "default: " *> emitBody b;
emitLn "}"
def emitInc (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do
emit $
if checkRef then (if n == 1 then "lean_inc" else "lean_inc_n")
else (if n == 1 then "lean_inc_ref" else "lean_inc_ref_n");
emit "(" *> emit x;
when (n != 1) (emit ", " *> emit n);
emitLn ");"
def emitDec (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do
emit (if checkRef then "lean_dec" else "lean_dec_ref");
emit "("; emit x;
when (n != 1) (do emit ", "; emit n);
emitLn ");"
def emitDel (x : VarId) : M Unit := do
emit "lean_free_object("; emit x; emitLn ");"
def emitSetTag (x : VarId) (i : Nat) : M Unit := do
emit "lean_ctor_set_tag("; emit x; emit ", "; emit i; emitLn ");"
def emitSet (x : VarId) (i : Nat) (y : Arg) : M Unit := do
emit "lean_ctor_set("; emit x; emit ", "; emit i; emit ", "; emitArg y; emitLn ");"
def emitOffset (n : Nat) (offset : Nat) : M Unit :=
if n > 0 then do
emit "sizeof(void*)*"; emit n;
when (offset > 0) (emit " + " *> emit offset)
else
emit offset
def emitUSet (x : VarId) (n : Nat) (y : VarId) : M Unit := do
emit "lean_ctor_set_usize("; emit x; emit ", "; emit n; emit ", "; emit y; emitLn ");"
def emitSSet (x : VarId) (n : Nat) (offset : Nat) (y : VarId) (t : IRType) : M Unit := do
match t with
| IRType.float => emit "lean_ctor_set_float"
| IRType.uint8 => emit "lean_ctor_set_uint8"
| IRType.uint16 => emit "lean_ctor_set_uint16"
| IRType.uint32 => emit "lean_ctor_set_uint32"
| IRType.uint64 => emit "lean_ctor_set_uint64"
| _ => throw "invalid instruction";
emit "("; emit x; emit ", "; emitOffset n offset; emit ", "; emit y; emitLn ");"
def emitJmp (j : JoinPointId) (xs : Array Arg) : M Unit := do
ps ← getJPParams j;
unless (xs.size == ps.size) (throw "invalid goto");
xs.size.forM $ fun i => do {
let p := ps.get! i;
let x := xs.get! i;
emit p.x; emit " = "; emitArg x; emitLn ";"
};
emit "goto "; emit j; emitLn ";"
def emitLhs (z : VarId) : M Unit := do
emit z; emit " = "
def emitArgs (ys : Array Arg) : M Unit :=
ys.size.forM $ fun i => do
when (i > 0) (emit ", ");
emitArg (ys.get! i)
def emitCtorScalarSize (usize : Nat) (ssize : Nat) : M Unit :=
if usize == 0 then emit ssize
else if ssize == 0 then emit "sizeof(size_t)*" *> emit usize
else emit "sizeof(size_t)*" *> emit usize *> emit " + " *> emit ssize
def emitAllocCtor (c : CtorInfo) : M Unit := do
emit "lean_alloc_ctor("; emit c.cidx; emit ", "; emit c.size; emit ", ";
emitCtorScalarSize c.usize c.ssize; emitLn ");"
def emitCtorSetArgs (z : VarId) (ys : Array Arg) : M Unit :=
ys.size.forM $ fun i => do
emit "lean_ctor_set("; emit z; emit ", "; emit i; emit ", "; emitArg (ys.get! i); emitLn ");"
def emitCtor (z : VarId) (c : CtorInfo) (ys : Array Arg) : M Unit := do
emitLhs z;
if c.size == 0 && c.usize == 0 && c.ssize == 0 then do
emit "lean_box("; emit c.cidx; emitLn ");"
else do
emitAllocCtor c; emitCtorSetArgs z ys
def emitReset (z : VarId) (n : Nat) (x : VarId) : M Unit := do
emit "if (lean_is_exclusive("; emit x; emitLn ")) {";
n.forM $ fun i => do {
emit " lean_ctor_release("; emit x; emit ", "; emit i; emitLn ");"
};
emit " "; emitLhs z; emit x; emitLn ";";
emitLn "} else {";
emit " lean_dec_ref("; emit x; emitLn ");";
emit " "; emitLhs z; emitLn "lean_box(0);";
emitLn "}"
def emitReuse (z : VarId) (x : VarId) (c : CtorInfo) (updtHeader : Bool) (ys : Array Arg) : M Unit := do
emit "if (lean_is_scalar("; emit x; emitLn ")) {";
emit " "; emitLhs z; emitAllocCtor c;
emitLn "} else {";
emit " "; emitLhs z; emit x; emitLn ";";
when updtHeader (do emit " lean_ctor_set_tag("; emit z; emit ", "; emit c.cidx; emitLn ");");
emitLn "}";
emitCtorSetArgs z ys
def emitProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do
emitLhs z; emit "lean_ctor_get("; emit x; emit ", "; emit i; emitLn ");"
def emitUProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do
emitLhs z; emit "lean_ctor_get_usize("; emit x; emit ", "; emit i; emitLn ");"
def emitSProj (z : VarId) (t : IRType) (n offset : Nat) (x : VarId) : M Unit := do
emitLhs z;
match t with
| IRType.float => emit "lean_ctor_get_float"
| IRType.uint8 => emit "lean_ctor_get_uint8"
| IRType.uint16 => emit "lean_ctor_get_uint16"
| IRType.uint32 => emit "lean_ctor_get_uint32"
| IRType.uint64 => emit "lean_ctor_get_uint64"
| _ => throw "invalid instruction";
emit "("; emit x; emit ", "; emitOffset n offset; emitLn ");"
def toStringArgs (ys : Array Arg) : List String :=
ys.toList.map argToCString
def emitSimpleExternalCall (f : String) (ps : Array Param) (ys : Array Arg) : M Unit := do
emit f; emit "(";
-- We must remove irrelevant arguments to extern calls.
_ ← ys.size.foldM
(fun i (first : Bool) =>
if (ps.get! i).ty.isIrrelevant then
pure first
else do
unless first (emit ", ");
emitArg (ys.get! i);
pure false)
true;
emitLn ");";
pure ()
def emitExternCall (f : FunId) (ps : Array Param) (extData : ExternAttrData) (ys : Array Arg) : M Unit :=
match getExternEntryFor extData `c with
| some (ExternEntry.standard _ extFn) => emitSimpleExternalCall extFn ps ys
| some (ExternEntry.inline _ pat) => do emit (expandExternPattern pat (toStringArgs ys)); emitLn ";"
| some (ExternEntry.foreign _ extFn) => emitSimpleExternalCall extFn ps ys
| _ => throw ("failed to emit extern application '" ++ toString f ++ "'")
def emitFullApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do
emitLhs z;
decl ← getDecl f;
match decl with
| Decl.extern _ ps _ extData => emitExternCall f ps extData ys
| _ => do emitCName f; when (ys.size > 0) (do emit "("; emitArgs ys; emit ")"); emitLn ";"
def emitPartialApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do
decl ← getDecl f;
let arity := decl.params.size;
emitLhs z; emit "lean_alloc_closure((void*)("; emitCName f; emit "), "; emit arity; emit ", "; emit ys.size; emitLn ");";
ys.size.forM $ fun i => do {
let y := ys.get! i;
emit "lean_closure_set("; emit z; emit ", "; emit i; emit ", "; emitArg y; emitLn ");"
}
def emitApp (z : VarId) (f : VarId) (ys : Array Arg) : M Unit :=
if ys.size > closureMaxArgs then do
emit "{ lean_object* _aargs[] = {"; emitArgs ys; emitLn "};";
emitLhs z; emit "lean_apply_m("; emit f; emit ", "; emit ys.size; emitLn ", _aargs); }"
else do
emitLhs z; emit "lean_apply_"; emit ys.size; emit "("; emit f; emit ", "; emitArgs ys; emitLn ");"
def emitBoxFn (xType : IRType) : M Unit :=
match xType with
| IRType.usize => emit "lean_box_usize"
| IRType.uint32 => emit "lean_box_uint32"
| IRType.uint64 => emit "lean_box_uint64"
| IRType.float => emit "lean_box_float"
| other => emit "lean_box"
def emitBox (z : VarId) (x : VarId) (xType : IRType) : M Unit := do
emitLhs z; emitBoxFn xType; emit "("; emit x; emitLn ");"
def emitUnbox (z : VarId) (t : IRType) (x : VarId) : M Unit := do
emitLhs z;
match t with
| IRType.usize => emit "lean_unbox_usize"
| IRType.uint32 => emit "lean_unbox_uint32"
| IRType.uint64 => emit "lean_unbox_uint64"
| IRType.float => emit "lean_unbox_float"
| other => emit "lean_unbox";
emit "("; emit x; emitLn ");"
def emitIsShared (z : VarId) (x : VarId) : M Unit := do
emitLhs z; emit "!lean_is_exclusive("; emit x; emitLn ");"
def emitIsTaggedPtr (z : VarId) (x : VarId) : M Unit := do
emitLhs z; emit "!lean_is_scalar("; emit x; emitLn ");"
def toHexDigit (c : Nat) : String :=
String.singleton c.digitChar
def quoteString (s : String) : String :=
let q := "\"";
let q := s.foldl
(fun q c => q ++
if c == '\n' then "\\n"
else if c == '\n' then "\\t"
else if c == '\\' then "\\\\"
else if c == '\"' then "\\\""
else if c.toNat <= 31 then
"\\x" ++ toHexDigit (c.toNat / 16) ++ toHexDigit (c.toNat % 16)
-- TODO(Leo): we should use `\unnnn` for escaping unicode characters.
else String.singleton c)
q;
q ++ "\""
def emitNumLit (t : IRType) (v : Nat) : M Unit :=
if t.isObj then do
if v < uint32Sz then
emit "lean_unsigned_to_nat(" *> emit v *> emit "u)"
else
emit "lean_cstr_to_nat(\"" *> emit v *> emit "\")"
else
emit v
def emitLit (z : VarId) (t : IRType) (v : LitVal) : M Unit :=
emitLhs z *>
match v with
| LitVal.num v => emitNumLit t v *> emitLn ";"
| LitVal.str v => do emit "lean_mk_string("; emit (quoteString v); emitLn ");"
def emitVDecl (z : VarId) (t : IRType) (v : Expr) : M Unit :=
match v with
| Expr.ctor c ys => emitCtor z c ys
| Expr.reset n x => emitReset z n x
| Expr.reuse x c u ys => emitReuse z x c u ys
| Expr.proj i x => emitProj z i x
| Expr.uproj i x => emitUProj z i x
| Expr.sproj n o x => emitSProj z t n o x
| Expr.fap c ys => emitFullApp z c ys
| Expr.pap c ys => emitPartialApp z c ys
| Expr.ap x ys => emitApp z x ys
| Expr.box t x => emitBox z x t
| Expr.unbox x => emitUnbox z t x
| Expr.isShared x => emitIsShared z x
| Expr.isTaggedPtr x => emitIsTaggedPtr z x
| Expr.lit v => emitLit z t v
def isTailCall (x : VarId) (v : Expr) (b : FnBody) : M Bool := do
ctx ← read;
match v, b with
| Expr.fap f _, FnBody.ret (Arg.var y) => pure $ f == ctx.mainFn && x == y
| _, _ => pure false
def paramEqArg (p : Param) (x : Arg) : Bool :=
match x with
| Arg.var x => p.x == x
| _ => false
/-
Given `[p_0, ..., p_{n-1}]`, `[y_0, ..., y_{n-1}]`, representing the assignments
```
p_0 := y_0,
...
p_{n-1} := y_{n-1}
```
Return true iff we have `(i, j)` where `j > i`, and `y_j == p_i`.
That is, we have
```
p_i := y_i,
...
p_j := p_i, -- p_i was overwritten above
```
-/
def overwriteParam (ps : Array Param) (ys : Array Arg) : Bool :=
let n := ps.size;
n.any $ fun i =>
let p := ps.get! i;
(i+1, n).anyI $ fun j => paramEqArg p (ys.get! j)
def emitTailCall (v : Expr) : M Unit :=
match v with
| Expr.fap _ ys => do
ctx ← read;
let ps := ctx.mainParams;
unless (ps.size == ys.size) (throw "invalid tail call");
if overwriteParam ps ys then do {
emitLn "{";
ps.size.forM $ fun i => do {
let p := ps.get! i;
let y := ys.get! i;
unless (paramEqArg p y) $ do {
emit (toCType p.ty); emit " _tmp_"; emit i; emit " = "; emitArg y; emitLn ";"
}
};
ps.size.forM $ fun i => do {
let p := ps.get! i;
let y := ys.get! i;
unless (paramEqArg p y) (do emit p.x; emit " = _tmp_"; emit i; emitLn ";")
};
emitLn "}"
} else do {
ys.size.forM $ fun i => do {
let p := ps.get! i;
let y := ys.get! i;
unless (paramEqArg p y) (do emit p.x; emit " = "; emitArg y; emitLn ";")
}
};
emitLn "goto _start;"
| _ => throw "bug at emitTailCall"
partial def emitBlock (emitBody : FnBody → M Unit) : FnBody → M Unit
| FnBody.jdecl j xs v b => emitBlock b
| d@(FnBody.vdecl x t v b) =>
do ctx ← read; if isTailCallTo ctx.mainFn d then emitTailCall v else emitVDecl x t v *> emitBlock b
| FnBody.inc x n c p b => unless p (emitInc x n c) *> emitBlock b
| FnBody.dec x n c p b => unless p (emitDec x n c) *> emitBlock b
| FnBody.del x b => emitDel x *> emitBlock b
| FnBody.setTag x i b => emitSetTag x i *> emitBlock b
| FnBody.set x i y b => emitSet x i y *> emitBlock b
| FnBody.uset x i y b => emitUSet x i y *> emitBlock b
| FnBody.sset x i o y t b => emitSSet x i o y t *> emitBlock b
| FnBody.mdata _ b => emitBlock b
| FnBody.ret x => emit "return " *> emitArg x *> emitLn ";"
| FnBody.case _ x xType alts => emitCase emitBody x xType alts
| FnBody.jmp j xs => emitJmp j xs
| FnBody.unreachable => emitLn "lean_panic_unreachable();"
partial def emitJPs (emitBody : FnBody → M Unit) : FnBody → M Unit
| FnBody.jdecl j xs v b => do emit j; emitLn ":"; emitBody v; emitJPs b
| e => unless e.isTerminal (emitJPs e.body)
partial def emitFnBody : FnBody → M Unit
| b => do
emitLn "{";
declared ← declareVars b false;
when declared (emitLn "");
emitBlock emitFnBody b;
emitJPs emitFnBody b;
emitLn "}"
def emitDeclAux (d : Decl) : M Unit := do
env ← getEnv;
let (vMap, jpMap) := mkVarJPMaps d;
adaptReader (fun (ctx : Context) => { ctx with jpMap := jpMap }) $ do
unless (hasInitAttr env d.name) $
match d with
| Decl.fdecl f xs t b => do
baseName ← toCName f;
emit (toCType t); emit " ";
if xs.size > 0 then do {
emit baseName;
emit "(";
if xs.size > closureMaxArgs && isBoxedName d.name then
emit "lean_object** _args"
else
xs.size.forM $ fun i => do {
when (i > 0) (emit ", ");
let x := xs.get! i;
emit (toCType x.ty); emit " "; emit x.x
};
emit ")"
} else do {
emit ("_init_" ++ baseName ++ "()")
};
emitLn " {";
when (xs.size > closureMaxArgs && isBoxedName d.name) $
xs.size.forM $ fun i => do {
let x := xs.get! i;
emit "lean_object* "; emit x.x; emit " = _args["; emit i; emitLn "];"
};
emitLn "_start:";
adaptReader (fun (ctx : Context) => { ctx with mainFn := f, mainParams := xs }) (emitFnBody b);
emitLn "}"
| _ => pure ()
def emitDecl (d : Decl) : M Unit :=
let d := d.normalizeIds; -- ensure we don't have gaps in the variable indices
catch
(emitDeclAux d)
(fun err => throw (err ++ "\ncompiling:\n" ++ toString d))
def emitFns : M Unit := do
env ← getEnv;
let decls := getDecls env;
decls.reverse.forM emitDecl
def emitMarkPersistent (d : Decl) (n : Name) : M Unit :=
when d.resultType.isObj $ do {
emit "lean_mark_persistent("; emitCName n; emitLn ");"
}
def emitDeclInit (d : Decl) : M Unit := do
env ← getEnv;
let n := d.name;
if isIOUnitInitFn env n then do {
emit "res = "; emitCName n; emitLn "(lean_io_mk_world());";
emitLn "if (lean_io_result_is_error(res)) return res;";
emitLn "lean_dec_ref(res);"
} else when (d.params.size == 0) $
match getInitFnNameFor env d.name with
| some initFn => do {
emit "res = "; emitCName initFn; emitLn "(lean_io_mk_world());";
emitLn "if (lean_io_result_is_error(res)) return res;";
emitCName n; emitLn " = lean_io_result_get_value(res);";
emitMarkPersistent d n;
emitLn "lean_dec_ref(res);"
}
| _ => do { emitCName n; emit " = "; emitCInitName n; emitLn "();"; emitMarkPersistent d n }
def emitInitFn : M Unit := do
env ← getEnv;
modName ← getModName;
env.imports.forM $ fun imp => emitLn ("lean_object* " ++ mkModuleInitializationFunctionName imp.module ++ "(lean_object*);");
emitLns [
"static bool _G_initialized = false;",
"lean_object* " ++ mkModuleInitializationFunctionName modName ++ "(lean_object* w) {",
"lean_object * res;",
"if (_G_initialized) return lean_io_result_mk_ok(lean_box(0));",
"_G_initialized = true;"
];
env.imports.forM $ fun imp => emitLns [
"res = " ++ mkModuleInitializationFunctionName imp.module ++ "(lean_io_mk_world());",
"if (lean_io_result_is_error(res)) return res;",
"lean_dec_ref(res);"];
let decls := getDecls env;
decls.reverse.forM emitDeclInit;
emitLns ["return lean_io_result_mk_ok(lean_box(0));", "}"]
def main : M Unit := do
emitFileHeader;
emitFnDecls;
emitFns;
emitInitFn;
emitMainFnIfNeeded;
emitFileFooter
end EmitC
@[export lean_ir_emit_c]
def emitC (env : Environment) (modName : Name) : Except String String :=
match (EmitC.main { env := env, modName := modName }).run "" with
| EStateM.Result.ok _ s => Except.ok s
| EStateM.Result.error err _ => Except.error err
end IR
end Lean
|
db75d76d04f82c21b48815fe27c7aa03ad554e9b | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/simp10.lean | a180800f4f3072e02dfd74afa4aa936d9c9dde6b | [
"Apache-2.0"
] | permissive | codyroux/lean0.1 | 1ce92751d664aacff0529e139083304a7bbc8a71 | 0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef | refs/heads/master | 1,610,830,535,062 | 1,402,150,480,000 | 1,402,150,480,000 | 19,588,851 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 359 | lean | variable f : Nat → Nat
variable g : Nat → Nat
variable a : Nat
axiom fid (x : Nat) : g x ≠ 0 → f x = x
add_rewrite fid
axiom gcnst (x : Nat) : g x = 1
add_rewrite gcnst
theorem one_neq_0 : 1 ≠ 0
:= Nat::succ_nz 0
add_rewrite one_neq_0
(*
local t = parse_lean("f a")
local r, pr = simplify(t)
print(r)
print(pr)
get_environment():type_check(pr)
*) |
f7f5653166f11cd6d890cdd05616cb98d8b93da8 | f608b09bd951f29eccb4c27187f55223000fa85f | /2020/lean/lovelib.lean | 2707a935217f4a239b763b13d6dc510b8a95221e | [] | no_license | bobismijnnaam/advent-of-code | 9482d954b8f381b28a4823337e3688963fd05d6d | 471b9cad04eba7010da79416aef7a3218b1f4541 | refs/heads/master | 1,639,530,767,572 | 1,639,425,773,000 | 1,639,425,773,000 | 225,140,719 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,810 | lean | import algebra
import data.real.basic
import data.vector
import tactic.explode
import tactic.find
import tactic.induction
import tactic.linarith
import tactic.rcases
import tactic.rewrite
import tactic.ring_exp
import tactic.tidy
import tactic.where
/-! # LoVe Library
This files contains a few extensions on top of Lean's core libraries and
`mathlib`. -/
namespace LoVe
/-! ## Structured Proofs -/
notation `fix ` binders `, ` r:(scoped f, f) := r
/-! ## Logical Connectives -/
attribute [pattern] or.intro_left or.intro_right
meta def tactic.dec_trivial := `[exact dec_trivial]
lemma not_def (a : Prop) :
¬ a ↔ a → false :=
by refl
@[simp] lemma not_not_iff (a : Prop) [decidable a] :
¬¬ a ↔ a :=
by by_cases a; simp [h]
@[simp] lemma and_imp_distrib (a b c : Prop) :
(a ∧ b → c) ↔ (a → b → c) :=
iff.intro
(assume h ha hb, h ⟨ha, hb⟩)
(assume h ⟨ha, hb⟩, h ha hb)
@[simp] lemma or_imp_distrib {a b c : Prop} :
a ∨ b → c ↔ (a → c) ∧ (b → c) :=
iff.intro
(assume h,
⟨assume ha, h (or.intro_left _ ha), assume hb, h (or.intro_right _ hb)⟩)
(assume ⟨ha, hb⟩ h, match h with or.inl h := ha h | or.inr h := hb h end)
@[simp] lemma exists_imp_distrib {α : Sort*} {p : α → Prop} {a : Prop} :
((∃x, p x) → a) ↔ (∀x, p x → a) :=
iff.intro
(assume h hp ha, h ⟨hp, ha⟩)
(assume h ⟨hp, ha⟩, h hp ha)
lemma and_exists {α : Sort*} {p : α → Prop} {a : Prop} :
(a ∧ (∃x, p x)) ↔ (∃x, a ∧ p x) :=
iff.intro
(assume ⟨ha, x, hp⟩, ⟨x, ha, hp⟩)
(assume ⟨x, ha, hp⟩, ⟨ha, x, hp⟩)
@[simp] lemma exists_false {α : Sort*} :
(∃x : α, false) ↔ false :=
iff.intro (assume ⟨a, f⟩, f) (assume h, h.elim)
/-! ## Natural Numbers -/
attribute [simp] nat.add
/-! ## Integers -/
@[simp] lemma int.neg_comp_neg :
int.neg ∘ int.neg = id :=
begin
apply funext,
apply neg_neg
end
/-! ## Reflexive Transitive Closure -/
namespace rtc
inductive star {α : Sort*} (r : α → α → Prop) (a : α) : α → Prop
| refl {} : star a
| tail {b c} : star b → r b c → star c
attribute [refl] star.refl
namespace star
variables {α : Sort*} {r : α → α → Prop} {a b c d : α}
@[trans] lemma trans (hab : star r a b) (hbc : star r b c) :
star r a c :=
begin
induction' hbc,
case refl {
assumption },
case tail : c d hbc hcd hac {
exact (tail (hac hab)) hcd }
end
lemma single (hab : r a b) :
star r a b :=
refl.tail hab
lemma head (hab : r a b) (hbc : star r b c) :
star r a c :=
begin
induction' hbc,
case refl {
exact (tail refl) hab },
case tail : c d hbc hcd hac {
exact (tail (hac hab)) hcd }
end
lemma head_induction_on {α : Sort*} {r : α → α → Prop} {b : α}
{P : ∀a : α, star r a b → Prop} {a : α} (h : star r a b)
(refl : P b refl)
(head : ∀{a c} (h' : r a c) (h : star r c b), P c h → P a (h.head h')) :
P a h :=
begin
induction' h,
case star.refl {
exact refl },
case star.tail : b c hab hbc ih {
apply ih,
show P b _, from
head hbc _ refl,
show ∀a a', r a a' → star r a' b → P a' _ → P a _, from
assume a a' hab hbc, head hab _ }
end
lemma trans_induction_on {α : Sort*} {r : α → α → Prop}
{p : ∀{a b : α}, star r a b → Prop} {a b : α} (h : star r a b)
(ih₁ : ∀a, @p a a refl) (ih₂ : ∀{a b} (h : r a b), p (single h))
(ih₃ : ∀{a b c} (h₁ : star r a b) (h₂ : star r b c), p h₁ →
p h₂ → p (h₁.trans h₂)) :
p h :=
begin
induction' h,
case star.refl {
exact ih₁ a },
case star.tail : b c hab hbc ih {
exact ih₃ hab (single hbc) (ih ih₁ @ih₂ @ih₃) (ih₂ hbc) }
end
lemma lift {β : Sort*} {s : β → β → Prop} (f : α → β)
(h : ∀a b, r a b → s (f a) (f b)) (hab : star r a b) :
star s (f a) (f b) :=
hab.trans_induction_on
(assume a, refl)
(assume a b, single ∘ h _ _)
(assume a b c _ _, trans)
lemma mono {p : α → α → Prop} :
(∀a b, r a b → p a b) → star r a b → star p a b :=
lift id
lemma star_star_eq :
star (star r) = star r :=
funext
(assume a,
funext
(assume b,
propext (iff.intro
(assume h,
begin
induction' h,
{ refl },
{ transitivity;
assumption }
end)
(star.mono (assume a b,
single)))))
end star
end rtc
export rtc
/-! ## States -/
def state :=
string → ℕ
def state.update (name : string) (val : ℕ) (s : state) : state :=
λname', if name' = name then val else s name'
notation s `{` name ` ↦ ` val `}` := state.update name val s
instance : has_emptyc state :=
{ emptyc := λ_, 0 }
@[simp] lemma update_apply (name : string) (val : ℕ) (s : state) :
s{name ↦ val} name = val :=
if_pos rfl
@[simp] lemma update_apply_ne (name name' : string) (val : ℕ) (s : state)
(h : name' ≠ name . tactic.dec_trivial) :
s{name ↦ val} name' = s name' :=
if_neg h
@[simp] lemma update_override (name : string) (val₁ val₂ : ℕ) (s : state) :
s{name ↦ val₂}{name ↦ val₁} = s{name ↦ val₁} :=
begin
apply funext,
intro name',
by_cases name' = name;
simp [h]
end
@[simp] lemma update_swap (name₁ name₂ : string) (val₁ val₂ : ℕ) (s : state)
(h : name₁ ≠ name₂ . tactic.dec_trivial) :
s{name₂ ↦ val₂}{name₁ ↦ val₁} = s{name₁ ↦ val₁}{name₂ ↦ val₂} :=
begin
apply funext,
intro name',
by_cases name' = name₁;
by_cases name' = name₂;
simp * at *
end
@[simp] lemma update_id (name : string) (s : state) :
s{name ↦ s name} = s :=
begin
apply funext,
intro name',
by_cases name' = name;
simp * at *
end
example (s : state) :
s{"a" ↦ 0}{"a" ↦ 2} = s{"a" ↦ 2} :=
by simp
example (s : state) :
s{"a" ↦ 0}{"b" ↦ 2} = s{"b" ↦ 2}{"a" ↦ 0} :=
by simp
example (s : state) :
s{"a" ↦ s "a"}{"b" ↦ 0} = s{"b" ↦ 0} :=
by simp
/-! ## Relations -/
def Id {α : Type} : set (α × α) :=
{ab | prod.snd ab = prod.fst ab}
@[simp] lemma mem_Id {α : Type} (a b : α) :
(a, b) ∈ @Id α ↔ b = a :=
by refl
def comp {α : Type} (r₁ r₂ : set (α × α)) : set (α × α) :=
{ac | ∃b, (prod.fst ac, b) ∈ r₁ ∧ (b, prod.snd ac) ∈ r₂}
infixl ` ◯ ` : 90 := comp
@[simp] lemma mem_comp {α : Type} (r₁ r₂ : set (α × α))
(a b : α) :
(a, b) ∈ r₁ ◯ r₂ ↔ (∃c, (a, c) ∈ r₁ ∧ (c, b) ∈ r₂) :=
by refl
def restrict {α : Type} (r : set (α × α)) (p : α → Prop) :
set (α × α) :=
{ab | p (prod.fst ab) ∧ ab ∈ r}
infixl ` ⇃ ` : 90 := restrict
@[simp] lemma mem_restrict {α : Type} (r : set (α × α))
(p : α → Prop) (a b : α) :
(a, b) ∈ r ⇃ p ↔ p a ∧ (a, b) ∈ r :=
by refl
end LoVe
|
668f6eac8ea5ec9c1c68efbfdc783d0969b59913 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/extra/597a.hlean | 66769a3b6ad43272422d5ca3491e999c37ca7c84 | [
"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 | 81 | hlean | open equiv
constants (A B : Type₀) (f : A ≃ B)
definition foo : A → B := f
|
4778e390f4ca1110d3808b98ce21995b620d5f1d | a4673261e60b025e2c8c825dfa4ab9108246c32e | /stage0/src/Std/Data/Queue.lean | 99f0aae3750673faf582700a3c4f4972287380bb | [
"Apache-2.0"
] | permissive | jcommelin/lean4 | c02dec0cc32c4bccab009285475f265f17d73228 | 2909313475588cc20ac0436e55548a4502050d0a | refs/heads/master | 1,674,129,550,893 | 1,606,415,348,000 | 1,606,415,348,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 957 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Selsam
Simple queue implemented using two lists.
Note: this is only a temporary placeholder.
-/
namespace Std
universes u v w
structure Queue (α : Type u) :=
(eList dList : List α := [])
namespace Queue
variable {α : Type u}
def empty : Queue α :=
{ eList := [], dList := [] }
def isEmpty (q : Queue α) : Bool :=
q.dList.isEmpty && q.eList.isEmpty
def enqueue (v : α) (q : Queue α) : Queue α :=
{ q with eList := v::q.eList }
def enqueueAll (vs : List α) (q : Queue α) : Queue α :=
{ q with eList := vs ++ q.eList }
def dequeue? (q : Queue α) : Option (α × Queue α) :=
match q.dList with
| d::ds => some (d, { q with dList := ds })
| [] =>
match q.eList.reverse with
| [] => none
| d::ds => some (d, { eList := [], dList := ds })
end Queue
end Std
|
662a9c9276e4a74c8074dfc9f0e77f207e762a26 | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /category_theory/examples/measurable_space.lean | f14d2cfb08001aa3e897982713a38aaabd6b9c22 | [
"Apache-2.0"
] | permissive | kckennylau/mathlib | 21fb810b701b10d6606d9002a4004f7672262e83 | 47b3477e20ffb5a06588dd3abb01fe0fe3205646 | refs/heads/master | 1,634,976,409,281 | 1,542,042,832,000 | 1,542,319,733,000 | 109,560,458 | 0 | 0 | Apache-2.0 | 1,542,369,208,000 | 1,509,867,494,000 | Lean | UTF-8 | Lean | false | false | 926 | 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
Basic setup for measurable spaces.
-/
import category_theory.examples.topological_spaces
import category_theory.types
import analysis.measure_theory.borel_space
open category_theory
universes u v
namespace category_theory.examples
@[reducible] def Meas : Type (u+1) := bundled measurable_space
instance (x : Meas) : measurable_space x := x.str
namespace Meas
instance : concrete_category @measurable := ⟨@measurable_id, @measurable.comp⟩
-- -- If `measurable` were a class, we would summon instances:
-- local attribute [class] measurable
-- instance {X Y : Meas} (f : X ⟶ Y) : measurable (f : X → Y) := f.2
end Meas
def Borel : Top ⥤ Meas :=
concrete_functor @measure_theory.borel @measure_theory.measurable_of_continuous
end category_theory.examples
|
a8d50c1829ba95876476f532b973ae725c46e8a5 | 367134ba5a65885e863bdc4507601606690974c1 | /src/topology/opens.lean | 3ddcbb93f1cf5187e25bdf0d49e41bfe73515eb7 | [
"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 | 8,780 | 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, Floris van Doorn
-/
import topology.bases
import topology.homeomorph
/-!
# Open sets
## Summary
We define the subtype of open sets in a topological space.
## Main Definitions
- `opens α` is the type of open subsets of a topological space `α`.
- `open_nhds_of x` is the type of open subsets of a topological space `α` containing `x : α`.
-
-/
open filter set
variables {α : Type*} {β : Type*} {γ : Type*}
[topological_space α] [topological_space β] [topological_space γ]
namespace topological_space
variable (α)
/-- The type of open subsets of a topological space. -/
def opens := {s : set α // is_open s}
variable {α}
namespace opens
instance : has_coe (opens α) (set α) := { coe := subtype.val }
lemma val_eq_coe (U : opens α) : U.1 = ↑U := rfl
/-- the coercion `opens α → set α` applied to a pair is the same as taking the first component -/
lemma coe_mk {α : Type*} [topological_space α] {U : set α} {hU : is_open U} :
↑(⟨U, hU⟩ : opens α) = U := rfl
instance : has_subset (opens α) :=
{ subset := λ U V, (U : set α) ⊆ V }
instance : has_mem α (opens α) :=
{ mem := λ a U, a ∈ (U : set α) }
@[simp] lemma subset_coe {U V : opens α} : ((U : set α) ⊆ (V : set α)) = (U ⊆ V) := rfl
@[simp] lemma mem_coe {x : α} {U : opens α} : (x ∈ (U : set α)) = (x ∈ U) := rfl
@[ext] lemma ext {U V : opens α} (h : (U : set α) = V) : U = V := subtype.ext_iff.mpr h
@[ext] lemma ext_iff {U V : opens α} : (U : set α) = V ↔ U = V :=
⟨opens.ext, congr_arg coe⟩
instance : partial_order (opens α) := subtype.partial_order _
/-- The interior of a set, as an element of `opens`. -/
def interior (s : set α) : opens α := ⟨interior s, is_open_interior⟩
lemma gc : galois_connection (coe : opens α → set α) interior :=
λ U s, ⟨λ h, interior_maximal h U.property, λ h, le_trans h interior_subset⟩
/-- The galois insertion between sets and opens, but ordered by reverse inclusion. -/
def gi : @galois_insertion (order_dual (set α)) (order_dual (opens α)) _ _ interior subtype.val :=
{ choice := λ s hs, ⟨s, interior_eq_iff_open.mp $ le_antisymm interior_subset hs⟩,
gc := gc.dual,
le_l_u := λ _, interior_subset,
choice_eq := λ s hs, le_antisymm interior_subset hs }
@[simp] lemma gi_choice_val {s : order_dual (set α)} {hs} : (gi.choice s hs).val = s := rfl
instance : complete_lattice (opens α) :=
complete_lattice.copy
(@order_dual.complete_lattice _ (galois_insertion.lift_complete_lattice (@gi α _)))
/- le -/ (λ U V, U ⊆ V) rfl
/- top -/ ⟨set.univ, is_open_univ⟩ (subtype.ext_iff_val.mpr interior_univ.symm)
/- bot -/ ⟨∅, is_open_empty⟩ rfl
/- sup -/ (λ U V, ⟨↑U ∪ ↑V, is_open_union U.2 V.2⟩) rfl
/- inf -/ (λ U V, ⟨↑U ∩ ↑V, is_open_inter U.2 V.2⟩)
begin
funext,
apply subtype.ext_iff_val.mpr,
exact (is_open_inter U.2 V.2).interior_eq.symm,
end
/- Sup -/ (λ Us, ⟨⋃₀ (coe '' Us), is_open_sUnion $ λ U hU,
by { rcases hU with ⟨⟨V, hV⟩, h, h'⟩, dsimp at h', subst h', exact hV}⟩)
begin
funext,
apply subtype.ext_iff_val.mpr,
simp [Sup_range],
refl,
end
/- Inf -/ _ rfl
lemma le_def {U V : opens α} : U ≤ V ↔ (U : set α) ≤ (V : set α) :=
by refl
@[simp] lemma mk_inf_mk {U V : set α} {hU : is_open U} {hV : is_open V} :
(⟨U, hU⟩ ⊓ ⟨V, hV⟩ : opens α) = ⟨U ⊓ V, is_open_inter hU hV⟩ := rfl
@[simp,norm_cast] lemma coe_inf {U V : opens α} :
((U ⊓ V : opens α) : set α) = (U : set α) ⊓ (V : set α) := rfl
instance : has_inter (opens α) := ⟨λ U V, U ⊓ V⟩
instance : has_union (opens α) := ⟨λ U V, U ⊔ V⟩
instance : has_emptyc (opens α) := ⟨⊥⟩
instance : inhabited (opens α) := ⟨∅⟩
@[simp] lemma inter_eq (U V : opens α) : U ∩ V = U ⊓ V := rfl
@[simp] lemma union_eq (U V : opens α) : U ∪ V = U ⊔ V := rfl
@[simp] lemma empty_eq : (∅ : opens α) = ⊥ := rfl
@[simp] lemma Sup_s {Us : set (opens α)} : ↑(Sup Us) = ⋃₀ ((coe : _ → set α) '' Us) :=
begin
rw [@galois_connection.l_Sup (opens α) (set α) _ _ (coe : opens α → set α) interior gc Us],
rw [set.sUnion_image]
end
lemma supr_def {ι} (s : ι → opens α) : (⨆ i, s i) = ⟨⋃ i, s i, is_open_Union $ λ i, (s i).2⟩ :=
by { ext, simp only [supr, opens.Sup_s, sUnion_image, bUnion_range], refl }
@[simp] lemma supr_mk {ι} (s : ι → set α) (h : Π i, is_open (s i)) :
(⨆ i, ⟨s i, h i⟩ : opens α) = ⟨⨆ i, s i, is_open_Union h⟩ :=
by { rw supr_def, simp }
@[simp] lemma supr_s {ι} (s : ι → opens α) : ((⨆ i, s i : opens α) : set α) = ⋃ i, s i :=
by simp [supr_def]
theorem mem_supr {ι} {x : α} {s : ι → opens α} : x ∈ supr s ↔ ∃ i, x ∈ s i :=
by { rw [←mem_coe], simp, }
lemma open_embedding_of_le {U V : opens α} (i : U ≤ V) :
open_embedding (set.inclusion i) :=
{ inj := set.inclusion_injective i,
induced := (@induced_compose _ _ _ _ (set.inclusion i) coe).symm,
open_range :=
begin
rw set.range_inclusion i,
exact U.property.preimage continuous_subtype_val
end, }
def is_basis (B : set (opens α)) : Prop := is_topological_basis ((coe : _ → set α) '' B)
lemma is_basis_iff_nbhd {B : set (opens α)} :
is_basis B ↔ ∀ {U : opens α} {x}, x ∈ U → ∃ U' ∈ B, x ∈ U' ∧ U' ⊆ U :=
begin
split; intro h,
{ rintros ⟨sU, hU⟩ x hx,
rcases (mem_nhds_of_is_topological_basis h).mp (mem_nhds_sets hU hx)
with ⟨sV, ⟨⟨V, H₁, H₂⟩, hsV⟩⟩,
refine ⟨V, H₁, _⟩,
cases V, dsimp at H₂, subst H₂, exact hsV },
{ refine is_topological_basis_of_open_of_nhds _ _,
{ rintros sU ⟨U, ⟨H₁, H₂⟩⟩, subst H₂, exact U.property },
{ intros x sU hx hsU,
rcases @h (⟨sU, hsU⟩ : opens α) x hx with ⟨V, hV, H⟩,
exact ⟨V, ⟨V, hV, rfl⟩, H⟩ } }
end
lemma is_basis_iff_cover {B : set (opens α)} :
is_basis B ↔ ∀ U : opens α, ∃ Us ⊆ B, U = Sup Us :=
begin
split,
{ intros hB U,
rcases sUnion_basis_of_is_open hB U.prop with ⟨sUs, H, hU⟩,
existsi {U : opens α | U ∈ B ∧ ↑U ∈ sUs},
split,
{ intros U hU, exact hU.left },
{ apply ext,
rw [Sup_s, hU],
congr' with s; split; intro hs,
{ rcases H hs with ⟨V, hV⟩,
rw ← hV.right at hs,
refine ⟨V, ⟨⟨hV.left, hs⟩, hV.right⟩⟩ },
{ rcases hs with ⟨V, ⟨⟨H₁, H₂⟩, H₃⟩⟩,
subst H₃, exact H₂ } } },
{ intro h,
rw is_basis_iff_nbhd,
intros U x hx,
rcases h U with ⟨Us, hUs, H⟩,
replace H := congr_arg (coe : _ → set α) H,
rw Sup_s at H,
change x ∈ ↑U at hx,
rw H at hx,
rcases set.mem_sUnion.mp hx with ⟨sV, ⟨⟨V, H₁, H₂⟩, hsV⟩⟩,
refine ⟨V,hUs H₁,_⟩,
cases V with V hV,
dsimp at H₂, subst H₂,
refine ⟨hsV,_⟩,
change V ⊆ U, rw H,
exact set.subset_sUnion_of_mem ⟨⟨V, _⟩, ⟨H₁, rfl⟩⟩ }
end
/-- The preimage of an open set, as an open set. -/
def comap {f : α → β} (hf : continuous f) (V : opens β) : opens α :=
⟨f ⁻¹' V.1, V.2.preimage hf⟩
@[simp] lemma comap_id (U : opens α) : U.comap continuous_id = U := by { ext, refl }
lemma comap_mono {f : α → β} (hf : continuous f) {V W : opens β} (hVW : V ⊆ W) :
V.comap hf ⊆ W.comap hf :=
λ _ h, hVW h
@[simp] lemma coe_comap {f : α → β} (hf : continuous f) (U : opens β) :
↑(U.comap hf) = f ⁻¹' U := rfl
@[simp] lemma comap_val {f : α → β} (hf : continuous f) (U : opens β) :
(U.comap hf).1 = f ⁻¹' U := rfl
protected lemma comap_comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f)
(U : opens γ) : U.comap (hg.comp hf) = (U.comap hg).comap hf :=
by { ext1, simp only [coe_comap, preimage_preimage] }
/-- A homeomorphism induces an equivalence on open sets, by taking comaps. -/
@[simp] protected def equiv (f : α ≃ₜ β) : opens α ≃ opens β :=
{ to_fun := opens.comap f.symm.continuous,
inv_fun := opens.comap f.continuous,
left_inv := by { intro U, ext1,
simp only [coe_comap, ← preimage_comp, f.symm_comp_self, preimage_id] },
right_inv := by { intro U, ext1,
simp only [coe_comap, ← preimage_comp, f.self_comp_symm, preimage_id] } }
end opens
/-- The open neighborhoods of a point. See also `opens` or `nhds`. -/
def open_nhds_of (x : α) : Type* := { s : set α // is_open s ∧ x ∈ s }
instance open_nhds_of.inhabited {α : Type*} [topological_space α] (x : α) :
inhabited (open_nhds_of x) := ⟨⟨set.univ, is_open_univ, set.mem_univ _⟩⟩
end topological_space
|
ce940da0a5ba791112f8e4caf3fd0ece3b64cd70 | a6b711a4e8db20755026231f7ed529a9014b2b6d | /ZZ_IGNORE/RAW/functions.lean | 0be38a66c3bee17753021bdc45a237f442862039 | [] | no_license | chaseboettner/cs-dm-1 | b67d4a7e86f56bce59d2af115503769749d423b2 | 80b35f2957ffaa45b8b7a4479a3570a2d6eb4db0 | refs/heads/master | 1,585,367,603,488 | 1,536,235,675,000 | 1,536,235,675,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,251 | lean | /-
Return to your earliest days of high school algebra and
consider the simple function f(x) = x + 1. Reflect on how
do you think about it?
* Do you first see a graph in your mind -- a line rising
from left to right at a 45 degree angle and crossing the
y-axis at the point y = 1?
* Do you think of the function as a set of ordered pairs,
namely all the pairs in which the second number is equal
to the first number plus one?
* Do you think of the function as a kind of "machine",
one that, when given a value for x hands you back a value
for f(x)? E.g., as a machine that when given an argument
value of 3 returns a result value of 4?
These are all perfectly wonderful ways to think about,
and indeed, to represent such a function. The first two
ways, as a graph and as a set of pairs, are closely
related: the graph is simply a drawing in which each
possible pair of values is represented as a point in
the Cartesian plane and where the pairs constituting
the function are highlighted in pencil. The result is
a continuous line infinite in extent hitting all and
only the pairs in the set of pairs for the function, f.
The view of the function as a kind of abstract machine
is different. Whereas the first two views explicitly
represent the set of pairs making up the function, the
machine view implicitly represents this set of pairs.
The machine says, "if you give me the first element
of such a pair, I will give you back the second one."
Mathematicians think of functions as sets of pairs.
Programmers tend to think of functions as machines.
Indeed when functions (viewed as sets of pairs) are
implemented as programs, those programs do serve as
machines that automatically compute function values:
if you give the machine a 3 (by applying the program
to the argument, 3) it returns 4, and more generally,
if you give it some value, x, it returns the value,
x + 1!
-/
-- FUNCTIONS AS SETS OF PAIRS
/-
Mathematicians think of a function most fundamentally
as a set of pairs. In paper-and-pencil mathematics, a
mathematician might denote such a set using what we
call "set comprehension notation." Here's what this
would look like:
f = { (x, y) | y = x + 1 }.
Here f is the name of the function and the set is
defined to be "the set of all x-y pairs where the
y value is equal to the x value plus one."
We can represent the function this way in Lean, as
well, using what we call set comprehension notation,
as follows:
-/
def f := { p: ℕ × ℕ | p.2 = p.1 + 1 }
/-
This can be read as saying, "We define f to
be the set of values, p, where each such p
is a pair of natural numbers, such that the
second component of the ordered pair, p, is
equal to the first component plus one.
-/
/-
We now take a few paragraphs to drill down
on some details.
First, here's more about math in Lean.
The #check command in Lean will tell us the
type of an object. Checking the type of f
reveals that it is indeed a set of pairs of
natural numbers. Hover your mouse pointer
over the #check command. The message you
get back says that the type of f is what
you can read as "set of values, the type
of which is "pair of natural numbers."
-/
#check f
/-
We can denote specific pairs of natural
numbers as ordered pairs using ordinary
mathematical notation. Here we assign the
pair, (3, 4), as the value of goodPair
(an identifier, or variable name, that
we just made up).
-/
def goodPair := (3, 4)
/-
Lean confirms that the type of goodPair
is ℕ × ℕ, which is to say, the type whose
values are the pairs of natural numbers.
Carefully compare the type of f with the
type of goodPair. The former is a set of
pairs. The latter is a specific individual
pair.
-/
#check goodPair
/-
We can access the elements of pair by
writing .1 or .2 after the pair, to get
its first or second element respectively.
The #reduce command takes and expression
and reduces it to the value it represents.
Hover your mouse over the #reduce to see
the result.
-/
#reduce goodPair.1
#reduce goodPair.2
/-
EXERCISE: Define badPair to be the pair
of natural numbers, (3, 3). We call it a
bad pair because it's not a pair in f.
Use #check to check its type and use
#reduce and .1 and .2 (the first and
second projection functions) to confirm
that both elements of the pair are 3.
-/
/-
So there you have it. We have defined
the function f declaratively as a set
of pairs. Declarative, "set-theoretic"
definitions of functions are ubiquitous
in mathematical writing and reasoning.
-/
/-
One of the advantages of this style of
specification is that it is expressive.
We can say *what* the relationship is
between the arguments to and results of
a function without having provide a
procedure for compute results given
arguments.
Here for example is a declarative
specification of the square root function
for natural numbers. This function contains
pairs of natural numbers where the second
element of each pair is the square root
of the first. Examples include (1, 1),
(4, 2) and (9, 3), but not (9, 4) or
(8, 2).
-/
/-
abh: When I first looked at this, I was about
to argue that this is a multi-valued function
until I realized that the domain is limited to
the naturals, so that {-9, 3} is not allowed.
I mention this because it's a common pitfall
in my experience, so it might be nice to ask
the class, if this is a well-behaved (i.e.,
single-valued) function, and then when some
argue that it is not, explain why it is, but
that it's good to ponder such things.
-/
def sqrt_nat := { p: ℕ × ℕ | p.2 * p.2 = p.1 }
/-
The pairs, (9, 3), (4, 2), and (1,1 ) are in
this function, but (9, 4) isn't because it is
not the case that 9 = 4 * 4.
-/
/-
This specification is crystal clear. It
really says what it means to be a square
root: that result times itself has to be
equal to the argument the the function.
By contrast, a Python program to compute
natural roots of natural numbers would
not be anywhere near as expressive. It might
for example use a loop to check each number,
n, between zero and an argument, a, to see
if n * n is equal to a, returning n if it
satisfies this condition, or an error if it
can't find such an n. Just looking at such
code would hardly make it clear what the
code is meant to do.
-/
/-
A second advantage of the declarative style
of specification is that it let's us specify
*partial* functions without having to explain
anything about values on which a function is
undefined.
Consider the argument 8, for example. There is
no natural number, n, such that n * n = 8. So
there is no pair in this function with first
element 8. We say that the function is not
defined for the value, 8. A function that is
not defined for some argument values is called
partial.
If we wanted to be mathematically precise in
stating that there is no integer square root
of 8, we could write ¬ ∃ n: ℕ | n * n = 8.
A mathematician would say this as "there does
not (¬) exist (∃) a natural number (ℕ), n,
such that n * n = 8." We can make this semi-
formal statement formally precise in Lean,
as what we call a proposition. A proposition
is a claim that some statement is true. Here
the statement is that ¬∃ n: nat, n * n = 8.
-/
lemma no_sqrt8: ¬ ∃ n: nat, n * n = 8 := sorry
/-
To formalize (make mathematically precise) a
proposition in lean, we define an identifier
(here no_sqrt8) whose value is ultimately
meant to be a proof of the proposition. We
next state the proposition itself. Finally,
we give a proof of the proposition (if there
is one, of course). In this case, we use the
Lean construct, sorry, to "apologize" for
not (yet) knowing how to give such a proof.
Sorry tells Lean to take our word for it
and accepts the proposition as being true,
whether it really is or not! Using sorry to
get Lean to accept a false proposition as
true is obviously not a good idea. It makes
a contradiction from which anything can then
be proved true, making the logic useless.
-/
/-
An even better way to explain that there is
no natural number square root of 8 would be
to claim that there is no natural number, s,
such that the pair, (8, n), is in f. (Again
we skip out on trying to provide a proof at
this point. We'll get to that later.)
-/
lemma no_sqrt8': ¬ ∃ s, (8, s) ∈ sqrt_nat := sorry
/-
You can pronounce this like so: there does
not exist an (or, there is no) s such that
the pair (8, s) is in sqrt_nat; please accept
this claim as true even though we don't give
an actual proof.
-/
/-
EXERCISES:
Write a similar lemma without giving a proof
stipulating that there is no square root of
10 in the natural numbers.
-/
/-
This is a great way to specify our function.
The problem is that you can't compute with such
a definition. It is "declarative in the sense
that it declares what the function is, but it
is not procedural, in that it does not give us a
step-by-step procedure for computing a value of
f(x) given a value of x.
The best that we can do with such a declarative
specification is assert that certain facts are
true about it, which we would then be left to try
to prove to be correct. Such assertions are called
propositions.
-/
/-
For example, in pencil-and-paper math, one might
write the proposition, (3, 4) ∈ f_set. The ∈ is
pronounced "is in", so the overall proposition
would be pronounced, "the pair, (3, 4), is in f.
Here's how we can write this proposition in Lean.
We explain the notation below.
-/
lemma three_four_is_in_f : (3, 4) ∈ f := sorry
/-
The "lemma" keyword indicates that we're about
to define a proposition. We give the proposition
the name, three_four_is_in_f. The proposition is
that (3, 4) ∈ f. Finally we tell Lean that we are
sorry, we can't give a proof at the moment, so
Lean should just take our word for it. (Later on
we'll talk much more about proofs.)
-/
/-
In this case, although we haven't tried, it
really is possible to give a proof, which
would show beyond any reasonable doubt that
it really is true (3, 4) is in f.
Of course there are many propositions that are
perfectly fine as propositions but that are
not true, and therefore for which it should
be (and is) impossible to give a proof. One
such proposition is that the pair, (3, 3), is
in f.
-/
/-
Uncomment the following line temporarily.
Once you're done reading about it, turn it
back into a comment. Otherwise your file will
have an error.
-/
-- lemma three_three_is_in_f: (3, 3) ∈ f := _
/-
We don't use sorry here because we don't
want Lean to accept as a given that (3, 3)
is a pair in f. It's not.
Instead of sorry, we use an underscore.
It's called a placeholder. Lean issues an
error saying that it can't figure out how
to fill in that placeholder with a valid
proof. That would of course require that
Lean Lean come up with a proof that doesn't
exist; so it's not going to happen. The
error message can be read as saying, "Hey,
I can't figure out what proof goes here."
-/
/-
The proposition that (3, 3) is NOT in f_set
is true, of course . A mathematician would
write either ¬ (3, 3) ∈ f or (3, 3) ∉ f.
These are two notations for the same idea.
(Just hover over these special symbols to
have Lean tell you what to type to use them
in your own Lean code.) Again, even though
in principle a proof could be given here,
we skip it for now and apologize instead.
-/
lemma three_three_not_in_f: (3, 3) ∉ f := sorry
/-
EXERCISE: Use set comprehension notation to specify
the square root function.
abh: Is this an old exercise, or is the definition above old,
or is this meant to be for types other than naturals?
-/
/-
sqrt = { (x, y) | y * y = x }
-/
/-
What is implicit in this kind of semi-formal mathematics is the
*type* of values over which x and y range. Are the values of x and
y drawn from the natural numbers (the non-negative integers from
zero on up), the integers (including negative whole numbers), the
rationals, the reals, complex numbers? In ordinary, semi-formal
mathematical writing, mathematicians expect the reader to be able
to infer the answer based on context. Here for example, most high
school mathematicians would assume that x and y range over the
reals.
A mathematician seeking to be more precise could instead write this:
f = { (x: ℕ, y: ℕ) | y * y = x }. The "blackboard font" ℕ is standard
mathematical notation for "the natural numbers". So this expression
could be pronounced as "f is the set of x-y pairs where x and y range
over the natural numbers and where in each pair the y value is equal
to one more than the x value." So in this function we have the pair
(4, 2) but not the pair (4.41, 2.1), because 4.41 and 2.1 are not
possible values for x and y. They are of the wrong type.
As an aside, mathematicians generally use the "blackboard font" symbol,
ℤ, for the integers; ℚ, for the rationals; and ℝ, for the real numbers.
In Lean, you can obtain these symbols by typing \nat for the naturals,
\int for the integers, \rat for the rationals, and \real for the reals.
These strings get replaced with the symbols when they are followed by
a space. Try it!
-/
-- REPRESENTING FUNCTIONS AS FUNCTIONAL PROGRAMS
/-
Whereas a mathematician generally thinks of a
function as a set of pairs, with one pair for each
argument value for which the function is defined,
a programmer, on the other hand, thinks of a
function as a kind of machine that takes the first
element of such a pair as an argument, and that
computes and returns the corresponding second
element. For example, if implement the function
f(x) = x + 1 as a program, let's also call it
f_prog, then we could write and evaluate the
expression f_prog(3) and the machine would
compute and return the value 4.
-/
/- Rather than defining a function as a set of
pairs, a "functional program" says, "if you give
me a value for x, I will compute and return the
corresponding value of f(x). The program thus
*implicitly* represents the set of pairs of the
function being represented.
So let's turn from declarative representations
of functions to computational representations.
In particular, we now see how we can write a
function is a mathematically clear way that
nevertheless supports computation of results
given arguments. The trick is to represent a
function not in a procedural language, such
as Python, but in a pure functional language.
There are many such languages. Indeed, even
popular, industrial-strength procedural
languages, such as Java and Python, are
increasingly supporting programming in a
functional style. But nothing beats a real
pure functional language for clarity and
precision.
You'll recall that one way a mathematician
would write our function is as f(x) = x + 1.
Now look at how we'd "implement" f in the
pure functional programming language of Lean.
-/
def f_prog (x: ℕ) := x + 1
/-
We define f_prog to be a function taking
an argument, x, of type ℕ, and returning
(or reducing to) the value of that x plus
1.
-/
/-
We can now use the #reduce command in
Lean to reduce expressions in which this
function is applied to an argument to
compute the corresponding result.
-/
#reduce f_prog 3
/-
If we check the type of f_prog, we find
that Lean says it's of type ℕ → ℕ.
-/
#check f_prog
/-
This can be read as "natural number to
natural number." That is, f_prog takes a
natural number and reduces it to another
natural number. The observant reader will
understand that what this is really saying
is that "f_prog is a value of type ℕ → ℕ."
The value of f_prog is one of many possible
functions taking nats to nats.
-/
/-
EXERCISE: Define g_prog to be a function
from ℕ → ℕ that reduces any given argument
x: ℕ to the value, x * x. Check its type
to confirm that this function is also of
type ℕ → ℕ. You have thus now defined two
values, each functions, both of this type.
Yes, functions are values, too, in a pure
functional programming language, Later on
we'll see that we can compute with
values of function types just as we can
compute with values of numerical types.
Mathematicians view functions as values.
Our good luck is that we can now use pure
functional languages to automate computing
with functions values.
-/
/-
Before we continue, we provide alternative
notations for defining f_prog.
The first declares f_prog' (we add a prime
to the name to make it unique) as a value of
type, ℕ → ℕ, and then uses what we call
lambda notation to represent the function
"value" assigned to f_prog'.
-/
def f_prog': nat → nat :=
λ x, x + 1
/-
The first line declares that f_prog' will
be bound to a value of type ℕ → ℕ. The
second line defines the value so bound.
The notation uses the Greek letter lambda,
which you can just pronounce from now on
as "a function that takes an argument, ...".
The argument it takes is called x. The
body of the function is the expression,
x + 1. The whole "lambda expression" can
thus be read as "a function that takes an
argument, x (already declared to be of type
ℕ by the way)" and that returns the value,
x + 1 (which we've also told Lean should
be of type ℕ.)
-/
/-
Without giving a formal proof, we claim
truthfully here that f_prog' is exactly
the same function as f_prog.
EXERCISE: (1) Use #check to confirm that
the types of f_prog and f_prog' are the
same. Then use #reduce to test the claim
that f_prog and f_prog' reduce to the same
results when applied to the same arguments.
-/
/-
Finally, we note we've left out explicit
type declarations in a few places where
Lean can infer them automatically. Here
we present versions of f_prog and f_prog'
that include explicit type declarations.
Sometimes it's helpful to people to give
explicit declarations. Oftentimes it's
better to leave them out, to make the
code easier to read.
abh: I'd argue that leaving it out also
increases the chances that a mistake
is not caught
-/
def f_prog'' (x: nat): nat := x + 1
/-
Here we declare the result type. Lean
could have figured it out by "seeing"
that the argument is a ℕ, and knowing
that a ℕ plus 1 is also a ℕ.
-/
/-
In the following code we tell Lean that
both the argument and result are of type
ℕ, even though it already knows that is
the case from the ℕ → ℕ type declaration.
-/
def f_prog''': nat → nat :=
λ x: nat, (x + 1: nat)
/-
Leave out explicit type declarations
when (1) Lean can infer them, and (2)
the result code is more rather than
less clear. We think the original
definition of f_prog is pretty clear!
-/
/-
abh: Notice that Lean infers the return
type to be nat
I'm really not a fan of type inference
for return types, or anything beyond a
intermediate variable
-/
def g (x: nat) := 0 - x
#check g
-- EVALUATING (REDUCING) FUNCTION APPLICATION EXPRESSIONS
/-
In a pure functional language, a program is simply the
expression of a ... wait for it ... mathematical function.
A function definition in such a language has an argument,
or "formal parameter", (such as x), and an expression,
the "body" of the function, in which the formal parameter,
x, can appear, as it does in the expression, x + 1.
When such a function is applied to a value, such as 3, the
resulting expression is *evaluated* by substituting the actual
value (here 3) for every occurrence of the formal parameter
(here x) in the function body (here x + 1). The resulting
expression (here 3 + 1) is itself then evaluated. Finally
the resulting value is returned. That value is the result
of "reducing" the original function application expression.
-/
/-
Note that the argument to a function can be any expression that
itself reduces to a value of the right type. Here's an example.
-/
#reduce f_prog (2 + 2)
/-
Here we're using Lean's built-in addition function applied to the
two arguments, 2 and 2, to represent the value to be passed as the
argument to f.
Just as in ordinary paper-and-pencil arithmetic, in Lean, he inner
expression (2 + 2) is evaluated first and result, 4, is then taken
as the argument to the outer function, f.
-/
/-
EXERCISE: First predict then confirm your prediction of the return
value of the following (nested) function application expression.
-/
#reduce f_prog (f_prog (f_prog 4))
/-
EXERCISES: more to come.
-/
|
da65706b64ccccf14e16f7651ab5550e9ad61019 | e61a235b8468b03aee0120bf26ec615c045005d2 | /stage0/src/Init/Lean/Elab/Tactic/Basic.lean | 0df895aefb05ca1c06aadd1e555cb166feaa3828 | [
"Apache-2.0"
] | permissive | SCKelemen/lean4 | 140dc63a80539f7c61c8e43e1c174d8500ec3230 | e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc | refs/heads/master | 1,660,973,595,917 | 1,590,278,033,000 | 1,590,278,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,796 | 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, Sebastian Ullrich
-/
prelude
import Init.Lean.Util.CollectMVars
import Init.Lean.Meta.Tactic.Assumption
import Init.Lean.Meta.Tactic.Intro
import Init.Lean.Meta.Tactic.Clear
import Init.Lean.Meta.Tactic.Revert
import Init.Lean.Meta.Tactic.Subst
import Init.Lean.Elab.Util
import Init.Lean.Elab.Term
namespace Lean
namespace Elab
def goalsToMessageData (goals : List MVarId) : MessageData :=
MessageData.joinSep (goals.map $ MessageData.ofGoal) (Format.line ++ Format.line)
def Term.reportUnsolvedGoals (ref : Syntax) (goals : List MVarId) : TermElabM Unit :=
let tailRef := ref.getTailWithPos.getD ref;
Term.throwError tailRef $ "unsolved goals" ++ Format.line ++ goalsToMessageData goals
namespace Tactic
structure Context extends toTermCtx : Term.Context :=
(main : MVarId)
(ref : Syntax)
structure State extends toTermState : Term.State :=
(goals : List MVarId)
instance State.inhabited : Inhabited State := ⟨{ goals := [], toTermState := arbitrary _ }⟩
structure BacktrackableState :=
(env : Environment)
(mctx : MetavarContext)
(goals : List MVarId)
abbrev Exception := Elab.Exception
abbrev TacticM := ReaderT Context (EStateM Exception State)
abbrev Tactic := Syntax → TacticM Unit
protected def save (s : State) : BacktrackableState :=
{ env := s.env, mctx := s.mctx, goals := s.goals }
protected def restore (s : State) (bs : BacktrackableState) : State :=
{ s with env := bs.env, mctx := bs.mctx, goals := bs.goals }
instance : EStateM.Backtrackable BacktrackableState State :=
{ save := Tactic.save,
restore := Tactic.restore }
def liftTermElabM {α} (x : TermElabM α) : TacticM α :=
fun ctx s => match x ctx.toTermCtx s.toTermState with
| EStateM.Result.ok a newS => EStateM.Result.ok a { s with toTermState := newS }
| EStateM.Result.error (Term.Exception.ex ex) newS => EStateM.Result.error ex { s with toTermState := newS }
| EStateM.Result.error Term.Exception.postpone _ => unreachable!
def liftMetaM {α} (ref : Syntax) (x : MetaM α) : TacticM α := liftTermElabM $ Term.liftMetaM ref x
def getEnv : TacticM Environment := do s ← get; pure s.env
def getMCtx : TacticM MetavarContext := do s ← get; pure s.mctx
@[inline] def modifyMCtx (f : MetavarContext → MetavarContext) : TacticM Unit := modify $ fun s => { s with mctx := f s.mctx }
def getLCtx : TacticM LocalContext := do ctx ← read; pure ctx.lctx
def getLocalInsts : TacticM LocalInstances := do ctx ← read; pure ctx.localInstances
def getOptions : TacticM Options := do ctx ← read; pure ctx.config.opts
def getMVarDecl (mvarId : MVarId) : TacticM MetavarDecl := do mctx ← getMCtx; pure $ mctx.getDecl mvarId
def instantiateMVars (ref : Syntax) (e : Expr) : TacticM Expr := liftTermElabM $ Term.instantiateMVars ref e
def addContext (msg : MessageData) : TacticM MessageData := liftTermElabM $ Term.addContext msg
def isExprMVarAssigned (mvarId : MVarId) : TacticM Bool := liftTermElabM $ Term.isExprMVarAssigned mvarId
def assignExprMVar (mvarId : MVarId) (val : Expr) : TacticM Unit := liftTermElabM $ Term.assignExprMVar mvarId val
def ensureHasType (ref : Syntax) (expectedType? : Option Expr) (e : Expr) : TacticM Expr := liftTermElabM $ Term.ensureHasType ref expectedType? e
def reportUnsolvedGoals (ref : Syntax) (goals : List MVarId) : TacticM Unit := liftTermElabM $ Term.reportUnsolvedGoals ref goals
def inferType (ref : Syntax) (e : Expr) : TacticM Expr := liftTermElabM $ Term.inferType ref e
def whnf (ref : Syntax) (e : Expr) : TacticM Expr := liftTermElabM $ Term.whnf ref e
def whnfCore (ref : Syntax) (e : Expr) : TacticM Expr := liftTermElabM $ Term.whnfCore ref e
def unfoldDefinition? (ref : Syntax) (e : Expr) : TacticM (Option Expr) := liftTermElabM $ Term.unfoldDefinition? ref e
def resolveGlobalName (n : Name) : TacticM (List (Name × List String)) := liftTermElabM $ Term.resolveGlobalName n
/-- Collect unassigned metavariables -/
def collectMVars (ref : Syntax) (e : Expr) : TacticM (List MVarId) := do
e ← instantiateMVars ref e;
let s := Lean.collectMVars {} e;
pure s.result.toList
instance monadLog : MonadLog TacticM :=
{ getCmdPos := do ctx ← read; pure ctx.cmdPos,
getFileMap := do ctx ← read; pure ctx.fileMap,
getFileName := do ctx ← read; pure ctx.fileName,
addContext := addContext,
logMessage := fun msg => modify $ fun s => { s with messages := s.messages.add msg } }
def throwError {α} (ref : Syntax) (msgData : MessageData) : TacticM α := do
ref ← if ref.getPos.isNone then do ctx ← read; pure ctx.ref else pure ref;
liftTermElabM $ Term.throwError ref msgData
def throwUnsupportedSyntax {α} : TacticM α := liftTermElabM $ Term.throwUnsupportedSyntax
@[inline] def withIncRecDepth {α} (ref : Syntax) (x : TacticM α) : TacticM α := do
ctx ← read;
when (ctx.currRecDepth == ctx.maxRecDepth) $ throwError ref maxRecDepthErrorMessage;
adaptReader (fun (ctx : Context) => { ctx with currRecDepth := ctx.currRecDepth + 1 }) x
protected def getCurrMacroScope : TacticM MacroScope := do ctx ← read; pure ctx.currMacroScope
protected def getMainModule : TacticM Name := do env ← getEnv; pure env.mainModule
@[inline] protected def withFreshMacroScope {α} (x : TacticM α) : TacticM α := do
fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }));
adaptReader (fun (ctx : Context) => { ctx with currMacroScope := fresh }) x
instance monadQuotation : MonadQuotation TacticM := {
getCurrMacroScope := Tactic.getCurrMacroScope,
getMainModule := Tactic.getMainModule,
withFreshMacroScope := @Tactic.withFreshMacroScope
}
unsafe def mkTacticAttribute : IO (KeyedDeclsAttribute Tactic) :=
mkElabAttribute Tactic `Lean.Elab.Tactic.tacticElabAttribute `builtinTactic `tactic `Lean.Parser.Tactic `Lean.Elab.Tactic.Tactic "tactic"
@[init mkTacticAttribute] constant tacticElabAttribute : KeyedDeclsAttribute Tactic := arbitrary _
def logTrace (cls : Name) (ref : Syntax) (msg : MessageData) : TacticM Unit := liftTermElabM $ Term.logTrace cls ref msg
@[inline] def trace (cls : Name) (ref : Syntax) (msg : Unit → MessageData) : TacticM Unit := liftTermElabM $ Term.trace cls ref msg
@[inline] def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TacticM Unit := liftTermElabM $ Term.traceAtCmdPos cls msg
def dbgTrace {α} [HasToString α] (a : α) : TacticM Unit :=_root_.dbgTrace (toString a) $ fun _ => pure ()
private def evalTacticUsing (s : State) (stx : Syntax) : List Tactic → TacticM Unit
| [] => do
let refFmt := stx.prettyPrint;
throwError stx ("unexpected syntax" ++ MessageData.nest 2 (Format.line ++ refFmt))
| (evalFn::evalFns) => catch (evalFn stx)
(fun ex => match ex with
| Exception.error _ =>
match evalFns with
| [] => throw ex
| _ => do set s; evalTacticUsing evalFns
| Exception.unsupportedSyntax => do set s; evalTacticUsing evalFns)
/- Elaborate `x` with `stx` on the macro stack -/
@[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : TacticM α) : TacticM α :=
adaptReader (fun (ctx : Context) => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x
instance : MonadMacroAdapter TacticM :=
{ getEnv := getEnv,
getCurrMacroScope := getCurrMacroScope,
getNextMacroScope := do s ← get; pure s.nextMacroScope,
setNextMacroScope := fun next => modify $ fun s => { s with nextMacroScope := next },
throwError := @throwError,
throwUnsupportedSyntax := @throwUnsupportedSyntax }
@[specialize] private def expandTacticMacroFns (evalTactic : Syntax → TacticM Unit) (stx : Syntax) : List Macro → TacticM Unit
| [] => throwError stx ("tactic '" ++ toString stx.getKind ++ "' has not been implemented")
| m::ms => do
scp ← getCurrMacroScope;
catch
(do stx' ← adaptMacro m stx; evalTactic stx')
(fun ex => match ms with
| [] => throw ex
| _ => expandTacticMacroFns ms)
@[inline] def expandTacticMacro (evalTactic : Syntax → TacticM Unit) (stx : Syntax) : TacticM Unit := do
env ← getEnv;
let k := stx.getKind;
let table := (macroAttribute.ext.getState env).table;
let macroFns := (table.find? k).getD [];
expandTacticMacroFns evalTactic stx macroFns
partial def evalTactic : Syntax → TacticM Unit
| stx => withIncRecDepth stx $ withFreshMacroScope $ match stx with
| Syntax.node k args =>
if k == nullKind then
-- list of tactics separated by `;` => evaluate in order
-- Syntax quotations can return multiple ones
stx.forSepArgsM evalTactic
else do
trace `Elab.step stx $ fun _ => stx;
s ← get;
let table := (tacticElabAttribute.ext.getState s.env).table;
let k := stx.getKind;
match table.find? k with
| some evalFns => evalTacticUsing s stx evalFns
| none => expandTacticMacro evalTactic stx
| _ => throwError stx "unexpected command"
/-- Adapt a syntax transformation to a regular tactic evaluator. -/
def adaptExpander (exp : Syntax → TacticM Syntax) : Tactic :=
fun stx => do
stx' ← exp stx;
withMacroExpansion stx stx' $ evalTactic stx'
@[inline] def withLCtx {α} (lctx : LocalContext) (localInsts : LocalInstances) (x : TacticM α) : TacticM α :=
adaptReader (fun (ctx : Context) => { ctx with lctx := lctx, localInstances := localInsts }) x
def resetSynthInstanceCache : TacticM Unit := liftTermElabM Term.resetSynthInstanceCache
@[inline] def resettingSynthInstanceCache {α} (x : TacticM α) : TacticM α := do
s ← get;
let savedSythInstance := s.cache.synthInstance;
resetSynthInstanceCache;
finally x (modify $ fun s => { s with cache := { s.cache with synthInstance := savedSythInstance } })
@[inline] def resettingSynthInstanceCacheWhen {α} (b : Bool) (x : TacticM α) : TacticM α :=
if b then resettingSynthInstanceCache x else x
def withMVarContext {α} (mvarId : MVarId) (x : TacticM α) : TacticM α := do
mvarDecl ← getMVarDecl mvarId;
ctx ← read;
let needReset := ctx.localInstances == mvarDecl.localInstances;
withLCtx mvarDecl.lctx mvarDecl.localInstances $ resettingSynthInstanceCacheWhen needReset x
def getGoals : TacticM (List MVarId) := do s ← get; pure s.goals
def setGoals (gs : List MVarId) : TacticM Unit := modify $ fun s => { s with goals := gs }
def appendGoals (gs : List MVarId) : TacticM Unit := modify $ fun s => { s with goals := s.goals ++ gs }
def pruneSolvedGoals : TacticM Unit := do
gs ← getGoals;
gs ← gs.filterM $ fun g => not <$> isExprMVarAssigned g;
setGoals gs
def getUnsolvedGoals : TacticM (List MVarId) := do pruneSolvedGoals; getGoals
def getMainGoal (ref : Syntax) : TacticM (MVarId × List MVarId) := do (g::gs) ← getUnsolvedGoals | throwError ref "no goals to be solved"; pure (g, gs)
def ensureHasNoMVars (ref : Syntax) (e : Expr) : TacticM Unit := do
e ← instantiateMVars ref e;
when e.hasMVar $ throwError ref ("tactic failed, resulting expression contains metavariables" ++ indentExpr e)
def withMainMVarContext {α} (ref : Syntax) (x : TacticM α) : TacticM α := do
(mvarId, _) ← getMainGoal ref;
withMVarContext mvarId x
@[inline] def liftMetaMAtMain {α} (ref : Syntax) (x : MVarId → MetaM α) : TacticM α := do
(g, _) ← getMainGoal ref;
withMVarContext g $ liftMetaM ref $ x g
@[inline] def liftMetaTacticAux {α} (ref : Syntax) (tactic : MVarId → MetaM (α × List MVarId)) : TacticM α := do
(g, gs) ← getMainGoal ref;
withMVarContext g $ do
(a, gs') ← liftMetaM ref $ tactic g;
setGoals (gs' ++ gs);
pure a
@[inline] def liftMetaTactic (ref : Syntax) (tactic : MVarId → MetaM (List MVarId)) : TacticM Unit :=
liftMetaTacticAux ref (fun mvarId => do gs ← tactic mvarId; pure ((), gs))
def done (ref : Syntax) : TacticM Unit := do
gs ← getUnsolvedGoals;
unless gs.isEmpty $ reportUnsolvedGoals ref gs
def focusAux {α} (ref : Syntax) (tactic : TacticM α) : TacticM α := do
(g, gs) ← getMainGoal ref;
setGoals [g];
a ← tactic;
gs' ← getGoals;
setGoals (gs' ++ gs);
pure a
def focus {α} (ref : Syntax) (tactic : TacticM α) : TacticM α :=
focusAux ref (do a ← tactic; done ref; pure a)
/--
Use `parentTag` to tag untagged goals at `newGoals`.
If there are multiple new goals, they are named using `<parentTag>.<newSuffix>_<idx>` where `idx > 0`.
If there is only one new goal, then we just use `parentTag` -/
def tagUntaggedGoals (parentTag : Name) (newSuffix : Name) (newGoals : List MVarId) : TacticM Unit := do
mctx ← getMCtx;
match newGoals with
| [g] => modifyMCtx $ fun mctx => if mctx.isAnonymousMVar g then mctx.renameMVar g parentTag else mctx
| _ => modifyMCtx $ fun mctx =>
let (mctx, _) := newGoals.foldl
(fun (acc : MetavarContext × Nat) (g : MVarId) =>
let (mctx, idx) := acc;
if mctx.isAnonymousMVar g then
(mctx.renameMVar g (parentTag ++ newSuffix.appendIndexAfter idx), idx+1)
else
acc)
(mctx, 1);
mctx
@[builtinTactic seq] def evalSeq : Tactic :=
fun stx => (stx.getArg 0).forSepArgsM evalTactic
partial def evalChoiceAux (tactics : Array Syntax) : Nat → TacticM Unit
| i =>
if h : i < tactics.size then
let tactic := tactics.get ⟨i, h⟩;
catch
(evalTactic tactic)
(fun ex => match ex with
| Exception.unsupportedSyntax => evalChoiceAux (i+1)
| _ => throw ex)
else
throwUnsupportedSyntax
@[builtinTactic choice] def evalChoice : Tactic :=
fun stx => evalChoiceAux stx.getArgs 0
@[builtinTactic skip] def evalSkip : Tactic :=
fun stx => pure ()
@[builtinTactic failIfSuccess] def evalFailIfSuccess : Tactic :=
fun stx =>
let tactic := stx.getArg 1;
whenM
(catch
(do evalTactic tactic; pure true)
(fun _ => pure false))
(throwError stx ("tactic succeeded"))
@[builtinTactic traceState] def evalTraceState : Tactic :=
fun stx => do
gs ← getUnsolvedGoals;
logInfo stx (goalsToMessageData gs)
@[builtinTactic «assumption»] def evalAssumption : Tactic :=
fun stx => liftMetaTactic stx $ fun mvarId => do Meta.assumption mvarId; pure []
@[builtinTactic «intro»] def evalIntro : Tactic :=
fun stx => match_syntax stx with
| `(tactic| intro) => liftMetaTactic stx $ fun mvarId => do (_, mvarId) ← Meta.intro1 mvarId; pure [mvarId]
| `(tactic| intro $h) => liftMetaTactic stx $ fun mvarId => do (_, mvarId) ← Meta.intro mvarId h.getId; pure [mvarId]
| _ => throwUnsupportedSyntax
private def getIntrosSize : Expr → Nat
| Expr.forallE _ _ b _ => getIntrosSize b + 1
| Expr.letE _ _ _ b _ => getIntrosSize b + 1
| _ => 0
@[builtinTactic «intros»] def evalIntros : Tactic :=
fun stx => match_syntax stx with
| `(tactic| intros) => liftMetaTactic stx $ fun mvarId => do
type ← Meta.getMVarType mvarId;
type ← Meta.instantiateMVars type;
let n := getIntrosSize type;
(_, mvarId) ← Meta.introN mvarId n;
pure [mvarId]
| `(tactic| intros $ids*) => liftMetaTactic stx $ fun mvarId => do
(_, mvarId) ← Meta.introN mvarId ids.size (ids.map Syntax.getId).toList;
pure [mvarId]
| _ => throwUnsupportedSyntax
def getFVarId (id : Syntax) : TacticM FVarId := do
fvar? ← liftTermElabM $ Term.isLocalTermId? id true;
match fvar? with
| some fvar => pure fvar.fvarId!
| none => throwError id ("unknown variable '" ++ toString id.getId ++ "'")
def getFVarIds (ids : Array Syntax) : TacticM (Array FVarId) :=
ids.mapM getFVarId
@[builtinTactic «revert»] def evalRevert : Tactic :=
fun stx => match_syntax stx with
| `(tactic| revert $hs*) => do
(g, gs) ← getMainGoal stx;
withMVarContext g $ do
fvarIds ← getFVarIds hs;
(_, g) ← liftMetaM stx $ Meta.revert g fvarIds;
setGoals (g :: gs)
| _ => throwUnsupportedSyntax
def forEachVar (ref : Syntax) (hs : Array Syntax) (tac : MVarId → FVarId → MetaM MVarId) : TacticM Unit :=
hs.forM $ fun h => do
(g, gs) ← getMainGoal ref;
withMVarContext g $ do
fvarId ← getFVarId h;
g ← liftMetaM ref $ tac g fvarId;
setGoals (g :: gs)
@[builtinTactic «clear»] def evalClear : Tactic :=
fun stx => match_syntax stx with
| `(tactic| clear $hs*) => forEachVar stx hs Meta.clear
| _ => throwUnsupportedSyntax
@[builtinTactic «subst»] def evalSubst : Tactic :=
fun stx => match_syntax stx with
| `(tactic| subst $hs*) => forEachVar stx hs Meta.subst
| _ => throwUnsupportedSyntax
@[builtinTactic paren] def evalParen : Tactic :=
fun stx => evalTactic (stx.getArg 1)
@[builtinTactic nestedTacticBlock] def evalNestedTacticBlock : Tactic :=
fun stx => focus stx (evalTactic (stx.getArg 1))
@[builtinTactic nestedTacticBlockCurly] def evalNestedTacticBlockCurly : Tactic :=
evalNestedTacticBlock
@[builtinTactic «case»] def evalCase : Tactic :=
fun stx => match_syntax stx with
| `(tactic| case $tag $tac) => do
let tag := tag.getId;
gs ← getUnsolvedGoals;
some g ← gs.findM? (fun g => do mvarDecl ← getMVarDecl g; pure $ tag.isSuffixOf mvarDecl.userName) | throwError stx "tag not found";
let gs := gs.erase g;
setGoals [g];
evalTactic tac;
done stx;
setGoals gs
| _ => throwUnsupportedSyntax
@[builtinTactic «orelse»] def evalOrelse : Tactic :=
fun stx => match_syntax stx with
| `(tactic| $tac1 <|> $tac2) => evalTactic tac1 <|> evalTactic tac2
| _ => throwUnsupportedSyntax
@[init] private def regTraceClasses : IO Unit := do
registerTraceClass `Elab.tactic;
pure ()
end Tactic
end Elab
end Lean
|
b1d1f84b420b3ff2af0eef9fbf01f482829c7849 | b147e1312077cdcfea8e6756207b3fa538982e12 | /analysis/real.lean | 8959bce9fa326bf30eca1c6af1a7ffe413f9158d | [
"Apache-2.0"
] | permissive | SzJS/mathlib | 07836ee708ca27cd18347e1e11ce7dd5afb3e926 | 23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29 | refs/heads/master | 1,584,980,332,064 | 1,532,063,841,000 | 1,532,063,841,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,110 | 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
The real numbers ℝ.
They are constructed as the topological completion of ℚ. With the following steps:
(1) prove that ℚ forms a uniform space.
(2) subtraction and addition are uniform continuous functions in this space
(3) for multiplication and inverse this only holds on bounded subsets
(4) ℝ is defined as separated Cauchy filters over ℚ (the separation requires a quotient construction)
(5) extend the uniform continuous functions along the completion
(6) proof field properties using the principle of extension of identities
TODO
generalizations:
* topological groups & rings
* order topologies
* Archimedean fields
-/
import logic.function analysis.metric_space
noncomputable theory
open classical set lattice filter topological_space
local attribute [instance] prop_decidable
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
instance : metric_space ℚ :=
metric_space.induced coe rat.cast_injective real.metric_space
theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl
instance : metric_space ℤ :=
begin
letI M := metric_space.induced coe int.cast_injective real.metric_space,
refine @metric_space.replace_uniformity _ int.uniform_space M
(le_antisymm refl_le_uniformity $ λ r ru,
mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h,
mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩),
simpa using (@int.cast_le ℝ _ _ 0).2 (int.lt_add_one_iff.1 $
(@int.cast_lt ℝ _ (abs (a - b)) 1).1 $ by simpa using h)
end
theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) :=
uniform_continuous_vmap
theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) :=
metric_space.induced_uniform_embedding _ _ _
theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) :=
uniform_embedding_of_rat.dense_embedding $
λ x, mem_closure_iff_nhds.2 $ λ t ht,
let ⟨ε,ε0, hε⟩ := mem_nhds_iff_metric.1 ht in
let ⟨q, h⟩ := exists_rat_near x ε0 in
ne_empty_iff_exists_mem.2 ⟨_, hε (mem_ball'.2 h), q, rfl⟩
theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.embedding
theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous
theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) :=
uniform_continuous_of_metric.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in
⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩
-- TODO(Mario): Find a way to use rat_add_continuous_lemma
theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) :=
uniform_embedding_of_rat.uniform_continuous_iff.2 $ by simp [(∘)]; exact
((uniform_continuous_fst.comp uniform_continuous_of_rat).prod_mk
(uniform_continuous_snd.comp uniform_continuous_of_rat)).comp real.uniform_continuous_add
theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) :=
uniform_continuous_of_metric.2 $ λ ε ε0, ⟨_, ε0, λ a b h,
by rw dist_comm at h; simpa [real.dist_eq] using h⟩
theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) :=
uniform_continuous_of_metric.2 $ λ ε ε0, ⟨_, ε0, λ a b h,
by rw dist_comm at h; simpa [rat.dist_eq] using h⟩
instance : uniform_add_group ℝ :=
uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg
instance : uniform_add_group ℚ :=
uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg
instance : topological_add_group ℝ := by apply_instance
instance : topological_add_group ℚ := by apply_instance
instance : orderable_topology ℚ :=
induced_orderable_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _)
lemma real.is_topological_basis_Ioo_rat :
@is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) :=
is_topological_basis_of_open_of_nhds
(by simp [is_open_Ioo] {contextual:=tt})
(assume a v hav hv,
let ⟨l, u, hl, hu, h⟩ := (mem_nhds_unbounded (no_top _) (no_bot _)).mp (mem_nhds_sets hv hav),
⟨q, hlq, hqa⟩ := exists_rat_btwn hl,
⟨p, hap, hpu⟩ := exists_rat_btwn hu in
⟨Ioo q p,
by simp; exact ⟨q, p, rat.cast_lt.1 $ lt_trans hqa hap, rfl⟩,
⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h _ (lt_trans hlq hqa') (lt_trans ha'p hpu)⟩)
instance : second_countable_topology ℝ :=
⟨⟨(⋃(a b : ℚ) (h : a < b), {Ioo a b}),
by simp [countable_Union, countable_Union_Prop],
real.is_topological_basis_Ioo_rat.2.2⟩⟩
/- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings
lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) :=
_
lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) :=
_ -/
lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) :
uniform_continuous (λp:s, p.1⁻¹) :=
uniform_continuous_of_metric.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in
⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩
lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) :=
uniform_continuous_of_metric.2 $ λ ε ε0,
⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩
lemma real.continuous_abs : continuous (abs : ℝ → ℝ) :=
real.uniform_continuous_abs.continuous
lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) :=
uniform_continuous_of_metric.2 $ λ ε ε0,
⟨ε, ε0, λ a b h, lt_of_le_of_lt
(by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩
lemma rat.continuous_abs : continuous (abs : ℚ → ℚ) :=
rat.uniform_continuous_abs.continuous
lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (nhds r) (nhds r⁻¹) :=
by rw ← abs_pos_iff at r0; exact
tendsto_of_uniform_continuous_subtype
(real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h))
(mem_nhds_sets (real.continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0))
lemma real.continuous_inv' : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) :=
continuous_iff_tendsto.mpr $ assume ⟨r, hr⟩,
(continuous_iff_tendsto.mp continuous_subtype_val _).comp (real.tendsto_inv hr)
lemma real.continuous_inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) :
continuous (λa, (f a)⁻¹) :=
show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩),
from (continuous_subtype_mk _ hf).comp real.continuous_inv'
lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) :=
uniform_continuous_of_metric.2 $ λ ε ε0, begin
cases no_top (abs x) with y xy,
have y0 := lt_of_le_of_lt (abs_nonneg _) xy,
refine ⟨_, div_pos ε0 y0, λ a b h, _⟩,
rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)],
exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0
end
lemma real.uniform_continuous_mul (s : set (ℝ × ℝ))
{r₁ r₂ : ℝ} (r₁0 : 0 < r₁) (r₂0 : 0 < r₂)
(H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) :
uniform_continuous (λp:s, p.1.1 * p.1.2) :=
uniform_continuous_of_metric.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 r₁0 r₂0 in
⟨δ, δ0, λ a b h,
let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩
lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) :=
continuous_iff_tendsto.2 $ λ ⟨a₁, a₂⟩,
tendsto_of_uniform_continuous_subtype
(real.uniform_continuous_mul
({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1})
(lt_of_le_of_lt (abs_nonneg _) (lt_add_one _))
(lt_of_le_of_lt (abs_nonneg _) (lt_add_one _))
(λ x, id))
(mem_nhds_sets
(is_open_prod
(real.continuous_abs _ $ is_open_gt' _)
(real.continuous_abs _ $ is_open_gt' _))
⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩)
instance : topological_ring ℝ :=
{ continuous_mul := real.continuous_mul, ..real.topological_add_group }
instance : topological_semiring ℝ := by apply_instance
lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) :=
embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact
((continuous_fst.comp continuous_of_rat).prod_mk
(continuous_snd.comp continuous_of_rat)).comp real.continuous_mul
instance : topological_ring ℚ :=
{ continuous_mul := rat.continuous_mul, ..rat.topological_add_group }
theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) :=
set.ext $ λ y, by rw [mem_ball, real.dist_eq,
abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl
theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) :=
by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add,
add_sub_cancel', add_self_div_two, ← add_div,
add_assoc, add_sub_cancel'_right, add_self_div_two]
lemma real.totally_bounded_Ioo (a b : ℝ) : totally_bounded (Ioo a b) :=
totally_bounded_of_metric.2 $ λ ε ε0, begin
rcases exists_nat_gt ((b - a) / ε) with ⟨n, ba⟩,
rw [div_lt_iff' ε0, sub_lt_iff_lt_add'] at ba,
let s := (λ i:ℕ, a + ε * i) '' {i:ℕ | i < n},
refine ⟨s, finite_image _ ⟨set.fintype_lt_nat _⟩, λ x h, _⟩,
rcases h with ⟨ax, xb⟩,
let i : ℕ := ⌊(x - a) / ε⌋.to_nat,
have : (i : ℤ) = ⌊(x - a) / ε⌋ :=
int.to_nat_of_nonneg (floor_nonneg.2 $ le_of_lt (div_pos (sub_pos.2 ax) ε0)),
simp, refine ⟨_, ⟨i, _, rfl⟩, _⟩,
{ rw [← int.coe_nat_lt, this],
refine int.cast_lt.1 (lt_of_le_of_lt (floor_le _) _),
rw [int.cast_coe_nat, div_lt_iff' ε0, sub_lt_iff_lt_add'],
exact lt_trans xb ba },
{ rw [real.dist_eq, ← int.cast_coe_nat, this, abs_of_nonneg,
← sub_sub, sub_lt_iff_lt_add'],
{ have := lt_floor_add_one ((x - a) / ε),
rwa [div_lt_iff' ε0, mul_add, mul_one] at this },
{ have := floor_le ((x - a) / ε),
rwa [ge, sub_nonneg, ← le_sub_iff_add_le', ← le_div_iff' ε0] } }
end
lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) :=
by rw real.ball_eq_Ioo; apply real.totally_bounded_Ioo
lemma real.totally_bounded_Ico (a b : ℝ) : totally_bounded (Ico a b) :=
let ⟨c, ac⟩ := no_bot a in totally_bounded_subset
(by exact λ x ⟨h₁, h₂⟩, ⟨lt_of_lt_of_le ac h₁, h₂⟩)
(real.totally_bounded_Ioo c b)
lemma real.totally_bounded_Icc (a b : ℝ) : totally_bounded (Icc a b) :=
let ⟨c, bc⟩ := no_top b in totally_bounded_subset
(by exact λ x ⟨h₁, h₂⟩, ⟨h₁, lt_of_le_of_lt h₂ bc⟩)
(real.totally_bounded_Ico a c)
lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) :=
begin
have := totally_bounded_preimage uniform_embedding_of_rat (real.totally_bounded_Icc a b),
rwa (set.ext (λ q, _) : Icc _ _ = _), simp
end
-- TODO(Mario): Generalize to first-countable uniform spaces?
instance : complete_space ℝ :=
⟨λ f cf, begin
have := (cauchy_of_metric.1 cf).2,
let S : ∀ ε:{ε:ℝ//ε>0}, {t : f.sets // ∀ x y ∈ t.1, dist x y < ε} :=
λ ε, classical.choice
(let ⟨t, tf, h⟩ := (cauchy_of_metric.1 cf).2 ε ε.2 in ⟨⟨⟨t, tf⟩, h⟩⟩),
let g : ℕ → {ε:ℝ//ε>0} := λ n,
⟨n.to_pnat'⁻¹, inv_pos (nat.cast_pos.2 n.to_pnat'.pos)⟩,
have hg : ∀ ε > 0, ∃ n, ∀ j ≥ n, (g j : ℝ) < ε,
{ intros ε ε0,
cases exists_nat_gt ε⁻¹ with n hn,
refine ⟨n, λ j nj, _⟩,
have hj := lt_of_lt_of_le hn (nat.cast_le.2 nj),
have j0 := lt_trans (inv_pos ε0) hj,
have jε := (inv_lt j0 ε0).2 hj,
rwa ← pnat.to_pnat'_coe (nat.cast_pos.1 j0) at jε },
let F : ∀ n : ℕ, {t : f.sets // ∀ x y ∈ t.1, dist x y < g n},
{ refine λ n, ⟨⟨_, Inter_mem_sets (finite_le_nat n) (λ i _, (S (g i)).1.2)⟩, _⟩,
have : (⋂ i ∈ {i : ℕ | i ≤ n}, (S (g i)).1.1) ⊆ S (g n) :=
bInter_subset_of_mem (le_refl n),
exact λ x y xs ys, (S (g n)).2 _ _ (this xs) (this ys) },
let G : ∀ n : ℕ, F n,
{ refine λ n, classical.choice _,
cases inhabited_of_mem_sets cf.1 (F n).1.2 with x xS,
exact ⟨⟨x, xS⟩⟩ },
let c : cau_seq ℝ abs,
{ refine ⟨λ n, G n, λ ε ε0, _⟩,
cases hg _ ε0 with n hn,
refine ⟨n, λ j jn, _⟩,
have : (F j).1.1 ⊆ (F n) :=
bInter_subset_bInter_left (λ i h, @le_trans _ _ i n j h jn),
exact lt_trans ((F n).2 _ _ (this (G j).2) (G n).2) (hn _ $ le_refl _) },
refine ⟨real.lim c, λ s h, _⟩,
rcases mem_nhds_iff_metric.1 h with ⟨ε, ε0, hε⟩,
cases exists_forall_ge_and (hg _ $ half_pos ε0)
(real.equiv_lim c _ $ half_pos ε0) with n hn,
cases hn _ (le_refl _) with h₁ h₂,
refine upwards_sets _ (F n).1.2 (subset.trans _ $
subset.trans (ball_half_subset (G n) h₂) hε),
exact λ x h, lt_trans ((F n).2 x (G n) h (G n).2) h₁
end⟩
-- TODO(Mario): This proof has nothing to do with reals
theorem real.Cauchy_eq {f g : Cauchy ℝ} :
lim f.1 = lim g.1 ↔ (f, g) ∈ separation_rel (Cauchy ℝ) :=
begin
split,
{ intros e s hs,
rcases Cauchy.mem_uniformity'.1 hs with ⟨t, tu, ts⟩,
apply ts,
rcases comp_mem_uniformity_sets tu with ⟨d, du, dt⟩,
refine mem_prod_iff.2
⟨_, le_nhds_lim_of_cauchy f.2 (mem_nhds_right (lim f.1) du),
_, le_nhds_lim_of_cauchy g.2 (mem_nhds_left (lim g.1) du), λ x h, _⟩,
cases x with a b, cases h with h₁ h₂,
rw ← e at h₂,
exact dt ⟨_, h₁, h₂⟩ },
{ intros H,
refine separated_def.1 (by apply_instance) _ _ (λ t tu, _),
rcases mem_uniformity_is_closed tu with ⟨d, du, dc, dt⟩,
refine H {p | (lim p.1.1, lim p.2.1) ∈ t}
(Cauchy.mem_uniformity'.2 ⟨d, du, λ f g h, _⟩),
rcases mem_prod_iff.1 h with ⟨x, xf, y, yg, h⟩,
have limc : ∀ (f : Cauchy ℝ) (x ∈ f.1.sets), lim f.1 ∈ closure x,
{ intros f x xf,
rw closure_eq_nhds,
exact neq_bot_of_le_neq_bot f.2.1
(le_inf (le_nhds_lim_of_cauchy f.2) (le_principal_iff.2 xf)) },
have := (closure_subset_iff_subset_of_is_closed dc).2 h,
rw closure_prod_eq at this,
refine dt (this ⟨_, _⟩); dsimp; apply limc; assumption }
end
lemma tendsto_of_nat_at_top_at_top : tendsto (coe : ℕ → ℝ) at_top at_top :=
tendsto_infi.2 $ assume r, tendsto_principal.2 $
let ⟨n, hn⟩ := exists_nat_gt r in
mem_at_top_sets.2 ⟨n, λ m h, le_trans (le_of_lt hn) (nat.cast_le.2 h)⟩
section
lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} :=
subset.antisymm
((closure_subset_iff_subset_of_is_closed (is_closed_ge' _)).2
(image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $
λ x hx, mem_closure_iff_nhds.2 $ λ t ht,
let ⟨ε, ε0, hε⟩ := mem_nhds_iff_metric.1 ht in
let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in
ne_empty_iff_exists_mem.2 ⟨_, hε (show abs _ < _,
by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']),
p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩
/- TODO(Mario): Put these back only if needed later
lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} :=
_
lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) :
closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} :=
_-/
lemma compact_Icc {a b : ℝ} : compact (Icc a b) :=
compact_of_totally_bounded_is_closed
(real.totally_bounded_Icc a b)
(is_closed_inter (is_closed_ge' a) (is_closed_le' b))
lemma exists_supremum_real {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) :
∃x, is_lub s x :=
⟨real.Sup s,
λ x xs, real.le_Sup s ⟨_, hb⟩ xs,
λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩
end
|
d08d6ff0a729fb2baac5130c014f6c7b52bc4479 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /06_Inductive_Types.org.29.lean | 91b9010aecd5682e3c57b73a5678c13b5ec2025c | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 641 | lean | /- page 86 -/
import standard
namespace hide
inductive nat : Type :=
| zero : nat
| succ : nat → nat
namespace nat
definition add (m n : nat) : nat :=
nat.rec_on n m (fun n add_m_n, succ add_m_n)
notation 0 := zero
infix `+` := add
theorem add_zero (m : nat) : m + 0 = m := rfl
theorem add_succ (m n : nat) : m + succ n = succ (m + n) := rfl
-- BEGIN
local abbreviation induction_on := @nat.induction_on
theorem zero_add (n : nat) : 0 + n = n :=
induction_on n
(show 0 + 0 = 0, from rfl)
(take n,
assume IH : 0 + n = n,
show 0 + succ n = succ n, from
calc
0 + succ n = succ (0 + n) : rfl
... = succ n : IH)
-- END
end nat
end hide
|
9bcc7c777835c23980dd67c491e2fbe339dbe9d1 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/category_theory/preadditive/schur.lean | 533e1234c484f0956913aded261b3f7cdded3ab6 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 8,302 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel, Scott Morrison
-/
import algebra.group.ext
import category_theory.simple
import category_theory.linear.basic
import category_theory.endomorphism
import algebra.algebra.spectrum
/-!
# Schur's lemma
We first prove the part of Schur's Lemma that holds in any preadditive category with kernels,
that any nonzero morphism between simple objects
is an isomorphism.
Second, we prove Schur's lemma for `𝕜`-linear categories with finite dimensional hom spaces,
over an algebraically closed field `𝕜`:
the hom space `X ⟶ Y` between simple objects `X` and `Y` is at most one dimensional,
and is 1-dimensional iff `X` and `Y` are isomorphic.
-/
namespace category_theory
open category_theory.limits
variables {C : Type*} [category C]
variables [preadditive C]
-- See also `epi_of_nonzero_to_simple`, which does not require `preadditive C`.
lemma mono_of_nonzero_from_simple [has_kernels C] {X Y : C} [simple X] {f : X ⟶ Y} (w : f ≠ 0) :
mono f :=
preadditive.mono_of_kernel_zero (kernel_zero_of_nonzero_from_simple w)
/--
The part of **Schur's lemma** that holds in any preadditive category with kernels:
that a nonzero morphism between simple objects is an isomorphism.
-/
lemma is_iso_of_hom_simple [has_kernels C] {X Y : C} [simple X] [simple Y] {f : X ⟶ Y} (w : f ≠ 0) :
is_iso f :=
begin
haveI := mono_of_nonzero_from_simple w,
exact is_iso_of_mono_of_nonzero w
end
/--
As a corollary of Schur's lemma for preadditive categories,
any morphism between simple objects is (exclusively) either an isomorphism or zero.
-/
lemma is_iso_iff_nonzero [has_kernels C] {X Y : C} [simple X] [simple Y] (f : X ⟶ Y) :
is_iso f ↔ f ≠ 0 :=
⟨λ I,
begin
introI h,
apply id_nonzero X,
simp only [←is_iso.hom_inv_id f, h, zero_comp],
end,
λ w, is_iso_of_hom_simple w⟩
/--
In any preadditive category with kernels,
the endomorphisms of a simple object form a division ring.
-/
noncomputable
instance [has_kernels C] {X : C} [simple X] : division_ring (End X) :=
by classical; exact
{ inv := λ f, if h : f = 0 then 0 else by { haveI := is_iso_of_hom_simple h, exact inv f, },
exists_pair_ne := ⟨𝟙 X, 0, id_nonzero _⟩,
inv_zero := dif_pos rfl,
mul_inv_cancel := λ f h, begin
haveI := is_iso_of_hom_simple h,
convert is_iso.inv_hom_id f,
exact dif_neg h,
end,
..(infer_instance : ring (End X)) }
open finite_dimensional
section
variables (𝕜 : Type*) [division_ring 𝕜]
/--
Part of **Schur's lemma** for `𝕜`-linear categories:
the hom space between two non-isomorphic simple objects is 0-dimensional.
-/
lemma finrank_hom_simple_simple_eq_zero_of_not_iso
[has_kernels C] [linear 𝕜 C] {X Y : C} [simple X] [simple Y]
(h : (X ≅ Y) → false):
finrank 𝕜 (X ⟶ Y) = 0 :=
begin
haveI := subsingleton_of_forall_eq (0 : X ⟶ Y) (λ f, begin
have p := not_congr (is_iso_iff_nonzero f),
simp only [not_not, ne.def] at p,
refine p.mp (λ _, by exactI h (as_iso f)),
end),
exact finrank_zero_of_subsingleton,
end
end
variables (𝕜 : Type*) [field 𝕜]
variables [is_alg_closed 𝕜] [linear 𝕜 C]
-- In the proof below we have some difficulty using `I : finite_dimensional 𝕜 (X ⟶ X)`
-- where we need a `finite_dimensional 𝕜 (End X)`.
-- These are definitionally equal, but without eta reduction Lean can't see this.
-- To get around this, we use `convert I`,
-- then check the various instances agree field-by-field,
/--
An auxiliary lemma for Schur's lemma.
If `X ⟶ X` is finite dimensional, and every nonzero endomorphism is invertible,
then `X ⟶ X` is 1-dimensional.
-/
-- We prove this with the explicit `is_iso_iff_nonzero` assumption,
-- rather than just `[simple X]`, as this form is useful for
-- Müger's formulation of semisimplicity.
lemma finrank_endomorphism_eq_one
{X : C} (is_iso_iff_nonzero : ∀ f : X ⟶ X, is_iso f ↔ f ≠ 0)
[I : finite_dimensional 𝕜 (X ⟶ X)] :
finrank 𝕜 (X ⟶ X) = 1 :=
begin
have id_nonzero := (is_iso_iff_nonzero (𝟙 X)).mp (by apply_instance),
refine finrank_eq_one (𝟙 X) id_nonzero _,
{ intro f,
haveI : nontrivial (End X) := nontrivial_of_ne _ _ id_nonzero,
obtain ⟨c, nu⟩ := @spectrum.nonempty_of_is_alg_closed_of_finite_dimensional 𝕜 (End X) _ _ _ _ _
(by { convert I, ext, refl, ext, refl, }) (End.of f),
use c,
rw [spectrum.mem_iff, is_unit.sub_iff, is_unit_iff_is_iso, is_iso_iff_nonzero, ne.def,
not_not, sub_eq_zero, algebra.algebra_map_eq_smul_one] at nu,
exact nu.symm, },
end
variables [has_kernels C]
/--
**Schur's lemma** for endomorphisms in `𝕜`-linear categories.
-/
lemma finrank_endomorphism_simple_eq_one
(X : C) [simple X] [I : finite_dimensional 𝕜 (X ⟶ X)] :
finrank 𝕜 (X ⟶ X) = 1 :=
finrank_endomorphism_eq_one 𝕜 is_iso_iff_nonzero
lemma endomorphism_simple_eq_smul_id
{X : C} [simple X] [I : finite_dimensional 𝕜 (X ⟶ X)] (f : X ⟶ X) :
∃ c : 𝕜, c • 𝟙 X = f :=
(finrank_eq_one_iff_of_nonzero' (𝟙 X) (id_nonzero X)).mp (finrank_endomorphism_simple_eq_one 𝕜 X) f
/--
Endomorphisms of a simple object form a field if they are finite dimensional.
This can't be an instance as `𝕜` would be undetermined.
-/
noncomputable
def field_End_of_finite_dimensional (X : C) [simple X] [I : finite_dimensional 𝕜 (X ⟶ X)] :
field (End X) :=
by classical; exact
{ mul_comm := λ f g, begin
obtain ⟨c, rfl⟩ := endomorphism_simple_eq_smul_id 𝕜 f,
obtain ⟨d, rfl⟩ := endomorphism_simple_eq_smul_id 𝕜 g,
simp [←mul_smul, mul_comm c d],
end,
..(infer_instance : division_ring (End X)) }
/--
**Schur's lemma** for `𝕜`-linear categories:
if hom spaces are finite dimensional, then the hom space between simples is at most 1-dimensional.
See `finrank_hom_simple_simple_eq_one_iff` and `finrank_hom_simple_simple_eq_zero_iff` below
for the refinements when we know whether or not the simples are isomorphic.
-/
-- There is a symmetric argument that uses `[finite_dimensional 𝕜 (Y ⟶ Y)]` instead,
-- but we don't bother proving that here.
lemma finrank_hom_simple_simple_le_one
(X Y : C) [finite_dimensional 𝕜 (X ⟶ X)] [simple X] [simple Y] :
finrank 𝕜 (X ⟶ Y) ≤ 1 :=
begin
cases subsingleton_or_nontrivial (X ⟶ Y) with h,
{ resetI,
rw finrank_zero_of_subsingleton,
exact zero_le_one },
{ obtain ⟨f, nz⟩ := (nontrivial_iff_exists_ne 0).mp h,
haveI fi := (is_iso_iff_nonzero f).mpr nz,
refine finrank_le_one f _,
intro g,
obtain ⟨c, w⟩ := endomorphism_simple_eq_smul_id 𝕜 (g ≫ inv f),
exact ⟨c, by simpa using w =≫ f⟩, },
end
lemma finrank_hom_simple_simple_eq_one_iff
(X Y : C) [finite_dimensional 𝕜 (X ⟶ X)] [finite_dimensional 𝕜 (X ⟶ Y)] [simple X] [simple Y] :
finrank 𝕜 (X ⟶ Y) = 1 ↔ nonempty (X ≅ Y) :=
begin
fsplit,
{ intro h,
rw finrank_eq_one_iff' at h,
obtain ⟨f, nz, -⟩ := h,
rw ←is_iso_iff_nonzero at nz,
exactI ⟨as_iso f⟩, },
{ rintro ⟨f⟩,
have le_one := finrank_hom_simple_simple_le_one 𝕜 X Y,
have zero_lt : 0 < finrank 𝕜 (X ⟶ Y) :=
finrank_pos_iff_exists_ne_zero.mpr ⟨f.hom, (is_iso_iff_nonzero f.hom).mp infer_instance⟩,
linarith, }
end
lemma finrank_hom_simple_simple_eq_zero_iff
(X Y : C) [finite_dimensional 𝕜 (X ⟶ X)] [finite_dimensional 𝕜 (X ⟶ Y)] [simple X] [simple Y] :
finrank 𝕜 (X ⟶ Y) = 0 ↔ is_empty (X ≅ Y) :=
begin
rw [← not_nonempty_iff, ← not_congr (finrank_hom_simple_simple_eq_one_iff 𝕜 X Y)],
refine ⟨λ h, by { rw h, simp, }, λ h, _⟩,
have := finrank_hom_simple_simple_le_one 𝕜 X Y,
interval_cases finrank 𝕜 (X ⟶ Y) with h',
{ exact h', },
{ exact false.elim (h h'), },
end
open_locale classical
lemma finrank_hom_simple_simple
(X Y : C) [∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)] [simple X] [simple Y] :
finrank 𝕜 (X ⟶ Y) = if nonempty (X ≅ Y) then 1 else 0 :=
begin
split_ifs,
exact (finrank_hom_simple_simple_eq_one_iff 𝕜 X Y).2 h,
exact (finrank_hom_simple_simple_eq_zero_iff 𝕜 X Y).2 (not_nonempty_iff.mp h),
end
end category_theory
|
d3691bdc5fa65b29fa0ebfa2984ec240cf5e6b4c | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/category/pairwise.lean | a4d82a1c13af1a5d73ce6b6e3a4bccf8236b944b | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 4,264 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.category.preorder
import category_theory.limits.is_limit
/-!
# The category of "pairwise intersections".
Given `ι : Type v`, we build the diagram category `pairwise ι`
with objects `single i` and `pair i j`, for `i j : ι`,
whose only non-identity morphisms are
`left : pair i j ⟶ single i` and `right : pair i j ⟶ single j`.
We use this later in describing (one formulation of) the sheaf condition.
Given any function `U : ι → α`, where `α` is some complete lattice (e.g. `(opens X)ᵒᵖ`),
we produce a functor `pairwise ι ⥤ α` in the obvious way,
and show that `supr U` provides a colimit cocone over this functor.
-/
noncomputable theory
universes v u
open category_theory
open category_theory.limits
namespace category_theory
/--
An inductive type representing either a single term of a type `ι`, or a pair of terms.
We use this as the objects of a category to describe the sheaf condition.
-/
inductive pairwise (ι : Type v)
| single : ι → pairwise
| pair : ι → ι → pairwise
variables {ι : Type v}
namespace pairwise
instance pairwise_inhabited [inhabited ι] : inhabited (pairwise ι) := ⟨single default⟩
/--
Morphisms in the category `pairwise ι`. The only non-identity morphisms are
`left i j : single i ⟶ pair i j` and `right i j : single j ⟶ pair i j`.
-/
inductive hom : pairwise ι → pairwise ι → Type v
| id_single : Π i, hom (single i) (single i)
| id_pair : Π i j, hom (pair i j) (pair i j)
| left : Π i j, hom (pair i j) (single i)
| right : Π i j, hom (pair i j) (single j)
open hom
instance hom_inhabited [inhabited ι] : inhabited (hom (single (default : ι)) (single default)) :=
⟨id_single default⟩
/--
The identity morphism in `pairwise ι`.
-/
def id : Π (o : pairwise ι), hom o o
| (single i) := id_single i
| (pair i j) := id_pair i j
/-- Composition of morphisms in `pairwise ι`. -/
def comp : Π {o₁ o₂ o₃ : pairwise ι} (f : hom o₁ o₂) (g : hom o₂ o₃), hom o₁ o₃
| _ _ _ (id_single i) g := g
| _ _ _ (id_pair i j) g := g
| _ _ _ (left i j) (id_single _) := left i j
| _ _ _ (right i j) (id_single _) := right i j
section
local attribute [tidy] tactic.case_bash
instance : category (pairwise ι) :=
{ hom := hom,
id := id,
comp := λ X Y Z f g, comp f g, }
end
variables {α : Type v} (U : ι → α)
section
variables [semilattice_inf α]
/-- Auxiliary definition for `diagram`. -/
@[simp]
def diagram_obj : pairwise ι → α
| (single i) := U i
| (pair i j) := U i ⊓ U j
/-- Auxiliary definition for `diagram`. -/
@[simp]
def diagram_map : Π {o₁ o₂ : pairwise ι} (f : o₁ ⟶ o₂), diagram_obj U o₁ ⟶ diagram_obj U o₂
| _ _ (id_single i) := 𝟙 _
| _ _ (id_pair i j) := 𝟙 _
| _ _ (left i j) := hom_of_le inf_le_left
| _ _ (right i j) := hom_of_le inf_le_right
/--
Given a function `U : ι → α` for `[semilattice_inf α]`, we obtain a functor `pairwise ι ⥤ α`,
sending `single i` to `U i` and `pair i j` to `U i ⊓ U j`,
and the morphisms to the obvious inequalities.
-/
@[simps]
def diagram : pairwise ι ⥤ α :=
{ obj := diagram_obj U,
map := λ X Y f, diagram_map U f, }
end
section
-- `complete_lattice` is not really needed, as we only ever use `inf`,
-- but the appropriate structure has not been defined.
variables [complete_lattice α]
/-- Auxiliary definition for `cocone`. -/
def cocone_ι_app : Π (o : pairwise ι), diagram_obj U o ⟶ supr U
| (single i) := hom_of_le (le_supr U i)
| (pair i j) := hom_of_le inf_le_left ≫ hom_of_le (le_supr U i)
/--
Given a function `U : ι → α` for `[complete_lattice α]`,
`supr U` provides a cocone over `diagram U`.
-/
@[simps]
def cocone : cocone (diagram U) :=
{ X := supr U,
ι := { app := cocone_ι_app U, } }
/--
Given a function `U : ι → α` for `[complete_lattice α]`,
`infi U` provides a limit cone over `diagram U`.
-/
def cocone_is_colimit : is_colimit (cocone U) :=
{ desc := λ s, hom_of_le
begin
apply complete_lattice.Sup_le,
rintros _ ⟨j, rfl⟩,
exact (s.ι.app (single j)).le
end }
end
end pairwise
end category_theory
|
cc81aef962973413f0d713613ad5bc7b860d7b3d | fe25de614feb5587799621c41487aaee0d083b08 | /stage0/src/Init/Core.lean | 8ab9b353f3bde92ced5a55eaa17b8ab8aff30795 | [
"Apache-2.0"
] | permissive | pollend/lean4 | e8469c2f5fb8779b773618c3267883cf21fb9fac | c913886938c4b3b83238a3f99673c6c5a9cec270 | refs/heads/master | 1,687,973,251,481 | 1,628,039,739,000 | 1,628,039,739,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 34,993 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
notation, basic datatypes and type classes
-/
prelude
import Init.Prelude
import Init.SizeOf
universe u v w
def inline {α : Sort u} (a : α) : α := a
@[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ :=
fun b a => f a b
/--
Thunks are "lazy" values that are evaluated when first accessed using `Thunk.get/map/bind`.
The value is then stored and not recomputed for all further accesses. -/
-- NOTE: the runtime has special support for the `Thunk` type to implement this behavior
structure Thunk (α : Type u) : Type u where
private fn : Unit → α
attribute [extern "lean_mk_thunk"] Thunk.mk
/-- Store a value in a thunk. Note that the value has already been computed, so there is no laziness. -/
@[extern "lean_thunk_pure"] protected def Thunk.pure (a : α) : Thunk α :=
⟨fun _ => a⟩
-- NOTE: we use `Thunk.get` instead of `Thunk.fn` as the accessor primitive as the latter has an additional `Unit` argument
@[extern "lean_thunk_get_own"] protected def Thunk.get (x : @& Thunk α) : α :=
x.fn ()
@[inline] protected def Thunk.map (f : α → β) (x : Thunk α) : Thunk β :=
⟨fun _ => f x.get⟩
@[inline] protected def Thunk.bind (x : Thunk α) (f : α → Thunk β) : Thunk β :=
⟨fun _ => (f x.get).get⟩
abbrev Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} {b : α} (h : a = b) (m : motive a) : motive b :=
Eq.ndrec m h
structure Iff (a b : Prop) : Prop where
intro :: (mp : a → b) (mpr : b → a)
infix:20 " <-> " => Iff
infix:20 " ↔ " => Iff
inductive Sum (α : Type u) (β : Type v) where
| inl (val : α) : Sum α β
| inr (val : β) : Sum α β
inductive PSum (α : Sort u) (β : Sort v) where
| inl (val : α) : PSum α β
| inr (val : β) : PSum α β
structure Sigma {α : Type u} (β : α → Type v) where
fst : α
snd : β fst
attribute [unbox] Sigma
structure PSigma {α : Sort u} (β : α → Sort v) where
fst : α
snd : β fst
inductive Exists {α : Sort u} (p : α → Prop) : Prop where
| intro (w : α) (h : p w) : Exists p
/- Auxiliary type used to compile `for x in xs` notation. -/
inductive ForInStep (α : Type u) where
| done : α → ForInStep α
| yield : α → ForInStep α
class ForIn (m : Type u₁ → Type u₂) (ρ : Type u) (α : outParam (Type v)) where
forIn {β} [Monad m] (x : ρ) (b : β) (f : α → β → m (ForInStep β)) : m β
export ForIn (forIn)
/- Auxiliary type used to compile `do` notation. -/
inductive DoResultPRBC (α β σ : Type u) where
| «pure» : α → σ → DoResultPRBC α β σ
| «return» : β → σ → DoResultPRBC α β σ
| «break» : σ → DoResultPRBC α β σ
| «continue» : σ → DoResultPRBC α β σ
/- Auxiliary type used to compile `do` notation. -/
inductive DoResultPR (α β σ : Type u) where
| «pure» : α → σ → DoResultPR α β σ
| «return» : β → σ → DoResultPR α β σ
/- Auxiliary type used to compile `do` notation. -/
inductive DoResultBC (σ : Type u) where
| «break» : σ → DoResultBC σ
| «continue» : σ → DoResultBC σ
/- Auxiliary type used to compile `do` notation. -/
inductive DoResultSBC (α σ : Type u) where
| «pureReturn» : α → σ → DoResultSBC α σ
| «break» : σ → DoResultSBC α σ
| «continue» : σ → DoResultSBC α σ
class HasEquiv (α : Sort u) where
Equiv : α → α → Sort v
infix:50 " ≈ " => HasEquiv.Equiv
class EmptyCollection (α : Type u) where
emptyCollection : α
notation "{" "}" => EmptyCollection.emptyCollection
notation "∅" => EmptyCollection.emptyCollection
/- Remark: tasks have an efficient implementation in the runtime. -/
structure Task (α : Type u) : Type u where
pure :: (get : α)
deriving Inhabited
attribute [extern "lean_task_pure"] Task.pure
attribute [extern "lean_task_get_own"] Task.get
namespace Task
/-- Task priority. Tasks with higher priority will always be scheduled before ones with lower priority. -/
abbrev Priority := Nat
def Priority.default : Priority := 0
-- see `LEAN_MAX_PRIO`
def Priority.max : Priority := 8
/--
Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread.
This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more
non-dedicated workers than the number of cores to reduce context switches. -/
def Priority.dedicated : Priority := 9
@[noinline, extern "lean_task_spawn"]
protected def spawn {α : Type u} (fn : Unit → α) (prio := Priority.default) : Task α :=
⟨fn ()⟩
@[noinline, extern "lean_task_map"]
protected def map {α : Type u} {β : Type v} (f : α → β) (x : Task α) (prio := Priority.default) : Task β :=
⟨f x.get⟩
@[noinline, extern "lean_task_bind"]
protected def bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) (prio := Priority.default) : Task β :=
⟨(f x.get).get⟩
end Task
/- Some type that is not a scalar value in our runtime. -/
structure NonScalar where
val : Nat
/- Some type that is not a scalar value in our runtime and is universe polymorphic. -/
inductive PNonScalar : Type u where
| mk (v : Nat) : PNonScalar
theorem natAddZero (n : Nat) : n + 0 = n := rfl
theorem optParamEq (α : Sort u) (default : α) : optParam α default = α := rfl
/- Boolean operators -/
@[extern c inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂
@[extern c inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂
@[inline] def bne {α : Type u} [BEq α] (a b : α) : Bool :=
!(a == b)
infix:50 " != " => bne
/- Logical connectives an equality -/
def implies (a b : Prop) := a → b
theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r :=
fun hp => h₂ (h₁ hp)
def trivial : True := ⟨⟩
theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a :=
fun ha => h₂ (h₁ ha)
theorem notFalse : ¬False := id
-- proof irrelevance is built in
theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl
theorem id.def {α : Sort u} (a : α) : id a = a := rfl
@[macroInline] def Eq.mp {α β : Sort u} (h : α = β) (a : α) : β :=
h ▸ a
@[macroInline] def Eq.mpr {α β : Sort u} (h : α = β) (b : β) : α :=
h ▸ b
theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b :=
h₁ ▸ h₂
theorem castEq {α : Sort u} (h : α = α) (a : α) : cast h a = a :=
rfl
@[reducible] def Ne {α : Sort u} (a b : α) :=
¬(a = b)
infix:50 " ≠ " => Ne
section Ne
variable {α : Sort u}
variable {a b : α} {p : Prop}
theorem Ne.intro (h : a = b → False) : a ≠ b := h
theorem Ne.elim (h : a ≠ b) : a = b → False := h
theorem Ne.irrefl (h : a ≠ a) : False := h rfl
theorem Ne.symm (h : a ≠ b) : b ≠ a :=
fun h₁ => h (h₁.symm)
theorem falseOfNe : a ≠ a → False := Ne.irrefl
theorem neFalseOfSelf : p → p ≠ False :=
fun (hp : p) (h : p = False) => h ▸ hp
theorem neTrueOfNot : ¬p → p ≠ True :=
fun (hnp : ¬p) (h : p = True) =>
have : ¬True := h ▸ hnp
this trivial
theorem trueNeFalse : ¬True = False :=
neFalseOfSelf trivial
end Ne
section
variable {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ}
theorem HEq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} (m : motive a) {β : Sort u2} {b : β} (h : a ≅ b) : motive b :=
@HEq.rec α a (fun b _ => motive b) m β b h
theorem HEq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} {β : Sort u2} {b : β} (h : a ≅ b) (m : motive a) : motive b :=
@HEq.rec α a (fun b _ => motive b) m β b h
theorem HEq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a ≅ b) (h₂ : p a) : p b :=
eqOfHEq h₁ ▸ h₂
theorem HEq.subst {p : (T : Sort u) → T → Prop} (h₁ : a ≅ b) (h₂ : p α a) : p β b :=
HEq.ndrecOn h₁ h₂
theorem HEq.symm (h : a ≅ b) : b ≅ a :=
HEq.ndrecOn (motive := fun x => x ≅ a) h (HEq.refl a)
theorem heqOfEq (h : a = a') : a ≅ a' :=
Eq.subst h (HEq.refl a)
theorem HEq.trans (h₁ : a ≅ b) (h₂ : b ≅ c) : a ≅ c :=
HEq.subst h₂ h₁
theorem heqOfHEqOfEq (h₁ : a ≅ b) (h₂ : b = b') : a ≅ b' :=
HEq.trans h₁ (heqOfEq h₂)
theorem heqOfEqOfHEq (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b :=
HEq.trans (heqOfEq h₁) h₂
def typeEqOfHEq (h : a ≅ b) : α = β :=
HEq.ndrecOn (motive := @fun (x : Sort u) _ => α = x) h (Eq.refl α)
end
theorem eqRecHEq {α : Sort u} {φ : α → Sort v} {a a' : α} : (h : a = a') → (p : φ a) → (Eq.recOn (motive := fun x _ => φ x) h p) ≅ p
| rfl, p => HEq.refl p
theorem heqOfEqRecEq {α β : Sort u} {a : α} {b : β} (h₁ : α = β) (h₂ : Eq.rec (motive := fun α _ => α) a h₁ = b) : a ≅ b := by
subst h₁
apply heqOfEq
exact h₂
theorem castHEq {α β : Sort u} : (h : α = β) → (a : α) → cast h a ≅ a
| rfl, a => HEq.refl a
variable {a b c d : Prop}
theorem iffIffImpliesAndImplies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) :=
Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right)
theorem Iff.refl (a : Prop) : a ↔ a :=
Iff.intro (fun h => h) (fun h => h)
theorem Iff.rfl {a : Prop} : a ↔ a :=
Iff.refl a
theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c :=
Iff.intro
(fun ha => Iff.mp h₂ (Iff.mp h₁ ha))
(fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc))
theorem Iff.symm (h : a ↔ b) : b ↔ a :=
Iff.intro (Iff.mpr h) (Iff.mp h)
theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) :=
Iff.intro Iff.symm Iff.symm
/- Exists -/
theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop}
(h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b :=
h₂ h₁.1 h₁.2
/- Decidable -/
theorem decideTrueEqTrue (h : Decidable True) : @decide True h = true :=
match h with
| isTrue h => rfl
| isFalse h => False.elim <| h ⟨⟩
theorem decideFalseEqFalse (h : Decidable False) : @decide False h = false :=
match h with
| isFalse h => rfl
| isTrue h => False.elim h
/-- Similar to `decide`, but uses an explicit instance -/
@[inline] def toBoolUsing {p : Prop} (d : Decidable p) : Bool :=
decide p (h := d)
theorem toBoolUsingEqTrue {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true :=
decideEqTrue (s := d) h
theorem ofBoolUsingEqTrue {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p :=
ofDecideEqTrue (s := d) h
theorem ofBoolUsingEqFalse {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p :=
ofDecideEqFalse (s := d) h
instance : Decidable True :=
isTrue trivial
instance : Decidable False :=
isFalse notFalse
namespace Decidable
variable {p q : Prop}
@[macroInline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q :=
match dec with
| isTrue h => h1 h
| isFalse h => h2 h
theorem em (p : Prop) [Decidable p] : p ∨ ¬p :=
byCases Or.inl Or.inr
theorem byContradiction [dec : Decidable p] (h : ¬p → False) : p :=
byCases id (fun np => False.elim (h np))
theorem ofNotNot [Decidable p] : ¬ ¬ p → p :=
fun hnn => byContradiction (fun hn => absurd hn hnn)
theorem notAndIffOrNot (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q :=
Iff.intro
(fun h => match d₁, d₂ with
| isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h
| _, isFalse h₂ => Or.inr h₂
| isFalse h₁, _ => Or.inl h₁)
(fun (h) ⟨hp, hq⟩ => match h with
| Or.inl h => h hp
| Or.inr h => h hq)
end Decidable
section
variable {p q : Prop}
@[inline] def decidableOfDecidableOfIff (hp : Decidable p) (h : p ↔ q) : Decidable q :=
if hp : p then
isTrue (Iff.mp h hp)
else
isFalse fun hq => absurd (Iff.mpr h hq) hp
@[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q :=
h ▸ hp
end
@[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p → q) :=
if hp : p then
if hq : q then isTrue (fun h => hq)
else isFalse (fun h => absurd (h hp) hq)
else isTrue (fun h => absurd h hp)
instance {p q} [Decidable p] [Decidable q] : Decidable (p ↔ q) :=
if hp : p then
if hq : q then
isTrue ⟨fun _ => hq, fun _ => hp⟩
else
isFalse fun h => hq (h.1 hp)
else
if hq : q then
isFalse fun h => hp (h.2 hq)
else
isTrue ⟨fun h => absurd h hp, fun h => absurd h hq⟩
/- if-then-else expression theorems -/
theorem ifPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t :=
match h with
| isTrue hc => rfl
| isFalse hnc => absurd hc hnc
theorem ifNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e :=
match h with
| isTrue hc => absurd hc hnc
| isFalse hnc => rfl
theorem difPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = t hc :=
match h with
| isTrue hc => rfl
| isFalse hnc => absurd hc hnc
theorem difNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = e hnc :=
match h with
| isTrue hc => absurd hc hnc
| isFalse hnc => rfl
-- Remark: dite and ite are "defally equal" when we ignore the proofs.
theorem difEqIf (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : dite c (fun h => t) (fun h => e) = ite c t e :=
match h with
| isTrue hc => rfl
| isFalse hnc => rfl
instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) :=
match dC with
| isTrue hc => dT
| isFalse hc => dE
instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) :=
match dC with
| isTrue hc => dT hc
| isFalse hc => dE hc
/- Inhabited -/
instance : Inhabited Prop where
default := True
deriving instance Inhabited for NonScalar, PNonScalar, True, ForInStep
class inductive Nonempty (α : Sort u) : Prop where
| intro (val : α) : Nonempty α
protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p :=
h₂ h₁.1
instance {α : Sort u} [Inhabited α] : Nonempty α :=
⟨arbitrary⟩
theorem nonemptyOfExists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α
| ⟨w, h⟩ => ⟨w⟩
/- Subsingleton -/
class Subsingleton (α : Sort u) : Prop where
intro :: allEq : (a b : α) → a = b
protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : (a b : α) → a = b :=
h.allEq
protected def Subsingleton.helim {α β : Sort u} [h₁ : Subsingleton α] (h₂ : α = β) (a : α) (b : β) : a ≅ b := by
subst h₂
apply heqOfEq
apply Subsingleton.elim
instance (p : Prop) : Subsingleton p :=
⟨fun a b => proofIrrel a b⟩
instance (p : Prop) : Subsingleton (Decidable p) :=
Subsingleton.intro fun
| isTrue t₁ => fun
| isTrue t₂ => rfl
| isFalse f₂ => absurd t₁ f₂
| isFalse f₁ => fun
| isTrue t₂ => absurd t₂ f₁
| isFalse f₂ => rfl
theorem recSubsingleton
{p : Prop} [h : Decidable p]
{h₁ : p → Sort u}
{h₂ : ¬p → Sort u}
[h₃ : ∀ (h : p), Subsingleton (h₁ h)]
[h₄ : ∀ (h : ¬p), Subsingleton (h₂ h)]
: Subsingleton (Decidable.casesOn (motive := fun _ => Sort u) h h₂ h₁) :=
match h with
| isTrue h => h₃ h
| isFalse h => h₄ h
structure Equivalence {α : Sort u} (r : α → α → Prop) : Prop where
refl : ∀ x, r x x
symm : ∀ {x y}, r x y → r y x
trans : ∀ {x y z}, r x y → r y z → r x z
def emptyRelation {α : Sort u} (a₁ a₂ : α) : Prop :=
False
def Subrelation {α : Sort u} (q r : α → α → Prop) :=
∀ {x y}, q x y → r x y
def InvImage {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) : α → α → Prop :=
fun a₁ a₂ => r (f a₁) (f a₂)
inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop where
| base : ∀ a b, r a b → TC r a b
| trans : ∀ a b c, TC r a b → TC r b c → TC r a c
/- Subtype -/
namespace Subtype
def existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x)
| ⟨a, h⟩ => ⟨a, h⟩
variable {α : Type u} {p : α → Prop}
protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2
| ⟨x, h1⟩, ⟨_, _⟩, rfl => rfl
theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a := by
cases a
exact rfl
instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} where
default := ⟨a, h⟩
instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} :=
fun ⟨a, h₁⟩ ⟨b, h₂⟩ =>
if h : a = b then isTrue (by subst h; exact rfl)
else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h))
end Subtype
/- Sum -/
section
variable {α : Type u} {β : Type v}
instance Sum.inhabitedLeft [h : Inhabited α] : Inhabited (Sum α β) where
default := Sum.inl arbitrary
instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (Sum α β) where
default := Sum.inr arbitrary
instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (Sum α β) := fun a b =>
match a, b with
| Sum.inl a, Sum.inl b =>
if h : a = b then isTrue (h ▸ rfl)
else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h
| Sum.inr a, Sum.inr b =>
if h : a = b then isTrue (h ▸ rfl)
else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h
| Sum.inr a, Sum.inl b => isFalse fun h => Sum.noConfusion h
| Sum.inl a, Sum.inr b => isFalse fun h => Sum.noConfusion h
end
/- Product -/
instance [Inhabited α] [Inhabited β] : Inhabited (α × β) where
default := (arbitrary, arbitrary)
instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) :=
fun (a, b) (a', b') =>
match decEq a a' with
| isTrue e₁ =>
match decEq b b' with
| isTrue e₂ => isTrue (e₁ ▸ e₂ ▸ rfl)
| isFalse n₂ => isFalse fun h => Prod.noConfusion h fun e₁' e₂' => absurd e₂' n₂
| isFalse n₁ => isFalse fun h => Prod.noConfusion h fun e₁' e₂' => absurd e₁' n₁
instance [BEq α] [BEq β] : BEq (α × β) where
beq := fun (a₁, b₁) (a₂, b₂) => a₁ == a₂ && b₁ == b₂
instance [LT α] [LT β] : LT (α × β) where
lt s t := s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)
instance prodHasDecidableLt
[LT α] [LT β] [DecidableEq α] [DecidableEq β]
[(a b : α) → Decidable (a < b)] [(a b : β) → Decidable (a < b)]
: (s t : α × β) → Decidable (s < t) :=
fun t s => inferInstanceAs (Decidable (_ ∨ _))
theorem Prod.ltDef [LT α] [LT β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) :=
rfl
theorem Prod.ext (p : α × β) : (p.1, p.2) = p := by
cases p; rfl
def Prod.map {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂}
(f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂
| (a, b) => (f a, g b)
/- Dependent products -/
theorem exOfPsig {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x)
| ⟨x, hx⟩ => ⟨x, hx⟩
protected theorem PSigma.eta {α : Sort u} {β : α → Sort v} {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂}
(h₁ : a₁ = a₂) (h₂ : Eq.ndrec b₁ h₁ = b₂) : PSigma.mk a₁ b₁ = PSigma.mk a₂ b₂ := by
subst h₁
subst h₂
exact rfl
/- Universe polymorphic unit -/
theorem PUnit.subsingleton (a b : PUnit) : a = b := by
cases a; cases b; exact rfl
@[simp] theorem PUnit.eq_punit (a : PUnit) : a = ⟨⟩ :=
PUnit.subsingleton a ⟨⟩
instance : Subsingleton PUnit :=
Subsingleton.intro PUnit.subsingleton
instance : Inhabited PUnit where
default := ⟨⟩
instance : DecidableEq PUnit :=
fun a b => isTrue (PUnit.subsingleton a b)
/- Setoid -/
class Setoid (α : Sort u) where
r : α → α → Prop
iseqv {} : Equivalence r
instance {α : Sort u} [Setoid α] : HasEquiv α :=
⟨Setoid.r⟩
namespace Setoid
variable {α : Sort u} [Setoid α]
theorem refl (a : α) : a ≈ a :=
(Setoid.iseqv α).refl a
theorem symm {a b : α} (hab : a ≈ b) : b ≈ a :=
(Setoid.iseqv α).symm hab
theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c :=
(Setoid.iseqv α).trans hab hbc
end Setoid
/- Propositional extensionality -/
axiom propext {a b : Prop} : (a ↔ b) → a = b
theorem Eq.propIntro {a b : Prop} (h₁ : a → b) (h₂ : b → a) : a = b :=
propext <| Iff.intro h₁ h₂
gen_injective_theorems% Prod
gen_injective_theorems% PProd
gen_injective_theorems% MProd
gen_injective_theorems% Subtype
gen_injective_theorems% Fin
gen_injective_theorems% Array
gen_injective_theorems% Sum
gen_injective_theorems% PSum
gen_injective_theorems% Nat
gen_injective_theorems% Option
gen_injective_theorems% List
gen_injective_theorems% Except
gen_injective_theorems% EStateM.Result
gen_injective_theorems% Lean.Name
gen_injective_theorems% Lean.Syntax
/- Quotients -/
-- Iff can now be used to do substitutions in a calculation
theorem iffSubst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b :=
Eq.subst (propext h₁) h₂
namespace Quot
axiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b
protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v}
(f : α → β)
(c : (a b : α) → r a b → f a = f b)
(a : α)
: lift f c (Quot.mk r a) = f a :=
rfl
protected theorem indBeta {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop}
(p : (a : α) → motive (Quot.mk r a))
(a : α)
: (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a :=
rfl
protected abbrev liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : (a b : α) → r a b → f a = f b) : β :=
lift f c q
protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop}
(q : Quot r)
(h : (a : α) → motive (Quot.mk r a))
: motive q :=
ind h q
theorem existsRep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) :=
Quot.inductionOn (motive := fun q => Exists (fun a => (Quot.mk r a) = q)) q (fun a => ⟨a, rfl⟩)
section
variable {α : Sort u}
variable {r : α → α → Prop}
variable {motive : Quot r → Sort v}
@[reducible, macroInline]
protected def indep (f : (a : α) → motive (Quot.mk r a)) (a : α) : PSigma motive :=
⟨Quot.mk r a, f a⟩
protected theorem indepCoherent
(f : (a : α) → motive (Quot.mk r a))
(h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b)
: (a b : α) → r a b → Quot.indep f a = Quot.indep f b :=
fun a b e => PSigma.eta (sound e) (h a b e)
protected theorem liftIndepPr1
(f : (a : α) → motive (Quot.mk r a))
(h : ∀ (a b : α) (p : r a b), Eq.ndrec (f a) (sound p) = f b)
(q : Quot r)
: (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q := by
induction q using Quot.ind
exact rfl
protected abbrev rec
(f : (a : α) → motive (Quot.mk r a))
(h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b)
(q : Quot r) : motive q :=
Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2)
protected abbrev recOn
(q : Quot r)
(f : (a : α) → motive (Quot.mk r a))
(h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b)
: motive q :=
Quot.rec f h q
protected abbrev recOnSubsingleton
[h : (a : α) → Subsingleton (motive (Quot.mk r a))]
(q : Quot r)
(f : (a : α) → motive (Quot.mk r a))
: motive q := by
induction q using Quot.rec
apply f
apply Subsingleton.elim
protected abbrev hrecOn
(q : Quot r)
(f : (a : α) → motive (Quot.mk r a))
(c : (a b : α) → (p : r a b) → f a ≅ f b)
: motive q :=
Quot.recOn q f fun a b p => eqOfHEq <|
have p₁ : Eq.ndrec (f a) (sound p) ≅ f a := eqRecHEq (sound p) (f a)
HEq.trans p₁ (c a b p)
end
end Quot
def Quotient {α : Sort u} (s : Setoid α) :=
@Quot α Setoid.r
namespace Quotient
@[inline]
protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s :=
Quot.mk Setoid.r a
def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → Quotient.mk a = Quotient.mk b :=
Quot.sound
protected abbrev lift {α : Sort u} {β : Sort v} [s : Setoid α] (f : α → β) : ((a b : α) → a ≈ b → f a = f b) → Quotient s → β :=
Quot.lift f
protected theorem ind {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} : ((a : α) → motive (Quotient.mk a)) → (q : Quot Setoid.r) → motive q :=
Quot.ind
protected abbrev liftOn {α : Sort u} {β : Sort v} [s : Setoid α] (q : Quotient s) (f : α → β) (c : (a b : α) → a ≈ b → f a = f b) : β :=
Quot.liftOn q f c
protected theorem inductionOn {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop}
(q : Quotient s)
(h : (a : α) → motive (Quotient.mk a))
: motive q :=
Quot.inductionOn q h
theorem existsRep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (fun (a : α) => Quotient.mk a = q) :=
Quot.existsRep q
section
variable {α : Sort u}
variable [s : Setoid α]
variable {motive : Quotient s → Sort v}
@[inline]
protected def rec
(f : (a : α) → motive (Quotient.mk a))
(h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b)
(q : Quotient s)
: motive q :=
Quot.rec f h q
protected abbrev recOn
(q : Quotient s)
(f : (a : α) → motive (Quotient.mk a))
(h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b)
: motive q :=
Quot.recOn q f h
protected abbrev recOnSubsingleton
[h : (a : α) → Subsingleton (motive (Quotient.mk a))]
(q : Quotient s)
(f : (a : α) → motive (Quotient.mk a))
: motive q :=
Quot.recOnSubsingleton (h := h) q f
protected abbrev hrecOn
(q : Quotient s)
(f : (a : α) → motive (Quotient.mk a))
(c : (a b : α) → (p : a ≈ b) → f a ≅ f b)
: motive q :=
Quot.hrecOn q f c
end
section
universe uA uB uC
variable {α : Sort uA} {β : Sort uB} {φ : Sort uC}
variable [s₁ : Setoid α] [s₂ : Setoid β]
protected abbrev lift₂
(f : α → β → φ)
(c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂)
(q₁ : Quotient s₁) (q₂ : Quotient s₂)
: φ := by
apply Quotient.lift (fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂) _ q₁
intros
induction q₂ using Quotient.ind
apply c; assumption; apply Setoid.refl
protected abbrev liftOn₂
(q₁ : Quotient s₁)
(q₂ : Quotient s₂)
(f : α → β → φ)
(c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂)
: φ :=
Quotient.lift₂ f c q₁ q₂
protected theorem ind₂
{motive : Quotient s₁ → Quotient s₂ → Prop}
(h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b))
(q₁ : Quotient s₁)
(q₂ : Quotient s₂)
: motive q₁ q₂ := by
induction q₁ using Quotient.ind
induction q₂ using Quotient.ind
apply h
protected theorem inductionOn₂
{motive : Quotient s₁ → Quotient s₂ → Prop}
(q₁ : Quotient s₁)
(q₂ : Quotient s₂)
(h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b))
: motive q₁ q₂ := by
induction q₁ using Quotient.ind
induction q₂ using Quotient.ind
apply h
protected theorem inductionOn₃
[s₃ : Setoid φ]
{motive : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop}
(q₁ : Quotient s₁)
(q₂ : Quotient s₂)
(q₃ : Quotient s₃)
(h : (a : α) → (b : β) → (c : φ) → motive (Quotient.mk a) (Quotient.mk b) (Quotient.mk c))
: motive q₁ q₂ q₃ := by
induction q₁ using Quotient.ind
induction q₂ using Quotient.ind
induction q₃ using Quotient.ind
apply h
end
section Exact
variable {α : Sort u}
private def rel [s : Setoid α] (q₁ q₂ : Quotient s) : Prop :=
Quotient.liftOn₂ q₁ q₂
(fun a₁ a₂ => a₁ ≈ a₂)
(fun a₁ a₂ b₁ b₂ a₁b₁ a₂b₂ =>
propext (Iff.intro
(fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂))
(fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂)))))
private theorem rel.refl [s : Setoid α] (q : Quotient s) : rel q q :=
Quot.inductionOn (motive := fun q => rel q q) q (fun a => Setoid.refl a)
private theorem eqImpRel [s : Setoid α] {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ :=
fun h => Eq.ndrecOn h (rel.refl q₁)
theorem exact [s : Setoid α] {a b : α} : Quotient.mk a = Quotient.mk b → a ≈ b :=
fun h => eqImpRel h
end Exact
section
universe uA uB uC
variable {α : Sort uA} {β : Sort uB}
variable [s₁ : Setoid α] [s₂ : Setoid β]
protected abbrev recOnSubsingleton₂
{motive : Quotient s₁ → Quotient s₂ → Sort uC}
[s : (a : α) → (b : β) → Subsingleton (motive (Quotient.mk a) (Quotient.mk b))]
(q₁ : Quotient s₁)
(q₂ : Quotient s₂)
(g : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b))
: motive q₁ q₂ := by
induction q₁ using Quot.recOnSubsingleton
induction q₂ using Quot.recOnSubsingleton
apply g
intro a; apply s
induction q₂ using Quot.recOnSubsingleton
intro a; apply s
inferInstance
end
end Quotient
section
variable {α : Type u}
variable (r : α → α → Prop)
instance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) :=
fun (q₁ q₂ : Quotient s) =>
Quotient.recOnSubsingleton₂ (motive := fun a b => Decidable (a = b)) q₁ q₂
fun a₁ a₂ =>
match d a₁ a₂ with
| isTrue h₁ => isTrue (Quotient.sound h₁)
| isFalse h₂ => isFalse fun h => absurd (Quotient.exact h) h₂
/- Function extensionality -/
namespace Function
variable {α : Sort u} {β : α → Sort v}
protected def Equiv (f₁ f₂ : ∀ (x : α), β x) : Prop := ∀ x, f₁ x = f₂ x
protected theorem Equiv.refl (f : ∀ (x : α), β x) : Function.Equiv f f :=
fun x => rfl
protected theorem Equiv.symm {f₁ f₂ : ∀ (x : α), β x} : Function.Equiv f₁ f₂ → Function.Equiv f₂ f₁ :=
fun h x => Eq.symm (h x)
protected theorem Equiv.trans {f₁ f₂ f₃ : ∀ (x : α), β x} : Function.Equiv f₁ f₂ → Function.Equiv f₂ f₃ → Function.Equiv f₁ f₃ :=
fun h₁ h₂ x => Eq.trans (h₁ x) (h₂ x)
protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) := {
refl := Equiv.refl
symm := Equiv.symm
trans := Equiv.trans
}
end Function
section
open Quotient
variable {α : Sort u} {β : α → Sort v}
@[instance]
private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (∀ (x : α), β x) :=
Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β)
private def extfunApp (f : Quotient <| funSetoid α β) (x : α) : β x :=
Quot.liftOn f
(fun (f : ∀ (x : α), β x) => f x)
(fun f₁ f₂ h => h x)
theorem funext {f₁ f₂ : ∀ (x : α), β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by
show extfunApp (Quotient.mk f₁) = extfunApp (Quotient.mk f₂)
apply congrArg
apply Quotient.sound
exact h
end
instance {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) where
allEq f₁ f₂ :=
funext (fun a => Subsingleton.elim (f₁ a) (f₂ a))
/- Squash -/
def Squash (α : Type u) := Quot (fun (a b : α) => True)
def Squash.mk {α : Type u} (x : α) : Squash α := Quot.mk _ x
theorem Squash.ind {α : Type u} {motive : Squash α → Prop} (h : ∀ (a : α), motive (Squash.mk a)) : ∀ (q : Squash α), motive q :=
Quot.ind h
@[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β :=
Quot.lift f (fun a b _ => Subsingleton.elim _ _) s
instance : Subsingleton (Squash α) where
allEq a b := by
induction a using Squash.ind
induction b using Squash.ind
apply Quot.sound
trivial
namespace Lean
/- Kernel reduction hints -/
/--
When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`.
The kernel will not use the interpreter if `c` is not a constant.
This feature is useful for performing proofs by reflection.
Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing
free variables. The frontend automatically declares a fresh auxiliary constant `c` and replaces the term with
`Lean.reduceBool c`. The main motivation is that the code for `t` will be pre-compiled.
Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base.
This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using
external type checkers (e.g., Trepplein) that do not implement this feature.
Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter.
So, you are mainly losing the capability of type checking your developement using external checkers.
Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations.
If an extern function is executed, then the trusted code base will also include the implementation of the associated
foreign function.
-/
constant reduceBool (b : Bool) : Bool := b
/--
Similar to `Lean.reduceBool` for closed `Nat` terms.
Remark: we do not have plans for supporting a generic `reduceValue {α} (a : α) : α := a`.
The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression.
We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/
constant reduceNat (n : Nat) : Nat := n
axiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b
axiom ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b
end Lean
|
a65da842576fe3d9a358c3b9767e12206a55f91a | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /src/Lean/Elab/Util.lean | 5f2db9d1901e0f5d9dda92f1024a4aff2f23dce0 | [
"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 | 7,371 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.Trace
import Lean.Parser.Syntax
import Lean.Parser.Extension
import Lean.KeyedDeclsAttribute
import Lean.Elab.Exception
namespace Lean
def Syntax.prettyPrint (stx : Syntax) : Format :=
match stx.unsetTrailing.reprint with -- TODO use syntax pretty printer
| some str => format str.toFormat
| none => format stx
def MacroScopesView.format (view : MacroScopesView) (mainModule : Name) : Format :=
fmt $
if view.scopes.isEmpty then
view.name
else if view.mainModule == mainModule then
view.scopes.foldl Name.mkNum (view.name ++ view.imported)
else
view.scopes.foldl Name.mkNum (view.name ++ view.imported ++ view.mainModule)
namespace Elab
def expandOptNamedPrio (stx : Syntax) : MacroM Nat :=
if stx.isNone then
return eval_prio default
else match stx[0] with
| `(Parser.Command.namedPrio| (priority := $prio)) => evalPrio prio
| _ => Macro.throwUnsupported
def expandOptNamedName (stx : Syntax) : MacroM (Option Name) := do
if stx.isNone then
return none
else match stx[0] with
| `(Parser.Command.namedName| (name := $name)) => return name.getId
| _ => Macro.throwUnsupported
structure MacroStackElem where
before : Syntax
after : Syntax
abbrev MacroStack := List MacroStackElem
/- If `ref` does not have position information, then try to use macroStack -/
def getBetterRef (ref : Syntax) (macroStack : MacroStack) : Syntax :=
match ref.getPos? with
| some _ => ref
| none =>
match macroStack.find? (·.before.getPos? != none) with
| some elem => elem.before
| none => ref
register_builtin_option pp.macroStack : Bool := {
defValue := false
group := "pp"
descr := "dispaly macro expansion stack"
}
def addMacroStack {m} [Monad m] [MonadOptions m] (msgData : MessageData) (macroStack : MacroStack) : m MessageData := do
if !pp.macroStack.get (← getOptions) then pure msgData else
match macroStack with
| [] => pure msgData
| stack@(top::_) =>
let msgData := msgData ++ Format.line ++ "with resulting expansion" ++ indentD top.after
pure $ stack.foldl
(fun (msgData : MessageData) (elem : MacroStackElem) =>
msgData ++ Format.line ++ "while expanding" ++ indentD elem.before)
msgData
def checkSyntaxNodeKind (k : Name) : AttrM Name := do
if Parser.isValidSyntaxNodeKind (← getEnv) k then pure k
else throwError "failed"
def checkSyntaxNodeKindAtNamespacesAux (k : Name) : Name → AttrM Name
| n@(Name.str p _ _) => checkSyntaxNodeKind (n ++ k) <|> checkSyntaxNodeKindAtNamespacesAux k p
| _ => throwError "failed"
def checkSyntaxNodeKindAtNamespaces (k : Name) : AttrM Name := do
let ctx ← read
checkSyntaxNodeKindAtNamespacesAux k ctx.currNamespace
def syntaxNodeKindOfAttrParam (defaultParserNamespace : Name) (stx : Syntax) : AttrM SyntaxNodeKind := do
let k ← Attribute.Builtin.getId stx
checkSyntaxNodeKind k
<|>
checkSyntaxNodeKindAtNamespaces k
<|>
checkSyntaxNodeKind (defaultParserNamespace ++ k)
<|>
throwError "invalid syntax node kind '{k}'"
private unsafe def evalSyntaxConstantUnsafe (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax :=
env.evalConstCheck Syntax opts `Lean.Syntax constName
@[implementedBy evalSyntaxConstantUnsafe]
constant evalSyntaxConstant (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax := throw ""
unsafe def mkElabAttribute (γ) (attrDeclName attrBuiltinName attrName : Name) (parserNamespace : Name) (typeName : Name) (kind : String)
: IO (KeyedDeclsAttribute γ) :=
KeyedDeclsAttribute.init {
builtinName := attrBuiltinName
name := attrName
descr := kind ++ " elaborator"
valueTypeName := typeName
evalKey := fun _ stx => syntaxNodeKindOfAttrParam parserNamespace stx
} attrDeclName
unsafe def mkMacroAttributeUnsafe : IO (KeyedDeclsAttribute Macro) :=
mkElabAttribute Macro `Lean.Elab.macroAttribute `builtinMacro `macro Name.anonymous `Lean.Macro "macro"
@[implementedBy mkMacroAttributeUnsafe]
constant mkMacroAttribute : IO (KeyedDeclsAttribute Macro)
builtin_initialize macroAttribute : KeyedDeclsAttribute Macro ← mkMacroAttribute
private def expandMacroFns (stx : Syntax) : List Macro → MacroM Syntax
| [] => throw Macro.Exception.unsupportedSyntax
| m::ms => do
try
m stx
catch
| Macro.Exception.unsupportedSyntax => expandMacroFns stx ms
| ex => throw ex
def getMacros (env : Environment) : Macro := fun stx =>
let k := stx.getKind
let table := (macroAttribute.ext.getState env).table
match table.find? k with
| some macroFns => expandMacroFns stx macroFns
| none => throw Macro.Exception.unsupportedSyntax
class MonadMacroAdapter (m : Type → Type) where
getCurrMacroScope : m MacroScope
getNextMacroScope : m MacroScope
setNextMacroScope : MacroScope → m Unit
instance (m n) [MonadLift m n] [MonadMacroAdapter m] : MonadMacroAdapter n := {
getCurrMacroScope := liftM (MonadMacroAdapter.getCurrMacroScope : m _),
getNextMacroScope := liftM (MonadMacroAdapter.getNextMacroScope : m _),
setNextMacroScope := fun s => liftM (MonadMacroAdapter.setNextMacroScope s : m _)
}
private def expandMacro? (env : Environment) (stx : Syntax) : MacroM (Option Syntax) := do
try
let newStx ← getMacros env stx
pure (some newStx)
catch
| Macro.Exception.unsupportedSyntax => pure none
| ex => throw ex
@[inline] def liftMacroM {α} {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] (x : MacroM α) : m α := do
let env ← getEnv
match x { macroEnv := Macro.mkMacroEnv (expandMacro? env),
ref := ← getRef,
currMacroScope := ← MonadMacroAdapter.getCurrMacroScope,
mainModule := env.mainModule,
currRecDepth := ← MonadRecDepth.getRecDepth,
maxRecDepth := ← MonadRecDepth.getMaxRecDepth } (← MonadMacroAdapter.getNextMacroScope) with
| EStateM.Result.error Macro.Exception.unsupportedSyntax _ => throwUnsupportedSyntax
| EStateM.Result.error (Macro.Exception.error ref msg) _ => throwErrorAt ref msg
| EStateM.Result.ok a nextMacroScope => MonadMacroAdapter.setNextMacroScope nextMacroScope; pure a
@[inline] def adaptMacro {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] (x : Macro) (stx : Syntax) : m Syntax :=
liftMacroM (x stx)
partial def mkUnusedBaseName [Monad m] [MonadEnv m] [MonadResolveName m] (baseName : Name) : m Name := do
let currNamespace ← getCurrNamespace
let env ← getEnv
if env.contains (currNamespace ++ baseName) then
let rec loop (idx : Nat) :=
let name := baseName.appendIndexAfter idx
if env.contains (currNamespace ++ name) then
loop (idx+1)
else
name
return loop 1
else
return baseName
builtin_initialize
registerTraceClass `Elab
registerTraceClass `Elab.step
end Lean.Elab
|
0f9c6528748b7a68662d92b0892793e4bc2377a6 | 556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e | /src/starkware/cairo/lean/semantics/air_encoding/instruction.lean | 975e6191590b09cfa4223707f9b3da3371501984 | [
"Apache-2.0"
] | permissive | starkware-libs/formal-proofs | d6b731604461bf99e6ba820e68acca62a21709e8 | f5fa4ba6a471357fd171175183203d0b437f6527 | refs/heads/master | 1,691,085,444,753 | 1,690,507,386,000 | 1,690,507,386,000 | 410,476,629 | 32 | 9 | Apache-2.0 | 1,690,506,773,000 | 1,632,639,790,000 | Lean | UTF-8 | Lean | false | false | 11,065 | lean | /-
Theorem 1 in Section 9.4 of the whitepaper, dealing with the encoding of an instruction as a field
element.
-/
import starkware.cairo.lean.semantics.cpu
import starkware.cairo.lean.semantics.air_encoding.constraints
open_locale big_operators
/-
Note: this is needed for the `classical.some`, but we can possibly remove it
based on the data from the range_check, if we assume `F` has decidable equality.
-/
noncomputable theory
/-
The tilde encoding of bit vectors.
-/
namespace bitvec
variables {n : ℕ} (b : bitvec n)
def tilde (i : fin (n + 1)) : ℕ :=
∑ j in i.rev.range, 2^(j.rev.cast_succ - i : ℕ) * (b.nth j.rev).to_nat
@[simp] theorem tilde_last : b.tilde (fin.last n) = 0 :=
by rw [tilde, fin.rev_last, fin.sum_range_zero]
theorem tilde_succ (i : fin n) :
b.tilde i.cast_succ = 2 * b.tilde i.succ + (b.nth i).to_nat :=
begin
rw [tilde, tilde, fin.rev_cast_succ, fin.sum_range_succ, finset.mul_sum,
add_comm, fin.rev_rev, nat.sub_self, pow_zero, one_mul, ←fin.cast_succ_rev],
congr' 1,
apply finset.sum_congr rfl,
intro j, rw [fin.mem_range, fin.cast_succ_lt_cast_succ_iff], intro hj,
rw [←mul_assoc, ←pow_succ, fin.coe_succ, nat.sub_succ, fin.coe_cast_succ, fin.coe_cast_succ], congr, symmetry, apply nat.succ_pred_eq_of_pos,
apply nat.sub_pos_of_lt,
rwa [←fin.lt_iff_coe_lt_coe, ←fin.rev_lt_rev_iff, fin.rev_rev]
end
section
variables {α : Type*} [semiring α]
theorem tilde_spec (f : fin (n + 1) → α)
(h0 : f (fin.last n) = 0)
(hsucc : ∀ i : fin n, f i.cast_succ = 2 * f i.succ + (b.nth i).to_nat) :
f = λ i, b.tilde i :=
begin
ext i, rw ←fin.rev_rev i,
generalize : i.rev = j,
apply fin.induction_on j,
{ rw [fin.rev_zero, h0, tilde_last, nat.cast_zero] },
intros i ih,
rw [←fin.cast_succ_rev, tilde_succ, hsucc, ←fin.rev_cast_succ, ih],
simp
end
end
theorem tilde_spec_nat (f : fin (n + 1) → ℕ)
(h0 : f (fin.last n) = 0)
(hsucc : ∀ i : fin n, f i.cast_succ = 2 * f i.succ + (b.nth i).to_nat) :
f = b.tilde :=
by { rw (tilde_spec b f h0); simp, exact hsucc }
theorem tilde_zero_eq : b.tilde 0 = b.to_natr :=
begin
rw [bitvec.to_natr, tilde, fin.rev_zero, fin.range_last, fin.coe_zero],
induction n with n ih,
{ rw [vector.eq_nil b], refl },
rw [fin.sum_univ_cast_succ],
conv { to_rhs, rw ←vector.cons_head_tail b },
rw [vector.reverse_cons, bitvec.to_nat_append, ←ih (vector.tail b)],
congr,
{ rw [mul_comm, finset.mul_sum],
apply finset.sum_congr rfl,
intros j _,
simp, rw [←mul_assoc, ←pow_succ, fin.rev_cast_succ],
congr,
apply tsub_eq_of_eq_add_rev,
rw [add_comm, add_assoc, add_comm 1, nat.sub_add_cancel],
exact j.2, },
rw [bitvec.singleton_to_nat], simp
end
def from_tilde (f : fin (n+1) → ℕ) : bitvec n :=
vector.of_fn (λ i : fin n, bool.of_nat $
(f i.cast_succ - 2 * f i.succ))
theorem from_tilde_tilde : from_tilde b.tilde = b :=
begin
ext i, dsimp [from_tilde],
rw [vector.nth_of_fn, tilde_succ, add_comm, nat.add_sub_cancel, bool.of_nat_to_nat]
end
theorem tilde_zero_inj {b1 b2 : bitvec n} (h : b1.tilde 0 = b2.tilde 0) : b1 = b2 :=
begin
rw [tilde_zero_eq, tilde_zero_eq] at h,
have := to_nat_inj h,
have h' := congr_arg vector.reverse this,
rwa [vector.reverse_reverse, vector.reverse_reverse] at h'
end
end bitvec
/-
Converting an instruction to a natural number.
This is only needed for the uniqueness theorem below, which may not be necessary for the
correctness proof.
-/
namespace instruction
theorem to_nat_le (inst : instruction) : inst.to_nat < 2^63 :=
calc
inst.to_nat ≤ (2^16 - 1) + 2^16 * (2^16 - 1) + 2^32 * (2^16 - 1) + 2^48 * (2^15 - 1) :
begin
apply add_le_add,
apply add_le_add,
apply add_le_add,
apply inst.off_dst.to_natr_le,
apply nat.mul_le_mul_left,
apply inst.off_op0.to_natr_le,
apply nat.mul_le_mul_left,
apply inst.off_op1.to_natr_le,
apply nat.mul_le_mul_left,
apply bitvec.to_natr_le
end
... = 2^63 - 1 : by norm_num
... < 2^63 : by norm_num
theorem to_nat_eq (inst : instruction) :
inst.to_nat = inst.off_dst.to_natr + 2^16 * (inst.off_op0.to_natr +
2^16 * (inst.off_op1.to_natr + 2^16 * inst.flags.to_natr)) :=
by { rw [instruction.to_nat], ring }
theorem to_nat_inj {i1 i2 : instruction} (h : i1.to_nat = i2.to_nat) : i1 = i2 :=
begin
have nez : 2^16 ≠ 0, norm_num,
rw [to_nat_eq, to_nat_eq] at h,
have h1 : i1.off_dst.to_natr = i2.off_dst.to_natr,
{ have := congr_arg (λ i, i % 2^16) h, dsimp at this,
simp [nat.add_mul_mod_self_left] at this,
rw [nat.mod_eq_of_lt i1.off_dst.to_natr_lt] at this,
rwa [nat.mod_eq_of_lt i2.off_dst.to_natr_lt] at this },
rw [h1, add_right_inj, mul_right_inj' nez] at h,
have h2 : i1.off_op0.to_natr = i2.off_op0.to_natr,
{ have := congr_arg (λ i, i % 2^16) h, dsimp at this,
simp [nat.add_mul_mod_self_left] at this,
rw [nat.mod_eq_of_lt i1.off_op0.to_natr_lt] at this,
rwa [nat.mod_eq_of_lt i2.off_op0.to_natr_lt] at this },
rw [h2, add_right_inj, mul_right_inj' nez] at h,
have h3 : i1.off_op1.to_natr = i2.off_op1.to_natr,
{ have := congr_arg (λ i, i % 2^16) h, dsimp at this,
simp [nat.add_mul_mod_self_left] at this,
rw [nat.mod_eq_of_lt i1.off_op1.to_natr_lt] at this,
rwa [nat.mod_eq_of_lt i2.off_op1.to_natr_lt] at this },
rw [h3, add_right_inj, mul_right_inj' nez] at h,
apply instruction.ext _ _ (bitvec.to_natr_inj h1) (bitvec.to_natr_inj h2)
(bitvec.to_natr_inj h3) (bitvec.to_natr_inj h)
end
end instruction
/-
Theorem 1.
-/
section theorem_one
variables {F : Type*} [field F]
-- so far, this is not used: [fintype F]
variable (char_ge: ring_char F ≥ 2^63)
/- the data -/
variables {inst
off_op0_tilde
off_op1_tilde
off_dst_tilde : F }
variable {f_tilde : tilde_type F}
/- the constraints -/
variable h_instruction : inst = off_dst_tilde + 2^16 * off_op0_tilde + 2^32 * off_op1_tilde +
2^48 * f_tilde 0
variable h_bit : ∀ i : fin 15, f_tilde.to_f i * (f_tilde.to_f i - 1) = 0
variable h_last_value : f_tilde ⟨15, by norm_num⟩ = 0
variable off_op0_in_range : ∃ j : ℕ, j < 2^16 ∧ off_op0_tilde = ↑j
variable off_op1_in_range : ∃ j : ℕ, j < 2^16 ∧ off_op1_tilde = ↑j
variable off_dst_in_range : ∃ j : ℕ, j < 2^16 ∧ off_dst_tilde = ↑j
/- recovering the instruction -/
def off_op0_nat := classical.some off_op0_in_range
theorem off_op0_lt : @off_op0_nat F _ _ off_op0_in_range < 2^16 :=
(classical.some_spec off_op0_in_range).left
theorem off_op0_eq : off_op0_tilde = ↑(@off_op0_nat F _ _ off_op0_in_range) :=
(classical.some_spec off_op0_in_range).right
def off_op1_nat := classical.some off_op1_in_range
theorem off_op1_lt : @off_op1_nat F _ _ off_op1_in_range < 2^16 :=
(classical.some_spec off_op1_in_range).left
theorem off_op1_eq : off_op1_tilde = ↑(@off_op1_nat F _ _ off_op1_in_range) :=
(classical.some_spec off_op1_in_range).right
def off_dst_nat := classical.some off_dst_in_range
theorem off_dst_lt : @off_dst_nat F _ _ off_dst_in_range < 2^16 :=
(classical.some_spec off_dst_in_range).left
theorem off_dst_eq : off_dst_tilde = ↑(@off_dst_nat F _ _ off_dst_in_range) :=
(classical.some_spec off_dst_in_range).right
section
include h_bit
theorem exists_bool_f_tilde_eq (i : fin 15) :
∃ b : bool, f_tilde.to_f i = ↑(b.to_nat) :=
begin
cases eq_zero_or_eq_zero_of_mul_eq_zero (h_bit i) with h h,
{ use ff, rw [h], simp only [bool.to_nat, bool.cond_ff, nat.cast_zero]},
use tt, rw [eq_of_sub_eq_zero h], exact nat.cast_one.symm
end
end
def flag_vec : bitvec 15 := vector.of_fn $ λ i, classical.some (exists_bool_f_tilde_eq h_bit i)
theorem flag_vec_spec (i : fin 15) : ↑((flag_vec h_bit).nth i).to_nat = f_tilde.to_f i :=
by rw [flag_vec, vector.nth_of_fn, ←classical.some_spec (exists_bool_f_tilde_eq h_bit i)]
section
include h_bit h_last_value
theorem f_tilde_eq : f_tilde = λ i, (flag_vec h_bit).tilde i :=
begin
apply bitvec.tilde_spec _ _ h_last_value,
intro i,
rw add_comm (2 * f_tilde _),
apply eq_add_of_sub_eq,
symmetry, apply flag_vec_spec
end
end
def the_instruction : instruction :=
{ off_dst := bitvec.of_natr 16 (off_dst_nat off_dst_in_range),
off_op0 := bitvec.of_natr 16 (off_op0_nat off_op0_in_range),
off_op1 := bitvec.of_natr 16 (off_op1_nat off_op1_in_range),
flags := flag_vec h_bit }
/-
The main theorem:
-/
section
include h_instruction h_last_value
theorem inst_eq : inst = (the_instruction h_bit off_op0_in_range
off_op1_in_range off_dst_in_range).to_nat :=
begin
rw [h_instruction, the_instruction, instruction.to_nat],
simp [bitvec.to_natr_of_natr],
have := congr_fun (f_tilde_eq h_bit h_last_value) 0,
dsimp at this,
rw [nat.mod_eq_of_lt (off_op0_lt off_op0_in_range),
nat.mod_eq_of_lt (off_op1_lt off_op1_in_range),
nat.mod_eq_of_lt (off_dst_lt off_dst_in_range),
←off_op0_eq off_op0_in_range,
←off_op1_eq off_op1_in_range,
←off_dst_eq off_dst_in_range,
this, bitvec.tilde_zero_eq]
end
end
theorem off_dst_tilde_eq : off_dst_tilde =
↑(the_instruction h_bit off_op0_in_range off_op1_in_range off_dst_in_range).off_dst.to_natr :=
begin
dsimp [the_instruction],
transitivity,
apply (off_dst_eq off_dst_in_range),
rw [bitvec.to_natr_of_natr, nat.mod_eq_of_lt (off_dst_lt off_dst_in_range)]
end
theorem off_op0_tilde_eq : off_op0_tilde =
↑(the_instruction h_bit off_op0_in_range off_op1_in_range off_dst_in_range).off_op0.to_natr :=
begin
dsimp [the_instruction],
transitivity,
apply (off_op0_eq off_op0_in_range),
rw [bitvec.to_natr_of_natr, nat.mod_eq_of_lt (off_op0_lt off_op0_in_range)]
end
theorem off_op1_tilde_eq : off_op1_tilde =
↑(the_instruction h_bit off_op0_in_range off_op1_in_range off_dst_in_range).off_op1.to_natr :=
begin
dsimp [the_instruction],
transitivity,
apply (@off_op1_eq F _ _ off_op1_in_range),
rw [bitvec.to_natr_of_natr, nat.mod_eq_of_lt (off_op1_lt off_op1_in_range)]
end
theorem f_tilde_to_f_eq : ∀ i, f_tilde.to_f i =
↑((the_instruction h_bit off_op0_in_range off_op1_in_range
off_dst_in_range).flags.nth i).to_nat :=
begin
intro i,
dsimp [the_instruction],
symmetry,
apply flag_vec_spec
end
section uniqueness
include char_ge
theorem inst_unique (i1 i2 : instruction) (h : (i1.to_nat : F) = i2.to_nat) :
i1 = i2 :=
begin
have h1 : i1.to_nat < ring_char F, from lt_of_lt_of_le i1.to_nat_le char_ge,
have h2 : i2.to_nat < ring_char F, from lt_of_lt_of_le i2.to_nat_le char_ge,
have : i1.to_nat = i2.to_nat, from nat.cast_inj_of_lt_char h1 h2 h,
exact instruction.to_nat_inj this
end
include h_instruction h_last_value
theorem inst_unique' (i : instruction) (h : inst = i.to_nat) :
i = the_instruction h_bit off_op0_in_range off_op1_in_range off_dst_in_range :=
begin
apply inst_unique char_ge,
rw ←h, apply inst_eq, apply h_instruction, apply h_last_value
end
end uniqueness
end theorem_one
|
255638e04a41184cd7b5f750f2007a75eeab5e1d | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/geometry/manifold/smooth_manifold_with_corners.lean | c9420ce7121ddfa4d594f77bdf8424c4903b9212 | [
"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 | 41,647 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.calculus.times_cont_diff
import geometry.manifold.charted_space
/-!
# Smooth manifolds (possibly with boundary or corners)
A smooth manifold is a manifold modelled on a normed vector space, or a subset like a
half-space (to get manifolds with boundaries) for which the changes of coordinates are smooth maps.
We define a model with corners as a map `I : H → E` embedding nicely the topological space `H` in
the vector space `E` (or more precisely as a structure containing all the relevant properties).
Given such a model with corners `I` on `(E, H)`, we define the groupoid of local
homeomorphisms of `H` which are smooth when read in `E` (for any regularity `n : with_top ℕ`).
With this groupoid at hand and the general machinery of charted spaces, we thus get the notion
of `C^n` manifold with respect to any model with corners `I` on `(E, H)`. We also introduce a
specific type class for `C^∞` manifolds as these are the most commonly used.
## Main definitions
* `model_with_corners 𝕜 E H` :
a structure containing informations on the way a space `H` embeds in a
model vector space E over the field `𝕜`. This is all that is needed to
define a smooth manifold with model space `H`, and model vector space `E`.
* `model_with_corners_self 𝕜 E` :
trivial model with corners structure on the space `E` embedded in itself by the identity.
* `times_cont_diff_groupoid n I` :
when `I` is a model with corners on `(𝕜, E, H)`, this is the groupoid of local homeos of `H`
which are of class `C^n` over the normed field `𝕜`, when read in `E`.
* `smooth_manifold_with_corners I M` :
a type class saying that the charted space `M`, modelled on the space `H`, has `C^∞` changes of
coordinates with respect to the model with corners `I` on `(𝕜, E, H)`. This type class is just
a shortcut for `has_groupoid M (times_cont_diff_groupoid ∞ I)`.
* `ext_chart_at I x`:
in a smooth manifold with corners with the model `I` on `(E, H)`, the charts take values in `H`,
but often we may want to use their `E`-valued version, obtained by composing the charts with `I`.
Since the target is in general not open, we can not register them as local homeomorphisms, but
we register them as local equivs. `ext_chart_at I x` is the canonical such local equiv around `x`.
As specific examples of models with corners, we define (in the file `real_instances.lean`)
* `model_with_corners_self ℝ (euclidean_space (fin n))` for the model space used to define
`n`-dimensional real manifolds without boundary (with notation `𝓡 n` in the locale `manifold`)
* `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_half_space n)` for the model space
used to define `n`-dimensional real manifolds with boundary (with notation `𝓡∂ n` in the locale
`manifold`)
* `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_quadrant n)` for the model space used
to define `n`-dimensional real manifolds with corners
With these definitions at hand, to invoke an `n`-dimensional real manifold without boundary,
one could use
`variables {n : ℕ} {M : Type*} [topological_space M] [charted_space (euclidean_space (fin n)) M]
[smooth_manifold_with_corners (𝓡 n) M]`.
However, this is not the recommended way: a theorem proved using this assumption would not apply
for instance to the tangent space of such a manifold, which is modelled on
`(euclidean_space (fin n)) × (euclidean_space (fin n))` and not on `euclidean_space (fin (2 * n))`!
In the same way, it would not apply to product manifolds, modelled on
`(euclidean_space (fin n)) × (euclidean_space (fin m))`.
The right invocation does not focus on one specific construction, but on all constructions sharing
the right properties, like
`variables {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E]
{I : model_with_corners ℝ E E} [I.boundaryless]
{M : Type*} [topological_space M] [charted_space E M] [smooth_manifold_with_corners I M]`
Here, `I.boundaryless` is a typeclass property ensuring that there is no boundary (this is for
instance the case for `model_with_corners_self`, or products of these). Note that one could consider
as a natural assumption to only use the trivial model with corners `model_with_corners_self ℝ E`,
but again in product manifolds the natural model with corners will not be this one but the product
one (and they are not defeq as `(λp : E × F, (p.1, p.2))` is not defeq to the identity). So, it is
important to use the above incantation to maximize the applicability of theorems.
## Implementation notes
We want to talk about manifolds modelled on a vector space, but also on manifolds with
boundary, modelled on a half space (or even manifolds with corners). For the latter examples,
we still want to define smooth functions, tangent bundles, and so on. As smooth functions are
well defined on vector spaces or subsets of these, one could take for model space a subtype of a
vector space. With the drawback that the whole vector space itself (which is the most basic
example) is not directly a subtype of itself: the inclusion of `univ : set E` in `set E` would
show up in the definition, instead of `id`.
A good abstraction covering both cases it to have a vector
space `E` (with basic example the Euclidean space), a model space `H` (with basic example the upper
half space), and an embedding of `H` into `E` (which can be the identity for `H = E`, or
`subtype.val` for manifolds with corners). We say that the pair `(E, H)` with their embedding is a
model with corners, and we encompass all the relevant properties (in particular the fact that the
image of `H` in `E` should have unique differentials) in the definition of `model_with_corners`.
We concentrate on `C^∞` manifolds: all the definitions work equally well for `C^n` manifolds, but
later on it is a pain to carry all over the smoothness parameter, especially when one wants to deal
with `C^k` functions as there would be additional conditions `k ≤ n` everywhere. Since one deals
almost all the time with `C^∞` (or analytic) manifolds, this seems to be a reasonable choice that
one could revisit later if needed. `C^k` manifolds are still available, but they should be called
using `has_groupoid M (times_cont_diff_groupoid k I)` where `I` is the model with corners.
I have considered using the model with corners `I` as a typeclass argument, possibly `out_param`, to
get lighter notations later on, but it did not turn out right, as on `E × F` there are two natural
model with corners, the trivial (identity) one, and the product one, and they are not defeq and one
needs to indicate to Lean which one we want to use.
This means that when talking on objects on manifolds one will most often need to specify the model
with corners one is using. For instance, the tangent bundle will be `tangent_bundle I M` and the
derivative will be `mfderiv I I' f`, instead of the more natural notations `tangent_bundle 𝕜 M` and
`mfderiv 𝕜 f` (the field has to be explicit anyway, as some manifolds could be considered both as
real and complex manifolds).
-/
noncomputable theory
universes u v w u' v' w'
open set filter
open_locale manifold filter topological_space
localized "notation `∞` := (⊤ : with_top ℕ)" in manifold
section model_with_corners
/-! ### Models with corners. -/
/-- A structure containing informations on the way a space `H` embeds in a
model vector space `E` over the field `𝕜`. This is all what is needed to
define a smooth manifold with model space `H`, and model vector space `E`.
-/
@[nolint has_inhabited_instance]
structure model_with_corners (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
(E : Type*) [normed_group E] [normed_space 𝕜 E] (H : Type*) [topological_space H]
extends local_equiv H E :=
(source_eq : source = univ)
(unique_diff' : unique_diff_on 𝕜 to_local_equiv.target)
(continuous_to_fun : continuous to_fun . tactic.interactive.continuity')
(continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity')
attribute [simp, mfld_simps] model_with_corners.source_eq
/-- A vector space is a model with corners. -/
def model_with_corners_self (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
(E : Type*) [normed_group E] [normed_space 𝕜 E] : model_with_corners 𝕜 E E :=
{ to_local_equiv := local_equiv.refl E,
source_eq := rfl,
unique_diff' := unique_diff_on_univ,
continuous_to_fun := continuous_id,
continuous_inv_fun := continuous_id }
localized "notation `𝓘(` 𝕜 `, ` E `)` := model_with_corners_self 𝕜 E" in manifold
localized "notation `𝓘(` 𝕜 `)` := model_with_corners_self 𝕜 𝕜" in manifold
section
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H]
(I : model_with_corners 𝕜 E H)
namespace model_with_corners
instance : has_coe_to_fun (model_with_corners 𝕜 E H) (λ _, H → E) := ⟨λ e, e.to_fun⟩
/-- The inverse to a model with corners, only registered as a local equiv. -/
protected def symm : local_equiv E H := I.to_local_equiv.symm
/- Register a few lemmas to make sure that `simp` puts expressions in normal form -/
@[simp, mfld_simps] lemma to_local_equiv_coe : (I.to_local_equiv : H → E) = I :=
rfl
@[simp, mfld_simps] lemma mk_coe (e : local_equiv H E) (a b c d) :
((model_with_corners.mk e a b c d : model_with_corners 𝕜 E H) : H → E) = (e : H → E) := rfl
@[simp, mfld_simps] lemma to_local_equiv_coe_symm : (I.to_local_equiv.symm : E → H) = I.symm := rfl
@[simp, mfld_simps] lemma mk_symm (e : local_equiv H E) (a b c d) :
(model_with_corners.mk e a b c d : model_with_corners 𝕜 E H).symm = e.symm :=
rfl
@[continuity] protected lemma continuous : continuous I := I.continuous_to_fun
protected lemma continuous_at {x} : continuous_at I x := I.continuous.continuous_at
protected lemma continuous_within_at {s x} : continuous_within_at I s x :=
I.continuous_at.continuous_within_at
@[continuity] lemma continuous_symm : continuous I.symm := I.continuous_inv_fun
lemma continuous_at_symm {x} : continuous_at I.symm x := I.continuous_symm.continuous_at
lemma continuous_within_at_symm {s x} : continuous_within_at I.symm s x :=
I.continuous_symm.continuous_within_at
@[simp, mfld_simps] lemma target_eq : I.target = range (I : H → E) :=
by { rw [← image_univ, ← I.source_eq], exact (I.to_local_equiv.image_source_eq_target).symm }
protected lemma unique_diff : unique_diff_on 𝕜 (range I) := I.target_eq ▸ I.unique_diff'
@[simp, mfld_simps] protected lemma left_inv (x : H) : I.symm (I x) = x :=
by { refine I.left_inv' _, simp }
protected lemma left_inverse : function.left_inverse I.symm I := I.left_inv
@[simp, mfld_simps] lemma symm_comp_self : I.symm ∘ I = id :=
I.left_inverse.comp_eq_id
protected lemma right_inv_on : right_inv_on I.symm I (range I) :=
I.left_inverse.right_inv_on_range
@[simp, mfld_simps] protected lemma right_inv {x : E} (hx : x ∈ range I) : I (I.symm x) = x :=
I.right_inv_on hx
protected lemma image_eq (s : set H) : I '' s = I.symm ⁻¹' s ∩ range I :=
begin
refine (I.to_local_equiv.image_eq_target_inter_inv_preimage _).trans _,
{ rw I.source_eq, exact subset_univ _ },
{ rw [inter_comm, I.target_eq, I.to_local_equiv_coe_symm] }
end
protected lemma closed_embedding : closed_embedding I :=
I.left_inverse.closed_embedding I.continuous_symm I.continuous
lemma closed_range : is_closed (range I) :=
I.closed_embedding.closed_range
lemma map_nhds_eq (x : H) : map I (𝓝 x) = 𝓝[range I] (I x) :=
I.closed_embedding.to_embedding.map_nhds_eq x
lemma image_mem_nhds_within {x : H} {s : set H} (hs : s ∈ 𝓝 x) :
I '' s ∈ 𝓝[range I] (I x) :=
I.map_nhds_eq x ▸ image_mem_map hs
lemma symm_map_nhds_within_range (x : H) :
map I.symm (𝓝[range I] (I x)) = 𝓝 x :=
by rw [← I.map_nhds_eq, map_map, I.symm_comp_self, map_id]
lemma unique_diff_preimage {s : set H} (hs : is_open s) :
unique_diff_on 𝕜 (I.symm ⁻¹' s ∩ range I) :=
by { rw inter_comm, exact I.unique_diff.inter (hs.preimage I.continuous_inv_fun) }
lemma unique_diff_preimage_source {β : Type*} [topological_space β]
{e : local_homeomorph H β} : unique_diff_on 𝕜 (I.symm ⁻¹' (e.source) ∩ range I) :=
I.unique_diff_preimage e.open_source
lemma unique_diff_at_image {x : H} : unique_diff_within_at 𝕜 (range I) (I x) :=
I.unique_diff _ (mem_range_self _)
protected lemma locally_compact [locally_compact_space E] (I : model_with_corners 𝕜 E H) :
locally_compact_space H :=
begin
have : ∀ (x : H), (𝓝 x).has_basis (λ s, s ∈ 𝓝 (I x) ∧ is_compact s)
(λ s, I.symm '' (s ∩ range ⇑I)),
{ intro x,
rw ← I.symm_map_nhds_within_range,
exact ((compact_basis_nhds (I x)).inf_principal _).map _ },
refine locally_compact_space_of_has_basis this _,
rintro x s ⟨-, hsc⟩,
exact (hsc.inter_right I.closed_range).image I.continuous_symm
end
open topological_space
protected lemma second_countable_topology [second_countable_topology E]
(I : model_with_corners 𝕜 E H) : second_countable_topology H :=
I.closed_embedding.to_embedding.second_countable_topology
end model_with_corners
section
variables (𝕜 E)
/-- In the trivial model with corners, the associated local equiv is the identity. -/
@[simp, mfld_simps] lemma model_with_corners_self_local_equiv :
(𝓘(𝕜, E)).to_local_equiv = local_equiv.refl E := rfl
@[simp, mfld_simps] lemma model_with_corners_self_coe :
(𝓘(𝕜, E) : E → E) = id := rfl
@[simp, mfld_simps] lemma model_with_corners_self_coe_symm :
(𝓘(𝕜, E).symm : E → E) = id := rfl
end
end
section model_with_corners_prod
/-- Given two model_with_corners `I` on `(E, H)` and `I'` on `(E', H')`, we define the model with
corners `I.prod I'` on `(E × E', model_prod H H')`. This appears in particular for the manifold
structure on the tangent bundle to a manifold modelled on `(E, H)`: it will be modelled on
`(E × E, H × E)`. See note [Manifold type tags] for explanation about `model_prod H H'`
vs `H × H'`. -/
def model_with_corners.prod
{𝕜 : Type u} [nondiscrete_normed_field 𝕜]
{E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H]
(I : model_with_corners 𝕜 E H)
{E' : Type v'} [normed_group E'] [normed_space 𝕜 E'] {H' : Type w'} [topological_space H']
(I' : model_with_corners 𝕜 E' H') : model_with_corners 𝕜 (E × E') (model_prod H H') :=
{ to_fun := λ x, (I x.1, I' x.2),
inv_fun := λ x, (I.symm x.1, I'.symm x.2),
source := {x | x.1 ∈ I.source ∧ x.2 ∈ I'.source},
source_eq := by simp only [set_of_true] with mfld_simps,
unique_diff' := I.unique_diff'.prod I'.unique_diff',
continuous_to_fun := I.continuous_to_fun.prod_map I'.continuous_to_fun,
continuous_inv_fun := I.continuous_inv_fun.prod_map I'.continuous_inv_fun,
.. I.to_local_equiv.prod I'.to_local_equiv }
/-- Given a finite family of `model_with_corners` `I i` on `(E i, H i)`, we define the model with
corners `pi I` on `(Π i, E i, model_pi H)`. See note [Manifold type tags] for explanation about
`model_pi H`. -/
def model_with_corners.pi
{𝕜 : Type u} [nondiscrete_normed_field 𝕜] {ι : Type v} [fintype ι]
{E : ι → Type w} [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)]
{H : ι → Type u'} [Π i, topological_space (H i)] (I : Π i, model_with_corners 𝕜 (E i) (H i)) :
model_with_corners 𝕜 (Π i, E i) (model_pi H) :=
{ to_local_equiv := local_equiv.pi (λ i, (I i).to_local_equiv),
source_eq := by simp only [set.pi_univ] with mfld_simps,
unique_diff' := unique_diff_on.pi ι E _ _ (λ i _, (I i).unique_diff'),
continuous_to_fun := continuous_pi $ λ i, (I i).continuous.comp (continuous_apply i),
continuous_inv_fun := continuous_pi $ λ i, (I i).continuous_symm.comp (continuous_apply i) }
/-- Special case of product model with corners, which is trivial on the second factor. This shows up
as the model to tangent bundles. -/
@[reducible] def model_with_corners.tangent
{𝕜 : Type u} [nondiscrete_normed_field 𝕜]
{E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H]
(I : model_with_corners 𝕜 E H) : model_with_corners 𝕜 (E × E) (model_prod H E) :=
I.prod (𝓘(𝕜, E))
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E']
{F : Type*} [normed_group F] [normed_space 𝕜 F] {F' : Type*} [normed_group F'] [normed_space 𝕜 F']
{H : Type*} [topological_space H] {H' : Type*} [topological_space H']
{G : Type*} [topological_space G] {G' : Type*} [topological_space G']
{I : model_with_corners 𝕜 E H} {J : model_with_corners 𝕜 F G}
@[simp, mfld_simps] lemma model_with_corners_prod_to_local_equiv :
(I.prod J).to_local_equiv = I.to_local_equiv.prod (J.to_local_equiv) :=
rfl
@[simp, mfld_simps] lemma model_with_corners_prod_coe
(I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') :
(I.prod I' : _ × _ → _ × _) = prod.map I I' := rfl
@[simp, mfld_simps] lemma model_with_corners_prod_coe_symm
(I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') :
((I.prod I').symm : _ × _ → _ × _) = prod.map I.symm I'.symm := rfl
end model_with_corners_prod
section boundaryless
/-- Property ensuring that the model with corners `I` defines manifolds without boundary. -/
class model_with_corners.boundaryless {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H]
(I : model_with_corners 𝕜 E H) : Prop :=
(range_eq_univ : range I = univ)
/-- The trivial model with corners has no boundary -/
instance model_with_corners_self_boundaryless (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
(E : Type*) [normed_group E] [normed_space 𝕜 E] : (model_with_corners_self 𝕜 E).boundaryless :=
⟨by simp⟩
/-- If two model with corners are boundaryless, their product also is -/
instance model_with_corners.range_eq_univ_prod {𝕜 : Type u} [nondiscrete_normed_field 𝕜]
{E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H]
(I : model_with_corners 𝕜 E H) [I.boundaryless]
{E' : Type v'} [normed_group E'] [normed_space 𝕜 E'] {H' : Type w'} [topological_space H']
(I' : model_with_corners 𝕜 E' H') [I'.boundaryless] :
(I.prod I').boundaryless :=
begin
split,
dsimp [model_with_corners.prod, model_prod],
rw [← prod_range_range_eq, model_with_corners.boundaryless.range_eq_univ,
model_with_corners.boundaryless.range_eq_univ, univ_prod_univ]
end
end boundaryless
section times_cont_diff_groupoid
/-! ### Smooth functions on models with corners -/
variables {m n : with_top ℕ} {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H]
(I : model_with_corners 𝕜 E H)
{M : Type*} [topological_space M]
variable (n)
/-- Given a model with corners `(E, H)`, we define the groupoid of `C^n` transformations of `H` as
the maps that are `C^n` when read in `E` through `I`. -/
def times_cont_diff_groupoid : structure_groupoid H :=
pregroupoid.groupoid
{ property := λf s, times_cont_diff_on 𝕜 n (I ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I),
comp := λf g u v hf hg hu hv huv, begin
have : I ∘ (g ∘ f) ∘ I.symm = (I ∘ g ∘ I.symm) ∘ (I ∘ f ∘ I.symm),
by { ext x, simp },
rw this,
apply times_cont_diff_on.comp hg _,
{ rintros x ⟨hx1, hx2⟩,
simp only with mfld_simps at ⊢ hx1,
exact hx1.2 },
{ refine hf.mono _,
rintros x ⟨hx1, hx2⟩,
exact ⟨hx1.1, hx2⟩ }
end,
id_mem := begin
apply times_cont_diff_on.congr (times_cont_diff_id.times_cont_diff_on),
rintros x ⟨hx1, hx2⟩,
rcases mem_range.1 hx2 with ⟨y, hy⟩,
rw ← hy,
simp only with mfld_simps,
end,
locality := λf u hu H, begin
apply times_cont_diff_on_of_locally_times_cont_diff_on,
rintros y ⟨hy1, hy2⟩,
rcases mem_range.1 hy2 with ⟨x, hx⟩,
rw ← hx at ⊢ hy1,
simp only with mfld_simps at ⊢ hy1,
rcases H x hy1 with ⟨v, v_open, xv, hv⟩,
have : ((I.symm ⁻¹' (u ∩ v)) ∩ (range I))
= ((I.symm ⁻¹' u) ∩ (range I) ∩ I.symm ⁻¹' v),
{ rw [preimage_inter, inter_assoc, inter_assoc],
congr' 1,
rw inter_comm },
rw this at hv,
exact ⟨I.symm ⁻¹' v, v_open.preimage I.continuous_symm, by simpa, hv⟩
end,
congr := λf g u hu fg hf, begin
apply hf.congr,
rintros y ⟨hy1, hy2⟩,
rcases mem_range.1 hy2 with ⟨x, hx⟩,
rw ← hx at ⊢ hy1,
simp only with mfld_simps at ⊢ hy1,
rw fg _ hy1
end }
variable {n}
/-- Inclusion of the groupoid of `C^n` local diffeos in the groupoid of `C^m` local diffeos when
`m ≤ n` -/
lemma times_cont_diff_groupoid_le (h : m ≤ n) :
times_cont_diff_groupoid n I ≤ times_cont_diff_groupoid m I :=
begin
rw [times_cont_diff_groupoid, times_cont_diff_groupoid],
apply groupoid_of_pregroupoid_le,
assume f s hfs,
exact times_cont_diff_on.of_le hfs h
end
/-- The groupoid of `0`-times continuously differentiable maps is just the groupoid of all
local homeomorphisms -/
lemma times_cont_diff_groupoid_zero_eq :
times_cont_diff_groupoid 0 I = continuous_groupoid H :=
begin
apply le_antisymm le_top,
assume u hu,
-- we have to check that every local homeomorphism belongs to `times_cont_diff_groupoid 0 I`,
-- by unfolding its definition
change u ∈ times_cont_diff_groupoid 0 I,
rw [times_cont_diff_groupoid, mem_groupoid_of_pregroupoid],
simp only [times_cont_diff_on_zero],
split,
{ apply continuous_on.comp (@continuous.continuous_on _ _ _ _ _ univ I.continuous)
_ (subset_univ _),
apply continuous_on.comp u.continuous_to_fun I.continuous_symm.continuous_on
(inter_subset_left _ _) },
{ apply continuous_on.comp (@continuous.continuous_on _ _ _ _ _ univ I.continuous)
_ (subset_univ _),
apply continuous_on.comp u.continuous_inv_fun I.continuous_inv_fun.continuous_on
(inter_subset_left _ _) },
end
variable (n)
/-- An identity local homeomorphism belongs to the `C^n` groupoid. -/
lemma of_set_mem_times_cont_diff_groupoid {s : set H} (hs : is_open s) :
local_homeomorph.of_set s hs ∈ times_cont_diff_groupoid n I :=
begin
rw [times_cont_diff_groupoid, mem_groupoid_of_pregroupoid],
suffices h : times_cont_diff_on 𝕜 n (I ∘ I.symm) (I.symm ⁻¹' s ∩ range I),
by simp [h],
have : times_cont_diff_on 𝕜 n id (univ : set E) :=
times_cont_diff_id.times_cont_diff_on,
exact this.congr_mono (λ x hx, by simp [hx.2]) (subset_univ _)
end
/-- The composition of a local homeomorphism from `H` to `M` and its inverse belongs to
the `C^n` groupoid. -/
lemma symm_trans_mem_times_cont_diff_groupoid (e : local_homeomorph M H) :
e.symm.trans e ∈ times_cont_diff_groupoid n I :=
begin
have : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target :=
local_homeomorph.trans_symm_self _,
exact structure_groupoid.eq_on_source _
(of_set_mem_times_cont_diff_groupoid n I e.open_target) this
end
variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H']
/-- The product of two smooth local homeomorphisms is smooth. -/
lemma times_cont_diff_groupoid_prod
{I : model_with_corners 𝕜 E H} {I' : model_with_corners 𝕜 E' H'}
{e : local_homeomorph H H} {e' : local_homeomorph H' H'}
(he : e ∈ times_cont_diff_groupoid ⊤ I) (he' : e' ∈ times_cont_diff_groupoid ⊤ I') :
e.prod e' ∈ times_cont_diff_groupoid ⊤ (I.prod I') :=
begin
cases he with he he_symm,
cases he' with he' he'_symm,
simp only at he he_symm he' he'_symm,
split;
simp only [local_equiv.prod_source, local_homeomorph.prod_to_local_equiv],
{ have h3 := times_cont_diff_on.prod_map he he',
rw [← I.image_eq, ← I'.image_eq, set.prod_image_image_eq] at h3,
rw ← (I.prod I').image_eq,
exact h3, },
{ have h3 := times_cont_diff_on.prod_map he_symm he'_symm,
rw [← I.image_eq, ← I'.image_eq, set.prod_image_image_eq] at h3,
rw ← (I.prod I').image_eq,
exact h3, }
end
/-- The `C^n` groupoid is closed under restriction. -/
instance : closed_under_restriction (times_cont_diff_groupoid n I) :=
(closed_under_restriction_iff_id_le _).mpr
begin
apply structure_groupoid.le_iff.mpr,
rintros e ⟨s, hs, hes⟩,
apply (times_cont_diff_groupoid n I).eq_on_source' _ _ _ hes,
exact of_set_mem_times_cont_diff_groupoid n I hs,
end
end times_cont_diff_groupoid
end model_with_corners
section smooth_manifold_with_corners
/-! ### Smooth manifolds with corners -/
/-- Typeclass defining smooth manifolds with corners with respect to a model with corners, over a
field `𝕜` and with infinite smoothness to simplify typeclass search and statements later on. -/
@[ancestor has_groupoid]
class smooth_manifold_with_corners {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
(M : Type*) [topological_space M] [charted_space H M] extends
has_groupoid M (times_cont_diff_groupoid ∞ I) : Prop
lemma smooth_manifold_with_corners.mk' {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
(M : Type*) [topological_space M] [charted_space H M]
[gr : has_groupoid M (times_cont_diff_groupoid ∞ I)] :
smooth_manifold_with_corners I M := { ..gr }
lemma smooth_manifold_with_corners_of_times_cont_diff_on
{𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
(M : Type*) [topological_space M] [charted_space H M]
(h : ∀ (e e' : local_homeomorph M H), e ∈ atlas H M → e' ∈ atlas H M →
times_cont_diff_on 𝕜 ⊤ (I ∘ (e.symm ≫ₕ e') ∘ I.symm)
(I.symm ⁻¹' (e.symm ≫ₕ e').source ∩ range I)) :
smooth_manifold_with_corners I M :=
{ compatible :=
begin
haveI : has_groupoid M (times_cont_diff_groupoid ∞ I) := has_groupoid_of_pregroupoid _ h,
apply structure_groupoid.compatible,
end }
/-- For any model with corners, the model space is a smooth manifold -/
instance model_space_smooth {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H]
{I : model_with_corners 𝕜 E H} :
smooth_manifold_with_corners I H := { .. has_groupoid_model_space _ _ }
end smooth_manifold_with_corners
namespace smooth_manifold_with_corners
/- We restate in the namespace `smooth_manifolds_with_corners` some lemmas that hold for general
charted space with a structure groupoid, avoiding the need to specify the groupoid
`times_cont_diff_groupoid ∞ I` explicitly. -/
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
(M : Type*) [topological_space M] [charted_space H M]
/-- The maximal atlas of `M` for the smooth manifold with corners structure corresponding to the
model with corners `I`. -/
def maximal_atlas := (times_cont_diff_groupoid ∞ I).maximal_atlas M
variable {M}
lemma mem_maximal_atlas_of_mem_atlas [smooth_manifold_with_corners I M]
{e : local_homeomorph M H} (he : e ∈ atlas H M) : e ∈ maximal_atlas I M :=
structure_groupoid.mem_maximal_atlas_of_mem_atlas _ he
lemma chart_mem_maximal_atlas [smooth_manifold_with_corners I M] (x : M) :
chart_at H x ∈ maximal_atlas I M :=
structure_groupoid.chart_mem_maximal_atlas _ x
variable {I}
lemma compatible_of_mem_maximal_atlas
{e e' : local_homeomorph M H} (he : e ∈ maximal_atlas I M) (he' : e' ∈ maximal_atlas I M) :
e.symm.trans e' ∈ times_cont_diff_groupoid ∞ I :=
structure_groupoid.compatible_of_mem_maximal_atlas he he'
/-- The product of two smooth manifolds with corners is naturally a smooth manifold with corners. -/
instance prod {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{E' : Type*} [normed_group E'] [normed_space 𝕜 E']
{H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H}
{H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
(M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M]
(M' : Type*) [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M'] :
smooth_manifold_with_corners (I.prod I') (M×M') :=
{ compatible :=
begin
rintros f g ⟨f1, f2, hf1, hf2, rfl⟩ ⟨g1, g2, hg1, hg2, rfl⟩,
rw [local_homeomorph.prod_symm, local_homeomorph.prod_trans],
have h1 := has_groupoid.compatible (times_cont_diff_groupoid ⊤ I) hf1 hg1,
have h2 := has_groupoid.compatible (times_cont_diff_groupoid ⊤ I') hf2 hg2,
exact times_cont_diff_groupoid_prod h1 h2,
end }
end smooth_manifold_with_corners
lemma local_homeomorph.singleton_smooth_manifold_with_corners
{𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
{M : Type*} [topological_space M]
(e : local_homeomorph M H) (h : e.source = set.univ) :
@smooth_manifold_with_corners 𝕜 _ E _ _ H _ I M _ (e.singleton_charted_space h) :=
@smooth_manifold_with_corners.mk' _ _ _ _ _ _ _ _ _ _ (id _) $
e.singleton_has_groupoid h (times_cont_diff_groupoid ∞ I)
lemma open_embedding.singleton_smooth_manifold_with_corners
{𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
{M : Type*} [topological_space M]
[nonempty M] {f : M → H} (h : open_embedding f) :
@smooth_manifold_with_corners 𝕜 _ E _ _ H _ I M _ h.singleton_charted_space :=
(h.to_local_homeomorph f).singleton_smooth_manifold_with_corners I (by simp)
namespace topological_space.opens
open topological_space
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
{M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M]
(s : opens M)
instance : smooth_manifold_with_corners I s := { ..s.has_groupoid (times_cont_diff_groupoid ∞ I) }
end topological_space.opens
section extended_charts
open_locale topological_space
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
{M : Type*} [topological_space M] [charted_space H M]
(x : M) {s t : set M}
/-!
### Extended charts
In a smooth manifold with corners, the model space is the space `H`. However, we will also
need to use extended charts taking values in the model vector space `E`. These extended charts are
not `local_homeomorph` as the target is not open in `E` in general, but we can still register them
as `local_equiv`.
-/
/-- The preferred extended chart on a manifold with corners around a point `x`, from a neighborhood
of `x` to the model vector space. -/
@[simp, mfld_simps] def ext_chart_at (x : M) : local_equiv M E :=
(chart_at H x).to_local_equiv.trans I.to_local_equiv
lemma ext_chart_at_coe : ⇑(ext_chart_at I x) = I ∘ chart_at H x := rfl
lemma ext_chart_at_coe_symm :
⇑(ext_chart_at I x).symm = (chart_at H x).symm ∘ I.symm := rfl
lemma ext_chart_at_source : (ext_chart_at I x).source = (chart_at H x).source :=
by rw [ext_chart_at, local_equiv.trans_source, I.source_eq, preimage_univ, inter_univ]
lemma ext_chart_at_open_source : is_open (ext_chart_at I x).source :=
by { rw ext_chart_at_source, exact (chart_at H x).open_source }
lemma mem_ext_chart_source : x ∈ (ext_chart_at I x).source :=
by simp only [ext_chart_at_source, mem_chart_source]
lemma ext_chart_at_to_inv :
(ext_chart_at I x).symm ((ext_chart_at I x) x) = x :=
(ext_chart_at I x).left_inv (mem_ext_chart_source I x)
lemma ext_chart_at_source_mem_nhds' {x' : M} (h : x' ∈ (ext_chart_at I x).source) :
(ext_chart_at I x).source ∈ 𝓝 x' :=
is_open.mem_nhds (ext_chart_at_open_source I x) h
lemma ext_chart_at_source_mem_nhds : (ext_chart_at I x).source ∈ 𝓝 x :=
ext_chart_at_source_mem_nhds' I x (mem_ext_chart_source I x)
lemma ext_chart_at_source_mem_nhds_within' {x' : M} (h : x' ∈ (ext_chart_at I x).source) :
(ext_chart_at I x).source ∈ 𝓝[s] x' :=
mem_nhds_within_of_mem_nhds (ext_chart_at_source_mem_nhds' I x h)
lemma ext_chart_at_source_mem_nhds_within :
(ext_chart_at I x).source ∈ 𝓝[s] x :=
mem_nhds_within_of_mem_nhds (ext_chart_at_source_mem_nhds I x)
lemma ext_chart_at_continuous_on :
continuous_on (ext_chart_at I x) (ext_chart_at I x).source :=
begin
refine I.continuous.comp_continuous_on _,
rw ext_chart_at_source,
exact (chart_at H x).continuous_on
end
lemma ext_chart_at_continuous_at' {x' : M} (h : x' ∈ (ext_chart_at I x).source) :
continuous_at (ext_chart_at I x) x' :=
(ext_chart_at_continuous_on I x).continuous_at $ ext_chart_at_source_mem_nhds' I x h
lemma ext_chart_at_continuous_at : continuous_at (ext_chart_at I x) x :=
ext_chart_at_continuous_at' _ _ (mem_ext_chart_source I x)
lemma ext_chart_at_continuous_on_symm :
continuous_on (ext_chart_at I x).symm (ext_chart_at I x).target :=
begin
apply continuous_on.comp (chart_at H x).continuous_on_symm I.continuous_symm.continuous_on,
simp [ext_chart_at, local_equiv.trans_target]
end
lemma ext_chart_at_map_nhds' {x y : M} (hy : y ∈ (ext_chart_at I x).source) :
map (ext_chart_at I x) (𝓝 y) = 𝓝[range I] (ext_chart_at I x y) :=
begin
rw [ext_chart_at_coe, (∘), ← I.map_nhds_eq, ← (chart_at H x).map_nhds_eq, map_map],
rwa ext_chart_at_source at hy
end
lemma ext_chart_at_map_nhds :
map (ext_chart_at I x) (𝓝 x) = 𝓝[range I] (ext_chart_at I x x) :=
ext_chart_at_map_nhds' I $ mem_ext_chart_source I x
lemma ext_chart_at_target_mem_nhds_within' {y : M} (hy : y ∈ (ext_chart_at I x).source) :
(ext_chart_at I x).target ∈ 𝓝[range I] (ext_chart_at I x y) :=
begin
rw [← local_equiv.image_source_eq_target, ← ext_chart_at_map_nhds' I hy],
exact image_mem_map (ext_chart_at_source_mem_nhds' _ _ hy)
end
lemma ext_chart_at_target_mem_nhds_within :
(ext_chart_at I x).target ∈ 𝓝[range I] (ext_chart_at I x x) :=
ext_chart_at_target_mem_nhds_within' I x (mem_ext_chart_source I x)
lemma ext_chart_at_target_subset_range : (ext_chart_at I x).target ⊆ range I :=
by simp only with mfld_simps
lemma nhds_within_ext_chart_target_eq' {y : M} (hy : y ∈ (ext_chart_at I x).source) :
𝓝[(ext_chart_at I x).target] (ext_chart_at I x y) =
𝓝[range I] (ext_chart_at I x y) :=
(nhds_within_mono _ (ext_chart_at_target_subset_range _ _)).antisymm $
nhds_within_le_of_mem (ext_chart_at_target_mem_nhds_within' _ _ hy)
lemma nhds_within_ext_chart_target_eq :
𝓝[(ext_chart_at I x).target] ((ext_chart_at I x) x) =
𝓝[range I] ((ext_chart_at I x) x) :=
nhds_within_ext_chart_target_eq' I x (mem_ext_chart_source I x)
lemma ext_chart_continuous_at_symm'' {y : E} (h : y ∈ (ext_chart_at I x).target) :
continuous_at (ext_chart_at I x).symm y :=
continuous_at.comp ((chart_at H x).continuous_at_symm h.2) (I.continuous_symm.continuous_at)
lemma ext_chart_continuous_at_symm' {x' : M} (h : x' ∈ (ext_chart_at I x).source) :
continuous_at (ext_chart_at I x).symm (ext_chart_at I x x') :=
ext_chart_continuous_at_symm'' I _ $ (ext_chart_at I x).map_source h
lemma ext_chart_continuous_at_symm :
continuous_at (ext_chart_at I x).symm ((ext_chart_at I x) x) :=
ext_chart_continuous_at_symm' I x (mem_ext_chart_source I x)
lemma ext_chart_continuous_on_symm :
continuous_on (ext_chart_at I x).symm (ext_chart_at I x).target :=
λ y hy, (ext_chart_continuous_at_symm'' _ _ hy).continuous_within_at
lemma ext_chart_preimage_open_of_open' {s : set E} (hs : is_open s) :
is_open ((ext_chart_at I x).source ∩ ext_chart_at I x ⁻¹' s) :=
(ext_chart_at_continuous_on I x).preimage_open_of_open (ext_chart_at_open_source _ _) hs
lemma ext_chart_preimage_open_of_open {s : set E} (hs : is_open s) :
is_open ((chart_at H x).source ∩ ext_chart_at I x ⁻¹' s) :=
by { rw ← ext_chart_at_source I, exact ext_chart_preimage_open_of_open' I x hs }
lemma ext_chart_at_map_nhds_within_eq_image' {y : M} (hy : y ∈ (ext_chart_at I x).source) :
map (ext_chart_at I x) (𝓝[s] y) =
𝓝[ext_chart_at I x '' ((ext_chart_at I x).source ∩ s)] (ext_chart_at I x y) :=
by set e := ext_chart_at I x;
calc map e (𝓝[s] y) = map e (𝓝[e.source ∩ s] y) :
congr_arg (map e) (nhds_within_inter_of_mem (ext_chart_at_source_mem_nhds_within' I x hy)).symm
... = 𝓝[e '' (e.source ∩ s)] (e y) :
((ext_chart_at I x).left_inv_on.mono $ inter_subset_left _ _).map_nhds_within_eq
((ext_chart_at I x).left_inv hy)
(ext_chart_continuous_at_symm' I x hy).continuous_within_at
(ext_chart_at_continuous_at' I x hy).continuous_within_at
lemma ext_chart_at_map_nhds_within_eq_image :
map (ext_chart_at I x) (𝓝[s] x) =
𝓝[ext_chart_at I x '' ((ext_chart_at I x).source ∩ s)] (ext_chart_at I x x) :=
ext_chart_at_map_nhds_within_eq_image' I x (mem_ext_chart_source I x)
lemma ext_chart_at_map_nhds_within' {y : M} (hy : y ∈ (ext_chart_at I x).source) :
map (ext_chart_at I x) (𝓝[s] y) =
𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] (ext_chart_at I x y) :=
by rw [ext_chart_at_map_nhds_within_eq_image' I x hy, nhds_within_inter,
← nhds_within_ext_chart_target_eq' _ _ hy, ← nhds_within_inter,
(ext_chart_at I x).image_source_inter_eq', inter_comm]
lemma ext_chart_at_map_nhds_within :
map (ext_chart_at I x) (𝓝[s] x) =
𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] (ext_chart_at I x x) :=
ext_chart_at_map_nhds_within' I x (mem_ext_chart_source I x)
lemma ext_chart_at_symm_map_nhds_within' {y : M} (hy : y ∈ (ext_chart_at I x).source) :
map (ext_chart_at I x).symm
(𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] (ext_chart_at I x y)) = 𝓝[s] y :=
begin
rw [← ext_chart_at_map_nhds_within' I x hy, map_map, map_congr, map_id],
exact (ext_chart_at I x).left_inv_on.eq_on.eventually_eq_of_mem
(ext_chart_at_source_mem_nhds_within' _ _ hy)
end
lemma ext_chart_at_symm_map_nhds_within_range' {y : M} (hy : y ∈ (ext_chart_at I x).source) :
map (ext_chart_at I x).symm (𝓝[range I] (ext_chart_at I x y)) = 𝓝 y :=
by rw [← nhds_within_univ, ← ext_chart_at_symm_map_nhds_within' I x hy, preimage_univ, univ_inter]
lemma ext_chart_at_symm_map_nhds_within :
map (ext_chart_at I x).symm
(𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] (ext_chart_at I x x)) = 𝓝[s] x :=
ext_chart_at_symm_map_nhds_within' I x (mem_ext_chart_source I x)
lemma ext_chart_at_symm_map_nhds_within_range :
map (ext_chart_at I x).symm (𝓝[range I] (ext_chart_at I x x)) = 𝓝 x :=
ext_chart_at_symm_map_nhds_within_range' I x (mem_ext_chart_source I x)
/-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of a point
in the source is a neighborhood of the preimage, within a set. -/
lemma ext_chart_preimage_mem_nhds_within' {x' : M} (h : x' ∈ (ext_chart_at I x).source)
(ht : t ∈ 𝓝[s] x') :
(ext_chart_at I x).symm ⁻¹' t ∈
𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x') :=
by rwa [← ext_chart_at_symm_map_nhds_within' I x h, mem_map] at ht
/-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of the
base point is a neighborhood of the preimage, within a set. -/
lemma ext_chart_preimage_mem_nhds_within (ht : t ∈ 𝓝[s] x) :
(ext_chart_at I x).symm ⁻¹' t ∈
𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) :=
ext_chart_preimage_mem_nhds_within' I x (mem_ext_chart_source I x) ht
/-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of a point
is a neighborhood of the preimage. -/
lemma ext_chart_preimage_mem_nhds (ht : t ∈ 𝓝 x) :
(ext_chart_at I x).symm ⁻¹' t ∈ 𝓝 ((ext_chart_at I x) x) :=
begin
apply (ext_chart_continuous_at_symm I x).preimage_mem_nhds,
rwa (ext_chart_at I x).left_inv (mem_ext_chart_source _ _)
end
/-- Technical lemma to rewrite suitably the preimage of an intersection under an extended chart, to
bring it into a convenient form to apply derivative lemmas. -/
lemma ext_chart_preimage_inter_eq :
((ext_chart_at I x).symm ⁻¹' (s ∩ t) ∩ range I)
= ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ∩ ((ext_chart_at I x).symm ⁻¹' t) :=
by mfld_set_tac
end extended_charts
/-- In the case of the manifold structure on a vector space, the extended charts are just the
identity.-/
lemma ext_chart_model_space_eq_id (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] (x : E) :
ext_chart_at (model_with_corners_self 𝕜 E) x = local_equiv.refl E :=
by simp only with mfld_simps
|
cb7cc1c0c8232173e77a97e0bfc95a162163913f | 0d2e44896897eda703992595d71a0b19ed30b8a1 | /uexp/tactic_paper_supplemental_material/monoid_cancellation/cancellation_solver.lean | 2c8597947abc057d25c9caaf848eb1e7a7c629af | [
"BSD-2-Clause"
] | permissive | wwombat/Cosette | a87312aabefdb53ea8b67c37731bd58c7485afb6 | 4c5dc6172e24d3546c9818ac1fad06f72fe1c991 | refs/heads/master | 1,619,479,568,051 | 1,520,292,502,000 | 1,520,292,502,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,312 | lean | import .smt
local infix * := star
open tactic smt_tactic
attribute [ematch] one_star
meta def qf_monoid := using_smt $ smt_tactic.intros; eblast
section
variables {a b c d : m}
lemma plus_unit_p : a = b → o * a = b := by qf_monoid
lemma plus_assoc_p1 : a * (b * c) = d → (a * b) * c = d := by qf_monoid
lemma plus_assoc_p2 : b * (a * c) = d → (a * b) * c = d := by qf_monoid
lemma plus_comm_p : a * b = c → b * a = c := by qf_monoid
lemma plus_unit_c : a = b → a = o * b := by qf_monoid
lemma plus_assoc_c1 : d = a * (b * c) → (a * b) * c = d := by qf_monoid
lemma plus_assoc_c2 : d = b * (a * c) → (a * b) * c = d := by qf_monoid
lemma plus_comm_c : c = a * b → c = b * a := by qf_monoid
lemma plus_cancel : a = c → b = d → a * b = c * d := by qf_monoid
lemma plus_refl : a = a := by qf_monoid
end
open tactic expr
meta def iter_right :=
applyc `plus_unit_c <|>
applyc `plus_assoc_c1 >> iter_right <|>
applyc `plus_assoc_c2 >> iter_right <|>
applyc `plus_cancel >> reflexivity
meta def iter_left :=
applyc `plus_unit_p <|>
applyc `plus_assoc_p1 >> iter_left <|>
applyc `plus_assoc_p2 >> iter_left <|>
iter_right <|> applyc `plus_comm_p >> iter_right
meta def cancel :=
iter_left <|> applyc `plus_comm_p >> iter_left
meta def solve : tactic unit :=
repeat $ reflexivity <|> cancel
|
09dd53b2618f09231b5e0a3bf66c42a15772fe67 | 46125763b4dbf50619e8846a1371029346f4c3db | /src/analysis/normed_space/multilinear.lean | 78ca625114f2b5933fd3e9de8613de0343d6200b | [
"Apache-2.0"
] | permissive | thjread/mathlib | a9d97612cedc2c3101060737233df15abcdb9eb1 | 7cffe2520a5518bba19227a107078d83fa725ddc | refs/heads/master | 1,615,637,696,376 | 1,583,953,063,000 | 1,583,953,063,000 | 246,680,271 | 0 | 0 | Apache-2.0 | 1,583,960,875,000 | 1,583,960,875,000 | null | UTF-8 | Lean | false | false | 48,850 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.normed_space.operator_norm topology.algebra.multilinear
import data.fintype.card
/-!
# Operator norm on the space of continuous multilinear maps
When `f` is a continuous multilinear map in finitely many variables, we define its norm `∥f∥` as the
smallest number such that `∥f m∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥)` for all `m`.
We show that it is indeed a norm, and prove its basic properties.
## Main results
Let `f` be a multilinear map in finitely many variables.
* `exists_bound_of_continuous` asserts that, if `f` is continuous, then there exists `C > 0`
with `∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)` for all `m`.
* `continuous_of_bound`, conversely, asserts that this bound implies continuity.
* `mk_continuous` constructs the associated continuous multilinear map.
Let `f` be a continuous multilinear map in finitely many variables.
* `∥f∥` is its norm, i.e., the smallest number such that `∥f m∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥)` for
all `m`.
* `le_op_norm f m` asserts the fundamental inequality `∥f m∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥)`.
* `norm_image_sub_le_of_bound f m₁ m₂` gives a control of the difference `f m₁ - f m₂` in terms of
`∥f∥` and `∥m₁ - m₂∥`.
We also register isomorphisms corresponding to currying or uncurrying variables, transforming a
continuous multilinear function `f` in `n+1` variables into a continuous linear function taking
values in continuous multilinear functions in `n` variables, and also into a continuous multilinear
function in `n` variables taking values in continuous linear functions. These operations are called
`f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and
`f.uncurry_right`). They induce continuous linear equivalences between spaces of
continuous multilinear functions in `n+1` variables and spaces of continuous linear functions into
continuous multilinear functions in `n` variables (resp. continuous multilinear functions in `n`
variables taking values in continuous linear functions), called respectively
`continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`.
## Implementation notes
We mostly follow the API (and the proofs) of `operator_norm.lean`, with the additional complexity
that we should deal with multilinear maps in several variables. The currying/uncurrying
constructions are based on those in `multilinear.lean`.
From the mathematical point of view, all the results follow from the results on operator norm in
one variable, by applying them to one variable after the other through currying. However, this
is only well defined when there is an order on the variables (for instance on `fin n`) although
the final result is independent of the order. While everything could be done following this
approach, it turns out that direct proofs are easier and more efficient.
-/
noncomputable theory
open_locale classical
open finset
set_option class.instance_max_depth 45
universes u v w w₁ w₂ wG
variables {𝕜 : Type u} {ι : Type v} {n : ℕ}
{G : Type wG} {E : fin n.succ → Type w} {E₁ : ι → Type w₁} {E₂ : Type w₂}
[decidable_eq ι] [fintype ι] [nondiscrete_normed_field 𝕜]
[normed_group G] [∀i, normed_group (E i)] [∀i, normed_group (E₁ i)] [normed_group E₂]
[normed_space 𝕜 G] [∀i, normed_space 𝕜 (E i)] [∀i, normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂]
/-!
### Continuity properties of multilinear maps
We relate continuity of multilinear maps to the inequality `∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)`, in
both directions. Along the way, we prove useful bounds on the difference `∥f m₁ - f m₂∥`.
-/
namespace multilinear_map
variable (f : multilinear_map 𝕜 E₁ E₂)
/-- If a multilinear map in finitely many variables on normed spaces is continuous, then it
satisfies the inequality `∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)`, for some `C` which can be chosen to be
positive. -/
theorem exists_bound_of_continuous (hf : continuous f) :
∃ (C : ℝ), 0 < C ∧ (∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) :=
begin
/- The proof only uses the continuity at `0`. Then, given a general point `m`, rescale each of
its coordinates to bring them to a shell of fixed width around `0`, on which one knows that `f` is
bounded, and then use the multiplicativity of `f` along each coordinate to deduce the desired
bound.-/
obtain ⟨ε, ε_pos, hε⟩ : ∃ ε > 0, ∀{m}, dist m 0 < ε → dist (f m) (f 0) < 1 :=
metric.tendsto_nhds_nhds.1 hf.continuous_at 1 zero_lt_one,
let δ := ε/2,
have δ_pos : δ > 0 := half_pos ε_pos,
/- On points of size at most `δ`, `f` is bounded (by `1 + ∥f 0∥`). -/
have H : ∀{a}, ∥a∥ ≤ δ → ∥f a∥ ≤ 1 + ∥f 0∥,
{ assume a ha,
have : dist (f a) (f 0) ≤ 1,
{ apply le_of_lt (hε _),
rw [dist_eq_norm, sub_zero],
exact lt_of_le_of_lt ha (half_lt_self ε_pos) },
calc ∥f a∥ = dist (f a) 0 : (dist_zero_right _).symm
... ≤ dist (f a) (f 0) + dist (f 0) 0 : dist_triangle _ _ _
... ≤ 1 + ∥f 0∥ : by { rw dist_zero_right, exact add_le_add_right this _ } },
obtain ⟨c, hc⟩ : ∃c : 𝕜, 1 < ∥c∥ := normed_field.exists_one_lt_norm 𝕜,
set C := (1 + ∥f 0∥) * univ.prod (λ(i : ι), δ⁻¹ * ∥c∥),
have C_pos : 0 < C :=
mul_pos (lt_of_lt_of_le zero_lt_one (by simp))
(prod_pos (λi hi, mul_pos (inv_pos δ_pos) (lt_of_le_of_lt zero_le_one hc))),
refine ⟨C, C_pos, λm, _⟩,
/- Given a general point `m`, rescale each coordinate to bring it to `[δ/∥c∥, δ]` by multiplication
by a power of a scalar `c` with norm `∥c∥ > 1`.-/
by_cases h : ∃i, m i = 0,
{ rcases h with ⟨i, hi⟩,
rw [f.map_coord_zero i hi, _root_.norm_zero],
exact mul_nonneg' (le_of_lt C_pos) (prod_nonneg (λi hi, norm_nonneg _)) },
{ push_neg at h,
have : ∀i, ∃d:𝕜, d ≠ 0 ∧ ∥d • m i∥ ≤ δ ∧ (δ/∥c∥ ≤ ∥d • m i∥) ∧ (∥d∥⁻¹ ≤ δ⁻¹ * ∥c∥ * ∥m i∥) :=
λi, rescale_to_shell hc δ_pos (h i),
choose d hd using this,
have A : 0 ≤ 1 + ∥f 0∥ := add_nonneg zero_le_one (norm_nonneg _),
have B : ∀ (i : ι), i ∈ univ → 0 ≤ ∥d i∥⁻¹ := λi hi, by simp,
-- use the bound on `f` on the ball of size `δ` to conclude.
calc
∥f m∥ = ∥f (λi, (d i)⁻¹ • (d i • m i))∥ :
by { unfold_coes, congr, ext i, rw [← mul_smul, inv_mul_cancel (hd i).1, one_smul] }
... = ∥univ.prod (λi, (d i)⁻¹) • f (λi, d i • m i)∥ : by rw f.map_smul_univ
... = univ.prod (λi, ∥d i∥⁻¹) * ∥f (λi, d i • m i)∥ :
by { rw [norm_smul, normed_field.norm_prod], congr, ext i, rw normed_field.norm_inv }
... ≤ univ.prod (λi, ∥d i∥⁻¹) * (1 + ∥f 0∥) :
mul_le_mul_of_nonneg_left (H ((pi_norm_le_iff (le_of_lt δ_pos)).2 (λi, (hd i).2.1)))
(prod_nonneg B)
... ≤ univ.prod (λi, δ⁻¹ * ∥c∥ * ∥m i∥) * (1 + ∥f 0∥) :
mul_le_mul_of_nonneg_right (prod_le_prod B (λi hi, (hd i).2.2.2)) A
... = univ.prod (λ(i : ι), δ⁻¹ * ∥c∥) * univ.prod (λi, ∥m i∥) * (1 + ∥f 0∥) :
by rw prod_mul_distrib
... = C * univ.prod (λ (i : ι), ∥m i∥) :
by rw [mul_comm, ← mul_assoc] }
end
/-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂`
using the multilinearity. Here, we give a precise but hard to use version. See
`norm_image_sub_le_of_bound` for a less precise but more usable version. The bound reads
`∥f m - f m'∥ ≤ C * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`,
where the other terms in the sum are the same products where `1` is replaced by any `i`. -/
lemma norm_image_sub_le_of_bound' {C : ℝ} (hC : 0 ≤ C)
(H : ∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) (m₁ m₂ : Πi, E₁ i) :
∥f m₁ - f m₂∥ ≤
C * univ.sum (λi, univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥)) :=
begin
have A : ∀(s : finset ι), ∥f m₁ - f (s.piecewise m₂ m₁)∥
≤ C * s.sum (λi, univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥)),
{ refine finset.induction (by simp) _,
assume i s his Hrec,
have I : ∥f (s.piecewise m₂ m₁) - f ((insert i s).piecewise m₂ m₁)∥
≤ C * univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥),
{ have A : ((insert i s).piecewise m₂ m₁)
= function.update (s.piecewise m₂ m₁) i (m₂ i) := s.piecewise_insert _ _ _,
have B : s.piecewise m₂ m₁ = function.update (s.piecewise m₂ m₁) i (m₁ i),
{ ext j,
by_cases h : j = i,
{ rw h, simp [his] },
{ simp [h] } },
rw [B, A, ← f.map_sub],
apply le_trans (H _) (mul_le_mul_of_nonneg_left _ hC),
refine prod_le_prod (λj hj, norm_nonneg _) (λj hj, _),
by_cases h : j = i,
{ rw h, simp },
{ by_cases h' : j ∈ s;
simp [h', h, le_refl] } },
calc ∥f m₁ - f ((insert i s).piecewise m₂ m₁)∥ ≤
∥f m₁ - f (s.piecewise m₂ m₁)∥ + ∥f (s.piecewise m₂ m₁) - f ((insert i s).piecewise m₂ m₁)∥ :
by { rw [← dist_eq_norm, ← dist_eq_norm, ← dist_eq_norm], exact dist_triangle _ _ _ }
... ≤ C * s.sum (λi, univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥))
+ C * univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) :
add_le_add Hrec I
... = C * (insert i s).sum (λi, univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥)) :
by simp [his, add_comm, left_distrib] },
convert A univ,
simp
end
/-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂`
using the multilinearity. Here, we give a usable but not very precise version. See
`norm_image_sub_le_of_bound'` for a more precise but less usable version. The bound is
`∥f m - f m'∥ ≤ C * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`. -/
lemma norm_image_sub_le_of_bound {C : ℝ} (hC : 0 ≤ C)
(H : ∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) (m₁ m₂ : Πi, E₁ i) :
∥f m₁ - f m₂∥ ≤ C * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ :=
begin
have A : ∀ (i : ι), univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥)
≤ ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1),
{ assume i,
calc univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥)
≤ (univ : finset ι).prod (function.update (λ j, max ∥m₁∥ ∥m₂∥) i (∥m₁ - m₂∥)) :
begin
apply prod_le_prod,
{ assume j hj, by_cases h : j = i; simp [h, norm_nonneg] },
{ assume j hj,
by_cases h : j = i,
{ rw h, simp, exact norm_le_pi_norm (m₁ - m₂) i },
{ simp [h, max_le_max, norm_le_pi_norm] } }
end
... = ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) :
by { rw prod_update_of_mem (finset.mem_univ _), simp [card_univ_diff] } },
calc
∥f m₁ - f m₂∥
≤ C * univ.sum (λi, univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥)) :
f.norm_image_sub_le_of_bound' hC H m₁ m₂
... ≤ C * univ.sum (λ (i : ι), ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1)) :
mul_le_mul_of_nonneg_left (sum_le_sum (λi hi, A i)) hC
... = C * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ :
by { rw [sum_const, card_univ, add_monoid.smul_eq_mul], ring }
end
/-- If a multilinear map satisfies an inequality `∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)`, then it is
continuous. -/
theorem continuous_of_bound (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) :
continuous f :=
begin
let D := max C 1,
have D_pos : 0 ≤ D := le_trans zero_le_one (le_max_right _ _),
replace H : ∀ m, ∥f m∥ ≤ D * univ.prod (λi, ∥m i∥),
{ assume m,
apply le_trans (H m) (mul_le_mul_of_nonneg_right (le_max_left _ _) _),
exact prod_nonneg (λ(i : ι) hi, norm_nonneg (m i)) },
refine continuous_iff_continuous_at.2 (λm, _),
refine continuous_at_of_locally_lipschitz zero_lt_one
(D * (fintype.card ι) * (∥m∥ + 1) ^ (fintype.card ι - 1)) (λm' h', _),
rw [dist_eq_norm, dist_eq_norm],
have : 0 ≤ (max ∥m'∥ ∥m∥), by simp,
have : (max ∥m'∥ ∥m∥) ≤ ∥m∥ + 1,
by simp [zero_le_one, norm_le_of_mem_closed_ball (le_of_lt h'), -add_comm],
calc
∥f m' - f m∥
≤ D * (fintype.card ι) * (max ∥m'∥ ∥m∥) ^ (fintype.card ι - 1) * ∥m' - m∥ :
f.norm_image_sub_le_of_bound D_pos H m' m
... ≤ D * (fintype.card ι) * (∥m∥ + 1) ^ (fintype.card ι - 1) * ∥m' - m∥ :
by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul_of_nonneg_left, mul_nonneg',
norm_nonneg, nat.cast_nonneg, pow_le_pow_of_le_left]
end
/-- Constructing a continuous multilinear map from a multilinear map satisfying a boundedness
condition. -/
def mk_continuous (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) :
continuous_multilinear_map 𝕜 E₁ E₂ :=
{ cont := f.continuous_of_bound C H, ..f }
end multilinear_map
/-!
### Continuous multilinear maps
We define the norm `∥f∥` of a continuous multilinear map `f` in finitely many variables as the
smallest number such that `∥f m∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥)` for all `m`. We show that this
defines a normed space structure on `continuous_multilinear_map 𝕜 E₁ E₂`.
-/
namespace continuous_multilinear_map
variables (c : 𝕜) (f g : continuous_multilinear_map 𝕜 E₁ E₂) (m : Πi, E₁ i)
theorem bound : ∃ (C : ℝ), 0 < C ∧ (∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) :=
f.to_multilinear_map.exists_bound_of_continuous f.2
open real
/-- The operator norm of a continuous multilinear map is the inf of all its bounds. -/
def op_norm := Inf {c | 0 ≤ (c : ℝ) ∧ ∀ m, ∥f m∥ ≤ c * finset.univ.prod (λi, ∥m i∥)}
instance has_op_norm : has_norm (continuous_multilinear_map 𝕜 E₁ E₂) := ⟨op_norm⟩
-- So that invocations of `real.Inf_le` make sense: we show that the set of
-- bounds is nonempty and bounded below.
lemma bounds_nonempty {f : continuous_multilinear_map 𝕜 E₁ E₂} :
∃ c, c ∈ {c | 0 ≤ c ∧ ∀ m, ∥f m∥ ≤ c * finset.univ.prod (λi, ∥m i∥)} :=
let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩
lemma bounds_bdd_below {f : continuous_multilinear_map 𝕜 E₁ E₂} :
bdd_below {c | 0 ≤ c ∧ ∀ m, ∥f m∥ ≤ c * finset.univ.prod (λi, ∥m i∥)} :=
⟨0, λ _ ⟨hn, _⟩, hn⟩
lemma op_norm_nonneg : 0 ≤ ∥f∥ :=
lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx)
/-- The fundamental property of the operator norm of a continuous multilinear map:
`∥f m∥` is bounded by `∥f∥` times the product of the `∥m i∥`. -/
theorem le_op_norm : ∥f m∥ ≤ ∥f∥ * finset.univ.prod (λi, ∥m i∥) :=
begin
have A : 0 ≤ finset.univ.prod (λi, ∥m i∥) := prod_nonneg (λj hj, norm_nonneg _),
by_cases h : finset.univ.prod (λi, ∥m i∥) = 0,
{ rcases prod_eq_zero_iff.1 h with ⟨i, _, hi⟩,
rw norm_eq_zero at hi,
have : f m = 0 := f.map_coord_zero i hi,
rw [this, norm_zero],
exact mul_nonneg' (op_norm_nonneg f) A },
{ have hlt : 0 < finset.univ.prod (λi, ∥m i∥) := lt_of_le_of_ne A (ne.symm h),
exact le_mul_of_div_le hlt ((le_Inf _ bounds_nonempty bounds_bdd_below).2
(λ c ⟨_, hc⟩, div_le_of_le_mul hlt (begin rw mul_comm, apply hc, end))) }
end
lemma ratio_le_op_norm : ∥f m∥ / finset.univ.prod (λi, ∥m i∥) ≤ ∥f∥ :=
begin
have : 0 ≤ finset.univ.prod (λi, ∥m i∥) := prod_nonneg (λj hj, norm_nonneg _),
cases eq_or_lt_of_le this with h h,
{ simp [h.symm, op_norm_nonneg f] },
{ rw div_le_iff h,
exact le_op_norm f m }
end
/-- The image of the unit ball under a continuous multilinear map is bounded. -/
lemma unit_le_op_norm (h : ∥m∥ ≤ 1) : ∥f m∥ ≤ ∥f∥ :=
calc
∥f m∥ ≤ ∥f∥ * finset.univ.prod (λi, ∥m i∥) : f.le_op_norm m
... ≤ ∥f∥ * finset.univ.prod (λ (i : ι), 1) :
mul_le_mul_of_nonneg_left (prod_le_prod (λi hi, norm_nonneg _) (λi hi, le_trans (norm_le_pi_norm _ _) h))
(op_norm_nonneg f)
... = ∥f∥ : by simp
/-- If one controls the norm of every `f x`, then one controls the norm of `f`. -/
lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ m, ∥f m∥ ≤ M * finset.univ.prod (λi, ∥m i∥)) :
∥f∥ ≤ M :=
Inf_le _ bounds_bdd_below ⟨hMp, hM⟩
/-- The operator norm satisfies the triangle inequality. -/
theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ :=
Inf_le _ bounds_bdd_below
⟨add_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw add_mul,
exact norm_add_le_of_le (le_op_norm _ _) (le_op_norm _ _) }⟩
/-- A continuous linear map is zero iff its norm vanishes. -/
theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 :=
begin
split,
{ assume h,
ext m,
simpa [h, norm_le_zero_iff.symm] using f.le_op_norm m },
{ assume h,
apply le_antisymm (op_norm_le_bound f (le_refl _) (λm, _)) (op_norm_nonneg _),
rw h,
simp }
end
@[simp] lemma norm_zero : ∥(0 : continuous_multilinear_map 𝕜 E₁ E₂)∥ = 0 :=
by rw op_norm_zero_iff
/-- The operator norm is homogeneous. -/
lemma op_norm_smul : ∥c • f∥ = ∥c∥ * ∥f∥ :=
le_antisymm
(Inf_le _ bounds_bdd_below
⟨mul_nonneg (norm_nonneg _) (op_norm_nonneg _), λ _,
begin
erw [norm_smul, mul_assoc],
exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _)
end⟩)
(lb_le_Inf _ bounds_nonempty (λ _ ⟨hn, hc⟩,
(or.elim (lt_or_eq_of_le (norm_nonneg c))
(λ hlt,
begin
rw mul_comm,
exact mul_le_of_le_div hlt (Inf_le _ bounds_bdd_below
⟨div_nonneg hn hlt, λ _,
(by { rw div_mul_eq_mul_div, exact le_div_of_mul_le hlt
(by { rw [ mul_comm, ←norm_smul ], exact hc _ }) })⟩)
end)
(λ heq, by { rw [←heq, zero_mul], exact hn }))))
lemma op_norm_neg : ∥-f∥ = ∥f∥ := calc
∥-f∥ = ∥(-1:𝕜) • f∥ : by rw neg_one_smul
... = ∥(-1:𝕜)∥ * ∥f∥ : by rw op_norm_smul
... = ∥f∥ : by simp
/-- Continuous multilinear maps themselves form a normed space with respect to
the operator norm. -/
instance to_normed_group : normed_group (continuous_multilinear_map 𝕜 E₁ E₂) :=
normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩
instance to_normed_space : normed_space 𝕜 (continuous_multilinear_map 𝕜 E₁ E₂) :=
⟨op_norm_smul⟩
/-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, precise version.
For a less precise but more usable version, see `norm_image_sub_le_of_bound`. The bound reads
`∥f m - f m'∥ ≤ ∥f∥ * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`,
where the other terms in the sum are the same products where `1` is replaced by any `i`.-/
lemma norm_image_sub_le_of_bound' (m₁ m₂ : Πi, E₁ i) :
∥f m₁ - f m₂∥ ≤
∥f∥ * univ.sum (λi, univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥)) :=
f.to_multilinear_map.norm_image_sub_le_of_bound' (norm_nonneg _) f.le_op_norm _ _
/-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, less precise
version. For a more precise but less usable version, see `norm_image_sub_le_of_bound'`.
The bound is `∥f m - f m'∥ ≤ ∥f∥ * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`.-/
lemma norm_image_sub_le_of_bound (m₁ m₂ : Πi, E₁ i) :
∥f m₁ - f m₂∥ ≤ ∥f∥ * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ :=
f.to_multilinear_map.norm_image_sub_le_of_bound (norm_nonneg _) f.le_op_norm _ _
/-- Applying a multilinear map to a vector is continuous in both coordinates. -/
lemma continuous_eval :
continuous (λ (p : (continuous_multilinear_map 𝕜 E₁ E₂ × (Πi, E₁ i))), p.1 p.2) :=
begin
apply continuous_iff_continuous_at.2 (λp, _),
apply continuous_at_of_locally_lipschitz zero_lt_one
((∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) + univ.prod (λi, ∥p.2 i∥))
(λq hq, _),
have : 0 ≤ (max ∥q.2∥ ∥p.2∥), by simp,
have : 0 ≤ ∥p∥ + 1, by simp [le_trans zero_le_one],
have A : ∥q∥ ≤ ∥p∥ + 1 := norm_le_of_mem_closed_ball (le_of_lt hq),
have : (max ∥q.2∥ ∥p.2∥) ≤ ∥p∥ + 1 :=
le_trans (max_le_max (norm_snd_le q) (norm_snd_le p)) (by simp [A, -add_comm, zero_le_one]),
have : ∀ (i : ι), i ∈ univ → 0 ≤ ∥p.2 i∥ := λ i hi, norm_nonneg _,
calc dist (q.1 q.2) (p.1 p.2)
≤ dist (q.1 q.2) (q.1 p.2) + dist (q.1 p.2) (p.1 p.2) : dist_triangle _ _ _
... = ∥q.1 q.2 - q.1 p.2∥ + ∥q.1 p.2 - p.1 p.2∥ : by rw [dist_eq_norm, dist_eq_norm]
... ≤ ∥q.1∥ * (fintype.card ι) * (max ∥q.2∥ ∥p.2∥) ^ (fintype.card ι - 1) * ∥q.2 - p.2∥
+ ∥q.1 - p.1∥ * univ.prod (λi, ∥p.2 i∥) :
add_le_add (norm_image_sub_le_of_bound _ _ _) ((q.1 - p.1).le_op_norm p.2)
... ≤ (∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) * ∥q - p∥
+ ∥q - p∥ * univ.prod (λi, ∥p.2 i∥) :
by apply_rules [add_le_add, mul_le_mul, le_refl, le_trans (norm_fst_le q) A, nat.cast_nonneg,
mul_nonneg', pow_le_pow_of_le_left, pow_nonneg, norm_snd_le (q - p), norm_nonneg,
norm_fst_le (q - p), norm_nonneg, prod_nonneg]
... = ((∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1)
+ univ.prod (λi, ∥p.2 i∥)) * dist q p : by { rw dist_eq_norm, ring }
end
end continuous_multilinear_map
/-- If a continuous multilinear map is constructed from a multilinear map via the constructor
`mk_continuous`, then its norm is bounded by the bound given to the constructor if it is
nonnegative. -/
lemma multilinear_map.mk_continuous_norm_le (f : multilinear_map 𝕜 E₁ E₂) {C : ℝ} (hC : 0 ≤ C)
(H : ∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) : ∥f.mk_continuous C H∥ ≤ C :=
continuous_multilinear_map.op_norm_le_bound _ hC (λm, H m)
namespace continuous_multilinear_map
/- The next two instances are not found automatically. Register them explicitly.
TODO: understand why, and fix. -/
instance : normed_group (continuous_multilinear_map 𝕜 (λ (i : ι), 𝕜) E₂) :=
@continuous_multilinear_map.to_normed_group 𝕜 ι (λ (i : ι), 𝕜) E₂ _ _ _ _ _ _ _
instance : normed_space 𝕜 (continuous_multilinear_map 𝕜 (λ (i : ι), 𝕜) E₂) :=
@continuous_multilinear_map.to_normed_space 𝕜 ι (λ (i : ι), 𝕜) E₂ _ _ _ _ _ _ _
variables (𝕜 ι)
/-- The canonical continuous multilinear map on `𝕜^ι`, associating to `m` the product of all the
`m i` (multiplied by a fixed reference element `z` in the target module) -/
protected def mk_pi_field (z : E₂) : continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂ :=
@multilinear_map.mk_continuous 𝕜 ι (λ(i : ι), 𝕜) E₂ _ _ _ _ _ _ _
(multilinear_map.mk_pi_ring 𝕜 ι z) (∥z∥)
(λ m, by simp only [multilinear_map.mk_pi_ring_apply, norm_smul, normed_field.norm_prod, mul_comm])
variables {𝕜 ι}
@[simp] lemma mk_pi_field_apply (z : E₂) (m : ι → 𝕜) :
(continuous_multilinear_map.mk_pi_field 𝕜 ι z : (ι → 𝕜) → E₂) m = finset.univ.prod m • z := rfl
lemma mk_pi_ring_apply_one_eq_self (f : continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂) :
continuous_multilinear_map.mk_pi_field 𝕜 ι (f (λi, 1)) = f :=
begin
ext m,
have : m = (λi, m i • 1), by { ext j, simp },
conv_rhs { rw [this, f.map_smul_univ] },
refl
end
variables (𝕜 ι E₂)
/-- Continuous multilinear maps on `𝕜^n` with values in `E₂` are in bijection with `E₂`, as such a
continuous multilinear map is completely determined by its value on the constant vector made of
ones. We register this bijection as a linear equivalence in
`continuous_multilinear_map.pi_field_equiv_aux`. The continuous linear equivalence is
`continuous_multilinear_map.pi_field_equiv`. -/
protected def pi_field_equiv_aux : E₂ ≃ₗ[𝕜] (continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂) :=
{ to_fun := λ z, continuous_multilinear_map.mk_pi_field 𝕜 ι z,
inv_fun := λ f, f (λi, 1),
add := λ z z', by { ext m, simp [smul_add] },
smul := λ c z, by { ext m, simp [smul_smul, mul_comm] },
left_inv := λ z, by simp,
right_inv := λ f, f.mk_pi_ring_apply_one_eq_self }
/-- Continuous multilinear maps on `𝕜^n` with values in `E₂` are in bijection with `E₂`, as such a
continuous multilinear map is completely determined by its value on the constant vector made of
ones. We register this bijection as a continuous linear equivalence in
`continuous_multilinear_map.pi_field_equiv`. -/
protected def pi_field_equiv : E₂ ≃L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂) :=
{ continuous_to_fun := begin
refine (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂).to_linear_map.continuous_of_bound
(1 : ℝ) (λz, _),
rw one_mul,
change ∥continuous_multilinear_map.mk_pi_field 𝕜 ι z∥ ≤ ∥z∥,
exact multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _
end,
continuous_inv_fun := begin
refine (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂).symm.to_linear_map.continuous_of_bound
(1 : ℝ) (λf, _),
rw one_mul,
change ∥f (λi, 1)∥ ≤ ∥f∥,
apply @continuous_multilinear_map.unit_le_op_norm 𝕜 ι (λ (i : ι), 𝕜) E₂ _ _ _ _ _ _ _ f,
simp [pi_norm_le_iff zero_le_one, le_refl]
end,
.. continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂ }
end continuous_multilinear_map
section currying
/-!
### Currying
We associate to a continuous multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two
curried functions, named `f.curry_left` (which is a continuous linear map on `E 0` taking values
in continuous multilinear maps in `n` variables) and `f.curry_right` (which is a continuous
multilinear map in `n` variables taking values in continuous linear maps on `E (last n)`).
The inverse operations are called `uncurry_left` and `uncurry_right`.
We also register continuous linear equiv versions of these correspondences, in
`continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`.
-/
set_option class.instance_max_depth 360
open fin function
lemma continuous_linear_map.norm_map_tail_le
(f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) (m : Πi, E i) :
∥f (m 0) (tail m)∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥) :=
calc
∥f (m 0) (tail m)∥ ≤ ∥f (m 0)∥ * univ.prod (λi, ∥(tail m) i∥) : (f (m 0)).le_op_norm _
... ≤ (∥f∥ * ∥m 0∥) * univ.prod (λi, ∥(tail m) i∥) :
mul_le_mul_of_nonneg_right (f.le_op_norm _) (prod_nonneg (λi hi, norm_nonneg _))
... = ∥f∥ * (∥m 0∥ * univ.prod (λi, ∥(tail m) i∥)) : by ring
... = ∥f∥ * univ.prod (λi, ∥m i∥) : by { rw prod_univ_succ, refl }
lemma continuous_multilinear_map.norm_map_init_le
(f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) (m : Πi, E i) :
∥f (init m) (m (last n))∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥) :=
calc
∥f (init m) (m (last n))∥ ≤ ∥f (init m)∥ * ∥m (last n)∥ : (f (init m)).le_op_norm _
... ≤ (∥f∥ * univ.prod (λi, ∥(init m) i∥)) * ∥m (last n)∥ :
mul_le_mul_of_nonneg_right (f.le_op_norm _) (norm_nonneg _)
... = ∥f∥ * (univ.prod (λi, ∥(init m) i∥) * ∥m (last n)∥) : mul_assoc _ _ _
... = ∥f∥ * univ.prod (λi, ∥m i∥) : by { rw prod_univ_cast_succ, refl }
lemma continuous_multilinear_map.norm_map_cons_le
(f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (m : Π(i : fin n), E i.succ) :
∥f (cons x m)∥ ≤ ∥f∥ * ∥x∥ * univ.prod (λi, ∥m i∥) :=
calc
∥f (cons x m)∥ ≤ ∥f∥ * univ.prod (λ(i : fin n.succ), ∥cons x m i∥) : f.le_op_norm _
... = (∥f∥ * ∥x∥) * univ.prod (λi, ∥m i∥) : by { rw prod_univ_succ, simp [mul_assoc] }
lemma continuous_multilinear_map.norm_map_snoc_le
(f : continuous_multilinear_map 𝕜 E E₂) (m : Π(i : fin n), E i.cast_succ) (x : E (last n)) :
∥f (snoc m x)∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥) * ∥x∥ :=
calc
∥f (snoc m x)∥ ≤ ∥f∥ * univ.prod (λ(i : fin n.succ), ∥snoc m x i∥) : f.le_op_norm _
... = ∥f∥ * univ.prod (λi, ∥m i∥) * ∥x∥ : by { rw prod_univ_cast_succ, simp [mul_assoc] }
/-! #### Left currying -/
/-- Given a continuous linear map `f` from `E 0` to continuous multilinear maps on `n` variables,
construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating
the variables, given by `m ↦ f (m 0) (tail m)`-/
def continuous_linear_map.uncurry_left
(f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) :
continuous_multilinear_map 𝕜 E E₂ :=
(@linear_map.uncurry_left 𝕜 n E E₂ _ _ _ _ _
(continuous_multilinear_map.to_multilinear_map_linear.comp f.to_linear_map)).mk_continuous
(∥f∥) (λm, continuous_linear_map.norm_map_tail_le f m)
@[simp] lemma continuous_linear_map.uncurry_left_apply
(f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) (m : Πi, E i) :
f.uncurry_left m = f (m 0) (tail m) := rfl
/-- Given a continuous multilinear map `f` in `n+1` variables, split the first variable to obtain
a continuous linear map into continuous multilinear maps in `n` variables, given by
`x ↦ (m ↦ f (cons x m))`. -/
def continuous_multilinear_map.curry_left
(f : continuous_multilinear_map 𝕜 E E₂) :
E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂) :=
linear_map.mk_continuous
{ -- define a linear map into `n` continuous multilinear maps from an `n+1` continuous multilinear map
to_fun := λx, (f.to_multilinear_map.curry_left x).mk_continuous (∥f∥ * ∥x∥) (f.norm_map_cons_le x),
add := λx y, by { ext m, exact f.cons_add m x y },
smul := λc x, by { ext m, exact f.cons_smul m c x } }
-- then register its continuity thanks to its boundedness properties.
(∥f∥) (λx, multilinear_map.mk_continuous_norm_le _ (mul_nonneg' (norm_nonneg _) (norm_nonneg _)) _)
@[simp] lemma continuous_multilinear_map.curry_left_apply
(f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (m : Π(i : fin n), E i.succ) :
f.curry_left x m = f (cons x m) := rfl
@[simp] lemma continuous_linear_map.curry_uncurry_left
(f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) :
f.uncurry_left.curry_left = f :=
begin
ext m x,
simp only [tail_cons, continuous_linear_map.uncurry_left_apply,
continuous_multilinear_map.curry_left_apply],
rw cons_zero
end
@[simp] lemma continuous_multilinear_map.uncurry_curry_left
(f : continuous_multilinear_map 𝕜 E E₂) : f.curry_left.uncurry_left = f :=
by { ext m, simp }
@[simp] lemma continuous_multilinear_map.curry_left_norm
(f : continuous_multilinear_map 𝕜 E E₂) : ∥f.curry_left∥ = ∥f∥ :=
begin
apply le_antisymm (linear_map.mk_continuous_norm_le _ (norm_nonneg _) _),
have : ∥f.curry_left.uncurry_left∥ ≤ ∥f.curry_left∥ :=
multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _,
simpa
end
@[simp] lemma continuous_linear_map.uncurry_left_norm
(f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) :
∥f.uncurry_left∥ = ∥f∥ :=
begin
apply le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _),
have : ∥f.uncurry_left.curry_left∥ ≤ ∥f.uncurry_left∥ :=
linear_map.mk_continuous_norm_le _ (norm_nonneg _) _,
simpa
end
variables (𝕜 E E₂)
/-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to
the space of continuous linear maps from `E 0` to the space of continuous multilinear maps on
`Π(i : fin n), E i.succ `, by separating the first variable. We register this isomorphism as a
linear isomorphism in `continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂`.
The algebraic version (without continuity assumption on the maps) is
`multilinear_curry_left_equiv 𝕜 E E₂`, and the topological isomorphism (registering
additionally that the isomorphism is continuous) is
`continuous_multilinear_curry_left_equiv 𝕜 E E₂`.
The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these
unless you need the full framework of linear equivs. -/
def continuous_multilinear_curry_left_equiv_aux :
(E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) ≃ₗ[𝕜]
(continuous_multilinear_map 𝕜 E E₂) :=
{ to_fun := continuous_linear_map.uncurry_left,
add := λf₁ f₂, by { ext m, refl },
smul := λc f, by { ext m, refl },
inv_fun := continuous_multilinear_map.curry_left,
left_inv := continuous_linear_map.curry_uncurry_left,
right_inv := continuous_multilinear_map.uncurry_curry_left }
/-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to
the space of continuous linear maps from `E 0` to the space of continuous multilinear maps on
`Π(i : fin n), E i.succ `, by separating the first variable. We register this isomorphism in
`continuous_multilinear_curry_left_equiv 𝕜 E E₂`. The algebraic version (without topology) is given
in `multilinear_curry_left_equiv 𝕜 E E₂`.
The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these
unless you need the full framework of continuous linear equivs. -/
def continuous_multilinear_curry_left_equiv :
(E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) ≃L[𝕜]
(continuous_multilinear_map 𝕜 E E₂) :=
{ continuous_to_fun := begin
refine (continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂).to_linear_map.continuous_of_bound
(1 : ℝ) (λf, le_of_eq _),
rw one_mul,
exact f.uncurry_left_norm
end,
continuous_inv_fun := begin
refine (continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂).symm.to_linear_map.continuous_of_bound
(1 : ℝ) (λf, le_of_eq _),
rw one_mul,
exact f.curry_left_norm
end,
.. continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂ }
variables {𝕜 E E₂}
@[simp] lemma continuous_multilinear_curry_left_equiv_apply
(f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) (v : Π i, E i) :
continuous_multilinear_curry_left_equiv 𝕜 E E₂ f v = f (v 0) (tail v) := rfl
@[simp] lemma continuous_multilinear_curry_left_equiv_symm_apply
(f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (v : Π (i : fin n), E i.succ) :
(continuous_multilinear_curry_left_equiv 𝕜 E E₂).symm f x v = f (cons x v) := rfl
/-! #### Right currying -/
/-- Given a continuous linear map `f` from continuous multilinear maps on `n` variables to
continuous linear maps on `E 0`, construct the corresponding continuous multilinear map on `n+1`
variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`. -/
def continuous_multilinear_map.uncurry_right
(f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) :
continuous_multilinear_map 𝕜 E E₂ :=
let f' : multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →ₗ[𝕜] E₂) :=
{ to_fun := λ m, (f m).to_linear_map,
add := λ m i x y, by { simp, refl },
smul := λ m i c x, by { simp, refl } } in
(@multilinear_map.uncurry_right 𝕜 n E E₂ _ _ _ _ _ f').mk_continuous
(∥f∥) (λm, f.norm_map_init_le m)
@[simp] lemma continuous_multilinear_map.uncurry_right_apply
(f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) (m : Πi, E i) :
f.uncurry_right m = f (init m) (m (last n)) := rfl
/-- Given a continuous multilinear map `f` in `n+1` variables, split the last variable to obtain
a continuous multilinear map in `n` variables into continuous linear maps, given by
`m ↦ (x ↦ f (snoc m x))`. -/
def continuous_multilinear_map.curry_right
(f : continuous_multilinear_map 𝕜 E E₂) :
continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂) :=
let f' : multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂) :=
{ to_fun := λm, (f.to_multilinear_map.curry_right m).mk_continuous
(∥f∥ * univ.prod (λ(i : fin n), ∥m i∥)) $ λx, f.norm_map_snoc_le m x,
add := λ m i x y, by { simp, refl },
smul := λ m i c x, by { simp, refl } } in
f'.mk_continuous (∥f∥) (λm, linear_map.mk_continuous_norm_le _
(mul_nonneg' (norm_nonneg _) (prod_nonneg (λj hj, norm_nonneg _))) _)
@[simp] lemma continuous_multilinear_map.curry_right_apply
(f : continuous_multilinear_map 𝕜 E E₂) (m : Π(i : fin n), E i.cast_succ) (x : E (last n)) :
f.curry_right m x = f (snoc m x) := rfl
@[simp] lemma continuous_multilinear_map.curry_uncurry_right
(f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) :
f.uncurry_right.curry_right = f :=
begin
ext m x,
simp only [snoc_last, continuous_multilinear_map.curry_right_apply,
continuous_multilinear_map.uncurry_right_apply],
rw init_snoc
end
@[simp] lemma continuous_multilinear_map.uncurry_curry_right
(f : continuous_multilinear_map 𝕜 E E₂) : f.curry_right.uncurry_right = f :=
by { ext m, simp }
@[simp] lemma continuous_multilinear_map.curry_right_norm
(f : continuous_multilinear_map 𝕜 E E₂) : ∥f.curry_right∥ = ∥f∥ :=
begin
refine le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _) _,
have : ∥f.curry_right.uncurry_right∥ ≤ ∥f.curry_right∥ :=
multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _,
simpa
end
@[simp] lemma continuous_multilinear_map.uncurry_right_norm
(f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) :
∥f.uncurry_right∥ = ∥f∥ :=
begin
refine le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _) _,
have : ∥f.uncurry_right.curry_right∥ ≤ ∥f.uncurry_right∥ :=
multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _,
simpa
end
variables (𝕜 E E₂)
/-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to
the space of continuous multilinear maps on `Π(i : fin n), E i.cast_succ` with values in the space
of continuous linear maps on `E (last n)`, by separating the last variable. We register this
isomorphism as a linear equiv in `continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂`.
The algebraic version (without continuity assumption on the maps) is
`multilinear_curry_right_equiv 𝕜 E E₂`, and the topological isomorphism (registering
additionally that the isomorphism is continuous) is
`continuous_multilinear_curry_right_equiv 𝕜 E E₂`.
The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these
unless you need the full framework of linear equivs. -/
def continuous_multilinear_curry_right_equiv_aux :
(continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) ≃ₗ[𝕜]
(continuous_multilinear_map 𝕜 E E₂) :=
{ to_fun := continuous_multilinear_map.uncurry_right,
add := λf₁ f₂, by { ext m, refl },
smul := λc f, by { ext m, refl },
inv_fun := continuous_multilinear_map.curry_right,
left_inv := continuous_multilinear_map.curry_uncurry_right,
right_inv := continuous_multilinear_map.uncurry_curry_right }
/-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to
the space of continuous multilinear maps on `Π(i : fin n), E i.cast_succ` with values in the space
of continuous linear maps on `E (last n)`, by separating the last variable. We register this
isomorphism as a continuous linear equiv in `continuous_multilinear_curry_right_equiv 𝕜 E E₂`.
The algebraic version (without topology) is given in `multilinear_curry_right_equiv 𝕜 E E₂`.
The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these
unless you need the full framework of continuous linear equivs. -/
def continuous_multilinear_curry_right_equiv :
(continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) ≃L[𝕜]
(continuous_multilinear_map 𝕜 E E₂) :=
{ continuous_to_fun := begin
refine (continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂).to_linear_map.continuous_of_bound
(1 : ℝ) (λf, le_of_eq _),
rw one_mul,
exact f.uncurry_right_norm
end,
continuous_inv_fun := begin
refine (continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂).symm.to_linear_map.continuous_of_bound
(1 : ℝ) (λf, le_of_eq _),
rw one_mul,
exact f.curry_right_norm
end,
.. continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂ }
variables {𝕜 G E E₂}
@[simp] lemma continuous_multilinear_curry_right_equiv_apply
(f : (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)))
(v : Π i, E i) :
(continuous_multilinear_curry_right_equiv 𝕜 E E₂) f v = f (init v) (v (last n)) := rfl
@[simp] lemma continuous_multilinear_curry_right_equiv_symm_apply
(f : continuous_multilinear_map 𝕜 E E₂)
(v : Π (i : fin n), E i.cast_succ) (x : E (last n)) :
(continuous_multilinear_curry_right_equiv 𝕜 E E₂).symm f v x = f (snoc v x) := rfl
/-!
#### Currying with `0` variables
The space of multilinear maps with `0` variables is trivial: such a multilinear map is just an
arbitrary constant (note that multilinear maps in `0` variables need not map `0` to `0`!).
Therefore, the space of continuous multilinear maps on `(fin 0) → G` with values in `E₂` is
isomorphic (and even isometric) to `E₂`. As this is the zeroth step in the construction of iterated
derivatives, we register this isomorphism. -/
variables {𝕜 G E₂}
/-- Associating to a continuous multilinear map in `0` variables the unique value it takes. -/
def continuous_multilinear_map.uncurry0
(f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : E₂ := f 0
variables (𝕜 G)
/-- Associating to an element `x` of a vector space `E₂` the continuous multilinear map in `0`
variables taking the (unique) value `x` -/
def continuous_multilinear_map.curry0 (x : E₂) :
continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂ :=
{ to_fun := λm, x,
add := λ m i, fin.elim0 i,
smul := λ m i, fin.elim0 i,
cont := continuous_const }
variable {G}
@[simp] lemma continuous_multilinear_map.curry0_apply (x : E₂) (m : (fin 0) → G) :
(continuous_multilinear_map.curry0 𝕜 G x : ((fin 0) → G) → E₂) m = x := rfl
variable {𝕜}
@[simp] lemma continuous_multilinear_map.uncurry0_apply
(f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) :
f.uncurry0 = f 0 := rfl
@[simp] lemma continuous_multilinear_map.apply_zero_curry0
(f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) {x : fin 0 → G} :
continuous_multilinear_map.curry0 𝕜 G (f x) = f :=
by { ext m, simp [(subsingleton.elim _ _ : x = m)] }
lemma continuous_multilinear_map.uncurry0_curry0
(f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) :
continuous_multilinear_map.curry0 𝕜 G (f.uncurry0) = f :=
by simp
variables (𝕜 G)
@[simp] lemma continuous_multilinear_map.curry0_uncurry0 (x : E₂) :
(continuous_multilinear_map.curry0 𝕜 G x).uncurry0 = x := rfl
@[simp] lemma continuous_multilinear_map.uncurry0_norm (x : E₂) :
∥continuous_multilinear_map.curry0 𝕜 G x∥ = ∥x∥ :=
begin
apply le_antisymm,
{ exact continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λm, by simp) },
{ simpa using (continuous_multilinear_map.curry0 𝕜 G x).le_op_norm 0 }
end
variables {𝕜 G}
@[simp] lemma continuous_multilinear_map.fin0_apply_norm
(f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) {x : fin 0 → G} :
∥f x∥ = ∥f∥ :=
begin
have : x = 0 := subsingleton.elim _ _, subst this,
refine le_antisymm (by simpa using f.le_op_norm 0) _,
have : ∥continuous_multilinear_map.curry0 𝕜 G (f.uncurry0)∥ ≤ ∥f.uncurry0∥ :=
continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λm, by simp),
simpa
end
lemma continuous_multilinear_map.curry0_norm
(f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : ∥f.uncurry0∥ = ∥f∥ :=
by simp
variables (𝕜 G E₂)
/-- The linear isomorphism between elements of a normed space, and continuous multilinear maps in
`0` variables with values in this normed space. The continuous version is given in
`continuous_multilinear_curry_fin0`.
The direct and inverse maps are `uncurry0` and `curry0`. Use these unless you need the full
framework of linear equivs. -/
def continuous_multilinear_curry_fin0_aux :
(continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) ≃ₗ[𝕜] E₂ :=
{ to_fun := λf, continuous_multilinear_map.uncurry0 f,
inv_fun := λf, continuous_multilinear_map.curry0 𝕜 G f,
add := λf g, rfl,
smul := λc f, rfl,
left_inv := continuous_multilinear_map.uncurry0_curry0,
right_inv := continuous_multilinear_map.curry0_uncurry0 𝕜 G }
/-- The continuous linear isomorphism between elements of a normed space, and continuous multilinear
maps in `0` variables with values in this normed space.
The direct and inverse maps are `uncurry0` and `curry0`. Use these unless you need the full
framework of continuous linear equivs. -/
def continuous_multilinear_curry_fin0 :
(continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) ≃L[𝕜] E₂ :=
{ continuous_to_fun := begin
change continuous (λ (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂),
(f : ((fin 0) → G) → E₂) 0),
exact continuous_multilinear_map.continuous_eval.comp (continuous_id.prod_mk continuous_const)
end,
continuous_inv_fun := begin
refine (continuous_multilinear_curry_fin0_aux 𝕜 G E₂).symm.to_linear_map.continuous_of_bound
(1 : ℝ) (λf, le_of_eq _),
rw one_mul,
exact continuous_multilinear_map.uncurry0_norm _ _ _
end,
.. continuous_multilinear_curry_fin0_aux 𝕜 G E₂ }
variables {𝕜 G E₂}
@[simp] lemma continuous_multilinear_curry_fin0_apply
(f : (continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂)) :
continuous_multilinear_curry_fin0 𝕜 G E₂ f = f 0 := rfl
@[simp] lemma continuous_multilinear_curry_fin0_symm_apply
(x : E₂) (v : (fin 0) → G) :
(continuous_multilinear_curry_fin0 𝕜 G E₂).symm x v = x := rfl
/-! #### With 1 variable -/
variables (𝕜 G E₂)
/-- Continuous multilinear maps from `G^1` to `E₂` are isomorphic with continuous linear maps from
`G` to `E₂`. -/
def continuous_multilinear_curry_fin1 :
(continuous_multilinear_map 𝕜 (λ (i : fin 1), G) E₂) ≃L[𝕜] (G →L[𝕜] E₂) :=
(continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin 1), G) E₂).symm.trans
(continuous_multilinear_curry_fin0 𝕜 G (G →L[𝕜] E₂))
variables {𝕜 G E₂}
@[simp] lemma continuous_multilinear_curry_fin1_apply
(f : (continuous_multilinear_map 𝕜 (λ (i : fin 1), G) E₂)) (x : G) :
continuous_multilinear_curry_fin1 𝕜 G E₂ f x = f (fin.snoc 0 x) := rfl
@[simp] lemma continuous_multilinear_curry_fin1_symm_apply
(f : G →L[𝕜] E₂) (v : (fin 1) → G) :
(continuous_multilinear_curry_fin1 𝕜 G E₂).symm f v = f (v 0) := rfl
end currying
|
d255a9a9a9b7a93ba83cb23721e68a2c2ac059ce | b2e508d02500f1512e1618150413e6be69d9db10 | /src/category_theory/limits/cones.lean | 1ab991acdc95d027a854eca6325e6ddac94fa608 | [
"Apache-2.0"
] | permissive | callum-sutton/mathlib | c3788f90216e9cd43eeffcb9f8c9f959b3b01771 | afd623825a3ac6bfbcc675a9b023edad3f069e89 | refs/heads/master | 1,591,371,888,053 | 1,560,990,690,000 | 1,560,990,690,000 | 192,476,045 | 0 | 0 | Apache-2.0 | 1,568,941,843,000 | 1,560,837,965,000 | Lean | UTF-8 | Lean | false | false | 15,544 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan, Scott Morrison, Floris van Doorn
import category_theory.const
import category_theory.yoneda
import category_theory.concrete_category
import category_theory.equivalence
universes v u u' -- declare the `v`'s first; see `category_theory.category` for an explanation
open category_theory
-- There is an awkward difficulty with universes here.
-- If we allowed `J` to be a small category in `Prop`, we'd run into trouble
-- because `yoneda.obj (F : (J ⥤ C)ᵒᵖ)` will be a functor into `Sort (max v 1)`,
-- not into `Sort v`.
-- So we don't allow this case; it's not particularly useful anyway.
variables {J : Type v} [small_category J]
variables {C : Type u} [𝒞 : category.{v+1} C]
include 𝒞
open category_theory
open category_theory.category
open category_theory.functor
open opposite
namespace category_theory
namespace functor
variables {J C} (F : J ⥤ C)
/--
`F.cones` is the functor assigning to an object `X` the type of
natural transformations from the constant functor with value `X` to `F`.
An object representing this functor is a limit of `F`.
-/
def cones : Cᵒᵖ ⥤ Type v := (const J).op ⋙ (yoneda.obj F)
lemma cones_obj (X : Cᵒᵖ) : F.cones.obj X = ((const J).obj (unop X) ⟶ F) := rfl
@[simp] lemma cones_map_app {X₁ X₂ : Cᵒᵖ} (f : X₁ ⟶ X₂) (t : F.cones.obj X₁) (j : J) :
(F.cones.map f t).app j = f.unop ≫ t.app j := rfl
/--
`F.cocones` is the functor assigning to an object `X` the type of
natural transformations from `F` to the constant functor with value `X`.
An object corepresenting this functor is a colimit of `F`.
-/
def cocones : C ⥤ Type v := const J ⋙ coyoneda.obj (op F)
lemma cocones_obj (X : C) : F.cocones.obj X = (F ⟶ (const J).obj X) := rfl
@[simp] lemma cocones_map_app {X₁ X₂ : C} (f : X₁ ⟶ X₂) (t : F.cocones.obj X₁) (j : J) :
(F.cocones.map f t).app j = t.app j ≫ f := rfl
end functor
section
variables (J C)
def cones : (J ⥤ C) ⥤ (Cᵒᵖ ⥤ Type v) :=
{ obj := functor.cones,
map := λ F G f, whisker_left (const J).op (yoneda.map f) }
def cocones : (J ⥤ C)ᵒᵖ ⥤ (C ⥤ Type v) :=
{ obj := λ F, functor.cocones (unop F),
map := λ F G f, whisker_left (const J) (coyoneda.map f) }
variables {J C}
@[simp] lemma cones_obj (F : J ⥤ C) : (cones J C).obj F = F.cones := rfl
@[simp] lemma cones_map {F G : J ⥤ C} {f : F ⟶ G} :
(cones J C).map f = (whisker_left (const J).op (yoneda.map f)) := rfl
@[simp] lemma cocones_obj (F : (J ⥤ C)ᵒᵖ) : (cocones J C).obj F = (unop F).cocones := rfl
@[simp] lemma cocones_map {F G : (J ⥤ C)ᵒᵖ} {f : F ⟶ G} :
(cocones J C).map f = (whisker_left (const J) (coyoneda.map f)) := rfl
end
namespace limits
/--
A `c : cone F` is:
* an object `c.X` and
* a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`.
`cone F` is equivalent, in the obvious way, to `Σ X, F.cones.obj X`.
-/
structure cone (F : J ⥤ C) :=
(X : C)
(π : (const J).obj X ⟶ F)
@[simp] lemma cone.w {F : J ⥤ C} (c : cone F) {j j' : J} (f : j ⟶ j') :
c.π.app j ≫ F.map f = c.π.app j' :=
by convert ←(c.π.naturality f).symm; apply id_comp
/--
A `c : cocone F` is
* an object `c.X` and
* a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor.
`cocone F` is equivalent, in the obvious way, to `Σ X, F.cocones.obj X`.
-/
structure cocone (F : J ⥤ C) :=
(X : C)
(ι : F ⟶ (const J).obj X)
@[simp] lemma cocone.w {F : J ⥤ C} (c : cocone F) {j j' : J} (f : j ⟶ j') :
F.map f ≫ c.ι.app j' = c.ι.app j :=
by convert ←(c.ι.naturality f); apply comp_id
variables {F : J ⥤ C}
namespace cone
@[simp] def extensions (c : cone F) : yoneda.obj c.X ⟶ F.cones :=
{ app := λ X f, ((const J).map f) ≫ c.π }
/-- A map to the vertex of a cone induces a cone by composition. -/
@[simp] def extend (c : cone F) {X : C} (f : X ⟶ c.X) : cone F :=
{ X := X,
π := c.extensions.app (op X) f }
@[simp] lemma extend_π (c : cone F) {X : Cᵒᵖ} (f : unop X ⟶ c.X) :
(extend c f).π = c.extensions.app X f :=
rfl
def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) :=
{ X := c.X,
π := whisker_left E c.π }
@[simp] lemma whisker_π_app (c : cone F) {K : Type v} [small_category K] (E : K ⥤ J) (k : K) :
(c.whisker E).π.app k = (c.π).app (E.obj k) := rfl
section
omit 𝒞
variables {m : Type v → Type v}
variables (hom : ∀ {α β : Type v}, m α → m β → (α → β) → Prop)
variables [h : concrete_category @hom]
include h
@[simp] lemma naturality_bundled {G : J ⥤ bundled m} (s : cone G) {j j' : J} (f : j ⟶ j') (x : s.X) :
(G.map f) ((s.π.app j) x) = (s.π.app j') x :=
congr_fun (congr_arg (λ k : s.X ⟶ G.obj j', (k : s.X → G.obj j')) (s.π.naturality f).symm) x
end
end cone
namespace cocone
@[simp] def extensions (c : cocone F) : coyoneda.obj (op c.X) ⟶ F.cocones :=
{ app := λ X f, c.ι ≫ (const J).map f }
/-- A map from the vertex of a cocone induces a cocone by composition. -/
@[simp] def extend (c : cocone F) {X : C} (f : c.X ⟶ X) : cocone F :=
{ X := X,
ι := c.extensions.app X f }
@[simp] lemma extend_ι (c : cocone F) {X : C} (f : c.X ⟶ X) :
(extend c f).ι = c.extensions.app X f :=
rfl
def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cocone F) : cocone (E ⋙ F) :=
{ X := c.X,
ι := whisker_left E c.ι }
@[simp] lemma whisker_ι_app (c : cocone F) {K : Type v} [small_category K] (E : K ⥤ J) (k : K) :
(c.whisker E).ι.app k = (c.ι).app (E.obj k) := rfl
section
omit 𝒞
variables {m : Type v → Type v}
variables (hom : ∀ {α β : Type v}, m α → m β → (α → β) → Prop)
variables [h : concrete_category @hom]
include h
@[simp] lemma naturality_bundled {G : J ⥤ bundled m} (s : cocone G) {j j' : J} (f : j ⟶ j') (x : G.obj j) :
(s.ι.app j') ((G.map f) x) = (s.ι.app j) x :=
congr_fun (congr_arg (λ k : G.obj j ⟶ s.X, (k : G.obj j → s.X)) (s.ι.naturality f)) x
end
end cocone
structure cone_morphism (A B : cone F) :=
(hom : A.X ⟶ B.X)
(w' : ∀ j : J, hom ≫ B.π.app j = A.π.app j . obviously)
restate_axiom cone_morphism.w'
attribute [simp] cone_morphism.w
@[extensionality] lemma cone_morphism.ext {A B : cone F} {f g : cone_morphism A B}
(w : f.hom = g.hom) : f = g :=
by cases f; cases g; simpa using w
instance cone.category : category.{v+1} (cone F) :=
{ hom := λ A B, cone_morphism A B,
comp := λ X Y Z f g,
{ hom := f.hom ≫ g.hom,
w' := by intro j; rw [assoc, g.w, f.w] },
id := λ B, { hom := 𝟙 B.X } }
namespace cones
@[simp] lemma id.hom (c : cone F) : (𝟙 c : cone_morphism c c).hom = 𝟙 (c.X) := rfl
@[simp] lemma comp.hom {c d e : cone F} (f : c ⟶ d) (g : d ⟶ e) :
(f ≫ g).hom = f.hom ≫ g.hom := rfl
/-- To give an isomorphism between cones, it suffices to give an
isomorphism between their vertices which commutes with the cone
maps. -/
@[extensionality] def ext {c c' : cone F}
(φ : c.X ≅ c'.X) (w : ∀ j, c.π.app j = φ.hom ≫ c'.π.app j) : c ≅ c' :=
{ hom := { hom := φ.hom },
inv := { hom := φ.inv, w' := λ j, φ.inv_comp_eq.mpr (w j) } }
@[simp] lemma ext_hom_hom {c c' : cone F} (φ : c.X ≅ c'.X)
(w : ∀ j, c.π.app j = φ.hom ≫ c'.π.app j) : (ext φ w).hom.hom = φ.hom := rfl
def postcompose {G : J ⥤ C} (α : F ⟶ G) : cone F ⥤ cone G :=
{ obj := λ c, { X := c.X, π := c.π ≫ α },
map := λ c₁ c₂ f, { hom := f.hom, w' :=
by intro; erw ← category.assoc; simp [-category.assoc] } }
@[simp] lemma postcompose_obj_X {G : J ⥤ C} (α : F ⟶ G) (c : cone F) :
((postcompose α).obj c).X = c.X := rfl
@[simp] lemma postcompose_obj_π {G : J ⥤ C} (α : F ⟶ G) (c : cone F) :
((postcompose α).obj c).π = c.π ≫ α := rfl
@[simp] lemma postcompose_map_hom {G : J ⥤ C} (α : F ⟶ G) {c₁ c₂ : cone F} (f : c₁ ⟶ c₂):
((postcompose α).map f).hom = f.hom := rfl
def postcompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) :
postcompose (α ≫ β) ≅ postcompose α ⋙ postcompose β :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def postcompose_id : postcompose (𝟙 F) ≅ functor.id (cone F) :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def postcompose_equivalence {G : J ⥤ C} (α : F ≅ G) : cone F ≌ cone G :=
begin
refine equivalence.mk (postcompose α.hom) (postcompose α.inv) _ _,
{ symmetry,
refine (postcompose_comp _ _).symm.trans _, rw [iso.hom_inv_id], exact postcompose_id },
{ refine (postcompose_comp _ _).symm.trans _, rw [iso.inv_hom_id], exact postcompose_id }
end
def forget : cone F ⥤ C :=
{ obj := λ t, t.X, map := λ s t f, f.hom }
@[simp] lemma forget_obj {t : cone F} : forget.obj t = t.X := rfl
@[simp] lemma forget_map {s t : cone F} {f : s ⟶ t} : forget.map f = f.hom := rfl
section
variables {D : Type u'} [𝒟 : category.{v+1} D]
include 𝒟
@[simp] def functoriality (G : C ⥤ D) : cone F ⥤ cone (F ⋙ G) :=
{ obj := λ A,
{ X := G.obj A.X,
π := { app := λ j, G.map (A.π.app j), naturality' := by intros; erw ←G.map_comp; tidy } },
map := λ X Y f,
{ hom := G.map f.hom,
w' := by intros; rw [←functor.map_comp, f.w] } }
end
end cones
structure cocone_morphism (A B : cocone F) :=
(hom : A.X ⟶ B.X)
(w' : ∀ j : J, A.ι.app j ≫ hom = B.ι.app j . obviously)
restate_axiom cocone_morphism.w'
attribute [simp] cocone_morphism.w
@[extensionality] lemma cocone_morphism.ext
{A B : cocone F} {f g : cocone_morphism A B} (w : f.hom = g.hom) : f = g :=
by cases f; cases g; simpa using w
instance cocone.category : category.{v+1} (cocone F) :=
{ hom := λ A B, cocone_morphism A B,
comp := λ _ _ _ f g,
{ hom := f.hom ≫ g.hom,
w' := by intro j; rw [←assoc, f.w, g.w] },
id := λ B, { hom := 𝟙 B.X } }
namespace cocones
@[simp] lemma id.hom (c : cocone F) : (𝟙 c : cocone_morphism c c).hom = 𝟙 (c.X) := rfl
@[simp] lemma comp.hom {c d e : cocone F} (f : c ⟶ d) (g : d ⟶ e) :
(f ≫ g).hom = f.hom ≫ g.hom := rfl
/-- To give an isomorphism between cocones, it suffices to give an
isomorphism between their vertices which commutes with the cocone
maps. -/
@[extensionality] def ext {c c' : cocone F}
(φ : c.X ≅ c'.X) (w : ∀ j, c.ι.app j ≫ φ.hom = c'.ι.app j) : c ≅ c' :=
{ hom := { hom := φ.hom },
inv := { hom := φ.inv, w' := λ j, φ.comp_inv_eq.mpr (w j).symm } }
@[simp] lemma ext_hom_hom {c c' : cocone F} (φ : c.X ≅ c'.X)
(w : ∀ j, c.ι.app j ≫ φ.hom = c'.ι.app j) : (ext φ w).hom.hom = φ.hom := rfl
def precompose {G : J ⥤ C} (α : G ⟶ F) : cocone F ⥤ cocone G :=
{ obj := λ c, { X := c.X, ι := α ≫ c.ι },
map := λ c₁ c₂ f, { hom := f.hom } }
@[simp] lemma precompose_obj_X {G : J ⥤ C} (α : G ⟶ F) (c : cocone F) :
((precompose α).obj c).X = c.X := rfl
@[simp] lemma precompose_obj_ι {G : J ⥤ C} (α : G ⟶ F) (c : cocone F) :
((precompose α).obj c).ι = α ≫ c.ι := rfl
@[simp] lemma precompose_map_hom {G : J ⥤ C} (α : G ⟶ F) {c₁ c₂ : cocone F} (f : c₁ ⟶ c₂) :
((precompose α).map f).hom = f.hom := rfl
def precompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) :
precompose (α ≫ β) ≅ precompose β ⋙ precompose α :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def precompose_id : precompose (𝟙 F) ≅ functor.id (cocone F) :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def precompose_equivalence {G : J ⥤ C} (α : G ≅ F) : cocone F ≌ cocone G :=
begin
refine equivalence.mk (precompose α.hom) (precompose α.inv) _ _,
{ symmetry, refine (precompose_comp _ _).symm.trans _, rw [iso.inv_hom_id], exact precompose_id },
{ refine (precompose_comp _ _).symm.trans _, rw [iso.hom_inv_id], exact precompose_id }
end
def forget : cocone F ⥤ C :=
{ obj := λ t, t.X, map := λ s t f, f.hom }
@[simp] lemma forget_obj {t : cocone F} : forget.obj t = t.X := rfl
@[simp] lemma forget_map {s t : cocone F} {f : s ⟶ t} : forget.map f = f.hom := rfl
section
variables {D : Type u'} [𝒟 : category.{v+1} D]
include 𝒟
@[simp] def functoriality (G : C ⥤ D) : cocone F ⥤ cocone (F ⋙ G) :=
{ obj := λ A,
{ X := G.obj A.X,
ι := { app := λ j, G.map (A.ι.app j), naturality' := by intros; erw ←G.map_comp; tidy } },
map := λ _ _ f,
{ hom := G.map f.hom,
w' := by intros; rw [←functor.map_comp, cocone_morphism.w] } }
end
end cocones
end limits
namespace functor
variables {D : Type u'} [category.{v+1} D]
variables {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D)
open category_theory.limits
/-- The image of a cone in C under a functor G : C ⥤ D is a cone in D. -/
def map_cone (c : cone F) : cone (F ⋙ H) := (cones.functoriality H).obj c
/-- The image of a cocone in C under a functor G : C ⥤ D is a cocone in D. -/
def map_cocone (c : cocone F) : cocone (F ⋙ H) := (cocones.functoriality H).obj c
def map_cone_morphism {c c' : cone F} (f : cone_morphism c c') :
cone_morphism (H.map_cone c) (H.map_cone c') := (cones.functoriality H).map f
def map_cocone_morphism {c c' : cocone F} (f : cocone_morphism c c') :
cocone_morphism (H.map_cocone c) (H.map_cocone c') := (cocones.functoriality H).map f
@[simp] lemma map_cone_π (c : cone F) (j : J) :
(map_cone H c).π.app j = H.map (c.π.app j) := rfl
@[simp] lemma map_cocone_ι (c : cocone F) (j : J) :
(map_cocone H c).ι.app j = H.map (c.ι.app j) := rfl
end functor
end category_theory
namespace category_theory.limits
variables {F : J ⥤ Cᵒᵖ}
def cone_of_cocone_left_op (c : cocone F.left_op) : cone F :=
{ X := op c.X,
π := nat_trans.right_op (c.ι ≫ (const.op_obj_unop (op c.X)).hom) }
@[simp] lemma cone_of_cocone_left_op_X (c : cocone F.left_op) :
(cone_of_cocone_left_op c).X = op c.X :=
rfl
@[simp] lemma cone_of_cocone_left_op_π_app (c : cocone F.left_op) (j) :
(cone_of_cocone_left_op c).π.app j = (c.ι.app (op j)).op :=
by { dsimp [cone_of_cocone_left_op], simp }
def cocone_left_op_of_cone (c : cone F) : cocone (F.left_op) :=
{ X := unop c.X,
ι := nat_trans.left_op c.π }
@[simp] lemma cocone_left_op_of_cone_X (c : cone F) :
(cocone_left_op_of_cone c).X = unop c.X :=
rfl
@[simp] lemma cocone_left_op_of_cone_ι_app (c : cone F) (j) :
(cocone_left_op_of_cone c).ι.app j = (c.π.app (unop j)).unop :=
by { dsimp [cocone_left_op_of_cone], simp }
def cocone_of_cone_left_op (c : cone F.left_op) : cocone F :=
{ X := op c.X,
ι := nat_trans.right_op ((const.op_obj_unop (op c.X)).hom ≫ c.π) }
@[simp] lemma cocone_of_cone_left_op_X (c : cone F.left_op) :
(cocone_of_cone_left_op c).X = op c.X :=
rfl
@[simp] lemma cocone_of_cone_left_op_ι_app (c : cone F.left_op) (j) :
(cocone_of_cone_left_op c).ι.app j = (c.π.app (op j)).op :=
by { dsimp [cocone_of_cone_left_op], simp }
def cone_left_op_of_cocone (c : cocone F) : cone (F.left_op) :=
{ X := unop c.X,
π := nat_trans.left_op c.ι }
@[simp] lemma cone_left_op_of_cocone_X (c : cocone F) :
(cone_left_op_of_cocone c).X = unop c.X :=
rfl
@[simp] lemma cone_left_op_of_cocone_π_app (c : cocone F) (j) :
(cone_left_op_of_cocone c).π.app j = (c.ι.app (unop j)).unop :=
by { dsimp [cone_left_op_of_cocone], simp }
end category_theory.limits
|
3fba9092ae2ef0fdaef688576ed5b8573f8a9b8d | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/data/nat/basic.lean | 10c69a3326b70b7cb81e652046acbc6502c647e6 | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 65,236 | lean | /-
Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import algebra.group_power.basic
import algebra.order_functions
import algebra.ordered_monoid
/-!
# Basic operations on the natural numbers
This file contains:
- instances on the natural numbers
- some basic lemmas about natural numbers
- extra recursors:
* `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers
* `decreasing_induction`: recursion growing downwards
* `strong_rec'`: recursion based on strong inequalities
- decidability instances on predicates about the natural numbers
-/
universes u v
/-! ### instances -/
instance : nontrivial ℕ :=
⟨⟨0, 1, nat.zero_ne_one⟩⟩
instance : comm_semiring nat :=
{ add := nat.add,
add_assoc := nat.add_assoc,
zero := nat.zero,
zero_add := nat.zero_add,
add_zero := nat.add_zero,
add_comm := nat.add_comm,
mul := nat.mul,
mul_assoc := nat.mul_assoc,
one := nat.succ nat.zero,
one_mul := nat.one_mul,
mul_one := nat.mul_one,
left_distrib := nat.left_distrib,
right_distrib := nat.right_distrib,
zero_mul := nat.zero_mul,
mul_zero := nat.mul_zero,
mul_comm := nat.mul_comm }
instance : linear_ordered_semiring nat :=
{ add_left_cancel := @nat.add_left_cancel,
add_right_cancel := @nat.add_right_cancel,
lt := nat.lt,
add_le_add_left := @nat.add_le_add_left,
le_of_add_le_add_left := @nat.le_of_add_le_add_left,
zero_le_one := nat.le_of_lt (nat.zero_lt_succ 0),
mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left,
mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right,
decidable_eq := nat.decidable_eq,
exists_pair_ne := ⟨0, 1, ne_of_lt nat.zero_lt_one⟩,
..nat.comm_semiring, ..nat.linear_order }
-- all the fields are already included in the linear_ordered_semiring instance
instance : linear_ordered_cancel_add_comm_monoid ℕ :=
{ add_left_cancel := @nat.add_left_cancel,
..nat.linear_ordered_semiring }
instance : linear_ordered_comm_monoid_with_zero ℕ :=
{ mul_le_mul_left := λ a b h c, nat.mul_le_mul_left c h,
..nat.linear_ordered_semiring,
..(infer_instance : comm_monoid_with_zero ℕ)}
/-! Extra instances to short-circuit type class resolution -/
instance : add_comm_monoid nat := by apply_instance
instance : add_monoid nat := by apply_instance
instance : monoid nat := by apply_instance
instance : comm_monoid nat := by apply_instance
instance : comm_semigroup nat := by apply_instance
instance : semigroup nat := by apply_instance
instance : add_comm_semigroup nat := by apply_instance
instance : add_semigroup nat := by apply_instance
instance : distrib nat := by apply_instance
instance : semiring nat := by apply_instance
instance : ordered_semiring nat := by apply_instance
instance : canonically_ordered_comm_semiring ℕ :=
{ le_iff_exists_add := assume a b,
⟨assume h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩,
assume ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩,
eq_zero_or_eq_zero_of_mul_eq_zero := assume a b, nat.eq_zero_of_mul_eq_zero,
bot := 0,
bot_le := nat.zero_le,
.. nat.nontrivial,
.. (infer_instance : ordered_add_comm_monoid ℕ),
.. (infer_instance : linear_ordered_semiring ℕ),
.. (infer_instance : comm_semiring ℕ) }
instance : canonically_linear_ordered_add_monoid ℕ :=
{ .. (infer_instance : canonically_ordered_add_monoid ℕ),
.. nat.linear_order }
instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred s] [h : nonempty s] :
semilattice_sup_bot s :=
{ bot := ⟨nat.find (nonempty_subtype.1 h), nat.find_spec (nonempty_subtype.1 h)⟩,
bot_le := λ x, nat.find_min' _ x.2,
..subtype.linear_order s,
..lattice_of_linear_order }
theorem nat.eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : 0 < m) (H : n * m = k * m) : n = k :=
by rw [mul_comm n m, mul_comm k m] at H; exact nat.eq_of_mul_eq_mul_left Hm H
instance nat.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero ℕ :=
{ mul_left_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_left (nat.pos_of_ne_zero h1) h2,
mul_right_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_right (nat.pos_of_ne_zero h1) h2,
.. (infer_instance : comm_monoid_with_zero ℕ) }
attribute [simp] nat.not_lt_zero
/-!
Inject some simple facts into the type class system.
This `fact` should not be confused with the factorial function `nat.fact`!
-/
section facts
instance succ_pos'' (n : ℕ) : fact (0 < n.succ) := n.succ_pos
instance pos_of_one_lt (n : ℕ) [h : fact (1 < n)] : fact (0 < n) :=
lt_trans zero_lt_one h
end facts
variables {m n k : ℕ}
namespace nat
/-!
### Recursion and `set.range`
-/
section set
open set
theorem zero_union_range_succ : {0} ∪ range succ = univ :=
by { ext n, cases n; simp }
variables {α : Type*}
theorem range_of_succ (f : ℕ → α) : {f 0} ∪ range (f ∘ succ) = range f :=
by rw [← image_singleton, range_comp, ← image_union, zero_union_range_succ, image_univ]
theorem range_rec {α : Type*} (x : α) (f : ℕ → α → α) :
(set.range (λ n, nat.rec x f n) : set α) =
{x} ∪ set.range (λ n, nat.rec (f 0 x) (f ∘ succ) n) :=
begin
convert (range_of_succ _).symm,
ext n,
induction n with n ihn,
{ refl },
{ dsimp at ihn ⊢,
rw ihn }
end
theorem range_cases_on {α : Type*} (x : α) (f : ℕ → α) :
(set.range (λ n, nat.cases_on n x f) : set α) = {x} ∪ set.range f :=
(range_of_succ _).symm
end set
/-! ### The units of the natural numbers as a `monoid` and `add_monoid` -/
theorem units_eq_one (u : units ℕ) : u = 1 :=
units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩
theorem add_units_eq_zero (u : add_units ℕ) : u = 0 :=
add_units.ext $ (nat.eq_zero_of_add_eq_zero u.val_neg).1
@[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 :=
iff.intro
(assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end)
(assume h, h.symm ▸ ⟨1, rfl⟩)
/-! ### Equalities and inequalities involving zero and one -/
lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1
| 0 := dec_trivial
| 1 := dec_trivial
| (n+2) := dec_trivial
protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0
| nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0
@[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 :=
iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt})
@[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 :=
by rw [eq_comm, nat.mul_eq_zero]
lemma eq_zero_of_double_le {a : ℕ} (h : 2 * a ≤ a) : a = 0 :=
nat.eq_zero_of_le_zero $
by rwa [two_mul, nat.add_le_to_le_sub, nat.sub_self] at h; refl
lemma eq_zero_of_mul_le {a b : ℕ} (hb : 2 ≤ b) (h : b * a ≤ a) : a = 0 :=
eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h
theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 :=
⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩
lemma zero_max {m : ℕ} : max 0 m = m :=
max_eq_right (zero_le _)
lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m :=
lt_of_le_of_lt (nat.zero_le _) h
theorem eq_one_of_mul_eq_one_right {m n : ℕ} (H : m * n = 1) : m = 1 :=
eq_one_of_dvd_one ⟨n, H.symm⟩
theorem eq_one_of_mul_eq_one_left {m n : ℕ} (H : m * n = 1) : n = 1 :=
eq_one_of_mul_eq_one_right (by rwa mul_comm)
/-! ### `succ` -/
theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b :=
have h3 : a ≤ b, from le_of_lt_succ h1,
or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3))
theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm]
@[simp] lemma succ_pos' {n : ℕ} : 0 < succ n := succ_pos n
theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m :=
⟨succ.inj, congr_arg _⟩
theorem succ_injective : function.injective nat.succ := λ x y, succ.inj
theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n :=
⟨le_of_succ_le_succ, succ_le_succ⟩
theorem max_succ_succ {m n : ℕ} :
max (succ m) (succ n) = succ (max m n) :=
begin
by_cases h1 : m ≤ n,
rw [max_eq_right h1, max_eq_right (succ_le_succ h1)],
{ rw not_le at h1, have h2 := le_of_lt h1,
rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] }
end
lemma not_succ_lt_self {n : ℕ} : ¬succ n < n :=
not_lt_of_ge (nat.le_succ _)
theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n :=
succ_le_succ_iff
lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n :=
⟨lt_of_succ_le, succ_le_of_lt⟩
lemma lt_iff_add_one_le {m n : ℕ} : m < n ↔ m + 1 ≤ n :=
by rw succ_le_iff
-- Just a restatement of `nat.lt_succ_iff` using `+1`.
lemma lt_add_one_iff {a b : ℕ} : a < b + 1 ↔ a ≤ b :=
lt_succ_iff
-- A flipped version of `lt_add_one_iff`.
lemma lt_one_add_iff {a b : ℕ} : a < 1 + b ↔ a ≤ b :=
by simp only [add_comm, lt_succ_iff]
-- This is true reflexively, by the definition of `≤` on ℕ,
-- but it's still useful to have, to convince Lean to change the syntactic type.
lemma add_one_le_iff {a b : ℕ} : a + 1 ≤ b ↔ a < b :=
iff.refl _
lemma one_add_le_iff {a b : ℕ} : 1 + a ≤ b ↔ a < b :=
by simp only [add_comm, add_one_le_iff]
theorem of_le_succ {n m : ℕ} (H : n ≤ m.succ) : n ≤ m ∨ n = m.succ :=
(lt_or_eq_of_le H).imp le_of_lt_succ id
lemma succ_lt_succ_iff {m n : ℕ} : succ m < succ n ↔ m < n :=
⟨lt_of_succ_lt_succ, succ_lt_succ⟩
/-! ### `add` -/
-- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding
-- during pattern matching. These lemmas package them back up as typeclass
-- mediated operations.
@[simp] theorem add_def {a b : ℕ} : nat.add a b = a + b := rfl
@[simp] theorem mul_def {a b : ℕ} : nat.mul a b = a * b := rfl
attribute [simp] nat.add_sub_cancel nat.add_sub_cancel_left
attribute [simp] nat.sub_self
lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k
| 0 0 h := ⟨0, by simp⟩
| 0 (n+1) h := ⟨n+1, by simp⟩
| (m+1) (n+1) h :=
let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in
⟨k, by simp [hk, add_comm, add_left_comm]⟩
lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1
| 0 0 h := false.elim $ lt_irrefl _ h
| 0 (n+1) h := ⟨n, by simp⟩
| (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in
⟨k, by simp [hk]⟩
theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n :=
calc
m + n > 0 + n : nat.add_lt_add_right h n
... = n : nat.zero_add n
... ≥ 0 : zero_le n
theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n :=
begin rw add_comm, exact add_pos_left h m end
theorem add_pos_iff_pos_or_pos (m n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n :=
iff.intro
begin
intro h,
cases m with m,
{simp [zero_add] at h, exact or.inr h},
exact or.inl (succ_pos _)
end
begin
intro h, cases h with mpos npos,
{ apply add_pos_left mpos },
apply add_pos_right _ npos
end
lemma add_eq_one_iff : ∀ {a b : ℕ}, a + b = 1 ↔ (a = 0 ∧ b = 1) ∨ (a = 1 ∧ b = 0)
| 0 0 := dec_trivial
| 0 1 := dec_trivial
| 1 0 := dec_trivial
| 1 1 := dec_trivial
| (a+2) _ := by rw add_right_comm; exact dec_trivial
| _ (b+2) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp
theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) :=
⟨assume h,
match nat.eq_or_lt_of_le h with
| or.inl h := or.inr h
| or.inr h := or.inl $ nat.le_of_succ_le_succ h
end,
or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩
lemma add_succ_lt_add {a b c d : ℕ} (hab : a < b) (hcd : c < d) : a + c + 1 < b + d :=
begin
rw add_assoc,
exact add_lt_add_of_lt_of_le hab (nat.succ_le_iff.2 hcd)
end
-- TODO: generalize to some ordered add_monoids, based on #6145
lemma le_of_add_le_left {a b c : ℕ} (h : a + b ≤ c) : a ≤ c :=
by { refine le_trans _ h, simp }
lemma le_of_add_le_right {a b c : ℕ} (h : a + b ≤ c) : b ≤ c :=
by { refine le_trans _ h, simp }
/-! ### `pred` -/
@[simp]
lemma add_succ_sub_one (n m : ℕ) : (n + succ m) - 1 = n + m :=
by rw [add_succ, succ_sub_one]
@[simp]
lemma succ_add_sub_one (n m : ℕ) : (succ n + m) - 1 = n + m :=
by rw [succ_add, succ_sub_one]
lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl
theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H]
@[simp] lemma pred_eq_succ_iff {n m : ℕ} : pred n = succ m ↔ n = m + 2 :=
by cases n; split; rintro ⟨⟩; refl
theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) :=
by rw [← sub_one, nat.sub_sub, one_add]; refl
lemma le_pred_of_lt {n m : ℕ} (h : m < n) : m ≤ n - 1 :=
nat.sub_le_sub_right h 1
lemma le_of_pred_lt {m n : ℕ} : pred m < n → m ≤ n :=
match m with
| 0 := le_of_lt
| m+1 := id
end
/-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/
@[simp] lemma pred_one_add (n : ℕ) : pred (1 + n) = n :=
by rw [add_comm, add_one, pred_succ]
/-! ### `sub` -/
protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m :=
or.elim (le_total n m)
(assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end)
(assume : m ≤ n, begin rw (nat.sub_add_cancel this) end)
theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m :=
eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂,
by rw ← nat.sub_add_cancel h₂; exact
add_le_add_right (nat.sub_le_sub_right h₁ _) _
theorem add_sub_eq_max (n m : ℕ) : n + (m - n) = max n m :=
by rw [add_comm, max_comm, sub_add_eq_max]
theorem sub_add_min (n m : ℕ) : n - m + min n m = n :=
(le_total n m).elim
(λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add])
(λ h, by rw [min_eq_right h, nat.sub_add_cancel h])
protected theorem add_sub_cancel' {n m : ℕ} (h : m ≤ n) : m + (n - m) = n :=
by rw [add_comm, nat.sub_add_cancel h]
protected theorem sub_add_sub_cancel {a b c : ℕ} (hab : b ≤ a) (hbc : c ≤ b) :
(a - b) + (b - c) = a - c :=
by rw [←nat.add_sub_assoc hbc, ←nat.sub_add_comm hab, nat.add_sub_cancel]
protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n :=
begin rw [h, nat.add_sub_cancel_left] end
theorem sub_cancel {a b c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c :=
by rw [←nat.sub_add_cancel h₁, ←nat.sub_add_cancel h₂, w]
lemma sub_sub_sub_cancel_right {a b c : ℕ} (h₂ : c ≤ b) : (a - c) - (b - c) = a - b :=
by rw [nat.sub_sub, ←nat.add_sub_assoc h₂, nat.add_sub_cancel_left]
lemma add_sub_cancel_right (n m k : ℕ) : n + (m + k) - k = n + m :=
by { rw [nat.add_sub_assoc, nat.add_sub_cancel], apply k.le_add_left }
protected lemma sub_add_eq_add_sub {a b c : ℕ} (h : b ≤ a) : (a - b) + c = (a + c) - b :=
by rw [add_comm a, nat.add_sub_assoc h, add_comm]
theorem sub_min (n m : ℕ) : n - min n m = n - m :=
nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min]
theorem sub_sub_assoc {a b c : ℕ} (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c :=
(nat.sub_eq_iff_eq_add (le_trans (nat.sub_le _ _) h₁)).2 $
by rw [add_right_comm, add_assoc, nat.sub_add_cancel h₂, nat.sub_add_cancel h₁]
protected theorem lt_of_sub_pos (h : 0 < n - m) : m < n :=
lt_of_not_ge
(assume : n ≤ m,
have n - m = 0, from sub_eq_zero_of_le this,
begin rw this at h, exact lt_irrefl _ h end)
protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n :=
lt_imp_lt_of_le_imp_le (λ h, nat.sub_le_sub_right h _)
protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n :=
lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left _)
protected theorem sub_lt_self (h₁ : 0 < m) (h₂ : 0 < n) : m - n < m :=
calc
m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂]
... = pred m - pred n : by rw succ_sub_succ
... ≤ pred m : sub_le _ _
... < succ (pred m) : lt_succ_self _
... = m : succ_pred_eq_of_pos h₁
protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k :=
by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k
protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k :=
nat.le_sub_right_of_add_le (by rwa add_comm at h)
protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k :=
lt_of_succ_le $ nat.le_sub_right_of_add_le $
by rw succ_add; exact succ_le_of_lt h
protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k :=
nat.lt_sub_right_of_add_lt (by rwa add_comm at h)
protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n :=
@nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel)
protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n :=
by rw add_comm; exact nat.add_lt_of_lt_sub_right h
protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k :=
le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt
protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m :=
le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt
protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k :=
lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le
protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m :=
lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le
protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m :=
le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left
protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m :=
le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right
protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m :=
⟨nat.lt_add_of_sub_lt_left,
λ h₁,
have succ k ≤ n + m, from succ_le_of_lt h₁,
have succ (k - n) ≤ m, from
calc succ (k - n) = succ k - n : by rw (succ_sub H)
... ≤ n + m - n : nat.sub_le_sub_right this n
... = m : by rw nat.add_sub_cancel_left,
lt_of_succ_le this⟩
protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k :=
le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H)
protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k :=
by rw [nat.le_sub_left_iff_add_le H, add_comm]
protected theorem lt_sub_left_iff_add_lt : n < k - m ↔ m + n < k :=
⟨nat.add_lt_of_lt_sub_left, nat.lt_sub_left_of_add_lt⟩
protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k :=
by rw [nat.lt_sub_left_iff_add_lt, add_comm]
theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k :=
le_iff_le_iff_lt_iff_lt.2 nat.lt_sub_left_iff_add_lt
theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k :=
by rw [nat.sub_le_left_iff_le_add, add_comm]
protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k :=
by rw [nat.sub_lt_left_iff_lt_add H, add_comm]
protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n :=
⟨λ h,
have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H,
nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this),
nat.sub_le_sub_left _⟩
protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n :=
lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff _ _ _ H)
protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n :=
lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H)
protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n :=
nat.sub_le_left_iff_le_add.trans nat.sub_le_right_iff_le_add.symm
protected lemma sub_le_self (n m : ℕ) : n - m ≤ n :=
nat.sub_le_left_of_le_add (nat.le_add_left _ _)
protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n :=
(nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm
lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m :=
@nat.sub_le_right_iff_le_add n m 1
lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m :=
@nat.lt_sub_right_iff_add_lt n 1 m
lemma lt_of_lt_pred {a b : ℕ} (h : a < b - 1) : a < b :=
lt_of_succ_lt (lt_pred_iff.1 h)
/-! ### `mul` -/
theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m :=
mul_le_mul h h (zero_le _) (zero_le _)
theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m
| 0 m h := mul_pos h h
| (succ n) m h := mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _)
theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m :=
⟨mul_self_le_mul_self, λh, decidable.by_contradiction $
λhn, not_lt_of_ge h $ mul_self_lt_mul_self $ lt_of_not_ge hn⟩
theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m :=
iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff mul_self_le_mul_self_iff) $
iff.symm (lt_iff_not_ge _ _)
theorem le_mul_self : Π (n : ℕ), n ≤ n * n
| 0 := le_refl _
| (n+1) := let t := mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t
lemma le_mul_of_pos_left {m n : ℕ} (h : 0 < n) : m ≤ n * m :=
begin
conv {to_lhs, rw [← one_mul(m)]},
exact mul_le_mul_of_nonneg_right (nat.succ_le_of_lt h) dec_trivial,
end
lemma le_mul_of_pos_right {m n : ℕ} (h : 0 < n) : m ≤ m * n :=
begin
conv {to_lhs, rw [← mul_one(m)]},
exact mul_le_mul_of_nonneg_left (nat.succ_le_of_lt h) dec_trivial,
end
theorem two_mul_ne_two_mul_add_one {n m} : 2 * n ≠ 2 * m + 1 :=
mt (congr_arg (%2)) (by rw [add_comm, add_mul_mod_self_left, mul_mod_right]; exact dec_trivial)
lemma mul_eq_one_iff : ∀ {a b : ℕ}, a * b = 1 ↔ a = 1 ∧ b = 1
| 0 0 := dec_trivial
| 0 1 := dec_trivial
| 1 0 := dec_trivial
| (a+2) 0 := by simp
| 0 (b+2) := by simp
| (a+1) (b+1) := ⟨λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one,
(add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2],
by clear_aux_decl; finish⟩
protected theorem mul_left_inj {a b c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c :=
⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩
protected theorem mul_right_inj {a b c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c :=
⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩
lemma mul_left_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, x * a) :=
λ _ _, eq_of_mul_eq_mul_right ha
lemma mul_right_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, a * x) :=
λ _ _, eq_of_mul_eq_mul_left ha
lemma mul_right_eq_self_iff {a b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 :=
suffices a * b = a * 1 ↔ b = 1, by rwa mul_one at this,
nat.mul_right_inj ha
lemma mul_left_eq_self_iff {a b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 :=
by rw [mul_comm, nat.mul_right_eq_self_iff hb]
lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) :=
lt_succ_iff.trans le_iff_lt_or_eq
theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m :=
le_antisymm_iff.trans (le_antisymm_iff.trans
(and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm
/-!
### Recursion and induction principles
This section is here due to dependencies -- the lemmas here require some of the lemmas
proved above, and some of the results in later sections depend on the definitions in this section.
-/
@[simp] lemma rec_zero {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) :
(nat.rec h0 h : Π n, C n) 0 = h0 :=
rfl
@[simp] lemma rec_add_one {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) (n : ℕ) :
(nat.rec h0 h : Π n, C n) (n + 1) = h n ((nat.rec h0 h : Π n, C n) n) :=
rfl
/-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k`,
there is a map from `C n` to each `C m`, `n ≤ m`. -/
@[elab_as_eliminator]
def le_rec_on {C : ℕ → Sort u} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π {k}, C k → C (k+1)) → C n → C m
| 0 H next x := eq.rec_on (eq_zero_of_le_zero H) x
| (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next $ le_rec_on h @next x)
(λ h : n = m + 1, eq.rec_on h x)
theorem le_rec_on_self {C : ℕ → Sort u} {n} {h : n ≤ n} {next} (x : C n) :
(le_rec_on h next x : C n) = x :=
by cases n; unfold le_rec_on or.by_cases; rw [dif_neg n.not_succ_le_self, dif_pos rfl]
theorem le_rec_on_succ {C : ℕ → Sort u} {n m} (h1 : n ≤ m) {h2 : n ≤ m+1} {next} (x : C n) :
(le_rec_on h2 @next x : C (m+1)) = next (le_rec_on h1 @next x : C m) :=
by conv { to_lhs, rw [le_rec_on, or.by_cases, dif_pos h1] }
theorem le_rec_on_succ' {C : ℕ → Sort u} {n} {h : n ≤ n+1} {next} (x : C n) :
(le_rec_on h next x : C (n+1)) = next x :=
by rw [le_rec_on_succ (le_refl n), le_rec_on_self]
theorem le_rec_on_trans {C : ℕ → Sort u} {n m k} (hnm : n ≤ m) (hmk : m ≤ k) {next} (x : C n) :
(le_rec_on (le_trans hnm hmk) @next x : C k) = le_rec_on hmk @next (le_rec_on hnm @next x) :=
begin
induction hmk with k hmk ih, { rw le_rec_on_self },
rw [le_rec_on_succ (le_trans hnm hmk), ih, le_rec_on_succ]
end
theorem le_rec_on_succ_left {C : ℕ → Sort u} {n m} (h1 : n ≤ m) (h2 : n+1 ≤ m)
{next : Π{{k}}, C k → C (k+1)} (x : C n) :
(le_rec_on h2 next (next x) : C m) = (le_rec_on h1 next x : C m) :=
begin
rw [subsingleton.elim h1 (le_trans (le_succ n) h2),
le_rec_on_trans (le_succ n) h2, le_rec_on_succ']
end
theorem le_rec_on_injective {C : ℕ → Sort u} {n m} (hnm : n ≤ m)
(next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.injective (next n)) :
function.injective (le_rec_on hnm next) :=
begin
induction hnm with m hnm ih, { intros x y H, rwa [le_rec_on_self, le_rec_on_self] at H },
intros x y H, rw [le_rec_on_succ hnm, le_rec_on_succ hnm] at H, exact ih (Hnext _ H)
end
theorem le_rec_on_surjective {C : ℕ → Sort u} {n m} (hnm : n ≤ m)
(next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.surjective (next n)) :
function.surjective (le_rec_on hnm next) :=
begin
induction hnm with m hnm ih, { intros x, use x, rw le_rec_on_self },
intros x, rcases Hnext _ x with ⟨w, rfl⟩, rcases ih w with ⟨x, rfl⟩, use x, rw le_rec_on_succ
end
/-- Recursion principle based on `<`. -/
@[elab_as_eliminator]
protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n
| n := H n (λ m hm, strong_rec' m)
/-- Recursion principle based on `<` applied to some natural number. -/
@[elab_as_eliminator]
def strong_rec_on' {P : ℕ → Sort*} (n : ℕ) (h : ∀ n, (∀ m, m < n → P m) → P n) : P n :=
nat.strong_rec' h n
theorem strong_rec_on_beta' {P : ℕ → Sort*} {h} {n : ℕ} :
(strong_rec_on' n h : P n) = h n (λ m hmn, (strong_rec_on' m h : P m)) :=
by { simp only [strong_rec_on'], rw nat.strong_rec' }
/-- Induction principle starting at a non-zero number. For maps to a `Sort*` see `le_rec_on`. -/
@[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m}
(h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (n + 1)) :
∀ n, m ≤ n → P n :=
by apply nat.less_than_or_equal.rec h0; exact h1
/-- Decreasing induction: if `P (k+1)` implies `P k`, then `P n` implies `P m` for all `m ≤ n`.
Also works for functions to `Sort*`. -/
@[elab_as_eliminator]
def decreasing_induction {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n)
(hP : P n) : P m :=
le_rec_on mn (λ k ih hsk, ih $ h k hsk) (λ h, h) hP
@[simp] lemma decreasing_induction_self {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {n : ℕ}
(nn : n ≤ n) (hP : P n) : (decreasing_induction h nn hP : P n) = hP :=
by { dunfold decreasing_induction, rw [le_rec_on_self] }
lemma decreasing_induction_succ {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n)
(msn : m ≤ n + 1) (hP : P (n+1)) :
(decreasing_induction h msn hP : P m) = decreasing_induction h mn (h n hP) :=
by { dunfold decreasing_induction, rw [le_rec_on_succ] }
@[simp] lemma decreasing_induction_succ' {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m : ℕ}
(msm : m ≤ m + 1) (hP : P (m+1)) : (decreasing_induction h msm hP : P m) = h m hP :=
by { dunfold decreasing_induction, rw [le_rec_on_succ'] }
lemma decreasing_induction_trans {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n k : ℕ}
(mn : m ≤ n) (nk : n ≤ k) (hP : P k) :
(decreasing_induction h (le_trans mn nk) hP : P m) =
decreasing_induction h mn (decreasing_induction h nk hP) :=
by { induction nk with k nk ih, rw [decreasing_induction_self],
rw [decreasing_induction_succ h (le_trans mn nk), ih, decreasing_induction_succ] }
lemma decreasing_induction_succ_left {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ}
(smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) :
(decreasing_induction h mn hP : P m) = h m (decreasing_induction h smn hP) :=
by { rw [subsingleton.elim mn (le_trans (le_succ m) smn), decreasing_induction_trans,
decreasing_induction_succ'] }
/-! ### `div` -/
attribute [simp] nat.div_self
protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n :=
(eq_zero_or_pos k).elim
(λ k0, by rw [k0, nat.div_zero]; apply zero_le)
(λ k0, (decidable.mul_le_mul_left k0).1 $
calc k * (m / k)
≤ m % k + k * (m / k) : le_add_left _ _
... = m : mod_add_div _ _
... ≤ k * n : h)
protected lemma div_le_self' (m n : ℕ) : m / n ≤ m :=
(eq_zero_or_pos n).elim
(λ n0, by rw [n0, nat.div_zero]; apply zero_le)
(λ n0, nat.div_le_of_le_mul' $ calc
m = 1 * m : (one_mul _).symm
... ≤ n * m : mul_le_mul_right _ n0)
/-- A version of `nat.div_lt_self` using successors, rather than additional hypotheses. -/
lemma div_lt_self' (n b : ℕ) : (n+1)/(b+2) < n+1 :=
nat.div_lt_self (nat.succ_pos n) (nat.succ_lt_succ (nat.succ_pos _))
theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y :=
le_div_iff_mul_le x y k0
theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k :=
lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0
protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k :=
(nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk,
(le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self _ _) h
lemma lt_of_div_lt_div {m n k : ℕ} (h : m / k < n / k) : m < n :=
by_contradiction $ λ h₁, absurd h (not_lt_of_ge (nat.div_le_div_right (not_lt.1 h₁)))
protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b :=
nat.pos_of_ne_zero (λ h, lt_irrefl a
(calc a = a % b : by simpa [h] using (mod_add_div a b).symm
... < b : nat.mod_lt a hb
... ≤ a : hba))
protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k :=
lt_of_mul_lt_mul_left
(calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _
... = m : mod_add_div _ _
... < n * k : h)
(nat.zero_le n)
lemma lt_mul_of_div_lt {a b c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c :=
lt_of_not_ge $ not_le_of_gt h ∘ (nat.le_div_iff_mul_le _ _ w).2
protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b :=
⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb,
λ h, by rw [← nat.mul_right_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div,
mod_eq_of_lt h, mul_zero, add_zero]⟩
protected lemma div_eq_zero {a b : ℕ} (hb : a < b) : a / b = 0 :=
(nat.div_eq_zero_iff $ (zero_le a).trans_lt hb).mpr hb
lemma eq_zero_of_le_div {a b : ℕ} (hb : 2 ≤ b) (h : a ≤ a / b) : a = 0 :=
eq_zero_of_mul_le hb $
by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hb)).1 h
lemma mul_div_le_mul_div_assoc (a b c : ℕ) : a * (b / c) ≤ (a * b) / c :=
if hc0 : c = 0 then by simp [hc0]
else (nat.le_div_iff_mul_le _ _ (nat.pos_of_ne_zero hc0)).2
(by rw [mul_assoc]; exact mul_le_mul_left _ (nat.div_mul_le_self _ _))
lemma div_mul_div_le_div (a b c : ℕ) : ((a / c) * b) / a ≤ b / c :=
if ha0 : a = 0 then by simp [ha0]
else calc a / c * b / a ≤ b * a / c / a :
nat.div_le_div_right (by rw [mul_comm];
exact mul_div_le_mul_div_assoc _ _ _)
... = b / c : by rw [nat.div_div_eq_div_mul, mul_comm b, mul_comm c,
nat.mul_div_mul _ _ (nat.pos_of_ne_zero ha0)]
lemma eq_zero_of_le_half {a : ℕ} (h : a ≤ a / 2) : a = 0 :=
eq_zero_of_le_div (le_refl _) h
protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) :
a = b * c :=
by rw [← H2, nat.mul_div_cancel' H1]
protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) :
a / b = c ↔ a = b * c :=
⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩
protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) :
a / b = c ↔ a = c * b :=
by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H'
protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) :
a = c * b :=
by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2]
protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b :=
by rw [mul_comm,nat.div_mul_cancel Hd]
/-! ### `mod`, `dvd` -/
lemma div_add_mod (m k : ℕ) : k * (m / k) + m % k = m :=
(nat.add_comm _ _).trans (mod_add_div _ _)
lemma mod_add_div' (m k : ℕ) : m % k + (m / k) * k = m :=
by { rw mul_comm, exact mod_add_div _ _ }
lemma div_add_mod' (m k : ℕ) : (m / k) * k + m % k = m :=
by { rw mul_comm, exact div_add_mod _ _ }
protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) :
n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k :=
⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩,
λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left];
simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩
lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 :=
by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]}
lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a :=
⟨b, (nat.div_mul_cancel h).symm⟩
protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b
| a 0 h₁ h₂ := by rw eq_zero_of_zero_dvd h₁; refl
| 0 b h₁ h₂ := absurd h₂ dec_trivial
| (a+1) (b+1) h₁ h₂ :=
(nat.mul_left_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $
by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁]
lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c :=
if hb : b = 0 then by simp [hb] else if hc : c = 0 then by simp [hc]
else by conv {to_rhs, rw ← mod_add_div a (b * c)};
rw [mul_assoc, nat.add_mul_div_left _ _ (nat.pos_of_ne_zero hb), add_mul_mod_self_left,
mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos (nat.pos_of_ne_zero hb) (nat.pos_of_ne_zero hc))))]
lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c :=
by rw [mul_comm c, mod_mul_right_div_self]
@[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 :=
⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩
protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m :=
(nat.dvd_add_iff_left h).symm
protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n :=
(nat.dvd_add_iff_right h).symm
@[simp] protected theorem not_two_dvd_bit1 (n : ℕ) : ¬ 2 ∣ bit1 n :=
mt (nat.dvd_add_right two_dvd_bit0).1 dec_trivial
/-- A natural number `m` divides the sum `m + n` if and only if `m` divides `n`.-/
@[simp] protected lemma dvd_add_self_left {m n : ℕ} :
m ∣ m + n ↔ m ∣ n :=
nat.dvd_add_right (dvd_refl m)
/-- A natural number `m` divides the sum `n + m` if and only if `m` divides `n`.-/
@[simp] protected lemma dvd_add_self_right {m n : ℕ} :
m ∣ n + m ↔ m ∣ n :=
nat.dvd_add_left (dvd_refl m)
lemma not_dvd_of_pos_of_lt {a b : ℕ} (h1 : 0 < b) (h2 : b < a) : ¬ a ∣ b :=
begin
rintros ⟨c, rfl⟩,
rcases eq_zero_or_pos c with (rfl | hc),
{ exact lt_irrefl 0 h1 },
{ exact not_lt.2 (le_mul_of_pos_right hc) h2 },
end
protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c :=
exists_congr $ λ d, by rw [mul_assoc, nat.mul_right_inj ha]
protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b :=
exists_congr $ λ d, by rw [mul_right_comm, nat.mul_left_inj hc]
lemma succ_div : ∀ (a b : ℕ), (a + 1) / b =
a / b + if b ∣ a + 1 then 1 else 0
| a 0 := by simp
| 0 1 := rfl
| 0 (b+2) := have hb2 : b + 2 > 1, from dec_trivial,
by simp [ne_of_gt hb2, div_eq_of_lt hb2]
| (a+1) (b+1) := begin
rw [nat.div_def], conv_rhs { rw nat.div_def },
by_cases hb_eq_a : b = a + 1,
{ simp [hb_eq_a, le_refl] },
by_cases hb_le_a1 : b ≤ a + 1,
{ have hb_le_a : b ≤ a, from le_of_lt_succ (lt_of_le_of_ne hb_le_a1 hb_eq_a),
have h₁ : (0 < b + 1 ∧ b + 1 ≤ a + 1 + 1),
from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a1⟩,
have h₂ : (0 < b + 1 ∧ b + 1 ≤ a + 1),
from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a⟩,
have dvd_iff : b + 1 ∣ a - b + 1 ↔ b + 1 ∣ a + 1 + 1,
{ rw [nat.dvd_add_iff_left (dvd_refl (b + 1)),
← nat.add_sub_add_right a 1 b, add_comm (_ - _), add_assoc,
nat.sub_add_cancel (succ_le_succ hb_le_a), add_comm 1] },
have wf : a - b < a + 1, from lt_succ_of_le (nat.sub_le_self _ _),
rw [if_pos h₁, if_pos h₂, nat.add_sub_add_right, nat.sub_add_comm hb_le_a,
by exact have _ := wf, succ_div (a - b),
nat.add_sub_add_right],
simp [dvd_iff, succ_eq_add_one, add_comm 1, add_assoc] },
{ have hba : ¬ b ≤ a,
from not_le_of_gt (lt_trans (lt_succ_self a) (lt_of_not_ge hb_le_a1)),
have hb_dvd_a : ¬ b + 1 ∣ a + 2,
from λ h, hb_le_a1 (le_of_succ_le_succ (le_of_dvd (succ_pos _) h)),
simp [hba, hb_le_a1, hb_dvd_a], }
end
lemma succ_div_of_dvd {a b : ℕ} (hba : b ∣ a + 1) :
(a + 1) / b = a / b + 1 :=
by rw [succ_div, if_pos hba]
lemma succ_div_of_not_dvd {a b : ℕ} (hba : ¬ b ∣ a + 1) :
(a + 1) / b = a / b :=
by rw [succ_div, if_neg hba, add_zero]
@[simp] theorem mod_mod_of_dvd (n : nat) {m k : nat} (h : m ∣ k) : n % k % m = n % m :=
begin
conv { to_rhs, rw ←mod_add_div n k },
rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left]
end
@[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n :=
(eq_zero_or_pos n).elim
(λ n0, by simp [n0])
(λ npos, mod_eq_of_lt (mod_lt _ npos))
/-- If `a` and `b` are equal mod `c`, `a - b` is zero mod `c`. -/
lemma sub_mod_eq_zero_of_mod_eq {a b c : ℕ} (h : a % c = b % c) : (a - b) % c = 0 :=
by rw [←nat.mod_add_div a c, ←nat.mod_add_div b c, ←h, ←nat.sub_sub, nat.add_sub_cancel_left,
←nat.mul_sub_left_distrib, nat.mul_mod_right]
@[simp] lemma one_mod (n : ℕ) : 1 % (n + 2) = 1 := nat.mod_eq_of_lt (add_lt_add_right n.succ_pos 1)
lemma dvd_sub_mod (k : ℕ) : n ∣ (k - (k % n)) :=
⟨k / n, nat.sub_eq_of_eq_add (nat.mod_add_div k n).symm⟩
@[simp] theorem mod_add_mod (m n k : ℕ) : (m % n + k) % n = (m + k) % n :=
by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm;
rwa [add_right_comm, mod_add_div] at this
@[simp] theorem add_mod_mod (m n k : ℕ) : (m + n % k) % k = (m + n) % k :=
by rw [add_comm, mod_add_mod, add_comm]
lemma add_mod (a b n : ℕ) : (a + b) % n = ((a % n) + (b % n)) % n :=
by rw [add_mod_mod, mod_add_mod]
theorem add_mod_eq_add_mod_right {m n k : ℕ} (i : ℕ) (H : m % n = k % n) :
(m + i) % n = (k + i) % n :=
by rw [← mod_add_mod, ← mod_add_mod k, H]
theorem add_mod_eq_add_mod_left {m n k : ℕ} (i : ℕ) (H : m % n = k % n) :
(i + m) % n = (i + k) % n :=
by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm]
lemma mul_mod (a b n : ℕ) : (a * b) % n = ((a % n) * (b % n)) % n :=
begin
conv_lhs {
rw [←mod_add_div a n, ←mod_add_div' b n, right_distrib, left_distrib, left_distrib,
mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, ← mul_assoc,
add_mul_mod_self_right] }
end
lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a :=
if ha : a = 0 then
by simp [ha]
else
have ha : 0 < a, from nat.pos_of_ne_zero ha,
have h1 : ∃ d, c = a * b * d, from h,
let ⟨d, hd⟩ := h1 in
have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd),
show ∃ d, c / a = b * d, from ⟨d, h2⟩
lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b :=
have h1 : ∃ d, b / c = a * d, from h,
have h2 : ∃ e, b = c * e, from hab,
let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in
have h3 : b = a * d * c, from
nat.eq_mul_of_div_eq_left hab hd,
show ∃ d, b = c * a * d, from ⟨d, by cc⟩
lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) :
(a / b) * (c / d) = (a * c) / (b * d) :=
have exi1 : ∃ x, a = b * x, from hab,
have exi2 : ∃ y, c = d * y, from hcd,
if hb : b = 0 then by simp [hb]
else have 0 < b, from nat.pos_of_ne_zero hb,
if hd : d = 0 then by simp [hd]
else have 0 < d, from nat.pos_of_ne_zero hd,
begin
cases exi1 with x hx, cases exi2 with y hy,
rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left],
symmetry,
apply nat.div_eq_of_eq_mul_left,
apply mul_pos,
repeat {assumption},
cc
end
@[simp]
lemma div_div_div_eq_div : ∀ {a b c : ℕ} (dvd : b ∣ a) (dvd2 : a ∣ c), (c / (a / b)) / b = c / a
| 0 _ := by simp
| (a + 1) 0 := λ _ dvd _, by simpa using dvd
| (a + 1) (c + 1) :=
have a_split : a + 1 ≠ 0 := succ_ne_zero a,
have c_split : c + 1 ≠ 0 := succ_ne_zero c,
λ b dvd dvd2,
begin
rcases dvd2 with ⟨k, rfl⟩,
rcases dvd with ⟨k2, pr⟩,
have k2_nonzero : k2 ≠ 0 := λ k2_zero, by simpa [k2_zero] using pr,
rw [nat.mul_div_cancel_left k (nat.pos_of_ne_zero a_split), pr,
nat.mul_div_cancel_left k2 (nat.pos_of_ne_zero c_split), nat.mul_comm ((c + 1) * k2) k,
←nat.mul_assoc k (c + 1) k2, nat.mul_div_cancel _ (nat.pos_of_ne_zero k2_nonzero),
nat.mul_div_cancel _ (nat.pos_of_ne_zero c_split)],
end
lemma eq_of_dvd_of_div_eq_one {a b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b :=
by rw [←nat.div_mul_cancel w, h, one_mul]
lemma eq_zero_of_dvd_of_div_eq_zero {a b : ℕ} (w : a ∣ b) (h : b / a = 0) : b = 0 :=
by rw [←nat.div_mul_cancel w, h, zero_mul]
/-- If a small natural number is divisible by a larger natural number,
the small number is zero. -/
lemma eq_zero_of_dvd_of_lt {a b : ℕ} (w : a ∣ b) (h : b < a) : b = 0 :=
nat.eq_zero_of_dvd_of_div_eq_zero w
((nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)).elim_right h)
lemma div_le_div_left {a b c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c :=
(nat.le_div_iff_mul_le _ _ h₂).2 $
le_trans (mul_le_mul_left _ h₁) (div_mul_le_self _ _)
lemma div_eq_self {a b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 :=
begin
split,
{ intro,
cases b,
{ simp * at * },
{ cases b,
{ right, refl },
{ left,
have : a / (b + 2) ≤ a / 2 := div_le_div_left (by simp) dec_trivial,
refine eq_zero_of_le_half _,
simp * at * } } },
{ rintros (rfl|rfl); simp }
end
/-! ### `pow` -/
-- This is redundant with `canonically_ordered_semiring.pow_le_pow_of_le_left`,
-- but `canonically_ordered_semiring` is not such an obvious abstraction, and also quite long.
-- So, we leave a version in the `nat` namespace as well.
-- (The global `pow_le_pow_of_le_left` needs an extra hypothesis `0 ≤ x`.)
protected theorem pow_le_pow_of_le_left {x y : ℕ} (H : x ≤ y) : ∀ i : ℕ, x^i ≤ y^i :=
canonically_ordered_semiring.pow_le_pow_of_le_left H
theorem pow_le_pow_of_le_right {x : ℕ} (H : x > 0) {i : ℕ} : ∀ {j}, i ≤ j → x^i ≤ x^j
| 0 h := by rw eq_zero_of_le_zero h; apply le_refl
| (succ j) h := (lt_or_eq_of_le h).elim
(λhl, by rw [pow_succ', ← nat.mul_one (x^i)]; exact
nat.mul_le_mul (pow_le_pow_of_le_right $ le_of_lt_succ hl) H)
(λe, by rw e; refl)
theorem pow_lt_pow_of_lt_left {x y : ℕ} (H : x < y) {i} (h : 0 < i) : x^i < y^i :=
begin
cases i with i, { exact absurd h (not_lt_zero _) },
rw [pow_succ', pow_succ'],
exact nat.mul_lt_mul' (nat.pow_le_pow_of_le_left (le_of_lt H) _) H
(pow_pos (lt_of_le_of_lt (zero_le _) H) _)
end
theorem pow_lt_pow_of_lt_right {x : ℕ} (H : x > 1) {i j : ℕ} (h : i < j) : x^i < x^j :=
begin
have xpos := lt_of_succ_lt H,
refine lt_of_lt_of_le _ (pow_le_pow_of_le_right xpos h),
rw [← nat.mul_one (x^i), pow_succ'],
exact nat.mul_lt_mul_of_pos_left H (pow_pos xpos _)
end
-- TODO: Generalize?
lemma pow_lt_pow_succ {p : ℕ} (h : 1 < p) (n : ℕ) : p^n < p^(n+1) :=
suffices 1*p^n < p*p^n, by simpa,
nat.mul_lt_mul_of_pos_right h (pow_pos (lt_of_succ_lt h) n)
lemma lt_pow_self {p : ℕ} (h : 1 < p) : ∀ n : ℕ, n < p ^ n
| 0 := by simp [zero_lt_one]
| (n+1) := calc
n + 1 < p^n + 1 : nat.add_lt_add_right (lt_pow_self _) _
... ≤ p ^ (n+1) : pow_lt_pow_succ h _
lemma lt_two_pow (n : ℕ) : n < 2^n :=
lt_pow_self dec_trivial n
lemma one_le_pow (n m : ℕ) (h : 0 < m) : 1 ≤ m^n :=
by { rw ←one_pow n, exact nat.pow_le_pow_of_le_left h n }
lemma one_le_pow' (n m : ℕ) : 1 ≤ (m+1)^n := one_le_pow n (m+1) (succ_pos m)
lemma one_le_two_pow (n : ℕ) : 1 ≤ 2^n := one_le_pow n 2 dec_trivial
lemma one_lt_pow (n m : ℕ) (h₀ : 0 < n) (h₁ : 1 < m) : 1 < m^n :=
by { rw ←one_pow n, exact pow_lt_pow_of_lt_left h₁ h₀ }
lemma one_lt_pow' (n m : ℕ) : 1 < (m+2)^(n+1) :=
one_lt_pow (n+1) (m+2) (succ_pos n) (nat.lt_of_sub_eq_succ rfl)
lemma one_lt_two_pow (n : ℕ) (h₀ : 0 < n) : 1 < 2^n := one_lt_pow n 2 h₀ dec_trivial
lemma one_lt_two_pow' (n : ℕ) : 1 < 2^(n+1) := one_lt_pow (n+1) 2 (succ_pos n) dec_trivial
lemma pow_right_strict_mono {x : ℕ} (k : 2 ≤ x) : strict_mono (λ (n : ℕ), x^n) :=
λ _ _, pow_lt_pow_of_lt_right k
lemma pow_le_iff_le_right {x m n : ℕ} (k : 2 ≤ x) : x^m ≤ x^n ↔ m ≤ n :=
strict_mono.le_iff_le (pow_right_strict_mono k)
lemma pow_lt_iff_lt_right {x m n : ℕ} (k : 2 ≤ x) : x^m < x^n ↔ m < n :=
strict_mono.lt_iff_lt (pow_right_strict_mono k)
lemma pow_right_injective {x : ℕ} (k : 2 ≤ x) : function.injective (λ (n : ℕ), x^n) :=
strict_mono.injective (pow_right_strict_mono k)
lemma pow_left_strict_mono {m : ℕ} (k : 1 ≤ m) : strict_mono (λ (x : ℕ), x^m) :=
λ _ _ h, pow_lt_pow_of_lt_left h k
lemma mul_lt_mul_pow_succ {n a q : ℕ} (a0 : 0 < a) (q1 : 1 < q) :
n * q < a * q ^ (n + 1) :=
begin
rw [pow_succ', ← mul_assoc, mul_lt_mul_right (zero_lt_one.trans q1)],
exact lt_mul_of_one_le_of_lt' (nat.succ_le_iff.mpr a0) (nat.lt_pow_self q1 n),
end
end nat
lemma strict_mono.nat_pow {n : ℕ} (hn : 1 ≤ n) {f : ℕ → ℕ} (hf : strict_mono f) :
strict_mono (λ m, (f m) ^ n) :=
(nat.pow_left_strict_mono hn).comp hf
namespace nat
lemma pow_le_iff_le_left {m x y : ℕ} (k : 1 ≤ m) : x^m ≤ y^m ↔ x ≤ y :=
strict_mono.le_iff_le (pow_left_strict_mono k)
lemma pow_lt_iff_lt_left {m x y : ℕ} (k : 1 ≤ m) : x^m < y^m ↔ x < y :=
strict_mono.lt_iff_lt (pow_left_strict_mono k)
lemma pow_left_injective {m : ℕ} (k : 1 ≤ m) : function.injective (λ (x : ℕ), x^m) :=
strict_mono.injective (pow_left_strict_mono k)
/-! ### `pow` and `mod` / `dvd` -/
theorem mod_pow_succ {b : ℕ} (b_pos : 0 < b) (w m : ℕ)
: m % (b^succ w) = b * (m/b % b^w) + m % b :=
begin
apply nat.strong_induction_on m,
clear m,
intros p IH,
cases lt_or_ge p (b^succ w) with h₁ h₁,
-- base case: p < b^succ w
{ have h₂ : p / b < b^w,
{ rw [div_lt_iff_lt_mul p _ b_pos],
simpa [pow_succ'] using h₁ },
rw [mod_eq_of_lt h₁, mod_eq_of_lt h₂],
simp [div_add_mod] },
-- step: p ≥ b^succ w
{ -- Generate condition for induction hypothesis
have h₂ : p - b^succ w < p,
{ apply sub_lt_of_pos_le _ _ (pow_pos b_pos _) h₁ },
-- Apply induction
rw [mod_eq_sub_mod h₁, IH _ h₂],
-- Normalize goal and h1
simp only [pow_succ],
simp only [ge, pow_succ] at h₁,
-- Pull subtraction outside mod and div
rw [sub_mul_mod _ _ _ h₁, sub_mul_div _ _ _ h₁],
-- Cancel subtraction inside mod b^w
have p_b_ge : b^w ≤ p / b,
{ rw [le_div_iff_mul_le _ _ b_pos, mul_comm],
exact h₁ },
rw [eq.symm (mod_eq_sub_mod p_b_ge)] }
end
lemma pow_dvd_pow_iff_pow_le_pow {k l : ℕ} : Π {x : ℕ} (w : 0 < x), x^k ∣ x^l ↔ x^k ≤ x^l
| (x+1) w :=
begin
split,
{ intro a, exact le_of_dvd (pow_pos (succ_pos x) l) a, },
{ intro a, cases x with x,
{ simp only [one_pow], },
{ have le := (pow_le_iff_le_right (le_add_left _ _)).mp a,
use (x+2)^(l-k),
rw [←pow_add, add_comm k, nat.sub_add_cancel le], } }
end
/-- If `1 < x`, then `x^k` divides `x^l` if and only if `k` is at most `l`. -/
lemma pow_dvd_pow_iff_le_right {x k l : ℕ} (w : 1 < x) : x^k ∣ x^l ↔ k ≤ l :=
by rw [pow_dvd_pow_iff_pow_le_pow (lt_of_succ_lt w), pow_le_iff_le_right w]
lemma pow_dvd_pow_iff_le_right' {b k l : ℕ} : (b+2)^k ∣ (b+2)^l ↔ k ≤ l :=
pow_dvd_pow_iff_le_right (nat.lt_of_sub_eq_succ rfl)
lemma not_pos_pow_dvd : ∀ {p k : ℕ} (hp : 1 < p) (hk : 1 < k), ¬ p^k ∣ p
| (succ p) (succ k) hp hk h :=
have succ p * (succ p)^k ∣ succ p * 1, by simpa,
have (succ p) ^ k ∣ 1, from dvd_of_mul_dvd_mul_left (succ_pos _) this,
have he : (succ p) ^ k = 1, from eq_one_of_dvd_one this,
have k < (succ p) ^ k, from lt_pow_self hp k,
have k < 1, by rwa [he] at this,
have k = 0, from eq_zero_of_le_zero $ le_of_lt_succ this,
have 1 < 1, by rwa [this] at hk,
absurd this dec_trivial
lemma pow_dvd_of_le_of_pow_dvd {p m n k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k :=
have p ^ m ∣ p ^ n, from pow_dvd_pow _ hmn,
dvd_trans this hdiv
lemma dvd_of_pow_dvd {p k m : ℕ} (hk : 1 ≤ k) (hpk : p^k ∣ m) : p ∣ m :=
by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk
lemma pow_div {x m n : ℕ} (h : n ≤ m) (hx : 0 < x) : x ^ m / x ^ n = x ^ (m - n) :=
by rw [nat.div_eq_iff_eq_mul_left (pow_pos hx n) (pow_dvd_pow _ h), pow_sub_mul_pow _ h]
/-- `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/
lemma exists_lt_and_lt_iff_not_dvd (m : ℕ) {n : ℕ} (hn : 0 < n) :
(∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬ n ∣ m :=
begin
split,
{ rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩, rw [mul_lt_mul_left hn] at h1k h2k,
rw [lt_succ_iff, ← not_lt] at h2k, exact h2k h1k },
{ intro h, rw [dvd_iff_mod_eq_zero, ← ne.def, ← pos_iff_ne_zero] at h,
simp only [← mod_add_div m n] {single_pass := tt},
refine ⟨m / n, lt_add_of_pos_left _ h, _⟩,
rw [add_comm _ 1, left_distrib, mul_one], exact add_lt_add_right (mod_lt _ hn) _ }
end
/-! ### `find` -/
section find
variables {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q]
lemma find_eq_iff (h : ∃ n : ℕ, p n) : nat.find h = m ↔ p m ∧ ∀ n < m, ¬ p n :=
begin
split,
{ rintro rfl, exact ⟨nat.find_spec h, λ _, nat.find_min h⟩ },
{ rintro ⟨hm, hlt⟩,
exact le_antisymm (nat.find_min' h hm) (not_lt.1 $ imp_not_comm.1 (hlt _) $ nat.find_spec h) }
end
@[simp] lemma find_lt_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h < n ↔ ∃ m < n, p m :=
⟨λ h2, ⟨nat.find h, h2, nat.find_spec h⟩, λ ⟨m, hmn, hm⟩, (nat.find_min' h hm).trans_lt hmn⟩
@[simp] lemma find_le_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h ≤ n ↔ ∃ m ≤ n, p m :=
by simp only [exists_prop, ← lt_succ_iff, find_lt_iff]
@[simp] lemma le_find_iff (h : ∃ (n : ℕ), p n) (n : ℕ) : n ≤ nat.find h ↔ ∀ m < n, ¬ p m :=
by simp_rw [← not_lt, not_iff_comm, not_forall, not_not, find_lt_iff]
@[simp] lemma lt_find_iff (h : ∃ n : ℕ, p n) (n : ℕ) : n < nat.find h ↔ ∀ m ≤ n, ¬ p m :=
by simp only [← succ_le_iff, le_find_iff, succ_le_succ_iff]
@[simp] lemma find_eq_zero (h : ∃ n : ℕ, p n) : nat.find h = 0 ↔ p 0 :=
by simp [find_eq_iff]
@[simp] lemma find_pos (h : ∃ n : ℕ, p n) : 0 < nat.find h ↔ ¬ p 0 :=
by rw [pos_iff_ne_zero, not_iff_not, nat.find_eq_zero]
theorem find_le (h : ∀ n, q n → p n) (hp : ∃ n, p n) (hq : ∃ n, q n) :
nat.find hp ≤ nat.find hq :=
nat.find_min' _ (h _ (nat.find_spec hq))
lemma find_comp_succ (h₁ : ∃ n, p n) (h₂ : ∃ n, p (n + 1)) (h0 : ¬ p 0) :
nat.find h₁ = nat.find h₂ + 1 :=
begin
refine (find_eq_iff _).2 ⟨nat.find_spec h₂, λ n hn, _⟩,
cases n with n,
exacts [h0, @nat.find_min (λ n, p (n + 1)) _ h₂ _ (succ_lt_succ_iff.1 hn)]
end
end find
/-! ### `find_greatest` -/
section find_greatest
/-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i`
exists -/
protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ
| 0 := 0
| (n + 1) := if P (n + 1) then n + 1 else find_greatest n
variables {P : ℕ → Prop} [decidable_pred P]
@[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl
@[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b
| 0 h := rfl
| (n + 1) h := by simp [nat.find_greatest, h]
@[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) :
nat.find_greatest P (b + 1) = nat.find_greatest P b :=
by simp [nat.find_greatest, h]
lemma find_greatest_eq_iff {b m} :
nat.find_greatest P b = m ↔ m ≤ b ∧ (m ≠ 0 → P m) ∧ (∀ ⦃n⦄, m < n → n ≤ b → ¬P n) :=
begin
induction b with b ihb generalizing m,
{ rw [eq_comm, iff.comm],
simp only [nonpos_iff_eq_zero, ne.def, and_iff_left_iff_imp, find_greatest_zero],
rintro rfl,
exact ⟨λ h, (h rfl).elim, λ n hlt heq, (hlt.ne heq.symm).elim⟩ },
{ by_cases hb : P (b + 1),
{ rw [find_greatest_eq hb], split,
{ rintro rfl,
exact ⟨le_refl _, λ _, hb, λ n hlt hle, (hlt.not_le hle).elim⟩ },
{ rintros ⟨hle, h0, hm⟩,
rcases hle.eq_or_lt with rfl|hlt,
exacts [rfl, (hm hlt (le_refl _) hb).elim] } },
{ rw [find_greatest_of_not hb, ihb],
split,
{ rintros ⟨hle, hP, hm⟩,
refine ⟨hle.trans b.le_succ, hP, λ n hlt hle, _⟩,
rcases hle.eq_or_lt with rfl|hlt',
exacts [hb, hm hlt $ lt_succ_iff.1 hlt'] },
{ rintros ⟨hle, hP, hm⟩,
refine ⟨lt_succ_iff.1 (hle.lt_of_ne _), hP, λ n hlt hle, hm hlt (hle.trans b.le_succ)⟩,
rintro rfl,
exact hb (hP b.succ_ne_zero) } } }
end
lemma find_greatest_eq_zero_iff {b} :
nat.find_greatest P b = 0 ↔ ∀ ⦃n⦄, 0 < n → n ≤ b → ¬P n :=
by simp [find_greatest_eq_iff]
lemma find_greatest_spec {b} (h : ∃m, m ≤ b ∧ P m) : P (nat.find_greatest P b) :=
begin
rcases h with ⟨m, hmb, hm⟩,
by_cases h : nat.find_greatest P b = 0,
{ cases m, { rwa h },
exact ((find_greatest_eq_zero_iff.1 h) m.zero_lt_succ hmb hm).elim },
{ exact (find_greatest_eq_iff.1 rfl).2.1 h }
end
lemma find_greatest_le {b} : nat.find_greatest P b ≤ b :=
(find_greatest_eq_iff.1 rfl).1
lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b :=
le_of_not_lt $ λ hlt, (find_greatest_eq_iff.1 rfl).2.2 hlt hmb hm
lemma find_greatest_is_greatest {b k} (hk : nat.find_greatest P b < k) (hkb : k ≤ b) :
¬ P k :=
(find_greatest_eq_iff.1 rfl).2.2 hk hkb
lemma find_greatest_of_ne_zero {b m} (h : nat.find_greatest P b = m) (h0 : m ≠ 0) : P m :=
(find_greatest_eq_iff.1 h).2.1 h0
end find_greatest
/-! ### `bodd_div2` and `bodd` -/
@[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) :=
by unfold bodd div2; cases bodd_div2 n; refl
@[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n
@[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n
@[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n
@[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n
/-! ### `bit0` and `bit1` -/
protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m :=
add_le_add h h
protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m :=
succ_le_succ (add_le_add h h)
theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m
| tt n m h := nat.bit1_le h
| ff n m h := nat.bit0_le h
theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 :=
by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _]
theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n
| tt m n h := le_of_lt $ nat.bit0_lt_bit1 h
| ff m n h := nat.bit0_le h
theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n
| ff m n h := le_of_lt $ nat.bit0_lt_bit1 h
| tt m n h := nat.bit1_le h
theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m
| tt n m h := nat.bit1_lt_bit0 h
| ff n m h := nat.bit0_lt h
theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m :=
lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _))
@[simp] lemma bit0_le_bit1_iff : bit0 k ≤ bit1 n ↔ k ≤ n :=
⟨λ h, by rwa [← nat.lt_succ_iff, n.bit1_eq_succ_bit0, ← n.bit0_succ_eq,
bit0_lt_bit0, nat.lt_succ_iff] at h, λ h, le_of_lt (nat.bit0_lt_bit1 h)⟩
@[simp] lemma bit0_lt_bit1_iff : bit0 k < bit1 n ↔ k ≤ n :=
⟨λ h, bit0_le_bit1_iff.1 (le_of_lt h), nat.bit0_lt_bit1⟩
@[simp] lemma bit1_le_bit0_iff : bit1 k ≤ bit0 n ↔ k < n :=
⟨λ h, by rwa [k.bit1_eq_succ_bit0, succ_le_iff, bit0_lt_bit0] at h,
λ h, le_of_lt (nat.bit1_lt_bit0 h)⟩
@[simp] lemma bit1_lt_bit0_iff : bit1 k < bit0 n ↔ k < n :=
⟨λ h, bit1_le_bit0_iff.1 (le_of_lt h), nat.bit1_lt_bit0⟩
@[simp] lemma one_le_bit0_iff : 1 ≤ bit0 n ↔ 0 < n :=
by { convert bit1_le_bit0_iff, refl, }
@[simp] lemma one_lt_bit0_iff : 1 < bit0 n ↔ 1 ≤ n :=
by { convert bit1_lt_bit0_iff, refl, }
@[simp] lemma bit_le_bit_iff : ∀ {b : bool}, bit b k ≤ bit b n ↔ k ≤ n
| ff := bit0_le_bit0
| tt := bit1_le_bit1
@[simp] lemma bit_lt_bit_iff : ∀ {b : bool}, bit b k < bit b n ↔ k < n
| ff := bit0_lt_bit0
| tt := bit1_lt_bit1
@[simp] lemma bit_le_bit1_iff : ∀ {b : bool}, bit b k ≤ bit1 n ↔ k ≤ n
| ff := bit0_le_bit1_iff
| tt := bit1_le_bit1
@[simp] lemma bit0_mod_two : bit0 n % 2 = 0 := by { rw nat.mod_two_of_bodd, simp }
@[simp] lemma bit1_mod_two : bit1 n % 2 = 1 := by { rw nat.mod_two_of_bodd, simp }
lemma pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n :=
by { cases n, cases h, apply succ_pos, }
/-- Define a function on `ℕ` depending on parity of the argument. -/
@[elab_as_eliminator]
def bit_cases {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : C n :=
eq.rec_on n.bit_decomp (H (bodd n) (div2 n))
/-! ### `shiftl` and `shiftr` -/
lemma shiftl_eq_mul_pow (m) : ∀ n, shiftl m n = m * 2 ^ n
| 0 := (nat.mul_one _).symm
| (k+1) := show bit0 (shiftl m k) = m * (2 * 2 ^ k),
by rw [bit0_val, shiftl_eq_mul_pow, mul_left_comm]
lemma shiftl'_tt_eq_mul_pow (m) : ∀ n, shiftl' tt m n + 1 = (m + 1) * 2 ^ n
| 0 := by simp [shiftl, shiftl', pow_zero, nat.one_mul]
| (k+1) :=
begin
change bit1 (shiftl' tt m k) + 1 = (m + 1) * (2 * 2 ^ k),
rw bit1_val,
change 2 * (shiftl' tt m k + 1) = _,
rw [shiftl'_tt_eq_mul_pow, mul_left_comm]
end
lemma one_shiftl (n) : shiftl 1 n = 2 ^ n :=
(shiftl_eq_mul_pow _ _).trans (nat.one_mul _)
@[simp] lemma zero_shiftl (n) : shiftl 0 n = 0 :=
(shiftl_eq_mul_pow _ _).trans (nat.zero_mul _)
lemma shiftr_eq_div_pow (m) : ∀ n, shiftr m n = m / 2 ^ n
| 0 := (nat.div_one _).symm
| (k+1) := (congr_arg div2 (shiftr_eq_div_pow k)).trans $
by rw [div2_val, nat.div_div_eq_div_mul, mul_comm]; refl
@[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 :=
(shiftr_eq_div_pow _ _).trans (nat.zero_div _)
theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 :=
by induction n; simp [shiftl', bit_ne_zero, *]
theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0
| 0 h := absurd rfl h
| (succ n) _ := nat.bit1_ne_zero _
/-! ### `size` -/
@[simp] theorem size_zero : size 0 = 0 := rfl
@[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) :=
begin
rw size,
conv { to_lhs, rw [binary_rec], simp [h] },
rw div2_bit,
end
@[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) :=
@size_bit ff n (nat.bit0_ne_zero h)
@[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) :=
@size_bit tt n (nat.bit1_ne_zero n)
@[simp] theorem size_one : size 1 = 1 := by apply size_bit1 0
@[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) :
size (shiftl' b m n) = size m + n :=
begin
induction n with n IH; simp [shiftl'] at h ⊢,
rw [size_bit h, nat.add_succ],
by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]],
rw s0 at h ⊢,
cases b, {exact absurd rfl h},
have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0,
rw [shiftl'_tt_eq_mul_pow] at this,
have m0 := succ.inj (eq_one_of_dvd_one ⟨_, this.symm⟩),
subst m0,
simp at this,
have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ λ hn,
ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this),
subst n, refl
end
@[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) :
size (shiftl m n) = size m + n :=
size_shiftl' (shiftl'_ne_zero_left _ h _)
theorem lt_size_self (n : ℕ) : n < 2^size n :=
begin
rw [← one_shiftl],
have : ∀ {n}, n = 0 → n < shiftl 1 (size n) :=
λ n e, by subst e; exact dec_trivial,
apply binary_rec _ _ n, {apply this rfl},
intros b n IH,
by_cases bit b n = 0, {apply this h},
rw [size_bit h, shiftl_succ],
exact bit_lt_bit0 _ IH
end
theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n :=
⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h),
begin
rw [← one_shiftl], revert n,
apply binary_rec _ _ m,
{ intros n h, apply zero_le },
{ intros b m IH n h,
by_cases e : bit b m = 0, { rw e, apply zero_le },
rw [size_bit e],
cases n with n,
{ exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) },
{ apply succ_le_succ (IH _),
apply lt_imp_lt_of_le_imp_le (λ h', bit0_le_bit _ h') h } }
end⟩
theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n :=
by rw [← not_lt, iff_not_comm, not_lt, size_le]
theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n :=
by rw lt_size; refl
theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 :=
by have := @size_pos n; simp [pos_iff_ne_zero] at this;
exact not_iff_not.1 this
theorem size_pow {n : ℕ} : size (2^n) = n+1 :=
le_antisymm
(size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _))
(lt_size.2 $ le_refl _)
theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n :=
size_le.2 $ lt_of_le_of_lt h (lt_size_self _)
/-! ### decidability of predicates -/
instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) :
∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) :=
begin
induction n with n IH; intro; resetI,
{ exact is_true (λ n, dec_trivial) },
cases IH (λ k h, P k (lt_succ_of_lt h)) with h,
{ refine is_false (mt _ h), intros hn k h, apply hn },
by_cases p : P n (lt_succ_self n),
{ exact is_true (λ k h',
(lt_or_eq_of_le $ le_of_lt_succ h').elim (h _)
(λ e, match k, e, h' with _, rfl, h := p end)) },
{ exact is_false (mt (λ hn, hn _ _) p) }
end
instance decidable_forall_fin {n : ℕ} (P : fin n → Prop)
[H : decidable_pred P] : decidable (∀ i, P i) :=
decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩
instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop)
[H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) :=
decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h))
⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩
instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] :
decidable (∀x, lo ≤ x → x < hi → P x) :=
decidable_of_iff (∀ x < hi - lo, P (lo + x))
⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $
(not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh);
rwa [nat.add_sub_of_le hl] at this,
λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩
instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] :
decidable (∀x, lo ≤ x → x ≤ hi → P x) :=
decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $
ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl
instance decidable_exists_lt {P : ℕ → Prop} [h : decidable_pred P] :
decidable_pred (λ n, ∃ (m : ℕ), m < n ∧ P m)
| 0 := is_false (by simp)
| (n + 1) := decidable_of_decidable_of_iff (@or.decidable _ _ (decidable_exists_lt n) (h n))
(by simp only [lt_succ_iff_lt_or_eq, or_and_distrib_right, exists_or_distrib, exists_eq_left])
end nat
|
68c49499e3cd8d9a5b769679d1ed2cc4d9118b47 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/uniform_space/abstract_completion.lean | 06110a8d31994b019fa5d4c0a796e97dd7e617ac | [
"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 | 11,692 | lean | /-
Copyright (c) 2019 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import topology.uniform_space.uniform_embedding
import topology.uniform_space.equiv
/-!
# Abstract theory of Hausdorff completions of uniform spaces
This file characterizes Hausdorff completions of a uniform space α as complete Hausdorff spaces
equipped with a map from α which has dense image and induce the original uniform structure on α.
Assuming these properties we "extend" uniformly continuous maps from α to complete Hausdorff spaces
to the completions of α. This is the universal property expected from a completion.
It is then used to extend uniformly continuous maps from α to α' to maps between
completions of α and α'.
This file does not construct any such completion, it only study consequences of their existence.
The first advantage is that formal properties are clearly highlighted without interference from
construction details. The second advantage is that this framework can then be used to compare
different completion constructions. See `topology/uniform_space/compare_reals` for an example.
Of course the comparison comes from the universal property as usual.
A general explicit construction of completions is done in `uniform_space/completion`, leading
to a functor from uniform spaces to complete Hausdorff uniform spaces that is left adjoint to the
inclusion, see `uniform_space/UniformSpace` for the category packaging.
## Implementation notes
A tiny technical advantage of using a characteristic predicate such as the properties listed in
`abstract_completion` instead of stating the universal property is that the universal property
derived from the predicate is more universe polymorphic.
## References
We don't know any traditional text discussing this. Real world mathematics simply silently
identify the results of any two constructions that lead to something one could reasonnably
call a completion.
## Tags
uniform spaces, completion, universal property
-/
noncomputable theory
local attribute [instance, priority 10] classical.prop_decidable
open filter set function
universes u
/-- A completion of `α` is the data of a complete separated uniform space (from the same universe)
and a map from `α` with dense range and inducing the original uniform structure on `α`. -/
structure abstract_completion (α : Type u) [uniform_space α] :=
(space : Type u)
(coe : α → space)
(uniform_struct : uniform_space space)
(complete : complete_space space)
(separation : separated_space space)
(uniform_inducing : uniform_inducing coe)
(dense : dense_range coe)
local attribute [instance]
abstract_completion.uniform_struct abstract_completion.complete abstract_completion.separation
namespace abstract_completion
variables {α : Type*} [uniform_space α] (pkg : abstract_completion α)
local notation `hatα` := pkg.space
local notation `ι` := pkg.coe
/-- If `α` is complete, then it is an abstract completion of itself. -/
def of_complete [separated_space α] [complete_space α] : abstract_completion α :=
mk α id infer_instance infer_instance infer_instance uniform_inducing_id dense_range_id
lemma closure_range : closure (range ι) = univ :=
pkg.dense.closure_range
lemma dense_inducing : dense_inducing ι :=
⟨pkg.uniform_inducing.inducing, pkg.dense⟩
lemma uniform_continuous_coe : uniform_continuous ι :=
uniform_inducing.uniform_continuous pkg.uniform_inducing
lemma continuous_coe : continuous ι :=
pkg.uniform_continuous_coe.continuous
@[elab_as_eliminator]
lemma induction_on {p : hatα → Prop}
(a : hatα) (hp : is_closed {a | p a}) (ih : ∀ a, p (ι a)) : p a :=
is_closed_property pkg.dense hp ih a
variables {β : Type*}
protected lemma funext [topological_space β] [t2_space β] {f g : hatα → β}
(hf : continuous f) (hg : continuous g)
(h : ∀ a, f (ι a) = g (ι a)) : f = g :=
funext $ assume a, pkg.induction_on a (is_closed_eq hf hg) h
variables [uniform_space β]
section extend
/-- Extension of maps to completions -/
protected def extend (f : α → β) : hatα → β :=
if uniform_continuous f then
pkg.dense_inducing.extend f
else
λ x, f (pkg.dense.some x)
variables {f : α → β}
lemma extend_def (hf : uniform_continuous f) : pkg.extend f = pkg.dense_inducing.extend f :=
if_pos hf
lemma extend_coe [t2_space β] (hf : uniform_continuous f) (a : α) :
(pkg.extend f) (ι a) = f a :=
begin
rw pkg.extend_def hf,
exact pkg.dense_inducing.extend_eq hf.continuous a
end
variables [complete_space β]
lemma uniform_continuous_extend : uniform_continuous (pkg.extend f) :=
begin
by_cases hf : uniform_continuous f,
{ rw pkg.extend_def hf,
exact uniform_continuous_uniformly_extend (pkg.uniform_inducing)
(pkg.dense) hf },
{ change uniform_continuous (ite _ _ _),
rw if_neg hf,
exact uniform_continuous_of_const (assume a b, by congr) }
end
lemma continuous_extend : continuous (pkg.extend f) :=
pkg.uniform_continuous_extend.continuous
variables [separated_space β]
lemma extend_unique (hf : uniform_continuous f) {g : hatα → β} (hg : uniform_continuous g)
(h : ∀ a : α, f a = g (ι a)) : pkg.extend f = g :=
begin
apply pkg.funext pkg.continuous_extend hg.continuous,
simpa only [pkg.extend_coe hf] using h
end
@[simp] lemma extend_comp_coe {f : hatα → β} (hf : uniform_continuous f) :
pkg.extend (f ∘ ι) = f :=
funext $ λ x, pkg.induction_on x (is_closed_eq pkg.continuous_extend hf.continuous)
(λ y, pkg.extend_coe (hf.comp $ pkg.uniform_continuous_coe) y)
end extend
section map_sec
variables (pkg' : abstract_completion β)
local notation `hatβ` := pkg'.space
local notation `ι'` := pkg'.coe
/-- Lifting maps to completions -/
protected def map (f : α → β) : hatα → hatβ := pkg.extend (ι' ∘ f)
local notation `map` := pkg.map pkg'
variables (f : α → β)
lemma uniform_continuous_map : uniform_continuous (map f) :=
pkg.uniform_continuous_extend
lemma continuous_map : continuous (map f) := pkg.continuous_extend
variables {f}
@[simp] lemma map_coe (hf : uniform_continuous f) (a : α) : map f (ι a) = ι' (f a) :=
pkg.extend_coe (pkg'.uniform_continuous_coe.comp hf) a
lemma map_unique {f : α → β} {g : hatα → hatβ}
(hg : uniform_continuous g) (h : ∀ a, ι' (f a) = g (ι a)) : map f = g :=
pkg.funext (pkg.continuous_map _ _) hg.continuous $
begin
intro a,
change pkg.extend (ι' ∘ f) _ = _,
simp only [(∘), h],
rw [pkg.extend_coe (hg.comp pkg.uniform_continuous_coe)]
end
@[simp] lemma map_id : pkg.map pkg id = id :=
pkg.map_unique pkg uniform_continuous_id (assume a, rfl)
variables {γ : Type*} [uniform_space γ]
lemma extend_map [complete_space γ] [separated_space γ] {f : β → γ} {g : α → β}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
pkg'.extend f ∘ map g = pkg.extend (f ∘ g) :=
pkg.funext (pkg'.continuous_extend.comp (pkg.continuous_map pkg' _)) pkg.continuous_extend $ λ a,
by rw [pkg.extend_coe (hf.comp hg), comp_app, pkg.map_coe pkg' hg, pkg'.extend_coe hf]
variables (pkg'' : abstract_completion γ)
lemma map_comp {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) :
(pkg'.map pkg'' g) ∘ (pkg.map pkg' f) = pkg.map pkg'' (g ∘ f) :=
pkg.extend_map pkg' (pkg''.uniform_continuous_coe.comp hg) hf
end map_sec
section compare
-- We can now compare two completion packages for the same uniform space
variables (pkg' : abstract_completion α)
/-- The comparison map between two completions of the same uniform space. -/
def compare : pkg.space → pkg'.space :=
pkg.extend pkg'.coe
lemma uniform_continuous_compare : uniform_continuous (pkg.compare pkg') :=
pkg.uniform_continuous_extend
lemma compare_coe (a : α) : pkg.compare pkg' (pkg.coe a) = pkg'.coe a :=
pkg.extend_coe pkg'.uniform_continuous_coe a
lemma inverse_compare : (pkg.compare pkg') ∘ (pkg'.compare pkg) = id :=
begin
have uc := pkg.uniform_continuous_compare pkg',
have uc' := pkg'.uniform_continuous_compare pkg,
apply pkg'.funext (uc.comp uc').continuous continuous_id,
intro a,
rw [comp_app, pkg'.compare_coe pkg, pkg.compare_coe pkg'],
refl
end
/-- The uniform bijection between two completions of the same uniform space. -/
def compare_equiv : pkg.space ≃ᵤ pkg'.space :=
{ to_fun := pkg.compare pkg',
inv_fun := pkg'.compare pkg,
left_inv := congr_fun (pkg'.inverse_compare pkg),
right_inv := congr_fun (pkg.inverse_compare pkg'),
uniform_continuous_to_fun := uniform_continuous_compare _ _,
uniform_continuous_inv_fun := uniform_continuous_compare _ _, }
lemma uniform_continuous_compare_equiv : uniform_continuous (pkg.compare_equiv pkg') :=
pkg.uniform_continuous_compare pkg'
lemma uniform_continuous_compare_equiv_symm : uniform_continuous (pkg.compare_equiv pkg').symm :=
pkg'.uniform_continuous_compare pkg
end compare
section prod
variables (pkg' : abstract_completion β)
local notation `hatβ` := pkg'.space
local notation `ι'` := pkg'.coe
/-- Products of completions -/
protected def prod : abstract_completion (α × β) :=
{ space := hatα × hatβ,
coe := λ p, ⟨ι p.1, ι' p.2⟩,
uniform_struct := prod.uniform_space,
complete := by apply_instance,
separation := by apply_instance,
uniform_inducing := uniform_inducing.prod pkg.uniform_inducing pkg'.uniform_inducing,
dense := pkg.dense.prod_map pkg'.dense }
end prod
section extension₂
variables (pkg' : abstract_completion β)
local notation `hatβ` := pkg'.space
local notation `ι'` := pkg'.coe
variables {γ : Type*} [uniform_space γ]
open function
/-- Extend two variable map to completions. -/
protected def extend₂ (f : α → β → γ) : hatα → hatβ → γ :=
curry $ (pkg.prod pkg').extend (uncurry f)
section separated_space
variables [separated_space γ] {f : α → β → γ}
lemma extension₂_coe_coe (hf : uniform_continuous $ uncurry f) (a : α) (b : β) :
pkg.extend₂ pkg' f (ι a) (ι' b) = f a b :=
show (pkg.prod pkg').extend (uncurry f) ((pkg.prod pkg').coe (a, b)) = uncurry f (a, b),
from (pkg.prod pkg').extend_coe hf _
end separated_space
variables {f : α → β → γ}
variables [complete_space γ] (f)
lemma uniform_continuous_extension₂ : uniform_continuous₂ (pkg.extend₂ pkg' f) :=
begin
rw [uniform_continuous₂_def, abstract_completion.extend₂, uncurry_curry],
apply uniform_continuous_extend
end
end extension₂
section map₂
variables (pkg' : abstract_completion β)
local notation `hatβ` := pkg'.space
local notation `ι'` := pkg'.coe
variables {γ : Type*} [uniform_space γ] (pkg'' : abstract_completion γ)
local notation `hatγ` := pkg''.space
local notation `ι''` := pkg''.coe
local notation f ` ∘₂ ` g := bicompr f g
/-- Lift two variable maps to completions. -/
protected def map₂ (f : α → β → γ) : hatα → hatβ → hatγ :=
pkg.extend₂ pkg' (pkg''.coe ∘₂ f)
lemma uniform_continuous_map₂ (f : α → β → γ) : uniform_continuous₂ (pkg.map₂ pkg' pkg'' f) :=
pkg.uniform_continuous_extension₂ pkg' _
lemma continuous_map₂ {δ} [topological_space δ] {f : α → β → γ}
{a : δ → hatα} {b : δ → hatβ} (ha : continuous a) (hb : continuous b) :
continuous (λd:δ, pkg.map₂ pkg' pkg'' f (a d) (b d)) :=
((pkg.uniform_continuous_map₂ pkg' pkg'' f).continuous.comp (continuous.prod_mk ha hb) : _)
lemma map₂_coe_coe (a : α) (b : β) (f : α → β → γ) (hf : uniform_continuous₂ f) :
pkg.map₂ pkg' pkg'' f (ι a) (ι' b) = ι'' (f a b) :=
pkg.extension₂_coe_coe pkg' (pkg''.uniform_continuous_coe.comp hf) a b
end map₂
end abstract_completion
|
7fcae2bb116e714cb1ccfeeff722171fda263885 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/group_power/order.lean | fd8c29cf9f09ae34dd78c99c802dfdce3d9a581f | [
"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 | 9,916 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis
-/
import algebra.ordered_ring
import algebra.group_power.basic
/-!
# Lemmas about the interaction of power operations with order
Note that some lemmas are in `algebra/group_power/lemmas.lean` as they import files which
depend on this file.
-/
variables {A R : Type*}
section add_monoid
variable [ordered_add_comm_monoid A]
theorem nsmul_nonneg {a : A} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n • a
| 0 := by rw [zero_nsmul]
| (n+1) := by { rw succ_nsmul, exact add_nonneg H (nsmul_nonneg n) }
lemma nsmul_pos {a : A} (ha : 0 < a) {k : ℕ} (hk : 0 < k) : 0 < k • a :=
begin
rcases nat.exists_eq_succ_of_ne_zero (ne_of_gt hk) with ⟨l, rfl⟩,
clear hk,
induction l with l IH,
{ simpa using ha },
{ rw succ_nsmul,
exact add_pos ha IH }
end
theorem nsmul_le_nsmul {a : A} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n • a ≤ m • a :=
let ⟨k, hk⟩ := nat.le.dest h in
calc n • a = n • a + 0 : (add_zero _).symm
... ≤ n • a + k • a : add_le_add_left (nsmul_nonneg ha _) _
... = m • a : by rw [← hk, add_nsmul]
lemma nsmul_le_nsmul_of_le_right {a b : A} (hab : a ≤ b) : ∀ i : ℕ, i • a ≤ i • b
| 0 := by simp [zero_nsmul]
| (k+1) := by { rw [succ_nsmul, succ_nsmul], exact add_le_add hab (nsmul_le_nsmul_of_le_right _) }
end add_monoid
section add_group
variable [ordered_add_comm_group A]
theorem gsmul_nonneg {a : A} (H : 0 ≤ a) {n : ℤ} (hn : 0 ≤ n) :
0 ≤ n • a :=
begin
lift n to ℕ using hn,
rw gsmul_coe_nat,
apply nsmul_nonneg H,
end
end add_group
section cancel_add_monoid
variable [ordered_cancel_add_comm_monoid A]
theorem nsmul_lt_nsmul {a : A} {n m : ℕ} (ha : 0 < a) (h : n < m) :
n • a < m • a :=
let ⟨k, hk⟩ := nat.le.dest h in
begin
have succ_swap : n.succ + k = n + k.succ := nat.succ_add n k,
calc n • a = (n • a : A) + (0 : A) : (add_zero _).symm
... < n • a + (k.succ • a : A) : add_lt_add_left (nsmul_pos ha (nat.succ_pos k)) _
... = m • a : by rw [← hk, succ_swap, add_nsmul]
end
end cancel_add_monoid
namespace canonically_ordered_semiring
variable [canonically_ordered_comm_semiring R]
theorem pow_pos {a : R} (H : 0 < a) : ∀ n : ℕ, 0 < a ^ n
| 0 := by { nontriviality, rw pow_zero, exact canonically_ordered_semiring.zero_lt_one }
| (n+1) := by { rw pow_succ, exact canonically_ordered_semiring.mul_pos.2 ⟨H, pow_pos n⟩ }
@[mono] lemma pow_le_pow_of_le_left {a b : R} (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i
| 0 := by simp
| (k+1) := by { rw [pow_succ, pow_succ],
exact canonically_ordered_semiring.mul_le_mul hab (pow_le_pow_of_le_left k) }
theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n :=
by simpa only [one_pow] using pow_le_pow_of_le_left H n
theorem pow_le_one {a : R} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1:=
by simpa only [one_pow] using pow_le_pow_of_le_left H n
end canonically_ordered_semiring
section ordered_semiring
variable [ordered_semiring R]
@[simp] theorem pow_pos {a : R} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n
| 0 := by { nontriviality, rw pow_zero, exact zero_lt_one }
| (n+1) := by { rw pow_succ, exact mul_pos H (pow_pos _) }
@[simp] theorem pow_nonneg {a : R} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n
| 0 := by { rw pow_zero, exact zero_le_one}
| (n+1) := by { rw pow_succ, exact mul_nonneg H (pow_nonneg _) }
theorem pow_add_pow_le {x y : R} {n : ℕ} (hx : 0 ≤ x) (hy : 0 ≤ y) (hn : n ≠ 0) :
x ^ n + y ^ n ≤ (x + y) ^ n :=
begin
rcases nat.exists_eq_succ_of_ne_zero hn with ⟨k, rfl⟩,
induction k with k ih, { simp only [pow_one] },
let n := k.succ,
have h1 := add_nonneg (mul_nonneg hx (pow_nonneg hy n)) (mul_nonneg hy (pow_nonneg hx n)),
have h2 := add_nonneg hx hy,
calc x^n.succ + y^n.succ
≤ x*x^n + y*y^n + (x*y^n + y*x^n) :
by { rw [pow_succ _ n, pow_succ _ n], exact le_add_of_nonneg_right h1 }
... = (x+y) * (x^n + y^n) :
by rw [add_mul, mul_add, mul_add, add_comm (y*x^n), ← add_assoc,
← add_assoc, add_assoc (x*x^n) (x*y^n), add_comm (x*y^n) (y*y^n), ← add_assoc]
... ≤ (x+y)^n.succ :
by { rw [pow_succ _ n], exact mul_le_mul_of_nonneg_left (ih (nat.succ_ne_zero k)) h2 }
end
theorem pow_lt_pow_of_lt_left {x y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) :
x ^ n < y ^ n :=
begin
cases lt_or_eq_of_le Hxpos,
{ rw ←nat.sub_add_cancel Hnpos,
induction (n - 1), { simpa only [pow_one] },
rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one],
apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) },
{ rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),}
end
theorem strict_mono_incr_on_pow {n : ℕ} (hn : 0 < n) :
strict_mono_incr_on (λ x : R, x ^ n) (set.Ici 0) :=
λ x hx y hy h, pow_lt_pow_of_lt_left h hx hn
theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n
| 0 := by rw [pow_zero]
| (n+1) := by { rw pow_succ, simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n)
zero_le_one (le_trans zero_le_one H) }
lemma pow_mono {a : R} (h : 1 ≤ a) : monotone (λ n : ℕ, a ^ n) :=
monotone_of_monotone_nat $ λ n,
by { rw pow_succ, exact le_mul_of_one_le_left (pow_nonneg (zero_le_one.trans h) _) h }
theorem pow_le_pow {a : R} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m :=
pow_mono ha h
lemma strict_mono_pow {a : R} (h : 1 < a) : strict_mono (λ n : ℕ, a ^ n) :=
have 0 < a := zero_le_one.trans_lt h,
strict_mono.nat $ λ n, by simpa only [one_mul, pow_succ]
using mul_lt_mul h (le_refl (a ^ n)) (pow_pos this _) this.le
lemma pow_lt_pow {a : R} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m :=
strict_mono_pow h h2
lemma pow_lt_pow_iff {a : R} {n m : ℕ} (h : 1 < a) : a ^ n < a ^ m ↔ n < m :=
(strict_mono_pow h).lt_iff_lt
@[mono] lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i
| 0 := by simp
| (k+1) := by { rw [pow_succ, pow_succ],
exact mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) }
end ordered_semiring
section linear_ordered_semiring
variable [linear_ordered_semiring R]
theorem pow_left_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n)
(Hxyn : x ^ n = y ^ n) : x = y :=
(@strict_mono_incr_on_pow R _ _ Hnpos).inj_on Hxpos Hypos Hxyn
lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b :=
lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h
lemma le_of_pow_le_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (hn : 0 < n) (h : a ^ n ≤ b ^ n) : a ≤ b :=
le_of_not_lt $ λ h1, not_le_of_lt (pow_lt_pow_of_lt_left h1 hb hn) h
end linear_ordered_semiring
section linear_ordered_ring
variable [linear_ordered_ring R]
lemma pow_abs (a : R) (n : ℕ) : (abs a) ^ n = abs (a ^ n) :=
((abs_hom.to_monoid_hom : R →* R).map_pow a n).symm
lemma abs_neg_one_pow (n : ℕ) : abs ((-1 : R) ^ n) = 1 :=
by rw [←pow_abs, abs_neg, abs_one, one_pow]
theorem pow_bit0_nonneg (a : R) (n : ℕ) : 0 ≤ a ^ bit0 n :=
by { rw pow_bit0, exact mul_self_nonneg _ }
theorem sq_nonneg (a : R) : 0 ≤ a ^ 2 :=
pow_bit0_nonneg a 1
alias sq_nonneg ← pow_two_nonneg
theorem pow_bit0_pos {a : R} (h : a ≠ 0) (n : ℕ) : 0 < a ^ bit0 n :=
(pow_bit0_nonneg a n).lt_of_ne (pow_ne_zero _ h).symm
theorem sq_pos_of_ne_zero (a : R) (h : a ≠ 0) : 0 < a ^ 2 :=
pow_bit0_pos h 1
alias sq_pos_of_ne_zero ← pow_two_pos_of_ne_zero
variables {x y : R}
theorem sq_abs (x : R) : abs x ^ 2 = x ^ 2 :=
by simpa only [sq] using abs_mul_abs_self x
theorem abs_sq (x : R) : abs (x ^ 2) = x ^ 2 :=
by simpa only [sq] using abs_mul_self x
theorem sq_lt_sq (h : abs x < y) : x ^ 2 < y ^ 2 :=
by simpa only [sq_abs] using pow_lt_pow_of_lt_left h (abs_nonneg x) (1:ℕ).succ_pos
theorem sq_lt_sq' (h1 : -y < x) (h2 : x < y) : x ^ 2 < y ^ 2 :=
sq_lt_sq (abs_lt.mpr ⟨h1, h2⟩)
theorem sq_le_sq (h : abs x ≤ abs y) : x ^ 2 ≤ y ^ 2 :=
by simpa only [sq_abs] using pow_le_pow_of_le_left (abs_nonneg x) h 2
theorem sq_le_sq' (h1 : -y ≤ x) (h2 : x ≤ y) : x ^ 2 ≤ y ^ 2 :=
sq_le_sq (le_trans (abs_le.mpr ⟨h1, h2⟩) (le_abs_self _))
theorem abs_lt_abs_of_sq_lt_sq (h : x^2 < y^2) : abs x < abs y :=
lt_of_pow_lt_pow 2 (abs_nonneg y) $ by rwa [← sq_abs x, ← sq_abs y] at h
theorem abs_lt_of_sq_lt_sq (h : x^2 < y^2) (hy : 0 ≤ y) : abs x < y :=
begin
rw [← abs_of_nonneg hy],
exact abs_lt_abs_of_sq_lt_sq h,
end
theorem abs_lt_of_sq_lt_sq' (h : x^2 < y^2) (hy : 0 ≤ y) : -y < x ∧ x < y :=
abs_lt.mp $ abs_lt_of_sq_lt_sq h hy
theorem abs_le_abs_of_sq_le_sq (h : x^2 ≤ y^2) : abs x ≤ abs y :=
le_of_pow_le_pow 2 (abs_nonneg y) (1:ℕ).succ_pos $ by rwa [← sq_abs x, ← sq_abs y] at h
theorem abs_le_of_sq_le_sq (h : x^2 ≤ y^2) (hy : 0 ≤ y) : abs x ≤ y :=
begin
rw [← abs_of_nonneg hy],
exact abs_le_abs_of_sq_le_sq h,
end
theorem abs_le_of_sq_le_sq' (h : x^2 ≤ y^2) (hy : 0 ≤ y) : -y ≤ x ∧ x ≤ y :=
abs_le.mp $ abs_le_of_sq_le_sq h hy
end linear_ordered_ring
section linear_ordered_comm_ring
variables [linear_ordered_comm_ring R]
@[simp] lemma eq_of_sq_eq_sq {a b : R} (ha : 0 ≤ a) (hb : 0 ≤ b) : a ^ 2 = b ^ 2 ↔ a = b :=
begin
refine ⟨_, congr_arg _⟩,
intros h,
refine (eq_or_eq_neg_of_sq_eq_sq _ _ h).elim id _,
rintros rfl,
rw le_antisymm (neg_nonneg.mp ha) hb,
exact neg_zero
end
/-- Arithmetic mean-geometric mean (AM-GM) inequality for linearly ordered commutative rings. -/
lemma two_mul_le_add_sq (a b : R) : 2 * a * b ≤ a ^ 2 + b ^ 2 :=
sub_nonneg.mp ((sub_add_eq_add_sub _ _ _).subst ((sub_sq a b).subst (sq_nonneg _)))
alias two_mul_le_add_sq ← two_mul_le_add_pow_two
end linear_ordered_comm_ring
|
9f741abcbec89b72b2c64c7758c4067f8c8b3267 | 6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b | /src/Lean/CoreM.lean | 9379c2a4486609c91e489f221d93e0d43f4d47eb | [
"Apache-2.0"
] | permissive | pbrinkmeier/lean4 | d31991fd64095e64490cb7157bcc6803f9c48af4 | 32fd82efc2eaf1232299e930ec16624b370eac39 | refs/heads/master | 1,681,364,001,662 | 1,618,425,427,000 | 1,618,425,427,000 | 358,314,562 | 0 | 0 | Apache-2.0 | 1,618,504,558,000 | 1,618,501,999,000 | null | UTF-8 | Lean | false | false | 5,886 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.RecDepth
import Lean.Util.Trace
import Lean.Data.Options
import Lean.Environment
import Lean.Exception
import Lean.InternalExceptionId
import Lean.Eval
import Lean.MonadEnv
import Lean.ResolveName
namespace Lean
namespace Core
register_builtin_option maxHeartbeats : Nat := {
defValue := 50000
descr := "maximum amount of heartbeats per command. A heartbeat is number of (small) memory allocations (in thousands), 0 means no limit"
}
def getMaxHeartbeats (opts : Options) : Nat :=
maxHeartbeats.get opts * 1000
structure State where
env : Environment
nextMacroScope : MacroScope := firstFrontendMacroScope + 1
ngen : NameGenerator := {}
traceState : TraceState := {}
deriving Inhabited
structure Context where
options : Options := {}
currRecDepth : Nat := 0
maxRecDepth : Nat := 1000
ref : Syntax := Syntax.missing
currNamespace : Name := Name.anonymous
openDecls : List OpenDecl := []
initHeartbeats : Nat := 0
maxHeartbeats : Nat := getMaxHeartbeats options
abbrev CoreM := ReaderT Context $ StateRefT State (EIO Exception)
instance : Inhabited (CoreM α) where
default := fun _ _ => throw arbitrary
instance : MonadRef CoreM where
getRef := return (← read).ref
withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x
instance : MonadEnv CoreM where
getEnv := return (← get).env
modifyEnv f := modify fun s => { s with env := f s.env }
instance : MonadOptions CoreM where
getOptions := return (← read).options
instance : AddMessageContext CoreM where
addMessageContext := addMessageContextPartial
instance : MonadNameGenerator CoreM where
getNGen := return (← get).ngen
setNGen ngen := modify fun s => { s with ngen := ngen }
instance : MonadRecDepth CoreM where
withRecDepth d x := withReader (fun ctx => { ctx with currRecDepth := d }) x
getRecDepth := return (← read).currRecDepth
getMaxRecDepth := return (← read).maxRecDepth
instance : MonadResolveName CoreM where
getCurrNamespace := return (← read).currNamespace
getOpenDecls := return (← read).openDecls
@[inline] def liftIOCore (x : IO α) : CoreM α := do
IO.toEIO (fun (err : IO.Error) => Exception.error (← getRef) (toString err)) x
instance : MonadLift IO CoreM where
monadLift := liftIOCore
instance : MonadTrace CoreM where
getTraceState := return (← get).traceState
modifyTraceState f := modify fun s => { s with traceState := f s.traceState }
/-- Restore backtrackable parts of the state. -/
def restore (b : State) : CoreM Unit :=
modify fun s => { s with env := b.env }
private def mkFreshNameImp (n : Name) : CoreM Name := do
let fresh ← modifyGet fun s => (s.nextMacroScope, { s with nextMacroScope := s.nextMacroScope + 1 })
return addMacroScope (← getEnv).mainModule n fresh
def mkFreshUserName (n : Name) : CoreM Name :=
mkFreshNameImp n
@[inline] def CoreM.run (x : CoreM α) (ctx : Context) (s : State) : EIO Exception (α × State) :=
(x ctx).run s
@[inline] def CoreM.run' (x : CoreM α) (ctx : Context) (s : State) : EIO Exception α :=
Prod.fst <$> x.run ctx s
@[inline] def CoreM.toIO (x : CoreM α) (ctx : Context) (s : State) : IO (α × State) := do
match (← (x.run { ctx with initHeartbeats := (← IO.getNumHeartbeats) } s).toIO') with
| Except.error (Exception.error _ msg) => do let e ← msg.toString; throw $ IO.userError e
| Except.error (Exception.internal id _) => throw <| IO.userError <| "internal exception #" ++ toString id.idx
| Except.ok a => return a
instance [MetaEval α] : MetaEval (CoreM α) where
eval env opts x _ := do
let x : CoreM α := do try x finally printTraces
let (a, s) ← x.toIO { maxRecDepth := maxRecDepth.get opts, options := opts } { env := env }
MetaEval.eval s.env opts a (hideUnit := true)
-- withIncRecDepth for a monad `m` such that `[MonadControlT CoreM n]`
protected def withIncRecDepth [Monad m] [MonadControlT CoreM m] (x : m α) : m α :=
controlAt CoreM fun runInBase => withIncRecDepth (runInBase x)
def checkMaxHeartbeatsCore (moduleName : String) (optionName : Name) (max : Nat) : CoreM Unit := do
unless max == 0 do
let numHeartbeats ← IO.getNumHeartbeats (ε := Exception)
if numHeartbeats - (← read).initHeartbeats > max then
throwError "(deterministic) timeout at '{moduleName}', maximum number of heartbeats ({max/1000}) has been reached (use 'set_option {optionName} <num>' to set the limit)"
def checkMaxHeartbeats (moduleName : String) : CoreM Unit := do
checkMaxHeartbeatsCore moduleName `maxHeartbeats (← read).maxHeartbeats
private def withCurrHeartbeatsImp (x : CoreM α) : CoreM α := do
let heartbeats ← IO.getNumHeartbeats (ε := Exception)
withReader (fun ctx => { ctx with initHeartbeats := heartbeats }) x
def withCurrHeartbeats [Monad m] [MonadControlT CoreM m] (x : m α) : m α :=
controlAt CoreM fun runInBase => withCurrHeartbeatsImp (runInBase x)
end Core
export Core (CoreM mkFreshUserName checkMaxHeartbeats withCurrHeartbeats)
@[inline] def catchInternalId [Monad m] [MonadExcept Exception m] (id : InternalExceptionId) (x : m α) (h : Exception → m α) : m α := do
try
x
catch ex => match ex with
| Exception.error _ _ => throw ex
| Exception.internal id' _ => if id == id' then h ex else throw ex
@[inline] def catchInternalIds [Monad m] [MonadExcept Exception m] (ids : List InternalExceptionId) (x : m α) (h : Exception → m α) : m α := do
try
x
catch ex => match ex with
| Exception.error _ _ => throw ex
| Exception.internal id _ => if ids.contains id then h ex else throw ex
end Lean
|
893e25eb2b2c4135ff360d9f1dfa81742cfd6d59 | cbcb0199842f03e7606d4e43666573fc15dd07a5 | /src/topology/basic.lean | 0234fe5e4ead5d5e255197bd7cbda463425bdec8 | [
"Apache-2.0"
] | permissive | truonghoangle/mathlib | a6a7c14b3767ec71156239d8ea97f6921fe79627 | 673bae584febcd830c2c9256eb7e7a81e27ed303 | refs/heads/master | 1,590,347,998,944 | 1,559,728,860,000 | 1,559,728,860,000 | 187,431,971 | 0 | 0 | null | 1,558,238,525,000 | 1,558,238,525,000 | null | UTF-8 | Lean | false | false | 35,249 | 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
Theory of topological spaces.
Parts of the formalization is based on the books:
N. Bourbaki: General Topology
I. M. James: Topologies and Uniformities
A major difference is that this formalization is heavily based on the filter library.
-/
import order.filter
open set filter lattice classical
local attribute [instance] prop_decidable
universes u v w
structure topological_space (α : Type u) :=
(is_open : set α → Prop)
(is_open_univ : is_open univ)
(is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t))
(is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s))
attribute [class] topological_space
section topological_space
variables {α : Type u} {β : Type v} {ι : Sort w} {a : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop}
@[extensionality]
lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g
| ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl
section
variables [t : topological_space α]
include t
/-- `is_open s` means that `s` is open in the ambient topological space on `α` -/
def is_open (s : set α) : Prop := topological_space.is_open t s
@[simp]
lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t
lemma is_open_inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) :=
topological_space.is_open_inter t s₁ s₂ h₁ h₂
lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) :=
topological_space.is_open_sUnion t s h
end
lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s :=
rfl
variables [topological_space α]
lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) :=
is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i
lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) :
is_open (⋃i∈s, f i) :=
is_open_Union $ assume i, is_open_Union $ assume hi, h i hi
lemma is_open_union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) :=
by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩)
@[simp] lemma is_open_empty : is_open (∅ : set α) :=
by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim)
lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) :=
finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $
λ a s has hs ih h, by rw sInter_insert; exact
is_open_inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _)
lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) :
(∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) :=
finite.induction_on hs
(λ _, by rw bInter_empty; exact is_open_univ)
(λ a s has hs ih h, by rw bInter_insert; exact
is_open_inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi))))
lemma is_open_const {p : Prop} : is_open {a : α | p} :=
by_cases
(assume : p, begin simp only [this]; exact is_open_univ end)
(assume : ¬ p, begin simp only [this]; exact is_open_empty end)
lemma is_open_and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} :=
is_open_inter
/-- A set is closed if its complement is open -/
def is_closed (s : set α) : Prop := is_open (-s)
@[simp] lemma is_closed_empty : is_closed (∅ : set α) :=
by unfold is_closed; rw compl_empty; exact is_open_univ
@[simp] lemma is_closed_univ : is_closed (univ : set α) :=
by unfold is_closed; rw compl_univ; exact is_open_empty
lemma is_closed_union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) :=
λ h₁ h₂, by unfold is_closed; rw compl_union; exact is_open_inter h₁ h₂
lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) :=
by simp only [is_closed, compl_sInter, sUnion_image]; exact assume h, is_open_Union $ assume t, is_open_Union $ assume ht, h t ht
lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) :=
is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq ▸ h i
@[simp] lemma is_open_compl_iff {s : set α} : is_open (-s) ↔ is_closed s := iff.rfl
@[simp] lemma is_closed_compl_iff {s : set α} : is_closed (-s) ↔ is_open s :=
by rw [←is_open_compl_iff, compl_compl]
lemma is_open_diff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) :=
is_open_inter h₁ $ is_open_compl_iff.mpr h₂
lemma is_closed_inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) :=
by rw [is_closed, compl_inter]; exact is_open_union h₁ h₂
lemma is_closed_Union {s : set β} {f : β → set α} (hs : finite s) :
(∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) :=
finite.induction_on hs
(λ _, by rw bUnion_empty; exact is_closed_empty)
(λ a s has hs ih h, by rw bUnion_insert; exact
is_closed_union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi))))
lemma is_closed_imp {p q : α → Prop} (hp : is_open {x | p x})
(hq : is_closed {x | q x}) : is_closed {x | p x → q x} :=
have {x | p x → q x} = (- {x | p x}) ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or,
by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq
lemma is_open_neg : is_closed {a | p a} → is_open {a | ¬ p a} :=
is_open_compl_iff.mpr
/-- The interior of a set `s` is the largest open subset of `s`. -/
def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s}
lemma mem_interior {s : set α} {x : α} :
x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm]
@[simp] lemma is_open_interior {s : set α} : is_open (interior s) :=
is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁
lemma interior_subset {s : set α} : interior s ⊆ s :=
sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂
lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s :=
subset_sUnion_of_mem ⟨h₂, h₁⟩
lemma interior_eq_of_open {s : set α} (h : is_open s) : interior s = s :=
subset.antisymm interior_subset (interior_maximal (subset.refl s) h)
lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s :=
⟨assume h, h ▸ is_open_interior, interior_eq_of_open⟩
lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s :=
by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and]
lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) :
s ⊆ interior t ↔ s ⊆ t :=
⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩
lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t :=
interior_maximal (subset.trans interior_subset h) is_open_interior
@[simp] lemma interior_empty : interior (∅ : set α) = ∅ :=
interior_eq_of_open is_open_empty
@[simp] lemma interior_univ : interior (univ : set α) = univ :=
interior_eq_of_open is_open_univ
@[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s :=
interior_eq_of_open is_open_interior
@[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t :=
subset.antisymm
(subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t))
(interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open_inter is_open_interior is_open_interior)
lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) :
interior (s ∪ t) = interior s :=
have interior (s ∪ t) ⊆ s, from
assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩,
classical.by_contradiction $ assume hx₂ : x ∉ s,
have u \ s ⊆ t,
from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂,
have u \ s ⊆ interior t,
by rwa subset_interior_iff_subset_of_open (is_open_diff hu₁ h₁),
have u \ s ⊆ ∅,
by rwa h₂ at this,
this ⟨hx₁, hx₂⟩,
subset.antisymm
(interior_maximal this is_open_interior)
(interior_mono $ subset_union_left _ _)
lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior]
/-- The closure of `s` is the smallest closed set containing `s`. -/
def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t}
@[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) :=
is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁
lemma subset_closure {s : set α} : s ⊆ closure s :=
subset_sInter $ assume t ⟨h₁, h₂⟩, h₂
lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t :=
sInter_subset_of_mem ⟨h₂, h₁⟩
lemma closure_eq_of_is_closed {s : set α} (h : is_closed s) : closure s = s :=
subset.antisymm (closure_minimal (subset.refl s) h) subset_closure
lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s :=
⟨assume h, h ▸ is_closed_closure, closure_eq_of_is_closed⟩
lemma closure_subset_iff_subset_of_is_closed {s t : set α} (h₁ : is_closed t) :
closure s ⊆ t ↔ s ⊆ t :=
⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩
lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_minimal (subset.trans h subset_closure) is_closed_closure
lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s :=
by rw subset.antisymm subset_closure h; exact is_closed_closure
@[simp] lemma closure_empty : closure (∅ : set α) = ∅ :=
closure_eq_of_is_closed is_closed_empty
lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ :=
begin
split; intro h,
{ rw set.eq_empty_iff_forall_not_mem,
intros x H,
simpa only [h] using subset_closure H },
{ exact (eq.symm h) ▸ closure_empty },
end
@[simp] lemma closure_univ : closure (univ : set α) = univ :=
closure_eq_of_is_closed is_closed_univ
@[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s :=
closure_eq_of_is_closed is_closed_closure
@[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t :=
subset.antisymm
(closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed_union is_closed_closure is_closed_closure)
(union_subset (closure_mono $ subset_union_left _ _) (closure_mono $ subset_union_right _ _))
lemma interior_subset_closure {s : set α} : interior s ⊆ closure s :=
subset.trans interior_subset subset_closure
lemma closure_eq_compl_interior_compl {s : set α} : closure s = - interior (- s) :=
begin
unfold interior closure is_closed,
rw [compl_sUnion, compl_image_set_of],
simp only [compl_subset_compl]
end
@[simp] lemma interior_compl {s : set α} : interior (- s) = - closure s :=
by simp [closure_eq_compl_interior_compl]
@[simp] lemma closure_compl {s : set α} : closure (- s) = - interior s :=
by simp [closure_eq_compl_interior_compl]
theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → o ∩ s ≠ ∅ :=
⟨λ h o oo ao os,
have s ⊆ -o, from λ x xs xo, @ne_empty_of_mem α (o∩s) x ⟨xo, xs⟩ os,
closure_minimal this (is_closed_compl_iff.2 oo) h ao,
λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc,
let ⟨x, hc, hs⟩ := exists_mem_of_ne_empty (H _ h₁ nc) in hc (h₂ hs)⟩
lemma dense_iff_inter_open {s : set α} : closure s = univ ↔ ∀ U, is_open U → U ≠ ∅ → U ∩ s ≠ ∅ :=
begin
split ; intro h,
{ intros U U_op U_ne,
cases exists_mem_of_ne_empty U_ne with x x_in,
exact mem_closure_iff.1 (by simp only [h]) U U_op x_in },
{ apply eq_univ_of_forall, intro x,
rw mem_closure_iff,
intros U U_op x_in,
exact h U U_op (ne_empty_of_mem x_in) },
end
/-- The frontier of a set is the set of points between the closure and interior. -/
def frontier (s : set α) : set α := closure s \ interior s
lemma frontier_eq_closure_inter_closure {s : set α} :
frontier s = closure s ∩ closure (- s) :=
by rw [closure_compl, frontier, diff_eq]
@[simp] lemma frontier_compl (s : set α) : frontier (-s) = frontier s :=
by simp only [frontier_eq_closure_inter_closure, lattice.neg_neg, inter_comm]
lemma is_closed_frontier {s : set α} : is_closed (frontier s) :=
by rw frontier_eq_closure_inter_closure; exact is_closed_inter is_closed_closure is_closed_closure
lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ :=
begin
have A : frontier s = s \ interior s, by rw [frontier, closure_eq_of_is_closed h],
have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _),
have C : interior (frontier s) ⊆ frontier s := interior_subset,
have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) :=
subset_inter B (by simpa [A] using C),
rwa [inter_diff_self, subset_empty_iff] at this,
end
/-- neighbourhood filter -/
def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s)
lemma nhds_sets {a : α} : (nhds a).sets = {s | ∃t⊆s, is_open t ∧ a ∈ t} :=
calc (nhds a).sets = (⋃s∈{s : set α| a ∈ s ∧ is_open s}, (principal s).sets) : infi_sets_eq'
(assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩,
⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩,
le_principal_iff.2 (inter_subset_left _ _),
le_principal_iff.2 (inter_subset_right _ _)⟩)
⟨univ, mem_univ _, is_open_univ⟩
... = {s | ∃t⊆s, is_open t ∧ a ∈ t} :
le_antisymm
(supr_le $ assume i, supr_le $ assume ⟨hi₁, hi₂⟩ t ht, ⟨i, ht, hi₂, hi₁⟩)
(assume t ⟨i, hi₁, hi₂, hi₃⟩, mem_Union.2 ⟨i, mem_Union.2 ⟨⟨hi₃, hi₂⟩, hi₁⟩⟩)
lemma map_nhds {a : α} {f : α → β} :
map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal (image f s)) :=
calc map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, map f (principal s)) :
map_binfi_eq
(assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩,
⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩,
le_principal_iff.2 (inter_subset_left _ _),
le_principal_iff.2 (inter_subset_right _ _)⟩)
⟨univ, mem_univ _, is_open_univ⟩
... = _ : by simp only [map_principal]
lemma mem_nhds_sets_iff {a : α} {s : set α} :
s ∈ nhds a ↔ ∃t⊆s, is_open t ∧ a ∈ t :=
by simp only [nhds_sets, mem_set_of_eq, exists_prop]
lemma mem_of_nhds {a : α} {s : set α} : s ∈ nhds a → a ∈ s :=
λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_sets_iff.1 H in ht hs
lemma mem_nhds_sets {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) :
s ∈ nhds a :=
mem_nhds_sets_iff.2 ⟨s, subset.refl _, hs, ha⟩
theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) :
(∀ s ∈ nhds x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) :=
iff.intro
(λ h s os xs, h s (mem_nhds_sets os xs))
(λ h t,
begin
change t ∈ (nhds x).sets → P t,
rw nhds_sets,
rintros ⟨s, hs, opens, xs⟩,
exact hP _ _ hs (h s opens xs),
end)
theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t)
(l : filter β) :
(∀ s ∈ nhds x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) :=
all_mem_nhds _ _ (λ s t ssubt h, mem_sets_of_superset h (hf s t ssubt))
theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} :
rtendsto r l (nhds a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) :=
all_mem_nhds_filter _ _ (λ s t h, λ x hx, λ y hy, h (hx y hy)) _
theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} :
rtendsto' r l (nhds a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) :=
by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono }
theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} :
ptendsto f l (nhds a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) :=
rtendsto_nhds
theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} :
ptendsto' f l (nhds a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) :=
rtendsto'_nhds
theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} :
tendsto f l (nhds a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) :=
all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _
lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (nhds a) :=
tendsto_nhds.mpr $ assume s hs ha, univ_mem_sets' $ assume _, ha
lemma pure_le_nhds : pure ≤ (nhds : α → filter α) :=
assume a, le_infi $ assume s, le_infi $ assume ⟨h₁, _⟩, principal_mono.mpr $
singleton_subset_iff.2 h₁
lemma tendsto_pure_nhds [topological_space β] (f : α → β) (a : α) :
tendsto f (pure a) (nhds (f a)) :=
begin
rw [tendsto, filter.map_pure],
exact pure_le_nhds (f a)
end
@[simp] lemma nhds_neq_bot {a : α} : nhds a ≠ ⊥ :=
assume : nhds a = ⊥,
have pure a = (⊥ : filter α),
from lattice.bot_unique $ this ▸ pure_le_nhds a,
pure_neq_bot this
lemma interior_eq_nhds {s : set α} : interior s = {a | nhds a ≤ principal s} :=
set.ext $ λ x, by simp only [mem_interior, le_principal_iff, mem_nhds_sets_iff]; refl
lemma mem_interior_iff_mem_nhds {s : set α} {a : α} :
a ∈ interior s ↔ s ∈ nhds a :=
by simp only [interior_eq_nhds, le_principal_iff]; refl
lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, nhds a ≤ principal s :=
calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm
... ↔ (∀a∈s, nhds a ≤ principal s) : by rw [interior_eq_nhds]; refl
lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ nhds a :=
is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff
lemma closure_eq_nhds {s : set α} : closure s = {a | nhds a ⊓ principal s ≠ ⊥} :=
calc closure s = - interior (- s) : closure_eq_compl_interior_compl
... = {a | ¬ nhds a ≤ principal (-s)} : by rw [interior_eq_nhds]; refl
... = {a | nhds a ⊓ principal s ≠ ⊥} : set.ext $ assume a, not_congr
(inf_eq_bot_iff_le_compl
(show principal s ⊔ principal (-s) = ⊤, by simp only [sup_principal, union_compl_self, principal_univ])
(by simp only [inf_principal, inter_compl_self, principal_empty])).symm
theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ nhds a, t ∩ s ≠ ∅ :=
mem_closure_iff.trans
⟨λ H t ht, subset_ne_empty
(inter_subset_inter_left _ interior_subset)
(H _ is_open_interior (mem_interior_iff_mem_nhds.2 ht)),
λ H o oo ao, H _ (mem_nhds_sets oo ao)⟩
/-- `x` belongs to the closure of `s` if and only if some ultrafilter
supported on `s` converges to `x`. -/
lemma mem_closure_iff_ultrafilter {s : set α} {x : α} :
x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u.val ∧ u.val ≤ nhds x :=
begin
rw closure_eq_nhds, change nhds x ⊓ principal s ≠ ⊥ ↔ _, symmetry,
convert exists_ultrafilter_iff _, ext u,
rw [←le_principal_iff, inf_comm, le_inf_iff]
end
lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s :=
calc is_closed s ↔ closure s = s : by rw [closure_eq_iff_is_closed]
... ↔ closure s ⊆ s : ⟨assume h, by rw h, assume h, subset.antisymm h subset_closure⟩
... ↔ (∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s) : by rw [closure_eq_nhds]; refl
lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) :=
assume a ⟨hs, ht⟩,
have s ∈ nhds a, from mem_nhds_sets h hs,
have nhds a ⊓ principal s = nhds a, from inf_of_le_left $ by rwa le_principal_iff,
have nhds a ⊓ principal (s ∩ t) ≠ ⊥,
from calc nhds a ⊓ principal (s ∩ t) = nhds a ⊓ (principal s ⊓ principal t) : by rw inf_principal
... = nhds a ⊓ principal t : by rw [←inf_assoc, this]
... ≠ ⊥ : by rw [closure_eq_nhds] at ht; assumption,
by rw [closure_eq_nhds]; assumption
lemma closure_diff {s t : set α} : closure s - closure t ⊆ closure (s - t) :=
calc closure s \ closure t = (- closure t) ∩ closure s : by simp only [diff_eq, inter_comm]
... ⊆ closure (- closure t ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure
... = closure (s \ closure t) : by simp only [diff_eq, inter_comm]
... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure
lemma mem_of_closed_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
(hb : b ≠ ⊥) (hf : tendsto f b (nhds a)) (hs : is_closed s) (h : f ⁻¹' s ∈ b) : a ∈ s :=
have b.map f ≤ nhds a ⊓ principal s,
from le_trans (le_inf (le_refl _) (le_principal_iff.mpr h)) (inf_le_inf hf (le_refl _)),
is_closed_iff_nhds.mp hs a $ neq_bot_of_le_neq_bot (map_ne_bot hb) this
lemma mem_of_closed_of_tendsto' {f : β → α} {x : filter β} {a : α} {s : set α}
(hf : tendsto f x (nhds a)) (hs : is_closed s) (h : x ⊓ principal (f ⁻¹' s) ≠ ⊥) : a ∈ s :=
is_closed_iff_nhds.mp hs _ $ neq_bot_of_le_neq_bot (@map_ne_bot _ _ _ f h) $
le_inf (le_trans (map_mono $ inf_le_left) hf) $
le_trans (map_mono $ inf_le_right_of_le $ by simp only [comap_principal, le_principal_iff]; exact subset.refl _) (@map_comap_le _ _ _ f)
lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
(hb : b ≠ ⊥) (hf : tendsto f b (nhds a)) (h : f ⁻¹' s ∈ b) : a ∈ closure s :=
mem_of_closed_of_tendsto hb hf (is_closed_closure) $
filter.mem_sets_of_superset h (preimage_mono subset_closure)
section lim
variables [inhabited α]
/-- If `f` is a filter, then `lim f` is a limit of the filter, if it exists. -/
noncomputable def lim (f : filter α) : α := epsilon $ λa, f ≤ nhds a
lemma lim_spec {f : filter α} (h : ∃a, f ≤ nhds a) : f ≤ nhds (lim f) := epsilon_spec h
end lim
/-
The nhds_within filter.
-/
def nhds_within (a : α) (s : set α) : filter α := nhds a ⊓ principal s
theorem nhds_within_eq (a : α) (s : set α) :
nhds_within a s = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, principal (t ∩ s) :=
have set.univ ∈ {s : set α | a ∈ s ∧ is_open s}, from ⟨set.mem_univ _, is_open_univ⟩,
begin
rw [nhds_within, nhds, lattice.binfi_inf]; try { exact this },
simp only [inf_principal]
end
theorem nhds_within_univ (a : α) : nhds_within a set.univ = nhds a :=
by rw [nhds_within, principal_univ, lattice.inf_top_eq]
theorem mem_nhds_within (t : set α) (a : α) (s : set α) :
t ∈ nhds_within a s ↔ ∃ u, is_open u ∧ a ∈ u ∧ u ∩ s ⊆ t :=
begin
rw [nhds_within, mem_inf_principal, mem_nhds_sets_iff], split,
{ rintros ⟨u, hu, openu, au⟩,
exact ⟨u, openu, au, λ x ⟨xu, xs⟩, hu xu xs⟩ },
rintros ⟨u, openu, au, hu⟩,
exact ⟨u, λ x xu xs, hu ⟨xu, xs⟩, openu, au⟩
end
theorem nhds_within_mono (a : α) {s t : set α} (h : s ⊆ t) : nhds_within a s ≤ nhds_within a t :=
lattice.inf_le_inf (le_refl _) (principal_mono.mpr 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) :=
have s ∩ t ∈ nhds_within a s,
from inter_mem_sets (mem_inf_sets_of_right (mem_principal_self s))
(mem_inf_sets_of_left (mem_nhds_sets h₁ h₀)),
le_antisymm
(lattice.le_inf lattice.inf_le_left (le_principal_iff.mpr this))
(lattice.inf_le_inf (le_refl _) (principal_mono.mpr (set.inter_subset_left _ _)))
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 = nhds 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, lattice.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 [←lattice.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 [lattice.inf_left_comm, lattice.inf_assoc, inf_principal,
←lattice.inf_assoc, lattice.inf_idem]
theorem nhds_within_inter' (a : α) (s t : set α) :
nhds_within a (s ∩ t) = (nhds_within a s) ⊓ principal t :=
by { unfold nhds_within, rw [←inf_principal, lattice.inf_assoc] }
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}, principal (set.image f (t ∩ s)) :=
have h₀ : directed_on ((λ (i : set α), principal (i ∩ s)) ⁻¹'o ge)
{x : set α | x ∈ {t : set α | a ∈ t ∧ is_open t}}, from
assume x ⟨ax, openx⟩ y ⟨ay, openy⟩,
⟨x ∩ y, ⟨⟨ax, ay⟩, is_open_inter openx openy⟩,
le_principal_iff.mpr (set.inter_subset_inter_left _ (set.inter_subset_left _ _)),
le_principal_iff.mpr (set.inter_subset_inter_left _ (set.inter_subset_right _ _))⟩,
have h₁ : ∃ (i : set α), i ∈ {t : set α | a ∈ t ∧ is_open t},
from ⟨set.univ, set.mem_univ _, is_open_univ⟩,
by { rw [nhds_within_eq, map_binfi_eq h₀ h₁], simp only [map_principal] }
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 (nhds 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
/- locally finite family [General Topology (Bourbaki, 1995)] -/
section locally_finite
/-- A family of sets in `set α` is locally finite if at every point `x:α`,
there is a neighborhood of `x` which meets only finitely many sets in the family -/
def locally_finite (f : β → set α) :=
∀x:α, ∃t ∈ nhds x, finite {i | f i ∩ t ≠ ∅ }
lemma locally_finite_of_finite {f : β → set α} (h : finite (univ : set β)) : locally_finite f :=
assume x, ⟨univ, univ_mem_sets, finite_subset h $ subset_univ _⟩
lemma locally_finite_subset
{f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ :=
assume a,
let ⟨t, ht₁, ht₂⟩ := hf₂ a in
⟨t, ht₁, finite_subset ht₂ $ assume i hi,
neq_bot_of_le_neq_bot hi $ inter_subset_inter (hf i) $ subset.refl _⟩
lemma is_closed_Union_of_locally_finite {f : β → set α}
(h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) :=
is_open_iff_nhds.mpr $ assume a, assume h : a ∉ (⋃i, f i),
have ∀i, a ∈ -f i,
from assume i hi, h $ mem_Union.2 ⟨i, hi⟩,
have ∀i, - f i ∈ (nhds a).sets,
by rw [nhds_sets]; exact assume i, ⟨- f i, subset.refl _, h₂ i, this i⟩,
let ⟨t, h_sets, (h_fin : finite {i | f i ∩ t ≠ ∅ })⟩ := h₁ a in
calc nhds a ≤ principal (t ∩ (⋂ i∈{i | f i ∩ t ≠ ∅ }, - f i)) :
begin
rw [le_principal_iff],
apply @filter.inter_mem_sets _ (nhds a) _ _ h_sets,
apply @filter.Inter_mem_sets _ (nhds a) _ _ _ h_fin,
exact assume i h, this i
end
... ≤ principal (- ⋃i, f i) :
begin
simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq,
mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists,
not_eq_empty_iff_exists, exists_imp_distrib, (≠)],
exact assume x xt ht i xfi, ht i x xfi xt xfi
end
end locally_finite
end topological_space
section continuous
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
variables [topological_space α] [topological_space β] [topological_space γ]
/-- A function between topological spaces is continuous if the preimage
of every open set is open. -/
def continuous (f : α → β) := ∀s, is_open s → is_open (f ⁻¹' s)
def continuous_at (f : α → β) (x : α) := tendsto f (nhds x) (nhds (f x))
def continuous_within_at (f : α → β) (s : set α) (x : α) : Prop :=
tendsto f (nhds_within x s) (nhds (f x))
def continuous_on (f : α → β) (s : set α) : Prop := ∀ x ∈ s, continuous_within_at f s x
lemma continuous_id : continuous (id : α → α) :=
assume s h, h
lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) :
continuous (g ∘ f) :=
assume s h, hf _ (hg s h)
lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) :
tendsto f (nhds x) (nhds (f x)) | s :=
show s ∈ nhds (f x) → s ∈ map f (nhds x),
by simp [nhds_sets]; exact
assume t t_subset t_open fx_in_t,
⟨f ⁻¹' t, preimage_mono t_subset, hf t t_open, fx_in_t⟩
lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x :=
⟨continuous.tendsto,
assume hf : ∀x, tendsto f (nhds x) (nhds (f x)),
assume s, assume hs : is_open s,
have ∀a, f a ∈ s → s ∈ nhds (f a),
by simp [nhds_sets]; exact assume a ha, ⟨s, subset.refl s, hs, ha⟩,
show is_open (f ⁻¹' s),
by simp [is_open_iff_nhds]; exact assume a ha, hf a (this a ha)⟩
lemma continuous_const {b : β} : continuous (λa:α, b) :=
continuous_iff_continuous_at.mpr $ assume a, tendsto_const_nhds
lemma continuous_iff_is_closed {f : α → β} :
continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) :=
⟨assume hf s hs, hf (-s) hs,
assume hf s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩
lemma continuous_at_iff_ultrafilter {f : α → β} (x) : continuous_at f x ↔
∀ g, is_ultrafilter g → g ≤ nhds x → g.map f ≤ nhds (f x) :=
tendsto_iff_ultrafilter f (nhds x) (nhds (f x))
lemma continuous_iff_ultrafilter {f : α → β} :
continuous f ↔ ∀ x g, is_ultrafilter g → g ≤ nhds x → g.map f ≤ nhds (f x) :=
by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter]
lemma continuous_if {p : α → Prop} {f g : α → β} {h : ∀a, decidable (p a)}
(hp : ∀a∈frontier {a | p a}, f a = g a) (hf : continuous f) (hg : continuous g) :
continuous (λa, @ite (p a) (h a) β (f a) (g a)) :=
continuous_iff_is_closed.mpr $
assume s hs,
have (λa, ite (p a) (f a) (g a)) ⁻¹' s =
(closure {a | p a} ∩ f ⁻¹' s) ∪ (closure {a | ¬ p a} ∩ g ⁻¹' s),
from set.ext $ assume a,
classical.by_cases
(assume : a ∈ frontier {a | p a},
have hac : a ∈ closure {a | p a}, from this.left,
have hai : a ∈ closure {a | ¬ p a},
from have a ∈ - interior {a | p a}, from this.right, by rwa [←closure_compl] at this,
by by_cases p a; simp [h, hp a this, hac, hai, iff_def] {contextual := tt})
(assume hf : a ∈ - frontier {a | p a},
classical.by_cases
(assume : p a,
have hc : a ∈ closure {a | p a}, from subset_closure this,
have hnc : a ∉ closure {a | ¬ p a},
by show a ∉ closure (- {a | p a}); rw [closure_compl]; simpa [frontier, hc] using hf,
by simp [this, hc, hnc])
(assume : ¬ p a,
have hc : a ∈ closure {a | ¬ p a}, from subset_closure this,
have hnc : a ∉ closure {a | p a},
begin
have hc : a ∈ closure (- {a | p a}), from hc,
simp [closure_compl] at hc,
simpa [frontier, hc] using hf
end,
by simp [this, hc, hnc])),
by rw [this]; exact is_closed_union
(is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hf s hs)
(is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hg s hs)
/- Continuity and partial functions -/
def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s)
lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom :=
by rw [←pfun.preimage_univ]; exact h _ is_open_univ
lemma pcontinuous_iff' {f : α →. β} :
pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (nhds x) (nhds y) :=
begin
split,
{ intros h x y h',
rw [ptendsto'_def],
change ∀ (s : set β), s ∈ (nhds y).sets → pfun.preimage f s ∈ (nhds x).sets,
rw [nhds_sets, nhds_sets],
rintros s ⟨t, tsubs, opent, yt⟩,
exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩
},
intros hf s os,
rw is_open_iff_nhds,
rintros x ⟨y, ys, fxy⟩ t,
rw [mem_principal_sets],
assume h : f.preimage s ⊆ t,
change t ∈ nhds x,
apply mem_sets_of_superset _ h,
have h' : ∀ s ∈ nhds y, f.preimage s ∈ nhds x,
{ intros s hs,
have : ptendsto' f (nhds x) (nhds y) := hf fxy,
rw ptendsto'_def at this,
exact this s hs },
show f.preimage s ∈ nhds x,
apply h', rw mem_nhds_sets_iff, exact ⟨s, set.subset.refl _, os, ys⟩
end
lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) :
f '' closure s ⊆ closure (f '' s) :=
have ∀ (a : α), nhds a ⊓ principal s ≠ ⊥ → nhds (f a) ⊓ principal (f '' s) ≠ ⊥,
from assume a ha,
have h₁ : ¬ map f (nhds a ⊓ principal s) = ⊥,
by rwa[map_eq_bot_iff],
have h₂ : map f (nhds a ⊓ principal s) ≤ nhds (f a) ⊓ principal (f '' s),
from le_inf
(le_trans (map_mono inf_le_left) $ by rw [continuous_iff_continuous_at] at h; exact h a)
(le_trans (map_mono inf_le_right) $ by simp; exact subset.refl _),
neq_bot_of_le_neq_bot h₁ h₂,
by simp [image_subset_iff, closure_eq_nhds]; assumption
lemma mem_closure [topological_space α] [topological_space β]
{s : set α} {t : set β} {f : α → β} {a : α}
(hf : continuous f) (ha : a ∈ closure s) (ht : ∀a∈s, f a ∈ t) : f a ∈ closure t :=
subset.trans (image_closure_subset_closure_image hf) (closure_mono $ image_subset_iff.2 ht) $
(mem_image_of_mem f ha)
end continuous
|
477ca6d8d4a9a1e2e8a70afaa37a091ea4d19223 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/order/absolute_value.lean | e5036eb1c1d9c9f531779b677499ae9899d2fb17 | [
"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 | 10,561 | lean | /-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Anne Baanen
-/
import algebra.order.field
import algebra.order.hom.basic
/-!
# Absolute values
This file defines a bundled type of absolute values `absolute_value R S`.
## Main definitions
* `absolute_value R S` is the type of absolute values on `R` mapping to `S`.
* `absolute_value.abs` is the "standard" absolute value on `S`, mapping negative `x` to `-x`.
* `absolute_value.to_monoid_with_zero_hom`: absolute values mapping to a
linear ordered field preserve `0`, `*` and `1`
* `is_absolute_value`: a type class stating that `f : β → α` satisfies the axioms of an abs val
-/
/-- `absolute_value R S` is the type of absolute values on `R` mapping to `S`:
the maps that preserve `*`, are nonnegative, positive definite and satisfy the triangle equality. -/
structure absolute_value (R S : Type*) [semiring R] [ordered_semiring S]
extends R →ₙ* S :=
(nonneg' : ∀ x, 0 ≤ to_fun x)
(eq_zero' : ∀ x, to_fun x = 0 ↔ x = 0)
(add_le' : ∀ x y, to_fun (x + y) ≤ to_fun x + to_fun y)
namespace absolute_value
attribute [nolint doc_blame] absolute_value.to_mul_hom
initialize_simps_projections absolute_value (to_mul_hom_to_fun → apply)
section ordered_semiring
section semiring
variables {R S : Type*} [semiring R] [ordered_semiring S] (abv : absolute_value R S)
instance zero_hom_class : zero_hom_class (absolute_value R S) R S :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' },
map_zero := λ f, (f.eq_zero' _).2 rfl }
instance mul_hom_class : mul_hom_class (absolute_value R S) R S :=
{ map_mul := λ f, f.map_mul'
..absolute_value.zero_hom_class }
instance nonneg_hom_class : nonneg_hom_class (absolute_value R S) R S :=
{ map_nonneg := λ f, f.nonneg',
..absolute_value.zero_hom_class }
instance subadditive_hom_class : subadditive_hom_class (absolute_value R S) R S :=
{ map_add_le_add := λ f, f.add_le',
..absolute_value.zero_hom_class }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (absolute_value R S) (λ f, R → S) := fun_like.has_coe_to_fun
@[simp] lemma coe_to_mul_hom : ⇑abv.to_mul_hom = abv := rfl
protected theorem nonneg (x : R) : 0 ≤ abv x := abv.nonneg' x
@[simp] protected theorem eq_zero {x : R} : abv x = 0 ↔ x = 0 := abv.eq_zero' x
protected theorem add_le (x y : R) : abv (x + y) ≤ abv x + abv y := abv.add_le' x y
@[simp] protected theorem map_mul (x y : R) : abv (x * y) = abv x * abv y := abv.map_mul' x y
protected theorem pos {x : R} (hx : x ≠ 0) : 0 < abv x :=
lt_of_le_of_ne (abv.nonneg x) (ne.symm $ mt abv.eq_zero.mp hx)
@[simp] protected theorem pos_iff {x : R} : 0 < abv x ↔ x ≠ 0 :=
⟨λ h₁, mt abv.eq_zero.mpr h₁.ne', abv.pos⟩
protected theorem ne_zero {x : R} (hx : x ≠ 0) : abv x ≠ 0 := (abv.pos hx).ne'
theorem map_one_of_is_regular (h : is_left_regular (abv 1)) : abv 1 = 1 :=
h $ by simp [←abv.map_mul]
@[simp] protected theorem map_zero : abv 0 = 0 := abv.eq_zero.2 rfl
end semiring
section ring
variables {R S : Type*} [ring R] [ordered_semiring S] (abv : absolute_value R S)
protected lemma sub_le (a b c : R) : abv (a - c) ≤ abv (a - b) + abv (b - c) :=
by simpa [sub_eq_add_neg, add_assoc] using abv.add_le (a - b) (b - c)
@[simp] lemma map_sub_eq_zero_iff (a b : R) : abv (a - b) = 0 ↔ a = b :=
abv.eq_zero.trans sub_eq_zero
end ring
end ordered_semiring
section ordered_ring
section semiring
section is_domain
-- all of these are true for `no_zero_divisors S`; but it doesn't work smoothly with the
-- `is_domain`/`cancel_monoid_with_zero` API
variables {R S : Type*} [semiring R] [ordered_ring S] (abv : absolute_value R S)
variables [is_domain S] [nontrivial R]
@[simp] protected theorem map_one : abv 1 = 1 :=
abv.map_one_of_is_regular ((is_regular_of_ne_zero $ abv.ne_zero one_ne_zero).left)
instance : monoid_with_zero_hom_class (absolute_value R S) R S :=
{ map_zero := λ f, f.map_zero,
map_one := λ f, f.map_one,
..absolute_value.mul_hom_class }
/-- Absolute values from a nontrivial `R` to a linear ordered ring preserve `*`, `0` and `1`. -/
def to_monoid_with_zero_hom : R →*₀ S := abv
@[simp] lemma coe_to_monoid_with_zero_hom : ⇑abv.to_monoid_with_zero_hom = abv := rfl
/-- Absolute values from a nontrivial `R` to a linear ordered ring preserve `*` and `1`. -/
def to_monoid_hom : R →* S := abv
@[simp] lemma coe_to_monoid_hom : ⇑abv.to_monoid_hom = abv := rfl
@[simp] protected lemma map_pow (a : R) (n : ℕ) : abv (a ^ n) = abv a ^ n :=
abv.to_monoid_hom.map_pow a n
end is_domain
end semiring
section ring
variables {R S : Type*} [ring R] [ordered_ring S] (abv : absolute_value R S)
protected lemma le_sub (a b : R) : abv a - abv b ≤ abv (a - b) :=
sub_le_iff_le_add.2 $ by simpa using abv.add_le (a - b) b
end ring
end ordered_ring
section ordered_comm_ring
variables {R S : Type*} [ring R] [ordered_comm_ring S] (abv : absolute_value R S)
variables [no_zero_divisors S]
@[simp] protected theorem map_neg (a : R) : abv (-a) = abv a :=
begin
by_cases ha : a = 0, { simp [ha] },
refine (mul_self_eq_mul_self_iff.mp
(by rw [← abv.map_mul, neg_mul_neg, abv.map_mul])).resolve_right _,
exact ((neg_lt_zero.mpr (abv.pos ha)).trans (abv.pos (neg_ne_zero.mpr ha))).ne'
end
protected theorem map_sub (a b : R) : abv (a - b) = abv (b - a) :=
by rw [← neg_sub, abv.map_neg]
end ordered_comm_ring
section linear_ordered_ring
variables {R S : Type*} [semiring R] [linear_ordered_ring S] (abv : absolute_value R S)
/-- `absolute_value.abs` is `abs` as a bundled `absolute_value`. -/
@[simps]
protected def abs : absolute_value S S :=
{ to_fun := abs,
nonneg' := abs_nonneg,
eq_zero' := λ _, abs_eq_zero,
add_le' := abs_add,
map_mul' := abs_mul }
instance : inhabited (absolute_value S S) := ⟨absolute_value.abs⟩
end linear_ordered_ring
section linear_ordered_comm_ring
variables {R S : Type*} [ring R] [linear_ordered_comm_ring S] (abv : absolute_value R S)
lemma abs_abv_sub_le_abv_sub (a b : R) :
abs (abv a - abv b) ≤ abv (a - b) :=
abs_sub_le_iff.2 ⟨abv.le_sub _ _, by rw abv.map_sub; apply abv.le_sub⟩
end linear_ordered_comm_ring
end absolute_value
/-- A function `f` is an absolute value if it is nonnegative, zero only at 0, additive, and
multiplicative.
See also the type `absolute_value` which represents a bundled version of absolute values.
-/
class is_absolute_value {S} [ordered_semiring S]
{R} [semiring R] (f : R → S) : Prop :=
(abv_nonneg [] : ∀ x, 0 ≤ f x)
(abv_eq_zero [] : ∀ {x}, f x = 0 ↔ x = 0)
(abv_add [] : ∀ x y, f (x + y) ≤ f x + f y)
(abv_mul [] : ∀ x y, f (x * y) = f x * f y)
namespace is_absolute_value
section ordered_semiring
variables {S : Type*} [ordered_semiring S]
variables {R : Type*} [semiring R] (abv : R → S) [is_absolute_value abv]
/-- A bundled absolute value is an absolute value. -/
instance _root_.absolute_value.is_absolute_value
(abv : absolute_value R S) : is_absolute_value abv :=
{ abv_nonneg := abv.nonneg,
abv_eq_zero := λ _, abv.eq_zero,
abv_add := abv.add_le,
abv_mul := abv.map_mul }
/-- Convert an unbundled `is_absolute_value` to a bundled `absolute_value`. -/
@[simps]
def to_absolute_value : absolute_value R S :=
{ to_fun := abv,
add_le' := abv_add abv,
eq_zero' := λ _, abv_eq_zero abv,
nonneg' := abv_nonneg abv,
map_mul' := abv_mul abv }
theorem abv_zero : abv 0 = 0 := (to_absolute_value abv).map_zero
theorem abv_pos {a : R} : 0 < abv a ↔ a ≠ 0 := (to_absolute_value abv).pos_iff
end ordered_semiring
section linear_ordered_ring
variables {S : Type*} [linear_ordered_ring S]
instance abs_is_absolute_value : is_absolute_value (abs : S → S) :=
absolute_value.abs.is_absolute_value
end linear_ordered_ring
section ordered_ring
variables {S : Type*} [ordered_ring S]
section semiring
variables {R : Type*} [semiring R] (abv : R → S) [is_absolute_value abv]
variables [is_domain S]
theorem abv_one [nontrivial R] : abv 1 = 1 := (to_absolute_value abv).map_one
/-- `abv` as a `monoid_with_zero_hom`. -/
def abv_hom [nontrivial R] : R →*₀ S := (to_absolute_value abv).to_monoid_with_zero_hom
lemma abv_pow [nontrivial R] (abv : R → S) [is_absolute_value abv]
(a : R) (n : ℕ) : abv (a ^ n) = abv a ^ n :=
(to_absolute_value abv).map_pow a n
end semiring
section ring
variables {R : Type*} [ring R] (abv : R → S) [is_absolute_value abv]
lemma abv_sub_le (a b c : R) : abv (a - c) ≤ abv (a - b) + abv (b - c) :=
by simpa [sub_eq_add_neg, add_assoc] using abv_add abv (a - b) (b - c)
lemma sub_abv_le_abv_sub (a b : R) : abv a - abv b ≤ abv (a - b) :=
(to_absolute_value abv).le_sub a b
end ring
end ordered_ring
section ordered_comm_ring
variables {S : Type*} [ordered_comm_ring S]
section ring
variables {R : Type*} [ring R] (abv : R → S) [is_absolute_value abv]
variables [no_zero_divisors S]
theorem abv_neg (a : R) : abv (-a) = abv a :=
(to_absolute_value abv).map_neg a
theorem abv_sub (a b : R) : abv (a - b) = abv (b - a) :=
(to_absolute_value abv).map_sub a b
end ring
end ordered_comm_ring
section linear_ordered_comm_ring
variables {S : Type*} [linear_ordered_comm_ring S]
section ring
variables {R : Type*} [ring R] (abv : R → S) [is_absolute_value abv]
lemma abs_abv_sub_le_abv_sub (a b : R) :
abs (abv a - abv b) ≤ abv (a - b) :=
(to_absolute_value abv).abs_abv_sub_le_abv_sub a b
end ring
end linear_ordered_comm_ring
section linear_ordered_field
variables {S : Type*} [linear_ordered_semifield S]
section semiring
variables {R : Type*} [semiring R] [nontrivial R] (abv : R → S) [is_absolute_value abv]
lemma abv_one' : abv 1 = 1 :=
(to_absolute_value abv).map_one_of_is_regular
$ (is_regular_of_ne_zero $ (to_absolute_value abv).ne_zero one_ne_zero).left
/-- An absolute value as a monoid with zero homomorphism, assuming the target is a semifield. -/
def abv_hom' : R →*₀ S := ⟨abv, abv_zero abv, abv_one' abv, abv_mul abv⟩
end semiring
section division_semiring
variables {R : Type*} [division_semiring R] (abv : R → S) [is_absolute_value abv]
theorem abv_inv (a : R) : abv a⁻¹ = (abv a)⁻¹ := map_inv₀ (abv_hom' abv) a
theorem abv_div (a b : R) : abv (a / b) = abv a / abv b := map_div₀ (abv_hom' abv) a b
end division_semiring
end linear_ordered_field
end is_absolute_value
|
145c4a85e876b60fd1462f5814c13f79491346c1 | 17eb1a9fda67ea006b0ea6e9f09e891681861bf9 | /iso.lean | 654e3d9a5d040483eb43ca25648f5d2746a8acba | [] | no_license | skaslev/zero-to-zipper | a9a402240a004da002aa9d4864ca910483e842b1 | d0615fc765d4a023df844fad5bb7f78a27bd01c2 | refs/heads/master | 1,597,028,473,080 | 1,571,393,101,000 | 1,571,393,101,000 | 214,240,337 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 415 | lean | structure iso (a b : Type) :=
(f : a → b) (g : b → a) (gf : Π x, g (f x) = x) (fg : Π x, f (g x) = x)
def inv {a b} : iso a b → iso b a
| ⟨f, g, gf, fg⟩ := ⟨g, f, fg, gf⟩
def comp {a b c} : iso a b → iso b c → iso a c
| ⟨f₁, g₁, g₁f₁, f₁g₁⟩ ⟨f₂, g₂, g₂f₂, f₂g₂⟩ := ⟨f₂ ∘ f₁, g₁ ∘ g₂, by simp [g₂f₂, g₁f₁], by simp [f₁g₁, f₂g₂]⟩
|
66c2adc12bee12d8a2dbdfb83b6f9e0739047908 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/number_theory/padics/ring_homs.lean | 2e90b9c350fea66282ad4c9d6cea7afd98ce4a78 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 24,349 | lean | /-
Copyright (c) 2020 Johan Commelin, Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Robert Y. Lewis
-/
import data.zmod.basic
import number_theory.padics.padic_integers
/-!
# Relating `ℤ_[p]` to `zmod (p ^ n)`
In this file we establish connections between the `p`-adic integers $\mathbb{Z}_p$
and the integers modulo powers of `p`, $\mathbb{Z}/p^n\mathbb{Z}$.
## Main declarations
We show that $\mathbb{Z}_p$ has a ring hom to $\mathbb{Z}/p^n\mathbb{Z}$ for each `n`.
The case for `n = 1` is handled separately, since it is used in the general construction
and we may want to use it without the `^1` getting in the way.
* `padic_int.to_zmod`: ring hom to `zmod p`
* `padic_int.to_zmod_pow`: ring hom to `zmod (p^n)`
* `padic_int.ker_to_zmod` / `padic_int.ker_to_zmod_pow`: the kernels of these maps are the ideals
generated by `p^n`
We also establish the universal property of $\mathbb{Z}_p$ as a projective limit.
Given a family of compatible ring homs $f_k : R \to \mathbb{Z}/p^n\mathbb{Z}$,
there is a unique limit $R \to \mathbb{Z}_p$.
* `padic_int.lift`: the limit function
* `padic_int.lift_spec` / `padic_int.lift_unique`: the universal property
## Implementation notes
The ring hom constructions go through an auxiliary constructor `padic_int.to_zmod_hom`,
which removes some boilerplate code.
-/
noncomputable theory
open_locale classical
open nat local_ring padic
namespace padic_int
variables {p : ℕ} [hp_prime : fact (p.prime)]
include hp_prime
section ring_homs
/-! ### Ring homomorphisms to `zmod p` and `zmod (p ^ n)` -/
variables (p) (r : ℚ)
omit hp_prime
/--
`mod_part p r` is an integer that satisfies
`∥(r - mod_part p r : ℚ_[p])∥ < 1` when `∥(r : ℚ_[p])∥ ≤ 1`,
see `padic_int.norm_sub_mod_part`.
It is the unique non-negative integer that is `< p` with this property.
(Note that this definition assumes `r : ℚ`.
See `padic_int.zmod_repr` for a version that takes values in `ℕ`
and works for arbitrary `x : ℤ_[p]`.) -/
def mod_part : ℤ :=
(r.num * gcd_a r.denom p) % p
include hp_prime
variable {p}
lemma mod_part_lt_p : mod_part p r < p :=
begin
convert int.mod_lt _ _,
{ simp },
{ exact_mod_cast hp_prime.1.ne_zero }
end
lemma mod_part_nonneg : 0 ≤ mod_part p r :=
int.mod_nonneg _ $ by exact_mod_cast hp_prime.1.ne_zero
lemma is_unit_denom (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : is_unit (r.denom : ℤ_[p]) :=
begin
rw is_unit_iff,
apply le_antisymm (r.denom : ℤ_[p]).2,
rw [← not_lt, val_eq_coe, coe_nat_cast],
intro norm_denom_lt,
have hr : ∥(r * r.denom : ℚ_[p])∥ = ∥(r.num : ℚ_[p])∥,
{ rw_mod_cast @rat.mul_denom_eq_num r, refl, },
rw padic_norm_e.mul at hr,
have key : ∥(r.num : ℚ_[p])∥ < 1,
{ calc _ = _ : hr.symm
... < 1 * 1 : mul_lt_mul' h norm_denom_lt (norm_nonneg _) zero_lt_one
... = 1 : mul_one 1 },
have : ↑p ∣ r.num ∧ (p : ℤ) ∣ r.denom,
{ simp only [← norm_int_lt_one_iff_dvd, ← padic_norm_e_of_padic_int],
norm_cast, exact ⟨key, norm_denom_lt⟩ },
apply hp_prime.1.not_dvd_one,
rwa [← r.cop.gcd_eq_one, nat.dvd_gcd_iff, ← int.coe_nat_dvd_left, ← int.coe_nat_dvd],
end
lemma norm_sub_mod_part_aux (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) :
↑p ∣ r.num - r.num * r.denom.gcd_a p % p * ↑(r.denom) :=
begin
rw ← zmod.int_coe_zmod_eq_zero_iff_dvd,
simp only [int.cast_coe_nat, zmod.nat_cast_mod, int.cast_mul, int.cast_sub],
have := congr_arg (coe : ℤ → zmod p) (gcd_eq_gcd_ab r.denom p),
simp only [int.cast_coe_nat, add_zero, int.cast_add, zmod.nat_cast_self, int.cast_mul, zero_mul]
at this,
push_cast,
rw [mul_right_comm, mul_assoc, ←this],
suffices rdcp : r.denom.coprime p,
{ rw rdcp.gcd_eq_one, simp only [mul_one, cast_one, sub_self], },
apply coprime.symm,
apply (coprime_or_dvd_of_prime hp_prime.1 _).resolve_right,
rw [← int.coe_nat_dvd, ← norm_int_lt_one_iff_dvd, not_lt],
apply ge_of_eq,
rw ← is_unit_iff,
exact is_unit_denom r h,
end
lemma norm_sub_mod_part (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∥(⟨r,h⟩ - mod_part p r : ℤ_[p])∥ < 1 :=
begin
let n := mod_part p r,
rw [norm_lt_one_iff_dvd, ← (is_unit_denom r h).dvd_mul_right],
suffices : ↑p ∣ r.num - n * r.denom,
{ convert (int.cast_ring_hom ℤ_[p]).map_dvd this,
simp only [sub_mul, int.cast_coe_nat, ring_hom.eq_int_cast, int.cast_mul,
sub_left_inj, int.cast_sub],
apply subtype.coe_injective,
simp only [coe_mul, subtype.coe_mk, coe_nat_cast],
rw_mod_cast @rat.mul_denom_eq_num r, refl },
exact norm_sub_mod_part_aux r h
end
lemma exists_mem_range_of_norm_rat_le_one (h : ∥(r : ℚ_[p])∥ ≤ 1) :
∃ n : ℤ, 0 ≤ n ∧ n < p ∧ ∥(⟨r,h⟩ - n : ℤ_[p])∥ < 1 :=
⟨mod_part p r, mod_part_nonneg _, mod_part_lt_p _, norm_sub_mod_part _ h⟩
lemma zmod_congr_of_sub_mem_span_aux (n : ℕ) (x : ℤ_[p]) (a b : ℤ)
(ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p]))
(hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) :
(a : zmod (p ^ n)) = b :=
begin
rw [ideal.mem_span_singleton] at ha hb,
rw [← sub_eq_zero, ← int.cast_sub,
zmod.int_coe_zmod_eq_zero_iff_dvd, int.coe_nat_pow],
rw [← dvd_neg, neg_sub] at ha,
have := dvd_add ha hb,
rwa [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left,
← sub_eq_add_neg, ← int.cast_sub, pow_p_dvd_int_iff] at this,
end
lemma zmod_congr_of_sub_mem_span (n : ℕ) (x : ℤ_[p]) (a b : ℕ)
(ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p]))
(hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) :
(a : zmod (p ^ n)) = b :=
by simpa using zmod_congr_of_sub_mem_span_aux n x a b ha hb
lemma zmod_congr_of_sub_mem_max_ideal (x : ℤ_[p]) (m n : ℕ)
(hm : x - m ∈ maximal_ideal ℤ_[p]) (hn : x - n ∈ maximal_ideal ℤ_[p]) :
(m : zmod p) = n :=
begin
rw maximal_ideal_eq_span_p at hm hn,
have := zmod_congr_of_sub_mem_span_aux 1 x m n,
simp only [pow_one] at this,
specialize this hm hn,
apply_fun zmod.cast_hom (show p ∣ p ^ 1, by rw pow_one) (zmod p) at this,
simp only [ring_hom.map_int_cast] at this,
simpa only [int.cast_coe_nat] using this
end
variable (x : ℤ_[p])
lemma exists_mem_range : ∃ n : ℕ, n < p ∧ (x - n ∈ maximal_ideal ℤ_[p]) :=
begin
simp only [maximal_ideal_eq_span_p, ideal.mem_span_singleton, ← norm_lt_one_iff_dvd],
obtain ⟨r, hr⟩ := rat_dense (x : ℚ_[p]) zero_lt_one,
have H : ∥(r : ℚ_[p])∥ ≤ 1,
{ rw norm_sub_rev at hr,
calc _ = ∥(r : ℚ_[p]) - x + x∥ : by ring_nf
... ≤ _ : padic_norm_e.nonarchimedean _ _
... ≤ _ : max_le (le_of_lt hr) x.2 },
obtain ⟨n, hzn, hnp, hn⟩ := exists_mem_range_of_norm_rat_le_one r H,
lift n to ℕ using hzn,
use n,
split, {exact_mod_cast hnp},
simp only [norm_def, coe_sub, subtype.coe_mk, coe_nat_cast] at hn ⊢,
rw show (x - n : ℚ_[p]) = (x - r) + (r - n), by ring,
apply lt_of_le_of_lt (padic_norm_e.nonarchimedean _ _),
apply max_lt hr,
simpa using hn
end
/--
`zmod_repr x` is the unique natural number smaller than `p`
satisfying `∥(x - zmod_repr x : ℤ_[p])∥ < 1`.
-/
def zmod_repr : ℕ :=
classical.some (exists_mem_range x)
lemma zmod_repr_spec : zmod_repr x < p ∧ (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) :=
classical.some_spec (exists_mem_range x)
lemma zmod_repr_lt_p : zmod_repr x < p := (zmod_repr_spec _).1
lemma sub_zmod_repr_mem : (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := (zmod_repr_spec _).2
/--
`to_zmod_hom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `zmod v`.
-/
def to_zmod_hom (v : ℕ) (f : ℤ_[p] → ℕ) (f_spec : ∀ x, x - f x ∈ (ideal.span {v} : ideal ℤ_[p]))
(f_congr : ∀ (x : ℤ_[p]) (a b : ℕ),
x - a ∈ (ideal.span {v} : ideal ℤ_[p]) → x - b ∈ (ideal.span {v} : ideal ℤ_[p]) →
(a : zmod v) = b) :
ℤ_[p] →+* zmod v :=
{ to_fun := λ x, f x,
map_zero' :=
begin
rw [f_congr (0 : ℤ_[p]) _ 0, cast_zero],
{ exact f_spec _ },
{ simp only [sub_zero, cast_zero, submodule.zero_mem], }
end,
map_one' :=
begin
rw [f_congr (1 : ℤ_[p]) _ 1, cast_one],
{ exact f_spec _ },
{ simp only [sub_self, cast_one, submodule.zero_mem], }
end,
map_add' :=
begin
intros x y,
rw [f_congr (x + y) _ (f x + f y), cast_add],
{ exact f_spec _ },
{ convert ideal.add_mem _ (f_spec x) (f_spec y),
rw cast_add,
ring, }
end,
map_mul' :=
begin
intros x y,
rw [f_congr (x * y) _ (f x * f y), cast_mul],
{ exact f_spec _ },
{ let I : ideal ℤ_[p] := ideal.span {v},
convert I.add_mem (I.mul_mem_left x (f_spec y)) (I.mul_mem_right (f y) (f_spec x)),
rw cast_mul,
ring, }
end, }
/--
`to_zmod` is a ring hom from `ℤ_[p]` to `zmod p`,
with the equality `to_zmod x = (zmod_repr x : zmod p)`.
-/
def to_zmod : ℤ_[p] →+* zmod p :=
to_zmod_hom p zmod_repr
(by { rw ←maximal_ideal_eq_span_p, exact sub_zmod_repr_mem })
(by { rw ←maximal_ideal_eq_span_p, exact zmod_congr_of_sub_mem_max_ideal } )
/--
`z - (to_zmod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`.
The coercion from `zmod p` to `ℤ_[p]` is `zmod.has_coe_t`,
which coerces `zmod p` into artibrary rings.
This is unfortunate, but a consequence of the fact that we allow `zmod p`
to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`.
This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides
`p`. While this is not the case here we can still make use of the coercion.
-/
lemma to_zmod_spec (z : ℤ_[p]) : z - (to_zmod z : ℤ_[p]) ∈ maximal_ideal ℤ_[p] :=
begin
convert sub_zmod_repr_mem z using 2,
dsimp [to_zmod, to_zmod_hom],
unfreezingI { rcases (exists_eq_add_of_lt (hp_prime.1.pos)) with ⟨p', rfl⟩ },
change ↑(zmod.val _) = _,
simp only [zmod.val_nat_cast, add_zero, add_def, nat.cast_inj, zero_add],
apply mod_eq_of_lt,
simpa only [zero_add] using zmod_repr_lt_p z,
end
lemma ker_to_zmod : (to_zmod : ℤ_[p] →+* zmod p).ker = maximal_ideal ℤ_[p] :=
begin
ext x,
rw ring_hom.mem_ker,
split,
{ intro h,
simpa only [h, zmod.cast_zero, sub_zero] using to_zmod_spec x, },
{ intro h,
rw ← sub_zero x at h,
dsimp [to_zmod, to_zmod_hom],
convert zmod_congr_of_sub_mem_max_ideal x _ 0 _ h,
norm_cast, apply sub_zmod_repr_mem, }
end
/-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`.
See `appr_spec`. -/
noncomputable def appr : ℤ_[p] → ℕ → ℕ
| x 0 := 0
| x (n+1) :=
let y := x - appr x n in
if hy : y = 0 then
appr x n
else
let u := unit_coeff hy in
appr x n + p ^ n * (to_zmod ((u : ℤ_[p]) * (p ^ (y.valuation - n).nat_abs))).val
lemma appr_lt (x : ℤ_[p]) (n : ℕ) : x.appr n < p ^ n :=
begin
induction n with n ih generalizing x,
{ simp only [appr, succ_pos', pow_zero], },
simp only [appr, map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, int.nat_abs,
ring_hom.map_mul],
have hp : p ^ n < p ^ (n + 1),
{ apply pow_lt_pow hp_prime.1.one_lt (lt_add_one n) },
split_ifs with h,
{ apply lt_trans (ih _) hp, },
{ calc _ < p ^ n + p ^ n * (p - 1) : _
... = p ^ (n + 1) : _,
{ apply add_lt_add_of_lt_of_le (ih _),
apply nat.mul_le_mul_left,
apply le_pred_of_lt,
apply zmod.val_lt },
{ rw [mul_tsub, mul_one, ← pow_succ'],
apply add_tsub_cancel_of_le (le_of_lt hp) } }
end
lemma appr_mono (x : ℤ_[p]) : monotone x.appr :=
begin
apply monotone_nat_of_le_succ,
intro n,
dsimp [appr],
split_ifs, { refl, },
apply nat.le_add_right,
end
lemma dvd_appr_sub_appr (x : ℤ_[p]) (m n : ℕ) (h : m ≤ n) :
p ^ m ∣ x.appr n - x.appr m :=
begin
obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le h, clear h,
induction k with k ih,
{ simp only [add_zero, tsub_self, dvd_zero], },
rw [nat.succ_eq_add_one, ← add_assoc],
dsimp [appr],
split_ifs with h,
{ exact ih },
rw [add_comm, add_tsub_assoc_of_le (appr_mono _ (nat.le_add_right m k))],
apply dvd_add _ ih,
apply dvd_mul_of_dvd_left,
apply pow_dvd_pow _ (nat.le_add_right m k),
end
lemma appr_spec (n : ℕ) : ∀ (x : ℤ_[p]), x - appr x n ∈ (ideal.span {p^n} : ideal ℤ_[p]) :=
begin
simp only [ideal.mem_span_singleton],
induction n with n ih,
{ simp only [is_unit_one, is_unit.dvd, pow_zero, forall_true_iff], },
intro x,
dsimp only [appr],
split_ifs with h,
{ rw h, apply dvd_zero },
push_cast, rw sub_add_eq_sub_sub,
obtain ⟨c, hc⟩ := ih x,
simp only [map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, ring_hom.map_mul,
zmod.nat_cast_val],
have hc' : c ≠ 0,
{ rintro rfl, simp only [mul_zero] at hc, contradiction },
conv_rhs { congr, simp only [hc], },
rw show (x - ↑(appr x n)).valuation = (↑p ^ n * c).valuation,
{ rw hc },
rw [valuation_p_pow_mul _ _ hc', add_sub_cancel', pow_succ', ← mul_sub],
apply mul_dvd_mul_left,
obtain hc0 | hc0 := c.valuation.nat_abs.eq_zero_or_pos,
{ simp only [hc0, mul_one, pow_zero],
rw [mul_comm, unit_coeff_spec h] at hc,
suffices : c = unit_coeff h,
{ rw [← this, ← ideal.mem_span_singleton, ← maximal_ideal_eq_span_p],
apply to_zmod_spec },
obtain ⟨c, rfl⟩ : is_unit c, -- TODO: write a can_lift instance for units
{ rw int.nat_abs_eq_zero at hc0,
rw [is_unit_iff, norm_eq_pow_val hc', hc0, neg_zero, zpow_zero], },
rw discrete_valuation_ring.unit_mul_pow_congr_unit _ _ _ _ _ hc,
exact irreducible_p },
{ rw zero_pow hc0,
simp only [sub_zero, zmod.cast_zero, mul_zero],
rw unit_coeff_spec hc',
exact (dvd_pow_self (p : ℤ_[p]) hc0.ne').mul_left _, },
end
attribute [irreducible] appr
/-- A ring hom from `ℤ_[p]` to `zmod (p^n)`, with underlying function `padic_int.appr n`. -/
def to_zmod_pow (n : ℕ) : ℤ_[p] →+* zmod (p ^ n) :=
to_zmod_hom (p^n) (λ x, appr x n)
(by { intros, convert appr_spec n _ using 1, simp })
(by { intros x a b ha hb,
apply zmod_congr_of_sub_mem_span n x a b,
{ simpa using ha },
{ simpa using hb } })
lemma ker_to_zmod_pow (n : ℕ) : (to_zmod_pow n : ℤ_[p] →+* zmod (p ^ n)).ker = ideal.span {p ^ n} :=
begin
ext x,
rw ring_hom.mem_ker,
split,
{ intro h,
suffices : x.appr n = 0,
{ convert appr_spec n x, simp only [this, sub_zero, cast_zero], },
dsimp [to_zmod_pow, to_zmod_hom] at h,
rw zmod.nat_coe_zmod_eq_zero_iff_dvd at h,
apply eq_zero_of_dvd_of_lt h (appr_lt _ _), },
{ intro h,
rw ← sub_zero x at h,
dsimp [to_zmod_pow, to_zmod_hom],
rw [zmod_congr_of_sub_mem_span n x _ 0 _ h, cast_zero],
apply appr_spec, }
end
@[simp] lemma zmod_cast_comp_to_zmod_pow (m n : ℕ) (h : m ≤ n) :
(zmod.cast_hom (pow_dvd_pow p h) (zmod (p ^ m))).comp (to_zmod_pow n) = to_zmod_pow m :=
begin
apply zmod.ring_hom_eq_of_ker_eq,
ext x,
rw [ring_hom.mem_ker, ring_hom.mem_ker],
simp only [function.comp_app, zmod.cast_hom_apply, ring_hom.coe_comp],
simp only [to_zmod_pow, to_zmod_hom, ring_hom.coe_mk],
rw [zmod.cast_nat_cast (pow_dvd_pow p h),
zmod_congr_of_sub_mem_span m (x.appr n) (x.appr n) (x.appr m)],
{ rw [sub_self], apply ideal.zero_mem _, },
{ rw ideal.mem_span_singleton,
rcases dvd_appr_sub_appr x m n h with ⟨c, hc⟩,
use c,
rw [← nat.cast_sub (appr_mono _ h), hc, nat.cast_mul, nat.cast_pow], },
{ apply_instance }
end
@[simp] lemma cast_to_zmod_pow (m n : ℕ) (h : m ≤ n) (x : ℤ_[p]) :
↑(to_zmod_pow n x) = to_zmod_pow m x :=
by { rw ← zmod_cast_comp_to_zmod_pow _ _ h, refl }
lemma dense_range_nat_cast :
dense_range (nat.cast : ℕ → ℤ_[p]) :=
begin
intro x,
rw metric.mem_closure_range_iff,
intros ε hε,
obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε,
use (x.appr n),
rw dist_eq_norm,
apply lt_of_le_of_lt _ hn,
rw norm_le_pow_iff_mem_span_pow,
apply appr_spec,
end
lemma dense_range_int_cast :
dense_range (int.cast : ℤ → ℤ_[p]) :=
begin
intro x,
apply dense_range_nat_cast.induction_on x,
{ exact is_closed_closure, },
{ intro a,
change (a.cast : ℤ_[p]) with (a : ℤ).cast,
apply subset_closure,
exact set.mem_range_self _ }
end
end ring_homs
section lift
/-! ### Universal property as projective limit -/
open cau_seq padic_seq
variables {R : Type*} [non_assoc_semiring R] (f : Π k : ℕ, R →+* zmod (p^k))
(f_compat : ∀ k1 k2 (hk : k1 ≤ k2), (zmod.cast_hom (pow_dvd_pow p hk) _).comp (f k2) = f k1)
omit hp_prime
/--
Given a family of ring homs `f : Π n : ℕ, R →+* zmod (p ^ n)`,
`nth_hom f r` is an integer-valued sequence
whose `n`th value is the unique integer `k` such that `0 ≤ k < p ^ n`
and `f n r = (k : zmod (p ^ n))`.
-/
def nth_hom (r : R) : ℕ → ℤ :=
λ n, (f n r : zmod (p^n)).val
@[simp] lemma nth_hom_zero : nth_hom f 0 = 0 :=
by simp [nth_hom]; refl
variable {f}
include hp_prime
include f_compat
lemma pow_dvd_nth_hom_sub (r : R) (i j : ℕ) (h : i ≤ j) :
↑p ^ i ∣ nth_hom f r j - nth_hom f r i :=
begin
specialize f_compat i j h,
rw [← int.coe_nat_pow, ← zmod.int_coe_zmod_eq_zero_iff_dvd,
int.cast_sub],
dsimp [nth_hom],
rw [← f_compat, ring_hom.comp_apply],
haveI : fact (p ^ i > 0) := ⟨pow_pos hp_prime.1.pos _⟩,
haveI : fact (p ^ j > 0) := ⟨pow_pos hp_prime.1.pos _⟩,
simp only [zmod.cast_id, zmod.cast_hom_apply, sub_self, zmod.nat_cast_val, zmod.int_cast_cast],
end
lemma is_cau_seq_nth_hom (r : R): is_cau_seq (padic_norm p) (λ n, nth_hom f r n) :=
begin
intros ε hε,
obtain ⟨k, hk⟩ : ∃ k : ℕ, (p ^ - (↑(k : ℕ) : ℤ) : ℚ) < ε := exists_pow_neg_lt_rat p hε,
use k,
intros j hj,
refine lt_of_le_of_lt _ hk,
norm_cast,
rw ← padic_norm.dvd_iff_norm_le,
exact_mod_cast pow_dvd_nth_hom_sub f_compat r k j hj
end
/--
`nth_hom_seq f_compat r` bundles `padic_int.nth_hom f r`
as a Cauchy sequence of rationals with respect to the `p`-adic norm.
The `n`th value of the sequence is `((f n r).val : ℚ)`.
-/
def nth_hom_seq (r : R) : padic_seq p := ⟨λ n, nth_hom f r n, is_cau_seq_nth_hom f_compat r⟩
lemma nth_hom_seq_one : nth_hom_seq f_compat 1 ≈ 1 :=
begin
intros ε hε,
change _ < _ at hε,
use 1,
intros j hj,
haveI : fact (1 < p^j) := ⟨nat.one_lt_pow _ _ (by linarith) hp_prime.1.one_lt⟩,
simp [nth_hom_seq, nth_hom, zmod.val_one, hε],
end
lemma nth_hom_seq_add (r s : R) :
nth_hom_seq f_compat (r + s) ≈ nth_hom_seq f_compat r + nth_hom_seq f_compat s :=
begin
intros ε hε,
obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε,
use n,
intros j hj,
dsimp [nth_hom_seq],
apply lt_of_le_of_lt _ hn,
rw [← int.cast_add, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le,
← zmod.int_coe_zmod_eq_zero_iff_dvd],
dsimp [nth_hom],
haveI : fact (p ^ n > 0) := ⟨pow_pos hp_prime.1.pos _⟩,
haveI : fact (p ^ j > 0) := ⟨pow_pos hp_prime.1.pos _⟩,
simp only [zmod.nat_cast_val, ring_hom.map_add, int.cast_sub, zmod.int_cast_cast, int.cast_add],
rw [zmod.cast_add (show p^n ∣ p^j, from pow_dvd_pow _ hj), sub_self],
{ apply_instance },
end
lemma nth_hom_seq_mul (r s : R) :
nth_hom_seq f_compat (r * s) ≈ nth_hom_seq f_compat r * nth_hom_seq f_compat s :=
begin
intros ε hε,
obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε,
use n,
intros j hj,
dsimp [nth_hom_seq],
apply lt_of_le_of_lt _ hn,
rw [← int.cast_mul, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le,
← zmod.int_coe_zmod_eq_zero_iff_dvd],
dsimp [nth_hom],
haveI : fact (p ^ n > 0) := ⟨pow_pos hp_prime.1.pos _⟩,
haveI : fact (p ^ j > 0) := ⟨pow_pos hp_prime.1.pos _⟩,
simp only [zmod.nat_cast_val, ring_hom.map_mul, int.cast_sub, zmod.int_cast_cast, int.cast_mul],
rw [zmod.cast_mul (show p^n ∣ p^j, from pow_dvd_pow _ hj), sub_self],
{ apply_instance },
end
/--
`lim_nth_hom f_compat r` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`.
This is itself a ring hom: see `padic_int.lift`.
-/
def lim_nth_hom (r : R) : ℤ_[p] :=
of_int_seq (nth_hom f r) (is_cau_seq_nth_hom f_compat r)
lemma lim_nth_hom_spec (r : R) :
∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ n ≥ N, ∥lim_nth_hom f_compat r - nth_hom f r n∥ < ε :=
begin
intros ε hε,
obtain ⟨ε', hε'0, hε'⟩ : ∃ v : ℚ, (0 : ℝ) < v ∧ ↑v < ε := exists_rat_btwn hε,
norm_cast at hε'0,
obtain ⟨N, hN⟩ := padic_norm_e.defn (nth_hom_seq f_compat r) hε'0,
use N,
intros n hn,
apply lt_trans _ hε',
change ↑(padic_norm_e _) < _,
norm_cast,
exact hN _ hn,
end
lemma lim_nth_hom_zero : lim_nth_hom f_compat 0 = 0 :=
by simp [lim_nth_hom]; refl
lemma lim_nth_hom_one : lim_nth_hom f_compat 1 = 1 :=
subtype.ext $ quot.sound $ nth_hom_seq_one _
lemma lim_nth_hom_add (r s : R) :
lim_nth_hom f_compat (r + s) = lim_nth_hom f_compat r + lim_nth_hom f_compat s :=
subtype.ext $ quot.sound $ nth_hom_seq_add _ _ _
lemma lim_nth_hom_mul (r s : R) :
lim_nth_hom f_compat (r * s) = lim_nth_hom f_compat r * lim_nth_hom f_compat s :=
subtype.ext $ quot.sound $ nth_hom_seq_mul _ _ _
-- TODO: generalize this to arbitrary complete discrete valuation rings
/--
`lift f_compat` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`,
with the equality `lift f_compat r = padic_int.lim_nth_hom f_compat r`.
-/
def lift : R →+* ℤ_[p] :=
{ to_fun := lim_nth_hom f_compat,
map_one' := lim_nth_hom_one f_compat,
map_mul' := lim_nth_hom_mul f_compat,
map_zero' := lim_nth_hom_zero f_compat,
map_add' := lim_nth_hom_add f_compat }
omit f_compat
lemma lift_sub_val_mem_span (r : R) (n : ℕ) :
(lift f_compat r - (f n r).val) ∈ (ideal.span {↑p ^ n} : ideal ℤ_[p]) :=
begin
obtain ⟨k, hk⟩ := lim_nth_hom_spec f_compat r _
(show (0 : ℝ) < p ^ (-n : ℤ), from nat.zpow_pos_of_pos hp_prime.1.pos _),
have := le_of_lt (hk (max n k) (le_max_right _ _)),
rw norm_le_pow_iff_mem_span_pow at this,
dsimp [lift],
rw sub_eq_sub_add_sub (lim_nth_hom f_compat r) _ ↑(nth_hom f r (max n k)),
apply ideal.add_mem _ _ this,
rw [ideal.mem_span_singleton],
simpa only [ring_hom.eq_int_cast, ring_hom.map_pow, int.cast_sub] using
(int.cast_ring_hom ℤ_[p]).map_dvd
(pow_dvd_nth_hom_sub f_compat r n (max n k) (le_max_left _ _)),
end
/--
One part of the universal property of `ℤ_[p]` as a projective limit.
See also `padic_int.lift_unique`.
-/
lemma lift_spec (n : ℕ) : (to_zmod_pow n).comp (lift f_compat) = f n :=
begin
ext r,
haveI : fact (0 < p ^ n) := ⟨pow_pos hp_prime.1.pos n⟩,
rw [ring_hom.comp_apply, ← zmod.nat_cast_zmod_val (f n r), ← map_nat_cast $ to_zmod_pow n,
← sub_eq_zero, ← ring_hom.map_sub, ← ring_hom.mem_ker, ker_to_zmod_pow],
apply lift_sub_val_mem_span,
end
/--
One part of the universal property of `ℤ_[p]` as a projective limit.
See also `padic_int.lift_spec`.
-/
lemma lift_unique (g : R →+* ℤ_[p]) (hg : ∀ n, (to_zmod_pow n).comp g = f n) :
lift f_compat = g :=
begin
ext1 r,
apply eq_of_forall_dist_le,
intros ε hε,
obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε,
apply le_trans _ (le_of_lt hn),
rw [dist_eq_norm, norm_le_pow_iff_mem_span_pow, ← ker_to_zmod_pow, ring_hom.mem_ker,
ring_hom.map_sub, ← ring_hom.comp_apply, ← ring_hom.comp_apply, lift_spec, hg, sub_self],
end
@[simp] lemma lift_self (z : ℤ_[p]) : @lift p _ ℤ_[p] _ to_zmod_pow
zmod_cast_comp_to_zmod_pow z = z :=
begin
show _ = ring_hom.id _ z,
rw @lift_unique p _ ℤ_[p] _ _ zmod_cast_comp_to_zmod_pow (ring_hom.id ℤ_[p]),
intro, rw ring_hom.comp_id,
end
end lift
lemma ext_of_to_zmod_pow {x y : ℤ_[p]} :
(∀ n, to_zmod_pow n x = to_zmod_pow n y) ↔ x = y :=
begin
split,
{ intro h,
rw [← lift_self x, ← lift_self y],
simp [lift, lim_nth_hom, nth_hom, h] },
{ rintro rfl _, refl }
end
lemma to_zmod_pow_eq_iff_ext {R : Type*} [non_assoc_semiring R] {g g' : R →+* ℤ_[p]} :
(∀ n, (to_zmod_pow n).comp g = (to_zmod_pow n).comp g') ↔ g = g' :=
begin
split,
{ intro hg,
ext x : 1,
apply ext_of_to_zmod_pow.mp,
intro n,
show (to_zmod_pow n).comp g x = (to_zmod_pow n).comp g' x,
rw hg n },
{ rintro rfl _, refl }
end
end padic_int
|
5942fd8454d7df463a7fecb969c3bae25b4c99b0 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/testing/slim_check/sampleable.lean | ce17328b73888c74023d9236f4ddbcd16cd01a6b | [
"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 | 31,364 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import data.lazy_list.basic
import data.tree
import data.int.basic
import control.bifunctor
import control.ulift
import tactic.linarith
import testing.slim_check.gen
/-!
# `sampleable` Class
This class permits the creation samples of a given type
controlling the size of those values using the `gen` monad`. It also
helps minimize examples by creating smaller versions of given values.
When testing a proposition like `∀ n : ℕ, prime n → n ≤ 100`,
`slim_check` requires that `ℕ` have an instance of `sampleable` and for
`prime n` to be decidable. `slim_check` will then use the instance of
`sampleable` to generate small examples of ℕ and progressively increase
in size. For each example `n`, `prime n` is tested. If it is false,
the example will be rejected (not a test success nor a failure) and
`slim_check` will move on to other examples. If `prime n` is true, `n
≤ 100` will be tested. If it is false, `n` is a counter-example of `∀
n : ℕ, prime n → n ≤ 100` and the test fails. If `n ≤ 100` is true,
the test passes and `slim_check` moves on to trying more examples.
This is a port of the Haskell QuickCheck library.
## Main definitions
* `sampleable` class
* `sampleable_functor` and `sampleable_bifunctor` class
* `sampleable_ext` class
### `sampleable`
`sampleable α` provides ways of creating examples of type `α`,
and given such an example `x : α`, gives us a way to shrink it
and find simpler examples.
### `sampleable_ext`
`sampleable_ext` generalizes the behavior of `sampleable`
and makes it possible to express instances for types that
do not lend themselves to introspection, such as `ℕ → ℕ`.
If we test a quantification over functions the
counter-examples cannot be shrunken or printed meaningfully.
For that purpose, `sampleable_ext` provides a proxy representation
`proxy_repr` that can be printed and shrunken as well
as interpreted (using `interp`) as an object of the right type.
### `sampleable_functor` and `sampleable_bifunctor`
`sampleable_functor F` and `sampleable_bifunctor F` makes it possible
to create samples of and shrink `F α` given a sampling function and a
shrinking function for arbitrary `α`.
This allows us to separate the logic for generating the shape of a
collection from the logic for generating its contents. Specifically,
the contents could be generated using either `sampleable` or
`sampleable_ext` instance and the `sampleable_(bi)functor` does not
need to use that information
## Shrinking
Shrinking happens when `slim_check` find a counter-example to a
property. It is likely that the example will be more complicated than
necessary so `slim_check` proceeds to shrink it as much as
possible. Although equally valid, a smaller counter-example is easier
for a user to understand and use.
The `sampleable` class, beside having the `sample` function, has a
`shrink` function so that we can use specialized knowledge while
shrinking a value. It is not responsible for the whole shrinking process
however. It only has to take one step in the shrinking process.
`slim_check` will repeatedly call `shrink` until no more steps can
be taken. Because `shrink` guarantees that the size of the candidates
it produces is strictly smaller than the argument, we know that
`slim_check` is guaranteed to terminate.
## Tags
random testing
## References
* https://hackage.haskell.org/package/QuickCheck
-/
universes u v w
namespace slim_check
variables (α : Type u)
local infix ` ≺ `:50 := has_well_founded.r
/-- `sizeof_lt x y` compares the sizes of `x` and `y`. -/
def sizeof_lt {α} [has_sizeof α] (x y : α) := sizeof x < sizeof y
/-- `shrink_fn α` is the type of functions that shrink an
argument of type `α` -/
@[reducible]
def shrink_fn (α : Type*) [has_sizeof α] := Π x : α, lazy_list { y : α // sizeof_lt y x }
/-- `sampleable α` provides ways of creating examples of type `α`,
and given such an example `x : α`, gives us a way to shrink it
and find simpler examples. -/
class sampleable :=
[wf : has_sizeof α]
(sample [] : gen α)
(shrink : Π x : α, lazy_list { y : α // @sizeof _ wf y < @sizeof _ wf x } := λ _, lazy_list.nil)
attribute [instance, priority 100] has_well_founded_of_has_sizeof default_has_sizeof
attribute [instance, priority 200] sampleable.wf
/-- `sampleable_functor F` makes it possible to create samples of and
shrink `F α` given a sampling function and a shrinking function for
arbitrary `α` -/
class sampleable_functor (F : Type u → Type v) [functor F] :=
[wf : Π α [has_sizeof α], has_sizeof (F α)]
(sample [] : ∀ {α}, gen α → gen (F α))
(shrink : ∀ α [has_sizeof α], shrink_fn α → shrink_fn (F α))
(p_repr : ∀ α, has_repr α → has_repr (F α))
/-- `sampleable_bifunctor F` makes it possible to create samples of
and shrink `F α β` given a sampling function and a shrinking function
for arbitrary `α` and `β` -/
class sampleable_bifunctor (F : Type u → Type v → Type w) [bifunctor F] :=
[wf : Π α β [has_sizeof α] [has_sizeof β], has_sizeof (F α β)]
(sample [] : ∀ {α β}, gen α → gen β → gen (F α β))
(shrink : ∀ α β [has_sizeof α] [has_sizeof β], shrink_fn α → shrink_fn β → shrink_fn (F α β))
(p_repr : ∀ α β, has_repr α → has_repr β → has_repr (F α β))
export sampleable (sample shrink)
/-- This function helps infer the proxy representation and
interpretation in `sampleable_ext` instances. -/
meta def sampleable.mk_trivial_interp : tactic unit :=
tactic.refine ``(id)
/-- `sampleable_ext` generalizes the behavior of `sampleable`
and makes it possible to express instances for types that
do not lend themselves to introspection, such as `ℕ → ℕ`.
If we test a quantification over functions the
counter-examples cannot be shrunken or printed meaningfully.
For that purpose, `sampleable_ext` provides a proxy representation
`proxy_repr` that can be printed and shrunken as well
as interpreted (using `interp`) as an object of the right type. -/
class sampleable_ext (α : Sort u) :=
(proxy_repr : Type v)
[wf : has_sizeof proxy_repr]
(interp [] : proxy_repr → α . sampleable.mk_trivial_interp)
[p_repr : has_repr proxy_repr]
(sample [] : gen proxy_repr)
(shrink : shrink_fn proxy_repr)
attribute [instance, priority 100] sampleable_ext.p_repr sampleable_ext.wf
open nat lazy_list
section prio
open sampleable_ext
set_option default_priority 50
instance sampleable_ext.of_sampleable {α} [sampleable α] [has_repr α] : sampleable_ext α :=
{ proxy_repr := α,
sample := sampleable.sample α,
shrink := shrink }
instance sampleable.functor {α} {F} [functor F] [sampleable_functor F] [sampleable α] :
sampleable (F α) :=
{ wf := _,
sample := sampleable_functor.sample F (sampleable.sample α),
shrink := sampleable_functor.shrink α sampleable.shrink }
instance sampleable.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable α]
[sampleable β] : sampleable (F α β) :=
{ wf := _,
sample := sampleable_bifunctor.sample F (sampleable.sample α) (sampleable.sample β),
shrink := sampleable_bifunctor.shrink α β sampleable.shrink sampleable.shrink }
set_option default_priority 100
instance sampleable_ext.functor {α} {F} [functor F] [sampleable_functor F] [sampleable_ext α] :
sampleable_ext (F α) :=
{ wf := _,
proxy_repr := F (proxy_repr α),
interp := functor.map (interp _),
sample := sampleable_functor.sample F (sampleable_ext.sample α),
shrink := sampleable_functor.shrink _ sampleable_ext.shrink,
p_repr := sampleable_functor.p_repr _ sampleable_ext.p_repr }
instance sampleable_ext.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F]
[sampleable_ext α] [sampleable_ext β] : sampleable_ext (F α β) :=
{ wf := _,
proxy_repr := F (proxy_repr α) (proxy_repr β),
interp := bifunctor.bimap (interp _) (interp _),
sample := sampleable_bifunctor.sample F (sampleable_ext.sample α) (sampleable_ext.sample β),
shrink := sampleable_bifunctor.shrink _ _ sampleable_ext.shrink sampleable_ext.shrink,
p_repr := sampleable_bifunctor.p_repr _ _ sampleable_ext.p_repr sampleable_ext.p_repr }
end prio
/-- `nat.shrink' k n` creates a list of smaller natural numbers by
successively dividing `n` by 2 and subtracting the difference from
`k`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/
def nat.shrink' (k : ℕ) : Π n : ℕ, n ≤ k →
list { m : ℕ // has_well_founded.r m k } → list { m : ℕ // has_well_founded.r m k }
| n hn ls :=
if h : n ≤ 1
then ls.reverse
else
have h₂ : 0 < n, by linarith,
have 1 * n / 2 < n,
from nat.div_lt_of_lt_mul (nat.mul_lt_mul_of_pos_right (by norm_num) h₂),
have n / 2 < n, by simpa,
let m := n / 2 in
have h₀ : m ≤ k, from le_trans (le_of_lt this) hn,
have h₃ : 0 < m,
by simp only [m, lt_iff_add_one_le, zero_add]; rw [nat.le_div_iff_mul_le]; linarith,
have h₁ : k - m < k,
from nat.sub_lt (lt_of_lt_of_le h₂ hn) h₃,
nat.shrink' m h₀ (⟨k - m, h₁⟩ :: ls)
/-- `nat.shrink n` creates a list of smaller natural numbers by
successively dividing by 2 and subtracting the difference from
`n`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/
def nat.shrink (n : ℕ) : list { m : ℕ // has_well_founded.r m n } :=
if h : n > 0 then
have ∀ k, 1 < k → n / k < n, from
λ k hk,
nat.div_lt_of_lt_mul
(suffices 1 * n < k * n, by simpa,
nat.mul_lt_mul_of_pos_right hk h),
⟨n/11, this _ (by norm_num)⟩ :: ⟨n/3, this _ (by norm_num)⟩ :: nat.shrink' n n le_rfl []
else
[]
open gen
/--
Transport a `sampleable` instance from a type `α` to a type `β` using
functions between the two, going in both directions.
Function `g` is used to define the well-founded order that
`shrink` is expected to follow.
-/
def sampleable.lift (α : Type u) {β : Type u} [sampleable α] (f : α → β) (g : β → α)
(h : ∀ (a : α), sizeof (g (f a)) ≤ sizeof a) : sampleable β :=
{ wf := ⟨ sizeof ∘ g ⟩,
sample := f <$> sample α,
shrink := λ x,
have ∀ a, sizeof a < sizeof (g x) → sizeof (g (f a)) < sizeof (g x),
by introv h'; solve_by_elim [lt_of_le_of_lt],
subtype.map f this <$> shrink (g x) }
instance nat.sampleable : sampleable ℕ :=
{ sample := sized $ λ sz, freq [(1, coe <$> choose_any (fin $ succ (sz^3))),
(3, coe <$> choose_any (fin $ succ sz))] dec_trivial,
shrink := λ x, lazy_list.of_list $ nat.shrink x }
/-- `iterate_shrink p x` takes a decidable predicate `p` and a
value `x` of some sampleable type and recursively shrinks `x`.
It first calls `shrink x` to get a list of candidate sample,
finds the first that satisfies `p` and recursively tries
to shrink that one. -/
def iterate_shrink {α} [has_to_string α] [sampleable α]
(p : α → Prop) [decidable_pred p] :
α → option α :=
well_founded.fix has_well_founded.wf $ λ x f_rec,
do trace sformat!"{x} : {(shrink x).to_list}" $ pure (),
y ← (shrink x).find (λ a, p a),
f_rec y y.property <|> some y.val .
instance fin.sampleable {n} [fact $ 0 < n] : sampleable (fin n) :=
sampleable.lift ℕ fin.of_nat' subtype.val $
λ i, (mod_le _ _ : i % n ≤ i)
@[priority 100]
instance fin.sampleable' {n} : sampleable (fin (succ n)) :=
sampleable.lift ℕ fin.of_nat subtype.val $
λ i, (mod_le _ _ : i % succ n ≤ i)
instance pnat.sampleable : sampleable ℕ+ :=
sampleable.lift ℕ nat.succ_pnat pnat.nat_pred $ λ a,
by unfold_wf; simp only [pnat.nat_pred, succ_pnat, pnat.mk_coe, tsub_zero, succ_sub_succ_eq_sub]
/-- Redefine `sizeof` for `int` to make it easier to use with `nat` -/
def int.has_sizeof : has_sizeof ℤ := ⟨ int.nat_abs ⟩
local attribute [instance, priority 2000] int.has_sizeof
instance int.sampleable : sampleable ℤ :=
{ wf := _,
sample := sized $ λ sz,
freq [(1, subtype.val <$> choose (-(sz^3 + 1) : ℤ) (sz^3 + 1) (neg_le_self dec_trivial)),
(3, subtype.val <$> choose (-(sz + 1)) (sz + 1) (neg_le_self dec_trivial))]
dec_trivial,
shrink :=
λ x, lazy_list.of_list $ (nat.shrink $ int.nat_abs x).bind $
λ ⟨y,h⟩, [⟨y, h⟩, ⟨-y, by dsimp [sizeof,has_sizeof.sizeof]; rw int.nat_abs_neg; exact h ⟩] }
instance bool.sampleable : sampleable bool :=
{ wf := ⟨ λ b, if b then 1 else 0 ⟩,
sample := do { x ← choose_any bool,
return x },
shrink := λ b, if h : b then lazy_list.singleton ⟨ff, by cases h; unfold_wf⟩
else lazy_list.nil }
/--
Provided two shrinking functions `prod.shrink` shrinks a pair `(x, y)` by
first shrinking `x` and pairing the results with `y` and then shrinking
`y` and pairing the results with `x`.
All pairs either contain `x` untouched or `y` untouched. We rely on
shrinking being repeated for `x` to get maximally shrunken and then
for `y` to get shrunken too.
-/
def prod.shrink {α β} [has_sizeof α] [has_sizeof β]
(shr_a : shrink_fn α) (shr_b : shrink_fn β) : shrink_fn (α × β)
| ⟨x₀,x₁⟩ :=
let xs₀ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } :=
(shr_a x₀).map $ subtype.map (λ a, (a, x₁))
(λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h),
xs₁ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } :=
(shr_b x₁).map $ subtype.map (λ a, (x₀, a))
(λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h) in
xs₀.append xs₁
instance prod.sampleable : sampleable_bifunctor.{u v} prod :=
{ wf := _,
sample := λ α β sama samb, do
{ ⟨x⟩ ← (uliftable.up $ sama : gen (ulift.{max u v} α)),
⟨y⟩ ← (uliftable.up $ samb : gen (ulift.{max u v} β)),
pure (x,y) },
shrink := @prod.shrink,
p_repr := @prod.has_repr }
instance sigma.sampleable {α β} [sampleable α] [sampleable β] : sampleable (Σ _ : α, β) :=
sampleable.lift (α × β) (λ ⟨x,y⟩, ⟨x,y⟩) (λ ⟨x,y⟩, ⟨x,y⟩) $ λ ⟨x,y⟩, le_rfl
/-- shrinking function for sum types -/
def sum.shrink {α β} [has_sizeof α] [has_sizeof β] (shrink_α : shrink_fn α)
(shrink_β : shrink_fn β) : shrink_fn (α ⊕ β)
| (sum.inr x) := (shrink_β x).map $ subtype.map sum.inr $ λ a,
by dsimp [sizeof_lt]; unfold_wf; solve_by_elim
| (sum.inl x) := (shrink_α x).map $ subtype.map sum.inl $ λ a,
by dsimp [sizeof_lt]; unfold_wf; solve_by_elim
instance sum.sampleable : sampleable_bifunctor.{u v} sum :=
{ wf := _,
sample := λ (α : Type u) (β : Type v) sam_α sam_β,
(@uliftable.up_map gen.{u} gen.{max u v} _ _ _ _ (@sum.inl α β) sam_α <|>
@uliftable.up_map gen.{v} gen.{max v u} _ _ _ _ (@sum.inr α β) sam_β),
shrink := λ α β Iα Iβ shr_α shr_β, @sum.shrink _ _ Iα Iβ shr_α shr_β,
p_repr := @sum.has_repr }
instance rat.sampleable : sampleable ℚ :=
sampleable.lift (ℤ × ℕ+) (λ x, prod.cases_on x rat.mk_pnat) (λ r, (r.num, ⟨r.denom, r.pos⟩)) $
begin
intro i,
rcases i with ⟨x,⟨y,hy⟩⟩; unfold_wf;
dsimp [rat.mk_pnat],
mono*,
{ rw [← int.coe_nat_le, ← int.abs_eq_nat_abs, ← int.abs_eq_nat_abs],
apply int.abs_div_le_abs },
{ change _ - 1 ≤ y-1,
apply tsub_le_tsub_right,
apply nat.div_le_of_le_mul,
suffices : 1 * y ≤ x.nat_abs.gcd y * y, { simpa },
apply nat.mul_le_mul_right,
apply gcd_pos_of_pos_right _ hy }
end
/-- `sampleable_char` can be specialized into customized `sampleable char` instances.
The resulting instance has `1 / length` chances of making an unrestricted choice of characters
and it otherwise chooses a character from `characters` with uniform probabilities. -/
def sampleable_char (length : nat) (characters : string) : sampleable char :=
{ sample := do { x ← choose_nat 0 length dec_trivial,
if x.val = 0 then do
n ← sample ℕ,
pure $ char.of_nat n
else do
i ← choose_nat 0 (characters.length - 1) dec_trivial,
pure (characters.mk_iterator.nextn i).curr },
shrink := λ _, lazy_list.nil }
instance char.sampleable : sampleable char :=
sampleable_char 3 " 0123abcABC:,;`\\/"
variables {α}
section list_shrink
variables [has_sizeof α] (shr : Π x : α, lazy_list { y : α // sizeof_lt y x })
lemma list.sizeof_drop_lt_sizeof_of_lt_length {xs : list α} {k}
(hk : 0 < k) (hk' : k < xs.length) :
sizeof (list.drop k xs) < sizeof xs :=
begin
induction xs with x xs generalizing k,
{ cases hk' },
cases k,
{ cases hk },
have : sizeof xs < sizeof (x :: xs),
{ unfold_wf, linarith },
cases k,
{ simp only [this, list.drop] },
{ simp only [list.drop],
transitivity,
{ solve_by_elim [xs_ih, lt_of_succ_lt_succ hk', zero_lt_succ] },
{ assumption } }
end
lemma list.sizeof_cons_lt_right (a b : α) {xs : list α} (h : sizeof a < sizeof b) :
sizeof (a :: xs) < sizeof (b :: xs) :=
by unfold_wf; assumption
lemma list.sizeof_cons_lt_left (x : α) {xs xs' : list α} (h : sizeof xs < sizeof xs') :
sizeof (x :: xs) < sizeof (x :: xs') :=
by unfold_wf; assumption
lemma list.sizeof_append_lt_left {xs ys ys' : list α} (h : sizeof ys < sizeof ys') :
sizeof (xs ++ ys) < sizeof (xs ++ ys') :=
begin
induction xs,
{ apply h },
{ unfold_wf,
simp only [list.sizeof, add_lt_add_iff_left],
exact xs_ih }
end
lemma list.one_le_sizeof (xs : list α) : 1 ≤ sizeof xs :=
by cases xs; unfold_wf; linarith
/--
`list.shrink_removes` shrinks a list by removing chunks of size `k` in
the middle of the list.
-/
def list.shrink_removes (k : ℕ) (hk : 0 < k) : Π (xs : list α) n,
n = xs.length → lazy_list { ys : list α // sizeof_lt ys xs }
| xs n hn :=
if hkn : k > n then lazy_list.nil
else
if hkn' : k = n then
have 1 < xs.sizeof,
by { subst_vars, cases xs, { contradiction },
unfold_wf, apply lt_of_lt_of_le,
show 1 < 1 + has_sizeof.sizeof xs_hd + 1, { linarith },
{ mono, apply list.one_le_sizeof, } },
lazy_list.singleton ⟨[], this ⟩
else
have h₂ : k < xs.length, from hn ▸ lt_of_le_of_ne (le_of_not_gt hkn) hkn',
match list.split_at k xs, rfl : Π ys, ys = list.split_at k xs → _ with
| ⟨xs₁,xs₂⟩, h :=
have h₄ : xs₁ = xs.take k,
by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto,
have h₃ : xs₂ = xs.drop k,
by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto,
have sizeof xs₂ < sizeof xs,
by rw h₃; solve_by_elim [list.sizeof_drop_lt_sizeof_of_lt_length],
have h₁ : n - k = xs₂.length,
by simp only [h₃, ←hn, list.length_drop],
have h₅ : ∀ (a : list α), sizeof_lt a xs₂ → sizeof_lt (xs₁ ++ a) xs,
by intros a h; rw [← list.take_append_drop k xs, ← h₃, ← h₄];
solve_by_elim [list.sizeof_append_lt_left],
lazy_list.cons ⟨xs₂, this⟩ $ subtype.map ((++) xs₁) h₅ <$> list.shrink_removes xs₂ (n - k) h₁
end
/--
`list.shrink_one xs` shrinks list `xs` by shrinking only one item in
the list.
-/
def list.shrink_one : shrink_fn (list α)
| [] := lazy_list.nil
| (x :: xs) :=
lazy_list.append
(subtype.map (λ x', x' :: xs) (λ a, list.sizeof_cons_lt_right _ _) <$> shr x)
(subtype.map ((::) x) (λ _, list.sizeof_cons_lt_left _) <$> list.shrink_one xs)
/-- `list.shrink_with shrink_f xs` shrinks `xs` by first
considering `xs` with chunks removed in the middle (starting with
chunks of size `xs.length` and halving down to `1`) and then
shrinks only one element of the list.
This strategy is taken directly from Haskell's QuickCheck -/
def list.shrink_with (xs : list α) :
lazy_list { ys : list α // sizeof_lt ys xs } :=
let n := xs.length in
lazy_list.append
((lazy_list.cons n $ (shrink n).reverse.map subtype.val).bind (λ k,
if hk : 0 < k
then list.shrink_removes k hk xs n rfl
else lazy_list.nil ))
(list.shrink_one shr _)
end list_shrink
instance list.sampleable : sampleable_functor list.{u} :=
{ wf := _,
sample := λ α sam_α, list_of sam_α,
shrink := λ α Iα shr_α, @list.shrink_with _ Iα shr_α,
p_repr := @list.has_repr }
instance Prop.sampleable_ext : sampleable_ext Prop :=
{ proxy_repr := bool,
interp := coe,
sample := choose_any bool,
shrink := λ _, lazy_list.nil }
/-- `no_shrink` is a type annotation to signal that
a certain type is not to be shrunk. It can be useful in
combination with other types: e.g. `xs : list (no_shrink ℤ)`
will result in the list being cut down but individual
integers being kept as is. -/
def no_shrink (α : Type*) := α
instance no_shrink.inhabited {α} [inhabited α] : inhabited (no_shrink α) :=
⟨ (default : α) ⟩
/-- Introduction of the `no_shrink` type. -/
def no_shrink.mk {α} (x : α) : no_shrink α := x
/-- Selector of the `no_shrink` type. -/
def no_shrink.get {α} (x : no_shrink α) : α := x
instance no_shrink.sampleable {α} [sampleable α] : sampleable (no_shrink α) :=
{ sample := no_shrink.mk <$> sample α }
instance string.sampleable : sampleable string :=
{ sample := do { x ← list_of (sample char), pure x.as_string },
.. sampleable.lift (list char) list.as_string string.to_list $ λ _, le_rfl }
/-- implementation of `sampleable (tree α)` -/
def tree.sample (sample : gen α) : ℕ → gen (tree α) | n :=
if h : n > 0
then have n / 2 < n, from div_lt_self h (by norm_num),
tree.node <$> sample <*> tree.sample (n / 2) <*> tree.sample (n / 2)
else pure tree.nil
/-- `rec_shrink x f_rec` takes the recursive call `f_rec` introduced
by `well_founded.fix` and turns it into a shrinking function whose
result is adequate to use in a recursive call. -/
def rec_shrink {α : Type*} [has_sizeof α] (t : α)
(sh : Π x : α, sizeof_lt x t → lazy_list { y : α // sizeof_lt y x }) :
shrink_fn { t' : α // sizeof_lt t' t }
| ⟨t',ht'⟩ := (λ t'' : { y : α // sizeof_lt y t' },
⟨⟨t''.val, lt_trans t''.property ht'⟩, t''.property⟩ ) <$> sh t' ht'
lemma tree.one_le_sizeof {α} [has_sizeof α] (t : tree α) : 1 ≤ sizeof t :=
by cases t; unfold_wf; linarith
instance : functor tree :=
{ map := @tree.map }
/--
Recursion principle for shrinking tree-like structures.
-/
def rec_shrink_with [has_sizeof α]
(shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } →
list (lazy_list { y : α // sizeof_lt y x })) :
shrink_fn α :=
well_founded.fix (sizeof_measure_wf _) $ λ t f_rec,
lazy_list.join
(lazy_list.of_list $
shrink_a t $ λ ⟨t', h⟩, rec_shrink _ f_rec _)
lemma rec_shrink_with_eq [has_sizeof α]
(shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } →
list (lazy_list { y : α // sizeof_lt y x }))
(x : α) :
rec_shrink_with shrink_a x =
lazy_list.join
(lazy_list.of_list $ shrink_a x $ λ t', rec_shrink _ (λ x h', rec_shrink_with shrink_a x) _) :=
begin
conv_lhs { rw [rec_shrink_with, well_founded.fix_eq], },
congr, ext ⟨y, h⟩, refl
end
/-- `tree.shrink_with shrink_f t` shrinks `xs` by using the empty tree,
each subtrees, and by shrinking the subtree to recombine them.
This strategy is taken directly from Haskell's QuickCheck -/
def tree.shrink_with [has_sizeof α] (shrink_a : shrink_fn α) : shrink_fn (tree α) :=
rec_shrink_with $ λ t,
match t with
| tree.nil := λ f_rec, []
| (tree.node x t₀ t₁) :=
λ f_rec,
have h₂ : sizeof_lt tree.nil (tree.node x t₀ t₁),
by clear _match; have := tree.one_le_sizeof t₀;
dsimp [sizeof_lt, sizeof, has_sizeof.sizeof] at *;
unfold_wf; linarith,
have h₀ : sizeof_lt t₀ (tree.node x t₀ t₁),
by dsimp [sizeof_lt]; unfold_wf; linarith,
have h₁ : sizeof_lt t₁ (tree.node x t₀ t₁),
by dsimp [sizeof_lt]; unfold_wf; linarith,
[lazy_list.of_list [⟨tree.nil, h₂⟩, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩],
(prod.shrink shrink_a (prod.shrink f_rec f_rec) (x, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩)).map
$ λ ⟨⟨y,⟨t'₀, _⟩,⟨t'₁, _⟩⟩,hy⟩, ⟨tree.node y t'₀ t'₁,
by revert hy; dsimp [sizeof_lt]; unfold_wf; intro; linarith⟩]
end
instance sampleable_tree : sampleable_functor tree :=
{ wf := _,
sample := λ α sam_α, sized $ tree.sample sam_α,
shrink := λ α Iα shr_α, @tree.shrink_with _ Iα shr_α,
p_repr := @tree.has_repr }
/-- Type tag that signals to `slim_check` to use small values for a given type. -/
def small (α : Type*) := α
/-- Add the `small` type tag -/
def small.mk {α} (x : α) : small α := x
/-- Type tag that signals to `slim_check` to use large values for a given type. -/
def large (α : Type*) := α
/-- Add the `large` type tag -/
def large.mk {α} (x : α) : large α := x
instance small.functor : functor small := id.monad.to_functor
instance large.functor : functor large := id.monad.to_functor
instance small.inhabited [inhabited α] : inhabited (small α) := ⟨ (default : α) ⟩
instance large.inhabited [inhabited α] : inhabited (large α) := ⟨ (default : α) ⟩
instance small.sampleable_functor : sampleable_functor small :=
{ wf := _,
sample := λ α samp, gen.resize (λ n, n / 5 + 5) samp,
shrink := λ α _, id,
p_repr := λ α, id }
instance large.sampleable_functor : sampleable_functor large :=
{ wf := _,
sample := λ α samp, gen.resize (λ n, n * 5) samp,
shrink := λ α _, id,
p_repr := λ α, id }
instance ulift.sampleable_functor : sampleable_functor ulift.{u v} :=
{ wf := λ α h, ⟨ λ ⟨x⟩, @sizeof α h x ⟩,
sample := λ α samp, uliftable.up_map ulift.up $ samp,
shrink := λ α _ shr ⟨x⟩, (shr x).map (subtype.map ulift.up (λ a h, h)),
p_repr := λ α h, ⟨ @repr α h ∘ ulift.down ⟩ }
/-!
## Subtype instances
The following instances are meant to improve the testing of properties of the form
`∀ i j, i ≤ j, ...`
The naive way to test them is to choose two numbers `i` and `j` and check that
the proper ordering is satisfied. Instead, the following instances make it
so that `j` will be chosen with considerations to the required ordering
constraints. The benefit is that we will not have to discard any choice
of `j`.
-/
/-! ### Subtypes of `ℕ` -/
instance nat_le.sampleable {y} : slim_check.sampleable { x : ℕ // x ≤ y } :=
{ sample :=
do { ⟨x,h⟩ ← slim_check.gen.choose_nat 0 y dec_trivial,
pure ⟨x, h.2⟩},
shrink := λ ⟨x, h⟩, (λ a : subtype _, subtype.rec_on a $
λ x' h', ⟨⟨x', le_trans (le_of_lt h') h⟩, h'⟩) <$> shrink x }
instance nat_ge.sampleable {x} : slim_check.sampleable { y : ℕ // x ≤ y } :=
{ sample :=
do { (y : ℕ) ← slim_check.sampleable.sample ℕ,
pure ⟨x+y, by norm_num⟩ },
shrink := λ ⟨y, h⟩, (λ a : { y' // sizeof y' < sizeof (y - x) },
subtype.rec_on a $ λ δ h', ⟨⟨x + δ, nat.le_add_right _ _⟩, lt_tsub_iff_left.mp h'⟩) <$>
shrink (y - x) }
/- there is no `nat_lt.sampleable` instance because if `y = 0`, there is no valid choice
to satisfy `x < y` -/
instance nat_gt.sampleable {x} : slim_check.sampleable { y : ℕ // x < y } :=
{ sample :=
do { (y : ℕ) ← slim_check.sampleable.sample ℕ,
pure ⟨x+y+1, by linarith⟩ },
shrink := λ x, shrink _ }
/-! ### Subtypes of any `linear_ordered_add_comm_group` -/
instance le.sampleable {y : α} [sampleable α] [linear_ordered_add_comm_group α] :
slim_check.sampleable { x : α // x ≤ y } :=
{ sample :=
do { x ← sample α,
pure ⟨y - |x|, sub_le_self _ (abs_nonneg _) ⟩ },
shrink := λ _, lazy_list.nil }
instance ge.sampleable {x : α} [sampleable α] [linear_ordered_add_comm_group α] :
slim_check.sampleable { y : α // x ≤ y } :=
{ sample :=
do { y ← sample α,
pure ⟨x + |y|, by norm_num [abs_nonneg]⟩ },
shrink := λ _, lazy_list.nil }
/-!
### Subtypes of `ℤ`
Specializations of `le.sampleable` and `ge.sampleable` for `ℤ` to help instance search.
-/
instance int_le.sampleable {y : ℤ} : slim_check.sampleable { x : ℤ // x ≤ y } :=
sampleable.lift ℕ (λ n, ⟨y - n, int.sub_left_le_of_le_add $ by simp⟩) (λ ⟨i, h⟩, (y - i).nat_abs)
(λ n, by unfold_wf; simp [int_le.sampleable._match_1]; ring)
instance int_ge.sampleable {x : ℤ} : slim_check.sampleable { y : ℤ // x ≤ y } :=
sampleable.lift ℕ (λ n, ⟨x + n, by simp⟩) (λ ⟨i, h⟩, (i - x).nat_abs)
(λ n, by unfold_wf; simp [int_ge.sampleable._match_1]; ring)
instance int_lt.sampleable {y} : slim_check.sampleable { x : ℤ // x < y } :=
sampleable.lift ℕ (λ n, ⟨y - (n+1), int.sub_left_lt_of_lt_add $
by linarith [int.coe_nat_nonneg n]⟩)
(λ ⟨i, h⟩, (y - i - 1).nat_abs)
(λ n, by unfold_wf; simp [int_lt.sampleable._match_1]; ring)
instance int_gt.sampleable {x} : slim_check.sampleable { y : ℤ // x < y } :=
sampleable.lift ℕ (λ n, ⟨x + (n+1), by linarith⟩) (λ ⟨i, h⟩, (i - x - 1).nat_abs)
(λ n, by unfold_wf; simp [int_gt.sampleable._match_1]; ring)
/-! ### Subtypes of any `list` -/
instance perm.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm xs ys } :=
{ sample := permutation_of xs,
shrink := λ _, lazy_list.nil }
instance perm'.slim_check {xs : list α} :
slim_check.sampleable { ys : list α // list.perm ys xs } :=
{ sample := subtype.map id (@list.perm.symm α _) <$> permutation_of xs,
shrink := λ _, lazy_list.nil }
setup_tactic_parser
open tactic
/--
Print (at most) 10 samples of a given type to stdout for debugging.
-/
def print_samples {t : Type u} [has_repr t] (g : gen t) : io unit := do
xs ← io.run_rand $ uliftable.down $
do { xs ← (list.range 10).mmap $ g.run ∘ ulift.up,
pure ⟨xs.map repr⟩ },
xs.mmap' io.put_str_ln
/-- Create a `gen α` expression from the argument of `#sample` -/
meta def mk_generator (e : expr) : tactic (expr × expr) := do
t ← infer_type e,
match t with
| `(gen %%t) := do
repr_inst ← mk_app ``has_repr [t] >>= mk_instance,
pure (repr_inst, e)
| _ := do
samp_inst ← to_expr ``(sampleable_ext %%e) >>= mk_instance,
repr_inst ← mk_mapp ``sampleable_ext.p_repr [e, samp_inst],
gen ← mk_mapp ``sampleable_ext.sample [none, samp_inst],
pure (repr_inst, gen)
end
/--
`#sample my_type`, where `my_type` has an instance of `sampleable`, prints ten random
values of type `my_type` of using an increasing size parameter.
```lean
#sample nat
-- prints
-- 0
-- 0
-- 2
-- 24
-- 64
-- 76
-- 5
-- 132
-- 8
-- 449
-- or some other sequence of numbers
#sample list int
-- prints
-- []
-- [1, 1]
-- [-7, 9, -6]
-- [36]
-- [-500, 105, 260]
-- [-290]
-- [17, 156]
-- [-2364, -7599, 661, -2411, -3576, 5517, -3823, -968]
-- [-643]
-- [11892, 16329, -15095, -15461]
-- or whatever
```
-/
@[user_command]
meta def sample_cmd (_ : parse $ tk "#sample") : lean.parser unit :=
do e ← texpr,
of_tactic $ do
e ← i_to_expr e,
(repr_inst, gen) ← mk_generator e,
print_samples ← mk_mapp ``print_samples [none, repr_inst, gen],
sample ← eval_expr (io unit) print_samples,
unsafe_run_io sample
end slim_check
|
8d0970891b04a027eb4b859edf18157971525587 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/zmod/basic.lean | 487128e792bdec91e0bc4d35e0d711a87570a45d | [
"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 | 32,686 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import algebra.char_p.basic
import ring_theory.ideal.operations
import tactic.fin_cases
/-!
# Integers mod `n`
Definition of the integers mod n, and the field structure on the integers mod p.
## Definitions
* `zmod n`, which is for integers modulo a nat `n : ℕ`
* `val a` is defined as a natural number:
- for `a : zmod 0` it is the absolute value of `a`
- for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class
* `val_min_abs` returns the integer closest to zero in the equivalence class.
* A coercion `cast` is defined from `zmod n` into any ring.
This is a ring hom if the ring has characteristic dividing `n`
-/
namespace fin
/-!
## Ring structure on `fin n`
We define a commutative ring structure on `fin n`, but we do not register it as instance.
Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions
to register the ring structure on `zmod n` as type class instance.
-/
open nat.modeq int
/-- Multiplicative commutative semigroup structure on `fin (n+1)`. -/
instance (n : ℕ) : comm_semigroup (fin (n+1)) :=
{ mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc ((a * b) % (n+1) * c) ≡ a * b * c [MOD (n+1)] : (nat.mod_modeq _ _).mul_right _
... ≡ a * (b * c) [MOD (n+1)] : by rw mul_assoc
... ≡ a * (b * c % (n+1)) [MOD (n+1)] : (nat.mod_modeq _ _).symm.mul_left _),
mul_comm := λ ⟨a, _⟩ ⟨b, _⟩,
fin.eq_of_veq (show (a * b) % (n+1) = (b * a) % (n+1), by rw mul_comm),
..fin.has_mul }
private lemma left_distrib_aux (n : ℕ) : ∀ a b c : fin (n+1), a * (b + c) = a * b + a * c :=
λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc a * ((b + c) % (n+1)) ≡ a * (b + c) [MOD (n+1)] : (nat.mod_modeq _ _).mul_left _
... ≡ a * b + a * c [MOD (n+1)] : by rw mul_add
... ≡ (a * b) % (n+1) + (a * c) % (n+1) [MOD (n+1)] :
(nat.mod_modeq _ _).symm.add (nat.mod_modeq _ _).symm)
/-- Commutative ring structure on `fin (n+1)`. -/
instance (n : ℕ) : comm_ring (fin (n+1)) :=
{ one_mul := fin.one_mul,
mul_one := fin.mul_one,
left_distrib := left_distrib_aux n,
right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl,
..fin.has_one,
..fin.add_comm_group n,
..fin.comm_semigroup n }
end fin
/-- The integers modulo `n : ℕ`. -/
def zmod : ℕ → Type
| 0 := ℤ
| (n+1) := fin (n+1)
namespace zmod
instance fintype : Π (n : ℕ) [fact (0 < n)], fintype (zmod n)
| 0 h := false.elim $ nat.not_lt_zero 0 h.1
| (n+1) _ := fin.fintype (n+1)
@[simp] lemma card (n : ℕ) [fact (0 < n)] : fintype.card (zmod n) = n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
{ exact fintype.card_fin (n+1) }
end
instance decidable_eq : Π (n : ℕ), decidable_eq (zmod n)
| 0 := int.decidable_eq
| (n+1) := fin.decidable_eq _
instance has_repr : Π (n : ℕ), has_repr (zmod n)
| 0 := int.has_repr
| (n+1) := fin.has_repr _
instance comm_ring : Π (n : ℕ), comm_ring (zmod n)
| 0 := int.comm_ring
| (n+1) := fin.comm_ring n
instance inhabited (n : ℕ) : inhabited (zmod n) := ⟨0⟩
/-- `val a` is a natural number defined as:
- for `a : zmod 0` it is the absolute value of `a`
- for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class
See `zmod.val_min_abs` for a variant that takes values in the integers.
-/
def val : Π {n : ℕ}, zmod n → ℕ
| 0 := int.nat_abs
| (n+1) := (coe : fin (n + 1) → ℕ)
lemma val_lt {n : ℕ} [fact (0 < n)] (a : zmod n) : a.val < n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
exact fin.is_lt a
end
lemma val_le {n : ℕ} [fact (0 < n)] (a : zmod n) : a.val ≤ n :=
a.val_lt.le
@[simp] lemma val_zero : ∀ {n}, (0 : zmod n).val = 0
| 0 := rfl
| (n+1) := rfl
@[simp] lemma val_one' : (1 : zmod 0).val = 1 := rfl
@[simp] lemma val_neg' {n : zmod 0} : (-n).val = n.val := by simp [val]
@[simp] lemma val_mul' {m n : zmod 0} : (m * n).val = m.val * n.val :=
by simp [val, int.nat_abs_mul]
lemma val_nat_cast {n : ℕ} (a : ℕ) : (a : zmod n).val = a % n :=
begin
casesI n,
{ rw [nat.mod_zero, int.nat_cast_eq_coe_nat],
exact int.nat_abs_of_nat a, },
rw ← fin.of_nat_eq_coe,
refl
end
instance (n : ℕ) : char_p (zmod n) n :=
{ cast_eq_zero_iff :=
begin
intro k,
cases n,
{ simp only [int.nat_cast_eq_coe_nat, zero_dvd_iff, int.coe_nat_eq_zero], },
rw [fin.eq_iff_veq],
show (k : zmod (n+1)).val = (0 : zmod (n+1)).val ↔ _,
rw [val_nat_cast, val_zero, nat.dvd_iff_mod_eq_zero],
end }
@[simp] lemma nat_cast_self (n : ℕ) : (n : zmod n) = 0 :=
char_p.cast_eq_zero (zmod n) n
@[simp] lemma nat_cast_self' (n : ℕ) : (n + 1 : zmod (n + 1)) = 0 :=
by rw [← nat.cast_add_one, nat_cast_self (n + 1)]
section universal_property
variables {n : ℕ} {R : Type*}
section
variables [has_zero R] [has_one R] [has_add R] [has_neg R]
/-- Cast an integer modulo `n` to another semiring.
This function is a morphism if the characteristic of `R` divides `n`.
See `zmod.cast_hom` for a bundled version. -/
def cast : Π {n : ℕ}, zmod n → R
| 0 := int.cast
| (n+1) := λ i, i.val
-- see Note [coercion into rings]
@[priority 900] instance (n : ℕ) : has_coe_t (zmod n) R := ⟨cast⟩
@[simp] lemma cast_zero : ((0 : zmod n) : R) = 0 :=
by { cases n; refl }
variables {S : Type*} [has_zero S] [has_one S] [has_add S] [has_neg S]
@[simp] lemma _root_.prod.fst_zmod_cast (a : zmod n) : (a : R × S).fst = a :=
by cases n; simp
@[simp] lemma _root_.prod.snd_zmod_cast (a : zmod n) : (a : R × S).snd = a :=
by cases n; simp
end
/-- So-named because the coercion is `nat.cast` into `zmod`. For `nat.cast` into an arbitrary ring,
see `zmod.nat_cast_val`. -/
lemma nat_cast_zmod_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : zmod n) = a :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
{ apply fin.coe_coe_eq_self }
end
lemma nat_cast_right_inverse [fact (0 < n)] : function.right_inverse val (coe : ℕ → zmod n) :=
nat_cast_zmod_val
lemma nat_cast_zmod_surjective [fact (0 < n)] : function.surjective (coe : ℕ → zmod n) :=
nat_cast_right_inverse.surjective
/-- So-named because the outer coercion is `int.cast` into `zmod`. For `int.cast` into an arbitrary
ring, see `zmod.int_cast_cast`. -/
lemma int_cast_zmod_cast (a : zmod n) : ((a : ℤ) : zmod n) = a :=
begin
cases n,
{ rw [int.cast_id a, int.cast_id a], },
{ rw [coe_coe, int.nat_cast_eq_coe_nat, int.cast_coe_nat, fin.coe_coe_eq_self] }
end
lemma int_cast_right_inverse : function.right_inverse (coe : zmod n → ℤ) (coe : ℤ → zmod n) :=
int_cast_zmod_cast
lemma int_cast_surjective : function.surjective (coe : ℤ → zmod n) :=
int_cast_right_inverse.surjective
@[norm_cast]
lemma cast_id : ∀ n (i : zmod n), ↑i = i
| 0 i := int.cast_id i
| (n+1) i := nat_cast_zmod_val i
@[simp]
lemma cast_id' : (coe : zmod n → zmod n) = id := funext (cast_id n)
variables (R) [ring R]
/-- The coercions are respectively `nat.cast` and `zmod.cast`. -/
@[simp] lemma nat_cast_comp_val [fact (0 < n)] :
(coe : ℕ → R) ∘ (val : zmod n → ℕ) = coe :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
refl
end
/-- The coercions are respectively `int.cast`, `zmod.cast`, and `zmod.cast`. -/
@[simp] lemma int_cast_comp_cast : (coe : ℤ → R) ∘ (coe : zmod n → ℤ) = coe :=
begin
cases n,
{ exact congr_arg ((∘) int.cast) zmod.cast_id', },
{ ext, simp }
end
variables {R}
@[simp] lemma nat_cast_val [fact (0 < n)] (i : zmod n) : (i.val : R) = i :=
congr_fun (nat_cast_comp_val R) i
@[simp] lemma int_cast_cast (i : zmod n) : ((i : ℤ) : R) = i :=
congr_fun (int_cast_comp_cast R) i
lemma coe_add_eq_ite {n : ℕ} (a b : zmod n) :
(↑(a + b) : ℤ) = if (n : ℤ) ≤ a + b then a + b - n else a + b :=
begin
cases n,
{ simp },
simp only [coe_coe, fin.coe_add_eq_ite, int.nat_cast_eq_coe_nat,
← int.coe_nat_add, ← int.coe_nat_succ, int.coe_nat_le],
split_ifs with h,
{ exact int.coe_nat_sub h },
{ refl }
end
section char_dvd
/-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/
variables {n} {m : ℕ} [char_p R m]
@[simp] lemma cast_one (h : m ∣ n) : ((1 : zmod n) : R) = 1 :=
begin
casesI n,
{ exact int.cast_one },
show ((1 % (n+1) : ℕ) : R) = 1,
cases n, { rw [nat.dvd_one] at h, substI m, apply subsingleton.elim },
rw nat.mod_eq_of_lt,
{ exact nat.cast_one },
exact nat.lt_of_sub_eq_succ rfl
end
lemma cast_add (h : m ∣ n) (a b : zmod n) : ((a + b : zmod n) : R) = a + b :=
begin
casesI n,
{ apply int.cast_add },
simp only [coe_coe],
symmetry,
erw [fin.coe_add, ← nat.cast_add, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _),
@char_p.cast_eq_zero_iff R _ _ m],
exact h.trans (nat.dvd_sub_mod _),
end
lemma cast_mul (h : m ∣ n) (a b : zmod n) : ((a * b : zmod n) : R) = a * b :=
begin
casesI n,
{ apply int.cast_mul },
simp only [coe_coe],
symmetry,
erw [fin.coe_mul, ← nat.cast_mul, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _),
@char_p.cast_eq_zero_iff R _ _ m],
exact h.trans (nat.dvd_sub_mod _),
end
/-- The canonical ring homomorphism from `zmod n` to a ring of characteristic `n`.
See also `zmod.lift` (in `data.zmod.quotient`) for a generalized version working in `add_group`s.
-/
def cast_hom (h : m ∣ n) (R : Type*) [ring R] [char_p R m] : zmod n →+* R :=
{ to_fun := coe,
map_zero' := cast_zero,
map_one' := cast_one h,
map_add' := cast_add h,
map_mul' := cast_mul h }
@[simp] lemma cast_hom_apply {h : m ∣ n} (i : zmod n) : cast_hom h R i = i := rfl
@[simp, norm_cast]
lemma cast_sub (h : m ∣ n) (a b : zmod n) : ((a - b : zmod n) : R) = a - b :=
(cast_hom h R).map_sub a b
@[simp, norm_cast]
lemma cast_neg (h : m ∣ n) (a : zmod n) : ((-a : zmod n) : R) = -a :=
(cast_hom h R).map_neg a
@[simp, norm_cast]
lemma cast_pow (h : m ∣ n) (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k :=
(cast_hom h R).map_pow a k
@[simp, norm_cast]
lemma cast_nat_cast (h : m ∣ n) (k : ℕ) : ((k : zmod n) : R) = k :=
map_nat_cast (cast_hom h R) k
@[simp, norm_cast]
lemma cast_int_cast (h : m ∣ n) (k : ℤ) : ((k : zmod n) : R) = k :=
(cast_hom h R).map_int_cast k
end char_dvd
section char_eq
/-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/
variable [char_p R n]
@[simp] lemma cast_one' : ((1 : zmod n) : R) = 1 :=
cast_one dvd_rfl
@[simp] lemma cast_add' (a b : zmod n) : ((a + b : zmod n) : R) = a + b :=
cast_add dvd_rfl a b
@[simp] lemma cast_mul' (a b : zmod n) : ((a * b : zmod n) : R) = a * b :=
cast_mul dvd_rfl a b
@[simp] lemma cast_sub' (a b : zmod n) : ((a - b : zmod n) : R) = a - b :=
cast_sub dvd_rfl a b
@[simp] lemma cast_pow' (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k :=
cast_pow dvd_rfl a k
@[simp, norm_cast]
lemma cast_nat_cast' (k : ℕ) : ((k : zmod n) : R) = k :=
cast_nat_cast dvd_rfl k
@[simp, norm_cast]
lemma cast_int_cast' (k : ℤ) : ((k : zmod n) : R) = k :=
cast_int_cast dvd_rfl k
variables (R)
lemma cast_hom_injective : function.injective (zmod.cast_hom (dvd_refl n) R) :=
begin
rw ring_hom.injective_iff,
intro x,
obtain ⟨k, rfl⟩ := zmod.int_cast_surjective x,
rw [ring_hom.map_int_cast, char_p.int_cast_eq_zero_iff R n,
char_p.int_cast_eq_zero_iff (zmod n) n],
exact id
end
lemma cast_hom_bijective [fintype R] (h : fintype.card R = n) :
function.bijective (zmod.cast_hom (dvd_refl n) R) :=
begin
haveI : fact (0 < n) :=
⟨begin
rw [pos_iff_ne_zero],
intro hn,
rw hn at h,
exact (fintype.card_eq_zero_iff.mp h).elim' 0
end⟩,
rw [fintype.bijective_iff_injective_and_card, zmod.card, h, eq_self_iff_true, and_true],
apply zmod.cast_hom_injective
end
/-- The unique ring isomorphism between `zmod n` and a ring `R`
of characteristic `n` and cardinality `n`. -/
noncomputable def ring_equiv [fintype R] (h : fintype.card R = n) : zmod n ≃+* R :=
ring_equiv.of_bijective _ (zmod.cast_hom_bijective R h)
end char_eq
end universal_property
lemma int_coe_eq_int_coe_iff (a b : ℤ) (c : ℕ) :
(a : zmod c) = (b : zmod c) ↔ a ≡ b [ZMOD c] :=
char_p.int_coe_eq_int_coe_iff (zmod c) c a b
lemma int_coe_eq_int_coe_iff' (a b : ℤ) (c : ℕ) :
(a : zmod c) = (b : zmod c) ↔ a % c = b % c :=
zmod.int_coe_eq_int_coe_iff a b c
lemma nat_coe_eq_nat_coe_iff (a b c : ℕ) :
(a : zmod c) = (b : zmod c) ↔ a ≡ b [MOD c] :=
begin
convert zmod.int_coe_eq_int_coe_iff a b c,
simp [nat.modeq_iff_dvd, int.modeq_iff_dvd],
end
lemma nat_coe_eq_nat_coe_iff' (a b c : ℕ) :
(a : zmod c) = (b : zmod c) ↔ a % c = b % c :=
zmod.nat_coe_eq_nat_coe_iff a b c
lemma int_coe_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : zmod b) = 0 ↔ (b : ℤ) ∣ a :=
begin
change (a : zmod b) = ((0 : ℤ) : zmod b) ↔ (b : ℤ) ∣ a,
rw [zmod.int_coe_eq_int_coe_iff, int.modeq_zero_iff_dvd],
end
lemma nat_coe_zmod_eq_zero_iff_dvd (a b : ℕ) : (a : zmod b) = 0 ↔ b ∣ a :=
begin
change (a : zmod b) = ((0 : ℕ) : zmod b) ↔ b ∣ a,
rw [zmod.nat_coe_eq_nat_coe_iff, nat.modeq_zero_iff_dvd],
end
@[push_cast, simp]
lemma int_cast_mod (a : ℤ) (b : ℕ) : ((a % b : ℤ) : zmod b) = (a : zmod b) :=
begin
rw zmod.int_coe_eq_int_coe_iff,
apply int.mod_modeq,
end
lemma ker_int_cast_add_hom (n : ℕ) :
(int.cast_add_hom (zmod n)).ker = add_subgroup.zmultiples n :=
by { ext, rw [int.mem_zmultiples_iff, add_monoid_hom.mem_ker,
int.coe_cast_add_hom, int_coe_zmod_eq_zero_iff_dvd] }
lemma ker_int_cast_ring_hom (n : ℕ) :
(int.cast_ring_hom (zmod n)).ker = ideal.span ({n} : set ℤ) :=
by { ext, rw [ideal.mem_span_singleton, ring_hom.mem_ker,
int.coe_cast_ring_hom, int_coe_zmod_eq_zero_iff_dvd] }
local attribute [semireducible] int.nonneg
@[simp] lemma nat_cast_to_nat (p : ℕ) :
∀ {z : ℤ} (h : 0 ≤ z), (z.to_nat : zmod p) = z
| (n : ℕ) h := by simp only [int.cast_coe_nat, int.to_nat_coe_nat]
| -[1+n] h := false.elim h
lemma val_injective (n : ℕ) [fact (0 < n)] :
function.injective (zmod.val : zmod n → ℕ) :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
assume a b h,
ext,
exact h
end
lemma val_one_eq_one_mod (n : ℕ) : (1 : zmod n).val = 1 % n :=
by rw [← nat.cast_one, val_nat_cast]
lemma val_one (n : ℕ) [fact (1 < n)] : (1 : zmod n).val = 1 :=
by { rw val_one_eq_one_mod, exact nat.mod_eq_of_lt (fact.out _) }
lemma val_add {n : ℕ} [fact (0 < n)] (a b : zmod n) : (a + b).val = (a.val + b.val) % n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
{ apply fin.val_add }
end
lemma val_mul {n : ℕ} (a b : zmod n) : (a * b).val = (a.val * b.val) % n :=
begin
cases n,
{ rw nat.mod_zero, apply int.nat_abs_mul },
{ apply fin.val_mul }
end
instance nontrivial (n : ℕ) [fact (1 < n)] : nontrivial (zmod n) :=
⟨⟨0, 1, assume h, zero_ne_one $
calc 0 = (0 : zmod n).val : by rw val_zero
... = (1 : zmod n).val : congr_arg zmod.val h
... = 1 : val_one n ⟩⟩
/-- The inversion on `zmod n`.
It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`.
In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/
def inv : Π (n : ℕ), zmod n → zmod n
| 0 i := int.sign i
| (n+1) i := nat.gcd_a i.val (n+1)
instance (n : ℕ) : has_inv (zmod n) := ⟨inv n⟩
lemma inv_zero : ∀ (n : ℕ), (0 : zmod n)⁻¹ = 0
| 0 := int.sign_zero
| (n+1) := show (nat.gcd_a _ (n+1) : zmod (n+1)) = 0,
by { rw val_zero, unfold nat.gcd_a nat.xgcd nat.xgcd_aux, refl }
lemma mul_inv_eq_gcd {n : ℕ} (a : zmod n) :
a * a⁻¹ = nat.gcd a.val n :=
begin
cases n,
{ calc a * a⁻¹ = a * int.sign a : rfl
... = a.nat_abs : by rw [int.mul_sign, int.nat_cast_eq_coe_nat]
... = a.val.gcd 0 : by rw nat.gcd_zero_right; refl },
{ set k := n.succ,
calc a * a⁻¹ = a * a⁻¹ + k * nat.gcd_b (val a) k : by rw [nat_cast_self, zero_mul, add_zero]
... = ↑(↑a.val * nat.gcd_a (val a) k + k * nat.gcd_b (val a) k) :
by { push_cast, rw nat_cast_zmod_val, refl }
... = nat.gcd a.val k : (congr_arg coe (nat.gcd_eq_gcd_ab a.val k)).symm, }
end
@[simp] lemma nat_cast_mod (n : ℕ) (a : ℕ) : ((a % n : ℕ) : zmod n) = a :=
by conv {to_rhs, rw ← nat.mod_add_div a n}; simp
lemma eq_iff_modeq_nat (n : ℕ) {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] :=
begin
cases n,
{ simp only [nat.modeq, int.coe_nat_inj', nat.mod_zero, int.nat_cast_eq_coe_nat], },
{ rw [fin.ext_iff, nat.modeq, ← val_nat_cast, ← val_nat_cast], exact iff.rfl, }
end
lemma coe_mul_inv_eq_one {n : ℕ} (x : ℕ) (h : nat.coprime x n) :
(x * x⁻¹ : zmod n) = 1 :=
begin
rw [nat.coprime, nat.gcd_comm, nat.gcd_rec] at h,
rw [mul_inv_eq_gcd, val_nat_cast, h, nat.cast_one],
end
/-- `unit_of_coprime` makes an element of `(zmod n)ˣ` given
a natural number `x` and a proof that `x` is coprime to `n` -/
def unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (zmod n)ˣ :=
⟨x, x⁻¹, coe_mul_inv_eq_one x h, by rw [mul_comm, coe_mul_inv_eq_one x h]⟩
@[simp] lemma coe_unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) :
(unit_of_coprime x h : zmod n) = x := rfl
lemma val_coe_unit_coprime {n : ℕ} (u : (zmod n)ˣ) :
nat.coprime (u : zmod n).val n :=
begin
cases n,
{ rcases int.units_eq_one_or u with rfl|rfl; simp },
apply nat.coprime_of_mul_modeq_one ((u⁻¹ : units (zmod (n+1))) : zmod (n+1)).val,
have := units.ext_iff.1 (mul_right_inv u),
rw [units.coe_one] at this,
rw [← eq_iff_modeq_nat, nat.cast_one, ← this], clear this,
rw [← nat_cast_zmod_val ((u * u⁻¹ : units (zmod (n+1))) : zmod (n+1))],
rw [units.coe_mul, val_mul, nat_cast_mod],
end
@[simp] lemma inv_coe_unit {n : ℕ} (u : (zmod n)ˣ) :
(u : zmod n)⁻¹ = (u⁻¹ : (zmod n)ˣ) :=
begin
have := congr_arg (coe : ℕ → zmod n) (val_coe_unit_coprime u),
rw [← mul_inv_eq_gcd, nat.cast_one] at this,
let u' : (zmod n)ˣ := ⟨u, (u : zmod n)⁻¹, this, by rwa mul_comm⟩,
have h : u = u', { apply units.ext, refl },
rw h,
refl
end
lemma mul_inv_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) :
a * a⁻¹ = 1 :=
begin
rcases h with ⟨u, rfl⟩,
rw [inv_coe_unit, u.mul_inv],
end
lemma inv_mul_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) :
a⁻¹ * a = 1 :=
by rw [mul_comm, mul_inv_of_unit a h]
/-- Equivalence between the units of `zmod n` and
the subtype of terms `x : zmod n` for which `x.val` is comprime to `n` -/
def units_equiv_coprime {n : ℕ} [fact (0 < n)] :
(zmod n)ˣ ≃ {x : zmod n // nat.coprime x.val n} :=
{ to_fun := λ x, ⟨x, val_coe_unit_coprime x⟩,
inv_fun := λ x, unit_of_coprime x.1.val x.2,
left_inv := λ ⟨_, _, _, _⟩, units.ext (nat_cast_zmod_val _),
right_inv := λ ⟨_, _⟩, by simp }
/-- The **Chinese remainder theorem**. For a pair of coprime natural numbers, `m` and `n`,
the rings `zmod (m * n)` and `zmod m × zmod n` are isomorphic.
See `ideal.quotient_inf_ring_equiv_pi_quotient` for the Chinese remainder theorem for ideals in any
ring.
-/
def chinese_remainder {m n : ℕ} (h : m.coprime n) :
zmod (m * n) ≃+* zmod m × zmod n :=
let to_fun : zmod (m * n) → zmod m × zmod n :=
zmod.cast_hom (show m.lcm n ∣ m * n, by simp [nat.lcm_dvd_iff]) (zmod m × zmod n) in
let inv_fun : zmod m × zmod n → zmod (m * n) :=
λ x, if m * n = 0
then if m = 1
then ring_hom.snd _ _ x
else ring_hom.fst _ _ x
else nat.chinese_remainder h x.1.val x.2.val in
have inv : function.left_inverse inv_fun to_fun ∧ function.right_inverse inv_fun to_fun :=
if hmn0 : m * n = 0
then begin
rcases h.eq_of_mul_eq_zero hmn0 with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩;
simp [inv_fun, to_fun, function.left_inverse, function.right_inverse,
ring_hom.eq_int_cast, prod.ext_iff]
end
else
begin
haveI : fact (0 < (m * n)) := ⟨nat.pos_of_ne_zero hmn0⟩,
haveI : fact (0 < m) := ⟨nat.pos_of_ne_zero $ left_ne_zero_of_mul hmn0⟩,
haveI : fact (0 < n) := ⟨nat.pos_of_ne_zero $ right_ne_zero_of_mul hmn0⟩,
have left_inv : function.left_inverse inv_fun to_fun,
{ intro x,
dsimp only [dvd_mul_left, dvd_mul_right, zmod.cast_hom_apply, coe_coe, inv_fun, to_fun],
conv_rhs { rw ← zmod.nat_cast_zmod_val x },
rw [if_neg hmn0, zmod.eq_iff_modeq_nat, ← nat.modeq_and_modeq_iff_modeq_mul h,
prod.fst_zmod_cast, prod.snd_zmod_cast],
refine
⟨(nat.chinese_remainder h (x : zmod m).val (x : zmod n).val).2.left.trans _,
(nat.chinese_remainder h (x : zmod m).val (x : zmod n).val).2.right.trans _⟩,
{ rw [← zmod.eq_iff_modeq_nat, zmod.nat_cast_zmod_val, zmod.nat_cast_val] },
{ rw [← zmod.eq_iff_modeq_nat, zmod.nat_cast_zmod_val, zmod.nat_cast_val] } },
exact ⟨left_inv, fintype.right_inverse_of_left_inverse_of_card_le left_inv (by simp)⟩,
end,
{ to_fun := to_fun,
inv_fun := inv_fun,
map_mul' := ring_hom.map_mul _,
map_add' := ring_hom.map_add _,
left_inv := inv.1,
right_inv := inv.2 }
instance subsingleton_units : subsingleton ((zmod 2)ˣ) :=
⟨λ x y, begin
ext1,
cases x with x xi hx1 hx2,
cases y with y yi hy1 hy2,
revert hx1 hx2 hy1 hy2,
fin_cases x; fin_cases y; simp
end⟩
lemma le_div_two_iff_lt_neg (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)]
{x : zmod n} (hx0 : x ≠ 0) : x.val ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).val :=
begin
haveI npos : fact (0 < n) := ⟨by
{ apply (nat.eq_zero_or_pos n).resolve_left,
unfreezingI { rintro rfl },
simpa [fact_iff] using hn, }⟩,
have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul
((lt_mul_iff_one_lt_left npos.1).2 dec_trivial),
have hn2' : (n : ℕ) - n / 2 = n / 2 + 1,
{ conv {to_lhs, congr, rw [← nat.succ_sub_one n, nat.succ_sub npos.1]},
rw [← nat.two_mul_odd_div_two hn.1, two_mul, ← nat.succ_add, add_tsub_cancel_right], },
have hxn : (n : ℕ) - x.val < n,
{ rw [tsub_lt_iff_tsub_lt x.val_le le_rfl, tsub_self],
rw ← zmod.nat_cast_zmod_val x at hx0,
exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0) },
by conv {to_rhs, rw [← nat.succ_le_iff, nat.succ_eq_add_one, ← hn2', ← zero_add (- x),
← zmod.nat_cast_self, ← sub_eq_add_neg, ← zmod.nat_cast_zmod_val x,
← nat.cast_sub x.val_le,
zmod.val_nat_cast, nat.mod_eq_of_lt hxn, tsub_le_tsub_iff_left x.val_le] }
end
lemma ne_neg_self (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {a : zmod n} (ha : a ≠ 0) : a ≠ -a :=
λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg n ha,
by rwa [← h, ← not_lt, not_iff_self] at this
lemma neg_one_ne_one {n : ℕ} [fact (2 < n)] :
(-1 : zmod n) ≠ 1 :=
char_p.neg_one_ne_one (zmod n) n
@[simp] lemma neg_eq_self_mod_two (a : zmod 2) : -a = a :=
by fin_cases a; ext; simp [fin.coe_neg, int.nat_mod]; norm_num
@[simp] lemma nat_abs_mod_two (a : ℤ) : (a.nat_abs : zmod 2) = a :=
begin
cases a,
{ simp only [int.nat_abs_of_nat, int.cast_coe_nat, int.of_nat_eq_coe] },
{ simp only [neg_eq_self_mod_two, nat.cast_succ, int.nat_abs, int.cast_neg_succ_of_nat] }
end
@[simp] lemma val_eq_zero : ∀ {n : ℕ} (a : zmod n), a.val = 0 ↔ a = 0
| 0 a := int.nat_abs_eq_zero
| (n+1) a := by { rw fin.ext_iff, exact iff.rfl }
lemma val_cast_of_lt {n : ℕ} {a : ℕ} (h : a < n) : (a : zmod n).val = a :=
by rw [val_nat_cast, nat.mod_eq_of_lt h]
lemma neg_val' {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = (n - a.val) % n :=
calc (-a).val = val (-a) % n : by rw nat.mod_eq_of_lt ((-a).val_lt)
... = (n - val a) % n : nat.modeq.add_right_cancel' _ (by rw [nat.modeq, ←val_add,
add_left_neg, tsub_add_cancel_of_le a.val_le, nat.mod_self, val_zero])
lemma neg_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = if a = 0 then 0 else n - a.val :=
begin
rw neg_val',
by_cases h : a = 0, { rw [if_pos h, h, val_zero, tsub_zero, nat.mod_self] },
rw if_neg h,
apply nat.mod_eq_of_lt,
apply nat.sub_lt (fact.out (0 < n)),
contrapose! h,
rwa [nat.le_zero_iff, val_eq_zero] at h,
end
/-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`,
The result will be in the interval `(-n/2, n/2]`. -/
def val_min_abs : Π {n : ℕ}, zmod n → ℤ
| 0 x := x
| n@(_+1) x := if x.val ≤ n / 2 then x.val else (x.val : ℤ) - n
@[simp] lemma val_min_abs_def_zero (x : zmod 0) : val_min_abs x = x := rfl
lemma val_min_abs_def_pos {n : ℕ} [fact (0 < n)] (x : zmod n) :
val_min_abs x = if x.val ≤ n / 2 then x.val else x.val - n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out (0 < 0)) },
{ refl }
end
@[simp] lemma coe_val_min_abs : ∀ {n : ℕ} (x : zmod n), (x.val_min_abs : zmod n) = x
| 0 x := int.cast_id x
| k@(n+1) x :=
begin
rw val_min_abs_def_pos,
split_ifs,
{ rw [int.cast_coe_nat, nat_cast_zmod_val] },
{ rw [int.cast_sub, int.cast_coe_nat, nat_cast_zmod_val, int.cast_coe_nat, nat_cast_self,
sub_zero] }
end
lemma nat_abs_val_min_abs_le {n : ℕ} [fact (0 < n)] (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 :=
begin
rw zmod.val_min_abs_def_pos,
split_ifs with h, { exact h },
have : (x.val - n : ℤ) ≤ 0,
{ rw [sub_nonpos, int.coe_nat_le], exact x.val_le, },
rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub],
conv_lhs { congr, rw [← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul,
int.coe_nat_bit0, int.coe_nat_one] },
suffices : ((n % 2 : ℕ) + (n / 2) : ℤ) ≤ (val x),
{ rw ← sub_nonneg at this ⊢, apply le_trans this (le_of_eq _), ring_nf, ring },
norm_cast,
calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 :
nat.add_le_add_right (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) _
... ≤ x.val :
by { rw add_comm, exact nat.succ_le_of_lt (lt_of_not_ge h) }
end
@[simp] lemma val_min_abs_zero : ∀ n, (0 : zmod n).val_min_abs = 0
| 0 := by simp only [val_min_abs_def_zero]
| (n+1) := by simp only [val_min_abs_def_pos, if_true, int.coe_nat_zero, zero_le, val_zero]
@[simp] lemma val_min_abs_eq_zero {n : ℕ} (x : zmod n) :
x.val_min_abs = 0 ↔ x = 0 :=
begin
cases n, { simp },
split,
{ simp only [val_min_abs_def_pos, int.coe_nat_succ],
split_ifs with h h; assume h0,
{ apply val_injective, rwa [int.coe_nat_eq_zero] at h0, },
{ apply absurd h0, rw sub_eq_zero, apply ne_of_lt, exact_mod_cast x.val_lt } },
{ rintro rfl, rw val_min_abs_zero }
end
lemma nat_cast_nat_abs_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) :
(a.val_min_abs.nat_abs : zmod n) = if a.val ≤ (n : ℕ) / 2 then a else -a :=
begin
have : (a.val : ℤ) - n ≤ 0,
by { erw [sub_nonpos, int.coe_nat_le], exact a.val_le, },
rw [zmod.val_min_abs_def_pos],
split_ifs,
{ rw [int.nat_abs_of_nat, nat_cast_zmod_val] },
{ rw [← int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this, int.cast_neg, int.cast_sub],
rw [int.cast_coe_nat, int.cast_coe_nat, nat_cast_self, sub_zero, nat_cast_zmod_val], }
end
@[simp] lemma nat_abs_val_min_abs_neg {n : ℕ} (a : zmod n) :
(-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs :=
begin
cases n, { simp only [int.nat_abs_neg, val_min_abs_def_zero], },
by_cases ha0 : a = 0, { rw [ha0, neg_zero] },
by_cases haa : -a = a, { rw [haa] },
suffices hpa : (n+1 : ℕ) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val,
{ rw [val_min_abs_def_pos, val_min_abs_def_pos],
rw ← not_le at hpa,
simp only [if_neg ha0, neg_val, hpa, int.coe_nat_sub a.val_le],
split_ifs,
all_goals { rw [← int.nat_abs_neg], congr' 1, ring } },
suffices : (((n+1 : ℕ) % 2) + 2 * ((n + 1) / 2)) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val,
by rwa [nat.mod_add_div] at this,
suffices : (n + 1) % 2 + (n + 1) / 2 ≤ val a ↔ (n + 1) / 2 < val a,
by rw [tsub_le_iff_tsub_le, two_mul, ← add_assoc, add_tsub_cancel_right, this],
cases (n + 1 : ℕ).mod_two_eq_zero_or_one with hn0 hn1,
{ split,
{ assume h,
apply lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h),
contrapose! haa,
rw [← zmod.nat_cast_zmod_val a, ← haa, neg_eq_iff_add_eq_zero, ← nat.cast_add],
rw [char_p.cast_eq_zero_iff (zmod (n+1)) (n+1)],
rw [← two_mul, ← zero_add (2 * _), ← hn0, nat.mod_add_div] },
{ rw [hn0, zero_add], exact le_of_lt } },
{ rw [hn1, add_comm, nat.succ_le_iff] }
end
lemma val_eq_ite_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) :
(a.val : ℤ) = a.val_min_abs + if a.val ≤ n / 2 then 0 else n :=
by { rw [zmod.val_min_abs_def_pos], split_ifs; simp only [add_zero, sub_add_cancel] }
lemma prime_ne_zero (p q : ℕ) [hp : fact p.prime] [hq : fact q.prime] (hpq : p ≠ q) :
(q : zmod p) ≠ 0 :=
by rwa [← nat.cast_zero, ne.def, eq_iff_modeq_nat, nat.modeq_zero_iff_dvd,
← hp.1.coprime_iff_not_dvd, nat.coprime_primes hp.1 hq.1]
end zmod
namespace zmod
variables (p : ℕ) [fact p.prime]
private lemma mul_inv_cancel_aux (a : zmod p) (h : a ≠ 0) : a * a⁻¹ = 1 :=
begin
obtain ⟨k, rfl⟩ := nat_cast_zmod_surjective a,
apply coe_mul_inv_eq_one,
apply nat.coprime.symm,
rwa [nat.prime.coprime_iff_not_dvd (fact.out p.prime), ← char_p.cast_eq_zero_iff (zmod p)]
end
/-- Field structure on `zmod p` if `p` is prime. -/
instance : field (zmod p) :=
{ mul_inv_cancel := mul_inv_cancel_aux p,
inv_zero := inv_zero p,
.. zmod.comm_ring p,
.. zmod.has_inv p,
.. zmod.nontrivial p }
/-- `zmod p` is an integral domain when `p` is prime. -/
instance (p : ℕ) [hp : fact p.prime] : is_domain (zmod p) :=
begin
-- We need `cases p` here in order to resolve which `comm_ring` instance is being used.
unfreezingI { cases p, { exact (nat.not_prime_zero hp.out).elim }, },
exact @field.is_domain (zmod _) (zmod.field _)
end
end zmod
lemma ring_hom.ext_zmod {n : ℕ} {R : Type*} [semiring R] (f g : (zmod n) →+* R) : f = g :=
begin
ext a,
obtain ⟨k, rfl⟩ := zmod.int_cast_surjective a,
let φ : ℤ →+* R := f.comp (int.cast_ring_hom (zmod n)),
let ψ : ℤ →+* R := g.comp (int.cast_ring_hom (zmod n)),
show φ k = ψ k,
rw φ.ext_int ψ,
end
namespace zmod
variables {n : ℕ} {R : Type*}
instance subsingleton_ring_hom [semiring R] : subsingleton ((zmod n) →+* R) :=
⟨ring_hom.ext_zmod⟩
instance subsingleton_ring_equiv [semiring R] : subsingleton (zmod n ≃+* R) :=
⟨λ f g, by { rw ring_equiv.coe_ring_hom_inj_iff, apply ring_hom.ext_zmod _ _ }⟩
@[simp] lemma ring_hom_map_cast [ring R] (f : R →+* (zmod n)) (k : zmod n) :
f k = k :=
by { cases n; simp }
lemma ring_hom_right_inverse [ring R] (f : R →+* (zmod n)) :
function.right_inverse (coe : zmod n → R) f :=
ring_hom_map_cast f
lemma ring_hom_surjective [ring R] (f : R →+* (zmod n)) : function.surjective f :=
(ring_hom_right_inverse f).surjective
lemma ring_hom_eq_of_ker_eq [comm_ring R] (f g : R →+* (zmod n))
(h : f.ker = g.ker) : f = g :=
begin
have := f.lift_of_right_inverse_comp _ (zmod.ring_hom_right_inverse f) ⟨g, le_of_eq h⟩,
rw subtype.coe_mk at this,
rw [←this, ring_hom.ext_zmod (f.lift_of_right_inverse _ _ _) (ring_hom.id _), ring_hom.id_comp],
end
section lift
variables (n) {A : Type*} [add_group A]
/-- The map from `zmod n` induced by `f : ℤ →+ A` that maps `n` to `0`. -/
@[simps]
def lift : {f : ℤ →+ A // f n = 0} ≃ (zmod n →+ A) :=
(equiv.subtype_equiv_right $ begin
intro f,
rw ker_int_cast_add_hom,
split,
{ rintro hf _ ⟨x, rfl⟩,
simp only [f.map_zsmul, zsmul_zero, f.mem_ker, hf] },
{ intro h,
refine h (add_subgroup.mem_zmultiples _) }
end).trans $ ((int.cast_add_hom (zmod n)).lift_of_right_inverse coe int_cast_zmod_cast)
variables (f : {f : ℤ →+ A // f n = 0})
@[simp] lemma lift_coe (x : ℤ) :
lift n f (x : zmod n) = f x :=
add_monoid_hom.lift_of_right_inverse_comp_apply _ _ _ _ _
lemma lift_cast_add_hom (x : ℤ) :
lift n f (int.cast_add_hom (zmod n) x) = f x :=
add_monoid_hom.lift_of_right_inverse_comp_apply _ _ _ _ _
@[simp] lemma lift_comp_coe : zmod.lift n f ∘ coe = f :=
funext $ lift_coe _ _
@[simp] lemma lift_comp_cast_add_hom :
(zmod.lift n f).comp (int.cast_add_hom (zmod n)) = f :=
add_monoid_hom.ext $ lift_cast_add_hom _ _
end lift
end zmod
|
1a00e6816eb4fb30fdcbbcc51f0af06ca925e873 | a46270e2f76a375564f3b3e9c1bf7b635edc1f2c | /5.8.1-3.7.classical.lean | 1f0ce1680831301d27e3a39bde08538fecb2a149 | [
"CC0-1.0"
] | permissive | wudcscheme/lean-exercise | 88ea2506714eac343de2a294d1132ee8ee6d3a20 | 5b23b9be3d361fff5e981d5be3a0a1175504b9f6 | refs/heads/master | 1,678,958,930,293 | 1,583,197,205,000 | 1,583,197,205,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,471 | lean | open classical
variables p q r s : Prop
example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := begin
intro h, apply by_cases, {
assume hp: p,
cases (h hp),
left, intro, assumption,
right, intro, assumption,
}, {
assume hnp: ¬ p,
exact (or.inl $ λ hp:p, absurd hp hnp)
}
end
example : ¬(p ∧ q) → ¬p ∨ ¬q := begin
intro h, apply by_cases, {
assume hp: p,
right, intro hq, exact (h ⟨hp, hq⟩)
}, {
assume hnp: ¬ p, left, assumption
}
end
lemma dne {p: Prop} (h: ¬ ¬ p) : p :=
or.elim (em p)
(assume hp: p, hp)
(assume hnp: ¬ p, absurd hnp h)
example : ¬(p → q) → p ∧ ¬q := begin
intro h, apply by_contradiction, {
intro hc,
have hcc: p -> ¬ q -> false, from λ x y, hc ⟨x, y⟩,
have: p -> q, {
intro hp,
have: ¬ ¬ q, from hcc hp, apply dne this
}, contradiction
}
end
example : (p → q) → (¬p ∨ q) := begin
intro h, apply by_cases, {
assume: p, right, exact (h this)
}, {
assume: ¬ p, left, assumption
}
end
example : (¬q → ¬p) → (p → q) := begin
intro h, intro hp, apply by_cases, {
assume: q, assumption
}, {
assume: ¬ q, have: ¬ p, from h this, contradiction
}
end
example : p ∨ ¬p := begin
apply em p
end
example : (((p → q) → p) → p) := begin
intro h, apply by_contradiction, {
intro hnp,
have: p -> q, from λ hp, absurd hp hnp,
have: p, from h this, contradiction
}
end
|
c95e7215608d8779266b7c2a3be30c3d96523240 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/1594_comment_issue.lean | 87d9b9c9b8489880ec2285991410f9e03c0df435 | [
"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 | 243 | lean | variables (A : Type) (f : A → ℕ → A) [has_mul A]
open nat
theorem thm' (a : A) : ∀ m n, f a m * f a n = f a n * f a m
| 0 n := sorry
| m 0 := sorry
| (succ m) (succ n) :=
have h : f a m * f a n = f a n * f a m, from thm' _ _,
sorry
|
9c266cb6007761f17615658d36b84f538225c06d | bce603343785d07c32cb8b35950aba0b4d9415ae | /lean4/Crypto.lean | 2d13df12191d91496dfc18044181bbddfe3a0ab1 | [] | no_license | fpvandoorn/cryptomorphism | db00cf0b12c8fd561a6200eee6a6ff2a023f1228 | d486419ecced54de3db759dae81110be44b7c28b | refs/heads/master | 1,693,198,883,854 | 1,636,562,038,000 | 1,636,562,038,000 | 363,219,330 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 75 | lean | import Crypto.Structure
def main : IO Unit :=
IO.println "Hello, world!" |
0107a105ca61b3b6e72e348683f423254dbee9e9 | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/number_theory/padics/padic_norm.lean | dca3e8b178dc520332bc6339e5e3500ee487c3d0 | [
"Apache-2.0"
] | permissive | jumpy4/mathlib | d3829e75173012833e9f15ac16e481e17596de0f | af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13 | refs/heads/master | 1,693,508,842,818 | 1,636,203,271,000 | 1,636,203,271,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 27,970 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
-/
import algebra.order.absolute_value
import algebra.field_power
import ring_theory.int.basic
import tactic.basic
import tactic.ring_exp
/-!
# p-adic norm
This file defines the p-adic valuation and the p-adic norm on ℚ.
The p-adic valuation on ℚ is the difference of the multiplicities of `p` in the numerator and
denominator of `q`. This function obeys the standard properties of a valuation, with the appropriate
assumptions on p.
The valuation induces a norm on ℚ. This norm is a nonarchimedean absolute value.
It takes values in {0} ∪ {1/p^k | k ∈ ℤ}.
## Notations
This file uses the local notation `/.` for `rat.mk`.
## Implementation notes
Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically
by taking `[fact (prime p)]` as a type class argument.
## References
* [F. Q. Gouêva, *p-adic numbers*][gouvea1997]
* [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]
* <https://en.wikipedia.org/wiki/P-adic_number>
## Tags
p-adic, p adic, padic, norm, valuation
-/
universe u
open nat
open_locale rat
open multiplicity
/--
For `p ≠ 1`, the p-adic valuation of an integer `z ≠ 0` is the largest natural number `n` such that
p^n divides z.
`padic_val_rat` defines the valuation of a rational `q` to be the valuation of `q.num` minus the
valuation of `q.denom`.
If `q = 0` or `p = 1`, then `padic_val_rat p q` defaults to 0.
-/
def padic_val_rat (p : ℕ) (q : ℚ) : ℤ :=
if h : q ≠ 0 ∧ p ≠ 1
then (multiplicity (p : ℤ) q.num).get
(multiplicity.finite_int_iff.2 ⟨h.2, rat.num_ne_zero_of_ne_zero h.1⟩) -
(multiplicity (p : ℤ) q.denom).get
(multiplicity.finite_int_iff.2 ⟨h.2, by exact_mod_cast rat.denom_ne_zero _⟩)
else 0
/--
A simplification of the definition of `padic_val_rat p q` when `q ≠ 0` and `p` is prime.
-/
lemma padic_val_rat_def (p : ℕ) [hp : fact p.prime] {q : ℚ} (hq : q ≠ 0) : padic_val_rat p q =
(multiplicity (p : ℤ) q.num).get (finite_int_iff.2 ⟨hp.1.ne_one, rat.num_ne_zero_of_ne_zero hq⟩) -
(multiplicity (p : ℤ) q.denom).get
(finite_int_iff.2 ⟨hp.1.ne_one, by exact_mod_cast rat.denom_ne_zero _⟩) :=
dif_pos ⟨hq, hp.1.ne_one⟩
namespace padic_val_rat
open multiplicity
variables {p : ℕ}
/--
`padic_val_rat p q` is symmetric in `q`.
-/
@[simp] protected lemma neg (q : ℚ) : padic_val_rat p (-q) = padic_val_rat p q :=
begin
unfold padic_val_rat,
split_ifs,
{ simp [-add_comm]; refl },
{ exfalso, simp * at * },
{ exfalso, simp * at * },
{ refl }
end
/--
`padic_val_rat p 1` is 0 for any `p`.
-/
@[simp] protected lemma one : padic_val_rat p 1 = 0 :=
by unfold padic_val_rat; split_ifs; simp *
/--
For `p ≠ 0, p ≠ 1, `padic_val_rat p p` is 1.
-/
@[simp] lemma padic_val_rat_self (hp : 1 < p) : padic_val_rat p p = 1 :=
by unfold padic_val_rat; split_ifs; simp [*, nat.one_lt_iff_ne_zero_and_ne_one] at *
/--
The p-adic value of an integer `z ≠ 0` is the multiplicity of `p` in `z`.
-/
lemma padic_val_rat_of_int (z : ℤ) (hp : p ≠ 1) (hz : z ≠ 0) :
padic_val_rat p (z : ℚ) = (multiplicity (p : ℤ) z).get
(finite_int_iff.2 ⟨hp, hz⟩) :=
by rw [padic_val_rat, dif_pos]; simp *; refl
end padic_val_rat
/--
A convenience function for the case of `padic_val_rat` when both inputs are natural numbers.
-/
def padic_val_nat (p : ℕ) (n : ℕ) : ℕ :=
int.to_nat (padic_val_rat p n)
section padic_val_nat
/--
`padic_val_nat` is defined as an `int.to_nat` cast;
this lemma ensures that the cast is well-behaved.
-/
lemma zero_le_padic_val_rat_of_nat (p n : ℕ) : 0 ≤ padic_val_rat p n :=
begin
unfold padic_val_rat,
split_ifs,
{ simp, },
{ trivial, },
end
/--
`padic_val_rat` coincides with `padic_val_nat`.
-/
@[simp, norm_cast] lemma padic_val_rat_of_nat (p n : ℕ) :
↑(padic_val_nat p n) = padic_val_rat p n :=
begin
unfold padic_val_nat,
rw int.to_nat_of_nonneg (zero_le_padic_val_rat_of_nat p n),
end
/--
A simplification of `padic_val_nat` when one input is prime, by analogy with `padic_val_rat_def`.
-/
lemma padic_val_nat_def {p : ℕ} [hp : fact p.prime] {n : ℕ} (hn : n ≠ 0) :
padic_val_nat p n =
(multiplicity p n).get
(multiplicity.finite_nat_iff.2 ⟨nat.prime.ne_one hp.1, bot_lt_iff_ne_bot.mpr hn⟩) :=
begin
have n_nonzero : (n : ℚ) ≠ 0, by simpa only [cast_eq_zero, ne.def],
-- Infinite loop with @simp padic_val_rat_of_nat unless we restrict the available lemmas here,
-- hence the very long list
simpa only
[ int.coe_nat_multiplicity p n, rat.coe_nat_denom n, (padic_val_rat_of_nat p n).symm,
int.coe_nat_zero, int.coe_nat_inj', sub_zero, get_one_right, int.coe_nat_succ, zero_add,
rat.coe_nat_num ]
using padic_val_rat_def p n_nonzero,
end
lemma one_le_padic_val_nat_of_dvd
{n p : nat} [prime : fact p.prime] (nonzero : n ≠ 0) (div : p ∣ n) :
1 ≤ padic_val_nat p n :=
begin
rw @padic_val_nat_def _ prime _ nonzero,
let one_le_mul : _ ≤ multiplicity p n :=
@multiplicity.le_multiplicity_of_pow_dvd _ _ _ p n 1 (begin norm_num, exact div end),
simp only [nat.cast_one] at one_le_mul,
rcases one_le_mul with ⟨_, q⟩,
dsimp at q,
solve_by_elim,
end
@[simp]
lemma padic_val_nat_zero (m : nat) : padic_val_nat m 0 = 0 := by simpa
@[simp]
lemma padic_val_nat_one (m : nat) : padic_val_nat m 1 = 0 := by simp [padic_val_nat]
end padic_val_nat
namespace padic_val_rat
open multiplicity
variables (p : ℕ) [p_prime : fact p.prime]
include p_prime
/--
The multiplicity of `p : ℕ` in `a : ℤ` is finite exactly when `a ≠ 0`.
-/
lemma finite_int_prime_iff {p : ℕ} [p_prime : fact p.prime] {a : ℤ} : finite (p : ℤ) a ↔ a ≠ 0 :=
by simp [finite_int_iff, ne.symm (ne_of_lt (p_prime.1.one_lt))]
/--
A rewrite lemma for `padic_val_rat p q` when `q` is expressed in terms of `rat.mk`.
-/
protected lemma defn {q : ℚ} {n d : ℤ} (hqz : q ≠ 0) (qdf : q = n /. d) :
padic_val_rat p q = (multiplicity (p : ℤ) n).get (finite_int_iff.2
⟨ne.symm $ ne_of_lt p_prime.1.one_lt, λ hn, by simp * at *⟩) -
(multiplicity (p : ℤ) d).get (finite_int_iff.2 ⟨ne.symm $ ne_of_lt p_prime.1.one_lt,
λ hd, by simp * at *⟩) :=
have hn : n ≠ 0, from rat.mk_num_ne_zero_of_ne_zero hqz qdf,
have hd : d ≠ 0, from rat.mk_denom_ne_zero_of_ne_zero hqz qdf,
let ⟨c, hc1, hc2⟩ := rat.num_denom_mk hn hd qdf in
by rw [padic_val_rat, dif_pos];
simp [hc1, hc2, multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime.1),
(ne.symm (ne_of_lt p_prime.1.one_lt)), hqz]
/--
A rewrite lemma for `padic_val_rat p (q * r)` with conditions `q ≠ 0`, `r ≠ 0`.
-/
protected lemma mul {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) :
padic_val_rat p (q * r) = padic_val_rat p q + padic_val_rat p r :=
have q*r = (q.num * r.num) /. (↑q.denom * ↑r.denom), by rw_mod_cast rat.mul_num_denom,
have hq' : q.num /. q.denom ≠ 0, by rw rat.num_denom; exact hq,
have hr' : r.num /. r.denom ≠ 0, by rw rat.num_denom; exact hr,
have hp' : _root_.prime (p : ℤ), from nat.prime_iff_prime_int.1 p_prime.1,
begin
rw [padic_val_rat.defn p (mul_ne_zero hq hr) this],
conv_rhs { rw [←(@rat.num_denom q), padic_val_rat.defn p hq',
←(@rat.num_denom r), padic_val_rat.defn p hr'] },
rw [multiplicity.mul' hp', multiplicity.mul' hp']; simp [add_comm, add_left_comm, sub_eq_add_neg]
end
/--
A rewrite lemma for `padic_val_rat p (q^k)` with condition `q ≠ 0`.
-/
protected lemma pow {q : ℚ} (hq : q ≠ 0) {k : ℕ} :
padic_val_rat p (q ^ k) = k * padic_val_rat p q :=
by induction k; simp [*, padic_val_rat.mul _ hq (pow_ne_zero _ hq),
pow_succ, add_mul, add_comm]
/--
A rewrite lemma for `padic_val_rat p (q⁻¹)` with condition `q ≠ 0`.
-/
protected lemma inv {q : ℚ} (hq : q ≠ 0) :
padic_val_rat p (q⁻¹) = -padic_val_rat p q :=
by rw [eq_neg_iff_add_eq_zero, ← padic_val_rat.mul p (inv_ne_zero hq) hq,
inv_mul_cancel hq, padic_val_rat.one]
/--
A rewrite lemma for `padic_val_rat p (q / r)` with conditions `q ≠ 0`, `r ≠ 0`.
-/
protected lemma div {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) :
padic_val_rat p (q / r) = padic_val_rat p q - padic_val_rat p r :=
by rw [div_eq_mul_inv, padic_val_rat.mul p hq (inv_ne_zero hr),
padic_val_rat.inv p hr, sub_eq_add_neg]
/--
A condition for `padic_val_rat p (n₁ / d₁) ≤ padic_val_rat p (n₂ / d₂),
in terms of divisibility by `p^n`.
-/
lemma padic_val_rat_le_padic_val_rat_iff {n₁ n₂ d₁ d₂ : ℤ}
(hn₁ : n₁ ≠ 0) (hn₂ : n₂ ≠ 0) (hd₁ : d₁ ≠ 0) (hd₂ : d₂ ≠ 0) :
padic_val_rat p (n₁ /. d₁) ≤ padic_val_rat p (n₂ /. d₂) ↔
∀ (n : ℕ), ↑p ^ n ∣ n₁ * d₂ → ↑p ^ n ∣ n₂ * d₁ :=
have hf1 : finite (p : ℤ) (n₁ * d₂),
from finite_int_prime_iff.2 (mul_ne_zero hn₁ hd₂),
have hf2 : finite (p : ℤ) (n₂ * d₁),
from finite_int_prime_iff.2 (mul_ne_zero hn₂ hd₁),
by conv {
to_lhs,
rw [padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₁ hd₁) rfl,
padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₂ hd₂) rfl,
sub_le_iff_le_add',
← add_sub_assoc,
le_sub_iff_add_le],
norm_cast,
rw [← multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime.1) hf1, add_comm,
← multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime.1) hf2,
enat.get_le_get, multiplicity_le_multiplicity_iff] }
/--
Sufficient conditions to show that the p-adic valuation of `q` is less than or equal to the
p-adic vlauation of `q + r`.
-/
theorem le_padic_val_rat_add_of_le {q r : ℚ}
(hq : q ≠ 0) (hr : r ≠ 0) (hqr : q + r ≠ 0)
(h : padic_val_rat p q ≤ padic_val_rat p r) :
padic_val_rat p q ≤ padic_val_rat p (q + r) :=
have hqn : q.num ≠ 0, from rat.num_ne_zero_of_ne_zero hq,
have hqd : (q.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _,
have hrn : r.num ≠ 0, from rat.num_ne_zero_of_ne_zero hr,
have hrd : (r.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _,
have hqreq : q + r = (((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ)),
from rat.add_num_denom _ _,
have hqrd : q.num * ↑(r.denom) + ↑(q.denom) * r.num ≠ 0,
from rat.mk_num_ne_zero_of_ne_zero hqr hqreq,
begin
conv_lhs { rw ←(@rat.num_denom q) },
rw [hqreq, padic_val_rat_le_padic_val_rat_iff p hqn hqrd hqd (mul_ne_zero hqd hrd),
← multiplicity_le_multiplicity_iff, mul_left_comm,
multiplicity.mul (nat.prime_iff_prime_int.1 p_prime.1), add_mul],
rw [←(@rat.num_denom q), ←(@rat.num_denom r),
padic_val_rat_le_padic_val_rat_iff p hqn hrn hqd hrd, ← multiplicity_le_multiplicity_iff] at h,
calc _ ≤ min (multiplicity ↑p (q.num * ↑(r.denom) * ↑(q.denom)))
(multiplicity ↑p (↑(q.denom) * r.num * ↑(q.denom))) : (le_min
(by rw [@multiplicity.mul _ _ _ _ (_ * _) _ (nat.prime_iff_prime_int.1 p_prime.1), add_comm])
(by rw [mul_assoc, @multiplicity.mul _ _ _ _ (q.denom : ℤ)
(_ * _) (nat.prime_iff_prime_int.1 p_prime.1)];
exact add_le_add_left h _))
... ≤ _ : min_le_multiplicity_add
end
/--
The minimum of the valuations of `q` and `r` is less than or equal to the valuation of `q + r`.
-/
theorem min_le_padic_val_rat_add {q r : ℚ}
(hq : q ≠ 0) (hr : r ≠ 0) (hqr : q + r ≠ 0) :
min (padic_val_rat p q) (padic_val_rat p r) ≤ padic_val_rat p (q + r) :=
(le_total (padic_val_rat p q) (padic_val_rat p r)).elim
(λ h, by rw [min_eq_left h]; exact le_padic_val_rat_add_of_le _ hq hr hqr h)
(λ h, by rw [min_eq_right h, add_comm]; exact le_padic_val_rat_add_of_le _ hr hq
(by rwa add_comm) h)
open_locale big_operators
/-- A finite sum of rationals with positive p-adic valuation has positive p-adic valuation
(if the sum is non-zero). -/
theorem sum_pos_of_pos {n : ℕ} {F : ℕ → ℚ}
(hF : ∀ i, i < n → 0 < padic_val_rat p (F i)) (hn0 : ∑ i in finset.range n, F i ≠ 0) :
0 < padic_val_rat p (∑ i in finset.range n, F i) :=
begin
induction n with d hd,
{ exact false.elim (hn0 rfl) },
{ rw finset.sum_range_succ at hn0 ⊢,
by_cases h : ∑ (x : ℕ) in finset.range d, F x = 0,
{ rw [h, zero_add],
exact hF d (lt_add_one _) },
{ refine lt_of_lt_of_le _ (min_le_padic_val_rat_add p h (λ h1, _) hn0),
{ refine lt_min (hd (λ i hi, _) h) (hF d (lt_add_one _)),
exact hF _ (lt_trans hi (lt_add_one _)) },
{ have h2 := hF d (lt_add_one _),
rw h1 at h2,
exact lt_irrefl _ h2 } } }
end
end padic_val_rat
namespace padic_val_nat
/--
A rewrite lemma for `padic_val_nat p (q * r)` with conditions `q ≠ 0`, `r ≠ 0`.
-/
protected lemma mul (p : ℕ) [p_prime : fact p.prime] {q r : ℕ} (hq : q ≠ 0) (hr : r ≠ 0) :
padic_val_nat p (q * r) = padic_val_nat p q + padic_val_nat p r :=
begin
apply int.coe_nat_inj,
simp only [padic_val_rat_of_nat, nat.cast_mul],
rw padic_val_rat.mul,
norm_cast,
exact cast_ne_zero.mpr hq,
exact cast_ne_zero.mpr hr,
end
/--
Dividing out by a prime factor reduces the padic_val_nat by 1.
-/
protected lemma div {p : ℕ} [p_prime : fact p.prime] {b : ℕ} (dvd : p ∣ b) :
(padic_val_nat p (b / p)) = (padic_val_nat p b) - 1 :=
begin
by_cases b_split : (b = 0),
{ simp [b_split], },
{ have split_frac : padic_val_rat p (b / p) = padic_val_rat p b - padic_val_rat p p :=
padic_val_rat.div p (nat.cast_ne_zero.mpr b_split)
(nat.cast_ne_zero.mpr (nat.prime.ne_zero p_prime.1)),
rw padic_val_rat.padic_val_rat_self (nat.prime.one_lt p_prime.1) at split_frac,
have r : 1 ≤ padic_val_nat p b := one_le_padic_val_nat_of_dvd b_split dvd,
exact_mod_cast split_frac, }
end
/-- A version of `padic_val_rat.pow` for `padic_val_nat` -/
protected lemma pow (p q n : ℕ) [fact p.prime] (hq : q ≠ 0) :
padic_val_nat p (q ^ n) = n * padic_val_nat p q :=
begin
apply @nat.cast_injective ℤ,
push_cast,
exact padic_val_rat.pow _ (cast_ne_zero.mpr hq),
end
end padic_val_nat
section padic_val_nat
/--
If a prime doesn't appear in `n`, `padic_val_nat p n` is `0`.
-/
lemma padic_val_nat_of_not_dvd {p : ℕ} [fact p.prime] {n : ℕ} (not_dvd : ¬(p ∣ n)) :
padic_val_nat p n = 0 :=
begin
by_cases hn : n = 0,
{ subst hn, simp at not_dvd, trivial, },
{ rw padic_val_nat_def hn,
exact (@multiplicity.unique' _ _ _ p n 0 (by simp) (by simpa using not_dvd)).symm,
assumption, },
end
lemma dvd_of_one_le_padic_val_nat {n p : nat} [prime : fact p.prime] (hp : 1 ≤ padic_val_nat p n) :
p ∣ n :=
begin
by_contra h,
rw padic_val_nat_of_not_dvd h at hp,
exact lt_irrefl 0 (lt_of_lt_of_le zero_lt_one hp),
end
lemma pow_padic_val_nat_dvd {p n : ℕ} [fact (nat.prime p)] : p ^ (padic_val_nat p n) ∣ n :=
begin
cases nat.eq_zero_or_pos n with hn hn,
{ rw hn, exact dvd_zero (p ^ padic_val_nat p 0) },
{ rw multiplicity.pow_dvd_iff_le_multiplicity,
apply le_of_eq,
rw padic_val_nat_def (ne_of_gt hn),
{ apply enat.coe_get },
{ apply_instance } }
end
lemma pow_succ_padic_val_nat_not_dvd {p n : ℕ} [hp : fact (nat.prime p)] (hn : 0 < n) :
¬ p ^ (padic_val_nat p n + 1) ∣ n :=
begin
{ rw multiplicity.pow_dvd_iff_le_multiplicity,
rw padic_val_nat_def (ne_of_gt hn),
{ rw [nat.cast_add, enat.coe_get],
simp only [nat.cast_one, not_le],
apply enat.lt_add_one (ne_top_iff_finite.2 (finite_nat_iff.2 ⟨hp.elim.ne_one, hn⟩)) },
{ apply_instance } }
end
lemma padic_val_nat_primes {p q : ℕ} [p_prime : fact p.prime] [q_prime : fact q.prime]
(neq : p ≠ q) : padic_val_nat p q = 0 :=
@padic_val_nat_of_not_dvd p p_prime q $
(not_congr (iff.symm (prime_dvd_prime_iff_eq p_prime.1 q_prime.1))).mp neq
protected lemma padic_val_nat.div' {p : ℕ} [p_prime : fact p.prime] :
∀ {m : ℕ} (cpm : coprime p m) {b : ℕ} (dvd : m ∣ b), padic_val_nat p (b / m) = padic_val_nat p b
| 0 := λ cpm b dvd, by { rw zero_dvd_iff at dvd, rw [dvd, nat.zero_div], }
| (n + 1) :=
λ cpm b dvd,
begin
rcases dvd with ⟨c, rfl⟩,
rw [mul_div_right c (nat.succ_pos _)],by_cases hc : c = 0,
{ rw [hc, mul_zero] },
{ rw padic_val_nat.mul,
{ suffices : ¬ p ∣ (n+1),
{ rw [padic_val_nat_of_not_dvd this, zero_add] },
contrapose! cpm,
exact p_prime.1.dvd_iff_not_coprime.mp cpm },
{ exact nat.succ_ne_zero _ },
{ exact hc } },
end
lemma padic_val_nat_eq_factors_count (p : ℕ) [hp : fact p.prime] :
∀ (n : ℕ), padic_val_nat p n = (factors n).count p
| 0 := by simp
| 1 := by simp
| (m + 2) :=
let n := m + 2 in
let q := min_fac n in
have hq : fact q.prime := ⟨min_fac_prime (show m + 2 ≠ 1, by linarith)⟩,
have wf : n / q < n := nat.div_lt_self (nat.succ_pos _) hq.1.one_lt,
begin
rw factors_add_two,
show padic_val_nat p n = list.count p (q :: (factors (n / q))),
rw [list.count_cons', ← padic_val_nat_eq_factors_count],
split_ifs with h,
have p_dvd_n : p ∣ n,
{ have: q ∣ n := nat.min_fac_dvd n,
cc },
{ rw [←h, padic_val_nat.div],
{ have: 1 ≤ padic_val_nat p n := one_le_padic_val_nat_of_dvd (by linarith) p_dvd_n,
exact (tsub_eq_iff_eq_add_of_le this).mp rfl, },
{ exact p_dvd_n, }, },
{ suffices : p.coprime q,
{ rw [padic_val_nat.div' this (min_fac_dvd n), add_zero], },
rwa nat.coprime_primes hp.1 hq.1, },
end
@[simp] lemma padic_val_nat_self (p : ℕ) [fact p.prime] : padic_val_nat p p = 1 :=
by simp [padic_val_nat_def (fact.out p.prime).ne_zero]
@[simp] lemma padic_val_nat_prime_pow (p n : ℕ) [fact p.prime] : padic_val_nat p (p ^ n) = n :=
by rw [padic_val_nat.pow p _ _ (fact.out p.prime).ne_zero, padic_val_nat_self p, mul_one]
open_locale big_operators
lemma prod_pow_prime_padic_val_nat (n : nat) (hn : n ≠ 0) (m : nat) (pr : n < m) :
∏ p in finset.filter nat.prime (finset.range m), p ^ (padic_val_nat p n) = n :=
begin
rw ← pos_iff_ne_zero at hn,
have H : (factors n : multiset ℕ).prod = n,
{ rw [multiset.coe_prod, prod_factors hn], },
rw finset.prod_multiset_count at H,
conv_rhs { rw ← H, },
refine finset.prod_bij_ne_one (λ p hp hp', p) _ _ _ _,
{ rintro p hp hpn,
rw [finset.mem_filter, finset.mem_range] at hp,
rw [multiset.mem_to_finset, multiset.mem_coe, mem_factors_iff_dvd hn hp.2],
contrapose! hpn,
haveI Hp : fact p.prime := ⟨hp.2⟩,
rw [padic_val_nat_of_not_dvd hpn, pow_zero], },
{ intros, assumption },
{ intros p hp hpn,
rw [multiset.mem_to_finset, multiset.mem_coe] at hp,
haveI Hp : fact p.prime := ⟨prime_of_mem_factors hp⟩,
simp only [exists_prop, ne.def, finset.mem_filter, finset.mem_range],
refine ⟨p, ⟨_, Hp.1⟩, ⟨_, rfl⟩⟩,
{ rw mem_factors_iff_dvd hn Hp.1 at hp, exact lt_of_le_of_lt (le_of_dvd hn hp) pr },
{ rw padic_val_nat_eq_factors_count,
simpa [ne.def, multiset.coe_count] using hpn } },
{ intros p hp hpn,
rw [finset.mem_filter, finset.mem_range] at hp,
haveI Hp : fact p.prime := ⟨hp.2⟩,
rw [padic_val_nat_eq_factors_count, multiset.coe_count] }
end
end padic_val_nat
/--
If `q ≠ 0`, the p-adic norm of a rational `q` is `p ^ (-(padic_val_rat p q))`.
If `q = 0`, the p-adic norm of `q` is 0.
-/
def padic_norm (p : ℕ) (q : ℚ) : ℚ :=
if q = 0 then 0 else (↑p : ℚ) ^ (-(padic_val_rat p q))
namespace padic_norm
section padic_norm
open padic_val_rat
variables (p : ℕ)
/--
Unfolds the definition of the p-adic norm of `q` when `q ≠ 0`.
-/
@[simp] protected lemma eq_zpow_of_nonzero {q : ℚ} (hq : q ≠ 0) :
padic_norm p q = p ^ (-(padic_val_rat p q)) :=
by simp [hq, padic_norm]
/--
The p-adic norm is nonnegative.
-/
protected lemma nonneg (q : ℚ) : 0 ≤ padic_norm p q :=
if hq : q = 0 then by simp [hq, padic_norm]
else
begin
unfold padic_norm; split_ifs,
apply zpow_nonneg,
exact_mod_cast nat.zero_le _
end
/--
The p-adic norm of 0 is 0.
-/
@[simp] protected lemma zero : padic_norm p 0 = 0 := by simp [padic_norm]
/--
The p-adic norm of 1 is 1.
-/
@[simp] protected lemma one : padic_norm p 1 = 1 := by simp [padic_norm]
/--
The p-adic norm of `p` is `1/p` if `p > 1`.
See also `padic_norm.padic_norm_p_of_prime` for a version that assumes `p` is prime.
-/
lemma padic_norm_p {p : ℕ} (hp : 1 < p) : padic_norm p p = 1 / p :=
by simp [padic_norm, (show p ≠ 0, by linarith), padic_val_rat.padic_val_rat_self hp]
/--
The p-adic norm of `p` is `1/p` if `p` is prime.
See also `padic_norm.padic_norm_p` for a version that assumes `1 < p`.
-/
@[simp] lemma padic_norm_p_of_prime (p : ℕ) [fact p.prime] : padic_norm p p = 1 / p :=
padic_norm_p $ nat.prime.one_lt (fact.out _)
/-- The p-adic norm of `q` is `1` if `q` is prime and not equal to `p`. -/
lemma padic_norm_of_prime_of_ne {p q : ℕ} [p_prime : fact p.prime] [q_prime : fact q.prime]
(neq : p ≠ q) : padic_norm p q = 1 :=
begin
have p : padic_val_rat p q = 0,
{ exact_mod_cast @padic_val_nat_primes p q p_prime q_prime neq },
simp [padic_norm, p, q_prime.1.1, q_prime.1.ne_zero],
end
/--
The p-adic norm of `p` is less than 1 if `1 < p`.
See also `padic_norm.padic_norm_p_lt_one_of_prime` for a version assuming `prime p`.
-/
lemma padic_norm_p_lt_one {p : ℕ} (hp : 1 < p) : padic_norm p p < 1 :=
begin
rw [padic_norm_p hp, div_lt_iff, one_mul],
{ exact_mod_cast hp },
{ exact_mod_cast zero_lt_one.trans hp },
end
/--
The p-adic norm of `p` is less than 1 if `p` is prime.
See also `padic_norm.padic_norm_p_lt_one` for a version assuming `1 < p`.
-/
lemma padic_norm_p_lt_one_of_prime (p : ℕ) [fact p.prime] : padic_norm p p < 1 :=
padic_norm_p_lt_one $ nat.prime.one_lt (fact.out _)
/--
`padic_norm p q` takes discrete values `p ^ -z` for `z : ℤ`.
-/
protected theorem values_discrete {q : ℚ} (hq : q ≠ 0) : ∃ z : ℤ, padic_norm p q = p ^ (-z) :=
⟨ (padic_val_rat p q), by simp [padic_norm, hq] ⟩
/--
`padic_norm p` is symmetric.
-/
@[simp] protected lemma neg (q : ℚ) : padic_norm p (-q) = padic_norm p q :=
if hq : q = 0 then by simp [hq]
else by simp [padic_norm, hq]
variable [hp : fact p.prime]
include hp
/--
If `q ≠ 0`, then `padic_norm p q ≠ 0`.
-/
protected lemma nonzero {q : ℚ} (hq : q ≠ 0) : padic_norm p q ≠ 0 :=
begin
rw padic_norm.eq_zpow_of_nonzero p hq,
apply zpow_ne_zero_of_ne_zero,
exact_mod_cast ne_of_gt hp.1.pos
end
/--
If the p-adic norm of `q` is 0, then `q` is 0.
-/
lemma zero_of_padic_norm_eq_zero {q : ℚ} (h : padic_norm p q = 0) : q = 0 :=
begin
apply by_contradiction, intro hq,
unfold padic_norm at h, rw if_neg hq at h,
apply absurd h,
apply zpow_ne_zero_of_ne_zero,
exact_mod_cast hp.1.ne_zero
end
/--
The p-adic norm is multiplicative.
-/
@[simp] protected theorem mul (q r : ℚ) : padic_norm p (q*r) = padic_norm p q * padic_norm p r :=
if hq : q = 0 then
by simp [hq]
else if hr : r = 0 then
by simp [hr]
else
have q*r ≠ 0, from mul_ne_zero hq hr,
have (↑p : ℚ) ≠ 0, by simp [hp.1.ne_zero],
by simp [padic_norm, *, padic_val_rat.mul, zpow_add₀ this, mul_comm]
/--
The p-adic norm respects division.
-/
@[simp] protected theorem div (q r : ℚ) : padic_norm p (q / r) = padic_norm p q / padic_norm p r :=
if hr : r = 0 then by simp [hr] else
eq_div_of_mul_eq (padic_norm.nonzero _ hr) (by rw [←padic_norm.mul, div_mul_cancel _ hr])
/--
The p-adic norm of an integer is at most 1.
-/
protected theorem of_int (z : ℤ) : padic_norm p ↑z ≤ 1 :=
if hz : z = 0 then by simp [hz, zero_le_one] else
begin
unfold padic_norm,
rw [if_neg _],
{ refine zpow_le_one_of_nonpos _ _,
{ exact_mod_cast le_of_lt hp.1.one_lt, },
{ rw [padic_val_rat_of_int _ hp.1.ne_one hz, neg_nonpos],
norm_cast, simp }},
exact_mod_cast hz
end
private lemma nonarchimedean_aux {q r : ℚ} (h : padic_val_rat p q ≤ padic_val_rat p r) :
padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) :=
have hnqp : padic_norm p q ≥ 0, from padic_norm.nonneg _ _,
have hnrp : padic_norm p r ≥ 0, from padic_norm.nonneg _ _,
if hq : q = 0 then
by simp [hq, max_eq_right hnrp, le_max_right]
else if hr : r = 0 then
by simp [hr, max_eq_left hnqp, le_max_left]
else if hqr : q + r = 0 then
le_trans (by simpa [hqr] using hnqp) (le_max_left _ _)
else
begin
unfold padic_norm, split_ifs,
apply le_max_iff.2,
left,
apply zpow_le_of_le,
{ exact_mod_cast le_of_lt hp.1.one_lt },
{ apply neg_le_neg,
have : padic_val_rat p q =
min (padic_val_rat p q) (padic_val_rat p r),
from (min_eq_left h).symm,
rw this,
apply min_le_padic_val_rat_add; assumption }
end
/--
The p-adic norm is nonarchimedean: the norm of `p + q` is at most the max of the norm of `p` and
the norm of `q`.
-/
protected theorem nonarchimedean {q r : ℚ} :
padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) :=
begin
wlog hle := le_total (padic_val_rat p q) (padic_val_rat p r) using [q r],
exact nonarchimedean_aux p hle
end
/--
The p-adic norm respects the triangle inequality: the norm of `p + q` is at most the norm of `p`
plus the norm of `q`.
-/
theorem triangle_ineq (q r : ℚ) : padic_norm p (q + r) ≤ padic_norm p q + padic_norm p r :=
calc padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) : padic_norm.nonarchimedean p
... ≤ padic_norm p q + padic_norm p r :
max_le_add_of_nonneg (padic_norm.nonneg p _) (padic_norm.nonneg p _)
/--
The p-adic norm of a difference is at most the max of each component. Restates the archimedean
property of the p-adic norm.
-/
protected theorem sub {q r : ℚ} : padic_norm p (q - r) ≤ max (padic_norm p q) (padic_norm p r) :=
by rw [sub_eq_add_neg, ←padic_norm.neg p r]; apply padic_norm.nonarchimedean
/--
If the p-adic norms of `q` and `r` are different, then the norm of `q + r` is equal to the max of
the norms of `q` and `r`.
-/
lemma add_eq_max_of_ne {q r : ℚ} (hne : padic_norm p q ≠ padic_norm p r) :
padic_norm p (q + r) = max (padic_norm p q) (padic_norm p r) :=
begin
wlog hle := le_total (padic_norm p r) (padic_norm p q) using [q r],
have hlt : padic_norm p r < padic_norm p q, from lt_of_le_of_ne hle hne.symm,
have : padic_norm p q ≤ max (padic_norm p (q + r)) (padic_norm p r), from calc
padic_norm p q = padic_norm p (q + r - r) : by congr; ring
... ≤ max (padic_norm p (q + r)) (padic_norm p (-r)) : padic_norm.nonarchimedean p
... = max (padic_norm p (q + r)) (padic_norm p r) : by simp,
have hnge : padic_norm p r ≤ padic_norm p (q + r),
{ apply le_of_not_gt,
intro hgt,
rw max_eq_right_of_lt hgt at this,
apply not_lt_of_ge this,
assumption },
have : padic_norm p q ≤ padic_norm p (q + r), by rwa [max_eq_left hnge] at this,
apply _root_.le_antisymm,
{ apply padic_norm.nonarchimedean p },
{ rw max_eq_left_of_lt hlt,
assumption }
end
/--
The p-adic norm is an absolute value: positive-definite and multiplicative, satisfying the triangle
inequality.
-/
instance : is_absolute_value (padic_norm p) :=
{ abv_nonneg := padic_norm.nonneg p,
abv_eq_zero :=
begin
intros,
constructor; intro,
{ apply zero_of_padic_norm_eq_zero p, assumption },
{ simp [*] }
end,
abv_add := padic_norm.triangle_ineq p,
abv_mul := padic_norm.mul p }
variable {p}
lemma dvd_iff_norm_le {n : ℕ} {z : ℤ} : ↑(p^n) ∣ z ↔ padic_norm p z ≤ ↑p ^ (-n : ℤ) :=
begin
unfold padic_norm, split_ifs with hz,
{ norm_cast at hz,
have : 0 ≤ (p^n : ℚ), {apply pow_nonneg, exact_mod_cast le_of_lt hp.1.pos },
simp [hz, this] },
{ rw [zpow_le_iff_le, neg_le_neg_iff, padic_val_rat_of_int _ hp.1.ne_one _],
{ norm_cast,
rw [← enat.coe_le_coe, enat.coe_get, ← multiplicity.pow_dvd_iff_le_multiplicity],
simp },
{ exact_mod_cast hz },
{ exact_mod_cast hp.1.one_lt } }
end
end padic_norm
end padic_norm
|
7504a3242a0c0b206e69db42a912f183c8e86c01 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/run/openInScopeBug.lean | b1498aab4ca56074dac4da2a3f12b17fcf3d26c2 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 809 | lean | opaque f : Nat → Nat
opaque g : Nat → Nat
namespace Foo
@[scoped simp] axiom ax1 (x : Nat) : f (g x) = x
@[scoped simp] axiom ax2 (x : Nat) : g (g x) = g x
end Foo
theorem ex1 : f (g (g (g x))) = x := by
simp -- does not use ax1 and ax2
simp [Foo.ax1, Foo.ax2]
theorem ex2 : f (g (g (g x))) = x :=
have h₁ : f (g (g (g x))) = f (g x) := by simp; /- try again with `Foo` scoped lemmas -/ open Foo in simp
have h₂ : f (g x) = x := by simp; open Foo in simp
Eq.trans h₁ h₂
-- open Foo in simp -- works
theorem ex3 : f (g (g (g x))) = x := by
simp
simp [Foo.ax1, Foo.ax2]
open Foo in
theorem ex4 : f (g (g (g x))) = x := by
simp
theorem ex5 : f (g (g (g x))) = x ∧ f (g x) = x := by
apply And.intro
{ simp; open Foo in simp }
{ simp; open Foo in simp }
|
f228f69965005d6ea952ca6d8286ea99e2f7c61a | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/category_theory/eq_to_hom.lean | 482160c728b5281c0b0d3d393046c9d9d457e750 | [
"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 | 3,967 | lean | /-
Copyright (c) 2018 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Scott Morrison
-/
import category_theory.opposites
universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
namespace category_theory
open opposite
variables {C : Type u₁} [category.{v₁} C]
/--
An equality `X = Y` gives us a morphism `X ⟶ Y`.
It is typically better to use this, rather than rewriting by the equality then using `𝟙 _`
which usually leads to dependent type theory hell.
-/
def eq_to_hom {X Y : C} (p : X = Y) : X ⟶ Y := by rw p; exact 𝟙 _
@[simp] lemma eq_to_hom_refl (X : C) (p : X = X) : eq_to_hom p = 𝟙 X := rfl
@[simp, reassoc] lemma eq_to_hom_trans {X Y Z : C} (p : X = Y) (q : Y = Z) :
eq_to_hom p ≫ eq_to_hom q = eq_to_hom (p.trans q) :=
by cases p; cases q; simp
/--
An equality `X = Y` gives us a morphism `X ⟶ Y`.
It is typically better to use this, rather than rewriting by the equality then using `iso.refl _`
which usually leads to dependent type theory hell.
-/
def eq_to_iso {X Y : C} (p : X = Y) : X ≅ Y :=
⟨eq_to_hom p, eq_to_hom p.symm, by simp, by simp⟩
@[simp] lemma eq_to_iso.hom {X Y : C} (p : X = Y) : (eq_to_iso p).hom = eq_to_hom p :=
rfl
@[simp] lemma eq_to_iso.inv {X Y : C} (p : X = Y) : (eq_to_iso p).inv = eq_to_hom p.symm :=
rfl
@[simp] lemma eq_to_iso_refl {X : C} (p : X = X) : eq_to_iso p = iso.refl X := rfl
@[simp] lemma eq_to_iso_trans {X Y Z : C} (p : X = Y) (q : Y = Z) :
eq_to_iso p ≪≫ eq_to_iso q = eq_to_iso (p.trans q) :=
by ext; simp
@[simp] lemma eq_to_hom_op {X Y : C} (h : X = Y) : (eq_to_hom h).op = eq_to_hom (congr_arg op h.symm) :=
by { cases h, refl, }
@[simp] lemma eq_to_hom_unop {X Y : Cᵒᵖ} (h : X = Y) : (eq_to_hom h).unop = eq_to_hom (congr_arg unop h.symm) :=
by { cases h, refl, }
instance {X Y : C} (h : X = Y) : is_iso (eq_to_hom h) := { .. eq_to_iso h }
@[simp] lemma inv_eq_to_hom {X Y : C} (h : X = Y) : inv (eq_to_hom h) = eq_to_hom h.symm := rfl
variables {D : Type u₂} [category.{v₂} D]
namespace functor
/-- Proving equality between functors. This isn't an extensionality lemma,
because usually you don't really want to do this. -/
lemma ext {F G : C ⥤ D} (h_obj : ∀ X, F.obj X = G.obj X)
(h_map : ∀ X Y f, F.map f = eq_to_hom (h_obj X) ≫ G.map f ≫ eq_to_hom (h_obj Y).symm) :
F = G :=
begin
cases F with F_obj _ _ _, cases G with G_obj _ _ _,
have : F_obj = G_obj, by ext X; apply h_obj,
subst this,
congr,
funext X Y f,
simpa using h_map X Y f
end
/-- Proving equality between functors using heterogeneous equality. -/
lemma hext {F G : C ⥤ D} (h_obj : ∀ X, F.obj X = G.obj X)
(h_map : ∀ X Y (f : X ⟶ Y), F.map f == G.map f) : F = G :=
begin
cases F with F_obj _ _ _, cases G with G_obj _ _ _,
have : F_obj = G_obj, by ext X; apply h_obj,
subst this,
congr,
funext X Y f,
exact eq_of_heq (h_map X Y f)
end
-- Using equalities between functors.
lemma congr_obj {F G : C ⥤ D} (h : F = G) (X) : F.obj X = G.obj X :=
by subst h
lemma congr_hom {F G : C ⥤ D} (h : F = G) {X Y} (f : X ⟶ Y) :
F.map f = eq_to_hom (congr_obj h X) ≫ G.map f ≫ eq_to_hom (congr_obj h Y).symm :=
by subst h; simp
end functor
@[simp] lemma eq_to_hom_map (F : C ⥤ D) {X Y : C} (p : X = Y) :
F.map (eq_to_hom p) = eq_to_hom (congr_arg F.obj p) :=
by cases p; simp
@[simp] lemma eq_to_iso_map (F : C ⥤ D) {X Y : C} (p : X = Y) :
F.map_iso (eq_to_iso p) = eq_to_iso (congr_arg F.obj p) :=
by ext; cases p; simp
@[simp] lemma eq_to_hom_app {F G : C ⥤ D} (h : F = G) (X : C) :
(eq_to_hom h : F ⟶ G).app X = eq_to_hom (functor.congr_obj h X) :=
by subst h; refl
lemma nat_trans.congr {F G : C ⥤ D} (α : F ⟶ G) {X Y : C} (h : X = Y) :
α.app X = F.map (eq_to_hom h) ≫ α.app Y ≫ G.map (eq_to_hom h.symm) :=
by { rw [α.naturality_assoc], simp }
end category_theory
|
5e533f464e1aa79c0d266f4c207910e438c469e0 | 618003631150032a5676f229d13a079ac875ff77 | /src/data/real/cau_seq_completion.lean | 3f603be43de9754f2137e11b025e481dfde2904e | [
"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 | 9,474 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Robert Y. Lewis
Generalizes the Cauchy completion of (ℚ, abs) to the completion of a
commutative ring with absolute value.
-/
import data.real.cau_seq
namespace cau_seq.completion
open cau_seq
section
parameters {α : Type*} [discrete_linear_ordered_field α]
parameters {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv]
def Cauchy := @quotient (cau_seq _ abv) cau_seq.equiv
def mk : cau_seq _ abv → Cauchy := quotient.mk
@[simp] theorem mk_eq_mk (f) : @eq Cauchy ⟦f⟧ (mk f) := rfl
theorem mk_eq {f g} : mk f = mk g ↔ f ≈ g := quotient.eq
def of_rat (x : β) : Cauchy := mk (const abv x)
instance : has_zero Cauchy := ⟨of_rat 0⟩
instance : has_one Cauchy := ⟨of_rat 1⟩
instance : inhabited Cauchy := ⟨0⟩
theorem of_rat_zero : of_rat 0 = 0 := rfl
theorem of_rat_one : of_rat 1 = 1 := rfl
@[simp] theorem mk_eq_zero {f} : mk f = 0 ↔ lim_zero f :=
by have : mk f = 0 ↔ lim_zero (f - 0) := quotient.eq;
rwa sub_zero at this
instance : has_add Cauchy :=
⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f + g)) $
λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $
by simpa [(≈), setoid.r, sub_eq_add_neg, add_comm, add_left_comm, add_assoc] using add_lim_zero hf hg⟩
@[simp] theorem mk_add (f g : cau_seq β abv) : mk f + mk g = mk (f + g) := rfl
instance : has_neg Cauchy :=
⟨λ x, quotient.lift_on x (λ f, mk (-f)) $
λ f₁ f₂ hf, quotient.sound $
by simpa [(≈), setoid.r] using neg_lim_zero hf⟩
@[simp] theorem mk_neg (f : cau_seq β abv) : -mk f = mk (-f) := rfl
instance : has_mul Cauchy :=
⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f * g)) $
λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $
by simpa [(≈), setoid.r, mul_add, mul_comm, add_assoc, sub_eq_add_neg] using
add_lim_zero (mul_lim_zero_right g₁ hf) (mul_lim_zero_right f₂ hg)⟩
@[simp] theorem mk_mul (f g : cau_seq β abv) : mk f * mk g = mk (f * g) := rfl
theorem of_rat_add (x y : β) : of_rat (x + y) = of_rat x + of_rat y :=
congr_arg mk (const_add _ _)
theorem of_rat_neg (x : β) : of_rat (-x) = -of_rat x :=
congr_arg mk (const_neg _)
theorem of_rat_mul (x y : β) : of_rat (x * y) = of_rat x * of_rat y :=
congr_arg mk (const_mul _ _)
private lemma zero_def : 0 = mk 0 := rfl
private lemma one_def : 1 = mk 1 := rfl
instance : comm_ring Cauchy :=
by refine { neg := has_neg.neg,
add := (+), zero := 0, mul := (*), one := 1, .. };
{ repeat {refine λ a, quotient.induction_on a (λ _, _)},
simp [zero_def, one_def, mul_left_comm, mul_comm, mul_add, add_comm, add_left_comm] }
theorem of_rat_sub (x y : β) : of_rat (x - y) = of_rat x - of_rat y :=
congr_arg mk (const_sub _ _)
end
open_locale classical
section
parameters {α : Type*} [discrete_linear_ordered_field α]
parameters {β : Type*} [field β] {abv : β → α} [is_absolute_value abv]
local notation `Cauchy` := @Cauchy _ _ _ _ abv _
noncomputable instance : has_inv Cauchy :=
⟨λ x, quotient.lift_on x
(λ f, mk $ if h : lim_zero f then 0 else inv f h) $
λ f g fg, begin
have := lim_zero_congr fg,
by_cases hf : lim_zero f,
{ simp [hf, this.1 hf, setoid.refl] },
{ have hg := mt this.2 hf, simp [hf, hg],
have If : mk (inv f hf) * mk f = 1 := mk_eq.2 (inv_mul_cancel hf),
have Ig : mk (inv g hg) * mk g = 1 := mk_eq.2 (inv_mul_cancel hg),
rw [mk_eq.2 fg, ← Ig] at If,
rw mul_comm at Ig,
rw [← mul_one (mk (inv f hf)), ← Ig, ← mul_assoc, If,
mul_assoc, Ig, mul_one] }
end⟩
@[simp] theorem inv_zero : (0 : Cauchy)⁻¹ = 0 :=
congr_arg mk $ by rw dif_pos; [refl, exact zero_lim_zero]
@[simp] theorem inv_mk {f} (hf) : (@mk α _ β _ abv _ f)⁻¹ = mk (inv f hf) :=
congr_arg mk $ by rw dif_neg
lemma cau_seq_zero_ne_one : ¬ (0 : cau_seq _ abv) ≈ 1 := λ h,
have lim_zero (1 - 0), from setoid.symm h,
have lim_zero 1, by simpa,
one_ne_zero $ const_lim_zero.1 this
lemma zero_ne_one : (0 : Cauchy) ≠ 1 :=
λ h, cau_seq_zero_ne_one $ mk_eq.1 h
protected theorem inv_mul_cancel {x : Cauchy} : x ≠ 0 → x⁻¹ * x = 1 :=
quotient.induction_on x $ λ f hf, begin
simp at hf, simp [hf],
exact quotient.sound (cau_seq.inv_mul_cancel hf)
end
noncomputable def field : field Cauchy :=
{ inv := has_inv.inv,
mul_inv_cancel := λ x x0, by rw [mul_comm, cau_seq.completion.inv_mul_cancel x0],
zero_ne_one := zero_ne_one,
inv_zero := inv_zero,
..cau_seq.completion.comm_ring }
local attribute [instance] field
theorem of_rat_inv (x : β) : of_rat (x⁻¹) = ((of_rat x)⁻¹ : Cauchy) :=
congr_arg mk $ by split_ifs with h; try {simp [const_lim_zero.1 h]}; refl
theorem of_rat_div (x y : β) : of_rat (x / y) = (of_rat x / of_rat y : Cauchy) :=
by simp only [div_eq_inv_mul, of_rat_inv, of_rat_mul]
end
end cau_seq.completion
variables {α : Type*} [discrete_linear_ordered_field α]
namespace cau_seq
section
variables (β : Type*) [ring β] (abv : β → α) [is_absolute_value abv]
class is_complete :=
(is_complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b)
end
section
variables {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv]
variable [is_complete β abv]
lemma complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b :=
is_complete.is_complete
noncomputable def lim (s : cau_seq β abv) := classical.some (complete s)
lemma equiv_lim (s : cau_seq β abv) : s ≈ const abv (lim s) :=
classical.some_spec (complete s)
lemma eq_lim_of_const_equiv {f : cau_seq β abv} {x : β} (h : cau_seq.const abv x ≈ f) : x = lim f :=
const_equiv.mp $ setoid.trans h $ equiv_lim f
lemma lim_eq_of_equiv_const {f : cau_seq β abv} {x : β} (h : f ≈ cau_seq.const abv x) : lim f = x :=
(eq_lim_of_const_equiv $ setoid.symm h).symm
lemma lim_eq_lim_of_equiv {f g : cau_seq β abv} (h : f ≈ g) : lim f = lim g :=
lim_eq_of_equiv_const $ setoid.trans h $ equiv_lim g
@[simp] lemma lim_const (x : β) : lim (const abv x) = x :=
lim_eq_of_equiv_const $ setoid.refl _
lemma lim_add (f g : cau_seq β abv) : lim f + lim g = lim (f + g) :=
eq_lim_of_const_equiv $ show lim_zero (const abv (lim f + lim g) - (f + g)),
by rw [const_add, add_sub_comm];
exact add_lim_zero (setoid.symm (equiv_lim f)) (setoid.symm (equiv_lim g))
lemma lim_mul_lim (f g : cau_seq β abv) : lim f * lim g = lim (f * g) :=
eq_lim_of_const_equiv $ show lim_zero (const abv (lim f * lim g) - f * g),
from have h : const abv (lim f * lim g) - f * g = (const abv (lim f) - f) * g
+ const abv (lim f) * (const abv (lim g) - g) :=
by simp [const_mul (lim f), mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm],
by rw h; exact add_lim_zero (mul_lim_zero_left _ (setoid.symm (equiv_lim _)))
(mul_lim_zero_right _ (setoid.symm (equiv_lim _)))
lemma lim_mul (f : cau_seq β abv) (x : β) : lim f * x = lim (f * const abv x) :=
by rw [← lim_mul_lim, lim_const]
lemma lim_neg (f : cau_seq β abv) : lim (-f) = -lim f :=
lim_eq_of_equiv_const (show lim_zero (-f - const abv (-lim f)),
by rw [const_neg, sub_neg_eq_add, add_comm];
exact setoid.symm (equiv_lim f))
lemma lim_eq_zero_iff (f : cau_seq β abv) : lim f = 0 ↔ lim_zero f :=
⟨assume h,
by have hf := equiv_lim f;
rw h at hf;
exact (lim_zero_congr hf).mpr (const_lim_zero.mpr rfl),
assume h,
have h₁ : f = (f - const abv 0) := ext (λ n, by simp [sub_apply, const_apply]),
by rw h₁ at h; exact lim_eq_of_equiv_const h ⟩
end
section
variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] [is_complete β abv]
lemma lim_inv {f : cau_seq β abv} (hf : ¬ lim_zero f) : lim (inv f hf) = (lim f)⁻¹ :=
have hl : lim f ≠ 0 := by rwa ← lim_eq_zero_iff at hf,
lim_eq_of_equiv_const $ show lim_zero (inv f hf - const abv (lim f)⁻¹),
from have h₁ : ∀ (g f : cau_seq β abv) (hf : ¬ lim_zero f), lim_zero (g - f * inv f hf * g) :=
λ g f hf, by rw [← one_mul g, ← mul_assoc, ← sub_mul, mul_one, mul_comm, mul_comm f];
exact mul_lim_zero_right _ (setoid.symm (cau_seq.inv_mul_cancel _)),
have h₂ : lim_zero ((inv f hf - const abv (lim f)⁻¹) - (const abv (lim f) - f) *
(inv f hf * const abv (lim f)⁻¹)) :=
by rw [sub_mul, ← sub_add, sub_sub, sub_add_eq_sub_sub, sub_right_comm, sub_add];
exact show lim_zero (inv f hf - const abv (lim f) * (inv f hf * const abv (lim f)⁻¹)
- (const abv (lim f)⁻¹ - f * (inv f hf * const abv (lim f)⁻¹))),
from sub_lim_zero
(by rw [← mul_assoc, mul_right_comm, const_inv hl]; exact h₁ _ _ _)
(by rw [← mul_assoc]; exact h₁ _ _ _),
(lim_zero_congr h₂).mpr $ mul_lim_zero_left _ (setoid.symm (equiv_lim f))
end
section
variables [is_complete α abs]
lemma lim_le {f : cau_seq α abs} {x : α}
(h : f ≤ cau_seq.const abs x) : lim f ≤ x :=
cau_seq.const_le.1 $ cau_seq.le_of_eq_of_le (setoid.symm (equiv_lim f)) h
lemma le_lim {f : cau_seq α abs} {x : α}
(h : cau_seq.const abs x ≤ f) : x ≤ lim f :=
cau_seq.const_le.1 $ cau_seq.le_of_le_of_eq h (equiv_lim f)
lemma lt_lim {f : cau_seq α abs} {x : α}
(h : cau_seq.const abs x < f) : x < lim f :=
cau_seq.const_lt.1 $ cau_seq.lt_of_lt_of_eq h (equiv_lim f)
lemma lim_lt {f : cau_seq α abs} {x : α}
(h : f < cau_seq.const abs x) : lim f < x :=
cau_seq.const_lt.1 $ cau_seq.lt_of_eq_of_lt (setoid.symm (equiv_lim f)) h
end
end cau_seq
|
4addee6141d74a2dcab2f3c1fe966242d20a001f | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/field_theory/fixed.lean | 115e8d2481a6d0616539c0dda51ff6ec2cb4811e | [
"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 | 6,529 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.group_action_hom
import field_theory.normal
import field_theory.subfield
import ring_theory.polynomial
/-!
# Fixed field under a group action.
This is the basis of the Fundamental Theorem of Galois Theory.
Given a (finite) group `G` that acts on a field `F`, we define `fixed_points G F`,
the subfield consisting of elements of `F` fixed_points by every element of `G`.
This subfield is then normal (proved in this file) and separable (TODO), and in addition
if `G` acts faithfully on `F` then `findim (fixed_points G F) F = fintype.card G` (TODO).
## Main Definitions
- `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`, where
`G` is a group that acts on `F`.
-/
noncomputable theory
open_locale classical
open mul_action
universes u v w
variables (G : Type u) [group G] (F : Type v) [field F] [mul_semiring_action G F] (g : G)
instance fixed_by.is_subfield : is_subfield (fixed_by G F g) :=
{ zero_mem := smul_zero g,
add_mem := λ x y hx hy, (smul_add g x y).trans $ congr_arg2 _ hx hy,
neg_mem := λ x hx, (smul_neg g x).trans $ congr_arg _ hx,
one_mem := smul_one g,
mul_mem := λ x y hx hy, (smul_mul' g x y).trans $ congr_arg2 _ hx hy,
inv_mem := λ x hx, (smul_inv F g x).trans $ congr_arg _ hx }
instance fixed_points.is_subfield : is_subfield (fixed_points G F) :=
by convert @is_subfield.Inter F _ G (fixed_by G F) _; rw fixed_eq_Inter_fixed_by
instance fixed_points.is_invariant_subring : is_invariant_subring G (fixed_points G F) :=
{ smul_mem := λ g x hx g', by rw [hx, hx] }
@[simp] theorem fixed_points.smul (g : G) (x : fixed_points G F) : g • x = x :=
subtype.eq $ x.2 g
-- Why is this so slow?
@[simp] theorem fixed_points.smul_polynomial (g : G) (p : polynomial (fixed_points G F)) : g • p = p :=
polynomial.induction_on p
(λ x, by rw [polynomial.smul_C, fixed_points.smul])
(λ p q ihp ihq, by rw [smul_add, ihp, ihq])
(λ n x ih, by rw [smul_mul', polynomial.smul_C, fixed_points.smul, smul_pow, polynomial.smul_X])
instance fixed_points.algebra : algebra (fixed_points G F) F :=
algebra.of_subring _
theorem fixed_points.coe_algebra_map :
(algebra_map (fixed_points G F) F) = is_subring.subtype (fixed_points G F) :=
rfl
variables [fintype G] (x : F)
/-- `fixed_points.minpoly G F x` is the minimal polynomial of `(x : F)` over `fixed_points G F`. -/
def fixed_points.minpoly : polynomial (fixed_points G F) :=
(prod_X_sub_smul G F x).to_subring _ $ λ c hc g,
let ⟨hc0, n, hn⟩ := finsupp.mem_frange.1 hc in
hn ▸ prod_X_sub_smul.coeff G F x g n
theorem fixed_points.minpoly.monic : (fixed_points.minpoly G F x).monic :=
subtype.eq $ prod_X_sub_smul.monic G F x
theorem fixed_points.minpoly.eval₂ :
polynomial.eval₂ (is_subring.subtype $ fixed_points G F) x (fixed_points.minpoly G F x) = 0 :=
prod_X_sub_smul.eval G F x
theorem fixed_points.is_integral : is_integral (fixed_points G F) x :=
⟨fixed_points.minpoly G F x,
fixed_points.minpoly.monic G F x,
fixed_points.minpoly.eval₂ G F x⟩
theorem fixed_points.minpoly.ne_one :
fixed_points.minpoly G F x ≠ (1 : polynomial (fixed_points G F)) :=
λ H, have _ := fixed_points.minpoly.eval₂ G F x,
(one_ne_zero : (1 : F) ≠ 0) $ by rwa [H, polynomial.eval₂_one] at this
theorem fixed_points.of_eval₂ (f : polynomial (fixed_points G F))
(hf : polynomial.eval₂ (is_subring.subtype $ fixed_points G F) x f = 0) :
fixed_points.minpoly G F x ∣ f :=
begin
rw [← polynomial.map_dvd_map' (is_subring.subtype $ fixed_points G F),
fixed_points.minpoly, polynomial.map_to_subring, prod_X_sub_smul],
refine fintype.prod_dvd_of_coprime
(polynomial.pairwise_coprime_X_sub $ mul_action.injective_of_quotient_stabilizer G x)
(λ y, quotient_group.induction_on y $ λ g, _),
rw [polynomial.dvd_iff_is_root, polynomial.is_root.def, mul_action.of_quotient_stabilizer_mk,
polynomial.eval_smul', ← is_invariant_subring.coe_subtype_hom' G (fixed_points G F),
← mul_semiring_action_hom.coe_polynomial, ← mul_semiring_action_hom.map_smul,
fixed_points.smul_polynomial, mul_semiring_action_hom.coe_polynomial,
is_invariant_subring.coe_subtype_hom', polynomial.eval_map, hf, smul_zero]
end
/- Why is this so slow? -/
theorem fixed_points.minpoly.irreducible_aux (f g : polynomial (fixed_points G F))
(hf : f.monic) (hg : g.monic) (hfg : f * g = fixed_points.minpoly G F x) :
f = 1 ∨ g = 1 :=
begin
have hf2 : f ∣ fixed_points.minpoly G F x,
{ rw ← hfg, exact dvd_mul_right _ _ },
have hg2 : g ∣ fixed_points.minpoly G F x,
{ rw ← hfg, exact dvd_mul_left _ _ },
have := fixed_points.minpoly.eval₂ G F x,
rw [← hfg, polynomial.eval₂_mul, mul_eq_zero] at this,
cases this,
{ right,
have hf3 : f = fixed_points.minpoly G F x,
{ exact polynomial.eq_of_monic_of_associated hf (fixed_points.minpoly.monic G F x)
(associated_of_dvd_dvd hf2 $ @fixed_points.of_eval₂ G _ F _ _ _ x f this) },
rwa [← mul_one (fixed_points.minpoly G F x), hf3,
mul_right_inj' (fixed_points.minpoly.monic G F x).ne_zero] at hfg },
{ left,
have hg3 : g = fixed_points.minpoly G F x,
{ exact polynomial.eq_of_monic_of_associated hg (fixed_points.minpoly.monic G F x)
(associated_of_dvd_dvd hg2 $ @fixed_points.of_eval₂ G _ F _ _ _ x g this) },
rwa [← one_mul (fixed_points.minpoly G F x), hg3,
mul_left_inj' (fixed_points.minpoly.monic G F x).ne_zero] at hfg }
end
theorem fixed_points.minpoly.irreducible : irreducible (fixed_points.minpoly G F x) :=
(polynomial.irreducible_of_monic
(fixed_points.minpoly.monic G F x)
(fixed_points.minpoly.ne_one G F x)).2
(fixed_points.minpoly.irreducible_aux G F x)
theorem fixed_points.minpoly.minimal_polynomial :
fixed_points.minpoly G F x = minimal_polynomial (fixed_points.is_integral G F x) :=
minimal_polynomial.unique' _ (fixed_points.minpoly.irreducible G F x)
(fixed_points.minpoly.eval₂ G F x) (fixed_points.minpoly.monic G F x)
instance fixed_points.normal : normal (fixed_points G F) F :=
λ x, ⟨fixed_points.is_integral G F x, (polynomial.splits_id_iff_splits _).1 $
by { rw [← fixed_points.minpoly.minimal_polynomial, fixed_points.minpoly,
fixed_points.coe_algebra_map, polynomial.map_to_subring, prod_X_sub_smul],
exact polynomial.splits_prod _ (λ _ _, polynomial.splits_X_sub_C _) }⟩
|
4eac4049eb1fcb2b7f8c955ceed06b91f8dc38fa | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/data/part.lean | 28671676fba0e622f02735027eed50f37660eb31 | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,808 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Jeremy Avigad, Simon Hudon
-/
import data.equiv.basic
/-!
# Partial values of a type
-/
/-- `part α` is the type of "partial values" of type `α`. It
is similar to `option α` except the domain condition can be an
arbitrary proposition, not necessarily decidable. -/
structure {u} part (α : Type u) : Type u :=
(dom : Prop)
(get : dom → α)
namespace part
variables {α : Type*} {β : Type*} {γ : Type*}
/-- Convert a `part α` with a decidable domain to an option -/
def to_option (o : part α) [decidable o.dom] : option α :=
if h : dom o then some (o.get h) else none
/-- `part` extensionality -/
theorem ext' : ∀ {o p : part α}
(H1 : o.dom ↔ p.dom)
(H2 : ∀h₁ h₂, o.get h₁ = p.get h₂), o = p
| ⟨od, o⟩ ⟨pd, p⟩ H1 H2 := have t : od = pd, from propext H1,
by cases t; rw [show o = p, from funext $ λp, H2 p p]
/-- `part` eta expansion -/
@[simp] theorem eta : Π (o : part α), (⟨o.dom, λ h, o.get h⟩ : part α) = o
| ⟨h, f⟩ := rfl
/-- `a ∈ o` means that `o` is defined and equal to `a` -/
protected def mem (a : α) (o : part α) : Prop := ∃ h, o.get h = a
instance : has_mem α (part α) := ⟨part.mem⟩
theorem mem_eq (a : α) (o : part α) : (a ∈ o) = (∃ h, o.get h = a) :=
rfl
theorem dom_iff_mem : ∀ {o : part α}, o.dom ↔ ∃y, y ∈ o
| ⟨p, f⟩ := ⟨λh, ⟨f h, h, rfl⟩, λ⟨_, h, rfl⟩, h⟩
theorem get_mem {o : part α} (h) : get o h ∈ o := ⟨_, rfl⟩
/-- `part` extensionality -/
@[ext]
theorem ext {o p : part α} (H : ∀ a, a ∈ o ↔ a ∈ p) : o = p :=
ext' ⟨λ h, ((H _).1 ⟨h, rfl⟩).fst,
λ h, ((H _).2 ⟨h, rfl⟩).fst⟩ $
λ a b, ((H _).2 ⟨_, rfl⟩).snd
/-- The `none` value in `part` has a `false` domain and an empty function. -/
def none : part α := ⟨false, false.rec _⟩
instance : inhabited (part α) := ⟨none⟩
@[simp] theorem not_mem_none (a : α) : a ∉ @none α := λ h, h.fst
/-- The `some a` value in `part` has a `true` domain and the
function returns `a`. -/
def some (a : α) : part α := ⟨true, λ_, a⟩
theorem mem_unique : ∀ {a b : α} {o : part α}, a ∈ o → b ∈ o → a = b
| _ _ ⟨p, f⟩ ⟨h₁, rfl⟩ ⟨h₂, rfl⟩ := rfl
theorem mem.left_unique : relator.left_unique ((∈) : α → part α → Prop) :=
⟨λ a o b, mem_unique⟩
theorem get_eq_of_mem {o : part α} {a} (h : a ∈ o) (h') : get o h' = a :=
mem_unique ⟨_, rfl⟩ h
protected theorem subsingleton (o : part α) : set.subsingleton {a | a ∈ o} :=
λ a ha b hb, mem_unique ha hb
@[simp] theorem get_some {a : α} (ha : (some a).dom) : get (some a) ha = a := rfl
theorem mem_some (a : α) : a ∈ some a := ⟨trivial, rfl⟩
@[simp] theorem mem_some_iff {a b} : b ∈ (some a : part α) ↔ b = a :=
⟨λ⟨h, e⟩, e.symm, λ e, ⟨trivial, e.symm⟩⟩
theorem eq_some_iff {a : α} {o : part α} : o = some a ↔ a ∈ o :=
⟨λ e, e.symm ▸ mem_some _,
λ ⟨h, e⟩, e ▸ ext' (iff_true_intro h) (λ _ _, rfl)⟩
theorem eq_none_iff {o : part α} : o = none ↔ ∀ a, a ∉ o :=
⟨λ e, e.symm ▸ not_mem_none, λ h, ext (by simpa)⟩
theorem eq_none_iff' {o : part α} : o = none ↔ ¬ o.dom :=
⟨λ e, e.symm ▸ id, λ h, eq_none_iff.2 (λ a h', h h'.fst)⟩
@[simp] lemma some_ne_none (x : α) : some x ≠ none :=
by { intro h, change none.dom, rw [← h], trivial }
@[simp] lemma none_ne_some (x : α) : none ≠ some x :=
(some_ne_none x).symm
lemma ne_none_iff {o : part α} : o ≠ none ↔ ∃x, o = some x :=
begin
split,
{ rw [ne, eq_none_iff', not_not], exact λ h, ⟨o.get h, eq_some_iff.2 (get_mem h)⟩ },
{ rintro ⟨x, rfl⟩, apply some_ne_none }
end
lemma eq_none_or_eq_some (o : part α) : o = none ∨ ∃ x, o = some x :=
or_iff_not_imp_left.2 ne_none_iff.1
@[simp] lemma some_inj {a b : α} : part.some a = some b ↔ a = b :=
function.injective.eq_iff (λ a b h, congr_fun (eq_of_heq (part.mk.inj h).2) trivial)
@[simp] lemma some_get {a : part α} (ha : a.dom) :
part.some (part.get a ha) = a :=
eq.symm (eq_some_iff.2 ⟨ha, rfl⟩)
lemma get_eq_iff_eq_some {a : part α} {ha : a.dom} {b : α} :
a.get ha = b ↔ a = some b :=
⟨λ h, by simp [h.symm], λ h, by simp [h]⟩
lemma get_eq_get_of_eq (a : part α) (ha : a.dom) {b : part α} (h : a = b) :
a.get ha = b.get (h ▸ ha) :=
by { congr, exact h }
lemma get_eq_iff_mem {o : part α} {a : α} (h : o.dom) : o.get h = a ↔ a ∈ o :=
⟨λ H, ⟨h, H⟩, λ ⟨h', H⟩, H⟩
lemma eq_get_iff_mem {o : part α} {a : α} (h : o.dom) : a = o.get h ↔ a ∈ o :=
eq_comm.trans (get_eq_iff_mem h)
@[simp] lemma none_to_option [decidable (@none α).dom] : (none : part α).to_option = option.none :=
dif_neg id
@[simp] lemma some_to_option (a : α) [decidable (some a).dom] :
(some a).to_option = option.some a :=
dif_pos trivial
instance none_decidable : decidable (@none α).dom := decidable.false
instance some_decidable (a : α) : decidable (some a).dom := decidable.true
/-- Retrieves the value of `a : part α` if it exists, and return the provided default value
otherwise. -/
def get_or_else (a : part α) [decidable a.dom] (d : α) :=
if ha : a.dom then a.get ha else d
@[simp] lemma get_or_else_none (d : α) [decidable (none : part α).dom] : get_or_else none d = d :=
dif_neg id
@[simp] lemma get_or_else_some (a : α) (d : α) [decidable (some a).dom] :
get_or_else (some a) d = a :=
dif_pos trivial
@[simp] theorem mem_to_option {o : part α} [decidable o.dom] {a : α} :
a ∈ to_option o ↔ a ∈ o :=
begin
unfold to_option,
by_cases h : o.dom; simp [h],
{ exact ⟨λ h, ⟨_, h⟩, λ ⟨_, h⟩, h⟩ },
{ exact mt Exists.fst h }
end
/-- Converts an `option α` into a `part α`. -/
def of_option : option α → part α
| option.none := none
| (option.some a) := some a
@[simp] theorem mem_of_option {a : α} : ∀ {o : option α}, a ∈ of_option o ↔ a ∈ o
| option.none := ⟨λ h, h.fst.elim, λ h, option.no_confusion h⟩
| (option.some b) := ⟨λ h, congr_arg option.some h.snd,
λ h, ⟨trivial, option.some.inj h⟩⟩
@[simp] theorem of_option_dom {α} : ∀ (o : option α), (of_option o).dom ↔ o.is_some
| option.none := by simp [of_option, none]
| (option.some a) := by simp [of_option]
theorem of_option_eq_get {α} (o : option α) : of_option o = ⟨_, @option.get _ o⟩ :=
part.ext' (of_option_dom o) $ λ h₁ h₂, by cases o; [cases h₁, refl]
instance : has_coe (option α) (part α) := ⟨of_option⟩
@[simp] theorem mem_coe {a : α} {o : option α} :
a ∈ (o : part α) ↔ a ∈ o := mem_of_option
@[simp] theorem coe_none : (@option.none α : part α) = none := rfl
@[simp] theorem coe_some (a : α) : (option.some a : part α) = some a := rfl
@[elab_as_eliminator] protected lemma induction_on {P : part α → Prop}
(a : part α) (hnone : P none) (hsome : ∀ a : α, P (some a)) : P a :=
(classical.em a.dom).elim
(λ h, part.some_get h ▸ hsome _)
(λ h, (eq_none_iff'.2 h).symm ▸ hnone)
instance of_option_decidable : ∀ o : option α, decidable (of_option o).dom
| option.none := part.none_decidable
| (option.some a) := part.some_decidable a
@[simp] theorem to_of_option (o : option α) : to_option (of_option o) = o :=
by cases o; refl
@[simp] theorem of_to_option (o : part α) [decidable o.dom] : of_option (to_option o) = o :=
ext $ λ a, mem_of_option.trans mem_to_option
/-- `part α` is (classically) equivalent to `option α`. -/
noncomputable def equiv_option : part α ≃ option α :=
by haveI := classical.dec; exact
⟨λ o, to_option o, of_option, λ o, of_to_option o,
λ o, eq.trans (by dsimp; congr) (to_of_option o)⟩
/-- We give `part α` the order where everything is greater than `none`. -/
instance : order_bot (part α) :=
{ le := λ x y, ∀ i, i ∈ x → i ∈ y,
le_refl := λ x y, id,
le_trans := λ x y z f g i, g _ ∘ f _,
le_antisymm := λ x y f g, part.ext $ λ z, ⟨f _, g _⟩,
bot := none,
bot_le := by { introv x, rintro ⟨⟨_⟩,_⟩, } }
instance : preorder (part α) :=
by apply_instance
lemma le_total_of_le_of_le {x y : part α} (z : part α) (hx : x ≤ z) (hy : y ≤ z) :
x ≤ y ∨ y ≤ x :=
begin
rcases part.eq_none_or_eq_some x with h | ⟨b, h₀⟩,
{ rw h, left, apply order_bot.bot_le _ },
right, intros b' h₁,
rw part.eq_some_iff at h₀,
replace hx := hx _ h₀, replace hy := hy _ h₁,
replace hx := part.mem_unique hx hy, subst hx,
exact h₀
end
/-- `assert p f` is a bind-like operation which appends an additional condition
`p` to the domain and uses `f` to produce the value. -/
def assert (p : Prop) (f : p → part α) : part α :=
⟨∃h : p, (f h).dom, λha, (f ha.fst).get ha.snd⟩
/-- The bind operation has value `g (f.get)`, and is defined when all the
parts are defined. -/
protected def bind (f : part α) (g : α → part β) : part β :=
assert (dom f) (λb, g (f.get b))
/-- The map operation for `part` just maps the value and maintains the same domain. -/
@[simps] def map (f : α → β) (o : part α) : part β :=
⟨o.dom, f ∘ o.get⟩
theorem mem_map (f : α → β) {o : part α} :
∀ {a}, a ∈ o → f a ∈ map f o
| _ ⟨h, rfl⟩ := ⟨_, rfl⟩
@[simp] theorem mem_map_iff (f : α → β) {o : part α} {b} :
b ∈ map f o ↔ ∃ a ∈ o, f a = b :=
⟨match b with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩, rfl⟩ end,
λ ⟨a, h₁, h₂⟩, h₂ ▸ mem_map f h₁⟩
@[simp] theorem map_none (f : α → β) :
map f none = none := eq_none_iff.2 $ λ a, by simp
@[simp] theorem map_some (f : α → β) (a : α) : map f (some a) = some (f a) :=
eq_some_iff.2 $ mem_map f $ mem_some _
theorem mem_assert {p : Prop} {f : p → part α}
: ∀ {a} (h : p), a ∈ f h → a ∈ assert p f
| _ x ⟨h, rfl⟩ := ⟨⟨x, h⟩, rfl⟩
@[simp] theorem mem_assert_iff {p : Prop} {f : p → part α} {a} :
a ∈ assert p f ↔ ∃ h : p, a ∈ f h :=
⟨match a with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩⟩ end,
λ ⟨a, h⟩, mem_assert _ h⟩
lemma assert_pos {p : Prop} {f : p → part α} (h : p) :
assert p f = f h :=
begin
dsimp [assert],
cases h' : f h,
simp only [h', h, true_and, iff_self, exists_prop_of_true, eq_iff_iff],
apply function.hfunext,
{ simp only [h,h',exists_prop_of_true] },
{ cc }
end
lemma assert_neg {p : Prop} {f : p → part α} (h : ¬ p) :
assert p f = none :=
begin
dsimp [assert,none], congr,
{ simp only [h, not_false_iff, exists_prop_of_false] },
{ apply function.hfunext,
{ simp only [h, not_false_iff, exists_prop_of_false] },
cc },
end
theorem mem_bind {f : part α} {g : α → part β} :
∀ {a b}, a ∈ f → b ∈ g a → b ∈ f.bind g
| _ _ ⟨h, rfl⟩ ⟨h₂, rfl⟩ := ⟨⟨h, h₂⟩, rfl⟩
@[simp] theorem mem_bind_iff {f : part α} {g : α → part β} {b} :
b ∈ f.bind g ↔ ∃ a ∈ f, b ∈ g a :=
⟨match b with _, ⟨⟨h₁, h₂⟩, rfl⟩ := ⟨_, ⟨_, rfl⟩, ⟨_, rfl⟩⟩ end,
λ ⟨a, h₁, h₂⟩, mem_bind h₁ h₂⟩
@[simp] theorem bind_none (f : α → part β) :
none.bind f = none := eq_none_iff.2 $ λ a, by simp
@[simp] theorem bind_some (a : α) (f : α → part β) :
(some a).bind f = f a := ext $ by simp
theorem bind_of_mem {o : part α} {a : α} (h : a ∈ o) (f : α → part β) :
o.bind f = f a :=
by rw [eq_some_iff.2 h, bind_some]
theorem bind_some_eq_map (f : α → β) (x : part α) :
x.bind (some ∘ f) = map f x :=
ext $ by simp [eq_comm]
theorem bind_assoc {γ} (f : part α) (g : α → part β) (k : β → part γ) :
(f.bind g).bind k = f.bind (λ x, (g x).bind k) :=
ext $ λ a, by simp; exact
⟨λ ⟨_, ⟨_, h₁, h₂⟩, h₃⟩, ⟨_, h₁, _, h₂, h₃⟩,
λ ⟨_, h₁, _, h₂, h₃⟩, ⟨_, ⟨_, h₁, h₂⟩, h₃⟩⟩
@[simp] theorem bind_map {γ} (f : α → β) (x) (g : β → part γ) :
(map f x).bind g = x.bind (λ y, g (f y)) :=
by rw [← bind_some_eq_map, bind_assoc]; simp
@[simp] theorem map_bind {γ} (f : α → part β) (x : part α) (g : β → γ) :
map g (x.bind f) = x.bind (λ y, map g (f y)) :=
by rw [← bind_some_eq_map, bind_assoc]; simp [bind_some_eq_map]
theorem map_map (g : β → γ) (f : α → β) (o : part α) :
map g (map f o) = map (g ∘ f) o :=
by rw [← bind_some_eq_map, bind_map, bind_some_eq_map]
instance : monad part :=
{ pure := @some,
map := @map,
bind := @part.bind }
instance : is_lawful_monad part :=
{ bind_pure_comp_eq_map := @bind_some_eq_map,
id_map := λ β f, by cases f; refl,
pure_bind := @bind_some,
bind_assoc := @bind_assoc }
theorem map_id' {f : α → α} (H : ∀ (x : α), f x = x) (o) : map f o = o :=
by rw [show f = id, from funext H]; exact id_map o
@[simp] theorem bind_some_right (x : part α) : x.bind some = x :=
by rw [bind_some_eq_map]; simp [map_id']
@[simp] theorem pure_eq_some (a : α) : pure a = some a := rfl
@[simp] theorem ret_eq_some (a : α) : return a = some a := rfl
@[simp] theorem map_eq_map {α β} (f : α → β) (o : part α) :
f <$> o = map f o := rfl
@[simp] theorem bind_eq_bind {α β} (f : part α) (g : α → part β) :
f >>= g = f.bind g := rfl
lemma bind_le {α} (x : part α) (f : α → part β) (y : part β) :
x >>= f ≤ y ↔ (∀ a, a ∈ x → f a ≤ y) :=
begin
split; intro h,
{ intros a h' b, replace h := h b,
simp only [and_imp, exists_prop, bind_eq_bind, mem_bind_iff, exists_imp_distrib] at h,
apply h _ h' },
{ intros b h',
simp only [exists_prop, bind_eq_bind, mem_bind_iff] at h',
rcases h' with ⟨a,h₀,h₁⟩, apply h _ h₀ _ h₁ },
end
instance : monad_fail part :=
{ fail := λ_ _, none, ..part.monad }
/-- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when
`p` implies `o` is defined. -/
def restrict (p : Prop) (o : part α) (H : p → o.dom) : part α :=
⟨p, λh, o.get (H h)⟩
@[simp]
theorem mem_restrict (p : Prop) (o : part α) (h : p → o.dom) (a : α) :
a ∈ restrict p o h ↔ p ∧ a ∈ o :=
begin
dsimp [restrict, mem_eq], split,
{ rintro ⟨h₀, h₁⟩, exact ⟨h₀, ⟨_, h₁⟩⟩ },
rintro ⟨h₀, h₁, h₂⟩, exact ⟨h₀, h₂⟩
end
/-- `unwrap o` gets the value at `o`, ignoring the condition. This function is unsound. -/
meta def unwrap (o : part α) : α := o.get undefined
theorem assert_defined {p : Prop} {f : p → part α} :
∀ (h : p), (f h).dom → (assert p f).dom := exists.intro
theorem bind_defined {f : part α} {g : α → part β} :
∀ (h : f.dom), (g (f.get h)).dom → (f.bind g).dom := assert_defined
@[simp] theorem bind_dom {f : part α} {g : α → part β} :
(f.bind g).dom ↔ ∃ h : f.dom, (g (f.get h)).dom := iff.rfl
end part
|
39e0c9da900271d2320fb174202cb22250014dfc | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /src/Lean/Server/Completion.lean | ed1803da9fcec8f23a2d6233fff0199e993cb10d | [
"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 | 12,732 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Environment
import Lean.Parser.Term
import Lean.Data.Lsp.LanguageFeatures
import Lean.Meta.Tactic.Apply
import Lean.Meta.Match.MatcherInfo
import Lean.Server.InfoUtils
import Lean.Parser.Extension
namespace Lean.Server.Completion
open Lsp
open Elab
open Meta
builtin_initialize completionBlackListExt : TagDeclarationExtension ← mkTagDeclarationExtension `blackListCompletion
@[export lean_completion_add_to_black_list]
def addToBlackList (env : Environment) (declName : Name) : Environment :=
completionBlackListExt.tag env declName
private def isBlackListed (declName : Name) : MetaM Bool := do
let env ← getEnv
(declName.isInternal && !isPrivateName declName)
<||> isAuxRecursor env declName
<||> isNoConfusion env declName
<||> isRec declName
<||> completionBlackListExt.isTagged env declName
<||> isMatcher declName
private partial def consumeImplicitPrefix (e : Expr) : MetaM Expr := do
match e with
| Expr.forallE n d b c =>
-- We do not consume instance implicit arguments because the user probably wants be aware of this dependency
if c.binderInfo == BinderInfo.implicit then
let arg ← mkFreshExprMVar (userName := n) d
consumeImplicitPrefix (b.instantiate1 arg)
else
return e
| _ => return e
private def isTypeApplicable (type : Expr) (expectedType? : Option Expr) : MetaM Bool :=
try
match expectedType? with
| none => return true
| some expectedType =>
let mut (numArgs, hasMVarHead) ← getExpectedNumArgsAux type
unless hasMVarHead do
let targetTypeNumArgs ← getExpectedNumArgs expectedType
numArgs := numArgs - targetTypeNumArgs
let (newMVars, _, type) ← forallMetaTelescopeReducing type (some numArgs)
-- TODO take coercions into account
-- We use `withReducible` to make sure we don't spend too much time unfolding definitions
-- Alternative: use default and small number of heartbeats
withReducible <| withoutModifyingState <| isDefEq type expectedType
catch _ =>
return false
private def sortCompletionItems (items : Array CompletionItem) : Array CompletionItem :=
items.qsort fun i1 i2 => i1.label < i2.label
private def mkCompletionItem (label : Name) (type : Expr) : MetaM CompletionItem := do
let detail ← Meta.ppExpr (← consumeImplicitPrefix type)
return { label := label.getString!, detail? := some (toString detail), documentation? := none }
structure State where
itemsMain : Array CompletionItem := #[]
itemsOther : Array CompletionItem := #[]
abbrev M := OptionT $ StateRefT State MetaM
private def addCompletionItem (label : Name) (type : Expr) (expectedType? : Option Expr) : M Unit := do
let item ← mkCompletionItem label type
if (← isTypeApplicable type expectedType?) then
modify fun s => { s with itemsMain := s.itemsMain.push item }
else
modify fun s => { s with itemsOther := s.itemsOther.push item }
private def addCompletionItemForDecl (label : Name) (declName : Name) (expectedType? : Option Expr) : M Unit := do
if let some c ← (← getEnv).find? declName then
addCompletionItem label c.type expectedType?
private def runM (ctx : ContextInfo) (lctx : LocalContext) (x : M Unit) : IO (Option CompletionList) :=
ctx.runMetaM lctx do
match (← x.run |>.run {}) with
| (none, _) => return none
| (some _, s) =>
return some { items := sortCompletionItems s.itemsMain ++ sortCompletionItems s.itemsOther, isIncomplete := true }
private def matchAtomic (id: Name) (declName : Name) : Bool :=
match id, declName with
| Name.str Name.anonymous s₁ _, Name.str Name.anonymous s₂ _ => s₁.isPrefixOf s₂
| _, _ => false
private def normPrivateName (declName : Name) : MetaM Name := do
match privateToUserName? declName with
| none => return declName
| some userName =>
if mkPrivateName (← getEnv) userName == declName then
return userName
else
return declName
/--
Return the auto-completion label if `id` can be auto completed using `declName` assuming namespace `ns` is open.
This function only succeeds with atomic labels. BTW, it seems most clients only use the last part.
Remark: `danglingDot == true` when the completion point is an identifier followed by `.`.
-/
private def matchDecl? (ns : Name) (id : Name) (danglingDot : Bool) (declName : Name) : MetaM (Option Name) := do
-- dbg_trace "{ns}, {id}, {declName}, {danglingDot}"
let declName ← normPrivateName declName
if !ns.isPrefixOf declName then
return none
else
let declName := declName.replacePrefix ns Name.anonymous
if id.isPrefixOf declName && danglingDot then
let declName := declName.replacePrefix id Name.anonymous
if declName.isAtomic && !declName.isAnonymous then
return some declName
else
return none
else if !danglingDot then
match id, declName with
| Name.str p₁ s₁ _, Name.str p₂ s₂ _ =>
if p₁ == p₂ && s₁.isPrefixOf s₂ then
return some s₂
else
return none
| _, _ => none
else
return none
private def idCompletionCore (ctx : ContextInfo) (id : Name) (danglingDot : Bool) (expectedType? : Option Expr) : M Unit := do
let id := id.eraseMacroScopes
-- dbg_trace ">> id {id} : {expectedType?}"
if id.isAtomic then
-- search for matches in the local context
for localDecl in (← getLCtx) do
if matchAtomic id localDecl.userName then
addCompletionItem localDecl.userName localDecl.type expectedType?
-- search for matches in the environment
let env ← getEnv
env.constants.forM fun declName c => do
unless (← isBlackListed declName) do
let matchUsingNamespace (ns : Name): M Bool := do
if let some label ← matchDecl? ns id danglingDot declName then
-- dbg_trace "matched with {id}, {declName}, {label}"
addCompletionItem label c.type expectedType?
return true
else
return false
if (← matchUsingNamespace Name.anonymous) then
return ()
-- use current namespace
let rec visitNamespaces (ns : Name) : M Bool := do
match ns with
| Name.str p .. => matchUsingNamespace ns <||> visitNamespaces p
| _ => return false
if (← visitNamespaces ctx.currNamespace) then
return ()
-- use open decls
for openDecl in ctx.openDecls do
match openDecl with
| OpenDecl.simple ns exs =>
unless exs.contains declName do
if (← matchUsingNamespace ns) then
return ()
| _ => pure ()
-- search explicitily open `ids`
for openDecl in ctx.openDecls do
match openDecl with
| OpenDecl.explicit openedId resolvedId =>
unless (← isBlackListed resolvedId) do
if matchAtomic id openedId then
addCompletionItemForDecl openedId resolvedId expectedType?
| _ => pure ()
-- search for aliases
getAliasState env |>.forM fun alias declNames => do
if matchAtomic id alias then
declNames.forM fun declName => do
unless (← isBlackListed declName) do
addCompletionItemForDecl alias declName expectedType?
-- TODO search macros
-- TODO search namespaces
private def idCompletion (ctx : ContextInfo) (lctx : LocalContext) (id : Name) (danglingDot : Bool) (expectedType? : Option Expr) : IO (Option CompletionList) :=
runM ctx lctx do
idCompletionCore ctx id danglingDot expectedType?
private def isDotCompletionMethod (typeName : Name) (info : ConstantInfo) : MetaM Bool :=
forallTelescopeReducing info.type fun xs _ => do
for x in xs do
let localDecl ← getLocalDecl x.fvarId!
let type := localDecl.type.consumeMData
if type.getAppFn.isConstOf typeName then
return true
return false
/--
Given a type, try to extract relevant type names for dot notation field completion.
We extract the type name, parent struct names, and unfold the type.
The process mimics the dot notation elaboration procedure at `App.lean` -/
private partial def getDotCompletionTypeNames (type : Expr) : MetaM NameSet :=
return (← visit type |>.run {}).2
where
visit (type : Expr) : StateRefT NameSet MetaM Unit := do
match type.getAppFn with
| Expr.const typeName .. =>
modify fun s => s.insert typeName
if isStructureLike (← getEnv) typeName then
for parentName in getAllParentStructures (← getEnv) typeName do
modify fun s => s.insert parentName
let type? ← try unfoldDefinition? type catch _ => pure none
match type? with
| some type => visit type
| none => pure ()
| _ => pure ()
private def dotCompletion (ctx : ContextInfo) (info : TermInfo) (expectedType? : Option Expr) : IO (Option CompletionList) :=
runM ctx info.lctx do
let nameSet ←
try
getDotCompletionTypeNames (← instantiateMVars (← inferType info.expr))
catch _ =>
pure {}
if nameSet.isEmpty then
if info.stx.isIdent then
idCompletionCore ctx info.stx.getId (danglingDot := false) expectedType?
else if info.stx.getKind == ``Lean.Parser.Term.completion && info.stx[0].isIdent then
idCompletionCore ctx info.stx[0].getId (danglingDot := true) expectedType?
else
failure
else
(← getEnv).constants.forM fun declName c => do
let typeName := (← normPrivateName declName).getPrefix
if nameSet.contains typeName then
unless (← isBlackListed c.name) do
if (← isDotCompletionMethod typeName c) then
addCompletionItem c.name.getString! c.type expectedType?
private def optionCompletion (ctx : ContextInfo) (stx : Syntax) : IO (Option CompletionList) :=
ctx.runMetaM {} do
let partialName := stx[1].getId
-- HACK(WN): unfold the type so ForIn works
let (decls : Std.RBMap _ _ _) ← getOptionDecls
let opts ← getOptions
let mut items := #[]
for ⟨name, decl⟩ in decls do
if partialName.isPrefixOf name ||
(match partialName, name with
| Name.str p₁ s₁ _, Name.str p₂ s₂ _ => p₁ == p₂ && s₁.isPrefixOf s₂
| _, _ => false) then
items := items.push
{ label := name.toString
detail? := s!"({opts.get name decl.defValue}), {decl.descr}"
documentation? := none }
return some { items := sortCompletionItems items, isIncomplete := true }
private def tacticCompletion (ctx : ContextInfo) : IO (Option CompletionList) :=
-- Just return the list of tactics for now.
ctx.runMetaM {} do
let table := Parser.getCategory (Parser.parserExtension.getState (← getEnv)).categories `tactic |>.get!.tables.leadingTable
let items : Array CompletionItem := table.fold (init := #[]) fun items tk parser =>
-- TODO pretty print tactic syntax
items.push { label := tk.toString, detail? := none, documentation? := none }
return some { items := sortCompletionItems items, isIncomplete := true }
partial def find? (fileMap : FileMap) (hoverPos : String.Pos) (infoTree : InfoTree) : IO (Option CompletionList) := do
let ⟨hoverLine, _⟩ := fileMap.toPosition hoverPos
match infoTree.foldInfo (init := none) (choose fileMap hoverLine) with
| some (ctx, Info.ofCompletionInfo info) =>
match info with
| CompletionInfo.dot info (expectedType? := expectedType?) .. => dotCompletion ctx info expectedType?
| CompletionInfo.id stx id danglingDot lctx expectedType? => idCompletion ctx lctx id danglingDot expectedType?
| CompletionInfo.option stx => optionCompletion ctx stx
| CompletionInfo.tactic .. => tacticCompletion ctx
| _ => return none
| _ =>
-- TODO try to extract id from `fileMap` and some `ContextInfo` from `InfoTree`
return none
where
choose (fileMap : FileMap) (hoverLine : Nat) (ctx : ContextInfo) (info : Info) (best? : Option (ContextInfo × Info)) : Option (ContextInfo × Info) :=
if !info.isCompletion then best?
else if let some d := info.occursBefore? hoverPos then
let pos := info.tailPos?.get!
let ⟨line, _⟩ := fileMap.toPosition pos
if line != hoverLine then best?
else match best? with
| none => return (ctx, info)
| some (_, best) =>
let dBest := best.occursBefore? hoverPos |>.get!
if d < dBest || (d == dBest && info.isSmaller best) then
return (ctx, info)
else
best?
else
best?
end Lean.Server.Completion
|
e6ce31c33abe07f2a2dffbf0eb0a9652e3b80581 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/algebraic_geometry/prime_spectrum.lean | 35c54069462b03fbad19432d0e110243e9f03d63 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 13,562 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import topology.opens
import ring_theory.ideal.operations
import linear_algebra.finsupp
import algebra.punit_instances
/-!
# Prime spectrum of a commutative ring
The prime spectrum of a commutative ring is the type of all prime ideals.
It is naturally endowed with a topology: the Zariski topology.
(It is also naturally endowed with a sheaf of rings,
which is constructed in `algebraic_geometry.structure_sheaf`.)
## Main definitions
* `prime_spectrum R`: The prime spectrum of a commutative ring `R`,
i.e., the set of all prime ideals of `R`.
* `zero_locus s`: The zero locus of a subset `s` of `R`
is the subset of `prime_spectrum R` consisting of all prime ideals that contain `s`.
* `vanishing_ideal t`: The vanishing ideal of a subset `t` of `prime_spectrum R`
is the intersection of points in `t` (viewed as prime ideals).
## Conventions
We denote subsets of rings with `s`, `s'`, etc...
whereas we denote subsets of prime spectra with `t`, `t'`, etc...
## Inspiration/contributors
The contents of this file draw inspiration from
<https://github.com/ramonfmir/lean-scheme>
which has contributions from Ramon Fernandez Mir, Kevin Buzzard, Kenny Lau,
and Chris Hughes (on an earlier repository).
-/
noncomputable theory
open_locale classical
universe variables u v
variables (R : Type u) [comm_ring R]
/-- The prime spectrum of a commutative ring `R`
is the type of all prime ideals of `R`.
It is naturally endowed with a topology (the Zariski topology),
and a sheaf of commutative rings (see `algebraic_geometry.structure_sheaf`).
It is a fundamental building block in algebraic geometry. -/
@[nolint has_inhabited_instance]
def prime_spectrum := {I : ideal R // I.is_prime}
variable {R}
namespace prime_spectrum
/-- A method to view a point in the prime spectrum of a commutative ring
as an ideal of that ring. -/
abbreviation as_ideal (x : prime_spectrum R) : ideal R := x.val
instance is_prime (x : prime_spectrum R) :
x.as_ideal.is_prime := x.2
/--
The prime spectrum of the zero ring is empty.
-/
lemma punit (x : prime_spectrum punit) : false :=
x.1.ne_top_iff_one.1 x.2.1 $ subsingleton.elim (0 : punit) 1 ▸ x.1.zero_mem
@[ext] lemma ext {x y : prime_spectrum R} :
x = y ↔ x.as_ideal = y.as_ideal :=
subtype.ext_iff_val
/-- The zero locus of a set `s` of elements of a commutative ring `R`
is the set of all prime ideals of the ring that contain the set `s`.
An element `f` of `R` can be thought of as a dependent function
on the prime spectrum of `R`.
At a point `x` (a prime ideal)
the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`.
In this manner, `zero_locus s` is exactly the subset of `prime_spectrum R`
where all "functions" in `s` vanish simultaneously.
-/
def zero_locus (s : set R) : set (prime_spectrum R) :=
{x | s ⊆ x.as_ideal}
@[simp] lemma mem_zero_locus (x : prime_spectrum R) (s : set R) :
x ∈ zero_locus s ↔ s ⊆ x.as_ideal := iff.rfl
@[simp] lemma zero_locus_span (s : set R) :
zero_locus (ideal.span s : set R) = zero_locus s :=
by { ext x, exact (submodule.gi R R).gc s x.as_ideal }
/-- The vanishing ideal of a set `t` of points
of the prime spectrum of a commutative ring `R`
is the intersection of all the prime ideals in the set `t`.
An element `f` of `R` can be thought of as a dependent function
on the prime spectrum of `R`.
At a point `x` (a prime ideal)
the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`.
In this manner, `vanishing_ideal t` is exactly the ideal of `R`
consisting of all "functions" that vanish on all of `t`.
-/
def vanishing_ideal (t : set (prime_spectrum R)) : ideal R :=
⨅ (x : prime_spectrum R) (h : x ∈ t), x.as_ideal
lemma coe_vanishing_ideal (t : set (prime_spectrum R)) :
(vanishing_ideal t : set R) = {f : R | ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal} :=
begin
ext f,
rw [vanishing_ideal, submodule.mem_coe, submodule.mem_infi],
apply forall_congr, intro x,
rw [submodule.mem_infi],
end
lemma mem_vanishing_ideal (t : set (prime_spectrum R)) (f : R) :
f ∈ vanishing_ideal t ↔ ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal :=
by rw [← submodule.mem_coe, coe_vanishing_ideal, set.mem_set_of_eq]
lemma subset_zero_locus_iff_le_vanishing_ideal (t : set (prime_spectrum R)) (I : ideal R) :
t ⊆ zero_locus I ↔ I ≤ vanishing_ideal t :=
begin
split; intro h,
{ intros f hf,
rw [mem_vanishing_ideal],
intros x hx,
have hxI := h hx,
rw mem_zero_locus at hxI,
exact hxI hf },
{ intros x hx,
rw mem_zero_locus,
refine le_trans h _,
intros f hf,
rw [mem_vanishing_ideal] at hf,
exact hf x hx }
end
section gc
variable (R)
/-- `zero_locus` and `vanishing_ideal` form a galois connection. -/
lemma gc : @galois_connection
(ideal R) (order_dual (set (prime_spectrum R))) _ _
(λ I, zero_locus I) (λ t, vanishing_ideal t) :=
λ I t, subset_zero_locus_iff_le_vanishing_ideal t I
/-- `zero_locus` and `vanishing_ideal` form a galois connection. -/
lemma gc_set : @galois_connection
(set R) (order_dual (set (prime_spectrum R))) _ _
(λ s, zero_locus s) (λ t, vanishing_ideal t) :=
have ideal_gc : galois_connection (ideal.span) coe := (submodule.gi R R).gc,
by simpa [zero_locus_span, function.comp] using galois_connection.compose _ _ _ _ ideal_gc (gc R)
lemma subset_zero_locus_iff_subset_vanishing_ideal (t : set (prime_spectrum R)) (s : set R) :
t ⊆ zero_locus s ↔ s ⊆ vanishing_ideal t :=
(gc_set R) s t
end gc
-- TODO: we actually get the radical ideal,
-- but I think that isn't in mathlib yet.
lemma subset_vanishing_ideal_zero_locus (s : set R) :
s ⊆ vanishing_ideal (zero_locus s) :=
(gc_set R).le_u_l s
lemma le_vanishing_ideal_zero_locus (I : ideal R) :
I ≤ vanishing_ideal (zero_locus I) :=
(gc R).le_u_l I
lemma subset_zero_locus_vanishing_ideal (t : set (prime_spectrum R)) :
t ⊆ zero_locus (vanishing_ideal t) :=
(gc R).l_u_le t
lemma zero_locus_bot :
zero_locus ((⊥ : ideal R) : set R) = set.univ :=
(gc R).l_bot
@[simp] lemma zero_locus_singleton_zero :
zero_locus (0 : set R) = set.univ :=
zero_locus_bot
@[simp] lemma zero_locus_empty :
zero_locus (∅ : set R) = set.univ :=
(gc_set R).l_bot
@[simp] lemma vanishing_ideal_univ :
vanishing_ideal (∅ : set (prime_spectrum R)) = ⊤ :=
by simpa using (gc R).u_top
lemma zero_locus_empty_of_one_mem {s : set R} (h : (1:R) ∈ s) :
zero_locus s = ∅ :=
begin
rw set.eq_empty_iff_forall_not_mem,
intros x hx,
rw mem_zero_locus at hx,
have x_prime : x.as_ideal.is_prime := by apply_instance,
have eq_top : x.as_ideal = ⊤, { rw ideal.eq_top_iff_one, exact hx h },
apply x_prime.1 eq_top,
end
lemma zero_locus_empty_iff_eq_top {I : ideal R} :
zero_locus (I : set R) = ∅ ↔ I = ⊤ :=
begin
split,
{ contrapose!,
intro h,
apply set.ne_empty_iff_nonempty.mpr,
rcases ideal.exists_le_maximal I h with ⟨M, hM, hIM⟩,
exact ⟨⟨M, hM.is_prime⟩, hIM⟩ },
{ rintro rfl, apply zero_locus_empty_of_one_mem, trivial }
end
@[simp] lemma zero_locus_univ :
zero_locus (set.univ : set R) = ∅ :=
zero_locus_empty_of_one_mem (set.mem_univ 1)
lemma zero_locus_sup (I J : ideal R) :
zero_locus ((I ⊔ J : ideal R) : set R) = zero_locus I ∩ zero_locus J :=
(gc R).l_sup
lemma zero_locus_union (s s' : set R) :
zero_locus (s ∪ s') = zero_locus s ∩ zero_locus s' :=
(gc_set R).l_sup
lemma vanishing_ideal_union (t t' : set (prime_spectrum R)) :
vanishing_ideal (t ∪ t') = vanishing_ideal t ⊓ vanishing_ideal t' :=
(gc R).u_inf
lemma zero_locus_supr {ι : Sort*} (I : ι → ideal R) :
zero_locus ((⨆ i, I i : ideal R) : set R) = (⋂ i, zero_locus (I i)) :=
(gc R).l_supr
lemma zero_locus_Union {ι : Sort*} (s : ι → set R) :
zero_locus (⋃ i, s i) = (⋂ i, zero_locus (s i)) :=
(gc_set R).l_supr
lemma vanishing_ideal_Union {ι : Sort*} (t : ι → set (prime_spectrum R)) :
vanishing_ideal (⋃ i, t i) = (⨅ i, vanishing_ideal (t i)) :=
(gc R).u_infi
lemma zero_locus_inf (I J : ideal R) :
zero_locus ((I ⊓ J : ideal R) : set R) = zero_locus I ∪ zero_locus J :=
begin
ext x,
split,
{ rintro h,
rw set.mem_union,
simp only [mem_zero_locus] at h ⊢,
-- TODO: The rest of this proof should be factored out.
rw or_iff_not_imp_right,
intros hs r hr,
rw set.not_subset at hs,
rcases hs with ⟨s, hs1, hs2⟩,
apply (ideal.is_prime.mem_or_mem (by apply_instance) _).resolve_left hs2,
apply h,
split,
{ exact ideal.mul_mem_left _ hr },
{ exact ideal.mul_mem_right _ hs1 } },
{ rintro (h|h),
all_goals
{ rw mem_zero_locus at h ⊢,
refine set.subset.trans _ h,
intros r hr, cases hr, assumption } }
end
lemma union_zero_locus (s s' : set R) :
zero_locus s ∪ zero_locus s' = zero_locus ((ideal.span s) ⊓ (ideal.span s') : ideal R) :=
by { rw zero_locus_inf, simp }
lemma sup_vanishing_ideal_le (t t' : set (prime_spectrum R)) :
vanishing_ideal t ⊔ vanishing_ideal t' ≤ vanishing_ideal (t ∩ t') :=
begin
intros r,
rw [submodule.mem_sup, mem_vanishing_ideal],
rintro ⟨f, hf, g, hg, rfl⟩ x ⟨hxt, hxt'⟩,
rw mem_vanishing_ideal at hf hg,
apply submodule.add_mem; solve_by_elim
end
/-- The Zariski topology on the prime spectrum of a commutative ring
is defined via the closed sets of the topology:
they are exactly those sets that are the zero locus of a subset of the ring. -/
instance zariski_topology : topological_space (prime_spectrum R) :=
topological_space.of_closed (set.range prime_spectrum.zero_locus)
(⟨set.univ, by simp⟩)
begin
intros Zs h,
rw set.sInter_eq_Inter,
let f : Zs → set R := λ i, classical.some (h i.2),
have hf : ∀ i : Zs, ↑i = zero_locus (f i) := λ i, (classical.some_spec (h i.2)).symm,
simp only [hf],
exact ⟨_, zero_locus_Union _⟩
end
(by { rintro _ _ ⟨s, rfl⟩ ⟨t, rfl⟩, exact ⟨_, (union_zero_locus s t).symm⟩ })
lemma is_open_iff (U : set (prime_spectrum R)) :
is_open U ↔ ∃ s, Uᶜ = zero_locus s :=
by simp only [@eq_comm _ Uᶜ]; refl
lemma is_closed_iff_zero_locus (Z : set (prime_spectrum R)) :
is_closed Z ↔ ∃ s, Z = zero_locus s :=
by rw [is_closed, is_open_iff, set.compl_compl]
lemma is_closed_zero_locus (s : set R) :
is_closed (zero_locus s) :=
by { rw [is_closed_iff_zero_locus], exact ⟨s, rfl⟩ }
section comap
variables {S : Type v} [comm_ring S] {S' : Type*} [comm_ring S']
/-- The function between prime spectra of commutative rings induced by a ring homomorphism.
This function is continuous. -/
def comap (f : R →+* S) : prime_spectrum S → prime_spectrum R :=
λ y, ⟨ideal.comap f y.as_ideal, by exact ideal.is_prime.comap _⟩
variables (f : R →+* S)
@[simp] lemma comap_as_ideal (y : prime_spectrum S) :
(comap f y).as_ideal = ideal.comap f y.as_ideal :=
rfl
@[simp] lemma comap_id : comap (ring_hom.id R) = id :=
funext $ λ x, ext.mpr $ by { rw [comap_as_ideal], apply ideal.ext, intros r, simp }
@[simp] lemma comap_comp (f : R →+* S) (g : S →+* S') :
comap (g.comp f) = comap f ∘ comap g :=
funext $ λ x, ext.mpr $ by { simp, refl }
@[simp] lemma preimage_comap_zero_locus (s : set R) :
(comap f) ⁻¹' (zero_locus s) = zero_locus (f '' s) :=
begin
ext x,
simp only [mem_zero_locus, set.mem_preimage, comap_as_ideal, set.image_subset_iff],
refl
end
lemma comap_continuous (f : R →+* S) : continuous (comap f) :=
begin
rw continuous_iff_is_closed,
simp only [is_closed_iff_zero_locus],
rintro _ ⟨s, rfl⟩,
exact ⟨_, preimage_comap_zero_locus f s⟩
end
end comap
lemma zero_locus_vanishing_ideal_eq_closure (t : set (prime_spectrum R)) :
zero_locus (vanishing_ideal t : set R) = closure t :=
begin
apply set.subset.antisymm,
{ rintro x hx t' ⟨ht', ht⟩,
obtain ⟨fs, rfl⟩ : ∃ s, t' = zero_locus s,
by rwa [is_closed_iff_zero_locus] at ht',
rw [subset_zero_locus_iff_subset_vanishing_ideal] at ht,
calc fs ⊆ vanishing_ideal t : ht
... ⊆ x.as_ideal : hx },
{ rw (is_closed_zero_locus _).closure_subset_iff,
exact subset_zero_locus_vanishing_ideal t }
end
/-- The prime spectrum of a commutative ring is a compact topological space. -/
instance : compact_space (prime_spectrum R) :=
begin
apply compact_space_of_finite_subfamily_closed,
intros ι Z hZc hZ,
let I : ι → ideal R := λ i, vanishing_ideal (Z i),
have hI : ∀ i, Z i = zero_locus (I i),
{ intro i,
rw [zero_locus_vanishing_ideal_eq_closure, is_closed.closure_eq],
exact hZc i },
have one_mem : (1:R) ∈ ⨆ (i : ι), I i,
{ rw [← ideal.eq_top_iff_one, ← zero_locus_empty_iff_eq_top, zero_locus_supr],
simpa only [hI] using hZ },
obtain ⟨s, hs⟩ : ∃ s : finset ι, (1:R) ∈ ⨆ i ∈ s, I i :=
submodule.exists_finset_of_mem_supr I one_mem,
show ∃ t : finset ι, (⋂ i ∈ t, Z i) = ∅,
use s,
rw [← ideal.eq_top_iff_one, ←zero_locus_empty_iff_eq_top] at hs,
simpa only [zero_locus_supr, hI] using hs
end
section basic_open
/-- `basic_open r` is the open subset containing all prime ideals not containing `r`. -/
def basic_open (r : R) : topological_space.opens (prime_spectrum R) :=
{ val := { x | r ∉ x.as_ideal },
property := ⟨{r}, set.ext $ λ x, set.singleton_subset_iff.trans $ not_not.symm⟩ }
end basic_open
end prime_spectrum
|
f19887ba739dab19f7a3a1ed7bcad28158902def | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/analysis/special_functions/integrals.lean | 8d471226dd47720658c6caf8cd72fc8595b4bfb0 | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,944 | lean | /-
Copyright (c) 2021 Benjamin Davidson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Benjamin Davidson
-/
import measure_theory.integral.interval_integral
/-!
# Integration of specific interval integrals
This file contains proofs of the integrals of various specific functions. This includes:
* Integrals of simple functions, such as `id`, `pow`, `inv`, `exp`, `log`
* Integrals of some trigonometric functions, such as `sin`, `cos`, `1 / (1 + x^2)`
* The integral of `cos x ^ 2 - sin x ^ 2`
* Reduction formulae for the integrals of `sin x ^ n` and `cos x ^ n` for `n ≥ 2`
* The computation of `∫ x in 0..π, sin x ^ n` as a product for even and odd `n` (used in proving the
Wallis product for pi)
* Integrals of the form `sin x ^ m * cos x ^ n`
With these lemmas, many simple integrals can be computed by `simp` or `norm_num`.
See `test/integration.lean` for specific examples.
This file also contains some facts about the interval integrability of specific functions.
This file is still being developed.
## Tags
integrate, integration, integrable, integrability
-/
open real nat set finset
open_locale real big_operators
variables {a b : ℝ} (n : ℕ)
namespace interval_integral
open measure_theory
variables {f : ℝ → ℝ} {μ ν : measure ℝ} [locally_finite_measure μ] (c d : ℝ)
/-! ### Interval integrability -/
@[simp]
lemma interval_integrable_pow : interval_integrable (λ x, x^n) μ a b :=
(continuous_pow n).interval_integrable a b
@[simp]
lemma interval_integrable_id : interval_integrable (λ x, x) μ a b :=
continuous_id.interval_integrable a b
@[simp]
lemma interval_integrable_const : interval_integrable (λ x, c) μ a b :=
continuous_const.interval_integrable a b
@[simp]
lemma interval_integrable.const_mul (h : interval_integrable f ν a b) :
interval_integrable (λ x, c * f x) ν a b :=
by convert h.smul c
@[simp]
lemma interval_integrable.mul_const (h : interval_integrable f ν a b) :
interval_integrable (λ x, f x * c) ν a b :=
by simp only [mul_comm, interval_integrable.const_mul c h]
@[simp]
lemma interval_integrable.div (h : interval_integrable f ν a b) :
interval_integrable (λ x, f x / c) ν a b :=
interval_integrable.mul_const c⁻¹ h
lemma interval_integrable_one_div (h : ∀ x : ℝ, x ∈ interval a b → f x ≠ 0)
(hf : continuous_on f (interval a b)) :
interval_integrable (λ x, 1 / f x) μ a b :=
(continuous_on_const.div hf h).interval_integrable
@[simp]
lemma interval_integrable_inv (h : ∀ x : ℝ, x ∈ interval a b → f x ≠ 0)
(hf : continuous_on f (interval a b)) :
interval_integrable (λ x, (f x)⁻¹) μ a b :=
by simpa only [one_div] using interval_integrable_one_div h hf
@[simp]
lemma interval_integrable_exp : interval_integrable exp μ a b :=
continuous_exp.interval_integrable a b
@[simp]
lemma interval_integrable.log
(hf : continuous_on f (interval a b)) (h : ∀ x : ℝ, x ∈ interval a b → f x ≠ 0) :
interval_integrable (λ x, log (f x)) μ a b :=
(continuous_on.log hf h).interval_integrable
@[simp]
lemma interval_integrable_log (h : (0:ℝ) ∉ interval a b) :
interval_integrable log μ a b :=
interval_integrable.log continuous_on_id $ λ x hx, ne_of_mem_of_not_mem hx h
@[simp]
lemma interval_integrable_sin : interval_integrable sin μ a b :=
continuous_sin.interval_integrable a b
@[simp]
lemma interval_integrable_cos : interval_integrable cos μ a b :=
continuous_cos.interval_integrable a b
lemma interval_integrable_one_div_one_add_sq : interval_integrable (λ x : ℝ, 1 / (1 + x^2)) μ a b :=
begin
refine (continuous_const.div _ (λ x, _)).interval_integrable a b,
{ continuity },
{ nlinarith },
end
@[simp]
lemma interval_integrable_inv_one_add_sq : interval_integrable (λ x : ℝ, (1 + x^2)⁻¹) μ a b :=
by simpa only [one_div] using interval_integrable_one_div_one_add_sq
/-! ### Integral of a function scaled by a constant -/
@[simp]
lemma integral_const_mul : ∫ x in a..b, c * f x = c * ∫ x in a..b, f x :=
integral_smul c
@[simp]
lemma integral_mul_const : ∫ x in a..b, f x * c = (∫ x in a..b, f x) * c :=
by simp only [mul_comm, integral_const_mul]
@[simp]
lemma integral_div : ∫ x in a..b, f x / c = (∫ x in a..b, f x) / c :=
integral_mul_const c⁻¹
/-! ### Integrals of the form `c * ∫ x in a..b, f (c * x + d)` -/
@[simp]
lemma mul_integral_comp_mul_right : c * ∫ x in a..b, f (x * c) = ∫ x in a*c..b*c, f x :=
smul_integral_comp_mul_right f c
@[simp]
lemma mul_integral_comp_mul_left : c * ∫ x in a..b, f (c * x) = ∫ x in c*a..c*b, f x :=
smul_integral_comp_mul_left f c
@[simp]
lemma inv_mul_integral_comp_div : c⁻¹ * ∫ x in a..b, f (x / c) = ∫ x in a/c..b/c, f x :=
inv_smul_integral_comp_div f c
@[simp]
lemma mul_integral_comp_mul_add : c * ∫ x in a..b, f (c * x + d) = ∫ x in c*a+d..c*b+d, f x :=
smul_integral_comp_mul_add f c d
@[simp]
lemma mul_integral_comp_add_mul : c * ∫ x in a..b, f (d + c * x) = ∫ x in d+c*a..d+c*b, f x :=
smul_integral_comp_add_mul f c d
@[simp]
lemma inv_mul_integral_comp_div_add : c⁻¹ * ∫ x in a..b, f (x / c + d) = ∫ x in a/c+d..b/c+d, f x :=
inv_smul_integral_comp_div_add f c d
@[simp]
lemma inv_mul_integral_comp_add_div : c⁻¹ * ∫ x in a..b, f (d + x / c) = ∫ x in d+a/c..d+b/c, f x :=
inv_smul_integral_comp_add_div f c d
@[simp]
lemma mul_integral_comp_mul_sub : c * ∫ x in a..b, f (c * x - d) = ∫ x in c*a-d..c*b-d, f x :=
smul_integral_comp_mul_sub f c d
@[simp]
lemma mul_integral_comp_sub_mul : c * ∫ x in a..b, f (d - c * x) = ∫ x in d-c*b..d-c*a, f x :=
smul_integral_comp_sub_mul f c d
@[simp]
lemma inv_mul_integral_comp_div_sub : c⁻¹ * ∫ x in a..b, f (x / c - d) = ∫ x in a/c-d..b/c-d, f x :=
inv_smul_integral_comp_div_sub f c d
@[simp]
lemma inv_mul_integral_comp_sub_div : c⁻¹ * ∫ x in a..b, f (d - x / c) = ∫ x in d-b/c..d-a/c, f x :=
inv_smul_integral_comp_sub_div f c d
end interval_integral
open interval_integral
/-! ### Integrals of simple functions -/
@[simp]
lemma integral_pow : ∫ x in a..b, x ^ n = (b ^ (n + 1) - a ^ (n + 1)) / (n + 1) :=
begin
have hderiv : deriv (λ x : ℝ, x ^ (n + 1) / (n + 1)) = λ x, x ^ n,
{ ext,
have hne : (n + 1 : ℝ) ≠ 0 := by exact_mod_cast succ_ne_zero n,
simp [mul_div_assoc, mul_div_cancel' _ hne] },
rw integral_deriv_eq_sub' _ hderiv;
norm_num [div_sub_div_same, continuous_on_pow],
end
@[simp]
lemma integral_id : ∫ x in a..b, x = (b ^ 2 - a ^ 2) / 2 :=
by simpa using integral_pow 1
@[simp]
lemma integral_one : ∫ x in a..b, (1 : ℝ) = b - a :=
by simp only [mul_one, smul_eq_mul, integral_const]
@[simp]
lemma integral_inv (h : (0:ℝ) ∉ interval a b) : ∫ x in a..b, x⁻¹ = log (b / a) :=
begin
have h' := λ x hx, ne_of_mem_of_not_mem hx h,
rw [integral_deriv_eq_sub' _ deriv_log' (λ x hx, differentiable_at_log (h' x hx))
(continuous_on_inv'.mono $ subset_compl_singleton_iff.mpr h),
log_div (h' b right_mem_interval) (h' a left_mem_interval)],
end
@[simp]
lemma integral_inv_of_pos (ha : 0 < a) (hb : 0 < b) : ∫ x in a..b, x⁻¹ = log (b / a) :=
integral_inv $ not_mem_interval_of_lt ha hb
@[simp]
lemma integral_inv_of_neg (ha : a < 0) (hb : b < 0) : ∫ x in a..b, x⁻¹ = log (b / a) :=
integral_inv $ not_mem_interval_of_gt ha hb
lemma integral_one_div (h : (0:ℝ) ∉ interval a b) : ∫ x : ℝ in a..b, 1/x = log (b / a) :=
by simp only [one_div, integral_inv h]
lemma integral_one_div_of_pos (ha : 0 < a) (hb : 0 < b) : ∫ x : ℝ in a..b, 1/x = log (b / a) :=
by simp only [one_div, integral_inv_of_pos ha hb]
lemma integral_one_div_of_neg (ha : a < 0) (hb : b < 0) : ∫ x : ℝ in a..b, 1/x = log (b / a) :=
by simp only [one_div, integral_inv_of_neg ha hb]
@[simp]
lemma integral_exp : ∫ x in a..b, exp x = exp b - exp a :=
by rw integral_deriv_eq_sub'; norm_num [continuous_on_exp]
@[simp]
lemma integral_log (h : (0:ℝ) ∉ interval a b) :
∫ x in a..b, log x = b * log b - a * log a - b + a :=
begin
obtain ⟨h', heq⟩ := ⟨λ x hx, ne_of_mem_of_not_mem hx h, λ x hx, mul_inv_cancel (h' x hx)⟩,
convert integral_mul_deriv_eq_deriv_mul (λ x hx, has_deriv_at_log (h' x hx))
(λ x hx, has_deriv_at_id x) (continuous_on_inv'.mono $ subset_compl_singleton_iff.mpr h)
continuous_on_const using 1; simp [integral_congr heq, mul_comm, ← sub_add],
end
@[simp]
lemma integral_log_of_pos (ha : 0 < a) (hb : 0 < b) :
∫ x in a..b, log x = b * log b - a * log a - b + a :=
integral_log $ not_mem_interval_of_lt ha hb
@[simp]
lemma integral_log_of_neg (ha : a < 0) (hb : b < 0) :
∫ x in a..b, log x = b * log b - a * log a - b + a :=
integral_log $ not_mem_interval_of_gt ha hb
@[simp]
lemma integral_sin : ∫ x in a..b, sin x = cos a - cos b :=
by rw integral_deriv_eq_sub' (λ x, -cos x); norm_num [continuous_on_sin]
@[simp]
lemma integral_cos : ∫ x in a..b, cos x = sin b - sin a :=
by rw integral_deriv_eq_sub'; norm_num [continuous_on_cos]
lemma integral_cos_sq_sub_sin_sq :
∫ x in a..b, cos x ^ 2 - sin x ^ 2 = sin b * cos b - sin a * cos a :=
by simpa only [sq, sub_eq_add_neg, neg_mul_eq_mul_neg] using integral_deriv_mul_eq_sub
(λ x hx, has_deriv_at_sin x) (λ x hx, has_deriv_at_cos x) continuous_on_cos continuous_on_sin.neg
@[simp]
lemma integral_inv_one_add_sq : ∫ x : ℝ in a..b, (1 + x^2)⁻¹ = arctan b - arctan a :=
begin
simp only [← one_div],
refine integral_deriv_eq_sub' _ _ _ (continuous_const.div _ (λ x, _)).continuous_on,
{ norm_num },
{ norm_num },
{ continuity },
{ nlinarith },
end
lemma integral_one_div_one_add_sq : ∫ x : ℝ in a..b, 1 / (1 + x^2) = arctan b - arctan a :=
by simp only [one_div, integral_inv_one_add_sq]
/-! ### Integral of `sin x ^ n` -/
lemma integral_sin_pow_aux :
∫ x in a..b, sin x ^ (n + 2) = sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b
+ (n + 1) * (∫ x in a..b, sin x ^ n) - (n + 1) * ∫ x in a..b, sin x ^ (n + 2) :=
begin
let C := sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b,
have h : ∀ α β γ : ℝ, α * (β * α * γ) = β * (α * α * γ) := λ α β γ, by ring,
have hu : ∀ x ∈ _, has_deriv_at (λ y, sin y ^ (n + 1)) ((n + 1) * cos x * sin x ^ n) x :=
λ x hx, by simpa [mul_right_comm] using (has_deriv_at_sin x).pow,
have hv : ∀ x ∈ interval a b, has_deriv_at (-cos) (sin x) x :=
λ x hx, by simpa only [neg_neg] using (has_deriv_at_cos x).neg,
have H := integral_mul_deriv_eq_deriv_mul hu hv _ _,
calc ∫ x in a..b, sin x ^ (n + 2)
= ∫ x in a..b, sin x ^ (n + 1) * sin x : by simp only [pow_succ']
... = C + (n + 1) * ∫ x in a..b, cos x ^ 2 * sin x ^ n : by simp [H, h, sq]
... = C + (n + 1) * ∫ x in a..b, sin x ^ n - sin x ^ (n + 2) : by simp [cos_sq', sub_mul,
← pow_add, add_comm]
... = C + (n + 1) * (∫ x in a..b, sin x ^ n) - (n + 1) * ∫ x in a..b, sin x ^ (n + 2) :
by rw [integral_sub, mul_sub, add_sub_assoc]; apply continuous.interval_integrable; continuity,
all_goals { apply continuous.continuous_on, continuity },
end
/-- The reduction formula for the integral of `sin x ^ n` for any natural `n ≥ 2`. -/
lemma integral_sin_pow :
∫ x in a..b, sin x ^ (n + 2) = (sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b) / (n + 2)
+ (n + 1) / (n + 2) * ∫ x in a..b, sin x ^ n :=
begin
have : (n : ℝ) + 2 ≠ 0 := by exact_mod_cast succ_ne_zero n.succ,
field_simp,
convert eq_sub_iff_add_eq.mp (integral_sin_pow_aux n),
ring,
end
@[simp]
lemma integral_sin_sq : ∫ x in a..b, sin x ^ 2 = (sin a * cos a - sin b * cos b + b - a) / 2 :=
by field_simp [integral_sin_pow, add_sub_assoc]
theorem integral_sin_pow_odd :
∫ x in 0..π, sin x ^ (2 * n + 1) = 2 * ∏ i in range n, (2 * i + 2) / (2 * i + 3) :=
begin
induction n with k ih, { norm_num },
rw [prod_range_succ_comm, mul_left_comm, ← ih, mul_succ, integral_sin_pow],
norm_cast,
simp [-cast_add] with field_simps,
end
theorem integral_sin_pow_even :
∫ x in 0..π, sin x ^ (2 * n) = π * ∏ i in range n, (2 * i + 1) / (2 * i + 2) :=
begin
induction n with k ih, { simp },
rw [prod_range_succ_comm, mul_left_comm, ← ih, mul_succ, integral_sin_pow],
norm_cast,
simp [-cast_add] with field_simps,
end
lemma integral_sin_pow_pos : 0 < ∫ x in 0..π, sin x ^ n :=
begin
rcases even_or_odd' n with ⟨k, (rfl | rfl)⟩;
simp only [integral_sin_pow_even, integral_sin_pow_odd];
refine mul_pos (by norm_num [pi_pos]) (prod_pos (λ n hn, div_pos _ _));
norm_cast;
linarith,
end
lemma integral_sin_pow_antimono : ∫ x in 0..π, sin x ^ (n + 1) ≤ ∫ x in 0..π, sin x ^ n :=
let H := λ x h, pow_le_pow_of_le_one (sin_nonneg_of_mem_Icc h) (sin_le_one x) (n.le_add_right 1) in
by refine integral_mono_on pi_pos.le _ _ H; exact (continuous_sin.pow _).interval_integrable 0 π
/-! ### Integral of `cos x ^ n` -/
lemma integral_cos_pow_aux :
∫ x in a..b, cos x ^ (n + 2) = cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a
+ (n + 1) * (∫ x in a..b, cos x ^ n) - (n + 1) * ∫ x in a..b, cos x ^ (n + 2) :=
begin
let C := cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a,
have h : ∀ α β γ : ℝ, α * (β * α * γ) = β * (α * α * γ) := λ α β γ, by ring,
have hu : ∀ x ∈ _, has_deriv_at (λ y, cos y ^ (n + 1)) (-(n + 1) * sin x * cos x ^ n) x :=
λ x hx, by simpa [mul_right_comm, -neg_add_rev] using (has_deriv_at_cos x).pow,
have hv : ∀ x ∈ interval a b, has_deriv_at sin (cos x) x := λ x hx, has_deriv_at_sin x,
have H := integral_mul_deriv_eq_deriv_mul hu hv _ _,
calc ∫ x in a..b, cos x ^ (n + 2)
= ∫ x in a..b, cos x ^ (n + 1) * cos x : by simp only [pow_succ']
... = C + (n + 1) * ∫ x in a..b, sin x ^ 2 * cos x ^ n : by simp [H, h, sq, -neg_add_rev]
... = C + (n + 1) * ∫ x in a..b, cos x ^ n - cos x ^ (n + 2) : by simp [sin_sq, sub_mul,
← pow_add, add_comm]
... = C + (n + 1) * (∫ x in a..b, cos x ^ n) - (n + 1) * ∫ x in a..b, cos x ^ (n + 2) :
by rw [integral_sub, mul_sub, add_sub_assoc]; apply continuous.interval_integrable; continuity,
all_goals { apply continuous.continuous_on, continuity },
end
/-- The reduction formula for the integral of `cos x ^ n` for any natural `n ≥ 2`. -/
lemma integral_cos_pow :
∫ x in a..b, cos x ^ (n + 2) = (cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a) / (n + 2)
+ (n + 1) / (n + 2) * ∫ x in a..b, cos x ^ n :=
begin
have : (n : ℝ) + 2 ≠ 0 := by exact_mod_cast succ_ne_zero n.succ,
field_simp,
convert eq_sub_iff_add_eq.mp (integral_cos_pow_aux n),
ring,
end
@[simp]
lemma integral_cos_sq : ∫ x in a..b, cos x ^ 2 = (cos b * sin b - cos a * sin a + b - a) / 2 :=
by field_simp [integral_cos_pow, add_sub_assoc]
/-! ### Integral of `sin x ^ m * cos x ^ n` -/
/-- Simplification of the integral of `sin x ^ m * cos x ^ n`, case `n` is odd. -/
lemma integral_sin_pow_mul_cos_pow_odd (m n : ℕ) :
∫ x in a..b, sin x ^ m * cos x ^ (2 * n + 1) = ∫ u in sin a..sin b, u ^ m * (1 - u ^ 2) ^ n :=
have hc : continuous (λ u : ℝ, u ^ m * (1 - u ^ 2) ^ n), by continuity,
calc ∫ x in a..b, sin x ^ m * cos x ^ (2 * n + 1)
= ∫ x in a..b, sin x ^ m * (1 - sin x ^ 2) ^ n * cos x : by simp only [pow_succ', ← mul_assoc,
pow_mul, cos_sq']
... = ∫ u in sin a..sin b, u ^ m * (1 - u ^ 2) ^ n : integral_comp_mul_deriv
(λ x hx, has_deriv_at_sin x)
continuous_on_cos hc
/-- The integral of `sin x * cos x`, given in terms of sin².
See `integral_sin_mul_cos₂` below for the integral given in terms of cos². -/
@[simp]
lemma integral_sin_mul_cos₁ :
∫ x in a..b, sin x * cos x = (sin b ^ 2 - sin a ^ 2) / 2 :=
by simpa using integral_sin_pow_mul_cos_pow_odd 1 0
@[simp]
lemma integral_sin_sq_mul_cos :
∫ x in a..b, sin x ^ 2 * cos x = (sin b ^ 3 - sin a ^ 3) / 3 :=
by simpa using integral_sin_pow_mul_cos_pow_odd 2 0
@[simp]
lemma integral_cos_pow_three :
∫ x in a..b, cos x ^ 3 = sin b - sin a - (sin b ^ 3 - sin a ^ 3) / 3 :=
by simpa using integral_sin_pow_mul_cos_pow_odd 0 1
/-- Simplification of the integral of `sin x ^ m * cos x ^ n`, case `m` is odd. -/
lemma integral_sin_pow_odd_mul_cos_pow (m n : ℕ) :
∫ x in a..b, sin x ^ (2 * m + 1) * cos x ^ n = ∫ u in cos b..cos a, u ^ n * (1 - u ^ 2) ^ m :=
have hc : continuous (λ u : ℝ, u ^ n * (1 - u ^ 2) ^ m), by continuity,
calc ∫ x in a..b, sin x ^ (2 * m + 1) * cos x ^ n
= -∫ x in b..a, sin x ^ (2 * m + 1) * cos x ^ n : by rw integral_symm
... = ∫ x in b..a, (1 - cos x ^ 2) ^ m * -sin x * cos x ^ n : by simp [pow_succ', pow_mul, sin_sq]
... = ∫ x in b..a, cos x ^ n * (1 - cos x ^ 2) ^ m * -sin x : by { congr, ext, ring }
... = ∫ u in cos b..cos a, u ^ n * (1 - u ^ 2) ^ m : integral_comp_mul_deriv
(λ x hx, has_deriv_at_cos x)
continuous_on_sin.neg hc
/-- The integral of `sin x * cos x`, given in terms of cos².
See `integral_sin_mul_cos₁` above for the integral given in terms of sin². -/
lemma integral_sin_mul_cos₂ :
∫ x in a..b, sin x * cos x = (cos a ^ 2 - cos b ^ 2) / 2 :=
by simpa using integral_sin_pow_odd_mul_cos_pow 0 1
@[simp]
lemma integral_sin_mul_cos_sq :
∫ x in a..b, sin x * cos x ^ 2 = (cos a ^ 3 - cos b ^ 3) / 3 :=
by simpa using integral_sin_pow_odd_mul_cos_pow 0 2
@[simp]
lemma integral_sin_pow_three :
∫ x in a..b, sin x ^ 3 = cos a - cos b - (cos a ^ 3 - cos b ^ 3) / 3 :=
by simpa using integral_sin_pow_odd_mul_cos_pow 1 0
/-- Simplification of the integral of `sin x ^ m * cos x ^ n`, case `m` and `n` are both even. -/
lemma integral_sin_pow_even_mul_cos_pow_even (m n : ℕ) :
∫ x in a..b, sin x ^ (2 * m) * cos x ^ (2 * n)
= ∫ x in a..b, ((1 - cos (2 * x)) / 2) ^ m * ((1 + cos (2 * x)) / 2) ^ n :=
by field_simp [pow_mul, sin_sq, cos_sq, ← sub_sub, (by ring : (2:ℝ) - 1 = 1)]
@[simp]
lemma integral_sin_sq_mul_cos_sq :
∫ x in a..b, sin x ^ 2 * cos x ^ 2 = (b - a) / 8 - (sin (4 * b) - sin (4 * a)) / 32 :=
begin
convert integral_sin_pow_even_mul_cos_pow_even 1 1 using 1,
have h1 : ∀ c : ℝ, (1 - c) / 2 * ((1 + c) / 2) = (1 - c ^ 2) / 4 := λ c, by ring,
have h2 : continuous (λ x, cos (2 * x) ^ 2) := by continuity,
have h3 : ∀ x, cos x * sin x = sin (2 * x) / 2, { intro, rw sin_two_mul, ring },
have h4 : ∀ d : ℝ, 2 * (2 * d) = 4 * d := λ d, by ring,
simp [h1, h2.interval_integrable, integral_comp_mul_left (λ x, cos x ^ 2), h3, h4],
ring,
end
|
f71855f703deff82c16d88875e66d64947a6b215 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/tactic/equiv_rw.lean | 4ec7390db0bd777a92193a56d51e373adb340367 | [
"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 | 12,008 | 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.equiv_functor
import tactic.simp_result
/-!
# The `equiv_rw` tactic transports goals or hypotheses along equivalences.
The basic syntax is `equiv_rw e`, where `e : α ≃ β` is an equivalence.
This will try to replace occurrences of `α` in the goal with `β`, for example
transforming
* `⊢ α` to `⊢ β`,
* `⊢ option α` to `⊢ option β`
* `⊢ {a // P}` to `{b // P (⇑(equiv.symm e) b)}`
The tactic can also be used to rewrite hypotheses, using the syntax `equiv_rw e at h`.
## Implementation details
The main internal function is `equiv_rw_type e t`,
which attempts to turn an expression `e : α ≃ β` into a new equivalence with left hand side `t`.
As an example, with `t = option α`, it will generate `functor.map_equiv option e`.
This is achieved by generating a new synthetic goal `%%t ≃ _`,
and calling `solve_by_elim` with an appropriate set of congruence lemmas.
To avoid having to specify the relevant congruence lemmas by hand,
we mostly rely on `equiv_functor.map_equiv` and `bifunctor.map_equiv`
along with some structural congruence lemmas such as
* `equiv.arrow_congr'`,
* `equiv.subtype_equiv_of_subtype'`,
* `equiv.sigma_congr_left'`, and
* `equiv.Pi_congr_left'`.
The main `equiv_rw` function, when operating on the goal, simply generates a new equivalence `e'`
with left hand side matching the target, and calls `apply e'.inv_fun`.
When operating on a hypothesis `x : α`, we introduce a new fact `h : x = e.symm (e x)`,
revert this, and then attempt to `generalize`, replacing all occurrences of `e x` with a new constant `y`,
before `intro`ing and `subst`ing `h`, and renaming `y` back to `x`.
## Future improvements
In a future PR I anticipate that `derive equiv_functor` should work on many examples,
(internally using `transport`, which is in turn based on `equiv_rw`)
and we can incrementally bootstrap the strength of `equiv_rw`.
An ambitious project might be to add `equiv_rw!`,
a tactic which, when failing to find appropriate `equiv_functor` instances,
attempts to `derive` them on the spot.
For now `equiv_rw` is entirely based on `equiv`,
but the framework can readily be generalised to also work with other types of equivalences,
for example specific notations such as ring equivalence (`≃+*`),
or general categorical isomorphisms (`≅`).
This will allow us to transport across more general types of equivalences,
but this will wait for another subsequent PR.
-/
namespace tactic
/-- A list of lemmas used for constructing congruence equivalences. -/
-- Although this looks 'hard-coded', in fact the lemma `equiv_functor.map_equiv`
-- allows us to extend `equiv_rw` simply by constructing new instance so `equiv_functor`.
-- TODO: We should also use `category_theory.functorial` and `category_theory.hygienic` instances.
-- (example goal: we could rewrite along an isomorphism of rings (either as `R ≅ S` or `R ≃+* S`)
-- and turn an `x : mv_polynomial σ R` into an `x : mv_polynomial σ S`.).
meta def equiv_congr_lemmas : tactic (list expr) :=
do exprs ←
[
`equiv.of_iff,
-- TODO decide what to do with this; it's an equiv_bifunctor?
`equiv.equiv_congr,
-- The function arrow is technically a bifunctor `Typeᵒᵖ → Type → Type`,
-- but the pattern matcher will never see this.
`equiv.arrow_congr',
-- Allow rewriting in subtypes:
`equiv.subtype_equiv_of_subtype',
-- Allow rewriting in the first component of a sigma-type:
`equiv.sigma_congr_left',
-- Allow rewriting ∀s:
-- (You might think that repeated application of `equiv.forall_congr'
-- would handle the higher arity cases, but unfortunately unification is not clever enough.)
`equiv.forall₃_congr',
`equiv.forall₂_congr',
`equiv.forall_congr',
-- Allow rewriting in argument of Pi types:
`equiv.Pi_congr_left',
-- Handles `sum` and `prod`, and many others:
`bifunctor.map_equiv,
-- Handles `list`, `option`, `unique`, and many others:
`equiv_functor.map_equiv,
-- We have to filter results to ensure we don't cheat and use exclusively `equiv.refl` and `iff.refl`!
`equiv.refl,
`iff.refl
].mmap (λ n, try_core (mk_const n)),
return (exprs.map option.to_list).join -- TODO: implement `.mfilter_map mk_const`?
declare_trace equiv_rw_type
/--
Configuration structure for `equiv_rw`.
* `max_depth` bounds the search depth for equivalences to rewrite along.
The default value is 10.
(e.g., if you're rewriting along `e : α ≃ β`, and `max_depth := 2`,
you can rewrite `option (option α))` but not `option (option (option α))`.
-/
meta structure equiv_rw_cfg :=
(max_depth : ℕ := 10)
/--
Implementation of `equiv_rw_type`, using `solve_by_elim`.
Expects a goal of the form `t ≃ _`,
and tries to solve it using `eq : α ≃ β` and congruence lemmas.
-/
meta def equiv_rw_type_core (eq : expr) (cfg : equiv_rw_cfg) : tactic unit :=
do
-- Assemble the relevant lemmas.
equiv_congr_lemmas ← equiv_congr_lemmas,
/-
We now call `solve_by_elim` to try to generate the requested equivalence.
There are a few subtleties!
* We make sure that `eq` is the first lemma, so it is applied whenever possible.
* In `equiv_congr_lemmas`, we put `equiv.refl` last so it is only used when it is not possible
to descend further.
* Since some congruence lemmas generate subgoals with `∀` statements,
we use the `pre_apply` subtactic of `solve_by_elim` to preprocess each new goal with `intros`.
-/
solve_by_elim
{ use_symmetry := false,
use_exfalso := false,
lemmas := some (eq :: equiv_congr_lemmas),
max_depth := cfg.max_depth,
-- Subgoals may contain function types,
-- and we want to continue trying to construct equivalences after the binders.
pre_apply := tactic.intros >> skip,
-- If solve_by_elim gets stuck, make sure it isn't because there's a later `≃` or `↔` goal
-- that we should still attempt.
discharger := `[show _ ≃ _] <|> `[show _ ↔ _] <|>
trace_if_enabled `equiv_rw_type "Failed, no congruence lemma applied!" >> failed,
-- We use the `accept` tactic in `solve_by_elim` to provide tracing.
accept := λ goals, lock_tactic_state (do
when_tracing `equiv_rw_type (do
goals.mmap pp >>= λ goals, trace format!"So far, we've built: {goals}"),
done <|>
when_tracing `equiv_rw_type (do
gs ← get_goals,
gs ← gs.mmap (λ g, infer_type g >>= pp),
trace format!"Attempting to adapt to {gs}")) }
/--
`equiv_rw_type e t` rewrites the type `t` using the equivalence `e : α ≃ β`,
returning a new equivalence `t ≃ t'`.
-/
meta def equiv_rw_type (eqv : expr) (ty : expr) (cfg : equiv_rw_cfg) : tactic expr :=
do
when_tracing `equiv_rw_type (do
ty_pp ← pp ty,
eqv_pp ← pp eqv,
eqv_ty_pp ← infer_type eqv >>= pp,
trace format!"Attempting to rewrite the type `{ty_pp}` using `{eqv_pp} : {eqv_ty_pp}`."),
`(_ ≃ _) ← infer_type eqv | fail format!"{eqv} must be an `equiv`",
-- We prepare a synthetic goal of type `(%%ty ≃ _)`, for some placeholder right hand side.
equiv_ty ← to_expr ``(%%ty ≃ _),
-- Now call `equiv_rw_type_core`.
new_eqv ← prod.snd <$> (solve_aux equiv_ty $ equiv_rw_type_core eqv cfg),
-- Check that we actually used the equivalence `eq`
-- (`equiv_rw_type_core` will always find `equiv.refl`, but hopefully only after all other possibilities)
new_eqv ← instantiate_mvars new_eqv,
guard (eqv.occurs new_eqv) <|> (do
eqv_pp ← pp eqv,
ty_pp ← pp ty,
fail format!"Could not construct an equivalence from {eqv_pp} of the form: {ty_pp} ≃ _"),
-- Finally we simplify the resulting equivalence,
-- to compress away some `map_equiv equiv.refl` subexpressions.
prod.fst <$> new_eqv.simp {fail_if_unchanged := ff}
mk_simp_attribute equiv_rw_simp "The simpset `equiv_rw_simp` is used by the tactic `equiv_rw` to
simplify applications of equivalences and their inverses."
attribute [equiv_rw_simp] equiv.symm_symm equiv.apply_symm_apply equiv.symm_apply_apply
/--
Attempt to replace the hypothesis with name `x`
by transporting it along the equivalence in `e : α ≃ β`.
-/
meta def equiv_rw_hyp (x : name) (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit :=
-- We call `dsimp_result` to perform the beta redex introduced by `revert`
dsimp_result (do
x' ← get_local x,
x_ty ← infer_type x',
-- Adapt `e` to an equivalence with left-hand-side `x_ty`.
e ← equiv_rw_type e x_ty cfg,
eq ← to_expr ``(%%x' = equiv.symm %%e (equiv.to_fun %%e %%x')),
prf ← to_expr ``((equiv.symm_apply_apply %%e %%x').symm),
h ← note_anon eq prf,
-- Revert the new hypothesis, so it is also part of the goal.
revert h,
ex ← to_expr ``(equiv.to_fun %%e %%x'),
-- Now call `generalize`,
-- attempting to replace all occurrences of `e x`,
-- calling it for now `j : β`, with `k : x = e.symm j`.
generalize ex (by apply_opt_param) transparency.none,
-- Reintroduce `x` (now of type `b`), and the hypothesis `h`.
intro x,
h ← intro1,
-- We may need to unfreeze `x` before we can `subst` or `clear` it.
unfreeze x',
-- Finally, if we're working on properties, substitute along `h`, then do some cleanup,
-- and if we're working on data, just throw out the old `x`.
b ← target >>= is_prop,
if b then do
subst h,
`[try { simp only [] with equiv_rw_simp }]
else
clear' tt (native.rb_map.set_of_list [x']) <|>
fail format!"equiv_rw expected to be able to clear the original hypothesis {x}, but couldn't.",
skip)
{fail_if_unchanged := ff} tt -- call `dsimp_result` with `no_defaults := tt`.
/-- Rewrite the goal using an equiv `e`. -/
meta def equiv_rw_target (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit :=
do
t ← target,
e ← equiv_rw_type e t cfg,
s ← to_expr ``(equiv.inv_fun %%e),
tactic.eapply s,
skip
end tactic
namespace tactic.interactive
open lean.parser
open interactive interactive.types
open tactic
local postfix `?`:9001 := optional
/--
`equiv_rw e at h`, where `h : α` is a hypothesis, and `e : α ≃ β`,
will attempt to transport `h` along `e`, producing a new hypothesis `h : β`,
with all occurrences of `h` in other hypotheses and the goal replaced with `e.symm h`.
`equiv_rw e` will attempt to transport the goal along an equivalence `e : α ≃ β`.
In its minimal form it replaces the goal `⊢ α` with `⊢ β` by calling `apply e.inv_fun`.
`equiv_rw` will also try rewriting under (equiv_)functors, so can turn
a hypothesis `h : list α` into `h : list β` or
a goal `⊢ unique α` into `⊢ unique β`.
The maximum search depth for rewriting in subexpressions is controlled by
`equiv_rw e {max_depth := n}`.
-/
meta def equiv_rw (e : parse texpr) (loc : parse $ (tk "at" *> ident)?) (cfg : equiv_rw_cfg := {}) : itactic :=
do e ← to_expr e,
match loc with
| (some hyp) := equiv_rw_hyp hyp e cfg
| none := equiv_rw_target e cfg
end
add_tactic_doc
{ name := "equiv_rw",
category := doc_category.tactic,
decl_names := [`tactic.interactive.equiv_rw],
tags := ["rewriting", "equiv", "transport"] }
/--
Solve a goal of the form `t ≃ _`,
by constructing an equivalence from `e : α ≃ β`.
This is the same equivalence that `equiv_rw` would use to rewrite a term of type `t`.
A typical usage might be:
```
have e' : option α ≃ option β := by equiv_rw_type e
```
-/
meta def equiv_rw_type (e : parse texpr) (cfg : equiv_rw_cfg := {}) : itactic :=
do
`(%%t ≃ _) ← target | fail "`equiv_rw_type` solves goals of the form `t ≃ _`.",
e ← to_expr e,
tactic.equiv_rw_type e t cfg >>= tactic.exact
add_tactic_doc
{ name := "equiv_rw_type",
category := doc_category.tactic,
decl_names := [`tactic.interactive.equiv_rw_type],
tags := ["rewriting", "equiv", "transport"] }
end tactic.interactive
|
bb6903b9fd75c29b4cceefc94576fec19f347f85 | 8c9f90127b78cbeb5bb17fd6b5db1db2ffa3cbc4 | /divisibility.lean | 07ae226ee531a70fa23c70be621e225daf3e70d2 | [] | no_license | picrin/lean | 420f4d08bb3796b911d56d0938e4410e1da0e072 | 3d10c509c79704aa3a88ebfb24d08b30ce1137cc | refs/heads/master | 1,611,166,610,726 | 1,536,671,438,000 | 1,536,671,438,000 | 60,029,899 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,019 | lean | def isEven (n : nat) : Prop :=
∃ (m : nat), 2 * m = n
lemma FourIsEven : isEven 4 :=
exists.intro 2 (eq.refl 4)
-- (isEven 4) fourIsEven = .....
--int four = 4
--class proofsOfFour {}
--proofsOfFour myProof = ...
lemma nat.lte_zero (n : nat) : 0 ≤ n :=
@nat.rec_on (λ k', 0 ≤ k') n (le_refl 0) (λ k (p : 0 ≤ k),
have q : 0 ≤ 1, from nat.le_add_left 0 1,
show (0 ≤ k + 1), from le_add_of_le_of_nonneg p q
)
lemma lt_eq {a b c : nat} (h1 : b = c) (h2 : a < b) : (a < c) :=
eq.subst h1 h2
lemma biggerIsBigger (a b c : nat) (h1: a < b) : (a < b + c) :=
have H1: c + b = b + c, from nat.add_comm c b,
lt_eq H1 (lt_add_of_nonneg_of_lt (nat.lte_zero c) h1)
lemma zero_not_succ : 0 ≠ 1 :=
λ (m : nat.zero = (nat.succ nat.zero)),
nat.no_confusion m
lemma same_lt {a : nat} (P : a < a) : false :=
have H : a = a, from eq.refl a,
ne_of_lt P H
lemma lt_neq {a b : nat} (Pab : a < b) : a ≠ b :=
assume P : a = b,
have P2 : b = a, from eq.symm P,
have X : a < a, from
calc a < b : Pab
... = a : P2,
show false, from (same_lt X)
lemma cases_on_nat (rel : nat → Prop) (p0 : rel 0) (Pa : ∀ {a}, 0 < a → rel a) : (∀ n : nat, rel n) :=
λ (n : nat),
nat.rec_on n (p0) (
λ (k : nat) (Pk : rel k),
have H1 : 0 < 1 + k, from biggerIsBigger 0 1 k zero_lt_one,
have H2 : rel (1 + k), from Pa H1,
show rel (k + 1), from eq.subst (add_comm 1 k) H2
)
open classical
lemma le_add_right (a b c : nat) (h1: a < b) : (a < b + c) :=
have H1: c + b = b + c, from nat.add_comm c b,
lt_eq H1 (lt_add_of_nonneg_of_lt (nat.lte_zero c) h1)
lemma subst2 (a b : nat) (H : a = b) (P1 : 1 < 2 * (a + 1)) : 1 < 2 * (b + 1) := eq.subst H P1
lemma zero_le_zero (k : nat) (H : k ≤ 0) : (k = 0) :=
have H1 : 0 ≤ k, from nat.lte_zero k,
iff.elim_right le_antisymm_iff (and.intro H H1)
lemma one_lt_twice (m : nat) : 0 < m → 1 < 2 * m :=
@nat.rec_on (assume k' : nat, 0 < k' → 1 < 2 * k') m (
assume (P : 0 < 0), (false.elim (same_lt P)))
( assume k : nat, assume (IH : 0 < k → 1 < 2 * k),
show (0 < k + 1 → 1 < 2 * (k + 1)), from
assume (P : 0 < k + 1),
show 1 < 2 * (k + 1), from
(or.elim (em (0 < k))
(assume H2 : 0 < k,
have H4 : 1 < 2 * k, from IH H2,
have H8 : 1 < 2 * k + 2, from biggerIsBigger 1 (2 * k) 2 H4,
have H7 : 2 * k + 2 = 2 * (k + 1), by simp [mul_add],
show 1 < 2 * (k + 1), from eq.subst H7 H8
)
(assume (H3 : 0 < k → false),
have H6 : k > 0 → false, from H3,
have H4 : k ≤ 0, from le_of_not_gt H6,
have H5 : k = 0, from zero_le_zero k H4,
have Q : (1 : nat) < 2 * (0 + 1), from of_as_true trivial,
show 1 < 2 * (k + 1), from (subst2 0 k (eq.symm H5)) Q
)
)
)
lemma neq.refl (m : nat) (X : 1 ≠ 2 * m) : (2 * m ≠ 1) :=
assume H1 : 2 * m = 1,
have H2 : 1 = 2 * m, from eq.symm H1,
false.elim (X H2)
lemma mNotEven (m : nat) : 2 * m = 1 → false :=
have P0 : 2 * 0 ≠ 1, from zero_not_succ,
have P1 : ∀ m, 0 < m → 2 * m > 1, from one_lt_twice,
have P2 : ∀ m, 0 < m → 1 ≠ 2 * m, from (λ m Pm, (lt_neq (P1 m Pm))),
have P3 : ∀ m, 0 < m → 2 * m ≠ 1, from (λ m Pm, neq.refl m (P2 m Pm)),
cases_on_nat (λ m, 2 * m ≠ 1) P0 P3 m
lemma OneIsNotEven : isEven 1 → false :=
λ P1e : ∃ (m : nat), 2 * m = 1,
exists.elim P1e (λ m : nat, λ Peven : 2 * m = 1,
mNotEven m Peven
)
#check @nat.rec_on
universe u
--have cases: k < n ∨ k ≥ n, from lt_or_ge k n, or.elim cases
-- (λ P : k < n,
-- )
-- (λ P : k ≥ n, sorry)
|
16d6bc00cc984161a96b5e02020097090a78caf9 | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /stage0/src/Lean/Elab/Util.lean | 07958760059dba8bd6d98808ef0c6c4c8dfa7dc5 | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,744 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.Trace
import Lean.Parser.Syntax
import Lean.Parser.Extension
import Lean.KeyedDeclsAttribute
import Lean.Elab.Exception
namespace Lean
def Syntax.prettyPrint (stx : Syntax) : Format :=
match stx.unsetTrailing.reprint with -- TODO use syntax pretty printer
| some str => format str.toFormat
| none => format stx
def MacroScopesView.format (view : MacroScopesView) (mainModule : Name) : Format :=
Std.format $
if view.scopes.isEmpty then
view.name
else if view.mainModule == mainModule then
view.scopes.foldl Name.mkNum (view.name ++ view.imported)
else
view.scopes.foldl Name.mkNum (view.name ++ view.imported ++ view.mainModule)
namespace Elab
def expandOptNamedPrio (stx : Syntax) : MacroM Nat :=
if stx.isNone then
return eval_prio default
else match stx[0] with
| `(Parser.Command.namedPrio| (priority := $prio)) => evalPrio prio
| _ => Macro.throwUnsupported
structure MacroStackElem where
before : Syntax
after : Syntax
abbrev MacroStack := List MacroStackElem
/- If `ref` does not have position information, then try to use macroStack -/
def getBetterRef (ref : Syntax) (macroStack : MacroStack) : Syntax :=
match ref.getPos? with
| some _ => ref
| none =>
match macroStack.find? (·.before.getPos? != none) with
| some elem => elem.before
| none => ref
register_builtin_option pp.macroStack : Bool := {
defValue := false
group := "pp"
descr := "dispaly macro expansion stack"
}
def addMacroStack {m} [Monad m] [MonadOptions m] (msgData : MessageData) (macroStack : MacroStack) : m MessageData := do
if !pp.macroStack.get (← getOptions) then pure msgData else
match macroStack with
| [] => pure msgData
| stack@(top::_) =>
let msgData := msgData ++ Format.line ++ "with resulting expansion" ++ indentD top.after
pure $ stack.foldl
(fun (msgData : MessageData) (elem : MacroStackElem) =>
msgData ++ Format.line ++ "while expanding" ++ indentD elem.before)
msgData
def checkSyntaxNodeKind [Monad m] [MonadEnv m] [MonadError m] (k : Name) : m Name := do
if Parser.isValidSyntaxNodeKind (← getEnv) k then pure k
else throwError "failed"
def checkSyntaxNodeKindAtNamespaces [Monad m] [MonadEnv m] [MonadError m] (k : Name) : Name → m Name
| n@(Name.str p _ _) => checkSyntaxNodeKind (n ++ k) <|> checkSyntaxNodeKindAtNamespaces k p
| Name.anonymous => checkSyntaxNodeKind k
| _ => throwError "failed"
def checkSyntaxNodeKindAtCurrentNamespaces (k : Name) : AttrM Name := do
let ctx ← read
checkSyntaxNodeKindAtNamespaces k ctx.currNamespace
def syntaxNodeKindOfAttrParam (defaultParserNamespace : Name) (stx : Syntax) : AttrM SyntaxNodeKind := do
let k ← Attribute.Builtin.getId stx
checkSyntaxNodeKindAtCurrentNamespaces k
<|>
checkSyntaxNodeKind (defaultParserNamespace ++ k)
<|>
throwError "invalid syntax node kind '{k}'"
private unsafe def evalSyntaxConstantUnsafe (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax :=
env.evalConstCheck Syntax opts `Lean.Syntax constName
@[implementedBy evalSyntaxConstantUnsafe]
constant evalSyntaxConstant (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax := throw ""
unsafe def mkElabAttribute (γ) (attrDeclName attrBuiltinName attrName : Name) (parserNamespace : Name) (typeName : Name) (kind : String)
: IO (KeyedDeclsAttribute γ) :=
KeyedDeclsAttribute.init {
builtinName := attrBuiltinName
name := attrName
descr := kind ++ " elaborator"
valueTypeName := typeName
evalKey := fun _ stx => syntaxNodeKindOfAttrParam parserNamespace stx
} attrDeclName
unsafe def mkMacroAttributeUnsafe : IO (KeyedDeclsAttribute Macro) :=
mkElabAttribute Macro `Lean.Elab.macroAttribute `builtinMacro `macro Name.anonymous `Lean.Macro "macro"
@[implementedBy mkMacroAttributeUnsafe]
constant mkMacroAttribute : IO (KeyedDeclsAttribute Macro)
builtin_initialize macroAttribute : KeyedDeclsAttribute Macro ← mkMacroAttribute
/--
Try to expand macro at syntax tree root and return macro declaration name and new syntax if successful.
Return none if all macros threw `Macro.Exception.unsupportedSyntax`.
-/
def expandMacroImpl? (env : Environment) : Syntax → MacroM (Option (Name × Syntax)) := fun stx => do
for e in macroAttribute.getEntries env stx.getKind do
try
let stx' ← e.value stx
return (e.declName, stx')
catch
| Macro.Exception.unsupportedSyntax => pure ()
| ex => throw ex
return none
class MonadMacroAdapter (m : Type → Type) where
getCurrMacroScope : m MacroScope
getNextMacroScope : m MacroScope
setNextMacroScope : MacroScope → m Unit
instance (m n) [MonadLift m n] [MonadMacroAdapter m] : MonadMacroAdapter n := {
getCurrMacroScope := liftM (MonadMacroAdapter.getCurrMacroScope : m _),
getNextMacroScope := liftM (MonadMacroAdapter.getNextMacroScope : m _),
setNextMacroScope := fun s => liftM (MonadMacroAdapter.setNextMacroScope s : m _)
}
def liftMacroM {α} {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] [MonadResolveName m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] (x : MacroM α) : m α := do
let env ← getEnv
let currNamespace ← getCurrNamespace
let openDecls ← getOpenDecls
let methods := Macro.mkMethods {
-- TODO: record recursive expansions in info tree?
expandMacro? := fun stx => do
match (← expandMacroImpl? env stx) with
| some (_, stx) => some stx
| none => none
hasDecl := fun declName => return env.contains declName
getCurrNamespace := return currNamespace
resolveNamespace? := fun n => return ResolveName.resolveNamespace? env currNamespace openDecls n
resolveGlobalName := fun n => return ResolveName.resolveGlobalName env currNamespace openDecls n
}
match x { methods := methods
ref := ← getRef
currMacroScope := ← MonadMacroAdapter.getCurrMacroScope
mainModule := env.mainModule
currRecDepth := ← MonadRecDepth.getRecDepth
maxRecDepth := ← MonadRecDepth.getMaxRecDepth
} { macroScope := (← MonadMacroAdapter.getNextMacroScope) } with
| EStateM.Result.error Macro.Exception.unsupportedSyntax _ => throwUnsupportedSyntax
| EStateM.Result.error (Macro.Exception.error ref msg) _ => throwErrorAt ref msg
| EStateM.Result.ok a s =>
MonadMacroAdapter.setNextMacroScope s.macroScope
s.traceMsgs.reverse.forM fun (clsName, msg) => trace clsName fun _ => msg
pure a
@[inline] def adaptMacro {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] [MonadResolveName m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] (x : Macro) (stx : Syntax) : m Syntax :=
liftMacroM (x stx)
partial def mkUnusedBaseName (baseName : Name) : MacroM Name := do
let currNamespace ← Macro.getCurrNamespace
if ← Macro.hasDecl (currNamespace ++ baseName) then
let rec loop (idx : Nat) := do
let name := baseName.appendIndexAfter idx
if ← Macro.hasDecl (currNamespace ++ name) then
loop (idx+1)
else
name
loop 1
else
return baseName
builtin_initialize
registerTraceClass `Elab
registerTraceClass `Elab.step
end Lean.Elab
|
bda9cfe8477f1adac742db6b6e641874f50ab694 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/linear_algebra/sesquilinear_form.lean | 28fe5b9b2159881ed62f4e3d5b84dc65ddf34f35 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,085 | lean | /-
Copyright (c) 2018 Andreas Swerdlow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Andreas Swerdlow
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.module.basic
import Mathlib.ring_theory.ring_invo
import Mathlib.PostPort
universes u v l u_1 u_2
namespace Mathlib
/-!
# Sesquilinear form
This file defines a sesquilinear form over a module. The definition requires a ring antiautomorphism
on the scalar ring. Basic ideas such as
orthogonality are also introduced.
A sesquilinear form on an `R`-module `M`, is a function from `M × M` to `R`, that is linear in the
first argument and antilinear in the second, with respect to an antiautomorphism on `R` (an
antiisomorphism from `R` to `R`).
## Notations
Given any term `S` of type `sesq_form`, due to a coercion, can use the notation `S x y` to
refer to the function field, ie. `S x y = S.sesq x y`.
## References
* <https://en.wikipedia.org/wiki/Sesquilinear_form#Over_arbitrary_rings>
## Tags
Sesquilinear form,
-/
/-- A sesquilinear form over a module -/
structure sesq_form (R : Type u) (M : Type v) [ring R] (I : R ≃+* (Rᵒᵖ)) [add_comm_group M] [module R M]
where
sesq : M → M → R
sesq_add_left : ∀ (x y z : M), sesq (x + y) z = sesq x z + sesq y z
sesq_smul_left : ∀ (a : R) (x y : M), sesq (a • x) y = a * sesq x y
sesq_add_right : ∀ (x y z : M), sesq x (y + z) = sesq x y + sesq x z
sesq_smul_right : ∀ (a : R) (x y : M), sesq x (a • y) = opposite.unop (coe_fn I a) * sesq x y
namespace sesq_form
protected instance has_coe_to_fun {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} : has_coe_to_fun (sesq_form R M I) :=
has_coe_to_fun.mk (fun (S : sesq_form R M I) => M → M → R) fun (S : sesq_form R M I) => sesq S
theorem add_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) (y : M) (z : M) : coe_fn S (x + y) z = coe_fn S x z + coe_fn S y z :=
sesq_add_left S x y z
theorem smul_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (a : R) (x : M) (y : M) : coe_fn S (a • x) y = a * coe_fn S x y :=
sesq_smul_left S a x y
theorem add_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) (y : M) (z : M) : coe_fn S x (y + z) = coe_fn S x y + coe_fn S x z :=
sesq_add_right S x y z
theorem smul_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (a : R) (x : M) (y : M) : coe_fn S x (a • y) = opposite.unop (coe_fn I a) * coe_fn S x y :=
sesq_smul_right S a x y
theorem zero_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) : coe_fn S 0 x = 0 :=
eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn S 0 x = 0)) (Eq.symm (zero_smul R 0))))
(eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn S (0 • 0) x = 0)) (smul_left 0 0 x)))
(eq.mpr (id (Eq._oldrec (Eq.refl (0 * coe_fn S 0 x = 0)) (zero_mul (coe_fn S 0 x)))) (Eq.refl 0)))
theorem zero_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) : coe_fn S x 0 = 0 := sorry
theorem neg_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) (y : M) : coe_fn S (-x) y = -coe_fn S x y := sorry
theorem neg_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) (y : M) : coe_fn S x (-y) = -coe_fn S x y := sorry
theorem sub_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) (y : M) (z : M) : coe_fn S (x - y) z = coe_fn S x z - coe_fn S y z := sorry
theorem sub_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) (y : M) (z : M) : coe_fn S x (y - z) = coe_fn S x y - coe_fn S x z := sorry
theorem ext {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} {D : sesq_form R M I} (H : ∀ (x y : M), coe_fn S x y = coe_fn D x y) : S = D := sorry
protected instance add_comm_group {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} : add_comm_group (sesq_form R M I) :=
add_comm_group.mk
(fun (S D : sesq_form R M I) => mk (fun (x y : M) => coe_fn S x y + coe_fn D x y) sorry sorry sorry sorry) sorry
(mk (fun (x y : M) => 0) sorry sorry sorry sorry) sorry sorry
(fun (S : sesq_form R M I) => mk (fun (x y : M) => -sesq S x y) sorry sorry sorry sorry)
(add_group.sub._default
(fun (S D : sesq_form R M I) => mk (fun (x y : M) => coe_fn S x y + coe_fn D x y) sorry sorry sorry sorry) sorry
(mk (fun (x y : M) => 0) sorry sorry sorry sorry) sorry sorry
fun (S : sesq_form R M I) => mk (fun (x y : M) => -sesq S x y) sorry sorry sorry sorry)
sorry sorry
protected instance inhabited {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} : Inhabited (sesq_form R M I) :=
{ default := 0 }
/-- The proposition that two elements of a sesquilinear form space are orthogonal -/
def is_ortho {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} (S : sesq_form R M I) (x : M) (y : M) :=
coe_fn S x y = 0
theorem ortho_zero {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (x : M) : is_ortho S 0 x :=
zero_left x
theorem is_add_monoid_hom_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} (S : sesq_form R M I) (x : M) : is_add_monoid_hom fun (z : M) => coe_fn S z x :=
is_add_monoid_hom.mk (zero_left x)
theorem is_add_monoid_hom_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} (S : sesq_form R M I) (x : M) : is_add_monoid_hom fun (z : M) => coe_fn S x z :=
is_add_monoid_hom.mk (zero_right x)
theorem map_sum_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {α : Type u_1} (S : sesq_form R M I) (t : finset α) (g : α → M) (w : M) : coe_fn S (finset.sum t fun (i : α) => g i) w = finset.sum t fun (i : α) => coe_fn S (g i) w :=
Eq.symm (finset.sum_hom t fun (z : M) => coe_fn S z w)
theorem map_sum_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {α : Type u_1} (S : sesq_form R M I) (t : finset α) (g : α → M) (w : M) : coe_fn S w (finset.sum t fun (i : α) => g i) = finset.sum t fun (i : α) => coe_fn S w (g i) :=
Eq.symm (finset.sum_hom t fun (z : M) => coe_fn S w z)
protected instance to_module {R : Type u_1} [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {J : R ≃+* (Rᵒᵖ)} : module R (sesq_form R M J) :=
semimodule.mk sorry sorry
theorem ortho_smul_left {R : Type u_1} [domain R] {M : Type v} [add_comm_group M] [module R M] {K : R ≃+* (Rᵒᵖ)} {G : sesq_form R M K} {x : M} {y : M} {a : R} (ha : a ≠ 0) : is_ortho G x y ↔ is_ortho G (a • x) y := sorry
theorem ortho_smul_right {R : Type u_1} [domain R] {M : Type v} [add_comm_group M] [module R M] {K : R ≃+* (Rᵒᵖ)} {G : sesq_form R M K} {x : M} {y : M} {a : R} (ha : a ≠ 0) : is_ortho G x y ↔ is_ortho G x (a • y) := sorry
end sesq_form
namespace refl_sesq_form
/-- The proposition that a sesquilinear form is reflexive -/
def is_refl {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} (S : sesq_form R M I) :=
∀ (x y : M), coe_fn S x y = 0 → coe_fn S y x = 0
theorem eq_zero {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_refl S) {x : M} {y : M} : coe_fn S x y = 0 → coe_fn S y x = 0 :=
H x y
theorem ortho_sym {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_refl S) {x : M} {y : M} : sesq_form.is_ortho S x y ↔ sesq_form.is_ortho S y x :=
{ mp := eq_zero H, mpr := eq_zero H }
end refl_sesq_form
namespace sym_sesq_form
/-- The proposition that a sesquilinear form is symmetric -/
def is_sym {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} (S : sesq_form R M I) :=
∀ (x y : M), opposite.unop (coe_fn I (coe_fn S x y)) = coe_fn S y x
theorem sym {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_sym S) (x : M) (y : M) : opposite.unop (coe_fn I (coe_fn S x y)) = coe_fn S y x :=
H x y
theorem is_refl {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_sym S) : refl_sesq_form.is_refl S := sorry
theorem ortho_sym {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_sym S) {x : M} {y : M} : sesq_form.is_ortho S x y ↔ sesq_form.is_ortho S y x :=
refl_sesq_form.ortho_sym (is_refl H)
end sym_sesq_form
namespace alt_sesq_form
/-- The proposition that a sesquilinear form is alternating -/
def is_alt {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} (S : sesq_form R M I) :=
∀ (x : M), coe_fn S x x = 0
theorem self_eq_zero {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_alt S) (x : M) : coe_fn S x x = 0 :=
H x
theorem neg {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {I : R ≃+* (Rᵒᵖ)} {S : sesq_form R M I} (H : is_alt S) (x : M) (y : M) : -coe_fn S x y = coe_fn S y x := sorry
|
5b85e85d2e88983ccf255ad4799b8ffe0bd6c51c | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Parser.lean | 7745db80ed2083efeda7c44318e7c7634824dc38 | [
"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 | 7,692 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Parser.Basic
import Lean.Parser.Level
import Lean.Parser.Term
import Lean.Parser.Tactic
import Lean.Parser.Command
import Lean.Parser.Module
import Lean.Parser.Syntax
import Lean.Parser.Do
namespace Lean
namespace Parser
open Lean.PrettyPrinter
open Lean.PrettyPrinter.Parenthesizer
open Lean.PrettyPrinter.Formatter
builtin_initialize
register_parser_alias "ws" checkWsBefore { stackSz? := some 0 }
register_parser_alias "noWs" checkNoWsBefore { stackSz? := some 0 }
register_parser_alias "linebreak" checkLinebreakBefore { stackSz? := some 0 }
register_parser_alias (kind := numLitKind) "num" numLit
register_parser_alias (kind := strLitKind) "str" strLit
register_parser_alias (kind := charLitKind) "char" charLit
register_parser_alias (kind := nameLitKind) "name" nameLit
register_parser_alias (kind := scientificLitKind) "scientific" scientificLit
register_parser_alias (kind := identKind) ident
register_parser_alias (kind := hygieneInfoKind) hygieneInfo
register_parser_alias "colGt" checkColGt { stackSz? := some 0 }
register_parser_alias "colGe" checkColGe { stackSz? := some 0 }
register_parser_alias "colEq" checkColEq { stackSz? := some 0 }
register_parser_alias "lineEq" checkLineEq { stackSz? := some 0 }
register_parser_alias lookahead { stackSz? := some 0 }
register_parser_alias atomic { stackSz? := none }
register_parser_alias many
register_parser_alias many1
register_parser_alias manyIndent
register_parser_alias many1Indent
register_parser_alias optional { autoGroupArgs := false }
register_parser_alias withPosition { stackSz? := none }
register_parser_alias withoutPosition { stackSz? := none }
register_parser_alias withoutForbidden { stackSz? := none }
register_parser_alias (kind := interpolatedStrKind) interpolatedStr
register_parser_alias orelse
register_parser_alias andthen { stackSz? := none }
registerAlias "notFollowedBy" ``notFollowedBy (notFollowedBy · "element")
Parenthesizer.registerAlias "notFollowedBy" notFollowedBy.parenthesizer
Formatter.registerAlias "notFollowedBy" notFollowedBy.formatter
end Parser
namespace PrettyPrinter
namespace Parenthesizer
-- Close the mutual recursion loop; see corresponding `[extern]` in the parenthesizer.
@[export lean_mk_antiquot_parenthesizer]
def mkAntiquot.parenthesizer (name : String) (kind : SyntaxNodeKind) (anonymous := true) (isPseudoKind := true) : Parenthesizer :=
Parser.mkAntiquot.parenthesizer name kind anonymous isPseudoKind
-- The parenthesizer auto-generated these instances correctly, but tagged them with the wrong kind, since the actual kind
-- (e.g. `ident`) is not equal to the parser name `Lean.Parser.Term.ident`.
@[builtin_parenthesizer ident] def ident.parenthesizer : Parenthesizer := Parser.Term.ident.parenthesizer
@[builtin_parenthesizer num] def numLit.parenthesizer : Parenthesizer := Parser.Term.num.parenthesizer
@[builtin_parenthesizer scientific] def scientificLit.parenthesizer : Parenthesizer := Parser.Term.scientific.parenthesizer
@[builtin_parenthesizer char] def charLit.parenthesizer : Parenthesizer := Parser.Term.char.parenthesizer
@[builtin_parenthesizer str] def strLit.parenthesizer : Parenthesizer := Parser.Term.str.parenthesizer
open Lean.Parser
@[export lean_pretty_printer_parenthesizer_interpret_parser_descr]
unsafe def interpretParserDescr : ParserDescr → CoreM Parenthesizer
| ParserDescr.const n => getConstAlias parenthesizerAliasesRef n
| ParserDescr.unary n d => return (← getUnaryAlias parenthesizerAliasesRef n) (← interpretParserDescr d)
| ParserDescr.binary n d₁ d₂ => return (← getBinaryAlias parenthesizerAliasesRef n) (← interpretParserDescr d₁) (← interpretParserDescr d₂)
| ParserDescr.node k prec d => return leadingNode.parenthesizer k prec (← interpretParserDescr d)
| ParserDescr.nodeWithAntiquot n k d => return withAntiquot.parenthesizer (mkAntiquot.parenthesizer' n k (anonymous := true)) <|
node.parenthesizer k (← interpretParserDescr d)
| ParserDescr.sepBy p sep psep trail => return sepBy.parenthesizer (← interpretParserDescr p) sep (← interpretParserDescr psep) trail
| ParserDescr.sepBy1 p sep psep trail => return sepBy1.parenthesizer (← interpretParserDescr p) sep (← interpretParserDescr psep) trail
| ParserDescr.trailingNode k prec lhsPrec d => return trailingNode.parenthesizer k prec lhsPrec (← interpretParserDescr d)
| ParserDescr.symbol tk => return symbol.parenthesizer tk
| ParserDescr.nonReservedSymbol tk includeIdent => return nonReservedSymbol.parenthesizer tk includeIdent
| ParserDescr.parser constName => combinatorParenthesizerAttribute.runDeclFor constName
| ParserDescr.cat catName prec => return categoryParser.parenthesizer catName prec
end Parenthesizer
namespace Formatter
@[export lean_mk_antiquot_formatter]
def mkAntiquot.formatter (name : String) (kind : SyntaxNodeKind) (anonymous := true) (isPseudoKind := true) : Formatter :=
Parser.mkAntiquot.formatter name kind anonymous isPseudoKind
@[builtin_formatter ident] def ident.formatter : Formatter := Parser.Term.ident.formatter
@[builtin_formatter num] def numLit.formatter : Formatter := Parser.Term.num.formatter
@[builtin_formatter scientific] def scientificLit.formatter : Formatter := Parser.Term.scientific.formatter
@[builtin_formatter char] def charLit.formatter : Formatter := Parser.Term.char.formatter
@[builtin_formatter str] def strLit.formatter : Formatter := Parser.Term.str.formatter
open Lean.Parser
@[export lean_pretty_printer_formatter_interpret_parser_descr]
unsafe def interpretParserDescr : ParserDescr → CoreM Formatter
| ParserDescr.const n => getConstAlias formatterAliasesRef n
| ParserDescr.unary n d => return (← getUnaryAlias formatterAliasesRef n) (← interpretParserDescr d)
| ParserDescr.binary n d₁ d₂ => return (← getBinaryAlias formatterAliasesRef n) (← interpretParserDescr d₁) (← interpretParserDescr d₂)
| ParserDescr.node k _ d => return node.formatter k (← interpretParserDescr d)
| ParserDescr.nodeWithAntiquot n k d => return withAntiquot.formatter (mkAntiquot.formatter' n k (anonymous := true)) <|
node.formatter k (← interpretParserDescr d)
| ParserDescr.sepBy p sep psep trail => return sepBy.formatter (← interpretParserDescr p) sep (← interpretParserDescr psep) trail
| ParserDescr.sepBy1 p sep psep trail => return sepBy1.formatter (← interpretParserDescr p) sep (← interpretParserDescr psep) trail
| ParserDescr.trailingNode k prec lhsPrec d => return trailingNode.formatter k prec lhsPrec (← interpretParserDescr d)
| ParserDescr.symbol tk => return symbol.formatter tk
| ParserDescr.nonReservedSymbol tk _ => return nonReservedSymbol.formatter tk
| ParserDescr.parser constName => combinatorFormatterAttribute.runDeclFor constName
| ParserDescr.cat catName _ => return categoryParser.formatter catName
end Formatter
end PrettyPrinter
end Lean
|
5e2ab54098b7e2a23d68dd0a69833c1a332c46a7 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/linear_algebra/clifford_algebra/contraction.lean | 152ebc5bd63b3c026786c8bcc3d992f968d165fb | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 15,014 | 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.exterior_algebra.basic
import linear_algebra.clifford_algebra.fold
import linear_algebra.clifford_algebra.conjugation
/-!
# Contraction in Clifford Algebras
This file contains some of the results from [grinberg_clifford_2016][].
The key result is `clifford_algebra.equiv_exterior`.
## Main definitions
* `clifford_algebra.contract_left`: contract a multivector by a `module.dual R M` on the left.
* `clifford_algebra.contract_right`: contract a multivector by a `module.dual R M` on the right.
* `clifford_algebra.change_form`: convert between two algebras of different quadratic form, sending
vectors to vectors. The difference of the quadratic forms must be a bilinear form.
* `clifford_algebra.equiv_exterior`: in characteristic not-two, the `clifford_algebra Q` is
isomorphic as a module to the exterior algebra.
## Implementation notes
This file somewhat follows [grinberg_clifford_2016][], although we are missing some of the induction
principles needed to prove many of the results. Here, we avoid the quotient-based approach described
in [grinberg_clifford_2016][], instead directly constructing our objects using the universal
property.
Note that [grinberg_clifford_2016][] concludes that its contents are not novel, and are in fact just
a rehash of parts of [bourbaki2007][]; we should at some point consider swapping our references to
refer to the latter.
Within this file, we use the local notation
* `x ⌊ d` for `contract_right x d`
* `d ⌋ x` for `contract_left d x`
-/
universes u1 u2 u3
variables {R : Type u1} [comm_ring R]
variables {M : Type u2} [add_comm_group M] [module R M]
variables (Q : quadratic_form R M)
namespace clifford_algebra
section contract_left
variables (d d' : module.dual R M)
/-- Auxiliary construction for `clifford_algebra.contract_left` -/
@[simps]
def contract_left_aux (d : module.dual R M) :
M →ₗ[R] clifford_algebra Q × clifford_algebra Q →ₗ[R] clifford_algebra Q :=
begin
have v_mul := (algebra.lmul R (clifford_algebra Q)).to_linear_map ∘ₗ (ι Q),
exact d.smul_right (linear_map.fst _ (clifford_algebra Q) (clifford_algebra Q)) -
v_mul.compl₂ (linear_map.snd _ (clifford_algebra Q) _),
end
lemma contract_left_aux_contract_left_aux (v : M) (x : clifford_algebra Q)
(fx : clifford_algebra Q) :
contract_left_aux Q d v (ι Q v * x, contract_left_aux Q d v (x, fx)) = Q v • fx :=
begin
simp only [contract_left_aux_apply_apply],
rw [mul_sub, ←mul_assoc, ι_sq_scalar, ←algebra.smul_def, ←sub_add, mul_smul_comm, sub_self,
zero_add],
end
variables {Q}
/-- Contract an element of the clifford algebra with an element `d : module.dual R M` from the left.
Note that $v ⌋ x$ is spelt `contract_left (Q.associated v) x`.
This includes [grinberg_clifford_2016][] Theorem 10.75 -/
def contract_left : module.dual R M →ₗ[R] clifford_algebra Q →ₗ[R] clifford_algebra Q :=
{ to_fun := λ d, foldr' Q (contract_left_aux Q d) (contract_left_aux_contract_left_aux Q d) 0,
map_add' := λ d₁ d₂, linear_map.ext $ λ x, begin
rw linear_map.add_apply,
induction x using clifford_algebra.left_induction with r x y hx hy m x hx,
{ simp_rw [foldr'_algebra_map, smul_zero, zero_add] },
{ rw [map_add, map_add, map_add, add_add_add_comm, hx, hy] },
{ rw [foldr'_ι_mul, foldr'_ι_mul, foldr'_ι_mul, hx],
dsimp only [contract_left_aux_apply_apply],
rw [sub_add_sub_comm, mul_add, linear_map.add_apply, add_smul] }
end,
map_smul' := λ c d, linear_map.ext $ λ x, begin
rw [linear_map.smul_apply, ring_hom.id_apply],
induction x using clifford_algebra.left_induction with r x y hx hy m x hx,
{ simp_rw [foldr'_algebra_map, smul_zero] },
{ rw [map_add, map_add, smul_add, hx, hy] },
{ rw [foldr'_ι_mul, foldr'_ι_mul, hx],
dsimp only [contract_left_aux_apply_apply],
rw [linear_map.smul_apply, smul_assoc, mul_smul_comm, smul_sub], }
end }
/-- Contract an element of the clifford algebra with an element `d : module.dual R M` from the
right.
Note that $x ⌊ v$ is spelt `contract_right x (Q.associated v)`.
This includes [grinberg_clifford_2016][] Theorem 16.75 -/
def contract_right : clifford_algebra Q →ₗ[R] module.dual R M →ₗ[R] clifford_algebra Q :=
linear_map.flip (linear_map.compl₂ (linear_map.compr₂ contract_left reverse) reverse)
lemma contract_right_eq (x : clifford_algebra Q) :
contract_right x d = reverse (contract_left d $ reverse x) := rfl
local infix `⌋`:70 := contract_left
local infix `⌊`:70 := contract_right
/-- This is [grinberg_clifford_2016][] Theorem 6 -/
lemma contract_left_ι_mul (a : M) (b : clifford_algebra Q) :
d ⌋ (ι Q a * b) = d a • b - ι Q a * (d ⌋ b) :=
foldr'_ι_mul _ _ _ _ _ _
/-- This is [grinberg_clifford_2016][] Theorem 12 -/
lemma contract_right_mul_ι (a : M) (b : clifford_algebra Q) :
(b * ι Q a) ⌊ d = d a • b - (b ⌊ d) * ι Q a :=
by rw [contract_right_eq, reverse.map_mul, reverse_ι, contract_left_ι_mul, map_sub, map_smul,
reverse_reverse, reverse.map_mul, reverse_ι, contract_right_eq]
lemma contract_left_algebra_map_mul (r : R) (b : clifford_algebra Q) :
d ⌋ (algebra_map _ _ r * b) = algebra_map _ _ r * (d ⌋ b) :=
by rw [←algebra.smul_def, map_smul, algebra.smul_def]
lemma contract_left_mul_algebra_map (a : clifford_algebra Q) (r : R) :
d ⌋ (a * algebra_map _ _ r) = (d ⌋ a) * algebra_map _ _ r :=
by rw [←algebra.commutes, contract_left_algebra_map_mul, algebra.commutes]
lemma contract_right_algebra_map_mul (r : R) (b : clifford_algebra Q) :
(algebra_map _ _ r * b) ⌊ d = algebra_map _ _ r * (b ⌊ d) :=
by rw [←algebra.smul_def, linear_map.map_smul₂, algebra.smul_def]
lemma contract_right_mul_algebra_map (a : clifford_algebra Q) (r : R) :
(a * algebra_map _ _ r) ⌊ d = (a ⌊ d) * algebra_map _ _ r :=
by rw [←algebra.commutes, contract_right_algebra_map_mul, algebra.commutes]
variables (Q)
@[simp] lemma contract_left_ι (x : M) : d ⌋ ι Q x = algebra_map R _ (d x) :=
(foldr'_ι _ _ _ _ _).trans $
by simp_rw [contract_left_aux_apply_apply, mul_zero, sub_zero, algebra.algebra_map_eq_smul_one]
@[simp] lemma contract_right_ι (x : M) : ι Q x ⌊ d = algebra_map R _ (d x) :=
by rw [contract_right_eq, reverse_ι, contract_left_ι, reverse.commutes]
@[simp] lemma contract_left_algebra_map (r : R) :
d ⌋ (algebra_map R (clifford_algebra Q) r) = 0 :=
(foldr'_algebra_map _ _ _ _ _).trans $ smul_zero _
@[simp] lemma contract_right_algebra_map (r : R) :
(algebra_map R (clifford_algebra Q) r) ⌊ d = 0 :=
by rw [contract_right_eq, reverse.commutes, contract_left_algebra_map, map_zero]
@[simp] lemma contract_left_one : d ⌋ (1 : clifford_algebra Q) = 0 :=
by simpa only [map_one] using contract_left_algebra_map Q d 1
@[simp] lemma contract_right_one : (1 : clifford_algebra Q) ⌊ d = 0 :=
by simpa only [map_one] using contract_right_algebra_map Q d 1
variables {Q}
/-- This is [grinberg_clifford_2016][] Theorem 7 -/
lemma contract_left_contract_left (x : clifford_algebra Q) :
d ⌋ (d ⌋ x) = 0 :=
begin
induction x using clifford_algebra.left_induction with r x y hx hy m x hx,
{ simp_rw [contract_left_algebra_map, map_zero] },
{ rw [map_add, map_add, hx, hy, add_zero] },
{ rw [contract_left_ι_mul, map_sub, contract_left_ι_mul, hx, linear_map.map_smul, mul_zero,
sub_zero, sub_self], }
end
/-- This is [grinberg_clifford_2016][] Theorem 13 -/
lemma contract_right_contract_right (x : clifford_algebra Q) :
(x ⌊ d) ⌊ d = 0 :=
by rw [contract_right_eq, contract_right_eq, reverse_reverse, contract_left_contract_left,
map_zero]
/-- This is [grinberg_clifford_2016][] Theorem 8 -/
lemma contract_left_comm (x : clifford_algebra Q) : d ⌋ (d' ⌋ x) = -(d' ⌋ (d ⌋ x)) :=
begin
induction x using clifford_algebra.left_induction with r x y hx hy m x hx,
{ simp_rw [contract_left_algebra_map, map_zero, neg_zero] },
{ rw [map_add, map_add, map_add, map_add, hx, hy, neg_add] },
{ simp only [contract_left_ι_mul, map_sub, linear_map.map_smul],
rw [neg_sub, sub_sub_eq_add_sub, hx, mul_neg, ←sub_eq_add_neg] }
end
/-- This is [grinberg_clifford_2016][] Theorem 14 -/
lemma contract_right_comm (x : clifford_algebra Q) : (x ⌊ d) ⌊ d' = -((x ⌊ d') ⌊ d) :=
by rw [contract_right_eq, contract_right_eq, contract_right_eq, contract_right_eq,
reverse_reverse, reverse_reverse, contract_left_comm, map_neg]
/- TODO:
lemma contract_right_contract_left (x : clifford_algebra Q) : (d ⌋ x) ⌊ d' = d ⌋ (x ⌊ d') :=
-/
end contract_left
local infix `⌋`:70 := contract_left
local infix `⌊`:70 := contract_right
/-- Auxiliary construction for `clifford_algebra.change_form` -/
@[simps]
def change_form_aux (B : bilin_form R M) : M →ₗ[R] clifford_algebra Q →ₗ[R] clifford_algebra Q :=
begin
have v_mul := (algebra.lmul R (clifford_algebra Q)).to_linear_map ∘ₗ ι Q,
exact v_mul - (contract_left ∘ₗ B.to_lin) ,
end
lemma change_form_aux_change_form_aux (B : bilin_form R M) (v : M) (x : clifford_algebra Q) :
change_form_aux Q B v (change_form_aux Q B v x) = (Q v - B v v) • x :=
begin
simp only [change_form_aux_apply_apply],
rw [mul_sub, ←mul_assoc, ι_sq_scalar, map_sub, contract_left_ι_mul, ←sub_add, sub_sub_sub_comm,
←algebra.smul_def, bilin_form.to_lin_apply, sub_self, sub_zero, contract_left_contract_left,
add_zero, sub_smul],
end
variables {Q}
variables {Q' Q'' : quadratic_form R M} {B B' : bilin_form R M}
variables (h : B.to_quadratic_form = Q' - Q) (h' : B'.to_quadratic_form = Q'' - Q')
/-- Convert between two algebras of different quadratic form, sending vector to vectors, scalars to
scalars, and adjusting products by a contraction term.
This is $\lambda_B$ from [bourbaki2007][] $9 Lemma 2. -/
def change_form (h : B.to_quadratic_form = Q' - Q) :
clifford_algebra Q →ₗ[R] clifford_algebra Q' :=
foldr Q (change_form_aux Q' B) (λ m x, (change_form_aux_change_form_aux Q' B m x).trans $
begin
dsimp [←bilin_form.to_quadratic_form_apply],
rw [h, quadratic_form.sub_apply, sub_sub_cancel],
end) 1
/-- Auxiliary lemma used as an argument to `clifford_algebra.change_form` -/
lemma change_form.zero_proof : (0 : bilin_form R M).to_quadratic_form = Q - Q :=
(sub_self _).symm
/-- Auxiliary lemma used as an argument to `clifford_algebra.change_form` -/
lemma change_form.add_proof : (B + B').to_quadratic_form = Q'' - Q :=
(congr_arg2 (+) h h').trans $ sub_add_sub_cancel' _ _ _
/-- Auxiliary lemma used as an argument to `clifford_algebra.change_form` -/
lemma change_form.neg_proof : (-B).to_quadratic_form = Q - Q' :=
(congr_arg has_neg.neg h).trans $ neg_sub _ _
lemma change_form.associated_neg_proof [invertible (2 : R)] :
(-Q).associated.to_quadratic_form = 0 - Q :=
by simp [quadratic_form.to_quadratic_form_associated]
@[simp]
lemma change_form_algebra_map (r : R) : change_form h (algebra_map R _ r) = algebra_map R _ r :=
(foldr_algebra_map _ _ _ _ _).trans $ eq.symm $ algebra.algebra_map_eq_smul_one r
@[simp] lemma change_form_one : change_form h (1 : clifford_algebra Q) = 1 :=
by simpa using change_form_algebra_map h (1 : R)
@[simp]
lemma change_form_ι (m : M) : change_form h (ι _ m) = ι _ m :=
(foldr_ι _ _ _ _ _).trans $ eq.symm $
by rw [change_form_aux_apply_apply, mul_one, contract_left_one, sub_zero]
lemma change_form_ι_mul (m : M) (x : clifford_algebra Q) :
change_form h (ι _ m * x) = ι _ m * change_form h x - bilin_form.to_lin B m ⌋ change_form h x :=
(foldr_mul _ _ _ _ _ _).trans $ begin rw foldr_ι, refl, end
lemma change_form_ι_mul_ι (m₁ m₂ : M) :
change_form h (ι _ m₁ * ι _ m₂) = ι _ m₁ * ι _ m₂ - algebra_map _ _ (B m₁ m₂) :=
by rw [change_form_ι_mul, change_form_ι, contract_left_ι, bilin_form.to_lin_apply]
/-- Theorem 23 of [grinberg_clifford_2016][] -/
lemma change_form_contract_left (d : module.dual R M) (x : clifford_algebra Q) :
change_form h (d ⌋ x) = d ⌋ change_form h x :=
begin
induction x using clifford_algebra.left_induction with r x y hx hy m x hx,
{ simp only [contract_left_algebra_map, change_form_algebra_map, map_zero] },
{ rw [map_add, map_add, map_add, map_add, hx, hy] },
{ simp only [contract_left_ι_mul, change_form_ι_mul, map_sub, linear_map.map_smul],
rw [←hx, contract_left_comm, ←sub_add, sub_neg_eq_add, ←hx] }
end
lemma change_form_self_apply (x : clifford_algebra Q) :
change_form (change_form.zero_proof) x = x :=
begin
induction x using clifford_algebra.left_induction with r x y hx hy m x hx,
{ simp_rw [change_form_algebra_map] },
{ rw [map_add, hx, hy] },
{ rw [change_form_ι_mul, hx, map_zero, linear_map.zero_apply, map_zero, linear_map.zero_apply,
sub_zero] }
end
@[simp]
lemma change_form_self :
change_form change_form.zero_proof = (linear_map.id : clifford_algebra Q →ₗ[R] _) :=
linear_map.ext $ change_form_self_apply
/-- This is [bourbaki2007][] $9 Lemma 3. -/
lemma change_form_change_form (x : clifford_algebra Q) :
change_form h' (change_form h x) = change_form (change_form.add_proof h h') x :=
begin
induction x using clifford_algebra.left_induction with r x y hx hy m x hx,
{ simp_rw [change_form_algebra_map] },
{ rw [map_add, map_add, map_add, hx, hy] },
{ rw [change_form_ι_mul, map_sub, change_form_ι_mul, change_form_ι_mul, hx, sub_sub, map_add,
linear_map.add_apply, map_add, linear_map.add_apply, change_form_contract_left, hx,
add_comm (_ : clifford_algebra Q'')] }
end
lemma change_form_comp_change_form :
(change_form h').comp (change_form h) = change_form (change_form.add_proof h h') :=
linear_map.ext $ change_form_change_form _ _
/-- Any two algebras whose quadratic forms differ by a bilinear form are isomorphic as modules.
This is $\bar \lambda_B$ from [bourbaki2007][] $9 Proposition 3. -/
@[simps apply]
def change_form_equiv : clifford_algebra Q ≃ₗ[R] clifford_algebra Q' :=
{ to_fun := change_form h,
inv_fun := change_form (change_form.neg_proof h),
left_inv := λ x, (change_form_change_form _ _ x).trans $
by simp_rw [add_right_neg, change_form_self_apply],
right_inv := λ x, (change_form_change_form _ _ x).trans $
by simp_rw [add_left_neg, change_form_self_apply],
..change_form h }
@[simp]
lemma change_form_equiv_symm :
(change_form_equiv h).symm = change_form_equiv (change_form.neg_proof h) :=
linear_equiv.ext $ λ x, (rfl : change_form _ x = change_form _ x)
variables (Q)
/-- The module isomorphism to the exterior algebra.
Note that this holds more generally when `Q` is divisible by two, rather than only when `1` is
divisible by two; but that would be more awkward to use. -/
@[simp]
def equiv_exterior [invertible (2 : R)] : clifford_algebra Q ≃ₗ[R] exterior_algebra R M :=
change_form_equiv change_form.associated_neg_proof
end clifford_algebra
|
c30a83ac0e2dc7d90663822196ca4c2a58cf5874 | f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58 | /algebra/field.lean | b6c62c49a0e15882cd9bbfbd83852c83abd698e7 | [
"Apache-2.0"
] | permissive | semorrison/mathlib | 1be6f11086e0d24180fec4b9696d3ec58b439d10 | 20b4143976dad48e664c4847b75a85237dca0a89 | refs/heads/master | 1,583,799,212,170 | 1,535,634,130,000 | 1,535,730,505,000 | 129,076,205 | 0 | 0 | Apache-2.0 | 1,551,697,998,000 | 1,523,442,265,000 | Lean | UTF-8 | Lean | false | false | 6,699 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import algebra.ring logic.basic
open set
universe u
variables {α : Type u}
instance division_ring.to_domain [s : division_ring α] : domain α :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h,
classical.by_contradiction $ λ hn,
division_ring.mul_ne_zero (mt or.inl hn) (mt or.inr hn) h
..s }
namespace units
variables [division_ring α] {a b : α}
/-- Embed an element of a division ring into the unit group.
By combining this function with the operations on units,
or the `/ₚ` operation, it is possible to write a division
as a partial function with three arguments. -/
def mk0 (a : α) (ha : a ≠ 0) : units α :=
⟨a, a⁻¹, mul_inv_cancel ha, inv_mul_cancel ha⟩
@[simp] theorem inv_eq_inv (u : units α) : (↑u⁻¹ : α) = u⁻¹ :=
(mul_left_inj u).1 $ by simp
@[simp] theorem mk0_val (ha : a ≠ 0) : (mk0 a ha : α) = a := rfl
@[simp] theorem mk0_inv (ha : a ≠ 0) : ((mk0 a ha)⁻¹ : α) = a⁻¹ := rfl
end units
section division_ring
variables [s : division_ring α] {a b c : α}
include s
lemma div_eq_mul_inv : a / b = a * b⁻¹ := rfl
attribute [simp] div_one zero_div div_self
theorem divp_eq_div (a : α) (u : units α) : a /ₚ u = a / u :=
by simp [divp, (/), algebra.div]
@[simp] theorem divp_mk0 (a : α) {b : α} (hb : b ≠ 0) :
a /ₚ units.mk0 b hb = a / b :=
divp_eq_div _ _
lemma inv_div (ha : a ≠ 0) (hb : b ≠ 0) : (a / b)⁻¹ = b / a :=
by rw [division_def, mul_inv_eq (inv_ne_zero hb) ha, division_ring.inv_inv hb, division_def]
lemma inv_div_left (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ / b = (b * a)⁻¹ :=
by rw [mul_inv_eq ha hb]; refl
lemma neg_inv (h : a ≠ 0) : - a⁻¹ = (- a)⁻¹ :=
by rwa [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div]
lemma division_ring.inv_comm_of_comm (h : a ≠ 0) (H : a * b = b * a) : a⁻¹ * b = b * a⁻¹ :=
begin
have : a⁻¹ * (b * a) * a⁻¹ = a⁻¹ * (a * b) * a⁻¹ :=
congr_arg (λ x:α, a⁻¹ * x * a⁻¹) H.symm,
rwa [mul_assoc, mul_assoc, mul_inv_cancel, mul_one,
← mul_assoc, inv_mul_cancel, one_mul] at this; exact h
end
lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 :=
division_ring.mul_ne_zero ha (inv_ne_zero hb)
lemma div_ne_zero_iff (hb : b ≠ 0) : a / b ≠ 0 ↔ a ≠ 0 :=
⟨mt (λ h, by simp [h]), λ ha, div_ne_zero ha hb⟩
lemma div_eq_zero_iff (hb : b ≠ 0) : a / b = 0 ↔ a = 0 :=
by haveI := classical.prop_decidable; exact
not_iff_not.1 (div_ne_zero_iff hb)
lemma add_div (a b c : α) : (a + b) / c = a / c + b / c :=
(div_add_div_same _ _ _).symm
lemma div_right_inj (hc : c ≠ 0) : a / c = b / c ↔ a = b :=
by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_right_inj]
lemma sub_div (a b c : α) : (a - b) / c = a / c - b / c :=
(div_sub_div_same _ _ _).symm
lemma division_ring.inv_inj (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ = b⁻¹ ↔ a = b :=
⟨λ h, by simpa [division_ring.inv_inv, ha, hb]
using congr_arg (λx,x⁻¹) h, congr_arg (λx,x⁻¹)⟩
lemma division_ring.inv_eq_iff (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ = b ↔ b⁻¹ = a :=
by rw [← division_ring.inv_inj (inv_ne_zero ha) hb,
eq_comm, division_ring.inv_inv ha]
lemma div_neg (a : α) (hb : b ≠ 0) : a / -b = -(a / b) :=
by rw [← division_ring.neg_div_neg_eq _ (neg_ne_zero.2 hb), neg_neg, neg_div]
lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a :=
⟨λ h, by rw [← h, div_mul_cancel _ hb],
λ h, by rw [← h, mul_div_cancel _ hb]⟩
end division_ring
instance field.to_integral_domain [F : field α] : integral_domain α :=
{ ..F, ..division_ring.to_domain }
section
variables [field α] {a b c d : α}
lemma div_eq_inv_mul : a / b = b⁻¹ * a := mul_comm _ _
lemma inv_add_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) :=
by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb]
lemma inv_sub_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) :=
by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one]
lemma mul_div_right_comm (a b c : α) : (a * b) / c = (a / c) * b :=
(div_mul_eq_mul_div _ _ _).symm
lemma mul_comm_div (a b c : α) : (a / b) * c = a * (c / b) :=
by rw [← mul_div_assoc, mul_div_right_comm]
lemma div_mul_comm (a b c : α) : (a / b) * c = (c / b) * a :=
by rw [div_mul_eq_mul_div, mul_comm, mul_div_right_comm]
lemma mul_div_comm (a b c : α) : a * (b / c) = b * (a / c) :=
by rw [← mul_div_assoc, mul_comm, mul_div_assoc]
lemma field.div_right_comm (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / b) / c = (a / c) / b :=
by rw [field.div_div_eq_div_mul _ hb hc, field.div_div_eq_div_mul _ hc hb, mul_comm]
lemma field.div_div_div_cancel_right (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / c) / (b / c) = a / b :=
by rw [field.div_div_eq_mul_div _ hb hc, div_mul_cancel _ hc]
lemma field.div_mul_div_cancel (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / c) * (c / b) = a / b :=
by rw [← mul_div_assoc, div_mul_cancel _ hc]
lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b :=
(domain.mul_right_inj (mul_ne_zero' hb hd)).symm.trans $
by rw [← mul_assoc, div_mul_cancel _ hb,
← mul_assoc, mul_right_comm, div_mul_cancel _ hd]
lemma field.div_div_cancel (ha : a ≠ 0) (hb : b ≠ 0) : a / (a / b) = b :=
by rw [div_eq_mul_inv, inv_div ha hb, mul_div_cancel' _ ha]
end
section
variables [discrete_field α] {a b c : α}
attribute [simp] inv_zero div_zero
lemma inv_sub_inv_eq (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) :=
have a * b ≠ 0, by simp [mul_eq_zero_iff_eq_zero_or_eq_zero, ha, hb],
calc (a⁻¹ - b⁻¹) = ((a⁻¹ - b⁻¹) * (a * b)) / (a * b) : by rwa [mul_div_cancel]
... = _ :
begin
simp [mul_add, add_mul, hb, mul_assoc, mul_comm, mul_left_comm],
rw [mul_comm a, mul_assoc, mul_comm a⁻¹, mul_inv_cancel ha],
simp
end
lemma div_right_comm (a b c : α) : (a / b) / c = (a / c) / b :=
if b0 : b = 0 then by simp [b0] else
if c0 : c = 0 then by simp [c0] else
field.div_right_comm _ b0 c0
lemma div_div_div_cancel_right (a b : α) (hc : c ≠ 0) : (a / c) / (b / c) = a / b :=
if b0 : b = 0 then by simp [b0] else
field.div_div_div_cancel_right _ b0 hc
lemma div_mul_div_cancel (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / c) * (c / b) = a / b :=
if b0 : b = 0 then by simp [b0] else
field.div_mul_div_cancel _ b0 hc
lemma div_div_cancel (ha : a ≠ 0) : a / (a / b) = b :=
if b0 : b = 0 then by simp [b0] else
field.div_div_cancel ha b0
end
|
fe6ebe03e1fb2603ac6dc166418c463e97e43c7e | 76df16d6c3760cb415f1294caee997cc4736e09b | /lean/src/cs/hp.lean | 5f86e2911a873a58421fb40d851dbdcedee4384c | [
"MIT"
] | permissive | uw-unsat/leanette-popl22-artifact | 70409d9cbd8921d794d27b7992bf1d9a4087e9fe | 80fea2519e61b45a283fbf7903acdf6d5528dbe7 | refs/heads/master | 1,681,592,449,670 | 1,637,037,431,000 | 1,637,037,431,000 | 414,331,908 | 6 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 6,310 | lean | import tactic.basic
import tactic.split_ifs
import tactic.linarith
import tactic.apply_fun
import .svm
import .lib
import .mrg
namespace sym
open lang
section hp
variables
{Model SymB SymV D O : Type}
[inhabited Model] [inhabited SymV]
(f : factory Model SymB SymV D O) {m : Model}
lemma factory.compose_hp {σ σ' : state SymB} :
¬ σ.normal f.to_has_eval m → state.eqv f.to_has_eval m (f.compose σ σ') σ :=
begin
intro hnn,
simp only [state.eqv, factory.compose],
simp only [state.normal, eq_ff_eq_not_eq_tt, not_and, bool.to_bool_and, bool.to_bool_coe, band_coe_iff] at hnn,
rewrite [f.and_sound, f.imp_sound],
rewrite [f.and_sound, f.imp_sound],
cases (f.to_has_eval.evalB m σ.assumes),
{ simp only [and_true, bool.to_bool_false, forall_prop_of_false,
bool.of_to_bool_iff, bool.coe_sort_ff, eq_self_iff_true,
bool.to_bool_coe, not_false_iff, false_and], },
{ simp only [forall_prop_of_true, bool.coe_sort_tt] at hnn,
simp only [hnn, bool.to_bool_false, forall_prop_of_false, bool.to_bool_true, bool.coe_sort_ff, eq_self_iff_true,
bool.to_bool_coe, not_false_iff, and_self, false_and], }
end
lemma factory.strengthen_hp {σ : state SymB} {ρ : result SymB SymV} :
¬ σ.normal f.to_has_eval m → state.eqv f.to_has_eval m (f.strengthen σ ρ).state σ :=
begin
intro hn,
cases ρ with σ' v σ',
{ simp only [factory.strengthen, factory.halt_or_ans],
cases (f.halted (f.compose σ σ')),
all_goals {
simp only [result.state, bool.coe_sort_ff, if_false, if_true, bool.coe_sort_tt],
apply f.compose_hp hn, }, },
{ simp only [factory.strengthen, result.state],
apply f.compose_hp hn, }
end
lemma factory.assert_hp {σ : state SymB} {b : SymB} :
¬ σ.normal f.to_has_eval m → state.eqv f.to_has_eval m (f.assert σ b) σ :=
begin
intro hnn,
simp only [state.normal, eq_ff_eq_not_eq_tt, not_and, bool.to_bool_and, bool.to_bool_coe, band_coe_iff] at hnn,
simp only [state.eqv, factory.assert, true_and, eq_self_iff_true],
rewrite [f.and_sound, f.imp_sound],
cases (f.to_has_eval.evalB m σ.assumes),
{ simp only [and_true, forall_prop_of_false, bool.to_bool_true,
bool.coe_sort_ff, bool.coe_sort_tt, bool.to_bool_coe,
not_false_iff], },
{ simp only [hnn, bool.to_bool_false, bool.coe_sort_ff, bool.coe_sort_tt,
false_and], }
end
lemma factory.assume_hp {σ : state SymB} {b : SymB} :
¬ σ.normal f.to_has_eval m → state.eqv f.to_has_eval m (f.assume σ b) σ :=
begin
intro hnn,
simp only [state.normal, eq_ff_eq_not_eq_tt, not_and, bool.to_bool_and, bool.to_bool_coe, band_coe_iff] at hnn,
simp only [state.eqv, factory.assume, true_and, eq_self_iff_true],
rewrite [f.and_sound, f.imp_sound],
cases (f.to_has_eval.evalB m σ.assumes),
{ simp only [bool.to_bool_false, bool.coe_sort_ff, eq_self_iff_true, and_self, false_and], },
{ simp only [hnn, forall_prop_of_false, bool.to_bool_true,
bool.coe_sort_ff, bool.coe_sort_tt, eq_self_iff_true,
not_false_iff, and_self], }
end
-- The SVM rules preserve the semantics of halted states across steps:
-- if the asserts or assumes evaluate to false under a model in the start
-- state, then the value of both the assumes and the asserts under that model
-- remains the same in the end state.
theorem svm_hp {x : exp D O} {ε : env SymV} {σ : state SymB} {ρ : result SymB SymV} :
¬ σ.normal f.to_has_eval m → evalS f x ε σ ρ → ρ.state.eqv f.to_has_eval m σ :=
begin
intros hnn hs,
induction hs,
case sym.evalS.app { apply f.strengthen_hp hnn, },
case sym.evalS.call_sym {
have hnn' : ¬↥(state.normal f.to_has_eval m hs_σ') :=
by { rewrite hs_h3, apply state.eqv_abnormal f.to_has_eval hnn, symmetry, apply f.assert_hp hnn, },
transitivity hs_σ',
{ apply f.merge_ρ_eqp,
intros i hr,
rcases (list.map_bound (eq.symm hs_h5) hr) with hc,
specialize hs_ih_h6 i hc hr,
transitivity (f.assume hs_σ' (list.nth_le (f.cast hs_c) i hc).guard),
{ apply hs_ih_h6,
apply state.eqv_abnormal f.to_has_eval hnn,
transitivity hs_σ',
{ rewrite hs_h3, symmetry, apply f.assert_hp hnn, },
{ symmetry,
apply f.assume_hp,
apply state.eqv_abnormal f.to_has_eval hnn,
symmetry,
rewrite hs_h3,
apply f.assert_hp hnn, } },
{ apply f.assume_hp hnn', } },
{ rewrite hs_h3,
apply f.assert_hp hnn, } },
case sym.evalS.call_halt {
rewrite hs_h3,
simp only [result.state],
apply f.assert_hp hnn, },
case sym.evalS.let0 {
specialize hs_ih_h1 hnn,
simp only [result.state] at hs_ih_h1,
transitivity hs_σ',
{ apply hs_ih_h2,
apply state.eqv_abnormal f.to_has_eval hnn (state.eqv.symm f.to_has_eval m hs_ih_h1), },
{ exact hs_ih_h1, } },
case sym.evalS.let0_halt { apply hs_ih hnn, },
case sym.evalS.if0_true { apply hs_ih_hr hnn, },
case sym.evalS.if0_false { apply hs_ih_hr hnn, },
case sym.evalS.if0_sym {
apply f.merge_ρ_eqp,
intros i hi,
simp only [list.length, zero_add] at hi,
rcases (nat.lt2_implies_01 hi) with hi01,
cases hi01; simp only [hi01, list.nth_le],
{ transitivity (f.assume hs_σ (f.truth hs_v)),
{ apply hs_ih_ht,
apply state.eqv_abnormal f.to_has_eval hnn,
symmetry,
apply f.assume_hp hnn, },
{ apply f.assume_hp hnn, } },
{ transitivity (f.assume hs_σ (f.not (f.truth hs_v))),
{ apply hs_ih_hf,
apply state.eqv_abnormal f.to_has_eval hnn,
symmetry,
apply f.assume_hp hnn, },
{ apply f.assume_hp hnn, } } },
case sym.evalS.error {
simp only [result.state],
apply f.assert_hp hnn, },
case sym.evalS.abort {
simp only [result.state],
apply f.assume_hp hnn, },
all_goals { -- bool, datum, lam, var
solve1 { simp only [result.state, eq_self_iff_true, and_self], } },
end
end hp
end sym |
5dbc3e0bffbd031cc439b6a393539ea59916ff1b | 56e5b79a7ab4f2c52e6eb94f76d8100a25273cf3 | /src/evaluation/bfs/baseline.lean | 3b97623da9ace96d5326d887f328d572f0e91ca8 | [
"Apache-2.0"
] | permissive | DyeKuu/lean-tpe-public | 3a9968f286ca182723ef7e7d97e155d8cb6b1e70 | 750ade767ab28037e80b7a80360d213a875038f8 | refs/heads/master | 1,682,842,633,115 | 1,621,330,793,000 | 1,621,330,793,000 | 368,475,816 | 0 | 0 | Apache-2.0 | 1,621,330,745,000 | 1,621,330,744,000 | null | UTF-8 | Lean | false | false | 841 | lean | import evaluation_step
import backends.bfs.baseline
import utils
section main
open baseline
-- use this version for testing using tidy_greedy_proof_search
meta def main : io unit := do {
args ← io.cmdline_args,
decls_file ← args.nth_except 0 "decls_file",
dest ← args.nth_except 1 "dest",
fuel ← string.to_nat <$> args.nth_except 2 "fuel",
max_width ← string.to_nat <$> args.nth_except 3 "max_width",
max_depth ← string.to_nat <$> args.nth_except 4 "max_depth",
tac_timeout ← string.to_nat <$> args.nth_except 5 "tac_timeout",
global_timeout ← string.to_nat <$> args.nth_except 6 "global_timeout",
evaluation_harness_from_decls_file
(tidy_bfs_proof_search_core fuel)
(decls_file)
(dest) global_timeout $
BFSState.of_current_state 0 max_width max_depth tac_timeout
}
end main
|
e2ea1d3080f9f6ece6d7f4f9a34e852d17c980d9 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/set_theory/ordinal/cantor_normal_form.lean | 148bc847319ef3dd03d752e38a8de96fbab172b5 | [
"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,511 | 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 set_theory.ordinal.arithmetic
/-!
# Cantor Normal Form
The Cantor normal form of an ordinal is generally defined as its base `ω` expansion, with its
non-zero exponents in decreasing order. Here, we more generally define a base `b` expansion
`ordinal.CNF` in this manner, which is well-behaved for any `b ≥ 2`.
# Implementation notes
We implement `ordinal.CNF` as an association list, where keys are exponents and values are
coefficients. This is because this structure intrinsically reflects two key properties of the Cantor
normal form:
- It is ordered.
- It has finitely many entries.
# Todo
- Add API for the coefficients of the Cantor normal form.
- Prove the basic results relating the CNF to the arithmetic operations on ordinals.
-/
noncomputable theory
universe u
open order
namespace ordinal
/-- Inducts on the base `b` expansion of an ordinal. -/
@[elab_as_eliminator] noncomputable def CNF_rec (b : ordinal)
{C : ordinal → Sort*} (H0 : C 0) (H : ∀ o, o ≠ 0 → C (o % b ^ log b o) → C o) : ∀ o, C o
| o :=
if ho : o = 0 then by rwa ho else
let hwf := mod_opow_log_lt_self b ho in H o ho (CNF_rec (o % b ^ log b o))
using_well_founded {dec_tac := `[assumption]}
@[simp] theorem CNF_rec_zero {C : ordinal → Sort*} (b : ordinal)
(H0 : C 0) (H : ∀ o, o ≠ 0 → C (o % b ^ log b o) → C o) : @CNF_rec b C H0 H 0 = H0 :=
by { rw [CNF_rec, dif_pos rfl], refl }
theorem CNF_rec_pos (b : ordinal) {o : ordinal} {C : ordinal → Sort*} (ho : o ≠ 0)
(H0 : C 0) (H : ∀ o, o ≠ 0 → C (o % b ^ log b o) → C o) :
@CNF_rec b C H0 H o = H o ho (@CNF_rec b C H0 H _) :=
by rw [CNF_rec, dif_neg ho]
/-- The Cantor normal form of an ordinal `o` is the list of coefficients and exponents in the
base-`b` expansion of `o`.
We special-case `CNF 0 o = CNF 1 o = [(0, o)]` for `o ≠ 0`.
`CNF b (b ^ u₁ * v₁ + b ^ u₂ * v₂) = [(u₁, v₁), (u₂, v₂)]` -/
@[pp_nodot] def CNF (b o : ordinal) : list (ordinal × ordinal) :=
CNF_rec b [] (λ o ho IH, (log b o, o / b ^ log b o) :: IH) o
@[simp] theorem CNF_zero (b : ordinal) : CNF b 0 = [] := CNF_rec_zero b _ _
/-- Recursive definition for the Cantor normal form. -/
theorem CNF_ne_zero {b o : ordinal} (ho : o ≠ 0) :
CNF b o = (log b o, o / b ^ log b o) :: CNF b (o % b ^ log b o) :=
CNF_rec_pos b ho _ _
theorem zero_CNF {o : ordinal} (ho : o ≠ 0) : CNF 0 o = [⟨0, o⟩] := by simp [CNF_ne_zero ho]
theorem one_CNF {o : ordinal} (ho : o ≠ 0) : CNF 1 o = [⟨0, o⟩] := by simp [CNF_ne_zero ho]
theorem CNF_of_le_one {b o : ordinal} (hb : b ≤ 1) (ho : o ≠ 0) : CNF b o = [⟨0, o⟩] :=
begin
rcases le_one_iff.1 hb with rfl | rfl,
{ exact zero_CNF ho },
{ exact one_CNF ho }
end
theorem CNF_of_lt {b o : ordinal} (ho : o ≠ 0) (hb : o < b) : CNF b o = [⟨0, o⟩] :=
by simp [CNF_ne_zero ho, log_eq_zero hb]
/-- Evaluating the Cantor normal form of an ordinal returns the ordinal. -/
theorem CNF_foldr (b o : ordinal) : (CNF b o).foldr (λ p r, b ^ p.1 * p.2 + r) 0 = o :=
CNF_rec b (by { rw CNF_zero, refl })
(λ o ho IH, by rw [CNF_ne_zero ho, list.foldr_cons, IH, div_add_mod]) o
/-- Every exponent in the Cantor normal form `CNF b o` is less or equal to `log b o`. -/
theorem CNF_fst_le_log {b o : ordinal.{u}} {x : ordinal × ordinal} :
x ∈ CNF b o → x.1 ≤ log b o :=
begin
refine CNF_rec b _ (λ o ho H, _) o,
{ rw CNF_zero,
exact false.elim },
{ rw [CNF_ne_zero ho, list.mem_cons_iff],
rintro (rfl | h),
{ exact le_rfl },
{ exact (H h).trans (log_mono_right _ (mod_opow_log_lt_self b ho).le) } }
end
/-- Every exponent in the Cantor normal form `CNF b o` is less or equal to `o`. -/
theorem CNF_fst_le {b o : ordinal.{u}} {x : ordinal × ordinal} (h : x ∈ CNF b o) : x.1 ≤ o :=
(CNF_fst_le_log h).trans $ log_le_self _ _
/-- Every coefficient in a Cantor normal form is positive. -/
theorem CNF_lt_snd {b o : ordinal.{u}} {x : ordinal × ordinal} : x ∈ CNF b o → 0 < x.2 :=
begin
refine CNF_rec b _ (λ o ho IH, _) o,
{ simp },
{ rcases eq_zero_or_pos b with rfl | hb,
{ rw [zero_CNF ho, list.mem_singleton],
rintro rfl,
exact ordinal.pos_iff_ne_zero.2 ho },
{ rw CNF_ne_zero ho,
rintro (rfl | h),
{ simp,
rw div_pos,
{ exact opow_log_le_self _ ho },
{ exact (opow_pos _ hb).ne' } },
{ exact IH h } } }
end
/-- Every coefficient in the Cantor normal form `CNF b o` is less than `b`. -/
theorem CNF_snd_lt {b o : ordinal.{u}} (hb : 1 < b) {x : ordinal × ordinal} :
x ∈ CNF b o → x.2 < b :=
begin
refine CNF_rec b _ (λ o ho IH, _) o,
{ simp },
{ rw CNF_ne_zero ho,
rintro (rfl | h),
{ simpa using div_opow_log_lt o hb },
{ exact IH h } }
end
/-- The exponents of the Cantor normal form are decreasing. -/
theorem CNF_sorted (b o : ordinal) : ((CNF b o).map prod.fst).sorted (>) :=
begin
refine CNF_rec b _ (λ o ho IH, _) o,
{ simp },
{ cases le_or_lt b 1 with hb hb,
{ simp [CNF_of_le_one hb ho] },
{ cases lt_or_le o b with hob hbo,
{ simp [CNF_of_lt ho hob] },
{ rw [CNF_ne_zero ho, list.map_cons, list.sorted_cons],
refine ⟨λ a H, _, IH⟩,
rw list.mem_map at H,
rcases H with ⟨⟨a, a'⟩, H, rfl⟩,
exact (CNF_fst_le_log H).trans_lt (log_mod_opow_log_lt_log_self hb ho hbo) } } }
end
end ordinal
|
3cc690fd65051198e64a39f57860187ae387a951 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/topology/algebra/mul_action.lean | b5719e3c8d659846243cb5ee73137405c1ae0715 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 6,765 | 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.algebra.constructions
import group_theory.group_action.prod
import group_theory.group_action.basic
import topology.algebra.const_mul_action
/-!
# Continuous monoid action
In this file we define class `has_continuous_smul`. We say `has_continuous_smul M X` if `M` acts on
`X` and the map `(c, x) ↦ c • x` is continuous on `M × X`. We reuse this class for topological
(semi)modules, vector spaces and algebras.
## Main definitions
* `has_continuous_smul M X` : typeclass saying that the map `(c, x) ↦ c • x` is continuous
on `M × X`;
* `homeomorph.smul_of_ne_zero`: if a group with zero `G₀` (e.g., a field) acts on `X` and `c : G₀`
is a nonzero element of `G₀`, then scalar multiplication by `c` is a homeomorphism of `X`;
* `homeomorph.smul`: scalar multiplication by an element of a group `G` acting on `X`
is a homeomorphism of `X`.
* `units.has_continuous_smul`: scalar multiplication by `Mˣ` is continuous when scalar
multiplication by `M` is continuous. This allows `homeomorph.smul` to be used with on monoids
with `G = Mˣ`.
## Main results
Besides homeomorphisms mentioned above, in this file we provide lemmas like `continuous.smul`
or `filter.tendsto.smul` that provide dot-syntax access to `continuous_smul`.
-/
open_locale topological_space pointwise
open filter
/-- Class `has_continuous_smul M X` says that the scalar multiplication `(•) : M → X → X`
is continuous in both arguments. We use the same class for all kinds of multiplicative actions,
including (semi)modules and algebras. -/
class has_continuous_smul (M X : Type*) [has_smul M X]
[topological_space M] [topological_space X] : Prop :=
(continuous_smul : continuous (λp : M × X, p.1 • p.2))
export has_continuous_smul (continuous_smul)
/-- Class `has_continuous_vadd M X` says that the additive action `(+ᵥ) : M → X → X`
is continuous in both arguments. We use the same class for all kinds of additive actions,
including (semi)modules and algebras. -/
class has_continuous_vadd (M X : Type*) [has_vadd M X]
[topological_space M] [topological_space X] : Prop :=
(continuous_vadd : continuous (λp : M × X, p.1 +ᵥ p.2))
export has_continuous_vadd (continuous_vadd)
attribute [to_additive] has_continuous_smul
section main
variables {M X Y α : Type*} [topological_space M] [topological_space X] [topological_space Y]
section has_smul
variables [has_smul M X] [has_continuous_smul M X]
@[priority 100, to_additive] instance has_continuous_smul.has_continuous_const_smul :
has_continuous_const_smul M X :=
{ continuous_const_smul := λ _, continuous_smul.comp (continuous_const.prod_mk continuous_id) }
@[to_additive]
lemma filter.tendsto.smul {f : α → M} {g : α → X} {l : filter α} {c : M} {a : X}
(hf : tendsto f l (𝓝 c)) (hg : tendsto g l (𝓝 a)) :
tendsto (λ x, f x • g x) l (𝓝 $ c • a) :=
(continuous_smul.tendsto _).comp (hf.prod_mk_nhds hg)
@[to_additive]
lemma filter.tendsto.smul_const {f : α → M} {l : filter α} {c : M}
(hf : tendsto f l (𝓝 c)) (a : X) :
tendsto (λ x, (f x) • a) l (𝓝 (c • a)) :=
hf.smul tendsto_const_nhds
variables {f : Y → M} {g : Y → X} {b : Y} {s : set Y}
@[to_additive]
lemma continuous_within_at.smul (hf : continuous_within_at f s b)
(hg : continuous_within_at g s b) :
continuous_within_at (λ x, f x • g x) s b :=
hf.smul hg
@[to_additive]
lemma continuous_at.smul (hf : continuous_at f b) (hg : continuous_at g b) :
continuous_at (λ x, f x • g x) b :=
hf.smul hg
@[to_additive]
lemma continuous_on.smul (hf : continuous_on f s) (hg : continuous_on g s) :
continuous_on (λ x, f x • g x) s :=
λ x hx, (hf x hx).smul (hg x hx)
@[continuity, to_additive]
lemma continuous.smul (hf : continuous f) (hg : continuous g) :
continuous (λ x, f x • g x) :=
continuous_smul.comp (hf.prod_mk hg)
/-- If a scalar is central, then its right action is continuous when its left action is. -/
instance has_continuous_smul.op [has_smul Mᵐᵒᵖ X] [is_central_scalar M X] :
has_continuous_smul Mᵐᵒᵖ X :=
⟨ suffices continuous (λ p : M × X, mul_opposite.op p.fst • p.snd),
from this.comp (mul_opposite.continuous_unop.prod_map continuous_id),
by simpa only [op_smul_eq_smul] using (continuous_smul : continuous (λ p : M × X, _)) ⟩
@[to_additive] instance mul_opposite.has_continuous_smul : has_continuous_smul M Xᵐᵒᵖ :=
⟨mul_opposite.continuous_op.comp $ continuous_smul.comp $
continuous_id.prod_map mul_opposite.continuous_unop⟩
end has_smul
section monoid
variables [monoid M] [mul_action M X] [has_continuous_smul M X]
@[to_additive] instance units.has_continuous_smul : has_continuous_smul Mˣ X :=
{ continuous_smul :=
show continuous ((λ p : M × X, p.fst • p.snd) ∘ (λ p : Mˣ × X, (p.1, p.2))),
from continuous_smul.comp ((units.continuous_coe.comp continuous_fst).prod_mk continuous_snd) }
end monoid
@[to_additive]
instance [has_smul M X] [has_smul M Y] [has_continuous_smul M X]
[has_continuous_smul M Y] :
has_continuous_smul M (X × Y) :=
⟨(continuous_fst.smul (continuous_fst.comp continuous_snd)).prod_mk
(continuous_fst.smul (continuous_snd.comp continuous_snd))⟩
@[to_additive]
instance {ι : Type*} {γ : ι → Type*}
[∀ i, topological_space (γ i)] [Π i, has_smul M (γ i)] [∀ i, has_continuous_smul M (γ i)] :
has_continuous_smul M (Π i, γ i) :=
⟨continuous_pi $ λ i,
(continuous_fst.smul continuous_snd).comp $
continuous_fst.prod_mk ((continuous_apply i).comp continuous_snd)⟩
end main
section lattice_ops
variables {ι : Sort*} {M X : Type*} [topological_space M] [has_smul M X]
@[to_additive] lemma has_continuous_smul_Inf {ts : set (topological_space X)}
(h : Π t ∈ ts, @has_continuous_smul M X _ _ t) :
@has_continuous_smul M X _ _ (Inf ts) :=
{ continuous_smul :=
begin
rw ← @Inf_singleton _ _ ‹topological_space M›,
exact continuous_Inf_rng.2 (λ t ht, continuous_Inf_dom₂ (eq.refl _) ht
(@has_continuous_smul.continuous_smul _ _ _ _ t (h t ht)))
end }
@[to_additive] lemma has_continuous_smul_infi {ts' : ι → topological_space X}
(h : Π i, @has_continuous_smul M X _ _ (ts' i)) :
@has_continuous_smul M X _ _ (⨅ i, ts' i) :=
has_continuous_smul_Inf $ set.forall_range_iff.mpr h
@[to_additive] lemma has_continuous_smul_inf {t₁ t₂ : topological_space X}
[@has_continuous_smul M X _ _ t₁] [@has_continuous_smul M X _ _ t₂] :
@has_continuous_smul M X _ _ (t₁ ⊓ t₂) :=
by { rw inf_eq_infi, refine has_continuous_smul_infi (λ b, _), cases b; assumption }
end lattice_ops
|
6cc33475f735ac6b18b48c541bd2d0af3fb73a86 | 618003631150032a5676f229d13a079ac875ff77 | /test/interval_cases.lean | 1c4d65a2ea8854be769f7557e831203409c6dacd | [
"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 | 3,887 | 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 tactic.interval_cases
example (n : ℕ) : true :=
begin
success_if_fail { interval_cases n },
trivial
end
example (n : ℕ) (h : 2 ≤ n) : true :=
begin
success_if_fail { interval_cases n },
trivial
end
example (n m : ℕ) (h : n ≤ m) : true :=
begin
success_if_fail { interval_cases n },
trivial,
end
example (n : ℕ) (w₂ : n < 0) : false :=
by interval_cases n
example (n : ℕ) (w₂ : n < 1) : n = 0 :=
by { interval_cases n, }
example (n : ℕ) (w₂ : n < 2) : n = 0 ∨ n = 1 :=
by { interval_cases n, { left, refl }, { right, refl }, }
example (n : ℕ) (w₁ : 1 ≤ n) (w₂ : n < 3) : n = 1 ∨ n = 2 :=
by { interval_cases n, { left, refl }, { right, refl }, }
example (n : ℕ) (w₁ : 1 ≤ n) (w₂ : n < 3) : n = 1 ∨ n = 2 :=
by { interval_cases using w₁ w₂, { left, refl }, { right, refl }, }
-- make sure we only pick up bounds on the specified variable:
example (n m : ℕ) (w₁ : 1 ≤ n) (w₂ : n < 3) (w₃ : m < 2) : n = 1 ∨ n = 2 :=
by { interval_cases n, { left, refl }, { right, refl }, }
example (n : ℕ) (w₁ : 1 < n) (w₂ : n < 4) : n = 2 ∨ n = 3 :=
by { interval_cases n, { left, refl }, { right, refl }, }
example (n : ℕ) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 :=
by { interval_cases n, { left, refl }, { right, refl }, }
example (n : ℕ) (w₀ : n ≥ 2) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 :=
by { interval_cases n, { left, refl }, { right, refl }, }
example (n : ℕ) (w₁ : n > 2) (w₂ : n < 5) : n = 3 ∨ n = 4 :=
by { interval_cases n, { left, refl }, { right, refl }, }
example (n : ℕ) (w₁ : n > 2) (w₂ : n ≤ 4) : n = 3 ∨ n = 4 :=
by { interval_cases n, { left, refl }, { right, refl }, }
example (n : ℕ) (w₁ : 2 < n) (w₂ : 4 ≥ n) : n = 3 ∨ n = 4 :=
by { interval_cases n, { left, refl }, { right, refl }, }
example (n : ℕ) (h1 : 4 < n) (h2 : n ≤ 6) : n < 20 :=
begin
interval_cases n,
guard_target 5 < 20, norm_num,
guard_target 6 < 20, norm_num,
end
example (n : ℕ) (w₁ : n % 3 < 1) : n % 3 = 0 :=
by { interval_cases n % 3, assumption }
example (n : ℕ) (h1 : 4 ≤ n) (h2 : n < 10) : n < 20 :=
begin
interval_cases using h1 h2,
all_goals {norm_num}
end
example (n : ℕ+) (w₂ : n < 1) : false :=
by interval_cases n
example (n : ℕ+) (w₂ : n < 2) : n = 1 :=
by interval_cases n
example (n : ℕ+) (h1 : 4 ≤ n) (h2 : n < 5) : n = 4 :=
by interval_cases n
example (n : ℕ+) (w₁ : 2 < n) (w₂ : 4 ≥ n) : n = 3 ∨ n = 4 :=
begin
interval_cases n,
{ guard_target (3 : ℕ+) = 3 ∨ (3 : ℕ+) = 4, left, refl },
{ guard_target (4 : ℕ+) = 3 ∨ (4 : ℕ+) = 4, right, refl },
end
example (n : ℕ+) (w₁ : 1 < n) (w₂ : n < 4) : n = 2 ∨ n = 3 :=
by { interval_cases n, { left, refl }, { right, refl }, }
example (n : ℕ+) (w₂ : n < 3) : n = 1 ∨ n = 2 :=
by { interval_cases n, { left, refl }, { right, refl }, }
example (n : ℕ+) (w₂ : n < 4) : n = 1 ∨ n = 2 ∨ n = 3 :=
by { interval_cases n, { left, refl }, { right, left, refl }, { right, right, refl }, }
example (z : ℤ) (h1 : z ≥ -3) (h2 : z < 2) : z < 20 :=
begin
interval_cases using h1 h2,
all_goals {norm_num}
end
example (z : ℤ) (h1 : z ≥ -3) (h2 : z < 2) : z < 20 :=
begin
interval_cases z,
guard_target (-3 : ℤ) < 20, norm_num,
guard_target (-2 : ℤ) < 20, norm_num,
guard_target (-1 : ℤ) < 20, norm_num,
guard_target (0 : ℤ) < 20, norm_num,
guard_target (1 : ℤ) < 20, norm_num,
end
/-
Sadly, this one doesn't work, reporting:
`deep recursion was detected at 'expression equality test'`
-/
-- example (n : ℕ) (w₁ : n > 1000000) (w₁ : n < 1000002) : n < 2000000 :=
-- begin
-- interval_cases n,
-- norm_num,
-- end
|
749e95a7b40b7c4b7e17dd8be713954694eb4ad9 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/deprecated/group.lean | a5ff15ccb53fcbee48ca2e1fd2b0ff88b3d9c821 | [
"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 | 12,520 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury Kudryashov
-/
import algebra.group.type_tags
import algebra.group.units_hom
import algebra.ring.basic
/-!
# Unbundled monoid and group homomorphisms (deprecated)
This file defines typeclasses for unbundled monoid and group homomorphisms. Though these classes are
deprecated, they are still widely used in mathlib, and probably will not go away before Lean 4
because Lean 3 often fails to coerce a bundled homomorphism to a function.
## main definitions
monoid_hom, is_monoid_hom (deprecated), is_group_hom (deprecated)
## implementation notes
There's a coercion from bundled homs to fun, and the canonical
notation is to use the bundled hom as a function via this coercion.
There is no `group_hom` -- the idea is that `monoid_hom` is used.
The constructor for `monoid_hom` needs a proof of `map_one` as well
as `map_mul`; a separate constructor `monoid_hom.mk'` will construct
group homs (i.e. monoid homs between groups) given only a proof
that multiplication is preserved,
Throughout the `monoid_hom` section implicit `{}` brackets are often used instead of type class `[]`
brackets. This is done when the instances can be inferred because they are implicit arguments to
the type `monoid_hom`. When they can be inferred from the type it is faster to use this method than
to use type class inference.
## Tags
is_group_hom, is_monoid_hom, monoid_hom
-/
/--
We have lemmas stating that the composition of two morphisms is again a morphism.
Since composition is reducible, type class inference will always succeed in applying these instances.
For example when the goal is just `⊢ is_mul_hom f` the instance `is_mul_hom.comp`
will still succeed, unifying `f` with `f ∘ (λ x, x)`. This causes type class inference to loop.
To avoid this, we do not make these lemmas instances.
-/
library_note "no instance on morphisms"
universes u v
variables {α : Type u} {β : Type v}
/-- Predicate for maps which preserve an addition. -/
class is_add_hom {α β : Type*} [has_add α] [has_add β] (f : α → β) : Prop :=
(map_add [] : ∀ x y, f (x + y) = f x + f y)
/-- Predicate for maps which preserve a multiplication. -/
@[to_additive]
class is_mul_hom {α β : Type*} [has_mul α] [has_mul β] (f : α → β) : Prop :=
(map_mul [] : ∀ x y, f (x * y) = f x * f y)
namespace is_mul_hom
variables [has_mul α] [has_mul β] {γ : Type*} [has_mul γ]
/-- The identity map preserves multiplication. -/
@[to_additive "The identity map preserves addition"]
instance id : is_mul_hom (id : α → α) := {map_mul := λ _ _, rfl}
/-- The composition of maps which preserve multiplication, also preserves multiplication. -/
-- see Note [no instance on morphisms]
@[to_additive "The composition of addition preserving maps also preserves addition"]
lemma comp (f : α → β) (g : β → γ) [is_mul_hom f] [hg : is_mul_hom g] : is_mul_hom (g ∘ f) :=
{ map_mul := λ x y, by simp only [function.comp, map_mul f, map_mul g] }
/-- A product of maps which preserve multiplication,
preserves multiplication when the target is commutative. -/
@[instance, priority 10, to_additive]
lemma mul {α β} [semigroup α] [comm_semigroup β]
(f g : α → β) [is_mul_hom f] [is_mul_hom g] :
is_mul_hom (λa, f a * g a) :=
{ map_mul := assume a b, by simp only [map_mul f, map_mul g, mul_comm, mul_assoc, mul_left_comm] }
/-- The inverse of a map which preserves multiplication,
preserves multiplication when the target is commutative. -/
@[instance, to_additive]
lemma inv {α β} [has_mul α] [comm_group β] (f : α → β) [is_mul_hom f] :
is_mul_hom (λa, (f a)⁻¹) :=
{ map_mul := assume a b, (map_mul f a b).symm ▸ mul_inv _ _ }
end is_mul_hom
section prio
set_option default_priority 100 -- see Note [default priority]
/-- Predicate for add_monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/
class is_add_monoid_hom [add_monoid α] [add_monoid β] (f : α → β) extends is_add_hom f : Prop :=
(map_zero [] : f 0 = 0)
/-- Predicate for monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/
@[to_additive is_add_monoid_hom]
class is_monoid_hom [monoid α] [monoid β] (f : α → β) extends is_mul_hom f : Prop :=
(map_one [] : f 1 = 1)
end prio
namespace monoid_hom
variables {M : Type*} {N : Type*} {P : Type*} [mM : monoid M] [mN : monoid N] {mP : monoid P}
variables {G : Type*} {H : Type*} [group G] [comm_group H]
include mM mN
/-- Interpret a map `f : M → N` as a homomorphism `M →* N`. -/
@[to_additive "Interpret a map `f : M → N` as a homomorphism `M →+ N`."]
def of (f : M → N) [h : is_monoid_hom f] : M →* N :=
{ to_fun := f,
map_one' := h.2,
map_mul' := h.1.1 }
variables {mM mN mP}
@[simp, to_additive]
lemma coe_of (f : M → N) [is_monoid_hom f] : ⇑ (monoid_hom.of f) = f :=
rfl
@[to_additive is_add_monoid_hom]
instance (f : M →* N) : is_monoid_hom (f : M → N) :=
{ map_mul := f.map_mul,
map_one := f.map_one }
end monoid_hom
namespace is_monoid_hom
variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
/-- A monoid homomorphism preserves multiplication. -/
@[to_additive]
lemma map_mul (x y) : f (x * y) = f x * f y :=
is_mul_hom.map_mul f x y
end is_monoid_hom
/-- A map to a group preserving multiplication is a monoid homomorphism. -/
@[to_additive]
theorem is_monoid_hom.of_mul [monoid α] [group β] (f : α → β) [is_mul_hom f] :
is_monoid_hom f :=
{ map_one := mul_self_iff_eq_one.1 $ by rw [← is_mul_hom.map_mul f, one_mul] }
namespace is_monoid_hom
variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
/-- The identity map is a monoid homomorphism. -/
@[to_additive]
instance id : is_monoid_hom (@id α) := { map_one := rfl }
/-- The composite of two monoid homomorphisms is a monoid homomorphism. -/
@[to_additive] -- see Note [no instance on morphisms]
lemma comp {γ} [monoid γ] (g : β → γ) [is_monoid_hom g] :
is_monoid_hom (g ∘ f) :=
{ map_one := show g _ = 1, by rw [map_one f, map_one g], ..is_mul_hom.comp _ _ }
end is_monoid_hom
namespace is_add_monoid_hom
/-- Left multiplication in a ring is an additive monoid morphism. -/
instance is_add_monoid_hom_mul_left {γ : Type*} [semiring γ] (x : γ) :
is_add_monoid_hom (λ y : γ, x * y) :=
{ map_zero := mul_zero x, map_add := λ y z, mul_add x y z }
/-- Right multiplication in a ring is an additive monoid morphism. -/
instance is_add_monoid_hom_mul_right {γ : Type*} [semiring γ] (x : γ) :
is_add_monoid_hom (λ y : γ, y * x) :=
{ map_zero := zero_mul x, map_add := λ y z, add_mul y z x }
end is_add_monoid_hom
section prio
set_option default_priority 100 -- see Note [default priority]
/-- Predicate for additive group homomorphism (deprecated -- use bundled `monoid_hom`). -/
class is_add_group_hom [add_group α] [add_group β] (f : α → β) extends is_add_hom f : Prop
/-- Predicate for group homomorphisms (deprecated -- use bundled `monoid_hom`). -/
@[to_additive is_add_group_hom]
class is_group_hom [group α] [group β] (f : α → β) extends is_mul_hom f : Prop
end prio
@[to_additive is_add_group_hom]
instance monoid_hom.is_group_hom {G H : Type*} {_ : group G} {_ : group H} (f : G →* H) :
is_group_hom (f : G → H) :=
{ map_mul := f.map_mul }
/-- Construct `is_group_hom` from its only hypothesis. The default constructor tries to get
`is_mul_hom` from class instances, and this makes some proofs fail. -/
@[to_additive]
lemma is_group_hom.mk' [group α] [group β] {f : α → β} (hf : ∀ x y, f (x * y) = f x * f y) :
is_group_hom f :=
{ map_mul := hf }
namespace is_group_hom
variables [group α] [group β] (f : α → β) [is_group_hom f]
open is_mul_hom (map_mul)
/-- A group homomorphism is a monoid homomorphism. -/
@[priority 100, to_additive to_is_add_monoid_hom] -- see Note [lower instance priority]
instance to_is_monoid_hom : is_monoid_hom f :=
is_monoid_hom.of_mul f
/-- A group homomorphism sends 1 to 1. -/
@[to_additive]
lemma map_one : f 1 = 1 := is_monoid_hom.map_one f
/-- A group homomorphism sends inverses to inverses. -/
@[to_additive]
theorem map_inv (a : α) : f a⁻¹ = (f a)⁻¹ :=
eq_inv_of_mul_eq_one $ by rw [← map_mul f, inv_mul_self, map_one f]
/-- The identity is a group homomorphism. -/
@[to_additive]
instance id : is_group_hom (@id α) := { }
/-- The composition of two group homomomorphisms is a group homomorphism. -/
@[to_additive] -- see Note [no instance on morphisms]
lemma comp {γ} [group γ] (g : β → γ) [is_group_hom g] : is_group_hom (g ∘ f) :=
{ ..is_mul_hom.comp _ _ }
/-- A group homomorphism is injective iff its kernel is trivial. -/
@[to_additive]
lemma injective_iff (f : α → β) [is_group_hom f] :
function.injective f ↔ (∀ a, f a = 1 → a = 1) :=
⟨λ h _, by rw ← is_group_hom.map_one f; exact @h _ _,
λ h x y hxy, by rw [← inv_inv (f x), inv_eq_iff_mul_eq_one, ← map_inv f,
← map_mul f] at hxy;
simpa using inv_eq_of_mul_eq_one (h _ hxy)⟩
/-- The product of group homomorphisms is a group homomorphism if the target is commutative. -/
@[instance, priority 10, to_additive]
lemma mul {α β} [group α] [comm_group β]
(f g : α → β) [is_group_hom f] [is_group_hom g] :
is_group_hom (λa, f a * g a) :=
{ }
/-- The inverse of a group homomorphism is a group homomorphism if the target is commutative. -/
@[instance, to_additive]
lemma inv {α β} [group α] [comm_group β] (f : α → β) [is_group_hom f] :
is_group_hom (λa, (f a)⁻¹) :=
{ }
end is_group_hom
/-- Inversion is a group homomorphism if the group is commutative. -/
@[instance, to_additive is_add_group_hom]
lemma inv.is_group_hom [comm_group α] : is_group_hom (has_inv.inv : α → α) :=
{ map_mul := mul_inv }
namespace is_add_group_hom
variables [add_group α] [add_group β] (f : α → β) [is_add_group_hom f]
/-- Additive group homomorphisms commute with subtraction. -/
lemma map_sub (a b) : f (a - b) = f a - f b :=
calc f (a + -b) = f a + f (-b) : is_add_hom.map_add f _ _
... = f a + -f b : by rw [map_neg f]
end is_add_group_hom
/-- The difference of two additive group homomorphisms is an additive group
homomorphism if the target is commutative. -/
@[instance]
lemma is_add_group_hom.sub {α β} [add_group α] [add_comm_group β]
(f g : α → β) [is_add_group_hom f] [is_add_group_hom g] :
is_add_group_hom (λa, f a - g a) :=
is_add_group_hom.add f (λa, - g a)
namespace units
variables {M : Type*} {N : Type*} [monoid M] [monoid N]
/-- The group homomorphism on units induced by a multiplicative morphism. -/
@[reducible] def map' (f : M → N) [is_monoid_hom f] : units M →* units N :=
map (monoid_hom.of f)
@[simp] lemma coe_map' (f : M → N) [is_monoid_hom f] (x : units M) :
↑((map' f : units M → units N) x) = f x :=
rfl
instance coe_is_monoid_hom : is_monoid_hom (coe : units M → M) := (coe_hom M).is_monoid_hom
end units
namespace is_unit
variables {M : Type*} {N : Type*} [monoid M] [monoid N] {x : M}
lemma map' (f : M → N) {x : M} (h : is_unit x) [is_monoid_hom f] :
is_unit (f x) :=
h.map (monoid_hom.of f)
end is_unit
lemma additive.is_add_hom [has_mul α] [has_mul β] (f : α → β) [is_mul_hom f] :
@is_add_hom (additive α) (additive β) _ _ f :=
{ map_add := @is_mul_hom.map_mul α β _ _ f _ }
lemma multiplicative.is_mul_hom [has_add α] [has_add β] (f : α → β) [is_add_hom f] :
@is_mul_hom (multiplicative α) (multiplicative β) _ _ f :=
{ map_mul := @is_add_hom.map_add α β _ _ f _ }
lemma additive.is_add_monoid_hom [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] :
@is_add_monoid_hom (additive α) (additive β) _ _ f :=
{ map_zero := @is_monoid_hom.map_one α β _ _ f _,
..additive.is_add_hom f }
lemma multiplicative.is_monoid_hom [add_monoid α] [add_monoid β] (f : α → β) [is_add_monoid_hom f] :
@is_monoid_hom (multiplicative α) (multiplicative β) _ _ f :=
{ map_one := @is_add_monoid_hom.map_zero α β _ _ f _,
..multiplicative.is_mul_hom f }
lemma additive.is_add_group_hom [group α] [group β] (f : α → β) [is_group_hom f] :
@is_add_group_hom (additive α) (additive β) _ _ f :=
{ map_add := @is_mul_hom.map_mul α β _ _ f _ }
lemma multiplicative.is_group_hom [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] :
@is_group_hom (multiplicative α) (multiplicative β) _ _ f :=
{ map_mul := @is_add_hom.map_add α β _ _ f _ }
|
4e23a2dda467744efe382ed0bd69b64b45de7bdd | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/sites/whiskering.lean | 595368886b0d1323cb6a5bf30fe3c90ff55678c3 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 4,247 | lean | /-
Copyright (c) 2021 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz
-/
import category_theory.sites.sheaf
/-!
In this file we construct the functor `Sheaf J A ⥤ Sheaf J B` between sheaf categories
obtained by composition with a functor `F : A ⥤ B`.
In order for the sheaf condition to be preserved, `F` must preserve the correct limits.
The lemma `presheaf.is_sheaf.comp` says that composition with such an `F` indeed preserves the
sheaf condition.
The functor between sheaf categories is called `Sheaf_compose J F`.
Given a natural transformation `η : F ⟶ G`, we obtain a natural transformation
`Sheaf_compose J F ⟶ Sheaf_compose J G`, which we call `Sheaf_compose_map J η`.
-/
namespace category_theory
open category_theory.limits
universes v₁ v₂ u₁ u₂ u₃
variables {C : Type u₁} [category.{v₁} C]
variables {A : Type u₂} [category.{max v₁ u₁} A]
variables {B : Type u₃} [category.{max v₁ u₁} B]
variables {J : grothendieck_topology C}
variables {U : C} (R : presieve U)
variables (F : A ⥤ B)
namespace grothendieck_topology.cover
variables (P : Cᵒᵖ ⥤ A) {X : C} (S : J.cover X)
/-- The multicospan associated to a cover `S : J.cover X` and a presheaf of the form `P ⋙ F`
is isomorphic to the composition of the multicospan associated to `S` and `P`,
composed with `F`. -/
def multicospan_comp : (S.index (P ⋙ F)).multicospan ≅ (S.index P).multicospan ⋙ F :=
nat_iso.of_components (λ t,
match t with
| walking_multicospan.left a := eq_to_iso rfl
| walking_multicospan.right b := eq_to_iso rfl
end) begin
rintros (a|b) (a|b) (f|f|f),
any_goals { dsimp, erw [functor.map_id, functor.map_id, category.id_comp] },
any_goals { dsimp, erw [category.comp_id, category.id_comp], refl }
end
@[simp] lemma multicospan_comp_app_left (a) :
(S.multicospan_comp F P).app (walking_multicospan.left a) = eq_to_iso rfl := rfl
@[simp] lemma multicospan_comp_app_right (b) :
(S.multicospan_comp F P).app (walking_multicospan.right b) = eq_to_iso rfl := rfl
@[simp] lemma multicospan_comp_hom_app_left (a) :
(S.multicospan_comp F P).hom.app (walking_multicospan.left a) = eq_to_hom rfl := rfl
@[simp] lemma multicospan_comp_hom_app_right (b) :
(S.multicospan_comp F P).hom.app (walking_multicospan.right b) = eq_to_hom rfl := rfl
@[simp] lemma multicospan_comp_hom_inv_left (P : Cᵒᵖ ⥤ A) {X : C}
(S : J.cover X) (a) : (S.multicospan_comp F P).inv.app (walking_multicospan.left a) =
eq_to_hom rfl := rfl
@[simp] lemma multicospan_comp_hom_inv_right (P : Cᵒᵖ ⥤ A) {X : C}
(S : J.cover X) (b) : (S.multicospan_comp F P).inv.app (walking_multicospan.right b) =
eq_to_hom rfl := rfl
/-- Mapping the multifork associated to a cover `S : J.cover X` and a presheaf `P` with
respect to a functor `F` is isomorphic (upto a natural isomorphism of the underlying functors)
to the multifork associated to `S` and `P ⋙ F`. -/
def map_multifork : F.map_cone (S.multifork P) ≅ (limits.cones.postcompose
(S.multicospan_comp F P).hom).obj (S.multifork (P ⋙ F)) :=
cones.ext (eq_to_iso rfl) begin
rintros (a|b),
{ dsimp, simpa },
{ dsimp, simp, dsimp [multifork.of_ι], simpa }
end
end grothendieck_topology.cover
variables [∀ (X : C) (S : J.cover X) (P : Cᵒᵖ ⥤ A), preserves_limit (S.index P).multicospan F]
lemma presheaf.is_sheaf.comp {P : Cᵒᵖ ⥤ A} (hP : presheaf.is_sheaf J P) :
presheaf.is_sheaf J (P ⋙ F) :=
begin
rw presheaf.is_sheaf_iff_multifork at ⊢ hP,
intros X S,
obtain ⟨h⟩ := hP X S,
replace h := is_limit_of_preserves F h,
replace h := limits.is_limit.of_iso_limit h (S.map_multifork F P),
exact ⟨limits.is_limit.postcompose_hom_equiv (S.multicospan_comp F P) _ h⟩,
end
variable (J)
/-- Composing a sheaf with a functor preserving the appropriate limits yields a functor
between sheaf categories. -/
@[simps]
def Sheaf_compose : Sheaf J A ⥤ Sheaf J B :=
{ obj := λ G, ⟨G.val ⋙ F, presheaf.is_sheaf.comp _ G.2⟩,
map := λ G H η, ⟨whisker_right η.val _⟩,
map_id' := λ G, Sheaf.hom.ext _ _ $ whisker_right_id _,
map_comp' := λ G H W f g, Sheaf.hom.ext _ _ $ whisker_right_comp _ _ _ }
end category_theory
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.