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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e89a36d88d10d49f314ca4bdb2007a5ff8bdf00 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /tests/lean/run/meta1.lean | 590a6ac87a43808b1854b8bdc51ebba002f6b344 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,041 | lean | import Lean.Meta
open Lean
open Lean.Meta
unsafe def tstInferType (mods : List Name) (e : Expr) : IO Unit :=
withImportModules (mods.map $ fun m => {module := m}) 0 fun env => do
(type, _, _) ← (inferType e : MetaM _).toIO {} { env := env } {} {};
IO.println (toString e ++ " : " ++ toString type)
unsafe def tstWHNF (mods : List Name) (e : Expr) (t := TransparencyMode.default) : IO Unit :=
withImportModules (mods.map $ fun m => {module := m}) 0 fun env => do
(s, _, _) ← (whnf e : MetaM _).toIO {} { env := env };
IO.println (toString e ++ " ==> " ++ toString s)
unsafe def tstIsProp (mods : List Name) (e : Expr) : IO Unit :=
withImportModules (mods.map $ fun m => {module := m}) 0 fun env => do
(b, _, _) ← (isProp e : MetaM _).toIO {} { env := env };
IO.println (toString e ++ ", isProp: " ++ toString b)
def t1 : Expr :=
let map := mkConst `List.map [levelOne, levelOne];
let nat := mkConst `Nat [];
let bool := mkConst `Bool [];
mkAppN map #[nat, bool]
#eval tstInferType [`Init.Data.List] t1
def t2 : Expr :=
let prop := mkSort levelZero;
mkForall `x BinderInfo.default prop prop
#eval tstInferType [`Init.Core] t2
def t3 : Expr :=
let nat := mkConst `Nat [];
let natLe := mkConst `Nat.le [];
let zero := mkLit (Literal.natVal 0);
let p := mkAppN natLe #[mkBVar 0, zero];
mkForall `x BinderInfo.default nat p
#eval tstInferType [`Init.Data.Nat] t3
def t4 : Expr :=
let nat := mkConst `Nat [];
let p := mkAppN (mkConst `Nat.succ []) #[mkBVar 0];
mkLambda `x BinderInfo.default nat p
#eval tstInferType [`Init.Core] t4
def t5 : Expr :=
let add := mkConst `Nat.add [];
mkAppN add #[mkLit (Literal.natVal 3), mkLit (Literal.natVal 5)]
#eval tstWHNF [`Init.Data.Nat] t5
#eval tstWHNF [`Init.Data.Nat] t5 TransparencyMode.reducible
set_option pp.all true
#check @List.cons Nat
def t6 : Expr :=
let map := mkConst `List.map [levelOne, levelOne];
let nat := mkConst `Nat [];
let add := mkConst `Nat.add [];
let f := mkLambda `x BinderInfo.default nat (mkAppN add #[mkBVar 0, mkLit (Literal.natVal 1)]);
let cons := mkApp (mkConst `List.cons [levelZero]) nat;
let nil := mkApp (mkConst `List.nil [levelZero]) nat;
let one := mkLit (Literal.natVal 1);
let four := mkLit (Literal.natVal 4);
let xs := mkApp (mkApp cons one) (mkApp (mkApp cons four) nil);
mkAppN map #[nat, nat, f, xs]
#eval tstInferType [`Init.Data.List] t6
#eval tstWHNF [`Init.Data.List] t6
#eval tstInferType [] $ mkSort levelZero
#eval tstInferType [`Init.Data.List] $ mkLambda `a BinderInfo.implicit (mkSort levelOne) (mkLambda `x BinderInfo.default (mkBVar 0) (mkLambda `xs BinderInfo.default (mkApp (mkConst `List [levelZero]) (mkBVar 1)) (mkBVar 0)))
def t7 : Expr :=
let nat := mkConst `Nat [];
let one := mkLit (Literal.natVal 1);
mkLet `x nat one one
#eval tstInferType [`Init.Core] $ t7
#eval tstWHNF [`Init.Core] $ t7
def t8 : Expr :=
let nat := mkConst `Nat [];
let one := mkLit (Literal.natVal 1);
let add := mkConst `Nat.add [];
mkLet `x nat one (mkAppN add #[one, mkBVar 0])
#eval tstInferType [`Init.Core] $ t8
#eval tstWHNF [`Init.Core] $ t8
def t9 : Expr :=
let nat := mkConst `Nat [];
mkLet `a (mkSort levelOne) nat (mkForall `x BinderInfo.default (mkBVar 0) (mkBVar 1))
#eval tstInferType [`Init.Core] $ t9
#eval tstWHNF [`Init.Core] $ t9
#eval tstInferType [`Init.Core] $ mkLit (Literal.natVal 10)
#eval tstInferType [`Init.Core] $ mkLit (Literal.strVal "hello")
#eval tstInferType [`Init.Core] $ mkMData {} $ mkLit (Literal.natVal 10)
#eval tstInferType [`Lean.Util.Trace] (mkProj `Inhabited 0 (mkConst `Lean.TraceState.Inhabited []))
#eval tstInferType [`Lean.Util.Trace] (mkProj `Lean.TraceState 0 (mkProj `Inhabited 0 (mkConst `Lean.TraceState.Inhabited [])))
#eval tstWHNF [`Lean.Util.Trace] (mkProj `Inhabited 0 (mkConst `Lean.TraceState.Inhabited []))
#eval tstWHNF [`Lean.Util.Trace] (mkProj `Lean.TraceState 0 (mkProj `Inhabited 0 (mkConst `Lean.TraceState.Inhabited [])))
def t10 : Expr :=
let nat := mkConst `Nat [];
let refl := mkApp (mkConst `Eq.refl [levelOne]) nat;
mkLambda `a BinderInfo.default nat (mkApp refl (mkBVar 0))
#eval tstInferType [`Init.Core] t10
#eval tstIsProp [`Init.Core] t10
#eval tstIsProp [`Init.Core] (mkAppN (mkConst `And []) #[mkConst `True [], mkConst `True []])
#eval tstIsProp [`Init.Core] (mkConst `And [])
-- Example where isPropQuick fails
#eval tstIsProp [`Init.Core] (mkAppN (mkConst `id [levelZero]) #[mkSort levelZero, mkAppN (mkConst `And []) #[mkConst `True [], mkConst
`True []]])
#eval tstIsProp [`Init.Core] (mkAppN (mkConst `Eq [levelOne]) #[mkConst `Nat [], mkLit (Literal.natVal 0), mkLit (Literal.natVal 1)])
#eval tstIsProp [`Init.Core] $
mkForall `x BinderInfo.default (mkConst `Nat [])
(mkAppN (mkConst `Eq [levelOne]) #[mkConst `Nat [], mkBVar 0, mkLit (Literal.natVal 1)])
#eval tstIsProp [`Init.Core] $
mkApp
(mkLambda `x BinderInfo.default (mkConst `Nat [])
(mkAppN (mkConst `Eq [levelOne]) #[mkConst `Nat [], mkBVar 0, mkLit (Literal.natVal 1)]))
(mkLit (Literal.natVal 0))
|
9d0bd70ece27f0fa6a313880c1d51a70e8b1b3b8 | b3fced0f3ff82d577384fe81653e47df68bb2fa1 | /src/data/finsupp.lean | 17d147bd1b7912ea8daa1dcc8cf1f2cf2f468632 | [
"Apache-2.0"
] | permissive | ratmice/mathlib | 93b251ef5df08b6fd55074650ff47fdcc41a4c75 | 3a948a6a4cd5968d60e15ed914b1ad2f4423af8d | refs/heads/master | 1,599,240,104,318 | 1,572,981,183,000 | 1,572,981,183,000 | 219,830,178 | 0 | 0 | Apache-2.0 | 1,572,980,897,000 | 1,572,980,896,000 | null | UTF-8 | Lean | false | false | 61,668 | 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
Type of functions with finite support.
Functions with finite support provide the basis for the following concrete instances:
* ℕ →₀ α: Polynomials (where α is a ring)
* (σ →₀ ℕ) →₀ α: Multivariate Polynomials (again α is a ring, and σ are variable names)
* α →₀ ℕ: Multisets
* α →₀ ℤ: Abelian groups freely generated by α
* β →₀ α: Linear combinations over β where α is the scalar ring
Most of the theory assumes that the range is a commutative monoid. This gives us the big sum
operator as a powerful way to construct `finsupp` elements.
A general advice is to not use α →₀ β directly, as the type class setup might not be fitting.
The best is to define a copy and select the instances best suited.
-/
import data.finset data.set.finite algebra.big_operators algebra.module
noncomputable theory
open_locale classical
open finset
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Type*}
{α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*}
/-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that
`f x = 0` for all but finitely many `x`. -/
structure finsupp (α : Type*) (β : Type*) [has_zero β] :=
(support : finset α)
(to_fun : α → β)
(mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0)
infixr ` →₀ `:25 := finsupp
namespace finsupp
section basic
variable [has_zero β]
instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, finsupp.to_fun⟩
instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩
@[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 := rfl
@[simp] lemma support_zero : (0 : α →₀ β).support = ∅ := rfl
instance : inhabited (α →₀ β) := ⟨0⟩
@[simp] lemma mem_support_iff {f : α →₀ β} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 :=
f.mem_support_to_fun
lemma not_mem_support_iff {f : α →₀ β} {a} : a ∉ f.support ↔ f a = 0 :=
not_iff_comm.1 mem_support_iff.symm
@[extensionality]
lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g
| ⟨s, f, hf⟩ ⟨t, g, hg⟩ h :=
begin
have : f = g, { funext a, exact h a },
subst this,
have : s = t, { ext a, exact (hf a).trans (hg a).symm },
subst this
end
lemma ext_iff {f g : α →₀ β} : f = g ↔ (∀a:α, f a = g a) :=
⟨by rintros rfl a; refl, ext⟩
@[simp] lemma support_eq_empty {f : α →₀ β} : f.support = ∅ ↔ f = 0 :=
⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext.1 h a).1 $
mem_support_iff.2 H, by rintro rfl; refl⟩
instance finsupp.decidable_eq [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) :=
assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a))
⟨assume ⟨h₁, h₂⟩, ext $ assume a,
if h : a ∈ f.support then h₂ a h else
have hf : f a = 0, by rwa [mem_support_iff, not_not] at h,
have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h,
by rw [hf, hg],
by rintro rfl; exact ⟨rfl, λ _ _, rfl⟩⟩
lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} :=
⟨fintype.of_finset f.support (λ _, mem_support_iff)⟩
lemma support_subset_iff {s : set α} {f : α →₀ β} :
↑f.support ⊆ s ↔ (∀a∉s, f a = 0) :=
by simp only [set.subset_def, mem_coe, mem_support_iff];
exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _))
def equiv_fun_on_fintype [fintype α] : (α →₀ β) ≃ (α → β) :=
⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp),
begin intro f, ext a, refl end,
begin intro f, ext a, refl end⟩
end basic
section single
variables [has_zero β] {a a' : α} {b : β}
/-- `single a b` is the finitely supported function which has
value `b` at `a` and zero otherwise. -/
def single (a : α) (b : β) : α →₀ β :=
⟨if b = 0 then ∅ else finset.singleton a, λ a', if a = a' then b else 0, λ a', begin
by_cases hb : b = 0; by_cases a = a';
simp only [hb, h, if_pos, if_false, mem_singleton],
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨λ _, hb, λ _, rfl⟩ },
{ exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ }
end⟩
lemma single_apply : (single a b : α →₀ β) a' = if a = a' then b else 0 := rfl
@[simp] lemma single_eq_same : (single a b : α →₀ β) a = b := if_pos rfl
@[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 := if_neg h
@[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, single_eq_same, zero_apply] },
{ rw [single_eq_of_ne h, zero_apply] }
end
lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} :=
if_neg hb
lemma support_single_subset : (single a b).support ⊆ {a} :=
show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _]
lemma injective_single (a : α) : function.injective (single a : β → α →₀ β) :=
assume b₁ b₂ eq,
have (single a b₁ : α →₀ β) a = (single a b₂ : α →₀ β) a, by rw eq,
by rwa [single_eq_same, single_eq_same] at this
lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : β) :
single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) :=
begin
split,
{ assume eq,
by_cases a₁ = a₂,
{ refine or.inl ⟨h, _⟩,
rwa [h, (injective_single a₂).eq_iff] at eq },
{ rw [finsupp.ext_iff] at eq,
have h₁ := eq a₁,
have h₂ := eq a₂,
simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂,
exact or.inr ⟨h₁, h₂.symm⟩ } },
{ rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩),
{ refl },
{ rw [single_zero, single_zero] } }
end
lemma single_right_inj (h : b ≠ 0) :
single a b = single a' b ↔ a = a' :=
⟨λ H, by simpa [h, single_eq_single_iff] using H, λ H, by rw [H]⟩
lemma single_eq_zero : single a b = 0 ↔ b = 0 :=
⟨λ h, by { rw ext_iff at h, simpa only [finsupp.single_eq_same, finsupp.zero_apply] using h a },
λ h, by rw [h, single_zero]⟩
lemma single_swap {α β : Type*} [has_zero β] (a₁ a₂ : α) (b : β) :
(single a₁ b : α → β) a₂ = (single a₂ b : α → β) a₁ :=
by simp [single_apply]; ac_refl
lemma unique_single [unique α] (x : α →₀ β) : x = single (default α) (x (default α)) :=
by ext i; simp [unique.eq_default i]
@[simp] lemma unique_single_eq_iff [unique α] {b' : β} :
single a b = single a' b' ↔ b = b' :=
begin
rw [single_eq_single_iff],
split,
{ rintros (⟨_, rfl⟩ | ⟨rfl, rfl⟩); refl },
{ intro h, left, exact ⟨subsingleton.elim _ _, h⟩ }
end
end single
section on_finset
variables [has_zero β]
/-- `on_finset s f hf` is the finsupp function representing `f` restricted to the set `s`.
The function needs to be 0 outside of `s`. Use this when the set needs filtered anyway, otherwise
often better set representation is available. -/
def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β :=
⟨s.filter (λa, f a ≠ 0), f,
assume a, classical.by_cases
(assume h : f a = 0, by rw mem_filter; exact ⟨and.right, λ H, (H h).elim⟩)
(assume h : f a ≠ 0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩
@[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} :
(on_finset s f hf : α →₀ β) a = f a :=
rfl
@[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} :
(on_finset s f hf).support ⊆ s := filter_subset _
end on_finset
section map_range
variables [has_zero β₁] [has_zero β₂]
/-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is
`map_range f hf g : α →₀ β₂`, well defined when `f 0 = 0`. -/
def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ :=
on_finset g.support (f ∘ g) $
assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf
@[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} :
map_range f hf g a = f (g a) :=
rfl
@[simp] lemma map_range_zero {f : β₁ → β₂} {hf : f 0 = 0} : map_range f hf (0 : α →₀ β₁) = 0 :=
finsupp.ext $ λ a, by simp [hf]
lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} :
(map_range f hf g).support ⊆ g.support :=
support_on_finset_subset
@[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} :
map_range f hf (single a b) = single a (f b) :=
finsupp.ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf]
end map_range
section emb_domain
variables [has_zero β]
/-- Given `f : α₁ ↪ α₂` and `v : α₁ →₀ β`, `emb_domain f v : α₂ →₀ β` is the finitely supported
function whose value at `f a : α₂` is `v a`. For a `b : α₂` outside the range of `f` it is zero. -/
def emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
begin
refine ⟨v.support.map f, λa₂,
if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩,
{ rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩,
exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.inj hb) },
{ assume a₂,
split_ifs,
{ simp [h],
rw [← finsupp.not_mem_support_iff, not_not],
apply finset.choose_mem },
{ simp [h] } }
end
lemma support_emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
(emb_domain f v).support = v.support.map f :=
rfl
lemma emb_domain_zero (f : α₁ ↪ α₂) : (emb_domain f 0 : α₂ →₀ β) = 0 :=
rfl
lemma emb_domain_apply (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₁) :
emb_domain f v (f a) = v a :=
begin
change dite _ _ _ = _,
split_ifs; rw [finset.mem_map' f] at h,
{ refine congr_arg (v : α₁ → β) (f.inj' _),
exact finset.choose_property (λa₁, f a₁ = f a) _ _ },
{ exact (finsupp.not_mem_support_iff.1 h).symm }
end
lemma emb_domain_notin_range (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
emb_domain f v a = 0 :=
begin
refine dif_neg (mt (assume h, _) h),
rcases finset.mem_map.1 h with ⟨a, h, rfl⟩,
exact set.mem_range_self a
end
lemma emb_domain_inj {f : α₁ ↪ α₂} {l₁ l₂ : α₁ →₀ β} :
emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ :=
⟨λ h, finsupp.ext $ λ a, by simpa [emb_domain_apply] using finsupp.ext_iff.1 h (f a),
λ h, by rw h⟩
lemma emb_domain_map_range
{β₁ β₂ : Type*} [has_zero β₁] [has_zero β₂]
(f : α₁ ↪ α₂) (g : β₁ → β₂) (p : α₁ →₀ β₁) (hg : g 0 = 0) :
emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a', rfl⟩,
rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] },
{ rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption }
end
lemma single_of_emb_domain_single
(l : α₁ →₀ β) (f : α₁ ↪ α₂) (a : α₂) (b : β) (hb : b ≠ 0)
(h : l.emb_domain f = finsupp.single a b) :
∃ x, l = finsupp.single x b ∧ f x = a :=
begin
have h_map_support : finset.map f (l.support) = finset.singleton a,
by rw [←finsupp.support_emb_domain, h, finsupp.support_single_ne_zero hb]; refl,
have ha : a ∈ finset.map f (l.support),
by simp [h_map_support],
rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩,
use c,
split,
{ ext d,
rw [← finsupp.emb_domain_apply f l, h],
by_cases h_cases : c = d,
{ simp [h_cases.symm, hc₂] },
{ rw [finsupp.single_apply, finsupp.single_apply, if_neg, if_neg h_cases],
by_contra hfd,
exact h_cases (f.inj (hc₂.trans hfd)) } },
{ exact hc₂ }
end
end emb_domain
section zip_with
variables [has_zero β] [has_zero β₁] [has_zero β₂]
/-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying
`zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and well defined when `f 0 0 = 0`. -/
def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) :=
on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin
simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib],
rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf
end
@[simp] lemma zip_with_apply
{f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} :
zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl
lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} :
(zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support :=
support_on_finset_subset
end zip_with
section erase
def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β :=
⟨f.support.erase a, (λa', if a' = a then 0 else f a'),
assume a', by rw [mem_erase, mem_support_iff]; split_ifs;
[exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩,
exact and_iff_right h]⟩
@[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} :
(f.erase a).support = f.support.erase a :=
rfl
@[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 :=
if_pos rfl
@[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' :=
if_neg h
end erase
-- [to_additive sum] for finsupp.prod doesn't work, the equation lemmas are not generated
/-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/
def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
f.support.sum (λa, g a (f a))
/-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/
@[to_additive]
def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
f.support.prod (λa, g a (f a))
@[to_additive]
lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ]
{f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) :
(map_range f hf g).prod h = g.prod (λa b, h a (f b)) :=
finset.prod_subset support_map_range $ λ _ _ H,
by rw [not_mem_support_iff.1 H, h0]
@[to_additive]
lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} :
(0 : α →₀ β).prod h = 1 := rfl
section nat_sub
instance nat_sub : has_sub (α →₀ ℕ) := ⟨zip_with (λ m n, m - n) (nat.sub_zero 0)⟩
@[simp] lemma nat_sub_apply {g₁ g₂ : α →₀ ℕ} {a : α} :
(g₁ - g₂) a = g₁ a - g₂ a := rfl
end nat_sub
section add_monoid
variables [add_monoid β]
@[to_additive]
lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) :
(single a b).prod h = h a b :=
begin
by_cases h : b = 0,
{ simp only [h, h_zero, single_zero]; refl },
{ simp only [finsupp.prod, support_single_ne_zero h, insert_empty_eq_singleton,
prod_singleton, single_eq_same] }
end
instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩
@[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a :=
rfl
lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support :=
support_zip_with
lemma support_add_eq {g₁ g₂ : α →₀ β} (h : disjoint g₁.support g₂.support) :
(g₁ + g₂).support = g₁.support ∪ g₂.support :=
le_antisymm support_zip_with $ assume a ha,
(finset.mem_union.1 ha).elim
(assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, add_zero])
(assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, zero_add])
@[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] },
{ rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] }
end
instance : add_monoid (α →₀ β) :=
{ add_monoid .
zero := 0,
add := (+),
add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _,
zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _,
add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ }
instance (a : α) : is_add_monoid_hom (λ g : α →₀ β, g a) :=
{ map_add := λ _ _, add_apply, map_zero := zero_apply }
lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero]
else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)]
lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add]
else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)]
@[elab_as_eliminator]
protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma map_range_add [add_monoid β₁] [add_monoid β₂]
{f : β₁ → β₂} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ β₁) :
map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ :=
finsupp.ext $ λ a, by simp [hf']
end add_monoid
instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) :=
{ add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _,
.. finsupp.add_monoid }
instance [add_group β] : add_group (α →₀ β) :=
{ neg := map_range (has_neg.neg) neg_zero,
add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _,
.. finsupp.add_monoid }
lemma single_multiset_sum [add_comm_monoid β] (s : multiset β) (a : α) :
single a s.sum = (s.map (single a)).sum :=
multiset.induction_on s single_zero $ λ a s ih,
by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons]
lemma single_finset_sum [add_comm_monoid β] (s : finset γ) (f : γ → β) (a : α) :
single a (s.sum f) = s.sum (λb, single a (f b)) :=
begin
transitivity,
apply single_multiset_sum,
rw [multiset.map_map],
refl
end
lemma single_sum [has_zero γ] [add_comm_monoid β] (s : δ →₀ γ) (f : δ → γ → β) (a : α) :
single a (s.sum f) = s.sum (λd c, single a (f d c)) :=
single_finset_sum _ _ _
@[to_additive]
lemma prod_neg_index [add_group β] [comm_monoid γ]
{g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) :
(-g).prod h = g.prod (λa b, h a (- b)) :=
prod_map_range_index h0
@[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a := rfl
@[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl
@[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f :=
finset.subset.antisymm
support_map_range
(calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm
... ⊆ support (- f) : support_map_range)
instance [add_comm_group β] : add_comm_group (α →₀ β) :=
{ add_comm := add_comm, ..finsupp.add_group }
@[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} :
(f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) :=
(finset.sum_hom (λf : α →₀ β, f a₂)).symm
lemma support_sum [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} :
(f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) :=
have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 →
(∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0),
from assume a₁ h,
let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in
⟨a, mem_support_iff.mp ha, ne⟩,
by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop] using this
@[simp] lemma sum_zero [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} :
f.sum (λa b, (0 : γ)) = 0 :=
finset.sum_const_zero
@[simp] lemma sum_add [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ :=
finset.sum_add_distrib
@[simp] lemma sum_neg [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h :=
finset.sum_hom (@has_neg.neg γ _)
@[simp] lemma sum_sub [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ :=
by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl
@[simp] lemma sum_single [add_comm_monoid β] (f : α →₀ β) :
f.sum single = f :=
have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) =
({a} : finset α).sum (λa', ite (a' = a) (f a') 0),
begin
intro a,
by_cases h : a ∈ f.support,
{ have : (finset.singleton a : finset α) ⊆ f.support,
{ simpa only [finset.subset_iff, mem_singleton, forall_eq] },
refine (finset.sum_subset this (λ _ _ H, _)).symm,
exact if_neg (mt mem_singleton.2 H) },
{ transitivity (f.support.sum (λa, (0 : β))),
{ refine (finset.sum_congr rfl $ λ a' ha', if_neg _),
rintro rfl, exact h ha' },
{ rw [sum_const_zero, insert_empty_eq_singleton, sum_singleton,
if_pos rfl, not_mem_support_iff.1 h] } }
end,
ext $ assume a, by simp only [sum_apply, single_apply, this,
insert_empty_eq_singleton, sum_singleton, if_pos]
@[to_additive]
lemma prod_add_index [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f + g).prod h = f.prod h * g.prod h :=
have f_eq : (f.support ∪ g.support).prod (λa, h a (f a)) = f.prod h,
from (finset.prod_subset (finset.subset_union_left _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
have g_eq : (f.support ∪ g.support).prod (λa, h a (g a)) = g.prod h,
from (finset.prod_subset (finset.subset_union_right _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
calc (f + g).support.prod (λa, h a ((f + g) a)) =
(f.support ∪ g.support).prod (λa, h a ((f + g) a)) :
finset.prod_subset support_add $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]
... = (f.support ∪ g.support).prod (λa, h a (f a)) *
(f.support ∪ g.support).prod (λa, h a (g a)) :
by simp only [add_apply, h_add, finset.prod_mul_distrib]
... = _ : by rw [f_eq, g_eq]
lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β}
{h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) :
(f - g).sum h = f.sum h - g.sum h :=
have h_zero : ∀a, h a 0 = 0,
from assume a,
have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0,
by simpa only [sub_self] using this,
have h_neg : ∀a b, h a (- b) = - h a b,
from assume a b,
have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b,
by simpa only [h_zero, zero_sub] using this,
have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂,
from assume a b₁ b₂,
have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂),
by simpa only [h_neg, sub_neg_eq_add] using this,
calc (f - g).sum h = (f + - g).sum h : rfl
... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero, h_neg, sum_neg]
... = f.sum h - g.sum h : rfl
@[to_additive]
lemma prod_finset_sum_index [add_comm_monoid β] [comm_monoid γ]
{s : finset ι} {g : ι → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
s.prod (λi, (g i).prod h) = (s.sum g).prod h :=
finset.induction_on s rfl $ λ a s has ih,
by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add]
@[to_additive]
lemma prod_sum_index
[add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f.sum g).prod h = f.prod (λa b, (g a b).prod h) :=
(prod_finset_sum_index h_zero h_add).symm
lemma multiset_sum_sum_index
[add_comm_monoid β] [add_comm_monoid γ]
(f : multiset (α →₀ β)) (h : α → β → γ)
(h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : β), h a (b₁ + b₂) = h a b₁ + h a b₂) :
(f.sum.sum h) = (f.map $ λg:α →₀ β, g.sum h).sum :=
multiset.induction_on f rfl $ assume a s ih,
by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih]
lemma multiset_map_sum [has_zero β] {f : α →₀ β} {m : γ → δ} {h : α → β → multiset γ} :
multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) :=
(finset.sum_hom _).symm
lemma multiset_sum_sum [has_zero β] [add_comm_monoid γ] {f : α →₀ β} {h : α → β → multiset γ} :
multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) :=
(finset.sum_hom multiset.sum).symm
section map_range
variables
[add_comm_monoid β₁] [add_comm_monoid β₂]
(f : β₁ → β₂) [hf : is_add_monoid_hom f]
instance is_add_monoid_hom_map_range :
is_add_monoid_hom (map_range f hf.map_zero : (α →₀ β₁) → (α →₀ β₂)) :=
{ map_zero := map_range_zero, map_add := λ a b, map_range_add hf.map_add _ _ }
lemma map_range_multiset_sum (m : multiset (α →₀ β₁)) :
map_range f hf.map_zero m.sum = (m.map $ λx, map_range f hf.map_zero x).sum :=
(m.sum_hom (map_range f hf.map_zero)).symm
lemma map_range_finset_sum {ι : Type*} (s : finset ι) (g : ι → (α →₀ β₁)) :
map_range f hf.map_zero (s.sum g) = s.sum (λx, map_range f hf.map_zero (g x)) :=
by rw [finset.sum.equations._eqn_1, map_range_multiset_sum, multiset.map_map]; refl
end map_range
section map_domain
variables [add_comm_monoid β] {v v₁ v₂ : α →₀ β}
/-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β`
is the finitely supported function whose value at `a : α₂` is the sum
of `v x` over all `x` such that `f x = a`. -/
def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
v.sum $ λa, single (f a)
lemma map_domain_apply {f : α₁ → α₂} (hf : function.injective f) (x : α₁ →₀ β) (a : α₁) :
map_domain f x (f a) = x a :=
begin
rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same],
{ assume b _ hba, exact single_eq_of_ne (hf.ne hba) },
{ simp only [(∉), (≠), not_not, mem_support_iff],
assume h,
rw [h, single_zero],
refl }
end
lemma map_domain_notin_range {f : α₁ → α₂} (x : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
map_domain f x a = 0 :=
begin
rw [map_domain, sum_apply, sum],
exact finset.sum_eq_zero
(assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _)
end
lemma map_domain_id : map_domain id v = v := sum_single _
lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} :
map_domain (g ∘ f) v = map_domain g (map_domain f v) :=
begin
refine ((sum_sum_index _ _).trans _).symm,
{ intros, exact single_zero },
{ intros, exact single_add },
refine sum_congr rfl (λ _ _, sum_single_index _),
{ exact single_zero }
end
lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b :=
sum_single_index single_zero
@[simp] lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) :=
sum_zero_index
lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) :
v.map_domain f = v.map_domain g :=
finset.sum_congr rfl $ λ _ H, by simp only [h _ H]
lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ :=
sum_add_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_finset_sum {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} :
map_domain f (s.sum v) = s.sum (λi, map_domain f (v i)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} :
map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_support {f : α → α₂} {s : α →₀ β} :
(s.map_domain f).support ⊆ s.support.image f :=
finset.subset.trans support_sum $
finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $
by rw [finset.bind_singleton]; exact subset.refl _
@[to_additive]
lemma prod_map_domain_index [comm_monoid γ] {f : α → α₂} {s : α →₀ β}
{h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(s.map_domain f).prod h = s.prod (λa b, h (f a) b) :=
(prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _)
lemma emb_domain_eq_map_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
emb_domain f v = map_domain f v :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a, rfl⟩,
rw [map_domain_apply (function.embedding.inj' _), emb_domain_apply] },
{ rw [map_domain_notin_range, emb_domain_notin_range]; assumption }
end
lemma injective_map_domain {f : α₁ → α₂} (hf : function.injective f) :
function.injective (map_domain f : (α₁ →₀ β) → (α₂ →₀ β)) :=
begin
assume v₁ v₂ eq, ext a,
have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq },
rwa [map_domain_apply hf, map_domain_apply hf] at this,
end
end map_domain
section comap_domain
noncomputable def comap_domain {α₁ α₂ γ : Type*} [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) : α₁ →₀ γ :=
{ support := l.support.preimage hf,
to_fun := (λ a, l (f a)),
mem_support_to_fun :=
begin
intros a,
simp only [finset.mem_def.symm, finset.mem_preimage],
exact l.mem_support_to_fun (f a),
end }
lemma comap_domain_apply {α₁ α₂ γ : Type*} [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) (a : α₁) :
comap_domain f l hf a = l (f a) :=
begin
unfold_coes,
unfold comap_domain,
simp,
refl
end
lemma sum_comap_domain {α₁ α₂ β γ : Type*} [has_zero β] [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ β) (g : α₂ → β → γ) (hf : set.bij_on f (f ⁻¹' l.support.to_set) l.support.to_set):
(comap_domain f l (set.inj_on_of_bij_on hf)).sum (g ∘ f) = l.sum g :=
begin
unfold sum,
haveI := classical.dec_eq α₂,
simp only [comap_domain, comap_domain_apply, finset.sum_preimage f _ _ (λ (x : α₂), g x (l x))],
end
lemma eq_zero_of_comap_domain_eq_zero {α₁ α₂ γ : Type*} [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.bij_on f (f ⁻¹' l.support.to_set) l.support.to_set) :
comap_domain f l (set.inj_on_of_bij_on hf) = 0 → l = 0 :=
begin
rw [← support_eq_empty, ← support_eq_empty, comap_domain],
simp only [finset.ext, finset.not_mem_empty, iff_false, mem_preimage],
assume h a ha,
cases hf.2.2 ha with b hb,
exact h b (hb.2.symm ▸ ha)
end
lemma map_domain_comap_domain {α₁ α₂ γ : Type*} [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ γ)
(hf : function.injective f) (hl : ↑l.support ⊆ set.range f):
map_domain f (comap_domain f l (set.inj_on_of_injective _ hf)) = l :=
begin
ext a,
haveI := classical.dec (a ∈ set.range f),
by_cases h_cases: a ∈ set.range f,
{ rcases set.mem_range.1 h_cases with ⟨b, hb⟩,
rw [hb.symm, map_domain_apply hf, comap_domain_apply] },
{ rw map_domain_notin_range _ _ h_cases,
by_contra h_contr,
apply h_cases (hl (finset.mem_coe.2 (mem_support_iff.2 (λ h, h_contr h.symm)))) }
end
end comap_domain
/-- The product of `f g : α →₀ β` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x + y = a`. (Think of the product of multivariate
polynomials where `α` is the monoid of monomial exponents.) -/
instance [has_add α] [semiring β] : has_mul (α →₀ β) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩
lemma mul_def [has_add α] [semiring β] {f g : α →₀ β} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl
lemma support_mul [has_add α] [semiring β] (a b : α →₀ β) :
(a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) :=
subset.trans support_sum $ bind_mono $ assume a₁ _,
subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset
/-- The unit of the multiplication is `single 0 1`, i.e. the function
that is 1 at 0 and zero elsewhere. -/
instance [has_zero α] [has_zero β] [has_one β] : has_one (α →₀ β) :=
⟨single 0 1⟩
lemma one_def [has_zero α] [has_zero β] [has_one β] : 1 = (single 0 1 : α →₀ β) := rfl
section filter
section has_zero
variables [has_zero β] (p : α → Prop) (f : α →₀ β)
/-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/
def filter (p : α → Prop) (f : α →₀ β) : α →₀ β :=
on_finset f.support (λa, if p a then f a else 0) $ λ a H,
mem_support_iff.2 $ λ h, by rw [h, if_t_t] at H; exact H rfl
@[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a :=
if_pos h
@[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 :=
if_neg h
@[simp] lemma support_filter : (f.filter p).support = f.support.filter p :=
finset.ext.mpr $ assume a, if H : p a
then by simp only [mem_support_iff, filter_apply_pos _ _ H, mem_filter, H, and_true]
else by simp only [mem_support_iff, filter_apply_neg _ _ H, mem_filter, H, and_false, ne.def, ne_self_iff_false]
lemma filter_zero : (0 : α →₀ β).filter p = 0 :=
by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty]
@[simp] lemma filter_single_of_pos
{a : α} {b : β} (h : p a) : (single a b).filter p = single a b :=
finsupp.ext $ λ x, begin
by_cases h' : p x; simp [h'],
rw single_eq_of_ne, rintro rfl, exact h' h
end
@[simp] lemma filter_single_of_neg
{a : α} {b : β} (h : ¬ p a) : (single a b).filter p = 0 :=
finsupp.ext $ λ x, begin
by_cases h' : p x; simp [h'],
rw single_eq_of_ne, rintro rfl, exact h h'
end
end has_zero
lemma filter_pos_add_filter_neg [add_monoid β] (f : α →₀ β) (p : α → Prop) :
f.filter p + f.filter (λa, ¬ p a) = f :=
finsupp.ext $ assume a, if H : p a
then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero]
else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add]
end filter
section frange
variables [has_zero β]
def frange (f : α →₀ β) : finset β :=
finset.image f f.support
theorem mem_frange {f : α →₀ β} {y : β} :
y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y :=
finset.mem_image.trans
⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩,
λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩
theorem zero_not_mem_frange {f : α →₀ β} : (0:β) ∉ f.frange :=
λ H, (mem_frange.1 H).1 rfl
theorem frange_single {x : α} {y : β} : frange (single x y) ⊆ {y} :=
λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸
(by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc])
end frange
section subtype_domain
variables {α' : Type*} [has_zero δ] {p : α → Prop}
section zero
variables [has_zero β] {v v' : α' →₀ β}
/-- `subtype_domain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtype_domain (p : α → Prop) (f : α →₀ β) : (subtype p →₀ β) :=
⟨f.support.subtype p, f ∘ subtype.val, λ a, by simp only [mem_subtype, mem_support_iff]⟩
@[simp] lemma support_subtype_domain {f : α →₀ β} :
(subtype_domain p f).support = f.support.subtype p :=
rfl
@[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} :
(subtype_domain p v) a = v (a.val) :=
rfl
@[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 :=
rfl
@[to_additive]
lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β}
{h : α → β → γ} (hp : ∀x∈v.support, p x) :
(v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h :=
prod_bij (λp _, p.val)
(λ _, mem_subtype.1)
(λ _ _, rfl)
(λ _ _ _ _, subtype.eq)
(λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩)
end zero
section monoid
variables [add_monoid β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_add {v v' : α →₀ β} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ λ _, rfl
instance subtype_domain.is_add_monoid_hom :
is_add_monoid_hom (subtype_domain p : (α →₀ β) → subtype p →₀ β) :=
{ map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero }
@[simp] lemma filter_add {v v' : α →₀ β} :
(v + v').filter p = v.filter p + v'.filter p :=
ext $ λ a, by by_cases p a; simp [h]
instance filter.is_add_monoid_hom (p : α → Prop) :
is_add_monoid_hom (filter p : (α →₀ β) → (α →₀ β)) :=
{ map_zero := filter_zero p, map_add := λ x y, filter_add }
end monoid
section comm_monoid
variables [add_comm_monoid β]
lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) :=
eq.symm (finset.sum_hom _)
lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) :=
subtype_domain_sum
lemma filter_sum (s : finset γ) (f : γ → α →₀ β) :
(s.sum f).filter p = s.sum (λa, filter p (f a)) :=
(finset.sum_hom (filter p)).symm
end comm_monoid
section group
variables [add_group β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_neg {v : α →₀ β} :
(- v).subtype_domain p = - v.subtype_domain p :=
ext $ λ _, rfl
@[simp] lemma subtype_domain_sub {v v' : α →₀ β} :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ λ _, rfl
end group
end subtype_domain
section multiset
def to_multiset (f : α →₀ ℕ) : multiset α :=
f.sum (λa n, add_monoid.smul n {a})
lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 :=
rfl
lemma to_multiset_add (m n : α →₀ ℕ) :
(m + n).to_multiset = m.to_multiset + n.to_multiset :=
sum_add_index (assume a, add_monoid.zero_smul _) (assume a b₁ b₂, add_monoid.add_smul _ _ _)
lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = add_monoid.smul n {a} :=
by rw [to_multiset, sum_single_index]; apply add_monoid.zero_smul
instance is_add_monoid_hom.to_multiset : is_add_monoid_hom (to_multiset : _ → multiset α) :=
{ map_zero := to_multiset_zero, map_add := to_multiset_add }
lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.card_zero, sum_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.card_add, ih, sum_add_index, to_multiset_single,
sum_single_index, multiset.card_smul, multiset.singleton_eq_singleton,
multiset.card_singleton, mul_one]; intros; refl }
end
lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) :
f.to_multiset.map g = (f.map_domain g).to_multiset :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single,
to_multiset_single, to_multiset_add, to_multiset_single,
is_add_monoid_hom.map_smul (multiset.map g)],
refl }
end
lemma prod_to_multiset [comm_monoid α] (f : α →₀ ℕ) :
f.to_multiset.prod = f.prod (λa n, a ^ n) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index,
finsupp.prod_single_index, multiset.prod_smul, multiset.singleton_eq_singleton,
multiset.prod_singleton],
{ exact pow_zero a },
{ exact pow_zero },
{ exact pow_add } }
end
lemma to_finset_to_multiset (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.to_finset_zero, support_zero] },
{ assume a n f ha hn ih,
rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq,
support_single_ne_zero hn, multiset.to_finset_smul _ _ hn,
multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero],
refl,
refine disjoint_mono support_single_subset (subset.refl _) _,
rwa [finset.singleton_eq_singleton, finset.singleton_disjoint] }
end
@[simp] lemma count_to_multiset (f : α →₀ ℕ) (a : α) :
f.to_multiset.count a = f a :=
calc f.to_multiset.count a = f.sum (λx n, (add_monoid.smul n {x} : multiset α).count a) :
(finset.sum_hom _).symm
... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul]
... = f.sum (λx n, n * (x :: 0 : multiset α).count a) : rfl
... = f a * (a :: 0 : multiset α).count a : sum_eq_single _
(λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero])
(λ H, by simp only [not_mem_support_iff.1 H, zero_mul])
... = f a : by simp only [multiset.count_singleton, mul_one]
def of_multiset (m : multiset α) : α →₀ ℕ :=
on_finset m.to_finset (λa, m.count a) $ λ a H, multiset.mem_to_finset.2 $
by_contradiction (mt multiset.count_eq_zero.2 H)
@[simp] lemma of_multiset_apply (m : multiset α) (a : α) :
of_multiset m a = m.count a :=
rfl
def equiv_multiset : (α →₀ ℕ) ≃ (multiset α) :=
⟨ to_multiset, of_multiset,
assume f, finsupp.ext $ λ a, by rw [of_multiset_apply, count_to_multiset],
assume m, multiset.ext.2 $ λ a, by rw [count_to_multiset, of_multiset_apply] ⟩
lemma mem_support_multiset_sum [add_comm_monoid β]
{s : multiset (α →₀ β)} (a : α) :
a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ β).support :=
multiset.induction_on s false.elim
begin
assume f s ih ha,
by_cases a ∈ f.support,
{ exact ⟨f, multiset.mem_cons_self _ _, h⟩ },
{ simp only [multiset.sum_cons, mem_support_iff, add_apply,
not_mem_support_iff.1 h, zero_add] at ha,
rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩,
exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ }
end
lemma mem_support_finset_sum [add_comm_monoid β]
{s : finset γ} {h : γ → α →₀ β} (a : α) (ha : a ∈ (s.sum h).support) : ∃c∈s, a ∈ (h c).support :=
let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in
let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in
⟨c, hc, eq.symm ▸ hfa⟩
lemma mem_support_single [has_zero β] (a a' : α) (b : β) :
a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 :=
⟨λ H : (a ∈ ite _ _ _), if h : b = 0
then by rw if_pos h at H; exact H.elim
else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩,
λ ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩
end multiset
section curry_uncurry
protected def curry [add_comm_monoid γ]
(f : (α × β) →₀ γ) : α →₀ (β →₀ γ) :=
f.sum $ λp c, single p.1 (single p.2 c)
lemma sum_curry_index
[add_comm_monoid γ] [add_comm_monoid δ]
(f : (α × β) →₀ γ) (g : α → β → γ → δ)
(hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) :
f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) :=
begin
rw [finsupp.curry],
transitivity,
{ exact sum_sum_index (assume a, sum_zero_index)
(assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) },
congr, funext p c,
transitivity,
{ exact sum_single_index sum_zero_index },
exact sum_single_index (hg₀ _ _)
end
protected def uncurry [add_comm_monoid γ] (f : α →₀ (β →₀ γ)) : (α × β) →₀ γ :=
f.sum $ λa g, g.sum $ λb c, single (a, b) c
def finsupp_prod_equiv [add_comm_monoid γ] : ((α × β) →₀ γ) ≃ (α →₀ (β →₀ γ)) :=
by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [
finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff,
forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single]
lemma filter_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) (p : α₁ → Prop) :
(f.filter (λa:α₁×α₂, p a.1)).curry = f.curry.filter p :=
begin
rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum,
@filter_sum _ (α₂ →₀ β) _ p _ f.support _],
rw [support_filter, sum_filter],
refine finset.sum_congr rfl _,
rintros ⟨a₁, a₂⟩ ha,
dsimp only,
split_ifs,
{ rw [filter_apply_pos, filter_single_of_pos]; exact h },
{ rwa [filter_single_of_neg] }
end
lemma support_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) :
f.curry.support ⊆ f.support.image prod.fst :=
begin
rw ← finset.bind_singleton,
refine finset.subset.trans support_sum _,
refine finset.bind_mono (assume a _, support_single_subset)
end
end curry_uncurry
section
variables [add_monoid α] [semiring β]
-- TODO: the simplifier unfolds 0 in the instance proof!
private lemma zero_mul (f : α →₀ β) : 0 * f = 0 := by simp only [mul_def, sum_zero_index]
private lemma mul_zero (f : α →₀ β) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero]
private lemma left_distrib (a b c : α →₀ β) : a * (b + c) = a * b + a * c :=
by simp only [mul_def, sum_add_index, mul_add, _root_.mul_zero, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add]
private lemma right_distrib (a b c : α →₀ β) : (a + b) * c = a * c + b * c :=
by simp only [mul_def, sum_add_index, add_mul, _root_.mul_zero, _root_.zero_mul, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add]
instance : semiring (α →₀ β) :=
{ one := 1,
mul := (*),
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.zero_mul, single_zero, sum_zero,
zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.mul_zero, single_zero, sum_zero,
add_zero, mul_one, sum_single],
zero_mul := zero_mul,
mul_zero := mul_zero,
mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index,
single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff,
add_mul, mul_add, add_assoc, mul_assoc, _root_.zero_mul, _root_.mul_zero, sum_zero, sum_add],
left_distrib := left_distrib,
right_distrib := right_distrib,
.. finsupp.add_comm_monoid }
end
instance [add_comm_monoid α] [comm_semiring β] : comm_semiring (α →₀ β) :=
{ mul_comm := assume f g,
begin
simp only [mul_def, finsupp.sum, mul_comm],
rw [finset.sum_comm],
simp only [add_comm]
end,
.. finsupp.semiring }
instance [add_monoid α] [ring β] : ring (α →₀ β) :=
{ neg := has_neg.neg,
add_left_neg := add_left_neg,
.. finsupp.semiring }
instance [add_comm_monoid α] [comm_ring β] : comm_ring (α →₀ β) :=
{ mul_comm := mul_comm, .. finsupp.ring}
lemma single_mul_single [has_add α] [semiring β] {a₁ a₂ : α} {b₁ b₂ : β}:
single a₁ b₁ * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) :=
(sum_single_index (by simp only [_root_.zero_mul, single_zero, sum_zero])).trans
(sum_single_index (by rw [_root_.mul_zero, single_zero]))
lemma prod_single [add_comm_monoid α] [comm_semiring β]
{s : finset ι} {a : ι → α} {b : ι → β} :
s.prod (λi, single (a i) (b i)) = single (s.sum a) (s.prod b) :=
finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih,
single_mul_single, sum_insert has, prod_insert has]
section
instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : has_scalar γ (α →₀ β) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩
variables (α β)
@[simp] lemma smul_apply' {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {a : α} {b : γ} {v : α →₀ β} :
(b • v) a = b • (v a) := rfl
instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : semimodule γ (α →₀ β) :=
{ smul := (•),
smul_add := λ a x y, finsupp.ext $ λ _, smul_add _ _ _,
add_smul := λ a x y, finsupp.ext $ λ _, add_smul _ _ _,
one_smul := λ x, finsupp.ext $ λ _, one_smul _ _,
mul_smul := λ r s x, finsupp.ext $ λ _, mul_smul _ _ _,
zero_smul := λ x, finsupp.ext $ λ _, zero_smul _ _,
smul_zero := λ x, finsupp.ext $ λ _, smul_zero _ }
instance [ring γ] [add_comm_group β] [module γ β] : module γ (α →₀ β) :=
{ ..finsupp.semimodule α β }
instance [discrete_field γ] [add_comm_group β] [vector_space γ β] : vector_space γ (α →₀ β) :=
{ ..finsupp.module α β }
variables {α β}
lemma support_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {g : α →₀ β} :
(b • g).support ⊆ g.support :=
λ a, by simp; exact mt (λ h, h.symm ▸ smul_zero _)
section
variables {α' : Type*} [has_zero δ] {p : α → Prop}
@[simp] lemma filter_smul {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
{b : γ} {v : α →₀ β} : (b • v).filter p = b • v.filter p :=
ext $ λ a, by by_cases p a; simp [h]
end
lemma map_domain_smul {α'} {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
{f : α → α'} (b : γ) (v : α →₀ β) : map_domain f (b • v) = b • map_domain f v :=
begin
change map_domain f (map_range _ _ _) = map_range _ _ _,
apply finsupp.induction v, {simp},
intros a b v' hv₁ hv₂ IH,
rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add,
map_range_single, map_domain_single, map_domain_single, map_range_single];
apply smul_add
end
@[simp] lemma smul_single {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
(c : γ) (a : α) (b : β) : c • finsupp.single a b = finsupp.single a (c • b) :=
ext $ λ a', by by_cases a = a'; [{subst h, simp}, simp [h]]
end
@[simp] lemma smul_apply [ring β] {a : α} {b : β} {v : α →₀ β} :
(b • v) a = b • (v a) := rfl
lemma sum_smul_index [ring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ}
(h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) :=
finsupp.sum_map_range_index h0
section
variables [semiring β] [semiring γ]
lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} :
(s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) :=
by simp only [finsupp.sum, finset.sum_mul]
lemma mul_sum (b : γ) (s : α →₀ β) {f : α → β → γ} :
b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) :=
by simp only [finsupp.sum, finset.mul_sum]
protected lemma eq_zero_of_zero_eq_one
(zero_eq_one : (0 : β) = 1) (l : α →₀ β) : l = 0 :=
by ext i; simp [eq_zero_of_zero_eq_one β zero_eq_one (l i)]
end
def restrict_support_equiv [add_comm_monoid β] (s : set α) :
{f : α →₀ β // ↑f.support ⊆ s } ≃ (s →₀ β):=
begin
refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩,
{ refine set.subset.trans (finset.coe_subset.2 map_domain_support) _,
rw [finset.coe_image, set.image_subset_iff],
exact assume x hx, x.2 },
{ rintros ⟨f, hf⟩,
apply subtype.eq,
ext a,
dsimp only,
refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _),
{ rcases h with ⟨x, rfl⟩,
rw [map_domain_apply subtype.val_injective, subtype_domain_apply] },
{ convert map_domain_notin_range _ _ h,
rw [← not_mem_support_iff],
refine mt _ h,
exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } },
{ assume f,
ext ⟨a, ha⟩,
dsimp only,
rw [subtype_domain_apply, map_domain_apply subtype.val_injective] }
end
protected def dom_congr [add_comm_monoid β] (e : α₁ ≃ α₂) : (α₁ →₀ β) ≃ (α₂ →₀ β) :=
⟨map_domain e, map_domain e.symm,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply],
exact map_domain_id
end,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply],
exact map_domain_id
end⟩
section sigma
variables {αs : ι → Type*} [has_zero β] (l : (Σ i, αs i) →₀ β)
noncomputable def split (i : ι) : αs i →₀ β :=
l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2)
lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ :=
begin
dunfold split,
rw comap_domain_apply
end
def split_support : finset ι := finset.image (sigma.fst) l.support
lemma mem_split_support_iff_nonzero (i : ι) :
i ∈ split_support l ↔ split l i ≠ 0 :=
begin
classical,
rw [split_support, mem_image, ne.def, ← support_eq_empty,
← exists_mem_iff_ne_empty, split, comap_domain],
simp
end
noncomputable def split_comp [has_zero γ] (g : Π i, (αs i →₀ β) → γ)
(hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ γ :=
{ support := split_support l,
to_fun := λ i, g i (split l i),
mem_support_to_fun :=
begin
intros i,
rw mem_split_support_iff_nonzero,
haveI := classical.dec,
rwa not_iff_not,
exact hg _ _,
end }
lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) :=
by simp [finset.ext, split_support, split, comap_domain]; tauto
lemma sigma_sum [add_comm_monoid γ] (f : (Σ (i : ι), αs i) → β → γ) :
l.sum f = (split_support l).sum (λ (i : ι), (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b)) :=
by simp [sum, sigma_support, sum_sigma,split_apply]
end sigma
end finsupp
namespace multiset
def to_finsupp (s : multiset α) : α →₀ ℕ :=
{ support := s.to_finset,
to_fun := λ a, s.count a,
mem_support_to_fun := λ a,
begin
rw mem_to_finset,
convert not_iff_not_of_iff (count_eq_zero.symm),
rw not_not
end }
@[simp] lemma to_finsupp_support (s : multiset α) :
s.to_finsupp.support = s.to_finset := rfl
@[simp] lemma to_finsupp_apply (s : multiset α) (a : α) :
s.to_finsupp a = s.count a := rfl
@[simp] lemma to_finsupp_zero :
to_finsupp (0 : multiset α) = 0 :=
finsupp.ext $ λ a, count_zero a
@[simp] lemma to_finsupp_add (s t : multiset α) :
to_finsupp (s + t) = to_finsupp s + to_finsupp t :=
finsupp.ext $ λ a, count_add a s t
lemma to_finsupp_singleton (a : α) :
to_finsupp {a} = finsupp.single a 1 :=
finsupp.ext $ λ b,
if h : a = b then by simp [finsupp.single_apply, h] else
begin
rw [to_finsupp_apply, finsupp.single_apply, if_neg h, count_eq_zero,
singleton_eq_singleton, mem_singleton],
rintro rfl, exact h rfl
end
namespace to_finsupp
instance : is_add_monoid_hom (to_finsupp : multiset α → α →₀ ℕ) :=
{ map_zero := to_finsupp_zero,
map_add := to_finsupp_add }
end to_finsupp
@[simp] lemma to_finsupp_to_multiset (s : multiset α) :
s.to_finsupp.to_multiset = s :=
ext.2 $ λ a, by rw [finsupp.count_to_multiset, to_finsupp_apply]
end multiset
namespace finsupp
variables {σ : Type*}
instance [preorder α] [has_zero α] : preorder (σ →₀ α) :=
{ le := λ f g, ∀ s, f s ≤ g s,
le_refl := λ f s, le_refl _,
le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) }
instance [partial_order α] [has_zero α] : partial_order (σ →₀ α) :=
{ le_antisymm := λ f g hfg hgf, finsupp.ext $ λ s, le_antisymm (hfg s) (hgf s),
.. finsupp.preorder }
instance [ordered_cancel_comm_monoid α] :
add_left_cancel_semigroup (σ →₀ α) :=
{ add_left_cancel := λ a b c h, finsupp.ext $ λ s,
by { rw finsupp.ext_iff at h, exact add_left_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_comm_monoid α] :
add_right_cancel_semigroup (σ →₀ α) :=
{ add_right_cancel := λ a b c h, finsupp.ext $ λ s,
by { rw finsupp.ext_iff at h, exact add_right_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_comm_monoid α] :
ordered_cancel_comm_monoid (σ →₀ α) :=
{ add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s),
le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s),
.. finsupp.add_comm_monoid, .. finsupp.partial_order,
.. finsupp.add_left_cancel_semigroup, .. finsupp.add_right_cancel_semigroup }
lemma le_iff [canonically_ordered_monoid α] (f g : σ →₀ α) :
f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s :=
⟨λ h s hs, h s,
λ h s, if H : s ∈ f.support then h s H else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩
attribute [simp] to_multiset_zero to_multiset_add
@[simp] lemma to_multiset_to_finsupp (f : σ →₀ ℕ) :
f.to_multiset.to_finsupp = f :=
ext $ λ s, by rw [multiset.to_finsupp_apply, count_to_multiset]
lemma to_multiset_strict_mono : strict_mono (@to_multiset σ) :=
λ m n h,
begin
rw lt_iff_le_and_ne at h ⊢, cases h with h₁ h₂,
split,
{ rw multiset.le_iff_count, intro s, erw [count_to_multiset m s, count_to_multiset], exact h₁ s },
{ intro H, apply h₂, replace H := congr_arg multiset.to_finsupp H, simpa using H }
end
lemma sum_id_lt_of_lt (m n : σ →₀ ℕ) (h : m < n) :
m.sum (λ _, id) < n.sum (λ _, id) :=
begin
rw [← card_to_multiset, ← card_to_multiset],
apply multiset.card_lt_of_lt,
exact to_multiset_strict_mono _ _ h
end
variable (σ)
/-- The order on σ →₀ ℕ is well-founded.-/
lemma lt_wf : well_founded (@has_lt.lt (σ →₀ ℕ) _) :=
subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf
instance decidable_le : decidable_rel (@has_le.le (σ →₀ ℕ) _) :=
λ m n, by rw le_iff; apply_instance
variable {σ}
def antidiagonal (f : σ →₀ ℕ) : ((σ →₀ ℕ) × (σ →₀ ℕ)) →₀ ℕ :=
(f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp
lemma mem_antidiagonal_support {f : σ →₀ ℕ} {p : (σ →₀ ℕ) × (σ →₀ ℕ)} :
p ∈ (antidiagonal f).support ↔ p.1 + p.2 = f :=
begin
erw [multiset.mem_to_finset, multiset.mem_map],
split,
{ rintros ⟨⟨a, b⟩, h, rfl⟩,
rw multiset.mem_antidiagonal at h,
simpa using congr_arg multiset.to_finsupp h },
{ intro h,
refine ⟨⟨p.1.to_multiset, p.2.to_multiset⟩, _, _⟩,
{ simpa using congr_arg to_multiset h },
{ rw [prod.map, to_multiset_to_finsupp, to_multiset_to_finsupp, prod.mk.eta] } }
end
@[simp] lemma antidiagonal_zero : antidiagonal (0 : σ →₀ ℕ) = single (0,0) 1 :=
by rw [← multiset.to_finsupp_singleton]; refl
lemma swap_mem_antidiagonal_support {n : σ →₀ ℕ} {f} (hf : f ∈ (antidiagonal n).support) :
f.swap ∈ (antidiagonal n).support :=
by simpa [mem_antidiagonal_support, add_comm] using hf
end finsupp
|
edf9b4858f99be11dced1d27a1c18c9302115cc4 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/ring_theory/euclidean_domain.lean | ddaeb0e0ffc558dc90b32bdf968395efb9c82765 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 1,924 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Chris Hughes
-/
import algebra.associated algebra.euclidean_domain ring_theory.ideals
noncomputable theory
local attribute [instance] classical.dec
open euclidean_domain set ideal
theorem span_gcd {α} [euclidean_domain α] (x y : α) :
span ({gcd x y} : set α) = span ({x, y} : set α) :=
begin
apply le_antisymm; refine span_le.1 _,
{ simp [submodule.span_span, mem_span_pair, submodule.le_def', mem_span_singleton'],
assume a b ha,
exact ⟨b * gcd_a x y, b * gcd_b x y, by rw [← ha, gcd_eq_gcd_ab x y];
simp [mul_add, mul_comm, mul_left_comm]⟩ },
{ assume z ,
simp [mem_span_singleton, euclidean_domain.gcd_dvd_left, mem_span_pair,
@eq_comm _ _ z] {contextual := tt},
assume a b h,
exact dvd_add (dvd_mul_of_dvd_right (gcd_dvd_left _ _) _)
(dvd_mul_of_dvd_right (gcd_dvd_right _ _) _) }
end
theorem gcd_is_unit_iff {α} [euclidean_domain α] {x y : α} :
is_unit (gcd x y) ↔ is_coprime x y :=
by rw [← span_singleton_eq_top, span_gcd, is_coprime]
theorem is_coprime_of_dvd {α} [euclidean_domain α] {x y : α}
(z : ¬ (x = 0 ∧ y = 0)) (H : ∀ z ∈ nonunits α, z ≠ 0 → z ∣ x → ¬ z ∣ y) :
is_coprime x y :=
begin
rw [← gcd_is_unit_iff],
by_contra h,
refine H _ h _ (gcd_dvd_left _ _) (gcd_dvd_right _ _),
rwa [ne, euclidean_domain.gcd_eq_zero_iff]
end
theorem dvd_or_coprime {α} [euclidean_domain α] (x y : α)
(h : irreducible x) : x ∣ y ∨ is_coprime x y :=
begin
refine or_iff_not_imp_left.2 (λ h', _),
unfreezeI, apply is_coprime_of_dvd,
{ rintro ⟨rfl, rfl⟩, simpa using h },
{ rintro z nu nz ⟨w, rfl⟩ dy,
refine h' (dvd.trans _ dy),
simpa using mul_dvd_mul_left z (is_unit_iff_dvd_one.1 $
(of_irreducible_mul h).resolve_left nu) }
end
|
176136e01baea9cbbe92e4b9e508772b94fb2883 | b7fc5b86b12212bea5542eb2c9d9f0988fd78697 | /src/solutions/friday/manifolds.lean | ded97a9f7ca13cf99068b57ddaf54f558cfef9dc | [] | no_license | stjordanis/lftcm2020 | 3b16591aec853c8546d9c8b69c0bf3f5f3956fee | 1f3485e4dafdc587b451ec5144a1d8d3ec9b411e | refs/heads/master | 1,675,958,865,413 | 1,609,901,722,000 | 1,609,901,722,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 42,308 | lean | import ...for_mathlib.manifolds
noncomputable theory
open_locale manifold classical big_operators
open set
universe u
/-!
## Reminder on updating the exercises
These instructions are now available at:
https://leanprover-community.github.io/lftcm2020/exercises.html
To get a new copy of the exercises,
run the following commands in your terminal:
```
leanproject get lftcm2020
cp -r lftcm2020/src/exercises_sources/ lftcm2020/src/my_exercises
code lftcm2020
```
To update your exercise files, run the following commands:
```
cd /path/to/lftcm2020
git pull
leanproject get-mathlib-cache
```
Don’t forget to copy the updated files to `src/my_exercises`.
-/
/-!
## An overview of manifolds in Lean, discussing design decisions
Warning: there are sorries in this section, they are not supposed to be filled! The exercises sections
start later, and there you will have plenty of sorries to fill.
What is a manifold?
1) allow field other than `ℝ` or `ℂ`?
2) allow infinite dimension?
3) allow boundary?
4) allow model space depending on the point of the manifold?
Bourbaki: 2, 4 (and just definitions and statements, no proofs!)
Lean: 1, 2, 3
Perelman geometrization theorem : any compact connected irreducible 3-manifold can
be cut along tori into finitely many pieces, each of which has a _geometric structure_ of
finite volume, i.e., it is locally like a model space, with changes of coordinates given
locally by the action of a Lie group
Typical dynamics theorem : let `M` be a compact manifold, and `f : M → M` a map with property
such and such. Then ...
Or : Consider a hyperbolic surface of genus `g`, and a random geodesic of length `T`. How many
times does it typically self-intersect?
Manifold in Lean:
* charted space structure, i.e., set of local homeos to a model space. This is data, fixed
once and for all (and a typeclass)
* compatibility condition, i.e., the change of coordinates should belong to some subgroup
of the group of local homeos of the model space. This is Prop (and a typeclass). The same
manifold can be at the same time an analytic manifold, a smooth manifold and a topological
manifold (with the same fixed atlas).
* A charted space is a smooth manifold (with corners) if it is compatible with the smooth
groupoid on the model space. To cover uniformly both situations with and without boundary,
the smooth groupoid is with respect to a map `I : H → E` (think of `H` as the half-space and
`E` the full space), which is the identity in the boundaryless situation, the inclusion in
the half-space situation. This map `I` is called a _model with corners_. The most standard ones
(identity in `ℝ^n` and inclusion of half-space in `ℝ^n`) have dedicated notations:
`𝓡 n` and `𝓡∂ n`.
-/
#check charted_space (euclidean_half_space 1) (Icc (0 : ℝ) 1)
#check has_groupoid (Icc (0 : ℝ) 1) (times_cont_diff_groupoid ∞ (𝓡∂ 1))
#check smooth_manifold_with_corners (𝓡∂ 1) (Icc (0 : ℝ) 1)
-- atlases are not maximal in general
#check (times_cont_diff_groupoid ∞ (𝓡∂ 1)).maximal_atlas (Icc (0 : ℝ) 1)
-- let's try to put a smooth manifold structure on the sphere
-- (we don't have submanifolds yet, but it's coming in the near future)
@[derive topological_space]
definition sphere (n : ℕ) : Type := metric.sphere (0 : euclidean_space ℝ (fin (n+1))) 1
instance (n : ℕ) : has_coe (sphere n) (euclidean_space ℝ (fin (n+1))) := ⟨subtype.val⟩
instance (n : ℕ) : charted_space (euclidean_space ℝ (fin n)) (sphere n) :=
{ atlas := begin sorry end,
chart_at := begin sorry end,
mem_chart_source := begin sorry end,
chart_mem_atlas := begin sorry end }
instance (n : ℕ) : smooth_manifold_with_corners (𝓡 n) (sphere n) :=
{ compatible := begin
assume e e' he he',
sorry
end }
-- smooth functions
def inc (n : ℕ) : sphere n → euclidean_space ℝ (fin (n+1)) :=
λ p : sphere n, (p : euclidean_space ℝ (fin (n+1)))
lemma inc_smooth (n : ℕ) : times_cont_mdiff (𝓡 n) (𝓡 (n+1)) ∞ (inc n) :=
begin
rw times_cont_mdiff_iff,
split,
{ exact continuous_subtype_coe, },
{ assume x y,
sorry }
end
lemma inc_continuous (n : ℕ) : continuous (inc n) :=
(inc_smooth n).continuous
lemma inc_mdifferentiable (n : ℕ) : mdifferentiable (𝓡 n) (𝓡 (n+1)) (inc n) :=
(inc_smooth n).mdifferentiable le_top
-- tangent space and tangent bundles
example (n : ℕ) (p : sphere n) (v : tangent_space (𝓡 n) p) :
tangent_bundle (𝓡 n) (sphere n) :=
⟨p, v⟩
-- tangent map, derivatives
example (n : ℕ) : times_cont_mdiff ((𝓡 n).prod (𝓡 n)) ((𝓡 (n+1)).prod (𝓡 (n+1))) ∞
(tangent_map (𝓡 n) (𝓡 (n+1)) (inc n)) :=
(inc_smooth n).times_cont_mdiff_tangent_map le_top
example (n : ℕ) (f : sphere n → sphere (n^2)) (p : sphere n) (v : tangent_space (𝓡 n) p) :
mfderiv (𝓡 n) (𝓡 (n^2)) f p v = (tangent_map (𝓡 n) (𝓡 (n^2)) f ⟨p, v⟩).2 :=
rfl
/- Can you express the sphere eversion theorem, i.e., the fact that there is a smooth isotopy
of immersions between the canonical embedding of the sphere `S^2` and `ℝ^3`, and the antipodal
embedding?
Note that we haven't defined immersions in mathlib, but you can jut require that the fiber
derivative is injective everywhere, which is easy to express if you know that the derivative
of a function `f` from a manifold of dimension `2` to a manifold of dimension `3` at a point `x` is
`mfderiv (𝓡 2) (𝓡 3) f x`.
Don't forget to require the global smoothness of the map! You may need to know that the interval
`[0,1]`, called `Icc (0 : ℝ) 1` in Lean, already has a manifold (with boundary!) structure,
where the corresponding model with corners is called `𝓡∂ 1`.
-/
theorem sphere_eversion :
∃ f : (Icc (0 : ℝ) 1) × sphere 2 → euclidean_space ℝ (fin 3),
times_cont_mdiff ((𝓡∂ 1).prod (𝓡 2)) (𝓡 3) ∞ f
∧ ∀ (t : (Icc (0 : ℝ) 1)), ∀ (p : sphere 2),
function.injective (mfderiv (𝓡 2) (𝓡 3) (f ∘ λ y, (t, y)) p)
∧ ∀ (p : sphere 2), f (0, p) = p
∧ ∀ (p : sphere 2), f (1, p) = - p :=
sorry
/- Dicussing three (controversial?) design decisions
#### Local homeos
What is a local homeo `f` between an open subset of `E` and an open subset of `F`?
1) a map defined on a subtype: `f x` only makes sense for `x : f.source`
2) a map defined on the whole space `E`, but taking values in `option F = F ∪ {junk}`, with
`f x = junk` when `x ∉ f.source`
3) a map defined on the whole space `E`, taking values in `F`, and we don't care about its values
outside of `f.source`.
Just like division by zero! But worse:
* issue with 1): you keep intersecting chart domains. But the subtype `u ∩ v` is not the same as
the subtype `v ∩ u`, so you keep adding casts everywhere
* issue with 2): if you want to say that a chart is smooth, then you define to define smooth functions
between `option E` and `option F` when `E` and `F` are vector spaces. All notions need to be
redefined with `option`.
* issue with 3): it works perfectly well, but it makes mathematicians unhappy/uneasy (and it is *not*
equivalent to 1) or 2) when one of the spaces is empty)
I picked 3)
#### Tangent vectors
What is a tangent vector (for a manifold `M` modelled on a vector space `E`)?
1) An equivalence class of germs of curves
2) A derivation
3) Physicist point of view: I don't know what a tangent vector is, but I know in charts.
Mathematician's interpretation: equivalence class of `(e, v)` where `e` is a chart at `x`, `v` a vector
in the vector space, and `(e, v) ∼ (e', v')` if `D(e' ∘ e ⁻¹) v = v'`
4) ...
Issues:
1) Pictures are pretty, but this doesn't bring anything compared to 3) when you go down to details.
And what about boundaries, where you can only have a half-curve
2) Need partitions of unity to show that this is local and coincides with the usual point of view.
Doesn't work well in finite smoothness, nor in complex manifolds
3) Fine, works in all situations, but requires a lot of work to define the equivalence classes,
the topology, check that the topology is compatible with the vector space structure, and so on.
In a vector space, the tangent space is not defeq to the vector space itself
4) Pick one favorite chart at `x`, say `e_x`, and *define* the tangent space at `x` to be `E`,
but "seen" in the chart `e_x` (this will show up in the definition of the derivative : the
derivative of `f : M → M'` at `x` is defined to be the derivative of the map
`e_{f x} ∘ f ∘ e_x⁻¹`). Works perfectly fine, but makes mathematicians unhappy/uneasy.
(Axiom of choice? In fact we put the choice of `e_x` in the *definition* of charted spaces,
so not further choice)
I picked 4)
#### Smooth functions in manifolds with boundary
Usual definition of smooth functions in a half space: extend to a smooth function a little bit
beyond the boundary, so one only really needs to speak of smooth functions in open subsets of
vector spaces.
When you define the derivative, you will need to check that it does not depend on the choice
of the extension. Even worse when you want to define the tangent bundle: choose an open extension
of your manifold with boundary, and then check that the restriction of the tangent bundle does
not depend on the choice of the extension. Very easy when handwaving, nightmare to formalize.
(What is the extension of the manifold with boundary? Another type?)
Instead, if you define derivatives in (non-open) domains, you can talk of smooth functions in
domains, and do everything without extending. Need to know this early enough: when starting to
define derivatives, you should already think of manifolds with boundaries! That's what we did
in mathlib.
Difficulty: if a domain `s` is too small (think `s = ℝ ⊆ ℝ^2`), the values of `f` on `s` do not
prescribe uniquely a derivative, so `fderiv_within_at ℝ f s x` may behave badly: the derivative of
a sum might be different from sum of derivatives, as there is an arbitrary choice to be made.
This does not happen with the half-space, as it is large enough: derivatives within domains only
work well if the tangent directions span the whole space. Predicate `unique_diff_on` for sets
in vector spaces. You won't find this in books!
-/
/-! ## Exercises -/
/-! ### Local homeomorphisms
Local homeomorphisms are globally defined maps with a globally defined "inverse", but the only
relevant set is the *source*, which should be mapped homeomorphically to the *target*.
-/
-- set up a simple helper simp lemma to simplify our life later.
@[simp] lemma neg_mem_Ioo_minus_one_one (x : ℝ) : -x ∈ Ioo (-1 : ℝ) 1 ↔ x ∈ Ioo (-1 : ℝ) 1 :=
begin
-- sorry
simp [neg_lt, and_comm],
-- sorry
end
/- Define a local homeomorphism from `ℝ` to `ℝ` which is just `x ↦ -x`, but on `(-1, 1)`. In
Lean, the interval `(-1, 1)` is denoted by `Ioo (-1 : ℝ) 1` (where `o` stands for _open_). -/
def my_first_local_homeo : local_homeomorph ℝ ℝ :=
{ to_fun := λ x, -x,
inv_fun := λ x, -x,
source := Ioo (-1) 1,
target := /- inline sorry -/Ioo (-1) 1/- inline sorry -/,
map_source' :=
begin
-- sorry
assume x hx,
simp [hx],
-- sorry
end,
map_target' :=
begin
-- sorry
assume x hx,
simp [hx],
-- sorry
end,
left_inv' :=
begin
-- sorry
simp,
-- sorry
end,
right_inv' :=
begin
-- sorry
simp,
-- sorry
end,
open_source := /- inline sorry -/is_open_Ioo/- inline sorry -/,
open_target := /- inline sorry -/is_open_Ioo/- inline sorry -/,
continuous_to_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/,
continuous_inv_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/ }
/- Two simple lemmas that will prove useful below. You can leave them sorried if you like. -/
lemma ne_3_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-1 : ℝ) 1) : x ≠ 3 :=
begin
-- sorry
exact ne_of_lt (lt_trans h.2 (by norm_num))
-- sorry
end
lemma neg_ne_3_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-1 : ℝ) 1) : -x ≠ 3 :=
begin
-- sorry
assume h',
simp at h,
linarith,
-- sorry
end
/- Now, define a second local homeomorphism which is almost like the previous one. You may find the
following lemma useful for `continuous_to_fun`: -/
#check continuous_on.congr
def my_second_local_homeo : local_homeomorph ℝ ℝ :=
{ to_fun := λ x, if x = 3 then 0 else - x,
inv_fun := λ x, -x,
source := Ioo (-1) 1,
target := /- inline sorry -/Ioo (-1) 1/- inline sorry -/,
map_source' := /- inline sorry -/λ x hx, by simp [hx, ne_3_of_mem_Ioo hx]/- inline sorry -/,
map_target' := /- inline sorry -/λ x hx, by simp [hx]/- inline sorry -/,
left_inv' := /- inline sorry -/λ x hx, by simp [hx, ne_3_of_mem_Ioo hx]/- inline sorry -/,
right_inv' := /- inline sorry -/λ x hx, by simp [hx, neg_ne_3_of_mem_Ioo hx]/- inline sorry -/,
open_source := /- inline sorry -/is_open_Ioo/- inline sorry -/,
open_target := /- inline sorry -/is_open_Ioo/- inline sorry -/,
continuous_to_fun :=
begin
-- sorry
refine continuous_neg.continuous_on.congr (λ x hx, _),
simp [hx, ne_3_of_mem_Ioo hx],
-- sorry
end,
continuous_inv_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/ }
/- Although the two above local homeos are the same for all practical purposes as they coincide
where relevant, they are not *equal*: -/
lemma my_first_local_homeo_ne_my_second_local_homeo :
my_first_local_homeo ≠ my_second_local_homeo :=
begin
-- sorry
assume h,
have : my_first_local_homeo 3 = my_second_local_homeo 3, by rw h,
simp [my_first_local_homeo, my_second_local_homeo] at this,
linarith,
-- sorry
end
/- The right equivalence relation for local homeos is not equality, but `eq_on_source`.
Indeed, the two local homeos we have defined above coincide from this point of view. -/
#check local_homeomorph.eq_on_source
lemma eq_on_source_my_first_local_homeo_my_second_local_homeo :
local_homeomorph.eq_on_source my_first_local_homeo my_second_local_homeo :=
begin
-- sorry
refine ⟨rfl, λ x hx, _⟩,
simp [my_first_local_homeo, my_second_local_homeo, ne_3_of_mem_Ioo hx],
-- sorry
end
/-! ### An example of a charted space structure on `ℝ`
A charted space is a topological space together with a set of local homeomorphisms to a model space,
whose sources cover the whole space. For instance, `ℝ` is already endowed with a charted space
structure with model space `ℝ`, where the unique chart is the identity:
-/
#check charted_space_self ℝ
/- For educational purposes only, we will put another charted space structure on `ℝ` using the
local homeomorphisms we have constructed above. To avoid using too much structure of `ℝ` (and to
avoid confusing Lean), we will work with a copy of `ℝ`, on which we will only register the
topology. -/
@[derive topological_space]
def myℝ : Type := ℝ
instance : charted_space ℝ myℝ :=
{ atlas := { local_homeomorph.refl ℝ, my_first_local_homeo },
chart_at := λ x, if x ∈ Ioo (-1 : ℝ) 1 then my_first_local_homeo else local_homeomorph.refl ℝ,
mem_chart_source :=
begin
-- sorry
assume x,
split_ifs,
{ exact h },
{ exact mem_univ _ }
-- sorry
end,
chart_mem_atlas :=
begin
-- sorry
assume x,
split_ifs;
simp,
-- sorry
end }
/- Now come more interesting bits. We have endowed `myℝ` with a charted space structure, with charts
taking values in `ℝ`. We want to say that this is a smooth structure, i.e., the changes of
coordinates are smooth. In Lean, this is written with `has_groupoid`. A groupoid is a set
of local homeomorphisms of the model space (for example, local homeos that are smooth on their
domain). A charted space admits the groupoid as a structure groupoid if all the changes of
coordinates belong to the groupoid.
There is a difficulty that the definitions are set up to be able to also speak of smooth manifolds
with boundary or with corners, so the name of the smooth groupoid on `ℝ` has the slightly strange
name `times_cont_diff_groupoid ∞ (model_with_corners_self ℝ ℝ)`. To avoid typing again and again
`model_with_corners_self ℝ ℝ`, let us introduce a shortcut
-/
abbreviation 𝓡1 := model_with_corners_self ℝ ℝ
/- In the library, there are such shortcuts for manifolds modelled on `ℝ^n`, denoted with `𝓡 n`,
but for `n = 1` this does not coincide with the above one, as `ℝ^1` (a.k.a. `fin 1 → ℝ`) is not
the same as `ℝ`! Still, since they are of the same nature, the notation we have just introduced
is very close, compare `𝓡1` with `𝓡 1` (and try not to get confused): -/
instance smooth_myℝ : has_groupoid myℝ (times_cont_diff_groupoid ∞ 𝓡1) :=
begin
-- in theory, we should prove that all compositions of charts are diffeos, i.e., they are smooth
-- and their inverse are smooth. For symmetry reasons, it suffices to check one direction
apply has_groupoid_of_pregroupoid,
-- take two charts `e` and `e'`
assume e e' he he',
-- if next line is a little bit slow for your taste, you can replace `simp` with `squeeze_simp`
-- and then follow the advice
simp [atlas] at he he',
dsimp,
-- to continue, some hints:
-- (1) don't hesitate to use the fact that the restriction of a smooth function to a
-- subset is still smooth there (`times_cont_diff.times_cont_diff_on`)
-- (2) hopefully, there is a theorem saying that the negation function is smooth.
-- you can either try to guess its name, or hope that `suggest` will help you there.
-- sorry
rcases he with rfl|rfl; rcases he' with rfl|rfl,
{ exact times_cont_diff_id.times_cont_diff_on },
{ exact times_cont_diff_id.neg.times_cont_diff_on },
{ exact times_cont_diff_id.neg.times_cont_diff_on },
{ convert times_cont_diff_id.times_cont_diff_on,
ext x,
simp [my_first_local_homeo], },
-- sorry
end
/- The statement of the previous instance is not very readable. There is a shortcut notation: -/
instance : smooth_manifold_with_corners 𝓡1 myℝ := { .. smooth_myℝ }
/- We will now study a very simple map from `myℝ` to `ℝ`, the identity. -/
def my_map : myℝ → ℝ := λ x, x
/- The map `my_map` is a map going from the type `myℝ` to the type `ℝ`. From the point of view of
the kernel of Lean, it is just the identity, but from the point of view of structures on `myℝ`
and `ℝ` it might not be trivial, as we have registered different instances on these two types. -/
/- The continuity should be trivial, as the topologies on `myℝ` and `ℝ` are definitionally the
same. So `continuous_id` might help. -/
lemma continuous_my_map : continuous my_map :=
-- sorry
continuous_id
-- sorry
/- Smoothness should not be obvious, though, as the manifold structures are not the same: the atlas
on `myℝ` has two elements, while the atlas on `ℝ` has one single element.
Note that `myℝ` is not a vector space, nor a normed space, so one can not ask whether `my_map`
is smooth in the usual sense (as a map between vector spaces): -/
-- lemma times_cont_diff_my_map : times_cont_diff ℝ ∞ my_map := sorry
/- does not make sense (try uncommenting it!) However, we can ask whether `my_map` is a smooth
map between manifolds, i.e., whether it is smooth when read in the charts. When we mention the
smoothness of a map, we should always specify explicitly the model with corners we are using,
because there might be several around (think of a complex manifold that you may want to consider
as a real manifold, to talk about functions which are real-smooth but not holomorphic) -/
lemma times_cont_mdiff_my_map : times_cont_mdiff 𝓡1 𝓡1 ∞ my_map :=
begin
-- put things in a nicer form. The simpset `mfld_simps` registers many simplification rules for
-- manifolds. `simp` is used heavily in manifold files to bring everything into manageable form.
rw times_cont_mdiff_iff,
simp only [continuous_my_map] with mfld_simps,
-- simp has erased the chart in the target, as it knows that the only chart in the manifold `ℝ`
-- is the identity.
assume x y,
-- sorry
simp [my_map, (∘), chart_at],
split_ifs,
{ exact times_cont_diff_id.neg.times_cont_diff_on },
{ exact times_cont_diff_id.times_cont_diff_on },
-- sorry
end
/- Now, let's go to tangent bundles. We have a smooth manifold, so its tangent bundle should also
be a smooth manifold. -/
-- the type `tangent_bundle 𝓡1 myℝ` makes sense
#check tangent_bundle 𝓡1 myℝ
/- The tangent space above a point of `myℝ` is just a one-dimensional vector space (identified with `ℝ`).
So, one can prescribe an element of the tangent bundle as a pair (more on this below) -/
example : tangent_bundle 𝓡1 myℝ := ⟨(4 : ℝ), 0⟩
/- Construct the smooth manifold structure on the tangent bundle. Hint: the answer is a one-liner,
and this instance is not really needed. -/
instance tangent_bundle_myℝ : smooth_manifold_with_corners (𝓡1.prod 𝓡1) (tangent_bundle 𝓡1 myℝ) :=
-- sorry
by apply_instance
-- sorry
/-
NB: the model space for the tangent bundle to a product manifold or a tangent space is not
`ℝ × ℝ`, but a copy called `model_prod ℝ ℝ`. Otherwise, `ℝ × ℝ` would have two charted space
structures with model `ℝ × ℝ`, the identity one and the product one, which are not definitionally
equal. And this would be bad.
-/
#check tangent_bundle.charted_space 𝓡1 myℝ
/- A smooth map between manifolds induces a map between their tangent bundles. In `mathlib` this is
called the `tangent_map` (you might instead know it as the "differential" or "pushforward" of the
map). Let us check that the `tangent_map` of `my_map` is smooth. -/
lemma times_cont_mdiff_tangent_map_my_map :
times_cont_mdiff (𝓡1.prod 𝓡1) (𝓡1.prod 𝓡1) ∞ (tangent_map 𝓡1 𝓡1 my_map) :=
begin
-- hopefully, there is a theorem providing the general result, i.e. the tangent map to a smooth
-- map is smooth.
-- you can either try to guess its name, or hope that `suggest` will help you there.
-- sorry
exact times_cont_mdiff_my_map.times_cont_mdiff_tangent_map le_top,
-- sorry
end
/- (Harder question) Can you show that this tangent bundle is homeomorphic to `ℝ × ℝ`? You could
try to build the homeomorphism by hand, using `tangent_map 𝓡1 𝓡1 my_map` in one direction and a
similar map in the other direction, but it is probably more efficient to use one of the charts of
the tangent bundle.
Remember, the model space for `tangent_bundle 𝓡1 myℝ` is `model_prod ℝ ℝ`, not `ℝ × ℝ`. But the
topologies on `model_prod ℝ ℝ` and `ℝ × ℝ` are the same, so it is by definition good enough to
construct a homeomorphism with `model_prod ℝ ℝ`.
-/
def my_homeo : tangent_bundle 𝓡1 myℝ ≃ₜ (ℝ × ℝ) :=
begin
-- sorry
let p : tangent_bundle 𝓡1 myℝ := ⟨(4 : ℝ), 0⟩,
let F := chart_at (model_prod ℝ ℝ) p,
have A : ¬ ((4 : ℝ) < 1), by norm_num,
have S : F.source = univ, by simp [F, chart_at, A, @local_homeomorph.refl_source ℝ _],
have T : F.target = univ, by simp [F, chart_at, A, @local_homeomorph.refl_target ℝ _],
exact F.to_homeomorph_of_source_eq_univ_target_eq_univ S T,
-- sorry
end
/- Up to now, we have never used the definition of the tangent bundle, and this corresponds to
the usual mathematical practice: one doesn't care if the tangent space is defined using germs of
curves, or spaces of derivations, or whatever equivalent definition. Instead, one relies all the
time on functoriality (i.e., a smooth map has a well defined derivative, and they compose well,
together with the fact that the tangent bundle to a vector space is the product).
If you want to know more about the internals of the tangent bundle in mathlib, you can browse
through the next section, but it is maybe wiser to skip it on first reading, as it is not needed
to use the library
-/
section you_should_probably_skip_this
/- If `M` is a manifold modelled on a vector space `E`, then the underlying type for the tangent
bundle is just `Σ (x : M), tangent_space x M` (i.e., the disjoint union of the tangent spaces,
indexed by `x` -- this is a basic object in dependent type theory). And `tangent_space x M`
is just (a copy of) `E` by definition. -/
lemma tangent_bundle_myℝ_is_prod : tangent_bundle 𝓡1 myℝ = Σ (x : myℝ), ℝ :=
/- inline sorry -/rfl/- inline sorry -/
/- This means that you can specify a point in the tangent bundle as a pair `⟨x, v⟩`.
However, in general, a tangent bundle is not trivial: the topology on `tangent_bundle 𝓡1 myℝ` is *not*
the product topology. Instead, the tangent space at a point `x` is identified with `ℝ` through some
preferred chart at `x`, called `chart_at ℝ x`, but the way they are glued together depends on the
manifold and the charts.
In vector spaces, the tangent space is canonically the product space, with the same topology, as
there is only one chart so there is no strange gluing at play. The fact that the canonical map
from the sigma type to the product type (called `equiv.sigma_equiv_prod`) is a homeomorphism is
given in the library by `tangent_bundle_model_space_homeomorph` (note that this is a definition,
constructing the homeomorphism, instead of a proposition asserting that `equiv.sigma_equiv_prod`
is a homeomorphism, because we use bundled homeomorphisms in mathlib).
Let us register the identification explicitly, as a homeomorphism. You can use the relevant fields
of `tangent_bundle_model_space_homeomorph` to fill the nontrivial fields here.
-/
def tangent_bundle_vector_space_triv (E : Type u) [normed_group E] [normed_space ℝ E] :
tangent_bundle (model_with_corners_self ℝ E) E ≃ₜ E × E :=
{ to_fun := λ p, (p.1, p.2),
inv_fun := λ p, ⟨p.1, p.2⟩,
left_inv := /- inline sorry -/begin rintro ⟨x, v⟩, refl end/- inline sorry -/,
right_inv := /- inline sorry -/begin rintro ⟨x, v⟩, refl end/- inline sorry -/,
continuous_to_fun := begin
-- sorry
exact (tangent_bundle_model_space_homeomorph E (model_with_corners_self ℝ E)).continuous,
-- sorry
end,
continuous_inv_fun :=
begin
-- sorry
exact (tangent_bundle_model_space_homeomorph E (model_with_corners_self ℝ E)).continuous_inv_fun,
-- sorry
end }
/- Even though the tangent bundle to `myℝ` is trivial abstractly, with this construction the
tangent bundle is *not* the product space with the product topology, as we have used various charts
so the gluing is not trivial. The following exercise unfolds the definition to see what is going on.
It is not a reasonable exercise, in the sense that one should never ever do this when working
with a manifold! -/
lemma crazy_formula_after_identifications (x : ℝ) (v : ℝ) :
let p : tangent_bundle 𝓡1 myℝ := ⟨(3 : ℝ), 0⟩ in
chart_at (model_prod ℝ ℝ) p ⟨x, v⟩ = if x ∈ Ioo (-1 : ℝ) 1 then (x, -v) else (x, v) :=
begin
-- this exercise is not easy (and shouldn't be: you are not supposed to use the library like this!)
-- if you really want to do this, you should unfold as much as you can using simp and dsimp, until you
-- are left with a statement speaking of derivatives of real functions, without any manifold code left.
-- sorry
have : ¬ ((3 : ℝ) < 1), by norm_num,
simp only [chart_at, this, mem_Ioo, if_false, and_false],
dsimp [tangent_bundle_core, basic_smooth_bundle_core.chart,
topological_fiber_bundle_core.local_triv, topological_fiber_bundle_core.local_triv',
topological_fiber_bundle_core.index_at,
basic_smooth_bundle_core.to_topological_fiber_bundle_core],
split_ifs,
{ simp only [chart_at, h, my_first_local_homeo, if_true, fderiv_within_univ, mem_Ioo, fderiv_id',
continuous_linear_map.coe_id', continuous_linear_map.neg_apply, fderiv_neg] with mfld_simps },
{ simp only [chart_at, h, fderiv_within_univ, mem_Ioo, if_false, @local_homeomorph.refl_symm ℝ,
fderiv_id, continuous_linear_map.coe_id'] with mfld_simps }
-- sorry
end
end you_should_probably_skip_this
/-!
### The language of manifolds
In this paragraph, we will try to write down interesting statements of theorems, without proving them. The
goal here is that Lean should not complain on the statement, but the proof should be sorried.
-/
/- Here is a first example, already filled up, to show you how diffeomorphisms are currently named
(we will probably introduce an abbreviation, but this hasn't been done yet).
Don't try to fill the sorried proof! -/
/-- Two zero-dimensional connected manifolds are diffeomorphic. -/
theorem diffeomorph_of_zero_dim_connected
(M M' : Type*) [topological_space M] [topological_space M']
[charted_space (euclidean_space ℝ (fin 0)) M] [charted_space (euclidean_space ℝ (fin 0)) M']
[connected_space M] [connected_space M'] :
nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 0)) M M') :=
sorry
/- Do you think that this statement is correct? (note that we have not assumed that our manifolds
are smooth, nor that they are separated, but this is maybe automatic in zero dimension).
Now, write down a version of this theorem in dimension 1, replacing the first sorry with meaningful content
(and adding what is needed before the colon).
Don't try to fill the sorried proof! -/
/-- Two one-dimensional smooth compact connected manifolds are diffeomorphic. -/
theorem diffeomorph_of_one_dim_compact_connected
-- omit
(M M' : Type*) [topological_space M] [topological_space M']
[charted_space (euclidean_space ℝ (fin 1)) M] [charted_space (euclidean_space ℝ (fin 1)) M']
[connected_space M] [connected_space M'] [compact_space M] [compact_space M']
[t2_space M] [t2_space M']
[smooth_manifold_with_corners (𝓡 1) M] [smooth_manifold_with_corners (𝓡 1) M']
-- omit
:
-- sorry
nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 1)) M M')
-- sorry
:= sorry
/- You will definitely need to require smoothness and separation in this case, as it is wrong otherwise.
Note that Lean won't complain if you don't put these assumptions, as the theorem would still make
sense, but it would just turn out to be wrong.
The previous statement is not really satisfactory: we would instead like to express that any such
manifold is diffeomorphic to the circle. The trouble is that we don't have the circle as a smooth
manifold yet. Since we have cheated and introduced it (with sorries) at the beginning of the tutorial,
let's cheat again and use it to reformulate the previous statement.
-/
-- the next result is not trivial, leave it sorried (but you can work on it if you don't like
-- manifolds and prefer topology -- then please PR it to mathlib!).
instance connected_sphere (n : ℕ) : connected_space (sphere (n+1)) := sorry
/- The next two instances are easier to prove, you can prove them or leave them sorried
as you like. For the second one, you may need to use facts of the library such as -/
#check compact_iff_compact_space
#check metric.compact_iff_closed_bounded
instance (n : ℕ) : t2_space (sphere n) :=
begin
-- sorry
dunfold sphere,
apply_instance
-- sorry
end
instance (n : ℕ) : compact_space (sphere n) :=
begin
-- sorry
dunfold sphere,
apply compact_iff_compact_space.1,
rw metric.compact_iff_closed_bounded,
split,
{ exact metric.is_closed_sphere },
{ rw metric.bounded_iff_subset_ball (0 : euclidean_space ℝ (fin (n+1))),
exact ⟨1, metric.sphere_subset_closed_ball⟩ }
-- sorry
end
/- Now, you can prove that any one-dimensional compact connected manifold is diffeomorphic to
the circle. Here, you should fill the `sorry` (but luckily you may use
`diffeomorph_of_one_dim_compact_connected`). -/
theorem diffeomorph_circle_of_one_dim_compact_connected
(M : Type*) [topological_space M] [charted_space (euclidean_space ℝ (fin 1)) M]
[connected_space M] [compact_space M] [t2_space M] [smooth_manifold_with_corners (𝓡 1) M] :
nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 1)) M (sphere 1)) :=
-- sorry
diffeomorph_of_one_dim_compact_connected M (sphere 1)
-- sorry
/- What about trying to say that there are uncountably many different smooth structures on `ℝ⁴`?
(see https://en.wikipedia.org/wiki/Exotic_R4). The library is not really designed with this in mind,
as in general we only work with one differentiable structure on a space, but it is perfectly
capable of expressing this fact if one uses the `@` version of some definitions.
Don't try to fill the sorried proof!
-/
theorem exotic_ℝ4 :
-- sorry
let E := (euclidean_space ℝ (fin 4)) in
∃ f : ℝ → charted_space E E,
∀ i, @has_groupoid E _ E _ (f i) (times_cont_diff_groupoid ∞ (𝓡 4))
∧ ∀ i j, nonempty (@structomorph _ _ (times_cont_diff_groupoid ∞ (𝓡 4)) E E _ _ (f i) (f j)) →
i = j
-- sorry
:=
sorry
/-!
### Smooth functions on `[0, 1]`
In this paragraph, you will prove several (math-trivial but Lean-nontrivial) statements on the smooth
structure of `[0,1]`. These facts should be Lean-trivial, but they are not (yet) since there is essentially
nothing in this direction for now in the library.
The goal is as much to be able to write the statements as to prove them. Most of the necessary vocabulary
has been introduced above, so don't hesitate to browse the file if you are stuck. Additionally, you will
need the notion of a smooth function on a subset: it is `times_cont_diff_on` for functions between vector
spaces and `times_cont_mdiff_on` for functions between manifolds.
Try to formulate the next math statements in Lean, and prove them (but see below for hints):
Lemma times_cont_mdiff_g : the inclusion `g` of `[0, 1]` in `ℝ` is smooth.
Lemma msmooth_of_smooth : Consider a function `f : ℝ → [0, 1]`, which is smooth in the usual sense as a function
from `ℝ` to `ℝ` on a set `s`. Then it is manifold-smooth on `s`.
Definition : construct a function `f` from `ℝ` to `[0,1]` which is the identity on `[0, 1]`.
Theorem : the tangent bundle to `[0, 1]` is homeomorphic to `[0, 1] × ℝ`
Hint for the last theorem: don't try to unfold the definition of the tangent bundle, it will only get you
into trouble. Instead, use the derivatives of the maps `f` and `g`, and rely on functoriality
to check that they are inverse to each other. (This advice is slightly misleading as these derivatives
do not go between the right spaces, so you will need to massage them a little bit).
A global advice: don't hesitate to use and abuse `simp`, it is the main workhorse in this
area of mathlib.
-/
/- After doing the exercise myself, I realized it was (way!) too hard. So I will give at least the statements
of the lemmas, to guide you a little bit more. To let you try the original version if you want,
I have left a big blank space to avoid spoilers. -/
def g : Icc (0 : ℝ) 1 → ℝ := subtype.val
-- smoothness results for `euclidean_space` are expressed for general `L^p` spaces
-- (as `euclidean_space` has the `L^2` norm), in:
#check pi_Lp.times_cont_diff_coord
#check pi_Lp.times_cont_diff_on_iff_coord
lemma times_cont_mdiff_g : times_cont_mdiff (𝓡∂ 1) 𝓡1 ∞ g :=
begin
-- sorry
rw times_cont_mdiff_iff,
refine ⟨continuous_subtype_val, λ x y, _⟩,
by_cases h : (x : ℝ) < 1,
{ simp only [g, chart_at, h, Icc_left_chart, function.comp, model_with_corners_euclidean_half_space,
add_zero, dif_pos, if_true, max_lt_iff, preimage_set_of_eq, sub_zero, subtype.range_coe_subtype,
subtype.coe_mk, subtype.val_eq_coe] with mfld_simps,
refine (pi_Lp.times_cont_diff_coord 0).times_cont_diff_on.congr (λ x hx, _),
simp only [mem_inter_eq, mem_set_of_eq] at hx,
simp only [hx, le_of_lt hx.right.left, min_eq_left, max_eq_left] },
{ simp only [chart_at, h, Icc_right_chart, function.comp, model_with_corners_euclidean_half_space, dif_pos,
max_lt_iff, preimage_set_of_eq, sub_zero, subtype.range_coe_subtype, if_false, subtype.coe_mk,
subtype.val_eq_coe, g] with mfld_simps,
have : times_cont_diff ℝ ⊤ (λ (x : euclidean_space ℝ (fin 1)), 1 - x 0) :=
times_cont_diff_const.sub (pi_Lp.times_cont_diff_coord 0),
apply this.times_cont_diff_on.congr (λ x hx, _),
simp only [mem_inter_eq, mem_set_of_eq] at hx,
have : 0 ≤ 1 - x 0, by linarith,
simp only [hx, this, max_eq_left] }
-- sorry
end
lemma msmooth_of_smooth {f : ℝ → Icc (0 : ℝ) 1} {s : set ℝ} (h : times_cont_diff_on ℝ ∞ (λ x, (f x : ℝ)) s) :
times_cont_mdiff_on 𝓡1 (𝓡∂ 1) ∞ f s :=
begin
-- sorry
rw times_cont_mdiff_on_iff,
split,
{ have : embedding (subtype.val : Icc (0 : ℝ) 1 → ℝ) := embedding_subtype_coe,
exact (embedding.continuous_on_iff this).2 h.continuous_on },
simp only with mfld_simps,
assume y,
by_cases hy : (y : ℝ) < 1,
{ simp [chart_at, model_with_corners_euclidean_half_space, (∘), hy, Icc_left_chart,
pi_Lp.times_cont_diff_on_iff_coord],
apply h.mono (inter_subset_left _ _) },
{ simp [chart_at, model_with_corners_euclidean_half_space, (∘), hy, Icc_right_chart,
pi_Lp.times_cont_diff_on_iff_coord],
assume i,
apply (times_cont_diff_on_const.sub h).mono (inter_subset_left _ _) }
-- sorry
end
/- A function from `ℝ` to `[0,1]` which is the identity on `[0,1]`. -/
def f : ℝ → Icc (0 : ℝ) 1 :=
λ x, ⟨max (min x 1) 0, by simp [le_refl, zero_le_one]⟩
lemma times_cont_mdiff_on_f : times_cont_mdiff_on 𝓡1 (𝓡∂ 1) ∞ f (Icc 0 1) :=
begin
-- sorry
apply msmooth_of_smooth,
apply times_cont_diff_id.times_cont_diff_on.congr,
assume x hx,
simp at hx,
simp [f, hx],
-- sorry
end
lemma fog : f ∘ g = id :=
begin
-- sorry
ext x,
rcases x with ⟨x', h'⟩,
simp at h',
simp [f, g, h'],
-- sorry
end
lemma gof : ∀ x ∈ Icc (0 : ℝ) 1, g (f x) = x :=
begin
-- sorry
assume x hx,
simp at hx,
simp [g, f],
simp [hx],
-- sorry
end
def G : tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) → (Icc (0 : ℝ) 1) × ℝ :=
λ p, (p.1, ((tangent_bundle_vector_space_triv ℝ) (tangent_map (𝓡∂ 1) 𝓡1 g p)).2)
lemma continuous_G : continuous G :=
begin
-- sorry
apply continuous.prod_mk (tangent_bundle_proj_continuous _ _),
refine continuous_snd.comp _,
apply continuous.comp (homeomorph.continuous _),
apply times_cont_mdiff.continuous_tangent_map times_cont_mdiff_g le_top,
-- sorry
end
def F : (Icc (0 : ℝ) 1) × ℝ → tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) :=
λ p, tangent_map_within 𝓡1 (𝓡∂ 1) f (Icc 0 1)
((tangent_bundle_vector_space_triv ℝ).symm (p.1, p.2))
lemma continuous_F : continuous F :=
begin
-- sorry
rw continuous_iff_continuous_on_univ,
apply (times_cont_mdiff_on_f.continuous_on_tangent_map_within le_top _).comp,
{ apply ((tangent_bundle_vector_space_triv ℝ).symm.continuous.comp _).continuous_on,
apply (continuous_subtype_coe.comp continuous_fst).prod_mk continuous_snd },
{ rintros ⟨⟨x, hx⟩, v⟩ _,
simp [tangent_bundle_vector_space_triv],
exact hx },
{ rw unique_mdiff_on_iff_unique_diff_on,
exact unique_diff_on_Icc_zero_one }
-- sorry
end
lemma FoG : F ∘ G = id :=
begin
-- sorry
ext1 ⟨x, v⟩,
simp [F, G, tangent_map_within, tangent_bundle_vector_space_triv, f],
dsimp,
split,
{ rcases x with ⟨x', h'⟩,
simp at h',
simp [h'] },
{ change (tangent_map_within 𝓡1 (𝓡∂ 1) f (Icc 0 1) (tangent_map (𝓡∂ 1) 𝓡1 g ⟨x, v⟩)).snd = v,
rw [← tangent_map_within_univ, ← tangent_map_within_comp_at, fog, tangent_map_within_univ, tangent_map_id],
{ refl },
{ apply times_cont_mdiff_on_f.mdifferentiable_on le_top,
simpa [g] using x.2 },
{ apply (times_cont_mdiff_g.times_cont_mdiff_at.mdifferentiable_at le_top).mdifferentiable_within_at },
{ assume z hz,
simpa [g] using z.2 },
{ apply unique_mdiff_on_univ _ (mem_univ _) } }
-- sorry
end
lemma GoF : G ∘ F = id :=
begin
-- sorry
ext1 ⟨x, v⟩,
simp [F, G, tangent_map_within, tangent_bundle_vector_space_triv, f],
dsimp,
split,
{ rcases x with ⟨x', h'⟩,
simp at h',
simp [h'] },
{ have A : unique_mdiff_within_at 𝓡1 (Icc 0 1) (⟨(x : ℝ), v⟩ : tangent_bundle 𝓡1 ℝ).fst,
{ rw unique_mdiff_within_at_iff_unique_diff_within_at,
apply unique_diff_on_Icc_zero_one _ x.2 },
change (tangent_map (𝓡∂ 1) 𝓡1 g (tangent_map_within 𝓡1 (𝓡∂ 1) f (Icc 0 1) ⟨x, v⟩)).snd = v,
rw [← tangent_map_within_univ, ← tangent_map_within_comp_at _ _ _ subset_preimage_univ A],
{ have : tangent_map_within 𝓡1 𝓡1 (g ∘ f) (Icc 0 1) ⟨x, v⟩
= tangent_map_within 𝓡1 𝓡1 id (Icc 0 1) ⟨x, v⟩ :=
tangent_map_within_congr gof _ x.2 A,
rw [this, tangent_map_within_id _ A] },
{ apply times_cont_mdiff_g.times_cont_mdiff_on.mdifferentiable_on le_top _ (mem_univ _) },
{ apply times_cont_mdiff_on_f.mdifferentiable_on le_top _ x.2 } }
-- sorry
end
def my_tangent_homeo : tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) ≃ₜ (Icc (0 : ℝ) 1) × ℝ :=
-- sorry
{ to_fun := G,
inv_fun := F,
continuous_to_fun := continuous_G,
continuous_inv_fun := continuous_F,
left_inv := λ p, show (F ∘ G) p = id p, by rw FoG,
right_inv := λ p, show (G ∘ F) p = id p, by rw GoF }
-- sorry
/-!
### Further things to do
1) can you prove `diffeomorph_of_zero_dim_connected` or `connected_sphere`?
2) Try to express and then prove the local inverse theorem in real manifolds: if a map between
real manifolds (without boundary, modelled on a complete vector space) is smooth, then it is
a local homeomorphism around each point. We already have versions of this statement in mathlib
for functions between vector spaces, but this is very much a work in progress.
3) What about trying to prove `diffeomorph_of_one_dim_compact_connected`? (I am not sure mathlib
is ready for this, as the proofs I am thinking of are currently a little bit too high-powered.
If you manage to do it, you should absolutely PR it!)
4) Why not contribute to the proof of `sphere_eversion`? You can have a look at
https://leanprover-community.github.io/sphere-eversion/ to learn more about this project
by Patrick Massot.
-/
|
8f8bd152764fa1318f1b70ab667d75401e2bbc72 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/fintype/order.lean | 2c350ed8a56b73f3b42e4e6b2f7c269b681a2f3d | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 6,087 | lean | /-
Copyright (c) 2021 Peter Nelson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Peter Nelson, Yaël Dillies
-/
import data.fintype.basic
import order.conditionally_complete_lattice
import data.finset.order
/-!
# Order structures on finite types
This file provides order instances on fintypes.
## Computable instances
On a `fintype`, we can construct
* an `order_bot` from `semilattice_inf`.
* an `order_top` from `semilattice_sup`.
* a `bounded_order` from `lattice`.
Those are marked as `def` to avoid defeqness issues.
## Completion instances
Those instances are noncomputable because the definitions of `Sup` and `Inf` use `set.to_finset` and
set membership is undecidable in general.
On a `fintype`, we can promote:
* a `lattice` to a `complete_lattice`.
* a `distrib_lattice` to a `complete_distrib_lattice`.
* a `linear_order` to a `complete_linear_order`.
* a `boolean_algebra` to a `complete_boolean_algebra`.
Those are marked as `def` to avoid typeclass loops.
## Concrete instances
We provide a few instances for concrete types:
* `fin.complete_linear_order`
* `bool.complete_linear_order`
* `bool.complete_boolean_algebra`
-/
open finset
namespace fintype
variables {ι α : Type*} [fintype ι] [fintype α]
section nonempty
variables (α) [nonempty α]
/-- Constructs the `⊥` of a finite nonempty `semilattice_inf`. -/
@[reducible] -- See note [reducible non-instances]
def to_order_bot [semilattice_inf α] : order_bot α :=
{ bot := univ.inf' univ_nonempty id,
bot_le := λ a, inf'_le _ $ mem_univ a }
/-- Constructs the `⊤` of a finite nonempty `semilattice_sup` -/
@[reducible] -- See note [reducible non-instances]
def to_order_top [semilattice_sup α] : order_top α :=
{ top := univ.sup' univ_nonempty id,
le_top := λ a, le_sup' _ $ mem_univ a }
/-- Constructs the `⊤` and `⊥` of a finite nonempty `lattice`. -/
@[reducible] -- See note [reducible non-instances]
def to_bounded_order [lattice α] : bounded_order α := { ..to_order_bot α, ..to_order_top α }
end nonempty
section bounded_order
variables (α)
open_locale classical
/-- A finite bounded lattice is complete. -/
@[reducible] -- See note [reducible non-instances]
noncomputable def to_complete_lattice [lattice α] [bounded_order α] :
complete_lattice α :=
{ Sup := λ s, s.to_finset.sup id,
Inf := λ s, s.to_finset.inf id,
le_Sup := λ _ _ ha, finset.le_sup (set.mem_to_finset.mpr ha),
Sup_le := λ s _ ha, finset.sup_le (λ b hb, ha _ $ set.mem_to_finset.mp hb),
Inf_le := λ _ _ ha, finset.inf_le (set.mem_to_finset.mpr ha),
le_Inf := λ s _ ha, finset.le_inf (λ b hb, ha _ $ set.mem_to_finset.mp hb),
.. ‹lattice α›, .. ‹bounded_order α› }
/-- A finite bounded distributive lattice is completely distributive. -/
@[reducible] -- See note [reducible non-instances]
noncomputable def to_complete_distrib_lattice [distrib_lattice α] [bounded_order α] :
complete_distrib_lattice α :=
{ infi_sup_le_sup_Inf := λ a s, begin
convert (finset.inf_sup_distrib_left _ _ _).ge,
convert (finset.inf_eq_infi _ _).symm,
simp_rw set.mem_to_finset,
refl,
end,
inf_Sup_le_supr_inf := λ a s, begin
convert (finset.sup_inf_distrib_left _ _ _).le,
convert (finset.sup_eq_supr _ _).symm,
simp_rw set.mem_to_finset,
refl,
end,
..to_complete_lattice α }
/-- A finite bounded linear order is complete. -/
@[reducible] -- See note [reducible non-instances]
noncomputable def to_complete_linear_order [linear_order α] [bounded_order α] :
complete_linear_order α :=
{ ..to_complete_lattice α, .. ‹linear_order α› }
/-- A finite boolean algebra is complete. -/
@[reducible] -- See note [reducible non-instances]
noncomputable def to_complete_boolean_algebra [boolean_algebra α] :
complete_boolean_algebra α :=
{ ..fintype.to_complete_distrib_lattice α, .. ‹boolean_algebra α› }
end bounded_order
section nonempty
variables (α) [nonempty α]
/-- A nonempty finite lattice is complete. If the lattice is already a `bounded_order`, then use
`fintype.to_complete_lattice` instead, as this gives definitional equality for `⊥` and `⊤`. -/
@[reducible] -- See note [reducible non-instances]
noncomputable def to_complete_lattice_of_nonempty [lattice α] : complete_lattice α :=
@to_complete_lattice _ _ _ $ @to_bounded_order α _ ⟨classical.arbitrary α⟩ _
/-- A nonempty finite linear order is complete. If the linear order is already a `bounded_order`,
then use `fintype.to_complete_linear_order` instead, as this gives definitional equality for `⊥` and
`⊤`. -/
@[reducible] -- See note [reducible non-instances]
noncomputable def to_complete_linear_order_of_nonempty [linear_order α] :
complete_linear_order α :=
{ ..to_complete_lattice_of_nonempty α, .. ‹linear_order α› }
end nonempty
end fintype
/-! ### Concrete instances -/
noncomputable instance {n : ℕ} : complete_linear_order (fin (n + 1)) :=
fintype.to_complete_linear_order _
noncomputable instance : complete_linear_order bool := fintype.to_complete_linear_order _
noncomputable instance : complete_boolean_algebra bool := fintype.to_complete_boolean_algebra _
/-! ### Directed Orders -/
variable {α : Type*}
theorem directed.fintype_le {r : α → α → Prop} [is_trans α r]
{β γ : Type*} [nonempty γ] {f : γ → α} [fintype β] (D : directed r f) (g : β → γ) :
∃ z, ∀ i, r (f (g i)) (f z) :=
begin
classical,
obtain ⟨z, hz⟩ := D.finset_le (finset.image g finset.univ),
exact ⟨z, λ i, hz (g i) (finset.mem_image_of_mem g (finset.mem_univ i))⟩,
end
lemma fintype.exists_le [nonempty α] [preorder α] [is_directed α (≤)]
{β : Type*} [fintype β] (f : β → α) :
∃ M, ∀ i, (f i) ≤ M :=
directed_id.fintype_le _
lemma fintype.bdd_above_range [nonempty α] [preorder α] [is_directed α (≤)]
{β : Type*} [fintype β] (f : β → α) :
bdd_above (set.range f) :=
begin
obtain ⟨M, hM⟩ := fintype.exists_le f,
refine ⟨M, λ a ha, _⟩,
obtain ⟨b, rfl⟩ := ha,
exact hM b,
end
|
db673f9dcabbfd7c380759ac3e7d20ad88b4b98e | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/order/liminf_limsup.lean | cbc9152efaeeddcde8d1fbb6ad34192717b9b898 | [
"Apache-2.0"
] | permissive | kmill/mathlib | ea5a007b67ae4e9e18dd50d31d8aa60f650425ee | 1a419a9fea7b959317eddd556e1bb9639f4dcc05 | refs/heads/master | 1,668,578,197,719 | 1,593,629,163,000 | 1,593,629,163,000 | 276,482,939 | 0 | 0 | null | 1,593,637,960,000 | 1,593,637,959,000 | null | UTF-8 | Lean | false | false | 19,889 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Johannes Hölzl
-/
import order.filter.partial
import order.filter.at_top_bot
/-!
# liminfs and limsups of functions and filters
Defines the Liminf/Limsup of a function taking values in a conditionally complete lattice, with
respect to an arbitrary filter.
We define `f.Limsup` (`f.Liminf`) where `f` is a filter taking values in a conditionally complete
lattice. `f.Limsup` is the smallest element `a` such that, eventually, `u ≤ a` (and vice versa for
`f.Liminf`). To work with the Limsup along a function `u` use `(f.map u).Limsup`.
Usually, one defines the Limsup as `Inf (Sup s)` where the Inf is taken over all sets in the filter.
For instance, in ℕ along a function `u`, this is `Inf_n (Sup_{k ≥ n} u k)` (and the latter quantity
decreases with `n`, so this is in fact a limit.). There is however a difficulty: it is well possible
that `u` is not bounded on the whole space, only eventually (think of `Limsup (λx, 1/x)` on ℝ. Then
there is no guarantee that the quantity above really decreases (the value of the `Sup` beforehand is
not really well defined, as one can not use ∞), so that the Inf could be anything. So one can not
use this `Inf Sup ...` definition in conditionally complete lattices, and one has to use a less
tractable definition.
In conditionally complete lattices, the definition is only useful for filters which are eventually
bounded above (otherwise, the Limsup would morally be +∞, which does not belong to the space) and
which are frequently bounded below (otherwise, the Limsup would morally be -∞, which is not in the
space either). We start with definitions of these concepts for arbitrary filters, before turning to
the definitions of Limsup and Liminf.
In complete lattices, however, it coincides with the `Inf Sup` definition.
-/
open filter set
open_locale filter
variables {α : Type*} {β : Type*}
namespace filter
section relation
/-- `f.is_bounded (≺)`: the filter `f` is eventually bounded w.r.t. the relation `≺`, i.e.
eventually, it is bounded by some uniform bound.
`r` will be usually instantiated with `≤` or `≥`. -/
def is_bounded (r : α → α → Prop) (f : filter α) := ∃ b, ∀ᶠ x in f, r x b
/-- `f.is_bounded_under (≺) u`: the image of the filter `f` under `u` is eventually bounded w.r.t.
the relation `≺`, i.e. eventually, it is bounded by some uniform bound. -/
def is_bounded_under (r : α → α → Prop) (f : filter β) (u : β → α) := (f.map u).is_bounded r
variables {r : α → α → Prop} {f g : filter α}
/-- `f` is eventually bounded if and only if, there exists an admissible set on which it is
bounded. -/
lemma is_bounded_iff : f.is_bounded r ↔ (∃s∈f.sets, ∃b, s ⊆ {x | r x b}) :=
iff.intro
(assume ⟨b, hb⟩, ⟨{a | r a b}, hb, b, subset.refl _⟩)
(assume ⟨s, hs, b, hb⟩, ⟨b, mem_sets_of_superset hs hb⟩)
/-- A bounded function `u` is in particular eventually bounded. -/
lemma is_bounded_under_of {f : filter β} {u : β → α} :
(∃b, ∀x, r (u x) b) → f.is_bounded_under r u
| ⟨b, hb⟩ := ⟨b, show ∀ᶠ x in f, r (u x) b, from eventually_of_forall _ hb⟩
lemma is_bounded_bot : is_bounded r ⊥ ↔ nonempty α :=
by simp [is_bounded, exists_true_iff_nonempty]
lemma is_bounded_top : is_bounded r ⊤ ↔ (∃t, ∀x, r x t) :=
by simp [is_bounded, eq_univ_iff_forall]
lemma is_bounded_principal (s : set α) : is_bounded r (𝓟 s) ↔ (∃t, ∀x∈s, r x t) :=
by simp [is_bounded, subset_def]
lemma is_bounded_sup [is_trans α r] (hr : ∀b₁ b₂, ∃b, r b₁ b ∧ r b₂ b) :
is_bounded r f → is_bounded r g → is_bounded r (f ⊔ g)
| ⟨b₁, h₁⟩ ⟨b₂, h₂⟩ := let ⟨b, rb₁b, rb₂b⟩ := hr b₁ b₂ in
⟨b, eventually_sup.mpr ⟨h₁.mono (λ x h, trans h rb₁b), h₂.mono (λ x h, trans h rb₂b)⟩⟩
lemma is_bounded_of_le (h : f ≤ g) : is_bounded r g → is_bounded r f
| ⟨b, hb⟩ := ⟨b, h hb⟩
lemma is_bounded_under_of_is_bounded {q : β → β → Prop} {u : α → β}
(hf : ∀a₀ a₁, r a₀ a₁ → q (u a₀) (u a₁)) : f.is_bounded r → f.is_bounded_under q u
| ⟨b, h⟩ := ⟨u b, show ∀ᶠ x in f, q (u x) (u b), from h.mono (λ x, hf x b)⟩
/-- `is_cobounded (≺) f` states that the filter `f` does not tend to infinity w.r.t. `≺`. This is
also called frequently bounded. Will be usually instantiated with `≤` or `≥`.
There is a subtlety in this definition: we want `f.is_cobounded` to hold for any `f` in the case of
complete lattices. This will be relevant to deduce theorems on complete lattices from their
versions on conditionally complete lattices with additional assumptions. We have to be careful in
the edge case of the trivial filter containing the empty set: the other natural definition
`¬ ∀ a, ∀ᶠ n in f, a ≤ n`
would not work as well in this case.
-/
def is_cobounded (r : α → α → Prop) (f : filter α) := ∃b, ∀a, (∀ᶠ x in f, r x a) → r b a
/-- `is_cobounded_under (≺) f u` states that the image of the filter `f` under the map `u` does not
tend to infinity w.r.t. `≺`. This is also called frequently bounded. Will be usually instantiated
with `≤` or `≥`. -/
def is_cobounded_under (r : α → α → Prop) (f : filter β) (u : β → α) := (f.map u).is_cobounded r
/-- To check that a filter is frequently bounded, it suffices to have a witness
which bounds `f` at some point for every admissible set.
This is only an implication, as the other direction is wrong for the trivial filter.-/
lemma is_cobounded.mk [is_trans α r] (a : α) (h : ∀s∈f, ∃x∈s, r a x) : f.is_cobounded r :=
⟨a, assume y s, let ⟨x, h₁, h₂⟩ := h _ s in trans h₂ h₁⟩
/-- A filter which is eventually bounded is in particular frequently bounded (in the opposite
direction). At least if the filter is not trivial. -/
lemma is_cobounded_of_is_bounded [is_trans α r] (hf : f ≠ ⊥) :
f.is_bounded r → f.is_cobounded (flip r)
| ⟨a, ha⟩ := ⟨a, assume b hb,
have ∀ᶠ x in f, r x a ∧ r b x, from ha.and hb,
let ⟨x, rxa, rbx⟩ := nonempty_of_mem_sets hf this in
show r b a, from trans rbx rxa⟩
lemma is_cobounded_bot : is_cobounded r ⊥ ↔ (∃b, ∀x, r b x) :=
by simp [is_cobounded]
lemma is_cobounded_top : is_cobounded r ⊤ ↔ nonempty α :=
by simp [is_cobounded, eq_univ_iff_forall, exists_true_iff_nonempty] {contextual := tt}
lemma is_cobounded_principal (s : set α) :
(𝓟 s).is_cobounded r↔ (∃b, ∀a, (∀x∈s, r x a) → r b a) :=
by simp [is_cobounded, subset_def]
lemma is_cobounded_of_le (h : f ≤ g) : f.is_cobounded r → g.is_cobounded r
| ⟨b, hb⟩ := ⟨b, assume a ha, hb a (h ha)⟩
end relation
instance is_trans_le [preorder α] : is_trans α (≤) := ⟨assume a b c, le_trans⟩
@[nolint ge_or_gt] -- see Note [nolint_ge]
instance is_trans_ge [preorder α] : is_trans α (≥) := ⟨assume a b c h₁ h₂, le_trans h₂ h₁⟩
lemma is_cobounded_le_of_bot [order_bot α] {f : filter α} : f.is_cobounded (≤) :=
⟨⊥, assume a h, bot_le⟩
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma is_cobounded_ge_of_top [order_top α] {f : filter α} : f.is_cobounded (≥) :=
⟨⊤, assume a h, le_top⟩
lemma is_bounded_le_of_top [order_top α] {f : filter α} : f.is_bounded (≤) :=
⟨⊤, eventually_of_forall _ $ λ _, le_top⟩
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma is_bounded_ge_of_bot [order_bot α] {f : filter α} : f.is_bounded (≥) :=
⟨⊥, eventually_of_forall _ $ λ _, bot_le⟩
lemma is_bounded_under_sup [semilattice_sup α] {f : filter β} {u v : β → α} :
f.is_bounded_under (≤) u → f.is_bounded_under (≤) v → f.is_bounded_under (≤) (λa, u a ⊔ v a)
| ⟨bu, (hu : ∀ᶠ x in f, u x ≤ bu)⟩ ⟨bv, (hv : ∀ᶠ x in f, v x ≤ bv)⟩ :=
⟨bu ⊔ bv, show ∀ᶠ x in f, u x ⊔ v x ≤ bu ⊔ bv,
by filter_upwards [hu, hv] assume x, sup_le_sup⟩
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma is_bounded_under_inf [semilattice_inf α] {f : filter β} {u v : β → α} :
f.is_bounded_under (≥) u → f.is_bounded_under (≥) v → f.is_bounded_under (≥) (λa, u a ⊓ v a)
| ⟨bu, (hu : ∀ᶠ x in f, u x ≥ bu)⟩ ⟨bv, (hv : ∀ᶠ x in f, v x ≥ bv)⟩ :=
⟨bu ⊓ bv, show ∀ᶠ x in f, u x ⊓ v x ≥ bu ⊓ bv,
by filter_upwards [hu, hv] assume x, inf_le_inf⟩
/-- Filters are automatically bounded or cobounded in complete lattices. To use the same statements
in complete and conditionally complete lattices but let automation fill automatically the
boundedness proofs in complete lattices, we use the tactic `is_bounded_default` in the statements,
in the form `(hf : f.is_bounded (≥) . is_bounded_default)`. -/
meta def is_bounded_default : tactic unit :=
tactic.applyc ``is_cobounded_le_of_bot <|>
tactic.applyc ``is_cobounded_ge_of_top <|>
tactic.applyc ``is_bounded_le_of_top <|>
tactic.applyc ``is_bounded_ge_of_bot
section conditionally_complete_lattice
variables [conditionally_complete_lattice α]
/-- The `Limsup` of a filter `f` is the infimum of the `a` such that, eventually for `f`,
holds `x ≤ a`. -/
def Limsup (f : filter α) : α := Inf { a | ∀ᶠ n in f, n ≤ a }
/-- The `Liminf` of a filter `f` is the supremum of the `a` such that, eventually for `f`,
holds `x ≥ a`. -/
def Liminf (f : filter α) : α := Sup { a | ∀ᶠ n in f, a ≤ n }
/-- The `limsup` of a function `u` along a filter `f` is the infimum of the `a` such that,
eventually for `f`, holds `u x ≤ a`. -/
def limsup (f : filter β) (u : β → α) : α := (f.map u).Limsup
/-- The `liminf` of a function `u` along a filter `f` is the supremum of the `a` such that,
eventually for `f`, holds `u x ≥ a`. -/
def liminf (f : filter β) (u : β → α) : α := (f.map u).Liminf
section
variables {f : filter β} {u : β → α}
theorem limsup_eq : f.limsup u = Inf { a | ∀ᶠ n in f, u n ≤ a } := rfl
theorem liminf_eq : f.liminf u = Sup { a | ∀ᶠ n in f, a ≤ u n } := rfl
end
theorem Limsup_le_of_le {f : filter α} {a}
(hf : f.is_cobounded (≤) . is_bounded_default) (h : ∀ᶠ n in f, n ≤ a) : f.Limsup ≤ a :=
cInf_le hf h
theorem le_Liminf_of_le {f : filter α} {a}
(hf : f.is_cobounded (≥) . is_bounded_default) (h : ∀ᶠ n in f, a ≤ n) : a ≤ f.Liminf :=
le_cSup hf h
theorem le_Limsup_of_le {f : filter α} {a}
(hf : f.is_bounded (≤) . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, n ≤ b) → a ≤ b) :
a ≤ f.Limsup :=
le_cInf hf h
theorem Liminf_le_of_le {f : filter α} {a}
(hf : f.is_bounded (≥) . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, b ≤ n) → b ≤ a) :
f.Liminf ≤ a :=
cSup_le hf h
theorem Liminf_le_Limsup {f : filter α} (hf : f ≠ ⊥)
(h₁ : f.is_bounded (≤) . is_bounded_default) (h₂ : f.is_bounded (≥) . is_bounded_default) :
f.Liminf ≤ f.Limsup :=
Liminf_le_of_le h₂ $ assume a₀ ha₀, le_Limsup_of_le h₁ $ assume a₁ ha₁, show a₀ ≤ a₁, from
have ∀ᶠ b in f, a₀ ≤ b ∧ b ≤ a₁, from ha₀.and ha₁,
let ⟨b, hb₀, hb₁⟩ := nonempty_of_mem_sets hf this in
le_trans hb₀ hb₁
lemma Liminf_le_Liminf {f g : filter α}
(hf : f.is_bounded (≥) . is_bounded_default) (hg : g.is_cobounded (≥) . is_bounded_default)
(h : ∀ a, (∀ᶠ n in f, a ≤ n) → ∀ᶠ n in g, a ≤ n) : f.Liminf ≤ g.Liminf :=
cSup_le_cSup hg hf h
lemma Limsup_le_Limsup {f g : filter α}
(hf : f.is_cobounded (≤) . is_bounded_default) (hg : g.is_bounded (≤) . is_bounded_default)
(h : ∀ a, (∀ᶠ n in g, n ≤ a) → ∀ᶠ n in f, n ≤ a) : f.Limsup ≤ g.Limsup :=
cInf_le_cInf hf hg h
lemma Limsup_le_Limsup_of_le {f g : filter α} (h : f ≤ g)
(hf : f.is_cobounded (≤) . is_bounded_default) (hg : g.is_bounded (≤) . is_bounded_default) :
f.Limsup ≤ g.Limsup :=
Limsup_le_Limsup hf hg (assume a ha, h ha)
lemma Liminf_le_Liminf_of_le {f g : filter α} (h : g ≤ f)
(hf : f.is_bounded (≥) . is_bounded_default) (hg : g.is_cobounded (≥) . is_bounded_default) :
f.Liminf ≤ g.Liminf :=
Liminf_le_Liminf hf hg (assume a ha, h ha)
lemma limsup_le_limsup {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β}
(h : ∀ᶠ a in f, u a ≤ v a)
(hu : f.is_cobounded_under (≤) u . is_bounded_default)
(hv : f.is_bounded_under (≤) v . is_bounded_default) :
f.limsup u ≤ f.limsup v :=
Limsup_le_Limsup hu hv $ assume b (hb : ∀ᶠ a in f, v a ≤ b), show ∀ᶠ a in f, u a ≤ b,
by filter_upwards [h, hb] assume a, le_trans
lemma liminf_le_liminf {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β}
(h : ∀ᶠ a in f, u a ≤ v a)
(hu : f.is_bounded_under (≥) u . is_bounded_default)
(hv : f.is_cobounded_under (≥) v . is_bounded_default) :
f.liminf u ≤ f.liminf v :=
Liminf_le_Liminf hu hv $ assume b (hb : ∀ᶠ a in f, b ≤ u a), show ∀ᶠ a in f, b ≤ v a,
by filter_upwards [hb, h] assume a, le_trans
theorem Limsup_principal {s : set α} (h : bdd_above s) (hs : s.nonempty) :
(𝓟 s).Limsup = Sup s :=
by simp [Limsup]; exact cInf_upper_bounds_eq_cSup h hs
theorem Liminf_principal {s : set α} (h : bdd_below s) (hs : s.nonempty) :
(𝓟 s).Liminf = Inf s :=
by simp [Liminf]; exact cSup_lower_bounds_eq_cInf h hs
lemma limsup_congr {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β}
(h : ∀ᶠ a in f, u a = v a) : limsup f u = limsup f v :=
begin
rw limsup_eq,
congr,
ext b,
exact eventually_congr (h.mono $ λ x hx, by simp [hx])
end
lemma liminf_congr {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β}
(h : ∀ᶠ a in f, u a = v a) : liminf f u = liminf f v :=
begin
rw liminf_eq,
congr,
ext b,
exact eventually_congr (h.mono $ λ x hx, by simp [hx])
end
lemma limsup_const {α : Type*} [conditionally_complete_lattice β] {f : filter α} (hf : f ≠ ⊥)
(b : β) : limsup f (λ x, b) = b :=
begin
rw limsup_eq,
apply le_antisymm,
{ refine cInf_le ⟨b, λ a ha, _⟩ (by simp [le_refl]),
obtain ⟨n, hn⟩ : ∃ n, b ≤ a := eventually.exists ha hf,
exact hn },
{ refine le_cInf ⟨b, by simp [le_refl]⟩ (λ a ha, _),
obtain ⟨n, hn⟩ : ∃ n, b ≤ a := eventually.exists ha hf,
exact hn }
end
lemma liminf_const {α : Type*} [conditionally_complete_lattice β] {f : filter α} (hf : f ≠ ⊥)
(b : β) : liminf f (λ x, b) = b :=
begin
rw liminf_eq,
apply le_antisymm,
{ refine cSup_le ⟨b, by simp [le_refl]⟩ (λ a ha, _),
obtain ⟨n, hn⟩ : ∃ n, a ≤ b := eventually.exists ha hf,
exact hn },
{ refine le_cSup ⟨b, λ a ha, _⟩ (by simp [le_refl]),
obtain ⟨n, hn⟩ : ∃ n, a ≤ b := eventually.exists ha hf,
exact hn }
end
end conditionally_complete_lattice
section complete_lattice
variables [complete_lattice α]
@[simp] theorem Limsup_bot : (⊥ : filter α).Limsup = ⊥ :=
bot_unique $ Inf_le $ by simp
@[simp] theorem Liminf_bot : (⊥ : filter α).Liminf = ⊤ :=
top_unique $ le_Sup $ by simp
@[simp] theorem Limsup_top : (⊤ : filter α).Limsup = ⊤ :=
top_unique $ le_Inf $
by simp [eq_univ_iff_forall]; exact assume b hb, (top_unique $ hb _)
@[simp] theorem Liminf_top : (⊤ : filter α).Liminf = ⊥ :=
bot_unique $ Sup_le $
by simp [eq_univ_iff_forall]; exact assume b hb, (bot_unique $ hb _)
lemma liminf_le_limsup {f : filter β} (hf : f ≠ ⊥) {u : β → α} : liminf f u ≤ limsup f u :=
Liminf_le_Limsup (map_ne_bot hf) is_bounded_le_of_top is_bounded_ge_of_bot
theorem Limsup_eq_infi_Sup {f : filter α} : f.Limsup = ⨅ s ∈ f, Sup s :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs, Inf_le $ show ∀ᶠ n in f, n ≤ Sup s,
by filter_upwards [hs] assume a, le_Sup)
(le_Inf $ assume a (ha : ∀ᶠ n in f, n ≤ a),
infi_le_of_le _ $ infi_le_of_le ha $ Sup_le $ assume b, id)
/-- In a complete lattice, the limsup of a function is the infimum over sets `s` in the filter
of the supremum of the function over `s` -/
theorem limsup_eq_infi_supr {f : filter β} {u : β → α} : f.limsup u = ⨅ s ∈ f, ⨆ a ∈ s, u a :=
calc f.limsup u = ⨅ s ∈ (f.map u), Sup s : Limsup_eq_infi_Sup
... = ⨅ s ∈ f, ⨆ a ∈ s, u a :
le_antisymm
(le_infi $ assume s, le_infi $ assume hs,
infi_le_of_le (u '' s) $ infi_le_of_le (image_mem_map hs) $ le_of_eq Sup_image)
(le_infi $ assume s, le_infi $ assume (hs : u ⁻¹' s ∈ f),
infi_le_of_le _ $ infi_le_of_le hs $ supr_le $ assume a, supr_le $ assume ha, le_Sup ha)
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma limsup_eq_infi_supr_of_nat {u : ℕ → α} : limsup at_top u = ⨅n:ℕ, ⨆i≥n, u i :=
calc
limsup at_top u = ⨅ s ∈ at_top, ⨆n∈s, u n : limsup_eq_infi_supr
... = ⨅ n, ⨆i≥n, u i :
le_antisymm
(le_infi $ assume n, infi_le_of_le {i | i ≥ n} $ infi_le_of_le
(mem_at_top _)
(supr_le_supr $ assume i, supr_le_supr_const (by simp)))
(le_infi $ assume s, le_infi $ assume hs,
let ⟨n, hn⟩ := mem_at_top_sets.1 hs in
infi_le_of_le n $ supr_le_supr $ assume i, supr_le_supr_const (hn i))
theorem Liminf_eq_supr_Inf {f : filter α} : f.Liminf = ⨆ s ∈ f, Inf s :=
le_antisymm
(Sup_le $ assume a (ha : ∀ᶠ n in f, a ≤ n),
le_supr_of_le _ $ le_supr_of_le ha $ le_Inf $ assume b, id)
(supr_le $ assume s, supr_le $ assume hs, le_Sup $ show ∀ᶠ n in f, Inf s ≤ n,
by filter_upwards [hs] assume a, Inf_le)
/-- In a complete lattice, the liminf of a function is the infimum over sets `s` in the filter
of the supremum of the function over `s` -/
theorem liminf_eq_supr_infi {f : filter β} {u : β → α} : f.liminf u = ⨆ s ∈ f, ⨅ a ∈ s, u a :=
calc f.liminf u = ⨆ s ∈ f.map u, Inf s : Liminf_eq_supr_Inf
... = ⨆ s ∈ f, ⨅a∈s, u a :
le_antisymm
(supr_le $ assume s, supr_le $ assume (hs : u ⁻¹' s ∈ f),
le_supr_of_le _ $ le_supr_of_le hs $ le_infi $ assume a, le_infi $ assume ha, Inf_le ha)
(supr_le $ assume s, supr_le $ assume hs,
le_supr_of_le (u '' s) $ le_supr_of_le (image_mem_map hs) $ ge_of_eq Inf_image)
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma liminf_eq_supr_infi_of_nat {u : ℕ → α} : liminf at_top u = ⨆n:ℕ, ⨅i≥n, u i :=
calc
liminf at_top u = ⨆ s ∈ at_top, ⨅ n ∈ s, u n : liminf_eq_supr_infi
... = ⨆n:ℕ, ⨅i≥n, u i :
le_antisymm
(supr_le $ assume s, supr_le $ assume hs,
let ⟨n, hn⟩ := mem_at_top_sets.1 hs in
le_supr_of_le n $ infi_le_infi $ assume i, infi_le_infi_const (hn _) )
(supr_le $ assume n, le_supr_of_le {i | n ≤ i} $
le_supr_of_le
(mem_at_top _)
(infi_le_infi $ assume i, infi_le_infi_const (by simp)))
end complete_lattice
section conditionally_complete_linear_order
lemma eventually_lt_of_lt_liminf {f : filter α} [conditionally_complete_linear_order β]
{u : α → β} {b : β} (h : b < liminf f u) (hu : f.is_bounded_under (≥) u . is_bounded_default) :
∀ᶠ a in f, b < u a :=
begin
obtain ⟨c, hc, hbc⟩ : ∃ (c : β) (hc : c ∈ {c : β | ∀ᶠ (n : α) in f, c ≤ u n}), b < c :=
exists_lt_of_lt_cSup hu h,
exact hc.mono (λ x hx, lt_of_lt_of_le hbc hx)
end
lemma eventually_lt_of_limsup_lt {f : filter α} [conditionally_complete_linear_order β]
{u : α → β} {b : β} (h : limsup f u < b) (hu : f.is_bounded_under (≤) u . is_bounded_default) :
∀ᶠ a in f, u a < b :=
begin
obtain ⟨c, hc, hbc⟩ : ∃ (c : β) (hc : c ∈ {c : β | ∀ᶠ (n : α) in f, u n ≤ c}), c < b :=
exists_lt_of_cInf_lt hu h,
exact hc.mono (λ x hx, lt_of_le_of_lt hx hbc)
end
end conditionally_complete_linear_order
end filter
|
ec52119d7e183711f9ea6ff189fa4efa9f085124 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/lint/misc.lean | 78ddc7dc12693c6b664ae7b45efab7df9b0574b2 | [
"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 | 24,730 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Robert Y. Lewis, Arthur Paulino
-/
import data.bool.basic
import meta.rb_map
import tactic.lint.basic
/-!
# Various linters
This file defines several small linters:
- `ge_or_gt` checks that `>` and `≥` do not occur in the statement of theorems.
- `dup_namespace` checks that no declaration has a duplicated namespace such as `list.list.monad`.
- `unused_arguments` checks that definitions and theorems do not have unused arguments.
- `doc_blame` checks that every definition has a documentation string.
- `doc_blame_thm` checks that every theorem has a documentation string (not enabled by default).
- `def_lemma` checks that a declaration is a lemma iff its type is a proposition.
- `check_type` checks that the statement of a declaration is well-typed.
- `check_univs` checks that there are no bad `max u v` universe levels.
- `syn_taut` checks that declarations are not syntactic tautologies.
- `unused_haves_suffices` checks that declarations produced via term mode do not have
ineffectual `have` or `suffices` statements
-/
open tactic expr
/-!
## Linter against use of `>`/`≥`
-/
/-- The names of `≥` and `>`, mostly disallowed in lemma statements -/
private meta def illegal_ge_gt : list name := [`gt, `ge]
set_option eqn_compiler.max_steps 20000
/--
Checks whether `≥` and `>` occurs in an illegal way in the expression.
The main ways we legally use these orderings are:
- `f (≥)`
- `∃ x ≥ t, b`. This corresponds to the expression
`@Exists α (fun (x : α), (@Exists (x > t) (λ (H : x > t), b)))`
This function returns `tt` when it finds `ge`/`gt`, except in the following patterns
(which are the same for `gt`):
- `f (@ge _ _)`
- `f (&0 ≥ y) (λ x : t, b)`
- `λ H : &0 ≥ t, b`
Here `&0` is the 0-th de Bruijn variable.
-/
private meta def contains_illegal_ge_gt : expr → bool
| (const nm us) := if nm ∈ illegal_ge_gt then tt else ff
| (app f e@(app (app (const nm us) tp) tc)) :=
contains_illegal_ge_gt f || if nm ∈ illegal_ge_gt then ff else contains_illegal_ge_gt e
| (app (app custom_binder (app (app (app (app (const nm us) tp) tc) (var 0)) t))
e@(lam var_name bi var_type body)) :=
contains_illegal_ge_gt e || if nm ∈ illegal_ge_gt then ff else contains_illegal_ge_gt e
| (app f x) := contains_illegal_ge_gt f || contains_illegal_ge_gt x
| (lam `H bi type@(app (app (app (app (const nm us) tp) tc) (var 0)) t) body) :=
contains_illegal_ge_gt body || if nm ∈ illegal_ge_gt then ff else contains_illegal_ge_gt type
| (lam var_name bi var_type body) := contains_illegal_ge_gt var_type || contains_illegal_ge_gt body
| (pi `H bi type@(app (app (app (app (const nm us) tp) tc) (var 0)) t) body) :=
contains_illegal_ge_gt body || if nm ∈ illegal_ge_gt then ff else contains_illegal_ge_gt type
| (pi var_name bi var_type body) := contains_illegal_ge_gt var_type || contains_illegal_ge_gt body
| (elet var_name type assignment body) :=
contains_illegal_ge_gt type || contains_illegal_ge_gt assignment || contains_illegal_ge_gt body
| _ := ff
/-- Checks whether a `>`/`≥` is used in the statement of `d`.
It first does a quick check to see if there is any `≥` or `>` in the statement, and then does a
slower check whether the occurrences of `≥` and `>` are allowed.
Currently it checks only the conclusion of the declaration, to eliminate false positive from
binders such as `∀ ε > 0, ...` -/
private meta def ge_or_gt_in_statement (d : declaration) : tactic (option string) :=
return $ if d.type.contains_constant (λ n, n ∈ illegal_ge_gt) &&
contains_illegal_ge_gt d.type
then some "the type contains ≥/>. Use ≤/< instead."
else none
-- TODO: the commented out code also checks for classicality in statements, but needs fixing
-- TODO: this probably needs to also check whether the argument is a variable or @eq <var> _ _
-- meta def illegal_constants_in_statement (d : declaration) : tactic (option string) :=
-- return $ if d.type.contains_constant (λ n, (n.get_prefix = `classical ∧
-- n.last ∈ ["prop_decidable", "dec", "dec_rel", "dec_eq"]) ∨ n ∈ [`gt, `ge])
-- then
-- let illegal1 := [`classical.prop_decidable, `classical.dec, `classical.dec_rel,
-- `classical.dec_eq],
-- illegal2 := [`gt, `ge],
-- occur1 := illegal1.filter (λ n, d.type.contains_constant (eq n)),
-- occur2 := illegal2.filter (λ n, d.type.contains_constant (eq n)) in
-- some $ sformat!"the type contains the following declarations: {occur1 ++ occur2}." ++
-- (if occur1 = [] then "" else " Add decidability type-class arguments instead.") ++
-- (if occur2 = [] then "" else " Use ≤/< instead.")
-- else none
/-- A linter for checking whether illegal constants (≥, >) appear in a declaration's type. -/
@[linter] meta def linter.ge_or_gt : linter :=
{ test := ge_or_gt_in_statement,
auto_decls := ff,
no_errors_found := "Not using ≥/> in declarations.",
errors_found := "The following declarations use ≥/>, probably in a way where we would prefer
to use ≤/< instead. See note [nolint_ge] for more information.",
is_fast := ff }
/--
Currently, the linter forbids the use of `>` and `≥` in definitions and
statements, as they cause problems in rewrites.
They are still allowed in statements such as `bounded (≥)` or `∀ ε > 0` or `⨆ n ≥ m`,
and the linter allows that.
If you write a pattern where you bind two or more variables, like `∃ n m > 0`, the linter will
flag this as illegal, but it is also allowed. In this case, add the line
```
@[nolint ge_or_gt] -- see Note [nolint_ge]
```
-/
library_note "nolint_ge"
/-!
## Linter for duplicate namespaces
-/
/-- Checks whether a declaration has a namespace twice consecutively in its name -/
private meta def dup_namespace (d : declaration) : tactic (option string) :=
is_instance d.to_name >>= λ is_inst,
return $ let nm := d.to_name.components in if nm.chain' (≠) ∨ is_inst then none
else let s := (nm.find $ λ n, nm.count n ≥ 2).iget.to_string in
some $ "The namespace `" ++ s ++ "` is duplicated in the name"
/-- A linter for checking whether a declaration has a namespace twice consecutively in its name. -/
@[linter] meta def linter.dup_namespace : linter :=
{ test := dup_namespace,
auto_decls := ff,
no_errors_found := "No declarations have a duplicate namespace.",
errors_found := "DUPLICATED NAMESPACES IN NAME:" }
attribute [nolint dup_namespace] iff.iff
/-!
## Linter for unused arguments
-/
/-- Auxiliary definition for `check_unused_arguments` -/
private meta def check_unused_arguments_aux : list ℕ → ℕ → ℕ → expr → list ℕ | l n n_max e :=
if n > n_max then l else
if ¬ is_lambda e ∧ ¬ is_pi e then l else
let b := e.binding_body in
let l' := if b.has_var_idx 0 then l else n :: l in check_unused_arguments_aux l' (n+1) n_max b
/-- Check which arguments of a declaration are not used.
Prints a list of natural numbers corresponding to which arguments are not used (e.g.
this outputs [1, 4] if the first and fourth arguments are unused).
Checks both the type and the value of `d` for whether the argument is used
(in rare cases an argument is used in the type but not in the value).
We return [] if the declaration was automatically generated.
We print arguments that are larger than the arity of the type of the declaration
(without unfolding definitions). -/
meta def check_unused_arguments (d : declaration) : option (list ℕ) :=
let l := check_unused_arguments_aux [] 1 d.type.pi_arity d.value in
if l = [] then none else
let l2 := check_unused_arguments_aux [] 1 d.type.pi_arity d.type in
(l.filter $ λ n, n ∈ l2).reverse
/-- Check for unused arguments, and print them with their position, variable name, type and whether
the argument is a duplicate.
See also `check_unused_arguments`.
This tactic additionally filters out all unused arguments of type `parse _`.
We skip all declarations that contain `sorry` in their value. -/
private meta def unused_arguments (d : declaration) : tactic (option string) := do
ff ← d.to_name.contains_sorry | return none,
let ns := check_unused_arguments d,
tt ← return ns.is_some | return none,
let ns := ns.iget,
(ds, _) ← get_pi_binders d.type,
let ns := ns.map (λ n, (n, (ds.nth $ n - 1).iget)),
let ns := ns.filter (λ x, x.2.type.get_app_fn ≠ const `interactive.parse []),
ff ← return ns.empty | return none,
ds' ← ds.mmap pp,
ns ← ns.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt n ++ ": " ++ s ++
(if ds.countp (λ b', b.type = b'.type) ≥ 2 then " (duplicate)" else "")) <$> pp b),
return $ some $ ns.to_string_aux tt
/-- A linter object for checking for unused arguments. This is in the default linter set. -/
@[linter] meta def linter.unused_arguments : linter :=
{ test := unused_arguments,
auto_decls := ff,
no_errors_found := "No unused arguments.",
errors_found := "UNUSED ARGUMENTS." }
attribute [nolint unused_arguments] imp_intro
/-!
## Linter for documentation strings
-/
/-- Reports definitions and constants that are missing doc strings -/
private meta def doc_blame_report_defn : declaration → tactic (option string)
| (declaration.defn n _ _ _ _ _) := doc_string n >> return none <|> return "def missing doc string"
| (declaration.cnst n _ _ _) := doc_string n >> return none <|> return "constant missing doc string"
| _ := return none
/-- Reports definitions and constants that are missing doc strings -/
private meta def doc_blame_report_thm : declaration → tactic (option string)
| (declaration.thm n _ _ _) := doc_string n >> return none <|> return "theorem missing doc string"
| _ := return none
/-- A linter for checking definition doc strings -/
@[linter] meta def linter.doc_blame : linter :=
{ test := λ d, mcond (bnot <$> has_attribute' `instance d.to_name)
(doc_blame_report_defn d) (return none),
auto_decls := ff,
no_errors_found := "No definitions are missing documentation.",
errors_found := "DEFINITIONS ARE MISSING DOCUMENTATION STRINGS:" }
/-- A linter for checking theorem doc strings. This is not in the default linter set. -/
meta def linter.doc_blame_thm : linter :=
{ test := doc_blame_report_thm,
auto_decls := ff,
no_errors_found := "No theorems are missing documentation.",
errors_found := "THEOREMS ARE MISSING DOCUMENTATION STRINGS:",
is_fast := ff }
/-!
## Linter for correct usage of `lemma`/`def`
-/
/--
Checks whether the correct declaration constructor (definition or theorem) by
comparing it to its sort. Instances will not be printed.
This test is not very quick: maybe we can speed-up testing that something is a proposition?
This takes almost all of the execution time.
-/
private meta def incorrect_def_lemma (d : declaration) : tactic (option string) :=
if d.is_constant ∨ d.is_axiom
then return none else do
is_instance_d ← is_instance d.to_name,
if is_instance_d then return none else do
-- the following seems to be a little quicker than `is_prop d.type`.
expr.sort n ← infer_type d.type,
is_pattern ← has_attribute' `pattern d.to_name,
return $
if d.is_theorem ↔ n = level.zero then none
else if d.is_theorem then "is a lemma/theorem, should be a def"
else if is_pattern then none -- declarations with `@[pattern]` are allowed to be a `def`.
else "is a def, should be a lemma/theorem"
/-- A linter for checking whether the correct declaration constructor (definition or theorem)
has been used. -/
@[linter] meta def linter.def_lemma : linter :=
{ test := incorrect_def_lemma,
auto_decls := ff,
no_errors_found := "All declarations correctly marked as def/lemma.",
errors_found := "INCORRECT DEF/LEMMA:" }
/-!
## Linter that checks whether declarations are well-typed
-/
/-- Checks whether the statement of a declaration is well-typed. -/
meta def check_type (d : declaration) : tactic (option string) :=
(type_check d.type >> return none) <|> return "The statement doesn't type-check"
/-- A linter for missing checking whether statements of declarations are well-typed. -/
@[linter]
meta def linter.check_type : linter :=
{ test := check_type,
auto_decls := ff,
no_errors_found :=
"The statements of all declarations type-check with default reducibility settings.",
errors_found := "THE STATEMENTS OF THE FOLLOWING DECLARATIONS DO NOT TYPE-CHECK.
Some definitions in the statement are marked `@[irreducible]`, which means that the statement " ++
"is now ill-formed. It is likely that these definitions were locally marked as `@[reducible]` " ++
"or `@[semireducible]`. This can especially cause problems with type class inference or " ++
"`@[simps]`.",
is_fast := tt }
/-!
## Linter for universe parameters
-/
open native
/--
`univ_params_grouped e` computes for each `level` `u` of `e` the parameters that occur in `u`,
and returns the corresponding set of lists of parameters.
In pseudo-mathematical form, this returns `{ { p : parameter | p ∈ u } | (u : level) ∈ e }`
We use `list name` instead of `name_set`, since `name_set` does not have an order.
It will ignore `nm₀._proof_i` declarations.
-/
meta def expr.univ_params_grouped (e : expr) (nm₀ : name) : rb_set (list name) :=
e.fold mk_rb_set $ λ e n l,
match e with
| e@(sort u) := l.insert u.params.to_list
| e@(const nm us) := if nm.get_prefix = nm₀ ∧ nm.last.starts_with "_proof_" then l else
l.union $ rb_set.of_list $ us.map $ λ u : level, u.params.to_list
| _ := l
end
/--
The good parameters are the parameters that occur somewhere in the `rb_set` as a singleton or
(recursively) with only other good parameters.
All other parameters in the `rb_set` are bad.
-/
meta def bad_params : rb_set (list name) → list name | l :=
let good_levels : name_set :=
l.fold mk_name_set $ λ us prev, if us.length = 1 then prev.insert us.head else prev in
if good_levels.empty then
l.fold [] list.union
else bad_params $ rb_set.of_list $ l.to_list.map $ λ us, us.filter $ λ nm, !good_levels.contains nm
/--
Checks whether all universe levels `u` in the type of `d` are "good".
This means that `u` either occurs in a `level` of `d` by itself, or (recursively)
with only other good levels.
When this fails, usually this means that there is a level `max u v`, where neither `u` nor `v`
occur by themselves in a level. It is ok if *one* of `u` or `v` never occurs alone. For example,
`(α : Type u) (β : Type (max u v))` is a occasionally useful method of saying that `β` lives in
a higher universe level than `α`.
-/
meta def check_univs (d : declaration) : tactic (option string) := do
let l := d.type.univ_params_grouped d.to_name,
let bad := bad_params l,
if bad.empty then return none else
return $ some $ "universes " ++ to_string bad ++ " only occur together."
/-- A linter for checking that there are no bad `max u v` universe levels. -/
@[linter]
meta def linter.check_univs : linter :=
{ test := check_univs,
auto_decls := ff,
no_errors_found :=
"All declarations have good universe levels.",
errors_found := "THE STATEMENTS OF THE FOLLOWING DECLARATIONS HAVE BAD UNIVERSE LEVELS. " ++
"This usually means that there is a `max u v` in the type where neither `u` nor `v` " ++
"occur by themselves. Solution: Find the type (or type bundled with data) that has this " ++
"universe argument and provide the universe level explicitly. If this happens in an implicit " ++
"argument of the declaration, a better solution is to move this argument to a `variables` " ++
"command (then it's not necessary to provide the universe level).
It is possible that this linter gives a false positive on definitions where the value of the " ++
"definition has the universes occur separately, and the definition will usually be used with " ++
"explicit universe arguments. In this case, feel free to add `@[nolint check_univs]`.",
is_fast := tt }
/-!
## Linter for syntactic tautologies
-/
/--
Checks whether a lemma is a declaration of the form `∀ a b ... z, e₁ = e₂`
where `e₁` and `e₂` are identical exprs.
We call declarations of this form syntactic tautologies.
Such lemmas are (mostly) useless and sometimes introduced unintentionally when proving basic facts
with rfl when elaboration results in a different term than the user intended.
-/
meta def syn_taut (d : declaration) : tactic (option string) :=
(do (el, er) ← d.type.pi_codomain.is_eq,
guardb (el =ₐ er),
return $ some "LHS equals RHS syntactically") <|>
return none
/-- A linter for checking that declarations aren't syntactic tautologies. -/
@[linter]
meta def linter.syn_taut : linter :=
{ test := syn_taut,
auto_decls := ff, -- many false positives with this enabled
no_errors_found :=
"No declarations are syntactic tautologies.",
errors_found := "THE FOLLOWING DECLARATIONS ARE SYNTACTIC TAUTOLOGIES. " ++
"This usually means that they are of the form `∀ a b ... z, e₁ = e₂` where `e₁` and `e₂` are " ++
"identical expressions. We call declarations of this form syntactic tautologies. " ++
"Such lemmas are (mostly) useless and sometimes introduced unintentionally when proving " ++
"basic facts using `rfl`, when elaboration results in a different term than the user intended. " ++
"You should check that the declaration really says what you think it does.",
is_fast := tt }
attribute [nolint syn_taut] rfl
/-!
## Linters for ineffectual have and suffices statements in term mode
-/
/--
Check if an expression contains `var 0` by folding over the expression and matching the binder depth
-/
meta def expr.has_zero_var (e : expr) : bool :=
e.fold ff $ λ e' d res, res || match e' with | var k := k = d | _ := ff end
/--
Return a list of unused have and suffices terms in an expression
-/
meta def find_unused_have_suffices_macros : expr → tactic (list string)
| (app a b) := (++) <$> find_unused_have_suffices_macros a <*> find_unused_have_suffices_macros b
| (lam var_name bi var_type body) := find_unused_have_suffices_macros body
| (pi var_name bi var_type body) := find_unused_have_suffices_macros body
| (elet var_name type assignment body) := (++) <$> find_unused_have_suffices_macros assignment
<*> find_unused_have_suffices_macros body
| m@(macro md [l@(lam ppnm bi vt bd)]) := do -- term mode have statements are tagged with a macro
-- if the macro annotation is `have then this lambda came from a term mode have statement
(++) (if m.is_annotation.iget.fst = `have ∧ ¬bd.has_zero_var then
["unnecessary have " ++ ppnm.to_string ++ " : " ++ vt.to_string]
else []) <$>
find_unused_have_suffices_macros l
| m@(macro md [app l@(lam ppnm bi vt bd) arg]) := do
-- term mode suffices statements are tagged with a macro
-- if the macro annotation is `suffices then this lambda came from a term mode suffices statement
(++) (if m.is_annotation.iget.fst = `suffices ∧ ¬bd.has_zero_var then
["unnecessary suffices " ++ ppnm.to_string ++ " : " ++ vt.to_string]
else []) <$>
((++) <$> find_unused_have_suffices_macros l <*> find_unused_have_suffices_macros arg)
| (macro md l) := list.join <$> l.mmap find_unused_have_suffices_macros
| _ := return []
/--
Return a list of unused have and suffices terms in a declaration
-/
meta def unused_have_of_decl : declaration → tactic (list string)
| (declaration.defn _ _ _ bd _ _) := find_unused_have_suffices_macros bd
| (declaration.thm _ _ _ bd) := find_unused_have_suffices_macros bd.get
| _ := return []
/--
Checks whether a declaration contains term mode have statements that have no effect on the resulting
term.
-/
meta def has_unused_haves_suffices (d : declaration) : tactic (option string) := do
ns ← unused_have_of_decl d,
if ns.length = 0 then
return none
else
return (", ".intercalate (ns.map to_string))
/-- A linter for checking that declarations don't have unused term mode have statements. We do not
tag this as `@[linter]` so that it is not in the default linter set as it is slow and an uncommon
problem. -/
meta def linter.unused_haves_suffices : linter :=
{ test := has_unused_haves_suffices,
auto_decls := ff,
no_errors_found := "No declarations have unused term mode have statements.",
errors_found := "THE FOLLOWING DECLARATIONS HAVE INEFFECTUAL TERM MODE HAVE/SUFFICES BLOCKS. " ++
"In the case of `have` this is a term of the form `have h := foo, bar` where `bar` does not " ++
"refer to `foo`. Such statements have no effect on the generated proof, and can just be " ++
"replaced by `bar`, in addition to being ineffectual, they may make unnecessary assumptions " ++
"in proofs appear as if they are used. " ++
"For `suffices` this is a term of the form `suffices h : foo, proof_of_goal, proof_of_foo` where" ++
" `proof_of_goal` does not refer to `foo`. " ++
"Such statements have no effect on the generated proof, and can just be replaced by " ++
"`proof_of_goal`, in addition to being ineffectual, they may make unnecessary assumptions in " ++
"proofs appear as if they are used. ",
is_fast := ff }
/-!
## Linter for unprintable interactive tactics
-/
/--
Ensures that every interactive tactic has arguments for which `interactive.param_desc` succeeds.
This is used to generate the parser documentation that appears in hovers on interactive tactics.
-/
meta def unprintable_interactive (d : declaration) : tactic (option string) :=
match d.to_name with
| name.mk_string _ (name.mk_string "interactive" (name.mk_string _ name.anonymous)) := do
(ds, _) ← mk_local_pis d.type,
ds ← ds.mfilter $ λ d, bnot <$> succeeds (interactive.param_desc d.local_type),
ff ← return ds.empty | return none,
ds ← ds.mmap (pp ∘ to_binder),
return $ some $ ds.to_string_aux tt
| _ := return none
end
/-- A linter for checking that interactive tactics have parser documentation. -/
@[linter]
meta def linter.unprintable_interactive : linter :=
{ test := unprintable_interactive,
auto_decls := tt,
no_errors_found := "No tactics are unprintable.",
errors_found := "THE FOLLOWING TACTICS ARE UNPRINTABLE. " ++
"This means that an interactive tactic is using `parse p` where `p` does not have " ++
"an associated description. You can fix this by wrapping `p` as `with_desc \"p\" p`, " ++
"and provide the description there, or you can stick to \"approved\" tactic combinators " ++
"like `?` `*>` `<*` `<*>` `<|>` and `<$>` (but not `>>=` or `do` blocks) " ++
"that automatically generate a description.",
is_fast := tt }
/-!
## Linter for iff's
-/
open binder_info
/--
Recursively consumes a Pi expression while accumulating names and the complement of de-Bruijn
indexes of explicit variables, ultimately obtaining the remaining non-Pi expression as well.
-/
meta def unravel_explicits_of_pi :
expr → ℕ → list name → list ℕ → (list name) × (list ℕ) × expr
| (pi n default _ e) i ln li := unravel_explicits_of_pi e (i + 1) (n :: ln) (i :: li)
| (pi n _ _ e) i ln li := unravel_explicits_of_pi e (i + 1) ln li
| e _ ln li := (ln, li, e)
/--
This function works as follows:
1. Call `unravel_explicits_of_pi` to obtain the names, complements of de-Bruijn indexes and the
remaining non-Pi expression;
2. Check if the remaining non-Pi expression is an iff, already obtaining the respective left and
right expressions if this is the case. Returns `none` otherwise;
3. Filter the explicit variables that appear on the left *and* right side of the iff;
4. If no variable satisfies the condition above, return `none`;
5. Return a message mentioning the variables that do, otherwise.
-/
meta def explicit_vars_of_iff (d : declaration) :
tactic (option string) := do
let (ln, li, e) := unravel_explicits_of_pi d.type 0 [] [],
match e.is_iff with
| none := return none
| some (el, er) := do
let li := li.map (λ i, d.type.pi_arity - i - 1), -- fixing for the actual de-Bruijn indexes
let l := (ln.zip li).filter (λ t, (el.has_var_idx t.2) && (er.has_var_idx t.2)),
if l = [] then return none
else return $ "The following variables are used on both sides of an iff and ".append $
"should be made implicit: ".append $ ", ".intercalate (l.map (λ t, to_string t.1))
end
/--
A linter for checking if variables appearing on both sides of an iff are explicit. Ideally, such
variables should be implicit instead.
-/
meta def linter.explicit_vars_of_iff : linter :=
{ test := explicit_vars_of_iff,
auto_decls := ff,
no_errors_found := "No explicit variables on both sides of iff",
errors_found := "EXPLICIT VARIABLES ON BOTH SIDES OF IFF" }
|
ca7a15c234d43f216916fd279f98add509eb3313 | 42610cc2e5db9c90269470365e6056df0122eaa0 | /library/data/real/order.lean | 25ada27633e4b6099a4ea8286c04065b981e445b | [
"Apache-2.0"
] | permissive | tomsib2001/lean | 2ab59bfaebd24a62109f800dcf4a7139ebd73858 | eb639a7d53fb40175bea5c8da86b51d14bb91f76 | refs/heads/master | 1,586,128,387,740 | 1,468,968,950,000 | 1,468,968,950,000 | 61,027,234 | 0 | 0 | null | 1,465,813,585,000 | 1,465,813,585,000 | null | UTF-8 | Lean | false | false | 38,845 | lean | /-
Copyright (c) 2015 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Robert Y. Lewis
The real numbers, constructed as equivalence classes of Cauchy sequences of rationals.
This construction follows Bishop and Bridges (1985).
To do:
o Rename things and possibly make theorems private
-/
import data.real.basic data.rat data.nat
open rat nat eq pnat
local postfix `⁻¹` := pnat.inv
local attribute real.real_has_zero [instance] [priority real.prio]
local attribute real.real_has_one [instance] [priority real.prio]
namespace rat_seq
definition pos (s : seq) := ∃ n : ℕ+, n⁻¹ < (s n)
definition nonneg (s : seq) := ∀ n : ℕ+, -(n⁻¹) ≤ s n
theorem sub_sub_comm (a b c : ℚ) : a - b - c = a - c - b :=
by rewrite [+sub_eq_add_neg, add.assoc, {-b+_}add.comm, -add.assoc]
theorem bdd_away_of_pos {s : seq} (Hs : regular s) (H : pos s) :
∃ N : ℕ+, ∀ n : ℕ+, n ≥ N → (s n) ≥ N⁻¹ :=
begin
cases H with [n, Hn],
cases sep_by_inv Hn with [N, HN],
existsi N,
intro m Hm,
have Habs : abs (s m - s n) ≥ s n - s m, by rewrite abs_sub; apply le_abs_self,
have Habs' : s m + abs (s m - s n) ≥ s n, from (iff.mpr (le_add_iff_sub_left_le _ _ _)) Habs,
have HN' : N⁻¹ + N⁻¹ ≤ s n - n⁻¹, begin
rewrite sub_eq_add_neg,
apply iff.mpr (le_add_iff_sub_right_le _ _ _),
rewrite [sub_neg_eq_add, add.comm, -add.assoc],
apply le_of_lt HN
end,
rewrite add.comm at Habs',
have Hin : s m ≥ N⁻¹, from calc
s m ≥ s n - abs (s m - s n) : (iff.mp (le_add_iff_sub_left_le _ _ _)) Habs'
... ≥ s n - (m⁻¹ + n⁻¹) : sub_le_sub_left !Hs
... = s n - m⁻¹ - n⁻¹ : by rewrite sub_add_eq_sub_sub
... = s n - n⁻¹ - m⁻¹ : by rewrite sub_sub_comm
... ≥ s n - n⁻¹ - N⁻¹ : sub_le_sub_left (inv_ge_of_le Hm)
... ≥ N⁻¹ + N⁻¹ - N⁻¹ : sub_le_sub_right HN'
... = N⁻¹ : by rewrite add_sub_cancel,
apply Hin
end
theorem pos_of_bdd_away {s : seq} (H : ∃ N : ℕ+, ∀ n : ℕ+, n ≥ N → (s n) ≥ N⁻¹) : pos s :=
begin
cases H with [N, HN],
existsi (N + pone),
apply lt_of_lt_of_le,
apply inv_add_lt_left,
apply HN,
apply pnat.le_of_lt,
apply lt_add_left
end
theorem bdd_within_of_nonneg {s : seq} (Hs : regular s) (H : nonneg s) :
∀ n : ℕ+, ∃ N : ℕ+, ∀ m : ℕ+, m ≥ N → s m ≥ -n⁻¹ :=
begin
intros,
existsi n,
intro m Hm,
apply le.trans,
apply neg_le_neg,
apply inv_ge_of_le,
apply Hm,
apply H
end
theorem nonneg_of_bdd_within {s : seq} (Hs : regular s)
(H : ∀n : ℕ+, ∃ N : ℕ+, ∀ m : ℕ+, m ≥ N → s m ≥ -n⁻¹) : nonneg s :=
begin
rewrite ↑nonneg,
intro k,
apply ge_of_forall_ge_sub,
intro ε Hε,
cases H (pceil ((2) / ε)) with [N, HN],
apply le.trans,
rotate 1,
apply sub_le_of_abs_sub_le_left,
apply Hs,
apply (max (pceil ((2)/ε)) N),
rewrite [+sub_eq_add_neg, neg_add, {_ + (-k⁻¹ + _)}add.comm, *add.assoc],
apply rat.add_le_add_left,
apply le.trans,
rotate 1,
apply add_le_add,
rotate 1,
apply HN (max (pceil ((2)/ε)) N) !pnat.max_right,
rotate_right 1,
apply neg_le_neg,
apply inv_ge_of_le,
apply pnat.max_left,
rewrite -neg_add,
apply neg_le_neg,
apply le.trans,
apply add_le_add,
repeat (apply inv_pceil_div;
apply add_pos;
repeat apply zero_lt_one;
exact Hε),
rewrite [add_halves],
apply rat.le_refl
end
theorem pos_of_pos_equiv {s t : seq} (Hs : regular s) (Heq : s ≡ t) (Hp : pos s) : pos t :=
begin
cases (bdd_away_of_pos Hs Hp) with [N, HN],
existsi 2 * 2 * N,
apply lt_of_lt_of_le,
rotate 1,
apply sub_le_of_abs_sub_le_right,
apply Heq,
have Hs4 : N⁻¹ ≤ s (2 * 2 * N), from HN _ (!pnat.mul_le_mul_left),
apply lt_of_lt_of_le,
rotate 1,
rewrite sub_eq_add_neg,
apply iff.mpr !add_le_add_right_iff,
apply Hs4,
rewrite [*pnat.mul_assoc, pnat.add_halves, -(pnat.add_halves N), -sub_eq_add_neg, add_sub_cancel],
apply inv_two_mul_lt_inv
end
theorem nonneg_of_nonneg_equiv {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t)
(Hp : nonneg s) : nonneg t :=
begin
apply nonneg_of_bdd_within,
apply Ht,
intros,
cases bdd_within_of_nonneg Hs Hp (2 * 2 * n) with [Ns, HNs],
existsi max Ns (2 * 2 * n),
intro m Hm,
apply le.trans,
rotate 1,
apply sub_le_of_abs_sub_le_right,
apply Heq,
apply le.trans,
rotate 1,
apply sub_le_sub_right,
apply HNs,
apply pnat.le_trans,
rotate 1,
apply Hm,
rotate_right 1,
apply pnat.max_left,
have Hms : m⁻¹ ≤ (2 * 2 * n)⁻¹, begin
apply inv_ge_of_le,
apply pnat.le_trans,
rotate 1,
apply Hm;
apply pnat.max_right
end,
have Hms' : m⁻¹ + m⁻¹ ≤ (2 * 2 * n)⁻¹ + (2 * 2 * n)⁻¹, from add_le_add Hms Hms,
apply le.trans,
rotate 1,
apply sub_le_sub_left,
apply Hms',
rewrite [*pnat.mul_assoc, pnat.add_halves, -neg_sub, -pnat.add_halves n, sub_neg_eq_add],
apply neg_le_neg,
apply add_le_add_left,
apply inv_two_mul_le_inv
end
definition s_le (a b : seq) := nonneg (sadd b (sneg a))
definition s_lt (a b : seq) := pos (sadd b (sneg a))
theorem zero_nonneg : nonneg zero :=
begin
intros,
apply neg_nonpos_of_nonneg,
apply rat.le_of_lt,
apply pnat.inv_pos
end
theorem s_zero_lt_one : s_lt zero one :=
begin
rewrite [↑s_lt, ↑zero, ↑sadd, ↑sneg, ↑one, neg_zero, add_zero, ↑pos],
existsi 2,
apply inv_lt_one_of_gt,
apply one_lt_two
end
protected theorem le_refl {s : seq} (Hs : regular s) : s_le s s :=
begin
apply nonneg_of_nonneg_equiv,
rotate 2,
apply equiv.symm,
apply neg_s_cancel s Hs,
apply zero_nonneg,
apply zero_is_reg,
apply reg_add_reg Hs (reg_neg_reg Hs)
end
theorem s_nonneg_of_pos {s : seq} (Hs : regular s) (H : pos s) : nonneg s :=
begin
apply nonneg_of_bdd_within,
apply Hs,
intros,
cases bdd_away_of_pos Hs H with [N, HN],
existsi N,
intro m Hm,
apply le.trans,
rotate 1,
apply HN,
apply Hm,
apply le.trans,
rotate 1,
apply rat.le_of_lt,
apply pnat.inv_pos,
rewrite -neg_zero,
apply neg_le_neg,
apply rat.le_of_lt,
apply pnat.inv_pos
end
theorem s_le_of_s_lt {s t : seq} (Hs : regular s) (Ht : regular t) (H : s_lt s t) : s_le s t :=
begin
rewrite [↑s_le, ↑s_lt at *],
apply s_nonneg_of_pos,
repeat (apply reg_add_reg | apply reg_neg_reg | assumption)
end
theorem s_neg_add_eq_s_add_neg (s t : seq) : sneg (sadd s t) ≡ sadd (sneg s) (sneg t) :=
begin
rewrite [↑equiv, ↑sadd, ↑sneg],
intros,
rewrite [neg_add, sub_self, abs_zero],
apply add_invs_nonneg
end
theorem equiv_cancel_middle {s t u : seq} (Hs : regular s) (Ht : regular t)
(Hu : regular u) : sadd (sadd u t) (sneg (sadd u s)) ≡ sadd t (sneg s) :=
begin
note Hz := zero_is_reg,
apply equiv.trans,
rotate 3,
apply add_well_defined,
rotate 4,
apply s_add_comm,
apply s_neg_add_eq_s_add_neg,
apply equiv.trans,
rotate 3,
apply s_add_assoc,
rotate 2,
apply add_well_defined,
rotate 4,
apply equiv.refl,
apply equiv.trans,
rotate 4,
apply equiv.refl,
rotate_right 1,
apply equiv.trans,
rotate 3,
apply equiv.symm,
apply s_add_assoc,
rotate 2,
apply equiv.trans,
rotate 4,
apply s_zero_add,
rotate_right 1,
apply add_well_defined,
rotate 4,
apply neg_s_cancel,
rotate 1,
apply equiv.refl,
repeat (apply reg_add_reg | apply reg_neg_reg | assumption)
end
protected theorem add_le_add_of_le_right {s t : seq} (Hs : regular s) (Ht : regular t)
(Lst : s_le s t) : ∀ u : seq, regular u → s_le (sadd u s) (sadd u t) :=
begin
intro u Hu,
rewrite [↑s_le at *],
apply nonneg_of_nonneg_equiv,
rotate 2,
apply equiv.symm,
apply equiv_cancel_middle,
repeat (apply reg_add_reg | apply reg_neg_reg | assumption)
end
theorem s_add_lt_add_left {s t : seq} (Hs : regular s) (Ht : regular t) (Hst : s_lt s t) {u : seq}
(Hu : regular u) : s_lt (sadd u s) (sadd u t) :=
begin
rewrite ↑s_lt at *,
apply pos_of_pos_equiv,
rotate 1,
apply equiv.symm,
apply equiv_cancel_middle,
repeat (apply reg_add_reg | apply reg_neg_reg | assumption)
end
protected theorem add_nonneg_of_nonneg {s t : seq} (Hs : nonneg s) (Ht : nonneg t) :
nonneg (sadd s t) :=
begin
intros,
rewrite [-pnat.add_halves, neg_add],
apply add_le_add,
apply Hs,
apply Ht
end
protected theorem le_trans {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u)
(Lst : s_le s t) (Ltu : s_le t u) : s_le s u :=
begin
rewrite ↑s_le at *,
note Rz := zero_is_reg,
have Hsum : nonneg (sadd (sadd u (sneg t)) (sadd t (sneg s))),
from rat_seq.add_nonneg_of_nonneg Ltu Lst,
have H' : nonneg (sadd (sadd u (sadd (sneg t) t)) (sneg s)), begin
apply nonneg_of_nonneg_equiv,
rotate 2,
apply add_well_defined,
rotate 4,
apply s_add_assoc,
repeat (apply reg_add_reg | apply reg_neg_reg | assumption),
apply equiv.refl,
apply nonneg_of_nonneg_equiv,
rotate 2,
apply equiv.symm,
apply s_add_assoc,
rotate 2,
repeat (apply reg_add_reg | apply reg_neg_reg | assumption)
end,
have H'' : sadd (sadd u (sadd (sneg t) t)) (sneg s) ≡ sadd u (sneg s), begin
apply add_well_defined,
rotate 4,
apply equiv.trans,
rotate 3,
apply add_well_defined,
rotate 4,
apply equiv.refl,
apply s_neg_cancel,
rotate 1,
apply s_add_zero,
rotate 1,
apply equiv.refl,
repeat (apply reg_add_reg | apply reg_neg_reg | assumption)
end,
apply nonneg_of_nonneg_equiv,
rotate 2,
apply H'',
apply H',
repeat (apply reg_add_reg | apply reg_neg_reg | assumption)
end
theorem equiv_of_le_of_ge {s t : seq} (Hs : regular s) (Ht : regular t) (Lst : s_le s t)
(Lts : s_le t s) : s ≡ t :=
begin
apply equiv_of_diff_equiv_zero,
rotate 2,
rewrite [↑s_le at *, ↑nonneg at *, ↑equiv, ↑sadd at *, ↑sneg at *],
intros,
rewrite [↑zero, sub_zero],
apply abs_le_of_le_of_neg_le,
apply le_of_neg_le_neg,
rewrite [2 neg_add, neg_neg],
apply rat.le_trans,
apply neg_add_neg_le_neg_of_pos,
apply pnat.inv_pos,
rewrite add.comm,
apply Lst,
apply le_of_neg_le_neg,
rewrite [neg_add, neg_neg],
apply rat.le_trans,
apply neg_add_neg_le_neg_of_pos,
apply pnat.inv_pos,
apply Lts,
repeat assumption
end
definition sep (s t : seq) := s_lt s t ∨ s_lt t s
local infix `≢` : 50 := sep
theorem le_and_sep_of_lt {s t : seq} (Hs : regular s) (Ht : regular t) (Lst : s_lt s t) :
s_le s t ∧ sep s t :=
begin
apply and.intro,
intros,
cases Lst with [N, HN],
let Rns := reg_neg_reg Hs,
let Rtns := reg_add_reg Ht Rns,
note Habs := sub_le_of_abs_sub_le_right (Rtns N n),
rewrite [sub_add_eq_sub_sub at Habs],
exact (calc
sadd t (sneg s) n ≥ sadd t (sneg s) N - N⁻¹ - n⁻¹ : Habs
... ≥ 0 - n⁻¹: begin
apply sub_le_sub_right,
apply rat.le_of_lt,
apply (iff.mpr (sub_pos_iff_lt _ _)),
apply HN
end
... = -n⁻¹ : by rewrite zero_sub),
exact or.inl Lst
end
theorem lt_of_le_and_sep {s t : seq} (Hs : regular s) (Ht : regular t) (H : s_le s t ∧ sep s t) :
s_lt s t :=
begin
note Le := and.left H,
cases and.right H with [P, Hlt],
exact P,
rewrite [↑s_le at Le, ↑nonneg at Le, ↑s_lt at Hlt, ↑pos at Hlt],
apply exists.elim Hlt,
intro N HN,
let LeN := Le N,
note HN' := (iff.mpr !neg_lt_neg_iff_lt) HN,
rewrite [↑sadd at HN', ↑sneg at HN', neg_add at HN', neg_neg at HN', add.comm at HN'],
let HN'' := not_le_of_gt HN',
apply absurd LeN HN''
end
theorem lt_iff_le_and_sep {s t : seq} (Hs : regular s) (Ht : regular t) :
s_lt s t ↔ s_le s t ∧ sep s t :=
iff.intro (le_and_sep_of_lt Hs Ht) (lt_of_le_and_sep Hs Ht)
theorem s_neg_zero : sneg zero ≡ zero :=
begin
rewrite ↑[sneg, zero, equiv],
intros,
rewrite [sub_zero, abs_neg, abs_zero],
apply add_invs_nonneg
end
theorem s_sub_zero {s : seq} (Hs : regular s) : sadd s (sneg zero) ≡ s :=
begin
apply equiv.trans,
rotate 3,
apply add_well_defined,
rotate 4,
apply equiv.refl,
apply s_neg_zero,
apply s_add_zero,
repeat (assumption | apply reg_add_reg | apply reg_neg_reg | apply zero_is_reg)
end
theorem s_pos_of_gt_zero {s : seq} (Hs : regular s) (Hgz : s_lt zero s) : pos s :=
begin
rewrite [↑s_lt at *],
apply pos_of_pos_equiv,
rotate 1,
apply s_sub_zero,
repeat (assumption | apply reg_add_reg | apply reg_neg_reg),
apply zero_is_reg
end
theorem s_gt_zero_of_pos {s : seq} (Hs : regular s) (Hp : pos s) : s_lt zero s :=
begin
rewrite ↑s_lt,
apply pos_of_pos_equiv,
rotate 1,
apply equiv.symm,
apply s_sub_zero,
repeat assumption
end
theorem s_nonneg_of_ge_zero {s : seq} (Hs : regular s) (Hgz : s_le zero s) : nonneg s :=
begin
rewrite ↑s_le at *,
apply nonneg_of_nonneg_equiv,
rotate 2,
apply s_sub_zero,
repeat (assumption | apply reg_add_reg | apply reg_neg_reg | apply zero_is_reg)
end
theorem s_ge_zero_of_nonneg {s : seq} (Hs : regular s) (Hn : nonneg s) : s_le zero s :=
begin
rewrite ↑s_le,
apply nonneg_of_nonneg_equiv,
rotate 2,
apply equiv.symm,
apply s_sub_zero,
repeat (assumption | apply reg_add_reg | apply reg_neg_reg | apply zero_is_reg)
end
theorem s_mul_pos_of_pos {s t : seq} (Hs : regular s) (Ht : regular t) (Hps : pos s)
(Hpt : pos t) : pos (smul s t) :=
begin
rewrite [↑pos at *],
cases bdd_away_of_pos Hs Hps with [Ns, HNs],
cases bdd_away_of_pos Ht Hpt with [Nt, HNt],
existsi 2 * max Ns Nt * max Ns Nt,
rewrite ↑smul,
apply lt_of_lt_of_le,
rotate 1,
apply mul_le_mul,
apply HNs,
apply pnat.le_trans,
apply pnat.max_left Ns Nt,
rewrite -pnat.mul_assoc,
apply pnat.mul_le_mul_left,
apply HNt,
apply pnat.le_trans,
apply pnat.max_right Ns Nt,
rewrite -pnat.mul_assoc,
apply pnat.mul_le_mul_left,
apply rat.le_of_lt,
apply pnat.inv_pos,
apply rat.le_trans,
rotate 1,
apply HNs,
apply pnat.le_trans,
apply pnat.max_left Ns Nt,
rewrite -pnat.mul_assoc,
apply pnat.mul_le_mul_left,
rewrite pnat.inv_mul_eq_mul_inv,
apply mul_lt_mul,
rewrite [pnat.inv_mul_eq_mul_inv, -one_mul Ns⁻¹],
apply mul_lt_mul,
apply inv_lt_one_of_gt,
apply dec_trivial,
apply inv_ge_of_le,
apply pnat.max_left,
apply pnat.inv_pos,
apply rat.le_of_lt zero_lt_one,
apply inv_ge_of_le,
apply pnat.max_right,
apply pnat.inv_pos,
repeat (apply le_of_lt; apply pnat.inv_pos)
end
theorem s_mul_gt_zero_of_gt_zero {s t : seq} (Hs : regular s) (Ht : regular t)
(Hzs : s_lt zero s) (Hzt : s_lt zero t) : s_lt zero (smul s t) :=
s_gt_zero_of_pos
(reg_mul_reg Hs Ht)
(s_mul_pos_of_pos Hs Ht (s_pos_of_gt_zero Hs Hzs) (s_pos_of_gt_zero Ht Hzt))
theorem le_of_lt_or_equiv {s t : seq} (Hs : regular s) (Ht : regular t)
(Hor : (s_lt s t) ∨ (s ≡ t)) : s_le s t :=
or.elim Hor
(begin
intro Hlt,
apply s_le_of_s_lt Hs Ht Hlt
end)
(begin
intro Heq,
rewrite ↑s_le,
apply nonneg_of_nonneg_equiv,
rotate 3,
apply zero_nonneg,
apply zero_is_reg,
apply reg_add_reg Ht (reg_neg_reg Hs),
apply equiv.symm,
apply diff_equiv_zero_of_equiv,
rotate 2,
apply equiv.symm,
apply Heq,
repeat assumption
end)
theorem s_zero_mul {s : seq} : smul s zero ≡ zero :=
begin
rewrite [↑equiv, ↑smul, ↑zero],
intros,
rewrite [mul_zero, sub_zero, abs_zero],
apply add_invs_nonneg
end
theorem s_mul_nonneg_of_pos_of_zero {s t : seq} (Hs : regular s) (Ht : regular t)
(Hps : pos s) (Hpt : zero ≡ t) : nonneg (smul s t) :=
begin
apply nonneg_of_nonneg_equiv,
rotate 2,
apply mul_well_defined,
rotate 4,
apply equiv.refl,
apply Hpt,
apply nonneg_of_nonneg_equiv,
rotate 2,
apply equiv.symm,
apply s_zero_mul,
apply zero_nonneg,
repeat (assumption | apply reg_mul_reg | apply zero_is_reg)
end
theorem s_mul_nonneg_of_nonneg {s t : seq} (Hs : regular s) (Ht : regular t)
(Hps : nonneg s) (Hpt : nonneg t) : nonneg (smul s t) :=
begin
intro n,
rewrite ↑smul,
apply rat.le_by_cases 0 (s (((K₂ s t) * 2) * n)),
intro Hsp,
apply rat.le_by_cases 0 (t (((K₂ s t) * 2) * n)),
intro Htp,
apply rat.le_trans,
rotate 1,
apply rat.mul_nonneg Hsp Htp,
rotate_right 1,
apply le_of_lt,
apply neg_neg_of_pos,
apply pnat.inv_pos,
intro Htn,
apply rat.le_trans,
rotate 1,
apply mul_le_mul_of_nonpos_right,
apply rat.le_trans,
apply le_abs_self,
apply canon_2_bound_left s t Hs,
apply Htn,
rotate_right 1,
apply rat.le_trans,
rotate 1,
apply mul_le_mul_of_nonneg_left,
apply Hpt,
apply le_of_lt,
apply rat_of_pnat_is_pos,
rotate 1,
rewrite -neg_mul_eq_mul_neg,
apply neg_le_neg,
rewrite [*pnat.mul_assoc, pnat.inv_mul_eq_mul_inv, -mul.assoc, pnat.inv_cancel_left, one_mul],
apply inv_ge_of_le,
apply pnat.mul_le_mul_left,
intro Hsn,
apply rat.le_by_cases 0 (t (((K₂ s t) * 2) * n)),
intro Htp,
apply rat.le_trans,
rotate 1,
apply mul_le_mul_of_nonpos_left,
apply rat.le_trans,
apply le_abs_self,
apply canon_2_bound_right s t Ht,
apply Hsn,
rotate_right 1,
apply rat.le_trans,
rotate 1,
apply mul_le_mul_of_nonneg_right,
apply Hps,
apply le_of_lt,
apply rat_of_pnat_is_pos,
rotate 1,
rewrite -neg_mul_eq_neg_mul,
apply neg_le_neg,
rewrite [+pnat.mul_assoc, pnat.inv_mul_eq_mul_inv, mul.comm, -mul.assoc, pnat.inv_cancel_left,
one_mul],
apply inv_ge_of_le,
apply pnat.mul_le_mul_left,
intro Htn,
apply le.trans,
rotate 1,
apply mul_nonneg_of_nonpos_of_nonpos,
apply Hsn,
apply Htn,
apply le_of_lt,
apply neg_neg_of_pos,
apply pnat.inv_pos
end
theorem s_mul_ge_zero_of_ge_zero {s t : seq} (Hs : regular s) (Ht : regular t)
(Hzs : s_le zero s) (Hzt : s_le zero t) : s_le zero (smul s t) :=
begin
note Hzs' := s_nonneg_of_ge_zero Hs Hzs,
note Htz' := s_nonneg_of_ge_zero Ht Hzt,
apply s_ge_zero_of_nonneg,
rotate 1,
apply s_mul_nonneg_of_nonneg,
repeat assumption,
apply reg_mul_reg Hs Ht
end
protected theorem not_lt_self (s : seq) : ¬ s_lt s s :=
begin
intro Hlt,
rewrite [↑s_lt at Hlt, ↑pos at Hlt],
apply exists.elim Hlt,
intro n Hn, esimp at Hn,
rewrite [↑sadd at Hn,↑sneg at Hn, -sub_eq_add_neg at Hn, sub_self at Hn],
apply absurd Hn (not_lt_of_ge (rat.le_of_lt !pnat.inv_pos))
end
theorem not_sep_self (s : seq) : ¬ s ≢ s :=
begin
intro Hsep,
rewrite ↑sep at Hsep,
let Hsep' := (iff.mp !or_self) Hsep,
apply absurd Hsep' (!rat_seq.not_lt_self)
end
theorem le_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u)
(Hv : regular v) (Hsu : s ≡ u) (Htv : t ≡ v) : s_le s t ↔ s_le u v :=
iff.intro
(begin
intro Hle,
rewrite [↑s_le at *],
apply nonneg_of_nonneg_equiv,
rotate 2,
apply add_well_defined,
rotate 4,
apply Htv,
apply neg_well_defined,
apply Hsu,
apply Hle,
repeat (apply reg_add_reg | apply reg_neg_reg | assumption)
end)
(begin
intro Hle,
rewrite [↑s_le at *],
apply nonneg_of_nonneg_equiv,
rotate 2,
apply add_well_defined,
rotate 4,
apply equiv.symm, apply Htv,
apply neg_well_defined,
apply equiv.symm, apply Hsu,
apply Hle,
repeat (apply reg_add_reg | apply reg_neg_reg | assumption)
end)
theorem lt_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u)
(Hv : regular v) (Hsu : s ≡ u) (Htv : t ≡ v) : s_lt s t ↔ s_lt u v :=
iff.intro
(begin
intro Hle,
rewrite [↑s_lt at *],
apply pos_of_pos_equiv,
rotate 1,
apply add_well_defined,
rotate 4,
apply Htv,
apply neg_well_defined,
apply Hsu,
apply Hle,
repeat (apply reg_add_reg | apply reg_neg_reg | assumption)
end)
(begin
intro Hle,
rewrite [↑s_lt at *],
apply pos_of_pos_equiv,
rotate 1,
apply add_well_defined,
rotate 4,
apply equiv.symm, apply Htv,
apply neg_well_defined,
apply equiv.symm, apply Hsu,
apply Hle,
repeat (apply reg_add_reg | apply reg_neg_reg | assumption)
end)
theorem sep_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u)
(Hv : regular v) (Hsu : s ≡ u) (Htv : t ≡ v) : s ≢ t ↔ u ≢ v :=
begin
rewrite ↑sep,
apply iff.intro,
intro Hor,
apply or.elim Hor,
intro Hlt,
apply or.inl,
apply iff.mp (lt_well_defined Hs Ht Hu Hv Hsu Htv),
assumption,
intro Hlt,
apply or.inr,
apply iff.mp (lt_well_defined Ht Hs Hv Hu Htv Hsu),
assumption,
intro Hor,
apply or.elim Hor,
intro Hlt,
apply or.inl,
apply iff.mpr (lt_well_defined Hs Ht Hu Hv Hsu Htv),
assumption,
intro Hlt,
apply or.inr,
apply iff.mpr (lt_well_defined Ht Hs Hv Hu Htv Hsu),
assumption
end
theorem s_lt_of_lt_of_le {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u)
(Hst : s_lt s t) (Htu : s_le t u) : s_lt s u :=
begin
let Rtns := reg_add_reg Ht (reg_neg_reg Hs),
let Runt := reg_add_reg Hu (reg_neg_reg Ht),
have Hcan : ∀ m, sadd u (sneg s) m = (sadd t (sneg s)) m + (sadd u (sneg t)) m, begin
intro m,
rewrite [↑sadd, ↑sneg, -*sub_eq_add_neg, -sub_eq_sub_add_sub]
end,
rewrite [↑s_lt at *, ↑s_le at *],
cases bdd_away_of_pos Rtns Hst with [Nt, HNt],
cases bdd_within_of_nonneg Runt Htu (2 * Nt) with [Nu, HNu],
apply pos_of_bdd_away,
existsi max (2 * Nt) Nu,
intro n Hn,
rewrite Hcan,
apply rat.le_trans,
rotate 1,
apply add_le_add,
apply HNt,
apply pnat.le_trans,
apply pnat.mul_le_mul_left 2,
apply pnat.le_trans,
rotate 1,
apply Hn,
rotate_right 1,
apply pnat.max_left,
apply HNu,
apply pnat.le_trans,
rotate 1,
apply Hn,
rotate_right 1,
apply pnat.max_right,
rewrite [-pnat.add_halves Nt, -sub_eq_add_neg, add_sub_cancel],
apply inv_ge_of_le,
apply pnat.max_left
end
theorem s_lt_of_le_of_lt {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u)
(Hst : s_le s t) (Htu : s_lt t u) : s_lt s u :=
begin
let Rtns := reg_add_reg Ht (reg_neg_reg Hs),
let Runt := reg_add_reg Hu (reg_neg_reg Ht),
have Hcan : ∀ m, sadd u (sneg s) m = (sadd t (sneg s)) m + (sadd u (sneg t)) m, begin
intro m,
rewrite [↑sadd, ↑sneg, -*sub_eq_add_neg, -sub_eq_sub_add_sub]
end,
rewrite [↑s_lt at *, ↑s_le at *],
cases bdd_away_of_pos Runt Htu with [Nu, HNu],
cases bdd_within_of_nonneg Rtns Hst (2 * Nu) with [Nt, HNt],
apply pos_of_bdd_away,
existsi max (2 * Nu) Nt,
intro n Hn,
rewrite Hcan,
apply rat.le_trans,
rotate 1,
apply add_le_add,
apply HNt,
apply pnat.le_trans,
rotate 1,
apply Hn,
rotate_right 1,
apply pnat.max_right,
apply HNu,
apply pnat.le_trans,
apply pnat.mul_le_mul_left 2,
apply pnat.le_trans,
rotate 1,
apply Hn,
rotate_right 1,
apply pnat.max_left,
rewrite [-pnat.add_halves Nu, neg_add_cancel_left],
apply inv_ge_of_le,
apply pnat.max_left
end
theorem le_of_le_reprs {s t : seq} (Hs : regular s) (Ht : regular t)
(Hle : ∀ n : ℕ+, s_le s (const (t n))) : s_le s t :=
by intro m; apply Hle (2 * m) m
theorem le_of_reprs_le {s t : seq} (Hs : regular s) (Ht : regular t)
(Hle : ∀ n : ℕ+, s_le (const (t n)) s) : s_le t s :=
by intro m; apply Hle (2 * m) m
-----------------------------
-- of_rat theorems
theorem const_le_const_of_le {a b : ℚ} (H : a ≤ b) : s_le (const a) (const b) :=
begin
rewrite [↑s_le, ↑nonneg],
intro n,
rewrite [↑sadd, ↑sneg, ↑const],
apply le.trans,
apply neg_nonpos_of_nonneg,
apply rat.le_of_lt,
apply pnat.inv_pos,
apply iff.mpr !sub_nonneg_iff_le,
apply H
end
theorem le_of_const_le_const {a b : ℚ} (H : s_le (const a) (const b)) : a ≤ b :=
begin
rewrite [↑s_le at H, ↑nonneg at H, ↑sadd at H, ↑sneg at H, ↑const at H],
apply iff.mp !sub_nonneg_iff_le,
apply nonneg_of_ge_neg_invs _ H
end
theorem nat_inv_lt_rat {a : ℚ} (H : a > 0) : ∃ n : ℕ+, n⁻¹ < a :=
begin
existsi (pceil (1 / (a / (2)))),
apply lt_of_le_of_lt,
rotate 1,
apply div_two_lt_of_pos H,
rewrite -(one_div_one_div (a / (1 + 1))),
apply pceil_helper,
apply pnat.le_refl,
apply one_div_pos_of_pos,
apply div_pos_of_pos_of_pos H dec_trivial
end
theorem const_lt_const_of_lt {a b : ℚ} (H : a < b) : s_lt (const a) (const b) :=
begin
rewrite [↑s_lt, ↑pos, ↑sadd, ↑sneg, ↑const],
apply nat_inv_lt_rat,
apply (iff.mpr !sub_pos_iff_lt H)
end
theorem lt_of_const_lt_const {a b : ℚ} (H : s_lt (const a) (const b)) : a < b :=
begin
rewrite [↑s_lt at H, ↑pos at H, ↑const at H, ↑sadd at H, ↑sneg at H],
cases H with [n, Hn],
apply (iff.mp !sub_pos_iff_lt),
apply lt.trans,
rotate 1,
exact Hn,
apply pnat.inv_pos
end
theorem s_le_of_le_pointwise {s t : seq} (Hs : regular s) (Ht : regular t)
(H : ∀ n : ℕ+, s n ≤ t n) : s_le s t :=
begin
rewrite [↑s_le, ↑nonneg, ↑sadd, ↑sneg],
intros,
apply le.trans,
apply iff.mpr !neg_nonpos_iff_nonneg,
apply le_of_lt,
apply pnat.inv_pos,
apply iff.mpr !sub_nonneg_iff_le,
apply H
end
-------- lift to reg_seqs
definition r_lt (s t : reg_seq) := s_lt (reg_seq.sq s) (reg_seq.sq t)
definition r_le (s t : reg_seq) := s_le (reg_seq.sq s) (reg_seq.sq t)
definition r_sep (s t : reg_seq) := sep (reg_seq.sq s) (reg_seq.sq t)
theorem r_le_well_defined (s t u v : reg_seq) (Hsu : requiv s u) (Htv : requiv t v)
: r_le s t = r_le u v :=
propext (le_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u)
(reg_seq.is_reg v) Hsu Htv)
theorem r_lt_well_defined (s t u v : reg_seq) (Hsu : requiv s u) (Htv : requiv t v)
: r_lt s t = r_lt u v :=
propext (lt_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u)
(reg_seq.is_reg v) Hsu Htv)
theorem r_sep_well_defined (s t u v : reg_seq) (Hsu : requiv s u) (Htv : requiv t v)
: r_sep s t = r_sep u v :=
propext (sep_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u)
(reg_seq.is_reg v) Hsu Htv)
theorem r_le.refl (s : reg_seq) : r_le s s := rat_seq.le_refl (reg_seq.is_reg s)
theorem r_le.trans {s t u : reg_seq} (Hst : r_le s t) (Htu : r_le t u) : r_le s u :=
rat_seq.le_trans (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Hst Htu
theorem r_equiv_of_le_of_ge {s t : reg_seq} (Hs : r_le s t) (Hu : r_le t s) :
requiv s t :=
equiv_of_le_of_ge (reg_seq.is_reg s) (reg_seq.is_reg t) Hs Hu
theorem r_lt_iff_le_and_sep (s t : reg_seq) : r_lt s t ↔ r_le s t ∧ r_sep s t :=
lt_iff_le_and_sep (reg_seq.is_reg s) (reg_seq.is_reg t)
theorem r_add_le_add_of_le_right {s t : reg_seq} (H : r_le s t) (u : reg_seq) :
r_le (u + s) (u + t) :=
rat_seq.add_le_add_of_le_right (reg_seq.is_reg s) (reg_seq.is_reg t) H
(reg_seq.sq u) (reg_seq.is_reg u)
theorem r_add_le_add_of_le_right_var (s t u : reg_seq) (H : r_le s t) :
r_le (u + s) (u + t) := r_add_le_add_of_le_right H u
theorem r_mul_pos_of_pos {s t : reg_seq} (Hs : r_lt r_zero s) (Ht : r_lt r_zero t) :
r_lt r_zero (s * t) :=
s_mul_gt_zero_of_gt_zero (reg_seq.is_reg s) (reg_seq.is_reg t) Hs Ht
theorem r_mul_nonneg_of_nonneg {s t : reg_seq} (Hs : r_le r_zero s) (Ht : r_le r_zero t) :
r_le r_zero (s * t) :=
s_mul_ge_zero_of_ge_zero (reg_seq.is_reg s) (reg_seq.is_reg t) Hs Ht
theorem r_not_lt_self (s : reg_seq) : ¬ r_lt s s :=
rat_seq.not_lt_self (reg_seq.sq s)
theorem r_not_sep_self (s : reg_seq) : ¬ r_sep s s :=
not_sep_self (reg_seq.sq s)
theorem r_le_of_lt {s t : reg_seq} (H : r_lt s t) : r_le s t :=
s_le_of_s_lt (reg_seq.is_reg s) (reg_seq.is_reg t) H
theorem r_lt_of_le_of_lt {s t u : reg_seq} (Hst : r_le s t) (Htu : r_lt t u) : r_lt s u :=
s_lt_of_le_of_lt (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Hst Htu
theorem r_lt_of_lt_of_le {s t u : reg_seq} (Hst : r_lt s t) (Htu : r_le t u) : r_lt s u :=
s_lt_of_lt_of_le (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Hst Htu
theorem r_add_lt_add_left (s t : reg_seq) (H : r_lt s t) (u : reg_seq) : r_lt (u + s) (u + t) :=
s_add_lt_add_left (reg_seq.is_reg s) (reg_seq.is_reg t) H (reg_seq.is_reg u)
theorem r_add_lt_add_left_var (s t u : reg_seq) (H : r_lt s t) : r_lt (u + s) (u + t) :=
r_add_lt_add_left s t H u
theorem r_zero_lt_one : r_lt r_zero r_one := s_zero_lt_one
theorem r_le_of_lt_or_eq (s t : reg_seq) (H : r_lt s t ∨ requiv s t) : r_le s t :=
le_of_lt_or_equiv (reg_seq.is_reg s) (reg_seq.is_reg t) H
theorem r_const_le_const_of_le {a b : ℚ} (H : a ≤ b) : r_le (r_const a) (r_const b) :=
const_le_const_of_le H
theorem r_le_of_const_le_const {a b : ℚ} (H : r_le (r_const a) (r_const b)) : a ≤ b :=
le_of_const_le_const H
theorem r_const_lt_const_of_lt {a b : ℚ} (H : a < b) : r_lt (r_const a) (r_const b) :=
const_lt_const_of_lt H
theorem r_lt_of_const_lt_const {a b : ℚ} (H : r_lt (r_const a) (r_const b)) : a < b :=
lt_of_const_lt_const H
theorem r_le_of_le_reprs (s t : reg_seq) (Hle : ∀ n : ℕ+, r_le s (r_const (reg_seq.sq t n))) : r_le s t :=
le_of_le_reprs (reg_seq.is_reg s) (reg_seq.is_reg t) Hle
theorem r_le_of_reprs_le (s t : reg_seq) (Hle : ∀ n : ℕ+, r_le (r_const (reg_seq.sq t n)) s) :
r_le t s :=
le_of_reprs_le (reg_seq.is_reg s) (reg_seq.is_reg t) Hle
end rat_seq
open real
open [class] rat_seq
namespace real
protected definition lt (x y : ℝ) :=
quot.lift_on₂ x y (λ a b, rat_seq.r_lt a b) rat_seq.r_lt_well_defined
protected definition le (x y : ℝ) :=
quot.lift_on₂ x y (λ a b, rat_seq.r_le a b) rat_seq.r_le_well_defined
definition real_has_lt [instance] [priority real.prio] : has_lt ℝ :=
has_lt.mk real.lt
definition real_has_le [instance] [priority real.prio] : has_le ℝ :=
has_le.mk real.le
definition sep (x y : ℝ) := quot.lift_on₂ x y (λ a b, rat_seq.r_sep a b) rat_seq.r_sep_well_defined
infix `≢` : 50 := sep
protected theorem le_refl (x : ℝ) : x ≤ x :=
quot.induction_on x (λ t, rat_seq.r_le.refl t)
protected theorem le_trans {x y z : ℝ} : x ≤ y → y ≤ z → x ≤ z :=
quot.induction_on₃ x y z (λ s t u, rat_seq.r_le.trans)
protected theorem eq_of_le_of_ge {x y : ℝ} : x ≤ y → y ≤ x → x = y :=
quot.induction_on₂ x y (λ s t Hst Hts, quot.sound (rat_seq.r_equiv_of_le_of_ge Hst Hts))
theorem lt_iff_le_and_sep (x y : ℝ) : x < y ↔ x ≤ y ∧ x ≢ y :=
quot.induction_on₂ x y (λ s t, rat_seq.r_lt_iff_le_and_sep s t)
protected theorem add_le_add_left' (x y z : ℝ) : x ≤ y → z + x ≤ z + y :=
quot.induction_on₃ x y z (λ s t u, rat_seq.r_add_le_add_of_le_right_var s t u)
protected theorem add_le_add_left (x y : ℝ) : x ≤ y → ∀ z : ℝ, z + x ≤ z + y :=
take H z, real.add_le_add_left' x y z H
protected theorem mul_pos (x y : ℝ) : 0 < x → 0 < y → 0 < x * y :=
quot.induction_on₂ x y (λ s t, rat_seq.r_mul_pos_of_pos)
protected theorem mul_nonneg (x y : ℝ) : 0 ≤ x → 0 ≤ y → 0 ≤ x * y :=
quot.induction_on₂ x y (λ s t, rat_seq.r_mul_nonneg_of_nonneg)
theorem not_sep_self (x : ℝ) : ¬ x ≢ x :=
quot.induction_on x (λ s, rat_seq.r_not_sep_self s)
protected theorem lt_irrefl (x : ℝ) : ¬ x < x :=
quot.induction_on x (λ s, rat_seq.r_not_lt_self s)
protected theorem le_of_lt {x y : ℝ} : x < y → x ≤ y :=
quot.induction_on₂ x y (λ s t H', rat_seq.r_le_of_lt H')
protected theorem lt_of_le_of_lt {x y z : ℝ} : x ≤ y → y < z → x < z :=
quot.induction_on₃ x y z (λ s t u H H', rat_seq.r_lt_of_le_of_lt H H')
protected theorem lt_of_lt_of_le {x y z : ℝ} : x < y → y ≤ z → x < z :=
quot.induction_on₃ x y z (λ s t u H H', rat_seq.r_lt_of_lt_of_le H H')
protected theorem add_lt_add_left' (x y z : ℝ) : x < y → z + x < z + y :=
quot.induction_on₃ x y z (λ s t u, rat_seq.r_add_lt_add_left_var s t u)
protected theorem add_lt_add_left (x y : ℝ) : x < y → ∀ z : ℝ, z + x < z + y :=
take H z, real.add_lt_add_left' x y z H
protected theorem zero_lt_one : (0 : ℝ) < (1 : ℝ) := rat_seq.r_zero_lt_one
protected theorem le_of_lt_or_eq (x y : ℝ) : x < y ∨ x = y → x ≤ y :=
(quot.induction_on₂ x y (λ s t H, or.elim H (take H', begin
apply rat_seq.r_le_of_lt_or_eq,
apply or.inl H'
end)
(take H', begin
apply rat_seq.r_le_of_lt_or_eq,
apply (or.inr (quot.exact H'))
end)))
definition ordered_ring [trans_instance] : ordered_ring ℝ :=
⦃ ordered_ring, real.comm_ring,
le_refl := real.le_refl,
le_trans := @real.le_trans,
mul_pos := real.mul_pos,
mul_nonneg := real.mul_nonneg,
zero_ne_one := real.zero_ne_one,
add_le_add_left := real.add_le_add_left,
le_antisymm := @real.eq_of_le_of_ge,
lt_irrefl := real.lt_irrefl,
lt_of_le_of_lt := @real.lt_of_le_of_lt,
lt_of_lt_of_le := @real.lt_of_lt_of_le,
le_of_lt := @real.le_of_lt,
add_lt_add_left := real.add_lt_add_left
⦄
open int
theorem of_rat_sub (a b : ℚ) : of_rat (a - b) = of_rat a - of_rat b := rfl
theorem of_int_sub (a b : ℤ) : of_int (a - b) = of_int a - of_int b :=
by rewrite [of_int_eq, rat.of_int_sub, of_rat_sub]
theorem of_rat_le_of_rat_of_le {a b : ℚ} : a ≤ b → of_rat a ≤ of_rat b :=
rat_seq.r_const_le_const_of_le
theorem le_of_of_rat_le_of_rat {a b : ℚ} : of_rat a ≤ of_rat b → a ≤ b :=
rat_seq.r_le_of_const_le_const
theorem of_rat_le_of_rat_iff (a b : ℚ) : of_rat a ≤ of_rat b ↔ a ≤ b :=
iff.intro le_of_of_rat_le_of_rat of_rat_le_of_rat_of_le
theorem of_rat_lt_of_rat_of_lt {a b : ℚ} : a < b → of_rat a < of_rat b :=
rat_seq.r_const_lt_const_of_lt
theorem lt_of_of_rat_lt_of_rat {a b : ℚ} : of_rat a < of_rat b → a < b :=
rat_seq.r_lt_of_const_lt_const
theorem of_rat_lt_of_rat_iff (a b : ℚ) : of_rat a < of_rat b ↔ a < b :=
iff.intro lt_of_of_rat_lt_of_rat of_rat_lt_of_rat_of_lt
theorem of_int_le_of_int_iff (a b : ℤ) : of_int a ≤ of_int b ↔ (a ≤ b) :=
begin rewrite [+of_int_eq, of_rat_le_of_rat_iff], apply rat.of_int_le_of_int_iff end
theorem of_int_le_of_int_of_le {a b : ℤ} : (a ≤ b) → of_int a ≤ of_int b :=
iff.mpr !of_int_le_of_int_iff
theorem le_of_of_int_le_of_int {a b : ℤ} : of_int a ≤ of_int b → (a ≤ b) :=
iff.mp !of_int_le_of_int_iff
theorem of_int_lt_of_int_iff (a b : ℤ) : of_int a < of_int b ↔ (a < b) :=
by rewrite [*of_int_eq, of_rat_lt_of_rat_iff]; apply rat.of_int_lt_of_int_iff
theorem of_int_lt_of_int_of_lt {a b : ℤ} : (a < b) → of_int a < of_int b :=
iff.mpr !of_int_lt_of_int_iff
theorem lt_of_of_int_lt_of_int {a b : ℤ} : of_int a < of_int b → (a < b) :=
iff.mp !of_int_lt_of_int_iff
theorem of_nat_le_of_nat_iff (a b : ℕ) : of_nat a ≤ of_nat b ↔ (a ≤ b) :=
by rewrite [*of_nat_eq, of_rat_le_of_rat_iff]; apply rat.of_nat_le_of_nat_iff
theorem of_nat_le_of_nat_of_le {a b : ℕ} : (a ≤ b) → of_nat a ≤ of_nat b :=
iff.mpr !of_nat_le_of_nat_iff
theorem le_of_of_nat_le_of_nat {a b : ℕ} : of_nat a ≤ of_nat b → (a ≤ b) :=
iff.mp !of_nat_le_of_nat_iff
theorem of_nat_lt_of_nat_iff (a b : ℕ) : of_nat a < of_nat b ↔ (a < b) :=
by rewrite [*of_nat_eq, of_rat_lt_of_rat_iff]; apply rat.of_nat_lt_of_nat_iff
theorem of_nat_lt_of_nat_of_lt {a b : ℕ} : (a < b) → of_nat a < of_nat b :=
iff.mpr !of_nat_lt_of_nat_iff
theorem lt_of_of_nat_lt_of_nat {a b : ℕ} : of_nat a < of_nat b → (a < b) :=
iff.mp !of_nat_lt_of_nat_iff
theorem of_rat_pos_of_pos {q : ℚ} (Hq : q > 0) : of_rat q > 0 :=
of_rat_lt_of_rat_of_lt Hq
theorem of_rat_nonneg_of_nonneg {q : ℚ} (Hq : q ≥ 0) : of_rat q ≥ 0 :=
of_rat_le_of_rat_of_le Hq
theorem of_rat_neg_of_neg {q : ℚ} (Hq : q < 0) : of_rat q < 0 :=
of_rat_lt_of_rat_of_lt Hq
theorem of_rat_nonpos_of_nonpos {q : ℚ} (Hq : q ≤ 0) : of_rat q ≤ 0 :=
of_rat_le_of_rat_of_le Hq
theorem of_nat_nonneg (a : ℕ) : of_nat a ≥ 0 :=
of_rat_le_of_rat_of_le !rat.of_nat_nonneg
theorem of_nat_succ_pos (k : ℕ) : 0 < of_nat k + 1 :=
add_pos_of_nonneg_of_pos (of_nat_nonneg k) real.zero_lt_one
theorem of_rat_pow (a : ℚ) (n : ℕ) : of_rat (a^n) = (of_rat a)^n :=
begin
induction n with n ih,
apply eq.refl,
rewrite [2 pow_succ, of_rat_mul, ih]
end
theorem of_int_pow (a : ℤ) (n : ℕ) : of_int (#int a^n) = (of_int a)^n :=
by rewrite [of_int_eq, rat.of_int_pow, of_rat_pow]
theorem of_nat_pow (a : ℕ) (n : ℕ) : of_nat (#nat a^n) = (of_nat a)^n :=
by rewrite [of_nat_eq, rat.of_nat_pow, of_rat_pow]
open rat_seq
theorem le_of_le_reprs (x : ℝ) (t : seq) (Ht : regular t) : (∀ n : ℕ+, x ≤ t n) →
x ≤ quot.mk (reg_seq.mk t Ht) :=
quot.induction_on x (take s Hs,
show r_le s (reg_seq.mk t Ht), from
have H' : ∀ n : ℕ+, r_le s (r_const (t n)), from Hs,
by apply r_le_of_le_reprs; apply Hs)
theorem le_of_reprs_le (x : ℝ) (t : seq) (Ht : regular t) : (∀ n : ℕ+, t n ≤ x) →
x ≥ ((quot.mk (reg_seq.mk t Ht)) : ℝ) :=
quot.induction_on x (take s Hs,
show r_le (reg_seq.mk t Ht) s, from
have H' : ∀ n : ℕ+, r_le (r_const (t n)) s, from Hs,
by apply r_le_of_reprs_le; apply Hs)
end real
|
0510317af6efa4736ad45e4970e6335c56e69dc0 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/filtered.lean | 6ec01b38894136014f1780b8ac9a4aa502807a56 | [] | 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 | 9,082 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.fin_category
import Mathlib.category_theory.limits.cones
import Mathlib.category_theory.adjunction.basic
import Mathlib.order.bounded_lattice
import Mathlib.PostPort
universes v u l v₁ u₁
namespace Mathlib
/-!
# Filtered categories
A category is filtered if every finite diagram admits a cocone.
We give a simple characterisation of this condition as
1. for every pair of objects there exists another object "to the right",
2. for every pair of parallel morphisms there exists a morphism to the right so the compositions
are equal, and
3. there exists some object.
Filtered colimits are often better behaved than arbitrary colimits.
See `category_theory/limits/types` for some details.
Filtered categories are nice because colimits indexed by filtered categories tend to be
easier to describe than general colimits (and often often preserved by functors).
In this file we show that any functor from a finite category to a filtered category admits a cocone:
* `cocone_nonempty [fin_category J] [is_filtered C] (F : J ⥤ C) : nonempty (cocone F)`
More generally,
for any finite collection of objects and morphisms between them in a filtered category
(even if not closed under composition) there exists some object `Z` receiving maps from all of them,
so that all the triangles (one edge from the finite set, two from morphisms to `Z`) commute.
This formulation is often more useful in practice. We give two variants,
`sup_exists'`, which takes a single finset of objects, and a finset of morphisms
(bundled with their sources and targets), and
`sup_exists`, which takes a finset of objects, and an indexed family (indexed by source and target)
of finsets of morphisms.
## Future work
* Finite limits commute with filtered colimits
* Forgetful functors for algebraic categories typically preserve filtered colimits.
-/
namespace category_theory
/--
A category `is_filtered_or_empty` if
1. for every pair of objects there exists another object "to the right", and
2. for every pair of parallel morphisms there exists a morphism to the right so the compositions
are equal.
-/
class is_filtered_or_empty (C : Type u) [category C]
where
cocone_objs : ∀ (X Y : C), ∃ (Z : C), ∃ (f : X ⟶ Z), ∃ (g : Y ⟶ Z), True
cocone_maps : ∀ {X Y : C} (f g : X ⟶ Y), ∃ (Z : C), ∃ (h : Y ⟶ Z), f ≫ h = g ≫ h
/--
A category `is_filtered` if
1. for every pair of objects there exists another object "to the right",
2. for every pair of parallel morphisms there exists a morphism to the right so the compositions
are equal, and
3. there exists some object.
See https://stacks.math.columbia.edu/tag/002V. (They also define a diagram being filtered.)
-/
class is_filtered (C : Type u) [category C]
extends is_filtered_or_empty C
where
nonempty : Nonempty C
protected instance is_filtered_or_empty_of_semilattice_sup (α : Type u) [semilattice_sup α] : is_filtered_or_empty α :=
is_filtered_or_empty.mk
(fun (X Y : α) =>
Exists.intro (X ⊔ Y) (Exists.intro (hom_of_le le_sup_left) (Exists.intro (hom_of_le le_sup_right) trivial)))
fun (X Y : α) (f g : X ⟶ Y) =>
Exists.intro Y (Exists.intro 𝟙 (ulift.ext (f ≫ 𝟙) (g ≫ 𝟙) (plift.ext (ulift.down (f ≫ 𝟙)) (ulift.down (g ≫ 𝟙)))))
protected instance is_filtered_of_semilattice_sup_top (α : Type u) [semilattice_sup_top α] : is_filtered α :=
is_filtered.mk
namespace is_filtered
/--
`max j j'` is an arbitrary choice of object to the right of both `j` and `j'`,
whose existence is ensured by `is_filtered`.
-/
def max {C : Type u} [category C] [is_filtered C] (j : C) (j' : C) : C :=
Exists.some sorry
/--
`left_to_max j j'` is an arbitrarily choice of morphism from `j` to `max j j'`,
whose existence is ensured by `is_filtered`.
-/
def left_to_max {C : Type u} [category C] [is_filtered C] (j : C) (j' : C) : j ⟶ max j j' :=
Exists.some sorry
/--
`right_to_max j j'` is an arbitrarily choice of morphism from `j'` to `max j j'`,
whose existence is ensured by `is_filtered`.
-/
def right_to_max {C : Type u} [category C] [is_filtered C] (j : C) (j' : C) : j' ⟶ max j j' :=
Exists.some sorry
/--
`coeq f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of object
which admits a morphism `coeq_hom f f' : j' ⟶ coeq f f'` such that
`coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`.
Its existence is ensured by `is_filtered`.
-/
def coeq {C : Type u} [category C] [is_filtered C] {j : C} {j' : C} (f : j ⟶ j') (f' : j ⟶ j') : C :=
Exists.some sorry
/--
`coeq_hom f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of morphism
`coeq_hom f f' : j' ⟶ coeq f f'` such that
`coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`.
Its existence is ensured by `is_filtered`.
-/
def coeq_hom {C : Type u} [category C] [is_filtered C] {j : C} {j' : C} (f : j ⟶ j') (f' : j ⟶ j') : j' ⟶ coeq f f' :=
Exists.some sorry
/--
`coeq_condition f f'`, for morphisms `f f' : j ⟶ j'`, is the proof that
`f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`.
-/
@[simp] theorem coeq_condition_assoc {C : Type u} [category C] [is_filtered C] {j : C} {j' : C} (f : j ⟶ j') (f' : j ⟶ j') {X' : C} : ∀ (f'_1 : coeq f f' ⟶ X'), f ≫ coeq_hom f f' ≫ f'_1 = f' ≫ coeq_hom f f' ≫ f'_1 := sorry
/--
Any finite collection of objects in a filtered category has an object "to the right".
-/
theorem sup_objs_exists {C : Type u} [category C] [is_filtered C] (O : finset C) : ∃ (S : C), ∀ {X : C}, X ∈ O → Nonempty (X ⟶ S) := sorry
/--
Given any `finset` of objects `{X, ...}` and
indexed collection of `finset`s of morphisms `{f, ...}` in `C`,
there exists an object `S`, with a morphism `T X : X ⟶ S` from each `X`,
such that the triangles commute: `f ≫ T X = T Y`, for `f : X ⟶ Y` in the `finset`.
-/
theorem sup_exists {C : Type u} [category C] [is_filtered C] (O : finset C) (H : finset (psigma fun (X : C) => psigma fun (Y : C) => psigma fun (mX : X ∈ O) => psigma fun (mY : Y ∈ O) => X ⟶ Y)) : ∃ (S : C),
∃ (T : {X : C} → X ∈ O → (X ⟶ S)),
∀ {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y},
psigma.mk X (psigma.mk Y (psigma.mk mX (psigma.mk mY f))) ∈ H → f ≫ T mY = T mX := sorry
/--
An arbitrary choice of object "to the right" of a finite collection of objects `O` and morphisms `H`,
making all the triangles commute.
-/
def sup {C : Type u} [category C] [is_filtered C] (O : finset C) (H : finset (psigma fun (X : C) => psigma fun (Y : C) => psigma fun (mX : X ∈ O) => psigma fun (mY : Y ∈ O) => X ⟶ Y)) : C :=
Exists.some (sup_exists O H)
/--
The morphisms to `sup O H`.
-/
def to_sup {C : Type u} [category C] [is_filtered C] (O : finset C) (H : finset (psigma fun (X : C) => psigma fun (Y : C) => psigma fun (mX : X ∈ O) => psigma fun (mY : Y ∈ O) => X ⟶ Y)) {X : C} (m : X ∈ O) : X ⟶ sup O H :=
Exists.some sorry X m
/--
The triangles of consisting of a morphism in `H` and the maps to `sup O H` commute.
-/
theorem to_sup_commutes {C : Type u} [category C] [is_filtered C] (O : finset C) (H : finset (psigma fun (X : C) => psigma fun (Y : C) => psigma fun (mX : X ∈ O) => psigma fun (mY : Y ∈ O) => X ⟶ Y)) {X : C} {Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y} (mf : psigma.mk X (psigma.mk Y (psigma.mk mX (psigma.mk mY f))) ∈ H) : f ≫ to_sup O H mY = to_sup O H mX :=
Exists.some_spec (Exists.some_spec (sup_exists O H)) X Y mX mY f mf
/--
If we have `is_filtered C`, then for any functor `F : J ⥤ C` with `fin_category J`,
there exists a cocone over `F`.
-/
theorem cocone_nonempty {C : Type u} [category C] [is_filtered C] {J : Type v} [small_category J] [fin_category J] (F : J ⥤ C) : Nonempty (limits.cocone F) := sorry
/--
An arbitrary choice of cocone over `F : J ⥤ C`, for `fin_category J` and `is_filtered C`.
-/
def cocone {C : Type u} [category C] [is_filtered C] {J : Type v} [small_category J] [fin_category J] (F : J ⥤ C) : limits.cocone F :=
nonempty.some (cocone_nonempty F)
/--
If `C` is filtered, and we have a functor `R : C ⥤ D` with a left adjoint, then `D` is filtered.
-/
theorem of_right_adjoint {C : Type u} [category C] [is_filtered C] {D : Type u₁} [category D] {L : D ⥤ C} {R : C ⥤ D} (h : L ⊣ R) : is_filtered D :=
mk
/-- If `C` is filtered, and we have a right adjoint functor `R : C ⥤ D`, then `D` is filtered. -/
theorem of_is_right_adjoint {C : Type u} [category C] [is_filtered C] {D : Type u₁} [category D] (R : C ⥤ D) [is_right_adjoint R] : is_filtered D :=
of_right_adjoint (adjunction.of_right_adjoint R)
/-- Being filtered is preserved by equivalence of categories. -/
theorem of_equivalence {C : Type u} [category C] [is_filtered C] {D : Type u₁} [category D] (h : C ≌ D) : is_filtered D :=
of_right_adjoint (equivalence.to_adjunction (equivalence.symm h))
|
6f9625d85f47dd0b426cb4aa771ceeb7f574a7f6 | 7a76361040c55ae1eba5856c1a637593117a6556 | /src/homework/love03_forward_proofs_homework_sheet.lean | 92b68b34fcb6f438c3293bcd26279bdc81eea9b8 | [] | no_license | rgreenblatt/fpv2021 | c2cbe7b664b648cef7d240a654d6bdf97a559272 | c65d72e48c8fa827d2040ed6ea86c2be62db36fa | refs/heads/main | 1,692,245,693,819 | 1,633,364,621,000 | 1,633,364,621,000 | 407,231,487 | 0 | 0 | null | 1,631,808,608,000 | 1,631,808,608,000 | null | UTF-8 | Lean | false | false | 2,168 | lean | import ..exercises.love02_backward_proofs_exercise_sheet
/-! # LoVe Homework 3: Forward Proofs
Homework must be done individually. -/
set_option pp.beta true
set_option pp.generalized_field_notation false
namespace LoVe
/-! ## Question 1 (3 points): Logic Puzzles
Consider the following tactical proof: -/
lemma about_implication :
∀a b : Prop, ¬ a ∨ b → a → b :=
begin
intros a b hor ha,
apply or.elim hor,
{ intro hna,
apply false.elim,
apply hna,
exact ha },
{ intro hb,
exact hb }
end
/-! 1.1 (1 point). Prove the same lemma again, this time by providing a proof
term.
Hint: There is an easy way. -/
lemma about_implication₂ :
∀a b : Prop, ¬ a ∨ b → a → b :=
sorry
/-! 1.2 (2 points). Prove the same lemma again, this time by providing a
structured proof, with `assume`s and `show`s. -/
lemma about_implication₃ :
∀a b : Prop, ¬ a ∨ b → a → b :=
sorry
/-! ## Question 2 (6 points + 1 bonus point): Connectives and Quantifiers
2.1 (4 points). Supply a structured proof of the commutativity of `∨` under a
`∀` quantifier, using no other lemmas than the introduction and elimination
rules for `∀`, `∨`, and `↔`. -/
lemma all_or_commute {α : Type} (p q : α → Prop) :
(∀x, p x ∨ q x) ↔ (∀x, q x ∨ p x) :=
sorry
/-! 2.2 (2 points). We have proved or stated three of the six possible
implications between `excluded_middle`, `peirce`, and `double_negation`. Prove
the three missing implications using structured proofs, exploiting the three
theorems we already have. -/
namespace backward_proofs
#check peirce_of_em
#check dn_of_peirce
#check sorry_lemmas.em_of_dn
lemma peirce_of_dn :
double_negation → peirce :=
sorry
lemma em_of_peirce :
peirce → excluded_middle :=
sorry
lemma dn_of_em :
excluded_middle → double_negation :=
sorry
end backward_proofs
/-! 2.3 (1 bonus point). Supply a structured proof of the following property,
which can be used pull a `∀`-quantifier past an `∃`-quantifier. -/
lemma forall_exists_of_exists_forall {α : Type} (p : α → α → Prop) :
(∃x, ∀y, p x y) → (∀y, ∃x, p x y) :=
sorry
end LoVe
|
2aeb7d11219716243634aea7b45b289ddb93eee8 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/star/self_adjoint.lean | d33bddca15b18dea7e7b10cb0dbdc6e6bdeb8fe2 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 14,397 | lean | /-
Copyright (c) 2021 Frédéric Dupuis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Frédéric Dupuis
-/
import algebra.star.basic
import group_theory.subgroup.basic
/-!
# Self-adjoint, skew-adjoint and normal elements of a star additive group
This file defines `self_adjoint R` (resp. `skew_adjoint R`), where `R` is a star additive group,
as the additive subgroup containing the elements that satisfy `star x = x` (resp. `star x = -x`).
This includes, for instance, (skew-)Hermitian operators on Hilbert spaces.
We also define `is_star_normal R`, a `Prop` that states that an element `x` satisfies
`star x * x = x * star x`.
## Implementation notes
* When `R` is a `star_module R₂ R`, then `self_adjoint R` has a natural
`module (self_adjoint R₂) (self_adjoint R)` structure. However, doing this literally would be
undesirable since in the main case of interest (`R₂ = ℂ`) we want `module ℝ (self_adjoint R)`
and not `module (self_adjoint ℂ) (self_adjoint R)`. We solve this issue by adding the typeclass
`[has_trivial_star R₃]`, of which `ℝ` is an instance (registered in `data/real/basic`), and then
add a `[module R₃ (self_adjoint R)]` instance whenever we have
`[module R₃ R] [has_trivial_star R₃]`. (Another approach would have been to define
`[star_invariant_scalars R₃ R]` to express the fact that `star (x • v) = x • star v`, but
this typeclass would have the disadvantage of taking two type arguments.)
## TODO
* Define `λ z x, z * x * star z` (i.e. conjugation by `z`) as a monoid action of `R` on `R`
(similar to the existing `conj_act` for groups), and then state the fact that `self_adjoint R` is
invariant under it.
-/
variables {R A : Type*}
/-- An element is self-adjoint if it is equal to its star. -/
def is_self_adjoint [has_star R] (x : R) : Prop := star x = x
/-- An element of a star monoid is normal if it commutes with its adjoint. -/
class is_star_normal [has_mul R] [has_star R] (x : R) : Prop :=
(star_comm_self : commute (star x) x)
export is_star_normal (star_comm_self)
lemma star_comm_self' [has_mul R] [has_star R] (x : R) [is_star_normal x] :
(star x) * x = x * star x :=
is_star_normal.star_comm_self
namespace is_self_adjoint
lemma star_eq [has_star R] {x : R} (hx : is_self_adjoint x) : star x = x := hx
lemma _root_.is_self_adjoint_iff [has_star R] {x : R} : is_self_adjoint x ↔ star x = x := iff.rfl
@[simp]
lemma star_mul_self [semigroup R] [star_semigroup R] (x : R) : is_self_adjoint (star x * x) :=
by simp only [is_self_adjoint, star_mul, star_star]
@[simp]
lemma mul_star_self [semigroup R] [star_semigroup R] (x : R) : is_self_adjoint (x * star x) :=
by simpa only [star_star] using star_mul_self (star x)
/-- Functions in a `star_hom_class` preserve self-adjoint elements. -/
lemma star_hom_apply {F R S : Type*} [has_star R] [has_star S] [star_hom_class F R S]
{x : R} (hx : is_self_adjoint x) (f : F) : is_self_adjoint (f x) :=
show star (f x) = f x, from map_star f x ▸ congr_arg f hx
section add_group
variables [add_group R] [star_add_monoid R]
variables (R)
lemma _root_.is_self_adjoint_zero : is_self_adjoint (0 : R) := star_zero R
variables {R}
lemma add {x y : R} (hx : is_self_adjoint x) (hy : is_self_adjoint y) : is_self_adjoint (x + y) :=
by simp only [is_self_adjoint_iff, star_add, hx.star_eq, hy.star_eq]
lemma neg {x : R} (hx : is_self_adjoint x) : is_self_adjoint (-x) :=
by simp only [is_self_adjoint_iff, star_neg, hx.star_eq]
lemma sub {x y : R} (hx : is_self_adjoint x) (hy : is_self_adjoint y) : is_self_adjoint (x - y) :=
by simp only [is_self_adjoint_iff, star_sub, hx.star_eq, hy.star_eq]
lemma bit0 {x : R} (hx : is_self_adjoint x) : is_self_adjoint (bit0 x) :=
by simp only [is_self_adjoint_iff, star_bit0, hx.star_eq]
end add_group
section non_unital_semiring
variables [non_unital_semiring R] [star_ring R]
lemma conjugate {x : R} (hx : is_self_adjoint x) (z : R) : is_self_adjoint (z * x * star z) :=
by simp only [is_self_adjoint_iff, star_mul, star_star, mul_assoc, hx.star_eq]
lemma conjugate' {x : R} (hx : is_self_adjoint x) (z : R) : is_self_adjoint (star z * x * z) :=
by simp only [is_self_adjoint_iff, star_mul, star_star, mul_assoc, hx.star_eq]
lemma is_star_normal {x : R} (hx : is_self_adjoint x) : is_star_normal x :=
⟨by simp only [hx.star_eq]⟩
end non_unital_semiring
section ring
variables [ring R] [star_ring R]
variables (R)
lemma _root_.is_self_adjoint_one : is_self_adjoint (1 : R) := star_one R
variables {R}
lemma bit1 {x : R} (hx : is_self_adjoint x) : is_self_adjoint (bit1 x) :=
by simp only [is_self_adjoint_iff, star_bit1, hx.star_eq]
lemma pow {x : R} (hx : is_self_adjoint x) (n : ℕ) : is_self_adjoint (x ^ n):=
by simp only [is_self_adjoint_iff, star_pow, hx.star_eq]
end ring
section non_unital_comm_ring
variables [non_unital_comm_ring R] [star_ring R]
lemma mul {x y : R} (hx : is_self_adjoint x) (hy : is_self_adjoint y) : is_self_adjoint (x * y) :=
by simp only [is_self_adjoint_iff, star_mul', hx.star_eq, hy.star_eq]
end non_unital_comm_ring
section field
variables [field R] [star_ring R]
lemma inv {x : R} (hx : is_self_adjoint x) : is_self_adjoint x⁻¹ :=
by simp only [is_self_adjoint_iff, star_inv', hx.star_eq]
lemma div {x y : R} (hx : is_self_adjoint x) (hy : is_self_adjoint y) : is_self_adjoint (x / y) :=
by simp only [is_self_adjoint_iff, star_div', hx.star_eq, hy.star_eq]
lemma zpow {x : R} (hx : is_self_adjoint x) (n : ℤ) : is_self_adjoint (x ^ n):=
by simp only [is_self_adjoint_iff, star_zpow₀, hx.star_eq]
end field
section has_smul
variables [has_star R] [has_trivial_star R] [add_group A] [star_add_monoid A]
lemma smul [has_smul R A] [star_module R A] (r : R) {x : A} (hx : is_self_adjoint x) :
is_self_adjoint (r • x) :=
by simp only [is_self_adjoint_iff, star_smul, star_trivial, hx.star_eq]
end has_smul
end is_self_adjoint
variables (R)
/-- The self-adjoint elements of a star additive group, as an additive subgroup. -/
def self_adjoint [add_group R] [star_add_monoid R] : add_subgroup R :=
{ carrier := {x | is_self_adjoint x},
zero_mem' := star_zero R,
add_mem' := λ _ _ hx, hx.add,
neg_mem' := λ _ hx, hx.neg }
/-- The skew-adjoint elements of a star additive group, as an additive subgroup. -/
def skew_adjoint [add_comm_group R] [star_add_monoid R] : add_subgroup R :=
{ carrier := {x | star x = -x},
zero_mem' := show star (0 : R) = -0, by simp only [star_zero, neg_zero],
add_mem' := λ x y (hx : star x = -x) (hy : star y = -y),
show star (x + y) = -(x + y), by rw [star_add x y, hx, hy, neg_add],
neg_mem' := λ x (hx : star x = -x), show star (-x) = (- -x), by simp only [hx, star_neg] }
variables {R}
namespace self_adjoint
section add_group
variables [add_group R] [star_add_monoid R]
lemma mem_iff {x : R} : x ∈ self_adjoint R ↔ star x = x :=
by { rw [←add_subgroup.mem_carrier], exact iff.rfl }
@[simp, norm_cast] lemma star_coe_eq {x : self_adjoint R} : star (x : R) = x := x.prop
instance : inhabited (self_adjoint R) := ⟨0⟩
end add_group
section ring
variables [ring R] [star_ring R]
instance : has_one (self_adjoint R) := ⟨⟨1, is_self_adjoint_one R⟩⟩
@[simp, norm_cast] lemma coe_one : ↑(1 : self_adjoint R) = (1 : R) := rfl
instance [nontrivial R] : nontrivial (self_adjoint R) := ⟨⟨0, 1, subtype.ne_of_val_ne zero_ne_one⟩⟩
instance : has_nat_cast (self_adjoint R) :=
⟨λ n, ⟨n, nat.rec_on n (by simp [zero_mem])
(λ k hk, (@nat.cast_succ R _ k).symm ▸ add_mem hk (is_self_adjoint_one R))⟩⟩
instance : has_int_cast (self_adjoint R) :=
⟨λ n, ⟨n,
begin
cases n;
simp [show ↑n ∈ self_adjoint R, from (n : self_adjoint R).2],
refine add_mem (is_self_adjoint_one R).neg (n : self_adjoint R).2.neg,
end ⟩ ⟩
instance : has_pow (self_adjoint R) ℕ :=
⟨λ x n, ⟨(x : R) ^ n, x.prop.pow n⟩⟩
@[simp, norm_cast] lemma coe_pow (x : self_adjoint R) (n : ℕ) : ↑(x ^ n) = (x : R) ^ n := rfl
end ring
section non_unital_comm_ring
variables [non_unital_comm_ring R] [star_ring R]
instance : has_mul (self_adjoint R) :=
⟨λ x y, ⟨(x : R) * y, x.prop.mul y.prop⟩⟩
@[simp, norm_cast] lemma coe_mul (x y : self_adjoint R) : ↑(x * y) = (x : R) * y := rfl
end non_unital_comm_ring
section comm_ring
variables [comm_ring R] [star_ring R]
instance : comm_ring (self_adjoint R) :=
function.injective.comm_ring _ subtype.coe_injective
(self_adjoint R).coe_zero coe_one (self_adjoint R).coe_add coe_mul (self_adjoint R).coe_neg
(self_adjoint R).coe_sub (self_adjoint R).coe_nsmul (self_adjoint R).coe_zsmul coe_pow
(λ _, rfl) (λ _, rfl)
end comm_ring
section field
variables [field R] [star_ring R]
instance : has_inv (self_adjoint R) :=
{ inv := λ x, ⟨(x.val)⁻¹, x.prop.inv⟩ }
@[simp, norm_cast] lemma coe_inv (x : self_adjoint R) : ↑(x⁻¹) = (x : R)⁻¹ := rfl
instance : has_div (self_adjoint R) :=
{ div := λ x y, ⟨x / y, x.prop.div y.prop⟩ }
@[simp, norm_cast] lemma coe_div (x y : self_adjoint R) : ↑(x / y) = (x / y : R) := rfl
instance : has_pow (self_adjoint R) ℤ :=
{ pow := λ x z, ⟨x ^ z, x.prop.zpow z⟩ }
@[simp, norm_cast] lemma coe_zpow (x : self_adjoint R) (z : ℤ) : ↑(x ^ z) = (x : R) ^ z := rfl
lemma rat_cast_mem : ∀ (x : ℚ), is_self_adjoint (x : R)
| ⟨a, b, h1, h2⟩ :=
by rw [is_self_adjoint, rat.cast_mk', star_mul', star_inv', star_nat_cast, star_int_cast]
instance : has_rat_cast (self_adjoint R) :=
⟨λ n, ⟨n, rat_cast_mem n⟩⟩
@[simp, norm_cast] lemma coe_rat_cast (x : ℚ) : ↑(x : self_adjoint R) = (x : R) :=
rfl
instance has_qsmul : has_smul ℚ (self_adjoint R) :=
⟨λ a x, ⟨a • x, by rw rat.smul_def; exact (rat_cast_mem a).mul x.prop⟩⟩
@[simp, norm_cast] lemma coe_rat_smul (x : self_adjoint R) (a : ℚ) : ↑(a • x) = a • (x : R) :=
rfl
instance : field (self_adjoint R) :=
function.injective.field _ subtype.coe_injective
(self_adjoint R).coe_zero coe_one (self_adjoint R).coe_add coe_mul (self_adjoint R).coe_neg
(self_adjoint R).coe_sub coe_inv coe_div (self_adjoint R).coe_nsmul (self_adjoint R).coe_zsmul
coe_rat_smul coe_pow coe_zpow (λ _, rfl) (λ _, rfl) coe_rat_cast
end field
section has_smul
variables [has_star R] [has_trivial_star R] [add_group A] [star_add_monoid A]
instance [has_smul R A] [star_module R A] : has_smul R (self_adjoint A) :=
⟨λ r x, ⟨r • x, x.prop.smul r⟩⟩
@[simp, norm_cast] lemma coe_smul [has_smul R A] [star_module R A] (r : R) (x : self_adjoint A) :
↑(r • x) = r • (x : A) := rfl
instance [monoid R] [mul_action R A] [star_module R A] : mul_action R (self_adjoint A) :=
function.injective.mul_action coe subtype.coe_injective coe_smul
instance [monoid R] [distrib_mul_action R A] [star_module R A] :
distrib_mul_action R (self_adjoint A) :=
function.injective.distrib_mul_action (self_adjoint A).subtype subtype.coe_injective coe_smul
end has_smul
section module
variables [has_star R] [has_trivial_star R] [add_comm_group A] [star_add_monoid A]
instance [semiring R] [module R A] [star_module R A] : module R (self_adjoint A) :=
function.injective.module R (self_adjoint A).subtype subtype.coe_injective coe_smul
end module
end self_adjoint
namespace skew_adjoint
section add_group
variables [add_comm_group R] [star_add_monoid R]
lemma mem_iff {x : R} : x ∈ skew_adjoint R ↔ star x = -x :=
by { rw [←add_subgroup.mem_carrier], exact iff.rfl }
@[simp, norm_cast] lemma star_coe_eq {x : skew_adjoint R} : star (x : R) = -x := x.prop
instance : inhabited (skew_adjoint R) := ⟨0⟩
lemma bit0_mem {x : R} (hx : x ∈ skew_adjoint R) : bit0 x ∈ skew_adjoint R :=
by rw [mem_iff, star_bit0, mem_iff.mp hx, bit0, bit0, neg_add]
end add_group
section ring
variables [ring R] [star_ring R]
lemma conjugate {x : R} (hx : x ∈ skew_adjoint R) (z : R) : z * x * star z ∈ skew_adjoint R :=
by simp only [mem_iff, star_mul, star_star, mem_iff.mp hx, neg_mul, mul_neg, mul_assoc]
lemma conjugate' {x : R} (hx : x ∈ skew_adjoint R) (z : R) : star z * x * z ∈ skew_adjoint R :=
by simp only [mem_iff, star_mul, star_star, mem_iff.mp hx, neg_mul, mul_neg, mul_assoc]
lemma is_star_normal_of_mem {x : R} (hx : x ∈ skew_adjoint R) : is_star_normal x :=
⟨by { simp only [mem_iff] at hx, simp only [hx, commute.neg_left] }⟩
instance (x : skew_adjoint R) : is_star_normal (x : R) :=
is_star_normal_of_mem (set_like.coe_mem _)
end ring
section has_smul
variables [has_star R] [has_trivial_star R] [add_comm_group A] [star_add_monoid A]
lemma smul_mem [monoid R] [distrib_mul_action R A] [star_module R A] (r : R) {x : A}
(h : x ∈ skew_adjoint A) : r • x ∈ skew_adjoint A :=
by rw [mem_iff, star_smul, star_trivial, mem_iff.mp h, smul_neg r]
instance [monoid R] [distrib_mul_action R A] [star_module R A] : has_smul R (skew_adjoint A) :=
⟨λ r x, ⟨r • x, smul_mem r x.prop⟩⟩
@[simp, norm_cast] lemma coe_smul [monoid R] [distrib_mul_action R A] [star_module R A]
(r : R) (x : skew_adjoint A) : ↑(r • x) = r • (x : A) := rfl
instance [monoid R] [distrib_mul_action R A] [star_module R A] :
distrib_mul_action R (skew_adjoint A) :=
function.injective.distrib_mul_action (skew_adjoint A).subtype subtype.coe_injective coe_smul
instance [semiring R] [module R A] [star_module R A] : module R (skew_adjoint A) :=
function.injective.module R (skew_adjoint A).subtype subtype.coe_injective coe_smul
end has_smul
end skew_adjoint
instance is_star_normal_zero [semiring R] [star_ring R] : is_star_normal (0 : R) :=
⟨by simp only [star_comm_self, star_zero]⟩
instance is_star_normal_one [monoid R] [star_semigroup R] : is_star_normal (1 : R) :=
⟨by simp only [star_comm_self, star_one]⟩
instance is_star_normal_star_self [monoid R] [star_semigroup R] {x : R} [is_star_normal x] :
is_star_normal (star x) :=
⟨show star (star x) * (star x) = (star x) * star (star x), by rw [star_star, star_comm_self']⟩
@[priority 100] -- see Note [lower instance priority]
instance has_trivial_star.is_star_normal [monoid R] [star_semigroup R]
[has_trivial_star R] {x : R} : is_star_normal x :=
⟨by rw [star_trivial]⟩
@[priority 100] -- see Note [lower instance priority]
instance comm_monoid.is_star_normal [comm_monoid R] [star_semigroup R] {x : R} :
is_star_normal x :=
⟨mul_comm _ _⟩
|
be8664a32004602d3b5a63def4db7b7e51583ad2 | e39f04f6ff425fe3b3f5e26a8998b817d1dba80f | /data/multiset.lean | 9923cc46a5afad5e2961135b7c16c9de59ee5522 | [
"Apache-2.0"
] | permissive | kristychoi/mathlib | c504b5e8f84e272ea1d8966693c42de7523bf0ec | 257fd84fe98927ff4a5ffe044f68c4e9d235cc75 | refs/heads/master | 1,586,520,722,896 | 1,544,030,145,000 | 1,544,031,933,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 121,217 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Multisets.
-/
import logic.function order.boolean_algebra
data.list.basic data.list.perm data.list.sort data.quot data.string
algebra.order_functions algebra.group_power algebra.ordered_group
category.traversable.lemmas tactic.interactive
category.traversable.instances category.basic
open list subtype nat lattice
variables {α : Type*} {β : Type*} {γ : Type*}
local infix ` • ` := add_monoid.smul
instance list.perm.setoid (α : Type*) : setoid (list α) :=
setoid.mk perm ⟨perm.refl, @perm.symm _, @perm.trans _⟩
/-- `multiset α` is the quotient of `list α` by list permutation. The result
is a type of finite sets with duplicates allowed. -/
def {u} multiset (α : Type u) : Type u :=
quotient (list.perm.setoid α)
namespace multiset
instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩
@[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl
@[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl
@[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl
@[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq
instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α)
| s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂,
decidable_of_iff' _ quotient.eq
/- empty multiset -/
/-- `0 : multiset α` is the empty set -/
protected def zero : multiset α := @nil α
instance : has_zero (multiset α) := ⟨multiset.zero⟩
instance : has_emptyc (multiset α) := ⟨0⟩
instance : inhabited (multiset α) := ⟨0⟩
@[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl
@[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl
/- cons -/
/-- `cons a s` is the multiset which contains `s` plus one more
instance of `a`. -/
def cons (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (a :: l : multiset α))
(λ l₁ l₂ p, quot.sound ((perm_cons a).2 p))
notation a :: b := cons a b
instance : has_insert α (multiset α) := ⟨cons⟩
@[simp] theorem insert_eq_cons (a : α) (s : multiset α) :
insert a s = a::s := rfl
@[simp] theorem cons_coe (a : α) (l : list α) :
(a::l : multiset α) = (a::l : list α) := rfl
theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl
@[simp] theorem cons_inj_left {a b : α} (s : multiset α) :
a::s = b::s ↔ a = b :=
⟨quot.induction_on s $ λ l e,
have [a] ++ l ~ [b] ++ l, from quotient.exact e,
eq_singleton_of_perm $ (perm_app_right_iff _).1 this, congr_arg _⟩
@[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a::s = a::t ↔ s = t :=
by rintros ⟨l₁⟩ ⟨l₂⟩; simp [perm_cons]
@[recursor 5] protected theorem induction {p : multiset α → Prop}
(h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : ∀s, p s :=
by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih]
@[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop}
(s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s :=
multiset.induction h₁ h₂ s
theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s :=
quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _
section rec
variables {C : multiset α → Sort*}
/-- Dependent recursor on multisets.
TODO: should be @[recursor 6], but then the definition of `multiset.pi` failes with a stack
overflow in `whnf`.
-/
protected def rec
(C_0 : C 0)
(C_cons : Πa m, C m → C (a::m))
(C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b))
(m : multiset α) : C m :=
quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $
assume l l' h,
list.rec_heq_of_perm h
(assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc)
(assume a a' l, C_cons_heq a a' ⟦l⟧)
@[elab_as_eliminator]
protected def rec_on (m : multiset α)
(C_0 : C 0)
(C_cons : Πa m, C m → C (a::m))
(C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) :
C m :=
multiset.rec C_0 C_cons C_cons_heq m
variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)}
{C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)}
@[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 :=
rfl
@[simp] lemma rec_on_cons (a : α) (m : multiset α) :
(a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) :=
quotient.induction_on m $ assume l, rfl
end rec
section mem
/-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/
def mem (a : α) (s : multiset α) : Prop :=
quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_of_perm e)
instance : has_mem α (multiset α) := ⟨mem⟩
@[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl
instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) :=
quot.rec_on_subsingleton s $ list.decidable_mem a
@[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, iff.rfl
lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s :=
mem_cons.2 $ or.inr h
@[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s :=
mem_cons.2 (or.inl rfl)
theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t :=
quot.induction_on s $ λ l (h : a ∈ l),
let ⟨l₁, l₂, e⟩ := mem_split h in
e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩
@[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id
theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 :=
quot.induction_on s $ λ l H, by rw eq_nil_of_forall_not_mem H; refl
theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s :=
quot.induction_on s $ assume l hl,
match l, hl with
| [] := assume h, false.elim $ h rfl
| (a :: l) := assume _, ⟨a, by simp⟩
end
@[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m :=
assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this
@[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm
lemma cons_eq_cons {a b : α} {as bs : multiset α} :
a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) :=
begin
haveI : decidable_eq α := classical.dec_eq α,
split,
{ assume eq,
by_cases a = b,
{ subst h, simp * at * },
{ have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _,
have : a ∈ bs, by simpa [h],
rcases exists_cons_of_mem this with ⟨cs, hcs⟩,
simp [h, hcs],
have : a :: as = b :: a :: cs, by simp [eq, hcs],
have : a :: as = a :: b :: cs, by rwa [cons_swap],
simpa using this } },
{ assume h,
rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ simp * },
{ simp [*, cons_swap a b] } }
end
end mem
/- subset -/
section subset
/-- `s ⊆ t` is the lift of the list subset relation. It means that any
element with nonzero multiplicity in `s` has nonzero multiplicity in `t`,
but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`;
see `s ≤ t` for this relation. -/
protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t
instance : has_subset (multiset α) := ⟨multiset.subset⟩
@[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl
@[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h
theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u :=
λ h₁ h₂ a m, h₂ (h₁ m)
theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl
theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _
@[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s :=
λ a, (not_mem_nil a).elim
@[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp [subset_iff, or_imp_distrib, forall_and_distrib]
theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 :=
eq_zero_of_forall_not_mem h
theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 :=
⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩
end subset
/- multiset order -/
/-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation).
Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/
protected def le (s t : multiset α) : Prop :=
quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
propext (p₂.subperm_left.trans p₁.subperm_right)
instance : partial_order (multiset α) :=
{ le := multiset.le,
le_refl := by rintros ⟨l⟩; exact subperm.refl _,
le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _,
le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) }
theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subset_of_subperm
theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t :=
mem_of_subset (subset_of_le h)
@[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl
@[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop}
{s t : multiset α} (h : s ≤ t)
(H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t :=
quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩,
(show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h
theorem zero_le (s : multiset α) : 0 ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist $ nil_sublist l
theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 :=
⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩
theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s :=
quot.induction_on s $ λ l,
suffices l <+~ a :: l ∧ (¬l ~ a :: l),
by simpa [lt_iff_le_and_ne],
⟨subperm_of_sublist (sublist_cons _ _),
λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩
theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s :=
le_of_lt $ lt_cons_self _ _
theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a
theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t :=
(cons_le_cons_iff a).2
theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t :=
begin
refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩,
suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t',
{ exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) },
introv h, revert m, refine le_induction_on h _,
introv s m₁ m₂,
rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩,
exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ subperm_of_sublist $
(sublist_or_mem_of_sublist s).resolve_right m₁)
end
/- cardinality -/
/-- The cardinality of a multiset is the sum of the multiplicities
of all its elements, or simply the length of the underlying list. -/
def card (s : multiset α) : ℕ :=
quot.lift_on s length $ λ l₁ l₂, perm_length
@[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl
@[simp] theorem card_zero : @card α 0 = 0 := rfl
@[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 :=
quot.induction_on s $ λ l, rfl
@[simp] theorem card_singleton (a : α) : card (a::0) = 1 := by simp
theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t :=
le_induction_on h $ λ l₁ l₂, length_le_of_sublist
theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t :=
le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂
theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t :=
lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂
theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t :=
⟨quotient.induction_on₂ s t $ λ l₁ l₂ h,
subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h),
λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩
@[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 :=
⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩
theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 :=
pos_iff_ne_zero.trans $ not_congr card_eq_zero
theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s :=
quot.induction_on s $ λ l, length_pos_iff_exists_mem
@[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} :
∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s
| s := λ ih, ih s $ λ t h,
have card t < card s, from card_lt_of_lt h,
strong_induction_on t ih
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]}
theorem strong_induction_eq {p : multiset α → Sort*}
(s : multiset α) (H) : @strong_induction_on _ p s H =
H s (λ t h, @strong_induction_on _ p t H) :=
by rw [strong_induction_on]
@[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop}
(s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s :=
multiset.strong_induction_on s $ assume s,
multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $
λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _
/- singleton -/
@[simp] theorem singleton_eq_singleton (a : α) : singleton a = a::0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp
theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _
theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _
@[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 :=
ne_of_gt (lt_cons_self _ _)
@[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s :=
⟨λ h, mem_of_le h (mem_singleton_self _),
λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩
theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a::0 :=
⟨quot.induction_on s $ λ l h,
(list.length_eq_one.1 h).imp $ λ a, congr_arg coe,
λ ⟨a, e⟩, e.symm ▸ rfl⟩
/- add -/
/-- The sum of two multisets is the lift of the list append operation.
This adds the multiplicities of each element,
i.e. `count a (s + t) = count a s + count a t`. -/
protected def add (s₁ s₂ : multiset α) : multiset α :=
quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $
λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_app p₁ p₂
instance : has_add (multiset α) := ⟨multiset.add⟩
@[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl
protected theorem add_comm (s t : multiset α) : s + t = t + s :=
quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_app_comm
protected theorem zero_add (s : multiset α) : 0 + s = s :=
quot.induction_on s $ λ l, rfl
theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl
protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u :=
quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_app_left _
protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u :=
le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h))
((multiset.add_le_add_left _).1 (le_of_eq h.symm))
instance : ordered_cancel_comm_monoid (multiset α) :=
{ zero := 0,
add := (+),
add_comm := multiset.add_comm,
add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃,
congr_arg coe $ append_assoc l₁ l₂ l₃,
zero_add := multiset.zero_add,
add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add],
add_left_cancel := multiset.add_left_cancel,
add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $
by simpa [multiset.add_comm] using h,
add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h,
le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1,
..@multiset.partial_order α }
@[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) :=
by rw [← singleton_add, ← singleton_add, add_assoc]
@[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) :=
by rw [add_comm, cons_add, add_comm]
theorem le_add_right (s t : multiset α) : s ≤ s + t :=
by simpa using add_le_add_left (zero_le t) s
theorem le_add_left (s t : multiset α) : s ≤ t + s :=
by simpa using add_le_add_right (zero_le t) s
@[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t :=
quotient.induction_on₂ s t length_append
@[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, mem_append
theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u :=
⟨λ h, le_induction_on h $ λ l₁ l₂ s,
let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩,
λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩
instance : canonically_ordered_monoid (multiset α) :=
{ lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _,
le_iff_exists_add := @le_iff_exists_add _,
..multiset.ordered_cancel_comm_monoid }
/- repeat -/
/-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/
def repeat (a : α) (n : ℕ) : multiset α := repeat a n
@[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl
@[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a :: repeat a n := by simp [repeat]
@[simp] lemma repeat_one (a : α) : repeat a 1 = a :: 0 := by simp
@[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat
theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat
theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
(perm_repeat.1 $ (quotient.exact h).symm).symm, congr_arg coe⟩ eq_repeat'
theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card :=
eq_repeat'.2
theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a :=
⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton
theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l :=
⟨λ ⟨l', p, s⟩, (perm_repeat.1 p.symm).symm ▸ s, subperm_of_sublist⟩
/- range -/
/-- `range n` is the multiset lifted from the list `range n`,
that is, the set `{0, 1, ..., n-1}`. -/
def range (n : ℕ) : multiset ℕ := range n
@[simp] theorem range_zero : range 0 = 0 := rfl
@[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n :=
by rw [range, range_concat, ← coe_add, add_comm]; refl
@[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self
/- erase -/
section erase
variables [decidable_eq α] {s t : multiset α} {a b : α}
/-- `erase s a` is the multiset that subtracts 1 from the
multiplicity of `a`. -/
def erase (s : multiset α) (a : α) : multiset α :=
quot.lift_on s (λ l, (l.erase a : multiset α))
(λ l₁ l₂ p, quot.sound (erase_perm_erase a p))
@[simp] theorem coe_erase (l : list α) (a : α) :
erase (l : multiset α) a = l.erase a := rfl
@[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl
@[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l
@[simp] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h
@[simp] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s :=
quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h
@[simp] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s :=
quot.induction_on s $ λ l h, quot.sound (perm_erase h).symm
theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a :=
if h : a ∈ s then le_of_eq (cons_erase h).symm
else by rw erase_of_not_mem h; apply le_cons_self
@[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) :=
quot.induction_on s $ λ l, length_erase_of_mem
theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h
theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a :=
by rw [add_comm, erase_add_left_pos s h, add_comm]
theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h
theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t :=
by rw [add_comm, erase_add_right_neg s h, add_comm]
theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist (erase_sublist a l)
@[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s :=
⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h),
λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩
theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s :=
subset_of_le (erase_le a s)
theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s :=
quot.induction_on s $ λ l, list.mem_erase_of_ne ab
theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s :=
mem_of_subset (erase_subset _ _)
theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a :=
quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b
theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a :=
le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist (erase_sublist_erase _ h)
theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t :=
⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h),
λ h, if m : a ∈ s
then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h
else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩
end erase
@[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l :=
quot.sound $ reverse_perm _
/- map -/
/-- `map f s` is the lift of the list `map` operation. The multiplicity
of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity)
such that `f a = b`. -/
def map (f : α → β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l : list α, (l.map f : multiset β))
(λ l₁ l₂ p, quot.sound (perm_map f p))
@[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl
@[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl
@[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s :=
quot.induction_on s $ λ l, rfl
@[simp] lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl
@[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _
@[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} :
b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b :=
quot.induction_on s $ λ l, mem_map
@[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s :=
quot.induction_on s $ λ l, length_map _ _
theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s :=
mem_map.2 ⟨_, h, rfl⟩
@[simp] theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} :
f a ∈ map f s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_map_of_inj H
@[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _
@[simp] theorem map_id (s : multiset α) : map id s = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_id _
@[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s
@[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card :=
quot.induction_on s $ λ l, congr_arg coe $ map_const _ _
@[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s :=
quot.induction_on s $ λ l H, congr_arg coe $ map_congr H
lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m :=
begin subst h, simp at hf, simp [map_congr hf] end
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
eq_of_mem_repeat $ by rwa map_const at h
@[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t :=
le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ map_sublist_map f h
@[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t :=
λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩
/- fold -/
/-- `foldl f H b s` is the lift of the list operation `foldl f b l`,
which folds `f` over the multiset. It is well defined when `f` is right-commutative,
that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/
def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldl f b l)
(λ l₁ l₂ p, foldl_eq_of_perm H p b)
@[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl
@[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _
/-- `foldr f H b s` is the lift of the list operation `foldr f b l`,
which folds `f` over the multiset. It is well defined when `f` is left-commutative,
that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/
def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldr f b l)
(λ l₁ l₂ p, foldr_eq_of_perm H p b)
@[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _
@[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldr f b := rfl
@[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) :
foldl f H b l = l.foldl f b := rfl
theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldl (λ x y, f y x) b :=
(congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _
theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) :
foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _
theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) :
foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
(foldr_swap _ _ _ _).symm
/-- Product of a multiset given a commutative monoid structure on `α`.
`prod {a, b, c} = a * b * c` -/
def prod [comm_monoid α] : multiset α → α :=
foldr (*) (λ x y z, by simp [mul_left_comm]) 1
attribute [to_additive multiset.sum._proof_1] prod._proof_1
attribute [to_additive multiset.sum] prod
@[to_additive multiset.sum_eq_foldr]
theorem prod_eq_foldr [comm_monoid α] (s : multiset α) :
prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl
@[to_additive multiset.sum_eq_foldl]
theorem prod_eq_foldl [comm_monoid α] (s : multiset α) :
prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s :=
(foldr_swap _ _ _ _).trans (by simp [mul_comm])
@[simp, to_additive multiset.coe_sum]
theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod :=
prod_eq_foldl _
@[simp, to_additive multiset.sum_zero]
theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl
@[simp, to_additive multiset.sum_cons]
theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s :=
foldr_cons _ _ _ _ _
@[to_additive multiset.sum_singleton]
theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp
@[simp, to_additive multiset.sum_add]
theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t :=
quotient.induction_on₂ s t $ λ l₁ l₂, by simp
@[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n :=
by simp [repeat, list.prod_repeat]
@[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a :=
@prod_repeat (multiplicative α) _
attribute [to_additive multiset.sum_repeat] prod_repeat
@[simp] lemma prod_map_one [comm_monoid γ] {m : multiset α} :
prod (m.map (λa, (1 : γ))) = (1 : γ) :=
multiset.induction_on m (by simp) (by simp)
@[simp] lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} :
sum (m.map (λa, (0 : γ))) = (0 : γ) :=
multiset.induction_on m (by simp) (by simp)
attribute [to_additive multiset.sum_map_zero] prod_map_one
@[simp, to_additive multiset.sum_map_add]
lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} :
prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc)
lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} :
prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih])
lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ},
sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) :=
@prod_map_prod_map _ _ (multiplicative γ) _
attribute [to_additive multiset.sum_map_sum_map] prod_map_prod_map
lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, b * f a)) = b * sum (s.map f) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add])
lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, f a * b)) = sum (s.map f) * b :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul])
/- join -/
/-- `join S`, where `S` is a multiset of multisets, is the lift of the list join
operation, that is, the union of all the sets.
join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/
def join : multiset (multiset α) → multiset α := sum
theorem coe_join : ∀ L : list (list α),
join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join
| [] := rfl
| (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L)
@[simp] theorem join_zero : @join α 0 = 0 := rfl
@[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S :=
sum_cons _ _
@[simp] theorem join_add (S T) : @join α (S + T) = join S + join T :=
sum_add _ _
@[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s :=
multiset.induction_on S (by simp) $
by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt}
@[simp] theorem card_join (S) : card (@join α S) = sum (map card S) :=
multiset.induction_on S (by simp) (by simp)
/- bind -/
/-- `bind s f` is the monad bind operation, defined as `join (map f s)`.
It is the union of `f a` as `a` ranges over `s`. -/
def bind (s : multiset α) (f : α → multiset β) : multiset β :=
join (map f s)
@[simp] theorem coe_bind (l : list α) (f : α → list β) :
@bind α β l (λ a, f a) = l.bind f :=
by rw [list.bind, ← coe_join, list.map_map]; refl
@[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl
@[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f :=
by simp [bind]
@[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f :=
by simp [bind]
@[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 :=
by simp [bind, -map_const, join]
@[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) :
bind s (λa, f a + g a) = bind s f + bind s g :=
by simp [bind, join]
@[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) :
bind s (λa, f a :: g a) = map f s + bind s g :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
@[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a :=
by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm];
rw exists_swap; simp [and_assoc]
@[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) :=
by simp [bind]
lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g :=
by simp [bind] {contextual := tt}
lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' :=
begin subst h, simp at hf, simp [bind_congr hf] end
lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) :
map f (bind m n) = bind m (λa, map f (n a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) :
bind (map f m) n = bind m (λa, n (f a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} :
(s.bind f).bind g = s.bind (λa, (f a).bind g) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} :
(bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} :
(bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
@[simp, to_additive multiset.sum_bind]
lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) :
prod (bind s t) = prod (s.map $ λa, prod (t a)) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind])
/- product -/
/-- The multiplicity of `(a, b)` in `product s t` is
the product of the multiplicity of `a` in `s` and `b` in `t`. -/
def product (s : multiset α) (t : multiset β) : multiset (α × β) :=
s.bind $ λ a, t.map $ prod.mk a
@[simp] theorem coe_product (l₁ : list α) (l₂ : list β) :
@product α β l₁ l₂ = l₁.product l₂ :=
by rw [product, list.product, ← coe_bind]; simp
@[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl
@[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) :
product (a :: s) t = map (prod.mk a) t + product s t :=
by simp [product]
@[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl
@[simp] theorem add_product (s t : multiset α) (u : multiset β) :
product (s + t) u = product s u + product t u :=
by simp [product]
@[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β,
product s (t + u) = product s t + product s u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_product, IH]; simp
@[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t
| (a, b) := by simp [product, and.left_comm]
@[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t :=
by simp [product, repeat, (∘), mul_comm]
/- sigma -/
section
variable {σ : α → Type*}
/-- `sigma s t` is the dependent version of `product`. It is the sum of
`(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/
protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) :=
s.bind $ λ a, (t a).map $ sigma.mk a
@[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
@multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ :=
by rw [multiset.sigma, list.sigma, ← coe_bind]; simp
@[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl
@[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) :
(a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t :=
by simp [multiset.sigma]
@[simp] theorem sigma_singleton (a : α) (b : α → β) :
(a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl
@[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) :
(s + t).sigma u = s.sigma u + t.sigma u :=
by simp [multiset.sigma]
@[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a),
s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_sigma, IH]; simp
@[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a},
p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1
| ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm]
@[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) :
card (s.sigma t) = sum (map (λ a, card (t a)) s) :=
by simp [multiset.sigma, (∘)]
end
/- map for partial functions -/
/-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset
`s` whose elements are all in the domain of `f`. -/
def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β :=
quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂),
funext $ λ (H₂ : ∀ a ∈ l₂, p a),
have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a ((mem_of_perm pp).1 h),
have ∀ {s₂ e H}, @eq.rec (multiset α) l₁
(λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁))
s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e,
this.trans $ quot.sound $ perm_pmap f pp
@[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β)
(l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl
@[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) :
pmap f 0 h = 0 := rfl
@[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) :
∀(h : ∀b∈a::m, p b), pmap f (a :: m) h =
f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) :=
quotient.induction_on m $ assume l h, rfl
/-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce
a multiset on `{x // x ∈ s}`. -/
def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id)
@[simp] theorem coe_attach (l : list α) :
@eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl
theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) :
∀ H, @pmap _ _ p (λ a _, f a) s H = map f s :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f s H₁ = pmap g s H₂ :=
quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H :=
quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H
theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s :=
quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l
@[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach :=
quot.induction_on s $ λ l, mem_attach _
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b :=
quot.induction_on s (λ l H, mem_pmap) H
@[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β)
(s H) : card (pmap f s H) = card s :=
quot.induction_on s (λ l H, length_pmap) H
@[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _
@[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl
lemma attach_cons (a : α) (m : multiset α) :
(a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) :=
quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $
by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl)
section decidable_pi_exists
variables {m : multiset α}
protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] :
decidable (∀a∈m, p a) :=
quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp)
instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∀a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _))
/-- decidable equality for functions whose domain is bounded by multisets -/
instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈m, β a) :=
assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff])
def decidable_exists_multiset {p : α → Prop} [decidable_pred p] :
decidable (∃ x ∈ m, p x) :=
quotient.rec_on_subsingleton m list.decidable_exists_mem
instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∃a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩)
(λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩))
end decidable_pi_exists
/- subtraction -/
section
variables [decidable_eq α] {s t u : multiset α} {a b : α}
/-- `s - t` is the multiset such that
`count a (s - t) = count a s - count a t` for all `a`. -/
protected def sub (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ p₁
instance : has_sub (multiset α) := ⟨multiset.sub⟩
@[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl
theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂,
by rw diff_eq_foldl l₁ l₂; exact foldl_hom _ _ _ _ (λ x y, rfl) _
@[simp] theorem sub_zero (s : multiset α) : s - 0 = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _
theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t :=
begin
revert t,
refine multiset.induction_on s (by simp) (λ a s IH t h, _),
have := cons_erase (mem_of_le h (mem_cons_self _ _)),
rw [cons_add, sub_cons, IH, this],
exact (cons_le_cons_iff a).1 (this.symm ▸ h)
end
theorem sub_add' : s - (t + u) = s - t - u :=
quotient.induction_on₃ s t u $
λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _
theorem sub_add_cancel (h : t ≤ s) : s - t + t = s :=
by rw [add_comm, add_sub_of_le h]
@[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t :=
multiset.induction_on s (by simp)
(λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH])
@[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s :=
by rw [add_comm, add_sub_cancel_left]
theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u :=
by revert s t h; exact
multiset.induction_on u (by simp {contextual := tt})
(λ a u IH s t h, by simp [IH, erase_le_erase a h])
theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s :=
le_induction_on h $ λ l₁ l₂ h, begin
induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u,
{ refl },
{ rw [← cons_coe, sub_cons],
exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) },
{ rw [← cons_coe, sub_cons, ← cons_coe, sub_cons],
exact IH _ }
end
theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t :=
by revert s; exact
multiset.induction_on t (by simp)
(λ a t IH s, by simp [IH, erase_le_iff_le_cons])
theorem le_sub_add (s t : multiset α) : s ≤ s - t + t :=
sub_le_iff_le_add.1 (le_refl _)
theorem sub_le_self (s t : multiset α) : s - t ≤ s :=
sub_le_iff_le_add.2 (le_add_right _ _)
@[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t :=
(nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm
/- union -/
/-- `s ∪ t` is the lattice join operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum
of the multiplicities in `s` and `t`. -/
def union (s t : multiset α) : multiset α := s - t + t
instance : has_union (multiset α) := ⟨union⟩
theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl
theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _
theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _
theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel
theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u :=
add_le_add_right (sub_le_sub_right h _) u
theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u :=
by rw ← eq_union_left h₂; exact union_le_union_right h₁ t
@[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t :=
⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _),
or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩
@[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} :
map f (s ∪ t) = map f s ∪ map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
congr_arg coe (by rw [list.map_append f, list.map_diff finj])
/- inter -/
/-- `s ∩ t` is the lattice meet operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum
of the multiplicities in `s` and `t`. -/
def inter (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ p₁
instance : has_inter (multiset α) := ⟨inter⟩
@[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil
@[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter
@[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} :
a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_pos _ h
@[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} :
a ∉ t → (a :: s) ∩ t = s ∩ t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_neg _ h
theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s :=
quotient.induction_on₂ s t $ λ l₁ l₂,
subperm_of_sublist $ bag_inter_sublist_left _ _
theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t :=
multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $
λ a s IH t, if h : a ∈ t
then by simpa [h] using cons_le_cons a (IH (t.erase a))
else by simp [h, IH]
theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u :=
begin
revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros,
{ simp [h₁] },
by_cases a ∈ u,
{ rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons],
exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) },
{ rw cons_inter_of_neg _ h,
exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ }
end
@[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t :=
⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩,
λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩
instance : lattice (multiset α) :=
{ sup := (∪),
sup_le := @union_le _ _,
le_sup_left := le_union_left,
le_sup_right := le_union_right,
inf := (∩),
le_inf := @le_inter _ _,
inf_le_left := inter_le_left,
inf_le_right := inter_le_right,
..@multiset.partial_order α }
@[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl
@[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl
@[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff
@[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff
instance : semilattice_inf_bot (multiset α) :=
{ bot := 0, bot_le := zero_le, ..multiset.lattice.lattice }
theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm
theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm
theorem eq_union_right (h : s ≤ t) : s ∪ t = t :=
by rw [union_comm, eq_union_left h]
theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t :=
sup_le_sup_left h _
theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t :=
union_le (le_add_right _ _) (le_add_left _ _)
theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) :=
by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t,
by rw [add_comm t, sub_add', add_sub_cancel]
theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) :=
by rw [add_comm, union_add_distrib, add_comm s, add_comm s]
theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) :=
by simpa using add_union_distrib (a::0) s t
theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) :=
begin
by_contra h,
cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter
(add_le_add_right (inter_le_left s t) u)
(add_le_add_right (inter_le_right s t) u)) h) with a hl,
rw ← cons_add at hl,
exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter
(le_of_add_le_add_right (le_trans hl (inter_le_left _ _)))
(le_of_add_le_add_right (le_trans hl (inter_le_right _ _))))
end
theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) :=
by rw [add_comm, inter_add_distrib, add_comm s, add_comm s]
theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) :=
by simp
theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t :=
begin
apply le_antisymm,
{ rw union_add_distrib,
refine union_le (add_le_add_left (inter_le_right _ _) _) _,
rw add_comm, exact add_le_add_right (inter_le_left _ _) _ },
{ rw [add_comm, add_inter_distrib],
refine le_inter (add_le_add_right (le_union_right _ _) _) _,
rw add_comm, exact add_le_add_right (le_union_left _ _) _ }
end
theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s :=
begin
rw [inter_comm],
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
by_cases a ∈ s,
{ rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] },
{ rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] }
end
theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t :=
add_right_cancel $
by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)]
end
/- filter -/
section
variables {p : α → Prop} [decidable_pred p]
/-- `filter p s` returns the elements in `s` (with the same multiplicities)
which satisfy `p`, and removes the rest. -/
def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (filter p l : multiset α))
(λ l₁ l₂ h, quot.sound $ perm_filter p h)
@[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p]
(l : list α) : filter p (↑l) = l.filter p := rfl
@[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl
@[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h
@[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s :=
quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
{s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h
@[simp] theorem filter_add (s t : multiset α) :
filter p (s + t) = filter p s + filter p t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _
@[simp] theorem filter_le (s : multiset α) : filter p s ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist $ filter_sublist _
@[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s :=
subset_of_le $ filter_le _
@[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a :=
quot.induction_on s $ λ l, mem_filter
theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a :=
(mem_filter.1 h).2
theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s :=
(mem_filter.1 h).1
theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l :=
mem_filter.2 ⟨m, h⟩
theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_self
theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_nil
theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t :=
le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h
theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a :=
⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩,
λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩
@[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) :
filter p (s - t) = filter p s - filter p t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
rw [sub_cons, IH],
by_cases p a,
{ rw [filter_cons_of_pos _ h, sub_cons], congr,
by_cases m : a ∈ s,
{ rw [← cons_inj_right a, ← filter_cons_of_pos _ h,
cons_erase (mem_filter_of_mem m h), cons_erase m] },
{ rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } },
{ rw [filter_cons_of_neg _ h],
by_cases m : a ∈ s,
{ rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)),
cons_erase m] },
{ rw [erase_of_not_mem m] } }
end
@[simp] theorem filter_union [decidable_eq α] (s t : multiset α) :
filter p (s ∪ t) = filter p s ∪ filter p t :=
by simp [(∪), union]
@[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) :
filter p (s ∩ t) = filter p s ∩ filter p t :=
le_antisymm (le_inter
(filter_le_filter $ inter_le_left _ _)
(filter_le_filter $ inter_le_right _ _)) $ le_filter.2
⟨inf_le_inf (filter_le _) (filter_le _),
λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩
@[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) :
filter p (filter q s) = filter (λ a, p a ∧ q a) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter l
theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) :
filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s :=
multiset.induction_on s rfl $ λ a s IH,
by by_cases p a; by_cases q a; simp *
theorem filter_add_not (s : multiset α) :
filter p s + filter (λ a, ¬ p a) s = s :=
by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em]
/- filter_map -/
/-- `filter_map f s` is a combination filter/map operation on `s`.
The function `f : α → option β` is applied to each element of `s`;
if `f a` is `some b` then `b` is added to the result, otherwise
`a` is removed from the resulting multiset. -/
def filter_map (f : α → option β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l, (filter_map f l : multiset β))
(λ l₁ l₂ h, quot.sound $perm_filter_map f h)
@[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl
@[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) :
filter_map f (a :: s) = filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (s : multiset α) {b : β} (h : f a = some b) :
filter_map f (a :: s) = b :: filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) :
filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l
theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) :
map g (filter_map f s) = filter_map (λ x, (f x).map g) s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l
theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) :
filter_map g (map f s) = filter_map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) :
filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) :
filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l
@[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l
@[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} :
b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b :=
quot.induction_on s $ λ l, mem_filter_map f l
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (s : multiset α) :
map g (filter_map f s) = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l
theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α}
(h : s ≤ t) : filter_map f s ≤ filter_map f t :=
le_induction_on h $ λ l₁ l₂ h,
subperm_of_sublist $ filter_map_sublist_filter_map _ h
/- powerset -/
def powerset_aux (l : list α) : list (multiset α) :=
0 :: sublists_aux l (λ x y, x :: y)
theorem powerset_aux_eq_map_coe {l : list α} :
powerset_aux l = (sublists l).map coe :=
by simp [powerset_aux, sublists];
rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) =
sublists_aux l (λ x, list.cons ↑x),
from sublists_aux₁_eq_sublists_aux _ _,
sublists_aux_cons_eq_sublists_aux₁,
← bind_ret_eq_map, sublists_aux₁_bind]; refl
@[simp] theorem mem_powerset_aux {l : list α} {s} :
s ∈ powerset_aux l ↔ s ≤ ↑l :=
quotient.induction_on s $
by simp [powerset_aux_eq_map_coe, subperm, and.comm]
def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe
theorem powerset_aux_perm_powerset_aux' {l : list α} :
powerset_aux l ~ powerset_aux' l :=
by rw powerset_aux_eq_map_coe; exact
perm_map _ (sublists_perm_sublists' _)
@[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl
@[simp] theorem powerset_aux'_cons (a : α) (l : list α) :
powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) :=
by simp [powerset_aux']; refl
theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux' l₁ ~ powerset_aux' l₂ :=
begin
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ simp, exact perm_app IH (perm_map _ IH) },
{ simp, apply perm_app_right,
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)],
exact perm_app_left _ perm_app_comm },
{ exact IH₁.trans IH₂ }
end
theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux l₁ ~ powerset_aux l₂ :=
powerset_aux_perm_powerset_aux'.trans $
(powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm
def powerset (s : multiset α) : multiset (multiset α) :=
quot.lift_on s
(λ l, (powerset_aux l : multiset (multiset α)))
(λ l₁ l₂ h, quot.sound (powerset_aux_perm h))
theorem powerset_coe (l : list α) :
@powerset α l = ((sublists l).map coe : list (multiset α)) :=
congr_arg coe powerset_aux_eq_map_coe
@[simp] theorem powerset_coe' (l : list α) :
@powerset α l = ((sublists' l).map coe : list (multiset α)) :=
quot.sound powerset_aux_perm_powerset_aux'
@[simp] theorem powerset_zero : @powerset α 0 = 0::0 := rfl
@[simp] theorem powerset_cons (a : α) (s) :
powerset (a::s) = powerset s + map (cons a) (powerset s) :=
quotient.induction_on s $ λ l, by simp; refl
@[simp] theorem mem_powerset {s t : multiset α} :
s ∈ powerset t ↔ s ≤ t :=
quotient.induction_on₂ s t $ by simp [subperm, and.comm]
theorem map_single_le_powerset (s : multiset α) :
s.map (λ a, a::0) ≤ powerset s :=
quotient.induction_on s $ λ l, begin
simp [powerset_coe],
show l.map (coe ∘ list.ret) <+~ (sublists l).map coe,
rw ← list.map_map,
exact subperm_of_sublist
(map_sublist_map _ (map_ret_sublist_sublists _))
end
@[simp] theorem card_powerset (s : multiset α) :
card (powerset s) = 2 ^ card s :=
quotient.induction_on s $ by simp
/- diagonal -/
theorem revzip_powerset_aux {l : list α} ⦃s t⦄
(h : (s, t) ∈ revzip (powerset_aux l)) : s + t = ↑l :=
begin
rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h,
simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩,
exact quot.sound (revzip_sublists _ _ _ h)
end
theorem revzip_powerset_aux' {l : list α} ⦃s t⦄
(h : (s, t) ∈ revzip (powerset_aux' l)) : s + t = ↑l :=
begin
rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h,
simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩,
exact quot.sound (revzip_sublists' _ _ _ h)
end
theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α)
{l' : list (multiset α)} (H : ∀ ⦃s t⦄, (s, t) ∈ revzip l' → s + t = ↑l) :
revzip l' = l'.map (λ x, (x, ↑l - x)) :=
begin
have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s))
(revzip l') ((revzip l').map prod.fst),
{ rw forall₂_map_right_iff,
apply forall₂_same, rintro ⟨s, t⟩ h,
dsimp, rw [← H h, add_sub_cancel_left] },
rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa
end
theorem revzip_powerset_aux_perm_aux' {l : list α} :
revzip (powerset_aux l) ~ revzip (powerset_aux' l) :=
begin
haveI := classical.dec_eq α,
rw [revzip_powerset_aux_lemma l revzip_powerset_aux,
revzip_powerset_aux_lemma l revzip_powerset_aux'],
exact perm_map _ powerset_aux_perm_powerset_aux',
end
theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) :=
begin
haveI := classical.dec_eq α,
simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p],
exact perm_map _ (powerset_aux_perm p)
end
def diagonal (s : multiset α) : multiset (multiset α × multiset α) :=
quot.lift_on s
(λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α)))
(λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h))
theorem diagonal_coe (l : list α) :
@diagonal α l = revzip (powerset_aux l) := rfl
@[simp] theorem diagonal_coe' (l : list α) :
@diagonal α l = revzip (powerset_aux' l) :=
quot.sound revzip_powerset_aux_perm_aux'
@[simp] theorem mem_diagonal {s₁ s₂ t : multiset α} :
(s₁, s₂) ∈ diagonal t ↔ s₁ + s₂ = t :=
quotient.induction_on t $ λ l, begin
simp [diagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩,
haveI := classical.dec_eq α,
simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm],
exact ⟨_, le_add_right _ _, rfl, add_sub_cancel_left _ _⟩
end
@[simp] theorem diagonal_map_fst (s : multiset α) :
(diagonal s).map prod.fst = powerset s :=
quotient.induction_on s $ λ l,
by simp [powerset_aux']
@[simp] theorem diagonal_map_snd (s : multiset α) :
(diagonal s).map prod.snd = powerset s :=
quotient.induction_on s $ λ l,
by simp [powerset_aux']
@[simp] theorem diagonal_zero : @diagonal α 0 = (0, 0)::0 := rfl
@[simp] theorem diagonal_cons (a : α) (s) : diagonal (a::s) =
map (prod.map id (cons a)) (diagonal s) +
map (prod.map (cons a) id) (diagonal s) :=
quotient.induction_on s $ λ l, begin
simp [revzip, reverse_append],
rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)],
{congr; simp}, {simp}
end
@[simp] theorem card_diagonal (s : multiset α) :
card (diagonal s) = 2 ^ card s :=
by have := card_powerset s;
rwa [← diagonal_map_fst, card_map] at this
lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} :
prod (s.map (λa, f a + g a)) = sum ((diagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) :=
begin
refine s.induction_on _ _,
{ simp },
{ assume a s ih, simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm] },
end
/- countp -/
/-- `countp p s` counts the number of elements of `s` (with multiplicity) that
satisfy `p`. -/
def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ :=
quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p)
@[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl
@[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 :=
quot.induction_on s countp_cons_of_pos
@[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s :=
quot.induction_on s countp_cons_of_neg
theorem countp_eq_card_filter (s) : countp p s = card (filter p s) :=
quot.induction_on s $ λ l, countp_eq_length_filter _
@[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t :=
by simp [countp_eq_card_filter]
theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a :=
by simp [countp_eq_card_filter, card_pos_iff_exists_mem]
@[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) :
countp p (s - t) = countp p s - countp p t :=
by simp [countp_eq_card_filter, h, filter_le_filter]
theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s :=
countp_pos.2 ⟨_, h, pa⟩
theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t :=
by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h)
@[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) :
countp p (filter q s) = countp (λ a, p a ∧ q a) s :=
by simp [countp_eq_card_filter]
end
/- count -/
section
variable [decidable_eq α]
/-- `count a s` is the multiplicity of `a` in `s`. -/
def count (a : α) : multiset α → ℕ := countp (eq a)
@[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _
@[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl
@[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) :=
countp_cons_of_pos _ rfl
@[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s :=
countp_cons_of_neg _ h
theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t :=
countp_le_of_le
theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) :=
count_le_of_le _ (le_cons_self _ _)
theorem count_singleton (a : α) : count a (a::0) = 1 :=
by simp
@[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t :=
countp_add
@[simp] theorem count_smul (a : α) (n s) : count a (n • s) = n * count a s :=
by induction n; simp [*, succ_smul', succ_mul]
theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s :=
by simp [count, countp_pos]
@[simp] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s :=
iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by simp [repeat]
@[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) :=
begin
by_cases a ∈ s,
{ rw [(by rw cons_erase h : count a s = count a (a::erase s a)),
count_cons_self]; refl },
{ rw [erase_of_not_mem h, count_eq_zero.2 h]; refl }
end
@[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s :=
begin
by_cases b ∈ s,
{ rw [← count_cons_of_ne ab, cons_erase h] },
{ rw [erase_of_not_mem h] }
end
@[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _),
rw [sub_cons, IH],
by_cases ab : a = b,
{ subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] },
{ rw [count_erase_of_ne ab, count_cons_of_ne ab] }
end
@[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) :=
by simp [(∪), union, sub_add_eq_max, -add_comm]
@[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) :=
begin
apply @nat.add_left_cancel (count a (s - t)),
rw [← count_add, sub_add_inter, count_sub, sub_add_min],
end
lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} :
count a (bind m f) = sum (m.map $ λb, count a $ f b) :=
multiset.induction_on m (by simp) (by simp)
theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s :=
quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm
@[simp] theorem count_filter {p} [decidable_pred p]
{a} {s : multiset α} (h : p a) : count a (filter p s) = count a s :=
quot.induction_on s $ λ l, count_filter h
theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t :=
quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count
@[extensionality]
theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t :=
ext.2
theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t :=
⟨λ h a, count_le_of_le a h, λ al,
by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t);
apply le_union_left⟩
instance : distrib_lattice (multiset α) :=
{ le_sup_inf := λ s t u, le_of_eq $ eq.symm $
ext.2 $ λ a, by simp [max_min_distrib_left],
..multiset.lattice.lattice }
instance : semilattice_sup_bot (multiset α) :=
{ bot := 0,
bot_le := zero_le,
..multiset.lattice.lattice }
end
/- relator -/
section rel
/-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`,
s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/
inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop
| zero {} : rel 0 0
| cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs)
run_cmd tactic.mk_iff_of_inductive_prop `multiset.rel `multiset.rel_iff
variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s :=
rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih)
lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s :=
⟨rel_flip_aux, rel_flip_aux⟩
lemma rel_eq_refl {s : multiset α} : rel (=) s s :=
multiset.induction_on s rel.zero (assume a s, rel.cons rfl)
lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t :=
begin
split,
{ assume h, induction h; simp * },
{ assume h, subst h, exact rel_eq_refl }
end
lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t :=
begin
induction hst,
case rel.zero { exact rel.zero },
case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) }
end
lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) :=
begin
induction hst,
case rel.zero { simpa using huv },
case rel.cons : a b s t hab hst ih { simpa using ih.cons hab }
end
lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t :=
show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm]
@[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 :=
by rw [rel_iff]; simp
@[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 :=
by rw [rel_iff]; simp
lemma rel_cons_left {a as bs} :
rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') :=
begin
split,
{ generalize hm : a :: as = m,
assume h,
induction h generalizing as,
case rel.zero { simp at hm, contradiction },
case rel.cons : a' b as' bs ha'b h ih {
rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ },
{ rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩,
exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ }
} },
{ exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h }
end
lemma rel_cons_right {as b bs} :
rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') :=
begin
rw [← rel_flip, rel_cons_left],
apply exists_congr, assume a,
apply exists_congr, assume as',
rw [rel_flip, flip]
end
lemma rel_add_left {as₀ as₁} :
∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) :=
multiset.induction_on as₀ (by simp)
begin
assume a s ih bs,
simp only [ih, cons_add, rel_cons_left],
split,
{ assume h,
rcases h with ⟨b, bs', hab, h, rfl⟩,
rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩,
exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ },
{ assume h,
rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩,
rcases h with ⟨b, bs, hab, h₀, rfl⟩,
exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ }
end
lemma rel_add_right {as bs₀ bs₁} :
rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) :=
by rw [← rel_flip, rel_add_left]; simp [rel_flip]
lemma rel_map_left {s : multiset γ} {f : γ → α} :
∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t :=
multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt})
lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} :
rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t :=
by rw [← rel_flip, rel_map_left, ← rel_flip]; refl
lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join :=
begin
induction h,
case rel.zero { simp },
case rel.cons : a b s t hab hst ih { simpa using hab.add ih }
end
lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) :
rel p (s.map f) (t.map g) :=
by rw [rel_map_left, rel_map_right]; exact hst.mono (assume a b, h)
lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ}
(h : (r ⇒ rel p) f g) (hst : rel r s t) :
rel p (s.bind f) (t.bind g) :=
by apply rel_join; apply rel_map; assumption
lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
card s = card t :=
by induction h; simp [*]
end rel
section map
theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} :
s.map f = t.map f ↔ s = t :=
by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff]
theorem injective_map {f : α → β} (hf : function.injective f) :
function.injective (multiset.map f) :=
assume x y, (map_eq_map hf).1
end map
section quot
theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) :
s.map (quot.mk r) = t.map (quot.mk r) :=
rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab]
theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) :
∃t:multiset α, s = t.map (quot.mk r) :=
multiset.induction_on s ⟨0, rfl⟩ $
assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a::t, (map_cons _ _ _).symm⟩
theorem induction_on_multiset_quot
{r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) :
(∀s:multiset α, p (s.map (quot.mk r))) → p s :=
match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end
end quot
/- disjoint -/
/-- `disjoint s t` means that `s` and `t` have no elements in common. -/
def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false
@[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl
theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s
| a i₂ i₁ := d i₁ i₂
@[simp] theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl
theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
disjoint_comm
theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp [disjoint_left, imp_not_comm]
theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t
| x m₁ := d (h m₁)
theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t
| x m m₁ := d m (h m₁)
theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t :=
disjoint_of_subset_left (subset_of_le h)
theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t :=
disjoint_of_subset_right (subset_of_le h)
@[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l
| a := (not_mem_nil a).elim
@[simp] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l :=
by simp [disjoint]; refl
@[simp] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l :=
by rw disjoint_comm; simp
@[simp] theorem disjoint_add_left {s t u : multiset α} :
disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_add_right {s t u : multiset α} :
disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u :=
disjoint_comm.trans $ by simp [disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} :
disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t :=
(@disjoint_add_left _ (a::0) s t).trans $ by simp
@[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} :
disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t :=
disjoint_comm.trans $ by simp [disjoint_cons_left]
theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
@[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} :
disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) :=
begin
simp [disjoint],
split,
from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm,
from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁)
end
/-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/
def pairwise (r : α → α → Prop) (m : multiset α) : Prop :=
∃l:list α, m = l ∧ l.pairwise r
lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} :
multiset.pairwise r l ↔ l.pairwise r :=
iff.intro
(assume ⟨l', eq, h⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h)
(assume h, ⟨l, rfl, h⟩)
/- nodup -/
/-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of
any element is at most 1. -/
def nodup (s : multiset α) : Prop :=
quot.lift_on s nodup (λ s t p, propext $ perm_nodup p)
@[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl
@[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l :=
⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩
@[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil _
@[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s :=
quot.induction_on s $ λ l, nodup_cons
theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) :=
nodup_cons.2 ⟨m, n⟩
theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton
theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s :=
(nodup_cons.1 h).2
theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s :=
(nodup_cons.1 h).1
theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s :=
le_induction_on h $ λ l₁ l₂, nodup_of_sublist
theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair
theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s :=
quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a,
not_congr (@repeat_le_coe _ a 2 _).symm
theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 :=
quot.induction_on s $ λ l, nodup_iff_count_le_one
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α}
(d : nodup s) (h : a ∈ s) : count a s = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h)
lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} :
(∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s :=
quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩
theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t :=
quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append
theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t :=
(nodup_add.1 d).2.2
theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t :=
by simp [nodup_add, d₁, d₂]
theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s :=
quot.induction_on s $ λ l, nodup_of_nodup_map f
theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) →
nodup s → nodup (map f s) :=
quot.induction_on s $ λ l, nodup_map_on
theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) :=
nodup_map_on (λ x _ y _ h, hf h)
theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) :=
quot.induction_on s $ λ l, nodup_filter p
@[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s :=
quot.induction_on s $ λ l, nodup_attach
theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) :=
quot.induction_on s (λ l H, nodup_pmap hf) H
instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) :=
quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable
theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s :=
quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d
theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) :=
nodup_of_le (erase_le _ _)
theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw nodup_erase_eq_filter b d; simp [and_comm]
theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a :=
by rw mem_erase_iff_of_nodup h; simp
theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂]
theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} :
nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) :=
quot.induction_on s $ assume l₁,
begin
choose f hf using assume a, quotient.exists_rep (t a),
rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a),
simpa using nodup_sigma
end
theorem nodup_filter_map (f : α → option β) {s : multiset α}
(H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') :
nodup s → nodup (filter_map f s) :=
quot.induction_on s $ λ l, nodup_filter_map H
theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _
theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) :=
nodup_of_le $ inter_le_left _ _
theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) :=
nodup_of_le $ inter_le_right _ _
@[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t :=
⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩,
λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact
max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩
@[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s :=
⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h),
quotient.induction_on s $ λ l h,
by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact
λ x sx y sy e,
(perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1
(quotient.exact e)⟩
@[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} :
nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) :=
have h₁ : ∀a, ∃l:list β, t a = l, from
assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩,
let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in
have t = λa, t' a, from funext h',
have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm,
quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd]
theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂
theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩
theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n :=
(le_iff_subset (nodup_range _)).trans range_subset
theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) :
a ∈ s - t ↔ a ∈ s ∧ a ∉ t :=
⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h',
by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le];
exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩,
λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩
section
variable [decidable_eq α]
/- erase_dup -/
/-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/
def erase_dup (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.erase_dup : multiset α))
(λ s t p, quot.sound (perm_erase_dup_of_perm p))
@[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl
@[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl
@[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_erase_dup
@[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s →
erase_dup (a::s) = erase_dup s :=
quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m
@[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s →
erase_dup (a::s) = a :: erase_dup s :=
quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m
theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _
theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s :=
subset_of_le $ erase_dup_le _
theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s :=
λ a, mem_erase_dup.2
@[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t :=
⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩
@[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t :=
⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩
@[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) :=
quot.induction_on s nodup_erase_dup
theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s :=
⟨λ e, e ▸ nodup_erase_dup s,
quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩
@[simp] theorem erase_dup_singleton {a : α} : erase_dup (a :: 0) = a :: 0 :=
erase_dup_eq_self.2 $ nodup_singleton _
theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s :=
⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩,
λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩
theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t :=
by simp [nodup_ext]
theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) :
erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext]
/- finset insert -/
/-- `ndinsert a s` is the lift of the list `insert` operation. This operation
does not respect multiplicities, unlike `cons`, but it is suitable as
an insert operation on `finset`. -/
def ndinsert (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.insert a : multiset α))
(λ s t p, quot.sound (perm_insert a p))
@[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl
@[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl
@[simp] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h
@[simp] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h
@[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, mem_insert_iff
@[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s :=
quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _
@[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s :=
mem_ndinsert.2 (or.inl rfl)
@[simp] theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s :=
mem_ndinsert.2 (or.inr h)
@[simp] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) :
card (ndinsert a s) = card s :=
by simp [h]
@[simp] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) :
card (ndinsert a s) = card s + 1 :=
by simp [h]
theorem erase_dup_cons {a : α} {s : multiset α} :
erase_dup (a::s) = ndinsert a (erase_dup s) :=
by by_cases a ∈ s; simp [h]
theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) :=
quot.induction_on s $ λ l, nodup_insert
theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t :=
⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩,
λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else
by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff,
← le_cons_of_not_mem h, cons_erase m]; exact l⟩
lemma attach_ndinsert (a : α) (s : multiset α) :
(s.ndinsert a).attach =
ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) :=
have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s,
(λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from
assume h, funext $ assume p, subtype.eq rfl,
have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩
(s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩),
begin
intros t ht,
by_cases a ∈ s,
{ rw [ndinsert_of_mem h] at ht,
subst ht,
rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] },
{ rw [ndinsert_of_not_mem h] at ht,
subst ht,
simp [attach_cons, h] }
end,
this _ rfl
@[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} :
disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t :=
iff.trans (by simp [disjoint]) disjoint_cons_left
@[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} :
disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t :=
disjoint_comm.trans $ by simp
/- finset union -/
/-- `ndunion s t` is the lift of the list `union` operation. This operation
does not respect multiplicities, unlike `s ∪ t`, but it is suitable as
a union operation on `finset`. (`s ∪ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndunion (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ perm_union p₁ p₂
@[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl
@[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, rfl
@[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union
theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _
theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _
theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u :=
multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt})
theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t :=
λ a h, mem_ndunion.2 $ or.inl h
theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t :=
(le_iff_subset d).2 $ subset_ndunion_left _ _
theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t :=
ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩
theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _
@[simp] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t :=
le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _)
theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _
/- finset inter -/
/-- `ndinter s t` is the lift of the list `∩` operation. This operation
does not respect multiplicities, unlike `s ∩ t`, but it is suitable as
an intersection operation on `finset`. (`s ∩ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndinter (s t : multiset α) : multiset α := filter (∈ t) s
@[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl
@[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl
@[simp] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) :
ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h]
@[simp] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) :
ndinter (a::s) t = ndinter s t := by simp [ndinter, h]
@[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t :=
mem_filter
theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) :=
nodup_filter _
theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u :=
by simp [ndinter, le_filter, subset_iff]
theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s :=
(le_ndinter.1 (le_refl _)).1
theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t :=
(le_ndinter.1 (le_refl _)).2
theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t :=
(le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _)
theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t :=
le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩
@[simp] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t :=
le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _)
theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
end
/- fold -/
section fold
variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op]
local notation a * b := op a b
include hc ha
/-- `fold op b s` folds a commutative associative operation `op` over
the multiset `s`. -/
def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc)
theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl
@[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl
theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b :=
(coe_foldr_swap op _ b l).trans $ by simp [hc.comm]
theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s :=
quot.induction_on s $ λ l, coe_fold_l _ _ _
@[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl
@[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α),
(a :: s).fold op b = a * s.fold op b := foldr_cons _ _
theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a :=
by simp [hc.comm]
theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) :=
by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl]
theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) :=
by rw [fold_cons'_right, hc.comm]
theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ :=
multiset.induction_on s₂
(by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op])
(by simp {contextual := tt}; cc)
theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp
theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) :
(s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ :=
multiset.induction_on s (by simp) (by simp {contextual := tt}; cc)
theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op']
{m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) :
(s.map m).fold op' (m b) = m (s.fold op b) :=
multiset.induction_on s (by simp) (by simp [hm] {contextual := tt})
theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) :
(s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ :=
by rw [← fold_add op, union_add_inter, fold_add op]
@[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) :
(erase_dup s).fold op b = s.fold op b :=
multiset.induction_on s (by simp) $ λ a s IH, begin
by_cases a ∈ s; simp [IH, h],
show fold op b s = op a (fold op b s),
rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent],
end
end fold
theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) :
∃ n : ℕ, s ≤ n • erase_dup s :=
⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin
rw count_smul, by_cases a ∈ s,
{ refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h),
have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a));
[simp [le_max_left], simpa [cons_erase h]] },
{ simp [count_eq_zero.2 h, nat.zero_le] }
end⟩
section sup
variables [semilattice_sup_bot α]
/-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/
def sup (s : multiset α) : α := s.fold (⊔) ⊥
@[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ :=
fold_zero _ _
@[simp] lemma sup_cons (a : α) (s : multiset α) :
(a :: s).sup = a ⊔ s.sup :=
fold_cons_left _ _ _ _
@[simp] lemma sup_singleton {a : α} : (a::0).sup = a := by simp
@[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup :=
eq.trans (by simp [sup]) (fold_add _ _ _ _ _)
variables [decidable_eq α]
@[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup :=
fold_erase_dup_idem _ _ _
@[simp] lemma sup_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp
@[simp] lemma sup_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp
@[simp] lemma sup_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).sup = a ⊔ s.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp
lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup :=
sup_le.1 (le_refl _) _ h
lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup :=
sup_le.2 $ assume b hb, le_sup (h hb)
end sup
section inf
variables [semilattice_inf_top α]
/-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/
def inf (s : multiset α) : α := s.fold (⊓) ⊤
@[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ :=
fold_zero _ _
@[simp] lemma inf_cons (a : α) (s : multiset α) :
(a :: s).inf = a ⊓ s.inf :=
fold_cons_left _ _ _ _
@[simp] lemma inf_singleton {a : α} : (a::0).inf = a := by simp
@[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf :=
eq.trans (by simp [inf]) (fold_add _ _ _ _ _)
variables [decidable_eq α]
@[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf :=
fold_erase_dup_idem _ _ _
@[simp] lemma inf_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp
@[simp] lemma inf_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp
@[simp] lemma inf_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).inf = a ⊓ s.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp
lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a :=
le_inf.1 (le_refl _) _ h
lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf :=
le_inf.2 $ assume b hb, inf_le (h hb)
end inf
section sort
variables (r : α → α → Prop) [decidable_rel r]
[is_trans α r] [is_antisymm α r] [is_total α r]
/-- `sort s` constructs a sorted list from the multiset `s`.
(Uses merge sort algorithm.) -/
def sort (s : multiset α) : list α :=
quot.lift_on s (merge_sort r) $ λ a b h,
eq_of_sorted_of_perm
((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm)
(sorted_merge_sort r _)
(sorted_merge_sort r _)
@[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl
@[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) :=
quot.induction_on s $ λ l, sorted_merge_sort r _
@[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s :=
quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _
@[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
by rw [← mem_coe, sort_eq]
end sort
instance [has_repr α] : has_repr (multiset α) :=
⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩
section sections
def sections (s : multiset (multiset α)) : multiset (multiset α) :=
multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a))
(assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap])
@[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 :=
rfl
@[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) :
sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) :=
rec_on_cons m s
lemma coe_sections : ∀(l : list (list α)),
sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) =
((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α))
| [] := rfl
| (a :: l) :=
begin
simp,
rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l],
simp [list.sections, (∘), list.bind]
end
@[simp] lemma sections_add (s t : multiset (multiset α)) :
sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) :=
multiset.induction_on s (by simp)
(assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm])
lemma mem_sections {s : multiset (multiset α)} :
∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a :=
multiset.induction_on s (by simp)
(assume a s ih a',
by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm])
lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} :
prod (s.map sum) = sum ((sections s).map prod) :=
multiset.induction_on s (by simp)
(assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right])
end sections
section pi
variables [decidable_eq α] {δ : α → Type*}
open function
def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' :=
λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h
def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) .
lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) :
pi.cons m a b f a h = b :=
dif_pos rfl
lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) :
pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) :=
dif_neg h
lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') :
pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) :=
begin
apply hfunext, { refl }, intros a'' _ h, subst h,
apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h,
by_cases h₁ : a'' = a; by_cases h₂ : a'' = a';
simp [*, pi.cons_same, pi.cons_ne] at *,
{ subst h₁, rw [pi.cons_same, pi.cons_same] },
{ subst h₂, rw [pi.cons_same, pi.cons_same] }
end
/-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/
def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) :=
m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b)
begin
intros a a' m n,
by_cases eq : a = a',
{ subst eq },
{ simp [map_bind, bind_bind (t a') (t a)],
apply bind_hcongr, { rw [cons_swap a a'] },
intros b hb,
apply bind_hcongr, { rw [cons_swap a a'] },
intros b' hb',
apply map_hcongr, { rw [cons_swap a a'] },
intros f hf,
exact pi.cons_swap eq }
end
@[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ :: 0 := rfl
@[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) :
pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) :=
rec_on_cons a m
lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) :
function.injective (pi.cons s a b) :=
assume f₁ f₂ eq, funext $ assume a', funext $ assume h',
have ne : a ≠ a', from assume h, hs $ h.symm ▸ h',
have a' ∈ a :: s, from mem_cons_of_mem h',
calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm]
... = pi.cons s a b f₂ a' this : by rw [eq]
... = f₂ a' h' : by rw [pi.cons_ne this ne.symm]
lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) :
card (pi m t) = prod (m.map $ λa, card (t a)) :=
multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt})
lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} :
nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) :=
multiset.induction_on s (assume _ _, nodup_singleton _)
begin
assume a s ih hs ht,
have has : a ∉ s, by simp at hs; exact hs.1,
have hs : nodup s, by simp at hs; exact hs.2,
simp,
split,
{ assume b hb,
from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') },
{ apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _),
from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq,
have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _),
by rw [eq],
neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) }
end
lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) :
∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) :=
begin
refine multiset.induction_on m (λ f, _) (λ a m ih f, _),
{ simpa using show f = pi.empty δ, by funext a ha; exact ha.elim },
simp, split,
{ rintro ⟨b, hb, f', hf', rfl⟩ a' ha',
rw [ih] at hf',
by_cases a' = a,
{ subst h, rwa [pi.cons_same] },
{ rw [pi.cons_ne _ h], apply hf' } },
{ intro hf,
refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha),
(ih _).2 (λ a' h', hf _ _), _⟩,
funext a' h',
by_cases a' = a,
{ subst h, rw [pi.cons_same] },
{ rw [pi.cons_ne _ h] } }
end
end pi
end multiset
namespace multiset
instance : functor multiset :=
{ map := @map }
instance : is_lawful_functor multiset :=
by refine { .. }; intros; simp
open is_lawful_traversable is_comm_applicative
variables {F : Type u_1 → Type u_1} [applicative F] [is_comm_applicative F]
variables {α' β' : Type u_1} (f : α' → F β')
def traverse : multiset α' → F (multiset β') :=
quotient.lift (functor.map coe ∘ traversable.traverse f)
begin
introv p, unfold function.comp,
induction p,
case perm.nil { refl },
case perm.skip {
have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) =
multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂),
{ rw [p_ih] },
simpa with functor_norm },
case perm.swap {
have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x =
(λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y,
{ rw [is_comm_applicative.commutative_map],
congr, funext a b l, simpa [flip] using perm.swap b a l },
simp [(∘), this] with functor_norm },
case perm.trans { simp [*] }
end
open functor
open traversable is_lawful_traversable
@[simp]
lemma lift_beta {α β : Type*} (x : list α) (f : list α → β)
(h : ∀ a b : list α, a ≈ b → f a = f b) :
quotient.lift f h (x : multiset α) = f x :=
quotient.lift_beta _ _ _
@[simp]
lemma map_comp_coe {α β} (h : α → β) :
functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) :=
by funext; simp [functor.map]
lemma id_traverse {α : Type*} (x : multiset α) :
traverse id.mk x = x :=
quotient.induction_on x
(by { intro, rw [traverse,quotient.lift_beta,function.comp],
simp, congr })
lemma comp_traverse {G H : Type* → Type*}
[applicative G] [applicative H]
[is_comm_applicative G] [is_comm_applicative H]
{α β γ : Type*}
(g : α → G β) (h : β → H γ) (x : multiset α) :
traverse (comp.mk ∘ functor.map h ∘ g) x =
comp.mk (functor.map (traverse h) (traverse g x)) :=
quotient.induction_on x
(by intro;
simp [traverse,comp_traverse] with functor_norm;
simp [(<$>),(∘)] with functor_norm)
lemma map_traverse {G : Type* → Type*}
[applicative G] [is_comm_applicative G]
{α β γ : Type*}
(g : α → G β) (h : β → γ)
(x : multiset α) :
functor.map (functor.map h) (traverse g x) =
traverse (functor.map h ∘ g) x :=
quotient.induction_on x
(by intro; simp [traverse] with functor_norm;
rw [comp_map,map_traverse])
lemma traverse_map {G : Type* → Type*}
[applicative G] [is_comm_applicative G]
{α β γ : Type*}
(g : α → β) (h : β → G γ)
(x : multiset α) :
traverse h (map g x) =
traverse (h ∘ g) x :=
quotient.induction_on x
(by intro; simp [traverse];
rw [← traversable.traverse_map h g];
[ refl, apply_instance ])
lemma naturality {G H : Type* → Type*}
[applicative G] [applicative H]
[is_comm_applicative G] [is_comm_applicative H]
(eta : applicative_transformation G H)
{α β : Type*} (f : α → G β) (x : multiset α) :
eta (traverse f x) = traverse (@eta _ ∘ f) x :=
quotient.induction_on x
(by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm)
section choose
variables (p : α → Prop) [decidable_pred p] (l : multiset α)
def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } :=
quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin
intros,
funext hp,
suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y,
{ apply all_equal },
{ rintros ⟨x, px⟩ ⟨y, py⟩,
rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩,
congr,
calc x = z : z_unique x px
... = y : (z_unique y py).symm }
end
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
end multiset
|
dae47b04c8afa859240464c5024227d4fbb68eef | 28be2ab6091504b6ba250b367205fb94d50ab284 | /src/game/world4/level8.lean | 77a634f6497d12488fcaf58e9f15f913c686a8b1 | [
"Apache-2.0"
] | permissive | postmasters/natural_number_game | 87304ac22e5e1c5ac2382d6e523d6914dd67a92d | 38a7adcdfdb18c49c87b37831736c8f15300d821 | refs/heads/master | 1,649,856,819,031 | 1,586,444,676,000 | 1,586,444,676,000 | 255,006,061 | 0 | 0 | Apache-2.0 | 1,586,664,599,000 | 1,586,664,598,000 | null | UTF-8 | Lean | false | false | 2,963 | lean | import game.world4.level7 -- hide
-- incantation for importing ring into framework -- hide
import tactic.ring -- hide
meta def nat_num_game.interactive.ring := tactic.interactive.ring -- hide
namespace mynat -- hide
def two_eq_succ_one : (2 : mynat) = succ 1 := rfl -- hide
/-
# Power World
-/
/-
## Level 8: `add_squared`
[final boss music]
You see something written on the stone dungeon wall:
```
begin
rw two_eq_succ_one,
rw one_eq_succ_zero,
repeat {rw pow_succ},
...
```
and you can't make out the last two lines because there's a kind
of thing in the way that will magically disappear
but only when you've beaten the boss.
-/
/- Theorem
For all naturals $a$ and $b$, we have
$$(a+b)^2=a^2+b^2+2ab.$$
-/
lemma add_squared (a b : mynat) :
(a + b) ^ (2 : mynat) = a ^ (2 : mynat) + b ^ (2 : mynat) + 2 * a * b :=
begin [nat_num_game]
rw two_eq_succ_one,
rw one_eq_succ_zero,
repeat {rw pow_succ},
repeat {rw pow_zero},
ring,
end
/-
As the boss lies smouldering, you notice on the dungeon wall that
<a href="https://twitter.com/XenaProject/status/1190453646904958976?s=20/" target="blank">
two more lines of code are now visible under the first three...</a> (Twitter.com)
I just beat this level with 27 rewrites followed by a `refl`.
Can you do any better? If you beat it then well done. Do you
fancy doing $(a+b)^3$ now? You might want to read
<a href="https://xenaproject.wordpress.com/2018/06/13/ab3/" target="blank">
this Xena Project blog post</a> before you start though.
-/
/-
If you got this far -- very well done! If you only learnt the three
tactics `rw`, `induction` and `refl` then there are now more tactics to
learn; go back to the main menu and choose Function World.
The main thing we really want to impress upon people is that we believe
that *all of pure mathematics* can be done in this new way.
A system called Coq (which is very like Lean) has
<a href="https://hal.inria.fr/hal-00816699" target="blank">
checked the proof of the Feit-Thompson theorem</a> (hundreds of pages of
group theory) and Lean has a
<a href="https://leanprover-community.github.io/lean-perfectoid-spaces/"
target="blank">
definition of perfectoid spaces</a> (a very complex modern
mathematical structure). I believe that these systems will one day
cause a paradigm shift in the way mathematics is done, but first we need
to build what we know, or at least build enough to state what we
mathematicians believe. If you want to get involved, come and join
us at the <a href="https://leanprover.zulipchat.com" target="blank">Zulip Lean chat</a>.
The #new members stream is a great place to start asking questions.
To come (possibly): the real number game, the group theory game,
the integer game, the natural number game 2,... . Alternatively
[see here](https://github.com/ImperialCollegeLondon/natural_number_game/blob/master/WHATS_NEXT.md)
for some more ideas about what to do next.
-/
end mynat -- hide
|
adf42de627136b5a5880b90700efddddcc2b1ae2 | 1f6fe2f89976b14a4567ab298c35792b21f2e50b | /coind_colim.hlean | 85ac54375e9de4a5ec4ef11616788a7b8a058e4c | [
"Apache-2.0"
] | permissive | jonas-frey/Spectral | e5c1c2f7bcac26aa55f7b1e041a81272a146198d | 72d521091525a4bc9a31cac859840efe9461cf66 | refs/heads/master | 1,610,235,743,345 | 1,505,417,795,000 | 1,505,417,795,000 | 102,653,342 | 0 | 0 | null | 1,504,728,483,000 | 1,504,728,483,000 | null | UTF-8 | Lean | false | false | 6,371 | hlean | -- author: Floris van Doorn
import .colim
open nat seq_colim seq_colim.ops eq equiv is_equiv is_trunc function
namespace seq_colim
variables {A : ℕ → Type} {f : seq_diagram A}
definition ι0 [reducible] : A 0 → seq_colim f :=
ι f
variable (f)
definition ι0' [reducible] : A 0 → seq_colim f :=
ι f
definition glue0 (a : A 0) : shift_down f (ι0 (f a)) = ι f a :=
glue f a
definition rec_coind_point {P : Π⦃A : ℕ → Type⦄ (f : seq_diagram A), seq_colim f → Type}
(P0 : Π⦃A⦄ (f : seq_diagram A) (a : A 0), P f (ι0 a))
(Ps : Π⦃A⦄ (f : seq_diagram A) (x : seq_colim (shift_diag f)),
P (shift_diag f) x → P f (shift_down f x))
(Pe : Π⦃A⦄ (f : seq_diagram A) (a : A 0),
pathover (P f) (Ps f (ι0 (f a)) !P0) (proof glue f a qed) (P0 f a))
(n : ℕ) : Π{A : ℕ → Type} {f : seq_diagram A} (a : A n), P f (ι f a) :=
begin
induction n with n IH: intro A f a,
{ exact P0 f a },
{ exact Ps f (ι _ a) (IH a) }
end
definition rec_coind_point_succ {P : Π⦃A : ℕ → Type⦄ (f : seq_diagram A), seq_colim f → Type}
(P0 : Π⦃A⦄ (f : seq_diagram A) (a : A 0), P f (ι0 a))
(Ps : Π⦃A⦄ (f : seq_diagram A) (x : seq_colim (shift_diag f)),
P (shift_diag f) x → P f (shift_down f x))
(Pe : Π⦃A⦄ (f : seq_diagram A) (a : A 0),
pathover (P f) (Ps f (ι0 (f a)) !P0) _ (P0 f a))
(n : ℕ) {A : ℕ → Type} {f : seq_diagram A} (a : A (succ n)) :
rec_coind_point P0 Ps Pe (succ n) a = Ps f (ι _ a) (rec_coind_point P0 Ps Pe n a) :=
by reflexivity
definition rec_coind {P : Π⦃A : ℕ → Type⦄ (f : seq_diagram A), seq_colim f → Type}
(P0 : Π⦃A⦄ (f : seq_diagram A) (a : A 0), P f (ι0 a))
(Ps : Π⦃A⦄ (f : seq_diagram A) (x : seq_colim (shift_diag f)),
P (shift_diag f) x → P f (shift_down f x))
(Pe : Π⦃A⦄ (f : seq_diagram A) (a : A 0),
pathover (P f) (Ps f (ι0 (f a)) !P0) (proof glue f a qed) (P0 f a))
{A : ℕ → Type} {f : seq_diagram A} (x : seq_colim f) : P f x :=
begin
induction x,
{ exact rec_coind_point P0 Ps Pe n a },
{ revert A f a, induction n with n IH: intro A f a,
{ exact Pe f a },
{ rewrite [rec_coind_point_succ _ _ _ n, rec_coind_point_succ],
note p := IH _ (shift_diag f) a,
refine change_path _ (pathover_ap _ _ (apo (Ps f) p)),
exact !elim_glue
}},
end
definition rec_coind_pt2 {P : Π⦃A : ℕ → Type⦄ (f : seq_diagram A), seq_colim f → Type}
(P0 : Π⦃A⦄ (f : seq_diagram A) (a : A 0), P f (ι0 a))
(Ps : Π⦃A⦄ (f : seq_diagram A) (x : seq_colim (shift_diag f)),
P (shift_diag f) x → P f (shift_down f x))
(Pe : Π⦃A⦄ (f : seq_diagram A) (a : A 0),
pathover (P f) (Ps f (ι0 (f a)) !P0) _ (P0 f a))
{A : ℕ → Type} {f : seq_diagram A} (x : seq_colim (shift_diag f))
: rec_coind P0 Ps Pe (shift_down f x) = Ps f x (rec_coind P0 Ps Pe x) :=
begin
induction x,
{ reflexivity },
{ apply eq_pathover_dep,
apply hdeg_squareover, esimp,
refine apd_compose2 (rec_coind P0 Ps Pe) _ _ ⬝ _ ⬝ (apd_compose1 (Ps f) _ _)⁻¹,
exact sorry
--refine ap (λx, pathover_of_pathover_ap _ _ (x)) _ ⬝ _ ,
}
end
definition elim_coind_point {P : Π⦃A : ℕ → Type⦄ (f : seq_diagram A), Type}
(P0 : Π⦃A⦄ (f : seq_diagram A) (a : A 0), P f)
(Ps : Π⦃A⦄ (f : seq_diagram A) (x : seq_colim (shift_diag f)), P (shift_diag f) → P f)
(Pe : Π⦃A⦄ (f : seq_diagram A) (a : A 0), Ps f (ι0 (f a)) (P0 _ (f a)) = P0 f a)
(n : ℕ) : Π{A : ℕ → Type} (f : seq_diagram A) (a : A n), P f :=
begin
induction n with n IH: intro A f a,
{ exact P0 f a },
{ exact Ps f (ι _ a) (IH _ a) }
end
definition elim_coind_point_succ {P : Π⦃A : ℕ → Type⦄ (f : seq_diagram A), Type}
(P0 : Π⦃A⦄ (f : seq_diagram A) (a : A 0), P f)
(Ps : Π⦃A⦄ (f : seq_diagram A) (x : seq_colim (shift_diag f)), P (shift_diag f) → P f)
(Pe : Π⦃A⦄ (f : seq_diagram A) (a : A 0), Ps f (ι0 (f a)) (P0 _ (f a)) = P0 f a)
(n : ℕ) {A : ℕ → Type} {f : seq_diagram A} (a : A (succ n)) :
elim_coind_point P0 Ps Pe (succ n) f a =
Ps f (ι _ a) (elim_coind_point P0 Ps Pe n (shift_diag f) a) :=
by reflexivity
definition elim_coind_path {P : Π⦃A : ℕ → Type⦄ (f : seq_diagram A), Type}
(P0 : Π⦃A⦄ (f : seq_diagram A) (a : A 0), P f)
(Ps : Π⦃A⦄ (f : seq_diagram A) (x : seq_colim (shift_diag f)), P (shift_diag f) → P f)
(Pe : Π⦃A⦄ (f : seq_diagram A) (a : A 0), Ps f (ι0 (f a)) (P0 _ (f a)) = P0 f a)
(n : ℕ) : Π{A : ℕ → Type} (f : seq_diagram A) (a : A n),
elim_coind_point P0 Ps Pe (succ n) f (f a) = elim_coind_point P0 Ps Pe n f a :=
begin
induction n with n IH: intro A f a,
{ exact Pe f a },
{ rewrite [elim_coind_point_succ _ _ _ n, elim_coind_point_succ],
note p := IH (shift_diag f) a,
refine ap011 (Ps f) !glue p }
end
definition elim_coind {P : Π⦃A : ℕ → Type⦄ (f : seq_diagram A), Type}
(P0 : Π⦃A⦄ (f : seq_diagram A) (a : A 0), P f)
(Ps : Π⦃A⦄ (f : seq_diagram A) (x : seq_colim (shift_diag f)), P (shift_diag f) → P f)
(Pe : Π⦃A⦄ (f : seq_diagram A) (a : A 0), Ps f (ι0 (f a)) (P0 _ (f a)) = P0 f a)
{A : ℕ → Type} {f : seq_diagram A} (x : seq_colim f) : P f :=
begin
induction x,
{ exact elim_coind_point P0 Ps Pe n f a },
{ exact elim_coind_path P0 Ps Pe n f a },
end
definition elim_coind_pt2 {P : Π⦃A : ℕ → Type⦄ (f : seq_diagram A), Type}
(P0 : Π⦃A⦄ (f : seq_diagram A) (a : A 0), P f)
(Ps : Π⦃A⦄ (f : seq_diagram A) (x : seq_colim (shift_diag f)), P (shift_diag f) → P f)
(Pe : Π⦃A⦄ (f : seq_diagram A) (a : A 0), Ps f (ι0 (f a)) (P0 _ (f a)) = P0 f a)
{A : ℕ → Type} {f : seq_diagram A} (x : seq_colim (shift_diag f))
: elim_coind P0 Ps Pe (shift_down f x) = Ps f x (elim_coind P0 Ps Pe x) :=
begin
induction x,
{ reflexivity },
{ apply eq_pathover, apply hdeg_square,
refine ap_compose (elim_coind P0 Ps Pe) _ _ ⬝ _ ⬝ (ap_eq_ap011 (Ps f) _ _ _)⁻¹,
refine ap02 _ !elim_glue ⬝ !elim_glue ⬝ ap011 (ap011 _) !ap_id⁻¹ !elim_glue⁻¹ }
end
end seq_colim
|
4843904b14c0ecbbe60663da3efd436f32d9d3e1 | 07c6143268cfb72beccd1cc35735d424ebcb187b | /archive/cubing_a_cube.lean | ae6bb4c7c8f6393bf37d57cc450686b82a3b2540 | [
"Apache-2.0"
] | permissive | khoek/mathlib | bc49a842910af13a3c372748310e86467d1dc766 | aa55f8b50354b3e11ba64792dcb06cccb2d8ee28 | refs/heads/master | 1,588,232,063,837 | 1,587,304,803,000 | 1,587,304,803,000 | 176,688,517 | 0 | 0 | Apache-2.0 | 1,553,070,585,000 | 1,553,070,585,000 | null | UTF-8 | Lean | false | false | 23,026 | lean | /-
Copyright (c) 2019 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
-/
import data.real.basic data.set.disjointed data.set.intervals set_theory.cardinal
/-!
Proof that a cube (in dimension n ≥ 3) cannot be cubed:
There does not exist a partition of a cube into finitely many smaller cubes (at least two)
of different sizes.
We follow the proof described here: http://www.alaricstephen.com/main-featured/2017/9/28/cubing-a-cube-proof
-/
open real set function fin
noncomputable theory
variable {n : ℕ}
/-- Given three intervals `I, J, K` such that `J ⊂ I`,
neither endpoint of `J` coincides with an endpoint of `I`, `¬ (K ⊆ J)` and
`K` does not lie completely to the left nor completely to the right of `J`.
Then `I ∩ K \ J` is nonempty. -/
lemma Ico_lemma {α} [decidable_linear_order α] {x₁ x₂ y₁ y₂ z₁ z₂ w : α}
(h₁ : x₁ < y₁) (hy : y₁ < y₂) (h₂ : y₂ < x₂)
(hz₁ : z₁ ≤ y₂) (hz₂ : y₁ ≤ z₂) (hw : w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂) :
∃w, w ∈ Ico x₁ x₂ ∧ w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂ :=
begin
simp at hw,
refine ⟨max x₁ (min w y₂), _, _, _⟩,
{ simp [le_refl, lt_trans h₁ (lt_trans hy h₂), h₂] },
{ simp [lt_irrefl, not_le_of_lt h₁], intros, apply hw.1, assumption },
{ simp [hw.2.1, hw.2.2, hz₁, lt_of_lt_of_le h₁ hz₂] at ⊢ }
end
/-- A (hyper)-cube (in standard orientation) is a vector `b` consisting of the bottom-left point
of the cube, a width `w` and a proof that `w > 0`. We use functions from `fin n` to denote vectors.
-/
structure cube (n : ℕ) : Type :=
(b : fin n → ℝ) -- bottom-left coordinate
(w : ℝ) -- width
(hw : 0 < w)
namespace cube
lemma hw' (c : cube n) : 0 ≤ c.w := le_of_lt c.hw
/-- The j-th side of a cube is the half-open interval `[b j, b j + w)` -/
def side (c : cube n) (j : fin n) : set ℝ :=
Ico (c.b j) (c.b j + c.w)
@[simp] lemma b_mem_side (c : cube n) (j : fin n) : c.b j ∈ c.side j :=
by simp [side, cube.hw, le_refl]
def to_set (c : cube n) : set (fin n → ℝ) :=
{ x | ∀j, x j ∈ side c j }
def to_set_subset {c c' : cube n} : c.to_set ⊆ c'.to_set ↔ ∀j, c.side j ⊆ c'.side j :=
begin
split, intros h j x hx,
let f : fin n → ℝ := λ j', if j' = j then x else c.b j',
have : f ∈ c.to_set,
{ intro j', by_cases hj' : j' = j; simp [f, hj', if_pos, if_neg, hx] },
convert h this j, { simp [f, if_pos] },
intros h f hf j, exact h j (hf j)
end
def to_set_disjoint {c c' : cube n} : disjoint c.to_set c'.to_set ↔
∃j, disjoint (c.side j) (c'.side j) :=
begin
split, intros h, classical, by_contra h',
simp only [not_disjoint_iff, classical.skolem, not_exists] at h',
cases h' with f hf,
apply not_disjoint_iff.mpr ⟨f, _, _⟩ h; intro j, exact (hf j).1, exact (hf j).2,
rintro ⟨j, hj⟩, rw [set.disjoint_iff], rintros f ⟨h1f, h2f⟩,
apply not_disjoint_iff.mpr ⟨f j, h1f j, h2f j⟩ hj
end
lemma b_mem_to_set (c : cube n) : c.b ∈ c.to_set :=
by simp [to_set]
protected def tail (c : cube (n+1)) : cube n :=
⟨tail c.b, c.w, c.hw⟩
lemma side_tail (c : cube (n+1)) (j : fin n) : c.tail.side j = c.side j.succ := rfl
def bottom (c : cube (n+1)) : set (fin (n+1) → ℝ) :=
{ x | x 0 = c.b 0 ∧ tail x ∈ c.tail.to_set }
lemma b_mem_bottom (c : cube (n+1)) : c.b ∈ c.bottom :=
by simp [bottom, to_set, side, cube.hw, le_refl, cube.tail]
def xm (c : cube (n+1)) : ℝ :=
c.b 0 + c.w
lemma b_lt_xm (c : cube (n+1)) : c.b 0 < c.xm := by simp [xm, hw]
lemma b_ne_xm (c : cube (n+1)) : c.b 0 ≠ c.xm := ne_of_lt c.b_lt_xm
def shift_up (c : cube (n+1)) : cube (n+1) :=
⟨cons c.xm $ tail c.b, c.w, c.hw⟩
@[simp] lemma tail_shift_up (c : cube (n+1)) : c.shift_up.tail = c.tail :=
by simp [shift_up, cube.tail]
@[simp] lemma head_shift_up (c : cube (n+1)) : c.shift_up.b 0 = c.xm := rfl
def unit_cube : cube n :=
⟨λ _, 0, 1, by norm_num⟩
@[simp] lemma side_unit_cube {j : fin n} : unit_cube.side j = Ico 0 1 :=
by norm_num [unit_cube, side]
end cube
open cube
variables {ι : Type} [fintype ι] {cs : ι → cube (n+1)} {i i' : ι}
/-- A finite family of (at least 2) cubes partitioning the unit cube with different sizes -/
def correct (cs : ι → cube n) : Prop :=
pairwise (disjoint on (cube.to_set ∘ cs)) ∧
(⋃(i : ι), (cs i).to_set) = unit_cube.to_set ∧
injective (cube.w ∘ cs) ∧
2 ≤ cardinal.mk ι ∧
3 ≤ n
variable (h : correct cs)
include h
lemma to_set_subset_unit_cube {i} : (cs i).to_set ⊆ unit_cube.to_set :=
by { rw [←h.2.1], exact subset_Union _ i }
lemma side_subset {i j} : (cs i).side j ⊆ Ico 0 1 :=
by { have := to_set_subset_unit_cube h, rw [to_set_subset] at this,
convert this j, norm_num [unit_cube] }
lemma zero_le_of_mem_side {i j x} (hx : x ∈ (cs i).side j) : 0 ≤ x :=
(side_subset h hx).1
lemma zero_le_of_mem {i p} (hp : p ∈ (cs i).to_set) (j) : 0 ≤ p j :=
zero_le_of_mem_side h (hp j)
lemma zero_le_b {i j} : 0 ≤ (cs i).b j :=
zero_le_of_mem h (cs i).b_mem_to_set j
lemma b_add_w_le_one {j} : (cs i).b j + (cs i).w ≤ 1 :=
by { have := side_subset h, rw [side, Ico_subset_Ico_iff] at this, convert this.2, simp [hw] }
/-- The width of any cube in the partition cannot be 1. -/
lemma w_ne_one (i : ι) : (cs i).w ≠ 1 :=
begin
intro hi,
have := h.2.2.2.1, rw [cardinal.two_le_iff' i] at this, cases this with i' hi',
let p := (cs i').b,
have hp : p ∈ (cs i').to_set := (cs i').b_mem_to_set,
have h2p : p ∈ (cs i).to_set,
{ intro j, split,
transitivity (0 : ℝ),
{ rw [←add_le_add_iff_right (1 : ℝ)], convert b_add_w_le_one h, rw hi, rw zero_add },
apply zero_le_b h, apply lt_of_lt_of_le (side_subset h $ (cs i').b_mem_side j).2,
simp [hi, zero_le_b h] },
apply not_disjoint_iff.mpr ⟨p, hp, h2p⟩,
apply h.1, exact hi'.symm
end
/-- The top of a cube (which is the bottom of the cube shifted up by its width) must be covered by
bottoms of (other) cubes in the family. -/
lemma shift_up_bottom_subset_bottoms (hc : (cs i).xm ≠ 1) :
(cs i).shift_up.bottom ⊆ ⋃(i : ι), (cs i).bottom :=
begin
intros p hp, cases hp with hp0 hps, rw [tail_shift_up] at hps,
have : p ∈ (unit_cube : cube (n+1)).to_set,
{ simp only [to_set, forall_fin_succ, hp0, side_unit_cube, mem_set_of_eq, mem_Ico,
head_shift_up], refine ⟨⟨_, _⟩, _⟩,
{ rw [←zero_add (0 : ℝ)], apply add_le_add, apply zero_le_b h, apply (cs i).hw' },
{ exact lt_of_le_of_ne (b_add_w_le_one h) hc },
intro j, exact side_subset h (hps j) },
rw [←h.2.1] at this, rcases this with ⟨_, ⟨i', rfl⟩, hi'⟩,
rw [mem_Union], use i', refine ⟨_, λ j, hi' j.succ⟩,
have : i ≠ i', { rintro rfl, apply not_le_of_lt (hi' 0).2, rw [hp0], refl },
have := h.1 i i' this, rw [on_fun, to_set_disjoint, exists_fin_succ] at this,
rcases this with h0|⟨j, hj⟩,
rw [hp0], symmetry, apply eq_of_Ico_disjoint h0 (by simp [hw]) _,
convert hi' 0, rw [hp0], refl,
exfalso, apply not_disjoint_iff.mpr ⟨tail p j, hps j, hi' j.succ⟩ hj
end
omit h
/-- A valley is a square on which cubes in the family of cubes are placed, so that the cubes
completely cover the valley and none of those cubes is partially outside the square.
We also require that no cube on it has the same size as the valley (so that there are at least
two cubes on the valley).
This is the main concept in the formalization.
We prove that the smallest cube on a valley has another valley on the top of it, which
gives an infinite sequence of cubes in the partition, which contradicts the finiteness.
A valley is characterized by a cube `c` (which is not a cube in the family cs) by considering
the bottom face of `c`. -/
def valley (cs : ι → cube (n+1)) (c : cube (n+1)) : Prop :=
c.bottom ⊆ (⋃(i : ι), (cs i).bottom) ∧
(∀i, (cs i).b 0 = c.b 0 → (∃x, x ∈ (cs i).tail.to_set ∩ c.tail.to_set) →
(cs i).tail.to_set ⊆ c.tail.to_set) ∧
∀(i : ι), (cs i).b 0 = c.b 0 → (cs i).w ≠ c.w
variables {c : cube (n+1)} (v : valley cs c)
/-- The bottom of the unit cube is a valley -/
lemma valley_unit_cube (h : correct cs) : valley cs unit_cube :=
begin
refine ⟨_, _, _⟩,
{ intro v, simp [bottom],
intros h0 hv,
have : v ∈ (unit_cube : cube (n+1)).to_set,
{ dsimp [to_set], rw [forall_fin_succ, h0], split, norm_num [side, unit_cube], exact hv },
rw [←h.2.1] at this, rcases this with ⟨_, ⟨i, rfl⟩, hi⟩,
use i,
split, { apply le_antisymm, rw h0, exact zero_le_b h, exact (hi 0).1 },
intro j, exact hi _ },
{ intros i hi h', rw to_set_subset, intro j, convert side_subset h, simp [side_tail] },
{ intros i hi, exact w_ne_one h i }
end
/-- the cubes which lie in the valley `c` -/
def bcubes (cs : ι → cube (n+1)) (c : cube (n+1)) : set ι :=
{ i : ι | (cs i).b 0 = c.b 0 ∧ (cs i).tail.to_set ⊆ c.tail.to_set }
/-- A cube which lies on the boundary of a valley in dimension `j` -/
def on_boundary (hi : i ∈ bcubes cs c) (j : fin n) : Prop :=
c.b j.succ = (cs i).b j.succ ∨ (cs i).b j.succ + (cs i).w = c.b j.succ + c.w
lemma tail_sub (hi : i ∈ bcubes cs c) : ∀j, (cs i).tail.side j ⊆ c.tail.side j :=
by { rw [←to_set_subset], exact hi.2 }
lemma bottom_mem_side (hi : i ∈ bcubes cs c) : c.b 0 ∈ (cs i).side 0 :=
by { convert b_mem_side (cs i) _ using 1, rw hi.1 }
lemma b_le_b (hi : i ∈ bcubes cs c) (j : fin n) : c.b j.succ ≤ (cs i).b j.succ :=
(tail_sub hi j $ b_mem_side _ _).1
lemma t_le_t (hi : i ∈ bcubes cs c) (j : fin n) :
(cs i).b j.succ + (cs i).w ≤ c.b j.succ + c.w :=
begin
have h' := tail_sub hi j, dsimp only [side] at h', rw [Ico_subset_Ico_iff] at h',
exact h'.2, simp [hw]
end
include h v
/-- Every cube in the valley must be smaller than it -/
lemma w_lt_w (hi : i ∈ bcubes cs c) : (cs i).w < c.w :=
begin
apply lt_of_le_of_ne _ (v.2.2 i hi.1),
have j : fin n := ⟨1, nat.le_of_succ_le_succ h.2.2.2.2⟩,
rw [←add_le_add_iff_left ((cs i).b j.succ)],
apply le_trans (t_le_t hi j), rw [add_le_add_iff_right], apply b_le_b hi,
end
open cardinal
/-- There are at least two cubes in a valley -/
lemma two_le_mk_bcubes : 2 ≤ cardinal.mk (bcubes cs c) :=
begin
rw [two_le_iff],
rcases v.1 c.b_mem_bottom with ⟨_, ⟨i, rfl⟩, hi⟩,
have h2i : i ∈ bcubes cs c := ⟨hi.1.symm, v.2.1 i hi.1.symm ⟨tail c.b, hi.2, λ j, c.b_mem_side j.succ⟩⟩,
let j : fin (n+1) := ⟨2, h.2.2.2.2⟩,
have hj : 0 ≠ j := by { intro h', have := congr_arg fin.val h', contradiction },
let p : fin (n+1) → ℝ := λ j', if j' = j then c.b j + (cs i).w else c.b j',
have hp : p ∈ c.bottom,
{ split, { simp only [bottom, p, if_neg hj] },
intro j', simp [tail, side_tail],
by_cases hj' : j'.succ = j,
{ simp [p, -add_comm, if_pos, side, hj', hw', w_lt_w h v h2i] },
{ simp [p, -add_comm, if_neg hj'] }},
rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩,
have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩,
refine ⟨⟨i, h2i⟩, ⟨i', h2i'⟩, _⟩,
intro hii', cases congr_arg subtype.val hii',
apply not_le_of_lt (hi'.2 ⟨1, nat.le_of_succ_le_succ h.2.2.2.2⟩).2,
simp only [-add_comm, tail, cube.tail, p], rw [if_pos], simp [-add_comm],
exact (hi.2 _).1, refl
end
/-- There is a cube in the valley -/
lemma nonempty_bcubes : (bcubes cs c).nonempty :=
begin
rw [←set.ne_empty_iff_nonempty], intro h', have := two_le_mk_bcubes h v, rw h' at this,
apply not_lt_of_le this, rw mk_emptyc, norm_cast, norm_num
end
/-- There is a smallest cube in the valley -/
lemma exists_mi : ∃(i : ι), i ∈ bcubes cs c ∧ ∀(i' ∈ bcubes cs c),
(cs i).w ≤ (cs i').w :=
by simpa using (bcubes cs c).exists_min_image (λ i, (cs i).w) (finite.of_fintype _) (nonempty_bcubes h v)
/-- We let `mi` be the (index for the) smallest cube in the valley `c` -/
def mi : ι := classical.some $ exists_mi h v
variables {h v}
lemma mi_mem_bcubes : mi h v ∈ bcubes cs c :=
(classical.some_spec $ exists_mi h v).1
lemma mi_minimal (hi : i ∈ bcubes cs c) : (cs $ mi h v).w ≤ (cs i).w :=
(classical.some_spec $ exists_mi h v).2 i hi
lemma mi_strict_minimal (hii' : mi h v ≠ i) (hi : i ∈ bcubes cs c) :
(cs $ mi h v).w < (cs i).w :=
by { apply lt_of_le_of_ne (mi_minimal hi), apply h.2.2.1.ne, apply hii' }
/-- The top of `mi` cannot be 1, since there is a larger cube in the valley -/
lemma mi_xm_ne_one : (cs $ mi h v).xm ≠ 1 :=
begin
apply ne_of_lt, rcases (two_le_iff' _).mp (two_le_mk_bcubes h v) with ⟨⟨i, hi⟩, h2i⟩,
swap, exact ⟨mi h v, mi_mem_bcubes⟩,
apply lt_of_lt_of_le _ (b_add_w_le_one h), exact i, exact 0,
rw [xm, mi_mem_bcubes.1, hi.1, _root_.add_lt_add_iff_left],
apply mi_strict_minimal _ hi, intro h', apply h2i, rw subtype.ext, exact h'
end
/-- If `mi` lies on the boundary of the valley in dimension j, then this lemma expresses that all
other cubes on the same boundary extend further from the boundary.
More precisely, there is a j-th coordinate `x : ℝ` in the valley, but not in `mi`,
such that every cube that shares a (particular) j-th coordinate with `mi` also contains j-th
coordinate `x` -/
lemma smallest_on_boundary {j} (bi : on_boundary (mi_mem_bcubes : mi h v ∈ _) j) :
∃(x : ℝ), x ∈ c.side j.succ \ (cs $ mi h v).side j.succ ∧
∀{{i'}} (hi' : i' ∈ bcubes cs c), i' ≠ mi h v →
(cs $ mi h v).b j.succ ∈ (cs i').side j.succ → x ∈ (cs i').side j.succ :=
begin
let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes,
cases bi,
{ refine ⟨(cs i).b j.succ + (cs i).w, ⟨_, _⟩, _⟩,
{ simp [side, bi, hw', w_lt_w h v hi] },
{ intro h', simpa [i, lt_irrefl] using h'.2 },
intros i' hi' i'_i h2i', split,
apply le_trans h2i'.1, { simp [hw'] },
apply lt_of_lt_of_le (add_lt_add_left (mi_strict_minimal i'_i.symm hi') _),
simp [bi.symm, b_le_b hi'] },
let s := bcubes cs c \ { i },
have hs : s.nonempty,
{ rcases (two_le_iff' (⟨i, hi⟩ : bcubes cs c)).mp (two_le_mk_bcubes h v) with ⟨⟨i', hi'⟩, h2i'⟩,
refine ⟨i', hi', _⟩, simp only [mem_singleton_iff], intro h, apply h2i', simp [h] },
rcases set.exists_min_image s (w ∘ cs) (finite.of_fintype _) hs with ⟨i', ⟨hi', h2i'⟩, h3i'⟩,
rw [mem_singleton_iff] at h2i',
let x := c.b j.succ + c.w - (cs i').w,
have hx : x < (cs i).b j.succ,
{ dsimp only [x], rw [←bi, add_sub_assoc, add_lt_iff_neg_left, sub_lt_zero],
apply mi_strict_minimal (ne.symm h2i') hi' },
refine ⟨x, ⟨_, _⟩, _⟩,
{ simp only [side, x, -add_comm, -add_assoc, neg_lt_zero, hw, add_lt_iff_neg_left, and_true,
mem_Ico, sub_eq_add_neg],
rw [add_assoc, le_add_iff_nonneg_right, ←sub_eq_add_neg, sub_nonneg],
apply le_of_lt (w_lt_w h v hi') },
{ simp only [side, not_and_distrib, not_lt, add_comm, not_le, mem_Ico], left, exact hx },
intros i'' hi'' h2i'' h3i'', split, swap, apply lt_trans hx h3i''.2,
simp only [x], rw [le_sub_iff_add_le],
refine le_trans _ (t_le_t hi'' j), rw [add_le_add_iff_left], apply h3i' i'' ⟨hi'', _⟩,
simp [mem_singleton, h2i'']
end
variables (h v)
/-- `mi` cannot lie on the boundary of the valley. Otherwise, the cube adjacent to it in the `j`-th
direction will intersect one of the neighbouring cubes on the same boundary as `mi`. -/
lemma mi_not_on_boundary (j : fin n) : ¬on_boundary (mi_mem_bcubes : mi h v ∈ _) j :=
begin
let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes,
rcases (two_le_iff' j).mp _ with ⟨j', hj'⟩, swap,
{ rw [mk_fin, ←nat.cast_two, nat_cast_le], apply nat.le_of_succ_le_succ h.2.2.2.2 },
intro hj,
rcases smallest_on_boundary hj with ⟨x, ⟨hx, h2x⟩, h3x⟩,
let p : fin (n+1) → ℝ := cons (c.b 0) (λ j₂, if j₂ = j then x else (cs i).b j₂.succ),
have hp : p ∈ c.bottom,
{ simp [bottom, p, to_set, tail, side_tail], intro j₂,
by_cases hj₂ : j₂ = j, simp [hj₂, hx],
simp [hj₂], apply tail_sub hi, apply b_mem_side },
rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩,
have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩,
have i_i' : i ≠ i', { rintro rfl, simpa [p, side_tail, i, h2x] using hi'.2 j },
have : nonempty ↥((cs i').tail.side j' \ (cs i).tail.side j'),
{ apply nonempty_Ico_sdiff, apply mi_strict_minimal i_i' h2i', apply hw },
rcases this with ⟨⟨x', hx'⟩⟩,
let p' : fin (n+1) → ℝ :=
cons (c.b 0) (λ j₂, if j₂ = j' then x' else (cs i).b j₂.succ),
have hp' : p' ∈ c.bottom,
{ simp [bottom, p', to_set, tail, side_tail], intro j₂,
by_cases hj₂ : j₂ = j', simp [hj₂], apply tail_sub h2i', apply hx'.1,
simp [hj₂], apply tail_sub hi, apply b_mem_side },
rcases v.1 hp' with ⟨_, ⟨i'', rfl⟩, hi''⟩,
have h2i'' : i'' ∈ bcubes cs c := ⟨hi''.1.symm, v.2.1 i'' hi''.1.symm ⟨tail p', hi''.2, hp'.2⟩⟩,
have i'_i'' : i' ≠ i'',
{ rintro ⟨⟩,
have : (cs i).b ∈ (cs i').to_set,
{ simp [to_set, forall_fin_succ, hi.1, bottom_mem_side h2i'],
intro j₂, by_cases hj₂ : j₂ = j, simpa [side_tail, p', hj', hj₂] using hi''.2 j,
simpa [hj₂] using hi'.2 j₂ },
apply not_disjoint_iff.mpr ⟨(cs i).b, (cs i).b_mem_to_set, this⟩ (h.1 i i' i_i') },
have i_i'' : i ≠ i'', { intro h, induction h, simpa [hx'.2] using hi''.2 j' },
apply not.elim _ (h.1 i' i'' i'_i''),
simp only [on_fun, to_set_disjoint, not_disjoint_iff, forall_fin_succ, not_exists, comp_app],
refine ⟨⟨c.b 0, bottom_mem_side h2i', bottom_mem_side h2i''⟩, _⟩,
intro j₂,
by_cases hj₂ : j₂ = j,
{ cases hj₂, refine ⟨x, _, _⟩,
{ convert hi'.2 j, simp [p] },
apply h3x h2i'' i_i''.symm, convert hi''.2 j, simp [p', hj'] },
by_cases h2j₂ : j₂ = j',
{ cases h2j₂, refine ⟨x', hx'.1, _⟩, convert hi''.2 j', simp },
refine ⟨(cs i).b j₂.succ, _, _⟩,
{ convert hi'.2 j₂, simp [hj₂] },
{ convert hi''.2 j₂, simp [h2j₂] }
end
variables {h v}
/-- The same result that `mi` cannot lie on the boundary of the valley written as inequalities. -/
lemma mi_not_on_boundary' (j : fin n) : c.tail.b j < (cs (mi h v)).tail.b j ∧
(cs (mi h v)).tail.b j + (cs (mi h v)).w < c.tail.b j + c.w :=
begin
have := mi_not_on_boundary h v j,
simp only [on_boundary, not_or_distrib] at this, cases this with h1 h2,
split,
apply lt_of_le_of_ne (b_le_b mi_mem_bcubes _) h1,
apply lt_of_le_of_ne _ h2,
apply ((Ico_subset_Ico_iff _).mp (tail_sub mi_mem_bcubes j)).2, simp [hw]
end
/-- The top of `mi` gives rise to a new valley, since the neighbouring cubes extend further upward
than `mi`. -/
def valley_mi : valley cs ((cs (mi h v)).shift_up) :=
begin
let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes,
refine ⟨_, _, _⟩,
{ intro p, apply shift_up_bottom_subset_bottoms h mi_xm_ne_one },
{ rintros i' hi' ⟨p2, hp2, h2p2⟩, simp only [head_shift_up] at hi', classical, by_contra h2i',
rw [tail_shift_up] at h2p2, simp only [not_subset, tail_shift_up] at h2i',
rcases h2i' with ⟨p1, hp1, h2p1⟩,
have : ∃p3, p3 ∈ (cs i').tail.to_set ∧ p3 ∉ (cs i).tail.to_set ∧ p3 ∈ c.tail.to_set,
{ simp [to_set, not_forall] at h2p1, cases h2p1 with j hj,
rcases Ico_lemma (mi_not_on_boundary' j).1 (by simp [hw]) (mi_not_on_boundary' j).2
(le_trans (hp2 j).1 $ le_of_lt (h2p2 j).2)
(le_trans (h2p2 j).1 $ le_of_lt (hp2 j).2) ⟨hj, hp1 j⟩ with ⟨w, hw, h2w, h3w⟩,
refine ⟨λ j', if j' = j then w else p2 j', _, _, _⟩,
{ intro j', by_cases h : j' = j, simp [if_pos h], convert h3w,
simp [if_neg h], exact hp2 j' },
{ simp [to_set, not_forall], use j, rw [if_pos rfl], convert h2w },
{ intro j', by_cases h : j' = j, simp [if_pos h, side_tail], convert hw,
simp [if_neg h], apply hi.2, apply h2p2 }},
rcases this with ⟨p3, h1p3, h2p3, h3p3⟩,
let p := @cons n (λ_, ℝ) (c.b 0) p3,
have hp : p ∈ c.bottom, { refine ⟨rfl, _⟩, rwa [tail_cons] },
rcases v.1 hp with ⟨_, ⟨i'', rfl⟩, hi''⟩,
have h2i'' : i'' ∈ bcubes cs c,
{ use hi''.1.symm, apply v.2.1 i'' hi''.1.symm,
use tail p, split, exact hi''.2, rw [tail_cons], exact h3p3 },
have h3i'' : (cs i).w < (cs i'').w,
{ apply mi_strict_minimal _ h2i'', rintro rfl, apply h2p3, convert hi''.2, rw [tail_cons] },
let p' := @cons n (λ_, ℝ) (cs i).xm p3,
have hp' : p' ∈ (cs i').to_set,
{ simpa [to_set, forall_fin_succ, p', hi'.symm] using h1p3 },
have h2p' : p' ∈ (cs i'').to_set,
{ simp [to_set, forall_fin_succ, p'],
refine ⟨_, by simpa [to_set, p] using hi''.2⟩,
have : (cs i).b 0 = (cs i'').b 0, { by rw [hi.1, h2i''.1] },
simp [side, hw', xm, this, h3i''] },
apply not_disjoint_iff.mpr ⟨p', hp', h2p'⟩,
apply h.1, rintro rfl, apply (cs i).b_ne_xm, rw [←hi', ←hi''.1, hi.1], refl },
{ intros i' hi' h2i', dsimp [shift_up] at h2i', replace h2i' := h.2.2.1 h2i'.symm, induction h2i',
exact b_ne_xm (cs i) hi' }
end
variables (h)
omit v
/-- We get a sequence of cubes whose size is decreasing -/
noncomputable def sequence_of_cubes : ℕ → { i : ι // valley cs ((cs i).shift_up) }
| 0 := let v := valley_unit_cube h in ⟨mi h v, valley_mi⟩
| (k+1) := let v := (sequence_of_cubes k).2 in ⟨mi h v, valley_mi⟩
def decreasing_sequence (k : ℕ) : order_dual ℝ :=
(cs (sequence_of_cubes h k).1).w
lemma strict_mono_sequence_of_cubes : strict_mono $ decreasing_sequence h :=
strict_mono.nat $
begin
intro k, let v := (sequence_of_cubes h k).2, dsimp [decreasing_sequence, sequence_of_cubes],
apply w_lt_w h v (mi_mem_bcubes : mi h v ∈ _),
end
omit h
/-- The infinite sequence of cubes contradicts the finiteness of the family. -/
theorem not_correct : ¬correct cs :=
begin
intro h, apply not_le_of_lt (lt_omega_iff_fintype.mpr ⟨_inst_1⟩),
rw [omega, lift_id], fapply mk_le_of_injective, exact λ n, (sequence_of_cubes h n).1,
intros n m hnm, apply strict_mono.injective (strict_mono_sequence_of_cubes h),
dsimp only [decreasing_sequence], rw hnm
end
/-- A cube cannot be cubed. -/
theorem cannot_cube_a_cube :
∀{n : ℕ}, n ≥ 3 → -- In ℝ^n for n ≥ 3
∀{ι : Type} [fintype ι] {cs : ι → cube n}, -- given a finite collection of (hyper)cubes
2 ≤ cardinal.mk ι → -- containing at least two elements
pairwise (disjoint on (cube.to_set ∘ cs)) → -- which is pairwise disjoint
(⋃(i : ι), (cs i).to_set) = unit_cube.to_set → -- whose union is the unit cube
injective (cube.w ∘ cs) → -- such that the widths of all cubes are different
false := -- then we can derive a contradiction
begin
intros n hn ι hι cs h1 h2 h3 h4, resetI,
rcases n, cases hn,
exact not_correct ⟨h2, h3, h4, h1, hn⟩
end
|
5e0d4575cb8211cb6dcdd03a0cdae9e522ccebdc | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/synth1.lean | 737fbe6137abfc531b1c540ddab00a577be9b780 | [
"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,578 | lean | import Lean.Meta
open Lean
open Lean.Meta
class HasCoerce (a : semiOutParam Type) (b : Type) :=
(coerce : a → b)
def coerce {a b : Type} [HasCoerce a b] : a → b :=
@HasCoerce.coerce a b _
instance coerceTrans {a b c : Type} [HasCoerce b c] [HasCoerce a b] : HasCoerce a c :=
⟨fun x => coerce (coerce x : b)⟩
instance coerceBoolToProp : HasCoerce Bool Prop :=
⟨fun y => y = true⟩
instance coerceDecidableEq (x : Bool) : Decidable (coerce x) :=
inferInstanceAs (Decidable (x = true))
instance coerceNatToBool : HasCoerce Nat Bool :=
⟨fun x => x == 0⟩
instance coerceNatToInt : HasCoerce Nat Int :=
⟨fun x => Int.ofNat x⟩
def print {α} [ToString α] (a : α) : MetaM Unit := do
trace[Meta.synthInstance] (toString a)
def tst1 : MetaM Unit := do
let inst ← mkAppM `HasCoerce #[mkConst `Nat, mkSort levelZero]
let r ← synthInstance inst
print r
set_option trace.Meta.synthInstance true in
set_option trace.Meta.synthInstance.tryResolve false in
#eval tst1
def tst2 : MetaM Unit := do
let inst ← mkAppM `Bind #[mkConst `IO]
-- globalInstances ← getGlobalInstances
-- print (format globalInstances)
-- result ← globalInstances.getUnify inst
-- print result
let r ← synthInstance inst
print r
pure ()
set_option trace.Meta.synthInstance true in
set_option trace.Meta.synthInstance.tryResolve false in
#eval tst2
def tst3 : MetaM Unit := do
let inst ← mkAppM `BEq #[mkConst `Nat]
let r ← synthInstance inst
print r
pure ()
set_option trace.Meta.synthInstance true in
set_option trace.Meta.synthInstance.tryResolve false in
#eval tst3
|
80a76cea694003bfadeb174dbaa1ec15e7c26ad6 | b00eb947a9c4141624aa8919e94ce6dcd249ed70 | /stage0/src/Lean/Elab/BuiltinNotation.lean | d170e0c4c99d4f35083e31aa6e9da73e1d26c67b | [
"Apache-2.0"
] | permissive | gebner/lean4-old | a4129a041af2d4d12afb3a8d4deedabde727719b | ee51cdfaf63ee313c914d83264f91f414a0e3b6e | refs/heads/master | 1,683,628,606,745 | 1,622,651,300,000 | 1,622,654,405,000 | 142,608,821 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,773 | 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 Init.Data.ToString
import Lean.Compiler.BorrowedAnnotation
import Lean.Meta.KAbstract
import Lean.Meta.Transform
import Lean.Elab.Term
import Lean.Elab.SyntheticMVars
namespace Lean.Elab.Term
open Meta
@[builtinTermElab anonymousCtor] def elabAnonymousCtor : TermElab := fun stx expectedType? =>
match stx with
| `(⟨$args,*⟩) => do
tryPostponeIfNoneOrMVar expectedType?
match expectedType? with
| some expectedType =>
let expectedType ← whnf expectedType
matchConstInduct expectedType.getAppFn
(fun _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type {indentExpr expectedType}")
(fun ival us => do
match ival.ctors with
| [ctor] =>
let cinfo ← getConstInfoCtor ctor
let numExplicitFields ← forallTelescopeReducing cinfo.type fun xs _ => do
let mut n := 0
for i in [cinfo.numParams:xs.size] do
if (← getFVarLocalDecl xs[i]).binderInfo.isExplicit then
n := n + 1
return n
let args := args.getElems
if args.size < numExplicitFields then
throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' has #{numExplicitFields} explicit fields, but only #{args.size} provided"
let newStx ←
if args.size == numExplicitFields then
`($(mkCIdentFrom stx ctor) $(args)*)
else if numExplicitFields == 0 then
throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' does not have explicit fields, but #{args.size} provided"
else
let extra := args[numExplicitFields-1:args.size]
let newLast ← `(⟨$[$extra],*⟩)
let newArgs := args[0:numExplicitFields-1].toArray.push newLast
`($(mkCIdentFrom stx ctor) $(newArgs)*)
withMacroExpansion stx newStx $ elabTerm newStx expectedType?
| _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type with only one constructor {indentExpr expectedType}")
| none => throwError "invalid constructor ⟨...⟩, expected type must be known"
| _ => throwUnsupportedSyntax
@[builtinTermElab borrowed] def elabBorrowed : TermElab := fun stx expectedType? =>
match stx with
| `(@& $e) => return markBorrowed (← elabTerm e expectedType?)
| _ => throwUnsupportedSyntax
@[builtinMacro Lean.Parser.Term.show] def expandShow : Macro := fun stx =>
match stx with
| `(show $type from $val) => let thisId := mkIdentFrom stx `this; `(let_fun $thisId : $type := $val; $thisId)
| `(show $type by%$b $tac:tacticSeq) => `(show $type from by%$b $tac:tacticSeq)
| _ => Macro.throwUnsupported
@[builtinMacro Lean.Parser.Term.have] def expandHave : Macro := fun stx =>
let thisId := mkIdentFrom stx `this
match stx with
| `(have $x $bs* $[: $type]? := $val $[;]? $body) => `(let_fun $x $bs* $[: $type]? := $val; $body)
| `(have $[: $type]? := $val $[;]? $body) => `(have $thisId:ident $[: $type]? := $val; $body)
| `(have $x $bs* $[: $type]? $alts:matchAlts $[;]? $body) => `(let_fun $x $bs* $[: $type]? $alts:matchAlts; $body)
| `(have $[: $type]? $alts:matchAlts $[;]? $body) => `(have $thisId:ident $[: $type]? $alts:matchAlts; $body)
| `(have $pattern:term := $val:term $[;]? $body) => `(let_fun $pattern:term := $val:term ; $body)
| _ => Macro.throwUnsupported
@[builtinMacro Lean.Parser.Term.suffices] def expandSuffices : Macro
| `(suffices $[$x :]? $type from $val $[;]? $body) => `(have $[$x]? : $type := $body; $val)
| `(suffices $[$x :]? $type by%$b $tac:tacticSeq $[;]? $body) => `(have $[$x]? : $type := $body; by%$b $tac:tacticSeq)
| _ => Macro.throwUnsupported
open Lean.Parser in
private def elabParserMacroAux (prec : Syntax) (e : Syntax) : TermElabM Syntax := do
let (some declName) ← getDeclName?
| throwError "invalid `leading_parser` macro, it must be used in definitions"
match extractMacroScopes declName with
| { name := Name.str _ s _, scopes := scps, .. } =>
let kind := quote declName
let s := quote s
-- if the parser decl is hidden by hygiene, it doesn't make sense to provide an antiquotation kind
let antiquotKind ← if scps == [] then `(some $kind) else `(none)
``(withAntiquot (mkAntiquot $s $antiquotKind) (leadingNode $kind $prec $e))
| _ => throwError "invalid `leading_parser` macro, unexpected declaration name"
@[builtinTermElab «leading_parser»] def elabLeadingParserMacro : TermElab :=
adaptExpander fun stx => match stx with
| `(leading_parser $e) => elabParserMacroAux (quote Parser.maxPrec) e
| `(leading_parser : $prec $e) => elabParserMacroAux prec e
| _ => throwUnsupportedSyntax
private def elabTParserMacroAux (prec lhsPrec : Syntax) (e : Syntax) : TermElabM Syntax := do
let declName? ← getDeclName?
match declName? with
| some declName => let kind := quote declName; ``(Lean.Parser.trailingNode $kind $prec $lhsPrec $e)
| none => throwError "invalid `trailing_parser` macro, it must be used in definitions"
@[builtinTermElab «trailing_parser»] def elabTrailingParserMacro : TermElab :=
adaptExpander fun stx => match stx with
| `(trailing_parser$[:$prec?]?$[:$lhsPrec?]? $e) =>
elabTParserMacroAux (prec?.getD <| quote Parser.maxPrec) (lhsPrec?.getD <| quote 0) e
| _ => throwUnsupportedSyntax
@[builtinTermElab panic] def elabPanic : TermElab := fun stx expectedType? => do
let arg := stx[1]
let pos ← getRefPosition
let env ← getEnv
let stxNew ← match (← getDeclName?) with
| some declName => `(panicWithPosWithDecl $(quote (toString env.mainModule)) $(quote (toString declName)) $(quote pos.line) $(quote pos.column) $arg)
| none => `(panicWithPos $(quote (toString env.mainModule)) $(quote pos.line) $(quote pos.column) $arg)
withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
@[builtinMacro Lean.Parser.Term.unreachable] def expandUnreachable : Macro := fun stx =>
`(panic! "unreachable code has been reached")
@[builtinMacro Lean.Parser.Term.assert] def expandAssert : Macro := fun stx =>
-- TODO: support for disabling runtime assertions
let cond := stx[1]
let body := stx[3]
match cond.reprint with
| some code => `(if $cond then $body else panic! ("assertion violation: " ++ $(quote code)))
| none => `(if $cond then $body else panic! ("assertion violation"))
@[builtinMacro Lean.Parser.Term.dbgTrace] def expandDbgTrace : Macro := fun stx =>
let arg := stx[1]
let body := stx[3]
if arg.getKind == interpolatedStrKind then
`(dbgTrace (s! $arg) fun _ => $body)
else
`(dbgTrace (toString $arg) fun _ => $body)
@[builtinTermElab «sorry»] def elabSorry : TermElab := fun stx expectedType? => do
logWarning "declaration uses 'sorry'"
let stxNew ← `(sorryAx _ false)
withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?
/-- Return syntax `Prod.mk elems[0] (Prod.mk elems[1] ... (Prod.mk elems[elems.size - 2] elems[elems.size - 1])))` -/
partial def mkPairs (elems : Array Syntax) : MacroM Syntax :=
let rec loop (i : Nat) (acc : Syntax) := do
if i > 0 then
let i := i - 1
let elem := elems[i]
let acc ← `(Prod.mk $elem $acc)
loop i acc
else
pure acc
loop (elems.size - 1) elems.back
private partial def hasCDot : Syntax → Bool
| Syntax.node k args =>
if k == `Lean.Parser.Term.paren then false
else if k == `Lean.Parser.Term.cdot then true
else args.any hasCDot
| _ => false
/--
Return `some` if succeeded expanding `·` notation occurring in
the given syntax. Otherwise, return `none`.
Examples:
- `· + 1` => `fun _a_1 => _a_1 + 1`
- `f · · b` => `fun _a_1 _a_2 => f _a_1 _a_2 b` -/
partial def expandCDot? (stx : Syntax) : MacroM (Option Syntax) := do
if hasCDot stx then
let (newStx, binders) ← (go stx).run #[];
`(fun $binders* => $newStx)
else
pure none
where
/--
Auxiliary function for expanding the `·` notation.
The extra state `Array Syntax` contains the new binder names.
If `stx` is a `·`, we create a fresh identifier, store in the
extra state, and return it. Otherwise, we just return `stx`. -/
go : Syntax → StateT (Array Syntax) MacroM Syntax
| stx@(Syntax.node k args) =>
if k == `Lean.Parser.Term.paren then pure stx
else if k == `Lean.Parser.Term.cdot then withFreshMacroScope do
let id ← `(a)
modify fun s => s.push id;
pure id
else do
let args ← args.mapM go
pure $ Syntax.node k args
| stx => pure stx
/--
Helper method for elaborating terms such as `(.+.)` where a constant name is expected.
This method is usually used to implement tactics that function names as arguments (e.g., `simp`).
-/
def elabCDotFunctionAlias? (stx : Syntax) : TermElabM (Option Expr) := do
let some stx ← liftMacroM <| expandCDotArg? stx | pure none
let stx ← liftMacroM <| expandMacros stx
match stx with
| `(fun $binders* => $f:ident $args*) =>
if binders == args then
try Term.resolveId? f catch _ => return none
else
return none
| `(fun $binders* => binop% $f:ident $a $b) =>
if binders == #[a, b] then
try Term.resolveId? f catch _ => return none
else
return none
| _ => return none
where
expandCDotArg? (stx : Syntax) : MacroM (Option Syntax) :=
match stx with
| `(($e)) => Term.expandCDot? e
| _ => Term.expandCDot? stx
/--
Try to expand `·` notation.
Recall that in Lean the `·` notation must be surrounded by parentheses.
We may change this is the future, but right now, here are valid examples
- `(· + 1)`
- `(f ⟨·, 1⟩ ·)`
- `(· + ·)`
- `(f · a b)` -/
@[builtinMacro Lean.Parser.Term.paren] def expandParen : Macro
| `(()) => `(Unit.unit)
| `(($e : $type)) => do
match ← expandCDot? e with
| some e => `(($e : $type))
| none => Macro.throwUnsupported
| `(($e)) => return (← expandCDot? e).getD e
| `(($e, $es,*)) => do
let pairs ← mkPairs (#[e] ++ es)
(← expandCDot? pairs).getD pairs
| stx =>
if !stx[1][0].isMissing && stx[1][1].isMissing then
-- parsed `(` and `term`, assume it's a basic parenthesis to get any elaboration output at all
`(($(stx[1][0])))
else
throw <| Macro.Exception.error stx "unexpected parentheses notation"
@[builtinTermElab paren] def elabParen : TermElab := fun stx expectedType? => do
match stx with
| `(($e : $type)) =>
let type ← withSynthesize (mayPostpone := true) <| elabType type
let e ← elabTerm e type
ensureHasType type e
| _ => throwUnsupportedSyntax
@[builtinTermElab subst] def elabSubst : TermElab := fun stx expectedType? => do
let expectedType ← tryPostponeIfHasMVars expectedType? "invalid `▸` notation"
match stx with
| `($heq ▸ $h) => do
let mut heq ← elabTerm heq none
let heqType ← inferType heq
let heqType ← instantiateMVars heqType
match (← Meta.matchEq? heqType) with
| none => throwError "invalid `▸` notation, argument{indentExpr heq}\nhas type{indentExpr heqType}\nequality expected"
| some (α, lhs, rhs) =>
let mut lhs := lhs
let mut rhs := rhs
let mkMotive (typeWithLooseBVar : Expr) := do
withLocalDeclD (← mkFreshUserName `x) α fun x => do
mkLambdaFVars #[x] $ typeWithLooseBVar.instantiate1 x
let mut expectedAbst ← kabstract expectedType rhs
unless expectedAbst.hasLooseBVars do
expectedAbst ← kabstract expectedType lhs
unless expectedAbst.hasLooseBVars do
throwError "invalid `▸` notation, expected type{indentExpr expectedType}\ndoes contain equation left-hand-side nor right-hand-side{indentExpr heqType}"
heq ← mkEqSymm heq
(lhs, rhs) := (rhs, lhs)
let hExpectedType := expectedAbst.instantiate1 lhs
let h ← withRef h do
let h ← elabTerm h hExpectedType
try
ensureHasType hExpectedType h
catch ex =>
-- if `rhs` occurs in `hType`, we try to apply `heq` to `h` too
let hType ← inferType h
let hTypeAbst ← kabstract hType rhs
unless hTypeAbst.hasLooseBVars do
throw ex
let hTypeNew := hTypeAbst.instantiate1 lhs
unless (← isDefEq hExpectedType hTypeNew) do
throw ex
mkEqNDRec (← mkMotive hTypeAbst) h (← mkEqSymm heq)
mkEqNDRec (← mkMotive expectedAbst) h heq
| _ => throwUnsupportedSyntax
@[builtinTermElab stateRefT] def elabStateRefT : TermElab := fun stx _ => do
let σ ← elabType stx[1]
let mut mStx := stx[2]
if mStx.getKind == `Lean.Parser.Term.macroDollarArg then
mStx := mStx[1]
let m ← elabTerm mStx (← mkArrow (mkSort levelOne) (mkSort levelOne))
let ω ← mkFreshExprMVar (mkSort levelOne)
let stWorld ← mkAppM `STWorld #[ω, m]
discard <| mkInstMVar stWorld
mkAppM `StateRefT' #[ω, σ, m]
@[builtinTermElab noindex] def elabNoindex : TermElab := fun stx expectedType? => do
let e ← elabTerm stx[1] expectedType?
return DiscrTree.mkNoindexAnnotation e
end Lean.Elab.Term
|
c0c3eae34647ad7af1f2db01735c9684512febdd | c3f2fcd060adfa2ca29f924839d2d925e8f2c685 | /tests/lean/bad_coercions.lean | d724b360373af5a14f46a4de6b0a1b8ff365fad7 | [
"Apache-2.0"
] | permissive | respu/lean | 6582d19a2f2838a28ecd2b3c6f81c32d07b5341d | 8c76419c60b63d0d9f7bc04ebb0b99812d0ec654 | refs/heads/master | 1,610,882,451,231 | 1,427,747,084,000 | 1,427,747,429,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 370 | lean | open nat
constant list.{l} : Type.{l} → Type.{l}
constant vector.{l} : Type.{l} → nat → Type.{l}
constant nil (A : Type) : list A
set_option pp.coercions true
context
parameter A : Type
parameter n : nat
definition foo2 [coercion] (v : vector A n) : list A :=
nil A
definition foo (v : vector A n) : list A :=
nil A
attribute foo [coercion]
end
|
06e2b3e1dd7af2a7d5761f489b0881d34e11575e | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/ack.lean | 61dbaae4a5f810588fb377e1ddbc45082267e926 | [
"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 | 141 | lean | def ack : Nat → Nat → Nat
| 0, y => y+1
| x+1, 0 => ack x 1
| x+1, y+1 => ack x (ack (x+1) y)
termination_by _ a b => (a, b)
|
bc8e25c67d6b51adf4c4c32f38de15c45c6bce77 | 32a2d1642d7519c99693bc1d3b24069e4853dd1f | /data/list/basic.lean | cdf09aa1e28cfb0d41942df4524c9f414cba3d46 | [
"Apache-2.0"
] | permissive | Cedric0099/mathlib | 7edb81d5d68e280b4d21f6c0377dad1f9b8c0d71 | a97101d2df5d186848075a2d0452f6a04d8a13eb | refs/heads/master | 1,584,201,847,599 | 1,524,979,632,000 | 1,524,979,632,000 | 131,690,350 | 0 | 0 | null | 1,525,162,341,000 | 1,525,162,341,000 | null | UTF-8 | Lean | false | false | 131,323 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
Basic properties of lists.
-/
import tactic.interactive algebra.group logic.basic logic.function
data.nat.basic data.option data.bool data.prod data.sigma
open function nat
namespace list
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
@[simp] theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ [].
theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → h₁ = h₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq)
theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → t₁ = t₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq)
theorem cons_inj {a : α} : injective (cons a) :=
assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe
@[simp] theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' :=
⟨λ e, cons_inj e, congr_arg _⟩
/- mem -/
theorem eq_nil_of_forall_not_mem : ∀ {l : list α}, (∀ a, a ∉ l) → l = nil
| [] := assume h, rfl
| (b :: l') := assume h, absurd (mem_cons_self b l') (h b)
theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _
theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b :=
assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, this)
(assume : a ∈ [], absurd this (not_mem_nil a))
@[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b :=
⟨eq_of_mem_singleton, by intro h; simp [h]⟩
theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l :=
assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl)
(assume : a = b, begin subst a, exact binl end)
(assume : a ∈ l, this)
theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t :=
mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩
theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] :=
⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩
theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l
| (b::l) _ := zero_lt_succ _
theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l
| (b::l) _ := ⟨b, mem_cons_self _ _⟩
theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l :=
⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩
theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t :=
begin
induction l with b l ih; simp at h; cases h with h h,
{ subst h, exact ⟨[], l, rfl⟩ },
{ cases ih h with s e, cases e with t e,
subst l, exact ⟨b::s, t, rfl⟩ }
end
theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l :=
or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r)
theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b :=
assume nin aeqb, absurd (or.inl aeqb) nin
theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l :=
assume nin nainl, absurd (or.inr nainl) nin
theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l :=
assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2))
theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l :=
assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p)
theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l :=
begin
induction l with b l' ih,
{simp at h, contradiction },
{simp, simp at h, cases h with h h,
{simp *},
{exact or.inr (ih h)}}
end
theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b :=
begin
induction l with c l' ih,
{simp at h, contradiction},
{cases (eq_or_mem_of_mem_cons h) with h h,
{existsi c, simp [h]},
{cases ih h with a ha, cases ha with ha₁ ha₂,
existsi a, simp * }}
end
@[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b :=
⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩
@[simp] theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} :
f a ∈ map f l ↔ a ∈ l :=
⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩
@[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l
| [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩
| (c :: L) := by simp [join, @mem_join L, or_and_distrib_right, exists_or_distrib]
theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l :=
mem_join.1
theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L :=
mem_join.2 ⟨l, lL, al⟩
@[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a :=
iff.trans mem_join
⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩,
λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩
theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a :=
mem_bind.1
theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f :=
mem_bind.2 ⟨a, al, h⟩
/- list subset -/
theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl
theorem subset_app_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_left _ _
theorem subset_app_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_right _ _
@[simp] theorem cons_subset {a : α} {l m : list α} :
a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m :=
by simp [subset_def, or_imp_distrib, forall_and_distrib]
theorem cons_subset_of_subset_of_mem {a : α} {l m : list α}
(ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m :=
cons_subset.2 ⟨ainm, lsubm⟩
theorem app_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) :
l₁ ++ l₂ ⊆ l :=
λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _)
theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = []
| [] s := rfl
| (a::l) s := false.elim $ s $ mem_cons_self a l
theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l :=
show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩
/- append -/
lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl
theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_foldl (f : α → β → α) (a : α) (s t : list β) : foldl f a (s ++ t) = foldl f (foldl f a s) t :=
by {induction s with b s H generalizing a, refl, simp [foldl], rw H _}
theorem append_foldr (f : α → β → β) (a : β) (s t : list α) : foldr f a (s ++ t) = foldr f (foldr f a t) s :=
by {induction s with b s H generalizing a, refl, simp [foldr], rw H _}
@[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] :=
by cases p; simp
@[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] :=
by rw [eq_comm, append_eq_nil]
lemma append_eq_cons_iff {a b c : list α} {x : α} :
a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by cases a; simp [and_assoc, @eq_comm _ c]
lemma cons_eq_append_iff {a b c : list α} {x : α} :
(x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by rw [eq_comm, append_eq_cons_iff]
lemma append_eq_append_iff {a b c d : list α} :
a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) :=
begin
induction a generalizing c,
case nil { simp [nil_eq_append_iff, iff_def, or_imp_distrib] {contextual := tt} },
case cons : a as ih {
cases c,
{ simp, exact eq_comm },
{ simp [ih, @eq_comm _ a, and_assoc, and_or_distrib_left] } }
end
/- join -/
attribute [simp] join
@[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ :=
by induction L₁; simp *
/- repeat take drop -/
/-- Split a list at an index. `split 2 [a, b, c] = ([a, b], [c])` -/
def split_at : ℕ → list α → list α × list α
| 0 a := ([], a)
| (succ n) [] := ([], [])
| (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r)
@[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l)
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := by simp [split_at, split_at_eq_take_drop n xs]
@[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := by simp [take_append_drop n xs]
-- TODO(Leo): cleanup proof after arith dec proc
theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂
| [] [] t₁ t₂ h hl := ⟨rfl, h⟩
| (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl
| [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm
| (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap,
let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in
by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩
theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ :=
(append_inj h hl).right
theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ :=
(append_inj h hl).left
theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ :=
append_inj h $ @nat.add_right_cancel _ (length t₁) _ $
let hap := congr_arg length h in by simp at hap; rwa [← hl] at hap
theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ :=
(append_inj' h hl).right
theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ :=
(append_inj' h hl).left
theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ :=
append_inj_left h rfl
theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ :=
append_inj_right' h rfl
theorem append_left_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ :=
⟨append_left_cancel, congr_arg _⟩
theorem append_right_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ :=
⟨append_right_cancel, congr_arg _⟩
theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a
| (n+1) h := or.elim h id $ @eq_of_mem_repeat _
theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length
| [] H := rfl
| (b::l) H :=
have b = a ∧ ∀ (x : α), x ∈ l → x = a,
by simpa [or_imp_distrib, forall_and_distrib] using H,
by dsimp; congr; [exact this.1, exact eq_repeat_of_mem this.2]
theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩
theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] :=
λ b h, mem_singleton.2 (eq_of_mem_repeat h)
@[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length :=
by induction l; simp [-add_comm, *]
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
by rw map_const at h; exact eq_of_mem_repeat h
/- bind -/
@[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) :
l >>= f = l.bind f := rfl
/- concat -/
/-- Concatenate an element at the end of a list. `concat [a, b] c = [a, b, c]` -/
@[simp] def concat : list α → α → list α
| [] a := [a]
| (b::l) a := b :: concat l a
@[simp] theorem concat_nil (a : α) : concat [] a = [a] := rfl
@[simp] theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl
@[simp] theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] :=
by induction l; intro h; contradiction
@[simp] theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ :=
by induction l₁ with b l₁ ih; [simp, simp [ih]]
@[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] :=
by induction l; simp [*, concat]
@[simp] theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) :=
by simp [succ_eq_add_one]
theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a :=
by induction l₂ with b l₂ ih; simp
/- reverse -/
@[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl
local attribute [simp] reverse_core
@[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a :=
have aux : ∀ l₁ l₂, reverse_core l₁ (concat l₂ a) = concat (reverse_core l₁ l₂) a,
by intros l₁; induction l₁; intros; rsimp,
aux l nil
theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] :=
by simp
@[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl
@[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) :=
by induction s; simp *
@[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l :=
by induction l; simp *
theorem reverse_injective : injective (@reverse α) :=
injective_of_left_inverse reverse_reverse
@[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ :=
reverse_injective.eq_iff
@[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] :=
@reverse_inj _ l []
theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) :=
by simp
@[simp] theorem length_reverse (l : list α) : length (reverse l) = length l :=
by induction l; simp *
@[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) :=
by induction l; simp *
@[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l :=
by induction l; simp [*, or_comm]
@[elab_as_eliminator] theorem reverse_rec_on {C : list α → Sort*}
(l : list α) (H0 : C [])
(H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l :=
begin
rw ← reverse_reverse l,
induction reverse l,
{ exact H0 },
{ simp, exact H1 _ _ ih }
end
/- last -/
@[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ :=
by {induction l; intros, contradiction, simp *, reflexivity}
@[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a :=
begin
induction l with hd tl ih; rsimp,
have haux : tl ++ [a] ≠ [],
{apply append_ne_nil_of_ne_nil_right, contradiction},
simp *
end
theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a :=
by simp *
@[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl
@[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) :
last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl
theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) :
last l₁ h₁ = last l₂ h₂ :=
by subst l₁
/- head and tail -/
@[simp] theorem head_cons [h : inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl
@[simp] theorem tail_nil : tail (@nil α) = [] := rfl
@[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl
@[simp] theorem head_append [h : inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s :=
by {induction s, contradiction, simp}
theorem cons_head_tail [h : inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l :=
by {induction l, contradiction, simp}
/- map -/
lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l
| [] _ := rfl
| (a::l) h :=
have f a = g a, from h _ (mem_cons_self _ _),
have map f l = map g l, from map_congr $ assume a', h _ ∘ mem_cons_of_mem _,
show f a :: map f l = g a :: map g l, by simp [*]
theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) :=
by induction l; simp *
theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l :=
by induction l; simp *
@[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l :=
by revert a; induction l; intros; simp *
@[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l :=
by revert a; induction l; intros; simp *
theorem foldl_hom (f : α → β) (g : α → γ → α) (g' : β → γ → β) (a : α)
(h : ∀a x, f (g a x) = g' (f a) x) (l : list γ) : f (foldl g a l) = foldl g' (f a) l :=
by revert a; induction l; intros; simp *
theorem foldr_hom (f : α → β) (g : γ → α → α) (g' : γ → β → β) (a : α)
(h : ∀x a, f (g x a) = g' x (f a)) (l : list γ) : f (foldr g a l) = foldr g' (f a) l :=
by revert a; induction l; intros; simp *
theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil :=
eq_nil_of_length_eq_zero (begin rw [← length_map f l], simp [h] end)
@[simp] theorem map_join (f : α → β) (L : list (list α)) :
map f (join L) = join (map (map f) L) :=
by induction L; simp *
theorem bind_ret_eq_map {α β} (f : α → β) (l : list α) :
l.bind (list.ret ∘ f) = map f l :=
by simp [list.bind]; induction l; simp [list.ret, join, *]
@[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) :
f <$> l = map f l := rfl
/- map₂ -/
theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] :=
by cases l; refl
theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] :=
by cases l; refl
/- sublists -/
@[simp] theorem nil_sublist : Π (l : list α), [] <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons _ _ a (nil_sublist l)
@[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons2 _ _ a (sublist.refl l)
@[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ :=
sublist.rec_on h₂ (λ_ s, s)
(λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁))
(λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁
(λ_, nil_sublist _)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl)
l₁ h₁
@[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l :=
sublist.cons _ _ _ (sublist.refl l)
theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ :=
sublist.trans (sublist_cons a l₁)
theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ :=
sublist.cons2 _ _ _ s
@[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂
| [] l₂ := nil_sublist _
| (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂)
@[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂
| [] l₂ := sublist.refl _
| (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂)
theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ :=
sublist.cons _ _ _
theorem sublist_app_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ :=
s.trans $ sublist_append_left _ _
theorem sublist_app_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ :=
s.trans $ sublist_append_right _ _
theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂
| ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s
| ._ (sublist.cons2 ._ ._ a s) := s
theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ :=
⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩
@[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂
| [] := iff.rfl
| (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l)
theorem append_sublist_append_of_sublist_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l :=
begin
induction h with _ _ a _ ih _ _ a _ ih,
{ refl },
{ apply sublist_cons_of_sublist a ih },
{ apply cons_sublist_cons a ih }
end
theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l :=
begin
induction l₁ with b l₁ IH generalizing l,
{ cases h; simp * },
{ cases h with _ _ _ h _ _ _ h,
{ exact or.imp_left (sublist_cons_of_sublist _) (IH h) },
{ exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } }
end
theorem reverse_sublist {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse :=
begin
induction h with _ _ _ _ ih _ _ a _ ih; simp,
{ exact sublist_app_of_sublist_left ih },
{ exact append_sublist_append_of_sublist_right ih [a] }
end
@[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ :=
⟨λ h, by have := reverse_sublist h; simp at this; assumption, reverse_sublist⟩
@[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ :=
⟨λ h, by have := reverse_sublist h; simp at this; assumption,
λ h, append_sublist_append_of_sublist_right h l⟩
theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂
| ._ ._ sublist.slnil b h := h
| ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist s h)
| ._ ._ (sublist.cons2 l₁ l₂ a s) b h :=
match eq_or_mem_of_mem_cons h with
| or.inl h := h ▸ mem_cons_self _ _
| or.inr h := mem_cons_of_mem _ (subset_of_sublist s h)
end
theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l :=
⟨λ h, subset_of_sublist h (mem_singleton_self _), λ h,
let ⟨s, t, e⟩ := mem_split h in e.symm ▸
(cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩
theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] :=
eq_nil_of_subset_nil $ subset_of_sublist s
theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n :=
⟨λ h, by simpa using length_le_of_sublist h,
λ h, by induction h; [apply sublist.refl, simp [*, sublist.cons]] ⟩
theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂
| ._ ._ sublist.slnil h := rfl
| ._ ._ (sublist.cons l₁ l₂ a s) h :=
absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self
| ._ ._ (sublist.cons2 l₁ l₂ a s) h :=
by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h
theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h)
theorem sublist_antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂)
instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂)
| [] l₂ := is_true $ nil_sublist _
| (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h
| (a::l₁) (b::l₂) :=
if h : a = b then
decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $
by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩
else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂)
⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with
| a, l₁, sublist.cons ._ ._ ._ s', h := s'
| ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h
end⟩
/- index_of -/
section index_of
variable [decidable_eq α]
@[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl
theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl
theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 :=
assume e, if_pos e
@[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 :=
index_of_cons_eq _ rfl
@[simp] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) :=
assume n, if_neg n
theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l :=
begin
induction l with b l ih; simp [-add_comm],
by_cases h : a = b; simp [h, -add_comm],
{ intro, contradiction },
{ rw ← ih, exact ⟨succ_inj, congr_arg _⟩ }
end
@[simp] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l :=
index_of_eq_length.2
theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l :=
begin
induction l with b l ih; simp [-add_comm, index_of_cons],
by_cases h : a = b; simp [h, -add_comm, zero_le],
exact succ_le_succ ih
end
theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l :=
⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al,
λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩
end index_of
/- nth element -/
theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a
| a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩
| a (b :: l) (or.inr m) :=
let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩
theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h)
| (a :: l) 0 h := rfl
| (a :: l) (n+1) h := @nth_le_nth l n _
theorem nth_ge_len : ∀ {l : list α} {n}, n ≥ length l → nth l n = none
| [] n h := rfl
| (a :: l) (n+1) h := nth_ge_len (le_of_succ_le_succ h)
theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a :=
⟨λ e,
have h : n < length l, from lt_of_not_ge $ λ hn,
by rw nth_ge_len hn at e; contradiction,
⟨h, by rw nth_le_nth h at e;
injection e with e; apply nth_le_mem⟩,
λ ⟨h, e⟩, e ▸ nth_le_nth _⟩
theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a :=
let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩
theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l
| (a :: l) 0 h := mem_cons_self _ _
| (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _)
theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l :=
let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _
theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a :=
⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩
theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a :=
mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm
@[extensionality]
theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂
| [] [] h := rfl
| (a::l₁) [] h := by have h0 := h 0; contradiction
| [] (a'::l₂) h := by have h0 := h 0; contradiction
| (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp [*, ext (λn, h (n+1))]
theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ :=
ext $ λn, if h₁ : n < length l₁
then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])]
else let h₁ := le_of_not_gt h₁ in by rw [nth_ge_len h₁, nth_ge_len (by rwa [← hl])]
@[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a
| (b::l) h := by by_cases h' : a = b; simp *
@[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a :=
by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)]
theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2
| [] r i := λh1 h2, rfl
| (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, by simp); exact
λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2)
theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2),
nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2
| [] r i h1 h2 := absurd h2 (not_lt_zero _)
| (a :: l) r 0 h1 h2 := begin
have aux := nth_le_reverse_aux1 l (a :: r) 0,
rw zero_add at aux,
exact aux _ (zero_lt_succ _)
end
| (a :: l) r (i+1) h1 h2 := begin
have aux := nth_le_reverse_aux2 l (a :: r) i,
have heq := calc length (a :: l) - 1 - (i + 1)
= length l - (1 + i) : by rw add_comm; refl
... = length l - 1 - i : by rw nat.sub_sub,
rw [← heq] at aux,
apply aux
end
@[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) :
nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 :=
nth_le_reverse_aux2 _ _ _ _ _
/-- Convert a list into an array (whose length is the length of `l`) -/
def to_array (l : list α) : array l.length α :=
{data := λ v, l.nth_le v.1 v.2}
/-- "inhabited" `nth` function: returns `default` instead of `none` in the case
that the index is out of bounds. -/
@[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget
/- nth tail operation -/
/-- Apply a function to the nth tail of `l`.
`modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c]`. Returns the input without
using `f` if the index is larger than the length of the list. -/
@[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α
| 0 l := f l
| (n+1) [] := []
| (n+1) (a::l) := a :: modify_nth_tail n l
/-- Apply `f` to the head of the list, if it exists. -/
@[simp] def modify_head (f : α → α) : list α → list α
| [] := []
| (a::l) := f a :: l
/-- Apply `f` to the nth element of the list, if it exists. -/
def modify_nth (f : α → α) : ℕ → list α → list α :=
modify_nth_tail (modify_head f)
theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _)
theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α),
update_nth l n a = modify_nth (λ _, a) n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _)
theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α),
modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := (congr_arg (cons b)
(modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl
theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m,
nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m
| n l 0 := by cases l; cases n; refl
| n [] (m+1) := by cases n; refl
| 0 (a::l) (m+1) := by cases nth l m; refl
| (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $
by cases nth l m with b; by_cases n = m; simp [h, mt succ_inj]
theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) :
∀ n l, length (modify_nth_tail f n l) = length l
| 0 l := H _
| (n+1) [] := rfl
| (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _)
@[simp] theorem modify_nth_length (f : α → α) :
∀ n l, length (modify_nth f n l) = length l :=
modify_nth_tail_length _ (λ l, by cases l; refl)
@[simp] theorem update_nth_length (l : list α) (n) (a : α) :
length (update_nth l n a) = length l :=
by simp [update_nth_eq_modify_nth]
@[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) :
nth (modify_nth f n l) n = f <$> nth l n :=
by simp [nth_modify_nth]
@[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) :
nth (modify_nth f m l) n = nth l n :=
by simp [nth_modify_nth, h]; cases nth l n; refl
theorem nth_update_nth_eq (a : α) (n) (l : list α) :
nth (update_nth l n a) n = (λ _, a) <$> nth l n :=
by simp [update_nth_eq_modify_nth]
theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) :
nth (update_nth l n a) n = some a :=
by rw [nth_update_nth_eq, nth_le_nth h]; refl
theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) :
nth (update_nth l m a) n = nth l n :=
by simp [update_nth_eq_modify_nth, h]
/- take, drop -/
@[simp] theorem take_zero : ∀ (l : list α), take 0 l = [] :=
begin intros, reflexivity end
@[simp] theorem take_nil : ∀ n, take n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl
theorem take_all : ∀ (l : list α), take (length l) l = l
| [] := rfl
| (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_all end
theorem take_all_of_ge : ∀ {n} {l : list α}, n ≥ length l → take n l = l
| 0 [] h := rfl
| 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _))
| (n+1) [] h := rfl
| (n+1) (a::l) h :=
begin
change a :: take n l = a :: l,
rw [take_all_of_ge (le_of_succ_le_succ h)]
end
theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l
| n 0 l := by rw [min_zero, take_zero, take_nil]
| 0 m l := by simp
| (succ n) (succ m) nil := by simp
| (succ n) (succ m) (a::l) := by simp [min_succ_succ, take_take]
theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h,
drop n l = nth_le l n h :: drop (n+1) l
| 0 (a::l) h := rfl
| (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _
theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) :
∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l)
| 0 l := rfl
| (n+1) [] := H.symm
| (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l)
theorem modify_nth_eq_take_drop (f : α → α) :
∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) :=
modify_nth_tail_eq_take_drop _ rfl
theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) :
modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l :=
by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl
theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) :
update_nth l n a = take n l ++ a :: drop (n+1) l :=
by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h]
@[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] :=
by cases l; cases n; simp [update_nth]
/- take_while -/
/-- Get the longest initial segment of the list whose members all satisfy `p`.
`take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2]` -/
def take_while (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then a :: take_while l else []
/- foldl, foldr, scanl, scanr -/
@[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl
@[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) :
foldl f a (b::l) = foldl f (f a b) l := rfl
@[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
foldr f b (a::l) = f a (foldr f b l) := rfl
@[simp] theorem foldl_append (f : α → β → α) :
∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂
| a [] l₂ := rfl
| a (b::l₁) l₂ := by simp [foldl_append]
@[simp] theorem foldr_append (f : α → β → β) :
∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁
| b [] l₂ := rfl
| b (a::l₁) l₂ := by simp [foldr_append]
@[simp] theorem foldl_join (f : α → β → α) :
∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L
| a [] := rfl
| a (l::L) := by simp [foldl_join]
@[simp] theorem foldr_join (f : α → β → β) :
∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L
| a [] := rfl
| a (l::L) := by simp [foldr_join]
theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l :=
by induction l; simp [*, foldr]
theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l :=
let t := foldl_reverse (λx y, f y x) a (reverse l) in
by rw reverse_reverse l at t; rwa t
@[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l
| [] := rfl
| (x::l) := by simp [foldr_eta l]
/-- Fold a function `f` over the list from the left, returning the list
of partial results. `scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6]` -/
def scanl (f : α → β → α) : α → list β → list α
| a [] := [a]
| a (b::l) := a :: scanl (f a b) l
def scanr_aux (f : α → β → β) (b : β) : list α → β × list β
| [] := (b, [])
| (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l')
/-- Fold a function `f` over the list from the right, returning the list
of partial results. `scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0]` -/
def scanr (f : α → β → β) (b : β) (l : list α) : list β :=
let (b', l') := scanr_aux f b l in b' :: l'
@[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl
@[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α),
scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l)
| a [] := rfl
| a (x::l) := let t := scanr_aux_cons x l in
by simp [scanr, scanr_aux] at t; simp [scanr, scanr_aux, t]
@[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
scanr f b (a::l) = foldr f b (a::l) :: scanr f b l :=
by simp [scanr]
section foldl_eq_foldr
-- foldl and foldr coincide when f is commutative and associative
variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f)
include hassoc
theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l)
| a b nil := rfl
| a b (c :: l) := by simp [foldl1_eq_foldr1 _ _ l]; rw hassoc
include hcomm
theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l)
| a b nil := hcomm a b
| a b (c::l) := by simp;
rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; simp
theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l
| a nil := rfl
| a (b :: l) :=
by simp [foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l)
end foldl_eq_foldr
section
variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op]
local notation a * b := op a b
local notation l <*> a := foldl op a l
include ha
lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂)
| [] a₁ a₂ := by simp
| (a :: l) a₁ a₂ :=
calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp [ha.assoc]
... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc]; simp
lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂
| [] a₁ a₂ := by simp
| (a :: l) a₁ a₂ := by simp [foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc]
include hc
lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) :=
by rw [foldl_cons, hc.comm, foldl_assoc]
end
/- sum -/
/-- Product of a list. `prod [a, b, c] = ((1 * a) * b) * c` -/
@[to_additive list.sum]
def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1
attribute [to_additive list.sum.equations._eqn_1] list.prod.equations._eqn_1
section monoid
variables [monoid α] {l l₁ l₂ : list α} {a : α}
@[simp, to_additive list.sum_nil]
theorem prod_nil : ([] : list α).prod = 1 := rfl
@[simp, to_additive list.sum_cons]
theorem prod_cons : (a::l).prod = a * l.prod :=
calc (a::l).prod = foldl (*) (a * 1) l : by simp [list.prod]
... = _ : foldl_assoc
@[simp, to_additive list.sum_append]
theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod :=
calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod]
... = l₁.prod * l₂.prod : foldl_assoc
@[simp, to_additive list.sum_join]
theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod :=
by induction l; simp [list.join, *] at *
end monoid
@[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n :=
by induction n; simp [*, nat.mul_succ]
@[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) :=
by induction L; simp *
@[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) :=
by rw [list.bind, length_join, map_map]
/- all & any, bounded quantifiers over lists -/
theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x :=
by simp
@[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} :
(∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp [or_imp_distrib, forall_and_distrib]
theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} :
(∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp
theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α}
(h : ∀ x ∈ a :: l, p x) :
∀ x ∈ l, p x :=
(forall_mem_cons.1 h).2
theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x :=
by simp
theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) :
∃ x ∈ a :: l, p x :=
bex.intro a (by simp) h
theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) :
∃ x ∈ a :: l, p x :=
bex.elim h (λ x xl px, bex.intro x (by simp [xl]) px)
theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) :
p a ∨ ∃ x ∈ l, p x :=
bex.elim h (λ x xal px,
or.elim (eq_or_mem_of_mem_cons xal)
(assume : x = a, begin rw ←this, simp [px] end)
(assume : x ∈ l, or.inr (bex.intro x this px)))
@[simp] theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) :
(∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x :=
iff.intro or_exists_of_exists_mem_cons
(assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists)
@[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl
@[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl
theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a :=
by induction l with a l; simp [forall_and_distrib, *]
theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p]
{l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a :=
by simp [all_iff_forall]
@[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl
@[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl
theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a :=
by induction l with a l; simp [or_and_distrib_right, exists_or_distrib, *]
theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p]
{l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a :=
by simp [any_iff_exists]
theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p :=
any_iff_exists.2 ⟨_, h₁, h₂⟩
instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∀ x ∈ l, p x) :=
decidable_of_iff _ all_iff_forall_prop
instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∃ x ∈ l, p x) :=
decidable_of_iff _ any_iff_exists_prop
/- map for partial functions -/
/-- Partial map. If `f : Π a, p a → β` is a partial function defined on
`a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`
but is defined only when all members of `l` satisfy `p`, using the proof
to apply `f`. -/
@[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β
| [] H := []
| (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2
/-- "Attach" the proof that the elements of `l` are in `l` to produce a new list
with the same elements but in the type `{x // x ∈ l}`. -/
def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id)
theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) :
@pmap _ _ p (λ a _, f a) l H = map f l :=
by induction l; simp *
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f l H₁ = pmap g l H₂ :=
by induction l with _ _ ih; simp *; apply ih
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H :=
by induction l; simp *
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) :=
by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl)
theorem attach_map_val (l : list α) : l.attach.map subtype.val = l :=
by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l)
@[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ :=
by have := mem_map.1 (by rw [attach_map_val]; exact h);
{ rcases this with ⟨a, m, rfl⟩, cases a, exact m }
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b :=
by simp [pmap_eq_map_attach]
@[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β}
{l H} : length (pmap f l H) = length l :=
by induction l; simp *
/- find -/
section find
variables (p : α → Prop) [decidable_pred p]
/-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such
element exists. -/
def find : list α → option α
| [] := none
| (a::l) := if p a then some a else find l
def find_indexes_aux (p : α → Prop) [decidable_pred p] : list α → nat → list nat
| [] n := []
| (a::l) n := let t := find_indexes_aux l (succ n) in if p a then n :: t else t
/-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/
def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat :=
find_indexes_aux p l 0
@[simp] theorem find_nil : find p [] = none := rfl
@[simp] theorem find_cons_of_pos {p : α → Prop} [h : decidable_pred p] {a : α}
(l) (h : p a) : find p (a::l) = some a :=
if_pos h
@[simp] theorem find_cons_of_neg {p : α → Prop} [h : decidable_pred p] {a : α}
(l) (h : ¬ p a) : find p (a::l) = find p l :=
if_neg h
@[simp] theorem find_eq_none {p : α → Prop} [h : decidable_pred p] {l : list α} :
find p l = none ↔ ∀ x ∈ l, ¬ p x :=
begin
induction l with a l IH, {simp},
by_cases p a; simp [h, IH]
end
@[simp] theorem find_some {p : α → Prop} [h : decidable_pred p] {l : list α} {a : α}
(H : find p l = some a) : p a :=
begin
induction l with b l IH, {contradiction},
by_cases p b; simp [h] at H,
{ subst b, assumption },
{ exact IH H }
end
@[simp] theorem find_mem {p : α → Prop} [h : decidable_pred p] {l : list α} {a : α}
(H : find p l = some a) : a ∈ l :=
begin
induction l with b l IH, {contradiction},
by_cases p b; simp [h] at H,
{ subst b, apply mem_cons_self },
{ exact mem_cons_of_mem _ (IH H) }
end
end find
/-- `indexes_of a l` is the list of all indexes of `a` in `l`.
`indexes_of a [a, b, a, a] = [0, 2, 3]` -/
def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a)
/- filter_map -/
@[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) :
filter_map f (a :: l) = filter_map f l :=
by simp [filter_map, h]
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (l : list α) {b : β} (h : f a = some b) :
filter_map f (a :: l) = b :: filter_map f l :=
by simp [filter_map, h]
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
begin
funext l,
induction l with a l IH, {simp},
simp [filter_map_cons_some (some ∘ f) _ _ rfl, IH]
end
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
begin
funext l,
induction l with a l IH, {simp},
by_cases pa : p a; simp [filter_map, option.guard, pa, IH]
end
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) :
filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l :=
begin
induction l with a l IH, {refl},
cases h : f a with b,
{ rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH],
simp [h, option.bind] },
rw filter_map_cons_some _ _ _ h,
cases h' : g b with c;
[ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH],
rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ];
simp [h, h', option.bind]
end
theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) :
map g (filter_map f l) = filter_map (λ x, (f x).map g) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) :
filter_map g (map f l) = filter_map (g ∘ f) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) :
filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l :=
by rw [← filter_map_eq_filter, filter_map_filter_map]; refl
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) :
filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l :=
begin
rw [← filter_map_eq_filter, filter_map_filter_map], congr,
funext x,
show (option.guard p x).bind f = ite (p x) (f x) none,
by_cases p x; simp [h, option.guard, option.bind]
end
@[simp] theorem filter_map_some (l : list α) : filter_map some l = l :=
by rw filter_map_eq_map; apply map_id
@[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} :
b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b :=
begin
induction l with a l IH, {simp},
cases h : f a with b',
{ have : f a ≠ some b, {rw h, intro, contradiction},
simp [filter_map_cons_none _ _ h, IH,
or_and_distrib_right, exists_or_distrib, this] },
{ have : f a = some b ↔ b = b',
{ split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} },
simp [filter_map_cons_some _ _ _ h, IH,
or_and_distrib_right, exists_or_distrib, this] }
end
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (l : list α) :
map g (filter_map f l) = l :=
by simp [map_filter_map, H]
theorem filter_map_sublist_filter_map (f : α → option β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ :=
by induction s with l₁ l₂ a s IH l₁ l₂ a s IH;
simp [filter_map]; cases f a with b;
simp [filter_map, IH, sublist.cons, sublist.cons2]
theorem map_sublist_map (f : α → β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : map f l₁ <+ map f l₂ :=
by rw ← filter_map_eq_map; exact filter_map_sublist_filter_map _ s
/- filter -/
section filter
variables {p : α → Prop} [decidable_pred p]
@[simp] theorem filter_subset (l : list α) : filter p l ⊆ l :=
subset_of_sublist $ filter_sublist l
theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a
| [] ain := absurd ain (not_mem_nil a)
| (b::l) ain :=
if pb : p b then
have a ∈ b :: filter p l, begin simp [pb] at ain, assumption end,
or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, begin rw [← this] at pb, exact pb end)
(assume : a ∈ filter p l, of_mem_filter this)
else
begin simp [pb] at ain, exact (of_mem_filter ain) end
theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l :=
filter_subset l h
theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l
| [] ain pa := absurd ain (not_mem_nil a)
| (b::l) ain pa :=
if pb : p b then
or.elim (eq_or_mem_of_mem_cons ain)
(assume : a = b, by simp [pb, this])
(assume : a ∈ l, begin simp [pb], exact (mem_cons_of_mem _ (mem_filter_of_mem this pa)) end)
else
or.elim (eq_or_mem_of_mem_cons ain)
(assume : a = b, begin simp [this] at pa, contradiction end) --absurd (this ▸ pa) pb)
(assume : a ∈ l, by simp [pa, pb, mem_filter_of_mem this])
@[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a :=
⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩
theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a :=
begin
induction l with a l, {simp},
by_cases p a; simp [filter, *],
show filter p l ≠ a :: l, intro e,
have := filter_sublist l, rw e at this,
exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _)
end
theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a :=
by simp [-and.comm, eq_nil_iff_forall_not_mem, mem_filter]
theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ :=
by rw ← filter_map_eq_filter; exact filter_map_sublist_filter_map _ s
@[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l)
| [] := rfl
| (a::l) := by by_cases pa : p a; simp [span, take_while, drop_while, pa, span_eq_take_drop l]
@[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l
| [] := rfl
| (a::l) := by by_cases pa : p a; simp [take_while, drop_while, pa, take_while_append_drop l]
/-- `countp p l` is the number of elements of `l` that satisfy `p`. -/
def countp (p : α → Prop) [decidable_pred p] : list α → nat
| [] := 0
| (x::xs) := if p x then succ (countp xs) else countp xs
@[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 :=
if_pos pa
@[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l :=
if_neg pa
theorem countp_eq_length_filter (l) : countp p l = length (filter p l) :=
by induction l with x l; [refl, by_cases (p x)]; simp [*, -add_comm]
local attribute [simp] countp_eq_length_filter
@[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ :=
by simp
theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a :=
by simp [countp_eq_length_filter, length_pos_iff_exists_mem]
theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ :=
by simpa using length_le_of_sublist (filter_sublist_filter s)
end filter
/- count -/
section count
variable [decidable_eq α]
/-- `count a l` is the number of occurrences of `a` in `l`. -/
def count (a : α) : list α → nat := countp (eq a)
@[simp] theorem count_nil (a : α) : count a [] = 0 := rfl
theorem count_cons (a b : α) (l : list α) :
count a (b :: l) = if a = b then succ (count a l) else count a l := rfl
theorem count_cons' (a b : α) (l : list α) :
count a (b :: l) = count a l + (if a = b then 1 else 0) :=
decidable.by_cases
(assume : a = b, begin rw [count_cons, if_pos this, if_pos this] end)
(assume : a ≠ b, begin rw [count_cons, if_neg this, if_neg this], reflexivity end)
@[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) :=
if_pos rfl
@[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l :=
if_neg h
theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ :=
countp_le_of_sublist
theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) :=
count_le_of_sublist _ (sublist_cons _ _)
theorem count_singleton (a : α) : count a [a] = 1 :=
by simp
@[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ :=
countp_append
@[simp] theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) :=
by rw [concat_eq_append, count_append, count_singleton]
theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l :=
by simp [count, countp_pos]
@[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l :=
λ h', ne_of_gt (count_pos.2 h') h
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat];
exact λ b m, (eq_of_mem_repeat m).symm
theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l :=
⟨λ h, ((repeat_sublist_repeat a).2 h).trans $
have filter (eq a) l = repeat a (count a l), from eq_repeat.2
⟨by simp [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩,
by rw ← this; apply filter_sublist,
λ h, by simpa using count_le_of_sublist a h⟩
end count
/- prefix, suffix, infix -/
/-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`,
that is, `l₂` has the form `l₁ ++ t` for some `t`. -/
def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂
/-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`,
that is, `l₂` has the form `t ++ l₁` for some `t`. -/
def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂
/-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous
substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/
def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂
infix ` <+: `:50 := is_prefix
infix ` <:+ `:50 := is_suffix
infix ` <:+: `:50 := is_infix
@[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩
@[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩
@[simp] theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩
theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩
theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩
@[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩
@[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩
@[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a]
@[simp] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp
theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨[], t, h⟩
theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨t, [], by simp [h]⟩
@[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l
theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l
theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ :=
λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩
@[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃
| l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, by simp⟩
@[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃
| l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, by simp⟩
@[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃
| l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp⟩
theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ :=
λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _)
theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_prefix
theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_suffix
theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ :=
⟨λ ⟨r, e⟩, ⟨reverse r,
by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩,
λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩
theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ :=
by rw ← reverse_suffix; simp
theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ :=
length_le_of_sublist $ sublist_of_infix s
theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] :=
eq_nil_of_sublist_nil $ sublist_of_infix s
theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_prefix s
theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_suffix s
theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ :=
⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩,
λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩
theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_infix s
theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_prefix s
theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_suffix s
theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α},
l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂
| [] l₂ l₃ h₁ h₂ _ := nil_prefix _
| (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin
injection e with _ e', subst b,
rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩
(le_of_succ_le_succ ll) with ⟨r₃, rfl⟩,
exact ⟨r₃, rfl⟩
end
theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ :=
(le_total (length l₁) (length l₂)).imp
(prefix_of_prefix_length_le h₁ h₂)
(prefix_of_prefix_length_le h₂ h₁)
theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ :=
reverse_prefix.1 $ prefix_of_prefix_length_le
(reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll])
theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ :=
(prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp
reverse_prefix.1 reverse_prefix.1
theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L
| (_ :: L) l (or.inl rfl) := infix_append [] _ _
| (l' :: L) l (or.inr h) :=
is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _
theorem prefix_append_left_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ :=
exists_congr $ λ r, by rw [append_assoc, append_left_inj]
theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ :=
prefix_append_left_inj [a]
theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩
theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩
theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ :=
⟨λ h, let ⟨r, e⟩ := h in begin
rwa append_inj_left ((take_append_drop (length l₁) l₂).trans e.symm) _,
simp [min_eq_left, length_le_of_sublist (sublist_of_prefix h)],
end, λ e, ⟨_, e⟩⟩
theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ :=
⟨λ ⟨r, e⟩, begin
rwa append_inj_right ((take_append_drop (length l₂ - length l₁) l₂).trans e.symm) _,
simp [min_eq_left, nat.sub_le, e.symm],
apply nat.add_sub_cancel_left
end, λ e, ⟨_, e⟩⟩
theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ :=
⟨λ h, append_right_cancel $
(prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ take_prefix _ _⟩
theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ :=
⟨λ h, append_left_cancel $
(suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ drop_suffix _ _⟩
instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂)
| [] l₂ := is_true ⟨l₂, rfl⟩
| (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te
| (a::l₁) (b::l₂) :=
if h : a = b then
@decidable_of_iff _ _ (by rw [← h, prefix_cons_inj])
(decidable_prefix l₁ l₂)
else
is_false $ λ ⟨t, te⟩, h $ by injection te
-- Alternatively, use mem_tails
instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂)
| [] l₂ := is_true ⟨l₂, append_nil _⟩
| (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial
| l₁ l₂ := let len1 := length l₁, len2 := length l₂ in
if hl : len1 ≤ len2 then
decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop
else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h
/-- `inits l` is the list of initial segments of `l`.
`inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]]` -/
@[simp] def inits : list α → list (list α)
| [] := [[]]
| (a::l) := [] :: map (λt, a::t) (inits l)
@[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t
| s [] := suffices s = nil ↔ s <+: nil, by simpa,
⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩
| s (a::t) :=
suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa,
⟨λo, match s, o with
| ._, or.inl rfl := ⟨_, rfl⟩
| s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in
by rw [← hs, ← ht]; exact ⟨s, rfl⟩
end, λmi, match s, mi with
| [], ⟨._, rfl⟩ := or.inl rfl
| (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $
by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩
end⟩
/-- `tails l` is the list of terminal segments of `l`.
`tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []]` -/
@[simp] def tails : list α → list (list α)
| [] := [[]]
| (a::l) := (a::l) :: tails l
@[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t
| s [] := by simp; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩
| s (a::t) := by simp [mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from
⟨λo, match s, t, o with
| ._, t, or.inl rfl := suffix_refl _
| s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩
end, λe, match s, t, e with
| ._, t, ⟨[], rfl⟩ := or.inl rfl
| s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩)
end⟩
instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂)
| [] l₂ := is_true ⟨[], l₂, rfl⟩
| (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $
append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h
| l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $
by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm;
exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩
/- sublists -/
def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β)
| [] f r := f [] :: r
| (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r)
/-- `sublists' l` is the list of all (non-contiguous) sublists of `l`.
It differs from `sublists` only in the order of appearance of the sublists;
`sublists'` uses the first element of the list as the MSB,
`sublists` uses the first element of the list as the LSB.
`sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]` -/
def sublists' (l : list α) : list (list α) :=
sublists'_aux l id []
@[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl
@[simp] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl
theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) :
map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) :=
by induction l generalizing f r; simp! *
theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) :
sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' :=
by induction l generalizing f r; simp! *
theorem sublists'_aux_eq_sublists' (l f r) :
@sublists'_aux α β l f r = map f (sublists' l) ++ r :=
by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl
@[simp] theorem sublists'_cons (a : α) (l : list α) :
sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) :=
by rw [sublists', sublists'_aux]; simp [sublists'_aux_eq_sublists']
@[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t :=
begin
induction t with a t IH generalizing s; simp,
{ exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ },
split; intro h, rcases h with h | ⟨s, h, rfl⟩,
{ exact sublist_cons_of_sublist _ (IH.1 h) },
{ exact cons_sublist_cons _ (IH.1 h) },
{ cases h with _ _ _ h s _ _ h,
{ exact or.inl (IH.2 h) },
{ exact or.inr ⟨s, IH.2 h, rfl⟩ } }
end
@[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l
| [] := rfl
| (a::l) := by simp [-add_comm, *]; rw [← two_mul, mul_comm]; refl
def sublists_aux : list α → (list α → list β → list β) → list β
| [] f := []
| (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r)))
/-- `sublists l` is the list of all (non-contiguous) sublists of `l`.
`sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]` -/
def sublists (l : list α) : list (list α) :=
[] :: sublists_aux l cons
@[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl
@[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl
def sublists_aux₁ : list α → (list α → list β) → list β
| [] f := []
| (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys))
theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β),
sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r)
| [] f := rfl
| (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp *
theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) :
sublists_aux l cons = sublists_aux₁ l (λ x, [x]) :=
by rw [sublists_aux₁_eq_sublists_aux]; refl
theorem sublists_aux_eq_foldr.aux {a : α} {l : list α}
(IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons))
(IH₂ : ∀ (f : list α → list (list α) → list (list α)),
sublists_aux l f = foldr f [] (sublists_aux l cons))
(f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) :=
begin
simp [sublists_aux], rw [IH₂, IH₁], congr_n 1,
induction sublists_aux l cons with _ _ ih; simp *
end
theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β),
sublists_aux l f = foldr f [] (sublists_aux l cons) :=
suffices _ ∧ ∀ f : list α → list (list α) → list (list α),
sublists_aux l f = foldr f [] (sublists_aux l cons),
from this.1,
begin
induction l with a l IH, {split; intro; refl},
exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2,
sublists_aux_eq_foldr.aux IH.2 IH.2⟩
end
theorem sublists_aux_cons_cons (l : list α) (a : α) :
sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) :=
by rw [← sublists_aux_eq_foldr]; refl
theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β),
sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++
sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x)))
| [] l₂ f := by simp [sublists_aux₁]
| (a::l₁) l₂ f := by simp [sublists_aux₁];
rw [sublists_aux₁_append]; simp
theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) :
sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++
f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) :=
by simp [sublists_aux₁_append, sublists_aux₁]
theorem sublists_aux₁_bind : ∀ (l : list α)
(f : list α → list β) (g : β → list γ),
(sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g)
| [] f g := by simp [sublists_aux₁]
| (a::l) f g := by simp [sublists_aux₁];
rw [sublists_aux₁_bind]; simp
theorem sublists_aux_cons_append (l₁ l₂ : list α) :
sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++
(do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) :=
begin
simp [sublists, sublists_aux_cons_eq_sublists_aux₁],
rw [sublists_aux₁_append, sublists_aux₁_bind],
congr, funext x, simp,
rw [← bind_ret_eq_map, sublists_aux₁_bind], simp [list.ret]
end
theorem sublists_append (l₁ l₂ : list α) :
sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) :=
by simp [sublists_aux_cons_append, sublists, map_id']
@[simp] theorem sublists_concat (l : list α) (a : α) :
sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) :=
by simp [sublists_append];
rw [sublists, sublists_aux_cons_eq_sublists_aux₁];
simp [map_id', sublists_aux₁]
theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) :=
by induction l; simp [(∘), *]
theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) :=
by rw [← sublists_reverse, reverse_reverse]
theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) :=
by simp [sublists_eq_sublists', map_id']
theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) :=
by rw [← sublists'_reverse, reverse_reverse]
theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons
| [] := id
| (a::l) := begin
rw [sublists_aux_cons_cons],
refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _,
have := sublists_aux_ne_nil l, revert this,
induction sublists_aux l cons; intro; simp [not_or_distrib],
exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩
end
@[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t :=
by rw [← reverse_sublist_iff, ← mem_sublists',
sublists'_reverse, mem_map_of_inj reverse_injective]
@[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l :=
by simp [sublists_eq_sublists', length_sublists']
theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l :=
reverse_rec_on l (nil_sublist _) $
λ l a IH, by simp; exact
((append_sublist_append_left _).2
(singleton_sublist.2 $ mem_map.2 ⟨[], by simp [list.ret]⟩)).trans
((append_sublist_append_right _).2 IH)
/- transpose -/
def transpose_aux : list α → list (list α) → list (list α)
| [] ls := ls
| (a::i) [] := [a] :: transpose_aux i []
| (a::i) (l::ls) := (a::l) :: transpose_aux i ls
/-- transpose of a list of lists, treated as a matrix.
`transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]]` -/
def transpose : list (list α) → list (list α)
| [] := []
| (l::ls) := transpose_aux l (transpose ls)
/- permutations -/
section permutations
def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β
| [] f := (ts, r)
| (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in
(y :: us, f (t :: y :: us) :: zs)
private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l)
local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas
@[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v}
(H0 : ∀ is, C [] is)
(H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂
| [] is := H0 is
| (t::ts) is :=
have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from
show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)),
by rw nat.succ_add; exact prod.lex.right _ _ (lt_succ_self _),
have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ _ (lt_add_of_pos_left _ (succ_pos _)),
H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is [])
using_well_founded {
dec_tac := tactic.assumption,
rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] }
def permutations_aux : list α → list α → list (list α) :=
@@permutations_aux.rec (λ _ _, list (list α)) (λ is, [])
(λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2))
/-- List of all permutations of `l`.
permutations [1, 2, 3] =
[[1, 2, 3], [2, 1, 3], [3, 2, 1],
[2, 3, 1], [3, 1, 2], [1, 3, 2]] -/
def permutations (l : list α) : list (list α) :=
l :: permutations_aux l []
@[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] :=
by simp [permutations_aux, permutations_aux.rec]
@[simp] theorem permutations_aux_cons (t : α) (ts is : list α) :
permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2)
(permutations_aux ts (t::is)) (permutations is) :=
by simp [permutations_aux, permutations_aux.rec, permutations]
end permutations
/- insert -/
section insert
variable [decidable_eq α]
@[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl
theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl
@[simp] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l :=
by simp [insert.def, h]
@[simp] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l :=
by simp [insert.def, h]
@[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l :=
begin
by_cases h' : b ∈ l; simp [h'],
apply (or_iff_right_of_imp _).symm,
exact λ e, e.symm ▸ h'
end
@[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l :=
by by_cases a ∈ l; simp *
@[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l :=
mem_insert_iff.2 (or.inl rfl)
@[simp] theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l :=
mem_insert_iff.2 (or.inr h)
theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l :=
mem_insert_iff.1 h
@[simp] theorem length_insert_of_mem {a : α} [decidable_eq α] {l : list α} (h : a ∈ l) :
length (insert a l) = length l :=
by simp [h]
@[simp] theorem length_insert_of_not_mem {a : α} [decidable_eq α] {l : list α} (h : a ∉ l) :
length (insert a l) = length l + 1 :=
by simp [h]
end insert
/- erase -/
section erase
variable [decidable_eq α]
@[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl
theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl
@[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l :=
by simp [erase_cons]
@[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a :=
by simp [erase_cons, h]
@[simp] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l :=
by induction l with _ _ ih; [refl,
simp [(ne_of_not_mem_cons h).symm, ih (not_mem_of_not_mem_cons h)]]
theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) :
∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ :=
by induction l with b l ih; [cases h, {
simp at h,
by_cases e : b = a,
{ subst b, exact ⟨[], l, not_mem_nil _, rfl, by simp⟩ },
{ exact let ⟨l₁, l₂, h₁, h₂, h₃⟩ := ih (h.resolve_left (ne.symm e)) in
⟨b::l₁, l₂, not_mem_cons_of_ne_of_not_mem (ne.symm e) h₁,
by rw h₂; refl,
by simp [e, h₃]⟩ } }]
@[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) :=
match l, l.erase a, exists_erase_eq h with
| ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp [-add_comm]; refl
end
theorem erase_append_left {a : α} : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erase a = l₁.erase a ++ l₂
| (x::xs) l₂ h := begin
by_cases h' : x = a; simp [h'],
rw erase_append_left l₂ (mem_of_ne_of_mem (ne.symm h') h)
end
theorem erase_append_right {a : α} : ∀ {l₁ : list α} (l₂), a ∉ l₁ → (l₁++l₂).erase a = l₁ ++ l₂.erase a
| [] l₂ h := rfl
| (x::xs) l₂ h := by simp [*, (ne_of_not_mem_cons h).symm, (not_mem_of_not_mem_cons h)]
theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l :=
if h : a ∈ l then match l, l.erase a, exists_erase_eq h with
| ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp
end else by simp [h]
theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l :=
subset_of_sublist (erase_sublist a l)
theorem erase_sublist_erase (a : α) : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → l₁.erase a <+ l₂.erase a
| ._ ._ sublist.slnil := sublist.slnil
| ._ ._ (sublist.cons l₁ l₂ b s) := if h : b = a
then by rw [h, erase_cons_head]; exact (erase_sublist _ _).trans s
else by rw erase_cons_tail _ h; exact (erase_sublist_erase s).cons _ _ _
| ._ ._ (sublist.cons2 l₁ l₂ b s) := if h : b = a
then by rw [h, erase_cons_head, erase_cons_head]; exact s
else by rw [erase_cons_tail _ h, erase_cons_tail _ h]; exact (erase_sublist_erase s).cons2 _ _ _
theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l :=
@erase_subset _ _ _ _ _
@[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l :=
⟨mem_of_mem_erase, λ al,
if h : b ∈ l then match l, l.erase b, exists_erase_eq h, al with
| ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩, al := by simpa [ab] using al
end else by simp [h, al]⟩
theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a :=
if ab : a = b then by simp [ab] else
if ha : a ∈ l then
if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with
| ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb :=
if h₁ : b ∈ l₁ then
by rw [erase_append_left _ h₁, erase_append_left _ h₁,
erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head]
else
by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha',
erase_cons_tail _ ab, erase_cons_head]
end
else by simp [hb, mt mem_of_mem_erase hb]
else by simp [ha, mt mem_of_mem_erase ha]
end erase
/- diff -/
section diff
variable [decidable_eq α]
@[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl
@[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ :=
by by_cases a ∈ l₁; simp [list.diff, h]
theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂
| l₁ [] := rfl
| l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _)
@[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ :=
by simp [diff_eq_foldl]
end diff
/- zip & unzip -/
@[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) :
zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl
@[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl
@[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] :=
by cases l; refl
@[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl
@[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) :
unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) :=
by rw unzip; cases unzip l; refl
theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l
| [] := rfl
| ((a, b) :: l) := by simp [zip_unzip l]
/- enum -/
theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l
| n [] := rfl
| n (a::l) := congr_arg nat.succ (length_enum_from _ _)
theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _
@[simp] theorem enum_from_nth : ∀ n (l : list α) m,
nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m
| n [] m := rfl
| n (a :: l) 0 := rfl
| n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $
by rw [add_right_comm]; refl
@[simp] theorem enum_nth : ∀ (l : list α) n,
nth (enum l) n = (λ a, (n, a)) <$> nth l n :=
by simp [enum]
@[simp] theorem enum_from_map_snd : ∀ n (l : list α),
map prod.snd (enum_from n l) = l
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _)
@[simp] theorem enum_map_snd : ∀ (l : list α),
map prod.snd (enum l) = l := enum_from_map_snd _
/- product -/
/-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`.
product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
def product (l₁ : list α) (l₂ : list β) : list (α × β) :=
l₁.bind $ λ a, l₂.map $ prod.mk a
@[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl
@[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β)
: product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl
@[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = []
| [] := rfl
| (a::l) := by rw [product_cons, product_nil]; refl
@[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} :
(a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ :=
by simp [product, and.left_comm]
theorem length_product (l₁ : list α) (l₂ : list β) :
length (product l₁ l₂) = length l₁ * length l₂ :=
by induction l₁ with x l₁ IH; simp [*, right_distrib]
/- sigma -/
section
variable {σ : α → Type*}
/-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`.
sigma [1, 2] (λ_, [5, 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
def sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) :=
l₁.bind $ λ a, (l₂ a).map $ sigma.mk a
@[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl
@[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a))
: (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl
@[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = []
| [] := rfl
| (a::l) := by rw [sigma_cons, sigma_nil]; refl
@[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} :
sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a :=
by simp [sigma, and.left_comm]
theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
length (sigma l₁ l₂) = (l₁.map (λ a, length (l₂ a))).sum :=
by induction l₁ with x l₁ IH; simp *
end
/- disjoint -/
section disjoint
/-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/
def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false
theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁
| a i₂ i₁ := d i₁ i₂
@[simp] theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl
theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ :=
disjoint_comm
theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b :=
by simp [disjoint_left, imp_not_comm]
theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂
| x m₁ := d (ss m₁)
theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂
| x m m₁ := d m (ss m₁)
theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ :=
disjoint_of_subset_left (list.subset_cons _ _)
theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ :=
disjoint_of_subset_right (list.subset_cons _ _)
@[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l
| a := (not_mem_nil a).elim
@[simp] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l :=
by simp [disjoint]; refl
@[simp] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l :=
by rw disjoint_comm; simp
@[simp] theorem disjoint_append_left {l₁ l₂ l : list α} :
disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_append_right {l₁ l₂ l : list α} :
disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ :=
disjoint_comm.trans $ by simp [disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} :
disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ :=
(@disjoint_append_left _ [a] l₁ l₂).trans $ by simp
@[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} :
disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ :=
disjoint_comm.trans $ by simp [disjoint_cons_left]
theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l :=
(disjoint_append_left.1 d).1
theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l :=
(disjoint_append_left.1 d).2
theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ :=
(disjoint_append_right.1 d).1
theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ :=
(disjoint_append_right.1 d).2
end disjoint
/- union -/
section union
variable [decidable_eq α]
@[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl
@[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl
@[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ :=
by induction l₁; simp [*, or_assoc]
theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inl h)
theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inr h)
theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂
| [] l₂ := ⟨[], by refl, rfl⟩
| (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
by simp [e.symm]; by_cases h : a ∈ t ++ l₂;
[existsi t, existsi a::t]; simp [h];
[apply sublist_cons_of_sublist _ s, apply cons_sublist_cons _ s]
theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ :=
(sublist_suffix_of_union l₁ l₂).imp (λ a, and.right)
theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ :=
let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
e ▸ (append_sublist_append_right _).2 s
theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp [or_imp_distrib, forall_and_distrib]
theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x :=
(forall_mem_union.1 h).1
theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x :=
(forall_mem_union.1 h).2
end union
/- inter -/
section inter
variable [decidable_eq α]
@[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl
@[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) :
(a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) :=
if_pos h
@[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) :
(a::l₁) ∩ l₂ = l₁ ∩ l₂ :=
if_neg h
theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ :=
mem_of_mem_filter
theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ :=
of_mem_filter
theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ :=
mem_filter_of_mem
@[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ :=
mem_filter
theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ :=
filter_subset _
theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ :=
λ a, mem_of_mem_inter_right
theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ :=
λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩
theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ :=
by simp [eq_nil_iff_forall_not_mem]; refl
theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x)
(l₂ : list α) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_left) h
theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α}
(h : ∀ x ∈ l₂, p x) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_right) h
end inter
/- bag_inter -/
section bag_inter
variable [decidable_eq α]
@[simp] theorem nil_bag_inter (l : list α) : [].bag_inter l = [] :=
by cases l; refl
@[simp] theorem bag_inter_nil (l : list α) : l.bag_inter [] = [] :=
by cases l; refl
@[simp] theorem cons_bag_inter_of_pos {a} (l₁ : list α) {l₂} (h : a ∈ l₂) :
(a :: l₁).bag_inter l₂ = a :: l₁.bag_inter (l₂.erase a) :=
by cases l₂; exact if_pos h
@[simp] theorem cons_bag_inter_of_neg {a} (l₁ : list α) {l₂} (h : a ∉ l₂) :
(a :: l₁).bag_inter l₂ = l₁.bag_inter l₂ :=
by cases l₂; simp [h, list.bag_inter]
theorem mem_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁.bag_inter l₂ ↔ a ∈ l₁ ∧ a ∈ l₂
| [] l₂ := by simp
| (b::l₁) l₂ := by
by_cases b ∈ l₂; simp [*, and_or_distrib_left];
by_cases ba : a = b; simp *
theorem bag_inter_sublist_left : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ <+ l₁
| [] l₂ := by simp [nil_sublist]
| (b::l₁) l₂ := begin
by_cases b ∈ l₂; simp [h],
{ apply cons_sublist_cons, apply bag_inter_sublist_left },
{ apply sublist_cons_of_sublist, apply bag_inter_sublist_left }
end
end bag_inter
/- pairwise relation (generalized no duplicate) -/
section pairwise
variable (R : α → α → Prop)
/-- `pairwise R l` means that all the elements with earlier indexes are
`R`-related to all the elements with later indexes.
pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3
For example if `R = (≠)` then it asserts `l` has no duplicates,
and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/
inductive pairwise : list α → Prop
| nil : pairwise []
| cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l)
attribute [simp] pairwise.nil
variable {R}
@[simp] theorem pairwise_cons {a : α} {l : list α} :
pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l :=
⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
theorem rel_of_pairwise_cons {a : α} {l : list α}
(p : pairwise R (a::l)) : ∀ {a'}, a' ∈ l → R a a' :=
(pairwise_cons.1 p).1
theorem pairwise_of_pairwise_cons {a : α} {l : list α}
(p : pairwise R (a::l)) : pairwise R l :=
(pairwise_cons.1 p).2
theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α}
(H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l :=
begin
induction p with a l r p IH generalizing H; constructor,
{ exact ball.imp_right
(λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r },
{ exact IH (λ a b m m', H
(mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) }
end
theorem pairwise.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l :=
pairwise.imp_of_mem (λ a b _ _, H a b)
theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α}
(H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l :=
⟨pairwise.imp_of_mem (λ a b m m', (H m m').1),
pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩
theorem pairwise.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l :=
pairwise.iff_of_mem (λ a b _ _, H a b)
theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l :=
by induction l; simp *
theorem pairwise.and_mem {l : list α} :
pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l :=
pairwise.iff_of_mem (by simp {contextual := tt})
theorem pairwise.imp_mem {l : list α} :
pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l :=
pairwise.iff_of_mem (by simp {contextual := tt})
theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁
| ._ ._ sublist.slnil h := h
| ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n
| ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) :=
(pairwise_of_sublist s n).cons (ball.imp_left (subset_of_sublist s) i)
theorem pairwise_singleton (R) (a : α) : pairwise R [a] :=
by simp
theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b :=
by simp
theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔
pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y :=
by induction l₁ with x l₁ IH; simp [*,
or_imp_distrib, forall_and_distrib, and_assoc, and.left_comm]
theorem pairwise_app_comm (s : symmetric R) {l₁ l₂ : list α} :
pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) :=
have ∀ l₁ l₂ : list α,
(∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) →
(∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y),
from λ l₁ l₂ a x xm y ym, s (a y ym x xm),
by simp [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁)
theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} :
pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) :=
show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂),
by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_app_comm s];
simp only [mem_append, or_comm]
theorem pairwise_map (f : β → α) :
∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l
| [] := by simp
| (b::l) :=
have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from
forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp,
by simp *; rw this
theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α}
(p : pairwise S (map f l)) : pairwise R l :=
((pairwise_map f).1 p).imp H
theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α}
(p : pairwise R l) : pairwise S (map f l) :=
(pairwise_map f).2 $ p.imp H
theorem pairwise_filter_map (f : β → option α) {l : list β} :
pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l :=
let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in
begin
simp, induction l with a l IH; simp,
cases e : f a with b; simp [e, IH],
rw [filter_map_cons_some _ _ _ e], simp [IH],
show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔
(∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l,
from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl
end
theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β)
(H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α}
(p : pairwise R l) : pairwise S (filter_map f l) :=
(pairwise_filter_map _).2 $ p.imp H
theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} :
pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l :=
begin
rw [← filter_map_eq_filter, pairwise_filter_map],
apply pairwise.iff, simp
end
theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α}
: pairwise R l → pairwise R (filter p l) :=
pairwise_of_sublist (filter_sublist _)
theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔
(∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L :=
begin
induction L with l L IH, {simp},
have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔
∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y :=
⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩,
simp [pairwise_append, IH, this], simp [and_assoc, and_comm, and.left_comm],
end
@[simp] theorem pairwise_reverse : ∀ {R} {l : list α},
pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l :=
suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l),
from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩,
λ R l p, by induction p with a l h p IH;
[simp, simpa [pairwise_append, IH] using h]
theorem pairwise_iff_nth_le {R} : ∀ {l : list α},
pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁)
| [] := by simp; exact λ i j h, (not_lt_zero j).elim h
| (a::l) := begin
rw [pairwise_cons, pairwise_iff_nth_le],
refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _,
λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩,
{ cases j with j, {exact (not_lt_zero _).elim h₂},
cases i with i,
{ apply H.1, simp [nth_le_mem] },
{ exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } },
{ rcases nth_le_of_mem m with ⟨n, h, rfl⟩,
exact H _ _ (succ_lt_succ h) (succ_pos _) }
end
inductive lex (R : α → α → Prop) : list α → list α → Prop
| nil {} (a l) : lex [] (a::l)
| cons {} (a) {l l'} : lex l l' → lex (a::l) (a::l')
| rel {a a'} (l l') : R a a' → lex (a::l) (a'::l')
theorem lex_append_right (R : α → α → Prop) :
∀ {s₁ s₂} t, lex R s₁ s₂ → lex R s₁ (s₂ ++ t)
| _ _ t (lex.nil a l) := lex.nil _ _
| _ _ t (lex.cons a h) := lex.cons _ (lex_append_right _ h)
| _ _ t (lex.rel _ _ r) := lex.rel _ _ r
theorem lex_append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) :
∀ s, lex R (s ++ t₁) (s ++ t₂)
| [] := h
| (a::l) := lex.cons _ (lex_append_left l)
theorem lex.imp {R S : α → α → Prop} (H : ∀ a b, R a b → S a b) :
∀ l₁ l₂, lex R l₁ l₂ → lex S l₁ l₂
| _ _ (lex.nil a l) := lex.nil _ _
| _ _ (lex.cons a h) := lex.cons _ (lex.imp _ _ h)
| _ _ (lex.rel _ _ r) := lex.rel _ _ (H _ _ r)
theorem ne_of_lex_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂
| _ _ (lex.cons a h) e := ne_of_lex_ne h (list.cons.inj e).2
| _ _ (lex.rel _ _ r) e := r (list.cons.inj e).1
theorem lex_ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) :
lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ :=
⟨ne_of_lex_ne, λ h, begin
induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂,
{ contradiction },
{ apply lex.nil },
{ exact (not_lt_of_ge H).elim (succ_pos _) },
{ cases classical.em (a = b) with ab ab,
{ subst b, apply lex.cons,
exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) },
{ exact lex.rel _ _ ab } }
end⟩
theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l →
pairwise (lex (swap R)) (sublists' l)
| _ (pairwise.nil _) := pairwise_singleton _ _
| _ (@pairwise.cons _ _ a l H₁ H₂) :=
begin
simp [pairwise_append, pairwise_map],
have IH := pairwise_sublists' H₂,
refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons _), _⟩,
intros l₁ sl₁ x l₂ sl₂ e, subst e,
cases l₁ with b l₁, {constructor},
exact lex.rel _ _ (H₁ _ $ subset_of_sublist sl₁ $ mem_cons_self _ _)
end
theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) :
pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) :=
by have := pairwise_sublists' (pairwise_reverse.2 H);
rwa [sublists'_reverse, pairwise_map] at this
variable [decidable_rel R]
instance decidable_pairwise (l : list α) : decidable (pairwise R l) :=
by induction l; simp; resetI; apply_instance
/- pairwise reduct -/
/-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`.
`pw_filter (≠)` is the erase duplicates function, and `pw_filter (<)` finds
a maximal increasing subsequence in `l`. For example,
pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 5, 6] -/
def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α
| [] := []
| (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH
@[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl
@[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) :
pw_filter R (a::l) = a :: pw_filter R l := if_pos h
@[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) :
pw_filter R (a::l) = pw_filter R l := if_neg h
theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l
| [] := nil_sublist _
| (x::l) := begin
by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h,
{ rw [pw_filter_cons_of_pos h],
exact cons_sublist_cons _ (pw_filter_sublist l) },
{ rw [pw_filter_cons_of_neg h],
exact sublist_cons_of_sublist _ (pw_filter_sublist l) },
end
theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l :=
subset_of_sublist (pw_filter_sublist _)
theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l)
| [] := pairwise.nil _
| (x::l) := begin
by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h,
{ rw [pw_filter_cons_of_pos h],
exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ },
{ rw [pw_filter_cons_of_neg h],
exact pairwise_pw_filter l },
end
theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l :=
⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin
induction l with x l IH, {simp},
cases pairwise_cons.1 p with al p,
rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p],
end⟩
theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z)
(a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) :=
⟨begin
induction l with x l IH; simp *,
by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h,
{ simp [pw_filter_cons_of_pos h],
exact λ r H, ⟨r, IH H⟩ },
{ rw [pw_filter_cons_of_neg h],
refine λ H, ⟨_, IH H⟩,
cases e : find (λ y, ¬ R x y) (pw_filter R l) with k,
{ refine h.elim (ball.imp_right _ (find_eq_none.1 e)),
exact λ y _, not_not.1 },
{ have := find_some e,
exact (neg_trans (H k (find_mem e))).resolve_right this } }
end, ball.imp_left (pw_filter_subset l)⟩
end pairwise
/- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/
section chain
variable (R : α → α → Prop)
/-- `chain R a l` means that `R` holds between adjacent elements of `a::l`.
`chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d` -/
inductive chain : α → list α → Prop
| nil (a : α) : chain a []
| cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l)
attribute [simp] chain.nil
variable {R}
@[simp] theorem chain_cons {a b : α} {l : list α} :
chain R a (b::l) ↔ R a b ∧ chain R b l :=
⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
theorem rel_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b::l)) : R a b :=
(chain_cons.1 p).1
theorem chain_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b::l)) : chain R b l :=
(chain_cons.1 p).2
theorem chain.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l :=
by induction p with _ a b l r p IH; constructor;
[exact H _ _ r, exact IH]
theorem chain.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l :=
⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩
theorem chain.iff_mem {S : α → α → Prop} {a : α} {l : list α} :
chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l :=
⟨λ p, by induction p with _ a b l r p IH; constructor;
[exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩,
exact IH.imp (λ a b ⟨am, bm, h⟩,
⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)],
chain.imp (λ a b h, h.2.2)⟩
theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b :=
by simp
theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔
chain R a (l₁++[b]) ∧ chain R b l₂ :=
by induction l₁ with x l₁ IH generalizing a; simp [*, and_assoc]
theorem chain_map (f : β → α) {b : β} {l : list β} :
chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l :=
by induction l generalizing b; simp *
theorem chain_of_chain_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α}
(p : chain S (f a) (map f l)) : chain R a l :=
((chain_map f).1 p).imp H
theorem chain_map_of_chain {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α}
(p : chain R a l) : chain S (f a) (map f l) :=
(chain_map f).2 $ p.imp H
theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l :=
begin
cases pairwise_cons.1 p with r p', clear p,
induction p' with b l r' p IH generalizing a; simp,
simp at r, simp [r],
show chain R b l, from IH r'
end
theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} :
chain R a l ↔ pairwise R (a::l) :=
⟨λ c, begin
induction c with b b c l r p IH, {simp},
apply IH.cons _, simp [r],
show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)),
end, chain_of_pairwise⟩
instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) :=
by induction l generalizing a; simp; resetI; apply_instance
end chain
/- no duplicates predicate -/
/-- `nodup l` means that `l` has no duplicates, that is, any element appears at most
once in the list. It is defined as `pairwise (≠)`. -/
def nodup : list α → Prop := pairwise (≠)
section nodup
@[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l :=
⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩
@[simp] theorem nodup_nil : @nodup α [] := pairwise.nil _
@[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l :=
by simp [nodup]
theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) :=
nodup_cons.2 ⟨m, n⟩
theorem nodup_singleton (a : α) : nodup [a] :=
nodup_cons_of_nodup (not_mem_nil a) nodup_nil
theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l :=
(nodup_cons.1 h).2
theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l :=
(nodup_cons.1 h).1
theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) :=
imp_not_comm.1 not_mem_of_nodup_cons
theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ :=
pairwise_of_sublist
theorem not_nodup_pair (a : α) : ¬ nodup [a, a] :=
not_nodup_cons_of_mem $ mem_singleton_self _
theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l :=
⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin
induction l with a l IH; intro h, {simp},
exact nodup_cons_of_nodup
(λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al)
(IH $ λ a s, h a $ sublist_cons_of_sublist _ s)
end⟩
theorem nodup_iff_nth_le_inj {l : list α} :
nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j :=
pairwise_iff_nth_le.trans
⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _)
.resolve_left (λ h', H _ _ h₂ h' h))
.resolve_right (λ h', H _ _ h₁ h' h.symm),
λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩
@[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n :=
nodup_iff_nth_le_inj.1 H _ _ _ h $
index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _
theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 :=
nodup_iff_sublist.trans $ forall_congr $ λ a,
have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm,
(not_congr this).trans not_lt
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α}
(d : nodup l) (h : a ∈ l) : count a l = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h)
theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ :=
nodup_of_sublist (sublist_append_left l₁ l₂)
theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ :=
nodup_of_sublist (sublist_append_right l₁ l₂)
theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ :=
by simp [nodup, pairwise_append, disjoint_iff_ne]
theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ :=
(nodup_append.1 d).2.2
theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) :=
nodup_append.2 ⟨d₁, d₂, dj⟩
theorem nodup_app_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) :=
by simp [nodup_append, and.left_comm]
theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) :=
by simp [nodup_append, not_or_distrib, and.left_comm, and_assoc]
theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l :=
pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f
theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y)
(d : nodup l) : nodup (map f l) :=
pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d)
theorem nodup_map {f : α → β} {l : list α} (hf : injective f) : nodup l → nodup (map f l) :=
nodup_map_on (assume x _ y _ h, hf h)
theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l :=
⟨nodup_of_nodup_map _, nodup_map hf⟩
@[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l :=
⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h,
λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩
theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) :=
by rw [pmap_eq_map_attach]; exact nodup_map
(λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h)
(nodup_attach.2 h)
theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) :=
pairwise_filter_of_pairwise p
@[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l :=
pairwise_reverse.trans $ by simp [nodup, eq_comm]
instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) :=
list.decidable_pairwise
theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : l.erase a = filter (≠ a) l :=
begin
induction d with b l m d IH; simp [list.erase, list.filter],
by_cases b = a; simp *, subst b,
show l = filter (λ a', ¬ a' = a) l, rw filter_eq_self.2,
simpa only [eq_comm] using m
end
theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) :=
nodup_of_sublist (erase_sublist _ _)
theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw nodup_erase_eq_filter b d; simp [and_comm]
theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a :=
by rw mem_erase_iff_of_nodup h; simp
theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L :=
by simp [nodup, pairwise_join, disjoint_left.symm]
theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔
(∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ :=
by simp [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm];
rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔
(∀ (x : α), x ∈ l₁ → nodup (f x)),
from forall_swap.trans $ forall_congr $ λ_, by simp]
theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) :
nodup (product l₁ l₂) :=
nodup_bind.2
⟨λ a ma, nodup_map (injective_of_left_inverse (λ b, (rfl : (a,b).2 = b))) d₂,
d₁.imp (λ a₁ a₂ n x,
suffices ∀ (b₁ : β), b₁ ∈ l₂ → (a₁, b₁) = x → ∀ (b₂ : β), b₂ ∈ l₂ → (a₂, b₂) ≠ x, by simpa,
λ b₁ mb₁ e b₂ mb₂ e', by subst e'; injection e; contradiction)⟩
theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)}
(d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (sigma l₁ l₂) :=
nodup_bind.2
⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a),
d₁.imp (λ a₁ a₂ n x,
suffices ∀ (b₁ : σ a₁), sigma.mk a₁ b₁ = x → b₁ ∈ l₂ a₁ →
∀ (b₂ : σ a₂), sigma.mk a₂ b₂ = x → b₂ ∉ l₂ a₂, by simpa [and_comm],
λ b₁ e mb₁ b₂ e' mb₂, by subst e'; injection e; contradiction)⟩
theorem nodup_filter_map {f : α → option β} {l : list α}
(H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') :
nodup l → nodup (filter_map f l) :=
pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm'
theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) :=
by simp; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h)
theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) :=
by by_cases h' : a ∈ l; simp [h', h]; apply nodup_cons h' h
theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) :
nodup (l₁ ∪ l₂) :=
begin
induction l₁ with a l₁ ih generalizing l₂,
{ exact h },
simp,
apply nodup_insert,
exact ih h
end
theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) :=
nodup_filter _
@[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l :=
⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h),
λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 (ne_of_lex_ne h))⟩
@[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l :=
by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective,
nodup_sublists, nodup_reverse]
end nodup
/- erase duplicates function -/
section erase_dup
variable [decidable_eq α]
/-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence).
erase_dup [1, 2, 2, 0, 1] = [1, 2, 0] -/
def erase_dup : list α → list α := pw_filter (≠)
@[simp] theorem erase_dup_nil : erase_dup [] = ([] : list α) := rfl
theorem erase_dup_cons_of_mem' {a : α} {l : list α} (h : a ∈ erase_dup l) :
erase_dup (a::l) = erase_dup l :=
pw_filter_cons_of_neg $ by simpa using h
theorem erase_dup_cons_of_not_mem' {a : α} {l : list α} (h : a ∉ erase_dup l) :
erase_dup (a::l) = a :: erase_dup l :=
pw_filter_cons_of_pos $ by simpa using h
@[simp] theorem mem_erase_dup {a : α} {l : list α} : a ∈ erase_dup l ↔ a ∈ l :=
by simpa using not_congr (@forall_mem_pw_filter α (≠) _
(λ x y z xz, not_and_distrib.1 $ mt (and.rec eq.trans) xz) a l)
@[simp] theorem erase_dup_cons_of_mem {a : α} {l : list α} (h : a ∈ l) :
erase_dup (a::l) = erase_dup l :=
erase_dup_cons_of_mem' $ mem_erase_dup.2 h
@[simp] theorem erase_dup_cons_of_not_mem {a : α} {l : list α} (h : a ∉ l) :
erase_dup (a::l) = a :: erase_dup l :=
erase_dup_cons_of_not_mem' $ mt mem_erase_dup.1 h
theorem erase_dup_sublist : ∀ (l : list α), erase_dup l <+ l := pw_filter_sublist
theorem erase_dup_subset : ∀ (l : list α), erase_dup l ⊆ l := pw_filter_subset
theorem subset_erase_dup (l : list α) : l ⊆ erase_dup l :=
λ a, mem_erase_dup.2
theorem nodup_erase_dup : ∀ l : list α, nodup (erase_dup l) := pairwise_pw_filter
theorem erase_dup_eq_self {l : list α} : erase_dup l = l ↔ nodup l := pw_filter_eq_self
theorem erase_dup_append (l₁ l₂ : list α) : erase_dup (l₁ ++ l₂) = l₁ ∪ erase_dup l₂ :=
begin
induction l₁ with a l₁ IH; simp, rw ← IH,
show erase_dup (a :: (l₁ ++ l₂)) = insert a (erase_dup (l₁ ++ l₂)),
by_cases a ∈ erase_dup (l₁ ++ l₂);
[ rw [erase_dup_cons_of_mem' h, insert_of_mem h],
rw [erase_dup_cons_of_not_mem' h, insert_of_not_mem h]]
end
end erase_dup
/- iota and range -/
/-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`.
It is intended mainly for proving properties of `range` and `iota`. -/
@[simp] def range' : ℕ → ℕ → list ℕ
| s 0 := []
| s (n+1) := s :: range' (s+1) n
@[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n
| s 0 := rfl
| s (n+1) := congr_arg succ (length_range' _ _)
@[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n
| s 0 := by simp
| s (n+1) :=
have m = s → m < s + (n + 1),
from λ e, e ▸ lt_succ_of_le (le_add_right _ _),
have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m,
by simpa [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm,
by simp [@mem_range' (s+1) n, or_and_distrib_left, or_iff_right_of_imp this, l]
theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n)
| s 0 := chain.nil _ _
| s (n+1) := (chain_succ_range' (s+1) n).cons rfl
theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) :=
(chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _)
theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n)
| s 0 := pairwise.nil _
| s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n)
theorem nodup_range' (s n : ℕ) : nodup (range' s n) :=
(pairwise_lt_range' s n).imp (λ a b, ne_of_lt)
theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m)
| s 0 n := rfl
| s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m),
by rw [add_right_comm, range'_append]
theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n :=
⟨λ h, by simpa using length_le_of_sublist h,
λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩
theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n :=
⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $
(mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2,
λ h, subset_of_sublist (range'_sublist_right.2 h)⟩
theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m)
| s 0 (n+1) _ := by simp
| s (m+1) (n+1) h := by simp [nth_range' (s+1) (lt_of_add_lt_add_right h)]
theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] :=
by rw add_comm n 1; exact (range'_append s n 1).symm
theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s)
| 0 n := rfl
| (s+1) n := by rw [show n+(s+1) = n+1+s, by simp]; exact range_core_range' s (n+1)
theorem range_eq_range' (n : ℕ) : range n = range' 0 n :=
(range_core_range' n 0).trans $ by rw zero_add
@[simp] theorem length_range (n : ℕ) : length (range n) = n :=
by simp [range_eq_range']
theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) :=
by simp [range_eq_range', pairwise_lt_range']
theorem nodup_range (n : ℕ) : nodup (range n) :=
by simp [range_eq_range', nodup_range']
theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n :=
by simp [range_eq_range', range'_sublist_right]
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n :=
by simp [range_eq_range', range'_subset_right]
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n :=
by simp [range_eq_range', zero_le]
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n :=
mt mem_range.1 $ lt_irrefl _
theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m :=
by simp [range_eq_range', nth_range' _ h]
theorem range_concat (n : ℕ) : range (n + 1) = range n ++ [n] :=
by simp [range_eq_range', range'_concat]
theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n)
| 0 := rfl
| (n+1) := by simp [iota, range'_concat, iota_eq_reverse_range' n]
@[simp] theorem length_iota (n : ℕ) : length (iota n) = n :=
by simp [iota_eq_reverse_range']
theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) :=
by simp [iota_eq_reverse_range', pairwise_lt_range']
theorem nodup_iota (n : ℕ) : nodup (iota n) :=
by simp [iota_eq_reverse_range', nodup_range']
theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n :=
by simp [iota_eq_reverse_range', lt_succ_iff]
@[simp] theorem enum_from_map_fst : ∀ n (l : list α),
map prod.fst (enum_from n l) = range' n l.length
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _)
@[simp] theorem enum_map_fst (l : list α) :
map prod.fst (enum l) = range l.length :=
by simp [enum, range_eq_range']
end list
theorem option.to_list_nodup {α} (o : option α) : o.to_list.nodup :=
by cases o; simp [option.to_list]
|
914a702579d9c8d06ec5f5a8e3b09732369c921d | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/control/traversable/lemmas.lean | 9c02a3d0b5fa17036012aa5fc6651bf864f3d22c | [
"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 | 3,805 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
Lemmas about traversing collections.
Inspired by:
The Essence of the Iterator Pattern
Jeremy Gibbons and Bruno César dos Santos Oliveira
In Journal of Functional Programming. Vol. 19. No. 3&4. Pages 377−402. 2009.
<http://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf>
-/
import control.traversable.basic
import control.applicative
universe variables u
open is_lawful_traversable
open function (hiding comp)
open functor
attribute [functor_norm] is_lawful_traversable.naturality
attribute [simp] is_lawful_traversable.id_traverse
namespace traversable
variable {t : Type u → Type u}
variables [traversable t] [is_lawful_traversable t]
variables F G : Type u → Type u
variables [applicative F] [is_lawful_applicative F]
variables [applicative G] [is_lawful_applicative G]
variables {α β γ : Type u}
variables g : α → F β
variables h : β → G γ
variables f : β → γ
/-- The natural applicative transformation from the identity functor
to `F`, defined by `pure : Π {α}, α → F α`. -/
def pure_transformation : applicative_transformation id F :=
{ app := @pure F _,
preserves_pure' := λ α x, rfl,
preserves_seq' := λ α β f x, by simp; refl }
@[simp] theorem pure_transformation_apply {α} (x : id α) :
(pure_transformation F) x = pure x := rfl
variables {F G} (x : t β)
lemma map_eq_traverse_id : map f = @traverse t _ _ _ _ _ (id.mk ∘ f) :=
funext $ λ y, (traverse_eq_map_id f y).symm
theorem map_traverse (x : t α) :
map f <$> traverse g x = traverse (map f ∘ g) x :=
begin
rw @map_eq_traverse_id t _ _ _ _ f,
refine (comp_traverse (id.mk ∘ f) g x).symm.trans _,
congr, apply comp.applicative_comp_id
end
theorem traverse_map (f : β → F γ) (g : α → β) (x : t α) :
traverse f (g <$> x) = traverse (f ∘ g) x :=
begin
rw @map_eq_traverse_id t _ _ _ _ g,
refine (comp_traverse f (id.mk ∘ g) x).symm.trans _,
congr, apply comp.applicative_id_comp
end
lemma pure_traverse (x : t α) :
traverse pure x = (pure x : F (t α)) :=
by have : traverse pure x = pure (traverse id.mk x) :=
(naturality (pure_transformation F) id.mk x).symm;
rwa id_traverse at this
lemma id_sequence (x : t α) :
sequence (id.mk <$> x) = id.mk x :=
by simp [sequence, traverse_map, id_traverse]; refl
lemma comp_sequence (x : t (F (G α))) :
sequence (comp.mk <$> x) = comp.mk (sequence <$> sequence x) :=
by simp [sequence, traverse_map]; rw ← comp_traverse; simp [map_id]
lemma naturality' (η : applicative_transformation F G) (x : t (F α)) :
η (sequence x) = sequence (@η _ <$> x) :=
by simp [sequence, naturality, traverse_map]
@[functor_norm]
lemma traverse_id :
traverse id.mk = (id.mk : t α → id (t α)) :=
by ext; simp [id_traverse]; refl
@[functor_norm]
lemma traverse_comp (g : α → F β) (h : β → G γ) :
traverse (comp.mk ∘ map h ∘ g) =
(comp.mk ∘ map (traverse h) ∘ traverse g : t α → comp F G (t γ)) :=
by ext; simp [comp_traverse]
lemma traverse_eq_map_id' (f : β → γ) :
traverse (id.mk ∘ f) =
id.mk ∘ (map f : t β → t γ) :=
by ext;rw traverse_eq_map_id
-- @[functor_norm]
lemma traverse_map' (g : α → β) (h : β → G γ) :
traverse (h ∘ g) =
(traverse h ∘ map g : t α → G (t γ)) :=
by ext; simp [traverse_map]
lemma map_traverse' (g : α → G β) (h : β → γ) :
traverse (map h ∘ g) =
(map (map h) ∘ traverse g : t α → G (t γ)) :=
by ext; simp [map_traverse]
lemma naturality_pf (η : applicative_transformation F G) (f : α → F β) :
traverse (@η _ ∘ f) = @η _ ∘ (traverse f : t α → F (t β)) :=
by ext; simp [naturality]
end traversable
|
852a4f1cc9e3f4bbed1b70983e8987cda83e1100 | 626e312b5c1cb2d88fca108f5933076012633192 | /src/measure_theory/integral/set_integral.lean | ef507d23cd41faf178d808bfcc2130b70b2396ac | [
"Apache-2.0"
] | permissive | Bioye97/mathlib | 9db2f9ee54418d29dd06996279ba9dc874fd6beb | 782a20a27ee83b523f801ff34efb1a9557085019 | refs/heads/master | 1,690,305,956,488 | 1,631,067,774,000 | 1,631,067,774,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 41,673 | lean | /-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Yury Kudryashov
-/
import measure_theory.integral.integrable_on
import measure_theory.integral.bochner
/-!
# Set integral
In this file we prove some properties of `∫ x in s, f x ∂μ`. Recall that this notation
is defined as `∫ x, f x ∂(μ.restrict s)`. In `integral_indicator` we prove that for a measurable
function `f` and a measurable set `s` this definition coincides with another natural definition:
`∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ`, where `indicator s f x` is equal to `f x` for `x ∈ s`
and is zero otherwise.
Since `∫ x in s, f x ∂μ` is a notation, one can rewrite or apply any theorem about `∫ x, f x ∂μ`
directly. In this file we prove some theorems about dependence of `∫ x in s, f x ∂μ` on `s`, e.g.
`integral_union`, `integral_empty`, `integral_univ`.
We use the property `integrable_on f s μ := integrable f (μ.restrict s)`, defined in
`measure_theory.integrable_on`. We also defined in that same file a predicate
`integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at
some set `s ∈ l`.
Finally, we prove a version of the
[Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus)
for set integral, see `filter.tendsto.integral_sub_linear_is_o_ae` and its corollaries.
Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and
a function `f` that has a finite limit `c` at `l ⊓ μ.ae`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)`
as `s` tends to `l.lift' powerset`, i.e. for any `ε>0` there exists `t ∈ l` such that
`∥∫ x in s, f x ∂μ - μ s • c∥ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this
theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`.
## Notation
We provide the following notations for expressing the integral of a function on a set :
* `∫ a in s, f a ∂μ` is `measure_theory.integral (μ.restrict s) f`
* `∫ a in s, f a` is `∫ a in s, f a ∂volume`
Note that the set notations are defined in the file `measure_theory/bochner_integration`,
but we reference them here because all theorems about set integrals are in this file.
## TODO
The file ends with over a hundred lines of commented out code. This is the old contents of this file
using the `indicator` approach to the definition of `∫ x in s, f x ∂μ`. This code should be
migrated to the new definition.
-/
noncomputable theory
open set filter topological_space measure_theory function
open_locale classical topological_space interval big_operators filter ennreal measure_theory
variables {α β E F : Type*} [measurable_space α]
namespace measure_theory
section normed_group
variables [normed_group E] [measurable_space E] {f g : α → E} {s t : set α} {μ ν : measure α}
{l l' : filter α} [borel_space E] [second_countable_topology E]
variables [complete_space E] [normed_space ℝ E]
lemma set_integral_congr_ae (hs : measurable_set s) (h : ∀ᵐ x ∂μ, x ∈ s → f x = g x) :
∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ :=
integral_congr_ae ((ae_restrict_iff' hs).2 h)
lemma set_integral_congr (hs : measurable_set s) (h : eq_on f g s) :
∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ :=
set_integral_congr_ae hs $ eventually_of_forall h
lemma integral_union (hst : disjoint s t) (hs : measurable_set s) (ht : measurable_set t)
(hfs : integrable_on f s μ) (hft : integrable_on f t μ) :
∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ :=
by simp only [integrable_on, measure.restrict_union hst hs ht, integral_add_measure hfs hft]
lemma integral_empty : ∫ x in ∅, f x ∂μ = 0 := by rw [measure.restrict_empty, integral_zero_measure]
lemma integral_univ : ∫ x in univ, f x ∂μ = ∫ x, f x ∂μ := by rw [measure.restrict_univ]
lemma integral_add_compl (hs : measurable_set s) (hfi : integrable f μ) :
∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ :=
by rw [← integral_union (@disjoint_compl_right (set α) _ _) hs hs.compl
hfi.integrable_on hfi.integrable_on, union_compl_self, integral_univ]
lemma set_integral_eq_zero_of_forall_eq_zero {f : α → E} (hf : measurable f)
(ht_eq : ∀ x ∈ t, f x = 0) :
∫ x in t, f x ∂μ = 0 :=
begin
refine integral_eq_zero_of_ae _,
rw [eventually_eq, ae_restrict_iff (measurable_set_eq_fun hf measurable_zero)],
refine eventually_of_forall (λ x hx, _),
rw pi.zero_apply,
exact ht_eq x hx,
end
private lemma set_integral_union_eq_left_of_disjoint {f : α → E} (hf : measurable f)
(hfi : integrable f μ) (hs : measurable_set s) (ht : measurable_set t) (ht_eq : ∀ x ∈ t, f x = 0)
(hs_disj : disjoint s t) :
∫ x in (s ∪ t), f x ∂μ = ∫ x in s, f x ∂μ :=
by rw [integral_union hs_disj hs ht hfi.integrable_on hfi.integrable_on,
set_integral_eq_zero_of_forall_eq_zero hf ht_eq, add_zero]
lemma set_integral_union_eq_left {f : α → E} (hf : measurable f) (hfi : integrable f μ)
(hs : measurable_set s) (ht : measurable_set t) (ht_eq : ∀ x ∈ t, f x = 0) :
∫ x in (s ∪ t), f x ∂μ = ∫ x in s, f x ∂μ :=
begin
let s_ := s \ {x | f x = 0},
have hs_ : measurable_set s_, from hs.diff (measurable_set_eq_fun hf measurable_const),
let s0 := s ∩ {x | f x = 0},
have hs0 : measurable_set s0, from hs.inter (measurable_set_eq_fun hf measurable_const),
have hs0_eq : ∀ x ∈ s0, f x = 0,
by { intros x hx, simp_rw [s0, set.mem_inter_iff] at hx, exact hx.2, },
have h_s_union : s = s_ ∪ s0, from (set.diff_union_inter s _).symm,
have h_s_disj : disjoint s_ s0,
from (@disjoint_sdiff_self_left (set α) {x | f x = 0} s _).mono_right
(set.inter_subset_right _ _),
rw [h_s_union, set_integral_union_eq_left_of_disjoint hf hfi hs_ hs0 hs0_eq h_s_disj],
have hst0_eq : ∀ x ∈ s0 ∪ t, f x = 0,
{ intros x hx,
rw set.mem_union at hx,
cases hx,
{ exact hs0_eq x hx, },
{ exact ht_eq x hx, }, },
have hst_disj : disjoint s_ (s0 ∪ t),
{ rw [← set.sup_eq_union, disjoint_sup_right],
exact ⟨h_s_disj, (@disjoint_sdiff_self_left (set α) {x | f x = 0} s _).mono_right ht_eq⟩, },
rw set.union_assoc,
exact set_integral_union_eq_left_of_disjoint hf hfi hs_ (hs0.union ht) hst0_eq hst_disj,
end
lemma set_integral_neg_eq_set_integral_nonpos [linear_order E] [order_closed_topology E]
{f : α → E} (hf : measurable f) (hfi : integrable f μ) :
∫ x in {x | f x < 0}, f x ∂μ = ∫ x in {x | f x ≤ 0}, f x ∂μ :=
begin
have h_union : {x | f x ≤ 0} = {x | f x < 0} ∪ {x | f x = 0},
by { ext, simp_rw [set.mem_union_eq, set.mem_set_of_eq], exact le_iff_lt_or_eq, },
rw h_union,
exact (set_integral_union_eq_left hf hfi (measurable_set_lt hf measurable_const)
(measurable_set_eq_fun hf measurable_const) (λ x hx, hx)).symm,
end
lemma integral_norm_eq_pos_sub_neg {f : α → ℝ} (hf : measurable f) (hfi : integrable f μ) :
∫ x, ∥f x∥ ∂μ = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | f x ≤ 0}, f x ∂μ :=
have h_meas : measurable_set {x | 0 ≤ f x}, from measurable_set_le measurable_const hf,
calc ∫ x, ∥f x∥ ∂μ = ∫ x in {x | 0 ≤ f x}, ∥f x∥ ∂μ + ∫ x in {x | 0 ≤ f x}ᶜ, ∥f x∥ ∂μ :
by rw ← integral_add_compl h_meas hfi.norm
... = ∫ x in {x | 0 ≤ f x}, f x ∂μ + ∫ x in {x | 0 ≤ f x}ᶜ, ∥f x∥ ∂μ :
begin
congr' 1,
refine set_integral_congr h_meas (λ x hx, _),
dsimp only,
rw [real.norm_eq_abs, abs_eq_self.mpr _],
exact hx,
end
... = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | 0 ≤ f x}ᶜ, f x ∂μ :
begin
congr' 1,
rw ← integral_neg,
refine set_integral_congr h_meas.compl (λ x hx, _),
dsimp only,
rw [real.norm_eq_abs, abs_eq_neg_self.mpr _],
rw [set.mem_compl_iff, set.nmem_set_of_eq] at hx,
linarith,
end
... = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | f x ≤ 0}, f x ∂μ :
by { rw ← set_integral_neg_eq_set_integral_nonpos hf hfi, congr, ext1 x, simp, }
/-- For a function `f` and a measurable set `s`, the integral of `indicator s f`
over the whole space is equal to `∫ x in s, f x ∂μ` defined as `∫ x, f x ∂(μ.restrict s)`. -/
lemma integral_indicator (hs : measurable_set s) :
∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ :=
begin
by_cases hf : ae_measurable f (μ.restrict s), swap,
{ rw integral_non_ae_measurable hf,
rw [← ae_measurable_indicator_iff hs] at hf,
exact integral_non_ae_measurable hf },
by_cases hfi : integrable_on f s μ, swap,
{ rwa [integral_undef, integral_undef],
rwa integrable_indicator_iff hs },
calc ∫ x, indicator s f x ∂μ = ∫ x in s, indicator s f x ∂μ + ∫ x in sᶜ, indicator s f x ∂μ :
(integral_add_compl hs (hfi.indicator hs)).symm
... = ∫ x in s, f x ∂μ + ∫ x in sᶜ, 0 ∂μ :
congr_arg2 (+) (integral_congr_ae (indicator_ae_eq_restrict hs))
(integral_congr_ae (indicator_ae_eq_restrict_compl hs))
... = ∫ x in s, f x ∂μ : by simp
end
lemma set_integral_congr_set_ae (hst : s =ᵐ[μ] t) :
∫ x in s, f x ∂μ = ∫ x in t, f x ∂μ :=
by rw restrict_congr_set hst
lemma set_integral_const (c : E) : ∫ x in s, c ∂μ = (μ s).to_real • c :=
by rw [integral_const, measure.restrict_apply_univ]
@[simp]
lemma integral_indicator_const (e : E) ⦃s : set α⦄ (s_meas : measurable_set s) :
∫ (a : α), s.indicator (λ (x : α), e) a ∂μ = (μ s).to_real • e :=
by rw [integral_indicator s_meas, ← set_integral_const]
lemma set_integral_map {β} [measurable_space β] {g : α → β} {f : β → E} {s : set β}
(hs : measurable_set s) (hf : ae_measurable f (measure.map g μ)) (hg : measurable g) :
∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ :=
begin
rw [measure.restrict_map hg hs, integral_map hg (hf.mono_measure _)],
exact measure.map_mono g measure.restrict_le_self
end
lemma set_integral_map_of_closed_embedding [topological_space α] [borel_space α]
{β} [measurable_space β] [topological_space β] [borel_space β]
{g : α → β} {f : β → E} {s : set β} (hs : measurable_set s) (hg : closed_embedding g) :
∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ :=
begin
rw [measure.restrict_map hg.measurable hs, integral_map_of_closed_embedding hg],
apply_instance,
end
lemma norm_set_integral_le_of_norm_le_const_ae {C : ℝ} (hs : μ s < ∞)
(hC : ∀ᵐ x ∂μ.restrict s, ∥f x∥ ≤ C) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
begin
rw ← measure.restrict_apply_univ at *,
haveI : is_finite_measure (μ.restrict s) := ⟨‹_›⟩,
exact norm_integral_le_of_norm_le_const hC
end
lemma norm_set_integral_le_of_norm_le_const_ae' {C : ℝ} (hs : μ s < ∞)
(hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) (hfm : ae_measurable f (μ.restrict s)) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
begin
apply norm_set_integral_le_of_norm_le_const_ae hs,
have A : ∀ᵐ (x : α) ∂μ, x ∈ s → ∥ae_measurable.mk f hfm x∥ ≤ C,
{ filter_upwards [hC, hfm.ae_mem_imp_eq_mk],
assume a h1 h2 h3,
rw [← h2 h3],
exact h1 h3 },
have B : measurable_set {x | ∥(hfm.mk f) x∥ ≤ C} := hfm.measurable_mk.norm measurable_set_Iic,
filter_upwards [hfm.ae_eq_mk, (ae_restrict_iff B).2 A],
assume a h1 h2,
rwa h1
end
lemma norm_set_integral_le_of_norm_le_const_ae'' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s)
(hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
norm_set_integral_le_of_norm_le_const_ae hs $ by rwa [ae_restrict_eq hsm, eventually_inf_principal]
lemma norm_set_integral_le_of_norm_le_const {C : ℝ} (hs : μ s < ∞)
(hC : ∀ x ∈ s, ∥f x∥ ≤ C) (hfm : ae_measurable f (μ.restrict s)) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
norm_set_integral_le_of_norm_le_const_ae' hs (eventually_of_forall hC) hfm
lemma norm_set_integral_le_of_norm_le_const' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s)
(hC : ∀ x ∈ s, ∥f x∥ ≤ C) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
norm_set_integral_le_of_norm_le_const_ae'' hs hsm $ eventually_of_forall hC
lemma set_integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f)
(hfi : integrable_on f s μ) :
∫ x in s, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict s] 0 :=
integral_eq_zero_iff_of_nonneg_ae hf hfi
lemma set_integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f)
(hfi : integrable_on f s μ) :
0 < ∫ x in s, f x ∂μ ↔ 0 < μ (support f ∩ s) :=
begin
rw [integral_pos_iff_support_of_nonneg_ae hf hfi, restrict_apply_of_null_measurable_set],
exact hfi.ae_measurable.null_measurable_set (measurable_set_singleton 0).compl
end
lemma set_integral_trim {α} {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) {f : α → E}
(hf_meas : @measurable _ _ m _ f) {s : set α} (hs : measurable_set[m] s) :
∫ x in s, f x ∂μ = ∫ x in s, f x ∂(μ.trim hm) :=
by rwa [integral_trim hm hf_meas, restrict_trim hm μ]
end normed_group
section mono
variables {μ : measure α} {f g : α → ℝ} {s : set α}
(hf : integrable_on f s μ) (hg : integrable_on g s μ)
lemma set_integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict s] g) :
∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ :=
integral_mono_ae hf hg h
lemma set_integral_mono_ae (h : f ≤ᵐ[μ] g) :
∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ :=
set_integral_mono_ae_restrict hf hg (ae_restrict_of_ae h)
lemma set_integral_mono_on (hs : measurable_set s) (h : ∀ x ∈ s, f x ≤ g x) :
∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ :=
set_integral_mono_ae_restrict hf hg
(by simp [hs, eventually_le, eventually_inf_principal, ae_of_all _ h])
lemma set_integral_mono (h : f ≤ g) :
∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ :=
integral_mono hf hg h
end mono
section nonneg
variables {μ : measure α} {f : α → ℝ} {s : set α}
lemma set_integral_nonneg_of_ae_restrict (hf : 0 ≤ᵐ[μ.restrict s] f) :
(0:ℝ) ≤ (∫ a in s, f a ∂μ) :=
integral_nonneg_of_ae hf
lemma set_integral_nonneg_of_ae (hf : 0 ≤ᵐ[μ] f) : (0:ℝ) ≤ (∫ a in s, f a ∂μ) :=
set_integral_nonneg_of_ae_restrict (ae_restrict_of_ae hf)
lemma set_integral_nonneg (hs : measurable_set s) (hf : ∀ a, a ∈ s → 0 ≤ f a) :
(0:ℝ) ≤ (∫ a in s, f a ∂μ) :=
set_integral_nonneg_of_ae_restrict ((ae_restrict_iff' hs).mpr (ae_of_all μ hf))
lemma set_integral_le_nonneg {s : set α} (hs : measurable_set s) (hf : measurable f)
(hfi : integrable f μ) :
∫ x in s, f x ∂μ ≤ ∫ x in {y | 0 ≤ f y}, f x ∂μ :=
begin
rw [← integral_indicator hs, ← integral_indicator (measurable_set_le measurable_const hf)],
exact integral_mono (hfi.indicator hs) (hfi.indicator (measurable_set_le measurable_const hf))
(indicator_le_indicator_nonneg s f),
end
lemma set_integral_nonpos_le {s : set α} (hs : measurable_set s) {f : α → ℝ} (hf : measurable f)
(hfi : integrable f μ) :
∫ x in {y | f y ≤ 0}, f x ∂μ ≤ ∫ x in s, f x ∂μ :=
begin
rw [← integral_indicator hs, ← integral_indicator (measurable_set_le hf measurable_const)],
exact integral_mono (hfi.indicator (measurable_set_le hf measurable_const)) (hfi.indicator hs)
(indicator_nonpos_le_indicator s f),
end
end nonneg
lemma set_integral_mono_set {α : Type*} [measurable_space α] {μ : measure α}
{s t : set α} {f : α → ℝ} (hfi : integrable f μ) (hf : 0 ≤ᵐ[μ] f) (hst : s ≤ᵐ[μ] t) :
∫ x in s, f x ∂μ ≤ ∫ x in t, f x ∂μ :=
begin
repeat { rw integral_eq_lintegral_of_nonneg_ae (ae_restrict_of_ae hf)
(hfi.1.mono_measure measure.restrict_le_self) },
rw ennreal.to_real_le_to_real
(ne_of_lt $ (has_finite_integral_iff_of_real (ae_restrict_of_ae hf)).mp hfi.integrable_on.2)
(ne_of_lt $ (has_finite_integral_iff_of_real (ae_restrict_of_ae hf)).mp hfi.integrable_on.2),
exact (lintegral_mono_set' hst),
end
section continuous_set_integral
/-! ### Continuity of the set integral
We prove that for any set `s`, the function `λ f : α →₁[μ] E, ∫ x in s, f x ∂μ` is continuous. -/
variables [normed_group E] [measurable_space E] [second_countable_topology E] [borel_space E]
{𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space 𝕜]
[normed_group F] [measurable_space F] [second_countable_topology F] [borel_space F]
[normed_space 𝕜 F]
{p : ℝ≥0∞} {μ : measure α}
/-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by
`(Lp.mem_ℒp f).restrict s).to_Lp f`. This map is additive. -/
lemma Lp_to_Lp_restrict_add (f g : Lp E p μ) (s : set α) :
((Lp.mem_ℒp (f + g)).restrict s).to_Lp ⇑(f + g)
= ((Lp.mem_ℒp f).restrict s).to_Lp f + ((Lp.mem_ℒp g).restrict s).to_Lp g :=
begin
ext1,
refine (ae_restrict_of_ae (Lp.coe_fn_add f g)).mp _,
refine (Lp.coe_fn_add (mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s))
(mem_ℒp.to_Lp g ((Lp.mem_ℒp g).restrict s))).mp _,
refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s)).mp _,
refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp g).restrict s)).mp _,
refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp (f+g)).restrict s)).mono (λ x hx1 hx2 hx3 hx4 hx5, _),
rw [hx4, hx1, pi.add_apply, hx2, hx3, hx5, pi.add_apply],
end
/-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by
`(Lp.mem_ℒp f).restrict s).to_Lp f`. This map commutes with scalar multiplication. -/
lemma Lp_to_Lp_restrict_smul [opens_measurable_space 𝕜] (c : 𝕜) (f : Lp F p μ) (s : set α) :
((Lp.mem_ℒp (c • f)).restrict s).to_Lp ⇑(c • f) = c • (((Lp.mem_ℒp f).restrict s).to_Lp f) :=
begin
ext1,
refine (ae_restrict_of_ae (Lp.coe_fn_smul c f)).mp _,
refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s)).mp _,
refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp (c • f)).restrict s)).mp _,
refine (Lp.coe_fn_smul c (mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s))).mono
(λ x hx1 hx2 hx3 hx4, _),
rw [hx2, hx1, pi.smul_apply, hx3, hx4, pi.smul_apply],
end
/-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by
`(Lp.mem_ℒp f).restrict s).to_Lp f`. This map is non-expansive. -/
lemma norm_Lp_to_Lp_restrict_le (s : set α) (f : Lp E p μ) :
∥((Lp.mem_ℒp f).restrict s).to_Lp f∥ ≤ ∥f∥ :=
begin
rw [Lp.norm_def, Lp.norm_def, ennreal.to_real_le_to_real (Lp.snorm_ne_top _) (Lp.snorm_ne_top _)],
refine (le_of_eq _).trans (snorm_mono_measure _ measure.restrict_le_self),
{ exact s, },
exact snorm_congr_ae (mem_ℒp.coe_fn_to_Lp _),
end
variables (α F 𝕜)
/-- Continuous linear map sending a function of `Lp F p μ` to the same function in
`Lp F p (μ.restrict s)`. -/
def Lp_to_Lp_restrict_clm [borel_space 𝕜] (μ : measure α) (p : ℝ≥0∞) [hp : fact (1 ≤ p)]
(s : set α) :
Lp F p μ →L[𝕜] Lp F p (μ.restrict s) :=
@linear_map.mk_continuous 𝕜 (Lp F p μ) (Lp F p (μ.restrict s)) _ _ _ _ _
⟨λ f, mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s), λ f g, Lp_to_Lp_restrict_add f g s,
λ c f, Lp_to_Lp_restrict_smul c f s⟩
1 (by { intro f, rw one_mul, exact norm_Lp_to_Lp_restrict_le s f, })
variables {α F 𝕜}
variables (𝕜)
lemma Lp_to_Lp_restrict_clm_coe_fn [borel_space 𝕜] [hp : fact (1 ≤ p)] (s : set α) (f : Lp F p μ) :
Lp_to_Lp_restrict_clm α F 𝕜 μ p s f =ᵐ[μ.restrict s] f :=
mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s)
variables {𝕜}
@[continuity]
lemma continuous_set_integral [normed_space ℝ E] [complete_space E] (s : set α) :
continuous (λ f : α →₁[μ] E, ∫ x in s, f x ∂μ) :=
begin
haveI : fact ((1 : ℝ≥0∞) ≤ 1) := ⟨le_rfl⟩,
have h_comp : (λ f : α →₁[μ] E, ∫ x in s, f x ∂μ)
= (integral (μ.restrict s)) ∘ (λ f, Lp_to_Lp_restrict_clm α E ℝ μ 1 s f),
{ ext1 f,
rw [function.comp_apply, integral_congr_ae (Lp_to_Lp_restrict_clm_coe_fn ℝ s f)], },
rw h_comp,
exact continuous_integral.comp (Lp_to_Lp_restrict_clm α E ℝ μ 1 s).continuous,
end
end continuous_set_integral
end measure_theory
open measure_theory asymptotics metric
variables {ι : Type*} [measurable_space E] [normed_group E]
/-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite at a
filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ μ.ae`, then `∫ x in
s i, f x ∂μ = μ (s i) • b + o(μ (s i))` at a filter `li` provided that `s i` tends to `l.lift'
powerset` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the
actual statement.
Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional
argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these
arguments, `m i = (μ (s i)).to_real` is used in the output. -/
lemma filter.tendsto.integral_sub_linear_is_o_ae
[normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E]
{μ : measure α} {l : filter α} [l.is_measurably_generated]
{f : α → E} {b : E} (h : tendsto f (l ⊓ μ.ae) (𝓝 b))
(hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l)
{s : ι → set α} {li : filter ι} (hs : tendsto s li (l.lift' powerset))
(m : ι → ℝ := λ i, (μ (s i)).to_real)
(hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) :
is_o (λ i, ∫ x in s i, f x ∂μ - m i • b) m li :=
begin
suffices : is_o (λ s, ∫ x in s, f x ∂μ - (μ s).to_real • b) (λ s, (μ s).to_real)
(l.lift' powerset),
from (this.comp_tendsto hs).congr' (hsμ.mono $ λ a ha, ha ▸ rfl) hsμ,
refine is_o_iff.2 (λ ε ε₀, _),
have : ∀ᶠ s in l.lift' powerset, ∀ᶠ x in μ.ae, x ∈ s → f x ∈ closed_ball b ε :=
eventually_lift'_powerset_eventually.2 (h.eventually $ closed_ball_mem_nhds _ ε₀),
filter_upwards [hμ.eventually, (hμ.integrable_at_filter_of_tendsto_ae hfm h).eventually,
hfm.eventually, this],
simp only [mem_closed_ball, dist_eq_norm],
intros s hμs h_integrable hfm h_norm,
rw [← set_integral_const, ← integral_sub h_integrable (integrable_on_const.2 $ or.inr hμs),
real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg],
exact norm_set_integral_le_of_norm_le_const_ae' hμs h_norm (hfm.sub ae_measurable_const)
end
/-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally
finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a`
within a measurable set `t`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at a filter `li`
provided that `s i` tends to `(𝓝[t] a).lift' powerset` along `li`. Since `μ (s i)` is an `ℝ≥0∞`
number, we use `(μ (s i)).to_real` in the actual statement.
Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional
argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these
arguments, `m i = (μ (s i)).to_real` is used in the output. -/
lemma continuous_within_at.integral_sub_linear_is_o_ae
[topological_space α] [opens_measurable_space α]
[normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E]
{μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α}
{f : α → E} (ha : continuous_within_at f t a) (ht : measurable_set t)
(hfm : measurable_at_filter f (𝓝[t] a) μ)
{s : ι → set α} {li : filter ι} (hs : tendsto s li ((𝓝[t] a).lift' powerset))
(m : ι → ℝ := λ i, (μ (s i)).to_real)
(hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) :
is_o (λ i, ∫ x in s i, f x ∂μ - m i • f a) m li :=
by haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _;
exact (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae
hfm (μ.finite_at_nhds_within a t) hs m hsμ
/-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite
measure and `f` is an almost everywhere measurable function that is continuous at a point `a`, then
`∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s` tends to `(𝓝 a).lift'
powerset` along `li. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the
actual statement.
Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional
argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these
arguments, `m i = (μ (s i)).to_real` is used in the output. -/
lemma continuous_at.integral_sub_linear_is_o_ae
[topological_space α] [opens_measurable_space α]
[normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E]
{μ : measure α} [is_locally_finite_measure μ] {a : α}
{f : α → E} (ha : continuous_at f a) (hfm : measurable_at_filter f (𝓝 a) μ)
{s : ι → set α} {li : filter ι} (hs : tendsto s li ((𝓝 a).lift' powerset))
(m : ι → ℝ := λ i, (μ (s i)).to_real)
(hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) :
is_o (λ i, ∫ x in s i, f x ∂μ - m i • f a) m li :=
(ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds a) hs m hsμ
/-- If a function is continuous on an open set `s`, then it is measurable at the filter `𝓝 x` for
all `x ∈ s`. -/
lemma continuous_on.measurable_at_filter
[topological_space α] [opens_measurable_space α] [borel_space E]
{f : α → E} {s : set α} {μ : measure α} (hs : is_open s) (hf : continuous_on f s) :
∀ x ∈ s, measurable_at_filter f (𝓝 x) μ :=
λ x hx, ⟨s, is_open.mem_nhds hs hx, hf.ae_measurable hs.measurable_set⟩
lemma continuous_at.measurable_at_filter
[topological_space α] [opens_measurable_space α] [borel_space E]
{f : α → E} {s : set α} {μ : measure α} (hs : is_open s) (hf : ∀ x ∈ s, continuous_at f x) :
∀ x ∈ s, measurable_at_filter f (𝓝 x) μ :=
continuous_on.measurable_at_filter hs $ continuous_at.continuous_on hf
/-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally
finite measure, `f` is continuous on a measurable set `t`, and `a ∈ t`, then `∫ x in (s i), f x ∂μ =
μ (s i) • f a + o(μ (s i))` at `li` provided that `s i` tends to `(𝓝[t] a).lift' powerset` along
`li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement.
Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional
argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these
arguments, `m i = (μ (s i)).to_real` is used in the output. -/
lemma continuous_on.integral_sub_linear_is_o_ae
[topological_space α] [opens_measurable_space α]
[normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E]
{μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α}
{f : α → E} (hft : continuous_on f t) (ha : a ∈ t) (ht : measurable_set t)
{s : ι → set α} {li : filter ι} (hs : tendsto s li ((𝓝[t] a).lift' powerset))
(m : ι → ℝ := λ i, (μ (s i)).to_real)
(hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) :
is_o (λ i, ∫ x in s i, f x ∂μ - m i • f a) m li :=
(hft a ha).integral_sub_linear_is_o_ae ht ⟨t, self_mem_nhds_within, hft.ae_measurable ht⟩ hs m hsμ
section
/-! ### Continuous linear maps composed with integration
The goal of this section is to prove that integration commutes with continuous linear maps.
This holds for simple functions. The general result follows from the continuity of all involved
operations on the space `L¹`. Note that composition by a continuous linear map on `L¹` is not just
the composition, as we are dealing with classes of functions, but it has already been defined
as `continuous_linear_map.comp_Lp`. We take advantage of this construction here.
-/
variables {μ : measure α} {𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E]
[normed_group F] [normed_space 𝕜 F]
{p : ennreal}
local attribute [instance] fact_one_le_one_ennreal
namespace continuous_linear_map
variables [measurable_space F] [borel_space F]
variables [second_countable_topology F] [complete_space F]
[borel_space E] [second_countable_topology E] [normed_space ℝ F]
lemma integral_comp_Lp (L : E →L[𝕜] F) (φ : Lp E p μ) :
∫ a, (L.comp_Lp φ) a ∂μ = ∫ a, L (φ a) ∂μ :=
integral_congr_ae $ coe_fn_comp_Lp _ _
lemma continuous_integral_comp_L1 [measurable_space 𝕜] [opens_measurable_space 𝕜] (L : E →L[𝕜] F) :
continuous (λ (φ : α →₁[μ] E), ∫ (a : α), L (φ a) ∂μ) :=
by { rw ← funext L.integral_comp_Lp, exact continuous_integral.comp (L.comp_LpL 1 μ).continuous, }
variables [complete_space E] [measurable_space 𝕜] [opens_measurable_space 𝕜]
[normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E] [is_scalar_tower ℝ 𝕜 F]
lemma integral_comp_comm (L : E →L[𝕜] F) {φ : α → E} (φ_int : integrable φ μ) :
∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) :=
begin
apply integrable.induction (λ φ, ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ)),
{ intros e s s_meas s_finite,
rw [integral_indicator_const e s_meas, ← @smul_one_smul E ℝ 𝕜 _ _ _ _ _ (μ s).to_real e,
continuous_linear_map.map_smul, @smul_one_smul F ℝ 𝕜 _ _ _ _ _ (μ s).to_real (L e),
← integral_indicator_const (L e) s_meas],
congr' 1 with a,
rw set.indicator_comp_of_zero L.map_zero },
{ intros f g H f_int g_int hf hg,
simp [L.map_add, integral_add f_int g_int,
integral_add (L.integrable_comp f_int) (L.integrable_comp g_int), hf, hg] },
{ exact is_closed_eq L.continuous_integral_comp_L1 (L.continuous.comp continuous_integral) },
{ intros f g hfg f_int hf,
convert hf using 1 ; clear hf,
{ exact integral_congr_ae (hfg.fun_comp L).symm },
{ rw integral_congr_ae hfg.symm } },
all_goals { assumption }
end
lemma integral_apply {H : Type*} [normed_group H] [normed_space ℝ H]
[second_countable_topology $ H →L[ℝ] E] {φ : α → H →L[ℝ] E} (φ_int : integrable φ μ) (v : H) :
(∫ a, φ a ∂μ) v = ∫ a, φ a v ∂μ :=
((continuous_linear_map.apply ℝ E v).integral_comp_comm φ_int).symm
lemma integral_comp_comm' (L : E →L[𝕜] F) {K} (hL : antilipschitz_with K L) (φ : α → E) :
∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) :=
begin
by_cases h : integrable φ μ,
{ exact integral_comp_comm L h },
have : ¬ (integrable (L ∘ φ) μ),
by rwa lipschitz_with.integrable_comp_iff_of_antilipschitz L.lipschitz hL (L.map_zero),
simp [integral_undef, h, this]
end
lemma integral_comp_L1_comm (L : E →L[𝕜] F) (φ : α →₁[μ] E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) :=
L.integral_comp_comm (L1.integrable_coe_fn φ)
end continuous_linear_map
namespace linear_isometry
variables [measurable_space F] [borel_space F] [second_countable_topology F] [complete_space F]
[normed_space ℝ F] [is_scalar_tower ℝ 𝕜 F]
[borel_space E] [second_countable_topology E] [complete_space E] [normed_space ℝ E]
[is_scalar_tower ℝ 𝕜 E]
[measurable_space 𝕜] [opens_measurable_space 𝕜]
lemma integral_comp_comm (L : E →ₗᵢ[𝕜] F) (φ : α → E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) :=
L.to_continuous_linear_map.integral_comp_comm' L.antilipschitz _
end linear_isometry
variables [borel_space E] [second_countable_topology E] [complete_space E] [normed_space ℝ E]
[measurable_space F] [borel_space F] [second_countable_topology F] [complete_space F]
[normed_space ℝ F]
[measurable_space 𝕜] [borel_space 𝕜]
@[norm_cast] lemma integral_of_real {f : α → ℝ} : ∫ a, (f a : 𝕜) ∂μ = ↑∫ a, f a ∂μ :=
(@is_R_or_C.of_real_li 𝕜 _).integral_comp_comm f
lemma integral_re {f : α → 𝕜} (hf : integrable f μ) :
∫ a, is_R_or_C.re (f a) ∂μ = is_R_or_C.re ∫ a, f a ∂μ :=
(@is_R_or_C.re_clm 𝕜 _).integral_comp_comm hf
lemma integral_im {f : α → 𝕜} (hf : integrable f μ) :
∫ a, is_R_or_C.im (f a) ∂μ = is_R_or_C.im ∫ a, f a ∂μ :=
(@is_R_or_C.im_clm 𝕜 _).integral_comp_comm hf
lemma integral_conj {f : α → 𝕜} : ∫ a, is_R_or_C.conj (f a) ∂μ = is_R_or_C.conj ∫ a, f a ∂μ :=
(@is_R_or_C.conj_lie 𝕜 _).to_linear_isometry.integral_comp_comm f
lemma fst_integral {f : α → E × F} (hf : integrable f μ) :
(∫ x, f x ∂μ).1 = ∫ x, (f x).1 ∂μ :=
((continuous_linear_map.fst ℝ E F).integral_comp_comm hf).symm
lemma snd_integral {f : α → E × F} (hf : integrable f μ) :
(∫ x, f x ∂μ).2 = ∫ x, (f x).2 ∂μ :=
((continuous_linear_map.snd ℝ E F).integral_comp_comm hf).symm
lemma integral_pair {f : α → E} {g : α → F} (hf : integrable f μ) (hg : integrable g μ) :
∫ x, (f x, g x) ∂μ = (∫ x, f x ∂μ, ∫ x, g x ∂μ) :=
have _ := hf.prod_mk hg, prod.ext (fst_integral this) (snd_integral this)
lemma integral_smul_const (f : α → ℝ) (c : E) :
∫ x, f x • c ∂μ = (∫ x, f x ∂μ) • c :=
begin
by_cases hf : integrable f μ,
{ exact ((continuous_linear_map.id ℝ ℝ).smul_right c).integral_comp_comm hf },
{ by_cases hc : c = 0,
{ simp only [hc, integral_zero, smul_zero] },
rw [integral_undef hf, integral_undef, zero_smul],
simp_rw [integrable_smul_const hc, hf, not_false_iff] }
end
section inner
variables {E' : Type*} [inner_product_space 𝕜 E'] [measurable_space E'] [borel_space E']
[second_countable_topology E'] [complete_space E'] [normed_space ℝ E'] [is_scalar_tower ℝ 𝕜 E']
local notation `⟪`x`, `y`⟫` := @inner 𝕜 E' _ x y
lemma integral_inner {f : α → E'} (hf : integrable f μ) (c : E') :
∫ x, ⟪c, f x⟫ ∂μ = ⟪c, ∫ x, f x ∂μ⟫ :=
((@inner_right 𝕜 E' _ _ c).restrict_scalars ℝ).integral_comp_comm hf
lemma integral_eq_zero_of_forall_integral_inner_eq_zero (f : α → E') (hf : integrable f μ)
(hf_int : ∀ (c : E'), ∫ x, ⟪c, f x⟫ ∂μ = 0) :
∫ x, f x ∂μ = 0 :=
by { specialize hf_int (∫ x, f x ∂μ), rwa [integral_inner hf, inner_self_eq_zero] at hf_int }
end inner
end
/-
namespace integrable
variables [measurable_space α] [measurable_space β] [normed_group E]
protected lemma measure_mono
end integrable
end measure_theory
section integral_on
variables [measurable_space α]
[normed_group β] [second_countable_topology β] [normed_space ℝ β] [complete_space β]
[measurable_space β] [borel_space β]
{s t : set α} {f g : α → β} {μ : measure α}
open set
lemma integral_on_congr (hf : measurable f) (hg : measurable g) (hs : measurable_set s)
(h : ∀ᵐ a ∂μ, a ∈ s → f a = g a) : ∫ a in s, f a ∂μ = ∫ a in s, g a ∂μ :=
integral_congr_ae hf hg $ _
lemma integral_on_congr_of_set (hsm : measurable_on s f) (htm : measurable_on t f)
(h : ∀ᵐ a, a ∈ s ↔ a ∈ t) : (∫ a in s, f a) = (∫ a in t, f a) :=
integral_congr_ae hsm htm $ indicator_congr_of_set h
lemma integral_on_add {s : set α} (hfm : measurable_on s f) (hfi : integrable_on s f)
(hgm : measurable_on s g) (hgi : integrable_on s g) :
(∫ a in s, f a + g a) = (∫ a in s, f a) + (∫ a in s, g a) :=
by { simp only [indicator_add], exact integral_add hfm hfi hgm hgi }
lemma integral_on_sub (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g)
(hgi : integrable_on s g) : (∫ a in s, f a - g a) = (∫ a in s, f a) - (∫ a in s, g a) :=
by { simp only [indicator_sub], exact integral_sub hfm hfi hgm hgi }
lemma integral_on_le_integral_on_ae {f g : α → ℝ} (hfm : measurable_on s f)
(hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g)
(h : ∀ᵐ a, a ∈ s → f a ≤ g a) :
(∫ a in s, f a) ≤ (∫ a in s, g a) :=
begin
apply integral_le_integral_ae hfm hfi hgm hgi,
apply indicator_le_indicator_ae,
exact h
end
lemma integral_on_le_integral_on {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f)
(hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ a, a ∈ s → f a ≤ g a) :
(∫ a in s, f a) ≤ (∫ a in s, g a) :=
integral_on_le_integral_on_ae hfm hfi hgm hgi $ by filter_upwards [] h
lemma integral_on_union (hsm : measurable_on s f) (hsi : integrable_on s f)
(htm : measurable_on t f) (hti : integrable_on t f) (h : disjoint s t) :
(∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) :=
by { rw [indicator_union_of_disjoint h, integral_add hsm hsi htm hti] }
lemma integral_on_union_ae (hs : measurable_set s) (ht : measurable_set t) (hsm : measurable_on s f)
(hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f)
(h : ∀ᵐ a, a ∉ s ∩ t) :
(∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) :=
begin
have := integral_congr_ae _ _ (indicator_union_ae h f),
rw [this, integral_add hsm hsi htm hti],
{ exact hsm.union hs ht htm },
{ exact measurable.add hsm htm }
end
lemma integral_on_nonneg_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) :=
integral_nonneg_of_ae $ by { filter_upwards [hf] λ a h, indicator_nonneg' h }
lemma integral_on_nonneg {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) :=
integral_on_nonneg_of_ae $ univ_mem' hf
lemma integral_on_nonpos_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 :=
integral_nonpos_of_nonpos_ae $ by { filter_upwards [hf] λ a h, indicator_nonpos' h }
lemma integral_on_nonpos {f : α → ℝ} (hf : ∀ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 :=
integral_on_nonpos_of_ae $ univ_mem' hf
lemma tendsto_integral_on_of_monotone {s : ℕ → set α} {f : α → β} (hsm : ∀i, measurable_set (s i))
(h_mono : monotone s) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) :
tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Union s), f a)) :=
let bound : α → ℝ := indicator (Union s) (λa, ∥f a∥) in
begin
apply tendsto_integral_of_dominated_convergence,
{ assume i, exact hfm.subset (hsm i) (subset_Union _ _) },
{ assumption },
{ show integrable_on (Union s) (λa, ∥f a∥), rwa integrable_on_norm_iff },
{ assume i, apply ae_of_all,
assume a,
rw [norm_indicator_eq_indicator_norm],
exact indicator_le_indicator_of_subset (subset_Union _ _) (λa, norm_nonneg _) _ },
{ filter_upwards [] λa, le_trans (tendsto_indicator_of_monotone _ h_mono _ _) (pure_le_nhds _) }
end
lemma tendsto_integral_on_of_antimono (s : ℕ → set α) (f : α → β) (hsm : ∀i, measurable_set (s i))
(h_mono : ∀i j, i ≤ j → s j ⊆ s i) (hfm : measurable_on (s 0) f) (hfi : integrable_on (s 0) f) :
tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Inter s), f a)) :=
let bound : α → ℝ := indicator (s 0) (λa, ∥f a∥) in
begin
apply tendsto_integral_of_dominated_convergence,
{ assume i, refine hfm.subset (hsm i) (h_mono _ _ (zero_le _)) },
{ exact hfm.subset (measurable_set.Inter hsm) (Inter_subset _ _) },
{ show integrable_on (s 0) (λa, ∥f a∥), rwa integrable_on_norm_iff },
{ assume i, apply ae_of_all,
assume a,
rw [norm_indicator_eq_indicator_norm],
refine indicator_le_indicator_of_subset (h_mono _ _ (zero_le _)) (λa, norm_nonneg _) _ },
{ filter_upwards [] λa, le_trans (tendsto_indicator_of_antimono _ h_mono _ _) (pure_le_nhds _) }
end
-- TODO : prove this for an encodable type
-- by proving an encodable version of `filter.is_countably_generated_at_top_finset_nat `
lemma integral_on_Union (s : ℕ → set α) (f : α → β) (hm : ∀i, measurable_set (s i))
(hd : ∀ i j, i ≠ j → s i ∩ s j = ∅) (hfm : measurable_on (Union s) f)
(hfi : integrable_on (Union s) f) :
(∫ a in (Union s), f a) = ∑'i, ∫ a in s i, f a :=
suffices h : tendsto (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) at_top (𝓝 $ (∫ a in (Union s), f a)),
by { rwa has_sum.tsum_eq },
begin
have : (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) = λn:finset ℕ, ∫ a in (⋃i∈n, s i), f a,
{ funext,
rw [← integral_finset_sum, indicator_finset_bUnion],
{ assume i hi j hj hij, exact hd i j hij },
{ assume i, refine hfm.subset (hm _) (subset_Union _ _) },
{ assume i, refine hfi.subset (subset_Union _ _) } },
rw this,
refine tendsto_integral_filter_of_dominated_convergence _ _ _ _ _ _ _,
{ exact indicator (Union s) (λ a, ∥f a∥) },
{ exact is_countably_generated_at_top_finset_nat },
{ refine univ_mem' (λ n, _),
simp only [mem_set_of_eq],
refine hfm.subset (measurable_set.Union (λ i, measurable_set.Union_Prop (λh, hm _)))
(bUnion_subset_Union _ _), },
{ assumption },
{ refine univ_mem' (λ n, univ_mem' $ _),
simp only [mem_set_of_eq],
assume a,
rw ← norm_indicator_eq_indicator_norm,
refine norm_indicator_le_of_subset (bUnion_subset_Union _ _) _ _ },
{ rw [← integrable_on, integrable_on_norm_iff], assumption },
{ filter_upwards [] λa, le_trans (tendsto_indicator_bUnion_finset _ _ _) (pure_le_nhds _) }
end
end integral_on
-/
|
afe735a7103c02a7d835c7d4610f9286d788f12f | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/algebra/char_p/basic.lean | a964c4926cd51b9e48c7faa95116804a59f37c72 | [
"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,185 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Joey van Langen, Casper Putz
-/
import data.nat.choose
import data.int.modeq
import algebra.iterate_hom
import group_theory.order_of_element
/-!
# Characteristic of semirings
-/
universes u v
variables (R : Type u)
/-- The generator of the kernel of the unique homomorphism ℕ → R for a semiring R -/
class char_p [add_monoid R] [has_one R] (p : ℕ) : Prop :=
(cast_eq_zero_iff [] : ∀ x:ℕ, (x:R) = 0 ↔ p ∣ x)
theorem char_p.cast_eq_zero [add_monoid R] [has_one R] (p : ℕ) [char_p R p] :
(p:R) = 0 :=
(char_p.cast_eq_zero_iff R p p).2 (dvd_refl p)
@[simp] lemma char_p.cast_card_eq_zero [add_group R] [has_one R] [fintype R] :
(fintype.card R : R) = 0 :=
begin
have : fintype.card R •ℕ (1 : R) = 0 :=
@pow_card_eq_one (multiplicative R) _ _ (multiplicative.of_add 1),
simpa only [nsmul_one]
end
lemma char_p.int_cast_eq_zero_iff [add_group R] [has_one R] (p : ℕ) [char_p R p]
(a : ℤ) :
(a : R) = 0 ↔ (p:ℤ) ∣ a :=
begin
rcases lt_trichotomy a 0 with h|rfl|h,
{ rw [← neg_eq_zero, ← int.cast_neg, ← dvd_neg],
lift -a to ℕ using neg_nonneg.mpr (le_of_lt h) with b,
rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] },
{ simp only [int.cast_zero, eq_self_iff_true, dvd_zero] },
{ lift a to ℕ using (le_of_lt h) with b,
rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] }
end
lemma char_p.int_coe_eq_int_coe_iff [add_group R] [has_one R] (p : ℕ) [char_p R p] (a b : ℤ) :
(a : R) = (b : R) ↔ a ≡ b [ZMOD p] :=
by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub,
char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd]
theorem char_p.eq [add_monoid R] [has_one R] {p q : ℕ} (c1 : char_p R p) (c2 : char_p R q) :
p = q :=
nat.dvd_antisymm
((char_p.cast_eq_zero_iff R p q).1 (char_p.cast_eq_zero _ _))
((char_p.cast_eq_zero_iff R q p).1 (char_p.cast_eq_zero _ _))
instance char_p.of_char_zero [add_monoid R] [has_one R] [char_zero R] : char_p R 0 :=
⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩
theorem char_p.exists [semiring R] : ∃ p, char_p R p :=
by letI := classical.dec_eq R; exact
classical.by_cases
(assume H : ∀ p:ℕ, (p:R) = 0 → p = 0, ⟨0,
⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩)
(λ H, ⟨nat.find (not_forall.1 H), ⟨λ x,
⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2,
nat.find_min (not_forall.1 H)
(nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $
nat.find_spec (not_forall.1 H))
(not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (not_forall.1 H)),
nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec
(not_forall.1 H)),
zero_mul, add_zero] at H1, H2⟩)),
λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul,
of_not_not (not_not_of_not_imp $ nat.find_spec (not_forall.1 H)), zero_mul]⟩⟩⟩)
theorem char_p.exists_unique [semiring R] : ∃! p, char_p R p :=
let ⟨c, H⟩ := char_p.exists R in ⟨c, H, λ y H2, char_p.eq R H2 H⟩
theorem char_p.congr {R : Type u} [semiring R] {p : ℕ} (q : ℕ) [hq : char_p R q] (h : q = p) :
char_p R p :=
h ▸ hq
/-- Noncomputable function that outputs the unique characteristic of a semiring. -/
noncomputable def ring_char [semiring R] : ℕ :=
classical.some (char_p.exists_unique R)
namespace ring_char
variables [semiring R]
theorem spec : ∀ x:ℕ, (x:R) = 0 ↔ ring_char R ∣ x :=
by letI := (classical.some_spec (char_p.exists_unique R)).1;
unfold ring_char; exact char_p.cast_eq_zero_iff R (ring_char R)
theorem eq {p : ℕ} (C : char_p R p) : p = ring_char R :=
(classical.some_spec (char_p.exists_unique R)).2 p C
instance char_p : char_p R (ring_char R) :=
⟨spec R⟩
variables {R}
theorem of_eq {p : ℕ} (h : ring_char R = p) : char_p R p :=
char_p.congr (ring_char R) h
theorem eq_iff {p : ℕ} : ring_char R = p ↔ char_p R p :=
⟨of_eq, eq.symm ∘ eq R⟩
theorem dvd {x : ℕ} (hx : (x : R) = 0) : ring_char R ∣ x :=
(spec R x).1 hx
@[simp]
lemma eq_zero [char_zero R] : ring_char R = 0 := (eq R (char_p.of_char_zero R)).symm
end ring_char
theorem add_pow_char_of_commute [semiring R] {p : ℕ} [fact p.prime]
[char_p R p] (x y : R) (h : commute x y) :
(x + y)^p = x^p + y^p :=
begin
rw [commute.add_pow h, finset.sum_range_succ, nat.sub_self, pow_zero, nat.choose_self],
rw [nat.cast_one, mul_one, mul_one], congr' 1,
convert finset.sum_eq_single 0 _ _,
{ simp only [mul_one, one_mul, nat.choose_zero_right, nat.sub_zero, nat.cast_one, pow_zero] },
{ intros b h1 h2,
suffices : (p.choose b : R) = 0, { rw this, simp },
rw char_p.cast_eq_zero_iff R p,
refine nat.prime.dvd_choose_self (pos_iff_ne_zero.mpr h2) _ (fact.out _),
rwa ← finset.mem_range },
{ intro h1,
contrapose! h1,
rw finset.mem_range,
exact nat.prime.pos (fact.out _) }
end
theorem add_pow_char_pow_of_commute [semiring R] {p : ℕ} [fact p.prime]
[char_p R p] {n : ℕ} (x y : R) (h : commute x y) :
(x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) :=
begin
induction n, { simp, },
rw [pow_succ', pow_mul, pow_mul, pow_mul, n_ih],
apply add_pow_char_of_commute, apply commute.pow_pow h,
end
theorem sub_pow_char_of_commute [ring R] {p : ℕ} [fact p.prime]
[char_p R p] (x y : R) (h : commute x y) :
(x - y)^p = x^p - y^p :=
begin
rw [eq_sub_iff_add_eq, ← add_pow_char_of_commute _ _ _ (commute.sub_left h rfl)],
simp, repeat {apply_instance},
end
theorem sub_pow_char_pow_of_commute [ring R] {p : ℕ} [fact p.prime]
[char_p R p] {n : ℕ} (x y : R) (h : commute x y) :
(x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) :=
begin
induction n, { simp, },
rw [pow_succ', pow_mul, pow_mul, pow_mul, n_ih],
apply sub_pow_char_of_commute, apply commute.pow_pow h,
end
theorem add_pow_char [comm_semiring R] {p : ℕ} [fact p.prime]
[char_p R p] (x y : R) : (x + y)^p = x^p + y^p :=
add_pow_char_of_commute _ _ _ (commute.all _ _)
theorem add_pow_char_pow [comm_semiring R] {p : ℕ} [fact p.prime]
[char_p R p] {n : ℕ} (x y : R) :
(x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) :=
add_pow_char_pow_of_commute _ _ _ (commute.all _ _)
theorem sub_pow_char [comm_ring R] {p : ℕ} [fact p.prime]
[char_p R p] (x y : R) : (x - y)^p = x^p - y^p :=
sub_pow_char_of_commute _ _ _ (commute.all _ _)
theorem sub_pow_char_pow [comm_ring R] {p : ℕ} [fact p.prime]
[char_p R p] {n : ℕ} (x y : R) :
(x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) :=
sub_pow_char_pow_of_commute _ _ _ (commute.all _ _)
lemma eq_iff_modeq_int [ring R] (p : ℕ) [char_p R p] (a b : ℤ) :
(a : R) = b ↔ a ≡ b [ZMOD p] :=
by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub,
char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd]
lemma char_p.neg_one_ne_one [ring R] (p : ℕ) [char_p R p] [fact (2 < p)] :
(-1 : R) ≠ (1 : R) :=
begin
suffices : (2 : R) ≠ 0,
{ symmetry, rw [ne.def, ← sub_eq_zero, sub_neg_eq_add], exact this },
assume h,
rw [show (2 : R) = (2 : ℕ), by norm_cast] at h,
have := (char_p.cast_eq_zero_iff R p 2).mp h,
have := nat.le_of_dvd dec_trivial this,
rw fact_iff at *, linarith,
end
lemma ring_hom.char_p_iff_char_p {K L : Type*} [field K] [field L] (f : K →+* L) (p : ℕ) :
char_p K p ↔ char_p L p :=
begin
split;
{ introI _c, constructor, intro n,
rw [← @char_p.cast_eq_zero_iff _ _ _ p _c n, ← f.injective.eq_iff, f.map_nat_cast, f.map_zero] }
end
section frobenius
section comm_semiring
variables [comm_semiring R] {S : Type v} [comm_semiring S] (f : R →* S) (g : R →+* S)
(p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R)
/-- The frobenius map that sends x to x^p -/
def frobenius : R →+* R :=
{ to_fun := λ x, x^p,
map_one' := one_pow p,
map_mul' := λ x y, mul_pow x y p,
map_zero' := zero_pow (lt_trans zero_lt_one (fact.out (nat.prime p)).one_lt),
map_add' := add_pow_char R }
variable {R}
theorem frobenius_def : frobenius R p x = x ^ p := rfl
theorem iterate_frobenius (n : ℕ) : (frobenius R p)^[n] x = x ^ p ^ n :=
begin
induction n, {simp},
rw [function.iterate_succ', pow_succ', pow_mul, function.comp_apply, frobenius_def, n_ih]
end
theorem frobenius_mul : frobenius R p (x * y) = frobenius R p x * frobenius R p y :=
(frobenius R p).map_mul x y
theorem frobenius_one : frobenius R p 1 = 1 := one_pow _
theorem monoid_hom.map_frobenius : f (frobenius R p x) = frobenius S p (f x) :=
f.map_pow x p
theorem ring_hom.map_frobenius : g (frobenius R p x) = frobenius S p (g x) :=
g.map_pow x p
theorem monoid_hom.map_iterate_frobenius (n : ℕ) :
f (frobenius R p^[n] x) = (frobenius S p^[n] (f x)) :=
function.semiconj.iterate_right (f.map_frobenius p) n x
theorem ring_hom.map_iterate_frobenius (n : ℕ) :
g (frobenius R p^[n] x) = (frobenius S p^[n] (g x)) :=
g.to_monoid_hom.map_iterate_frobenius p x n
theorem monoid_hom.iterate_map_frobenius (f : R →* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) :
f^[n] (frobenius R p x) = frobenius R p (f^[n] x) :=
f.iterate_map_pow _ _ _
theorem ring_hom.iterate_map_frobenius (f : R →+* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) :
f^[n] (frobenius R p x) = frobenius R p (f^[n] x) :=
f.iterate_map_pow _ _ _
variable (R)
theorem frobenius_zero : frobenius R p 0 = 0 := (frobenius R p).map_zero
theorem frobenius_add : frobenius R p (x + y) = frobenius R p x + frobenius R p y :=
(frobenius R p).map_add x y
theorem frobenius_nat_cast (n : ℕ) : frobenius R p n = n := (frobenius R p).map_nat_cast n
end comm_semiring
section comm_ring
variables [comm_ring R] {S : Type v} [comm_ring S] (f : R →* S) (g : R →+* S)
(p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R)
theorem frobenius_neg : frobenius R p (-x) = -frobenius R p x := (frobenius R p).map_neg x
theorem frobenius_sub : frobenius R p (x - y) = frobenius R p x - frobenius R p y :=
(frobenius R p).map_sub x y
end comm_ring
end frobenius
theorem frobenius_inj [comm_ring R] [no_zero_divisors R]
(p : ℕ) [fact p.prime] [char_p R p] :
function.injective (frobenius R p) :=
λ x h H, by { rw ← sub_eq_zero at H ⊢, rw ← frobenius_sub at H, exact pow_eq_zero H }
namespace char_p
section
variables [ring R]
lemma char_p_to_char_zero [char_p R 0] : char_zero R :=
char_zero_of_inj_zero $
λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff R 0 n).mp h0)
lemma cast_eq_mod (p : ℕ) [char_p R p] (k : ℕ) : (k : R) = (k % p : ℕ) :=
calc (k : R) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div]
... = ↑(k % p) : by simp[cast_eq_zero]
theorem char_ne_zero_of_fintype (p : ℕ) [hc : char_p R p] [fintype R] : p ≠ 0 :=
assume h : p = 0,
have char_zero R := @char_p_to_char_zero R _ (h ▸ hc),
absurd (@nat.cast_injective R _ _ this) (not_injective_infinite_fintype coe)
end
section semiring
open nat
variables [semiring R]
theorem char_ne_one [nontrivial R] (p : ℕ) [hc : char_p R p] : p ≠ 1 :=
assume hp : p = 1,
have ( 1 : R) = 0, by simpa using (cast_eq_zero_iff R p 1).mpr (hp ▸ dvd_refl p),
absurd this one_ne_zero
section no_zero_divisors
variable [no_zero_divisors R]
theorem char_is_prime_of_two_le (p : ℕ) [hc : char_p R p] (hp : 2 ≤ p) : nat.prime p :=
suffices ∀d ∣ p, d = 1 ∨ d = p, from ⟨hp, this⟩,
assume (d : ℕ) (hdvd : ∃ e, p = d * e),
let ⟨e, hmul⟩ := hdvd in
have (p : R) = 0, from (cast_eq_zero_iff R p p).mpr (dvd_refl p),
have (d : R) * e = 0, from (@cast_mul R _ d e) ▸ (hmul ▸ this),
or.elim (eq_zero_or_eq_zero_of_mul_eq_zero this)
(assume hd : (d : R) = 0,
have p ∣ d, from (cast_eq_zero_iff R p d).mp hd,
show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this))
(assume he : (e : R) = 0,
have p ∣ e, from (cast_eq_zero_iff R p e).mp he,
have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul),
have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›,
have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1),
have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul,
show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this))
section nontrivial
variables [nontrivial R]
theorem char_is_prime_or_zero (p : ℕ) [hc : char_p R p] : nat.prime p ∨ p = 0 :=
match p, hc with
| 0, _ := or.inr rfl
| 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one R _ _ (1 : ℕ) hc)
| (m+2), hc := or.inl (@char_is_prime_of_two_le R _ _ (m+2) hc (nat.le_add_left 2 m))
end
lemma char_is_prime_of_pos (p : ℕ) [h : fact (0 < p)] [char_p R p] : fact p.prime :=
⟨(char_p.char_is_prime_or_zero R _).resolve_right (pos_iff_ne_zero.1 h.1)⟩
end nontrivial
end no_zero_divisors
end semiring
section ring
variables (R) [ring R] [no_zero_divisors R] [nontrivial R] [fintype R]
theorem char_is_prime (p : ℕ) [char_p R p] :
p.prime :=
or.resolve_right (char_is_prime_or_zero R p) (char_ne_zero_of_fintype R p)
end ring
section char_one
variables {R} [semiring R]
@[priority 100] -- see Note [lower instance priority]
instance [char_p R 1] : subsingleton R :=
subsingleton.intro $
suffices ∀ (r : R), r = 0,
from assume a b, show a = b, by rw [this a, this b],
assume r,
calc r = 1 * r : by rw one_mul
... = (1 : ℕ) * r : by rw nat.cast_one
... = 0 * r : by rw char_p.cast_eq_zero
... = 0 : by rw zero_mul
lemma false_of_nontrivial_of_char_one [nontrivial R] [char_p R 1] : false :=
false_of_nontrivial_of_subsingleton R
lemma ring_char_ne_one [nontrivial R] : ring_char R ≠ 1 :=
by { intros h, apply @zero_ne_one R, symmetry, rw [←nat.cast_one, ring_char.spec, h], }
lemma nontrivial_of_char_ne_one {v : ℕ} (hv : v ≠ 1) [hr : char_p R v] :
nontrivial R :=
⟨⟨(1 : ℕ), 0, λ h, hv $ by rwa [char_p.cast_eq_zero_iff _ v, nat.dvd_one] at h; assumption ⟩⟩
end char_one
end char_p
section
variables (R) [comm_ring R] [fintype R] (n : ℕ)
lemma char_p_of_ne_zero (hn : fintype.card R = n) (hR : ∀ i < n, (i : R) = 0 → i = 0) :
char_p R n :=
{ cast_eq_zero_iff :=
begin
have H : (n : R) = 0, by { rw [← hn, char_p.cast_card_eq_zero] },
intro k,
split,
{ intro h,
rw [← nat.mod_add_div k n, nat.cast_add, nat.cast_mul, H, zero_mul, add_zero] at h,
rw nat.dvd_iff_mod_eq_zero,
apply hR _ (nat.mod_lt _ _) h,
rw [← hn, fintype.card_pos_iff],
exact ⟨0⟩, },
{ rintro ⟨k, rfl⟩, rw [nat.cast_mul, H, zero_mul] }
end }
lemma char_p_of_prime_pow_injective (p : ℕ) [hp : fact p.prime] (n : ℕ)
(hn : fintype.card R = p ^ n) (hR : ∀ i ≤ n, (p ^ i : R) = 0 → i = n) :
char_p R (p ^ n) :=
begin
obtain ⟨c, hc⟩ := char_p.exists R, resetI,
have hcpn : c ∣ p ^ n,
{ rw [← char_p.cast_eq_zero_iff R c, ← hn, char_p.cast_card_eq_zero], },
obtain ⟨i, hi, hc⟩ : ∃ i ≤ n, c = p ^ i, by rwa nat.dvd_prime_pow hp.1 at hcpn,
obtain rfl : i = n,
{ apply hR i hi, rw [← nat.cast_pow, ← hc, char_p.cast_eq_zero] },
rwa ← hc
end
end
|
2d14062e36f6adca58614214b8d89b7faf15ee03 | 0dbd5f7001f62ee8d54ed48bada66bfeaf55e550 | /src/ent/factorization.lean | a3d0ab5dca73bf484417344bdb147e6c1235471c | [] | no_license | rwbarton/lean-elementary-number-theory | 667203b08501792eef48217759539f6c1e2da25a | fabef0737fd2486e3f24f9e04652db4c182d5425 | refs/heads/master | 1,670,605,651,029 | 1,599,565,470,000 | 1,599,565,470,000 | 293,792,043 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,928 | lean | import data.multiset
import data.list
import data.nat.prime
import ent.order
open order
open list
open nat
local notation `prod` := list.prod
/-
set_option pp.all true
variables {x : ℕ} {lx : list ℕ}
set_option pp.all true
#check prod (map succ (x :: lx))
-/
-- def prime_factorization := multiset PP
section
-- factors facts
lemma factors_lemma_nil : ∀ (n : ℕ), factors n = [] → n = 0 ∨ n = 1
| 0 h := or.inl rfl
| 1 h := or.inr rfl
| n@(k+2) h := absurd h dec_trivial
lemma factors_lemma_cons : ∀ (n : ℕ) (m : ℕ) (fs' : list ℕ),
factors n = m :: fs' → n ≠ 1 ∧ min_fac n = m ∧ factors (n / min_fac n) = fs'
| 0 _ _ h := absurd h dec_trivial
| 1 _ _ h := absurd h dec_trivial
| n@(k+2) m fs' hn := ⟨dec_trivial, cons.inj hn⟩
-- wouldn't it be easier to just start from scratch
-- almost certainly
def factors_as_primes :
Π (fs : list ℕ) (n : ℕ) (h : factors n = fs),
{l : list PP // l.map subtype.val = fs}
| [] _ _ := ⟨[], rfl⟩
| (m :: fs') n h :=
begin
rcases factors_lemma_cons n m fs' h with ⟨n_ne_1, hm, hfs'⟩,
let r := factors_as_primes fs' (n / min_fac n) hfs',
have prime_m := min_fac_prime n_ne_1, rw hm at prime_m,
existsi subtype.mk m prime_m :: r.val,
transitivity list.cons m (map subtype.val (r.val)),
apply map_cons subtype.val,
rw r.property
end
lemma factors_as_factorization :
∀ (fs : list ℕ) (n : ℕ) (h : factors n = fs), n > 0 → prod fs = n
| [] n h n_pos := eq.symm $
(factors_lemma_nil n h).resolve_left
(λ e, absurd (calc 0 = n : e.symm ... > 0 : n_pos) dec_trivial)
| (m :: fs') n h n_pos :=
begin
rcases factors_lemma_cons n m fs' h with ⟨_, hm, hfs'⟩,
have : min_fac n ∣ n := min_fac_dvd n,
rw hm at this hfs',
let n' := n / m,
have p : m * n' = n := nat.mul_div_cancel' this,
have : n' > 0 := pos_of_mul_pos_left (p.symm ▸ n_pos : 0 < m * n') dec_trivial,
have r' := factors_as_factorization fs' n' hfs' this,
rw ←r' at p, rwa prod_cons
end
def factors_prime_factorization (n : ℕ) (n_pos : n > 0) :
{l : list PP // (l.map subtype.val).prod = n} :=
let ⟨l, h⟩ := factors_as_primes (factors n) n rfl in
⟨l, h.symm ▸ factors_as_factorization (factors n) n rfl n_pos⟩
-- or just
lemma factors_is_factorization (n : ℕ) (n_pos : n > 0) :
(factors n).prod = n :=
factors_as_factorization (factors n) n rfl n_pos
-- ∀ m ∈ factors n, prime m
/-
instance {α β : Sort*} [has_coe α β] : has_coe (list α) (list β) := ⟨map coe⟩
lemma coe_cons {α β : Sort*} [has_coe α β] (hd : α) (tl : list α) :
(↑(@list.cons α hd tl)) = (@list.cons β hd tl) := sorry
@[reducible] def prodN := @list.prod ℕ
-/
def p_to_pnat (p : PP) : ℕ+ := ↑p
lemma ord_of_prod (l : list PP) (p : PP) :
ord p (prod (l.map p_to_pnat)) = count p l :=
begin
induction l with l_hd l_tl ih,
{ exact ord_one },
{ by_cases h : p = l_hd,
exact calc
ord p (prod (map p_to_pnat (l_hd :: l_tl)))
= ord p (prod (p_to_pnat l_hd :: (l_tl.map p_to_pnat))) : rfl
... = ord p (p_to_pnat l_hd * prod (l_tl.map p_to_pnat)) : by rw prod_cons
... = ord p (p_to_pnat p * prod (l_tl.map p_to_pnat)) : by rw ←h
... = ord p (p * prod (l_tl.map p_to_pnat)) : rfl
... = succ (ord p (prod (l_tl.map p_to_pnat))) : by rw ord_div
... = succ (count p l_tl) : by rw ih
... = count p (p :: l_tl) : by simp [count_cons]
... = count p (l_hd :: l_tl) : by rw h,
let q := l_hd,
have : ord p q = 0 :=
ord_not_div.mp
((prime.coprime_iff_not_dvd p.property).mp
((coprime_primes p.property q.property).mpr (mt subtype.eq h))),
exact calc
ord p (prod (map p_to_pnat (l_hd :: l_tl)))
= ord p (prod (p_to_pnat l_hd :: (l_tl.map p_to_pnat))) : rfl
... = ord p (p_to_pnat l_hd * prod (l_tl.map p_to_pnat)) : by rw prod_cons
... = ord p (p_to_pnat q * prod (l_tl.map p_to_pnat)) : rfl
... = ord p (q * prod (l_tl.map p_to_pnat)) : rfl
... = ord p q + ord p (prod (l_tl.map p_to_pnat)) : by rw ord_mul
... = ord p (prod (l_tl.map p_to_pnat)) : by simp [this]
... = count p l_tl : by rw ih
... = count p (l_hd :: l_tl) : by simp [count_cons, h]
}
end
lemma ord_of_prod_multi (l : multiset PP) (p : PP) :
ord p ((l.map p_to_pnat).prod) = l.count p :=
begin
revert l, apply quot.ind, intro l,
exact calc
ord p ((multiset.map p_to_pnat ↑l).prod)
= ord p (prod (l.map p_to_pnat)) : by simp
... = count p l : by rw ord_of_prod
... = multiset.count p ↑l : by simp
end
lemma uniq (l1 l2 : multiset PP) :
(l1.map p_to_pnat).prod = (l2.map p_to_pnat).prod → l1 = l2 :=
begin
intro h,
rw multiset.ext, intro p,
rw [←ord_of_prod_multi, ←ord_of_prod_multi, h]
end
-- old weird stuff below
/-
def orders := PP →₀ ℕ
-- Yuck
lemma big_prime (p : PP) (n : ℕ+) : (p : ℕ) > n → ord p n = 0 :=
λ p_big, ord_not_div.mp (λ d, not_le_of_gt p_big (nat.le_of_dvd n.pos d))
lemma big_prime_2 (p : PP) (n : ℕ+) : ord p n ≠ 0 → (p : ℕ) ≤ n :=
le_of_not_gt ∘ mt (big_prime p n)
lemma val_is_injective {α : Type} {p : α → Prop} :
injective (subtype.val : subtype p → α) :=
λ a1 a2 e, subtype.eq e
-- euclid's lesser known theorem
lemma finitely_many_primes (n : ℕ) : finite {p : PP | ↑p ≤ n} :=
@finite_preimage PP ℕ {i : ℕ | i ≤ n} (λ p, p.val) val_is_injective (finite_le_nat n)
lemma primes_contained (n : ℕ+) : {p | ord p n ≠ 0} ⊆ {p : PP | (p : ℕ) ≤ n} :=
swap big_prime_2 n
def prime_orders (n : ℕ+) : orders :=
⟨λ p, ord p n, finite_subset (finitely_many_primes n) (primes_contained n)⟩
-- Multiplying
noncomputable def product : orders → ℕ+ :=
λ os, finsupp.prod os (λ p r, pnat.pow p r)
-/
end
|
c17c29f0f598988adeb236d1464a336553985ab2 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/ring_theory/polynomial/tower.lean | 316675f299ce7d92670bfbefd3734bb6ac6a97cb | [
"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 | 2,589 | 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.algebra.tower
import data.polynomial.algebra_map
/-!
# Algebra towers for polynomial
This file proves some basic results about the algebra tower structure for the type `polynomial R`.
This structure itself is provided elsewhere as `polynomial.is_scalar_tower`
-/
universes u v w u₁
variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁)
namespace is_scalar_tower
section semiring
variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B]
variables [algebra R S] [algebra S A] [algebra S B] [algebra R A] [algebra R B]
variables [is_scalar_tower R S A] [is_scalar_tower R S B]
variables (R S A) {B}
theorem aeval_apply (x : A) (p : polynomial R) : polynomial.aeval x p =
polynomial.aeval x (polynomial.map (algebra_map R S) p) :=
by rw [polynomial.aeval_def, polynomial.aeval_def, polynomial.eval₂_map, algebra_map_eq R S A]
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A] [semiring B]
variables [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B]
lemma algebra_map_aeval (x : A) (p : polynomial R) :
algebra_map A B (polynomial.aeval x p) = polynomial.aeval (algebra_map A B x) p :=
by rw [polynomial.aeval_def, polynomial.aeval_def, polynomial.hom_eval₂,
←is_scalar_tower.algebra_map_eq]
lemma aeval_eq_zero_of_aeval_algebra_map_eq_zero {x : A} {p : polynomial R}
(h : function.injective (algebra_map A B)) (hp : polynomial.aeval (algebra_map A B x) p = 0) :
polynomial.aeval x p = 0 :=
begin
rw [← algebra_map_aeval, ← (algebra_map A B).map_zero] at hp,
exact h hp,
end
lemma aeval_eq_zero_of_aeval_algebra_map_eq_zero_field {R A B : Type*} [comm_semiring R] [field A]
[comm_semiring B] [nontrivial B] [algebra R A] [algebra R B] [algebra A B] [is_scalar_tower R A B]
{x : A} {p : polynomial R} (h : polynomial.aeval (algebra_map A B x) p = 0) :
polynomial.aeval x p = 0 :=
aeval_eq_zero_of_aeval_algebra_map_eq_zero R A B (algebra_map A B).injective h
end comm_semiring
end is_scalar_tower
namespace subalgebra
open is_scalar_tower
section comm_semiring
variables (R) {S A} [comm_semiring R] [comm_semiring S] [comm_semiring A]
variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A]
@[simp] lemma aeval_coe {S : subalgebra R A} {x : S} {p : polynomial R} :
polynomial.aeval (x : A) p = polynomial.aeval x p :=
(algebra_map_aeval R S A x p).symm
end comm_semiring
end subalgebra
|
3df96800c63b0c5f17c430c95140c2dd722d42b6 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/algebra/lie/weights.lean | 81c97fb74f5fa77acea115b906e65169c3f3b832 | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 21,710 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.nilpotent
import algebra.lie.tensor_product
import algebra.lie.character
import algebra.lie.cartan_subalgebra
import linear_algebra.eigenspace
import ring_theory.tensor_product
/-!
# Weights and roots of Lie modules and Lie algebras
Just as a key tool when studying the behaviour of a linear operator is to decompose the space on
which it acts into a sum of (generalised) eigenspaces, a key tool when studying a representation `M`
of Lie algebra `L` is to decompose `M` into a sum of simultaneous eigenspaces of `x` as `x` ranges
over `L`. These simultaneous generalised eigenspaces are known as the weight spaces of `M`.
When `L` is nilpotent, it follows from the binomial theorem that weight spaces are Lie submodules.
Even when `L` is not nilpotent, it may be useful to study its representations by restricting them
to a nilpotent subalgebra (e.g., a Cartan subalgebra). In the particular case when we view `L` as a
module over itself via the adjoint action, the weight spaces of `L` restricted to a nilpotent
subalgebra are known as root spaces.
Basic definitions and properties of the above ideas are provided in this file.
## Main definitions
* `lie_module.weight_space`
* `lie_module.is_weight`
* `lie_algebra.root_space`
* `lie_algebra.is_root`
* `lie_algebra.root_space_weight_space_product`
* `lie_algebra.root_space_product`
## References
* [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 7--9*](bourbaki1975b)
## Tags
lie character, eigenvalue, eigenspace, weight, weight vector, root, root vector
-/
universes u v w w₁ w₂ w₃
variables {R : Type u} {L : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L]
variables (H : lie_subalgebra R L) [lie_algebra.is_nilpotent R H]
variables (M : Type w) [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
namespace lie_module
open lie_algebra
open tensor_product
open tensor_product.lie_module
open_locale big_operators
open_locale tensor_product
/-- Given a Lie module `M` over a Lie algebra `L`, the pre-weight space of `M` with respect to a
map `χ : L → R` is the simultaneous generalized eigenspace of the action of all `x : L` on `M`,
with eigenvalues `χ x`.
See also `lie_module.weight_space`. -/
def pre_weight_space (χ : L → R) : submodule R M :=
⨅ (x : L), (to_endomorphism R L M x).maximal_generalized_eigenspace (χ x)
lemma mem_pre_weight_space (χ : L → R) (m : M) :
m ∈ pre_weight_space M χ ↔ ∀ x, ∃ (k : ℕ), ((to_endomorphism R L M x - (χ x) • 1)^k) m = 0 :=
by simp [pre_weight_space, -linear_map.pow_apply]
variables (L)
/-- See also `bourbaki1975b` Chapter VII §1.1, Proposition 2 (ii). -/
protected lemma weight_vector_multiplication (M₁ : Type w₁) (M₂ : Type w₂) (M₃ : Type w₃)
[add_comm_group M₁] [module R M₁] [lie_ring_module L M₁] [lie_module R L M₁]
[add_comm_group M₂] [module R M₂] [lie_ring_module L M₂] [lie_module R L M₂]
[add_comm_group M₃] [module R M₃] [lie_ring_module L M₃] [lie_module R L M₃]
(g : M₁ ⊗[R] M₂ →ₗ⁅R,L⁆ M₃) (χ₁ χ₂ : L → R) :
((g : M₁ ⊗[R] M₂ →ₗ[R] M₃).comp
(map_incl (pre_weight_space M₁ χ₁) (pre_weight_space M₂ χ₂))).range ≤
pre_weight_space M₃ (χ₁ + χ₂) :=
begin
/- Unpack the statement of the goal. -/
intros m₃,
simp only [lie_module_hom.coe_to_linear_map, pi.add_apply, function.comp_app,
mem_pre_weight_space, linear_map.coe_comp, tensor_product.map_incl, exists_imp_distrib,
linear_map.mem_range],
rintros t rfl x,
/- Set up some notation. -/
let F : module.End R M₃ := (to_endomorphism R L M₃ x) - (χ₁ x + χ₂ x) • 1,
change ∃ k, (F^k) (g _) = 0,
/- The goal is linear in `t` so use induction to reduce to the case that `t` is a pure tensor. -/
apply t.induction_on,
{ use 0, simp only [linear_map.map_zero, lie_module_hom.map_zero], },
swap,
{ rintros t₁ t₂ ⟨k₁, hk₁⟩ ⟨k₂, hk₂⟩, use max k₁ k₂,
simp only [lie_module_hom.map_add, linear_map.map_add,
linear_map.pow_map_zero_of_le (le_max_left k₁ k₂) hk₁,
linear_map.pow_map_zero_of_le (le_max_right k₁ k₂) hk₂, add_zero], },
/- Now the main argument: pure tensors. -/
rintros ⟨m₁, hm₁⟩ ⟨m₂, hm₂⟩,
change ∃ k, (F^k) ((g : M₁ ⊗[R] M₂ →ₗ[R] M₃) (m₁ ⊗ₜ m₂)) = 0,
/- Eliminate `g` from the picture. -/
let f₁ : module.End R (M₁ ⊗[R] M₂) := (to_endomorphism R L M₁ x - (χ₁ x) • 1).rtensor M₂,
let f₂ : module.End R (M₁ ⊗[R] M₂) := (to_endomorphism R L M₂ x - (χ₂ x) • 1).ltensor M₁,
have h_comm_square : F ∘ₗ ↑g = (g : M₁ ⊗[R] M₂ →ₗ[R] M₃).comp (f₁ + f₂),
{ ext m₁ m₂, simp only [← g.map_lie x (m₁ ⊗ₜ m₂), add_smul, sub_tmul, tmul_sub, smul_tmul,
lie_tmul_right, tmul_smul, to_endomorphism_apply_apply, lie_module_hom.map_smul,
linear_map.one_apply, lie_module_hom.coe_to_linear_map, linear_map.smul_apply,
function.comp_app, linear_map.coe_comp, linear_map.rtensor_tmul, lie_module_hom.map_add,
linear_map.add_apply, lie_module_hom.map_sub, linear_map.sub_apply, linear_map.ltensor_tmul,
algebra_tensor_module.curry_apply, curry_apply, linear_map.to_fun_eq_coe,
linear_map.coe_restrict_scalars_eq_coe], abel, },
suffices : ∃ k, ((f₁ + f₂)^k) (m₁ ⊗ₜ m₂) = 0,
{ obtain ⟨k, hk⟩ := this, use k,
rw [← linear_map.comp_apply, linear_map.commute_pow_left_of_commute h_comm_square,
linear_map.comp_apply, hk, linear_map.map_zero], },
/- Unpack the information we have about `m₁`, `m₂`. -/
simp only [mem_pre_weight_space] at hm₁ hm₂,
obtain ⟨k₁, hk₁⟩ := hm₁ x,
obtain ⟨k₂, hk₂⟩ := hm₂ x,
have hf₁ : (f₁^k₁) (m₁ ⊗ₜ m₂) = 0,
{ simp only [hk₁, zero_tmul, linear_map.rtensor_tmul, linear_map.rtensor_pow], },
have hf₂ : (f₂^k₂) (m₁ ⊗ₜ m₂) = 0,
{ simp only [hk₂, tmul_zero, linear_map.ltensor_tmul, linear_map.ltensor_pow], },
/- It's now just an application of the binomial theorem. -/
use k₁ + k₂ - 1,
have hf_comm : commute f₁ f₂,
{ ext m₁ m₂, simp only [linear_map.mul_apply, linear_map.rtensor_tmul, linear_map.ltensor_tmul,
algebra_tensor_module.curry_apply, linear_map.to_fun_eq_coe, linear_map.ltensor_tmul,
curry_apply, linear_map.coe_restrict_scalars_eq_coe], },
rw hf_comm.add_pow',
simp only [tensor_product.map_incl, submodule.subtype_apply, finset.sum_apply,
submodule.coe_mk, linear_map.coe_fn_sum, tensor_product.map_tmul, linear_map.smul_apply],
/- The required sum is zero because each individual term is zero. -/
apply finset.sum_eq_zero,
rintros ⟨i, j⟩ hij,
/- Eliminate the binomial coefficients from the picture. -/
suffices : (f₁^i * f₂^j) (m₁ ⊗ₜ m₂) = 0, { rw this, apply smul_zero, },
/- Finish off with appropriate case analysis. -/
cases nat.le_or_le_of_add_eq_add_pred (finset.nat.mem_antidiagonal.mp hij) with hi hj,
{ rw [(hf_comm.pow_pow i j).eq, linear_map.mul_apply, linear_map.pow_map_zero_of_le hi hf₁,
linear_map.map_zero], },
{ rw [linear_map.mul_apply, linear_map.pow_map_zero_of_le hj hf₂, linear_map.map_zero], },
end
variables {L M}
lemma lie_mem_pre_weight_space_of_mem_pre_weight_space {χ₁ χ₂ : L → R} {x : L} {m : M}
(hx : x ∈ pre_weight_space L χ₁) (hm : m ∈ pre_weight_space M χ₂) :
⁅x, m⁆ ∈ pre_weight_space M (χ₁ + χ₂) :=
begin
apply lie_module.weight_vector_multiplication L L M M (to_module_hom R L M) χ₁ χ₂,
simp only [lie_module_hom.coe_to_linear_map, function.comp_app, linear_map.coe_comp,
tensor_product.map_incl, linear_map.mem_range],
use [⟨x, hx⟩ ⊗ₜ ⟨m, hm⟩],
simp only [submodule.subtype_apply, to_module_hom_apply, tensor_product.map_tmul],
refl,
end
variables (M)
/-- If a Lie algebra is nilpotent, then pre-weight spaces are Lie submodules. -/
def weight_space [lie_algebra.is_nilpotent R L] (χ : L → R) : lie_submodule R L M :=
{ lie_mem := λ x m hm,
begin
rw ← zero_add χ,
refine lie_mem_pre_weight_space_of_mem_pre_weight_space _ hm,
suffices : pre_weight_space L (0 : L → R) = ⊤, { simp only [this, submodule.mem_top], },
exact lie_algebra.infi_max_gen_zero_eigenspace_eq_top_of_nilpotent R L,
end,
.. pre_weight_space M χ }
lemma mem_weight_space [lie_algebra.is_nilpotent R L] (χ : L → R) (m : M) :
m ∈ weight_space M χ ↔ m ∈ pre_weight_space M χ :=
iff.rfl
/-- See also the more useful form `lie_module.zero_weight_space_eq_top_of_nilpotent`. -/
@[simp] lemma zero_weight_space_eq_top_of_nilpotent'
[lie_algebra.is_nilpotent R L] [is_nilpotent R L M] :
weight_space M (0 : L → R) = ⊤ :=
begin
rw [← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.top_coe_submodule],
exact infi_max_gen_zero_eigenspace_eq_top_of_nilpotent R L M,
end
lemma coe_weight_space_of_top [lie_algebra.is_nilpotent R L] (χ : L → R) :
(weight_space M (χ ∘ (⊤ : lie_subalgebra R L).incl) : submodule R M) = weight_space M χ :=
begin
ext m,
simp only [weight_space, lie_submodule.coe_to_submodule_mk, lie_subalgebra.coe_bracket_of_module,
function.comp_app, mem_pre_weight_space],
split; intros h x,
{ obtain ⟨k, hk⟩ := h ⟨x, set.mem_univ x⟩, use k, exact hk, },
{ obtain ⟨k, hk⟩ := h x, use k, exact hk, },
end
@[simp] lemma zero_weight_space_eq_top_of_nilpotent
[lie_algebra.is_nilpotent R L] [is_nilpotent R L M] :
weight_space M (0 : (⊤ : lie_subalgebra R L) → R) = ⊤ :=
begin
/- We use `coe_weight_space_of_top` as a trick to circumvent the fact that we don't (yet) know
`is_nilpotent R (⊤ : lie_subalgebra R L) M` is equivalent to `is_nilpotent R L M`. -/
have h₀ : (0 : L → R) ∘ (⊤ : lie_subalgebra R L).incl = 0, { ext, refl, },
rw [← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.top_coe_submodule, ← h₀,
coe_weight_space_of_top, ← infi_max_gen_zero_eigenspace_eq_top_of_nilpotent R L M],
refl,
end
/-- Given a Lie module `M` of a Lie algebra `L`, a weight of `M` with respect to a nilpotent
subalgebra `H ⊆ L` is a Lie character whose corresponding weight space is non-empty. -/
def is_weight (χ : lie_character R H) : Prop := weight_space M χ ≠ ⊥
/-- For a non-trivial nilpotent Lie module over a nilpotent Lie algebra, the zero character is a
weight with respect to the `⊤` Lie subalgebra. -/
lemma is_weight_zero_of_nilpotent
[nontrivial M] [lie_algebra.is_nilpotent R L] [is_nilpotent R L M] :
is_weight (⊤ : lie_subalgebra R L) M 0 :=
by { rw [is_weight, lie_hom.coe_zero, zero_weight_space_eq_top_of_nilpotent], exact top_ne_bot, }
end lie_module
namespace lie_algebra
open_locale tensor_product
open tensor_product.lie_module
open lie_module
/-- Given a nilpotent Lie subalgebra `H ⊆ L`, the root space of a map `χ : H → R` is the weight
space of `L` regarded as a module of `H` via the adjoint action. -/
abbreviation root_space (χ : H → R) : lie_submodule R H L := weight_space L χ
@[simp] lemma zero_root_space_eq_top_of_nilpotent [h : is_nilpotent R L] :
root_space (⊤ : lie_subalgebra R L) 0 = ⊤ :=
zero_weight_space_eq_top_of_nilpotent L
/-- A root of a Lie algebra `L` with respect to a nilpotent subalgebra `H ⊆ L` is a weight of `L`,
regarded as a module of `H` via the adjoint action. -/
abbreviation is_root := is_weight H L
@[simp] lemma root_space_comap_eq_weight_space (χ : H → R) :
(root_space H χ).comap H.incl' = weight_space H χ :=
begin
ext x,
let f : H → module.End R L := λ y, to_endomorphism R H L y - (χ y) • 1,
let g : H → module.End R H := λ y, to_endomorphism R H H y - (χ y) • 1,
suffices : (∀ (y : H), ∃ (k : ℕ), ((f y)^k).comp (H.incl : H →ₗ[R] L) x = 0) ↔
∀ (y : H), ∃ (k : ℕ), (H.incl : H →ₗ[R] L).comp ((g y)^k) x = 0,
{ simp only [lie_hom.coe_to_linear_map, lie_subalgebra.coe_incl, function.comp_app,
linear_map.coe_comp, submodule.coe_eq_zero] at this,
simp only [mem_weight_space, mem_pre_weight_space,
lie_subalgebra.coe_incl', lie_submodule.mem_comap, this], },
have hfg : ∀ (y : H), (f y).comp (H.incl : H →ₗ[R] L) = (H.incl : H →ₗ[R] L).comp (g y),
{ rintros ⟨y, hz⟩, ext ⟨z, hz⟩,
simp only [submodule.coe_sub, to_endomorphism_apply_apply, lie_hom.coe_to_linear_map,
linear_map.one_apply, lie_subalgebra.coe_incl, lie_subalgebra.coe_bracket_of_module,
lie_subalgebra.coe_bracket, linear_map.smul_apply, function.comp_app,
submodule.coe_smul_of_tower, linear_map.coe_comp, linear_map.sub_apply], },
simp_rw [linear_map.commute_pow_left_of_commute (hfg _)],
end
variables {H M}
lemma lie_mem_weight_space_of_mem_weight_space {χ₁ χ₂ : H → R} {x : L} {m : M}
(hx : x ∈ root_space H χ₁) (hm : m ∈ weight_space M χ₂) : ⁅x, m⁆ ∈ weight_space M (χ₁ + χ₂) :=
begin
apply lie_module.weight_vector_multiplication
H L M M ((to_module_hom R L M).restrict_lie H) χ₁ χ₂,
simp only [lie_module_hom.coe_to_linear_map, function.comp_app, linear_map.coe_comp,
tensor_product.map_incl, linear_map.mem_range],
use [⟨x, hx⟩ ⊗ₜ ⟨m, hm⟩],
simp only [submodule.subtype_apply, to_module_hom_apply, submodule.coe_mk,
lie_module_hom.coe_restrict_lie, tensor_product.map_tmul],
end
variables (R L H M)
/--
Auxiliary definition for `root_space_weight_space_product`,
which is close to the deterministic timeout limit.
-/
def root_space_weight_space_product_aux {χ₁ χ₂ χ₃ : H → R} (hχ : χ₁ + χ₂ = χ₃) :
(root_space H χ₁) →ₗ[R] (weight_space M χ₂) →ₗ[R] (weight_space M χ₃) :=
{ to_fun := λ x,
{ to_fun :=
λ m, ⟨⁅(x : L), (m : M)⁆,
hχ ▸ (lie_mem_weight_space_of_mem_weight_space x.property m.property) ⟩,
map_add' := λ m n, by { simp only [lie_submodule.coe_add, lie_add], refl, },
map_smul' := λ t m, by { conv_lhs { congr, rw [lie_submodule.coe_smul, lie_smul], }, refl, }, },
map_add' := λ x y, by ext m; rw [linear_map.add_apply, linear_map.coe_mk, linear_map.coe_mk,
linear_map.coe_mk, subtype.coe_mk, lie_submodule.coe_add, lie_submodule.coe_add, add_lie,
subtype.coe_mk, subtype.coe_mk],
map_smul' := λ t x,
begin
simp only [ring_hom.id_apply],
ext m,
rw [linear_map.smul_apply, linear_map.coe_mk, linear_map.coe_mk,
subtype.coe_mk, lie_submodule.coe_smul, smul_lie, lie_submodule.coe_smul, subtype.coe_mk],
end, }
/-- Given a nilpotent Lie subalgebra `H ⊆ L` together with `χ₁ χ₂ : H → R`, there is a natural
`R`-bilinear product of root vectors and weight vectors, compatible with the actions of `H`. -/
def root_space_weight_space_product (χ₁ χ₂ χ₃ : H → R) (hχ : χ₁ + χ₂ = χ₃) :
(root_space H χ₁) ⊗[R] (weight_space M χ₂) →ₗ⁅R,H⁆ weight_space M χ₃ :=
lift_lie R H (root_space H χ₁) (weight_space M χ₂) (weight_space M χ₃)
{ to_linear_map := root_space_weight_space_product_aux R L H M hχ,
map_lie' := λ x y, by ext m; rw [root_space_weight_space_product_aux,
lie_hom.lie_apply, lie_submodule.coe_sub, linear_map.coe_mk,
linear_map.coe_mk, subtype.coe_mk, subtype.coe_mk, lie_submodule.coe_bracket,
lie_submodule.coe_bracket, subtype.coe_mk, lie_subalgebra.coe_bracket_of_module,
lie_subalgebra.coe_bracket_of_module, lie_submodule.coe_bracket,
lie_subalgebra.coe_bracket_of_module, lie_lie], }
@[simp] lemma coe_root_space_weight_space_product_tmul
(χ₁ χ₂ χ₃ : H → R) (hχ : χ₁ + χ₂ = χ₃) (x : root_space H χ₁) (m : weight_space M χ₂) :
(root_space_weight_space_product R L H M χ₁ χ₂ χ₃ hχ (x ⊗ₜ m) : M) = ⁅(x : L), (m : M)⁆ :=
by simp only [root_space_weight_space_product, root_space_weight_space_product_aux,
lift_apply, lie_module_hom.coe_to_linear_map,
coe_lift_lie_eq_lift_coe, submodule.coe_mk, linear_map.coe_mk, lie_module_hom.coe_mk]
/-- Given a nilpotent Lie subalgebra `H ⊆ L` together with `χ₁ χ₂ : H → R`, there is a natural
`R`-bilinear product of root vectors, compatible with the actions of `H`. -/
def root_space_product (χ₁ χ₂ χ₃ : H → R) (hχ : χ₁ + χ₂ = χ₃) :
(root_space H χ₁) ⊗[R] (root_space H χ₂) →ₗ⁅R,H⁆ root_space H χ₃ :=
root_space_weight_space_product R L H L χ₁ χ₂ χ₃ hχ
@[simp] lemma root_space_product_def :
root_space_product R L H = root_space_weight_space_product R L H L :=
rfl
lemma root_space_product_tmul
(χ₁ χ₂ χ₃ : H → R) (hχ : χ₁ + χ₂ = χ₃) (x : root_space H χ₁) (y : root_space H χ₂) :
(root_space_product R L H χ₁ χ₂ χ₃ hχ (x ⊗ₜ y) : L) = ⁅(x : L), (y : L)⁆ :=
by simp only [root_space_product_def, coe_root_space_weight_space_product_tmul]
/-- Given a nilpotent Lie subalgebra `H ⊆ L`, the root space of the zero map `0 : H → R` is a Lie
subalgebra of `L`. -/
def zero_root_subalgebra : lie_subalgebra R L :=
{ lie_mem' := λ x y hx hy, by
{ let xy : (root_space H 0) ⊗[R] (root_space H 0) := ⟨x, hx⟩ ⊗ₜ ⟨y, hy⟩,
suffices : (root_space_product R L H 0 0 0 (add_zero 0) xy : L) ∈ root_space H 0,
{ rwa [root_space_product_tmul, subtype.coe_mk, subtype.coe_mk] at this, },
exact (root_space_product R L H 0 0 0 (add_zero 0) xy).property, },
.. (root_space H 0 : submodule R L) }
@[simp] lemma coe_zero_root_subalgebra :
(zero_root_subalgebra R L H : submodule R L) = root_space H 0 :=
rfl
lemma mem_zero_root_subalgebra (x : L) :
x ∈ zero_root_subalgebra R L H ↔ ∀ (y : H), ∃ (k : ℕ), ((to_endomorphism R H L y)^k) x = 0 :=
by simp only [zero_root_subalgebra, mem_weight_space, mem_pre_weight_space, pi.zero_apply, sub_zero,
set_like.mem_coe, zero_smul, lie_submodule.mem_coe_submodule, submodule.mem_carrier,
lie_subalgebra.mem_mk_iff]
lemma to_lie_submodule_le_root_space_zero : H.to_lie_submodule ≤ root_space H 0 :=
begin
intros x hx,
simp only [lie_subalgebra.mem_to_lie_submodule] at hx,
simp only [mem_weight_space, mem_pre_weight_space, pi.zero_apply, sub_zero, zero_smul],
intros y,
unfreezingI { obtain ⟨k, hk⟩ := (infer_instance : is_nilpotent R H) },
use k,
let f : module.End R H := to_endomorphism R H H y,
let g : module.End R L := to_endomorphism R H L y,
have hfg : g.comp (H : submodule R L).subtype = (H : submodule R L).subtype.comp f,
{ ext z, simp only [to_endomorphism_apply_apply, submodule.subtype_apply,
lie_subalgebra.coe_bracket_of_module, lie_subalgebra.coe_bracket, function.comp_app,
linear_map.coe_comp], },
change (g^k).comp (H : submodule R L).subtype ⟨x, hx⟩ = 0,
rw linear_map.commute_pow_left_of_commute hfg k,
have h := iterate_to_endomorphism_mem_lower_central_series R H H y ⟨x, hx⟩ k,
rw [hk, lie_submodule.mem_bot] at h,
simp only [submodule.subtype_apply, function.comp_app, linear_map.pow_apply, linear_map.coe_comp,
submodule.coe_eq_zero],
exact h,
end
lemma le_zero_root_subalgebra : H ≤ zero_root_subalgebra R L H :=
begin
rw [← lie_subalgebra.coe_submodule_le_coe_submodule, ← H.coe_to_lie_submodule,
coe_zero_root_subalgebra, lie_submodule.coe_submodule_le_coe_submodule],
exact to_lie_submodule_le_root_space_zero R L H,
end
@[simp] lemma zero_root_subalgebra_normalizer_eq_self :
(zero_root_subalgebra R L H).normalizer = zero_root_subalgebra R L H :=
begin
refine le_antisymm _ (lie_subalgebra.le_normalizer _),
intros x hx,
rw lie_subalgebra.mem_normalizer_iff at hx,
rw mem_zero_root_subalgebra,
rintros ⟨y, hy⟩,
specialize hx y (le_zero_root_subalgebra R L H hy),
rw mem_zero_root_subalgebra at hx,
obtain ⟨k, hk⟩ := hx ⟨y, hy⟩,
rw [← lie_skew, linear_map.map_neg, neg_eq_zero] at hk,
use k + 1,
rw [linear_map.iterate_succ, linear_map.coe_comp, function.comp_app, to_endomorphism_apply_apply,
lie_subalgebra.coe_bracket_of_module, submodule.coe_mk, hk],
end
/-- In finite dimensions over a field (and possibly more generally) Engel's theorem shows that
the converse of this is also true, i.e.,
`zero_root_subalgebra R L H = H ↔ lie_subalgebra.is_cartan_subalgebra H`. -/
lemma zero_root_subalgebra_is_cartan_of_eq (h : zero_root_subalgebra R L H = H) :
lie_subalgebra.is_cartan_subalgebra H :=
{ nilpotent := infer_instance,
self_normalizing := by { rw ← h, exact zero_root_subalgebra_normalizer_eq_self R L H, } }
end lie_algebra
namespace lie_module
open lie_algebra
variables {R L H}
/-- A priori, weight spaces are Lie submodules over the Lie subalgebra `H` used to define them.
However they are naturally Lie submodules over the (in general larger) Lie subalgebra
`zero_root_subalgebra R L H`. Even though it is often the case that
`zero_root_subalgebra R L H = H`, it is likely to be useful to have the flexibility not to have
to invoke this equality (as well as to work more generally). -/
def weight_space' (χ : H → R) : lie_submodule R (zero_root_subalgebra R L H) M :=
{ lie_mem := λ x m hm, by
{ have hx : (x : L) ∈ root_space H 0,
{ rw [← lie_submodule.mem_coe_submodule, ← coe_zero_root_subalgebra], exact x.property, },
rw ← zero_add χ,
exact lie_mem_weight_space_of_mem_weight_space hx hm, },
.. (weight_space M χ : submodule R M) }
@[simp] lemma coe_weight_space' (χ : H → R) :
(weight_space' M χ : submodule R M) = weight_space M χ :=
rfl
end lie_module
|
f014b9e02b7e3bf5bc65fe103e08a5f399ecc064 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/control/equiv_functor.lean | 4d29f809169a9e5f59f00c939576a510db76f15f | [
"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 | 3,316 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Scott Morrison
-/
import category_theory.category
import data.equiv.functor
/-!
# Functions functorial with respect to equivalences
An `equiv_functor` is a function from `Type → Type` equipped with the additional data of
coherently mapping equivalences to equivalences.
In categorical language, it is an endofunctor of the "core" of the category `Type`.
-/
universes u₀ u₁ u₂ v₀ v₁ v₂
open function
/--
An `equiv_functor` is only functorial with respect to equivalences.
To construct an `equiv_functor`, it suffices to supply just the function `f α → f β` from
an equivalence `α ≃ β`, and then prove the functor laws. It's then a consequence that
this function is part of an equivalence, provided by `equiv_functor.map_equiv`.
-/
class equiv_functor (f : Type u₀ → Type u₁) :=
(map : Π {α β}, (α ≃ β) → (f α → f β))
(map_refl' : Π α, map (equiv.refl α) = @id (f α) . obviously)
(map_trans' : Π {α β γ} (k : α ≃ β) (h : β ≃ γ),
map (k.trans h) = (map h) ∘ (map k) . obviously)
restate_axiom equiv_functor.map_refl'
restate_axiom equiv_functor.map_trans'
attribute [simp] equiv_functor.map_refl
namespace equiv_functor
section
variables (f : Type u₀ → Type u₁) [equiv_functor f] {α β : Type u₀} (e : α ≃ β)
/-- An `equiv_functor` in fact takes every equiv to an equiv. -/
def map_equiv :
f α ≃ f β :=
{ to_fun := equiv_functor.map e,
inv_fun := equiv_functor.map e.symm,
left_inv := λ x, begin convert (congr_fun (equiv_functor.map_trans e e.symm) x).symm, simp, end,
right_inv := λ y, begin convert (congr_fun (equiv_functor.map_trans e.symm e) y).symm, simp, end, }
@[simp] lemma map_equiv_apply (x : f α) :
map_equiv f e x = equiv_functor.map e x := rfl
lemma map_equiv_symm_apply (y : f β) :
(map_equiv f e).symm y = equiv_functor.map e.symm y := rfl
@[simp] lemma map_equiv_refl (α) :
map_equiv f (equiv.refl α) = equiv.refl (f α) :=
by simpa [equiv_functor.map_equiv]
@[simp] lemma map_equiv_symm :
(map_equiv f e).symm = map_equiv f e.symm :=
equiv.ext $ map_equiv_symm_apply f e
/--
The composition of `map_equiv`s is carried over the `equiv_functor`.
For plain `functor`s, this lemma is named `map_map` when applied
or `map_comp_map` when not applied.
-/
@[simp] lemma map_equiv_trans {γ : Type u₀} (ab : α ≃ β) (bc : β ≃ γ) :
(map_equiv f ab).trans (map_equiv f bc) = map_equiv f (ab.trans bc) :=
equiv.ext $ λ x, by simp [map_equiv, map_trans']
end
@[priority 100]
instance of_is_lawful_functor
(f : Type u₀ → Type u₁) [functor f] [is_lawful_functor f] : equiv_functor f :=
{ map := λ α β e, functor.map e,
map_refl' := λ α, by { ext, apply is_lawful_functor.id_map, },
map_trans' := λ α β γ k h, by { ext x, apply (is_lawful_functor.comp_map k h x), } }
lemma map_equiv.injective
(f : Type u₀ → Type u₁) [applicative f] [is_lawful_applicative f] {α β : Type u₀}
(h : ∀ γ, function.injective (pure : γ → f γ)) :
function.injective (@equiv_functor.map_equiv f _ α β) :=
λ e₁ e₂ H, equiv.ext $ λ x, h β (by simpa [equiv_functor.map] using equiv.congr_fun H (pure x))
end equiv_functor
|
fad78a8c3edb509193f105d464fe95b993e06ddc | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /stage0/src/Std/Data/RBMap.lean | 682dcb4027805947fdbffc6d42f1d870b25db9ed | [
"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 | 13,503 | 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
-/
namespace Std
universes u v w w'
inductive Rbcolor where
| red | black
inductive RBNode (α : Type u) (β : α → Type v) where
| leaf : RBNode α β
| node (color : Rbcolor) (lchild : RBNode α β) (key : α) (val : β key) (rchild : RBNode α β) : RBNode α β
namespace RBNode
variable {α : Type u} {β : α → Type v} {σ : Type w}
open Std.Rbcolor Nat
def depth (f : Nat → Nat → Nat) : RBNode α β → Nat
| leaf => 0
| node _ l _ _ r => succ (f (depth f l) (depth f r))
protected def min : RBNode α β → Option (Sigma (fun k => β k))
| leaf => none
| node _ leaf k v _ => some ⟨k, v⟩
| node _ l k v _ => RBNode.min l
protected def max : RBNode α β → Option (Sigma (fun k => β k))
| leaf => none
| node _ _ k v leaf => some ⟨k, v⟩
| node _ _ k v r => RBNode.max r
@[specialize] def fold (f : σ → (k : α) → β k → σ) : (init : σ) → RBNode α β → σ
| b, leaf => b
| b, node _ l k v r => fold f (f (fold f b l) k v) r
@[specialize] def foldM {m : Type w → Type w'} [Monad m] (f : σ → (k : α) → β k → m σ) : (init : σ) → RBNode α β → m σ
| b, leaf => pure b
| b, node _ l k v r => do
let b ← foldM f b l
let b ← f b k v
foldM f b r
@[inline] protected def forIn [Monad m] (as : RBNode α β) (init : σ) (f : (k : α) → β k → σ → m (ForInStep σ)) : m σ := do
let rec @[specialize] visit : RBNode α β → σ → m (ForInStep σ)
| leaf, b => return ForInStep.yield b
| node _ l k v r, b => do
match (← visit l b) with
| r@(ForInStep.done _) => return r
| ForInStep.yield b =>
match (← f k v b) with
| r@(ForInStep.done _) => return r
| ForInStep.yield b => visit r b
match ← visit as init with
| ForInStep.done b => pure b
| ForInStep.yield b => pure b
@[specialize] def revFold (f : σ → (k : α) → β k → σ) : (init : σ) → RBNode α β → σ
| b, leaf => b
| b, node _ l k v r => revFold f (f (revFold f b r) k v) l
@[specialize] def all (p : (k : α) → β k → Bool) : RBNode α β → Bool
| leaf => true
| node _ l k v r => p k v && all p l && all p r
@[specialize] def any (p : (k : α) → β k → Bool) : RBNode α β → Bool
| leaf => false
| node _ l k v r => p k v || any p l || any p r
def singleton (k : α) (v : β k) : RBNode α β :=
node red leaf k v leaf
@[inline] def balance1 : (a : α) → β a → RBNode α β → RBNode α β → RBNode α β
| kv, vv, t, node _ (node red l kx vx r₁) ky vy r₂ => node red (node black l kx vx r₁) ky vy (node black r₂ kv vv t)
| kv, vv, t, node _ l₁ ky vy (node red l₂ kx vx r) => node red (node black l₁ ky vy l₂) kx vx (node black r kv vv t)
| kv, vv, t, node _ l ky vy r => node black (node red l ky vy r) kv vv t
| _, _, _, _ => leaf -- unreachable
@[inline] def balance2 : RBNode α β → (a : α) → β a → RBNode α β → RBNode α β
| t, kv, vv, node _ (node red l kx₁ vx₁ r₁) ky vy r₂ => node red (node black t kv vv l) kx₁ vx₁ (node black r₁ ky vy r₂)
| t, kv, vv, node _ l₁ ky vy (node red l₂ kx₂ vx₂ r₂) => node red (node black t kv vv l₁) ky vy (node black l₂ kx₂ vx₂ r₂)
| t, kv, vv, node _ l ky vy r => node black t kv vv (node red l ky vy r)
| _, _, _, _ => leaf -- unreachable
def isRed : RBNode α β → Bool
| node red .. => true
| _ => false
def isBlack : RBNode α β → Bool
| node black .. => true
| _ => false
section Insert
variable (lt : α → α → Bool)
@[specialize] def ins : RBNode α β → (k : α) → β k → RBNode α β
| leaf, kx, vx => node red leaf kx vx leaf
| node red a ky vy b, kx, vx =>
if lt kx ky then node red (ins a kx vx) ky vy b
else if lt ky kx then node red a ky vy (ins b kx vx)
else node red a kx vx b
| node black a ky vy b, kx, vx =>
if lt kx ky then
if isRed a then balance1 ky vy b (ins a kx vx)
else node black (ins a kx vx) ky vy b
else if lt ky kx then
if isRed b then balance2 a ky vy (ins b kx vx)
else node black a ky vy (ins b kx vx)
else
node black a kx vx b
def setBlack : RBNode α β → RBNode α β
| node _ l k v r => node black l k v r
| e => e
@[specialize] def insert (t : RBNode α β) (k : α) (v : β k) : RBNode α β :=
if isRed t then setBlack (ins lt t k v)
else ins lt t k v
end Insert
def balance₃ (a : RBNode α β) (k : α) (v : β k) (d : RBNode α β) : RBNode α β :=
match a with
| node red (node red a kx vx b) ky vy c => node red (node black a kx vx b) ky vy (node black c k v d)
| node red a kx vx (node red b ky vy c) => node red (node black a kx vx b) ky vy (node black c k v d)
| a => match d with
| node red b ky vy (node red c kz vz d) => node red (node black a k v b) ky vy (node black c kz vz d)
| node red (node red b ky vy c) kz vz d => node red (node black a k v b) ky vy (node black c kz vz d)
| _ => node black a k v d
def setRed : RBNode α β → RBNode α β
| node _ a k v b => node red a k v b
| e => e
def balLeft : RBNode α β → (k : α) → β k → RBNode α β → RBNode α β
| node red a kx vx b, k, v, r => node red (node black a kx vx b) k v r
| l, k, v, node black a ky vy b => balance₃ l k v (node red a ky vy b)
| l, k, v, node red (node black a ky vy b) kz vz c => node red (node black l k v a) ky vy (balance₃ b kz vz (setRed c))
| l, k, v, r => node red l k v r -- unreachable
def balRight (l : RBNode α β) (k : α) (v : β k) (r : RBNode α β) : RBNode α β :=
match r with
| (node red b ky vy c) => node red l k v (node black b ky vy c)
| _ => match l with
| node black a kx vx b => balance₃ (node red a kx vx b) k v r
| node red a kx vx (node black b ky vy c) => node red (balance₃ (setRed a) kx vx b) ky vy (node black c k v r)
| _ => node red l k v r -- unreachable
-- TODO: use wellfounded recursion
partial def appendTrees : RBNode α β → RBNode α β → RBNode α β
| leaf, x => x
| x, leaf => x
| node red a kx vx b, node red c ky vy d =>
match appendTrees b c with
| node red b' kz vz c' => node red (node red a kx vx b') kz vz (node red c' ky vy d)
| bc => node red a kx vx (node red bc ky vy d)
| node black a kx vx b, node black c ky vy d =>
match appendTrees b c with
| node red b' kz vz c' => node red (node black a kx vx b') kz vz (node black c' ky vy d)
| bc => balLeft a kx vx (node black bc ky vy d)
| a, node red b kx vx c => node red (appendTrees a b) kx vx c
| node red a kx vx b, c => node red a kx vx (appendTrees b c)
section Erase
variable (lt : α → α → Bool)
@[specialize] def del (x : α) : RBNode α β → RBNode α β
| leaf => leaf
| node _ a y v b =>
if lt x y then
if a.isBlack then balLeft (del x a) y v b
else node red (del x a) y v b
else if lt y x then
if b.isBlack then balRight a y v (del x b)
else node red a y v (del x b)
else appendTrees a b
@[specialize] def erase (x : α) (t : RBNode α β) : RBNode α β :=
let t := del lt x t;
t.setBlack
end Erase
section Membership
variable (lt : α → α → Bool)
@[specialize] def findCore : RBNode α β → (k : α) → Option (Sigma (fun k => β k))
| leaf, x => none
| node _ a ky vy b, x =>
if lt x ky then findCore a x
else if lt ky x then findCore b x
else some ⟨ky, vy⟩
@[specialize] def find {β : Type v} : RBNode α (fun _ => β) → α → Option β
| leaf, x => none
| node _ a ky vy b, x =>
if lt x ky then find a x
else if lt ky x then find b x
else some vy
@[specialize] def lowerBound : RBNode α β → α → Option (Sigma β) → Option (Sigma β)
| leaf, x, lb => lb
| node _ a ky vy b, x, lb =>
if lt x ky then lowerBound a x lb
else if lt ky x then lowerBound b x (some ⟨ky, vy⟩)
else some ⟨ky, vy⟩
end Membership
inductive WellFormed (lt : α → α → Bool) : RBNode α β → Prop where
| leafWff : WellFormed lt leaf
| insertWff {n n' : RBNode α β} {k : α} {v : β k} : WellFormed lt n → n' = insert lt n k v → WellFormed lt n'
| eraseWff {n n' : RBNode α β} {k : α} : WellFormed lt n → n' = erase lt k n → WellFormed lt n'
end RBNode
open Std.RBNode
/- TODO(Leo): define dRBMap -/
def RBMap (α : Type u) (β : Type v) (lt : α → α → Bool) : Type (max u v) :=
{t : RBNode α (fun _ => β) // t.WellFormed lt }
@[inline] def mkRBMap (α : Type u) (β : Type v) (lt : α → α → Bool) : RBMap α β lt :=
⟨leaf, WellFormed.leafWff⟩
@[inline] def RBMap.empty {α : Type u} {β : Type v} {lt : α → α → Bool} : RBMap α β lt :=
mkRBMap ..
instance (α : Type u) (β : Type v) (lt : α → α → Bool) : EmptyCollection (RBMap α β lt) :=
⟨RBMap.empty⟩
namespace RBMap
variable {α : Type u} {β : Type v} {σ : Type w} {lt : α → α → Bool}
def depth (f : Nat → Nat → Nat) (t : RBMap α β lt) : Nat :=
t.val.depth f
@[inline] def fold (f : σ → α → β → σ) : (init : σ) → RBMap α β lt → σ
| b, ⟨t, _⟩ => t.fold f b
@[inline] def revFold (f : σ → α → β → σ) : (init : σ) → RBMap α β lt → σ
| b, ⟨t, _⟩ => t.revFold f b
@[inline] def foldM [Monad m] (f : σ → α → β → m σ) : (init : σ) → RBMap α β lt → m σ
| b, ⟨t, _⟩ => t.foldM f b
@[inline] def forM [Monad m] (f : α → β → m PUnit) (t : RBMap α β lt) : m PUnit :=
t.foldM (fun _ k v => f k v) ⟨⟩
@[inline] protected def forIn [Monad m] (t : RBMap α β lt) (init : σ) (f : (α × β) → σ → m (ForInStep σ)) : m σ :=
t.val.forIn init (fun a b acc => f (a, b) acc)
instance : ForIn m (RBMap α β lt) (α × β) where
forIn := RBMap.forIn
@[inline] def isEmpty : RBMap α β lt → Bool
| ⟨leaf, _⟩ => true
| _ => false
@[specialize] def toList : RBMap α β lt → List (α × β)
| ⟨t, _⟩ => t.revFold (fun ps k v => (k, v)::ps) []
@[inline] protected def min : RBMap α β lt → Option (α × β)
| ⟨t, _⟩ =>
match t.min with
| some ⟨k, v⟩ => some (k, v)
| none => none
@[inline] protected def max : RBMap α β lt → Option (α × β)
| ⟨t, _⟩ =>
match t.max with
| some ⟨k, v⟩ => some (k, v)
| none => none
instance [Repr α] [Repr β] : Repr (RBMap α β lt) where
reprPrec m prec := Repr.addAppParen ("Std.rbmapOf " ++ repr m.toList) prec
@[inline] def insert : RBMap α β lt → α → β → RBMap α β lt
| ⟨t, w⟩, k, v => ⟨t.insert lt k v, WellFormed.insertWff w rfl⟩
@[inline] def erase : RBMap α β lt → α → RBMap α β lt
| ⟨t, w⟩, k => ⟨t.erase lt k, WellFormed.eraseWff w rfl⟩
@[specialize] def ofList : List (α × β) → RBMap α β lt
| [] => mkRBMap ..
| ⟨k,v⟩::xs => (ofList xs).insert k v
@[inline] def findCore? : RBMap α β lt → α → Option (Sigma (fun (k : α) => β))
| ⟨t, _⟩, x => t.findCore lt x
@[inline] def find? : RBMap α β lt → α → Option β
| ⟨t, _⟩, x => t.find lt x
@[inline] def findD (t : RBMap α β lt) (k : α) (v₀ : β) : β :=
(t.find? k).getD v₀
/-- (lowerBound k) retrieves the kv pair of the largest key smaller than or equal to `k`,
if it exists. -/
@[inline] def lowerBound : RBMap α β lt → α → Option (Sigma (fun (k : α) => β))
| ⟨t, _⟩, x => t.lowerBound lt x none
@[inline] def contains (t : RBMap α β lt) (a : α) : Bool :=
(t.find? a).isSome
@[inline] def fromList (l : List (α × β)) (lt : α → α → Bool) : RBMap α β lt :=
l.foldl (fun r p => r.insert p.1 p.2) (mkRBMap α β lt)
@[inline] def all : RBMap α β lt → (α → β → Bool) → Bool
| ⟨t, _⟩, p => t.all p
@[inline] def any : RBMap α β lt → (α → β → Bool) → Bool
| ⟨t, _⟩, p => t.any p
def size (m : RBMap α β lt) : Nat :=
m.fold (fun sz _ _ => sz+1) 0
def maxDepth (t : RBMap α β lt) : Nat :=
t.val.depth Nat.max
@[inline] def min! [Inhabited α] [Inhabited β] (t : RBMap α β lt) : α × β :=
match t.min with
| some p => p
| none => panic! "map is empty"
@[inline] def max! [Inhabited α] [Inhabited β] (t : RBMap α β lt) : α × β :=
match t.max with
| some p => p
| none => panic! "map is empty"
@[inline] def find! [Inhabited β] (t : RBMap α β lt) (k : α) : β :=
match t.find? k with
| some b => b
| none => panic! "key is not in the map"
end RBMap
def rbmapOf {α : Type u} {β : Type v} (l : List (α × β)) (lt : α → α → Bool) : RBMap α β lt :=
RBMap.fromList l lt
end Std
|
b3175bfa8c1572bdd7e8e34a820e8e1e2d214219 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Util/Trace.lean | 7d0af333024aabf2d6dab420a2f5d476eb3a4456 | [
"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 | 5,957 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich, Leonardo de Moura
-/
import Lean.Message
import Lean.MonadEnv
universe u
namespace Lean
open Std (PersistentArray)
structure TraceElem where
ref : Syntax
msg : MessageData
deriving Inhabited
structure TraceState where
enabled : Bool := true
traces : PersistentArray TraceElem := {}
deriving Inhabited
namespace TraceState
private def toFormat (traces : PersistentArray TraceElem) (sep : Format) : IO Format :=
traces.size.foldM
(fun i r => do
let curr ← (traces.get! i).msg.format
return if i > 0 then r ++ sep ++ curr else r ++ curr)
Format.nil
end TraceState
class MonadTrace (m : Type → Type) where
modifyTraceState : (TraceState → TraceState) → m Unit
getTraceState : m TraceState
export MonadTrace (getTraceState modifyTraceState)
instance (m n) [MonadLift m n] [MonadTrace m] : MonadTrace n where
modifyTraceState := fun f => liftM (modifyTraceState f : m _)
getTraceState := liftM (getTraceState : m _)
variable {α : Type} {m : Type → Type} [Monad m] [MonadTrace m]
def printTraces {m} [Monad m] [MonadTrace m] [MonadLiftT IO m] : m Unit := do
let traceState ← getTraceState
traceState.traces.forM fun m => do
let d ← m.msg.format
IO.println d
def resetTraceState {m} [MonadTrace m] : m Unit :=
modifyTraceState (fun _ => {})
private def checkTraceOptionAux (opts : Options) : Name → Bool
| n@(.str p _) => opts.getBool n || (!opts.contains n && checkTraceOptionAux opts p)
| _ => false
def checkTraceOption (opts : Options) (cls : Name) : Bool :=
if opts.isEmpty then false
else checkTraceOptionAux opts (`trace ++ cls)
private def checkTraceOptionM [MonadOptions m] (cls : Name) : m Bool :=
return checkTraceOption (← getOptions) cls
@[inline] def isTracingEnabledFor [MonadOptions m] (cls : Name) : m Bool := do
let s ← getTraceState
if !s.enabled then pure false
else checkTraceOptionM cls
@[inline] def enableTracing (b : Bool) : m Bool := do
let s ← getTraceState
let oldEnabled := s.enabled
modifyTraceState fun s => { s with enabled := b }
pure oldEnabled
@[inline] def getTraces : m (PersistentArray TraceElem) := do
let s ← getTraceState
pure s.traces
@[inline] def modifyTraces (f : PersistentArray TraceElem → PersistentArray TraceElem) : m Unit :=
modifyTraceState fun s => { s with traces := f s.traces }
@[inline] def setTraceState (s : TraceState) : m Unit :=
modifyTraceState fun _ => s
private def addNode (oldTraces : PersistentArray TraceElem) (cls : Name) (ref : Syntax) : m Unit :=
modifyTraces fun traces =>
if traces.isEmpty then
oldTraces
else
let d := MessageData.tagged (cls ++ `_traceCtx) (MessageData.node (traces.toArray.map fun elem => elem.msg))
oldTraces.push { ref := ref, msg := d }
private def getResetTraces : m (PersistentArray TraceElem) := do
let oldTraces ← getTraces
modifyTraces fun _ => {}
pure oldTraces
section
variable [MonadRef m] [AddMessageContext m] [MonadOptions m]
private def addTraceOptions (msg : MessageData) : MessageData :=
match msg with
| MessageData.withContext ctx msg => MessageData.withContext { ctx with opts := ctx.opts.setBool `pp.analyze false } msg
| msg => msg
def addRawTrace (msg : MessageData) : m Unit := do
let ref ← getRef
let msg ← addMessageContext msg
let msg := addTraceOptions msg
modifyTraces fun traces => traces.push { ref, msg }
def addTrace (cls : Name) (msg : MessageData) : m Unit := do
let ref ← getRef
let msg ← addMessageContext msg
let msg := addTraceOptions msg
modifyTraces fun traces => traces.push { ref := ref, msg := MessageData.tagged (cls ++ `_traceMsg) m!"[{cls}] {msg}" }
@[inline] def trace (cls : Name) (msg : Unit → MessageData) : m Unit := do
if (← isTracingEnabledFor cls) then
addTrace cls (msg ())
@[inline] def traceM (cls : Name) (mkMsg : m MessageData) : m Unit := do
if (← isTracingEnabledFor cls) then
let msg ← mkMsg
addTrace cls msg
@[inline] def traceCtx [MonadFinally m] (cls : Name) (ctx : m α) : m α := do
let b ← isTracingEnabledFor cls
if !b then
let old ← enableTracing false
try ctx finally enableTracing old
else
let ref ← getRef
let oldCurrTraces ← getResetTraces
try ctx finally addNode oldCurrTraces cls ref
-- TODO: delete after fix old frontend
def MonadTracer.trace (cls : Name) (msg : Unit → MessageData) : m Unit :=
Lean.trace cls msg
end
def registerTraceClass (traceClassName : Name) : IO Unit :=
registerOption (`trace ++ traceClassName) { group := "trace", defValue := false, descr := "enable/disable tracing for the given module and submodules" }
macro "trace[" id:ident "]" s:(interpolatedStr(term) <|> term) : doElem => do
let msg ← if s.raw.getKind == interpolatedStrKind then `(m! $(⟨s⟩)) else `(($(⟨s⟩) : MessageData))
`(doElem| do
let cls := $(quote id.getId.eraseMacroScopes)
if (← Lean.isTracingEnabledFor cls) then
Lean.addTrace cls $msg)
private def withNestedTracesFinalizer [Monad m] [MonadTrace m] (ref : Syntax) (currTraces : PersistentArray TraceElem) : m Unit := do
modifyTraces fun traces =>
if traces.size == 0 then
currTraces
else if traces.size == 1 && traces[0]!.msg.isNest then
currTraces ++ traces -- No nest of nest
else
let d := traces.foldl (init := MessageData.nil) fun d elem =>
if d.isNil then elem.msg else m!"{d}\n{elem.msg}"
currTraces.push { ref := ref, msg := MessageData.nestD d }
@[inline] def withNestedTraces [Monad m] [MonadFinally m] [MonadTrace m] [MonadRef m] (x : m α) : m α := do
let currTraces ← getTraces
modifyTraces fun _ => {}
let ref ← getRef
try x finally withNestedTracesFinalizer ref currTraces
end Lean
|
1f17e978773efe160c0210ae00cdeab6445a514a | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/number_theory/l_series.lean | 47fd7d2cd9d66507a146e8a246262a3a3ecc7bd1 | [
"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 | 4,914 | lean | /-
Copyright (c) 2021 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import analysis.p_series
import number_theory.arithmetic_function
import topology.algebra.infinite_sum
/-!
# L-series
Given an arithmetic function, we define the corresponding L-series.
## Main Definitions
* `nat.arithmetic_function.l_series` is the `l_series` with a given arithmetic function as its
coefficients. This is not the analytic continuation, just the infinite series.
* `nat.arithmetic_function.l_series_summable` indicates that the `l_series`
converges at a given point.
## Main Results
* `nat.arithmetic_function.l_series_summable_of_bounded_of_one_lt_re`: the `l_series` of a bounded
arithmetic function converges when `1 < z.re`.
* `nat.arithmetic_function.zeta_l_series_summable_iff_one_lt_re`: the `l_series` of `ζ`
(whose analytic continuation is the Riemann ζ) converges iff `1 < z.re`.
-/
noncomputable theory
open_locale big_operators
namespace nat
namespace arithmetic_function
/-- The L-series of an `arithmetic_function`. -/
def l_series (f : arithmetic_function ℂ) (z : ℂ) : ℂ := ∑'n, (f n) / (n ^ z)
/-- `f.l_series_summable z` indicates that the L-series of `f` converges at `z`. -/
def l_series_summable (f : arithmetic_function ℂ) (z : ℂ) : Prop := summable (λ n, (f n) / (n ^ z))
lemma l_series_eq_zero_of_not_l_series_summable (f : arithmetic_function ℂ) (z : ℂ) :
¬ f.l_series_summable z → f.l_series z = 0 :=
tsum_eq_zero_of_not_summable
@[simp]
lemma l_series_summable_zero {z : ℂ} : l_series_summable 0 z :=
by simp [l_series_summable, summable_zero]
theorem l_series_summable_of_bounded_of_one_lt_real {f : arithmetic_function ℂ} {m : ℝ}
(h : ∀ (n : ℕ), complex.abs (f n) ≤ m) {z : ℝ} (hz : 1 < z) :
f.l_series_summable z :=
begin
by_cases h0 : m = 0,
{ subst h0,
have hf : f = 0 := arithmetic_function.ext (λ n, complex.abs.eq_zero.1
(le_antisymm (h n) (complex.abs.nonneg _))),
simp [hf] },
refine summable_of_norm_bounded (λ (n : ℕ), m / (n ^ z)) _ _,
{ simp_rw [div_eq_mul_inv],
exact (summable_mul_left_iff h0).1 (real.summable_nat_rpow_inv.2 hz) },
{ intro n,
have hm : 0 ≤ m := le_trans (complex.abs.nonneg _) (h 0),
cases n,
{ simp [hm, real.zero_rpow (ne_of_gt (lt_trans real.zero_lt_one hz))] },
simp only [map_div₀, complex.norm_eq_abs],
apply div_le_div hm (h _) (real.rpow_pos_of_pos (nat.cast_pos.2 n.succ_pos) _) (le_of_eq _),
rw [complex.abs_cpow_real, complex.abs_cast_nat] }
end
theorem l_series_summable_iff_of_re_eq_re {f : arithmetic_function ℂ} {w z : ℂ} (h : w.re = z.re) :
f.l_series_summable w ↔ f.l_series_summable z :=
begin
suffices h : ∀ n : ℕ, complex.abs (f n) / complex.abs (↑n ^ w) =
complex.abs (f n) / complex.abs (↑n ^ z),
{ simp [l_series_summable, ← summable_norm_iff, h, complex.norm_eq_abs] },
intro n,
cases n, { simp },
apply congr rfl,
have h0 : (n.succ : ℂ) ≠ 0,
{ rw [ne.def, nat.cast_eq_zero],
apply n.succ_ne_zero },
rw [complex.cpow_def, complex.cpow_def, if_neg h0, if_neg h0, complex.abs_exp_eq_iff_re_eq],
simp only [h, complex.mul_re, mul_eq_mul_left_iff, sub_right_inj],
right,
rw [complex.log_im, ← complex.of_real_nat_cast],
exact complex.arg_of_real_of_nonneg (le_of_lt (cast_pos.2 n.succ_pos)),
end
theorem l_series_summable_of_bounded_of_one_lt_re {f : arithmetic_function ℂ} {m : ℝ}
(h : ∀ (n : ℕ), complex.abs (f n) ≤ m) {z : ℂ} (hz : 1 < z.re) :
f.l_series_summable z :=
begin
rw ← l_series_summable_iff_of_re_eq_re (complex.of_real_re z.re),
apply l_series_summable_of_bounded_of_one_lt_real h,
exact hz,
end
open_locale arithmetic_function
theorem zeta_l_series_summable_iff_one_lt_re {z : ℂ} :
l_series_summable ζ z ↔ 1 < z.re :=
begin
rw [← l_series_summable_iff_of_re_eq_re (complex.of_real_re z.re), l_series_summable,
← summable_norm_iff, ← real.summable_one_div_nat_rpow, iff_iff_eq],
by_cases h0 : z.re = 0,
{ rw [h0, ← summable_nat_add_iff 1],
swap, { apply_instance },
apply congr rfl,
ext n,
simp [n.succ_ne_zero] },
{ apply congr rfl,
ext ⟨-|n⟩,
{ simp [h0] },
simp only [cast_zero, nat_coe_apply, zeta_apply, succ_ne_zero, if_false, cast_succ, one_div,
complex.norm_eq_abs, map_inv₀, complex.abs_cpow_real, inv_inj, zero_add],
rw [←cast_one, ←cast_add, complex.abs_of_nat, cast_add, cast_one] }
end
@[simp] theorem l_series_add {f g : arithmetic_function ℂ} {z : ℂ}
(hf : f.l_series_summable z) (hg : g.l_series_summable z) :
(f + g).l_series z = f.l_series z + g.l_series z :=
begin
simp only [l_series, add_apply],
rw ← tsum_add hf hg,
apply congr rfl (funext (λ n, _)),
apply _root_.add_div,
end
end arithmetic_function
end nat
|
12390e39432fc5c537213852adf24b82456b7ec8 | 3863d2564418bccb1859e057bf5a4ef240e75fd7 | /hott/algebra/e_closure.hlean | 3048e6938a67efad0242e98056e982762ba410a3 | [
"Apache-2.0"
] | permissive | JacobGross/lean | 118bbb067ff4d4af48a266face2c7eb9868fa91c | eb26087df940c54337cb807b4bc6d345d1fc1085 | refs/heads/master | 1,582,735,011,532 | 1,462,557,826,000 | 1,462,557,826,000 | 46,451,196 | 0 | 0 | null | 1,462,557,826,000 | 1,447,885,161,000 | C++ | UTF-8 | Lean | false | false | 8,677 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
The "equivalence closure" of a type-valued relation.
A more appropriate intuition is the type of words formed from the relation,
and inverses, concatenations and reflexivity
-/
import algebra.relation eq2 arity cubical.pathover2
open eq equiv
inductive e_closure {A : Type} (R : A → A → Type) : A → A → Type :=
| of_rel : Π{a a'} (r : R a a'), e_closure R a a'
| of_path : Π{a a'} (pp : a = a'), e_closure R a a'
| symm : Π{a a'} (r : e_closure R a a'), e_closure R a' a
| trans : Π{a a' a''} (r : e_closure R a a') (r' : e_closure R a' a''), e_closure R a a''
namespace e_closure
infix ` ⬝r `:75 := e_closure.trans
postfix `⁻¹ʳ`:(max+10) := e_closure.symm
notation `[`:max a `]`:0 := e_closure.of_rel a
notation `<`:max p `>`:0 := e_closure.of_path _ p
abbreviation rfl [constructor] {A : Type} {R : A → A → Type} {a : A} := of_path R (idpath a)
end e_closure
open e_closure
namespace relation
section
parameters {A : Type}
{R : A → A → Type}
local abbreviation T := e_closure R
variables ⦃a a' a'' : A⦄ {s : R a a'} {r : T a a} {B C : Type}
protected definition e_closure.elim [unfold 8] {f : A → B}
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a') : f a = f a' :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
exact e r,
exact ap f pp,
exact IH⁻¹,
exact IH₁ ⬝ IH₂
end
definition ap_e_closure_elim_h [unfold 12] {B C : Type} {f : A → B} {g : B → C}
(e : Π⦃a a' : A⦄, R a a' → f a = f a')
{e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')}
(p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a')
: ap g (e_closure.elim e t) = e_closure.elim e' t :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
apply p,
induction pp, reflexivity,
exact ap_inv g (e_closure.elim e r) ⬝ inverse2 IH,
exact ap_con g (e_closure.elim e r) (e_closure.elim e r') ⬝ (IH₁ ◾ IH₂)
end
definition ap_e_closure_elim [unfold 10] {B C : Type} {f : A → B} (g : B → C)
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a')
: ap g (e_closure.elim e t) = e_closure.elim (λa a' r, ap g (e r)) t :=
ap_e_closure_elim_h e (λa a' s, idp) t
definition ap_e_closure_elim_inv [unfold_full] {B C : Type} {f : A → B} (g : B → C)
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a')
: ap_e_closure_elim g e t⁻¹ʳ = ap_inv g (e_closure.elim e t) ⬝ (ap_e_closure_elim g e t)⁻² :=
by reflexivity
definition ap_e_closure_elim_con [unfold_full] {B C : Type} {f : A → B} (g : B → C)
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a') (t' : T a' a'')
: ap_e_closure_elim g e (t ⬝r t') = ap_con g (e_closure.elim e t) (e_closure.elim e t') ⬝
(ap_e_closure_elim g e t ◾ ap_e_closure_elim g e t') :=
by reflexivity
definition ap_e_closure_elim_h_eq {B C : Type} {f : A → B} {g : B → C}
(e : Π⦃a a' : A⦄, R a a' → f a = f a')
{e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')}
(p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a')
: ap_e_closure_elim_h e p t =
ap_e_closure_elim g e t ⬝ ap (λx, e_closure.elim x t) (eq_of_homotopy3 p) :=
begin
fapply homotopy3.rec_on p,
intro q, esimp at q, induction q,
esimp, rewrite eq_of_homotopy3_id
end
theorem ap_ap_e_closure_elim_h {B C D : Type} {f : A → B}
{g : B → C} (h : C → D)
(e : Π⦃a a' : A⦄, R a a' → f a = f a')
{e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')}
(p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a')
: square (ap (ap h) (ap_e_closure_elim_h e p t))
(ap_e_closure_elim_h e (λa a' s, ap_compose h g (e s)) t)
(ap_compose h g (e_closure.elim e t))⁻¹
(ap_e_closure_elim_h e' (λa a' s, (ap (ap h) (p s))⁻¹) t) :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
{ esimp,
apply square_of_eq, exact !con.right_inv ⬝ !con.left_inv⁻¹},
{ induction pp, apply ids},
{ rewrite [▸*,ap_con (ap h)],
refine (transpose !ap_compose_inv)⁻¹ᵛ ⬝h _,
rewrite [con_inv,inv_inv,-inv2_inv],
exact !ap_inv2 ⬝v square_inv2 IH},
{ rewrite [▸*,ap_con (ap h)],
refine (transpose !ap_compose_con)⁻¹ᵛ ⬝h _,
rewrite [con_inv,inv_inv,con2_inv],
refine !ap_con2 ⬝v square_con2 IH₁ IH₂},
end
theorem ap_ap_e_closure_elim {B C D : Type} {f : A → B}
(g : B → C) (h : C → D)
(e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a')
: square (ap (ap h) (ap_e_closure_elim g e t))
(ap_e_closure_elim_h e (λa a' s, ap_compose h g (e s)) t)
(ap_compose h g (e_closure.elim e t))⁻¹
(ap_e_closure_elim h (λa a' r, ap g (e r)) t) :=
!ap_ap_e_closure_elim_h
definition is_equivalence_e_closure : is_equivalence T :=
begin
constructor,
intro a, exact rfl,
intro a a' t, exact t⁻¹ʳ,
intro a a' a'' t t', exact t ⬝r t',
end
/-
definition e_closure.transport_left {f : A → B} (e : Π⦃a a' : A⦄, R a a' → f a = f a')
(t : e_closure R a a') (p : a = a'')
: e_closure.elim e (p ▸ t) = (ap f p)⁻¹ ⬝ e_closure.elim e t :=
by induction p; exact !idp_con⁻¹
definition e_closure.transport_right {f : A → B} (e : Π⦃a a' : A⦄, R a a' → f a = f a')
(t : e_closure R a a') (p : a' = a'')
: e_closure.elim e (p ▸ t) = e_closure.elim e t ⬝ (ap f p) :=
by induction p; reflexivity
definition e_closure.transport_lr {f : A → B} (e : Π⦃a a' : A⦄, R a a' → f a = f a')
(t : e_closure R a a) (p : a = a')
: e_closure.elim e (p ▸ t) = (ap f p)⁻¹ ⬝ e_closure.elim e t ⬝ (ap f p) :=
by induction p; esimp; exact !idp_con⁻¹
-/
/- dependent elimination -/
variables {P : B → Type} {Q : C → Type} {f : A → B} {g : B → C} {f' : Π(a : A), P (f a)}
protected definition e_closure.elimo [unfold 11] (p : Π⦃a a' : A⦄, R a a' → f a = f a')
(po : Π⦃a a' : A⦄ (s : R a a'), f' a =[p s] f' a') (t : T a a')
: f' a =[e_closure.elim p t] f' a' :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
exact po r,
induction pp, constructor,
exact IH⁻¹ᵒ,
exact IH₁ ⬝o IH₂
end
definition elimo_inv [unfold_full] (p : Π⦃a a' : A⦄, R a a' → f a = f a')
(po : Π⦃a a' : A⦄ (s : R a a'), f' a =[p s] f' a') (t : T a a')
: e_closure.elimo p po t⁻¹ʳ = (e_closure.elimo p po t)⁻¹ᵒ :=
by reflexivity
definition elimo_con [unfold_full] (p : Π⦃a a' : A⦄, R a a' → f a = f a')
(po : Π⦃a a' : A⦄ (s : R a a'), f' a =[p s] f' a') (t : T a a') (t' : T a' a'')
: e_closure.elimo p po (t ⬝r t') = e_closure.elimo p po t ⬝o e_closure.elimo p po t' :=
by reflexivity
definition ap_e_closure_elimo_h [unfold 12] {g' : Πb, Q (g b)}
(p : Π⦃a a' : A⦄, R a a' → f a = f a')
(po : Π⦃a a' : A⦄ (s : R a a'), g' (f a) =[p s] g' (f a'))
(q : Π⦃a a' : A⦄ (s : R a a'), apd g' (p s) = po s)
(t : T a a') : apd g' (e_closure.elim p t) = e_closure.elimo p po t :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
apply q,
induction pp, reflexivity,
esimp [e_closure.elim],
exact apd_inv g' (e_closure.elim p r) ⬝ IH⁻²ᵒ,
exact apd_con g' (e_closure.elim p r) (e_closure.elim p r') ⬝ (IH₁ ◾o IH₂)
end
theorem e_closure_elimo_ap {g' : Π(a : A), Q (g (f a))}
(p : Π⦃a a' : A⦄, R a a' → f a = f a')
(po : Π⦃a a' : A⦄ (s : R a a'), g' a =[ap g (p s)] g' a')
(t : T a a') : e_closure.elimo p (λa a' s, pathover_of_pathover_ap Q g (po s)) t =
pathover_of_pathover_ap Q g (change_path (ap_e_closure_elim g p t)⁻¹
(e_closure.elimo (λa a' r, ap g (p r)) po t)) :=
begin
induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂,
{ reflexivity},
{ induction pp; reflexivity},
{ rewrite [+elimo_inv, ap_e_closure_elim_inv, IH, con_inv, change_path_con, ▸*, -inv2_inv,
change_path_invo, pathover_of_pathover_ap_invo]},
{ rewrite [+elimo_con, ap_e_closure_elim_con, IH₁, IH₂, con_inv, change_path_con, ▸*, con2_inv,
change_path_cono, pathover_of_pathover_ap_cono]},
end
end
end relation
|
e919ab2c741a76983b167647e501f1bb22ddde05 | 5883d9218e6f144e20eee6ca1dab8529fa1a97c0 | /src/data/category.lean | f50ec6a27ca36c4e87dde1037ad3f203652af5e0 | [] | no_license | spl/alpha-conversion-is-easy | 0d035bc570e52a6345d4890e4d0c9e3f9b8126c1 | ed937fe85d8495daffd9412a5524c77b9fcda094 | refs/heads/master | 1,607,649,280,020 | 1,517,380,240,000 | 1,517,380,240,000 | 52,174,747 | 4 | 0 | null | 1,456,052,226,000 | 1,456,001,163,000 | Lean | UTF-8 | Lean | false | false | 1,458 | lean | /-
This file contains definitions and theorems for `category`.
Some of this was adapted from work by Simon Hudon.
Source: https://github.com/unitb/lean-lib/blob/master/src/util/category.lean
-/
universes u v
variables {O : Sort u} -- Type of objects in a category
/-
A class for homomorphisms with composition.
-/
class has_comp (H : O → O → Type v) :=
(comp : ∀ {a b c : O}, H b c → H a b → H a c)
instance has_comp.arrow : has_comp (→) :=
{ comp := @function.comp
}
-- Convenient composition notation.
infixr ` ∘ ` := has_comp.comp _
/-
A class for categories uniquely identified by the homomorphism `H` (i.e. the
arrow). The object type `O` is implicit.
We use a setoid rather than `=` for equalities that do not exactly fit the `eq`
type.
-/
class category (H : O → O → Type v) [∀ a b, setoid (H a b)] extends has_comp H :=
(id : ∀ {a : O}, H a a) -- Identity
(left_id : ∀ {a b : O} (f : H a b), id ∘ f ≈ f) -- Left unit of identity
(right_id : ∀ {a b : O} (f : H a b), f ∘ id ≈ f) -- Right unit of identity
(assoc : ∀ {a b c d : O} (h : H c d) (g : H b c) (f : H a b), h ∘ (g ∘ f) ≈ (h ∘ g) ∘ f) -- Associativity
instance category.arrow : category (→) :=
{ comp := @function.comp
, id := @id
, left_id := λ a b, function.equiv.refl
, right_id := λ a b, function.equiv.refl
, assoc := λ a b c d h g f, function.equiv.refl (h ∘ (g ∘ f))
}
|
6b3cfe5dcea2258858a2ba8caf877a5e092daa2c | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/nat/choose/sum.lean | aa8d25b8f635226ab9276ecd3d72d53c2fcc05e5 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 6,910 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Patrick Stevens
-/
import data.nat.choose.basic
import tactic.linarith
import algebra.big_operators.ring
import algebra.big_operators.intervals
import algebra.big_operators.order
import algebra.big_operators.nat_antidiagonal
/-!
# Sums of binomial coefficients
This file includes variants of the binomial theorem and other results on sums of binomial
coefficients. Theorems whose proofs depend on such sums may also go in this file for import
reasons.
-/
open nat
open finset
open_locale big_operators
variables {R : Type*}
namespace commute
variables [semiring R] {x y : R} (h : commute x y) (n : ℕ)
include h
/-- A version of the **binomial theorem** for noncommutative semirings. -/
theorem add_pow :
(x + y) ^ n = ∑ m in range (n + 1), x ^ m * y ^ (n - m) * choose n m :=
begin
let t : ℕ → ℕ → R := λ n m, x ^ m * (y ^ (n - m)) * (choose n m),
change (x + y) ^ n = ∑ m in range (n + 1), t n m,
have h_first : ∀ n, t n 0 = y ^ n :=
λ n, by { dsimp [t], rw [choose_zero_right, pow_zero, nat.cast_one, mul_one, one_mul] },
have h_last : ∀ n, t n n.succ = 0 :=
λ n, by { dsimp [t], rw [choose_succ_self, nat.cast_zero, mul_zero] },
have h_middle : ∀ (n i : ℕ), (i ∈ range n.succ) →
((t n.succ) ∘ nat.succ) i = x * (t n i) + y * (t n i.succ) :=
begin
intros n i h_mem,
have h_le : i ≤ n := nat.le_of_lt_succ (mem_range.mp h_mem),
dsimp [t],
rw [choose_succ_succ, nat.cast_add, mul_add],
congr' 1,
{ rw [pow_succ x, succ_sub_succ, mul_assoc, mul_assoc, mul_assoc] },
{ rw [← mul_assoc y, ← mul_assoc y, (h.symm.pow_right i.succ).eq],
by_cases h_eq : i = n,
{ rw [h_eq, choose_succ_self, nat.cast_zero, mul_zero, mul_zero] },
{ rw [succ_sub (lt_of_le_of_ne h_le h_eq)],
rw [pow_succ y, mul_assoc, mul_assoc, mul_assoc, mul_assoc] } }
end,
induction n with n ih,
{ rw [pow_zero, sum_range_succ, range_zero, sum_empty, zero_add],
dsimp [t], rw [pow_zero, pow_zero, choose_self, nat.cast_one, mul_one, mul_one] },
{ rw [sum_range_succ', h_first],
rw [sum_congr rfl (h_middle n), sum_add_distrib, add_assoc],
rw [pow_succ (x + y), ih, add_mul, mul_sum, mul_sum],
congr' 1,
rw [sum_range_succ', sum_range_succ, h_first, h_last,
mul_zero, add_zero, pow_succ] }
end
/-- A version of `commute.add_pow` that avoids ℕ-subtraction by summing over the antidiagonal and
also with the binomial coefficient applied via scalar action of ℕ. -/
lemma add_pow' :
(x + y) ^ n = ∑ m in nat.antidiagonal n, choose n m.fst • (x ^ m.fst * y ^ m.snd) :=
by simp_rw [finset.nat.sum_antidiagonal_eq_sum_range_succ (λ m p, choose n m • (x^m * y^p)),
_root_.nsmul_eq_mul, cast_comm, h.add_pow]
end commute
/-- The **binomial theorem** -/
theorem add_pow [comm_semiring R] (x y : R) (n : ℕ) :
(x + y) ^ n = ∑ m in range (n + 1), x ^ m * y ^ (n - m) * choose n m :=
(commute.all x y).add_pow n
namespace nat
/-- The sum of entries in a row of Pascal's triangle -/
theorem sum_range_choose (n : ℕ) :
∑ m in range (n + 1), choose n m = 2 ^ n :=
by simpa using (add_pow 1 1 n).symm
lemma sum_range_choose_halfway (m : nat) :
∑ i in range (m + 1), choose (2 * m + 1) i = 4 ^ m :=
have ∑ i in range (m + 1), choose (2 * m + 1) (2 * m + 1 - i) =
∑ i in range (m + 1), choose (2 * m + 1) i,
from sum_congr rfl $ λ i hi, choose_symm $ by linarith [mem_range.1 hi],
(nat.mul_right_inj zero_lt_two).1 $
calc 2 * (∑ i in range (m + 1), choose (2 * m + 1) i) =
(∑ i in range (m + 1), choose (2 * m + 1) i) +
∑ i in range (m + 1), choose (2 * m + 1) (2 * m + 1 - i) :
by rw [two_mul, this]
... = (∑ i in range (m + 1), choose (2 * m + 1) i) +
∑ i in Ico (m + 1) (2 * m + 2), choose (2 * m + 1) i : begin
rw [range_eq_Ico, sum_Ico_reflect],
{ congr,
have A : m + 1 ≤ 2 * m + 1, by linarith,
rw [add_comm, add_tsub_assoc_of_le A, ← add_comm],
congr,
rw tsub_eq_iff_eq_add_of_le A,
ring, },
{ linarith }
end
... = ∑ i in range (2 * m + 2), choose (2 * m + 1) i : sum_range_add_sum_Ico _ (by linarith)
... = 2^(2 * m + 1) : sum_range_choose (2 * m + 1)
... = 2 * 4^m : by { rw [pow_succ, pow_mul], refl }
lemma choose_middle_le_pow (n : ℕ) : choose (2 * n + 1) n ≤ 4 ^ n :=
begin
have t : choose (2 * n + 1) n ≤ ∑ i in range (n + 1), choose (2 * n + 1) i :=
single_le_sum (λ x _, by linarith) (self_mem_range_succ n),
simpa [sum_range_choose_halfway n] using t
end
lemma four_pow_le_two_mul_add_one_mul_central_binom (n : ℕ) :
4 ^ n ≤ (2 * n + 1) * choose (2 * n) n :=
calc 4 ^ n = (1 + 1) ^ (2 * n) : by norm_num [pow_mul]
... = ∑ m in range (2 * n + 1), choose (2 * n) m : by simp [add_pow]
... ≤ ∑ m in range (2 * n + 1), choose (2 * n) (2 * n / 2) :
sum_le_sum (λ i hi, choose_le_middle i (2 * n))
... = (2 * n + 1) * choose (2 * n) n : by simp
end nat
theorem int.alternating_sum_range_choose {n : ℕ} :
∑ m in range (n + 1), ((-1) ^ m * ↑(choose n m) : ℤ) = if n = 0 then 1 else 0 :=
begin
cases n, { simp },
have h := add_pow (-1 : ℤ) 1 n.succ,
simp only [one_pow, mul_one, add_left_neg, int.nat_cast_eq_coe_nat] at h,
rw [← h, zero_pow (nat.succ_pos n), if_neg (nat.succ_ne_zero n)],
end
theorem int.alternating_sum_range_choose_of_ne {n : ℕ} (h0 : n ≠ 0) :
∑ m in range (n + 1), ((-1) ^ m * ↑(choose n m) : ℤ) = 0 :=
by rw [int.alternating_sum_range_choose, if_neg h0]
namespace finset
theorem sum_powerset_apply_card {α β : Type*} [add_comm_monoid α] (f : ℕ → α) {x : finset β} :
∑ m in x.powerset, f m.card = ∑ m in range (x.card + 1), (x.card.choose m) • f m :=
begin
transitivity ∑ m in range (x.card + 1), ∑ j in x.powerset.filter (λ z, z.card = m), f j.card,
{ refine (sum_fiberwise_of_maps_to _ _).symm,
intros y hy,
rw [mem_range, nat.lt_succ_iff],
rw mem_powerset at hy,
exact card_le_of_subset hy },
{ refine sum_congr rfl (λ y hy, _),
rw [← card_powerset_len, ← sum_const],
refine sum_congr powerset_len_eq_filter.symm (λ z hz, _),
rw (mem_powerset_len.1 hz).2 }
end
theorem sum_powerset_neg_one_pow_card {α : Type*} [decidable_eq α] {x : finset α} :
∑ m in x.powerset, (-1 : ℤ) ^ m.card = if x = ∅ then 1 else 0 :=
begin
rw sum_powerset_apply_card,
simp only [nsmul_eq_mul', ← card_eq_zero],
convert int.alternating_sum_range_choose,
ext,
simp,
end
theorem sum_powerset_neg_one_pow_card_of_nonempty {α : Type*} {x : finset α}
(h0 : x.nonempty) :
∑ m in x.powerset, (-1 : ℤ) ^ m.card = 0 :=
begin
classical,
rw [sum_powerset_neg_one_pow_card, if_neg],
rw [← ne.def, ← nonempty_iff_ne_empty],
apply h0,
end
end finset
|
a4697e2bcb50f5b4bac04ada8669a0dced067d0c | 99b36386640f67a61e85dddccbc0f82edec9bf9c | /src/piecewise.lean | 793a599ca50193f46e226535ea77962d4cd67abe | [] | no_license | aymonwuolanne/lean-theorem-proving | 1ba46fb89f446b78b7f8f8cb084aad68fadce9a3 | 701a7873f9f66f2c24962b02450ec90b20935702 | refs/heads/master | 1,586,068,982,414 | 1,575,091,205,000 | 1,575,091,205,000 | 156,647,753 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,007 | lean | import topology.continuity
import topology.algebra.topological_structures
import data.real.basic
noncomputable theory
universes u v
open set
variables {α : Type u} {β : Type v} [topological_space α] [topological_space β]
variables {s: set α} [decidable_pred s]
variables (f : subtype (closure s) → β) (g : subtype (closure (-s)) → β)
@[reducible] def pw : α → β := λ x, if h : x ∈ s then f ⟨ x, subset_closure h ⟩ else g ⟨ x, subset_closure h ⟩
lemma frontier_subset_closure : frontier s ⊆ closure s := λ x hx, hx.left
lemma frontier_subset_closure_compl : frontier s ⊆ closure (-s) :=
have h : closure s ∩ closure (-s) = frontier s,
from symm frontier_eq_closure_inter_closure,
h ▸ inter_subset_right (closure s) (closure (-s))
local notation `val` := @subtype.val _
theorem continuous_pw (hs : ∀ x (h : x ∈ frontier s),
f ⟨x, frontier_subset_closure h⟩ = g ⟨x, frontier_subset_closure_compl h⟩)
(hf : continuous f) (hg : continuous g) : (continuous (pw f g)) :=
continuous_iff_is_closed.mpr $ assume t ht,
have h₁ : ∃ t₁, is_closed t₁ ∧ f ⁻¹' t = val (closure s) ⁻¹' t₁,
from is_closed_induced_iff.mp (continuous_iff_is_closed.mp hf t ht),
have h₂ : ∃ t₂, is_closed t₂ ∧ g ⁻¹' t = val (closure (-s)) ⁻¹' t₂,
from is_closed_induced_iff.mp (continuous_iff_is_closed.mp hg t ht),
exists.elim h₁ $
assume t₁ ht₁,
exists.elim h₂ $
assume t₂ ht₂,
begin
have : pw f g ⁻¹' t = (closure s ∩ t₁) ∪ (closure (-s) ∩ t₂),
apply set.ext,
intro x,
have hxt₁ : Π hxc : x ∈ closure s, (x ∈ t₁ ↔ f ⟨x, hxc⟩ ∈ t),
intro hxc,
let x' : subtype (closure s) := ⟨x, hxc⟩,
have h₁ : x ∈ t₁ ↔ x' ∈ val (closure s) ⁻¹' t₁,
refl,
have h₂ : x' ∈ val (closure s) ⁻¹' t₁ ↔ x' ∈ f ⁻¹' t,
rw [ht₁.right],
rw [h₁, h₂],
refl,
have hxt₂ : Π hxi : x ∈ closure (-s), (x ∈ t₂ ↔ g ⟨x, hxi⟩ ∈ t),
intro hxi,
let x' : subtype (closure (-s)) := ⟨x, hxi⟩,
have h₁ : x ∈ t₂ ↔ x' ∈ val (closure (-s)) ⁻¹' t₂,
refl,
have h₂ : x' ∈ val (closure (-s)) ⁻¹' t₂ ↔ x' ∈ g ⁻¹' t,
rw [ht₂.right],
rw [h₁, h₂],
refl,
have hxf : x ∈ frontier s → (x ∈ pw f g ⁻¹' t ↔ x ∈ (closure s ∩ t₁) ∪ (closure (-s) ∩ t₂)),
intro hx,
have hxc : x ∈ closure s, from frontier_subset_closure hx,
have hxi : x ∈ closure (-s), from frontier_subset_closure_compl hx,
by_cases x ∈ s; simp [pw, h, hxc, hxi, hs x hx, hxt₁ hxc, hxt₂ hxi, -closure_compl],
have hxnf : x ∉ frontier s → (x ∈ pw f g ⁻¹' t ↔ x ∈ (closure s ∩ t₁) ∪ (closure (-s) ∩ t₂)),
intro hf,
by_cases x ∈ s,
have hc : x ∈ closure s, from subset_closure h,
have hnc : x ∉ closure (-s),
rw [closure_compl],
simpa [frontier, hc] using hf,
simp [pw, h, hc, hnc, hxt₁ hc, -closure_compl],
have hc : x ∈ closure (-s), from subset_closure h,
have hnc : x ∉ closure s,
simp [closure_compl] at hc,
simpa [frontier, hc] using hf,
simp [pw, h, hc, hnc, hxt₂ hc, -closure_compl],
exact classical.by_cases hxf hxnf,
exact by rw [this]; exact is_closed_union
(is_closed_inter is_closed_closure ht₁.left)
(is_closed_inter is_closed_closure ht₂.left)
end
#check continuous_if
-- continuous_if is a corollorary of continuous_pw
theorem 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_pw (f ∘ subtype.val) (g ∘ subtype.val) hp
(continuous.comp continuous_induced_dom hf)
(continuous.comp continuous_induced_dom hg) |
0f1636bc4c1818efa82badbdb2a1960d9bd92662 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/playground/partial_eq_lemma.lean | eb74c18d1c49c9ad942dfa12bde3d72cdd22f905 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 4,124 | lean | universes u
inductive Partial (α : Type u)
| val (a : α) : Partial
| bot {} : Partial
def terminates {α : Type u} (p : Partial α) : Prop := p ≠ Partial.bot
def fooAux (s : String) (c : Char) : Nat → String.Pos → Partial String.Pos
| 0 i := Partial.bot
| (Nat.succ k) i :=
if s.atEnd i then Partial.val i
else if s.get i == c then Partial.val i
else fooAux k (s.next i)
theorem fooAuxEqSucc (s : String) (c : Char) : ∀ (k : Nat) (i : String.Pos), terminates (fooAux s c k i) → fooAux s c k.succ i = fooAux s c k i
| 0 i ht := absurd rfl ht
| (Nat.succ k) i ht :=
show (fooAux s c k.succ.succ i = fooAux s c k.succ i), from
Decidable.byCases
(λ h : s.atEnd i,
have h₁ : fooAux s c (k.succ.succ) i = Partial.val i, from ifPos h,
have h₂ : fooAux s c k.succ i = Partial.val i, from ifPos h,
Eq.trans h₁ h₂.symm)
(λ h : ¬ s.atEnd i,
Decidable.byCases
(λ h' : s.get i == c,
have h₁ : fooAux s c (k.succ.succ) i = Partial.val i, from Eq.trans (ifNeg h) (ifPos h'),
have h₂ : fooAux s c k.succ i = Partial.val i, from Eq.trans (ifNeg h) (ifPos h'),
Eq.trans h₁ h₂.symm)
(λ h' : ¬ s.get i == c,
have h₁ : fooAux s c (k.succ.succ) i = fooAux s c k.succ (s.next i), from Eq.trans (ifNeg h) (ifNeg h'),
have h₂ : fooAux s c k.succ i = fooAux s c k (s.next i), from Eq.trans (ifNeg h) (ifNeg h'),
have h₃ : fooAux s c k (s.next i) ≠ Partial.bot, from h₂ ▸ ht,
have ih : fooAux s c k.succ (s.next i) = fooAux s c k (s.next i), from fooAuxEqSucc k _ h₃,
Eq.trans h₁ (Eq.trans ih h₂.symm)))
theorem fooAuxTermSucc (s : String) (c : Char) (k : Nat) (i : String.Pos)
(h₁ : terminates (fooAux s c k.succ i)) (h₂ : ¬ (s.atEnd i)) (h₃ : ¬ (s.get i == c)) : terminates (fooAux s c k (s.next i)) :=
have (fooAux s c k.succ i) = fooAux s c k (s.next i), from Eq.trans (ifNeg h₂) (ifNeg h₃),
this ▸ h₁
constant bigNat : Nat := 1000000
def foo (s : String) (c : Char) (i : String.Pos) : Partial String.Pos :=
fooAux s c bigNat i
theorem fooEq (s : String) (c : Char) (i : String.Pos) :
terminates (foo s c i) →
foo s c i = if s.atEnd i then Partial.val i
else if s.get i == c then Partial.val i
else foo s c (s.next i) :=
show terminates (fooAux s c bigNat i) → fooAux s c bigNat i = (if s.atEnd i then Partial.val i
else if s.get i == c then Partial.val i
else fooAux s c bigNat (s.next i)), from
Nat.casesOn bigNat
(λ h : fooAux s c 0 i ≠ Partial.bot, absurd rfl h)
(λ N h,
have h₁ : fooAux s c N.succ i = (if s.atEnd i then Partial.val i
else if s.get i == c then Partial.val i
else fooAux s c N (s.next i)), from rfl,
Decidable.byCases
(λ c₁ : s.atEnd i,
have aux₁ : fooAux s c N.succ i = Partial.val i, from ifPos c₁,
have aux₂ : ite (String.atEnd s i) (Partial.val i)
(ite (String.get s i == c) (Partial.val i) (fooAux s c (Nat.succ N) (String.next s i))) = Partial.val i, from ifPos c₁,
Eq.trans aux₁ aux₂.symm)
(λ c₁ : ¬ s.atEnd i,
Decidable.byCases
(λ c₂ : s.get i == c,
have aux₁ : fooAux s c N.succ i = Partial.val i, from Eq.trans (ifNeg c₁) (ifPos c₂),
have aux₂ : ite (String.atEnd s i) (Partial.val i)
(ite (String.get s i == c) (Partial.val i) (fooAux s c (Nat.succ N) (String.next s i))) = Partial.val i, from Eq.trans (ifNeg c₁) (ifPos c₂),
Eq.trans aux₁ aux₂.symm)
(λ c₂ : ¬ s.get i == c,
have h₂ : terminates (fooAux s c N (s.next i)), from fooAuxTermSucc _ _ _ _ h c₁ c₂,
have h₃ : fooAux s c N (s.next i) = fooAux s c N.succ (s.next i), from (fooAuxEqSucc _ _ _ _ h₂).symm,
h₃ ▸ h₁)))
|
7837d82ef25f67bc11d68238d7528b3fa8b61436 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/algebra/order/archimedean.lean | d408f5dc9ae6bd1c1c594b98d8d2e410039c9a20 | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,982 | 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 algebra.field_power
import data.rat
import data.int.least_greatest
/-!
# Archimedean groups and fields.
This file defines the archimedean property for ordered groups and proves several results connected
to this notion. Being archimedean means that for all elements `x` and `y>0` there exists a natural
number `n` such that `x ≤ n • y`.
## Main definitions
* `archimedean` is a typeclass for an ordered additive commutative monoid to have the archimedean
property.
* `archimedean.floor_ring` defines a floor function on an archimedean linearly ordered ring making
it into a `floor_ring`.
* `round` defines a function rounding to the nearest integer for a linearly ordered field which is
also a floor ring.
## Main statements
* `ℕ`, `ℤ`, and `ℚ` are archimedean.
-/
open int
variables {α : Type*}
/-- An ordered additive commutative monoid is called `archimedean` if for any two elements `x`, `y`
such that `0 < y` there exists a natural number `n` such that `x ≤ n • y`. -/
class archimedean (α) [ordered_add_comm_monoid α] : Prop :=
(arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y)
instance order_dual.archimedean [ordered_add_comm_group α] [archimedean α] :
archimedean (order_dual α) :=
⟨λ x y hy, let ⟨n, hn⟩ := archimedean.arch (-x : α) (neg_pos.2 hy) in
⟨n, by rwa [neg_nsmul, neg_le_neg_iff] at hn⟩⟩
namespace linear_ordered_add_comm_group
variables [linear_ordered_add_comm_group α] [archimedean α]
/-- An archimedean decidable linearly ordered `add_comm_group` has a version of the floor: for
`a > 0`, any `g` in the group lies between some two consecutive multiples of `a`. -/
lemma exists_int_smul_near_of_pos {a : α} (ha : 0 < a) (g : α) :
∃ (k : ℤ), k • a ≤ g ∧ g < (k + 1) • a :=
begin
let s : set ℤ := {n : ℤ | n • a ≤ g},
obtain ⟨k, hk : -g ≤ k • a⟩ := archimedean.arch (-g) ha,
have h_ne : s.nonempty := ⟨-k, by simpa using neg_le_neg hk⟩,
obtain ⟨k, hk⟩ := archimedean.arch g ha,
have h_bdd : ∀ n ∈ s, n ≤ (k : ℤ),
{ assume n hn,
apply (gsmul_le_gsmul_iff ha).mp,
rw ← gsmul_coe_nat at hk,
exact le_trans hn hk },
obtain ⟨m, hm, hm'⟩ := int.exists_greatest_of_bdd ⟨k, h_bdd⟩ h_ne,
refine ⟨m, hm, _⟩,
by_contra H,
linarith [hm' _ $ not_lt.mp H]
end
lemma exists_int_smul_near_of_pos' {a : α} (ha : 0 < a) (g : α) :
∃ (k : ℤ), 0 ≤ g - k • a ∧ g - k • a < a :=
begin
obtain ⟨k, h1, h2⟩ := exists_int_smul_near_of_pos ha g,
rw add_gsmul at h2,
refine ⟨k, sub_nonneg.mpr h1, _⟩,
simpa [sub_lt_iff_lt_add'] using h2
end
end linear_ordered_add_comm_group
theorem exists_nat_gt [ordered_semiring α] [nontrivial α] [archimedean α]
(x : α) : ∃ n : ℕ, x < n :=
let ⟨n, h⟩ := archimedean.arch x zero_lt_one in
⟨n+1, lt_of_le_of_lt (by rwa ← nsmul_one)
(nat.cast_lt.2 (nat.lt_succ_self _))⟩
theorem exists_nat_ge [ordered_semiring α] [archimedean α] (x : α) :
∃ n : ℕ, x ≤ n :=
begin
nontriviality α,
exact (exists_nat_gt x).imp (λ n, le_of_lt)
end
lemma add_one_pow_unbounded_of_pos [ordered_semiring α] [nontrivial α] [archimedean α]
(x : α) {y : α} (hy : 0 < y) :
∃ n : ℕ, x < (y + 1) ^ n :=
have 0 ≤ 1 + y, from add_nonneg zero_le_one hy.le,
let ⟨n, h⟩ := archimedean.arch x hy in
⟨n, calc x ≤ n • y : h
... = n * y : nsmul_eq_mul _ _
... < 1 + n * y : lt_one_add _
... ≤ (1 + y) ^ n : one_add_mul_le_pow' (mul_nonneg hy.le hy.le) (mul_nonneg this this)
(add_nonneg zero_le_two hy.le) _
... = (y + 1) ^ n : by rw [add_comm]⟩
section linear_ordered_ring
variables [linear_ordered_ring α] [archimedean α]
lemma pow_unbounded_of_one_lt (x : α) {y : α} (hy1 : 1 < y) :
∃ n : ℕ, x < y ^ n :=
sub_add_cancel y 1 ▸ add_one_pow_unbounded_of_pos _ (sub_pos.2 hy1)
/-- Every x greater than or equal to 1 is between two successive
natural-number powers of every y greater than one. -/
lemma exists_nat_pow_near {x : α} {y : α} (hx : 1 ≤ x) (hy : 1 < y) :
∃ n : ℕ, y ^ n ≤ x ∧ x < y ^ (n + 1) :=
have h : ∃ n : ℕ, x < y ^ n, from pow_unbounded_of_one_lt _ hy,
by classical; exact let n := nat.find h in
have hn : x < y ^ n, from nat.find_spec h,
have hnp : 0 < n, from pos_iff_ne_zero.2 (λ hn0,
by rw [hn0, pow_zero] at hn; exact (not_le_of_gt hn hx)),
have hnsp : nat.pred n + 1 = n, from nat.succ_pred_eq_of_pos hnp,
have hltn : nat.pred n < n, from nat.pred_lt (ne_of_gt hnp),
⟨nat.pred n, le_of_not_lt (nat.find_min h hltn), by rwa hnsp⟩
theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n :=
let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa ← coe_coe⟩
theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x :=
let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩
theorem exists_floor (x : α) :
∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x :=
begin
haveI := classical.prop_decidable,
have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub :=
int.exists_greatest_of_bdd
(let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h',
int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩)
(let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩),
refine this.imp (λ fl h z, _),
cases h with h₁ h₂,
exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩,
end
end linear_ordered_ring
section linear_ordered_field
variables [linear_ordered_field α]
/-- Every positive `x` is between two successive integer powers of
another `y` greater than one. This is the same as `exists_int_pow_near'`,
but with ≤ and < the other way around. -/
lemma exists_int_pow_near [archimedean α]
{x : α} {y : α} (hx : 0 < x) (hy : 1 < y) :
∃ n : ℤ, y ^ n ≤ x ∧ x < y ^ (n + 1) :=
by classical; exact
let ⟨N, hN⟩ := pow_unbounded_of_one_lt x⁻¹ hy in
have he: ∃ m : ℤ, y ^ m ≤ x, from
⟨-N, le_of_lt (by { rw [fpow_neg y (↑N), gpow_coe_nat],
exact (inv_lt hx (lt_trans (inv_pos.2 hx) hN)).1 hN })⟩,
let ⟨M, hM⟩ := pow_unbounded_of_one_lt x hy in
have hb: ∃ b : ℤ, ∀ m, y ^ m ≤ x → m ≤ b, from
⟨M, λ m hm, le_of_not_lt (λ hlt, not_lt_of_ge
(fpow_le_of_le hy.le hlt.le)
(lt_of_le_of_lt hm (by rwa ← gpow_coe_nat at hM)))⟩,
let ⟨n, hn₁, hn₂⟩ := int.exists_greatest_of_bdd hb he in
⟨n, hn₁, lt_of_not_ge (λ hge, not_le_of_gt (int.lt_succ _) (hn₂ _ hge))⟩
/-- Every positive `x` is between two successive integer powers of
another `y` greater than one. This is the same as `exists_int_pow_near`,
but with ≤ and < the other way around. -/
lemma exists_int_pow_near' [archimedean α]
{x : α} {y : α} (hx : 0 < x) (hy : 1 < y) :
∃ n : ℤ, y ^ n < x ∧ x ≤ y ^ (n + 1) :=
let ⟨m, hle, hlt⟩ := exists_int_pow_near (inv_pos.2 hx) hy in
have hyp : 0 < y, from lt_trans zero_lt_one hy,
⟨-(m+1),
by rwa [fpow_neg, inv_lt (fpow_pos_of_pos hyp _) hx],
by rwa [neg_add, neg_add_cancel_right, fpow_neg,
le_inv hx (fpow_pos_of_pos hyp _)]⟩
/-- For any `y < 1` and any positive `x`, there exists `n : ℕ` with `y ^ n < x`. -/
lemma exists_pow_lt_of_lt_one [archimedean α] {x y : α} (hx : 0 < x) (hy : y < 1) :
∃ n : ℕ, y ^ n < x :=
begin
by_cases y_pos : y ≤ 0,
{ use 1, simp only [pow_one], linarith, },
rw [not_le] at y_pos,
rcases pow_unbounded_of_one_lt (x⁻¹) (one_lt_inv y_pos hy) with ⟨q, hq⟩,
exact ⟨q, by rwa [inv_pow₀, inv_lt_inv hx (pow_pos y_pos _)] at hq⟩
end
/-- Given `x` and `y` between `0` and `1`, `x` is between two successive powers of `y`.
This is the same as `exists_nat_pow_near`, but for elements between `0` and `1` -/
lemma exists_nat_pow_near_of_lt_one [archimedean α]
{x : α} {y : α} (xpos : 0 < x) (hx : x ≤ 1) (ypos : 0 < y) (hy : y < 1) :
∃ n : ℕ, y ^ (n + 1) < x ∧ x ≤ y ^ n :=
begin
rcases exists_nat_pow_near (one_le_inv_iff.2 ⟨xpos, hx⟩) (one_lt_inv_iff.2 ⟨ypos, hy⟩)
with ⟨n, hn, h'n⟩,
refine ⟨n, _, _⟩,
{ rwa [inv_pow₀, inv_lt_inv xpos (pow_pos ypos _)] at h'n },
{ rwa [inv_pow₀, inv_le_inv (pow_pos ypos _) xpos] at hn }
end
variables [floor_ring α]
lemma sub_floor_div_mul_nonneg (x : α) {y : α} (hy : 0 < y) :
0 ≤ x - ⌊x / y⌋ * y :=
begin
conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm},
rw ← sub_mul,
exact mul_nonneg (sub_nonneg.2 (floor_le _)) (le_of_lt hy)
end
lemma sub_floor_div_mul_lt (x : α) {y : α} (hy : 0 < y) :
x - ⌊x / y⌋ * y < y :=
sub_lt_iff_lt_add.2 begin
conv in y {rw ← one_mul y},
conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm},
rw ← add_mul,
exact (mul_lt_mul_right hy).2 (by rw add_comm; exact lt_floor_add_one _),
end
end linear_ordered_field
instance : archimedean ℕ :=
⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.nsmul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩
instance : archimedean ℤ :=
⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $
by simpa only [nsmul_eq_mul, int.nat_cast_eq_coe_nat, zero_add, mul_one]
using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩
/-- A linear ordered archimedean ring is a floor ring. This is not an `instance` because in some
cases we have a computable `floor` function. -/
noncomputable def archimedean.floor_ring (α)
[linear_ordered_ring α] [archimedean α] : floor_ring α :=
floor_ring.of_floor α (λ a, classical.some (exists_floor a))
(λ z a, (classical.some_spec (exists_floor a) z).symm)
section linear_ordered_field
variables [linear_ordered_field α]
theorem archimedean_iff_nat_lt :
archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n :=
⟨@exists_nat_gt α _ _, λ H, ⟨λ x y y0,
(H (x / y)).imp $ λ n h, le_of_lt $
by rwa [div_lt_iff y0, ← nsmul_eq_mul] at h⟩⟩
theorem archimedean_iff_nat_le :
archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n :=
archimedean_iff_nat_lt.trans
⟨λ H x, (H x).imp $ λ _, le_of_lt,
λ H x, let ⟨n, h⟩ := H x in ⟨n+1,
lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩
theorem exists_rat_gt [archimedean α] (x : α) : ∃ q : ℚ, x < q :=
let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩
theorem archimedean_iff_rat_lt :
archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q :=
⟨@exists_rat_gt α _,
λ H, archimedean_iff_nat_lt.2 $ λ x,
let ⟨q, h⟩ := H x in
⟨⌈q⌉₊, lt_of_lt_of_le h $
by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (nat.le_ceil _)⟩⟩
theorem archimedean_iff_rat_le :
archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q :=
archimedean_iff_rat_lt.trans
⟨λ H x, (H x).imp $ λ _, le_of_lt,
λ H x, let ⟨n, h⟩ := H x in ⟨n+1,
lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩
variable [archimedean α]
theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x :=
let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩
theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y :=
begin
cases exists_nat_gt (y - x)⁻¹ with n nh,
cases exists_floor (x * n) with z zh,
refine ⟨(z + 1 : ℤ) / n, _⟩,
have n0' := (inv_pos.2 (sub_pos.2 h)).trans nh,
have n0 := nat.cast_pos.1 n0',
rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'],
refine ⟨(lt_div_iff n0').2 $
(lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩,
rw [int.cast_add, int.cast_one],
refine lt_of_le_of_lt (add_le_add_right ((zh _).1 (le_refl _)) _) _,
rwa [← lt_sub_iff_add_lt', ← sub_mul,
← div_lt_iff' (sub_pos.2 h), one_div],
{ rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero },
{ intro H, rw [rat.coe_nat_num, ← coe_coe, nat.cast_eq_zero] at H, subst H, cases n0 },
{ rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero }
end
theorem exists_nat_one_div_lt {ε : α} (hε : 0 < ε) : ∃ n : ℕ, 1 / (n + 1: α) < ε :=
begin
cases exists_nat_gt (1/ε) with n hn,
use n,
rw [div_lt_iff, ← div_lt_iff' hε],
{ apply hn.trans,
simp [zero_lt_one] },
{ exact n.cast_add_one_pos }
end
theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x :=
by simpa only [rat.cast_pos] using exists_rat_btwn x0
end linear_ordered_field
section
variables [linear_ordered_field α] [floor_ring α]
/-- `round` rounds a number to the nearest integer. `round (1 / 2) = 1` -/
def round (x : α) : ℤ := ⌊x + 1 / 2⌋
@[simp] lemma round_zero : round (0 : α) = 0 := floor_eq_iff.2 (by norm_num)
@[simp] lemma round_one : round (1 : α) = 1 := floor_eq_iff.2 (by norm_num)
lemma abs_sub_round (x : α) : |x - round x| ≤ 1 / 2 :=
begin
rw [round, abs_sub_le_iff],
have := floor_le (x + 1 / 2),
have := lt_floor_add_one (x + 1 / 2),
split; linarith
end
@[simp, norm_cast] theorem rat.cast_floor (x : ℚ) : ⌊(x:α)⌋ = ⌊x⌋ :=
floor_eq_iff.2 (by exact_mod_cast floor_eq_iff.1 (eq.refl ⌊x⌋))
@[simp, norm_cast] theorem rat.cast_ceil (x : ℚ) : ⌈(x:α)⌉ = ⌈x⌉ :=
by rw [←neg_inj, ←floor_neg, ←floor_neg, ← rat.cast_neg, rat.cast_floor]
@[simp, norm_cast] theorem rat.cast_round (x : ℚ) : round (x:α) = round x :=
have ((x + 1 / 2 : ℚ) : α) = x + 1 / 2, by simp,
by rw [round, round, ← this, rat.cast_floor]
end
section
variables [linear_ordered_field α] [archimedean α]
theorem exists_rat_near (x : α) {ε : α} (ε0 : 0 < ε) :
∃ q : ℚ, |x - q| < ε :=
let ⟨q, h₁, h₂⟩ := exists_rat_btwn $
lt_trans ((sub_lt_self_iff x).2 ε0) ((lt_add_iff_pos_left x).2 ε0) in
⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩
instance : archimedean ℚ :=
archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩
end
|
3dc7d5793d16a5decf08aa9ebbbc8f290a2cc0b8 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /stage0/src/Init/Data/UInt.lean | 44e15a429963704a254ce9cda3548bf65d7c17a2 | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,119 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Fin.Basic
import Init.System.Platform
open Nat
@[extern "lean_uint8_of_nat"]
def UInt8.ofNat (n : @& Nat) : UInt8 := ⟨Fin.ofNat n⟩
abbrev Nat.toUInt8 := UInt8.ofNat
@[extern "lean_uint8_to_nat"]
def UInt8.toNat (n : UInt8) : Nat := n.val.val
@[extern c inline "#1 + #2"]
def UInt8.add (a b : UInt8) : UInt8 := ⟨a.val + b.val⟩
@[extern c inline "#1 - #2"]
def UInt8.sub (a b : UInt8) : UInt8 := ⟨a.val - b.val⟩
@[extern c inline "#1 * #2"]
def UInt8.mul (a b : UInt8) : UInt8 := ⟨a.val * b.val⟩
@[extern c inline "#2 == 0 ? 0 : #1 / #2"]
def UInt8.div (a b : UInt8) : UInt8 := ⟨a.val / b.val⟩
@[extern c inline "#2 == 0 ? #1 : #1 % #2"]
def UInt8.mod (a b : UInt8) : UInt8 := ⟨a.val % b.val⟩
@[extern "lean_uint8_modn"]
def UInt8.modn (a : UInt8) (n : @& Nat) : UInt8 := ⟨a.val % n⟩
@[extern c inline "#1 & #2"]
def UInt8.land (a b : UInt8) : UInt8 := ⟨Fin.land a.val b.val⟩
@[extern c inline "#1 | #2"]
def UInt8.lor (a b : UInt8) : UInt8 := ⟨Fin.lor a.val b.val⟩
def UInt8.lt (a b : UInt8) : Prop := a.val < b.val
def UInt8.le (a b : UInt8) : Prop := a.val ≤ b.val
instance : OfNat UInt8 n := ⟨UInt8.ofNat n⟩
instance : Add UInt8 := ⟨UInt8.add⟩
instance : Sub UInt8 := ⟨UInt8.sub⟩
instance : Mul UInt8 := ⟨UInt8.mul⟩
instance : Mod UInt8 := ⟨UInt8.mod⟩
instance : HMod UInt8 Nat UInt8 := ⟨UInt8.modn⟩
instance : Div UInt8 := ⟨UInt8.div⟩
instance : HasLess UInt8 := ⟨UInt8.lt⟩
instance : HasLessEq UInt8 := ⟨UInt8.le⟩
@[extern c inline "#1 << #2"]
constant UInt8.shiftLeft (a b : UInt8) : UInt8
@[extern c inline "#1 >> #2"]
constant UInt8.shiftRight (a b : UInt8) : UInt8
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 < #2"]
def UInt8.decLt (a b : UInt8) : Decidable (a < b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m))
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 <= #2"]
def UInt8.decLe (a b : UInt8) : Decidable (a ≤ b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m))
instance (a b : UInt8) : Decidable (a < b) := UInt8.decLt a b
instance (a b : UInt8) : Decidable (a ≤ b) := UInt8.decLe a b
@[extern "lean_uint16_of_nat"]
def UInt16.ofNat (n : @& Nat) : UInt16 := ⟨Fin.ofNat n⟩
abbrev Nat.toUInt16 := UInt16.ofNat
@[extern "lean_uint16_to_nat"]
def UInt16.toNat (n : UInt16) : Nat := n.val.val
@[extern c inline "#1 + #2"]
def UInt16.add (a b : UInt16) : UInt16 := ⟨a.val + b.val⟩
@[extern c inline "#1 - #2"]
def UInt16.sub (a b : UInt16) : UInt16 := ⟨a.val - b.val⟩
@[extern c inline "#1 * #2"]
def UInt16.mul (a b : UInt16) : UInt16 := ⟨a.val * b.val⟩
@[extern c inline "#2 == 0 ? 0 : #1 / #2"]
def UInt16.div (a b : UInt16) : UInt16 := ⟨a.val / b.val⟩
@[extern c inline "#2 == 0 ? #1 : #1 % #2"]
def UInt16.mod (a b : UInt16) : UInt16 := ⟨a.val % b.val⟩
@[extern "lean_uint16_modn"]
def UInt16.modn (a : UInt16) (n : @& Nat) : UInt16 := ⟨a.val % n⟩
@[extern c inline "#1 & #2"]
def UInt16.land (a b : UInt16) : UInt16 := ⟨Fin.land a.val b.val⟩
@[extern c inline "#1 | #2"]
def UInt16.lor (a b : UInt16) : UInt16 := ⟨Fin.lor a.val b.val⟩
def UInt16.lt (a b : UInt16) : Prop := a.val < b.val
def UInt16.le (a b : UInt16) : Prop := a.val ≤ b.val
instance : OfNat UInt16 n := ⟨UInt16.ofNat n⟩
instance : Add UInt16 := ⟨UInt16.add⟩
instance : Sub UInt16 := ⟨UInt16.sub⟩
instance : Mul UInt16 := ⟨UInt16.mul⟩
instance : Mod UInt16 := ⟨UInt16.mod⟩
instance : HMod UInt16 Nat UInt16 := ⟨UInt16.modn⟩
instance : Div UInt16 := ⟨UInt16.div⟩
instance : HasLess UInt16 := ⟨UInt16.lt⟩
instance : HasLessEq UInt16 := ⟨UInt16.le⟩
@[extern c inline "#1 << #2"]
constant UInt16.shiftLeft (a b : UInt16) : UInt16
@[extern c inline "#1 >> #2"]
constant UInt16.shiftRight (a b : UInt16) : UInt16
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 < #2"]
def UInt16.decLt (a b : UInt16) : Decidable (a < b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m))
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 <= #2"]
def UInt16.decLe (a b : UInt16) : Decidable (a ≤ b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m))
instance (a b : UInt16) : Decidable (a < b) := UInt16.decLt a b
instance (a b : UInt16) : Decidable (a ≤ b) := UInt16.decLe a b
@[extern "lean_uint32_of_nat"]
def UInt32.ofNat (n : @& Nat) : UInt32 := ⟨Fin.ofNat n⟩
@[extern "lean_uint32_of_nat"]
def UInt32.ofNat' (n : Nat) (h : n < UInt32.size) : UInt32 := ⟨⟨n, h⟩⟩
abbrev Nat.toUInt32 := UInt32.ofNat
@[extern c inline "#1 + #2"]
def UInt32.add (a b : UInt32) : UInt32 := ⟨a.val + b.val⟩
@[extern c inline "#1 - #2"]
def UInt32.sub (a b : UInt32) : UInt32 := ⟨a.val - b.val⟩
@[extern c inline "#1 * #2"]
def UInt32.mul (a b : UInt32) : UInt32 := ⟨a.val * b.val⟩
@[extern c inline "#2 == 0 ? 0 : #1 / #2"]
def UInt32.div (a b : UInt32) : UInt32 := ⟨a.val / b.val⟩
@[extern c inline "#2 == 0 ? #1 : #1 % #2"]
def UInt32.mod (a b : UInt32) : UInt32 := ⟨a.val % b.val⟩
@[extern "lean_uint32_modn"]
def UInt32.modn (a : UInt32) (n : @& Nat) : UInt32 := ⟨a.val % n⟩
@[extern c inline "#1 & #2"]
def UInt32.land (a b : UInt32) : UInt32 := ⟨Fin.land a.val b.val⟩
@[extern c inline "#1 | #2"]
def UInt32.lor (a b : UInt32) : UInt32 := ⟨Fin.lor a.val b.val⟩
@[extern c inline "((uint8_t)#1)"]
def UInt32.toUInt8 (a : UInt32) : UInt8 := a.toNat.toUInt8
@[extern c inline "((uint16_t)#1)"]
def UInt32.toUInt16 (a : UInt32) : UInt16 := a.toNat.toUInt16
@[extern c inline "((uint32_t)#1)"]
def UInt8.toUInt32 (a : UInt8) : UInt32 := a.toNat.toUInt32
instance : OfNat UInt32 n := ⟨UInt32.ofNat n⟩
instance : Add UInt32 := ⟨UInt32.add⟩
instance : Sub UInt32 := ⟨UInt32.sub⟩
instance : Mul UInt32 := ⟨UInt32.mul⟩
instance : Mod UInt32 := ⟨UInt32.mod⟩
instance : HMod UInt32 Nat UInt32 := ⟨UInt32.modn⟩
instance : Div UInt32 := ⟨UInt32.div⟩
@[extern c inline "#1 << #2"]
constant UInt32.shiftLeft (a b : UInt32) : UInt32
@[extern c inline "#1 >> #2"]
constant UInt32.shiftRight (a b : UInt32) : UInt32
@[extern "lean_uint64_of_nat"]
def UInt64.ofNat (n : @& Nat) : UInt64 := ⟨Fin.ofNat n⟩
abbrev Nat.toUInt64 := UInt64.ofNat
@[extern "lean_uint64_to_nat"]
def UInt64.toNat (n : UInt64) : Nat := n.val.val
@[extern c inline "#1 + #2"]
def UInt64.add (a b : UInt64) : UInt64 := ⟨a.val + b.val⟩
@[extern c inline "#1 - #2"]
def UInt64.sub (a b : UInt64) : UInt64 := ⟨a.val - b.val⟩
@[extern c inline "#1 * #2"]
def UInt64.mul (a b : UInt64) : UInt64 := ⟨a.val * b.val⟩
@[extern c inline "#2 == 0 ? 0 : #1 / #2"]
def UInt64.div (a b : UInt64) : UInt64 := ⟨a.val / b.val⟩
@[extern c inline "#2 == 0 ? #1 : #1 % #2"]
def UInt64.mod (a b : UInt64) : UInt64 := ⟨a.val % b.val⟩
@[extern "lean_uint64_modn"]
def UInt64.modn (a : UInt64) (n : @& Nat) : UInt64 := ⟨a.val % n⟩
@[extern c inline "#1 & #2"]
def UInt64.land (a b : UInt64) : UInt64 := ⟨Fin.land a.val b.val⟩
@[extern c inline "#1 | #2"]
def UInt64.lor (a b : UInt64) : UInt64 := ⟨Fin.lor a.val b.val⟩
def UInt64.lt (a b : UInt64) : Prop := a.val < b.val
def UInt64.le (a b : UInt64) : Prop := a.val ≤ b.val
@[extern c inline "((uint8_t)#1)"]
def UInt64.toUInt8 (a : UInt64) : UInt8 := a.toNat.toUInt8
@[extern c inline "((uint16_t)#1)"]
def UInt64.toUInt16 (a : UInt64) : UInt16 := a.toNat.toUInt16
@[extern c inline "((uint32_t)#1)"]
def UInt64.toUInt32 (a : UInt64) : UInt32 := a.toNat.toUInt32
@[extern c inline "((uint64_t)#1)"]
def UInt32.toUInt64 (a : UInt32) : UInt64 := a.toNat.toUInt64
-- TODO(Leo): give reference implementation for shiftLeft and shiftRight, and define them for other UInt types
@[extern c inline "#1 << #2"]
constant UInt64.shiftLeft (a b : UInt64) : UInt64
@[extern c inline "#1 >> #2"]
constant UInt64.shiftRight (a b : UInt64) : UInt64
instance : OfNat UInt64 n := ⟨UInt64.ofNat n⟩
instance : Add UInt64 := ⟨UInt64.add⟩
instance : Sub UInt64 := ⟨UInt64.sub⟩
instance : Mul UInt64 := ⟨UInt64.mul⟩
instance : Mod UInt64 := ⟨UInt64.mod⟩
instance : HMod UInt64 Nat UInt64 := ⟨UInt64.modn⟩
instance : Div UInt64 := ⟨UInt64.div⟩
instance : HasLess UInt64 := ⟨UInt64.lt⟩
instance : HasLessEq UInt64 := ⟨UInt64.le⟩
@[extern c inline "(uint64_t)#1"]
def Bool.toUInt64 (b : Bool) : UInt64 := if b then 1 else 0
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 < #2"]
def UInt64.decLt (a b : UInt64) : Decidable (a < b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m))
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 <= #2"]
def UInt64.decLe (a b : UInt64) : Decidable (a ≤ b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m))
instance (a b : UInt64) : Decidable (a < b) := UInt64.decLt a b
instance (a b : UInt64) : Decidable (a ≤ b) := UInt64.decLe a b
theorem usizeSzGt0 : USize.size > 0 :=
Nat.posPowOfPos System.Platform.numBits (Nat.zeroLtSucc _)
@[extern "lean_usize_of_nat"]
def USize.ofNat (n : @& Nat) : USize := ⟨Fin.ofNat' n usizeSzGt0⟩
abbrev Nat.toUSize := USize.ofNat
@[extern "lean_usize_to_nat"]
def USize.toNat (n : USize) : Nat := n.val.val
@[extern c inline "#1 + #2"]
def USize.add (a b : USize) : USize := ⟨a.val + b.val⟩
@[extern c inline "#1 - #2"]
def USize.sub (a b : USize) : USize := ⟨a.val - b.val⟩
@[extern c inline "#1 * #2"]
def USize.mul (a b : USize) : USize := ⟨a.val * b.val⟩
@[extern c inline "#2 == 0 ? 0 : #1 / #2"]
def USize.div (a b : USize) : USize := ⟨a.val / b.val⟩
@[extern c inline "#2 == 0 ? #1 : #1 % #2"]
def USize.mod (a b : USize) : USize := ⟨a.val % b.val⟩
@[extern "lean_usize_modn"]
def USize.modn (a : USize) (n : @& Nat) : USize := ⟨a.val % n⟩
@[extern c inline "#1 & #2"]
def USize.land (a b : USize) : USize := ⟨Fin.land a.val b.val⟩
@[extern c inline "#1 | #2"]
def USize.lor (a b : USize) : USize := ⟨Fin.lor a.val b.val⟩
@[extern c inline "#1"]
def UInt32.toUSize (a : UInt32) : USize := a.toNat.toUSize
@[extern c inline "((size_t)#1)"]
def UInt64.toUSize (a : UInt64) : USize := a.toNat.toUSize
@[extern c inline "(uint32_t)#1"]
def USize.toUInt32 (a : USize) : UInt32 := a.toNat.toUInt32
-- TODO(Leo): give reference implementation for shiftLeft and shiftRight, and define them for other UInt types
@[extern c inline "#1 << #2"]
constant USize.shiftLeft (a b : USize) : USize
@[extern c inline "#1 >> #2"]
constant USize.shiftRight (a b : USize) : USize
def USize.lt (a b : USize) : Prop := a.val < b.val
def USize.le (a b : USize) : Prop := a.val ≤ b.val
instance : OfNat USize n := ⟨USize.ofNat n⟩
instance : Add USize := ⟨USize.add⟩
instance : Sub USize := ⟨USize.sub⟩
instance : Mul USize := ⟨USize.mul⟩
instance : Mod USize := ⟨USize.mod⟩
instance : HMod USize Nat USize := ⟨USize.modn⟩
instance : Div USize := ⟨USize.div⟩
instance : HasLess USize := ⟨USize.lt⟩
instance : HasLessEq USize := ⟨USize.le⟩
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 < #2"]
def USize.decLt (a b : USize) : Decidable (a < b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m))
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 <= #2"]
def USize.decLe (a b : USize) : Decidable (a ≤ b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m))
instance (a b : USize) : Decidable (a < b) := USize.decLt a b
instance (a b : USize) : Decidable (a ≤ b) := USize.decLe a b
theorem USize.modnLt {m : Nat} : ∀ (u : USize), m > 0 → USize.toNat (u % m) < m
| ⟨u⟩, h => Fin.modnLt u h
|
67819361cb8a094bc431ad1e20549ff914accd37 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/def1.lean | 4ad2261b4d85da53c1e30cc10901f2d3c2131176 | [
"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 | 372 | lean |
namespace tst
variable {A : Type}
attribute [reducible]
definition foo₁ (a b c : A) (H₁ : a = b) (H₂ : c = b) : a = c :=
eq.trans H₁ (eq.symm H₂)
lemma foo₂ (f : A → A → A) (a b c : A) (H₁ : a = b) (H₂ : c = b) : f a = f c :=
eq.symm H₂ ▸ H₁ ▸ rfl
#check foo₁
#check foo₂
end tst
#check tst.foo₁
#check tst.foo₂
#print tst.foo₁
|
f88294cc1519325357ac748067447e9e58a5fc6a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/finsupp/to_dfinsupp.lean | e855ec369bbb3fa2a07ea4f09d148b114a91c388 | [
"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 | 11,740 | 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.module.equiv
import data.dfinsupp.basic
import data.finsupp.basic
/-!
# Conversion between `finsupp` and homogenous `dfinsupp`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This module provides conversions between `finsupp` and `dfinsupp`.
It is in its own file since neither `finsupp` or `dfinsupp` depend on each other.
## Main definitions
* "identity" maps between `finsupp` and `dfinsupp`:
* `finsupp.to_dfinsupp : (ι →₀ M) → (Π₀ i : ι, M)`
* `dfinsupp.to_finsupp : (Π₀ i : ι, M) → (ι →₀ M)`
* Bundled equiv versions of the above:
* `finsupp_equiv_dfinsupp : (ι →₀ M) ≃ (Π₀ i : ι, M)`
* `finsupp_add_equiv_dfinsupp : (ι →₀ M) ≃+ (Π₀ i : ι, M)`
* `finsupp_lequiv_dfinsupp R : (ι →₀ M) ≃ₗ[R] (Π₀ i : ι, M)`
* stronger versions of `finsupp.split`:
* `sigma_finsupp_equiv_dfinsupp : ((Σ i, η i) →₀ N) ≃ (Π₀ i, (η i →₀ N))`
* `sigma_finsupp_add_equiv_dfinsupp : ((Σ i, η i) →₀ N) ≃+ (Π₀ i, (η i →₀ N))`
* `sigma_finsupp_lequiv_dfinsupp : ((Σ i, η i) →₀ N) ≃ₗ[R] (Π₀ i, (η i →₀ N))`
## Theorems
The defining features of these operations is that they preserve the function and support:
* `finsupp.to_dfinsupp_coe`
* `finsupp.to_dfinsupp_support`
* `dfinsupp.to_finsupp_coe`
* `dfinsupp.to_finsupp_support`
and therefore map `finsupp.single` to `dfinsupp.single` and vice versa:
* `finsupp.to_dfinsupp_single`
* `dfinsupp.to_finsupp_single`
as well as preserving arithmetic operations.
For the bundled equivalences, we provide lemmas that they reduce to `finsupp.to_dfinsupp`:
* `finsupp_add_equiv_dfinsupp_apply`
* `finsupp_lequiv_dfinsupp_apply`
* `finsupp_add_equiv_dfinsupp_symm_apply`
* `finsupp_lequiv_dfinsupp_symm_apply`
## Implementation notes
We provide `dfinsupp.to_finsupp` and `finsupp_equiv_dfinsupp` computably by adding
`[decidable_eq ι]` and `[Π m : M, decidable (m ≠ 0)]` arguments. To aid with definitional unfolding,
these arguments are also present on the `noncomputable` equivs.
-/
variables {ι : Type*} {R : Type*} {M : Type*}
/-! ### Basic definitions and lemmas -/
section defs
/-- Interpret a `finsupp` as a homogenous `dfinsupp`. -/
def finsupp.to_dfinsupp [has_zero M] (f : ι →₀ M) : Π₀ i : ι, M :=
{ to_fun := f,
support' := trunc.mk
⟨f.support.1, λ i, (classical.em (f i = 0)).symm.imp_left (finsupp.mem_support_iff.mpr)⟩ }
@[simp] lemma finsupp.to_dfinsupp_coe [has_zero M] (f : ι →₀ M) : ⇑f.to_dfinsupp = f := rfl
section
variables [decidable_eq ι] [has_zero M]
@[simp] lemma finsupp.to_dfinsupp_single (i : ι) (m : M) :
(finsupp.single i m).to_dfinsupp = dfinsupp.single i m :=
by { ext, simp [finsupp.single_apply, dfinsupp.single_apply] }
variables [Π m : M, decidable (m ≠ 0)]
@[simp] lemma to_dfinsupp_support (f : ι →₀ M) : f.to_dfinsupp.support = f.support :=
by { ext, simp, }
/-- Interpret a homogenous `dfinsupp` as a `finsupp`.
Note that the elaborator has a lot of trouble with this definition - it is often necessary to
write `(dfinsupp.to_finsupp f : ι →₀ M)` instead of `f.to_finsupp`, as for some unknown reason
using dot notation or omitting the type ascription prevents the type being resolved correctly. -/
def dfinsupp.to_finsupp (f : Π₀ i : ι, M) : ι →₀ M :=
⟨f.support, f, λ i, by simp only [dfinsupp.mem_support_iff]⟩
@[simp] lemma dfinsupp.to_finsupp_coe (f : Π₀ i : ι, M) : ⇑f.to_finsupp = f := rfl
@[simp] lemma dfinsupp.to_finsupp_support (f : Π₀ i : ι, M) : f.to_finsupp.support = f.support :=
by { ext, simp, }
@[simp] lemma dfinsupp.to_finsupp_single (i : ι) (m : M) :
(dfinsupp.single i m : Π₀ i : ι, M).to_finsupp = finsupp.single i m :=
by { ext, simp [finsupp.single_apply, dfinsupp.single_apply] }
@[simp] lemma finsupp.to_dfinsupp_to_finsupp (f : ι →₀ M) : f.to_dfinsupp.to_finsupp = f :=
finsupp.coe_fn_injective rfl
@[simp] lemma dfinsupp.to_finsupp_to_dfinsupp (f : Π₀ i : ι, M) : f.to_finsupp.to_dfinsupp = f :=
dfinsupp.coe_fn_injective rfl
end
end defs
/-! ### Lemmas about arithmetic operations -/
section lemmas
namespace finsupp
@[simp] lemma to_dfinsupp_zero [has_zero M] :
(0 : ι →₀ M).to_dfinsupp = 0 := dfinsupp.coe_fn_injective rfl
@[simp] lemma to_dfinsupp_add [add_zero_class M] (f g : ι →₀ M) :
(f + g).to_dfinsupp = f.to_dfinsupp + g.to_dfinsupp := dfinsupp.coe_fn_injective rfl
@[simp] lemma to_dfinsupp_neg [add_group M] (f : ι →₀ M) :
(-f).to_dfinsupp = -f.to_dfinsupp := dfinsupp.coe_fn_injective rfl
@[simp] lemma to_dfinsupp_sub [add_group M] (f g : ι →₀ M) :
(f - g).to_dfinsupp = f.to_dfinsupp - g.to_dfinsupp :=
dfinsupp.coe_fn_injective rfl
@[simp] lemma to_dfinsupp_smul [monoid R] [add_monoid M] [distrib_mul_action R M]
(r : R) (f : ι →₀ M) : (r • f).to_dfinsupp = r • f.to_dfinsupp :=
dfinsupp.coe_fn_injective rfl
end finsupp
namespace dfinsupp
variables [decidable_eq ι]
@[simp] lemma to_finsupp_zero [has_zero M] [Π m : M, decidable (m ≠ 0)] :
to_finsupp 0 = (0 : ι →₀ M) := finsupp.coe_fn_injective rfl
@[simp] lemma to_finsupp_add [add_zero_class M] [Π m : M, decidable (m ≠ 0)] (f g : Π₀ i : ι, M) :
(to_finsupp (f + g) : ι →₀ M) = (to_finsupp f + to_finsupp g) :=
finsupp.coe_fn_injective $ dfinsupp.coe_add _ _
@[simp] lemma to_finsupp_neg [add_group M] [Π m : M, decidable (m ≠ 0)] (f : Π₀ i : ι, M) :
(to_finsupp (-f) : ι →₀ M) = -to_finsupp f :=
finsupp.coe_fn_injective $ dfinsupp.coe_neg _
@[simp] lemma to_finsupp_sub [add_group M] [Π m : M, decidable (m ≠ 0)] (f g : Π₀ i : ι, M) :
(to_finsupp (f - g) : ι →₀ M) = to_finsupp f - to_finsupp g :=
finsupp.coe_fn_injective $ dfinsupp.coe_sub _ _
@[simp] lemma to_finsupp_smul [monoid R] [add_monoid M] [distrib_mul_action R M]
[Π m : M, decidable (m ≠ 0)]
(r : R) (f : Π₀ i : ι, M) : (to_finsupp (r • f) : ι →₀ M) = r • to_finsupp f :=
finsupp.coe_fn_injective $ dfinsupp.coe_smul _ _
end dfinsupp
end lemmas
/-! ### Bundled `equiv`s -/
section equivs
/-- `finsupp.to_dfinsupp` and `dfinsupp.to_finsupp` together form an equiv. -/
@[simps {fully_applied := ff}]
def finsupp_equiv_dfinsupp [decidable_eq ι] [has_zero M] [Π m : M, decidable (m ≠ 0)] :
(ι →₀ M) ≃ (Π₀ i : ι, M) :=
{ to_fun := finsupp.to_dfinsupp, inv_fun := dfinsupp.to_finsupp,
left_inv := finsupp.to_dfinsupp_to_finsupp, right_inv := dfinsupp.to_finsupp_to_dfinsupp }
/-- The additive version of `finsupp.to_finsupp`. Note that this is `noncomputable` because
`finsupp.has_add` is noncomputable. -/
@[simps {fully_applied := ff}]
def finsupp_add_equiv_dfinsupp
[decidable_eq ι] [add_zero_class M] [Π m : M, decidable (m ≠ 0)] :
(ι →₀ M) ≃+ (Π₀ i : ι, M) :=
{ to_fun := finsupp.to_dfinsupp, inv_fun := dfinsupp.to_finsupp,
map_add' := finsupp.to_dfinsupp_add,
.. finsupp_equiv_dfinsupp}
variables (R)
/-- The additive version of `finsupp.to_finsupp`. Note that this is `noncomputable` because
`finsupp.has_add` is noncomputable. -/
@[simps {fully_applied := ff}]
def finsupp_lequiv_dfinsupp
[decidable_eq ι] [semiring R] [add_comm_monoid M] [Π m : M, decidable (m ≠ 0)] [module R M] :
(ι →₀ M) ≃ₗ[R] (Π₀ i : ι, M) :=
{ to_fun := finsupp.to_dfinsupp, inv_fun := dfinsupp.to_finsupp,
map_smul' := finsupp.to_dfinsupp_smul,
map_add' := finsupp.to_dfinsupp_add,
.. finsupp_equiv_dfinsupp}
section sigma
/-- ### Stronger versions of `finsupp.split` -/
noncomputable theory
variables {η : ι → Type*} {N : Type*} [semiring R]
open finsupp
/-- `finsupp.split` is an equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/
def sigma_finsupp_equiv_dfinsupp [has_zero N] : ((Σ i, η i) →₀ N) ≃ (Π₀ i, (η i →₀ N)) :=
{ to_fun := λ f, ⟨split f, trunc.mk ⟨(split_support f : finset ι).val, λ i,
begin
rw [← finset.mem_def, mem_split_support_iff_nonzero],
exact (em _).symm
end⟩⟩,
inv_fun := λ f,
begin
haveI := classical.dec_eq ι,
haveI := λ i, classical.dec_eq (η i →₀ N),
refine on_finset (finset.sigma f.support (λ j, (f j).support)) (λ ji, f ji.1 ji.2)
(λ g hg, finset.mem_sigma.mpr ⟨_, mem_support_iff.mpr hg⟩),
simp only [ne.def, dfinsupp.mem_support_to_fun],
intro h,
rw h at hg,
simpa using hg
end,
left_inv := λ f, by { ext, simp [split] },
right_inv := λ f, by { ext, simp [split] } }
@[simp]
lemma sigma_finsupp_equiv_dfinsupp_apply [has_zero N] (f : (Σ i, η i) →₀ N) :
(sigma_finsupp_equiv_dfinsupp f : Π i, (η i →₀ N)) = finsupp.split f := rfl
@[simp]
lemma sigma_finsupp_equiv_dfinsupp_symm_apply [has_zero N] (f : Π₀ i, (η i →₀ N)) (s : Σ i, η i) :
(sigma_finsupp_equiv_dfinsupp.symm f : (Σ i, η i) →₀ N) s = f s.1 s.2 := rfl
@[simp]
lemma sigma_finsupp_equiv_dfinsupp_support
[decidable_eq ι] [has_zero N] [Π (i : ι) (x : η i →₀ N), decidable (x ≠ 0)]
(f : (Σ i, η i) →₀ N) :
(sigma_finsupp_equiv_dfinsupp f).support = finsupp.split_support f :=
begin
ext,
rw dfinsupp.mem_support_to_fun,
exact (finsupp.mem_split_support_iff_nonzero _ _).symm,
end
@[simp] lemma sigma_finsupp_equiv_dfinsupp_single [decidable_eq ι] [has_zero N]
(a : Σ i, η i) (n : N) :
sigma_finsupp_equiv_dfinsupp (finsupp.single a n)
= @dfinsupp.single _ (λ i, η i →₀ N) _ _ a.1 (finsupp.single a.2 n) :=
begin
obtain ⟨i, a⟩ := a,
ext j b,
by_cases h : i = j,
{ subst h,
classical,
simp [split_apply, finsupp.single_apply] },
suffices : finsupp.single (⟨i, a⟩ : Σ i, η i) n ⟨j, b⟩ = 0,
{ simp [split_apply, dif_neg h, this] },
have H : (⟨i, a⟩ : Σ i, η i) ≠ ⟨j, b⟩ := by simp [h],
classical,
rw [finsupp.single_apply, if_neg H]
end
-- Without this Lean fails to find the `add_zero_class` instance on `Π₀ i, (η i →₀ N)`.
local attribute [-instance] finsupp.has_zero
@[simp]
lemma sigma_finsupp_equiv_dfinsupp_add [add_zero_class N] (f g : (Σ i, η i) →₀ N) :
sigma_finsupp_equiv_dfinsupp (f + g) =
(sigma_finsupp_equiv_dfinsupp f + (sigma_finsupp_equiv_dfinsupp g) : (Π₀ (i : ι), η i →₀ N)) :=
by {ext, refl}
/-- `finsupp.split` is an additive equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/
@[simps]
def sigma_finsupp_add_equiv_dfinsupp [add_zero_class N] : ((Σ i, η i) →₀ N) ≃+ (Π₀ i, (η i →₀ N)) :=
{ to_fun := sigma_finsupp_equiv_dfinsupp,
inv_fun := sigma_finsupp_equiv_dfinsupp.symm,
map_add' := sigma_finsupp_equiv_dfinsupp_add,
.. sigma_finsupp_equiv_dfinsupp }
local attribute [-instance] finsupp.add_zero_class
--tofix: r • (sigma_finsupp_equiv_dfinsupp f) doesn't work.
@[simp]
lemma sigma_finsupp_equiv_dfinsupp_smul {R} [monoid R] [add_monoid N] [distrib_mul_action R N]
(r : R) (f : (Σ i, η i) →₀ N) : sigma_finsupp_equiv_dfinsupp (r • f) =
@has_smul.smul R (Π₀ i, η i →₀ N) mul_action.to_has_smul r (sigma_finsupp_equiv_dfinsupp f) :=
by { ext, refl }
local attribute [-instance] finsupp.add_monoid
/-- `finsupp.split` is a linear equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/
@[simps]
def sigma_finsupp_lequiv_dfinsupp [add_comm_monoid N] [module R N] :
((Σ i, η i) →₀ N) ≃ₗ[R] (Π₀ i, (η i →₀ N)) :=
{ map_smul' := sigma_finsupp_equiv_dfinsupp_smul,
.. sigma_finsupp_add_equiv_dfinsupp }
end sigma
end equivs
|
20d7c7d2c4c1a8474357ed903d34f68f3afbc4a9 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/test/globs/Test/1.lean | 205de3c3565a6ede8f0bb66f3e6235c449093a53 | [
"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 | 28 | lean | #eval "visited Test/1.lean"
|
2bb5857c4983d3bcfc16c3984dbe41bd4d48b12e | 42c01158c2730cc6ac3e058c1339c18cb90366e2 | /xenalib/complex.lean | 4b2f1b49dbdd8e4b88a35440f214f32e2776f3c0 | [] | no_license | ChrisHughes24/xena | c80d94355d0c2ae8deddda9d01e6d31bc21c30ae | 337a0d7c9f0e255e08d6d0a383e303c080c6ec0c | refs/heads/master | 1,631,059,898,392 | 1,511,200,551,000 | 1,511,200,551,000 | 111,468,589 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,567 | lean | /-
Copyright (c) 2017 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Kevin Buzzard
The complex numbers, modelled as R^2 in the obvious way.
Natural next step: one could prove that complexes are a topological ring.
-/
import analysis.real
noncomputable theory
-- because reals are noncomputable
local attribute [instance] classical.decidable_inhabited classical.prop_decidable
-- because I don't know how to do inverses sensibly otherwise;
-- e.g. I needed to know that if z was non-zero then either its real part
-- was non-zero or its imaginary part was non-zero.
structure complex : Type :=
(re : ℝ) (im : ℝ)
notation `ℂ` := complex
-- definition goes outside namespace, then everything else in it?
namespace complex
-- handy checks for equality etc
theorem eta (z : complex) : complex.mk z.re z.im = z :=
cases_on z (λ _ _, rfl)
-- very useful
theorem eq_of_re_eq_and_im_eq (z w : complex) : z.re=w.re ∧ z.im=w.im → z=w :=
begin
intro H,rw [←eta z,←eta w,H.left,H.right],
end
-- simp version
theorem eq_iff_re_eq_and_im_eq (z w : complex) : z=w ↔ z.re=w.re ∧ z.im=w.im :=
begin
split,
intro H,rw [H],split;trivial,
exact eq_of_re_eq_and_im_eq _ _,
end
lemma proj_re (r0 i0 : real) : (complex.mk r0 i0).re = r0 := rfl
lemma proj_im (r0 i0 : real) : (complex.mk r0 i0).im = i0 := rfl
local attribute [simp] eq_iff_re_eq_and_im_eq proj_re proj_im
-- Am I right in
-- thinking that the end user should not need to
-- have to use this function?
def of_real : ℝ → ℂ := λ x, { re := x, im := 0 }
-- does one name these instances or not? I've named a random selection
instance coe_real_complex : has_coe ℝ ℂ := ⟨of_real⟩
instance : has_zero complex := ⟨of_real 0⟩
instance : has_one complex := ⟨of_real 1⟩
instance inhabited_complex : inhabited complex := ⟨0⟩
-- dangerously short variable name so I protected it.
-- It's never used in the library (other than in the projection
-- commands) but I think end users will use it.
protected def i : complex := {re := 0, im := 1}
def conjugate (z : complex) : complex := {re := z.re, im := -(z.im)}
-- Are these supposed to be protected too?
def add : complex → complex → complex :=
λ z w, { re :=z.re+w.re, im:=z.im+w.im}
def neg : complex → complex :=
λ z, { re := -z.re, im := -z.im}
def mul : complex → complex → complex :=
λ z w, { re := z.re*w.re - z.im*w.im,
im := z.re*w.im + z.im*w.re}
def norm_squared : complex → real :=
λ z, z.re*z.re+z.im*z.im
def inv : complex → complex :=
λ z, { re := z.re / norm_squared z,
im := -z.im / norm_squared z }
instance : has_add complex := ⟨complex.add⟩
instance : has_neg complex := ⟨complex.neg⟩
instance : has_sub complex := ⟨λx y, x + - y⟩
instance : has_mul complex := ⟨complex.mul⟩
instance : has_inv complex := ⟨complex.inv⟩
instance : has_div complex := ⟨λx y, x * y⁻¹⟩
-- I was initially astounded to find that at some point there was a typo in has_div but
-- this didn't cause any problems at all. I have since understood what is
-- going on: "/" is never used in the field axioms, only ^{-1} .
-- These are very useful for proofs in the library so I make them local simp lemmas.
lemma proj_zero_re : (0:complex).re=0 := rfl
lemma proj_zero_im : (0:complex).im=0 := rfl
lemma proj_one_re : (1:complex).re=1 := rfl
lemma proj_one_im : (1:complex).im=0 := rfl
lemma proj_i_re : complex.i.re=0 := rfl
lemma proj_i_im : complex.i.im=1 := rfl
lemma proj_conj_re (z : complex) : (conjugate z).re = z.re := rfl
lemma proj_conj_im (z : complex) : (conjugate z).im = -z.im := rfl
lemma proj_add_re (z w: complex) : (z+w).re=z.re+w.re := rfl
lemma proj_add_im (z w: complex) : (z+w).im=z.im+w.im := rfl
lemma proj_neg_re (z: complex) : (-z).re=-z.re := rfl
lemma proj_neg_im (z: complex) : (-z).im=-z.im := rfl
lemma proj_neg_re' (z: complex) : (neg z).re=-z.re := rfl
lemma proj_neg_im' (z: complex) : (neg z).im=-z.im := rfl
lemma proj_sub_re (z w : complex) : (z-w).re=z.re-w.re := rfl
lemma proj_sub_im (z w : complex) : (z-w).im=z.im-w.im := rfl
lemma proj_mul_re (z w: complex) : (z*w).re=z.re*w.re-z.im*w.im := rfl
lemma proj_mul_im (z w: complex) : (z*w).im=z.re*w.im+z.im*w.re := rfl
lemma proj_of_real_re (r:real) : (of_real r).re = r := rfl
lemma proj_of_real_im (r:real) : (of_real r).im = 0 := rfl
local attribute [simp] proj_zero_re proj_zero_im proj_one_re proj_one_im
local attribute [simp] proj_i_re proj_i_im proj_conj_re proj_conj_im
local attribute [simp] proj_add_re proj_add_im proj_neg_re proj_neg_im
local attribute [simp] proj_neg_re' proj_neg_im' proj_sub_re proj_sub_im
local attribute [simp] proj_mul_re proj_mul_im proj_of_real_re proj_of_real_im
lemma norm_squared_pos_of_nonzero (z : complex) (H : z ≠ 0) : norm_squared z > 0 :=
begin -- far more painful than it should be but I need it for inverses
suffices : z.re ≠ 0 ∨ z.im ≠ 0,
apply lt_of_le_of_ne,
exact add_nonneg (mul_self_nonneg _) (mul_self_nonneg _),
intro H2,
cases this with Hre Him,
exact Hre (eq_zero_of_mul_self_add_mul_self_eq_zero (eq.symm H2)),
unfold norm_squared at H2,rw [add_comm] at H2,
exact Him (eq_zero_of_mul_self_add_mul_self_eq_zero (eq.symm H2)),
have : ¬ (z.re = 0 ∧ z.im = 0),
intro H2,
exact H (eq_of_re_eq_and_im_eq z 0 H2),
cases classical.em (z.re = 0) with Hre_eq Hre_ne,
right,
intro H2,
apply this,
exact ⟨Hre_eq,H2⟩,
left,assumption,
end
-- I don't know how to set up
-- real.cast_zero etc
lemma of_real_injective : function.injective of_real :=
begin
intros x₁ x₂ H,
exact congr_arg complex.re H,
end
lemma of_real_zero : (0:complex) = of_real 0 := rfl
lemma of_real_one : (1:complex) = of_real 1 := rfl
-- amateurish definition of killer tactic but it works!
meta def crunch : tactic unit := do
`[intros],
`[rw [eq_iff_re_eq_and_im_eq]],
`[split;simp[add_mul,mul_add]]
lemma of_real_neg (r : real) : -of_real r = of_real (-r) := by crunch
lemma of_real_add (r s: real) : of_real r + of_real s = of_real (r+s) := by crunch
lemma of_real_sub (r s:real) : of_real r - of_real s = of_real(r-s) := by crunch
lemma of_real_mul (r s:real) : of_real r * of_real s = of_real (r*s) := by crunch
lemma of_real_inv (r:real) : (of_real r)⁻¹ = of_real (r⁻¹) :=
begin
rw [eq_iff_re_eq_and_im_eq],
split,
suffices : r/(r*r+0*0) = r⁻¹,
exact this,
cases classical.em (r=0) with Heq Hne,
-- this is taking longer than it should be.
rw [Heq],
simp [inv_zero,div_zero],
rw [mul_zero,add_zero,div_mul_left r Hne,inv_eq_one_div],
suffices : -0/(r*r+0*0) = 0,
exact this,
rw [neg_zero,zero_div],
end
lemma of_real_abs_squared (r:real) : norm_squared (of_real r) = (abs r)*(abs r) :=
begin
rw [abs_mul_abs_self],
suffices : r*r+0*0=r*r,
exact this,
simp,
end
lemma add_comm : ∀ (a b : ℂ), a + b = b + a := by crunch
-- I don't think I ever use these actually.
local attribute [simp] of_real_zero of_real_one of_real_neg of_real_add
local attribute [simp] of_real_sub of_real_mul of_real_inv
instance : discrete_field complex :=
{ discrete_field .
zero := 0,
add := (+),
neg := complex.neg,
zero_add := by crunch,
add_zero := by crunch,
add_comm := by crunch,
add_assoc := by crunch,
add_left_neg := by crunch,
one := 1,
mul := (*),
inv := has_inv.inv,
mul_one := by crunch,
one_mul := by crunch,
mul_comm := by crunch,
mul_assoc := by crunch,
left_distrib := by crunch,
right_distrib := by crunch,
zero_ne_one := begin
intro H,
suffices : (0:complex).re = (1:complex).re,
revert this,
apply zero_ne_one,
rw [←H],
end,
mul_inv_cancel := begin
intros z H,
have H2 : norm_squared z ≠ 0 := ne_of_gt (norm_squared_pos_of_nonzero z H),
apply eq_of_re_eq_and_im_eq,
unfold has_inv.inv inv,
rw [proj_mul_re,proj_mul_im],
split,
suffices : z.re*(z.re/norm_squared z) + -z.im*(-z.im/norm_squared z) = 1,
by simpa,
rw [←mul_div_assoc,←mul_div_assoc,neg_mul_neg,div_add_div_same],
unfold norm_squared at *,
exact div_self H2,
suffices : z.im * (z.re / norm_squared z) + z.re * (-z.im / norm_squared z) = 0,
by simpa,
rw [←mul_div_assoc,←mul_div_assoc,div_add_div_same],
simp [zero_div],
end,
inv_mul_cancel := begin -- let's try cut and pasting mul_inv_cancel proof
intros z H,
have H2 : norm_squared z ≠ 0 := ne_of_gt (norm_squared_pos_of_nonzero z H),
apply eq_of_re_eq_and_im_eq,
unfold has_inv.inv inv,
rw [proj_mul_re,proj_mul_im],
split,
suffices : z.re*(z.re/norm_squared z) + -z.im*(-z.im/norm_squared z) = 1,
by simpa,
rw [←mul_div_assoc,←mul_div_assoc,neg_mul_neg,div_add_div_same],
unfold norm_squared at *,
exact div_self H2,
suffices : z.im * (z.re / norm_squared z) + z.re * (-z.im / norm_squared z) = 0,
by simpa,
rw [←mul_div_assoc,←mul_div_assoc,div_add_div_same],
simp [zero_div],
end, -- it worked without modification!
-- Presumably I could just have proved mul_comm outside the verification that C is a field
-- and then used that too?
inv_zero := begin
unfold has_inv.inv inv add_comm_group.zero,
apply eq_of_re_eq_and_im_eq,
split;simp [zero_div],
end,
has_decidable_eq := by apply_instance }
-- instance : topological_ring complex := missing
end complex
|
c72ad969358b6093629aea3df22fa1fe727fd6a2 | a4673261e60b025e2c8c825dfa4ab9108246c32e | /stage0/src/Lean/Elab/Print.lean | 9b52a32e0b8539a5d13d70a7f89e6007998780a4 | [
"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 | 5,275 | 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.FoldConsts
import Lean.Elab.Command
namespace Lean.Elab.Command
private def throwUnknownId (id : Name) : CommandElabM Unit :=
throwError! "unknown identifier '{id}'"
private def lparamsToMessageData (lparams : List Name) : MessageData :=
match lparams with
| [] => ""
| u::us => do
let mut m : MessageData := ".{" ++ u
for u in us do
m := m ++ ", " ++ u
return m ++ "}"
private def mkHeader (kind : String) (id : Name) (lparams : List Name) (type : Expr) (isUnsafe : Bool) : CommandElabM MessageData := do
let m : MessageData := if isUnsafe then "unsafe " else ""
let m := if isProtected (← getEnv) id then m ++ "protected " else m
let (m, id) := match privateToUserName? id with
| some id => (m ++ "private ", id)
| none => (m, id)
let m := m ++ kind ++ " " ++ id ++ lparamsToMessageData lparams ++ " : " ++ type
pure m
private def printDefLike (kind : String) (id : Name) (lparams : List Name) (type : Expr) (value : Expr) (isUnsafe := false) : CommandElabM Unit := do
let m ← mkHeader kind id lparams type isUnsafe
let m := m ++ " :=" ++ Format.line ++ value
logInfo m
private def printAxiomLike (kind : String) (id : Name) (lparams : List Name) (type : Expr) (isUnsafe := false) : CommandElabM Unit := do
logInfo (← mkHeader kind id lparams type isUnsafe)
private def printQuot (kind : QuotKind) (id : Name) (lparams : List Name) (type : Expr) : CommandElabM Unit := do
printAxiomLike "Quotient primitive" id lparams type
private def printInduct (id : Name) (lparams : List Name) (nparams : Nat) (nindices : Nat) (type : Expr)
(ctors : List Name) (isUnsafe : Bool) : CommandElabM Unit := do
let mut m ← mkHeader "inductive" id lparams type isUnsafe
m := m ++ Format.line ++ "constructors:"
for ctor in ctors do
let cinfo ← getConstInfo ctor
m := m ++ Format.line ++ ctor ++ " : " ++ cinfo.type
logInfo m
private def printIdCore (id : Name) : CommandElabM Unit := do
match (← getEnv).find? id with
| ConstantInfo.axiomInfo { lparams := us, type := t, isUnsafe := u, .. } => printAxiomLike "axiom" id us t u
| ConstantInfo.defnInfo { lparams := us, type := t, value := v, isUnsafe := u, .. } => printDefLike "def" id us t v u
| ConstantInfo.thmInfo { lparams := us, type := t, value := v, .. } => printDefLike "theorem" id us t v
| ConstantInfo.opaqueInfo { lparams := us, type := t, isUnsafe := u, .. } => printAxiomLike "constant" id us t u
| ConstantInfo.quotInfo { kind := kind, lparams := us, type := t, .. } => printQuot kind id us t
| ConstantInfo.ctorInfo { lparams := us, type := t, isUnsafe := u, .. } => printAxiomLike "constructor" id us t u
| ConstantInfo.recInfo { lparams := us, type := t, isUnsafe := u, .. } => printAxiomLike "recursor" id us t u
| ConstantInfo.inductInfo { lparams := us, nparams := nparams, nindices := nindices, type := t, ctors := ctors, isUnsafe := u, .. } =>
printInduct id us nparams nindices t ctors u
| none => throwUnknownId id
private def printId (id : Name) : CommandElabM Unit := do
let cs ← resolveGlobalConst id
cs.forM printIdCore
@[builtinCommandElab «print»] def elabPrint : CommandElab := fun stx =>
let numArgs := stx.getNumArgs
if numArgs == 2 then
let arg := stx[1]
if arg.isIdent then
printId arg.getId
else match arg.isStrLit? with
| some val => logInfo val
| none => throwError "WIP"
else
throwError "invalid #print command"
namespace CollectAxioms
structure State :=
(visited : NameSet := {})
(axioms : Array Name := #[])
abbrev M := ReaderT Environment $ StateM State
partial def collect (c : Name) : M Unit := do
let collectExpr (e : Expr) : M Unit := e.getUsedConstants.forM collect
let s ← get
unless s.visited.contains c do
modify fun s => { s with visited := s.visited.insert c }
let env ← read
match env.find? c with
| some (ConstantInfo.axiomInfo _) => modify fun s => { s with axioms := s.axioms.push c }
| some (ConstantInfo.defnInfo v) => collectExpr v.type *> collectExpr v.value
| some (ConstantInfo.thmInfo v) => collectExpr v.type *> collectExpr v.value
| some (ConstantInfo.opaqueInfo v) => collectExpr v.type *> collectExpr v.value
| some (ConstantInfo.quotInfo _) => pure ()
| some (ConstantInfo.ctorInfo v) => collectExpr v.type
| some (ConstantInfo.recInfo v) => collectExpr v.type
| some (ConstantInfo.inductInfo v) => collectExpr v.type *> v.ctors.forM collect
| none => pure ()
end CollectAxioms
private def printAxiomsOf (constName : Name) : CommandElabM Unit := do
let env ← getEnv
let (_, s) := ((CollectAxioms.collect constName).run env).run {}
if s.axioms.isEmpty then
logInfo m!"'{constName}' does not depend on any axioms"
else
logInfo m!"'{constName}' depends on axioms: {s.axioms.toList}"
@[builtinCommandElab «printAxioms»] def elabPrintAxioms : CommandElab := fun stx => do
let id := stx[2].getId
let cs ← resolveGlobalConst id
cs.forM printAxiomsOf
end Lean.Elab.Command
|
38db554b78b4d7a372503c2e86ba89c56987bc9a | 2a6c509a979150555f6f8a010f76e9398dd01e09 | /src/binary_tree.lean | 67730aa6114db9f9203ce19b47ae502e59948bb5 | [] | no_license | VArtem/lean-catalan | fa053f8262b471f45ac7c3706f313ec38c831b72 | 7cf17acf3bdddddf8819dc3ff23774bfaa3f5d92 | refs/heads/main | 1,689,556,449,322 | 1,630,267,370,000 | 1,630,267,370,000 | 400,530,852 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,112 | lean | import catalan
open finset catalan
@[derive decidable_eq]
inductive binary_tree
| empty : binary_tree
| branch : binary_tree → binary_tree → binary_tree
namespace binary_tree
def vertices : binary_tree → ℕ
| empty := 0
| (branch l r) := (vertices l) + (vertices r) + 1
@[simp] def vertices_Empty : empty.vertices = 0 := rfl
@[simp] def vertices_Branch (l r : binary_tree) : (branch l r).vertices = l.vertices + r.vertices + 1 := rfl
lemma eq_Empty_of_vertices_zero {t : binary_tree} (h : t.vertices = 0) : t = empty :=
begin
cases t with l r,
{ refl },
{ rw [vertices_Branch] at h, simpa only using h },
end
lemma eq_Branch_of_vertices_succ {n : ℕ} {t : binary_tree} (h : t.vertices = n.succ) :
∃ l r, t = branch l r :=
begin
cases t with l r,
{ rw [vertices_Empty] at h, simpa only using h},
{ use [l, r] },
end
def all_trees : Π (n : ℕ), finset binary_tree
| 0 := ({ empty } : finset binary_tree)
| (n + 1) :=
finset.bUnion (finset.nat.antidiagonal n) $
λ p, if h : p.1 + p.2 = n then
let h₁ : p.1 < n + 1 := nat.lt_succ_of_add_right_eq h in
let h₂ : p.2 < n + 1 := nat.lt_succ_of_add_left_eq h in
finset.image
(λ i : binary_tree × binary_tree, branch i.1 i.2)
(finset.product (all_trees p.1) (all_trees p.2))
else ∅
@[simp] lemma all_trees_zero : all_trees 0 = ({ empty } : finset binary_tree) := by rw all_trees
@[simp] lemma all_trees_succ {n : ℕ} : all_trees n.succ =
(nat.antidiagonal n).bUnion
(λ p, finset.image (λ i : binary_tree × binary_tree, branch i.1 i.2) $ finset.product (all_trees p.1) (all_trees p.2)) :=
begin
-- TODO: extract as bUnion_congr or something
rw [all_trees],
ext t,
simp only [mem_bUnion, mem_image, dite_eq_ite, exists_prop, nat.mem_antidiagonal, prod.exists, mem_product],
split,
{
rintro ⟨a, b, rfl, h⟩,
use [a, b, rfl],
simpa only [mem_image, exists_prop, if_pos rfl, prod.exists, mem_product] using h,
}, {
rintro ⟨a, b, rfl, h⟩,
use [a, b, rfl],
rw if_pos rfl,
simpa only [mem_image, exists_prop, prod.exists, mem_product] using h,
}
end
def mem_all_trees {t : binary_tree} : t ∈ all_trees t.vertices :=
begin
induction t with a b iha ihb, {
simp only [vertices_Empty, mem_singleton, all_trees_zero],
}, {
simp only [mem_bUnion, mem_image, exists_prop, vertices_Branch, exists_eq_right_right, exists_eq_right, all_trees_succ,
nat.mem_antidiagonal, prod.exists, mem_product],
use [a.vertices, b.vertices, rfl],
exact ⟨iha, ihb⟩,
}
end
def vertices_eq_of_mem_all_trees {t : binary_tree} {n : ℕ} (h : t ∈ all_trees n) : t.vertices = n :=
begin
induction t with a b iha ihb generalizing n, {
cases n, {
exact vertices_Empty,
}, {
simp [all_trees] at h,
rcases h with ⟨a, b, rfl, h⟩,
simpa only [if_pos rfl, mem_image, if_true, exists_false] using h,
}
}, {
cases n, {
simpa using h,
}, {
simp [all_trees] at h,
rcases h with ⟨x, y, rfl, h⟩,
simp only [mem_image, exists_prop, if_true, exists_eq_right_right, eq_self_iff_true, exists_eq_right, prod.exists, mem_product] at h,
rw [←iha h.1, ←ihb h.2],
exact vertices_Branch _ _,
}
}
end
end binary_tree
open binary_tree
lemma all_trees_card_eq_catalan {n} : (all_trees n).card = catalan n :=
begin
apply nat.strong_induction_on n,
clear n,
rintro n ih,
cases n, {
rw [catalan_zero, all_trees_zero, card_singleton],
}, {
simp only [catalan_succ, all_trees_succ],
rw [card_bUnion], {
apply sum_congr rfl,
rintro ⟨a, b⟩ h,
rw nat.mem_antidiagonal at h,
rw [card_image_of_injective, card_product],
{
rw [ih _ $ nat.lt_succ_of_add_right_eq h],
rw [ih _ $ nat.lt_succ_of_add_left_eq h],
}, {
rintro a b,
simp only [and_imp],
exact prod.ext,
},
}, {
rintro x - y - hneq k hk,
simp only [mem_image, exists_prop, inf_eq_inter, mem_inter, prod.exists, mem_product] at hk,
rcases hk with ⟨⟨a1, b1, ha1, hc1⟩, ⟨a2, b2, ha2, rfl⟩⟩,
rcases branch.inj hc1 with ⟨rfl, rfl⟩,
apply hneq,
ext, {
rw [←vertices_eq_of_mem_all_trees ha1.1, ←vertices_eq_of_mem_all_trees ha2.1],
}, {
rw [←vertices_eq_of_mem_all_trees ha1.2, ←vertices_eq_of_mem_all_trees ha2.2],
},
}
}
end
def sized_binary_tree (n : ℕ) := {t : binary_tree // vertices t = n}
@[simp] lemma sized_binary_tree_def {n : ℕ} : (sized_binary_tree n) = {t : binary_tree // vertices t = n} := rfl
instance {n : ℕ} : fintype (sized_binary_tree n) :=
⟨(all_trees n).subtype (λ t, t.vertices = n),
begin
rintro ⟨t, rfl⟩,
rw mem_subtype,
exact mem_all_trees,
end⟩
lemma catalan_eq_TreeN_card {n : ℕ} : fintype.card (sized_binary_tree n) = catalan n :=
begin
rw [←all_trees_card_eq_catalan],
apply fintype.card_of_subtype,
intro x,
split, {
exact vertices_eq_of_mem_all_trees,
}, {
rintro rfl,
exact mem_all_trees,
}
end |
19e646dbaed34f7795ff9e6816fa6c1056390893 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Data/HashMap.lean | 99660540ba4bee67075b7e09cb9e969aad5d47a5 | [
"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 | 9,264 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Lean.Data.AssocList
namespace Lean
def HashMapBucket (α : Type u) (β : Type v) :=
{ b : Array (AssocList α β) // b.size.isPowerOfTwo }
def HashMapBucket.update {α : Type u} {β : Type v} (data : HashMapBucket α β) (i : USize) (d : AssocList α β) (h : i.toNat < data.val.size) : HashMapBucket α β :=
⟨ data.val.uset i d h,
by erw [Array.size_set]; apply data.property ⟩
structure HashMapImp (α : Type u) (β : Type v) where
size : Nat
buckets : HashMapBucket α β
private def numBucketsForCapacity (capacity : Nat) : Nat :=
-- a "load factor" of 0.75 is the usual standard for hash maps
capacity * 4 / 3
def mkHashMapImp {α : Type u} {β : Type v} (capacity := 8) : HashMapImp α β :=
{ size := 0
buckets :=
⟨mkArray (numBucketsForCapacity capacity).nextPowerOfTwo AssocList.nil,
by simp; apply Nat.isPowerOfTwo_nextPowerOfTwo⟩ }
namespace HashMapImp
variable {α : Type u} {β : Type v}
/- Remark: we use a C implementation because this function is performance critical. -/
@[extern "lean_hashmap_mk_idx"]
private def mkIdx {sz : Nat} (hash : UInt64) (h : sz.isPowerOfTwo) : { u : USize // u.toNat < sz } :=
-- TODO: avoid `if` in the reference implementation
let u := hash.toUSize &&& (sz.toUSize - 1)
if h' : u.toNat < sz then
⟨u, h'⟩
else
⟨0, by simp [USize.toNat, OfNat.ofNat, USize.ofNat, Fin.ofNat']; apply Nat.pos_of_isPowerOfTwo h⟩
@[inline] def reinsertAux (hashFn : α → UInt64) (data : HashMapBucket α β) (a : α) (b : β) : HashMapBucket α β :=
let ⟨i, h⟩ := mkIdx (hashFn a) data.property
data.update i (AssocList.cons a b data.val[i]) h
@[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (d : δ) (f : δ → α → β → m δ) : m δ :=
data.val.foldlM (init := d) fun d b => b.foldlM f d
@[inline] def foldBuckets {δ : Type w} (data : HashMapBucket α β) (d : δ) (f : δ → α → β → δ) : δ :=
Id.run $ foldBucketsM data d f
@[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (d : δ) (h : HashMapImp α β) : m δ :=
foldBucketsM h.buckets d f
@[inline] def fold {δ : Type w} (f : δ → α → β → δ) (d : δ) (m : HashMapImp α β) : δ :=
foldBuckets m.buckets d f
@[inline] def forBucketsM {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (f : α → β → m PUnit) : m PUnit :=
data.val.forM fun b => b.forM f
@[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMapImp α β) : m PUnit :=
forBucketsM h.buckets f
def findEntry? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option (α × β) :=
match m with
| ⟨_, buckets⟩ =>
let ⟨i, h⟩ := mkIdx (hash a) buckets.property
buckets.val[i].findEntry? a
def find? [beq : BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option β :=
match m with
| ⟨_, buckets⟩ =>
let ⟨i, h⟩ := mkIdx (hash a) buckets.property
buckets.val[i].find? a
def contains [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Bool :=
match m with
| ⟨_, buckets⟩ =>
let ⟨i, h⟩ := mkIdx (hash a) buckets.property
buckets.val[i].contains a
def moveEntries [Hashable α] (i : Nat) (source : Array (AssocList α β)) (target : HashMapBucket α β) : HashMapBucket α β :=
if h : i < source.size then
let idx : Fin source.size := ⟨i, h⟩
let es : AssocList α β := source.get idx
-- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl
let source := source.set idx AssocList.nil
let target := es.foldl (reinsertAux hash) target
moveEntries (i+1) source target
else target
termination_by _ i source _ => source.size - i
def expand [Hashable α] (size : Nat) (buckets : HashMapBucket α β) : HashMapImp α β :=
let bucketsNew : HashMapBucket α β := ⟨
mkArray (buckets.val.size * 2) AssocList.nil,
by simp; apply Nat.mul2_isPowerOfTwo_of_isPowerOfTwo buckets.property
⟩
{ size := size,
buckets := moveEntries 0 buckets.val bucketsNew }
@[inline] def insert [beq : BEq α] [Hashable α] (m : HashMapImp α β) (a : α) (b : β) : HashMapImp α β × Bool :=
match m with
| ⟨size, buckets⟩ =>
let ⟨i, h⟩ := mkIdx (hash a) buckets.property
let bkt := buckets.val[i]
if bkt.contains a then
(⟨size, buckets.update i (bkt.replace a b) h⟩, true)
else
let size' := size + 1
let buckets' := buckets.update i (AssocList.cons a b bkt) h
if numBucketsForCapacity size' ≤ buckets.val.size then
({ size := size', buckets := buckets' }, false)
else
(expand size' buckets', false)
def erase [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : HashMapImp α β :=
match m with
| ⟨ size, buckets ⟩ =>
let ⟨i, h⟩ := mkIdx (hash a) buckets.property
let bkt := buckets.val[i]
if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩
else m
inductive WellFormed [BEq α] [Hashable α] : HashMapImp α β → Prop where
| mkWff : ∀ n, WellFormed (mkHashMapImp n)
| insertWff : ∀ m a b, WellFormed m → WellFormed (insert m a b |>.1)
| eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a)
end HashMapImp
def HashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] :=
{ m : HashMapImp α β // m.WellFormed }
open Lean.HashMapImp
def mkHashMap {α : Type u} {β : Type v} [BEq α] [Hashable α] (capacity := 8) : HashMap α β :=
⟨ mkHashMapImp capacity, WellFormed.mkWff capacity ⟩
namespace HashMap
instance [BEq α] [Hashable α] : Inhabited (HashMap α β) where
default := mkHashMap
instance [BEq α] [Hashable α] : EmptyCollection (HashMap α β) := ⟨mkHashMap⟩
@[inline] def empty [BEq α] [Hashable α] : HashMap α β :=
mkHashMap
variable {α : Type u} {β : Type v} {_ : BEq α} {_ : Hashable α}
def insert (m : HashMap α β) (a : α) (b : β) : HashMap α β :=
match m with
| ⟨ m, hw ⟩ =>
match h:m.insert a b with
| (m', _) => ⟨ m', by have aux := WellFormed.insertWff m a b hw; rw [h] at aux; assumption ⟩
/-- Similar to `insert`, but also returns a Boolean flad indicating whether an existing entry has been replaced with `a -> b`. -/
def insert' (m : HashMap α β) (a : α) (b : β) : HashMap α β × Bool :=
match m with
| ⟨ m, hw ⟩ =>
match h:m.insert a b with
| (m', replaced) => (⟨ m', by have aux := WellFormed.insertWff m a b hw; rw [h] at aux; assumption ⟩, replaced)
@[inline] def erase (m : HashMap α β) (a : α) : HashMap α β :=
match m with
| ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩
@[inline] def findEntry? (m : HashMap α β) (a : α) : Option (α × β) :=
match m with
| ⟨ m, _ ⟩ => m.findEntry? a
@[inline] def find? (m : HashMap α β) (a : α) : Option β :=
match m with
| ⟨ m, _ ⟩ => m.find? a
@[inline] def findD (m : HashMap α β) (a : α) (b₀ : β) : β :=
(m.find? a).getD b₀
@[inline] def find! [Inhabited β] (m : HashMap α β) (a : α) : β :=
match m.find? a with
| some b => b
| none => panic! "key is not in the map"
instance : GetElem (HashMap α β) α (Option β) fun _ _ => True where
getElem m k _ := m.find? k
@[inline] def contains (m : HashMap α β) (a : α) : Bool :=
match m with
| ⟨ m, _ ⟩ => m.contains a
@[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (init : δ) (h : HashMap α β) : m δ :=
match h with
| ⟨ h, _ ⟩ => h.foldM f init
@[inline] def fold {δ : Type w} (f : δ → α → β → δ) (init : δ) (m : HashMap α β) : δ :=
match m with
| ⟨ m, _ ⟩ => m.fold f init
@[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMap α β) : m PUnit :=
match h with
| ⟨ h, _ ⟩ => h.forM f
@[inline] def size (m : HashMap α β) : Nat :=
match m with
| ⟨ {size := sz, ..}, _ ⟩ => sz
@[inline] def isEmpty (m : HashMap α β) : Bool :=
m.size = 0
def toList (m : HashMap α β) : List (α × β) :=
m.fold (init := []) fun r k v => (k, v)::r
def toArray (m : HashMap α β) : Array (α × β) :=
m.fold (init := #[]) fun r k v => r.push (k, v)
def numBuckets (m : HashMap α β) : Nat :=
m.val.buckets.val.size
/-- Builds a `HashMap` from a list of key-value pairs. Values of duplicated keys are replaced by their respective last occurrences. -/
def ofList (l : List (α × β)) : HashMap α β :=
l.foldl (init := HashMap.empty) (fun m p => m.insert p.fst p.snd)
/-- Variant of `ofList` which accepts a function that combines values of duplicated keys. -/
def ofListWith (l : List (α × β)) (f : β → β → β) : HashMap α β :=
l.foldl (init := HashMap.empty)
(fun m p =>
match m.find? p.fst with
| none => m.insert p.fst p.snd
| some v => m.insert p.fst $ f v p.snd)
|
157f4c33cb7dc30cc878802ba0b2af8df585d5d1 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/topology/instances/ennreal.lean | d184869990f07eb3f6143f6c8e8d344869d8fe93 | [
"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 | 50,384 | 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 topology.instances.nnreal
import topology.algebra.ordered.liminf_limsup
/-!
# Extended non-negative reals
-/
noncomputable theory
open classical set filter metric
open_locale classical topological_space ennreal nnreal big_operators filter
variables {α : Type*} {β : Type*} {γ : Type*}
namespace ennreal
variables {a b c d : ℝ≥0∞} {r p q : ℝ≥0}
variables {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : set ℝ≥0∞}
section topological_space
open topological_space
/-- Topology on `ℝ≥0∞`.
Note: this is different from the `emetric_space` topology. The `emetric_space` topology has
`is_open {⊤}`, while this topology doesn't have singleton elements. -/
instance : topological_space ℝ≥0∞ := preorder.topology ℝ≥0∞
instance : order_topology ℝ≥0∞ := ⟨rfl⟩
instance : t2_space ℝ≥0∞ := by apply_instance -- short-circuit type class inference
instance : second_countable_topology ℝ≥0∞ :=
⟨⟨⋃q ≥ (0:ℚ), {{a : ℝ≥0∞ | a < real.to_nnreal q}, {a : ℝ≥0∞ | ↑(real.to_nnreal q) < a}},
(countable_encodable _).bUnion $ assume a ha, (countable_singleton _).insert _,
le_antisymm
(le_generate_from $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt})
(le_generate_from $ λ s h, begin
rcases h with ⟨a, hs | hs⟩;
[ rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ a < real.to_nnreal q}, {b | ↑(real.to_nnreal q) < b},
from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn a b, and_assoc]),
rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ ↑(real.to_nnreal q) < a}, {b | b < ↑(real.to_nnreal q)},
from set.ext (assume b,
by simp [hs, @ennreal.lt_iff_exists_rat_btwn b a, and_comm, and_assoc])];
{ apply is_open_Union, intro q,
apply is_open_Union, intro hq,
exact generate_open.basic _ (mem_bUnion hq.1 $ by simp) }
end)⟩⟩
lemma embedding_coe : embedding (coe : ℝ≥0 → ℝ≥0∞) :=
⟨⟨begin
refine le_antisymm _ _,
{ rw [@order_topology.topology_eq_generate_intervals ℝ≥0∞ _,
← coinduced_le_iff_le_induced],
refine le_generate_from (assume s ha, _),
rcases ha with ⟨a, rfl | rfl⟩,
show is_open {b : ℝ≥0 | a < ↑b},
{ cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] },
show is_open {b : ℝ≥0 | ↑b < a},
{ cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } },
{ rw [@order_topology.topology_eq_generate_intervals ℝ≥0 _],
refine le_generate_from (assume s ha, _),
rcases ha with ⟨a, rfl | rfl⟩,
exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩,
exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ }
end⟩,
assume a b, coe_eq_coe.1⟩
lemma is_open_ne_top : is_open {a : ℝ≥0∞ | a ≠ ⊤} := is_open_ne
lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio}
lemma open_embedding_coe : open_embedding (coe : ℝ≥0 → ℝ≥0∞) :=
⟨embedding_coe, by { convert is_open_ne_top, ext (x|_); simp [none_eq_top, some_eq_coe] }⟩
lemma coe_range_mem_nhds : range (coe : ℝ≥0 → ℝ≥0∞) ∈ 𝓝 (r : ℝ≥0∞) :=
is_open.mem_nhds open_embedding_coe.open_range $ mem_range_self _
@[norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {a : ℝ≥0} :
tendsto (λa, (m a : ℝ≥0∞)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) :=
embedding_coe.tendsto_nhds_iff.symm
lemma continuous_coe : continuous (coe : ℝ≥0 → ℝ≥0∞) :=
embedding_coe.continuous
lemma continuous_coe_iff {α} [topological_space α] {f : α → ℝ≥0} :
continuous (λa, (f a : ℝ≥0∞)) ↔ continuous f :=
embedding_coe.continuous_iff.symm
lemma nhds_coe {r : ℝ≥0} : 𝓝 (r : ℝ≥0∞) = (𝓝 r).map coe :=
(open_embedding_coe.map_nhds_eq r).symm
lemma tendsto_nhds_coe_iff {α : Type*} {l : filter α} {x : ℝ≥0} {f : ℝ≥0∞ → α} :
tendsto f (𝓝 ↑x) l ↔ tendsto (f ∘ coe : ℝ≥0 → α) (𝓝 x) l :=
show _ ≤ _ ↔ _ ≤ _, by rw [nhds_coe, filter.map_map]
lemma continuous_at_coe_iff {α : Type*} [topological_space α] {x : ℝ≥0} {f : ℝ≥0∞ → α} :
continuous_at f (↑x) ↔ continuous_at (f ∘ coe : ℝ≥0 → α) x :=
tendsto_nhds_coe_iff
lemma nhds_coe_coe {r p : ℝ≥0} :
𝓝 ((r : ℝ≥0∞), (p : ℝ≥0∞)) = (𝓝 (r, p)).map (λp:ℝ≥0×ℝ≥0, (p.1, p.2)) :=
((open_embedding_coe.prod open_embedding_coe).map_nhds_eq (r, p)).symm
lemma continuous_of_real : continuous ennreal.of_real :=
(continuous_coe_iff.2 continuous_id).comp nnreal.continuous_of_real
lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (𝓝 a)) :
tendsto (λa, ennreal.of_real (m a)) f (𝓝 (ennreal.of_real a)) :=
tendsto.comp (continuous.tendsto continuous_of_real _) h
lemma tendsto_to_nnreal {a : ℝ≥0∞} (ha : a ≠ ⊤) :
tendsto ennreal.to_nnreal (𝓝 a) (𝓝 a.to_nnreal) :=
begin
lift a to ℝ≥0 using ha,
rw [nhds_coe, tendsto_map'_iff],
exact tendsto_id
end
lemma continuous_on_to_nnreal : continuous_on ennreal.to_nnreal {a | a ≠ ∞} :=
λ a ha, continuous_at.continuous_within_at (tendsto_to_nnreal ha)
lemma tendsto_to_real {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_real (𝓝 a) (𝓝 a.to_real) :=
nnreal.tendsto_coe.2 $ tendsto_to_nnreal ha
/-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/
def ne_top_homeomorph_nnreal : {a | a ≠ ∞} ≃ₜ ℝ≥0 :=
{ continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_nnreal,
continuous_inv_fun := continuous_subtype_mk _ continuous_coe,
.. ne_top_equiv_nnreal }
/-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/
def lt_top_homeomorph_nnreal : {a | a < ∞} ≃ₜ ℝ≥0 :=
by refine (homeomorph.set_congr $ set.ext $ λ x, _).trans ne_top_homeomorph_nnreal;
simp only [mem_set_of_eq, lt_top_iff_ne_top]
lemma nhds_top : 𝓝 ∞ = ⨅ a ≠ ∞, 𝓟 (Ioi a) :=
nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi]
lemma nhds_top' : 𝓝 ∞ = ⨅ r : ℝ≥0, 𝓟 (Ioi r) :=
nhds_top.trans $ infi_ne_top _
lemma tendsto_nhds_top_iff_nnreal {m : α → ℝ≥0∞} {f : filter α} :
tendsto m f (𝓝 ⊤) ↔ ∀ x : ℝ≥0, ∀ᶠ a in f, ↑x < m a :=
by simp only [nhds_top', tendsto_infi, tendsto_principal, mem_Ioi]
lemma tendsto_nhds_top_iff_nat {m : α → ℝ≥0∞} {f : filter α} :
tendsto m f (𝓝 ⊤) ↔ ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a :=
tendsto_nhds_top_iff_nnreal.trans ⟨λ h n, by simpa only [ennreal.coe_nat] using h n,
λ h x, let ⟨n, hn⟩ := exists_nat_gt x in
(h n).mono (λ y, lt_trans $ by rwa [← ennreal.coe_nat, coe_lt_coe])⟩
lemma tendsto_nhds_top {m : α → ℝ≥0∞} {f : filter α}
(h : ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a) : tendsto m f (𝓝 ⊤) :=
tendsto_nhds_top_iff_nat.2 h
lemma tendsto_nat_nhds_top : tendsto (λ n : ℕ, ↑n) at_top (𝓝 ∞) :=
tendsto_nhds_top $ λ n, mem_at_top_sets.2
⟨n+1, λ m hm, ennreal.coe_nat_lt_coe_nat.2 $ nat.lt_of_succ_le hm⟩
@[simp, norm_cast] lemma tendsto_coe_nhds_top {f : α → ℝ≥0} {l : filter α} :
tendsto (λ x, (f x : ℝ≥0∞)) l (𝓝 ∞) ↔ tendsto f l at_top :=
by rw [tendsto_nhds_top_iff_nnreal, at_top_basis_Ioi.tendsto_right_iff];
[simp, apply_instance, apply_instance]
lemma nhds_zero : 𝓝 (0 : ℝ≥0∞) = ⨅a ≠ 0, 𝓟 (Iio a) :=
nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio]
@[instance] lemma nhds_within_Ioi_coe_ne_bot {r : ℝ≥0} : (𝓝[Ioi r] (r : ℝ≥0∞)).ne_bot :=
nhds_within_Ioi_self_ne_bot' ennreal.coe_lt_top
@[instance] lemma nhds_within_Ioi_zero_ne_bot : (𝓝[Ioi 0] (0 : ℝ≥0∞)).ne_bot :=
nhds_within_Ioi_coe_ne_bot
-- using Icc because
-- • don't have 'Ioo (x - ε) (x + ε) ∈ 𝓝 x' unless x > 0
-- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not
lemma Icc_mem_nhds : x ≠ ⊤ → 0 < ε → Icc (x - ε) (x + ε) ∈ 𝓝 x :=
begin
assume xt ε0, rw _root_.mem_nhds_iff,
by_cases x0 : x = 0,
{ use Iio (x + ε),
have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt,
use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ },
{ use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self,
exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ }
end
lemma nhds_of_ne_top : x ≠ ⊤ → 𝓝 x = ⨅ε > 0, 𝓟 (Icc (x - ε) (x + ε)) :=
begin
assume xt, refine le_antisymm _ _,
-- first direction
simp only [le_infi_iff, le_principal_iff], assume ε ε0, exact Icc_mem_nhds xt ε0,
-- second direction
rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _),
simp only [mem_set_of_eq] at hs, rcases hs with ⟨xs, ⟨a, ha⟩⟩,
cases ha,
{ rw ha at *,
rcases exists_between xs with ⟨b, ⟨ab, bx⟩⟩,
have xb_pos : x - b > 0 := zero_lt_sub_iff_lt.2 bx,
have xxb : x - (x - b) = b := sub_sub_cancel (by rwa lt_top_iff_ne_top) (le_of_lt bx),
refine infi_le_of_le (x - b) (infi_le_of_le xb_pos _),
simp only [mem_principal_sets, le_principal_iff],
assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ },
{ rw ha at *,
rcases exists_between xs with ⟨b, ⟨xb, ba⟩⟩,
have bx_pos : b - x > 0 := zero_lt_sub_iff_lt.2 xb,
have xbx : x + (b - x) = b := add_sub_cancel_of_le (le_of_lt xb),
refine infi_le_of_le (b - x) (infi_le_of_le bx_pos _),
simp only [mem_principal_sets, le_principal_iff],
assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba },
end
/-- Characterization of neighborhoods for `ℝ≥0∞` numbers. See also `tendsto_order`
for a version with strict inequalities. -/
protected theorem tendsto_nhds {f : filter α} {u : α → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, (u x) ∈ Icc (a - ε) (a + ε) :=
by simp only [nhds_of_ne_top ha, tendsto_infi, tendsto_principal, mem_Icc]
protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} {a : ℝ≥0∞}
(ha : a ≠ ⊤) : tendsto f at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) :=
by simp only [ennreal.tendsto_nhds ha, mem_at_top_sets, mem_set_of_eq, filter.eventually]
instance : has_continuous_add ℝ≥0∞ :=
begin
refine ⟨continuous_iff_continuous_at.2 _⟩,
rintro ⟨(_|a), b⟩,
{ exact tendsto_nhds_top_mono' continuous_at_fst (λ p, le_add_right le_rfl) },
rcases b with (_|b),
{ exact tendsto_nhds_top_mono' continuous_at_snd (λ p, le_add_left le_rfl) },
simp only [continuous_at, some_eq_coe, nhds_coe_coe, ← coe_add, tendsto_map'_iff, (∘),
tendsto_coe, tendsto_add]
end
protected lemma tendsto_at_top_zero [hβ : nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} :
filter.at_top.tendsto f (𝓝 0) ↔ ∀ ε > 0, ∃ N, ∀ n ≥ N, f n ≤ ε :=
begin
rw ennreal.tendsto_at_top zero_ne_top,
{ simp_rw [set.mem_Icc, zero_add, zero_sub, zero_le _, true_and], },
{ exact hβ, },
end
protected lemma tendsto_mul (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) :
tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 (a, b)) (𝓝 (a * b)) :=
have ht : ∀b:ℝ≥0∞, b ≠ 0 → tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 ((⊤:ℝ≥0∞), b)) (𝓝 ⊤),
begin
refine assume b hb, tendsto_nhds_top_iff_nnreal.2 $ assume n, _,
rcases lt_iff_exists_nnreal_btwn.1 (pos_iff_ne_zero.2 hb) with ⟨ε, hε, hεb⟩,
replace hε : 0 < ε, from coe_pos.1 hε,
filter_upwards [prod_is_open.mem_nhds (lt_mem_nhds $ @coe_lt_top (n / ε)) (lt_mem_nhds hεb)],
rintros ⟨a₁, a₂⟩ ⟨h₁, h₂⟩,
dsimp at h₁ h₂ ⊢,
rw [← div_mul_cancel n hε.ne', coe_mul],
exact mul_lt_mul h₁ h₂
end,
begin
cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] },
cases b, {
simp [none_eq_top] at ha,
simp [*, nhds_swap (a : ℝ≥0∞) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘),
mul_comm] },
simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)],
simp only [coe_mul.symm, tendsto_coe, tendsto_mul]
end
protected lemma tendsto.mul {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞}
(hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) :
tendsto (λa, ma a * mb a) f (𝓝 (a * b)) :=
show tendsto ((λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a * b)), from
tendsto.comp (ennreal.tendsto_mul ha hb) (hma.prod_mk_nhds hmb)
protected lemma tendsto.const_mul {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞}
(hm : tendsto m f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (𝓝 (a * b)) :=
by_cases
(assume : a = 0, by simp [this, tendsto_const_nhds])
(assume ha : a ≠ 0, ennreal.tendsto.mul tendsto_const_nhds (or.inl ha) hm hb)
protected lemma tendsto.mul_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞}
(hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) : tendsto (λx, m x * b) f (𝓝 (a * b)) :=
by simpa only [mul_comm] using ennreal.tendsto.const_mul hm ha
protected lemma continuous_at_const_mul {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) :
continuous_at ((*) a) b :=
tendsto.const_mul tendsto_id h.symm
protected lemma continuous_at_mul_const {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) :
continuous_at (λ x, x * a) b :=
tendsto.mul_const tendsto_id h.symm
protected lemma continuous_const_mul {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous ((*) a) :=
continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_const_mul (or.inl ha)
protected lemma continuous_mul_const {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous (λ x, x * a) :=
continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_mul_const (or.inl ha)
lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0∞} (h : ∀ a < 1, a * x ≤ y) : x ≤ y :=
begin
have : tendsto (* x) (𝓝[Iio 1] 1) (𝓝 (1 * x)) :=
(ennreal.continuous_at_mul_const (or.inr one_ne_zero)).mono_left inf_le_left,
rw one_mul at this,
haveI : (𝓝[Iio 1] (1 : ℝ≥0∞)).ne_bot := nhds_within_Iio_self_ne_bot' ennreal.zero_lt_one,
exact le_of_tendsto this (eventually_nhds_within_iff.2 $ eventually_of_forall h)
end
lemma infi_mul_left' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞}
(h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) :
(⨅ i, a * f i) = a * ⨅ i, f i :=
begin
by_cases H : a = ⊤ ∧ (⨅ i, f i) = 0,
{ rcases h H.1 H.2 with ⟨i, hi⟩,
rw [H.2, mul_zero, ← bot_eq_zero, infi_eq_bot],
exact λ b hb, ⟨i, by rwa [hi, mul_zero, ← bot_eq_zero]⟩ },
{ rw not_and_distrib at H,
by_cases hι : nonempty ι,
{ resetI,
exact (map_infi_of_continuous_at_of_monotone' (ennreal.continuous_at_const_mul H)
ennreal.mul_left_mono).symm },
{ rw [infi_of_empty hι, infi_of_empty hι, mul_top, if_neg],
exact mt h0 hι } }
end
lemma infi_mul_left {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞}
(h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) :
(⨅ i, a * f i) = a * ⨅ i, f i :=
infi_mul_left' h (λ _, ‹nonempty ι›)
lemma infi_mul_right' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞}
(h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) :
(⨅ i, f i * a) = (⨅ i, f i) * a :=
by simpa only [mul_comm a] using infi_mul_left' h h0
lemma infi_mul_right {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞}
(h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) :
(⨅ i, f i * a) = (⨅ i, f i) * a :=
infi_mul_right' h (λ _, ‹nonempty ι›)
protected lemma continuous_inv : continuous (has_inv.inv : ℝ≥0∞ → ℝ≥0∞) :=
continuous_iff_continuous_at.2 $ λ a, tendsto_order.2
⟨begin
assume b hb,
simp only [@ennreal.lt_inv_iff_lt_inv b],
exact gt_mem_nhds (ennreal.lt_inv_iff_lt_inv.1 hb),
end,
begin
assume b hb,
simp only [gt_iff_lt, @ennreal.inv_lt_iff_inv_lt _ b],
exact lt_mem_nhds (ennreal.inv_lt_iff_inv_lt.1 hb)
end⟩
@[simp] protected lemma tendsto_inv_iff {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} :
tendsto (λ x, (m x)⁻¹) f (𝓝 a⁻¹) ↔ tendsto m f (𝓝 a) :=
⟨λ h, by simpa only [function.comp, ennreal.inv_inv]
using (ennreal.continuous_inv.tendsto a⁻¹).comp h,
(ennreal.continuous_inv.tendsto a).comp⟩
protected lemma tendsto.div {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞}
(hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) :
tendsto (λa, ma a / mb a) f (𝓝 (a / b)) :=
by { apply tendsto.mul hma _ (ennreal.tendsto_inv_iff.2 hmb) _; simp [ha, hb] }
protected lemma tendsto.const_div {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞}
(hm : tendsto m f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λb, a / m b) f (𝓝 (a / b)) :=
by { apply tendsto.const_mul (ennreal.tendsto_inv_iff.2 hm), simp [hb] }
protected lemma tendsto.div_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞}
(hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) : tendsto (λx, m x / b) f (𝓝 (a / b)) :=
by { apply tendsto.mul_const hm, simp [ha] }
protected lemma tendsto_inv_nat_nhds_zero : tendsto (λ n : ℕ, (n : ℝ≥0∞)⁻¹) at_top (𝓝 0) :=
ennreal.inv_top ▸ ennreal.tendsto_inv_iff.2 tendsto_nat_nhds_top
lemma bsupr_add {ι} {s : set ι} (hs : s.nonempty) {f : ι → ℝ≥0∞} :
(⨆ i ∈ s, f i) + a = ⨆ i ∈ s, f i + a :=
begin
simp only [← Sup_image], symmetry,
rw [image_comp (+ a)],
refine is_lub.Sup_eq ((is_lub_Sup $ f '' s).is_lub_of_tendsto _ (hs.image _) _),
exacts [λ x _ y _ hxy, add_le_add hxy le_rfl,
tendsto.add (tendsto_id' inf_le_left) tendsto_const_nhds]
end
lemma Sup_add {s : set ℝ≥0∞} (hs : s.nonempty) : Sup s + a = ⨆b∈s, b + a :=
by rw [Sup_eq_supr, bsupr_add hs]
lemma supr_add {ι : Sort*} {s : ι → ℝ≥0∞} [h : nonempty ι] : supr s + a = ⨆b, s b + a :=
let ⟨x⟩ := h in
calc supr s + a = Sup (range s) + a : by rw Sup_range
... = (⨆b∈range s, b + a) : Sup_add ⟨s x, x, rfl⟩
... = _ : supr_range
lemma add_supr {ι : Sort*} {s : ι → ℝ≥0∞} [h : nonempty ι] : a + supr s = ⨆b, a + s b :=
by rw [add_comm, supr_add]; simp [add_comm]
lemma supr_add_supr {ι : Sort*} {f g : ι → ℝ≥0∞} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) :
supr f + supr g = (⨆ a, f a + g a) :=
begin
by_cases hι : nonempty ι,
{ letI := hι,
refine le_antisymm _ (supr_le $ λ a, add_le_add (le_supr _ _) (le_supr _ _)),
simpa [add_supr, supr_add] using
λ i j:ι, show f i + g j ≤ ⨆ a, f a + g a, from
let ⟨k, hk⟩ := h i j in le_supr_of_le k hk },
{ have : ∀f:ι → ℝ≥0∞, (⨆i, f i) = 0 := λ f, supr_eq_zero.mpr (λ i, (hι ⟨i⟩).elim),
rw [this, this, this, zero_add] }
end
lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι]
{f g : ι → ℝ≥0∞} (hf : monotone f) (hg : monotone g) :
supr f + supr g = (⨆ a, f a + g a) :=
supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add (hf $ le_sup_left) (hg $ le_sup_right)⟩
lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ℝ≥0∞}
(hf : ∀a, monotone (f a)) :
∑ a in s, supr (f a) = (⨆ n, ∑ a in s, f a n) :=
begin
refine finset.induction_on s _ _,
{ simp, },
{ assume a s has ih,
simp only [finset.sum_insert has],
rw [ih, supr_add_supr_of_monotone (hf a)],
assume i j h,
exact (finset.sum_le_sum $ assume a ha, hf a h) }
end
lemma mul_Sup {s : set ℝ≥0∞} {a : ℝ≥0∞} : a * Sup s = ⨆i∈s, a * i :=
begin
by_cases hs : ∀x∈s, x = (0:ℝ≥0∞),
{ have h₁ : Sup s = 0 := (bot_unique $ Sup_le $ assume a ha, (hs a ha).symm ▸ le_refl 0),
have h₂ : (⨆i ∈ s, a * i) = 0 :=
(bot_unique $ supr_le $ assume a, supr_le $ assume ha, by simp [hs a ha]),
rw [h₁, h₂, mul_zero] },
{ simp only [not_forall] at hs,
rcases hs with ⟨x, hx, hx0⟩,
have s₁ : Sup s ≠ 0 :=
pos_iff_ne_zero.1 (lt_of_lt_of_le (pos_iff_ne_zero.2 hx0) (le_Sup hx)),
have : Sup ((λb, a * b) '' s) = a * Sup s :=
is_lub.Sup_eq ((is_lub_Sup s).is_lub_of_tendsto
(assume x _ y _ h, canonically_ordered_semiring.mul_le_mul (le_refl _) h)
⟨x, hx⟩
(ennreal.tendsto.const_mul (tendsto_id' inf_le_left) (or.inl s₁))),
rw [this.symm, Sup_image] }
end
lemma mul_supr {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : a * supr f = ⨆i, a * f i :=
by rw [← Sup_range, mul_Sup, supr_range]
lemma supr_mul {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f * a = ⨆i, f i * a :=
by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm]
protected lemma tendsto_coe_sub : ∀{b:ℝ≥0∞}, tendsto (λb:ℝ≥0∞, ↑r - b) (𝓝 b) (𝓝 (↑r - b)) :=
begin
refine (forall_ennreal.2 $ and.intro (assume a, _) _),
{ simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, coe_sub.symm],
exact tendsto_const_nhds.sub tendsto_id },
simp,
exact (tendsto.congr' (mem_sets_of_superset (lt_mem_nhds $ @coe_lt_top r) $
by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds
end
lemma sub_supr {ι : Sort*} [nonempty ι] {b : ι → ℝ≥0∞} (hr : a < ⊤) :
a - (⨆i, b i) = (⨅i, a - b i) :=
let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in
have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i),
from is_glb.Inf_eq $ is_lub_supr.is_glb_of_tendsto
(assume x _ y _, sub_le_sub (le_refl _))
(range_nonempty _)
(ennreal.tendsto_coe_sub.comp (tendsto_id' inf_le_left)),
by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_refl _
end topological_space
section tsum
variables {f g : α → ℝ≥0∞}
@[norm_cast] protected lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} :
has_sum (λa, (f a : ℝ≥0∞)) ↑r ↔ has_sum f r :=
have (λs:finset α, ∑ a in s, ↑(f a)) = (coe : ℝ≥0 → ℝ≥0∞) ∘ (λs:finset α, ∑ a in s, f a),
from funext $ assume s, ennreal.coe_finset_sum.symm,
by unfold has_sum; rw [this, tendsto_coe]
protected lemma tsum_coe_eq {f : α → ℝ≥0} (h : has_sum f r) : ∑'a, (f a : ℝ≥0∞) = r :=
(ennreal.has_sum_coe.2 h).tsum_eq
protected lemma coe_tsum {f : α → ℝ≥0} : summable f → ↑(tsum f) = ∑'a, (f a : ℝ≥0∞)
| ⟨r, hr⟩ := by rw [hr.tsum_eq, ennreal.tsum_coe_eq hr]
protected lemma has_sum : has_sum f (⨆s:finset α, ∑ a in s, f a) :=
tendsto_at_top_supr $ λ s t, finset.sum_le_sum_of_subset
@[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩
lemma tsum_coe_ne_top_iff_summable {f : β → ℝ≥0} :
∑' b, (f b:ℝ≥0∞) ≠ ∞ ↔ summable f :=
begin
refine ⟨λ h, _, λ h, ennreal.coe_tsum h ▸ ennreal.coe_ne_top⟩,
lift (∑' b, (f b:ℝ≥0∞)) to ℝ≥0 using h with a ha,
refine ⟨a, ennreal.has_sum_coe.1 _⟩,
rw ha,
exact ennreal.summable.has_sum
end
protected lemma tsum_eq_supr_sum : ∑'a, f a = (⨆s:finset α, ∑ a in s, f a) :=
ennreal.has_sum.tsum_eq
protected lemma tsum_eq_supr_sum' {ι : Type*} (s : ι → finset α) (hs : ∀ t, ∃ i, t ⊆ s i) :
∑' a, f a = ⨆ i, ∑ a in s i, f a :=
begin
rw [ennreal.tsum_eq_supr_sum],
symmetry,
change (⨆i:ι, (λ t : finset α, ∑ a in t, f a) (s i)) = ⨆s:finset α, ∑ a in s, f a,
exact (finset.sum_mono_set f).supr_comp_eq hs
end
protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ℝ≥0∞) :
∑'p:Σa, β a, f p.1 p.2 = ∑'a b, f a b :=
tsum_sigma' (assume b, ennreal.summable) ennreal.summable
protected lemma tsum_sigma' {β : α → Type*} (f : (Σ a, β a) → ℝ≥0∞) :
∑'p:(Σa, β a), f p = ∑'a b, f ⟨a, b⟩ :=
tsum_sigma' (assume b, ennreal.summable) ennreal.summable
protected lemma tsum_prod {f : α → β → ℝ≥0∞} : ∑'p:α×β, f p.1 p.2 = ∑'a, ∑'b, f a b :=
tsum_prod' ennreal.summable $ λ _, ennreal.summable
protected lemma tsum_comm {f : α → β → ℝ≥0∞} : ∑'a, ∑'b, f a b = ∑'b, ∑'a, f a b :=
tsum_comm' ennreal.summable (λ _, ennreal.summable) (λ _, ennreal.summable)
protected lemma tsum_add : ∑'a, (f a + g a) = (∑'a, f a) + (∑'a, g a) :=
tsum_add ennreal.summable ennreal.summable
protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : ∑'a, f a ≤ ∑'a, g a :=
tsum_le_tsum h ennreal.summable ennreal.summable
protected lemma sum_le_tsum {f : α → ℝ≥0∞} (s : finset α) : ∑ x in s, f x ≤ ∑' x, f x :=
sum_le_tsum s (λ x hx, zero_le _) ennreal.summable
protected lemma tsum_eq_supr_nat' {f : ℕ → ℝ≥0∞} {N : ℕ → ℕ} (hN : tendsto N at_top at_top) :
∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range (N i), f a) :=
ennreal.tsum_eq_supr_sum' _ $ λ t,
let ⟨n, hn⟩ := t.exists_nat_subset_range,
⟨k, _, hk⟩ := exists_le_of_tendsto_at_top hN 0 n in
⟨k, finset.subset.trans hn (finset.range_mono hk)⟩
protected lemma tsum_eq_supr_nat {f : ℕ → ℝ≥0∞} :
∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range i, f a) :=
ennreal.tsum_eq_supr_sum' _ finset.exists_nat_subset_range
protected lemma tsum_eq_liminf_sum_nat {f : ℕ → ℝ≥0∞} :
∑' i, f i = filter.at_top.liminf (λ n, ∑ i in finset.range n, f i) :=
begin
rw [ennreal.tsum_eq_supr_nat, filter.liminf_eq_supr_infi_of_nat],
congr,
refine funext (λ n, le_antisymm _ _),
{ refine le_binfi (λ i hi, finset.sum_le_sum_of_subset_of_nonneg _ (λ _ _ _, zero_le _)),
simpa only [finset.range_subset, add_le_add_iff_right] using hi, },
{ refine le_trans (infi_le _ n) _,
simp [le_refl n, le_refl ((finset.range n).sum f)], },
end
protected lemma le_tsum (a : α) : f a ≤ ∑'a, f a :=
le_tsum' ennreal.summable a
protected lemma tsum_eq_top_of_eq_top : (∃ a, f a = ∞) → ∑' a, f a = ∞
| ⟨a, ha⟩ := top_unique $ ha ▸ ennreal.le_tsum a
@[simp] protected lemma tsum_top [nonempty α] : ∑' a : α, ∞ = ∞ :=
let ⟨a⟩ := ‹nonempty α› in ennreal.tsum_eq_top_of_eq_top ⟨a, rfl⟩
protected lemma ne_top_of_tsum_ne_top (h : ∑' a, f a ≠ ∞) (a : α) : f a ≠ ∞ :=
λ ha, h $ ennreal.tsum_eq_top_of_eq_top ⟨a, ha⟩
protected lemma tsum_mul_left : ∑'i, a * f i = a * ∑'i, f i :=
if h : ∀i, f i = 0 then by simp [h] else
let ⟨i, (hi : f i ≠ 0)⟩ := not_forall.mp h in
have sum_ne_0 : ∑'i, f i ≠ 0, from ne_of_gt $
calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm
... ≤ ∑'i, f i : ennreal.le_tsum _,
have tendsto (λs:finset α, ∑ j in s, a * f j) at_top (𝓝 (a * ∑'i, f i)),
by rw [← show (*) a ∘ (λs:finset α, ∑ j in s, f j) = λs, ∑ j in s, a * f j,
from funext $ λ s, finset.mul_sum];
exact ennreal.tendsto.const_mul ennreal.summable.has_sum (or.inl sum_ne_0),
has_sum.tsum_eq this
protected lemma tsum_mul_right : (∑'i, f i * a) = (∑'i, f i) * a :=
by simp [mul_comm, ennreal.tsum_mul_left]
@[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ℝ≥0∞} :
∑'b:α, (⨆ (h : a = b), f b) = f a :=
le_antisymm
(by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s,
calc (∑ b in s, ⨆ (h : a = b), f b) ≤ ∑ b in {a}, ⨆ (h : a = b), f b :
finset.sum_le_sum_of_ne_zero $ assume b _ hb,
suffices a = b, by simpa using this.symm,
classical.by_contradiction $ assume h,
by simpa [h] using hb
... = f a : by simp))
(calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl
... ≤ (∑'b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _)
lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0∞} (r : ℝ≥0∞) :
has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) :=
begin
refine ⟨has_sum.tendsto_sum_nat, assume h, _⟩,
rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat],
{ exact ennreal.summable.has_sum },
{ exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) }
end
lemma tendsto_nat_tsum (f : ℕ → ℝ≥0∞) :
tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 (∑' n, f n)) :=
by { rw ← has_sum_iff_tendsto_nat, exact ennreal.summable.has_sum }
lemma to_nnreal_apply_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) (x : α) :
(((ennreal.to_nnreal ∘ f) x : ℝ≥0) : ℝ≥0∞) = f x :=
coe_to_nnreal $ ennreal.ne_top_of_tsum_ne_top hf _
lemma summable_to_nnreal_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) :
summable (ennreal.to_nnreal ∘ f) :=
by simpa only [←tsum_coe_ne_top_iff_summable, to_nnreal_apply_of_tsum_ne_top hf] using hf
lemma tendsto_cofinite_zero_of_tsum_lt_top {α} {f : α → ℝ≥0∞} (hf : ∑' x, f x < ∞) :
tendsto f cofinite (𝓝 0) :=
begin
have f_ne_top : ∀ n, f n ≠ ∞, from ennreal.ne_top_of_tsum_ne_top hf.ne,
have h_f_coe : f = λ n, ((f n).to_nnreal : ennreal),
from funext (λ n, (coe_to_nnreal (f_ne_top n)).symm),
rw [h_f_coe, ←@coe_zero, tendsto_coe],
exact nnreal.tendsto_cofinite_zero_of_summable (summable_to_nnreal_of_tsum_ne_top hf.ne),
end
lemma tendsto_at_top_zero_of_tsum_lt_top {f : ℕ → ℝ≥0∞} (hf : ∑' x, f x < ∞) :
tendsto f at_top (𝓝 0) :=
by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_tsum_lt_top hf }
protected lemma tsum_apply {ι α : Type*} {f : ι → α → ℝ≥0∞} {x : α} :
(∑' i, f i) x = ∑' i, f i x :=
tsum_apply $ pi.summable.mpr $ λ _, ennreal.summable
lemma tsum_sub {f : ℕ → ℝ≥0∞} {g : ℕ → ℝ≥0∞} (h₁ : ∑' i, g i < ∞) (h₂ : g ≤ f) :
∑' i, (f i - g i) = (∑' i, f i) - (∑' i, g i) :=
begin
have h₃: ∑' i, (f i - g i) = ∑' i, (f i - g i + g i) - ∑' i, g i,
{ rw [ennreal.tsum_add, add_sub_self h₁]},
have h₄:(λ i, (f i - g i) + (g i)) = f,
{ ext n, rw ennreal.sub_add_cancel_of_le (h₂ n)},
rw h₄ at h₃, apply h₃,
end
end tsum
lemma tendsto_to_real_iff {ι} {fi : filter ι} {f : ι → ℝ≥0∞} (hf : ∀ i, f i ≠ ∞) {x : ℝ≥0∞}
(hx : x ≠ ∞) :
fi.tendsto (λ n, (f n).to_real) (𝓝 x.to_real) ↔ fi.tendsto f (𝓝 x) :=
begin
refine ⟨λ h, _, λ h, tendsto.comp (ennreal.tendsto_to_real hx) h⟩,
have h_eq : f = (λ n, ennreal.of_real (f n).to_real),
by { ext1 n, rw ennreal.of_real_to_real (hf n), },
rw [h_eq, ← ennreal.of_real_to_real hx],
exact ennreal.tendsto_of_real h,
end
end ennreal
namespace nnreal
open_locale nnreal
lemma tsum_eq_to_nnreal_tsum {f : β → ℝ≥0} :
(∑' b, f b) = (∑' b, (f b : ℝ≥0∞)).to_nnreal :=
begin
by_cases h : summable f,
{ rw [← ennreal.coe_tsum h, ennreal.to_nnreal_coe] },
{ have A := tsum_eq_zero_of_not_summable h,
simp only [← ennreal.tsum_coe_ne_top_iff_summable, not_not] at h,
simp only [h, ennreal.top_to_nnreal, A] }
end
/-- Comparison test of convergence of `ℝ≥0`-valued series. -/
lemma exists_le_has_sum_of_le {f g : β → ℝ≥0} {r : ℝ≥0}
(hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p :=
have ∑'b, (g b : ℝ≥0∞) ≤ r,
begin
refine has_sum_le (assume b, _) ennreal.summable.has_sum (ennreal.has_sum_coe.2 hfr),
exact ennreal.coe_le_coe.2 (hgf _)
end,
let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in
⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ ennreal.summable.has_sum⟩
/-- Comparison test of convergence of `ℝ≥0`-valued series. -/
lemma summable_of_le {f g : β → ℝ≥0} (hgf : ∀b, g b ≤ f b) : summable f → summable g
| ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in hp.summable
/-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if
the sequence of partial sum converges to `r`. -/
lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0} {r : ℝ≥0} :
has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) :=
begin
rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat],
simp only [ennreal.coe_finset_sum.symm],
exact ennreal.tendsto_coe
end
lemma not_summable_iff_tendsto_nat_at_top {f : ℕ → ℝ≥0} :
¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top :=
begin
split,
{ intros h,
refine ((tendsto_of_monotone _).resolve_right h).comp _,
exacts [finset.sum_mono_set _, tendsto_finset_range] },
{ rintros hnat ⟨r, hr⟩,
exact not_tendsto_nhds_of_tendsto_at_top hnat _ (has_sum_iff_tendsto_nat.1 hr) }
end
lemma summable_iff_not_tendsto_nat_at_top {f : ℕ → ℝ≥0} :
summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top :=
by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top]
lemma summable_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0}
(h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f :=
begin
apply summable_iff_not_tendsto_nat_at_top.2 (λ H, _),
rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩,
exact lt_irrefl _ (hn.trans_le (h n)),
end
lemma tsum_le_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0}
(h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c :=
le_of_tendsto' (has_sum_iff_tendsto_nat.1 (summable_of_sum_range_le h).has_sum) h
lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ≥0} (hf : summable f)
{i : β → α} (hi : function.injective i) : ∑' x, f (i x) ≤ ∑' x, f x :=
tsum_le_tsum_of_inj i hi (λ c hc, zero_le _) (λ b, le_refl _) (summable_comp_injective hf hi) hf
lemma summable_sigma {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ≥0} :
summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) :=
begin
split,
{ simp only [← nnreal.summable_coe, nnreal.coe_tsum],
exact λ h, ⟨h.sigma_factor, h.sigma⟩ },
{ rintro ⟨h₁, h₂⟩,
simpa only [← ennreal.tsum_coe_ne_top_iff_summable, ennreal.tsum_sigma', ennreal.coe_tsum, h₁]
using h₂ }
end
lemma indicator_summable {f : α → ℝ≥0} (hf : summable f) (s : set α) :
summable (s.indicator f) :=
begin
refine nnreal.summable_of_le (λ a, le_trans (le_of_eq (s.indicator_apply f a)) _) hf,
split_ifs,
exact le_refl (f a),
exact zero_le_coe,
end
lemma tsum_indicator_ne_zero {f : α → ℝ≥0} (hf : summable f) {s : set α} (h : ∃ a ∈ s, f a ≠ 0) :
∑' x, (s.indicator f) x ≠ 0 :=
λ h', let ⟨a, ha, hap⟩ := h in
hap (trans (set.indicator_apply_eq_self.mpr (absurd ha)).symm
(((tsum_eq_zero_iff (indicator_summable hf s)).1 h') a))
open finset
/-- For `f : ℕ → ℝ≥0`, then `∑' k, f (k + i)` tends to zero. This does not require a summability
assumption on `f`, as otherwise all sums are zero. -/
lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) :=
begin
rw ← tendsto_coe,
convert tendsto_sum_nat_add (λ i, (f i : ℝ)),
norm_cast,
end
lemma has_sum_lt {f g : α → ℝ≥0} {sf sg : ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i)
(hf : has_sum f sf) (hg : has_sum g sg) : sf < sg :=
begin
have A : ∀ (a : α), (f a : ℝ) ≤ g a := λ a, nnreal.coe_le_coe.2 (h a),
have : (sf : ℝ) < sg :=
has_sum_lt A (nnreal.coe_lt_coe.2 hi) (has_sum_coe.2 hf) (has_sum_coe.2 hg),
exact nnreal.coe_lt_coe.1 this
end
@[mono] lemma has_sum_strict_mono
{f g : α → ℝ≥0} {sf sg : ℝ≥0} (hf : has_sum f sf) (hg : has_sum g sg) (h : f < g) : sf < sg :=
let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg
lemma tsum_lt_tsum {f g : α → ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i)
(hg : summable g) : ∑' n, f n < ∑' n, g n :=
has_sum_lt h hi (summable_of_le h hg).has_sum hg.has_sum
@[mono] lemma tsum_strict_mono {f g : α → ℝ≥0} (hg : summable g) (h : f < g) :
∑' n, f n < ∑' n, g n :=
let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hg
lemma tsum_pos {g : α → ℝ≥0} (hg : summable g) (i : α) (hi : 0 < g i) :
0 < ∑' b, g b :=
by { rw ← tsum_zero, exact tsum_lt_tsum (λ a, zero_le _) hi hg }
end nnreal
namespace ennreal
lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0∞) (hf : ∑' i, f i ≠ ∞) :
tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) :=
begin
lift f to ℕ → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hf,
replace hf : summable f := tsum_coe_ne_top_iff_summable.1 hf,
simp only [← ennreal.coe_tsum, nnreal.summable_nat_add _ hf, ← ennreal.coe_zero],
exact_mod_cast nnreal.tendsto_sum_nat_add f
end
end ennreal
lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ} (hf : summable f) (hn : ∀ a, 0 ≤ f a)
{i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f :=
begin
let g : α → ℝ≥0 := λ a, ⟨f a, hn a⟩,
have hg : summable g, by rwa ← nnreal.summable_coe,
convert nnreal.coe_le_coe.2 (nnreal.tsum_comp_le_tsum_of_inj hg hi);
{ rw nnreal.coe_tsum, congr }
end
/-- Comparison test of convergence of series of non-negative real numbers. -/
lemma summable_of_nonneg_of_le {f g : β → ℝ}
(hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g :=
let f' (b : β) : ℝ≥0 := ⟨f b, le_trans (hg b) (hgf b)⟩ in
let g' (b : β) : ℝ≥0 := ⟨g b, hg b⟩ in
have summable f', from nnreal.summable_coe.1 hf,
have summable g', from
nnreal.summable_of_le (assume b, (@nnreal.coe_le_coe (g' b) (f' b)).2 $ hgf b) this,
show summable (λb, g' b : β → ℝ), from nnreal.summable_coe.2 this
/-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if
the sequence of partial sum converges to `r`. -/
lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) :
has_sum f r ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) :=
begin
lift f to ℕ → ℝ≥0 using hf,
simp only [has_sum, ← nnreal.coe_sum, nnreal.tendsto_coe'],
exact exists_congr (λ hr, nnreal.has_sum_iff_tendsto_nat)
end
lemma ennreal.of_real_tsum_of_nonneg {f : α → ℝ} (hf_nonneg : ∀ n, 0 ≤ f n) (hf : summable f) :
ennreal.of_real (∑' n, f n) = ∑' n, ennreal.of_real (f n) :=
by simp_rw [ennreal.of_real, ennreal.tsum_coe_eq (nnreal.has_sum_of_real_of_nonneg hf_nonneg hf)]
lemma not_summable_iff_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) :
¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top :=
begin
lift f to ℕ → ℝ≥0 using hf,
exact_mod_cast nnreal.not_summable_iff_tendsto_nat_at_top
end
lemma summable_iff_not_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) :
summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top :=
by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top_of_nonneg hf]
lemma summable_sigma_of_nonneg {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ} (hf : ∀ x, 0 ≤ f x) :
summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) :=
by { lift f to (Σ x, β x) → ℝ≥0 using hf, exact_mod_cast nnreal.summable_sigma }
lemma summable_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n)
(h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f :=
begin
apply (summable_iff_not_tendsto_nat_at_top_of_nonneg hf).2 (λ H, _),
rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩,
exact lt_irrefl _ (hn.trans_le (h n)),
end
lemma tsum_le_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n)
(h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c :=
le_of_tendsto' ((has_sum_iff_tendsto_nat_of_nonneg hf _).1
(summable_of_sum_range_le hf h).has_sum) h
/-- If a sequence `f` with non-negative terms is dominated by a sequence `g` with summable
series and at least one term of `f` is strictly smaller than the corresponding term in `g`,
then the series of `f` is strictly smaller than the series of `g`. -/
lemma tsum_lt_tsum_of_nonneg {i : ℕ} {f g : ℕ → ℝ}
(h0 : ∀ (b : ℕ), 0 ≤ f b) (h : ∀ (b : ℕ), f b ≤ g b) (hi : f i < g i) (hg : summable g) :
∑' n, f n < ∑' n, g n :=
tsum_lt_tsum h hi (summable_of_nonneg_of_le h0 h hg) hg
section
variables [emetric_space β]
open ennreal filter emetric
/-- In an emetric ball, the distance between points is everywhere finite -/
lemma edist_ne_top_of_mem_ball {a : β} {r : ℝ≥0∞} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ :=
lt_top_iff_ne_top.1 $
calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a
... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2
... ≤ ⊤ : le_top
/-- Each ball in an extended metric space gives us a metric space, as the edist
is everywhere finite. -/
def metric_space_emetric_ball (a : β) (r : ℝ≥0∞) : metric_space (ball a r) :=
emetric_space.to_metric_space edist_ne_top_of_mem_ball
local attribute [instance] metric_space_emetric_ball
lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ℝ≥0∞) (h : x ∈ ball a r) :
𝓝 x = map (coe : ball a r → β) (𝓝 ⟨x, h⟩) :=
(map_nhds_subtype_coe_eq _ $ is_open.mem_nhds emetric.is_open_ball h).symm
end
section
variable [pseudo_emetric_space α]
open emetric
lemma tendsto_iff_edist_tendsto_0 {l : filter β} {f : β → α} {y : α} :
tendsto f l (𝓝 y) ↔ tendsto (λ x, edist (f x) y) l (𝓝 0) :=
by simp only [emetric.nhds_basis_eball.tendsto_right_iff, emetric.mem_ball,
@tendsto_order ℝ≥0∞ β _ _, forall_prop_of_false ennreal.not_lt_zero, forall_const, true_and]
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
lemma emetric.cauchy_seq_iff_le_tendsto_0 [nonempty β] [semilattice_sup β] {s : β → α} :
cauchy_seq s ↔ (∃ (b: β → ℝ≥0∞), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N)
∧ (tendsto b at_top (𝓝 0))) :=
⟨begin
assume hs,
rw emetric.cauchy_seq_iff at hs,
/- `s` is Cauchy sequence. The sequence `b` will be constructed by taking
the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/
let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}),
--Prove that it bounds the distances of points in the Cauchy sequence
have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N,
{ refine λm n N hm hn, le_Sup _,
use (prod.mk m n),
simp only [and_true, eq_self_iff_true, set.mem_set_of_eq],
exact ⟨hm, hn⟩ },
--Prove that it tends to `0`, by using the Cauchy property of `s`
have D : tendsto b at_top (𝓝 0),
{ refine tendsto_order.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩,
rcases exists_between εpos with ⟨δ, δpos, δlt⟩,
rcases hs δ δpos with ⟨N, hN⟩,
refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩,
have : b n ≤ δ := Sup_le begin
simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists],
intros d p q hp hq hd,
rw ← hd,
exact le_of_lt (hN p q (le_trans hn hp) (le_trans hn hq))
end,
simpa using lt_of_le_of_lt this δlt },
-- Conclude
exact ⟨b, ⟨C, D⟩⟩
end,
begin
rintros ⟨b, ⟨b_bound, b_lim⟩⟩,
/-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N,
b_lim : tendsto b at_top (𝓝 0)-/
refine emetric.cauchy_seq_iff.2 (λε εpos, _),
have : ∀ᶠ n in at_top, b n < ε := (tendsto_order.1 b_lim ).2 _ εpos,
rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩,
exact ⟨N, λm n hm hn, calc
edist (s m) (s n) ≤ b N : b_bound m n N hm hn
... < ε : (hN _ (le_refl N)) ⟩
end⟩
lemma continuous_of_le_add_edist {f : α → ℝ≥0∞} (C : ℝ≥0∞)
(hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f :=
begin
refine continuous_iff_continuous_at.2 (λx, tendsto_order.2 ⟨_, _⟩),
show ∀e, e < f x → ∀ᶠ y in 𝓝 x, e < f y,
{ assume e he,
let ε := min (f x - e) 1,
have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]),
have : 0 < ε := by simp [ε, hC, he, ennreal.zero_lt_one],
have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, mul_eq_zero]),
have I : C * (C⁻¹ * (ε/2)) < ε,
{ by_cases C_zero : C = 0,
{ simp [C_zero, ‹0 < ε›] },
{ calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc]
... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC]
... < ε : ennreal.half_lt_self (‹0 < ε›.ne') (‹ε < ⊤›.ne) }},
have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | e < f y},
{ rintros y hy,
by_cases htop : f y = ⊤,
{ simp [htop, lt_top_iff_ne_top, ne_top_of_lt he] },
{ simp at hy,
have : e + ε < f y + ε := calc
e + ε ≤ e + (f x - e) : add_le_add_left (min_le_left _ _) _
... = f x : by simp [le_of_lt he]
... ≤ f y + C * edist x y : h x y
... = f y + C * edist y x : by simp [edist_comm]
... ≤ f y + C * (C⁻¹ * (ε/2)) :
add_le_add_left (canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy)) _
... < f y + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I,
show e < f y, from
(ennreal.add_lt_add_iff_right ‹ε < ⊤›).1 this }},
apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this },
show ∀e, f x < e → ∀ᶠ y in 𝓝 x, f y < e,
{ assume e he,
let ε := min (e - f x) 1,
have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]),
have : 0 < ε := by simp [ε, he, ennreal.zero_lt_one],
have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, mul_eq_zero]),
have I : C * (C⁻¹ * (ε/2)) < ε,
{ by_cases C_zero : C = 0,
simp [C_zero, ‹0 < ε›],
calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc]
... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC]
... < ε : ennreal.half_lt_self (‹0 < ε›.ne') (‹ε < ⊤›.ne) },
have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | f y < e},
{ rintros y hy,
have htop : f x ≠ ⊤ := ne_top_of_lt he,
show f y < e, from calc
f y ≤ f x + C * edist y x : h y x
... ≤ f x + C * (C⁻¹ * (ε/2)) :
add_le_add_left (canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy)) _
... < f x + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I
... ≤ f x + (e - f x) : add_le_add_left (min_le_left _ _) _
... = e : by simp [le_of_lt he] },
apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this },
end
theorem continuous_edist : continuous (λp:α×α, edist p.1 p.2) :=
begin
apply continuous_of_le_add_edist 2 (by norm_num),
rintros ⟨x, y⟩ ⟨x', y'⟩,
calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _
... = edist x' y' + (edist x x' + edist y y') : by simp [edist_comm]; cc
... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) :
add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _
... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm]
end
theorem continuous.edist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) :=
continuous_edist.comp (hf.prod_mk hg : _)
theorem filter.tendsto.edist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, edist (f x) (g x)) x (𝓝 (edist a b)) :=
(continuous_edist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
lemma cauchy_seq_of_edist_le_of_tsum_ne_top {f : ℕ → α} (d : ℕ → ℝ≥0∞)
(hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : tsum d ≠ ∞) :
cauchy_seq f :=
begin
lift d to (ℕ → nnreal) using (λ i, ennreal.ne_top_of_tsum_ne_top hd i),
rw ennreal.tsum_coe_ne_top_iff_summable at hd,
exact cauchy_seq_of_edist_le_of_summable d hf hd
end
lemma emetric.is_closed_ball {a : α} {r : ℝ≥0∞} : is_closed (closed_ball a r) :=
is_closed_le (continuous_id.edist continuous_const) continuous_const
@[simp] lemma emetric.diam_closure (s : set α) : diam (closure s) = diam s :=
begin
refine le_antisymm (diam_le $ λ x hx y hy, _) (diam_mono subset_closure),
have : edist x y ∈ closure (Iic (diam s)),
from map_mem_closure2 (@continuous_edist α _) hx hy (λ _ _, edist_le_diam_of_mem),
rwa closure_Iic at this
end
/-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`,
then the distance from `f n` to the limit is bounded by `∑'_{k=n}^∞ d k`. -/
lemma edist_le_tsum_of_edist_le_of_tendsto {f : ℕ → α} (d : ℕ → ℝ≥0∞)
(hf : ∀ n, edist (f n) (f n.succ) ≤ d n)
{a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
edist (f n) a ≤ ∑' m, d (n + m) :=
begin
refine le_of_tendsto (tendsto_const_nhds.edist ha)
(mem_at_top_sets.2 ⟨n, λ m hnm, _⟩),
refine le_trans (edist_le_Ico_sum_of_edist_le hnm (λ k _ _, hf k)) _,
rw [finset.sum_Ico_eq_sum_range],
exact sum_le_tsum _ (λ _ _, zero_le _) ennreal.summable
end
/-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`,
then the distance from `f 0` to the limit is bounded by `∑'_{k=0}^∞ d k`. -/
lemma edist_le_tsum_of_edist_le_of_tendsto₀ {f : ℕ → α} (d : ℕ → ℝ≥0∞)
(hf : ∀ n, edist (f n) (f n.succ) ≤ d n)
{a : α} (ha : tendsto f at_top (𝓝 a)) :
edist (f 0) a ≤ ∑' m, d m :=
by simpa using edist_le_tsum_of_edist_le_of_tendsto d hf ha 0
end --section
|
5b1b7f64cc5aac4d2258a59a7f5e779f0a0c591e | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Util/Closure.lean | 9d23965d429fcbd4255b4b6f517258ab8cd36ccd | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 7,221 | 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 Init.Lean.MetavarContext
import Init.Lean.Environment
import Init.Lean.Util.FoldConsts
namespace Lean
namespace Closure
structure Context :=
(mctx : MetavarContext)
(lctxInput : LocalContext)
structure State :=
(lctxOutput : LocalContext := {})
(ngen : NameGenerator := { namePrefix := `_closure })
(visitedLevel : LevelMap Level := {})
(visitedExpr : ExprStructMap Expr := {})
(levelParams : Array Name := #[])
(nextLevelIdx : Nat := 1)
(levelClosure : Array Level := #[])
(nextExprIdx : Nat := 1)
(exprClosure : Array Expr := #[])
def Exception := String
abbrev ClosureM := ReaderT Context (EStateM Exception State)
@[inline] def visitLevel (f : Level → ClosureM Level) (u : Level) : ClosureM Level :=
if !u.hasMVar && !u.hasParam then pure u
else do
s ← get;
match s.visitedLevel.find? u with
| some v => pure v
| none => do
v ← f u;
modify $ fun s => { visitedLevel := s.visitedLevel.insert u v, .. s };
pure v
def mkNewLevelParam (u : Level) : ClosureM Level := do
s ← get;
let p := (`u).appendIndexAfter s.nextLevelIdx;
modify $ fun s => { levelParams := s.levelParams.push p, nextLevelIdx := s.nextLevelIdx + 1, levelClosure := s.levelClosure.push u, .. s };
pure $ mkLevelParam p
partial def collectLevelAux : Level → ClosureM Level
| u@(Level.succ v _) => do v ← visitLevel collectLevelAux v; pure $ u.updateSucc! v
| u@(Level.max v w _) => do v ← visitLevel collectLevelAux v; w ← visitLevel collectLevelAux w; pure $ u.updateMax! v w
| u@(Level.imax v w _) => do v ← visitLevel collectLevelAux v; w ← visitLevel collectLevelAux w; pure $ u.updateIMax! v w
| u@(Level.mvar _ _) => mkNewLevelParam u
| u@(Level.param _ _) => mkNewLevelParam u
| u@(Level.zero _) => pure u
def collectLevel (u : Level) : ClosureM Level :=
visitLevel collectLevelAux u
def mkFreshFVarId : ClosureM FVarId := do
s ← get;
let id := s.ngen.curr;
modify $ fun s => { ngen := s.ngen.next, .. s };
pure id
/--
Remark: This method does not guarantee unique user names.
The correctness of the procedure does not rely on unique user names.
Recall that the pretty printer takes care of unintended collisions. -/
def mkNextUserName : ClosureM Name := do
s ← get;
let n := (`_x).appendIndexAfter s.nextExprIdx;
modify $ fun s => { nextExprIdx := s.nextExprIdx + 1, .. s };
pure n
def getUserName (userName? : Option Name) : ClosureM Name :=
match userName? with
| some userName => pure userName
| none => mkNextUserName
def mkLocalDecl (userName? : Option Name) (type : Expr) : ClosureM Expr := do
userName ← getUserName userName?;
fvarId ← mkFreshFVarId;
modify $ fun s => { lctxOutput := s.lctxOutput.mkLocalDecl fvarId userName type, .. s };
pure $ mkFVar fvarId
def mkLetDecl (userName : Name) (type : Expr) (value : Expr) : ClosureM Expr := do
fvarId ← mkFreshFVarId;
modify $ fun s => { lctxOutput := s.lctxOutput.mkLetDecl fvarId userName type value, .. s };
pure $ mkFVar fvarId
@[inline] def visitExpr (f : Expr → ClosureM Expr) (e : Expr) : ClosureM Expr :=
if !e.hasLevelParam && !e.hasFVar && !e.hasMVar then pure e
else do
s ← get;
match s.visitedExpr.find? e with
| some r => pure r
| none => do
r ← f e;
modify $ fun s => { visitedExpr := s.visitedExpr.insert e r, .. s };
pure r
partial def collectExprAux : Expr → ClosureM Expr
| e =>
let collect (e : Expr) := visitExpr collectExprAux e;
match e with
| Expr.proj _ _ s _ => do s ← collect s; pure (e.updateProj! s)
| Expr.forallE _ d b _ => do d ← collect d; b ← collect b; pure (e.updateForallE! d b)
| Expr.lam _ d b _ => do d ← collect d; b ← collect b; pure (e.updateLambdaE! d b)
| Expr.letE _ t v b _ => do t ← collect t; v ← collect v; b ← collect b; pure (e.updateLet! t v b)
| Expr.app f a _ => do f ← collect f; a ← collect a; pure (e.updateApp! f a)
| Expr.mdata _ b _ => do b ← collect b; pure (e.updateMData! b)
| Expr.sort u _ => do u ← collectLevel u; pure (e.updateSort! u)
| Expr.const c us _ => do us ← us.mapM collectLevel; pure (e.updateConst! us)
| Expr.mvar mvarId _ => do
ctx ← read;
match ctx.mctx.findDecl? mvarId with
| none => throw "unknown metavariable"
| some mvarDecl => do
type ← collect mvarDecl.type;
x ← mkLocalDecl none type;
modify $ fun s => { exprClosure := s.exprClosure.push e, .. s };
pure x
| Expr.fvar fvarId _ => do
ctx ← read;
match ctx.lctxInput.find? fvarId with
| none => throw "unknown free variable"
| some (LocalDecl.cdecl _ _ userName type _) => do
type ← collect type;
x ← mkLocalDecl userName type;
modify $ fun s => { exprClosure := s.exprClosure.push e, .. s };
pure x
| some (LocalDecl.ldecl _ _ userName type value) => do
type ← collect type;
value ← collect value;
-- Note that let-declarations do not need to be provided to the closure being constructed.
mkLetDecl userName type value
| e => pure e
def collectExpr (e : Expr) : ClosureM Expr :=
visitExpr collectExprAux e
structure MkClosureResult :=
(levelParams : Array Name)
(type : Expr)
(value : Expr)
(levelClosure : Array Level)
(exprClosure : Array Expr)
def mkClosure (mctx : MetavarContext) (lctx : LocalContext) (type : Expr) (value : Expr) : Except String MkClosureResult :=
let shareCommonTypeValue : ShareCommonM (Expr × Expr) := do {
type ← withShareCommon type;
value ← withShareCommon value;
pure (type, value)
};
let (type, value) := shareCommonTypeValue.run;
let mkTypeValue : ClosureM (Expr × Expr) := do {
type ← collectExpr type;
value ← collectExpr value;
pure (type, value)
};
match (mkTypeValue { mctx := mctx, lctxInput := lctx }).run {} with
| EStateM.Result.ok (type, value) s =>
let fvars := s.lctxOutput.getFVars;
let type := s.lctxOutput.mkForall fvars type;
let value := s.lctxOutput.mkLambda fvars value;
Except.ok {
levelParams := s.levelParams,
type := type,
value := value,
levelClosure := s.levelClosure,
exprClosure := s.exprClosure }
| EStateM.Result.error ex s => Except.error ex
end Closure
def mkAuxDefinition (env : Environment) (opts : Options) (mctx : MetavarContext) (lctx : LocalContext) (name : Name) (type : Expr) (value : Expr)
: Except KernelException (Expr × Environment) :=
match Closure.mkClosure mctx lctx type value with
| Except.error ex => throw $ KernelException.other ex
| Except.ok result => do
let decl := Declaration.defnDecl {
name := name,
lparams := result.levelParams.toList,
type := result.type,
value := result.value,
hints := ReducibilityHints.regular (getMaxHeight env result.value + 1),
isUnsafe := env.hasUnsafe result.type || env.hasUnsafe result.value
};
env ← env.addAndCompile opts decl;
let c := mkAppN (mkConst name result.levelClosure.toList) result.exprClosure;
pure (c, env)
end Lean
|
3a245ddde117ee813d1c62c2cbf3bd9f3df81a62 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/reserve_bugs.lean | 9f47b520caf43488cdfa1c2244d5fed53df9ccd5 | [
"Apache-2.0"
] | permissive | soonhokong/lean | cb8aa01055ffe2af0fb99a16b4cda8463b882cd1 | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | refs/heads/master | 1,611,187,284,081 | 1,450,766,737,000 | 1,476,122,547,000 | 11,513,992 | 2 | 0 | null | 1,401,763,102,000 | 1,374,182,235,000 | C++ | UTF-8 | Lean | false | false | 467 | lean | import logic
constant f : num → num
constant g : num → num → num
constant h : num → num → num
reserve infixl `+`:65
reserve infixr `&`:70
reserve infixl `-`:65
reserve prefix `-`:100
infixl `+` := g
infixl `-` := h
prefix `-` := f
infixr `&` := h
set_option pp.notation false
check -(1:num) + 2
check 1 & 2 & 3 & 4
check (1:num) - 2 - 3 - 4
infixr `~~`:60 := h
infixl `!!`:60 := h
check 1 ~~ 2 ~~ 3 ~~ 4
check 1 !! 2 !! 3 !! 4
check 1 ~~ 2 + 3 ~~ 4
|
76e52395216162ffffb667a158e76e8382f14d42 | c3f2fcd060adfa2ca29f924839d2d925e8f2c685 | /library/logic/identities.lean | 1862936a3d4fd332402fc9793a0a86c120d12d08 | [
"Apache-2.0"
] | permissive | respu/lean | 6582d19a2f2838a28ecd2b3c6f81c32d07b5341d | 8c76419c60b63d0d9f7bc04ebb0b99812d0ec654 | refs/heads/master | 1,610,882,451,231 | 1,427,747,084,000 | 1,427,747,429,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,438 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: logic.identities
Authors: Jeremy Avigad, Leonardo de Moura
Useful logical identities. Since we are not using propositional extensionality, some of the
calculations use the type class support provided by logic.instances.
-/
import logic.connectives logic.instances logic.quantifiers logic.cast
open relation decidable relation.iff_ops
theorem or.right_comm (a b c : Prop) : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b :=
calc
(a ∨ b) ∨ c ↔ a ∨ (b ∨ c) : or.assoc
... ↔ a ∨ (c ∨ b) : {or.comm}
... ↔ (a ∨ c) ∨ b : iff.symm or.assoc
theorem or.left_comm (a b c : Prop) : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) :=
calc
a ∨ (b ∨ c) ↔ (a ∨ b) ∨ c : iff.symm or.assoc
... ↔ (b ∨ a) ∨ c : {or.comm}
... ↔ b ∨ (a ∨ c) : or.assoc
theorem and.right_comm (a b c : Prop) : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b :=
calc
(a ∧ b) ∧ c ↔ a ∧ (b ∧ c) : and.assoc
... ↔ a ∧ (c ∧ b) : {and.comm}
... ↔ (a ∧ c) ∧ b : iff.symm and.assoc
theorem and.left_comm (a b c : Prop) : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) :=
calc
a ∧ (b ∧ c) ↔ (a ∧ b) ∧ c : iff.symm and.assoc
... ↔ (b ∧ a) ∧ c : {and.comm}
... ↔ b ∧ (a ∧ c) : and.assoc
theorem not_not_iff {a : Prop} [D : decidable a] : (¬¬a) ↔ a :=
iff.intro
(assume H : ¬¬a,
by_cases (assume H' : a, H') (assume H' : ¬a, absurd H' H))
(assume H : a, assume H', H' H)
theorem not_not_elim {a : Prop} [D : decidable a] (H : ¬¬a) : a :=
iff.mp not_not_iff H
theorem not_true_iff_false : ¬true ↔ false :=
iff.intro (assume H, H trivial) false.elim
theorem not_false_iff_true : ¬false ↔ true :=
iff.intro (assume H, trivial) (assume H H', H')
theorem not_or_iff_not_and_not {a b : Prop} [Da : decidable a] [Db : decidable b] :
¬(a ∨ b) ↔ ¬a ∧ ¬b :=
iff.intro
(assume H, or.elim (em a)
(assume Ha, absurd (or.inl Ha) H)
(assume Hna, or.elim (em b)
(assume Hb, absurd (or.inr Hb) H)
(assume Hnb, and.intro Hna Hnb)))
(assume (H : ¬a ∧ ¬b) (N : a ∨ b),
or.elim N
(assume Ha, absurd Ha (and.elim_left H))
(assume Hb, absurd Hb (and.elim_right H)))
theorem not_and_iff_not_or_not {a b : Prop} [Da : decidable a] [Db : decidable b] :
¬(a ∧ b) ↔ ¬a ∨ ¬b :=
iff.intro
(assume H, or.elim (em a)
(assume Ha, or.elim (em b)
(assume Hb, absurd (and.intro Ha Hb) H)
(assume Hnb, or.inr Hnb))
(assume Hna, or.inl Hna))
(assume (H : ¬a ∨ ¬b) (N : a ∧ b),
or.elim H
(assume Hna, absurd (and.elim_left N) Hna)
(assume Hnb, absurd (and.elim_right N) Hnb))
theorem imp_iff_not_or {a b : Prop} [Da : decidable a] : (a → b) ↔ ¬a ∨ b :=
iff.intro
(assume H : a → b, (or.elim (em a)
(assume Ha : a, or.inr (H Ha))
(assume Hna : ¬a, or.inl Hna)))
(assume (H : ¬a ∨ b) (Ha : a),
or_resolve_right H (not_not_iff⁻¹ ▸ Ha))
theorem not_implies_iff_and_not {a b : Prop} [Da : decidable a] [Db : decidable b] :
¬(a → b) ↔ a ∧ ¬b :=
calc
¬(a → b) ↔ ¬(¬a ∨ b) : {imp_iff_not_or}
... ↔ ¬¬a ∧ ¬b : not_or_iff_not_and_not
... ↔ a ∧ ¬b : {not_not_iff}
theorem peirce {a b : Prop} [D : decidable a] : ((a → b) → a) → a :=
assume H, by_contradiction (assume Hna : ¬a,
have Hnna : ¬¬a, from not_not_of_not_implies (mt H Hna),
absurd (not_not_elim Hnna) Hna)
theorem forall_not_of_not_exists {A : Type} {P : A → Prop} [D : ∀x, decidable (P x)]
(H : ¬∃x, P x) : ∀x, ¬P x :=
take x, or.elim (em (P x))
(assume Hp : P x, absurd (exists.intro x Hp) H)
(assume Hn : ¬P x, Hn)
theorem exists_not_of_not_forall {A : Type} {P : A → Prop} [D : ∀x, decidable (P x)]
[D' : decidable (∃x, ¬P x)] (H : ¬∀x, P x) :
∃x, ¬P x :=
@by_contradiction _ D' (assume H1 : ¬∃x, ¬P x,
have H2 : ∀x, ¬¬P x, from @forall_not_of_not_exists _ _ (take x, decidable_not) H1,
have H3 : ∀x, P x, from take x, @not_not_elim _ (D x) (H2 x),
absurd H3 H)
theorem iff_true_intro {a : Prop} (H : a) : a ↔ true :=
iff.intro
(assume H1 : a, trivial)
(assume H2 : true, H)
theorem iff_false_intro {a : Prop} (H : ¬a) : a ↔ false :=
iff.intro
(assume H1 : a, absurd H1 H)
(assume H2 : false, false.elim H2)
theorem ne_self_iff_false {A : Type} (a : A) : (a ≠ a) ↔ false :=
iff.intro
(assume H, false.of_ne H)
(assume H, false.elim H)
theorem eq_self_iff_true {A : Type} (a : A) : (a = a) ↔ true :=
iff_true_intro rfl
theorem heq_self_iff_true {A : Type} (a : A) : (a == a) ↔ true :=
iff_true_intro (heq.refl a)
theorem iff_not_self (a : Prop) : (a ↔ ¬a) ↔ false :=
iff.intro
(assume H,
have H' : ¬a, from assume Ha, (H ▸ Ha) Ha,
H' (H⁻¹ ▸ H'))
(assume H, false.elim H)
theorem true_iff_false : (true ↔ false) ↔ false :=
not_true_iff_false ▸ (iff_not_self true)
theorem false_iff_true : (false ↔ true) ↔ false :=
not_false_iff_true ▸ (iff_not_self false)
theorem iff_true_iff (a : Prop) : (a ↔ true) ↔ a :=
iff.intro (assume H, of_iff_true H) (assume H, iff_true_intro H)
theorem iff_false_iff_not (a : Prop) : (a ↔ false) ↔ ¬a :=
iff.intro (assume H, not_of_iff_false H) (assume H, iff_false_intro H)
|
c1ec22d286070033d5d11aa2d2171ab2b990287e | 46125763b4dbf50619e8846a1371029346f4c3db | /src/topology/uniform_space/compare_reals.lean | bdee9f60e919f2c9f730d7555bb232867e6a537e | [
"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 | 4,790 | 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.absolute_value
import topology.instances.real
import topology.uniform_space.completion
/-!
# Comparison of Cauchy reals and Bourbaki reals
In `data.real.basic` real numbers are defined using the so called Cauchy construction (although
it is due to Georg Cantor). More precisely, this construction applies to commutative rings equipped
with an absolute value with values in a linear ordered field.
On the other hand, in the `uniform_space` folder, we construct completions of general uniform
spaces, which allows to construct the Bourbaki real numbers. In this file we build uniformly
continuous bijections from Cauchy reals to Bourbaki reals and back. This is a cross sanity check of
both constructions. Of course those two constructions are variations on the completion idea, simply
with different level of generality. Comparing with Dedekind cuts or quasi-morphisms would be of a
completely different nature.
Note that `metric_space/cau_seq_filter` also relates the notions of Cauchy sequences in metric
spaces and Cauchy filters in general uniform spaces, and `metric_space/completion` makes sure
the completion (as a uniform space) of a metric space is a metric space.
Historical note: mathlib used to define real numbers in an intermediate way, using completion
of uniform spaces but extending multiplication in an ad-hoc way.
TODO:
* Upgrade this isomorphism to a topological ring isomorphism.
* Do the same comparison for p-adic numbers
## Implementation notes
The heavy work is done in `topology/uniform_space/abstract_completion` which provides an abstract
caracterization of completions of uniform spaces, and isomorphisms between them. The only work left
here is to prove the uniform space structure coming from the absolute value on ℚ (with values in ℚ,
not referring to ℝ) coincides with the one coming from the metric space structure (which of course
does use ℝ).
## References
* [N. Bourbaki, *Topologie générale*][bourbaki1966]
## Tags
real numbers, completion, uniform spaces
-/
open set function lattice filter cau_seq uniform_space
/-- The metric space uniform structure on ℚ (which presupposes the existence
of real numbers) agrees with the one coming directly from (abs : ℚ → ℚ). -/
lemma rat.uniform_space_eq :
is_absolute_value.uniform_space (abs : ℚ → ℚ) = metric_space.to_uniform_space' :=
begin
ext s,
erw [metric.mem_uniformity_dist, is_absolute_value.mem_uniformity],
split ; rintro ⟨ε, ε_pos, h⟩,
{ use [ε, by exact_mod_cast ε_pos],
intros a b hab,
apply h,
rw [rat.dist_eq, abs_sub] at hab,
exact_mod_cast hab },
{ obtain ⟨ε', h', h''⟩ : ∃ ε' : ℚ, 0 < ε' ∧ (ε' : ℝ) < ε, from exists_pos_rat_lt ε_pos,
use [ε', h'],
intros a b hab,
apply h,
rw [rat.dist_eq, abs_sub],
refine lt_trans _ h'',
exact_mod_cast hab }
end
/-- Cauchy reals packaged as a completion of ℚ using the absolute value route. -/
noncomputable
def rational_cau_seq_pkg : @abstract_completion ℚ $ is_absolute_value.uniform_space (abs : ℚ → ℚ) :=
{ space := ℝ,
coe := (coe : ℚ → ℝ),
uniform_struct := by apply_instance,
complete := by apply_instance,
separation := by apply_instance,
uniform_inducing := by { rw rat.uniform_space_eq,
exact uniform_embedding_of_rat.to_uniform_inducing },
dense := dense_embedding_of_rat.dense }
namespace compare_reals
/-- Type wrapper around ℚ to make sure the absolute value uniform space instance is picked up
instead of the metric space one. We proved in rat.uniform_space_eq that they are equal,
but they are not definitionaly equal, so it would confuse the type class system (and probably
also human readers). -/
@[derive comm_ring, derive inhabited] def Q := ℚ
instance : uniform_space Q := is_absolute_value.uniform_space (abs : ℚ → ℚ)
/-- Real numbers constructed as in Bourbaki. -/
@[derive inhabited]
def Bourbakiℝ : Type := completion Q
instance bourbaki.uniform_space: uniform_space Bourbakiℝ := completion.uniform_space Q
/-- Bourbaki reals packaged as a completion of Q using the general theory. -/
def Bourbaki_pkg : abstract_completion Q := completion.cpkg
/-- The equivalence between Bourbaki and Cauchy reals-/
noncomputable def compare_equiv : Bourbakiℝ ≃ ℝ :=
Bourbaki_pkg.compare_equiv rational_cau_seq_pkg
lemma compare_uc : uniform_continuous (compare_equiv) :=
Bourbaki_pkg.uniform_continuous_compare_equiv _
lemma compare_uc_symm : uniform_continuous (compare_equiv).symm :=
Bourbaki_pkg.uniform_continuous_compare_equiv_symm _
end compare_reals
|
ec89fa6463871fb4b0f41ceff21b8602984f334b | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/topology/continuous_function/bounded.lean | d2fe2e5e2cd2b9c45ee47b8a6b6fb798c3de1e76 | [
"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 | 36,673 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Mario Carneiro, Yury Kudryashov, Heather Macbeth
-/
import analysis.normed_space.operator_norm
import topology.continuous_function.algebra
/-!
# Bounded continuous functions
The type of bounded continuous functions taking values in a metric space, with
the uniform distance.
-/
noncomputable theory
open_locale topological_space classical nnreal
open set filter metric
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- The type of bounded continuous functions from a topological space to a metric space -/
structure bounded_continuous_function
(α : Type u) (β : Type v) [topological_space α] [metric_space β] extends continuous_map α β :
Type (max u v) :=
(bounded' : ∃C, ∀x y:α, dist (to_fun x) (to_fun y) ≤ C)
localized "infixr ` →ᵇ `:25 := bounded_continuous_function" in bounded_continuous_function
namespace bounded_continuous_function
section basics
variables [topological_space α] [metric_space β] [metric_space γ]
variables {f g : α →ᵇ β} {x : α} {C : ℝ}
instance : has_coe_to_fun (α →ᵇ β) := ⟨_, λ f, f.to_fun⟩
protected lemma bounded (f : α →ᵇ β) : ∃C, ∀ x y : α, dist (f x) (f y) ≤ C := f.bounded'
@[continuity]
protected lemma continuous (f : α →ᵇ β) : continuous f := f.to_continuous_map.continuous
@[ext] lemma ext (H : ∀x, f x = g x) : f = g :=
by { cases f, cases g, congr, ext, exact H x, }
lemma ext_iff : f = g ↔ ∀ x, f x = g x :=
⟨λ h, λ x, h ▸ rfl, ext⟩
lemma bounded_range : bounded (range f) :=
bounded_range_iff.2 f.bounded
/-- A continuous function with an explicit bound is a bounded continuous function. -/
def mk_of_bound (f : C(α, β)) (C : ℝ) (h : ∀ x y : α, dist (f x) (f y) ≤ C) : α →ᵇ β :=
⟨f, ⟨C, h⟩⟩
@[simp] lemma mk_of_bound_coe {f} {C} {h} : (mk_of_bound f C h : α → β) = (f : α → β) :=
rfl
/-- A continuous function on a compact space is automatically a bounded continuous function. -/
def mk_of_compact [compact_space α] (f : C(α, β)) : α →ᵇ β :=
⟨f, bounded_range_iff.1 $ bounded_of_compact $ is_compact_range f.continuous⟩
@[simp] lemma mk_of_compact_apply [compact_space α] (f : C(α, β)) (a : α) :
mk_of_compact f a = f a :=
rfl
/-- If a function is bounded on a discrete space, it is automatically continuous,
and therefore gives rise to an element of the type of bounded continuous functions -/
def mk_of_discrete [discrete_topology α] (f : α → β)
(C : ℝ) (h : ∀ x y : α, dist (f x) (f y) ≤ C) : α →ᵇ β :=
⟨⟨f, continuous_of_discrete_topology⟩, ⟨C, h⟩⟩
@[simp] lemma mk_of_discrete_apply
[discrete_topology α] (f : α → β) (C) (h) (a : α) :
mk_of_discrete f C h a = f a :=
rfl
section
variables (α β)
/--
The map forgetting that a bounded continuous function is bounded.
-/
def forget_boundedness : (α →ᵇ β) → C(α, β) :=
λ f, f.1
@[simp] lemma forget_boundedness_coe (f : α →ᵇ β) : (forget_boundedness α β f : α → β) = f :=
rfl
end
/-- The uniform distance between two bounded continuous functions -/
instance : has_dist (α →ᵇ β) :=
⟨λf g, Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C}⟩
lemma dist_eq : dist f g = Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C} := rfl
lemma dist_set_exists : ∃ C, 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C :=
begin
refine if h : nonempty α then _ else ⟨0, le_refl _, λ x, h.elim ⟨x⟩⟩,
cases h with x,
rcases f.bounded with ⟨Cf, hCf : ∀ x y, dist (f x) (f y) ≤ Cf⟩,
rcases g.bounded with ⟨Cg, hCg : ∀ x y, dist (g x) (g y) ≤ Cg⟩,
let C := max 0 (dist (f x) (g x) + (Cf + Cg)),
refine ⟨C, le_max_left _ _, λ y, _⟩,
calc dist (f y) (g y) ≤ dist (f x) (g x) + (dist (f x) (f y) + dist (g x) (g y)) :
dist_triangle4_left _ _ _ _
... ≤ dist (f x) (g x) + (Cf + Cg) : by mono*
... ≤ C : le_max_right _ _
end
/-- The pointwise distance is controlled by the distance between functions, by definition. -/
lemma dist_coe_le_dist (x : α) : dist (f x) (g x) ≤ dist f g :=
le_cInf dist_set_exists $ λb hb, hb.2 x
/- This lemma will be needed in the proof of the metric space instance, but it will become
useless afterwards as it will be superseded by the general result that the distance is nonnegative
in metric spaces. -/
private lemma dist_nonneg' : 0 ≤ dist f g :=
le_cInf dist_set_exists (λ C, and.left)
/-- The distance between two functions is controlled by the supremum of the pointwise distances -/
lemma dist_le (C0 : (0 : ℝ) ≤ C) : dist f g ≤ C ↔ ∀x:α, dist (f x) (g x) ≤ C :=
⟨λ h x, le_trans (dist_coe_le_dist x) h, λ H, cInf_le ⟨0, λ C, and.left⟩ ⟨C0, H⟩⟩
lemma dist_le_iff_of_nonempty [nonempty α] :
dist f g ≤ C ↔ ∀ x, dist (f x) (g x) ≤ C :=
⟨λ h x, le_trans (dist_coe_le_dist x) h,
λ w, (dist_le (le_trans dist_nonneg (w (nonempty.some ‹_›)))).mpr w⟩
lemma dist_lt_of_nonempty_compact [nonempty α] [compact_space α]
(w : ∀x:α, dist (f x) (g x) < C) : dist f g < C :=
begin
have c : continuous (λ x, dist (f x) (g x)), { continuity, },
obtain ⟨x, -, le⟩ :=
is_compact.exists_forall_ge compact_univ set.univ_nonempty (continuous.continuous_on c),
exact lt_of_le_of_lt (dist_le_iff_of_nonempty.mpr (λ y, le y trivial)) (w x),
end
lemma dist_lt_iff_of_compact [compact_space α] (C0 : (0 : ℝ) < C) :
dist f g < C ↔ ∀x:α, dist (f x) (g x) < C :=
begin
fsplit,
{ intros w x,
exact lt_of_le_of_lt (dist_coe_le_dist x) w, },
{ by_cases h : nonempty α,
{ resetI,
exact dist_lt_of_nonempty_compact, },
{ rintro -,
convert C0,
apply le_antisymm _ dist_nonneg',
rw [dist_eq],
exact cInf_le ⟨0, λ C, and.left⟩ ⟨le_refl _, λ x, false.elim (h (nonempty.intro x))⟩, }, },
end
lemma dist_lt_iff_of_nonempty_compact [nonempty α] [compact_space α] :
dist f g < C ↔ ∀x:α, dist (f x) (g x) < C :=
⟨λ w x, lt_of_le_of_lt (dist_coe_le_dist x) w, dist_lt_of_nonempty_compact⟩
/-- On an empty space, bounded continuous functions are at distance 0 -/
lemma dist_zero_of_empty (e : ¬ nonempty α) : dist f g = 0 :=
le_antisymm ((dist_le (le_refl _)).2 $ λ x, e.elim ⟨x⟩) dist_nonneg'
/-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/
instance : metric_space (α →ᵇ β) :=
{ dist_self := λ f, le_antisymm ((dist_le (le_refl _)).2 $ λ x, by simp) dist_nonneg',
eq_of_dist_eq_zero := λ f g hfg, by ext x; exact
eq_of_dist_eq_zero (le_antisymm (hfg ▸ dist_coe_le_dist _) dist_nonneg),
dist_comm := λ f g, by simp [dist_eq, dist_comm],
dist_triangle := λ f g h,
(dist_le (add_nonneg dist_nonneg' dist_nonneg')).2 $ λ x,
le_trans (dist_triangle _ _ _) (add_le_add (dist_coe_le_dist _) (dist_coe_le_dist _)) }
variables (α) {β}
/-- Constant as a continuous bounded function. -/
def const (b : β) : α →ᵇ β := ⟨continuous_map.const b, 0, by simp [le_refl]⟩
variable {α}
@[simp] lemma coe_const (b : β) : ⇑(const α b) = function.const α b := rfl
lemma const_apply (a : α) (b : β) : (const α b : α → β) a = b := rfl
/-- If the target space is inhabited, so is the space of bounded continuous functions -/
instance [inhabited β] : inhabited (α →ᵇ β) := ⟨const α (default β)⟩
/-- The evaluation map is continuous, as a joint function of `u` and `x` -/
@[continuity] theorem continuous_eval : continuous (λ p : (α →ᵇ β) × α, p.1 p.2) :=
continuous_iff'.2 $ λ ⟨f, x⟩ ε ε0,
/- use the continuity of `f` to find a neighborhood of `x` where it varies at most by ε/2 -/
have Hs : _ := continuous_iff'.1 f.continuous x (ε/2) (half_pos ε0),
mem_sets_of_superset (prod_is_open.mem_nhds (ball_mem_nhds _ (half_pos ε0)) Hs) $
λ ⟨g, y⟩ ⟨hg, hy⟩, calc dist (g y) (f x)
≤ dist (g y) (f y) + dist (f y) (f x) : dist_triangle _ _ _
... < ε/2 + ε/2 : add_lt_add (lt_of_le_of_lt (dist_coe_le_dist _) hg) hy
... = ε : add_halves _
/-- In particular, when `x` is fixed, `f → f x` is continuous -/
@[continuity] theorem continuous_evalx {x : α} : continuous (λ f : α →ᵇ β, f x) :=
continuous_eval.comp (continuous_id.prod_mk continuous_const)
/-- Bounded continuous functions taking values in a complete space form a complete space. -/
instance [complete_space β] : complete_space (α →ᵇ β) :=
complete_of_cauchy_seq_tendsto $ λ (f : ℕ → α →ᵇ β) (hf : cauchy_seq f),
begin
/- We have to show that `f n` converges to a bounded continuous function.
For this, we prove pointwise convergence to define the limit, then check
it is a continuous bounded function, and then check the norm convergence. -/
rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩,
have f_bdd := λx n m N hn hm, le_trans (dist_coe_le_dist x) (b_bound n m N hn hm),
have fx_cau : ∀x, cauchy_seq (λn, f n x) :=
λx, cauchy_seq_iff_le_tendsto_0.2 ⟨b, b0, f_bdd x, b_lim⟩,
choose F hF using λx, cauchy_seq_tendsto_of_complete (fx_cau x),
/- F : α → β, hF : ∀ (x : α), tendsto (λ (n : ℕ), f n x) at_top (𝓝 (F x))
`F` is the desired limit function. Check that it is uniformly approximated by `f N` -/
have fF_bdd : ∀x N, dist (f N x) (F x) ≤ b N :=
λ x N, le_of_tendsto (tendsto_const_nhds.dist (hF x))
(filter.eventually_at_top.2 ⟨N, λn hn, f_bdd x N n N (le_refl N) hn⟩),
refine ⟨⟨⟨F, _⟩, _⟩, _⟩,
{ /- Check that `F` is continuous, as a uniform limit of continuous functions -/
have : tendsto_uniformly (λn x, f n x) F at_top,
{ refine metric.tendsto_uniformly_iff.2 (λ ε ε0, _),
refine ((tendsto_order.1 b_lim).2 ε ε0).mono (λ n hn x, _),
rw dist_comm,
exact lt_of_le_of_lt (fF_bdd x n) hn },
exact this.continuous (λN, (f N).continuous) },
{ /- Check that `F` is bounded -/
rcases (f 0).bounded with ⟨C, hC⟩,
refine ⟨C + (b 0 + b 0), λ x y, _⟩,
calc dist (F x) (F y) ≤ dist (f 0 x) (f 0 y) + (dist (f 0 x) (F x) + dist (f 0 y) (F y)) :
dist_triangle4_left _ _ _ _
... ≤ C + (b 0 + b 0) : by mono* },
{ /- Check that `F` is close to `f N` in distance terms -/
refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero (λ _, dist_nonneg) _ b_lim),
exact λ N, (dist_le (b0 _)).2 (λx, fF_bdd x N) }
end
/-- Composition (in the target) of a bounded continuous function with a Lipschitz map again
gives a bounded continuous function -/
def comp (G : β → γ) {C : ℝ≥0} (H : lipschitz_with C G)
(f : α →ᵇ β) : α →ᵇ γ :=
⟨⟨λx, G (f x), H.continuous.comp f.continuous⟩,
let ⟨D, hD⟩ := f.bounded in
⟨max C 0 * D, λ x y, calc
dist (G (f x)) (G (f y)) ≤ C * dist (f x) (f y) : H.dist_le_mul _ _
... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left C 0) dist_nonneg
... ≤ max C 0 * D : mul_le_mul_of_nonneg_left (hD _ _) (le_max_right C 0)⟩⟩
/-- The composition operator (in the target) with a Lipschitz map is Lipschitz -/
lemma lipschitz_comp {G : β → γ} {C : ℝ≥0} (H : lipschitz_with C G) :
lipschitz_with C (comp G H : (α →ᵇ β) → α →ᵇ γ) :=
lipschitz_with.of_dist_le_mul $ λ f g,
(dist_le (mul_nonneg C.2 dist_nonneg)).2 $ λ x,
calc dist (G (f x)) (G (g x)) ≤ C * dist (f x) (g x) : H.dist_le_mul _ _
... ≤ C * dist f g : mul_le_mul_of_nonneg_left (dist_coe_le_dist _) C.2
/-- The composition operator (in the target) with a Lipschitz map is uniformly continuous -/
lemma uniform_continuous_comp {G : β → γ} {C : ℝ≥0} (H : lipschitz_with C G) :
uniform_continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) :=
(lipschitz_comp H).uniform_continuous
/-- The composition operator (in the target) with a Lipschitz map is continuous -/
lemma continuous_comp {G : β → γ} {C : ℝ≥0} (H : lipschitz_with C G) :
continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) :=
(lipschitz_comp H).continuous
/-- Restriction (in the target) of a bounded continuous function taking values in a subset -/
def cod_restrict (s : set β) (f : α →ᵇ β) (H : ∀x, f x ∈ s) : α →ᵇ s :=
⟨⟨s.cod_restrict f H, continuous_subtype_mk _ f.continuous⟩, f.bounded⟩
end basics
section arzela_ascoli
variables [topological_space α] [compact_space α] [metric_space β]
variables {f g : α →ᵇ β} {x : α} {C : ℝ}
/- Arzela-Ascoli theorem asserts that, on a compact space, a set of functions sharing
a common modulus of continuity and taking values in a compact set forms a compact
subset for the topology of uniform convergence. In this section, we prove this theorem
and several useful variations around it. -/
/-- First version, with pointwise equicontinuity and range in a compact space -/
theorem arzela_ascoli₁ [compact_space β]
(A : set (α →ᵇ β))
(closed : is_closed A)
(H : ∀ (x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε) :
is_compact A :=
begin
refine compact_of_totally_bounded_is_closed _ closed,
refine totally_bounded_of_finite_discretization (λ ε ε0, _),
rcases exists_between ε0 with ⟨ε₁, ε₁0, εε₁⟩,
let ε₂ := ε₁/2/2,
/- We have to find a finite discretization of `u`, i.e., finite information
that is sufficient to reconstruct `u` up to ε. This information will be
provided by the values of `u` on a sufficiently dense set tα,
slightly translated to fit in a finite ε₂-dense set tβ in the image. Such
sets exist by compactness of the source and range. Then, to check that these
data determine the function up to ε, one uses the control on the modulus of
continuity to extend the closeness on tα to closeness everywhere. -/
have ε₂0 : ε₂ > 0 := half_pos (half_pos ε₁0),
have : ∀x:α, ∃U, x ∈ U ∧ is_open U ∧ ∀ (y z ∈ U) {f : α →ᵇ β},
f ∈ A → dist (f y) (f z) < ε₂ := λ x,
let ⟨U, nhdsU, hU⟩ := H x _ ε₂0,
⟨V, VU, openV, xV⟩ := _root_.mem_nhds_iff.1 nhdsU in
⟨V, xV, openV, λy z hy hz f hf, hU y z (VU hy) (VU hz) f hf⟩,
choose U hU using this,
/- For all x, the set hU x is an open set containing x on which the elements of A
fluctuate by at most ε₂.
We extract finitely many of these sets that cover the whole space, by compactness -/
rcases compact_univ.elim_finite_subcover_image
(λx _, (hU x).2.1) (λx hx, mem_bUnion (mem_univ _) (hU x).1)
with ⟨tα, _, ⟨_⟩, htα⟩,
/- tα : set α, htα : univ ⊆ ⋃x ∈ tα, U x -/
rcases @finite_cover_balls_of_compact β _ _ compact_univ _ ε₂0
with ⟨tβ, _, ⟨_⟩, htβ⟩, resetI,
/- tβ : set β, htβ : univ ⊆ ⋃y ∈ tβ, ball y ε₂ -/
/- Associate to every point `y` in the space a nearby point `F y` in tβ -/
choose F hF using λy, show ∃z∈tβ, dist y z < ε₂, by simpa using htβ (mem_univ y),
/- F : β → β, hF : ∀ (y : β), F y ∈ tβ ∧ dist y (F y) < ε₂ -/
/- Associate to every function a discrete approximation, mapping each point in `tα`
to a point in `tβ` close to its true image by the function. -/
refine ⟨tα → tβ, by apply_instance, λ f a, ⟨F (f a), (hF (f a)).1⟩, _⟩,
rintro ⟨f, hf⟩ ⟨g, hg⟩ f_eq_g,
/- If two functions have the same approximation, then they are within distance ε -/
refine lt_of_le_of_lt ((dist_le $ le_of_lt ε₁0).2 (λ x, _)) εε₁,
obtain ⟨x', x'tα, hx'⟩ : ∃x' ∈ tα, x ∈ U x' := mem_bUnion_iff.1 (htα (mem_univ x)),
refine calc dist (f x) (g x)
≤ dist (f x) (f x') + dist (g x) (g x') + dist (f x') (g x') : dist_triangle4_right _ _ _ _
... ≤ ε₂ + ε₂ + ε₁/2 : le_of_lt (add_lt_add (add_lt_add _ _) _)
... = ε₁ : by rw [add_halves, add_halves],
{ exact (hU x').2.2 _ _ hx' ((hU x').1) hf },
{ exact (hU x').2.2 _ _ hx' ((hU x').1) hg },
{ have F_f_g : F (f x') = F (g x') :=
(congr_arg (λ f:tα → tβ, (f ⟨x', x'tα⟩ : β)) f_eq_g : _),
calc dist (f x') (g x')
≤ dist (f x') (F (f x')) + dist (g x') (F (f x')) : dist_triangle_right _ _ _
... = dist (f x') (F (f x')) + dist (g x') (F (g x')) : by rw F_f_g
... < ε₂ + ε₂ : add_lt_add (hF (f x')).2 (hF (g x')).2
... = ε₁/2 : add_halves _ }
end
/-- Second version, with pointwise equicontinuity and range in a compact subset -/
theorem arzela_ascoli₂
(s : set β) (hs : is_compact s)
(A : set (α →ᵇ β))
(closed : is_closed A)
(in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s)
(H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε) :
is_compact A :=
/- This version is deduced from the previous one by restricting to the compact type in the target,
using compactness there and then lifting everything to the original space. -/
begin
have M : lipschitz_with 1 coe := lipschitz_with.subtype_coe s,
let F : (α →ᵇ s) → α →ᵇ β := comp coe M,
refine compact_of_is_closed_subset
((_ : is_compact (F ⁻¹' A)).image (continuous_comp M)) closed (λ f hf, _),
{ haveI : compact_space s := is_compact_iff_compact_space.1 hs,
refine arzela_ascoli₁ _ (continuous_iff_is_closed.1 (continuous_comp M) _ closed)
(λ x ε ε0, bex.imp_right (λ U U_nhds hU y z hy hz f hf, _) (H x ε ε0)),
calc dist (f y) (f z) = dist (F f y) (F f z) : rfl
... < ε : hU y z hy hz (F f) hf },
{ let g := cod_restrict s f (λx, in_s f x hf),
rw [show f = F g, by ext; refl] at hf ⊢,
exact ⟨g, hf, rfl⟩ }
end
/-- Third (main) version, with pointwise equicontinuity and range in a compact subset, but
without closedness. The closure is then compact -/
theorem arzela_ascoli
(s : set β) (hs : is_compact s)
(A : set (α →ᵇ β))
(in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s)
(H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε) :
is_compact (closure A) :=
/- This version is deduced from the previous one by checking that the closure of A, in
addition to being closed, still satisfies the properties of compact range and equicontinuity -/
arzela_ascoli₂ s hs (closure A) is_closed_closure
(λ f x hf, (mem_of_closed' hs.is_closed).2 $ λ ε ε0,
let ⟨g, gA, dist_fg⟩ := metric.mem_closure_iff.1 hf ε ε0 in
⟨g x, in_s g x gA, lt_of_le_of_lt (dist_coe_le_dist _) dist_fg⟩)
(λ x ε ε0, show ∃ U ∈ 𝓝 x,
∀ y z ∈ U, ∀ (f : α →ᵇ β), f ∈ closure A → dist (f y) (f z) < ε,
begin
refine bex.imp_right (λ U U_set hU y z hy hz f hf, _) (H x (ε/2) (half_pos ε0)),
rcases metric.mem_closure_iff.1 hf (ε/2/2) (half_pos (half_pos ε0)) with ⟨g, gA, dist_fg⟩,
replace dist_fg := λ x, lt_of_le_of_lt (dist_coe_le_dist x) dist_fg,
calc dist (f y) (f z) ≤ dist (f y) (g y) + dist (f z) (g z) + dist (g y) (g z) :
dist_triangle4_right _ _ _ _
... < ε/2/2 + ε/2/2 + ε/2 :
add_lt_add (add_lt_add (dist_fg y) (dist_fg z)) (hU y z hy hz g gA)
... = ε : by rw [add_halves, add_halves]
end)
/- To apply the previous theorems, one needs to check the equicontinuity. An important
instance is when the source space is a metric space, and there is a fixed modulus of continuity
for all the functions in the set A -/
lemma equicontinuous_of_continuity_modulus {α : Type u} [metric_space α]
(b : ℝ → ℝ) (b_lim : tendsto b (𝓝 0) (𝓝 0))
(A : set (α →ᵇ β))
(H : ∀(x y:α) (f : α →ᵇ β), f ∈ A → dist (f x) (f y) ≤ b (dist x y))
(x:α) (ε : ℝ) (ε0 : 0 < ε) : ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε :=
begin
rcases tendsto_nhds_nhds.1 b_lim ε ε0 with ⟨δ, δ0, hδ⟩,
refine ⟨ball x (δ/2), ball_mem_nhds x (half_pos δ0), λ y z hy hz f hf, _⟩,
have : dist y z < δ := calc
dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _
... < δ/2 + δ/2 : add_lt_add hy hz
... = δ : add_halves _,
calc
dist (f y) (f z) ≤ b (dist y z) : H y z f hf
... ≤ abs (b (dist y z)) : le_abs_self _
... = dist (b (dist y z)) 0 : by simp [real.dist_eq]
... < ε : hδ (by simpa [real.dist_eq] using this),
end
end arzela_ascoli
section normed_group
/- In this section, if β is a normed group, then we show that the space of bounded
continuous functions from α to β inherits a normed group structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables [topological_space α] [normed_group β]
variables (f g : α →ᵇ β) {x : α} {C : ℝ}
instance : has_zero (α →ᵇ β) := ⟨const α 0⟩
@[simp] lemma coe_zero : ((0 : α →ᵇ β) : α → β) = 0 := rfl
instance : has_norm (α →ᵇ β) := ⟨λu, dist u 0⟩
lemma norm_def : ∥f∥ = dist f 0 := rfl
/-- The norm of a bounded continuous function is the supremum of `∥f x∥`.
We use `Inf` to ensure that the definition works if `α` has no elements. -/
lemma norm_eq (f : α →ᵇ β) :
∥f∥ = Inf {C : ℝ | 0 ≤ C ∧ ∀ (x : α), ∥f x∥ ≤ C} :=
by simp [norm_def, bounded_continuous_function.dist_eq]
lemma norm_coe_le_norm (x : α) : ∥f x∥ ≤ ∥f∥ := calc
∥f x∥ = dist (f x) ((0 : α →ᵇ β) x) : by simp [dist_zero_right]
... ≤ ∥f∥ : dist_coe_le_dist _
lemma dist_le_two_norm' {f : γ → β} {C : ℝ} (hC : ∀ x, ∥f x∥ ≤ C) (x y : γ) :
dist (f x) (f y) ≤ 2 * C :=
calc dist (f x) (f y) ≤ ∥f x∥ + ∥f y∥ : dist_le_norm_add_norm _ _
... ≤ C + C : add_le_add (hC x) (hC y)
... = 2 * C : (two_mul _).symm
/-- Distance between the images of any two points is at most twice the norm of the function. -/
lemma dist_le_two_norm (x y : α) : dist (f x) (f y) ≤ 2 * ∥f∥ :=
dist_le_two_norm' f.norm_coe_le_norm x y
variable {f}
/-- The norm of a function is controlled by the supremum of the pointwise norms -/
lemma norm_le (C0 : (0 : ℝ) ≤ C) : ∥f∥ ≤ C ↔ ∀x:α, ∥f x∥ ≤ C :=
by simpa using @dist_le _ _ _ _ f 0 _ C0
lemma norm_le_of_nonempty [nonempty α]
{f : α →ᵇ β} {M : ℝ} : ∥f∥ ≤ M ↔ ∀ x, ∥f x∥ ≤ M :=
begin
simp_rw [norm_def, ←dist_zero_right],
exact dist_le_iff_of_nonempty,
end
lemma norm_lt_iff_of_compact [compact_space α]
{f : α →ᵇ β} {M : ℝ} (M0 : 0 < M) : ∥f∥ < M ↔ ∀ x, ∥f x∥ < M :=
begin
simp_rw [norm_def, ←dist_zero_right],
exact dist_lt_iff_of_compact M0,
end
lemma norm_lt_iff_of_nonempty_compact [nonempty α] [compact_space α]
{f : α →ᵇ β} {M : ℝ} : ∥f∥ < M ↔ ∀ x, ∥f x∥ < M :=
begin
simp_rw [norm_def, ←dist_zero_right],
exact dist_lt_iff_of_nonempty_compact,
end
variable (f)
/-- Norm of `const α b` is less than or equal to `∥b∥`. If `α` is nonempty,
then it is equal to `∥b∥`. -/
lemma norm_const_le (b : β) : ∥const α b∥ ≤ ∥b∥ :=
(norm_le (norm_nonneg b)).2 $ λ x, le_refl _
@[simp] lemma norm_const_eq [h : nonempty α] (b : β) : ∥const α b∥ = ∥b∥ :=
le_antisymm (norm_const_le b) $ h.elim $ λ x, (const α b).norm_coe_le_norm x
/-- Constructing a bounded continuous function from a uniformly bounded continuous
function taking values in a normed group. -/
def of_normed_group {α : Type u} {β : Type v} [topological_space α] [normed_group β]
(f : α → β) (Hf : continuous f) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) : α →ᵇ β :=
⟨⟨λn, f n, Hf⟩, ⟨_, dist_le_two_norm' H⟩⟩
@[simp] lemma coe_of_normed_group
{α : Type u} {β : Type v} [topological_space α] [normed_group β]
(f : α → β) (Hf : continuous f) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) :
(of_normed_group f Hf C H : α → β) = f := rfl
lemma norm_of_normed_group_le {f : α → β} (hfc : continuous f) {C : ℝ} (hC : 0 ≤ C)
(hfC : ∀ x, ∥f x∥ ≤ C) : ∥of_normed_group f hfc C hfC∥ ≤ C :=
(norm_le hC).2 hfC
/-- Constructing a bounded continuous function from a uniformly bounded
function on a discrete space, taking values in a normed group -/
def of_normed_group_discrete {α : Type u} {β : Type v}
[topological_space α] [discrete_topology α] [normed_group β]
(f : α → β) (C : ℝ) (H : ∀x, norm (f x) ≤ C) : α →ᵇ β :=
of_normed_group f continuous_of_discrete_topology C H
@[simp] lemma coe_of_normed_group_discrete
{α : Type u} {β : Type v} [topological_space α] [discrete_topology α] [normed_group β]
(f : α → β) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) :
(of_normed_group_discrete f C H : α → β) = f := rfl
/-- The pointwise sum of two bounded continuous functions is again bounded continuous. -/
instance : has_add (α →ᵇ β) :=
⟨λf g, of_normed_group (f + g) (f.continuous.add g.continuous) (∥f∥ + ∥g∥) $ λ x,
le_trans (norm_add_le _ _) (add_le_add (f.norm_coe_le_norm x) (g.norm_coe_le_norm x))⟩
/-- The pointwise opposite of a bounded continuous function is again bounded continuous. -/
instance : has_neg (α →ᵇ β) :=
⟨λf, of_normed_group (-f) f.continuous.neg ∥f∥ $ λ x,
trans_rel_right _ (norm_neg _) (f.norm_coe_le_norm x)⟩
/-- The pointwise difference of two bounded continuous functions is again bounded continuous. -/
instance : has_sub (α →ᵇ β) :=
⟨λf g, of_normed_group (f - g) (f.continuous.sub g.continuous) (∥f∥ + ∥g∥) $ λ x,
by { simp only [sub_eq_add_neg],
exact le_trans (norm_add_le _ _) (add_le_add (f.norm_coe_le_norm x) $
trans_rel_right _ (norm_neg _) (g.norm_coe_le_norm x)) }⟩
@[simp] lemma coe_add : ⇑(f + g) = f + g := rfl
lemma add_apply : (f + g) x = f x + g x := rfl
@[simp] lemma coe_neg : ⇑(-f) = -f := rfl
lemma neg_apply : (-f) x = -f x := rfl
lemma forall_coe_zero_iff_zero : (∀x, f x = 0) ↔ f = 0 :=
(@ext_iff _ _ _ _ f 0).symm
instance : add_comm_group (α →ᵇ β) :=
{ add_assoc := assume f g h, by ext; simp [add_assoc],
zero_add := assume f, by ext; simp,
add_zero := assume f, by ext; simp,
add_left_neg := assume f, by ext; simp,
add_comm := assume f g, by ext; simp [add_comm],
sub_eq_add_neg := assume f g, by { ext, apply sub_eq_add_neg },
..bounded_continuous_function.has_add,
..bounded_continuous_function.has_neg,
..bounded_continuous_function.has_sub,
..bounded_continuous_function.has_zero }
@[simp] lemma coe_sub : ⇑(f - g) = f - g := rfl
lemma sub_apply : (f - g) x = f x - g x := rfl
/-- Coercion of a `normed_group_hom` is an `add_monoid_hom`. Similar to `add_monoid_hom.coe_fn` -/
@[simps]
def coe_fn_add_hom : (α →ᵇ β) →+ (α → β) :=
{ to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add}
open_locale big_operators
@[simp] lemma coe_sum {ι : Type*} (s : finset ι) (f : ι → (α →ᵇ β)) :
⇑(∑ i in s, f i) = (∑ i in s, (f i : α → β)) :=
(@coe_fn_add_hom α β _ _).map_sum f s
lemma sum_apply {ι : Type*} (s : finset ι) (f : ι → (α →ᵇ β)) (a : α) :
(∑ i in s, f i) a = (∑ i in s, f i a) :=
by simp
instance : normed_group (α →ᵇ β) :=
{ dist_eq := λ f g, by simp only [norm_eq, dist_eq, dist_eq_norm, sub_apply] }
lemma abs_diff_coe_le_dist : ∥f x - g x∥ ≤ dist f g :=
by { rw dist_eq_norm, exact (f - g).norm_coe_le_norm x }
lemma coe_le_coe_add_dist {f g : α →ᵇ ℝ} : f x ≤ g x + dist f g :=
sub_le_iff_le_add'.1 $ (abs_le.1 $ @dist_coe_le_dist _ _ _ _ f g x).2
variables (α β)
/--
The additive map forgetting that a bounded continuous function is bounded.
-/
@[simps]
def forget_boundedness_add_hom : (α →ᵇ β) →+ C(α, β) :=
{ to_fun := forget_boundedness α β,
map_zero' := by { ext, simp, },
map_add' := by { intros, ext, simp, }, }
end normed_group
section normed_space
/-!
### Normed space structure
In this section, if `β` is a normed space, then we show that the space of bounded
continuous functions from `α` to `β` inherits a normed space structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables {𝕜 : Type*}
variables [topological_space α] [normed_group β]
variables {f g : α →ᵇ β} {x : α} {C : ℝ}
section normed_field
variables [normed_field 𝕜] [normed_space 𝕜 β]
instance : has_scalar 𝕜 (α →ᵇ β) :=
⟨λ c f, of_normed_group (c • f) (f.continuous.const_smul c) (∥c∥ * ∥f∥) $ λ x,
trans_rel_right _ (norm_smul _ _)
(mul_le_mul_of_nonneg_left (f.norm_coe_le_norm _) (norm_nonneg _))⟩
@[simp] lemma coe_smul (c : 𝕜) (f : α →ᵇ β) : ⇑(c • f) = λ x, c • (f x) := rfl
lemma smul_apply (c : 𝕜) (f : α →ᵇ β) (x : α) : (c • f) x = c • f x := rfl
instance : module 𝕜 (α →ᵇ β) :=
module.of_core $
{ smul := (•),
smul_add := λ c f g, ext $ λ x, smul_add c (f x) (g x),
add_smul := λ c₁ c₂ f, ext $ λ x, add_smul c₁ c₂ (f x),
mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul c₁ c₂ (f x),
one_smul := λ f, ext $ λ x, one_smul 𝕜 (f x) }
instance : normed_space 𝕜 (α →ᵇ β) := ⟨λ c f, norm_of_normed_group_le _
(mul_nonneg (norm_nonneg _) (norm_nonneg _)) _⟩
variables (𝕜)
/-- The evaluation at a point, as a continuous linear map from `α →ᵇ β` to `β`. -/
def eval_clm (x : α) : (α →ᵇ β) →L[𝕜] β :=
{ to_fun := λ f, f x,
map_add' := λ f g, by simp only [pi.add_apply, coe_add],
map_smul' := λ c f, by simp only [coe_smul] }
@[simp] lemma eval_clm_apply (x : α) (f : α →ᵇ β) :
eval_clm 𝕜 x f = f x := rfl
variables (α β)
/-- The linear map forgetting that a bounded continuous function is bounded. -/
@[simps]
def forget_boundedness_linear_map : (α →ᵇ β) →ₗ[𝕜] C(α, β) :=
{ to_fun := forget_boundedness α β,
map_smul' := by { intros, ext, simp, },
map_add' := by { intros, ext, simp, }, }
end normed_field
variables [nondiscrete_normed_field 𝕜] [normed_space 𝕜 β]
variables [normed_group γ] [normed_space 𝕜 γ]
variables (α)
/--
Postcomposition of bounded continuous functions into a normed module by a continuous linear map is
a continuous linear map.
Upgraded version of `continuous_linear_map.comp_left_continuous`, similar to
`linear_map.comp_left`. -/
protected def _root_.continuous_linear_map.comp_left_continuous_bounded (g : β →L[𝕜] γ) :
(α →ᵇ β) →L[𝕜] (α →ᵇ γ) :=
linear_map.mk_continuous
{ to_fun := λ f, of_normed_group
(g ∘ f)
(g.continuous.comp f.continuous)
(∥g∥ * ∥f∥)
(λ x, (g.le_op_norm_of_le (f.norm_coe_le_norm x))),
map_add' := λ f g, by ext; simp,
map_smul' := λ c f, by ext; simp }
∥g∥
(λ f, norm_of_normed_group_le _ (mul_nonneg (norm_nonneg g) (norm_nonneg f)) _)
@[simp] lemma _root_.continuous_linear_map.comp_left_continuous_bounded_apply (g : β →L[𝕜] γ)
(f : α →ᵇ β) (x : α) :
(g.comp_left_continuous_bounded α f) x = g (f x) :=
rfl
end normed_space
section normed_ring
/-!
### Normed ring structure
In this section, if `R` is a normed ring, then we show that the space of bounded
continuous functions from `α` to `R` inherits a normed ring structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables [topological_space α] {R : Type*} [normed_ring R]
instance : ring (α →ᵇ R) :=
{ one := const α 1,
mul := λ f g, of_normed_group (f * g) (f.continuous.mul g.continuous) (∥f∥ * ∥g∥) $ λ x,
le_trans (normed_ring.norm_mul (f x) (g x)) $
mul_le_mul (f.norm_coe_le_norm x) (g.norm_coe_le_norm x) (norm_nonneg _) (norm_nonneg _),
one_mul := λ f, ext $ λ x, one_mul (f x),
mul_one := λ f, ext $ λ x, mul_one (f x),
mul_assoc := λ f₁ f₂ f₃, ext $ λ x, mul_assoc _ _ _,
left_distrib := λ f₁ f₂ f₃, ext $ λ x, left_distrib _ _ _,
right_distrib := λ f₁ f₂ f₃, ext $ λ x, right_distrib _ _ _,
.. bounded_continuous_function.add_comm_group }
@[simp] lemma coe_mul (f g : α →ᵇ R) : ⇑(f * g) = f * g := rfl
lemma mul_apply (f g : α →ᵇ R) (x : α) : (f * g) x = f x * g x := rfl
instance : normed_ring (α →ᵇ R) :=
{ norm_mul := λ f g, norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _,
.. bounded_continuous_function.normed_group }
end normed_ring
section normed_comm_ring
/-!
### Normed commutative ring structure
In this section, if `R` is a normed commutative ring, then we show that the space of bounded
continuous functions from `α` to `R` inherits a normed commutative ring structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables [topological_space α] {R : Type*} [normed_comm_ring R]
instance : comm_ring (α →ᵇ R) :=
{ mul_comm := λ f₁ f₂, ext $ λ x, mul_comm _ _,
.. bounded_continuous_function.ring }
instance : normed_comm_ring (α →ᵇ R) :=
{ .. bounded_continuous_function.comm_ring, .. bounded_continuous_function.normed_group }
end normed_comm_ring
section normed_algebra
/-!
### Normed algebra structure
In this section, if `γ` is a normed algebra, then we show that the space of bounded
continuous functions from `α` to `γ` inherits a normed algebra structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables {𝕜 : Type*} [normed_field 𝕜]
variables [topological_space α] [normed_group β] [normed_space 𝕜 β]
variables [normed_ring γ] [normed_algebra 𝕜 γ]
variables {f g : α →ᵇ γ} {x : α} {c : 𝕜}
/-- `bounded_continuous_function.const` as a `ring_hom`. -/
def C : 𝕜 →+* (α →ᵇ γ) :=
{ to_fun := λ (c : 𝕜), const α ((algebra_map 𝕜 γ) c),
map_one' := ext $ λ x, (algebra_map 𝕜 γ).map_one,
map_mul' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_mul _ _,
map_zero' := ext $ λ x, (algebra_map 𝕜 γ).map_zero,
map_add' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_add _ _ }
instance : algebra 𝕜 (α →ᵇ γ) :=
{ to_ring_hom := C,
commutes' := λ c f, ext $ λ x, algebra.commutes' _ _,
smul_def' := λ c f, ext $ λ x, algebra.smul_def' _ _,
..bounded_continuous_function.module,
..bounded_continuous_function.ring }
@[simp] lemma algebra_map_apply (k : 𝕜) (a : α) :
algebra_map 𝕜 (α →ᵇ γ) k a = k • 1 :=
by { rw algebra.algebra_map_eq_smul_one, refl, }
instance [nonempty α] : normed_algebra 𝕜 (α →ᵇ γ) :=
{ norm_algebra_map_eq := λ c, begin
calc ∥ (algebra_map 𝕜 (α →ᵇ γ)).to_fun c∥ = ∥(algebra_map 𝕜 γ) c∥ : _
... = ∥c∥ : norm_algebra_map_eq _ _,
apply norm_const_eq ((algebra_map 𝕜 γ) c), assumption,
end,
..bounded_continuous_function.algebra }
/-!
### Structure as normed module over scalar functions
If `β` is a normed `𝕜`-space, then we show that the space of bounded continuous
functions from `α` to `β` is naturally a module over the algebra of bounded continuous
functions from `α` to `𝕜`. -/
instance has_scalar' : has_scalar (α →ᵇ 𝕜) (α →ᵇ β) :=
⟨λ (f : α →ᵇ 𝕜) (g : α →ᵇ β), of_normed_group (λ x, (f x) • (g x))
(f.continuous.smul g.continuous) (∥f∥ * ∥g∥) (λ x, calc
∥f x • g x∥ ≤ ∥f x∥ * ∥g x∥ : normed_space.norm_smul_le _ _
... ≤ ∥f∥ * ∥g∥ : mul_le_mul (f.norm_coe_le_norm _) (g.norm_coe_le_norm _) (norm_nonneg _)
(norm_nonneg _)) ⟩
instance module' : module (α →ᵇ 𝕜) (α →ᵇ β) :=
module.of_core $
{ smul := (•),
smul_add := λ c f₁ f₂, ext $ λ x, smul_add _ _ _,
add_smul := λ c₁ c₂ f, ext $ λ x, add_smul _ _ _,
mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _,
one_smul := λ f, ext $ λ x, one_smul 𝕜 (f x) }
lemma norm_smul_le (f : α →ᵇ 𝕜) (g : α →ᵇ β) : ∥f • g∥ ≤ ∥f∥ * ∥g∥ :=
norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _
/- TODO: When `normed_module` has been added to `normed_space.basic`, the above facts
show that the space of bounded continuous functions from `α` to `β` is naturally a normed
module over the algebra of bounded continuous functions from `α` to `𝕜`. -/
end normed_algebra
end bounded_continuous_function
|
58dcc1623ba8953526f43b9a5b58cc6fc56c0b9f | d436468d80b739ba7e06843c4d0d2070e43448e5 | /src/topology/uniform_space/pi.lean | 86eb386353e69bfe38b76af29c9a10e2a3d0c841 | [
"Apache-2.0"
] | permissive | roro47/mathlib | 761fdc002aef92f77818f3fef06bf6ec6fc1a28e | 80aa7d52537571a2ca62a3fdf71c9533a09422cf | refs/heads/master | 1,599,656,410,625 | 1,573,649,488,000 | 1,573,649,488,000 | 221,452,951 | 0 | 0 | Apache-2.0 | 1,573,647,693,000 | 1,573,647,692,000 | null | UTF-8 | Lean | false | false | 1,982 | lean | /-
Copyright (c) 2019 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
Indexed product of uniform spaces
-/
import topology.uniform_space.cauchy
import topology.uniform_space.separation
noncomputable theory
open_locale uniformity topological_space
section
open filter lattice uniform_space
universe u
variables {ι : Type*} (α : ι → Type u) [U : Πi, uniform_space (α i)]
include U
instance Pi.uniform_space : uniform_space (Πi, α i) :=
uniform_space.of_core_eq
(⨅i, uniform_space.comap (λ a : Πi, α i, a i) (U i)).to_core
Pi.topological_space $ eq.symm to_topological_space_infi
lemma Pi.uniformity :
𝓤 (Π i, α i) = ⨅ i : ι, filter.comap (λ a, (a.1 i, a.2 i)) $ 𝓤 (α i) :=
infi_uniformity
lemma Pi.uniform_continuous_proj (i : ι) : uniform_continuous (λ (a : Π (i : ι), α i), a i) :=
begin
rw uniform_continuous_iff,
exact infi_le (λ j, uniform_space.comap (λ (a : Π (i : ι), α i), a j) (U j)) i
end
lemma Pi.uniform_space_topology :
(Pi.uniform_space α).to_topological_space = Pi.topological_space := rfl
instance Pi.complete [∀ i, complete_space (α i)] : complete_space (Π i, α i) :=
⟨begin
intros f hf,
have : ∀ i, ∃ x : α i, filter.map (λ a : Πi, α i, a i) f ≤ 𝓝 x,
{ intro i,
have key : cauchy (map (λ (a : Π (i : ι), α i), a i) f),
from cauchy_map (Pi.uniform_continuous_proj α i) hf,
exact (cauchy_iff_exists_le_nhds $ map_ne_bot hf.1).1 key },
choose x hx using this,
use x,
rw [show 𝓝 x = (⨅i, comap (λa, a i) (𝓝 (x i))),
by rw Pi.uniform_space_topology ; exact nhds_pi,
le_infi_iff],
exact λ i, map_le_iff_le_comap.mp (hx i),
end⟩
instance Pi.separated [∀ i, separated (α i)] : separated (Π i, α i) :=
separated_def.2 $ assume x y H,
begin
ext i,
apply eq_of_separated_of_uniform_continuous (Pi.uniform_continuous_proj α i),
apply H,
end
end
|
20341de26fd12497de52f1c61f5311c913ea61b9 | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/data/rbtree/basic.lean | ea62e68897f589bae0eadcb2c3cb653c08e6e873 | [
"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 | 8,873 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import tactic.interactive
import data.rbtree.init
universe u
meta def tactic.interactive.blast_disjs : tactic unit :=
`[cases_type* or]
namespace rbnode
variables {α : Type u}
open color nat
inductive is_node_of : rbnode α → rbnode α → α → rbnode α → Prop
| of_red (l v r) : is_node_of (red_node l v r) l v r
| of_black (l v r) : is_node_of (black_node l v r) l v r
def lift (lt : α → α → Prop) : option α → option α → Prop
| (some a) (some b) := lt a b
| _ _ := true
inductive is_searchable (lt : α → α → Prop) : rbnode α → option α → option α → Prop
| leaf_s {lo hi} (hlt : lift lt lo hi) : is_searchable leaf lo hi
| red_s {l r v lo hi} (hs₁ : is_searchable l lo (some v)) (hs₂ : is_searchable r (some v) hi) :
is_searchable (red_node l v r) lo hi
| black_s {l r v lo hi} (hs₁ : is_searchable l lo (some v)) (hs₂ : is_searchable r (some v) hi) :
is_searchable (black_node l v r) lo hi
meta def is_searchable_tactic : tactic unit :=
`[
constructor_matching*
[is_searchable _ leaf _ _,
is_searchable _ (red_node _ _ _) _ _,
is_searchable _ (black_node _ _ _) _ _];
cases_matching*
[is_searchable _ leaf _ _,
is_searchable _ (red_node _ _ _) _ _,
is_searchable _ (black_node _ _ _) _ _];
try { assumption }
]
open rbnode (mem)
open is_searchable
section is_searchable_lemmas
variable {lt : α → α → Prop}
lemma lo_lt_hi {t : rbnode α} {lt} [is_trans α lt] :
∀ {lo hi}, is_searchable lt t lo hi → lift lt lo hi :=
begin
induction t; intros lo hi hs,
case leaf { cases hs, assumption },
all_goals {
cases hs,
have h₁ := t_ih_lchild hs_hs₁,
have h₂ := t_ih_rchild hs_hs₂,
cases lo; cases hi; simp [lift] at *,
apply trans_of lt h₁ h₂,
}
end
lemma is_searchable_of_is_searchable_of_incomp [is_strict_weak_order α lt] {t} :
∀ {lo hi hi'} (hc : ¬ lt hi' hi ∧ ¬ lt hi hi') (hs : is_searchable lt t lo (some hi)),
is_searchable lt t lo (some hi') :=
begin
classical,
induction t; intros; is_searchable_tactic,
{ cases lo; simp [lift, *] at *, apply lt_of_lt_of_incomp, assumption, exact ⟨hc.2, hc.1⟩ },
all_goals { apply t_ih_rchild hc hs_hs₂ }
end
lemma is_searchable_of_incomp_of_is_searchable [is_strict_weak_order α lt] {t} :
∀ {lo lo' hi} (hc : ¬ lt lo' lo ∧ ¬ lt lo lo') (hs : is_searchable lt t (some lo) hi),
is_searchable lt t (some lo') hi :=
begin
classical,
induction t; intros; is_searchable_tactic,
{ cases hi; simp [lift, *] at *, apply lt_of_incomp_of_lt, assumption, assumption },
all_goals { apply t_ih_lchild hc hs_hs₁ }
end
lemma is_searchable_some_low_of_is_searchable_of_lt {t} [is_trans α lt] :
∀ {lo hi lo'} (hlt : lt lo' lo) (hs : is_searchable lt t (some lo) hi),
is_searchable lt t (some lo') hi :=
begin
induction t; intros; is_searchable_tactic,
{ cases hi; simp [lift, *] at *, apply trans_of lt hlt, assumption },
all_goals { apply t_ih_lchild hlt hs_hs₁ }
end
lemma is_searchable_none_low_of_is_searchable_some_low {t} :
∀ {y hi} (hlt : is_searchable lt t (some y) hi), is_searchable lt t none hi :=
begin
induction t; intros; is_searchable_tactic,
{ simp [lift] },
all_goals { apply t_ih_lchild hlt_hs₁ }
end
lemma is_searchable_some_high_of_is_searchable_of_lt {t} [is_trans α lt] :
∀ {lo hi hi'} (hlt : lt hi hi') (hs : is_searchable lt t lo (some hi)),
is_searchable lt t lo (some hi') :=
begin
induction t; intros; is_searchable_tactic,
{ cases lo; simp [lift, *] at *, apply trans_of lt, assumption, assumption},
all_goals { apply t_ih_rchild hlt hs_hs₂ }
end
lemma is_searchable_none_high_of_is_searchable_some_high {t} :
∀ {lo y} (hlt : is_searchable lt t lo (some y)), is_searchable lt t lo none :=
begin
induction t; intros; is_searchable_tactic,
{ cases lo; simp [lift] },
all_goals { apply t_ih_rchild hlt_hs₂ }
end
lemma range [is_strict_weak_order α lt] {t : rbnode α} {x} :
∀ {lo hi}, is_searchable lt t lo hi → mem lt x t → lift lt lo (some x) ∧ lift lt (some x) hi :=
begin
classical,
induction t,
case leaf { simp [mem] },
all_goals { -- red_node and black_node are identical
intros lo hi h₁ h₂, cases h₁,
simp only [mem] at h₂,
have val_hi : lift lt (some t_val) hi, { apply lo_lt_hi, assumption },
have lo_val : lift lt lo (some t_val), { apply lo_lt_hi, assumption },
blast_disjs,
{
have h₃ : lift lt lo (some x) ∧ lift lt (some x) (some t_val),
{ apply t_ih_lchild, assumption, assumption },
cases h₃ with lo_x x_val,
split,
show lift lt lo (some x), { assumption },
show lift lt (some x ) hi, {
cases hi with hi; simp [lift] at *,
apply trans_of lt x_val val_hi
}
},
{
cases h₂,
cases lo with lo; cases hi with hi; simp [lift] at *,
{ apply lt_of_incomp_of_lt _ val_hi, simp [*] },
{ apply lt_of_lt_of_incomp lo_val, simp [*] },
split,
{ apply lt_of_lt_of_incomp lo_val, simp [*] },
{ apply lt_of_incomp_of_lt _ val_hi, simp [*] }
},
{
have h₃ : lift lt (some t_val) (some x) ∧ lift lt (some x) hi,
{ apply t_ih_rchild, assumption, assumption },
cases h₃ with val_x x_hi,
cases lo with lo; cases hi with hi; simp [lift] at *,
{ assumption },
{ apply trans_of lt lo_val val_x },
split,
{ apply trans_of lt lo_val val_x, },
{ assumption }
}
}
end
lemma lt_of_mem_left [is_strict_weak_order α lt] {y : α} {t l r : rbnode α} :
∀ {lo hi}, is_searchable lt t lo hi → is_node_of t l y r → ∀ {x}, mem lt x l → lt x y :=
begin
intros _ _ hs hn x hm, cases hn; cases hs,
all_goals { exact (range hs_hs₁ hm).2 }
end
lemma lt_of_mem_right [is_strict_weak_order α lt] {y : α} {t l r : rbnode α} :
∀ {lo hi}, is_searchable lt t lo hi → is_node_of t l y r → ∀ {z}, mem lt z r → lt y z :=
begin
intros _ _ hs hn z hm, cases hn; cases hs,
all_goals { exact (range hs_hs₂ hm).1 }
end
lemma lt_of_mem_left_right [is_strict_weak_order α lt] {y : α} {t l r : rbnode α} :
∀ {lo hi}, is_searchable lt t lo hi → is_node_of t l y r →
∀ {x z}, mem lt x l → mem lt z r → lt x z :=
begin
intros _ _ hs hn x z hm₁ hm₂, cases hn; cases hs,
all_goals {
have h₁ := range hs_hs₁ hm₁,
have h₂ := range hs_hs₂ hm₂,
exact trans_of lt h₁.2 h₂.1,
}
end
end is_searchable_lemmas
inductive is_red_black : rbnode α → color → nat → Prop
| leaf_rb : is_red_black leaf black 0
| red_rb {v l r n} (rb_l : is_red_black l black n) (rb_r : is_red_black r black n) :
is_red_black (red_node l v r) red n
| black_rb {v l r n c₁ c₂} (rb_l : is_red_black l c₁ n) (rb_r : is_red_black r c₂ n) :
is_red_black (black_node l v r) black (succ n)
open is_red_black
lemma depth_min : ∀ {c n} {t : rbnode α}, is_red_black t c n → n ≤ depth min t :=
begin
intros c n' t h,
induction h,
case leaf_rb {apply le_refl},
case red_rb { simp [depth],
have : min (depth min h_l) (depth min h_r) ≥ h_n,
{ apply le_min; assumption },
apply le_succ_of_le, assumption },
case black_rb { simp [depth],
apply succ_le_succ,
apply le_min; assumption }
end
private def upper : color → nat → nat
| red n := 2*n + 1
| black n := 2*n
private lemma upper_le : ∀ c n, upper c n ≤ 2 * n + 1
| red n := by apply le_refl
| black n := by apply le_succ
lemma depth_max' : ∀ {c n} {t : rbnode α}, is_red_black t c n → depth max t ≤ upper c n :=
begin
intros c n' t h,
induction h,
case leaf_rb { simp [max, depth, upper, nat.mul_zero] },
case red_rb {
suffices : succ (max (depth max h_l) (depth max h_r)) ≤ 2 * h_n + 1,
{ simp [depth, upper, *] at * },
apply succ_le_succ,
apply max_le; assumption },
case black_rb {
have : depth max h_l ≤ 2*h_n + 1, from le_trans h_ih_rb_l (upper_le _ _),
have : depth max h_r ≤ 2*h_n + 1, from le_trans h_ih_rb_r (upper_le _ _),
suffices new : max (depth max h_l) (depth max h_r) + 1 ≤ 2 * h_n + 2*1,
{ simp [depth, upper, succ_eq_add_one, nat.left_distrib, *] at * },
apply succ_le_succ, apply max_le; assumption
}
end
lemma depth_max {c n} {t : rbnode α} (h : is_red_black t c n) : depth max t ≤ 2 * n + 1:=
le_trans (depth_max' h) (upper_le _ _)
lemma balanced {c n} {t : rbnode α} (h : is_red_black t c n) : depth max t ≤ 2 * depth min t + 1 :=
begin
have : 2 * depth min t + 1 ≥ 2 * n + 1,
{ apply succ_le_succ, apply nat.mul_le_mul_left, apply depth_min h},
apply le_trans, apply depth_max h, apply this
end
end rbnode
|
6d4702754319cdf402e1a06646a9805f4d78be29 | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/algebraic_geometry/prime_spectrum.lean | 723378015e9b296de83d6c7278f8656d319527b0 | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 13,127 | 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
/-!
# 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,
but that sheaf is not constructed in this file.
It should be contributed to mathlib in future work.)
## 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 ideal of `R`.
It is naturally endowed with a topology (the Zariski topology),
and a sheaf of commutative rings (not yet in mathlib).
It is a fundamental building block in algebraic geometry. -/
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 as_ideal.is_prime (x : prime_spectrum R) :
x.as_ideal.is_prime := x.2
@[ext] lemma ext {x y : prime_spectrum R} :
x = y ↔ x.as_ideal = y.as_ideal :=
subtype.ext
/-- 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 [submodule.mem_coe, 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 set.subset.trans h _,
intros f hf,
rw [submodule.mem_coe, 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 classical.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_coe, submodule.mem_sup, submodule.mem_coe, 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.1 = 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 closure_subset_iff_subset_of_is_closed (is_closed_zero_locus _),
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, closure_eq_of_is_closed],
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
end prime_spectrum
|
47013ef40f10320be9883bd7d734d536a3ee9a2c | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/order/monoid_lemmas_zero_lt.lean | 78c077cb399e325c2843872bd07d8968eb7a7c53 | [
"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 | 37,561 | lean | /-
Copyright (c) 2022 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa, Yuyang Zhao
-/
import algebra.covariant_and_contravariant
import algebra.group_with_zero.defs
/-!
# Multiplication by ·positive· elements is monotonic
Let `α` be a type with `<` and `0`. We use the type `{x : α // 0 < x}` of positive elements of `α`
to prove results about monotonicity of multiplication. We also introduce the local notation `α>0`
for the subtype `{x : α // 0 < x}`:
If the type `α` also has a multiplication, then we combine this with (`contravariant_`)
`covariant_class`es to assume that multiplication by positive elements is (strictly) monotone on a
`mul_zero_class`, `monoid_with_zero`,...
More specifically, we use extensively the following typeclasses:
* monotone left
* * `covariant_class α>0 α (λ x y, x * y) (≤)`, abbreviated `pos_mul_mono α`,
expressing that multiplication by positive elements on the left is monotone;
* * `covariant_class α>0 α (λ x y, x * y) (<)`, abbreviated `pos_mul_strict_mono α`,
expressing that multiplication by positive elements on the left is strictly monotone;
* monotone right
* * `covariant_class α>0 α (λ x y, y * x) (≤)`, abbreviated `mul_pos_mono α`,
expressing that multiplication by positive elements on the right is monotone;
* * `covariant_class α>0 α (λ x y, y * x) (<)`, abbreviated `mul_pos_strict_mono α`,
expressing that multiplication by positive elements on the right is strictly monotone.
* reverse monotone left
* * `contravariant_class α>0 α (λ x y, x * y) (≤)`, abbreviated `pos_mul_mono_rev α`,
expressing that multiplication by positive elements on the left is reverse monotone;
* * `contravariant_class α>0 α (λ x y, x * y) (<)`, abbreviated `pos_mul_reflect_lt α`,
expressing that multiplication by positive elements on the left is strictly reverse monotone;
* reverse reverse monotone right
* * `contravariant_class α>0 α (λ x y, y * x) (≤)`, abbreviated `mul_pos_mono_rev α`,
expressing that multiplication by positive elements on the right is reverse monotone;
* * `contravariant_class α>0 α (λ x y, y * x) (<)`, abbreviated `mul_pos_reflect_lt α`,
expressing that multiplication by positive elements on the right is strictly reverse monotone.
## Notation
The following is local notation in this file:
* `α≥0`: `{x : α // 0 ≤ x}`
* `α>0`: `{x : α // 0 < x}`
-/
variable (α : Type*)
/- Notations for nonnegative and positive elements
https://
leanprover.zulipchat.com/#narrow/stream/113488-general/topic/notation.20for.20positive.20elements
-/
local notation `α≥0` := {x : α // 0 ≤ x}
local notation `α>0` := {x : α // 0 < x}
section abbreviations
variables [has_mul α] [has_zero α] [preorder α]
/-- `pos_mul_mono α` is an abbreviation for `covariant_class α≥0 α (λ x y, x * y) (≤)`,
expressing that multiplication by nonnegative elements on the left is monotone. -/
abbreviation pos_mul_mono : Prop := covariant_class α≥0 α (λ x y, x * y) (≤)
/-- `mul_pos_mono α` is an abbreviation for `covariant_class α≥0 α (λ x y, y * x) (≤)`,
expressing that multiplication by nonnegative elements on the right is monotone. -/
abbreviation mul_pos_mono : Prop := covariant_class α≥0 α (λ x y, y * x) (≤)
/-- `pos_mul_strict_mono α` is an abbreviation for `covariant_class α>0 α (λ x y, x * y) (<)`,
expressing that multiplication by positive elements on the left is strictly monotone. -/
abbreviation pos_mul_strict_mono : Prop := covariant_class α>0 α (λ x y, x * y) (<)
/-- `mul_pos_strict_mono α` is an abbreviation for `covariant_class α>0 α (λ x y, y * x) (<)`,
expressing that multiplication by positive elements on the right is strictly monotone. -/
abbreviation mul_pos_strict_mono : Prop := covariant_class α>0 α (λ x y, y * x) (<)
/-- `pos_mul_reflect_lt α` is an abbreviation for `contravariant_class α≥0 α (λ x y, x * y) (<)`,
expressing that multiplication by nonnegative elements on the left is strictly reverse monotone. -/
abbreviation pos_mul_reflect_lt : Prop := contravariant_class α≥0 α (λ x y, x * y) (<)
/-- `mul_pos_reflect_lt α` is an abbreviation for `contravariant_class α≥0 α (λ x y, y * x) (<)`,
expressing that multiplication by nonnegative elements on the right is strictly reverse monotone. -/
abbreviation mul_pos_reflect_lt : Prop := contravariant_class α≥0 α (λ x y, y * x) (<)
/-- `pos_mul_mono_rev α` is an abbreviation for `contravariant_class α>0 α (λ x y, x * y) (≤)`,
expressing that multiplication by positive elements on the left is reverse monotone. -/
abbreviation pos_mul_mono_rev : Prop := contravariant_class α>0 α (λ x y, x * y) (≤)
/-- `mul_pos_mono_rev α` is an abbreviation for `contravariant_class α>0 α (λ x y, y * x) (≤)`,
expressing that multiplication by positive elements on the right is reverse monotone. -/
abbreviation mul_pos_mono_rev : Prop := contravariant_class α>0 α (λ x y, y * x) (≤)
end abbreviations
variables {α} {a b c d : α}
section has_mul_zero
variables [has_mul α] [has_zero α]
section preorder
variables [preorder α]
instance pos_mul_mono.to_covariant_class_pos_mul_le [pos_mul_mono α] :
covariant_class α>0 α (λ x y, x * y) (≤) :=
⟨λ a b c bc, @covariant_class.elim α≥0 α (λ x y, x * y) (≤) _ ⟨_, a.2.le⟩ _ _ bc⟩
instance mul_pos_mono.to_covariant_class_pos_mul_le [mul_pos_mono α] :
covariant_class α>0 α (λ x y, y * x) (≤) :=
⟨λ a b c bc, @covariant_class.elim α≥0 α (λ x y, y * x) (≤) _ ⟨_, a.2.le⟩ _ _ bc⟩
instance pos_mul_reflect_lt.to_contravariant_class_pos_mul_lt [pos_mul_reflect_lt α] :
contravariant_class α>0 α (λ x y, x * y) (<) :=
⟨λ a b c bc, @contravariant_class.elim α≥0 α (λ x y, x * y) (<) _ ⟨_, a.2.le⟩ _ _ bc⟩
instance mul_pos_reflect_lt.to_contravariant_class_pos_mul_lt [mul_pos_reflect_lt α] :
contravariant_class α>0 α (λ x y, y * x) (<) :=
⟨λ a b c bc, @contravariant_class.elim α≥0 α (λ x y, y * x) (<) _ ⟨_, a.2.le⟩ _ _ bc⟩
lemma mul_le_mul_of_nonneg_left [pos_mul_mono α] (h : b ≤ c) (ha : 0 ≤ a) : a * b ≤ a * c :=
@covariant_class.elim α≥0 α (λ x y, x * y) (≤) _ ⟨a, ha⟩ _ _ h
lemma mul_le_mul_of_nonneg_right [mul_pos_mono α] (h : b ≤ c) (ha : 0 ≤ a) : b * a ≤ c * a :=
@covariant_class.elim α≥0 α (λ x y, y * x) (≤) _ ⟨a, ha⟩ _ _ h
lemma mul_lt_mul_of_pos_left [pos_mul_strict_mono α] (bc : b < c) (ha : 0 < a) : a * b < a * c :=
@covariant_class.elim α>0 α (λ x y, x * y) (<) _ ⟨a, ha⟩ _ _ bc
lemma mul_lt_mul_of_pos_right [mul_pos_strict_mono α] (bc : b < c) (ha : 0 < a) : b * a < c * a :=
@covariant_class.elim α>0 α (λ x y, y * x) (<) _ ⟨a, ha⟩ _ _ bc
lemma lt_of_mul_lt_mul_left [pos_mul_reflect_lt α] (h : a * b < a * c) (ha : 0 ≤ a) : b < c :=
@contravariant_class.elim α≥0 α (λ x y, x * y) (<) _ ⟨a, ha⟩ _ _ h
lemma lt_of_mul_lt_mul_right [mul_pos_reflect_lt α] (h : b * a < c * a) (ha : 0 ≤ a) : b < c :=
@contravariant_class.elim α≥0 α (λ x y, y * x) (<) _ ⟨a, ha⟩ _ _ h
@[simp]
lemma mul_lt_mul_left [pos_mul_strict_mono α] [pos_mul_reflect_lt α]
(a0 : 0 < a) :
a * b < a * c ↔ b < c :=
@rel_iff_cov α>0 α (λ x y, x * y) (<) _ _ ⟨a, a0⟩ _ _
@[simp]
lemma mul_lt_mul_right [mul_pos_strict_mono α] [mul_pos_reflect_lt α]
(a0 : 0 < a) :
b * a < c * a ↔ b < c :=
@rel_iff_cov α>0 α (λ x y, y * x) (<) _ _ ⟨a, a0⟩ _ _
lemma le_of_mul_le_mul_of_pos_left [pos_mul_mono_rev α]
(bc : a * b ≤ a * c) (a0 : 0 < a) :
b ≤ c :=
@contravariant_class.elim α>0 α (λ x y, x * y) (≤) _ ⟨a, a0⟩ _ _ bc
lemma le_of_mul_le_mul_of_pos_right [mul_pos_mono_rev α]
(bc : b * a ≤ c * a) (a0 : 0 < a) :
b ≤ c :=
@contravariant_class.elim α>0 α (λ x y, y * x) (≤) _ ⟨a, a0⟩ _ _ bc
alias le_of_mul_le_mul_of_pos_left ← le_of_mul_le_mul_left
alias le_of_mul_le_mul_of_pos_right ← le_of_mul_le_mul_right
@[simp] lemma mul_le_mul_left [pos_mul_mono α] [pos_mul_mono_rev α] (ha : 0 < a) :
a * b ≤ a * c ↔ b ≤ c :=
@rel_iff_cov α>0 α (λ x y, x * y) (≤) _ _ ⟨a, ha⟩ _ _
@[simp] lemma mul_le_mul_right [mul_pos_mono α] [mul_pos_mono_rev α] (ha : 0 < a) :
b * a ≤ c * a ↔ b ≤ c :=
@rel_iff_cov α>0 α (λ x y, y * x) (≤) _ _ ⟨a, ha⟩ _ _
lemma mul_lt_mul_of_pos_of_nonneg [pos_mul_strict_mono α] [mul_pos_mono α]
(h₁ : a ≤ b) (h₂ : c < d) (a0 : 0 < a) (d0 : 0 ≤ d) : a * c < b * d :=
(mul_lt_mul_of_pos_left h₂ a0).trans_le (mul_le_mul_of_nonneg_right h₁ d0)
lemma mul_lt_mul_of_le_of_le' [pos_mul_strict_mono α] [mul_pos_mono α]
(h₁ : a ≤ b) (h₂ : c < d) (b0 : 0 < b) (c0 : 0 ≤ c) : a * c < b * d :=
(mul_le_mul_of_nonneg_right h₁ c0).trans_lt (mul_lt_mul_of_pos_left h₂ b0)
lemma mul_lt_mul_of_nonneg_of_pos [pos_mul_mono α] [mul_pos_strict_mono α]
(h₁ : a < b) (h₂ : c ≤ d) (a0 : 0 ≤ a) (d0 : 0 < d) : a * c < b * d :=
(mul_le_mul_of_nonneg_left h₂ a0).trans_lt (mul_lt_mul_of_pos_right h₁ d0)
lemma mul_lt_mul_of_le_of_lt' [pos_mul_mono α] [mul_pos_strict_mono α]
(h₁ : a < b) (h₂ : c ≤ d) (b0 : 0 ≤ b) (c0 : 0 < c) : a * c < b * d :=
(mul_lt_mul_of_pos_right h₁ c0).trans_le (mul_le_mul_of_nonneg_left h₂ b0)
lemma mul_lt_mul_of_pos_of_pos [pos_mul_strict_mono α] [mul_pos_strict_mono α]
(h₁ : a < b) (h₂ : c < d) (a0 : 0 < a) (d0 : 0 < d) : a * c < b * d :=
(mul_lt_mul_of_pos_left h₂ a0).trans (mul_lt_mul_of_pos_right h₁ d0)
lemma mul_lt_mul_of_lt_of_lt' [pos_mul_strict_mono α] [mul_pos_strict_mono α]
(h₁ : a < b) (h₂ : c < d) (b0 : 0 < b) (c0 : 0 < c) : a * c < b * d :=
(mul_lt_mul_of_pos_right h₁ c0).trans (mul_lt_mul_of_pos_left h₂ b0)
lemma mul_lt_of_mul_lt_of_nonneg_left [pos_mul_mono α] (h : a * b < c) (hdb : d ≤ b) (ha : 0 ≤ a) :
a * d < c :=
(mul_le_mul_of_nonneg_left hdb ha).trans_lt h
lemma lt_mul_of_lt_mul_of_nonneg_left [pos_mul_mono α] (h : a < b * c) (hcd : c ≤ d) (hb : 0 ≤ b) :
a < b * d :=
h.trans_le $ mul_le_mul_of_nonneg_left hcd hb
lemma mul_lt_of_mul_lt_of_nonneg_right [mul_pos_mono α] (h : a * b < c) (hda : d ≤ a) (hb : 0 ≤ b) :
d * b < c :=
(mul_le_mul_of_nonneg_right hda hb).trans_lt h
lemma lt_mul_of_lt_mul_of_nonneg_right [mul_pos_mono α] (h : a < b * c) (hbd : b ≤ d) (hc : 0 ≤ c) :
a < d * c :=
h.trans_le $ mul_le_mul_of_nonneg_right hbd hc
end preorder
section linear_order
variables [linear_order α]
@[priority 100] -- see Note [lower instance priority]
instance pos_mul_strict_mono.to_pos_mul_mono_rev [pos_mul_strict_mono α] : pos_mul_mono_rev α :=
⟨λ x a b h, le_of_not_lt $ λ h', h.not_lt $ mul_lt_mul_of_pos_left h' x.prop⟩
@[priority 100] -- see Note [lower instance priority]
instance mul_pos_strict_mono.to_mul_pos_mono_rev [mul_pos_strict_mono α] : mul_pos_mono_rev α :=
⟨λ x a b h, le_of_not_lt $ λ h', h.not_lt $ mul_lt_mul_of_pos_right h' x.prop⟩
lemma pos_mul_mono_rev.to_pos_mul_strict_mono [pos_mul_mono_rev α] : pos_mul_strict_mono α :=
⟨λ x a b h, lt_of_not_le $ λ h', h.not_le $ le_of_mul_le_mul_of_pos_left h' x.prop⟩
lemma mul_pos_mono_rev.to_mul_pos_strict_mono [mul_pos_mono_rev α] : mul_pos_strict_mono α :=
⟨λ x a b h, lt_of_not_le $ λ h', h.not_le $ le_of_mul_le_mul_of_pos_right h' x.prop⟩
lemma pos_mul_strict_mono_iff_pos_mul_mono_rev : pos_mul_strict_mono α ↔ pos_mul_mono_rev α :=
⟨@pos_mul_strict_mono.to_pos_mul_mono_rev _ _ _ _, @pos_mul_mono_rev.to_pos_mul_strict_mono _ _ _ _⟩
lemma mul_pos_strict_mono_iff_mul_pos_mono_rev : mul_pos_strict_mono α ↔ mul_pos_mono_rev α :=
⟨@mul_pos_strict_mono.to_mul_pos_mono_rev _ _ _ _, @mul_pos_mono_rev.to_mul_pos_strict_mono _ _ _ _⟩
lemma pos_mul_reflect_lt.to_pos_mul_mono [pos_mul_reflect_lt α] : pos_mul_mono α :=
⟨λ x a b h, le_of_not_lt $ λ h', h.not_lt $ lt_of_mul_lt_mul_left h' x.prop⟩
lemma mul_pos_reflect_lt.to_mul_pos_mono [mul_pos_reflect_lt α] : mul_pos_mono α :=
⟨λ x a b h, le_of_not_lt $ λ h', h.not_lt $ lt_of_mul_lt_mul_right h' x.prop⟩
lemma pos_mul_mono.to_pos_mul_reflect_lt [pos_mul_mono α] : pos_mul_reflect_lt α :=
⟨λ x a b h, lt_of_not_le $ λ h', h.not_le $ mul_le_mul_of_nonneg_left h' x.prop⟩
lemma mul_pos_mono.to_mul_pos_reflect_lt [mul_pos_mono α] : mul_pos_reflect_lt α :=
⟨λ x a b h, lt_of_not_le $ λ h', h.not_le $ mul_le_mul_of_nonneg_right h' x.prop⟩
lemma pos_mul_mono_iff_pos_mul_reflect_lt : pos_mul_mono α ↔ pos_mul_reflect_lt α :=
⟨@pos_mul_mono.to_pos_mul_reflect_lt _ _ _ _, @pos_mul_reflect_lt.to_pos_mul_mono _ _ _ _⟩
lemma mul_pos_mono_iff_mul_pos_reflect_lt : mul_pos_mono α ↔ mul_pos_reflect_lt α :=
⟨@mul_pos_mono.to_mul_pos_reflect_lt _ _ _ _, @mul_pos_reflect_lt.to_mul_pos_mono _ _ _ _⟩
end linear_order
end has_mul_zero
section mul_zero_class
variables [mul_zero_class α]
section preorder
variables [preorder α]
/-- Assumes left covariance. -/
lemma left.mul_pos [pos_mul_strict_mono α] (ha : 0 < a) (hb : 0 < b) : 0 < a * b :=
by simpa only [mul_zero] using mul_lt_mul_of_pos_left hb ha
alias left.mul_pos ← mul_pos
lemma mul_neg_of_pos_of_neg [pos_mul_strict_mono α] (ha : 0 < a) (hb : b < 0) : a * b < 0 :=
by simpa only [mul_zero] using mul_lt_mul_of_pos_left hb ha
@[simp] lemma zero_lt_mul_left [pos_mul_strict_mono α] [pos_mul_reflect_lt α] (h : 0 < c) :
0 < c * b ↔ 0 < b :=
by { convert mul_lt_mul_left h, simp }
/-- Assumes right covariance. -/
lemma right.mul_pos [mul_pos_strict_mono α] (ha : 0 < a) (hb : 0 < b) : 0 < a * b :=
by simpa only [zero_mul] using mul_lt_mul_of_pos_right ha hb
lemma mul_neg_of_neg_of_pos [mul_pos_strict_mono α] (ha : a < 0) (hb : 0 < b) : a * b < 0 :=
by simpa only [zero_mul] using mul_lt_mul_of_pos_right ha hb
@[simp] lemma zero_lt_mul_right [mul_pos_strict_mono α] [mul_pos_reflect_lt α] (h : 0 < c) :
0 < b * c ↔ 0 < b :=
by { convert mul_lt_mul_right h, simp }
/-- Assumes left covariance. -/
lemma left.mul_nonneg [pos_mul_mono α] (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b :=
by simpa only [mul_zero] using mul_le_mul_of_nonneg_left hb ha
alias left.mul_nonneg ← mul_nonneg
lemma mul_nonpos_of_nonneg_of_nonpos [pos_mul_mono α] (ha : 0 ≤ a) (hb : b ≤ 0) : a * b ≤ 0 :=
by simpa only [mul_zero] using mul_le_mul_of_nonneg_left hb ha
/-- Assumes right covariance. -/
lemma right.mul_nonneg [mul_pos_mono α] (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b :=
by simpa only [zero_mul] using mul_le_mul_of_nonneg_right ha hb
lemma mul_nonpos_of_nonpos_of_nonneg [mul_pos_mono α] (ha : a ≤ 0) (hb : 0 ≤ b) : a * b ≤ 0 :=
by simpa only [zero_mul] using mul_le_mul_of_nonneg_right ha hb
lemma pos_of_mul_pos_right [pos_mul_reflect_lt α] (h : 0 < a * b) (ha : 0 ≤ a) : 0 < b :=
lt_of_mul_lt_mul_left ((mul_zero a).symm ▸ h : a * 0 < a * b) ha
lemma pos_of_mul_pos_left [mul_pos_reflect_lt α] (h : 0 < a * b) (hb : 0 ≤ b) : 0 < a :=
lt_of_mul_lt_mul_right ((zero_mul b).symm ▸ h : 0 * b < a * b) hb
lemma pos_iff_pos_of_mul_pos [pos_mul_reflect_lt α] [mul_pos_reflect_lt α] (hab : 0 < a * b) :
0 < a ↔ 0 < b :=
⟨pos_of_mul_pos_right hab ∘ le_of_lt, pos_of_mul_pos_left hab ∘ le_of_lt⟩
lemma mul_le_mul_of_le_of_le [pos_mul_mono α] [mul_pos_mono α]
(h₁ : a ≤ b) (h₂ : c ≤ d) (a0 : 0 ≤ a) (d0 : 0 ≤ d) : a * c ≤ b * d :=
(mul_le_mul_of_nonneg_left h₂ a0).trans $ mul_le_mul_of_nonneg_right h₁ d0
lemma mul_le_mul [pos_mul_mono α] [mul_pos_mono α]
(h₁ : a ≤ b) (h₂ : c ≤ d) (c0 : 0 ≤ c) (b0 : 0 ≤ b) : a * c ≤ b * d :=
(mul_le_mul_of_nonneg_right h₁ c0).trans $ mul_le_mul_of_nonneg_left h₂ b0
lemma mul_le_of_mul_le_of_nonneg_left [pos_mul_mono α] (h : a * b ≤ c) (hle : d ≤ b) (a0 : 0 ≤ a) :
a * d ≤ c :=
(mul_le_mul_of_nonneg_left hle a0).trans h
lemma le_mul_of_le_mul_of_nonneg_left [pos_mul_mono α] (h : a ≤ b * c) (hle : c ≤ d) (b0 : 0 ≤ b) :
a ≤ b * d :=
h.trans (mul_le_mul_of_nonneg_left hle b0)
lemma mul_le_of_mul_le_of_nonneg_right [mul_pos_mono α] (h : a * b ≤ c) (hle : d ≤ a) (b0 : 0 ≤ b) :
d * b ≤ c :=
(mul_le_mul_of_nonneg_right hle b0).trans h
lemma le_mul_of_le_mul_of_nonneg_right [mul_pos_mono α] (h : a ≤ b * c) (hle : b ≤ d) (c0 : 0 ≤ c) :
a ≤ d * c :=
h.trans (mul_le_mul_of_nonneg_right hle c0)
end preorder
section partial_order
variables [partial_order α]
lemma pos_mul_mono_iff_covariant_pos : pos_mul_mono α ↔ covariant_class α>0 α (λ x y, x * y) (≤) :=
⟨@pos_mul_mono.to_covariant_class_pos_mul_le _ _ _ _, λ h, ⟨λ a b c h, begin
obtain ha | ha := a.prop.eq_or_gt,
{ simp only [ha, zero_mul] },
{ exactI @covariant_class.elim α>0 α (λ x y, x * y) (≤) _ ⟨_, ha⟩ _ _ h }
end⟩⟩
lemma mul_pos_mono_iff_covariant_pos : mul_pos_mono α ↔ covariant_class α>0 α (λ x y, y * x) (≤) :=
⟨@mul_pos_mono.to_covariant_class_pos_mul_le _ _ _ _, λ h, ⟨λ a b c h, begin
obtain ha | ha := a.prop.eq_or_gt,
{ simp only [ha, mul_zero] },
{ exactI @covariant_class.elim α>0 α (λ x y, y * x) (≤) _ ⟨_, ha⟩ _ _ h }
end⟩⟩
lemma pos_mul_reflect_lt_iff_contravariant_pos :
pos_mul_reflect_lt α ↔ contravariant_class α>0 α (λ x y, x * y) (<) :=
⟨@pos_mul_reflect_lt.to_contravariant_class_pos_mul_lt _ _ _ _, λ h, ⟨λ a b c h, begin
obtain ha | ha := a.prop.eq_or_gt,
{ simpa [ha] using h },
{ exactI (@contravariant_class.elim α>0 α (λ x y, x * y) (<) _ ⟨_, ha⟩ _ _ h) }
end⟩⟩
lemma mul_pos_reflect_lt_iff_contravariant_pos :
mul_pos_reflect_lt α ↔ contravariant_class α>0 α (λ x y, y * x) (<) :=
⟨@mul_pos_reflect_lt.to_contravariant_class_pos_mul_lt _ _ _ _, λ h, ⟨λ a b c h, begin
obtain ha | ha := a.prop.eq_or_gt,
{ simpa [ha] using h },
{ exactI (@contravariant_class.elim α>0 α (λ x y, y * x) (<) _ ⟨_, ha⟩ _ _ h) }
end⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance pos_mul_strict_mono.to_pos_mul_mono [pos_mul_strict_mono α] : pos_mul_mono α :=
pos_mul_mono_iff_covariant_pos.2 $ ⟨λ a, strict_mono.monotone $ @covariant_class.elim _ _ _ _ _ _⟩
@[priority 100] -- see Note [lower instance priority]
instance mul_pos_strict_mono.to_mul_pos_mono [mul_pos_strict_mono α] : mul_pos_mono α :=
mul_pos_mono_iff_covariant_pos.2 $ ⟨λ a, strict_mono.monotone $ @covariant_class.elim _ _ _ _ _ _⟩
@[priority 100] -- see Note [lower instance priority]
instance pos_mul_mono_rev.to_pos_mul_reflect_lt [pos_mul_mono_rev α] : pos_mul_reflect_lt α :=
pos_mul_reflect_lt_iff_contravariant_pos.2
⟨λ a b c h, (le_of_mul_le_mul_of_pos_left h.le a.2).lt_of_ne $ by { rintro rfl, simpa using h }⟩
@[priority 100] -- see Note [lower instance priority]
instance mul_pos_mono_rev.to_mul_pos_reflect_lt [mul_pos_mono_rev α] : mul_pos_reflect_lt α :=
mul_pos_reflect_lt_iff_contravariant_pos.2
⟨λ a b c h, (le_of_mul_le_mul_of_pos_right h.le a.2).lt_of_ne $ by { rintro rfl, simpa using h }⟩
lemma mul_left_cancel_iff_of_pos [pos_mul_mono_rev α] (a0 : 0 < a) : a * b = a * c ↔ b = c :=
⟨λ h, (le_of_mul_le_mul_of_pos_left h.le a0).antisymm $ le_of_mul_le_mul_of_pos_left h.ge a0,
congr_arg _⟩
lemma mul_right_cancel_iff_of_pos [mul_pos_mono_rev α] (b0 : 0 < b) : a * b = c * b ↔ a = c :=
⟨λ h, (le_of_mul_le_mul_of_pos_right h.le b0).antisymm $ le_of_mul_le_mul_of_pos_right h.ge b0,
congr_arg _⟩
lemma mul_eq_mul_iff_eq_and_eq_of_pos [pos_mul_strict_mono α] [mul_pos_strict_mono α]
[pos_mul_mono_rev α] [mul_pos_mono_rev α]
(hac : a ≤ b) (hbd : c ≤ d) (a0 : 0 < a) (d0 : 0 < d) :
a * c = b * d ↔ a = b ∧ c = d :=
begin
refine ⟨λ h, _, λ h, congr_arg2 (*) h.1 h.2⟩,
rcases hac.eq_or_lt with rfl | hac,
{ exact ⟨rfl, (mul_left_cancel_iff_of_pos a0).mp h⟩ },
rcases eq_or_lt_of_le hbd with rfl | hbd,
{ exact ⟨(mul_right_cancel_iff_of_pos d0).mp h, rfl⟩ },
exact ((mul_lt_mul_of_pos_of_pos hac hbd a0 d0).ne h).elim,
end
lemma mul_eq_mul_iff_eq_and_eq_of_pos' [pos_mul_strict_mono α] [mul_pos_strict_mono α]
[pos_mul_mono_rev α] [mul_pos_mono_rev α]
(hac : a ≤ b) (hbd : c ≤ d) (b0 : 0 < b) (c0 : 0 < c) :
a * c = b * d ↔ a = b ∧ c = d :=
begin
refine ⟨λ h, _, λ h, congr_arg2 (*) h.1 h.2⟩,
rcases hac.eq_or_lt with rfl | hac,
{ exact ⟨rfl, (mul_left_cancel_iff_of_pos b0).mp h⟩ },
rcases eq_or_lt_of_le hbd with rfl | hbd,
{ exact ⟨(mul_right_cancel_iff_of_pos c0).mp h, rfl⟩ },
exact ((mul_lt_mul_of_lt_of_lt' hac hbd b0 c0).ne h).elim,
end
end partial_order
section linear_order
variables [linear_order α]
lemma pos_and_pos_or_neg_and_neg_of_mul_pos [pos_mul_mono α] [mul_pos_mono α]
(hab : 0 < a * b) :
(0 < a ∧ 0 < b) ∨ (a < 0 ∧ b < 0) :=
begin
rcases lt_trichotomy 0 a with ha | rfl | ha,
{ refine or.inl ⟨ha, lt_imp_lt_of_le_imp_le (λ hb, _) hab⟩,
exact mul_nonpos_of_nonneg_of_nonpos ha.le hb },
{ rw [zero_mul] at hab, exact hab.false.elim },
{ refine or.inr ⟨ha, lt_imp_lt_of_le_imp_le (λ hb, _) hab⟩,
exact mul_nonpos_of_nonpos_of_nonneg ha.le hb }
end
lemma neg_of_mul_pos_right [pos_mul_mono α] [mul_pos_mono α]
(h : 0 < a * b) (ha : a ≤ 0) :
b < 0 :=
((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_left $ λ h, h.1.not_le ha).2
lemma neg_of_mul_pos_left [pos_mul_mono α] [mul_pos_mono α]
(h : 0 < a * b) (ha : b ≤ 0) :
a < 0 :=
((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_left $ λ h, h.2.not_le ha).1
lemma neg_iff_neg_of_mul_pos [pos_mul_mono α] [mul_pos_mono α]
(hab : 0 < a * b) :
a < 0 ↔ b < 0 :=
⟨neg_of_mul_pos_right hab ∘ le_of_lt, neg_of_mul_pos_left hab ∘ le_of_lt⟩
lemma left.neg_of_mul_neg_left [pos_mul_mono α]
(h : a * b < 0) (h1 : 0 ≤ a) :
b < 0 :=
lt_of_not_ge (assume h2 : b ≥ 0, (left.mul_nonneg h1 h2).not_lt h)
lemma right.neg_of_mul_neg_left [mul_pos_mono α]
(h : a * b < 0) (h1 : 0 ≤ a) :
b < 0 :=
lt_of_not_ge (assume h2 : b ≥ 0, (right.mul_nonneg h1 h2).not_lt h)
lemma left.neg_of_mul_neg_right [pos_mul_mono α]
(h : a * b < 0) (h1 : 0 ≤ b) : a < 0 :=
lt_of_not_ge (assume h2 : a ≥ 0, (left.mul_nonneg h2 h1).not_lt h)
lemma right.neg_of_mul_neg_right [mul_pos_mono α]
(h : a * b < 0) (h1 : 0 ≤ b) : a < 0 :=
lt_of_not_ge (assume h2 : a ≥ 0, (right.mul_nonneg h2 h1).not_lt h)
end linear_order
end mul_zero_class
section mul_one_class
variables [mul_one_class α] [has_zero α]
section preorder
variables [preorder α]
/-! Lemmas of the form `a ≤ a * b ↔ 1 ≤ b` and `a * b ≤ a ↔ b ≤ 1`,
which assume left covariance. -/
@[simp]
lemma le_mul_iff_one_le_right
[pos_mul_mono α] [pos_mul_mono_rev α]
(a0 : 0 < a) :
a ≤ a * b ↔ 1 ≤ b :=
iff.trans (by rw [mul_one]) (mul_le_mul_left a0)
@[simp]
lemma lt_mul_iff_one_lt_right
[pos_mul_strict_mono α] [pos_mul_reflect_lt α]
(a0 : 0 < a) :
a < a * b ↔ 1 < b :=
iff.trans (by rw [mul_one]) (mul_lt_mul_left a0)
@[simp]
lemma mul_le_iff_le_one_right
[pos_mul_mono α] [pos_mul_mono_rev α]
(a0 : 0 < a) :
a * b ≤ a ↔ b ≤ 1 :=
iff.trans (by rw [mul_one]) (mul_le_mul_left a0)
@[simp]
lemma mul_lt_iff_lt_one_right
[pos_mul_strict_mono α] [pos_mul_reflect_lt α]
(a0 : 0 < a) :
a * b < a ↔ b < 1 :=
iff.trans (by rw [mul_one]) (mul_lt_mul_left a0)
/-! Lemmas of the form `a ≤ b * a ↔ 1 ≤ b` and `a * b ≤ b ↔ a ≤ 1`,
which assume right covariance. -/
@[simp]
lemma le_mul_iff_one_le_left
[mul_pos_mono α] [mul_pos_mono_rev α]
(a0 : 0 < a) :
a ≤ b * a ↔ 1 ≤ b :=
iff.trans (by rw [one_mul]) (mul_le_mul_right a0)
@[simp]
lemma lt_mul_iff_one_lt_left
[mul_pos_strict_mono α] [mul_pos_reflect_lt α]
(a0 : 0 < a) :
a < b * a ↔ 1 < b :=
iff.trans (by rw [one_mul]) (mul_lt_mul_right a0)
@[simp]
lemma mul_le_iff_le_one_left
[mul_pos_mono α] [mul_pos_mono_rev α]
(b0 : 0 < b) :
a * b ≤ b ↔ a ≤ 1 :=
iff.trans (by rw [one_mul]) (mul_le_mul_right b0)
@[simp]
lemma mul_lt_iff_lt_one_left
[mul_pos_strict_mono α] [mul_pos_reflect_lt α]
(b0 : 0 < b) :
a * b < b ↔ a < 1 :=
iff.trans (by rw [one_mul]) (mul_lt_mul_right b0)
/-! Lemmas of the form `1 ≤ b → a ≤ a * b`. -/
lemma mul_le_of_le_one_left [mul_pos_mono α] (hb : 0 ≤ b) (h : a ≤ 1) : a * b ≤ b :=
by simpa only [one_mul] using mul_le_mul_of_nonneg_right h hb
lemma le_mul_of_one_le_left [mul_pos_mono α] (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ a * b :=
by simpa only [one_mul] using mul_le_mul_of_nonneg_right h hb
lemma mul_le_of_le_one_right [pos_mul_mono α] (ha : 0 ≤ a) (h : b ≤ 1) : a * b ≤ a :=
by simpa only [mul_one] using mul_le_mul_of_nonneg_left h ha
lemma le_mul_of_one_le_right [pos_mul_mono α] (ha : 0 ≤ a) (h : 1 ≤ b) : a ≤ a * b :=
by simpa only [mul_one] using mul_le_mul_of_nonneg_left h ha
lemma mul_lt_of_lt_one_left [mul_pos_strict_mono α] (hb : 0 < b) (h : a < 1) : a * b < b :=
by simpa only [one_mul] using mul_lt_mul_of_pos_right h hb
lemma lt_mul_of_one_lt_left [mul_pos_strict_mono α] (hb : 0 < b) (h : 1 < a) : b < a * b :=
by simpa only [one_mul] using mul_lt_mul_of_pos_right h hb
lemma mul_lt_of_lt_one_right [pos_mul_strict_mono α] (ha : 0 < a) (h : b < 1) : a * b < a :=
by simpa only [mul_one] using mul_lt_mul_of_pos_left h ha
lemma lt_mul_of_one_lt_right [pos_mul_strict_mono α] (ha : 0 < a) (h : 1 < b) : a < a * b :=
by simpa only [mul_one] using mul_lt_mul_of_pos_left h ha
/-! Lemmas of the form `b ≤ c → a ≤ 1 → b * a ≤ c`. -/
/- Yaël: What's the point of these lemmas? They just chain an existing lemma with an assumption in
all possible ways, thereby artificially inflating the API and making the truly relevant lemmas hard
to find -/
lemma mul_le_of_le_of_le_one_of_nonneg [pos_mul_mono α] (h : b ≤ c) (ha : a ≤ 1) (hb : 0 ≤ b) :
b * a ≤ c :=
(mul_le_of_le_one_right hb ha).trans h
lemma mul_lt_of_le_of_lt_one_of_pos [pos_mul_strict_mono α] (bc : b ≤ c) (ha : a < 1) (b0 : 0 < b) :
b * a < c :=
(mul_lt_of_lt_one_right b0 ha).trans_le bc
lemma mul_lt_of_lt_of_le_one_of_nonneg [pos_mul_mono α] (h : b < c) (ha : a ≤ 1) (hb : 0 ≤ b) :
b * a < c :=
(mul_le_of_le_one_right hb ha).trans_lt h
/-- Assumes left covariance. -/
lemma left.mul_le_one_of_le_of_le [pos_mul_mono α] (ha : a ≤ 1) (hb : b ≤ 1) (a0 : 0 ≤ a) :
a * b ≤ 1 :=
mul_le_of_le_of_le_one_of_nonneg ha hb a0
/-- Assumes left covariance. -/
lemma left.mul_lt_of_le_of_lt_one_of_pos [pos_mul_strict_mono α]
(ha : a ≤ 1) (hb : b < 1) (a0 : 0 < a) : a * b < 1 :=
mul_lt_of_le_of_lt_one_of_pos ha hb a0
/-- Assumes left covariance. -/
lemma left.mul_lt_of_lt_of_le_one_of_nonneg [pos_mul_mono α]
(ha : a < 1) (hb : b ≤ 1) (a0 : 0 ≤ a) : a * b < 1 :=
mul_lt_of_lt_of_le_one_of_nonneg ha hb a0
lemma mul_le_of_le_of_le_one' [pos_mul_mono α] [mul_pos_mono α]
(bc : b ≤ c) (ha : a ≤ 1) (a0 : 0 ≤ a) (c0 : 0 ≤ c) : b * a ≤ c :=
(mul_le_mul_of_nonneg_right bc a0).trans $ mul_le_of_le_one_right c0 ha
lemma mul_lt_of_lt_of_le_one' [pos_mul_mono α] [mul_pos_strict_mono α]
(bc : b < c) (ha : a ≤ 1) (a0 : 0 < a) (c0 : 0 ≤ c) : b * a < c :=
(mul_lt_mul_of_pos_right bc a0).trans_le $ mul_le_of_le_one_right c0 ha
lemma mul_lt_of_le_of_lt_one' [pos_mul_strict_mono α] [mul_pos_mono α]
(bc : b ≤ c) (ha : a < 1) (a0 : 0 ≤ a) (c0 : 0 < c) : b * a < c :=
(mul_le_mul_of_nonneg_right bc a0).trans_lt $ mul_lt_of_lt_one_right c0 ha
lemma mul_lt_of_lt_of_lt_one_of_pos [pos_mul_mono α] [mul_pos_strict_mono α]
(bc : b < c) (ha : a ≤ 1) (a0 : 0 < a) (c0 : 0 ≤ c) : b * a < c :=
(mul_lt_mul_of_pos_right bc a0).trans_le $ mul_le_of_le_one_right c0 ha
/-! Lemmas of the form `b ≤ c → 1 ≤ a → b ≤ c * a`. -/
lemma le_mul_of_le_of_one_le_of_nonneg [pos_mul_mono α] (h : b ≤ c) (ha : 1 ≤ a) (hc : 0 ≤ c) :
b ≤ c * a :=
h.trans $ le_mul_of_one_le_right hc ha
lemma lt_mul_of_le_of_one_lt_of_pos [pos_mul_strict_mono α] (bc : b ≤ c) (ha : 1 < a) (c0 : 0 < c) :
b < c * a :=
bc.trans_lt $ lt_mul_of_one_lt_right c0 ha
lemma lt_mul_of_lt_of_one_le_of_nonneg [pos_mul_mono α] (h : b < c) (ha : 1 ≤ a) (hc : 0 ≤ c) :
b < c * a :=
h.trans_le $ le_mul_of_one_le_right hc ha
/-- Assumes left covariance. -/
lemma left.one_le_mul_of_le_of_le [pos_mul_mono α] (ha : 1 ≤ a) (hb : 1 ≤ b) (a0 : 0 ≤ a) :
1 ≤ a * b :=
le_mul_of_le_of_one_le_of_nonneg ha hb a0
/-- Assumes left covariance. -/
lemma left.one_lt_mul_of_le_of_lt_of_pos [pos_mul_strict_mono α]
(ha : 1 ≤ a) (hb : 1 < b) (a0 : 0 < a) : 1 < a * b :=
lt_mul_of_le_of_one_lt_of_pos ha hb a0
/-- Assumes left covariance. -/
lemma left.lt_mul_of_lt_of_one_le_of_nonneg [pos_mul_mono α]
(ha : 1 < a) (hb : 1 ≤ b) (a0 : 0 ≤ a) : 1 < a * b :=
lt_mul_of_lt_of_one_le_of_nonneg ha hb a0
lemma le_mul_of_le_of_one_le' [pos_mul_mono α] [mul_pos_mono α]
(bc : b ≤ c) (ha : 1 ≤ a) (a0 : 0 ≤ a) (b0 : 0 ≤ b) : b ≤ c * a :=
(le_mul_of_one_le_right b0 ha).trans $ mul_le_mul_of_nonneg_right bc a0
lemma lt_mul_of_le_of_one_lt' [pos_mul_strict_mono α] [mul_pos_mono α]
(bc : b ≤ c) (ha : 1 < a) (a0 : 0 ≤ a) (b0 : 0 < b) : b < c * a :=
(lt_mul_of_one_lt_right b0 ha).trans_le $ mul_le_mul_of_nonneg_right bc a0
lemma lt_mul_of_lt_of_one_le' [pos_mul_mono α] [mul_pos_strict_mono α]
(bc : b < c) (ha : 1 ≤ a) (a0 : 0 < a) (b0 : 0 ≤ b) : b < c * a :=
(le_mul_of_one_le_right b0 ha).trans_lt $ mul_lt_mul_of_pos_right bc a0
lemma lt_mul_of_lt_of_one_lt_of_pos [pos_mul_strict_mono α] [mul_pos_strict_mono α]
(bc : b < c) (ha : 1 < a) (a0 : 0 < a) (b0 : 0 < b) : b < c * a :=
(lt_mul_of_one_lt_right b0 ha).trans $ mul_lt_mul_of_pos_right bc a0
/-! Lemmas of the form `a ≤ 1 → b ≤ c → a * b ≤ c`. -/
lemma mul_le_of_le_one_of_le_of_nonneg [mul_pos_mono α] (ha : a ≤ 1) (h : b ≤ c) (hb : 0 ≤ b) :
a * b ≤ c :=
(mul_le_of_le_one_left hb ha).trans h
lemma mul_lt_of_lt_one_of_le_of_pos [mul_pos_strict_mono α] (ha : a < 1) (h : b ≤ c) (hb : 0 < b) :
a * b < c :=
(mul_lt_of_lt_one_left hb ha).trans_le h
lemma mul_lt_of_le_one_of_lt_of_nonneg [mul_pos_mono α] (ha : a ≤ 1) (h : b < c) (hb : 0 ≤ b) :
a * b < c :=
(mul_le_of_le_one_left hb ha).trans_lt h
/-- Assumes right covariance. -/
lemma right.mul_lt_one_of_lt_of_le_of_pos [mul_pos_strict_mono α]
(ha : a < 1) (hb : b ≤ 1) (b0 : 0 < b) : a * b < 1 :=
mul_lt_of_lt_one_of_le_of_pos ha hb b0
/-- Assumes right covariance. -/
lemma right.mul_lt_one_of_le_of_lt_of_nonneg [mul_pos_mono α]
(ha : a ≤ 1) (hb : b < 1) (b0 : 0 ≤ b) : a * b < 1 :=
mul_lt_of_le_one_of_lt_of_nonneg ha hb b0
lemma mul_lt_of_lt_one_of_lt_of_pos [pos_mul_strict_mono α] [mul_pos_strict_mono α]
(ha : a < 1) (bc : b < c) (a0 : 0 < a) (c0 : 0 < c) : a * b < c :=
(mul_lt_mul_of_pos_left bc a0).trans $ mul_lt_of_lt_one_left c0 ha
/-- Assumes right covariance. -/
lemma right.mul_le_one_of_le_of_le [mul_pos_mono α]
(ha : a ≤ 1) (hb : b ≤ 1) (b0 : 0 ≤ b) : a * b ≤ 1 :=
mul_le_of_le_one_of_le_of_nonneg ha hb b0
lemma mul_le_of_le_one_of_le' [pos_mul_mono α] [mul_pos_mono α]
(ha : a ≤ 1) (bc : b ≤ c) (a0 : 0 ≤ a) (c0 : 0 ≤ c) : a * b ≤ c :=
(mul_le_mul_of_nonneg_left bc a0).trans $ mul_le_of_le_one_left c0 ha
lemma mul_lt_of_lt_one_of_le' [pos_mul_mono α] [mul_pos_strict_mono α]
(ha : a < 1) (bc : b ≤ c) (a0 : 0 ≤ a) (c0 : 0 < c) : a * b < c :=
(mul_le_mul_of_nonneg_left bc a0).trans_lt $ mul_lt_of_lt_one_left c0 ha
lemma mul_lt_of_le_one_of_lt' [pos_mul_strict_mono α] [mul_pos_mono α]
(ha : a ≤ 1) (bc : b < c) (a0 : 0 < a) (c0 : 0 ≤ c) : a * b < c :=
(mul_lt_mul_of_pos_left bc a0).trans_le $ mul_le_of_le_one_left c0 ha
/-! Lemmas of the form `1 ≤ a → b ≤ c → b ≤ a * c`. -/
lemma lt_mul_of_one_lt_of_le_of_pos [mul_pos_strict_mono α] (ha : 1 < a) (h : b ≤ c) (hc : 0 < c) :
b < a * c :=
h.trans_lt $ lt_mul_of_one_lt_left hc ha
lemma lt_mul_of_one_le_of_lt_of_nonneg [mul_pos_mono α] (ha : 1 ≤ a) (h : b < c) (hc : 0 ≤ c) :
b < a * c :=
h.trans_le $ le_mul_of_one_le_left hc ha
lemma lt_mul_of_one_lt_of_lt_of_pos [mul_pos_strict_mono α] (ha : 1 < a) (h : b < c) (hc : 0 < c) :
b < a * c :=
h.trans $ lt_mul_of_one_lt_left hc ha
/-- Assumes right covariance. -/
lemma right.one_lt_mul_of_lt_of_le_of_pos [mul_pos_strict_mono α]
(ha : 1 < a) (hb : 1 ≤ b) (b0 : 0 < b) : 1 < a * b :=
lt_mul_of_one_lt_of_le_of_pos ha hb b0
/-- Assumes right covariance. -/
lemma right.one_lt_mul_of_le_of_lt_of_nonneg [mul_pos_mono α]
(ha : 1 ≤ a) (hb : 1 < b) (b0 : 0 ≤ b) : 1 < a * b :=
lt_mul_of_one_le_of_lt_of_nonneg ha hb b0
/-- Assumes right covariance. -/
lemma right.one_lt_mul_of_lt_of_lt [mul_pos_strict_mono α]
(ha : 1 < a) (hb : 1 < b) (b0 : 0 < b) : 1 < a * b :=
lt_mul_of_one_lt_of_lt_of_pos ha hb b0
lemma lt_mul_of_one_lt_of_lt_of_nonneg [mul_pos_mono α] (ha : 1 ≤ a) (h : b < c) (hc : 0 ≤ c) :
b < a * c :=
h.trans_le $ le_mul_of_one_le_left hc ha
lemma lt_of_mul_lt_of_one_le_of_nonneg_left [pos_mul_mono α] (h : a * b < c) (hle : 1 ≤ b)
(ha : 0 ≤ a) :
a < c :=
(le_mul_of_one_le_right ha hle).trans_lt h
lemma lt_of_lt_mul_of_le_one_of_nonneg_left [pos_mul_mono α] (h : a < b * c) (hc : c ≤ 1)
(hb : 0 ≤ b) :
a < b :=
h.trans_le $ mul_le_of_le_one_right hb hc
lemma lt_of_lt_mul_of_le_one_of_nonneg_right [mul_pos_mono α] (h : a < b * c) (hb : b ≤ 1)
(hc : 0 ≤ c) :
a < c :=
h.trans_le $ mul_le_of_le_one_left hc hb
lemma le_mul_of_one_le_of_le_of_nonneg [mul_pos_mono α] (ha : 1 ≤ a) (bc : b ≤ c) (c0 : 0 ≤ c) :
b ≤ a * c :=
bc.trans $ le_mul_of_one_le_left c0 ha
/-- Assumes right covariance. -/
lemma right.one_le_mul_of_le_of_le [mul_pos_mono α] (ha : 1 ≤ a) (hb : 1 ≤ b) (b0 : 0 ≤ b) :
1 ≤ a * b :=
le_mul_of_one_le_of_le_of_nonneg ha hb b0
lemma le_of_mul_le_of_one_le_of_nonneg_left [pos_mul_mono α] (h : a * b ≤ c) (hb : 1 ≤ b)
(ha : 0 ≤ a) :
a ≤ c :=
(le_mul_of_one_le_right ha hb).trans h
lemma le_of_le_mul_of_le_one_of_nonneg_left [pos_mul_mono α] (h : a ≤ b * c) (hc : c ≤ 1)
(hb : 0 ≤ b) :
a ≤ b :=
h.trans $ mul_le_of_le_one_right hb hc
lemma le_of_mul_le_of_one_le_nonneg_right [mul_pos_mono α] (h : a * b ≤ c) (ha : 1 ≤ a)
(hb : 0 ≤ b) :
b ≤ c :=
(le_mul_of_one_le_left hb ha).trans h
lemma le_of_le_mul_of_le_one_of_nonneg_right [mul_pos_mono α] (h : a ≤ b * c) (hb : b ≤ 1)
(hc : 0 ≤ c) :
a ≤ c :=
h.trans $ mul_le_of_le_one_left hc hb
end preorder
section linear_order
variables [linear_order α]
-- Yaël: What's the point of this lemma? If we have `0 * 0 = 0`, then we can just take `b = 0`.
-- proven with `a0 : 0 ≤ a` as `exists_square_le`
lemma exists_square_le' [pos_mul_strict_mono α] (a0 : 0 < a) : ∃ (b : α), b * b ≤ a :=
begin
obtain ha | ha := lt_or_le a 1,
{ exact ⟨a, (mul_lt_of_lt_one_right a0 ha).le⟩ },
{ exact ⟨1, by rwa mul_one⟩ }
end
end linear_order
end mul_one_class
section cancel_monoid_with_zero
variables [cancel_monoid_with_zero α]
section partial_order
variables [partial_order α]
lemma pos_mul_mono.to_pos_mul_strict_mono [pos_mul_mono α] : pos_mul_strict_mono α :=
⟨λ x a b h, (mul_le_mul_of_nonneg_left h.le x.2.le).lt_of_ne (h.ne ∘ mul_left_cancel₀ x.2.ne')⟩
lemma pos_mul_mono_iff_pos_mul_strict_mono : pos_mul_mono α ↔ pos_mul_strict_mono α :=
⟨@pos_mul_mono.to_pos_mul_strict_mono α _ _, @pos_mul_strict_mono.to_pos_mul_mono α _ _⟩
lemma mul_pos_mono.to_mul_pos_strict_mono [mul_pos_mono α] : mul_pos_strict_mono α :=
⟨λ x a b h, (mul_le_mul_of_nonneg_right h.le x.2.le).lt_of_ne (h.ne ∘ mul_right_cancel₀ x.2.ne')⟩
lemma mul_pos_mono_iff_mul_pos_strict_mono : mul_pos_mono α ↔ mul_pos_strict_mono α :=
⟨@mul_pos_mono.to_mul_pos_strict_mono α _ _, @mul_pos_strict_mono.to_mul_pos_mono α _ _⟩
lemma pos_mul_reflect_lt.to_pos_mul_mono_rev [pos_mul_reflect_lt α] : pos_mul_mono_rev α :=
⟨λ x a b h, h.eq_or_lt.elim (le_of_eq ∘ mul_left_cancel₀ x.2.ne.symm)
(λ h', (lt_of_mul_lt_mul_left h' x.2.le).le)⟩
lemma pos_mul_mono_rev_iff_pos_mul_reflect_lt : pos_mul_mono_rev α ↔ pos_mul_reflect_lt α :=
⟨@pos_mul_mono_rev.to_pos_mul_reflect_lt α _ _, @pos_mul_reflect_lt.to_pos_mul_mono_rev α _ _⟩
lemma mul_pos_reflect_lt.to_mul_pos_mono_rev [mul_pos_reflect_lt α] : mul_pos_mono_rev α :=
⟨λ x a b h, h.eq_or_lt.elim (le_of_eq ∘ mul_right_cancel₀ x.2.ne.symm)
(λ h', (lt_of_mul_lt_mul_right h' x.2.le).le)⟩
lemma mul_pos_mono_rev_iff_mul_pos_reflect_lt : mul_pos_mono_rev α ↔ mul_pos_reflect_lt α :=
⟨@mul_pos_mono_rev.to_mul_pos_reflect_lt α _ _, @mul_pos_reflect_lt.to_mul_pos_mono_rev α _ _⟩
end partial_order
end cancel_monoid_with_zero
section comm_semigroup_has_zero
variables [comm_semigroup α] [has_zero α] [preorder α]
lemma pos_mul_strict_mono_iff_mul_pos_strict_mono :
pos_mul_strict_mono α ↔ mul_pos_strict_mono α :=
by simp ! only [mul_comm]
lemma pos_mul_reflect_lt_iff_mul_pos_reflect_lt :
pos_mul_reflect_lt α ↔ mul_pos_reflect_lt α :=
by simp ! only [mul_comm]
lemma pos_mul_mono_iff_mul_pos_mono :
pos_mul_mono α ↔ mul_pos_mono α :=
by simp ! only [mul_comm]
lemma pos_mul_mono_rev_iff_mul_pos_mono_rev :
pos_mul_mono_rev α ↔ mul_pos_mono_rev α :=
by simp ! only [mul_comm]
end comm_semigroup_has_zero
|
1e2a2a452ba1a214b8ae3a0f468dfd7414648787 | 556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e | /src/starkware/cairo/lean/semantics/air_encoding/correctness.lean | bce496b1232c95284166c0747b5c8b62ec014821 | [
"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 | 8,173 | lean | /-
A proof of the main theorem of the whitepaper:
Given a collection of data meeting all the constraints in `constraints`, assuming the extra
probabilistic assumptions hold, there is an execution trace according to the semantics given in
`cpu`, with the given length, start state, and final value of the program counter.
-/
import starkware.cairo.lean.semantics.cpu
import starkware.cairo.lean.semantics.air_encoding.constraints
import starkware.cairo.lean.semantics.air_encoding.memory
import starkware.cairo.lean.semantics.air_encoding.range_check
import starkware.cairo.lean.semantics.air_encoding.instruction
import starkware.cairo.lean.semantics.air_encoding.step
import starkware.cairo.lean.semantics.air_encoding.range_check_builtin
open_locale classical
/- assume F is a sufficiently large finite field -/
variables {F : Type} [field F] [fintype F]
/-
The probabilistic assumptions.
-/
structure hprob {inp : input_data_aux F} (c : constraints inp) :=
(hprob₁ : c.mc.mb.alpha ∉ bad_set_1 (real_a inp.mem_star c.mc.a c.mc.em.embed_mem)
(real_v inp.mem_star c.mc.v c.mc.em.embed_mem) c.mc.mb.a' c.mc.mb.v')
(hprob₂ : c.mc.mb.z ∉ bad_set_2 (real_a inp.mem_star c.mc.a c.mc.em.embed_mem)
(real_v inp.mem_star c.mc.v c.mc.em.embed_mem) c.mc.mb.a' c.mc.mb.v'
c.mc.mb.alpha)
(hprob₃ : c.mc.mb.z ≠ 0)
(hprob₄ : c.rc.z ∉ bad_set_3 c.rc.a c.rc.a')
/--
The main theorem: if the constraints hold for the trace data, then for any memory assignment
that agrees with the input data, the memory locations associated with the range check builtin
have been range checked, and there is an execution trace that agrees with the input data.
-/
theorem execution_exists (char_ge : ring_char F ≥ 2^63)
(inp : input_data_aux F) (c : constraints inp) (hp : hprob c) :
∃ mem : F → F,
option.fn_extends mem inp.mem_star ∧
(∀ i < inp.rc_len, ∃ n < 2^128, mem (inp.initial_rc_addr + i) = ↑n) ∧
∃ exec : fin (inp.T + 1) → register_state F,
(exec 0).pc = inp.pc_I ∧
(exec 0).ap = inp.ap_I ∧
(exec 0).fp = inp.ap_I ∧
(exec (fin.last inp.T)).pc = inp.pc_F ∧
(exec (fin.last inp.T)).ap = inp.ap_F ∧
∀ i : fin inp.T, next_state mem (exec i.cast_succ) (exec i.succ) :=
begin
have char_gt : ring_char F > 2^16,
{ apply lt_of_lt_of_le _ char_ge, apply pow_lt_pow; norm_num },
let m := mem c.mc.mb.a' c.mc.mb.v',
have mem_extends : option.fn_extends m inp.mem_star :=
mem_extends c.mc.mb.h_continuity c.mc.mb.h_single_valued
c.mc.mb.h_initial c.mc.mb.h_cumulative c.mc.mb.h_final c.mc.em.h_embed_dom
c.mc.em.h_embed_val c.mc.em.h_embed_mem_inj hp.hprob₃ hp.hprob₁ hp.hprob₂ c.mc.h_n_lt,
have mem_pc_addr : ∀ i : fin inp.T, m (c.pc i.cast_succ) = c.inst i :=
mem_pc c.mc.mb.h_continuity c.mc.mb.h_single_valued c.mc.mb.h_initial
c.mc.mb.h_cumulative c.mc.mb.h_final c.mc.em.h_embed_pc c.mc.em.h_embed_inst
c.mc.em.h_embed_dom c.mc.em.h_embed_val c.mc.em.h_embed_mem_inj
c.mc.em.h_embed_mem_disj_inst hp.hprob₃ hp.hprob₁ hp.hprob₂ c.mc.h_n_lt,
have mem_dst_addr : ∀ i, m (c.dst_addr i) = c.dst i :=
mem_dst_addr
c.mc.mb.h_continuity c.mc.mb.h_single_valued c.mc.mb.h_initial c.mc.mb.h_cumulative
c.mc.mb.h_final c.mc.em.h_embed_dst_addr c.mc.em.h_embed_dst c.mc.em.h_embed_dom
c.mc.em.h_embed_val c.mc.em.h_embed_mem_inj c.mc.em.h_embed_mem_disj_dst
hp.hprob₃ hp.hprob₁ hp.hprob₂ c.mc.h_n_lt,
have mem_op0_addr : ∀ i, m (c.op0_addr i) = c.op0 i :=
mem_op0_addr
c.mc.mb.h_continuity c.mc.mb.h_single_valued c.mc.mb.h_initial c.mc.mb.h_cumulative
c.mc.mb.h_final c.mc.em.h_embed_op0_addr c.mc.em.h_embed_op0 c.mc.em.h_embed_dom
c.mc.em.h_embed_val c.mc.em.h_embed_mem_inj c.mc.em.h_embed_mem_disj_op0
hp.hprob₃ hp.hprob₁ hp.hprob₂ c.mc.h_n_lt,
have mem_op1_addr : ∀ i, m (c.op1_addr i) = c.op1 i :=
mem_op1_addr
c.mc.mb.h_continuity c.mc.mb.h_single_valued c.mc.mb.h_initial c.mc.mb.h_cumulative
c.mc.mb.h_final c.mc.em.h_embed_op1_addr c.mc.em.h_embed_op1 c.mc.em.h_embed_dom
c.mc.em.h_embed_val c.mc.em.h_embed_mem_inj c.mc.em.h_embed_mem_disj_op1
hp.hprob₃ hp.hprob₁ hp.hprob₂ c.mc.h_n_lt,
have mem_rc_addr : ∀ i, m (c.rc_addr i) = c.rc_val i :=
mem_rc_addr
c.mc.mb.h_continuity c.mc.mb.h_single_valued c.mc.mb.h_initial c.mc.mb.h_cumulative
c.mc.mb.h_final c.mc.em.h_embed_rc_addr c.mc.em.h_embed_rc c.mc.em.h_embed_dom
c.mc.em.h_embed_val c.mc.em.h_embed_mem_inj c.mc.em.h_embed_mem_disj_rc
hp.hprob₃ hp.hprob₁ hp.hprob₂ c.mc.h_n_lt,
have off_op0_in_range : ∀ i, ∃ k : ℕ, k < 2^16 ∧ c.off_op0_tilde i = ↑k :=
off_op0_in_range c.rc.h_continuity c.rc.h_initial c.rc.h_cumulative c.rc.h_final
c.rc.h_rc_min c.rc.h_rc_max c.rc.h_embed_op0 c.rc.h_n_lt inp.h_rc_lt inp.h_rc_le char_gt
hp.hprob₄,
have off_op1_in_range : ∀ i, ∃ k : ℕ, k < 2^16 ∧ c.off_op1_tilde i = ↑k :=
off_op1_in_range c.rc.h_continuity c.rc.h_initial c.rc.h_cumulative c.rc.h_final
c.rc.h_rc_min c.rc.h_rc_max c.rc.h_embed_op1 c.rc.h_n_lt inp.h_rc_lt inp.h_rc_le char_gt
hp.hprob₄,
have off_dst_in_range : ∀ i, ∃ k : ℕ, k < 2^16 ∧ c.off_dst_tilde i = ↑k :=
off_dst_in_range c.rc.h_continuity c.rc.h_initial c.rc.h_cumulative c.rc.h_final
c.rc.h_rc_min c.rc.h_rc_max c.rc.h_embed_dst c.rc.h_n_lt inp.h_rc_lt inp.h_rc_le char_gt
hp.hprob₄,
have rc16_vals_in_range : ∀ i, ∃ k : ℕ, k < 2^16 ∧ c.rc16_val i = ↑k :=
rc16_vals_in_range c.rc.h_continuity c.rc.h_initial c.rc.h_cumulative c.rc.h_final
c.rc.h_rc_min c.rc.h_rc_max c.rc.h_embed_rc16 c.rc.h_n_lt inp.h_rc_lt inp.h_rc_le char_gt
hp.hprob₄,
have range_checked :
∀ i < inp.rc_len, ∃ n < 2^128, m (inp.initial_rc_addr + i) = ↑n,
{ intros i hi,
rcases rc_val_checked rc16_vals_in_range c.rcb.h_rc_value ⟨i, hi⟩ with ⟨n, nlt, neq⟩,
use [n, nlt],
rw ←neq, dsimp, rw ←mem_rc_addr,
rw rc_addr_eq c.rcb.h_rc_init_addr c.rcb.h_rc_addr_step ⟨i, hi⟩,
refl },
use [m, mem_extends, range_checked],
let e := λ i : fin (inp.T + 1), register_state.mk (c.pc i) (c.ap i) (c.fp i),
use [e, c.h_pc_I, c.h_ap_I, c.h_fp_I, c.h_pc_F, c.h_ap_F],
intro i,
show next_state m (e i.cast_succ) (e i.succ),
let inst' := the_instruction (c.ic i).h_bit (off_op0_in_range i) (off_op1_in_range i)
(off_dst_in_range i),
have inst_eq : c.inst i = ↑(inst'.to_nat) :=
inst_eq (c.ic i).h_instruction (c.ic i).h_bit (c.ic i).h_last_value
(off_op0_in_range i) (off_op1_in_range i) (off_dst_in_range i),
have off_dst_tilde_eq : c.off_dst_tilde i = ↑(inst'.off_dst.to_natr) :=
off_dst_tilde_eq (c.ic i).h_bit (off_op0_in_range i) (off_op1_in_range i)
(off_dst_in_range i),
have off_op0_tilde_eq : c.off_op0_tilde i = ↑(inst'.off_op0.to_natr) :=
off_op0_tilde_eq (c.ic i).h_bit (off_op0_in_range i) (off_op1_in_range i)
(off_dst_in_range i),
have off_op1_tilde_eq : c.off_op1_tilde i = ↑(inst'.off_op1.to_natr) :=
off_op1_tilde_eq (c.ic i).h_bit (off_op0_in_range i) (off_op1_in_range i)
(off_dst_in_range i),
have f_tilde_to_f_eq : ∀ j, (c.f_tilde i).to_f j = ↑((inst'.flags.nth j).to_nat) :=
f_tilde_to_f_eq (c.ic i).h_bit (off_op0_in_range i) (off_op1_in_range i)
(off_dst_in_range i),
exact next_state_eq off_dst_tilde_eq off_op0_tilde_eq off_op1_tilde_eq f_tilde_to_f_eq
((mem_pc_addr i).trans inst_eq) (mem_dst_addr i) (mem_op0_addr i) (mem_op1_addr i)
(c.sc i).h_dst_addr (c.sc i).h_op0_addr (c.sc i).h_op1_addr (c.sc i).h_mul
(c.sc i).h_res (c.sc i).h_t0_eq (c.sc i).h_t1_eq (c.sc i).h_next_pc_eq (c.sc i).h_next_pc_eq'
(c.sc i).h_opcode_call (c.sc i).h_opcode_call' (c.sc i).h_opcode_assert_eq
(c.sc i).h_next_ap (c.sc i).h_next_fp
end
|
eafb21da9a0ca406cbedf6146db35269f09b11af | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/ring_theory/polynomial/pochhammer.lean | a57088073ac9a42c350bc0585cb8015dc17a4a3e | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 5,327 | 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 tactic.abel
import data.polynomial.eval
/-!
# The Pochhammer polynomials
We define and prove some basic relations about
`pochhammer S n : polynomial S = X * (X+1) * ... * (X + n - 1)`
which is also known as the rising factorial. A version of this definition
that is focused on `nat` can be found in `data.nat.factorial` as `asc_factorial`.
## Implementation
As with many other families of polynomials, even though the coefficients are always in `ℕ`,
we define the polynomial with coefficients in any `[semiring S]`.
## TODO
There is lots more in this direction:
* q-factorials, q-binomials, q-Pochhammer.
-/
universes u v
open polynomial
section
variables (S : Type u) [semiring S]
/--
`pochhammer S n` is the polynomial `X * (X+1) * ... * (X + n - 1)`,
with coefficients in the semiring `S`.
-/
noncomputable def pochhammer : ℕ → polynomial S
| 0 := 1
| (n+1) := X * (pochhammer n).comp (X + 1)
@[simp] lemma pochhammer_zero : pochhammer S 0 = 1 := rfl
@[simp] lemma pochhammer_one : pochhammer S 1 = X := by simp [pochhammer]
lemma pochhammer_succ_left (n : ℕ) : pochhammer S (n+1) = X * (pochhammer S n).comp (X+1) :=
by rw pochhammer
section
variables {S} {T : Type v} [semiring T]
@[simp] lemma pochhammer_map (f : S →+* T) (n : ℕ) : (pochhammer S n).map f = pochhammer T n :=
begin
induction n with n ih,
{ simp, },
{ simp [ih, pochhammer_succ_left, map_comp], },
end
end
@[simp, norm_cast] lemma pochhammer_eval_cast (n k : ℕ) :
((pochhammer ℕ n).eval k : S) = (pochhammer S n).eval k :=
begin
rw [←pochhammer_map (algebra_map ℕ S), eval_map, ←(algebra_map ℕ S).eq_nat_cast,
eval₂_at_nat_cast, nat.cast_id, ring_hom.eq_nat_cast],
end
lemma pochhammer_eval_zero {n : ℕ} : (pochhammer S n).eval 0 = if n = 0 then 1 else 0 :=
begin
cases n,
{ simp, },
{ simp [X_mul, nat.succ_ne_zero, pochhammer_succ_left], }
end
lemma pochhammer_zero_eval_zero : (pochhammer S 0).eval 0 = 1 :=
by simp
@[simp] lemma pochhammer_ne_zero_eval_zero {n : ℕ} (h : n ≠ 0) : (pochhammer S n).eval 0 = 0 :=
by simp [pochhammer_eval_zero, h]
lemma pochhammer_succ_right (n : ℕ) : pochhammer S (n+1) = pochhammer S n * (X + n) :=
begin
suffices h : pochhammer ℕ (n+1) = pochhammer ℕ n * (X + n),
{ apply_fun polynomial.map (algebra_map ℕ S) at h,
simpa only [pochhammer_map, map_mul, map_add, map_X, map_nat_cast] using h, },
induction n with n ih,
{ simp, },
{ conv_lhs {
rw [pochhammer_succ_left, ih, mul_comp, ←mul_assoc, ←pochhammer_succ_left, add_comp, X_comp,
nat_cast_comp, add_assoc, add_comm (1 : polynomial ℕ)], },
refl, },
end
lemma polynomial.mul_X_add_nat_cast_comp {p q : polynomial S} {n : ℕ} :
(p * (X + n)).comp q = (p.comp q) * (q + n) :=
by rw [mul_add, add_comp, mul_X_comp, ←nat.cast_comm, nat_cast_mul_comp, nat.cast_comm, mul_add]
lemma pochhammer_mul (n m : ℕ) :
pochhammer S n * (pochhammer S m).comp (X + n) = pochhammer S (n + m) :=
begin
induction m with m ih,
{ simp, },
{ rw [pochhammer_succ_right, polynomial.mul_X_add_nat_cast_comp, ←mul_assoc, ih,
nat.succ_eq_add_one, ←add_assoc, pochhammer_succ_right, nat.cast_add, add_assoc], }
end
lemma pochhammer_nat_eq_asc_factorial (n : ℕ) :
∀ k, (pochhammer ℕ k).eval (n + 1) = n.asc_factorial k
| 0 := by erw [eval_one]; refl
| (t + 1) := begin
rw [pochhammer_succ_right, eval_mul, pochhammer_nat_eq_asc_factorial t],
suffices : n.asc_factorial t * (n + 1 + t) = n.asc_factorial (t + 1), by simpa,
rw [nat.asc_factorial_succ, add_right_comm, mul_comm]
end
end
section
variables {S : Type*} [ordered_semiring S] [nontrivial S]
lemma pochhammer_pos (n : ℕ) (s : S) (h : 0 < s) : 0 < (pochhammer S n).eval s :=
begin
induction n with n ih,
{ simp only [nat.nat_zero_eq_zero, pochhammer_zero, eval_one], exact zero_lt_one, },
{ rw [pochhammer_succ_right, mul_add, eval_add, ←nat.cast_comm, eval_nat_cast_mul, eval_mul_X,
nat.cast_comm, ←mul_add],
exact mul_pos ih
(lt_of_lt_of_le h ((le_add_iff_nonneg_right _).mpr (nat.cast_nonneg n))), }
end
end
section factorial
open_locale nat
variables (S : Type*) [semiring S] (r n : ℕ)
@[simp]
lemma pochhammer_eval_one (S : Type*) [semiring S] (n : ℕ) :
(pochhammer S n).eval (1 : S) = (n! : S) :=
by rw_mod_cast [pochhammer_nat_eq_asc_factorial, nat.zero_asc_factorial]
lemma factorial_mul_pochhammer (S : Type*) [semiring S] (r n : ℕ) :
(r! : S) * (pochhammer S n).eval (r + 1) = (r + n)! :=
by rw_mod_cast [pochhammer_nat_eq_asc_factorial, nat.factorial_mul_asc_factorial]
lemma pochhammer_nat_eval_succ (r : ℕ) :
∀ n : ℕ, n * (pochhammer ℕ r).eval (n + 1) = (n + r) * (pochhammer ℕ r).eval n
| 0 := begin
by_cases h : r = 0,
{ simp only [h, zero_mul, zero_add], },
{ simp only [pochhammer_eval_zero, zero_mul, if_neg h, mul_zero], }
end
| (k + 1) := by simp only [pochhammer_nat_eq_asc_factorial, nat.succ_asc_factorial, add_right_comm]
lemma pochhammer_eval_succ (r n : ℕ) :
(n : S) * (pochhammer S r).eval (n + 1 : S) = (n + r) * (pochhammer S r).eval n :=
by exact_mod_cast congr_arg nat.cast (pochhammer_nat_eval_succ r n)
end factorial
|
6ac67a2e357031ba97ea41f3eed98848a7bd2152 | f02b05b665ad2d2cd970e93758a98d57f310a822 | /src/tactic/tcache/enable.lean | 8fd8acc2965bb5bf81f9b296c6cbb13a56bae8ab | [] | no_license | khoek/leancache | b0ed5d2a9a2e87f58d4ad27343d957a9cd49ce5f | 5c8329f7b647b8d82966ab180c4473b20d1f249c | refs/heads/master | 1,585,344,140,717 | 1,549,094,327,000 | 1,549,094,327,000 | 147,138,187 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14 | lean | import .hijack |
83ead407728d51ee2a4495b046a4bab173a4c8c0 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /tests/lean/simpcfg.lean | e0803ad9ed03bc799a459f0e6a6b19cee07d1901 | [
"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 | 185 | lean | theorem ex6 (f : Nat → Nat) (x y z : Nat) (h : (x, z).1 = (fun x => x) y) : f x = f y := by
simp (config := { beta := false }) at h
traceState
simp at h
traceState
simp [h]
|
8b9dea689786ddda20481f3681481599c47005b2 | a537b538f2bea3181e24409d8a52590603d1ddd9 | /src/tidy/rewrite_search/discovery/suggest.lean | 385617b78b9096b4bf671c2d2fcc6672adc6382e | [] | no_license | rwbarton/lean-tidy | 6134813ded72b275d19d4d32514dba80c21708e3 | fe1125d32adb60decda7a77d0f679614ba9f6fbb | refs/heads/master | 1,585,549,718,705 | 1,538,120,619,000 | 1,538,120,624,000 | 150,864,330 | 0 | 0 | null | 1,538,225,790,000 | 1,538,225,790,000 | null | UTF-8 | Lean | false | false | 2,039 | lean | import tidy.lib.tactic
import .bundle
namespace tidy.rewrite_search.discovery
open tactic
private meta def suggest_fail {α : Type} : format → tactic α := atrr_fail "suggest"
-- Reads the name of a list/single annotated with `[suggest]`.
meta def read_suggestion (n : name) : tactic (list name) := do
let n : expr := expr.const n [],
(do l ← eval_expr (list name) n, return l) -- Is the suggestion a list?
<|> (do s ← eval_expr name n, return [s]) -- Is the suggestion a singleton?
<|> fail "[suggest] error: only `name`s, or `list names`, can be tagged with `suggest`. These names should all refer to `bundle`s."
-- Reads a list of bundle names and converts them into the actual
-- identifiers of the bundles (which unfortunately are also just names).
-- I fail if I can't find a bundle, since `get_bundle` does too.
meta def lookup_suggestion (l : list name) : tactic (list name) :=
l.mmap (λ n, do b ← get_bundle n, return b.name)
-- Reads the name of a list/single annotated with `[suggest]` and
-- returns the list of identifiers for the bundles which were
-- referred to.
meta def resolve_suggestion (n : name) : tactic (list name) :=
read_suggestion n >>= lookup_suggestion
@[user_attribute]
meta def suggest_attr : user_attribute unit (list name) := {
name := `suggest,
descr := "suggests the name of a bundle, or a list of names of bundles, to the `rewrite_search`er",
parser := return [],
after_set := some (λ n _ _, do
p ← suggest_attr.get_param n,
match p with
| [] := do
ls ← resolve_suggestion n,
if ls.length = 0 then skip -- prevent infinite recursion
else suggest_attr.set n ls tt
| _ := skip
end
),
before_unset := some (λ _ _, skip)
}
meta def get_suggested_bundle_idents : tactic (list name) := do
ls ← attribute.get_instances `suggest,
ls ← ls.mmap suggest_attr.get_param,
return ls.join.erase_duplicates
@[suggest]
meta def default_suggestions : list name := default_bundles
end tidy.rewrite_search.discovery
|
3ee5bc12d4568e8664e58088e664195666a2fa55 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/help_cmd.lean | 202dc769f5ff78af92fab23d6e7f999e99cc7c48 | [
"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 | 46 | lean | #help options
#help commands
#print options
|
6739cf278eced279a6a33b682230565bfef93796 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/adjunction/whiskering.lean | 5a82ed48a9f7d35451e60e8d397772c50adf09bf | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,607 | 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.whiskering
import category_theory.adjunction.basic
/-!
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Given categories `C D E`, functors `F : D ⥤ E` and `G : E ⥤ D` with an adjunction
`F ⊣ G`, we provide the induced adjunction between the functor categories `C ⥤ D` and `C ⥤ E`,
and the functor categories `E ⥤ C` and `D ⥤ C`.
-/
namespace category_theory.adjunction
open category_theory
variables (C : Type*) {D E : Type*} [category C] [category D] [category E]
{F : D ⥤ E} {G : E ⥤ D}
-- `tidy` works for all the proofs in this definition, but it's fairly slow.
/-- Given an adjunction `F ⊣ G`, this provides the natural adjunction
`(whiskering_right C _ _).obj F ⊣ (whiskering_right C _ _).obj G`. -/
@[simps unit_app_app counit_app_app]
protected def whisker_right (adj : F ⊣ G) :
(whiskering_right C D E).obj F ⊣ (whiskering_right C E D).obj G :=
mk_of_unit_counit
{ unit :=
{ app := λ X, (functor.right_unitor _).inv ≫
whisker_left X adj.unit ≫ (functor.associator _ _ _).inv,
naturality' := by { intros, ext, dsimp, simp } },
counit :=
{ app := λ X, (functor.associator _ _ _).hom ≫
whisker_left X adj.counit ≫ (functor.right_unitor _).hom,
naturality' := by { intros, ext, dsimp, simp } },
left_triangle' := by { ext, dsimp, simp },
right_triangle' := by { ext, dsimp, simp } }
-- `tidy` gets stuck for `left_triangle'` and `right_triangle'`.
/-- Given an adjunction `F ⊣ G`, this provides the natural adjunction
`(whiskering_left _ _ C).obj G ⊣ (whiskering_left _ _ C).obj F`. -/
@[simps unit_app_app counit_app_app]
protected def whisker_left (adj : F ⊣ G) :
(whiskering_left E D C).obj G ⊣ (whiskering_left D E C).obj F :=
mk_of_unit_counit
{ unit :=
{ app := λ X, (functor.left_unitor _).inv ≫
whisker_right adj.unit X ≫ (functor.associator _ _ _).hom,
naturality' := by { intros, ext, dsimp, simp } },
counit :=
{ app := λ X, (functor.associator _ _ _).inv ≫
whisker_right adj.counit X ≫ (functor.left_unitor _).hom,
naturality' := by { intros, ext, dsimp, simp } },
left_triangle' := by { ext x, dsimp,
simp only [category.id_comp, category.comp_id, ← x.map_comp], simp },
right_triangle' := by { ext x, dsimp,
simp only [category.id_comp, category.comp_id, ← x.map_comp], simp } }
end category_theory.adjunction
|
bb3f9b51b271a388e64f00f36df31f60a1ed6ae9 | 4d5b7055cbdeb6cba319e752a30efb69c82b0366 | /src/solutions/friday/manifolds.lean | b446b3cfa80b8f72973b7b14decda9ff3f8fbfc7 | [] | no_license | jipsen/lftcm2020 | f214f06cef58527e1bec605cc1c5d1f61a2fd951 | d91768875dc3c54ec28debb6c2c63384a38d537b | refs/heads/master | 1,669,013,666,809 | 1,594,928,693,000 | 1,594,928,693,000 | 280,284,719 | 0 | 0 | null | 1,594,944,305,000 | 1,594,944,304,000 | null | UTF-8 | Lean | false | false | 32,770 | lean | import for_mathlib.manifolds
noncomputable theory
open_locale manifold classical big_operators
open set
universe u
/-! ### Local homeomorphisms
Local homeomorphisms are globally defined maps with a globally defined "inverse", but the only
relevant set is the *source*, which should be mapped homeomorphically to the *target*.
-/
/- Define a local homeomorphism from `ℝ` to `ℝ` which is just `x ↦ -x`, but on `(-1, 1)`. In
Lean, the interval `(-1, 1)` is denoted by `Ioo (-1 : ℝ) 1` (where `o` stands for _open_). -/
@[simp] lemma neg_mem_Ioo_minus_one_one (x : ℝ) : -x ∈ Ioo (-1 : ℝ) 1 ↔ x ∈ Ioo (-1 : ℝ) 1 :=
begin
-- sorry
simp [neg_lt, and_comm],
-- sorry
end
def my_first_local_homeo : local_homeomorph ℝ ℝ :=
{ to_fun := λ x, -x,
inv_fun := λ x, -x,
source := Ioo (-1) 1,
target := /- inline sorry -/Ioo (-1) 1/- inline sorry -/,
map_source' :=
begin
-- sorry
assume x hx,
simp [hx],
-- sorry
end,
map_target' :=
begin
-- sorry
assume x hx,
simp [hx],
-- sorry
end,
left_inv' :=
begin
-- sorry
simp,
-- sorry
end,
right_inv' :=
begin
-- sorry
simp,
-- sorry
end,
open_source := /- inline sorry -/is_open_Ioo/- inline sorry -/,
open_target := /- inline sorry -/is_open_Ioo/- inline sorry -/,
continuous_to_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/,
continuous_inv_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/ }
/- Two simple lemmas that will prove useful below. You can leave them sorried if you like. -/
lemma ne_3_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-1 : ℝ) 1) : x ≠ 3 :=
begin
-- sorry
exact ne_of_lt (lt_trans h.2 (by norm_num))
-- sorry
end
lemma neg_ne_3_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-1 : ℝ) 1) : -x ≠ 3 :=
begin
-- sorry
assume h',
simp at h,
linarith,
-- sorry
end
/- Now, define a second local homeomorphism which is almost like the previous one. You may find the
following lemma useful for `continuous_to_fun`: -/
#check continuous_on.congr
def my_second_local_homeo : local_homeomorph ℝ ℝ :=
{ to_fun := λ x, if x = 3 then 0 else - x,
inv_fun := λ x, -x,
source := Ioo (-1) 1,
target := /- inline sorry -/Ioo (-1) 1/- inline sorry -/,
map_source' := /- inline sorry -/λ x hx, by simp [hx, ne_3_of_mem_Ioo hx]/- inline sorry -/,
map_target' := /- inline sorry -/λ x hx, by simp [hx]/- inline sorry -/,
left_inv' := /- inline sorry -/λ x hx, by simp [hx, ne_3_of_mem_Ioo hx]/- inline sorry -/,
right_inv' := /- inline sorry -/λ x hx, by simp [hx, neg_ne_3_of_mem_Ioo hx]/- inline sorry -/,
open_source := /- inline sorry -/is_open_Ioo/- inline sorry -/,
open_target := /- inline sorry -/is_open_Ioo/- inline sorry -/,
continuous_to_fun :=
begin
-- sorry
refine continuous_neg.continuous_on.congr (λ x hx, _),
simp [hx, ne_3_of_mem_Ioo hx],
-- sorry
end,
continuous_inv_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/ }
/- Although the two above local homeos are the same for all practical purposes as they coincide
where relevant, they are not *equal*: -/
lemma my_first_local_homeo_ne_my_second_local_homeo :
my_first_local_homeo ≠ my_second_local_homeo :=
begin
-- sorry
assume h,
have : my_first_local_homeo 3 = my_second_local_homeo 3, by rw h,
simp [my_first_local_homeo, my_second_local_homeo] at this,
linarith,
-- sorry
end
/- The right equivalence relation for local homeos is not equality, but `eq_on_source`.
Indeed, the two local homeos we have defined above coincide from this point of view. -/
#check @local_homeomorph.eq_on_source
lemma eq_on_source_my_first_local_homeo_my_second_local_homeo :
local_homeomorph.eq_on_source my_first_local_homeo my_second_local_homeo :=
begin
-- sorry
refine ⟨rfl, λ x hx, _⟩,
simp [my_first_local_homeo, my_second_local_homeo, ne_3_of_mem_Ioo hx],
-- sorry
end
/-! ### An example of a charted space structure on `ℝ`
A charted space is a topological space together with a set of local homeomorphisms to a model space,
whose sources cover the whole space. For instance, `ℝ` is already endowed with a charted space
structure with model space `ℝ`, where the unique chart is the identity:
-/
#check charted_space_self ℝ
/- For educational purposes only, we will put another charted space structure on `ℝ` using the
local homeomorphisms we have constructed above. To avoid using too much structure of `ℝ` (and to
avoid confusing Lean), we will work with a copy of `ℝ`, on which we will only register the
topology. -/
@[derive topological_space]
def myℝ : Type := ℝ
instance : charted_space ℝ myℝ :=
{ atlas := { local_homeomorph.refl ℝ, my_first_local_homeo },
chart_at := λ x, if x ∈ Ioo (-1 : ℝ) 1 then my_first_local_homeo else local_homeomorph.refl ℝ,
mem_chart_source :=
begin
-- sorry
assume x,
split_ifs,
{ exact h },
{ exact mem_univ _ }
-- sorry
end,
chart_mem_atlas :=
begin
-- sorry
assume x,
split_ifs;
simp,
-- sorry
end }
/- Now come more interesting bits. We have endowed `myℝ` with a charted space structure, with charts
taking values in `ℝ`. We want to say that this is a smooth structure, i.e., the changes of
coordinates are smooth. In Lean, this is written with `has_structure_groupoid`. A groupoid is a set
of local homeomorphisms of the model space (for example, local homeos that are smooth on their
domain). A charted space admits the groupoid as a structure groupoid if all the changes of
coordinates belong to the groupoid.
There is a difficulty that the definitions are set up to be able to also speak of smooth manifolds
with boundary or with corners, so the name of the smooth groupoid on `ℝ` has the slightly strange
name `times_cont_diff_groupoid ∞ (model_with_corners_self ℝ ℝ)`. To avoid typing again and again
`model_with_corners_self ℝ ℝ`, let us introduce a shortcut
-/
abbreviation I := model_with_corners_self ℝ ℝ
/- In the library, there are such shortcuts for manifolds modelled on `ℝ^n`, denoted with `𝓡 n`,
but for `n = 1` this does not coincide with the above one, as `ℝ^1` (a.k.a. `fin 1 → ℝ`) is not
the same as `ℝ`! -/
instance : has_groupoid myℝ (times_cont_diff_groupoid ∞ I) :=
begin
-- in theory, we should prove that all compositions of charts are diffeos, i.e., they are smooth
-- and their inverse are smooth. For symmetry reasons, it suffices to check one direction
apply has_groupoid_of_pregroupoid,
-- take two charts `e` and `e'`
assume e e' he he',
-- if next line is a little bit slow for your taste, you can replace `simp` with `squeeze_simp`
-- and then follow the advice
simp [atlas] at he he',
dsimp,
-- to continue, some hints:
-- (1) don't hesitate to use the fact that the restriction of a smooth function to a
-- subset is still smooth there (`times_cont_diff.times_cont_diff_on`)
-- (2) hopefully, there is a theorem saying that the negation function is smooth.
-- you can either try to guess its name, or hope that `suggest` will help you there.
-- sorry
rcases he with rfl|rfl; rcases he' with rfl|rfl,
{ exact times_cont_diff_id.times_cont_diff_on },
{ exact times_cont_diff_id.neg.times_cont_diff_on },
{ exact times_cont_diff_id.neg.times_cont_diff_on },
{ convert times_cont_diff_id.times_cont_diff_on,
ext x,
simp [my_first_local_homeo], },
-- sorry
end
/- The statement of the previous instance is not very readable. There is a shortcut notation: -/
instance : smooth_manifold_with_corners I myℝ := {}
/- We will now study a very simple map from `myℝ` to `ℝ`, the identity. -/
def my_map : myℝ → ℝ := λ x, x
/- The map `my_map` is a map going from the type `myℝ` to the type `ℝ`. From the point of view of
the kernel of Lean, it is just the identity, but from the point of view of structures on `myℝ`
and `ℝ` it might not be trivial, as we have registered different instances on these two types. -/
/- The continuity should be trivial, as the topologies on `myℝ` and `ℝ` are definitionally the
same. So `continuous_id` might help. -/
lemma continuous_my_map : continuous my_map :=
-- sorry
continuous_id
-- sorry
/- Smoothness should not be obvious, though, as the manifold structures are not the same: the atlas
on `myℝ` has two elements, while the atlas on `ℝ` has one single element.
Note that `myℝ` is not a vector space, nor a normed space, so one can not ask whether `my_map`
is smooth in the usual sense (as a map between vector spaces): -/
-- lemma times_cont_diff_my_map : times_cont_diff ℝ ∞ my_map := sorry
/- does not make sense (try uncommenting it!) However, we can ask whether `my_map` is a smooth
map between manifolds, i.e., whether it is smooth when read in the charts. When we mention the
smoothness of a map, we should always specify explicitly the model with corners we are using,
because there might be several around (think of a complex manifold that you may want to consider
as a real manifold, to talk about functions which are real-smooth but not holomorphic) -/
lemma times_cont_mdiff_my_map : times_cont_mdiff I I ∞ my_map :=
begin
-- put things in a nicer form. The simpset `mfld_simps` registers many simplification rules for
-- manifolds. `simp` is used heavily in manifold files to bring everything into manageable form.
rw times_cont_mdiff_iff,
simp only [continuous_my_map] with mfld_simps,
-- simp has erased the chart in the target, as it knows that the only chart in the manifold `ℝ`
-- is the identity.
assume x y,
-- sorry
simp [my_map, (∘), chart_at],
split_ifs,
{ exact times_cont_diff_id.neg.times_cont_diff_on },
{ exact times_cont_diff_id.times_cont_diff_on },
-- sorry
end
/- Now, let's go to tangent bundles. We have a smooth manifold, so its tangent bundle should also
be a smooth manifold. -/
-- the type `tangent_bundle I myℝ` makes sense
#check tangent_bundle I myℝ
/- The tangent space above a point of `myℝ` is just a one-dimensional vector space (identified with `ℝ`).
So, one can prescribe an element of the tangent bundle as a pair (more on this below) -/
example : tangent_bundle I myℝ := ((4 : ℝ), 0)
/- Construct the smooth manifold structure on the tangent bundle. Hint: the answer is a one-liner,
and this instance is not really needed. -/
instance tangent_bundle_myℝ : smooth_manifold_with_corners (I.prod I) (tangent_bundle I myℝ) :=
-- sorry
by apply_instance
-- sorry
/-
NB: the model space for the tangent bundle to a product manifold or a tangent space is not
`ℝ × ℝ`, but a copy called `model_prod ℝ ℝ`. Otherwise, `ℝ × ℝ` would have two charted space
structures with model `ℝ × ℝ`, the identity one and the product one, which are not definitionally
equal. And this would be bad.
-/
#check tangent_bundle.charted_space I myℝ
/- A smooth map between manifolds induces a map between their tangent bundles. In `mathlib` this is
called the `tangent_map` (you might instead know it as the "differential" or "pushforward" of the
map). Let us check that the `tangent_map` of `my_map` is smooth. -/
lemma times_cont_mdiff_tangent_map_my_map :
times_cont_mdiff (I.prod I) (I.prod I) ∞ (tangent_map I I my_map) :=
begin
-- hopefully, there is a theorem providing the general result, i.e. the tangent map to a smooth
-- map is smooth.
-- you can either try to guess its name, or hope that `suggest` will help you there.
-- sorry
exact times_cont_mdiff_my_map.times_cont_mdiff_tangent_map le_top,
-- sorry
end
/- (Harder question) Can you show that this tangent bundle is homeomorphic to `ℝ × ℝ`? You could
try to build the homeomorphism by hand, using `tangent_map I I my_map` in one direction and a
similar map in the other direction, but it is probably more efficient to use one of the charts of
the tangent bundle.
Remember, the model space for `tangent_bundle I myℝ` is `model_prod ℝ ℝ`, not `ℝ × ℝ`. But the
topologies on `model_prod ℝ ℝ` and `ℝ × ℝ` are the same, so it is by definition good enough to
construct a homeomorphism with `model_prod ℝ ℝ`.
-/
def my_homeo : tangent_bundle I myℝ ≃ₜ (ℝ × ℝ) :=
begin
-- sorry
let p : tangent_bundle I myℝ := ((4 : ℝ), 0),
let F := chart_at (model_prod ℝ ℝ) p,
have A : ¬ ((4 : ℝ) < 1), by norm_num,
have S : F.source = univ, by simp [F, chart_at, A, @local_homeomorph.refl_source ℝ _],
have T : F.target = univ, by simp [F, chart_at, A, @local_homeomorph.refl_target ℝ _],
exact F.to_homeomorph_of_source_eq_univ_target_eq_univ S T,
-- sorry
end
/- Up to now, we have never used the definition of the tangent bundle, and this corresponds to
the usual mathematical practice: one doesn't care if the tangent space is defined using germs of
curves, or spaces of derivations, or whatever equivalent definition. Instead, one relies all the
time on functoriality (i.e., a smooth map has a well defined derivative, and they compose well,
together with the fact that the tangent bundle to a vector space is the product).
If you want to know more about the internals of the tangent bundle in mathlib, you can browse
through the next section, but it is maybe wiser to skip it on first reading, as it is not needed
to use the library
-/
section you_should_probably_skip_this
/- If `M` is a manifold modelled on a vector space `E`, then the underlying type for the tangent
bundle is just `M × E` -/
lemma tangent_bundle_myℝ_is_prod : tangent_bundle I myℝ = (myℝ × ℝ) :=
/- inline sorry -/rfl/- inline sorry -/
/- This means that you can specify a point in the tangent bundle as a pair `(x, y)`.
However, in general, a tangent bundle is not trivial: the topology on `tangent_bundle I myℝ` is *not*
the product topology. Instead, the tangent space at a point `x` is identified with `ℝ` through some
preferred chart at `x`, called `chart_at ℝ x`, but the way they are glued together depends on the
manifold and the charts.
In vector spaces, the tangent space is canonically the product space, with the same topology, as
there is only one chart so there is no strange gluing at play. The equality of the topologies
is given in `tangent_bundle_model_space_topology_eq_prod`, but they are not definitionally equal
so one can get strange behavior if abusing identifications.
Let us register the identification explicitly, as a homeomorphism:
-/
def tangent_bundle_vector_space_triv (E : Type u) [normed_group E] [normed_space ℝ E] :
tangent_bundle (model_with_corners_self ℝ E) E ≃ₜ E × E :=
{ to_fun := id,
inv_fun := id,
left_inv := /- inline sorry -/λ x, rfl/- inline sorry -/,
right_inv := /- inline sorry -/λ x, rfl/- inline sorry -/,
continuous_to_fun := begin
-- if you think that `continuous_id` should work but `exact continuous_id` fails, you
-- can try `convert continuous_id`: it might show you what doesn't match and let you
-- fix it afterwards.
-- sorry
convert continuous_id,
exact (tangent_bundle_model_space_topology_eq_prod _ _).symm
-- sorry
end,
continuous_inv_fun :=
begin
-- sorry
convert continuous_id,
exact (tangent_bundle_model_space_topology_eq_prod _ _)
-- sorry
end }
/- Even though the tangent bundle to `myℝ` is trivial abstractly, with this construction the
tangent bundle is *not* the product space with the product topology, as we have used various charts
so the gluing is not trivial. The following exercise unfolds the definition to see what is going on.
It is not a reasonable exercise, in the sense that one should never ever do this when working
with a manifold! -/
lemma crazy_formula_after_identifications (x : ℝ) (v : ℝ) :
let p : tangent_bundle I myℝ := ((3 : ℝ), 0) in
chart_at (model_prod ℝ ℝ) p (x, v) = if x ∈ Ioo (-1 : ℝ) 1 then (x, -v) else (x, v) :=
begin
-- this exercise is not easy (and shouldn't be: you are not supposed to use the library like this!)
-- if you really want to do this, you should unfold as much as you can using simp and dsimp, until you
-- are left with a statement speaking of derivatives of real functions, without any manifold code left.
-- sorry
have : ¬ ((3 : ℝ) < 1), by norm_num,
simp only [chart_at, this, mem_Ioo, if_false, and_false],
dsimp [tangent_bundle_core, basic_smooth_bundle_core.chart,
topological_fiber_bundle_core.local_triv, topological_fiber_bundle_core.local_triv',
topological_fiber_bundle_core.index_at,
basic_smooth_bundle_core.to_topological_fiber_bundle_core],
split_ifs,
{ simp only [chart_at, h, my_first_local_homeo, if_true, fderiv_within_univ, prod.mk.inj_iff, mem_Ioo,
fderiv_neg differentiable_at_id', fderiv_id', id.def, continuous_linear_map.coe_id',
continuous_linear_map.neg_apply] with mfld_simps },
{ simp only [chart_at, h, fderiv_within_univ, mem_Ioo, if_false, @local_homeomorph.refl_symm ℝ,
fderiv_id, continuous_linear_map.coe_id'] with mfld_simps }
-- sorry
end
end you_should_probably_skip_this
/-!
### The language of manifolds
In this paragraph, we will try to write down interesting statements of theorems, without proving them. The
goal here is that Lean should not complain on the statement, but the proof should be sorried.
-/
/- Here is a first example, already filled up, to show you how diffeomorphisms are currently named
(we will probably introduce an abbreviation, but this hasn't been done yet): -/
/-- Two zero-dimensional connected manifolds are diffeomorphic. -/
theorem diffeomorph_of_zero_dim_connected
(M M' : Type*) [topological_space M] [topological_space M']
[charted_space (euclidean_space (fin 0)) M] [charted_space (euclidean_space (fin 0)) M']
[connected_space M] [connected_space M'] :
nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 0)) M M') :=
sorry
/- Do you think that this statement is correct? (note that we have not assumed that our manifolds
are smooth, nor that they are separated, but this is maybe automatic in zero dimension).
Now, write down a version of this theorem in dimension 1, replacing the first sorry with meaningful content
(and adding what is needed before the colon): -/
/-- Two one-dimensional smooth compact connected manifolds are diffeomorphic. -/
theorem diffeomorph_of_one_dim_compact_connected
-- omit
(M M' : Type*) [topological_space M] [topological_space M']
[charted_space (euclidean_space (fin 1)) M] [charted_space (euclidean_space (fin 1)) M']
[connected_space M] [connected_space M'] [compact_space M] [compact_space M']
[t2_space M] [t2_space M']
[smooth_manifold_with_corners (𝓡 1) M] [smooth_manifold_with_corners (𝓡 1) M']
-- omit
:
-- sorry
nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 1)) M M')
-- sorry
:= sorry
/- You will definitely need to require smoothness and separation in this case, as it is wrong otherwise.
Note that Lean won't complain if you don't put these assumptions, as the theorem would still make
sense, but it would just turn out to be wrong.
The previous statement is not really satisfactory: we would instead like to express that any such
manifold is diffeomorphic to the circle. The trouble is that we don't have the circle as a smooth
manifold yet. Let's cheat and introduce it nevertheless.
-/
@[derive topological_space]
definition sphere (n : ℕ) : Type := metric.sphere (0 : euclidean_space (fin (n+1))) 1
instance (n : ℕ) : has_coe (sphere n) (euclidean_space (fin (n+1))) := ⟨subtype.val⟩
/- Don't try to fill the following instances: the first two should follow from general theory, and
the third one is too much work for an exercise session (but you can work on it if you don't like
manifolds and prefer topology -- then please PR it to mathlib!). -/
instance (n : ℕ) : charted_space (euclidean_space (fin n)) (sphere n) := sorry
instance (n : ℕ) : smooth_manifold_with_corners (𝓡 n) (sphere n) := sorry
instance connected_sphere (n : ℕ) : connected_space (sphere (n+1)) := sorry
/- The next two instances are easier to prove, you can prove them or leave them sorried
as you like. For the second one, you may need to use facts of the library such as -/
#check compact_iff_compact_space
#check metric.compact_iff_closed_bounded
instance (n : ℕ) : t2_space (sphere n) :=
begin
-- sorry
dunfold sphere,
apply_instance
-- sorry
end
instance (n : ℕ) : compact_space (sphere n) :=
begin
-- sorry
dunfold sphere,
apply compact_iff_compact_space.1,
rw metric.compact_iff_closed_bounded,
split,
{ exact metric.is_closed_sphere },
{ rw metric.bounded_iff_subset_ball (0 : euclidean_space (fin (n+1))),
exact ⟨1, metric.sphere_subset_closed_ball⟩ }
-- sorry
end
/- Now, you can prove that any one-dimensional compact connected manifold is diffeomorphic to
the circle -/
theorem diffeomorph_circle_of_one_dim_compact_connected
(M : Type*) [topological_space M] [charted_space (euclidean_space (fin 1)) M]
[connected_space M] [compact_space M] [t2_space M] [smooth_manifold_with_corners (𝓡 1) M] :
nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 1)) M (sphere 1)) :=
-- sorry
diffeomorph_of_one_dim_compact_connected M (sphere 1)
-- sorry
/- Can you express the sphere eversion theorem, i.e., the fact that there is a smooth isotopy
of immersions between the canonical embedding of the sphere `S^2` and `ℝ^3`, and the antipodal
embedding?
Note that we haven't defined immersions in mathlib, but you can jut require that the fiber
derivative is injective everywhere, which is easy to express if you know that the derivative
of a function `f` from a manifold of dimension `2` to a manifold of dimension `3` at a point `x` is
`mfderiv (𝓡 2) (𝓡 3) f x`.
Don't forget to require the global smoothness of the map! You may need to know that the interval
`[0,1]`, called `Icc (0 : ℝ) 1` in Lean, already has a manifold (with boundary!) structure,
where the corresponding model with corners is called `𝓡∂ 1`.
-/
/-- The sphere eversion theorem. You should fill the first sorry, the second one is out of reach
(now). -/
theorem sphere_eversion :
-- sorry
∃ f : Icc (0 : ℝ) 1 × sphere 2 → euclidean_space (fin 3),
times_cont_mdiff ((𝓡∂ 1).prod (𝓡 2)) (𝓡 3) ∞ f
∧ ∀ (t : (Icc (0 : ℝ) 1)), ∀ (p : sphere 2),
function.injective (mfderiv (𝓡 2) (𝓡 3) (f ∘ λ y, (t, y)) p)
∧ ∀ (p : sphere 2), f (0, p) = p
∧ ∀ (p : sphere 2), f (1, p) = - p
-- sorry
:=
sorry
/- What about trying to say that there are uncountably many different smooth structures on `ℝ⁴`?
(see https://en.wikipedia.org/wiki/Exotic_R4). The library is not really designed with this in mind,
as in general we only work with one differentiable structure on a space, but it is perfectly
capable of expressing this fact if one uses the `@` version of some definitions. -/
theorem exotic_ℝ4 :
-- sorry
let E := (euclidean_space (fin 4)) in
∃ f : ℝ → charted_space E E,
∀ i, @has_groupoid E _ E _ (f i) (times_cont_diff_groupoid ∞ (𝓡 4))
∧ ∀ i j, nonempty (@structomorph _ _ (times_cont_diff_groupoid ∞ (𝓡 4)) E E _ _ (f i) (f j)) →
i = j
-- sorry
:=
sorry
/-!
### Smooth functions on `[0, 1]`
In this paragraph, you will prove several (math-trivial but Lean-nontrivial) statements on the smooth
structure of `[0,1]`. These facts should be Lean-trivial, but they are not (yet) since there is essentially
nothing in this direction for now in the library.
The goal is as much to be able to write the statements as to prove them. Most of the necessary vocabulary
has been introduced above, so don't hesitate to browse the file if you are stuck. Additionally, you will
need the notion of a smooth function on a subset: it is `times_cont_diff_on` for functions between vector
spaces and `times_cont_mdiff_on` for functions between manifolds.
Lemma times_cont_mdiff_g : the inclusion `g` of `[0, 1]` in `ℝ` is smooth.
Lemma msmooth_of_smooth : Consider a function `f : ℝ → [0, 1]`, which is smooth in the usual sense as a function
from `ℝ` to `ℝ` on a set `s`. Then it is manifold-smooth on `s`.
Definition : construct a function `f` from `ℝ` to `[0,1]` which is the identity on `[0, 1]`.
Theorem : the tangent bundle to `[0, 1]` is homeomorphic to `[0, 1] × ℝ`
Hint for Theorem 4: don't try to unfold the definition of the tangent bundle, it will only get you
into trouble. Instead, use the derivatives of the maps `f` and `g`, and rely on functoriality
to check that they are inverse to each other. (This advice is slightly misleading as these derivatives
do not go between the right spaces, so you will need to massage them a little bit).
A global advice: don't hesitate to use and abuse `simp`, it is the main workhorse in this
area of mathlib.
-/
/- After doing the exercise myself, I realized it was (way!) too hard. So I will give at least the statements
of the lemmas, to guide you a little bit more. To let you try the original version if you want,
I have left a big blank space to avoid spoilers. -/
def g : Icc (0 : ℝ) 1 → ℝ := subtype.val
-- smoothness results for `euclidean_space` are expressed for general `L^p` spaces
-- (as `euclidean_space` has the `L^2` norm), in:
#check pi_Lp.times_cont_diff_coord
#check pi_Lp.times_cont_diff_on_iff_coord
lemma times_cont_mdiff_g : times_cont_mdiff (𝓡∂ 1) I ∞ g :=
begin
-- sorry
rw times_cont_mdiff_iff,
refine ⟨continuous_subtype_val, λ x y, _⟩,
by_cases h : (x : ℝ) < 1,
{ simp only [g, chart_at, h, Icc_left_chart, function.comp, model_with_corners_euclidean_half_space,
add_zero, dif_pos, if_true, max_lt_iff, preimage_set_of_eq, sub_zero, subtype.range_coe_subtype,
subtype.coe_mk, subtype.val_eq_coe] with mfld_simps,
refine (pi_Lp.times_cont_diff_coord 0).times_cont_diff_on.congr (λ x hx, _),
simp only [mem_inter_eq, mem_set_of_eq] at hx,
simp only [hx, le_of_lt hx.right.left, min_eq_left, max_eq_left] },
{ simp only [chart_at, h, Icc_right_chart, function.comp, model_with_corners_euclidean_half_space, dif_pos,
max_lt_iff, preimage_set_of_eq, sub_zero, subtype.range_coe_subtype, if_false, subtype.coe_mk,
subtype.val_eq_coe, g] with mfld_simps,
have : times_cont_diff ℝ ⊤ (λ (x : euclidean_space (fin 1)), 1 - x 0) :=
times_cont_diff_const.sub (pi_Lp.times_cont_diff_coord 0),
apply this.times_cont_diff_on.congr (λ x hx, _),
simp only [mem_inter_eq, mem_set_of_eq] at hx,
have : 0 ≤ 1 - x 0, by linarith,
simp only [hx, this, max_eq_left] }
-- sorry
end
lemma msmooth_of_smooth {f : ℝ → Icc (0 : ℝ) 1} {s : set ℝ} (h : times_cont_diff_on ℝ ∞ (λ x, (f x : ℝ)) s) :
times_cont_mdiff_on I (𝓡∂ 1) ∞ f s :=
begin
-- sorry
rw times_cont_mdiff_on_iff,
split,
{ have : embedding (subtype.val : Icc (0 : ℝ) 1 → ℝ) := embedding_subtype_coe,
exact (embedding.continuous_on_iff this).2 h.continuous_on },
simp only with mfld_simps,
assume y,
by_cases hy : (y : ℝ) < 1,
{ simp [chart_at, model_with_corners_euclidean_half_space, (∘), hy, Icc_left_chart,
pi_Lp.times_cont_diff_on_iff_coord],
apply h.mono (inter_subset_left _ _) },
{ simp [chart_at, model_with_corners_euclidean_half_space, (∘), hy, Icc_right_chart,
pi_Lp.times_cont_diff_on_iff_coord],
assume i,
apply (times_cont_diff_on_const.sub h).mono (inter_subset_left _ _) }
-- sorry
end
/- A function from `ℝ` to `[0,1]` which is the identity on `[0,1]`. -/
def f : ℝ → Icc (0 : ℝ) 1 :=
λ x, ⟨max (min x 1) 0, by simp [le_refl, zero_le_one]⟩
lemma times_cont_mdiff_on_f : times_cont_mdiff_on I (𝓡∂ 1) ∞ f (Icc 0 1) :=
begin
-- sorry
apply msmooth_of_smooth,
apply times_cont_diff_id.times_cont_diff_on.congr,
assume x hx,
simp at hx,
simp [f, hx],
-- sorry
end
lemma fog : f ∘ g = id :=
begin
-- sorry
ext x,
rcases x with ⟨x', h'⟩,
simp at h',
simp [f, g, h'],
-- sorry
end
lemma gof : ∀ x ∈ Icc (0 : ℝ) 1, g (f x) = x :=
begin
-- sorry
assume x hx,
simp at hx,
simp [g, f],
simp [hx],
-- sorry
end
def G : tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) → (Icc (0 : ℝ) 1) × ℝ :=
λ p, (p.1, (tangent_map (𝓡∂ 1) I g p).2)
lemma continuous_G : continuous G :=
begin
-- sorry
apply continuous.prod_mk (tangent_bundle_proj_continuous _ _),
refine continuous_snd.comp _,
have Z := times_cont_mdiff_g.continuous_tangent_map le_top,
convert Z,
exact (tangent_bundle_model_space_topology_eq_prod ℝ I).symm
-- sorry
end
/- in the definition of `F`, we use the map `tangent_bundle_vector_space_triv`
(which is just the identity pointwise) to make sure that Lean is not lost
between the different topologies. -/
def F : (Icc (0 : ℝ) 1) × ℝ → tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) :=
λ p, tangent_map_within I (𝓡∂ 1) f (Icc 0 1)
((tangent_bundle_vector_space_triv ℝ).symm (p.1, p.2))
lemma continuous_F : continuous F :=
begin
-- sorry
rw continuous_iff_continuous_on_univ,
apply (times_cont_mdiff_on_f.continuous_on_tangent_map_within le_top _).comp,
{ apply ((tangent_bundle_vector_space_triv ℝ).symm.continuous.comp _).continuous_on,
apply (continuous_subtype_coe.comp continuous_fst).prod_mk continuous_snd },
{ rintros ⟨⟨x, hx⟩, v⟩ _,
simp [tangent_bundle_vector_space_triv],
exact hx },
{ rw unique_mdiff_on_iff_unique_diff_on,
exact unique_diff_on_Icc_zero_one }
-- sorry
end
lemma FoG : F ∘ G = id :=
begin
-- sorry
ext1 p,
rcases p with ⟨x, v⟩,
simp [F, G, tangent_map_within, tangent_bundle_vector_space_triv, f],
dsimp,
split,
{ rcases x with ⟨x', h'⟩,
simp at h',
simp [h'] },
{ change (tangent_map_within I (𝓡∂ 1) f (Icc 0 1) (tangent_map (𝓡∂ 1) I g (x, v))).snd = v,
rw [← tangent_map_within_univ, ← tangent_map_within_comp_at, fog, tangent_map_within_univ, tangent_map_id],
{ refl },
{ apply times_cont_mdiff_on_f.mdifferentiable_on le_top,
simpa [g] using x.2 },
{ apply (times_cont_mdiff_g.times_cont_mdiff_at.mdifferentiable_at le_top).mdifferentiable_within_at },
{ assume z hz,
simpa [g] using z.2 },
{ apply unique_mdiff_on_univ _ (mem_univ _) } }
-- sorry
end
lemma GoF : G ∘ F = id :=
begin
-- sorry
ext1 p,
rcases p with ⟨x, v⟩,
simp [F, G, tangent_map_within, tangent_bundle_vector_space_triv, f],
dsimp,
split,
{ rcases x with ⟨x', h'⟩,
simp at h',
simp [h'] },
{ have A : unique_mdiff_within_at I (Icc 0 1) ((x : ℝ), v).fst,
{ rw unique_mdiff_within_at_iff_unique_diff_within_at,
apply unique_diff_on_Icc_zero_one _ x.2 },
change (tangent_map (𝓡∂ 1) I g (tangent_map_within I (𝓡∂ 1) f (Icc 0 1) (x, v))).snd = v,
rw [← tangent_map_within_univ, ← tangent_map_within_comp_at _ _ _ _ A],
{ have : tangent_map_within I I (g ∘ f) (Icc 0 1) (x, v) = tangent_map_within I I id (Icc 0 1) (x, v) :=
tangent_map_within_congr gof _ x.2 A,
rw [this, tangent_map_within_id A] },
{ apply times_cont_mdiff_g.times_cont_mdiff_on.mdifferentiable_on le_top _ (mem_univ _) },
{ apply times_cont_mdiff_on_f.mdifferentiable_on le_top _ x.2 },
{ simp only [preimage_univ, subset_univ], } }
-- sorry
end
def my_tangent_homeo : tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) ≃ₜ (Icc (0 : ℝ) 1) × ℝ :=
-- sorry
{ to_fun := G,
inv_fun := F,
continuous_to_fun := continuous_G,
continuous_inv_fun := continuous_F,
left_inv := λ p, show (F ∘ G) p = id p, by rw FoG,
right_inv := λ p, show (G ∘ F) p = id p, by rw GoF }
-- sorry
/-!
### Further things to do
1) can you prove `diffeomorph_of_zero_dim_connected` or `connected_sphere`?
2) Try to express and then prove the local inverse theorem in real manifolds: if a map between
real manifolds (without boundary, modelled on a complete vector space) is smooth, then it is
a local homeomorphism around each point. We already have versions of this statement in mathlib
for functions between vector spaces, but this is very much a work in progress.
3) What about trying to prove `diffeomorph_of_one_dim_compact_connected`? (I am not sure mathlib
is ready for this, as the proofs I am thinking of are currently a little bit too high-powered.
If you manage to do it, you should absolutely PR it!)
4) Why not contribute to the proof of `sphere_eversion`? You can have a look at
https://leanprover-community.github.io/sphere-eversion/ to learn more about this project
by Patrick Massot.
-/
|
dc0f60c61f8ec4917d73ee0b9e876b8cb573e2e5 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /stage0/src/Lean/Data/Format.lean | cc7c5cc66a8ccc3f11597f2831270fdebab81a2f | [
"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 | 1,695 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Lean.Data.Options
universe u v
namespace Std
namespace Format
open Lean
def getWidth (o : Options) : Nat := o.get `format.width defWidth
def getIndent (o : Options) : Nat := o.get `format.indent defIndent
def getUnicode (o : Options) : Bool := o.get `format.unicode defUnicode
register_builtin_option format.width : Nat := {
defValue := defWidth
descr := "indentation"
}
register_builtin_option format.unicode : Bool := {
defValue := defUnicode
descr := "unicode characters"
}
register_builtin_option format.indent : Nat := {
defValue := defIndent
descr := "indentation"
}
def pretty' (f : Format) (o : Options := {}) : String :=
pretty f (format.width.get o)
end Format
end Std
namespace Lean
open Std
export Std
(Format ToFormat fmt Format.nest Format.nil Format.joinSep Format.line
Format.sbracket Format.bracket Format.group Format.pretty Format.fill Format.paren Format.join)
export Std.ToFormat (format)
instance : ToFormat Name where
format n := n.toString
instance : ToFormat DataValue where
format
| DataValue.ofString v => format (repr v)
| DataValue.ofBool v => format v
| DataValue.ofName v => "`" ++ format v
| DataValue.ofNat v => format v
| DataValue.ofInt v => format v
instance : ToFormat (Name × DataValue) where
format
| (n, v) => format n ++ " := " ++ format v
open Std.Format
def formatKVMap (m : KVMap) : Format :=
sbracket (Format.joinSep m.entries ", ")
instance : ToFormat KVMap := ⟨formatKVMap⟩
end Lean
|
ab11474f8f161ba2b86256164503857bca19c98a | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/group_theory/group_action/defs.lean | 812ffdacb5851981c6fcb656e1438a1c21a3288b | [
"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 | 13,359 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Yury Kudryashov
-/
import algebra.group.defs
import algebra.group.hom
import logic.embedding
/-!
# Definitions of group actions
This file defines a hierarchy of group action type-classes:
* `has_scalar M α` and its additive version `has_vadd G P` are notation typeclasses for
`•` and `+ᵥ`, respectively;
* `mul_action M α` and its additive version `add_action G P` are typeclasses used for
actions of multiplicative and additive monoids and groups;
* `distrib_mul_action M A` is a typeclass for an action of a multiplicative monoid on
an additive monoid such that `a • (b + c) = a • b + a • c` and `a • 0 = 0`.
The hierarchy is extended further by `module`, defined elsewhere.
Also provided are type-classes regarding the interaction of different group actions,
* `smul_comm_class M N α` and its additive version `vadd_comm_class M N α`;
* `is_scalar_tower M N α` (no additive version).
## Notation
- `a • b` is used as notation for `has_scalar.smul a b`.
- `a +ᵥ b` is used as notation for `has_vadd.vadd a b`.
## Implementation details
This file should avoid depending on other parts of `group_theory`, to avoid import cycles.
More sophisticated lemmas belong in `group_theory.group_action`.
## Tags
group action
-/
variables {M N G A B α β γ : Type*}
open function
/-- Type class for the `+ᵥ` notation. -/
class has_vadd (G : Type*) (P : Type*) := (vadd : G → P → P)
/-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/
@[to_additive has_vadd]
class has_scalar (M : Type*) (α : Type*) := (smul : M → α → α)
infix ` +ᵥ `:65 := has_vadd.vadd
infixr ` • `:73 := has_scalar.smul
/-- See also `monoid.to_mul_action` and `mul_zero_class.to_smul_with_zero`. -/
@[priority 910, to_additive] -- see Note [lower instance priority]
instance has_mul.to_has_scalar (α : Type*) [has_mul α] : has_scalar α α := ⟨(*)⟩
@[simp, to_additive] lemma smul_eq_mul (α : Type*) [has_mul α] {a a' : α} : a • a' = a * a' := rfl
/-- Type class for additive monoid actions. -/
@[protect_proj] class add_action (G : Type*) (P : Type*) [add_monoid G] extends has_vadd G P :=
(zero_vadd : ∀ p : P, (0 : G) +ᵥ p = p)
(add_vadd : ∀ (g₁ g₂ : G) (p : P), (g₁ + g₂) +ᵥ p = g₁ +ᵥ (g₂ +ᵥ p))
/-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/
@[protect_proj, to_additive]
class mul_action (α : Type*) (β : Type*) [monoid α] extends has_scalar α β :=
(one_smul : ∀ b : β, (1 : α) • b = b)
(mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b)
/-- A typeclass mixin saying that two additive actions on the same space commute. -/
class vadd_comm_class (M N α : Type*) [has_vadd M α] [has_vadd N α] : Prop :=
(vadd_comm : ∀ (m : M) (n : N) (a : α), m +ᵥ (n +ᵥ a) = n +ᵥ (m +ᵥ a))
/-- A typeclass mixin saying that two multiplicative actions on the same space commute. -/
@[to_additive] class smul_comm_class (M N α : Type*) [has_scalar M α] [has_scalar N α] : Prop :=
(smul_comm : ∀ (m : M) (n : N) (a : α), m • n • a = n • m • a)
export mul_action (mul_smul) add_action (add_vadd) smul_comm_class (smul_comm)
vadd_comm_class (vadd_comm)
/--
Frequently, we find ourselves wanting to express a bilinear map `M →ₗ[R] N →ₗ[R] P` or an
equivalence between maps `(M →ₗ[R] N) ≃ₗ[R] (M' →ₗ[R] N')` where the maps have an associated ring
`R`. Unfortunately, using definitions like these requires that `R` satisfy `comm_semiring R`, and
not just `semiring R`. Using `M →ₗ[R] N →+ P` and `(M →ₗ[R] N) ≃+ (M' →ₗ[R] N')` avoids this
problem, but throws away structure that is useful for when we _do_ have a commutative (semi)ring.
To avoid making this compromise, we instead state these definitions as `M →ₗ[R] N →ₗ[S] P` or
`(M →ₗ[R] N) ≃ₗ[S] (M' →ₗ[R] N')` and require `smul_comm_class S R` on the appropriate modules. When
the caller has `comm_semiring R`, they can set `S = R` and `smul_comm_class_self` will populate the
instance. If the caller only has `semiring R` they can still set either `R = ℕ` or `S = ℕ`, and
`add_comm_monoid.nat_smul_comm_class` or `add_comm_monoid.nat_smul_comm_class'` will populate
the typeclass, which is still sufficient to recover a `≃+` or `→+` structure.
An example of where this is used is `linear_map.prod_equiv`.
-/
library_note "bundled maps over different rings"
/-- Commutativity of actions is a symmetric relation. This lemma can't be an instance because this
would cause a loop in the instance search graph. -/
@[to_additive] lemma smul_comm_class.symm (M N α : Type*) [has_scalar M α] [has_scalar N α]
[smul_comm_class M N α] : smul_comm_class N M α :=
⟨λ a' a b, (smul_comm a a' b).symm⟩
/-- Commutativity of additive actions is a symmetric relation. This lemma can't be an instance
because this would cause a loop in the instance search graph. -/
add_decl_doc vadd_comm_class.symm
@[to_additive] instance smul_comm_class_self (M α : Type*) [comm_monoid M] [mul_action M α] :
smul_comm_class M M α :=
⟨λ a a' b, by rw [← mul_smul, mul_comm, mul_smul]⟩
/-- An instance of `is_scalar_tower M N α` states that the multiplicative
action of `M` on `α` is determined by the multiplicative actions of `M` on `N`
and `N` on `α`. -/
class is_scalar_tower (M N α : Type*) [has_scalar M N] [has_scalar N α] [has_scalar M α] : Prop :=
(smul_assoc : ∀ (x : M) (y : N) (z : α), (x • y) • z = x • (y • z))
@[simp] lemma smul_assoc {M N} [has_scalar M N] [has_scalar N α] [has_scalar M α]
[is_scalar_tower M N α] (x : M) (y : N) (z : α) :
(x • y) • z = x • y • z :=
is_scalar_tower.smul_assoc x y z
section
variables [monoid M] [mul_action M α]
@[to_additive] lemma smul_smul (a₁ a₂ : M) (b : α) : a₁ • a₂ • b = (a₁ * a₂) • b :=
(mul_smul _ _ _).symm
variable (M)
@[simp, to_additive] theorem one_smul (b : α) : (1 : M) • b = b := mul_action.one_smul _
variables {M}
/-- Pullback a multiplicative action along an injective map respecting `•`.
See note [reducible non-instances]. -/
@[reducible, to_additive "Pullback an additive action along an injective map respecting `+ᵥ`."]
protected def function.injective.mul_action [has_scalar M β] (f : β → α)
(hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) :
mul_action M β :=
{ smul := (•),
one_smul := λ x, hf $ (smul _ _).trans $ one_smul _ (f x),
mul_smul := λ c₁ c₂ x, hf $ by simp only [smul, mul_smul] }
/-- Pushforward a multiplicative action along a surjective map respecting `•`.
See note [reducible non-instances]. -/
@[reducible, to_additive "Pushforward an additive action along a surjective map respecting `+ᵥ`."]
protected def function.surjective.mul_action [has_scalar M β] (f : α → β) (hf : surjective f)
(smul : ∀ (c : M) x, f (c • x) = c • f x) :
mul_action M β :=
{ smul := (•),
one_smul := λ y, by { rcases hf y with ⟨x, rfl⟩, rw [← smul, one_smul] },
mul_smul := λ c₁ c₂ y, by { rcases hf y with ⟨x, rfl⟩, simp only [← smul, mul_smul] } }
section ite
variables (p : Prop) [decidable p]
@[to_additive] lemma ite_smul (a₁ a₂ : M) (b : α) : (ite p a₁ a₂) • b = ite p (a₁ • b) (a₂ • b) :=
by split_ifs; refl
@[to_additive] lemma smul_ite (a : M) (b₁ b₂ : α) : a • (ite p b₁ b₂) = ite p (a • b₁) (a • b₂) :=
by split_ifs; refl
end ite
section
variables (M)
/-- The regular action of a monoid on itself by left multiplication.
This is promoted to a module by `semiring.to_module`. -/
@[priority 910, to_additive] -- see Note [lower instance priority]
instance monoid.to_mul_action : mul_action M M :=
{ smul := (*),
one_smul := one_mul,
mul_smul := mul_assoc }
/-- The regular action of a monoid on itself by left addition.
This is promoted to an `add_torsor` by `add_group_is_add_torsor`. -/
add_decl_doc add_monoid.to_add_action
instance is_scalar_tower.left : is_scalar_tower M M α :=
⟨λ x y z, mul_smul x y z⟩
variables {M}
/-- Note that the `smul_comm_class M α α` typeclass argument is usually satisfied by `algebra M α`.
-/
@[to_additive]
lemma mul_smul_comm [has_mul α] (s : M) (x y : α) [smul_comm_class M α α] :
x * (s • y) = s • (x * y) :=
(smul_comm s x y).symm
/-- Note that the `is_scalar_tower M α α` typeclass argument is usually satisfied by `algebra M α`.
-/
lemma smul_mul_assoc [has_mul α] (r : M) (x y : α) [is_scalar_tower M α α] :
(r • x) * y = r • (x * y) :=
smul_assoc r x y
/-- Note that the `is_scalar_tower M α α` and `smul_comm_class M α α` typeclass arguments are
usually satisfied by `algebra M α`. -/
lemma smul_mul_smul [has_mul α] (r s : M) (x y : α)
[is_scalar_tower M α α] [smul_comm_class M α α] :
(r • x) * (s • y) = (r * s) • (x * y) :=
by rw [smul_mul_assoc, mul_smul_comm, ← smul_assoc, smul_eq_mul]
end
namespace mul_action
variables (M α)
/-- Embedding of `α` into functions `M → α` induced by a multiplicative action of `M` on `α`. -/
@[to_additive] def to_fun : α ↪ (M → α) :=
⟨λ y x, x • y, λ y₁ y₂ H, one_smul M y₁ ▸ one_smul M y₂ ▸ by convert congr_fun H 1⟩
/-- Embedding of `α` into functions `M → α` induced by an additive action of `M` on `α`. -/
add_decl_doc add_action.to_fun
variables {M α}
@[simp, to_additive] lemma to_fun_apply (x : M) (y : α) : mul_action.to_fun M α y x = x • y :=
rfl
variable (α)
/-- A multiplicative action of `M` on `α` and a monoid homomorphism `N → M` induce
a multiplicative action of `N` on `α`. -/
@[to_additive] def comp_hom [monoid N] (g : N →* M) :
mul_action N α :=
{ smul := λ x b, (g x) • b,
one_smul := by simp [g.map_one, mul_action.one_smul],
mul_smul := by simp [g.map_mul, mul_action.mul_smul] }
/-- An additive action of `M` on `α` and an additive monoid homomorphism `N → M` induce
an additive action of `N` on `α`. -/
add_decl_doc add_action.comp_hom
end mul_action
end
section compatible_scalar
@[simp] lemma smul_one_smul {M} (N) [monoid N] [has_scalar M N] [mul_action N α] [has_scalar M α]
[is_scalar_tower M N α] (x : M) (y : α) :
(x • (1 : N)) • y = x • y :=
by rw [smul_assoc, one_smul]
end compatible_scalar
/-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/
class distrib_mul_action (M : Type*) (A : Type*) [monoid M] [add_monoid A]
extends mul_action M A :=
(smul_add : ∀(r : M) (x y : A), r • (x + y) = r • x + r • y)
(smul_zero : ∀(r : M), r • (0 : A) = 0)
section
variables [monoid M] [add_monoid A] [distrib_mul_action M A]
theorem smul_add (a : M) (b₁ b₂ : A) : a • (b₁ + b₂) = a • b₁ + a • b₂ :=
distrib_mul_action.smul_add _ _ _
@[simp] theorem smul_zero (a : M) : a • (0 : A) = 0 :=
distrib_mul_action.smul_zero _
/-- Pullback a distributive multiplicative action along an injective additive monoid
homomorphism.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.distrib_mul_action [add_monoid B] [has_scalar M B] (f : B →+ A)
(hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) :
distrib_mul_action M B :=
{ smul := (•),
smul_add := λ c x y, hf $ by simp only [smul, f.map_add, smul_add],
smul_zero := λ c, hf $ by simp only [smul, f.map_zero, smul_zero],
.. hf.mul_action f smul }
/-- Pushforward a distributive multiplicative action along a surjective additive monoid
homomorphism.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.distrib_mul_action [add_monoid B] [has_scalar M B] (f : A →+ B)
(hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) :
distrib_mul_action M B :=
{ smul := (•),
smul_add := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩,
simp only [smul_add, ← smul, ← f.map_add] },
smul_zero := λ c, by simp only [← f.map_zero, ← smul, smul_zero],
.. hf.mul_action f smul }
variable (A)
/-- Compose a `distrib_mul_action` with a `monoid_hom`, with action `f r' • m` -/
def distrib_mul_action.comp_hom [monoid N] (f : N →* M) :
distrib_mul_action N A :=
{ smul := (•) ∘ f,
smul_zero := λ x, smul_zero (f x),
smul_add := λ x, smul_add (f x),
.. mul_action.comp_hom A f }
/-- Scalar multiplication by `r` as an `add_monoid_hom`. -/
def const_smul_hom (r : M) : A →+ A :=
{ to_fun := (•) r,
map_zero' := smul_zero r,
map_add' := smul_add r }
variable {A}
@[simp] lemma const_smul_hom_apply (r : M) (x : A) :
const_smul_hom A r x = r • x := rfl
@[simp] lemma const_smul_hom_one :
const_smul_hom A (1:M) = add_monoid_hom.id _ :=
by { ext, rw [const_smul_hom_apply, one_smul, add_monoid_hom.id_apply] }
end
section
variables [monoid M] [add_group A] [distrib_mul_action M A]
@[simp] theorem smul_neg (r : M) (x : A) : r • (-x) = -(r • x) :=
eq_neg_of_add_eq_zero $ by rw [← smul_add, neg_add_self, smul_zero]
theorem smul_sub (r : M) (x y : A) : r • (x - y) = r • x - r • y :=
by rw [sub_eq_add_neg, sub_eq_add_neg, smul_add, smul_neg]
end
|
b52615277713a86852b3e2da3cb3063522678c29 | 4e3bf8e2b29061457a887ac8889e88fa5aa0e34c | /lean/love10_denotational_semantics_exercise_solution.lean | ad7a8af0af731e535c24862bf015326c2eae4ba6 | [] | no_license | mukeshtiwari/logical_verification_2019 | 9f964c067a71f65eb8884743273fbeef99e6503d | 16f62717f55ed5b7b87e03ae0134791a9bef9b9a | refs/heads/master | 1,619,158,844,208 | 1,585,139,500,000 | 1,585,139,500,000 | 249,906,380 | 0 | 0 | null | 1,585,118,728,000 | 1,585,118,727,000 | null | UTF-8 | Lean | false | false | 5,675 | lean | /- LoVe Exercise 10: Denotational Semantics -/
import .love10_denotational_semantics_demo
namespace LoVe
/- Question 1: Monotonicity -/
/- Prove the following two lemmas from the lecture. -/
lemma monotone_comp {α β : Type} [partial_order α] (f g : α → set (β × β))
(hf : monotone f) (hg : monotone g) :
monotone (λa, f a ◯ g a) :=
begin
intros a₁ a₂ ha b hb,
cases hb with m hm,
cases hm,
use m,
apply and.intro,
{ exact hf _ _ ha hm_left },
{ exact hg _ _ ha hm_right }
end
lemma monotone_restrict {α β : Type} [partial_order α] (f : α → set (β × β))
(p : β → Prop) (hf : monotone f) :
monotone (λa, f a ⇃ p) :=
begin
intros a₁ a₂ ha b hb,
cases hb,
apply and.intro,
{ exact hb_left },
{ apply hf _ _ ha,
exact hb_right }
end
/- Question 2: Kleene's Theorem -/
/- We can compute the fixpoint by iteration by taking the union of all finite
iterations of `f`:
lfp f = ⋃n, f^^[n] ∅
where
f^^[n] = f ∘ ⋯ ∘ f ∘ id
iterates the function `f` `n` times. However, the above characterization of
`lfp` only holds for continuous functions, a concept we will introduce below. -/
def iterate {α : Type} (f : α → α) : ℕ → α → α
| 0 a := a
| (n + 1) a := f (iterate n a)
notation f`^^[`n`]` := iterate f n
/- 2.1. Fill in the missing proofs below. -/
def Union {α : Type} (s : ℕ → set α) : set α :=
{a | ∃n, a ∈ s n}
lemma Union_le {α : Type} {s : ℕ → set α} (a : set α) (h : ∀i, s i ≤ a) :
Union s ≤ a :=
begin
intros x hx,
cases hx with i hi,
exact h i hi
end
/- A continuous function `f` is a function that commutes with the union of any
monotone sequence `s`: -/
def continuous {α : Type} (f : set α → set α) : Prop :=
∀s : ℕ → set α, monotone s → f (Union s) = Union (λn, f (s n))
/- We need to prove that each continuous function is monotone. To achieve this,
we will need the following sequence: -/
def bi_seq {α : Type} (a₁ a₂ : set α) : ℕ → set α
| 0 := a₁
| (n + 1) := a₂
/- For example, `bi_seq 0 1` is the sequence 0, 1, 1, 1, etc. -/
lemma monotone_bi_seq {α : Type} (a₁ a₂ : set α) (h : a₁ ≤ a₂) :
monotone (bi_seq a₁ a₂)
| 0 0 _ := le_refl _
| 0 (n + 1) _ := h
| (n + 1) (m + 1) _ := le_refl _
lemma Union_bi_seq {α : Type} (a₁ a₂ : set α) (ha : a₁ ≤ a₂) :
Union (bi_seq a₁ a₂) = a₂ :=
begin
apply le_antisymm,
{ apply Union_le,
intros n a h,
cases n,
{ exact ha h },
{ exact h } },
{ intros a h,
use 1,
exact h }
end
lemma monotone_of_continuous {α : Type} (f : set α → set α)
(hf : continuous f) :
monotone f :=
begin
intros a₁ a₂ ha,
rw [← Union_bi_seq a₁ a₂ ha, hf _ (monotone_bi_seq a₁ a₂ ha)],
{ intros a ha,
rw Union,
use 0,
exact ha }
end
/- 2.2. Provide the following proof, using a similar case distinction as for
`monotone_bi_seq` above. -/
lemma monotone_iterate {α : Type} (f : set α → set α) (hf : monotone f) :
monotone (λn, f^^[n] ∅)
| 0 0 _ := le_refl _
| 0 (m + 1) _ :=
assume h,
false.elim
| (n + 1) (m + 1) h :=
hf _ _ (monotone_iterate n m (nat.le_of_succ_le_succ h))
/- 2.3. Prove the main theorem. A proof sketch is given below.
We break the proof into two proofs of inclusion.
Case 1. lfp f ≤ Union (λn, f^[n] ∅): The key is to use the lemma `lfp_le`
together with continuity of `f`.
Case 2. Union (λn, f^[n] ∅) ≤ lfp f: The lemma `Union_le` gives us a natural
number `i`, on which you can perform induction. You will also need the lemma
`lfp_eq` to unfold one iteration of `lfp f`. -/
lemma lfp_Kleene {α : Type} (f : set α → set α) (hf : continuous f) :
complete_lattice.lfp f = Union (λn, f^^[n] ∅) :=
begin
apply le_antisymm,
{ apply complete_lattice.lfp_le _ _ _,
rw [hf],
{ apply Union_le,
intros n a hn,
use n + 1,
exact hn },
{ exact monotone_iterate f (monotone_of_continuous f hf) } },
{ apply Union_le (complete_lattice.lfp f),
intro i,
induction i,
{ intros a,
exact false.elim },
{ rw [nat.succ_eq_add_one,
complete_lattice.lfp_eq f (monotone_of_continuous f hf)],
exact (monotone_of_continuous f hf) _ _ i_ih } }
end
/- Question 3 (**optional**): Regular Expressions -/
inductive regex (α : Type) : Type
| empty {} : regex
| nothing {} : regex
| atom (a : α) : regex
| concat : regex → regex → regex
| alt : regex → regex → regex
| star : regex → regex
/- 3.1 (**optional**). Define a translation of regular expressions to relations.
The idea is that an atom corresponds to a relation, concatenation corresponds to
composition of relations, and alternation is union. -/
def rel_of_regex {α : Type} : regex (set (α × α)) → set (α × α)
| regex.empty := Id α
| regex.nothing := ∅
| (regex.atom r) := r
| (regex.concat r₁ r₂) := rel_of_regex r₁ ◯ rel_of_regex r₂
| (regex.alt r₁ r₂) := rel_of_regex r₁ ∪ rel_of_regex r₂
| (regex.star r) := complete_lattice.lfp (λf, (rel_of_regex r ◯ f) ∪ Id α)
/- 3.2 (**optional**). Prove the following recursive equation about your
definition. -/
lemma rel_of_regex_star {α : Type} (r : regex (set (α × α))) :
rel_of_regex (regex.star r) =
rel_of_regex (regex.alt (regex.concat r (regex.star r)) regex.empty) :=
begin
apply complete_lattice.lfp_eq _ _,
apply monotone.union,
{ apply monotone_comp,
{ exact monotone.const _ },
{ exact monotone.id } },
{ exact monotone.const _ }
end
end LoVe
|
067b59940f3d7a2dfdfccb56f4a8401cc551be89 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /src/Lean/Server/FileSource.lean | 158103c541541d4b764ce94e5e0a874e8e1e21f3 | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,761 | lean | /-
Copyright (c) 2020 Marc Huisinga. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Marc Huisinga
-/
import Lean.Data.Lsp
namespace Lean
namespace Lsp
class FileSource (α : Type) where
fileSource : α → DocumentUri
export FileSource (fileSource)
instance Location.hasFileSource : FileSource Location :=
⟨fun l => l.uri⟩
instance TextDocumentIdentifier.hasFileSource : FileSource TextDocumentIdentifier :=
⟨fun i => i.uri⟩
instance VersionedTextDocumentIdentifier.hasFileSource : FileSource VersionedTextDocumentIdentifier :=
⟨fun i => i.uri⟩
instance TextDocumentEdit.hasFileSource : FileSource TextDocumentEdit :=
⟨fun e => fileSource e.textDocument⟩
instance TextDocumentItem.hasFileSource : FileSource TextDocumentItem :=
⟨fun i => i.uri⟩
instance TextDocumentPositionParams.hasFileSource : FileSource TextDocumentPositionParams :=
⟨fun p => fileSource p.textDocument⟩
instance DidOpenTextDocumentParams.hasFileSource : FileSource DidOpenTextDocumentParams :=
⟨fun p => fileSource p.textDocument⟩
instance DidChangeTextDocumentParams.hasFileSource : FileSource DidChangeTextDocumentParams :=
⟨fun p => fileSource p.textDocument⟩
instance DidCloseTextDocumentParams.hasFileSource : FileSource DidCloseTextDocumentParams :=
⟨fun p => fileSource p.textDocument⟩
instance HoverParams.hasFileSource : FileSource HoverParams :=
⟨fun h => fileSource h.toTextDocumentPositionParams⟩
instance WaitForDiagnosticsParam.hasFileSource : FileSource WaitForDiagnosticsParam :=
⟨fun p => p.uri⟩
instance DocumentSymbolParams.hasFileSource : FileSource DocumentSymbolParams :=
⟨fun p => fileSource p.textDocument⟩
end Lsp
end Lean
|
73fd8fc52a80ac0c4609adf71a0a14fdcd687e82 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Meta/Match/MatchEqs.lean | 3e2b76b972424c16e2e9fd91b49fc53a533bca17 | [
"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 | 32,877 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Match.Match
import Lean.Meta.Match.MatchEqsExt
import Lean.Meta.Tactic.Apply
import Lean.Meta.Tactic.Refl
import Lean.Meta.Tactic.Delta
import Lean.Meta.Tactic.SplitIf
import Lean.Meta.Tactic.Injection
import Lean.Meta.Tactic.Contradiction
namespace Lean.Meta
/--
Helper method for `proveCondEqThm`. Given a goal of the form `C.rec ... xMajor = rhs`,
apply `cases xMajor`. -/
partial def casesOnStuckLHS (mvarId : MVarId) : MetaM (Array MVarId) := do
let target ← mvarId.getType
if let some (_, lhs, _) ← matchEq? target then
if let some fvarId ← findFVar? lhs then
return (← mvarId.cases fvarId).map fun s => s.mvarId
throwError "'casesOnStuckLHS' failed"
where
findFVar? (e : Expr) : MetaM (Option FVarId) := do
match e.getAppFn with
| Expr.proj _ _ e => findFVar? e
| f =>
if !f.isConst then
return none
else
let declName := f.constName!
let args := e.getAppArgs
match (← getProjectionFnInfo? declName) with
| some projInfo =>
if projInfo.numParams < args.size then
findFVar? args[projInfo.numParams]!
else
return none
| none =>
matchConstRec f (fun _ => return none) fun recVal _ => do
if recVal.getMajorIdx >= args.size then
return none
let major := args[recVal.getMajorIdx]!
if major.isFVar then
return some major.fvarId!
else
return none
def casesOnStuckLHS? (mvarId : MVarId) : MetaM (Option (Array MVarId)) := do
try casesOnStuckLHS mvarId catch _ => return none
namespace Match
def unfoldNamedPattern (e : Expr) : MetaM Expr := do
let visit (e : Expr) : MetaM TransformStep := do
if let some e := isNamedPattern? e then
if let some eNew ← unfoldDefinition? e then
return TransformStep.visit eNew
return .continue
Meta.transform e (pre := visit)
/--
Similar to `forallTelescopeReducing`, but
1. Eliminates arguments for named parameters and the associated equation proofs.
2. Equality parameters associated with the `h : discr` notation are replaced with `rfl` proofs.
Recall that this kind of parameter always occurs after the parameters correspoting to pattern variables.
`numNonEqParams` is the size of the prefix.
The continuation `k` takes four arguments `ys args mask type`.
- `ys` are variables for the hypotheses that have not been eliminated.
- `eqs` are variables for equality hypotheses associated with discriminants annotated with `h : discr`.
- `args` are the arguments for the alternative `alt` that has type `altType`. `ys.size <= args.size`
- `mask[i]` is true if the hypotheses has not been eliminated. `mask.size == args.size`.
- `type` is the resulting type for `altType`.
We use the `mask` to build the splitter proof. See `mkSplitterProof`.
-/
partial def forallAltTelescope (altType : Expr) (numNonEqParams : Nat)
(k : (ys : Array Expr) → (eqs : Array Expr) → (args : Array Expr) → (mask : Array Bool) → (type : Expr) → MetaM α)
: MetaM α := do
go #[] #[] #[] #[] 0 altType
where
go (ys : Array Expr) (eqs : Array Expr) (args : Array Expr) (mask : Array Bool) (i : Nat) (type : Expr) : MetaM α := do
let type ← whnfForall type
match type with
| Expr.forallE n d b .. =>
if i < numNonEqParams then
let d ← unfoldNamedPattern d
withLocalDeclD n d fun y => do
let typeNew := b.instantiate1 y
if let some (_, lhs, rhs) ← matchEq? d then
if lhs.isFVar && ys.contains lhs && args.contains lhs && isNamedPatternProof typeNew y then
let some i := ys.getIdx? lhs | unreachable!
let ys := ys.eraseIdx i
let some j := args.getIdx? lhs | unreachable!
let mask := mask.set! j false
let args := args.map fun arg => if arg == lhs then rhs else arg
let args := args.push (← mkEqRefl rhs)
let typeNew := typeNew.replaceFVar lhs rhs
return (← go ys eqs args (mask.push false) (i+1) typeNew)
go (ys.push y) eqs (args.push y) (mask.push true) (i+1) typeNew
else
let arg ← if let some (_, _, rhs) ← matchEq? d then
mkEqRefl rhs
else if let some (_, _, _, rhs) ← matchHEq? d then
mkHEqRefl rhs
else
throwError "unexpected match alternative type{indentExpr altType}"
withLocalDeclD n d fun eq => do
let typeNew := b.instantiate1 eq
go ys (eqs.push eq) (args.push arg) (mask.push false) (i+1) typeNew
| _ =>
let type ← unfoldNamedPattern type
/- Recall that alternatives that do not have variables have a `Unit` parameter to ensure
they are not eagerly evaluated. -/
if ys.size == 1 then
if (← inferType ys[0]!).isConstOf ``Unit && !(← dependsOn type ys[0]!.fvarId!) then
return (← k #[] #[] #[mkConst ``Unit.unit] #[false] type)
k ys eqs args mask type
isNamedPatternProof (type : Expr) (h : Expr) : Bool :=
Option.isSome <| type.find? fun e =>
if let some e := isNamedPattern? e then
e.appArg! == h
else
false
namespace SimpH
/--
State for the equational theorem hypothesis simplifier.
Recall that each equation contains additional hypotheses to ensure the associated case does not taken by previous cases.
We have one hypothesis for each previous case.
Each hypothesis is of the form `forall xs, eqs → False`
We use tactics to minimize code duplication.
-/
structure State where
mvarId : MVarId -- Goal representing the hypothesis
xs : List FVarId -- Pattern variables for a previous case
eqs : List FVarId -- Equations to be processed
eqsNew : List FVarId := [] -- Simplied (already processed) equations
abbrev M := StateRefT State MetaM
/--
Apply the given substitution to `fvarIds`.
This is an auxiliary method for `substRHS`.
-/
private def applySubst (s : FVarSubst) (fvarIds : List FVarId) : List FVarId :=
fvarIds.filterMap fun fvarId => match s.apply (mkFVar fvarId) with
| Expr.fvar fvarId .. => some fvarId
| _ => none
/--
Given an equation of the form `lhs = rhs` where `rhs` is variable in `xs`,
replace it everywhere with `lhs`.
-/
private def substRHS (eq : FVarId) (rhs : FVarId) : M Unit := do
assert! (← get).xs.contains rhs
let (subst, mvarId) ← substCore (← get).mvarId eq (symm := true)
modify fun s => { s with
mvarId,
xs := applySubst subst (s.xs.erase rhs)
eqs := applySubst subst s.eqs
eqsNew := applySubst subst s.eqsNew
}
private def isDone : M Bool :=
return (← get).eqs.isEmpty
/-- Customized `contradiction` tactic for `simpH?` -/
private def contradiction (mvarId : MVarId) : MetaM Bool :=
mvarId.contradictionCore { genDiseq := false, emptyType := false }
/--
Auxiliary tactic that tries to replace as many variables as possible and then apply `contradiction`.
We use it to discard redundant hypotheses.
-/
partial def trySubstVarsAndContradiction (mvarId : MVarId) : MetaM Bool :=
commitWhen do
let mvarId ← substVars mvarId
match (← injections mvarId) with
| .solved => return true -- closed goal
| .subgoal mvarId' _ =>
if mvarId' == mvarId then
contradiction mvarId
else
trySubstVarsAndContradiction mvarId'
private def processNextEq : M Bool := do
let s ← get
s.mvarId.withContext do
-- If the goal is contradictory, the hypothesis is redundant.
if (← contradiction s.mvarId) then
return false
if let eq :: eqs := s.eqs then
modify fun s => { s with eqs }
let eqType ← inferType (mkFVar eq)
-- See `substRHS`. Recall that if `rhs` is a variable then if must be in `s.xs`
if let some (_, lhs, rhs) ← matchEq? eqType then
if (← isDefEq lhs rhs) then
return true
if rhs.isFVar && s.xs.contains rhs.fvarId! then
substRHS eq rhs.fvarId!
return true
if let some (α, lhs, β, rhs) ← matchHEq? eqType then
-- Try to convert `HEq` into `Eq`
if (← isDefEq α β) then
let (eqNew, mvarId) ← heqToEq s.mvarId eq (tryToClear := true)
modify fun s => { s with mvarId, eqs := eqNew :: s.eqs }
return true
-- If it is not possible, we try to show the hypothesis is redundant by substituting even variables that are not at `s.xs`, and then use contradiction.
else
match lhs.isConstructorApp? (← getEnv), rhs.isConstructorApp? (← getEnv) with
| some lhsCtor, some rhsCtor =>
if lhsCtor.name != rhsCtor.name then
return false -- If the constructors are different, we can discard the hypothesis even if it a heterogeneous equality
else if (← trySubstVarsAndContradiction s.mvarId) then
return false
| _, _ =>
if (← trySubstVarsAndContradiction s.mvarId) then
return false
try
-- Try to simplify equation using `injection` tactic.
match (← injection s.mvarId eq) with
| InjectionResult.solved => return false
| InjectionResult.subgoal mvarId eqNews .. =>
modify fun s => { s with mvarId, eqs := eqNews.toList ++ s.eqs }
catch _ =>
modify fun s => { s with eqsNew := eq :: s.eqsNew }
return true
partial def go : M Bool := do
if (← isDone) then
return true
else if (← processNextEq) then
go
else
return false
end SimpH
/--
Auxiliary method for simplifying equational theorem hypotheses.
Recall that each equation contains additional hypotheses to ensure the associated case was not taken by previous cases.
We have one hypothesis for each previous case.
-/
private partial def simpH? (h : Expr) (numEqs : Nat) : MetaM (Option Expr) := withDefault do
let numVars ← forallTelescope h fun ys _ => pure (ys.size - numEqs)
let mvarId := (← mkFreshExprSyntheticOpaqueMVar h).mvarId!
let (xs, mvarId) ← mvarId.introN numVars
let (eqs, mvarId) ← mvarId.introN numEqs
let (r, s) ← SimpH.go |>.run { mvarId, xs := xs.toList, eqs := eqs.toList }
if r then
s.mvarId.withContext do
let eqs := s.eqsNew.reverse.toArray.map mkFVar
let mut r ← mkForallFVars eqs (mkConst ``False)
/- We only include variables in `xs` if there is a dependency. -/
for x in s.xs.reverse do
if (← dependsOn r x) then
r ← mkForallFVars #[mkFVar x] r
trace[Meta.Match.matchEqs] "simplified hypothesis{indentExpr r}"
check r
return some r
else
return none
private def substSomeVar (mvarId : MVarId) : MetaM (Array MVarId) := mvarId.withContext do
for localDecl in (← getLCtx) do
if let some (_, lhs, rhs) ← matchEq? localDecl.type then
if lhs.isFVar then
if !(← dependsOn rhs lhs.fvarId!) then
match (← subst? mvarId lhs.fvarId!) with
| some mvarId => return #[mvarId]
| none => pure ()
throwError "substSomeVar failed"
/--
Helper method for proving a conditional equational theorem associated with an alternative of
the `match`-eliminator `matchDeclName`. `type` contains the type of the theorem. -/
partial def proveCondEqThm (matchDeclName : Name) (type : Expr) : MetaM Expr := withLCtx {} {} do
let type ← instantiateMVars type
forallTelescope type fun ys target => do
let mvar0 ← mkFreshExprSyntheticOpaqueMVar target
trace[Meta.Match.matchEqs] "proveCondEqThm {mvar0.mvarId!}"
let mvarId ← mvar0.mvarId!.deltaTarget (· == matchDeclName)
withDefault <| go mvarId 0
mkLambdaFVars ys (← instantiateMVars mvar0)
where
go (mvarId : MVarId) (depth : Nat) : MetaM Unit := withIncRecDepth do
trace[Meta.Match.matchEqs] "proveCondEqThm.go {mvarId}"
let mvarId' ← mvarId.modifyTargetEqLHS whnfCore
let mvarId := mvarId'
let subgoals ←
(do mvarId.refl; return #[])
<|>
(do mvarId.contradiction { genDiseq := true }; return #[])
<|>
(casesOnStuckLHS mvarId)
<|>
(do let mvarId' ← simpIfTarget mvarId (useDecide := true)
if mvarId' == mvarId then throwError "simpIf failed"
return #[mvarId'])
<|>
(do if let some (s₁, s₂) ← splitIfTarget? mvarId then
let mvarId₁ ← trySubst s₁.mvarId s₁.fvarId
return #[mvarId₁, s₂.mvarId]
else
throwError "spliIf failed")
<|>
(substSomeVar mvarId)
<|>
(throwError "failed to generate equality theorems for `match` expression `{matchDeclName}`\n{MessageData.ofGoal mvarId}")
subgoals.forM (go · (depth+1))
/-- Construct new local declarations `xs` with types `altTypes`, and then execute `f xs` -/
private partial def withSplitterAlts (altTypes : Array Expr) (f : Array Expr → MetaM α) : MetaM α := do
let rec go (i : Nat) (xs : Array Expr) : MetaM α := do
if h : i < altTypes.size then
let hName := (`h).appendIndexAfter (i+1)
withLocalDeclD hName (altTypes.get ⟨i, h⟩) fun x =>
go (i+1) (xs.push x)
else
f xs
go 0 #[]
inductive InjectionAnyResult where
| solved
| failed
| subgoal (mvarId : MVarId)
private def injectionAnyCandidate? (type : Expr) : MetaM (Option (Expr × Expr)) := do
if let some (_, lhs, rhs) ← matchEq? type then
return some (lhs, rhs)
else if let some (α, lhs, β, rhs) ← matchHEq? type then
if (← isDefEq α β) then
return some (lhs, rhs)
return none
private def injectionAny (mvarId : MVarId) : MetaM InjectionAnyResult :=
mvarId.withContext do
for localDecl in (← getLCtx) do
if let some (lhs, rhs) ← injectionAnyCandidate? localDecl.type then
unless (← isDefEq lhs rhs) do
let lhs ← whnf lhs
let rhs ← whnf rhs
unless lhs.isNatLit && rhs.isNatLit do
try
match (← injection mvarId localDecl.fvarId) with
| InjectionResult.solved => return InjectionAnyResult.solved
| InjectionResult.subgoal mvarId .. => return InjectionAnyResult.subgoal mvarId
catch ex =>
trace[Meta.Match.matchEqs] "injectionAnyFailed at {localDecl.userName}, error\n{ex.toMessageData}"
pure ()
return InjectionAnyResult.failed
private abbrev ConvertM := ReaderT (FVarIdMap (Expr × Nat × Array Bool)) $ StateRefT (Array MVarId) MetaM
/--
Construct a proof for the splitter generated by `mkEquationsfor`.
The proof uses the definition of the `match`-declaration as a template (argument `template`).
- `alts` are free variables corresponding to alternatives of the `match` auxiliary declaration being processed.
- `altNews` are the new free variables which contains aditional hypotheses that ensure they are only used
when the previous overlapping alternatives are not applicable. -/
private partial def mkSplitterProof (matchDeclName : Name) (template : Expr) (alts altsNew : Array Expr)
(altsNewNumParams : Array Nat)
(altArgMasks : Array (Array Bool)) : MetaM Expr := do
trace[Meta.Match.matchEqs] "proof template: {template}"
let map := mkMap
let (proof, mvarIds) ← convertTemplate template |>.run map |>.run #[]
trace[Meta.Match.matchEqs] "splitter proof: {proof}"
for mvarId in mvarIds do
proveSubgoal mvarId
instantiateMVars proof
where
mkMap : FVarIdMap (Expr × Nat × Array Bool) := Id.run do
let mut m := {}
for alt in alts, altNew in altsNew, numParams in altsNewNumParams, argMask in altArgMasks do
m := m.insert alt.fvarId! (altNew, numParams, argMask)
return m
trimFalseTrail (argMask : Array Bool) : Array Bool :=
if argMask.isEmpty then
argMask
else if !argMask.back then
trimFalseTrail argMask.pop
else
argMask
/--
Auxiliary function used at `convertTemplate` to decide whether to use `convertCastEqRec`.
See `convertCastEqRec`. -/
isCastEqRec (e : Expr) : ConvertM Bool := do
-- TODO: we do not handle `Eq.rec` since we never found an example that needed it.
-- If we find one we must extend `convertCastEqRec`.
unless e.isAppOf ``Eq.ndrec do return false
unless e.getAppNumArgs > 6 do return false
for arg in e.getAppArgs[6:] do
if arg.isFVar && (← read).contains arg.fvarId! then
return true
return true
/--
Auxiliary function used at `convertTemplate`. It is needed when the auxiliary `match` declaration had to refine the type of its
minor premises during dependent pattern match. For an example, consider
```
inductive Foo : Nat → Type _
| nil : Foo 0
| cons (t: Foo l): Foo l
def Foo.bar (t₁: Foo l₁): Foo l₂ → Bool
| cons s₁ => t₁.bar s₁
| _ => false
attribute [simp] Foo.bar
```
The auxiliary `Foo.bar.match_1` is of the form
```
def Foo.bar.match_1.{u_1} : {l₂ : Nat} →
(t₂ : Foo l₂) →
(motive : Foo l₂ → Sort u_1) →
(t₂ : Foo l₂) → ((s₁ : Foo l₂) → motive (Foo.cons s₁)) → ((x : Foo l₂) → motive x) → motive t₂ :=
fun {l₂} t₂ motive t₂_1 h_1 h_2 =>
(fun t₂_2 =>
Foo.casesOn (motive := fun a x => l₂ = a → HEq t₂_1 x → motive t₂_1) t₂_2
(fun h =>
Eq.ndrec (motive := fun {l₂} =>
(t₂ t₂ : Foo l₂) →
(motive : Foo l₂ → Sort u_1) →
((s₁ : Foo l₂) → motive (Foo.cons s₁)) → ((x : Foo l₂) → motive x) → HEq t₂ Foo.nil → motive t₂)
(fun t₂ t₂ motive h_1 h_2 h => Eq.symm (eq_of_heq h) ▸ h_2 Foo.nil) (Eq.symm h) t₂ t₂_1 motive h_1 h_2) --- HERE
fun {l} t h =>
Eq.ndrec (motive := fun {l} => (t : Foo l) → HEq t₂_1 (Foo.cons t) → motive t₂_1)
(fun t h => Eq.symm (eq_of_heq h) ▸ h_1 t) h t)
t₂_1 (Eq.refl l₂) (HEq.refl t₂_1)
```
The `HERE` comment marks the place where the type of `Foo.bar.match_1` minor premises `h_1` and `h_2` is being "refined"
using `Eq.ndrec`.
This function will adjust the motive and minor premise of the `Eq.ndrec` to reflect the new minor premises used in the
corresponding splitter theorem.
We may have to extend this function to handle `Eq.rec` too.
This function was added to address issue #1179
-/
convertCastEqRec (e : Expr) : ConvertM Expr := do
assert! (← isCastEqRec e)
e.withApp fun f args => do
let mut argsNew := args
let mut isAlt := #[]
for i in [6:args.size] do
let arg := argsNew[i]!
if arg.isFVar then
match (← read).find? arg.fvarId! with
| some (altNew, _, _) =>
argsNew := argsNew.set! i altNew
trace[Meta.Match.matchEqs] "arg: {arg} : {← inferType arg}, altNew: {altNew} : {← inferType altNew}"
isAlt := isAlt.push true
| none =>
argsNew := argsNew.set! i (← convertTemplate arg)
isAlt := isAlt.push false
else
argsNew := argsNew.set! i (← convertTemplate arg)
isAlt := isAlt.push false
assert! isAlt.size == args.size - 6
let rhs := args[4]!
let motive := args[2]!
-- Construct new motive using the splitter theorem minor premise types.
let motiveNew ← lambdaTelescope motive fun motiveArgs body => do
unless motiveArgs.size == 1 do
throwError "unexpected `Eq.ndrec` motive while creating splitter/eliminator theorem for `{matchDeclName}`, expected lambda with 1 binder{indentExpr motive}"
let x := motiveArgs[0]!
forallTelescopeReducing body fun motiveTypeArgs resultType => do
unless motiveTypeArgs.size >= isAlt.size do
throwError "unexpected `Eq.ndrec` motive while creating splitter/eliminator theorem for `{matchDeclName}`, expected arrow with at least #{isAlt.size} binders{indentExpr body}"
let rec go (i : Nat) (motiveTypeArgsNew : Array Expr) : ConvertM Expr := do
assert! motiveTypeArgsNew.size == i
if h : i < motiveTypeArgs.size then
let motiveTypeArg := motiveTypeArgs.get ⟨i, h⟩
if i < isAlt.size && isAlt[i]! then
let altNew := argsNew[6+i]! -- Recall that `Eq.ndrec` has 6 arguments
let altTypeNew ← inferType altNew
trace[Meta.Match.matchEqs] "altNew: {altNew} : {altTypeNew}"
-- Replace `rhs` with `x` (the lambda binder in the motive)
let mut altTypeNewAbst := (← kabstract altTypeNew rhs).instantiate1 x
-- Replace args[6:6+i] with `motiveTypeArgsNew`
for j in [:i] do
altTypeNewAbst := (← kabstract altTypeNewAbst argsNew[6+j]!).instantiate1 motiveTypeArgsNew[j]!
let localDecl ← motiveTypeArg.fvarId!.getDecl
withLocalDecl localDecl.userName localDecl.binderInfo altTypeNewAbst fun motiveTypeArgNew =>
go (i+1) (motiveTypeArgsNew.push motiveTypeArgNew)
else
go (i+1) (motiveTypeArgsNew.push motiveTypeArg)
else
mkLambdaFVars motiveArgs (← mkForallFVars motiveTypeArgsNew resultType)
go 0 #[]
trace[Meta.Match.matchEqs] "new motive: {motiveNew}"
unless (← isTypeCorrect motiveNew) do
throwError "failed to construct new type correct motive for `Eq.ndrec` while creating splitter/eliminator theorem for `{matchDeclName}`{indentExpr motiveNew}"
argsNew := argsNew.set! 2 motiveNew
-- Construct the new minor premise for the `Eq.ndrec` application.
-- First, we use `eqRecNewPrefix` to infer the new minor premise binders for `Eq.ndrec`
let eqRecNewPrefix := mkAppN f argsNew[:3] -- `Eq.ndrec` minor premise is the fourth argument.
let .forallE _ minorTypeNew .. ← whnf (← inferType eqRecNewPrefix) | unreachable!
trace[Meta.Match.matchEqs] "new minor type: {minorTypeNew}"
let minor := args[3]!
let minorNew ← forallBoundedTelescope minorTypeNew isAlt.size fun minorArgsNew _ => do
let mut minorBodyNew := minor
-- We have to extend the mapping to make sure `convertTemplate` can "fix" occurrences of the refined minor premises
let mut m ← read
for i in [:isAlt.size] do
if isAlt[i]! then
-- `convertTemplate` will correct occurrences of the alternative
let alt := args[6+i]! -- Recall that `Eq.ndrec` has 6 arguments
let some (_, numParams, argMask) := m.find? alt.fvarId! | unreachable!
-- We add a new entry to `m` to make sure `convertTemplate` will correct the occurrences of the alternative
m := m.insert minorArgsNew[i]!.fvarId! (minorArgsNew[i]!, numParams, argMask)
unless minorBodyNew.isLambda do
throwError "unexpected `Eq.ndrec` minor premise while creating splitter/eliminator theorem for `{matchDeclName}`, expected lambda with at least #{isAlt.size} binders{indentExpr minor}"
minorBodyNew := minorBodyNew.bindingBody!
minorBodyNew := minorBodyNew.instantiateRev minorArgsNew
trace[Meta.Match.matchEqs] "minor premise new body before convertTemplate:{indentExpr minorBodyNew}"
minorBodyNew ← withReader (fun _ => m) <| convertTemplate minorBodyNew
trace[Meta.Match.matchEqs] "minor premise new body after convertTemplate:{indentExpr minorBodyNew}"
mkLambdaFVars minorArgsNew minorBodyNew
unless (← isTypeCorrect minorNew) do
throwError "failed to construct new type correct minor premise for `Eq.ndrec` while creating splitter/eliminator theorem for `{matchDeclName}`{indentExpr minorNew}"
argsNew := argsNew.set! 3 minorNew
-- trace[Meta.Match.matchEqs] "argsNew: {argsNew}"
trace[Meta.Match.matchEqs] "found cast target {e}"
return mkAppN f argsNew
convertTemplate (e : Expr) : ConvertM Expr :=
transform e fun e => do
if (← isCastEqRec e) then
return .done (← convertCastEqRec e)
else
let Expr.fvar fvarId .. := e.getAppFn | return .continue
let some (altNew, numParams, argMask) := (← read).find? fvarId | return .continue
trace[Meta.Match.matchEqs] ">> argMask: {argMask}, e: {e}, {altNew}"
let mut newArgs := #[]
let argMask := trimFalseTrail argMask
unless e.getAppNumArgs ≥ argMask.size do
throwError "unexpected occurrence of `match`-expression alternative (aka minor premise) while creating splitter/eliminator theorem for `{matchDeclName}`, minor premise is partially applied{indentExpr e}\npossible solution if you are matching on inductive families: add its indices as additional discriminants"
for arg in e.getAppArgs, includeArg in argMask do
if includeArg then
newArgs := newArgs.push arg
let eNew := mkAppN altNew newArgs
/- Recall that `numParams` does not include the equalities associated with discriminants of the form `h : discr`. -/
let (mvars, _, _) ← forallMetaBoundedTelescope (← inferType eNew) (numParams - newArgs.size) (kind := MetavarKind.syntheticOpaque)
modify fun s => s ++ (mvars.map (·.mvarId!))
let eNew := mkAppN eNew mvars
return TransformStep.done eNew
proveSubgoalLoop (mvarId : MVarId) : MetaM Unit := do
trace[Meta.Match.matchEqs] "proveSubgoalLoop\n{mvarId}"
match (← injectionAny mvarId) with
| InjectionAnyResult.solved => return ()
| InjectionAnyResult.failed =>
let mvarId' ← substVars mvarId
if mvarId' == mvarId then
if (← mvarId.contradictionCore {}) then
return ()
throwError "failed to generate splitter for match auxiliary declaration '{matchDeclName}', unsolved subgoal:\n{MessageData.ofGoal mvarId}"
else
proveSubgoalLoop mvarId'
| InjectionAnyResult.subgoal mvarId => proveSubgoalLoop mvarId
proveSubgoal (mvarId : MVarId) : MetaM Unit := do
trace[Meta.Match.matchEqs] "subgoal {mkMVar mvarId}, {repr (← mvarId.getDecl).kind}, {← mvarId.isAssigned}\n{MessageData.ofGoal mvarId}"
let (_, mvarId) ← mvarId.intros
let mvarId ← mvarId.tryClearMany (alts.map (·.fvarId!))
proveSubgoalLoop mvarId
/--
Create new alternatives (aka minor premises) by replacing `discrs` with `patterns` at `alts`.
Recall that `alts` depends on `discrs` when `numDiscrEqs > 0`, where `numDiscrEqs` is the number of discriminants
annotated with `h : discr`.
-/
private partial def withNewAlts (numDiscrEqs : Nat) (discrs : Array Expr) (patterns : Array Expr) (alts : Array Expr) (k : Array Expr → MetaM α) : MetaM α :=
if numDiscrEqs == 0 then
k alts
else
go 0 #[]
where
go (i : Nat) (altsNew : Array Expr) : MetaM α := do
if h : i < alts.size then
let alt := alts.get ⟨i, h⟩
let altLocalDecl ← getFVarLocalDecl alt
let typeNew := altLocalDecl.type.replaceFVars discrs patterns
withLocalDecl altLocalDecl.userName altLocalDecl.binderInfo typeNew fun altNew =>
go (i+1) (altsNew.push altNew)
else
k altsNew
/--
Create conditional equations and splitter for the given match auxiliary declaration. -/
private partial def mkEquationsFor (matchDeclName : Name) : MetaM MatchEqns := withLCtx {} {} do
trace[Meta.Match.matchEqs] "mkEquationsFor '{matchDeclName}'"
withConfig (fun c => { c with etaStruct := .none }) do
let baseName := mkPrivateName (← getEnv) matchDeclName
let constInfo ← getConstInfo matchDeclName
let us := constInfo.levelParams.map mkLevelParam
let some matchInfo ← getMatcherInfo? matchDeclName | throwError "'{matchDeclName}' is not a matcher function"
let numDiscrEqs := getNumEqsFromDiscrInfos matchInfo.discrInfos
forallTelescopeReducing constInfo.type fun xs matchResultType => do
let mut eqnNames := #[]
let params := xs[:matchInfo.numParams]
let motive := xs[matchInfo.getMotivePos]!
let alts := xs[xs.size - matchInfo.numAlts:]
let firstDiscrIdx := matchInfo.numParams + 1
let discrs := xs[firstDiscrIdx : firstDiscrIdx + matchInfo.numDiscrs]
let mut notAlts := #[]
let mut idx := 1
let mut splitterAltTypes := #[]
let mut splitterAltNumParams := #[]
let mut altArgMasks := #[] -- masks produced by `forallAltTelescope`
for i in [:alts.size] do
let altNumParams := matchInfo.altNumParams[i]!
let altNonEqNumParams := altNumParams - numDiscrEqs
let thmName := baseName ++ ((`eq).appendIndexAfter idx)
eqnNames := eqnNames.push thmName
let (notAlt, splitterAltType, splitterAltNumParam, argMask) ← forallAltTelescope (← inferType alts[i]!) altNonEqNumParams fun ys eqs rhsArgs argMask altResultType => do
let patterns := altResultType.getAppArgs
let mut hs := #[]
for notAlt in notAlts do
let h ← instantiateForall notAlt patterns
if let some h ← simpH? h patterns.size then
hs := hs.push h
trace[Meta.Match.matchEqs] "hs: {hs}"
let splitterAltType ← mkForallFVars ys (← hs.foldrM (init := (← mkForallFVars eqs altResultType)) (mkArrow · ·))
let splitterAltNumParam := hs.size + ys.size
-- Create a proposition for representing terms that do not match `patterns`
let mut notAlt := mkConst ``False
for discr in discrs.toArray.reverse, pattern in patterns.reverse do
notAlt ← mkArrow (← mkEqHEq discr pattern) notAlt
notAlt ← mkForallFVars (discrs ++ ys) notAlt
/- Recall that when we use the `h : discr`, the alternative type depends on the discriminant.
Thus, we need to create new `alts`. -/
withNewAlts numDiscrEqs discrs patterns alts fun alts => do
let alt := alts[i]!
let lhs := mkAppN (mkConst constInfo.name us) (params ++ #[motive] ++ patterns ++ alts)
let rhs := mkAppN alt rhsArgs
let thmType ← mkEq lhs rhs
let thmType ← hs.foldrM (init := thmType) (mkArrow · ·)
let thmType ← mkForallFVars (params ++ #[motive] ++ ys ++ alts) thmType
let thmType ← unfoldNamedPattern thmType
let thmVal ← proveCondEqThm matchDeclName thmType
addDecl <| Declaration.thmDecl {
name := thmName
levelParams := constInfo.levelParams
type := thmType
value := thmVal
}
return (notAlt, splitterAltType, splitterAltNumParam, argMask)
notAlts := notAlts.push notAlt
splitterAltTypes := splitterAltTypes.push splitterAltType
splitterAltNumParams := splitterAltNumParams.push splitterAltNumParam
altArgMasks := altArgMasks.push argMask
trace[Meta.Match.matchEqs] "splitterAltType: {splitterAltType}"
idx := idx + 1
-- Define splitter with conditional/refined alternatives
withSplitterAlts splitterAltTypes fun altsNew => do
let splitterParams := params.toArray ++ #[motive] ++ discrs.toArray ++ altsNew
let splitterType ← mkForallFVars splitterParams matchResultType
trace[Meta.Match.matchEqs] "splitterType: {splitterType}"
let template := mkAppN (mkConst constInfo.name us) (params ++ #[motive] ++ discrs ++ alts)
let template ← deltaExpand template (· == constInfo.name)
let template := template.headBeta
let splitterVal ← mkLambdaFVars splitterParams (← mkSplitterProof matchDeclName template alts altsNew splitterAltNumParams altArgMasks)
let splitterName := baseName ++ `splitter
addAndCompile <| Declaration.defnDecl {
name := splitterName
levelParams := constInfo.levelParams
type := splitterType
value := splitterVal
hints := .abbrev
safety := .safe
}
setInlineAttribute splitterName
let result := { eqnNames, splitterName, splitterAltNumParams }
registerMatchEqns matchDeclName result
return result
/- See header at `MatchEqsExt.lean` -/
@[export lean_get_match_equations_for]
def getEquationsForImpl (matchDeclName : Name) : MetaM MatchEqns := do
match matchEqnsExt.getState (← getEnv) |>.map.find? matchDeclName with
| some matchEqns => return matchEqns
| none => mkEquationsFor matchDeclName
builtin_initialize registerTraceClass `Meta.Match.matchEqs
end Lean.Meta.Match
|
823ae2bbac86c597e9ee93a55643613eed9966cb | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/finset/pimage.lean | 9ed110e3d7479d5c019c758e3e9828b245f48120 | [
"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 | 3,119 | 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 data.finset.option
import data.pfun
/-!
# Image of a `finset α` under a partially defined function
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define `part.to_finset` and `finset.pimage`. We also prove some trivial lemmas about
these definitions.
## Tags
finite set, image, partial function
-/
variables {α β : Type*}
namespace part
/-- Convert a `o : part α` with decidable `part.dom o` to `finset α`. -/
def to_finset (o : part α) [decidable o.dom] : finset α := o.to_option.to_finset
@[simp] lemma mem_to_finset {o : part α} [decidable o.dom] {x : α} :
x ∈ o.to_finset ↔ x ∈ o :=
by simp [to_finset]
@[simp] theorem to_finset_none [decidable (none : part α).dom] :
none.to_finset = (∅ : finset α) :=
by simp [to_finset]
@[simp] theorem to_finset_some {a : α} [decidable (some a).dom] :
(some a).to_finset = {a} :=
by simp [to_finset]
@[simp] lemma coe_to_finset (o : part α) [decidable o.dom] :
(o.to_finset : set α) = {x | x ∈ o} :=
set.ext $ λ x, mem_to_finset
end part
namespace finset
variables [decidable_eq β] {f g : α →. β} [∀ x, decidable (f x).dom]
[∀ x, decidable (g x).dom] {s t : finset α} {b : β}
/-- Image of `s : finset α` under a partially defined function `f : α →. β`. -/
def pimage (f : α →. β) [∀ x, decidable (f x).dom] (s : finset α) : finset β :=
s.bUnion (λ x, (f x).to_finset)
@[simp] lemma mem_pimage : b ∈ s.pimage f ↔ ∃ (a ∈ s), b ∈ f a := by simp [pimage]
@[simp, norm_cast] lemma coe_pimage : (s.pimage f : set β) = f.image s :=
set.ext $ λ x, mem_pimage
@[simp] lemma pimage_some (s : finset α) (f : α → β) [∀ x, decidable (part.some $ f x).dom] :
s.pimage (λ x, part.some (f x)) = s.image f :=
by { ext, simp [eq_comm] }
lemma pimage_congr (h₁ : s = t) (h₂ : ∀ x ∈ t, f x = g x) : s.pimage f = t.pimage g :=
by { subst s, ext y, simp [h₂] { contextual := tt } }
/-- Rewrite `s.pimage f` in terms of `finset.filter`, `finset.attach`, and `finset.image`. -/
lemma pimage_eq_image_filter : s.pimage f =
(filter (λ x, (f x).dom) s).attach.image (λ x, (f x).get (mem_filter.1 x.coe_prop).2) :=
by { ext x, simp [part.mem_eq, and.exists, -exists_prop] }
lemma pimage_union [decidable_eq α] : (s ∪ t).pimage f = s.pimage f ∪ t.pimage f :=
coe_inj.1 $ by simp only [coe_pimage, pfun.image_union, coe_union]
@[simp] lemma pimage_empty : pimage f ∅ = ∅ := by { ext, simp }
lemma pimage_subset {t : finset β} : s.pimage f ⊆ t ↔ ∀ (x ∈ s) (y ∈ f x), y ∈ t :=
by simp [subset_iff, @forall_swap _ β]
@[mono] lemma pimage_mono (h : s ⊆ t) : s.pimage f ⊆ t.pimage f :=
pimage_subset.2 $ λ x hx y hy, mem_pimage.2 ⟨x, h hx, hy⟩
lemma pimage_inter [decidable_eq α] : (s ∩ t).pimage f ⊆ s.pimage f ∩ t.pimage f :=
by simp only [← coe_subset, coe_pimage, coe_inter, pfun.image_inter]
end finset
|
139ba34965a9f7dbbacbadc3ad1a6b2082aebf42 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/monad/monadicity.lean | 8a15ac2fb424700ca0fb899a59cfe3c6e24928c2 | [
"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,223 | 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.shapes.equalizers
import category_theory.limits.shapes.reflexive
import category_theory.monad.coequalizer
import category_theory.monad.limits
/-!
# Monadicity theorems
We prove monadicity theorems which can establish a given functor is monadic. In particular, we
show three versions of Beck's monadicity theorem, and the reflexive (crude) monadicity theorem:
`G` is a monadic right adjoint if it has a right adjoint, and:
* `D` has, `G` preserves and reflects `G`-split coequalizers, see
`category_theory.monad.monadic_of_has_preserves_reflects_G_split_coequalizers`
* `G` creates `G`-split coequalizers, see
`category_theory.monad.monadic_of_creates_G_split_coequalizers`
(The converse of this is also shown, see
`category_theory.monad.creates_G_split_coequalizers_of_monadic`)
* `D` has and `G` preserves `G`-split coequalizers, and `G` reflects isomorphisms, see
`category_theory.monad.monadic_of_has_preserves_G_split_coequalizers_of_reflects_isomorphisms`
* `D` has and `G` preserves reflexive coequalizers, and `G` reflects isomorphisms, see
`category_theory.monad.monadic_of_has_preserves_reflexive_coequalizers_of_reflects_isomorphisms`
## Tags
Beck, monadicity, descent
## TODO
Dualise to show comonadicity theorems.
-/
universes v₁ v₂ u₁ u₂
namespace category_theory
namespace monad
open limits
noncomputable theory
-- Hide the implementation details in this namespace.
namespace monadicity_internal
section
-- We use these parameters and notations to simplify the statements of internal constructions
-- here.
parameters {C : Type u₁} {D : Type u₂}
parameters [category.{v₁} C] [category.{v₁} D]
parameters {G : D ⥤ C} [is_right_adjoint G]
-- An unfortunate consequence of the local notation is that it is only recognised if there is an
-- extra space after the reference.
local notation `F` := left_adjoint G
local notation `adj` := adjunction.of_right_adjoint G
/--
The "main pair" for an algebra `(A, α)` is the pair of morphisms `(F α, ε_FA)`. It is always a
reflexive pair, and will be used to construct the left adjoint to the comparison functor and show it
is an equivalence.
-/
instance main_pair_reflexive (A : adj .to_monad.algebra) :
is_reflexive_pair (F .map A.a) (adj .counit.app (F .obj A.A)) :=
begin
apply is_reflexive_pair.mk' (F .map (adj .unit.app _)) _ _,
{ rw [← F .map_comp, ← F .map_id],
exact congr_arg (λ _, F .map _) A.unit },
{ rw adj .left_triangle_components,
refl },
end
/--
The "main pair" for an algebra `(A, α)` is the pair of morphisms `(F α, ε_FA)`. It is always a
`G`-split pair, and will be used to construct the left adjoint to the comparison functor and show it
is an equivalence.
-/
instance main_pair_G_split (A : adj .to_monad.algebra) :
G.is_split_pair (F .map A.a) (adj .counit.app (F .obj A.A)) :=
{ splittable := ⟨_, _, ⟨beck_split_coequalizer A⟩⟩ }
/-- The object function for the left adjoint to the comparison functor. -/
def comparison_left_adjoint_obj
(A : adj .to_monad.algebra) [has_coequalizer (F .map A.a) (adj .counit.app _)] : D :=
coequalizer (F .map A.a) (adj .counit.app _)
/--
We have a bijection of homsets which will be used to construct the left adjoint to the comparison
functor.
-/
@[simps]
def comparison_left_adjoint_hom_equiv (A : adj .to_monad.algebra) (B : D)
[has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))] :
(comparison_left_adjoint_obj A ⟶ B) ≃ (A ⟶ (comparison adj).obj B) :=
calc (comparison_left_adjoint_obj A ⟶ B) ≃ {f : F .obj A.A ⟶ B // _} :
cofork.is_colimit.hom_iso (colimit.is_colimit _) B
... ≃ {g : A.A ⟶ G.obj B // G.map (F .map g) ≫ G.map (adj .counit.app B) = A.a ≫ g} :
begin
refine (adj .hom_equiv _ _).subtype_equiv _,
intro f,
rw [← (adj .hom_equiv _ _).injective.eq_iff, adjunction.hom_equiv_naturality_left,
adj .hom_equiv_unit, adj .hom_equiv_unit, G.map_comp],
dsimp,
rw [adj .right_triangle_components_assoc, ← G.map_comp, F .map_comp, category.assoc,
adj .counit_naturality, adj .left_triangle_components_assoc],
apply eq_comm,
end
... ≃ (A ⟶ (comparison adj).obj B) :
{ to_fun := λ g, { f := _, h' := g.prop },
inv_fun := λ f, ⟨f.f, f.h⟩,
left_inv := λ g, begin ext, refl end,
right_inv := λ f, begin ext, refl end }
/--
Construct the adjunction to the comparison functor.
-/
def left_adjoint_comparison
[∀ (A : adj .to_monad.algebra), has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))] :
adj .to_monad.algebra ⥤ D :=
begin
refine @adjunction.left_adjoint_of_equiv _ _ _ _
(comparison adj) (λ A, comparison_left_adjoint_obj A) (λ A B, _) _,
{ apply comparison_left_adjoint_hom_equiv },
{ intros A B B' g h,
ext1,
dsimp [comparison_left_adjoint_hom_equiv],
rw [← adj .hom_equiv_naturality_right, category.assoc] },
end
/--
Provided we have the appropriate coequalizers, we have an adjunction to the comparison functor.
-/
@[simps counit]
def comparison_adjunction
[∀ (A : adj .to_monad.algebra), has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))] :
left_adjoint_comparison ⊣ comparison adj :=
adjunction.adjunction_of_equiv_left _ _
lemma comparison_adjunction_unit_f_aux
[∀ (A : adj .to_monad.algebra), has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))]
(A : adj .to_monad.algebra) :
(comparison_adjunction.unit.app A).f =
adj .hom_equiv A.A _ (coequalizer.π (F .map A.a) (adj .counit.app (F .obj A.A))) :=
congr_arg (adj .hom_equiv _ _) (category.comp_id _)
/--
This is a cofork which is helpful for establishing monadicity: the morphism from the Beck
coequalizer to this cofork is the unit for the adjunction on the comparison functor.
-/
@[simps X]
def unit_cofork (A : adj .to_monad.algebra)
[has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))] :
cofork (G.map (F .map A.a)) (G.map (adj .counit.app (F .obj A.A))) :=
cofork.of_π (G.map (coequalizer.π (F .map A.a) (adj .counit.app (F .obj A.A))))
begin
change _ = G.map _ ≫ _,
rw [← G.map_comp, coequalizer.condition, G.map_comp],
end
@[simp] lemma unit_cofork_π (A : adj .to_monad.algebra)
[has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))] :
(unit_cofork A).π = G.map (coequalizer.π (F .map A.a) (adj .counit.app (F .obj A.A))) := rfl
lemma comparison_adjunction_unit_f
[∀ (A : adj .to_monad.algebra), has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))]
(A : adj .to_monad.algebra) :
(comparison_adjunction.unit.app A).f =
(beck_coequalizer A).desc (unit_cofork A) :=
begin
apply limits.cofork.is_colimit.hom_ext (beck_coequalizer A),
rw [cofork.is_colimit.π_desc],
dsimp only [beck_cofork_π, unit_cofork_π],
rw [comparison_adjunction_unit_f_aux, ← adj .hom_equiv_naturality_left A.a, coequalizer.condition,
adj .hom_equiv_naturality_right, adj .hom_equiv_unit, category.assoc],
apply adj .right_triangle_components_assoc,
end
/--
The cofork which describes the counit of the adjunction: the morphism from the coequalizer of
this pair to this morphism is the counit.
-/
@[simps]
def counit_cofork (B : D) :
cofork (F .map (G.map (adj .counit.app B))) (adj .counit.app (F .obj (G.obj B))) :=
cofork.of_π (adj .counit.app B) (adj .counit_naturality _)
/-- The unit cofork is a colimit provided `G` preserves it. -/
def unit_colimit_of_preserves_coequalizer
(A : adj .to_monad.algebra) [has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))]
[preserves_colimit (parallel_pair (F .map A.a) (adj .counit.app (F .obj A.A))) G] :
is_colimit (unit_cofork A) :=
is_colimit_of_has_coequalizer_of_preserves_colimit G _ _
/-- The counit cofork is a colimit provided `G` reflects it. -/
def counit_coequalizer_of_reflects_coequalizer (B : D)
[reflects_colimit (parallel_pair
(F .map (G.map (adj .counit.app B)))
(adj .counit.app (F .obj (G.obj B)))) G] :
is_colimit (counit_cofork B) :=
is_colimit_of_is_colimit_cofork_map G _ (beck_coequalizer ((comparison adj).obj B))
lemma comparison_adjunction_counit_app
[∀ (A : adj .to_monad.algebra), has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))]
(B : D) :
comparison_adjunction.counit.app B = colimit.desc _ (counit_cofork B) :=
begin
apply coequalizer.hom_ext,
change coequalizer.π _ _ ≫ coequalizer.desc ((adj .hom_equiv _ B).symm (𝟙 _)) _ =
coequalizer.π _ _ ≫ coequalizer.desc _ _,
simp,
end
end
end monadicity_internal
open category_theory.adjunction
open monadicity_internal
variables {C : Type u₁} {D : Type u₂}
variables [category.{v₁} C] [category.{v₁} D]
variables (G : D ⥤ C)
/--
If `G` is monadic, it creates colimits of `G`-split pairs. This is the "boring" direction of Beck's
monadicity theorem, the converse is given in `monadic_of_creates_G_split_coequalizers`.
-/
def creates_G_split_coequalizers_of_monadic [monadic_right_adjoint G] ⦃A B⦄ (f g : A ⟶ B)
[G.is_split_pair f g] :
creates_colimit (parallel_pair f g) G :=
begin
apply monadic_creates_colimit_of_preserves_colimit _ _,
apply_instance,
{ apply preserves_colimit_of_iso_diagram _ (diagram_iso_parallel_pair.{v₁} _).symm,
dsimp,
apply_instance },
{ apply preserves_colimit_of_iso_diagram _ (diagram_iso_parallel_pair.{v₁} _).symm,
dsimp,
apply_instance }
end
variables [is_right_adjoint G]
section beck_monadicity
/--
To show `G` is a monadic right adjoint, we can show it preserves and reflects `G`-split
coequalizers, and `C` has them.
-/
def monadic_of_has_preserves_reflects_G_split_coequalizers
[∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], has_coequalizer f g]
[∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], preserves_colimit (parallel_pair f g) G]
[∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], reflects_colimit (parallel_pair f g) G] :
monadic_right_adjoint G :=
begin
let L : (adjunction.of_right_adjoint G).to_monad.algebra ⥤ D := left_adjoint_comparison,
letI i : is_right_adjoint (comparison (of_right_adjoint G)) :=
⟨_, comparison_adjunction⟩,
constructor,
let : Π (X : (of_right_adjoint G).to_monad.algebra),
is_iso ((of_right_adjoint (comparison (of_right_adjoint G))).unit.app X),
{ intro X,
apply is_iso_of_reflects_iso _ (monad.forget (of_right_adjoint G).to_monad),
{ change is_iso (comparison_adjunction.unit.app X).f,
rw comparison_adjunction_unit_f,
change
is_iso
(is_colimit.cocone_point_unique_up_to_iso
(beck_coequalizer X)
(unit_colimit_of_preserves_coequalizer X)).hom,
refine is_iso.of_iso (is_colimit.cocone_point_unique_up_to_iso _ _) } },
let : Π (Y : D),
is_iso ((of_right_adjoint (comparison (of_right_adjoint G))).counit.app Y),
{ intro Y,
change is_iso (comparison_adjunction.counit.app Y),
rw comparison_adjunction_counit_app,
change is_iso (is_colimit.cocone_point_unique_up_to_iso _ _).hom,
apply_instance,
apply counit_coequalizer_of_reflects_coequalizer _,
letI : G.is_split_pair
((left_adjoint G).map (G.map ((adjunction.of_right_adjoint G).counit.app Y)))
((adjunction.of_right_adjoint G).counit.app ((left_adjoint G).obj (G.obj Y))) :=
monadicity_internal.main_pair_G_split ((comparison (adjunction.of_right_adjoint G)).obj Y),
apply_instance },
exactI adjunction.is_right_adjoint_to_is_equivalence,
end
/--
Beck's monadicity theorem. If `G` has a right adjoint and creates coequalizers of `G`-split pairs,
then it is monadic.
This is the converse of `creates_G_split_of_monadic`.
-/
def monadic_of_creates_G_split_coequalizers
[∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], creates_colimit (parallel_pair f g) G] :
monadic_right_adjoint G :=
begin
letI : ∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], has_colimit (parallel_pair f g ⋙ G),
{ introsI A B f g i,
apply has_colimit_of_iso (diagram_iso_parallel_pair.{v₁} _),
change has_coequalizer (G.map f) (G.map g),
apply_instance },
apply monadic_of_has_preserves_reflects_G_split_coequalizers _,
{ apply_instance },
{ introsI A B f g i,
apply has_colimit_of_created (parallel_pair f g) G },
{ introsI A B f g i,
apply_instance },
{ introsI A B f g i,
apply_instance }
end
/--
An alternate version of Beck's monadicity theorem. If `G` reflects isomorphisms, preserves
coequalizers of `G`-split pairs and `C` has coequalizers of `G`-split pairs, then it is monadic.
-/
def monadic_of_has_preserves_G_split_coequalizers_of_reflects_isomorphisms
[reflects_isomorphisms G]
[∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], has_coequalizer f g]
[∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], preserves_colimit (parallel_pair f g) G] :
monadic_right_adjoint G :=
begin
apply monadic_of_has_preserves_reflects_G_split_coequalizers _,
{ apply_instance },
{ assumption },
{ assumption },
{ introsI A B f g i,
apply reflects_colimit_of_reflects_isomorphisms },
end
end beck_monadicity
section reflexive_monadicity
variables [has_reflexive_coequalizers D] [reflects_isomorphisms G]
variables [∀ ⦃A B⦄ (f g : A ⟶ B) [is_reflexive_pair f g], preserves_colimit (parallel_pair f g) G]
/--
Reflexive (crude) monadicity theorem. If `G` has a right adjoint, `D` has and `G` preserves
reflexive coequalizers and `G` reflects isomorphisms, then `G` is monadic.
-/
def monadic_of_has_preserves_reflexive_coequalizers_of_reflects_isomorphisms :
monadic_right_adjoint G :=
begin
let L : (adjunction.of_right_adjoint G).to_monad.algebra ⥤ D := left_adjoint_comparison,
letI i : is_right_adjoint (comparison (adjunction.of_right_adjoint G)) :=
⟨_, comparison_adjunction⟩,
constructor,
let : Π (X : (adjunction.of_right_adjoint G).to_monad.algebra),
is_iso ((adjunction.of_right_adjoint (comparison (adjunction.of_right_adjoint G))).unit.app X),
{ intro X,
apply is_iso_of_reflects_iso _ (monad.forget (adjunction.of_right_adjoint G).to_monad),
{ change is_iso (comparison_adjunction.unit.app X).f,
rw comparison_adjunction_unit_f,
change
is_iso
(is_colimit.cocone_point_unique_up_to_iso
(beck_coequalizer X)
(unit_colimit_of_preserves_coequalizer X)).hom,
apply is_iso.of_iso (is_colimit.cocone_point_unique_up_to_iso _ _) } },
let : Π (Y : D),
is_iso ((of_right_adjoint (comparison (adjunction.of_right_adjoint G))).counit.app Y),
{ intro Y,
change is_iso (comparison_adjunction.counit.app Y),
rw comparison_adjunction_counit_app,
change is_iso (is_colimit.cocone_point_unique_up_to_iso _ _).hom,
apply_instance,
apply counit_coequalizer_of_reflects_coequalizer _,
apply reflects_colimit_of_reflects_isomorphisms },
exactI adjunction.is_right_adjoint_to_is_equivalence,
end
end reflexive_monadicity
end monad
end category_theory
|
b5d035a4046ea5f7529b1136a87b2c6bb8aa67c6 | aa101d73b1a3173c7ec56de02b96baa8ca64c42e | /src/exercises/09_limits_final.lean | 66bff98560e929fc5fb1b4b955d40efa29e0463c | [
"Apache-2.0"
] | permissive | gihanmarasingha/tutorials | b554d4d53866c493c4341dc13e914b01444e95a6 | 56617114ef0f9f7b808476faffd11e22e4380918 | refs/heads/master | 1,671,141,758,153 | 1,599,173,318,000 | 1,599,173,318,000 | 282,405,870 | 0 | 0 | Apache-2.0 | 1,595,666,751,000 | 1,595,666,750,000 | null | UTF-8 | Lean | false | false | 7,228 | lean | import tuto_lib
set_option pp.beta true
set_option pp.coercions false
/-
This is the final file in the series. Here we use everything covered
in previous files to prove a couple of famous theorems from
elementary real analysis. Of course they all have more general versions
in mathlib.
As usual, keep in mind the following:
abs_le (x y : ℝ) : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y
ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q
le_max_left p q : p ≤ max p q
le_max_right p q : q ≤ max p q
as well as a lemma from the previous file:
le_of_le_add_all : (∀ ε > 0, y ≤ x + ε) → y ≤ x
Let's start with a variation on a known exercise.
-/
-- 0071
lemma le_lim {x y : ℝ} {u : ℕ → ℝ} (hu : seq_limit u x)
(ineg : ∃ N, ∀ n ≥ N, y ≤ u n) : y ≤ x :=
begin
sorry
end
/-
Let's now return to the result proved in the `00_` file of this series,
and prove again the sequential characterization of upper bounds (with a slighly
different proof).
For this, and other exercises below, we'll need many things that we proved in previous files,
and a couple of extras.
From the 5th file:
limit_const (x : ℝ) : seq_limit (λ n, x) x
squeeze (lim_u : seq_limit u l) (lim_w : seq_limit w l)
(hu : ∀ n, u n ≤ v n) (hw : ∀ n, v n ≤ w n) : seq_limit v l
From the 8th:
def upper_bound (A : set ℝ) (x : ℝ) := ∀ a ∈ A, a ≤ x
def is_sup (A : set ℝ) (x : ℝ) := upper_bound A x ∧ ∀ y, upper_bound A y → x ≤ y
lt_sup (hx : is_sup A x) : ∀ y, y < x → ∃ a ∈ A, y < a :=
You can also use:
nat.one_div_pos_of_nat {n : ℕ} : 0 < 1 / (n + 1 : ℝ)
inv_succ_le_all : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1/(n + 1 : ℝ) ≤ ε
and their easy consequences:
limit_of_sub_le_inv_succ (h : ∀ n, |u n - x| ≤ 1/(n+1)) : seq_limit u x
limit_const_add_inv_succ (x : ℝ) : seq_limit (λ n, x + 1/(n+1)) x
limit_const_sub_inv_succ (x : ℝ) : seq_limit (λ n, x - 1/(n+1)) x
The structure of the proof is offered. It features a new tactic:
`choose` which invokes the axiom of choice (observing the tactic state before and
after using it should be enough to understand everything).
-/
-- 0072
lemma is_sup_iff (A : set ℝ) (x : ℝ) :
(is_sup A x) ↔ (upper_bound A x ∧ ∃ u : ℕ → ℝ, seq_limit u x ∧ ∀ n, u n ∈ A ) :=
begin
split,
{ intro h,
split,
{
sorry
},
{ have : ∀ n : ℕ, ∃ a ∈ A, x - 1/(n+1) < a,
{ intros n,
have : 1/(n+1 : ℝ) > 0,
exact nat.one_div_pos_of_nat,
sorry
},
choose u hu using this,
sorry
} },
{ rintro ⟨maj, u, limu, u_in⟩,
sorry
},
end
/-- Continuity of a function at a point -/
def continuous_at_pt (f : ℝ → ℝ) (x₀ : ℝ) : Prop :=
∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - f x₀| ≤ ε
variables {f : ℝ → ℝ} {x₀ : ℝ} {u : ℕ → ℝ}
-- 0073
lemma seq_continuous_of_continuous (hf : continuous_at_pt f x₀)
(hu : seq_limit u x₀) : seq_limit (f ∘ u) (f x₀) :=
begin
sorry
end
-- 0074
example :
(∀ u : ℕ → ℝ, seq_limit u x₀ → seq_limit (f ∘ u) (f x₀)) →
continuous_at_pt f x₀ :=
begin
sorry
end
/-
Recall from the 6th file:
def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m
def cluster_point (u : ℕ → ℝ) (a : ℝ) :=
∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a
id_le_extraction : extraction φ → ∀ n, n ≤ φ n
and from the 8th file:
def tendsto_infinity (u : ℕ → ℝ) := ∀ A, ∃ N, ∀ n ≥ N, u n ≥ A
not_seq_limit_of_tendstoinfinity : tendsto_infinity u → ∀ l, ¬ seq_limit u l
-/
variables {φ : ℕ → ℕ}
-- 0075
lemma subseq_tenstoinfinity
(h : tendsto_infinity u) (hφ : extraction φ) :
tendsto_infinity (u ∘ φ) :=
begin
sorry
end
-- 0076
lemma squeeze_infinity {u v : ℕ → ℝ} (hu : tendsto_infinity u)
(huv : ∀ n, u n ≤ v n) : tendsto_infinity v :=
begin
sorry
end
/-
We will use segments: Icc a b := { x | a ≤ x ∧ x ≤ b }
The notation stands for Interval-closed-closed. Variations exist with
o or i instead of c, where o stands for open and i for infinity.
We will use the following version of Bolzano-Weirstrass
bolzano_weierstrass (h : ∀ n, u n ∈ [a, b]) :
∃ c ∈ [a, b], cluster_point u c
as well as the obvious
seq_limit_id : tendsto_infinity (λ n, n)
-/
open set
-- 0077
lemma bdd_above_segment {f : ℝ → ℝ} {a b : ℝ} (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) :
∃ M, ∀ x ∈ Icc a b, f x ≤ M :=
begin
sorry
end
/-
In the next exercise, we can use:
abs_neg x : |-x| = |x|
-/
-- 0078
lemma continuous_opposite {f : ℝ → ℝ} {x₀ : ℝ} (h : continuous_at_pt f x₀) :
continuous_at_pt (λ x, -f x) x₀ :=
begin
sorry
end
/-
Now let's combine the two exercises above
-/
-- 0079
lemma bdd_below_segment {f : ℝ → ℝ} {a b : ℝ} (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) :
∃ m, ∀ x ∈ Icc a b, m ≤ f x :=
begin
sorry
end
/-
Remember from the 5th file:
unique_limit : seq_limit u l → seq_limit u l' → l = l'
and from the 6th one:
subseq_tendsto_of_tendsto (h : seq_limit u l) (hφ : extraction φ) :
seq_limit (u ∘ φ) l
We now admit the following version of the least upper bound theorem
(that cannot be proved without discussing the construction of real numbers
or admitting another strong theorem).
sup_segment {a b : ℝ} {A : set ℝ} (hnonvide : ∃ x, x ∈ A) (h : A ⊆ Icc a b) :
∃ x ∈ Icc a b, is_sup A x
In the next exercise, it can be useful to prove inclusions of sets of real number.
By definition, A ⊆ B means : ∀ x, x ∈ A → x ∈ B.
Hence one can start a proof of A ⊆ B by `intros x x_in`,
which brings `x : ℝ` and `x_in : x ∈ A` in the local context,
and then prove `x ∈ B`.
Note also the use of
{x | P x}
which denotes the set of x satisfying predicate P.
Hence `x' ∈ { x | P x} ↔ P x'`, by definition.
-/
-- 0080
example {a b : ℝ} (hab : a ≤ b) (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) :
∃ x₀ ∈ Icc a b, ∀ x ∈ Icc a b, f x ≤ f x₀ :=
begin
sorry
end
lemma stupid {a b x : ℝ} (h : x ∈ Icc a b) (h' : x ≠ b) : x < b :=
lt_of_le_of_ne h.right h'
/-
And now the final boss...
-/
def I := (Icc 0 1 : set ℝ) -- the type ascription makes sure 0 and 1 are real numbers here
-- 0081
example (f : ℝ → ℝ) (hf : ∀ x, continuous_at_pt f x) (h₀ : f 0 < 0) (h₁ : f 1 > 0) :
∃ x₀ ∈ I, f x₀ = 0 :=
begin
let A := { x | x ∈ I ∧ f x < 0},
have ex_x₀ : ∃ x₀ ∈ I, is_sup A x₀,
{
sorry
},
rcases ex_x₀ with ⟨x₀, x₀_in, x₀_sup⟩,
use [x₀, x₀_in],
have : f x₀ ≤ 0,
{
sorry
},
have x₀_1: x₀ < 1,
{
sorry
},
have : f x₀ ≥ 0,
{ have dans : ∃ N : ℕ, ∀ n ≥ N, x₀ + 1/(n+1) ∈ I,
{ have : ∃ N : ℕ, ∀ n≥ N, 1/(n+1 : ℝ) ≤ 1-x₀,
{
sorry
},
sorry
},
have not_in : ∀ n : ℕ, x₀ + 1/(n+1) ∉ A,
-- By definition, x ∉ A means ¬ (x ∈ A).
{
sorry
},
dsimp [A] at not_in, -- This is useful to unfold a let
sorry
},
linarith,
end
|
45f1fad3ece289bec690f4a014cd6408b8b19113 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/simple.lean | dc8e6f685979f26ee974fe111d12eb0c104a70f4 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 572 | lean | prelude
definition Prop : Type.{1} := Type.{0}
section
parameter A : Type*
definition eq (a b : A) : Prop
:= ∀P : A → Prop, P a → P b
theorem subst (P : A → Prop) (a b : A) (H1 : eq a b) (H2 : P a) : P b
:= H1 P H2
theorem refl (a : A) : eq a a
:= λ (P : A → Prop) (H : P a), H
theorem symm (a b : A) (H : eq a b) : eq b a
:= subst (λ x : A, eq x a) a b H (refl a)
theorem trans (a b c : A) (H1 : eq a b) (H2 : eq b c) : eq a c
:= subst (λ x : A, eq a x) b c H2 H1
end
check subst.{1}
check refl.{1}
check symm.{1}
check trans.{1}
|
d2d8c6ed123d4d162e20f511c89af5f1a663fcac | 1fbca480c1574e809ae95a3eda58188ff42a5e41 | /src/util/meta/tactic/perm.lean | 62f27d1a52b586a1f60f85a4e71a0d2180230698 | [] | no_license | unitb/lean-lib | 560eea0acf02b1fd4bcaac9986d3d7f1a4290e7e | 439b80e606b4ebe4909a08b1d77f4f5c0ee3dee9 | refs/heads/master | 1,610,706,025,400 | 1,570,144,245,000 | 1,570,144,245,000 | 99,579,229 | 5 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,155 | lean |
import data.list.perm
namespace tactic
private meta def is_cons : expr → option (expr × expr)
| `(list.cons %%x %%xs) := some (x,xs)
| _ := none
private meta def parse_list' (t : expr) : expr → tactic (list expr)
| e := do
(do (x,xs) ← is_cons e,
list.cons x <$> parse_list' xs)
<|> (do guard (e.is_app_of `list.nil),
return [])
private meta def parse_list (e : expr) : tactic (list expr) :=
do `(list %%t) ← infer_type e | fail (to_fmt "expecting a list type in " ++ to_fmt e),
parse_list' t e <|> fail (to_fmt "expecting a list literal in " ++ to_fmt e)
meta def find (e : expr) : list expr → tactic (expr × list expr × list expr)
| [] := tactic.fail "foo"
| (x :: xs) :=
do b ← try_core (tactic.is_def_eq e x),
if b.is_some then
return (x,[],xs)
else do
(x',ys,xs') ← find xs,
return (x',x::ys,xs')
meta def list_literal : list expr → tactic expr
| [] := to_expr ``([])
| (x :: xs) :=
do xs' ← list_literal xs,
to_expr ``(%%x :: %%xs')
meta def mk_perm_proof : list expr → list expr → tactic expr
| [] ys :=
if ys = [] then
to_expr ``(list.perm.nil)
else do
ys' ← pp ys,
fail $ to_fmt "unmatched left-over: " ++ ys'
| (x :: xs) ys := do
x' ← pp x, ys' ← pp ys,
(y,ys₀,ys₁) ← find x ys <|> fail (x' ++ " not found in " ++ ys'),
left_p ← mk_perm_proof xs (ys₀ ++ ys₁),
-- make a proof of xs ~ ys₀ ++ ys₁
left ← to_expr ``(list.perm.skip %%x %%left_p),
zs₀ ← list_literal ys₀,
zs₁ ← list_literal ys₁,
-- right_p ← to_expr ``(list.perm_cons_app %%y %%zs₀),
right ← to_expr ``(list.perm.symm $ @list.perm_middle _ %%y %%zs₀ %%zs₁),
-- make a proof of y :: ys₀ ++ ys₁ ~ ys₀ ++ y :: ys₁
to_expr ``(list.perm.trans %%left %%right)
namespace interactive
/-- prove a goal of the form `perm [a,b,c] [c,a,b]` -/
meta def prove_perm : tactic unit := do
`(list.perm %%xs %%ys) ← target
| fail "expecting goal of the form `(list.perm [...] [...])`",
xs' ← parse_list xs,
ys' ← parse_list ys,
() <$ (mk_perm_proof xs' ys' >>= tactic.apply)
end interactive
end tactic
|
98df9b767b57856e174784a264991800f7f4976a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/squarefree.lean | dd70a525e1e706c1da7babbb89ceb485fa5dd2b5 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 9,088 | 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 ring_theory.unique_factorization_domain
/-!
# Squarefree elements of monoids
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
An element of a monoid is squarefree when it is not divisible by any squares
except the squares of units.
Results about squarefree natural numbers are proved in `data/nat/squarefree`.
## Main Definitions
- `squarefree r` indicates that `r` is only divisible by `x * x` if `x` is a unit.
## Main Results
- `multiplicity.squarefree_iff_multiplicity_le_one`: `x` is `squarefree` iff for every `y`, either
`multiplicity y x ≤ 1` or `is_unit y`.
- `unique_factorization_monoid.squarefree_iff_nodup_factors`: A nonzero element `x` of a unique
factorization monoid is squarefree iff `factors x` has no duplicate factors.
## Tags
squarefree, multiplicity
-/
variables {R : Type*}
/-- An element of a monoid is squarefree if the only squares that
divide it are the squares of units. -/
def squarefree [monoid R] (r : R) : Prop := ∀ x : R, x * x ∣ r → is_unit x
@[simp]
lemma is_unit.squarefree [comm_monoid R] {x : R} (h : is_unit x) :
squarefree x :=
λ y hdvd, is_unit_of_mul_is_unit_left (is_unit_of_dvd_unit hdvd h)
@[simp]
lemma squarefree_one [comm_monoid R] : squarefree (1 : R) :=
is_unit_one.squarefree
@[simp]
lemma not_squarefree_zero [monoid_with_zero R] [nontrivial R] : ¬ squarefree (0 : R) :=
begin
erw [not_forall],
exact ⟨0, by simp⟩,
end
lemma squarefree.ne_zero [monoid_with_zero R] [nontrivial R] {m : R}
(hm : squarefree (m : R)) : m ≠ 0 :=
begin
rintro rfl,
exact not_squarefree_zero hm,
end
@[simp]
lemma irreducible.squarefree [comm_monoid R] {x : R} (h : irreducible x) :
squarefree x :=
begin
rintros y ⟨z, hz⟩,
rw mul_assoc at hz,
rcases h.is_unit_or_is_unit hz with hu | hu,
{ exact hu },
{ apply is_unit_of_mul_is_unit_left hu },
end
@[simp]
lemma prime.squarefree [cancel_comm_monoid_with_zero R] {x : R} (h : prime x) :
squarefree x :=
h.irreducible.squarefree
lemma squarefree.of_mul_left [comm_monoid R] {m n : R} (hmn : squarefree (m * n)) : squarefree m :=
(λ p hp, hmn p (dvd_mul_of_dvd_left hp n))
lemma squarefree.of_mul_right [comm_monoid R] {m n : R} (hmn : squarefree (m * n)) : squarefree n :=
(λ p hp, hmn p (dvd_mul_of_dvd_right hp m))
lemma squarefree.squarefree_of_dvd [comm_monoid R]
{x y : R} (hdvd : x ∣ y) (hsq : squarefree y) :
squarefree x :=
λ a h, hsq _ (h.trans hdvd)
section squarefree_gcd_of_squarefree
variables {α : Type*} [cancel_comm_monoid_with_zero α] [gcd_monoid α]
lemma squarefree.gcd_right (a : α) {b : α} (hb : squarefree b) :
squarefree (gcd a b) :=
hb.squarefree_of_dvd (gcd_dvd_right _ _)
lemma squarefree.gcd_left {a : α} (b : α) (ha : squarefree a) :
squarefree (gcd a b) :=
ha.squarefree_of_dvd (gcd_dvd_left _ _)
end squarefree_gcd_of_squarefree
namespace multiplicity
section comm_monoid
variables [comm_monoid R] [decidable_rel (has_dvd.dvd : R → R → Prop)]
lemma squarefree_iff_multiplicity_le_one (r : R) :
squarefree r ↔ ∀ x : R, multiplicity x r ≤ 1 ∨ is_unit x :=
begin
refine forall_congr (λ a, _),
rw [← sq, pow_dvd_iff_le_multiplicity, or_iff_not_imp_left, not_le, imp_congr _ iff.rfl],
simpa using part_enat.add_one_le_iff_lt (part_enat.coe_ne_top 1)
end
end comm_monoid
section cancel_comm_monoid_with_zero
variables [cancel_comm_monoid_with_zero R] [wf_dvd_monoid R]
lemma finite_prime_left {a b : R} (ha : prime a) (hb : b ≠ 0) :
multiplicity.finite a b :=
begin
classical,
revert hb,
refine wf_dvd_monoid.induction_on_irreducible b (by contradiction) (λ u hu hu', _)
(λ b p hb hp ih hpb, _),
{ rw [multiplicity.finite_iff_dom, multiplicity.is_unit_right ha.not_unit hu],
exact part_enat.dom_coe 0, },
{ refine multiplicity.finite_mul ha
(multiplicity.finite_iff_dom.mpr
(part_enat.dom_of_le_coe (show multiplicity a p ≤ ↑1, from _))) (ih hb),
norm_cast,
exact (((multiplicity.squarefree_iff_multiplicity_le_one p).mp hp.squarefree a)
.resolve_right ha.not_unit) }
end
end cancel_comm_monoid_with_zero
end multiplicity
section irreducible
variables [comm_monoid_with_zero R] [wf_dvd_monoid R]
lemma irreducible_sq_not_dvd_iff_eq_zero_and_no_irreducibles_or_squarefree (r : R) :
(∀ x : R, irreducible x → ¬ x * x ∣ r) ↔ ((r = 0 ∧ ∀ x : R, ¬irreducible x) ∨ squarefree r) :=
begin
symmetry,
split,
{ rintro (⟨rfl, h⟩ | h),
{ simpa using h },
intros x hx t,
exact hx.not_unit (h x t) },
intro h,
rcases eq_or_ne r 0 with rfl | hr,
{ exact or.inl (by simpa using h) },
right,
intros x hx,
by_contra i,
have : x ≠ 0,
{ rintro rfl,
apply hr,
simpa only [zero_dvd_iff, mul_zero] using hx},
obtain ⟨j, hj₁, hj₂⟩ := wf_dvd_monoid.exists_irreducible_factor i this,
exact h _ hj₁ ((mul_dvd_mul hj₂ hj₂).trans hx),
end
lemma squarefree_iff_irreducible_sq_not_dvd_of_ne_zero {r : R} (hr : r ≠ 0) :
squarefree r ↔ ∀ x : R, irreducible x → ¬ x * x ∣ r :=
by simpa [hr] using (irreducible_sq_not_dvd_iff_eq_zero_and_no_irreducibles_or_squarefree r).symm
lemma squarefree_iff_irreducible_sq_not_dvd_of_exists_irreducible
{r : R} (hr : ∃ (x : R), irreducible x) :
squarefree r ↔ ∀ x : R, irreducible x → ¬ x * x ∣ r :=
begin
rw [irreducible_sq_not_dvd_iff_eq_zero_and_no_irreducibles_or_squarefree, ←not_exists],
simp only [hr, not_true, false_or, and_false],
end
end irreducible
section is_radical
variables [cancel_comm_monoid_with_zero R]
theorem is_radical.squarefree {x : R} (h0 : x ≠ 0) (h : is_radical x) : squarefree x :=
begin
rintro z ⟨w, rfl⟩,
specialize h 2 (z * w) ⟨w, by simp_rw [pow_two, mul_left_comm, ← mul_assoc]⟩,
rwa [← one_mul (z * w), mul_assoc, mul_dvd_mul_iff_right, ← is_unit_iff_dvd_one] at h,
rw [mul_assoc, mul_ne_zero_iff] at h0, exact h0.2,
end
variable [gcd_monoid R]
theorem squarefree.is_radical {x : R} (hx : squarefree x) : is_radical x :=
(is_radical_iff_pow_one_lt 2 one_lt_two).2 $ λ y hy, and.right $ (dvd_gcd_iff x x y).1
begin
by_cases gcd x y = 0, { rw h, apply dvd_zero },
replace hy := ((dvd_gcd_iff x x _).2 ⟨dvd_rfl, hy⟩).trans gcd_pow_right_dvd_pow_gcd,
obtain ⟨z, hz⟩ := gcd_dvd_left x y,
nth_rewrite 0 hz at hy ⊢,
rw [pow_two, mul_dvd_mul_iff_left h] at hy,
obtain ⟨w, hw⟩ := hy,
exact (hx z ⟨w, by rwa [mul_right_comm, ←hw]⟩).mul_right_dvd.2 dvd_rfl,
end
theorem is_radical_iff_squarefree_or_zero {x : R} : is_radical x ↔ squarefree x ∨ x = 0 :=
⟨λ hx, (em $ x = 0).elim or.inr (λ h, or.inl $ hx.squarefree h),
or.rec squarefree.is_radical $ by { rintro rfl, rw zero_is_radical_iff, apply_instance }⟩
theorem is_radical_iff_squarefree_of_ne_zero {x : R} (h : x ≠ 0) : is_radical x ↔ squarefree x :=
⟨is_radical.squarefree h, squarefree.is_radical⟩
end is_radical
namespace unique_factorization_monoid
variables [cancel_comm_monoid_with_zero R] [unique_factorization_monoid R]
lemma squarefree_iff_nodup_normalized_factors [normalization_monoid R] [decidable_eq R] {x : R}
(x0 : x ≠ 0) : squarefree x ↔ multiset.nodup (normalized_factors x) :=
begin
have drel : decidable_rel (has_dvd.dvd : R → R → Prop),
{ classical,
apply_instance, },
haveI := drel,
rw [multiplicity.squarefree_iff_multiplicity_le_one, multiset.nodup_iff_count_le_one],
haveI := nontrivial_of_ne x 0 x0,
split; intros h a,
{ by_cases hmem : a ∈ normalized_factors x,
{ have ha := irreducible_of_normalized_factor _ hmem,
rcases h a with h | h,
{ rw ← normalize_normalized_factor _ hmem,
rw [multiplicity_eq_count_normalized_factors ha x0] at h,
assumption_mod_cast },
{ have := ha.1, contradiction, } },
{ simp [multiset.count_eq_zero_of_not_mem hmem] } },
{ rw or_iff_not_imp_right, intro hu,
by_cases h0 : a = 0,
{ simp [h0, x0] },
rcases wf_dvd_monoid.exists_irreducible_factor hu h0 with ⟨b, hib, hdvd⟩,
apply le_trans (multiplicity.multiplicity_le_multiplicity_of_dvd_left hdvd),
rw [multiplicity_eq_count_normalized_factors hib x0],
specialize h (normalize b),
assumption_mod_cast }
end
lemma dvd_pow_iff_dvd_of_squarefree {x y : R} {n : ℕ} (hsq : squarefree x) (h0 : n ≠ 0) :
x ∣ y ^ n ↔ x ∣ y :=
begin
classical,
haveI := unique_factorization_monoid.to_gcd_monoid R,
exact ⟨hsq.is_radical n y, λ h, h.pow h0⟩,
end
end unique_factorization_monoid
namespace int
@[simp] lemma squarefree_nat_abs {n : ℤ} : squarefree n.nat_abs ↔ squarefree n :=
by simp_rw [squarefree, nat_abs_surjective.forall, ←nat_abs_mul, nat_abs_dvd_iff_dvd,
is_unit_iff_nat_abs_eq, nat.is_unit_iff]
@[simp] lemma squarefree_coe_nat {n : ℕ} : squarefree (n : ℤ) ↔ squarefree n :=
by rw [←squarefree_nat_abs, nat_abs_of_nat]
end int
|
97ba2f4682f0cd9a22e1011ff9d54d8fb6810840 | 4d7079ae603c07560e99d1ce35876f769cbb3e24 | /src/cycles.lean | 703a51a20e5c97f5430892d0f359f7128a0efa36 | [] | no_license | chasenorman/Formalized-Voting | 72493a08aa09d98d0fb589731b842e2d08c991d0 | de04e630b83525b042db166670ba97f9952b5691 | refs/heads/main | 1,687,282,160,284 | 1,627,155,031,000 | 1,627,155,031,000 | 370,472,025 | 13 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,575 | lean | import tactic
import data.list.chain
import data.fintype.basic
import data.list.rotate
import data.list.basic
import tactic.omega
import data.nat.modeq
import tactic.zify
import data.stream.basic
open_locale classical
noncomputable theory
variables {X : Type}
def cycle := λ (P : X → X → Prop) (c : list X), ∃ (e : c ≠ list.nil), list.chain P (c.last e) c
def reverse := λ (P : X → X → Prop) (x y : X), P y x
def length_cycle_pos {l : list X} {P : X → X → Prop} (c : cycle P l) : 0 < l.length :=
begin
cases c with a b,
exact list.length_pos_of_ne_nil a,
end
-- updated acyclic definition.
def acyclic : (X → X → Prop) → Prop := λ P, ∀ (c : list X), ¬ cycle P c
lemma size_lemma {x : ℕ} (l : list X) (y : x < l.reverse.length) : l.length - 1 - x < l.length :=
begin
rw list.length_reverse at y,
omega,
end
lemma nth_reverse {x : ℕ} (l : list X) (y: x < l.reverse.length) : l.reverse.nth_le x y = l.nth_le (l.length - 1 - x) (size_lemma l y) :=
begin
have to_use := eq.symm (list.nth_le_reverse l.reverse x _ _),
rw to_use,
simp,
simp only [list.length_reverse],
exact size_lemma l y,
end
lemma nonempty_last (l : list X) (e : l.length > 0) : l.reverse ≠ list.nil :=
begin
rw eq.symm (list.length_reverse l) at e,
exact list.ne_nil_of_length_pos e,
end
lemma last_reverse (l : list X) (e : l.length > 0) : l.reverse.last (nonempty_last l e) = l.nth_le 0 e :=
begin
rw list.last_eq_nth_le,
rw nth_reverse,
have ineq : (l.length - 1 - (l.reverse.length - 1)) = 0,
rw list.length_reverse,
simp,
simp,
end
lemma head'_eq_nth_le_zero (l : list X) (y : X) (e : l ≠ list.nil) : y ∈ l.head' → y = (l.nth_le 0 (list.length_pos_of_ne_nil e)) :=
begin
intro a,
obviously,
rw ←list.nth_zero at a,
rw list.nth_le_nth (list.length_pos_of_ne_nil e) at a,
obviously,
end
lemma within_rotate_of_within {l : list X} {i : ℕ} (n : ℕ) (e : i < l.length) : i < (l.rotate n).length := by obviously
lemma ne_nil_of_lt_length {a b : ℕ} : a < b → b > 0 := by omega
lemma nth_le_rotate {l : list X} {n i : ℕ} (e : i < l.length) : ((l.rotate n).nth_le i (within_rotate_of_within n e)) = l.nth_le ((i + n) % l.length) (nat.mod_lt (i+n) (ne_nil_of_lt_length e)) :=
begin
have first := list.nth_rotate e,
work_on_goal 1 {exact n,},
rw list.nth_le_nth (within_rotate_of_within n e) at first,
rw list.nth_le_nth ((i + n).mod_lt (ne_nil_of_lt_length e)) at first,
obviously,
end
lemma rotate1_cycle_of_cycle {a : X} {l : list X} {P : X → X → Prop} : cycle P (a :: l) → cycle P (l ++ [a]) :=
begin
intro c,
unfold cycle at *,
cases c with _ c,
obviously,
change list.chain' P (a :: l ++ [a]),
apply list.chain'.append,
change list.chain' P (a :: l) at c_right,
exact c_right,
exact list.chain'_singleton a,
intros x x_mem y y_mem,
have i := list.mem_last'_eq_last x_mem,
cases i with _ i,
rw i,
obviously,
end
-- proof by induction? cycle (a :: l) iff cycle (l ++ [a]), list.rotate_cons_succ
lemma rotate'_cycle_of_cycle {c : list X} {P : X → X → Prop} {n : ℕ} : cycle P c → cycle P (list.rotate' c n) :=
begin
intro cy,
induction n,
rw list.rotate'_zero,
exact cy,
rw nat.succ_eq_add_one,
rw ←list.rotate'_rotate',
have i := n_ih,
cases i with n _,
have e := list.exists_cons_of_ne_nil n,
cases e with a e,
cases e with l e,
rw e,
rw list.rotate'_cons_succ,
rw list.rotate'_zero,
rw e at n_ih,
exact rotate1_cycle_of_cycle n_ih,
end
lemma dominate_ineq1 (i n : ℕ) : ¬(i = 0) → (i < n → i - 1 < n - 1) := by omega
lemma dominate_ineq2 (i : ℕ) : ¬(i = 0) → (i - 1 + 1) = i := by omega
lemma ineq4 (i n : ℕ) (e : i < n) : i.pred < n :=
begin
rw nat.pred_eq_sub_one i,
omega,
end
lemma ineq5 (i n : ℕ) (e : i < n) (z: ¬i = n - 1) : i < n - 1 := by omega
-- every node in a cycle is defeated by some other node in that cycle.
lemma dominate_of_cycle (l : list X) (P : X → X → Prop) (c : cycle P l) : ∀ x ∈ l, ∃ y ∈ l, P y x :=
begin
intro x, -- for any element x
intro mem, -- and a proof that x is in the list
unfold cycle at c,
cases c with e c,
rw list.chain_iff_nth_le at c,
cases c with c_right c_left,
let i := l.index_of x,
have i_bound : i < l.length,
apply list.index_of_lt_length.mpr,
exact mem,
by_cases z : i = 0,
{use (l.last e),
use list.last_mem e,
rw ←(list.index_of_nth_le i_bound),
change P (l.last e) (l.nth_le i i_bound),
simp_rw z,
exact (c_right (eq.rec i_bound z)),},
{use l.nth_le (i - 1) ((ineq4 i l.length) i_bound),
use l.nth_le_mem (i - 1) ((ineq4 i l.length) i_bound),
specialize c_left (i - 1),
specialize c_left ((dominate_ineq1 i l.length) z i_bound),
simp_rw (dominate_ineq2 i z) at c_left,
rw ←(list.index_of_nth_le i_bound),
change P (l.nth_le (i - 1) _) (l.nth_le i i_bound),
exact c_left,},
end
lemma succ_pred {i : ℕ} (e : 0 < i) : i - 1 + 1 = i := by omega
lemma dominate_ineq3 {a b : ℕ} (e : 0 < b) : a < b - 1 → a + 1 < b := by omega
-- have defeats := dominates_of_cycle X c (split_cycle_VCCR_function V X P) cy mini mini_mem,
lemma dominates_of_cycle_index (l : list X) (P : X → X → Prop) (c : cycle P l) (i : ℕ) (i_bound : i < l.length)
: P (l.nth_le i i_bound) (l.nth_le ((i + 1) % l.length) (nat.mod_lt (i + 1) (length_cycle_pos c))) :=
begin
unfold cycle at c,
cases c with e c,
rw list.chain_iff_nth_le at c,
cases c with c_left c_right,
by_cases z : i = l.length - 1,
{simp_rw z, rw ←list.last_eq_nth_le l e,
specialize c_left (list.length_pos_of_ne_nil e),
simp_rw succ_pred (list.length_pos_of_ne_nil e),
simp_rw nat.mod_self,
exact c_left,},
specialize c_right i,
have i_bound2 := ineq5 i l.length i_bound z,
specialize c_right i_bound2,
have underflow : (i + 1) % l.length = (i + 1),
rw nat.mod_eq_of_lt,
exact dominate_ineq3 (list.length_pos_of_ne_nil e) i_bound2,
simp_rw underflow,
exact c_right,
end
lemma dominates_of_cycle (l : list X) (P : X → X → Prop) (c : cycle P l) : ∀ x ∈ l, ∃ y ∈ l, P x y :=
begin
intro x,
intro mem,
let i := l.index_of x,
have d := dominates_of_cycle_index l P c,
specialize d i,
specialize d (list.index_of_lt_length.mpr mem),
use (l.nth_le ((i + 1) % l.length) ((i + 1).mod_lt (length_cycle_pos c))),
split,
apply list.nth_le_mem,
simp_rw list.index_of_nth_le at d,
exact d,
end
lemma cycle_reverse_in_reverse_relation (P : X → X → Prop) (l : list X) (c : cycle P l) : cycle (reverse P) (l.reverse) :=
begin
obviously, -- handles proof of reverse ne nil,
rw list.chain_iff_nth_le,
rw list.chain_iff_nth_le at c_h,
obviously, -- performs the necessary splitting and rewriting
rw last_reverse l (list.length_pos_of_ne_nil c_w),
rw nth_reverse,
simp_rw nat.sub_zero,
rw ←list.last_eq_nth_le,
specialize c_h_left (list.length_pos_of_ne_nil c_w),
exact c_h_left,
rw nth_reverse,
rw nth_reverse,
simp [reverse],
specialize c_h_right (l.length - 1 - (i + 1)),
have o : ∀ n, (i < n - 1) → n - 1 - (i + 1) < n - 1 := by omega,
specialize c_h_right (o l.length h),
have o : ∀ n, (i < n - 1) → (n - 1 - (i + 1) + 1) = (n - 1 - i) := by omega,
simp_rw (o l.length h) at c_h_right,
exact c_h_right,
end
noncomputable def to_path : list X → list X
| list.nil := list.nil
| (list.cons u p) :=
let p' := to_path p
in if p'.index_of u < p'.length
then (p'.drop (p'.index_of u))
else (list.cons u p')
lemma ite_left_if {α : Type} {p : Prop} [decidable p] {a b : α} : p → ite p a b = a := by obviously
lemma ite_right_if {α : Type} {p : Prop} [decidable p] {a b : α} : ¬ p → ite p a b = b := by obviously
lemma nodup_drop_of_nodup {l : list X} {n : ℕ} : l.nodup → (l.drop n).nodup :=
begin
by_cases n < l.length,
rw list.nodup_iff_nth_le_inj,
rw list.nodup_iff_nth_le_inj,
intros a i j h₁ h₂,
rw list.nth_le_drop',
rw list.nth_le_drop',
intro eq,
specialize a (n+i),
specialize a (n+j),
rw list.length_drop at h₁,
rw list.length_drop at h₂,
have o : ∀ (a b c : ℕ), c < b → a < b - c → c + a < b := by omega,
specialize a (o i l.length n h h₁),
specialize a (o j l.length n h h₂),
specialize a eq,
exact (add_right_inj n).mp a,
push_neg at h,
intro a,
have sub : (list.drop n l).length = 0,
rw list.length_drop,
omega,
rw (list.eq_nil_of_length_eq_zero sub),
exact list.nodup_nil,
end
lemma to_path_nodup (l : list X) : (to_path l).nodup :=
begin
induction l,
exact list.nodup_nil,
simp [to_path],
by_cases (list.index_of l_hd (to_path l_tl) < (to_path l_tl).length),
simp_rw (ite_left_if h),
exact nodup_drop_of_nodup l_ih,
simp_rw (ite_right_if h),
have not_mem : l_hd ∉ (to_path l_tl),
contrapose h,
push_neg at h, push_neg,
exact list.index_of_lt_length.mpr h,
exact list.nodup_cons_of_nodup not_mem l_ih,
end
lemma to_path_eq_nil_iff (l : list X) : (to_path l) = list.nil ↔ l = list.nil :=
begin
induction l,
obviously,
simp [to_path] at ᾰ,
contrapose ᾰ,
by_cases (list.index_of l_hd (to_path l_tl) < (to_path l_tl).length),
apply list.ne_nil_of_length_pos,
rw (ite_left_if h),
rw list.length_drop,
have ineq : ∀ (a b : ℕ), a < b → 0 < b - a := by omega,
exact ineq (list.index_of l_hd (to_path l_tl)) ((to_path l_tl).length) h,
rw (ite_right_if h),
exact list.cons_ne_nil (l_hd) (to_path l_tl),
end
lemma helper (X : Type) (l : list X) (n : l ≠ list.nil) : 0 < (to_path l).length :=
begin
apply list.length_pos_of_ne_nil,
contrapose n,
push_neg, push_neg at n,
exact (to_path_eq_nil_iff l).mp n,
end
lemma to_path_first_elem (X : Type) (l : list X) (n : l ≠ list.nil) : (list.nth_le (to_path l) 0 (helper X l n)) = (list.nth_le l 0 (list.length_pos_of_ne_nil n)) :=
begin
induction l,
obviously,
simp [to_path],
by_cases (list.index_of l_hd (to_path l_tl) < (to_path l_tl).length),
simp_rw (ite_left_if h),
rw list.nth_le_drop',
simp_rw nat.add_zero,
rw list.index_of_nth_le,
simp_rw (ite_right_if h),
obviously,
end
lemma helper' (X : Type) (l : list X) (n: 0 < (to_path l).length) : l ≠ list.nil :=
begin
contrapose n,
push_neg at n,
have a := (to_path_eq_nil_iff l).mpr n,
contrapose a,
push_neg at a,
exact list.ne_nil_of_length_pos a,
end
lemma to_path_first_elem' (X : Type) (l : list X) (n : (to_path l).length > 0) : (list.nth_le (to_path l) 0 n) = (list.nth_le l 0 (list.length_pos_of_ne_nil (helper' X l n))) :=
begin
induction l,
obviously,
simp [to_path],
by_cases (list.index_of l_hd (to_path l_tl) < (to_path l_tl).length),
simp_rw (ite_left_if h),
rw list.nth_le_drop',
simp_rw nat.add_zero,
rw list.index_of_nth_le,
simp_rw (ite_right_if h),
obviously,
end
lemma to_path_ne_nil_iff (l : list X) (n : l ≠ list.nil) : (to_path l) ≠ list.nil :=
begin
by_contradiction,
push_neg at h,
have test := (to_path_eq_nil_iff l).mp h,
exact n test,
end
-- list.index_of l_hd (to_path l_tl) + ((to_path l_tl).length - list.index_of l_hd (to_path l_tl) - 1) = (to_path l_tl).length - 1
lemma last_elem_lemma {a b : ℕ} : (a < b) → a + (b - a - 1) = b - 1 := by omega
lemma to_path_last_elem (l : list X) (n : l ≠ list.nil) : ((to_path l).last (to_path_ne_nil_iff l n)) = (l.last n) :=
begin
induction l,
obviously,
simp [to_path],
by_cases (list.index_of l_hd (to_path l_tl) < (to_path l_tl).length),
simp_rw (ite_left_if h),
rw list.last_eq_nth_le,
simp_rw list.length_drop,
rw list.nth_le_drop',
simp_rw last_elem_lemma h,
have to_path_ne_nil : (to_path l_tl) ≠ list.nil,
apply list.ne_nil_of_length_pos,
have pos_of_lt : ∀ (a b : ℕ), a < b → 0 < b := by omega,
exact pos_of_lt (list.index_of l_hd (to_path l_tl)) (to_path l_tl).length h,
have to_path_ne_nil := (not_iff_not_of_iff (to_path_eq_nil_iff l_tl)).mp to_path_ne_nil,
specialize l_ih to_path_ne_nil,
rw ←list.last_eq_nth_le (to_path l_tl) (to_path_ne_nil_iff l_tl to_path_ne_nil),
rw l_ih,
exact (eq.symm (list.last_cons n to_path_ne_nil)),
simp_rw (ite_right_if h),
induction l_tl,
obviously,
rw list.last_cons,
exact l_ih,
end
lemma drop_chain'_of_chain' {X : Type} {l : list X} {P : X → X → Prop} {n : ℕ} : l.chain' P → (l.drop n).chain' P :=
begin
by_cases n < l.length,
rw list.chain'_iff_nth_le,
rw list.chain'_iff_nth_le,
intros a i t,
rw list.nth_le_drop',
rw list.nth_le_drop',
rw list.length_drop at t,
specialize a (n + i),
have o : ∀ (n i l : ℕ), n < l → i < l - n - 1 → n + i < l - 1 := by omega,
specialize a (o n i l.length h t),
exact a,
push_neg at h,
intro a,
have sub : (list.drop n l).length = 0,
rw list.length_drop,
omega,
rw (list.eq_nil_of_length_eq_zero sub),
exact list.chain'_nil,
end
lemma nth_le_cons {l : list X} {i : ℕ} {e : (i - 1) < l.length} {a : X} {p : i < (a :: l).length} (n : ¬ i = 0) : ((a :: l).nth_le i p) = (l.nth_le (i - 1) e) :=
begin
let j := i - 1,
change (a :: l).nth_le (i) p = l.nth_le j e,
change (a :: l).nth_le (i) p = (a :: l).nth_le (j + 1) _,
congr,
change i = i - 1 + 1,
omega,
dsimp at *, simp at *, assumption,
end
lemma to_path_chain'_of_chain' {X : Type} {l : list X} {P : X → X → Prop} : list.chain' P l → list.chain' P (to_path l) :=
begin
intro a,
induction l,
obviously,
simp [to_path],
specialize l_ih (and.right (list.chain'_cons'.mp a)),
by_cases (list.index_of l_hd (to_path l_tl) < (to_path l_tl).length),
simp_rw (ite_left_if h),
exact drop_chain'_of_chain' l_ih,
simp_rw (ite_right_if h),
by_cases j : l_tl = list.nil,
rw (to_path_eq_nil_iff l_tl).mpr j,
exact list.chain'_singleton l_hd,
rw list.chain'_iff_nth_le,
rw list.chain'_iff_nth_le at l_ih,
rw list.chain'_iff_nth_le at a,
intros i i_bounds,
by_cases i = 0,
simp_rw h,
rw [list.nth_le], rw [list.nth_le],
specialize a 0,
have a_proof : 0 < (l_hd :: l_tl).length - 1,
rw list.length_cons,
simp only [nat.add_succ_sub_one, add_zero],
exact (list.length_pos_of_ne_nil j),
specialize a a_proof,
rw [list.nth_le] at a, rw [list.nth_le] at a,
have x := (to_path_first_elem X l_tl j),
have z : (to_path l_tl).nth_le 0 (helper X l_tl j) = (to_path l_tl).nth_le 0 (list.nth_le._main._proof_1 l_hd (to_path l_tl) 0
(eq.rec (nat.lt_pred_iff.mp i_bounds)
((λ [c : has_add ℕ] (ᾰ ᾰ_1 : ℕ) (e_2 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : ℕ) (e_3 : ᾰ_2 = ᾰ_3),
congr (congr_arg has_add.add e_2) e_3) i 0 h 1 1 (eq.refl 1)))),
refl,
rw z at x,
rw x,
exact a,
rw [list.nth_le],
specialize l_ih (i - 1),
rw list.length_cons at i_bounds,
simp only [nat.add_succ_sub_one, add_zero] at i_bounds,
have o : ∀ i n, ¬ i = 0 → i < n → i - 1 < n - 1 := by omega,
specialize l_ih (o i (to_path l_tl).length h i_bounds),
rw nth_le_cons h,
have o : ∀ i, ¬ i = 0 → i - 1 + 1 = i := by omega,
simp_rw (o i h) at l_ih,
exact l_ih,
end
lemma rotate'_eq_nil_iff (X : Type) (l : list X) (n : ℕ) : l.rotate' n = list.nil ↔ l = list.nil :=
begin
have a := list.length_eq_zero,
work_on_goal 2 {
exact l,
},
rw ←a,
have a := list.length_eq_zero,
work_on_goal 2 {
exact l.rotate' n,
},
rw ←a,
rw list.length_rotate' l n,
end
lemma cycle_of_cycle_imp {X : Type} {l : list X} {p₁ p₂ : X → X → Prop} (e : ∀ x y, p₁ x y → p₂ x y) : cycle p₁ l → cycle p₂ l :=
begin
obviously,
exact list.chain.imp e ᾰ_h,
end
lemma chain'_of_chain'_append {x : list X} {y : list X} {P : X → X → Prop} (e : list.chain' P (x ++ y)) : list.chain' P x :=
begin
rw list.chain'_iff_nth_le, rw list.chain'_iff_nth_le at e,
intros i h,
specialize e i,
have o : ∀ a b c, a < b - 1 → a < b + c - 1 := by omega,
have t := (o i x.length y.length h),
rw ←list.length_append at t,
specialize e t,
rw list.nth_le_append (nat.lt_of_lt_pred t) (nat.lt_of_lt_pred h) at e,
rw list.nth_le_append at e,
exact e,
end
lemma chain'_take_of_chain {l : list X} {P : X → X → Prop} (a : l ≠ list.nil) {n : ℕ} (c : list.chain P (l.last a) l) : list.chain' P (l.take n) :=
begin
change list.chain' P ((l.last a) :: l) at c,
rw list.chain'_cons' at c,
cases c with _ c,
rw ←(list.take_append_drop n l) at c,
let y := (list.drop n l),
change list.chain' P (list.take n l ++ y) at c,
exact chain'_of_chain'_append c,
end
lemma nth_take_ineq {a b c : ℕ} (d : a < b) (e : c = b) : (a < c) :=
begin
have e := eq.symm e,
rw e at d,
exact d,
end
lemma nth_take {X : Type} {n x : ℕ} (e : x < n) (s : stream X) : ((s.take n).nth_le x (nth_take_ineq e (s.length_take n))) = (s.nth x) :=
begin
unfold stream.take,
rw list.nth_le_map,
rw list.nth_le_range,
rw list.length_range,
exact e,
end |
d897a9d988b142de098c912da4cfafba43a4a28c | 737dc4b96c97368cb66b925eeea3ab633ec3d702 | /src/Init/System/IOError.lean | 503963bb8443e21bdad178b88618a9c1cb3a3412 | [
"Apache-2.0"
] | permissive | Bioye97/lean4 | 1ace34638efd9913dc5991443777b01a08983289 | bc3900cbb9adda83eed7e6affeaade7cfd07716d | refs/heads/master | 1,690,589,820,211 | 1,631,051,000,000 | 1,631,067,598,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,941 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
prelude
import Init.Core
import Init.Data.UInt
import Init.Data.ToString.Basic
import Init.Data.String.Basic
/-
Imitate the structure of IOErrorType in Haskell:
https://hackage.haskell.org/package/base-4.12.0.0/docs/System-IO-Error.html#t:IOErrorType
-/
inductive IO.Error where
| alreadyExists (filename : Option String) (osCode : UInt32) (details : String) -- EEXIST, EINPROGRESS, EISCONN
| otherError (osCode : UInt32) (details : String) -- EFAULT, default
| resourceBusy (osCode : UInt32) (details : String)
-- EADDRINUSE, EBUSY, EDEADLK, ETXTBSY
| resourceVanished (osCode : UInt32) (details : String)
-- ECONNRESET, EIDRM, ENETDOWN, ENETRESET,
-- ENOLINK, EPIPE
| unsupportedOperation (osCode : UInt32) (details : String)
-- EADDRNOTAVAIL, EAFNOSUPPORT, ENODEV, ENOPROTOOPT
-- ENOSYS, EOPNOTSUPP, ERANGE, ESPIPE, EXDEV
| hardwareFault (osCode : UInt32) (details : String) -- EIO
| unsatisfiedConstraints (osCode : UInt32) (details : String) -- ENOTEMPTY
| illegalOperation (osCode : UInt32) (details : String) -- ENOTTY
| protocolError (osCode : UInt32) (details : String)
-- EPROTO, EPROTONOSUPPORT, EPROTOTYPE
| timeExpired (osCode : UInt32) (details : String)
-- ETIME, ETIMEDOUT
| interrupted (filename : String) (osCode : UInt32) (details : String) -- EINTR
| noFileOrDirectory (filename : String) (osCode : UInt32) (details : String) -- ENOENT
| invalidArgument (filename : Option String) (osCode : UInt32) (details : String)
-- ELOOP, ENAMETOOLONG, EDESTADDRREQ, EILSEQ, EINVAL, EDOM, EBADF
-- ENOEXEC, ENOSTR, ENOTCONN, ENOTSOCK
| permissionDenied (filename : Option String) (osCode : UInt32) (details : String)
-- EACCES, EROFS, ECONNABORTED, EFBIG, EPERM
| resourceExhausted (filename : Option String) (osCode : UInt32) (details : String)
-- EMFILE, ENFILE, ENOSPC, E2BIG, EAGAIN, EMLINK:
-- EMSGSIZE, ENOBUFS, ENOLCK, ENOMEM, ENOSR:
| inappropriateType (filename : Option String) (osCode : UInt32) (details : String)
-- EISDIR, EBADMSG, ENOTDIR:
| noSuchThing (filename : Option String) (osCode : UInt32) (details : String)
-- ENXIO, EHOSTUNREACH, ENETUNREACH, ECHILD, ECONNREFUSED,
-- ENODATA, ENOMSG, ESRCH
| unexpectedEof
| userError (msg : String)
deriving Inhabited
@[export mk_io_user_error]
def IO.userError (s : String) : IO.Error :=
IO.Error.userError s
instance : Coe String IO.Error := ⟨IO.userError⟩
namespace IO.Error
@[export lean_mk_io_error_already_exists_file]
def mkAlreadyExistsFile : String → UInt32 → String → IO.Error :=
alreadyExists ∘ some
@[export lean_mk_io_error_eof]
def mkEofError : Unit → IO.Error := fun _ =>
unexpectedEof
@[export lean_mk_io_error_inappropriate_type_file]
def mkInappropriateTypeFile : String → UInt32 → String → IO.Error :=
inappropriateType ∘ some
@[export lean_mk_io_error_interrupted]
def mkInterrupted : String → UInt32 → String → IO.Error :=
interrupted
@[export lean_mk_io_error_invalid_argument_file]
def mkInvalidArgumentFile : String → UInt32 → String → IO.Error :=
invalidArgument ∘ some
@[export lean_mk_io_error_no_file_or_directory]
def mkNoFileOrDirectory : String → UInt32 → String → IO.Error :=
noFileOrDirectory
@[export lean_mk_io_error_no_such_thing_file]
def mkNoSuchThingFile : String → UInt32 → String → IO.Error :=
noSuchThing ∘ some
@[export lean_mk_io_error_permission_denied_file]
def mkPermissionDeniedFile : String → UInt32 → String → IO.Error :=
permissionDenied ∘ some
@[export lean_mk_io_error_resource_exhausted_file]
def mkResourceExhaustedFile : String → UInt32 → String → IO.Error :=
resourceExhausted ∘ some
@[export lean_mk_io_error_unsupported_operation]
def mkUnsupportedOperation : UInt32 → String → IO.Error :=
unsupportedOperation
@[export lean_mk_io_error_resource_exhausted]
def mkResourceExhausted : UInt32 → String → IO.Error :=
resourceExhausted none
@[export lean_mk_io_error_already_exists]
def mkAlreadyExists : UInt32 → String → IO.Error :=
alreadyExists none
@[export lean_mk_io_error_inappropriate_type]
def mkInappropriateType : UInt32 → String → IO.Error :=
inappropriateType none
@[export lean_mk_io_error_no_such_thing]
def mkNoSuchThing : UInt32 → String → IO.Error :=
noSuchThing none
@[export lean_mk_io_error_resource_vanished]
def mkResourceVanished : UInt32 → String → IO.Error :=
resourceVanished
@[export lean_mk_io_error_resource_busy]
def mkResourceBusy : UInt32 → String → IO.Error :=
resourceBusy
@[export lean_mk_io_error_invalid_argument]
def mkInvalidArgument : UInt32 → String → IO.Error :=
invalidArgument none
@[export lean_mk_io_error_other_error]
def mkOtherError : UInt32 → String → IO.Error :=
otherError
@[export lean_mk_io_error_permission_denied]
def mkPermissionDenied : UInt32 → String → IO.Error :=
permissionDenied none
@[export lean_mk_io_error_hardware_fault]
def mkHardwareFault : UInt32 → String → IO.Error :=
hardwareFault
@[export lean_mk_io_error_unsatisfied_constraints]
def mkUnsatisfiedConstraints : UInt32 → String → IO.Error :=
unsatisfiedConstraints
@[export lean_mk_io_error_illegal_operation]
def mkIllegalOperation : UInt32 → String → IO.Error :=
illegalOperation
@[export lean_mk_io_error_protocol_error]
def mkProtocolError : UInt32 → String → IO.Error :=
protocolError
@[export lean_mk_io_error_time_expired]
def mkTimeExpired : UInt32 → String → IO.Error :=
timeExpired
private def downCaseFirst (s : String) : String := s.modify 0 Char.toLower
def fopenErrorToString (gist fn : String) (code : UInt32) : Option String → String
| some details => downCaseFirst gist ++ " (error code: " ++ toString code ++ ", " ++ downCaseFirst details ++ ")\n file: " ++ fn
| none => downCaseFirst gist ++ " (error code: " ++ toString code ++ ")\n file: " ++ fn
def otherErrorToString (gist : String) (code : UInt32) : Option String → String
| some details => downCaseFirst gist ++ " (error code: " ++ toString code ++ ", " ++ downCaseFirst details ++ ")"
| none => downCaseFirst gist ++ " (error code: " ++ toString code ++ ")"
@[export lean_io_error_to_string]
def toString : IO.Error → String
| unexpectedEof => "end of file"
| inappropriateType (some fn) code details => fopenErrorToString "inappropriate type" fn code details
| inappropriateType none code details => otherErrorToString "inappropriate type" code details
| interrupted fn code details => fopenErrorToString "interrupted system call" fn code details
| invalidArgument (some fn) code details => fopenErrorToString "invalid argument" fn code details
| invalidArgument none code details => otherErrorToString "invalid argument" code details
| noFileOrDirectory fn code _ => fopenErrorToString "no such file or directory" fn code none
| noSuchThing (some fn) code details => fopenErrorToString "no such thing" fn code details
| noSuchThing none code details => otherErrorToString "no such thing" code details
| permissionDenied (some fn) code details => fopenErrorToString details fn code none
| permissionDenied none code details => otherErrorToString details code none
| resourceExhausted (some fn) code details => fopenErrorToString "resource exhausted" fn code details
| resourceExhausted none code details => otherErrorToString "resource exhausted" code details
| alreadyExists none code details => otherErrorToString "already exists" code details
| alreadyExists (some fn) code details => fopenErrorToString "already exists" fn code details
| otherError code details => otherErrorToString details code none
| resourceBusy code details => otherErrorToString "resource busy" code details
| resourceVanished code details => otherErrorToString "resource vanished" code details
| hardwareFault code _ => otherErrorToString "hardware fault" code none
| illegalOperation code details => otherErrorToString "illegal operation" code details
| protocolError code details => otherErrorToString "protocol error" code details
| timeExpired code details => otherErrorToString "time expired" code details
| unsatisfiedConstraints code _ => otherErrorToString "directory not empty" code none
| unsupportedOperation code details => otherErrorToString "unsupported operation" code details
| userError msg => msg
instance : ToString IO.Error := ⟨ IO.Error.toString ⟩
end IO.Error
|
1bf8d7ef05bffbb6c6b5b2eb5421915aad2bbdcd | 05b503addd423dd68145d68b8cde5cd595d74365 | /test/coinductive.lean | 05c48bda47ba9f5fb1a21f9372aa09b290f6e95c | [
"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 | 5,300 | lean | /- test cases for coinductive predicates -/
import data.stream meta.coinductive_predicates
universe u
coinductive all_stream {α : Type u} (s : set α) : stream α → Prop
| step {} : ∀{a : α} {ω : stream α}, a ∈ s → all_stream ω → all_stream (a :: ω)
example : Π {α : Type u}, set α → stream α → Prop :=
@all_stream
example : ∀ {α : Type u} {s : set α} {a : α} {ω : stream α}, a ∈ s → all_stream s ω → all_stream s (a :: ω) :=
@all_stream.step
example : ∀ {α : Type u} (s : set α) {a : stream α}, all_stream s a → all_stream.functional s (all_stream s) a :=
@all_stream.destruct
example : ∀ {α : Type u} (s : set α) (C : stream α → Prop) {a : stream α},
C a →
(∀ (a : stream α), C a → (∃ {a_1 : α} {ω : stream α}, a_1 ∈ s ∧ C ω ∧ a_1 :: ω = a)) →
all_stream s a :=
@all_stream.corec_on
example : ∀ {α : Type u} (s : set α) (C : stream α → Prop),
(∀ (a : stream α), C a → all_stream.functional s C a) → ∀ (a : stream α), C a → all_stream s a :=
@all_stream.corec_functional
coinductive all_stream' {α : Type u} (s : set α) : stream α → Prop
| step {} : ∀{ω : stream α}, stream.head ω ∈ s → all_stream' (stream.tail ω) → all_stream' ω
coinductive alt_stream : stream bool → Prop
| tt_step : ∀{ω : stream bool}, alt_stream (ff :: ω) → alt_stream (tt :: ff :: ω)
| ff_step : ∀{ω : stream bool}, alt_stream (tt :: ω) → alt_stream (ff :: tt :: ω)
example : stream bool → Prop := @alt_stream
example : ∀ {ω : stream bool}, alt_stream (ff :: ω) → alt_stream (tt :: ff :: ω) :=
@alt_stream.tt_step
example : ∀ {ω : stream bool}, alt_stream (tt :: ω) → alt_stream (ff :: tt :: ω) :=
@alt_stream.ff_step
example : ∀ (C : stream bool → Prop),
(∀ (a : stream bool), C a → alt_stream.functional C a) → ∀ (a : stream bool), C a → alt_stream a :=
@alt_stream.corec_functional
mutual coinductive tt_stream, ff_stream
with tt_stream : stream bool → Prop
| step {} : ∀{ω : stream bool}, ff_stream ω → tt_stream (stream.cons tt ω)
with ff_stream : stream bool → Prop
| step {} : ∀{ω : stream bool}, tt_stream ω → ff_stream (stream.cons ff ω)
example : stream bool → Prop := @tt_stream
example : stream bool → Prop := @ff_stream
example : ∀ (C_tt_stream C_ff_stream : stream bool → Prop),
(∀ (a : stream bool), C_tt_stream a → tt_stream.functional C_tt_stream C_ff_stream a) →
(∀ (a : stream bool), C_ff_stream a → ff_stream.functional C_tt_stream C_ff_stream a) →
∀ (a : stream bool), C_tt_stream a → tt_stream a :=
@tt_stream.corec_functional
example : ∀ (C_tt_stream C_ff_stream : stream bool → Prop),
(∀ (a : stream bool), C_tt_stream a → tt_stream.functional C_tt_stream C_ff_stream a) →
(∀ (a : stream bool), C_ff_stream a → ff_stream.functional C_tt_stream C_ff_stream a) →
∀ (a : stream bool), C_ff_stream a → ff_stream a :=
@ff_stream.corec_functional
mutual coinductive tt_ff_stream, ff_tt_stream
with tt_ff_stream : stream bool → Prop
| step {} : ∀{ω : stream bool}, tt_ff_stream ω ∨ ff_tt_stream ω → tt_ff_stream (stream.cons tt ω)
with ff_tt_stream : stream bool → Prop
| step {} : ∀{ω : stream bool}, ff_tt_stream ω ∨ tt_ff_stream ω → ff_tt_stream (stream.cons ff ω)
inductive all_list {α : Type} (p : α → Prop) : list α → Prop
| nil : all_list []
| cons : ∀a xs, p a → all_list xs → all_list (a :: xs)
@[monotonicity]
lemma monotonicity.all_list {α : Type} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) :
∀xs, implies (all_list p xs) (all_list q xs)
| ._ (all_list.nil ._) := all_list.nil _
| ._ (all_list.cons a xs ha hxs) := all_list.cons _ _ (h a ha) (monotonicity.all_list _ hxs)
mutual coinductive walk_a, walk_b {α β : Type} (f : α → list β) (g : β → α) (p : α → Prop) (t : α → Prop)
with walk_a : α → Prop
| step : ∀a, all_list walk_b (f a) → p a → walk_a a
| term : ∀a, t a → walk_a a
with walk_b : β → Prop
| step : ∀b, walk_a (g b) → walk_b b
example : ∀ {α β : Type} (f : α → list β) (g : β → α) (p t C_walk_a : α → Prop) (C_walk_b : β → Prop)
{a : α},
C_walk_a a →
(∀ (a : α), C_walk_a a → all_list C_walk_b (f a) ∧ p a ∨ t a) →
(∀ (a : β), C_walk_b a → C_walk_a (g a)) → walk_a f g p t a :=
@walk_a.corec_on
coinductive walk_list {α : Type} (f : α → list α) (p : α → Prop) : ℕ → α → Prop
| step : ∀n a, all_list (walk_list n) (f a) → p a → walk_list (n + 1) a
example {f : ℕ → list ℕ} {a' : ℕ} {n : ℕ} {a : fin n} : true :=
begin
suffices : walk_list f (λ a'', a'' = a') (n + 1) a', {trivial},
coinduction walk_list.corec_on generalizing a n,
show ∃ (n : ℕ),
all_list (λ (a : ℕ), ∃ {n_1 : ℕ} {a_1 : fin n_1}, n_1 + 1 = n ∧ a' = a) (f a') ∧
a' = a' ∧ n + 1 = w + 1,
admit
end
coinductive coind_foo : list ℕ → Prop
| mk : ∀ xs, (∀ k l m, coind_foo (k::l::m::xs)) → coind_foo xs
meta example : true :=
begin
success_if_fail { let := compact_relation },
trivial
end
import_private compact_relation from tactic.coinduction
meta example : true :=
begin
let := compact_relation,
trivial
end
|
3fa7bf775c102fe9c315decc299aab9a4120cf93 | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/real/irrational.lean | 74d28f0653f307d40dc6e9c9951550d9c91a030d | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 9,302 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Yury Kudryashov.
-/
import data.real.sqrt
import data.rat.sqrt
import ring_theory.int.basic
import data.polynomial.eval
import data.polynomial.degree
import tactic.interval_cases
/-!
# Irrational real numbers
In this file we define a predicate `irrational` on `ℝ`, prove that the `n`-th root of an integer
number is irrational if it is not integer, and that `sqrt q` is irrational if and only if
`rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q`.
We also provide dot-style constructors like `irrational.add_rat`, `irrational.rat_sub` etc.
-/
open rat real multiplicity
/-- A real number is irrational if it is not equal to any rational number. -/
def irrational (x : ℝ) := x ∉ set.range (coe : ℚ → ℝ)
lemma irrational_iff_ne_rational (x : ℝ) : irrational x ↔ ∀ a b : ℤ, x ≠ a / b :=
by simp only [irrational, rat.forall, cast_mk, not_exists, set.mem_range, cast_coe_int, cast_div,
eq_comm]
/-!
### Irrationality of roots of integer and rational numbers
-/
/-- If `x^n`, `n > 0`, is integer and is not the `n`-th power of an integer, then
`x` is irrational. -/
theorem irrational_nrt_of_notint_nrt {x : ℝ} (n : ℕ) (m : ℤ)
(hxr : x ^ n = m) (hv : ¬ ∃ y : ℤ, x = y) (hnpos : 0 < n) :
irrational x :=
begin
rintros ⟨⟨N, D, P, C⟩, rfl⟩,
rw [← cast_pow] at hxr,
have c1 : ((D : ℤ) : ℝ) ≠ 0,
{ rw [int.cast_ne_zero, int.coe_nat_ne_zero], exact ne_of_gt P },
have c2 : ((D : ℤ) : ℝ) ^ n ≠ 0 := pow_ne_zero _ c1,
rw [num_denom', cast_pow, cast_mk, div_pow, div_eq_iff_mul_eq c2,
← int.cast_pow, ← int.cast_pow, ← int.cast_mul, int.cast_inj] at hxr,
have hdivn : ↑D ^ n ∣ N ^ n := dvd.intro_left m hxr,
rw [← int.dvd_nat_abs, ← int.coe_nat_pow, int.coe_nat_dvd, int.nat_abs_pow,
nat.pow_dvd_pow_iff hnpos] at hdivn,
have hD : D = 1 := by rw [← nat.gcd_eq_right hdivn, C.gcd_eq_one],
subst D,
refine hv ⟨N, _⟩,
rw [num_denom', int.coe_nat_one, mk_eq_div, int.cast_one, div_one, cast_coe_int]
end
/-- If `x^n = m` is an integer and `n` does not divide the `multiplicity p m`, then `x`
is irrational. -/
theorem irrational_nrt_of_n_not_dvd_multiplicity {x : ℝ} (n : ℕ) {m : ℤ} (hm : m ≠ 0) (p : ℕ)
[hp : fact p.prime] (hxr : x ^ n = m)
(hv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.ne_one, hm⟩) % n ≠ 0) :
irrational x :=
begin
rcases nat.eq_zero_or_pos n with rfl | hnpos,
{ rw [eq_comm, pow_zero, ← int.cast_one, int.cast_inj] at hxr,
simpa [hxr, multiplicity.one_right (mt is_unit_iff_dvd_one.1
(mt int.coe_nat_dvd.1 hp.not_dvd_one)), nat.zero_mod] using hv },
refine irrational_nrt_of_notint_nrt _ _ hxr _ hnpos,
rintro ⟨y, rfl⟩,
rw [← int.cast_pow, int.cast_inj] at hxr, subst m,
have : y ≠ 0, { rintro rfl, rw zero_pow hnpos at hm, exact hm rfl },
erw [multiplicity.pow' (nat.prime_iff_prime_int.1 hp)
(finite_int_iff.2 ⟨hp.ne_one, this⟩), nat.mul_mod_right] at hv,
exact hv rfl
end
theorem irrational_sqrt_of_multiplicity_odd (m : ℤ) (hm : 0 < m)
(p : ℕ) [hp : fact p.prime]
(Hpv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.ne_one, (ne_of_lt hm).symm⟩) % 2 = 1) :
irrational (sqrt m) :=
@irrational_nrt_of_n_not_dvd_multiplicity _ 2 _ (ne.symm (ne_of_lt hm)) p hp
(sqr_sqrt (int.cast_nonneg.2 $ le_of_lt hm))
(by rw Hpv; exact one_ne_zero)
theorem nat.prime.irrational_sqrt {p : ℕ} (hp : nat.prime p) : irrational (sqrt p) :=
@irrational_sqrt_of_multiplicity_odd p (int.coe_nat_pos.2 hp.pos) p hp $
by simp [multiplicity_self (mt is_unit_iff_dvd_one.1 (mt int.coe_nat_dvd.1 hp.not_dvd_one) : _)];
refl
theorem irrational_sqrt_two : irrational (sqrt 2) :=
by simpa using nat.prime_two.irrational_sqrt
theorem irrational_sqrt_rat_iff (q : ℚ) : irrational (sqrt q) ↔
rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q :=
if H1 : rat.sqrt q * rat.sqrt q = q
then iff_of_false (not_not_intro ⟨rat.sqrt q,
by rw [← H1, cast_mul, sqrt_mul_self (cast_nonneg.2 $ rat.sqrt_nonneg q),
sqrt_eq, abs_of_nonneg (rat.sqrt_nonneg q)]⟩) (λ h, h.1 H1)
else if H2 : 0 ≤ q
then iff_of_true (λ ⟨r, hr⟩, H1 $ (exists_mul_self _).1 ⟨r,
by rwa [eq_comm, sqrt_eq_iff_mul_self_eq (cast_nonneg.2 H2), ← cast_mul, cast_inj] at hr;
rw [← hr]; exact real.sqrt_nonneg _⟩) ⟨H1, H2⟩
else iff_of_false (not_not_intro ⟨0,
by rw cast_zero; exact (sqrt_eq_zero_of_nonpos (rat.cast_nonpos.2 $ le_of_not_le H2)).symm⟩)
(λ h, H2 h.2)
instance (q : ℚ) : decidable (irrational (sqrt q)) :=
decidable_of_iff' _ (irrational_sqrt_rat_iff q)
/-!
### Adding/subtracting/multiplying by rational numbers
-/
lemma rat.not_irrational (q : ℚ) : ¬irrational q := λ h, h ⟨q, rfl⟩
namespace irrational
variables (q : ℚ) {x y : ℝ}
open_locale classical
theorem add_cases : irrational (x + y) → irrational x ∨ irrational y :=
begin
delta irrational,
contrapose!,
rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩,
exact ⟨rx + ry, cast_add rx ry⟩
end
theorem of_rat_add (h : irrational (q + x)) : irrational x :=
h.add_cases.elim (λ h, absurd h q.not_irrational) id
theorem rat_add (h : irrational x) : irrational (q + x) :=
of_rat_add (-q) $ by rwa [cast_neg, neg_add_cancel_left]
theorem of_add_rat : irrational (x + q) → irrational x :=
add_comm ↑q x ▸ of_rat_add q
theorem add_rat (h : irrational x) : irrational (x + q) :=
add_comm ↑q x ▸ h.rat_add q
theorem of_neg (h : irrational (-x)) : irrational x :=
λ ⟨q, hx⟩, h ⟨-q, by rw [cast_neg, hx]⟩
protected theorem neg (h : irrational x) : irrational (-x) :=
of_neg $ by rwa neg_neg
theorem sub_rat (h : irrational x) : irrational (x - q) :=
by simpa only [sub_eq_add_neg, cast_neg] using h.add_rat (-q)
theorem rat_sub (h : irrational x) : irrational (q - x) :=
by simpa only [sub_eq_add_neg] using h.neg.rat_add q
theorem of_sub_rat (h : irrational (x - q)) : irrational x :=
(of_add_rat (-q) $ by simpa only [cast_neg, sub_eq_add_neg] using h)
theorem of_rat_sub (h : irrational (q - x)) : irrational x :=
of_neg (of_rat_add q (by simpa only [sub_eq_add_neg] using h))
theorem mul_cases : irrational (x * y) → irrational x ∨ irrational y :=
begin
delta irrational,
contrapose!,
rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩,
exact ⟨rx * ry, cast_mul rx ry⟩
end
theorem of_mul_rat (h : irrational (x * q)) : irrational x :=
h.mul_cases.elim id (λ h, absurd h q.not_irrational)
theorem mul_rat (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (x * q) :=
of_mul_rat q⁻¹ $ by rwa [mul_assoc, ← cast_mul, mul_inv_cancel hq, cast_one, mul_one]
theorem of_rat_mul : irrational (q * x) → irrational x :=
mul_comm x q ▸ of_mul_rat q
theorem rat_mul (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (q * x) :=
mul_comm x q ▸ h.mul_rat hq
theorem of_mul_self (h : irrational (x * x)) : irrational x :=
h.mul_cases.elim id id
theorem of_inv (h : irrational x⁻¹) : irrational x :=
λ ⟨q, hq⟩, h $ hq ▸ ⟨q⁻¹, q.cast_inv⟩
protected theorem inv (h : irrational x) : irrational x⁻¹ :=
of_inv $ by rwa inv_inv'
theorem div_cases (h : irrational (x / y)) : irrational x ∨ irrational y :=
h.mul_cases.imp id of_inv
theorem of_rat_div (h : irrational (q / x)) : irrational x :=
(h.of_rat_mul q).of_inv
theorem of_one_div (h : irrational (1 / x)) : irrational x :=
of_rat_div 1 $ by rwa [cast_one]
theorem of_pow : ∀ n : ℕ, irrational (x^n) → irrational x
| 0 := λ h, (h ⟨1, cast_one⟩).elim
| (n+1) := λ h, h.mul_cases.elim id (of_pow n)
theorem of_fpow : ∀ m : ℤ, irrational (x^m) → irrational x
| (n:ℕ) := of_pow n
| -[1+n] := λ h, by { rw fpow_neg_succ_of_nat at h, exact h.of_inv.of_pow _ }
end irrational
section polynomial
open polynomial
variables (x : ℝ) (p : polynomial ℤ)
lemma one_lt_nat_degree_of_irrational_root (hx : irrational x) (p_nonzero : p ≠ 0)
(x_is_root : aeval x p = 0) : 1 < p.nat_degree :=
begin
by_contra rid,
rcases exists_eq_X_add_C_of_nat_degree_le_one (not_lt.1 rid) with ⟨a, b, rfl⟩, clear rid,
have : (a : ℝ) * x = -b, by simpa [eq_neg_iff_add_eq_zero] using x_is_root,
rcases em (a = 0) with (rfl|ha),
{ obtain rfl : b = 0, by simpa,
simpa using p_nonzero },
{ rw [mul_comm, ← eq_div_iff_mul_eq, eq_comm] at this,
refine hx ⟨-b / a, _⟩,
assumption_mod_cast, assumption_mod_cast }
end
end polynomial
section
variables {q : ℚ} {x : ℝ}
open irrational
@[simp] theorem irrational_rat_add_iff : irrational (q + x) ↔ irrational x :=
⟨of_rat_add q, rat_add q⟩
@[simp] theorem irrational_add_rat_iff : irrational (x + q) ↔ irrational x :=
⟨of_add_rat q, add_rat q⟩
@[simp] theorem irrational_rat_sub_iff : irrational (q - x) ↔ irrational x :=
⟨of_rat_sub q, rat_sub q⟩
@[simp] theorem irrational_sub_rat_iff : irrational (x - q) ↔ irrational x :=
⟨of_sub_rat q, sub_rat q⟩
@[simp] theorem irrational_neg_iff : irrational (-x) ↔ irrational x :=
⟨of_neg, irrational.neg⟩
@[simp] theorem irrational_inv_iff : irrational x⁻¹ ↔ irrational x :=
⟨of_inv, irrational.inv⟩
end
|
95df1e1253fc3cab00b7fa82e416487615f0c4bb | a7dd8b83f933e72c40845fd168dde330f050b1c9 | /src/data/equiv/basic.lean | 6f28f04e9ec915edd368e53acd62ba10125c421e | [
"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 | 36,416 | 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, Mario Carneiro
In the standard library we cannot assume the univalence axiom.
We say two types are equivalent if they are isomorphic.
Two equivalent types have the same cardinality.
-/
import tactic.split_ifs logic.function logic.unique data.set.function data.bool data.quot
open function
universes u v w
variables {α : Sort u} {β : Sort v} {γ : Sort w}
/-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/
structure equiv (α : Sort*) (β : Sort*) :=
(to_fun : α → β)
(inv_fun : β → α)
(left_inv : left_inverse inv_fun to_fun)
(right_inv : right_inverse inv_fun to_fun)
namespace equiv
/-- `perm α` is the type of bijections from `α` to itself. -/
@[reducible] def perm (α : Sort*) := equiv α α
infix ` ≃ `:50 := equiv
instance : has_coe_to_fun (α ≃ β) :=
⟨_, to_fun⟩
@[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f :=
rfl
theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : equiv α β}, (e₁ : α → β) = e₂ → e₁ = e₂
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h :=
have f₁ = f₂, from h,
have g₁ = g₂, from funext $ assume x,
have f₁ (g₁ x) = f₂ (g₂ x), from (r₁ x).trans (r₂ x).symm,
have f₁ (g₁ x) = f₁ (g₂ x), by subst f₂; exact this,
show g₁ x = g₂ x, from injective_of_left_inverse l₁ this,
by simp *
@[extensionality] lemma ext (f g : equiv α β) (H : ∀ x, f x = g x) : f = g :=
eq_of_to_fun_eq (funext H)
@[extensionality] lemma perm.ext (σ τ : equiv.perm α) (H : ∀ x, σ x = τ x) : σ = τ :=
equiv.ext _ _ H
@[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩
@[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩
@[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ :=
⟨e₂.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ e₂.inv_fun,
e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩
protected theorem injective : ∀ f : α ≃ β, injective f
| ⟨f, g, h₁, h₂⟩ := injective_of_left_inverse h₁
protected theorem surjective : ∀ f : α ≃ β, surjective f
| ⟨f, g, h₁, h₂⟩ := surjective_of_has_right_inverse ⟨_, h₂⟩
protected theorem bijective (f : α ≃ β) : bijective f :=
⟨f.injective, f.surjective⟩
protected theorem subsingleton (e : α ≃ β) : ∀ [subsingleton β], subsingleton α
| ⟨H⟩ := ⟨λ a b, e.injective (H _ _)⟩
protected def decidable_eq (e : α ≃ β) [H : decidable_eq β] : decidable_eq α
| a b := decidable_of_iff _ e.injective.eq_iff
lemma nonempty_iff_nonempty : α ≃ β → (nonempty α ↔ nonempty β)
| ⟨f, g, _, _⟩ := nonempty.congr f g
protected def cast {α β : Sort*} (h : α = β) : α ≃ β :=
⟨cast h, cast h.symm, λ x, by cases h; refl, λ x, by cases h; refl⟩
@[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g :=
rfl
@[simp] theorem refl_apply (x : α) : equiv.refl α x = x := rfl
@[simp] theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl
@[simp] theorem apply_symm_apply : ∀ (e : α ≃ β) (x : β), e (e.symm x) = x
| ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw r₁
@[simp] theorem symm_apply_apply : ∀ (e : α ≃ β) (x : α), e.symm (e x) = x
| ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw l₁
@[simp] lemma symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) :
(f.trans g).symm a = f.symm (g.symm a) := rfl
@[simp] theorem apply_eq_iff_eq : ∀ (f : α ≃ β) (x y : α), f x = f y ↔ x = y
| ⟨f₁, g₁, l₁, r₁⟩ x y := (injective_of_left_inverse l₁).eq_iff
@[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl
lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y :=
⟨λ H, by simp [H.symm], λ H, by simp [H]⟩
lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x :=
(eq_comm.trans e.symm_apply_eq).trans eq_comm
@[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by cases e; refl
@[simp] theorem symm_symm_apply (e : α ≃ β) (a : α) : e.symm.symm a = e a := by cases e; refl
@[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by cases e; refl
@[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by cases e; refl
@[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext _ _ (by simp)
@[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext _ _ (by simp)
lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) :
(ab.trans bc).trans cd = ab.trans (bc.trans cd) :=
equiv.ext _ _ $ assume a, rfl
theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv
theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv
def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) :=
⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm,
assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end,
assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, ⟩
def perm_congr {α : Type*} {β : Type*} (e : α ≃ β) : perm α ≃ perm β :=
equiv_congr e e
protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s :=
set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv
protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ e '' s ↔ e.symm '' t ⊆ s :=
by rw [set.image_subset_iff, e.image_eq_preimage]
lemma symm_image_image {α β} (f : equiv α β) (s : set α) : f.symm '' (f '' s) = s :=
by { rw [← set.image_comp], simp }
protected lemma image_compl {α β} (f : equiv α β) (s : set α) :
f '' -s = -(f '' s) :=
set.image_compl_eq f.bijective
/- The group of permutations (self-equivalences) of a type `α` -/
namespace perm
instance perm_group {α : Type u} : group (perm α) :=
begin
refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..};
intros; apply equiv.ext; try { apply trans_apply },
apply symm_apply_apply
end
@[simp] theorem mul_apply {α : Type u} (f g : perm α) (x) : (f * g) x = f (g x) :=
equiv.trans_apply _ _ _
@[simp] theorem one_apply {α : Type u} (x) : (1 : perm α) x = x := rfl
@[simp] lemma inv_apply_self {α : Type u} (f : perm α) (x) :
f⁻¹ (f x) = x := equiv.symm_apply_apply _ _
@[simp] lemma apply_inv_self {α : Type u} (f : perm α) (x) :
f (f⁻¹ x) = x := equiv.apply_symm_apply _ _
lemma one_def {α : Type u} : (1 : perm α) = equiv.refl α := rfl
lemma mul_def {α : Type u} (f g : perm α) : f * g = g.trans f := rfl
lemma inv_def {α : Type u} (f : perm α) : f⁻¹ = f.symm := rfl
end perm
def equiv_empty (h : α → false) : α ≃ empty :=
⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩
def false_equiv_empty : false ≃ empty :=
equiv_empty _root_.id
def equiv_pempty (h : α → false) : α ≃ pempty :=
⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩
def false_equiv_pempty : false ≃ pempty :=
equiv_pempty _root_.id
def empty_equiv_pempty : empty ≃ pempty :=
equiv_pempty $ empty.rec _
def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} :=
equiv_pempty pempty.elim
def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty :=
equiv_empty $ assume a, h ⟨a⟩
def pempty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ pempty :=
equiv_pempty $ assume a, h ⟨a⟩
def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit :=
⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩
def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial
protected def ulift {α : Type u} : ulift α ≃ α :=
⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩
protected def plift : plift α ≃ α :=
⟨plift.down, plift.up, plift.up_down, plift.down_up⟩
@[congr] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ → β₁) ≃ (α₂ → β₂)
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ :=
⟨λ (h : α₁ → β₁) (a : α₂), f₂ (h (g₁ a)),
λ (h : α₂ → β₂) (a : α₁), g₂ (h (f₁ a)),
λ h, by funext a; dsimp; rw [l₁, l₂],
λ h, by funext a; dsimp; rw [r₁, r₂]⟩
def punit_equiv_punit : punit.{v} ≃ punit.{w} :=
⟨λ _, punit.star, λ _, punit.star, λ u, by cases u; refl, λ u, by cases u; reflexivity⟩
section
@[simp] def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} :=
⟨λ f, punit.star, λ u f, punit.star, λ f, by funext x; cases f x; refl, λ u, by cases u; reflexivity⟩
@[simp] def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α :=
⟨λ f, f punit.star, λ a u, a, λ f, by funext x; cases x; refl, λ u, rfl⟩
@[simp] def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} :=
⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩
@[simp] def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} :=
⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩
@[simp] def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} :=
calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _)
... ≃ punit : empty_arrow_equiv_punit _
end
@[congr] def prod_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ :β₁ ≃ β₂) : (α₁ × β₁) ≃ (α₂ × β₂) :=
⟨λp, (e₁ p.1, e₂ p.2), λp, (e₁.symm p.1, e₂.symm p.2),
λ ⟨a, b⟩, show (e₁.symm (e₁ a), e₂.symm (e₂ b)) = (a, b), by rw [symm_apply_apply, symm_apply_apply],
λ ⟨a, b⟩, show (e₁ (e₁.symm a), e₂ (e₂.symm b)) = (a, b), by rw [apply_symm_apply, apply_symm_apply]⟩
@[simp] theorem prod_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) (b : β₁) :
prod_congr e₁ e₂ (a, b) = (e₁ a, e₂ b) :=
rfl
@[simp] def prod_comm (α β : Sort*) : (α × β) ≃ (β × α) :=
⟨λ p, (p.2, p.1), λ p, (p.2, p.1), λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩
@[simp] def prod_assoc (α β γ : Sort*) : ((α × β) × γ) ≃ (α × (β × γ)) :=
⟨λ p, ⟨p.1.1, ⟨p.1.2, p.2⟩⟩, λp, ⟨⟨p.1, p.2.1⟩, p.2.2⟩, λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩
@[simp] theorem prod_assoc_apply {α β γ : Sort*} (p : (α × β) × γ) :
prod_assoc α β γ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl
section
@[simp] def prod_punit (α : Sort*) : (α × punit.{u+1}) ≃ α :=
⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩
@[simp] theorem prod_punit_apply {α : Sort*} (a : α × punit.{u+1}) : prod_punit α a = a.1 := rfl
@[simp] def punit_prod (α : Sort*) : (punit.{u+1} × α) ≃ α :=
calc (punit × α) ≃ (α × punit) : prod_comm _ _
... ≃ α : prod_punit _
@[simp] theorem punit_prod_apply {α : Sort*} (a : punit.{u+1} × α) : punit_prod α a = a.2 := rfl
@[simp] def prod_empty (α : Sort*) : (α × empty) ≃ empty :=
equiv_empty (λ ⟨_, e⟩, e.rec _)
@[simp] def empty_prod (α : Sort*) : (empty × α) ≃ empty :=
equiv_empty (λ ⟨e, _⟩, e.rec _)
@[simp] def prod_pempty (α : Sort*) : (α × pempty) ≃ pempty :=
equiv_pempty (λ ⟨_, e⟩, e.rec _)
@[simp] def pempty_prod (α : Sort*) : (pempty × α) ≃ pempty :=
equiv_pempty (λ ⟨e, _⟩, e.rec _)
end
section
open sum
def psum_equiv_sum (α β : Sort*) : psum α β ≃ (α ⊕ β) :=
⟨λ s, psum.cases_on s inl inr,
λ s, sum.cases_on s psum.inl psum.inr,
λ s, by cases s; refl,
λ s, by cases s; refl⟩
def sum_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ ⊕ β₁) ≃ (α₂ ⊕ β₂)
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ :=
⟨λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end,
λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end,
λ s, match s with inl a := congr_arg inl (l₁ a) | inr a := congr_arg inr (l₂ a) end,
λ s, match s with inl a := congr_arg inl (r₁ a) | inr a := congr_arg inr (r₂ a) end⟩
@[simp] theorem sum_congr_apply_inl {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) :
sum_congr e₁ e₂ (inl a) = inl (e₁ a) :=
by cases e₁; cases e₂; refl
@[simp] theorem sum_congr_apply_inr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (b : β₁) :
sum_congr e₁ e₂ (inr b) = inr (e₂ b) :=
by cases e₁; cases e₂; refl
def bool_equiv_punit_sum_punit : bool ≃ (punit.{u+1} ⊕ punit.{v+1}) :=
⟨λ b, cond b (inr punit.star) (inl punit.star),
λ s, sum.rec_on s (λ_, ff) (λ_, tt),
λ b, by cases b; refl,
λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩
noncomputable def Prop_equiv_bool : Prop ≃ bool :=
⟨λ p, @to_bool p (classical.prop_decidable _),
λ b, b, λ p, by simp, λ b, by simp⟩
@[simp] def sum_comm (α β : Sort*) : (α ⊕ β) ≃ (β ⊕ α) :=
⟨λ s, match s with inl a := inr a | inr b := inl b end,
λ s, match s with inl b := inr b | inr a := inl a end,
λ s, by cases s; refl,
λ s, by cases s; refl⟩
@[simp] def sum_assoc (α β γ : Sort*) : ((α ⊕ β) ⊕ γ) ≃ (α ⊕ (β ⊕ γ)) :=
⟨λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end,
λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end,
λ s, by rcases s with ⟨_ | _⟩ | _; refl,
λ s, by rcases s with _ | _ | _; refl⟩
@[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl
@[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl
@[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl
@[simp] def sum_empty (α : Sort*) : (α ⊕ empty) ≃ α :=
⟨λ s, match s with inl a := a | inr e := empty.rec _ e end,
inl,
λ s, by rcases s with _ | ⟨⟨⟩⟩; refl,
λ a, rfl⟩
@[simp] def empty_sum (α : Sort*) : (empty ⊕ α) ≃ α :=
(sum_comm _ _).trans $ sum_empty _
@[simp] def sum_pempty (α : Sort*) : (α ⊕ pempty) ≃ α :=
⟨λ s, match s with inl a := a | inr e := pempty.rec _ e end,
inl,
λ s, by rcases s with _ | ⟨⟨⟩⟩; refl,
λ a, rfl⟩
@[simp] def pempty_sum (α : Sort*) : (pempty ⊕ α) ≃ α :=
(sum_comm _ _).trans $ sum_pempty _
@[simp] def option_equiv_sum_punit (α : Sort*) : option α ≃ (α ⊕ punit.{u+1}) :=
⟨λ o, match o with none := inr punit.star | some a := inl a end,
λ s, match s with inr _ := none | inl a := some a end,
λ o, by cases o; refl,
λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩
def sum_equiv_sigma_bool (α β : Sort*) : (α ⊕ β) ≃ (Σ b: bool, cond b α β) :=
⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end,
λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end,
λ s, by cases s; refl,
λ s, by rcases s with ⟨_|_, _⟩; refl⟩
def equiv_fib {α β : Type*} (f : α → β) :
α ≃ Σ y : β, {x // f x = y} :=
⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨y, x, rfl⟩, rfl⟩
end
section
def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) :=
⟨λ H a, F a (H a), λ H a, (F a).symm (H a),
λ H, funext $ by simp, λ H, funext $ by simp⟩
end
section
def psigma_equiv_sigma {α} (β : α → Sort*) : psigma β ≃ sigma β :=
⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩
def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : sigma β₁ ≃ sigma β₂ :=
⟨λ ⟨a, b⟩, ⟨a, F a b⟩, λ ⟨a, b⟩, ⟨a, (F a).symm b⟩,
λ ⟨a, b⟩, congr_arg (sigma.mk a) $ symm_apply_apply (F a) b,
λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_symm_apply (F a) b⟩
def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} : ∀ f : α₁ ≃ α₂, (Σ a:α₁, β (f a)) ≃ (Σ a:α₂, β a)
| ⟨f, g, l, r⟩ :=
⟨λ ⟨a, b⟩, ⟨f a, b⟩, λ ⟨a, b⟩, ⟨g a, @@eq.rec β b (r a).symm⟩,
λ ⟨a, b⟩, match g (f a), l a : ∀ a' (h : a' = a),
@sigma.mk _ (β ∘ f) _ (@@eq.rec β b (congr_arg f h.symm)) = ⟨a, b⟩ with
| _, rfl := rfl end,
λ ⟨a, b⟩, match f (g a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with
| _, rfl := rfl end⟩
def sigma_equiv_prod (α β : Sort*) : (Σ_:α, β) ≃ (α × β) :=
⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩
def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : ∀ a, β₁ a ≃ β) : sigma β₁ ≃ (α × β) :=
(sigma_congr_right F).trans (sigma_equiv_prod α β)
end
section
def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ ((γ → α) × (γ → β)) :=
⟨λ f, (λ c, (f c).1, λ c, (f c).2),
λ p c, (p.1 c, p.2 c),
λ f, funext $ λ c, prod.mk.eta,
λ p, by cases p; refl⟩
def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) :=
⟨λ f, λ p, f p.1 p.2,
λ f, λ a b, f (a, b),
λ f, rfl,
λ f, by funext p; cases p; refl⟩
open sum
def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ ((α → γ) × (β → γ)) :=
⟨λ f, (f ∘ inl, f ∘ inr),
λ p s, sum.rec_on s p.1 p.2,
λ f, by funext s; cases s; refl,
λ p, by cases p; refl⟩
def sum_prod_distrib (α β γ : Sort*) : ((α ⊕ β) × γ) ≃ ((α × γ) ⊕ (β × γ)) :=
⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end,
λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end,
λ p, by rcases p with ⟨_ | _, _⟩; refl,
λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩
@[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) :
sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl
@[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) :
sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl
def prod_sum_distrib (α β γ : Sort*) : (α × (β ⊕ γ)) ≃ ((α × β) ⊕ (α × γ)) :=
calc (α × (β ⊕ γ)) ≃ ((β ⊕ γ) × α) : prod_comm _ _
... ≃ ((β × α) ⊕ (γ × α)) : sum_prod_distrib _ _ _
... ≃ ((α × β) ⊕ (α × γ)) : sum_congr (prod_comm _ _) (prod_comm _ _)
@[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) :
prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl
@[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) :
prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl
def bool_prod_equiv_sum (α : Type u) : (bool × α) ≃ (α ⊕ α) :=
calc (bool × α) ≃ ((unit ⊕ unit) × α) : prod_congr bool_equiv_punit_sum_punit (equiv.refl _)
... ≃ (α × (unit ⊕ unit)) : prod_comm _ _
... ≃ ((α × unit) ⊕ (α × unit)) : prod_sum_distrib _ _ _
... ≃ (α ⊕ α) : sum_congr (prod_punit _) (prod_punit _)
end
section
open sum nat
def nat_equiv_nat_sum_punit : ℕ ≃ (ℕ ⊕ punit.{u+1}) :=
⟨λ n, match n with zero := inr punit.star | succ a := inl a end,
λ s, match s with inl n := succ n | inr punit.star := zero end,
λ n, begin cases n, repeat { refl } end,
λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩
@[simp] def nat_sum_punit_equiv_nat : (ℕ ⊕ punit.{u+1}) ≃ ℕ :=
nat_equiv_nat_sum_punit.symm
def int_equiv_nat_sum_nat : ℤ ≃ (ℕ ⊕ ℕ) :=
by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl}
end
def list_equiv_of_equiv {α β : Type*} : α ≃ β → list α ≃ list β
| ⟨f, g, l, r⟩ :=
by refine ⟨list.map f, list.map g, λ x, _, λ x, _⟩;
simp [id_of_left_inverse l, id_of_right_inverse r]
def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} :=
⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩
def decidable_eq_of_equiv [decidable_eq β] (e : α ≃ β) : decidable_eq α
| a₁ a₂ := decidable_of_iff (e a₁ = e a₂) e.injective.eq_iff
def inhabited_of_equiv [inhabited β] (e : α ≃ β) : inhabited α :=
⟨e.symm (default _)⟩
def unique_of_equiv (e : α ≃ β) (h : unique β) : unique α :=
unique.of_surjective e.symm.surjective
def unique_congr (e : α ≃ β) : unique α ≃ unique β :=
{ to_fun := e.symm.unique_of_equiv,
inv_fun := e.unique_of_equiv,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
section
open subtype
def subtype_congr {p : α → Prop} {q : β → Prop}
(e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} :=
⟨λ x, ⟨e x.1, (h _).1 x.2⟩,
λ y, ⟨e.symm y.1, (h _).2 (by simp; exact y.2)⟩,
λ ⟨x, h⟩, subtype.eq' $ by simp,
λ ⟨y, h⟩, subtype.eq' $ by simp⟩
def subtype_congr_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : subtype p ≃ subtype q :=
subtype_congr (equiv.refl _) e
@[simp] lemma subtype_congr_right_mk {p q : α → Prop} (e : ∀x, p x ↔ q x)
{x : α} (h : p x) : subtype_congr_right e ⟨x, h⟩ = ⟨x, (e x).1 h⟩ := rfl
def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) :
{a : α // p a} ≃ {b : β // p (e.symm b)} :=
subtype_congr e $ by simp
def subtype_congr_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q :=
subtype_congr (equiv.refl α) (assume a, h ▸ iff.refl _)
def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t :=
subtype_congr_prop h
def subtype_subtype_equiv_subtype {α : Type u} (p : α → Prop) (q : subtype p → Prop) :
subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } :=
⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩,
λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by cases ha; exact ha_h⟩,
assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩
/-- aka coimage -/
def equiv_sigma_subtype {α : Type u} {β : Type v} (f : α → β) : α ≃ Σ b, {x : α // f x = b} :=
⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨b, x, H⟩, sigma.eq H $ eq.drec_on H $ subtype.eq rfl⟩
def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) :
(Πi, π i) ≃ {f : ι → Σi, π i | ∀i, (f i).1 = i } :=
⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end,
assume f, funext $ assume i, rfl,
assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $
eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩
def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} :
{f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } :=
⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩,
by rintro ⟨f, h⟩; refl,
by rintro f; funext a; exact subtype.eq' rfl⟩
end
section
local attribute [elab_with_expected_type] quot.lift
def quot_equiv_of_quot' {r : α → α → Prop} {s : β → β → Prop} (e : α ≃ β)
(h : ∀ a a', r a a' ↔ s (e a) (e a')) : quot r ≃ quot s :=
⟨quot.lift (λ a, quot.mk _ (e a)) (λ a a' H, quot.sound ((h a a').mp H)),
quot.lift (λ b, quot.mk _ (e.symm b)) (λ b b' H, quot.sound ((h _ _).mpr (by convert H; simp))),
quot.ind $ by simp,
quot.ind $ by simp⟩
def quot_equiv_of_quot {r : α → α → Prop} (e : α ≃ β) :
quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) :=
quot_equiv_of_quot' e (by simp)
end
namespace set
open set
protected def univ (α) : @univ α ≃ α :=
⟨subtype.val, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩
@[simp] lemma univ_apply {α : Type u} (x : @univ α) :
equiv.set.univ α x = x := rfl
@[simp] lemma univ_symm_apply {α : Type u} (x : α) :
(equiv.set.univ α).symm x = ⟨x, trivial⟩ := rfl
protected def empty (α) : (∅ : set α) ≃ empty :=
equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h
protected def pempty (α) : (∅ : set α) ≃ pempty :=
equiv_pempty $ λ ⟨x, h⟩, not_mem_empty x h
protected def union' {α} {s t : set α}
(p : α → Prop) [decidable_pred p]
(hs : ∀ x ∈ s, p x)
(ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ (s ⊕ t) :=
{ to_fun := λ x, if hp : p x.1
then sum.inl ⟨_, x.2.resolve_right (λ xt, ht _ xt hp)⟩
else sum.inr ⟨_, x.2.resolve_left (λ xs, hp (hs _ xs))⟩,
inv_fun := λ o, match o with
| (sum.inl x) := ⟨x.1, or.inl x.2⟩
| (sum.inr x) := ⟨x.1, or.inr x.2⟩
end,
left_inv := λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, h]; congr,
right_inv := λ o, begin
rcases o with ⟨x, h⟩ | ⟨x, h⟩;
dsimp [union'._match_1];
[simp [hs _ h], simp [ht _ h]]
end }
protected def union {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) :
(s ∪ t : set α) ≃ (s ⊕ t) :=
set.union' s (λ _, id) (λ x xt xs, subset_empty_iff.2 H ⟨xs, xt⟩)
lemma union_apply_left {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅)
{a : (s ∪ t : set α)} (ha : ↑a ∈ s) : equiv.set.union H a = sum.inl ⟨a, ha⟩ :=
dif_pos ha
lemma union_apply_right {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅)
{a : (s ∪ t : set α)} (ha : ↑a ∈ t) : equiv.set.union H a = sum.inr ⟨a, ha⟩ :=
dif_neg (show ↑a ∉ s, by finish [set.ext_iff])
protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} :=
⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩,
λ ⟨x, h⟩, by simp at h; subst x,
λ ⟨⟩, rfl⟩
protected def of_eq {α : Type u} {s t : set α} (h : s = t) : s ≃ t :=
{ to_fun := λ x, ⟨x.1, h ▸ x.2⟩,
inv_fun := λ x, ⟨x.1, h.symm ▸ x.2⟩,
left_inv := λ _, subtype.eq rfl,
right_inv := λ _, subtype.eq rfl }
@[simp] lemma of_eq_apply {α : Type u} {s t : set α} (h : s = t) (a : s) :
equiv.set.of_eq h a = ⟨a, h ▸ a.2⟩ := rfl
@[simp] lemma of_eq_symm_apply {α : Type u} {s t : set α} (h : s = t) (a : t) :
(equiv.set.of_eq h).symm a = ⟨a, h.symm ▸ a.2⟩ := rfl
protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) :
(insert a s : set α) ≃ (s ⊕ punit.{u+1}) :=
calc (insert a s : set α) ≃ ↥(s ∪ {a}) : equiv.set.of_eq (by simp)
... ≃ (s ⊕ ({a} : set α)) : equiv.set.union (by finish [set.ext_iff])
... ≃ (s ⊕ punit.{u+1}) : sum_congr (equiv.refl _) (equiv.set.singleton _)
protected def sum_compl {α} (s : set α) [decidable_pred s] :
(s ⊕ (-s : set α)) ≃ α :=
calc (s ⊕ (-s : set α)) ≃ ↥(s ∪ -s) : (equiv.set.union (by simp [set.ext_iff])).symm
... ≃ @univ α : equiv.set.of_eq (by simp)
... ≃ α : equiv.set.univ _
@[simp] lemma sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred s] (x : s) :
equiv.set.sum_compl s (sum.inl x) = x := rfl
@[simp] lemma sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred s] (x : -s) :
equiv.set.sum_compl s (sum.inr x) = x := rfl
lemma sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred s] {x : α}
(hx : x ∈ s) : (equiv.set.sum_compl s).symm x = sum.inl ⟨x, hx⟩ :=
have ↑(⟨x, or.inl hx⟩ : (s ∪ -s : set α)) ∈ s, from hx,
by rw [equiv.set.sum_compl]; simpa using set.union_apply_left _ this
lemma sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred s] {x : α}
(hx : x ∉ s) : (equiv.set.sum_compl s).symm x = sum.inr ⟨x, hx⟩ :=
have ↑(⟨x, or.inr hx⟩ : (s ∪ -s : set α)) ∈ -s, from hx,
by rw [equiv.set.sum_compl]; simpa using set.union_apply_right _ this
protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred s] :
((s ∪ t : set α) ⊕ (s ∩ t : set α)) ≃ (s ⊕ t) :=
calc ((s ∪ t : set α) ⊕ (s ∩ t : set α))
≃ ((s ∪ t \ s : set α) ⊕ (s ∩ t : set α)) : by rw [union_diff_self]
... ≃ ((s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α)) :
sum_congr (set.union (inter_diff_self _ _)) (equiv.refl _)
... ≃ (s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α)) : sum_assoc _ _ _
... ≃ (s ⊕ (t \ s ∪ s ∩ t : set α)) : sum_congr (equiv.refl _) begin
refine (set.union' (∉ s) _ _).symm,
exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1]
end
... ≃ (s ⊕ t) : by rw (_ : t \ s ∪ s ∩ t = t);
rw [union_comm, inter_comm, inter_union_diff]
protected def prod {α β} (s : set α) (t : set β) :
(s.prod t) ≃ (s × t) :=
⟨λp, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩,
λp, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩,
λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, rfl,
λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, rfl⟩
protected noncomputable def image_of_inj_on {α β} (f : α → β) (s : set α) (H : inj_on f s) :
s ≃ (f '' s) :=
⟨λ ⟨x, h⟩, ⟨f x, mem_image_of_mem f h⟩,
λ ⟨y, h⟩, ⟨classical.some h, (classical.some_spec h).1⟩,
λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).1 h
(classical.some_spec (mem_image_of_mem f h)).2),
λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩
protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) :=
equiv.set.image_of_inj_on f s (λ x y hx hy hxy, H hxy)
@[simp] theorem image_apply {α β} (f : α → β) (s : set α) (H : injective f) (a h) :
set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl
protected noncomputable def range {α β} (f : α → β) (H : injective f) :
α ≃ range f :=
{ to_fun := λ x, ⟨f x, mem_range_self _⟩,
inv_fun := λ x, classical.some x.2,
left_inv := λ x, H (classical.some_spec (show f x ∈ range f, from mem_range_self _)),
right_inv := λ x, subtype.eq $ classical.some_spec x.2 }
@[simp] theorem range_apply {α β} (f : α → β) (H : injective f) (a) :
set.range f H a = ⟨f a, set.mem_range_self _⟩ := rfl
protected def congr {α β : Type*} (e : α ≃ β) : set α ≃ set β :=
⟨λ s, e '' s, λ t, e.symm '' t, symm_image_image e, symm_image_image e.symm⟩
protected def sep {α : Type u} (s : set α) (t : α → Prop) :
({ x ∈ s | t x } : set α) ≃ { x : s | t x.1 } :=
begin
symmetry, apply (equiv.subtype_subtype_equiv_subtype _ _).trans _,
simp only [mem_set_of_eq, exists_prop], refl
end
end set
noncomputable def of_bijective {α β} {f : α → β} (hf : bijective f) : α ≃ β :=
⟨f, λ x, classical.some (hf.2 x), λ x, hf.1 (classical.some_spec (hf.2 (f x))),
λ x, classical.some_spec (hf.2 x)⟩
@[simp] theorem of_bijective_to_fun {α β} {f : α → β} (hf : bijective f) : (of_bijective hf : α → β) = f := rfl
lemma subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α]
[s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧)
(h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) :
{x // p₂ x} ≃ quotient s₂ :=
{ to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧)
(λ a b hab, hfunext (by rw quotient.sound hab)
(λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2,
inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x}))
(λ a b hab, subtype.eq' (quotient.sound ((h _ _).1 hab))),
left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha,
right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) }
section swap
variable [decidable_eq α]
open decidable
def swap_core (a b r : α) : α :=
if r = a then b
else if r = b then a
else r
theorem swap_core_self (r a : α) : swap_core a a r = r :=
by unfold swap_core; split_ifs; cc
theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r :=
by unfold swap_core; split_ifs; cc
theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r :=
by unfold swap_core; split_ifs; cc
/-- `swap a b` is the permutation that swaps `a` and `b` and
leaves other values as is. -/
def swap (a b : α) : perm α :=
⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩
theorem swap_self (a : α) : swap a a = equiv.refl _ :=
eq_of_to_fun_eq $ funext $ λ r, swap_core_self r a
theorem swap_comm (a b : α) : swap a b = swap b a :=
eq_of_to_fun_eq $ funext $ λ r, swap_core_comm r _ _
theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x :=
rfl
@[simp] theorem swap_apply_left (a b : α) : swap a b a = b :=
if_pos rfl
@[simp] theorem swap_apply_right (a b : α) : swap a b b = a :=
by by_cases b = a; simp [swap_apply_def, *]
theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x :=
by simp [swap_apply_def] {contextual := tt}
@[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ :=
eq_of_to_fun_eq $ funext $ λ x, swap_core_swap_core _ _ _
theorem swap_comp_apply {a b x : α} (π : perm α) :
π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x :=
by cases π; refl
@[simp] lemma swap_inv {α : Type*} [decidable_eq α] (x y : α) :
(swap x y)⁻¹ = swap x y := rfl
@[simp] lemma symm_trans_swap_trans [decidable_eq α] [decidable_eq β] (a b : α)
(e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) :=
equiv.ext _ _ (λ x, begin
have : ∀ a, e.symm x = a ↔ x = e a :=
λ a, by rw @eq_comm _ (e.symm x); split; intros; simp * at *,
simp [swap_apply_def, this],
split_ifs; simp
end)
@[simp] lemma swap_mul_self {α : Type*} [decidable_eq α] (i j : α) : swap i j * swap i j = 1 :=
equiv.swap_swap i j
@[simp] lemma swap_apply_self {α : Type*} [decidable_eq α] (i j a : α) : swap i j (swap i j a) = a :=
by rw [← perm.mul_apply, swap_mul_self, perm.one_apply]
/-- Augment an equivalence with a prescribed mapping `f a = b` -/
def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β :=
(swap a (f.symm b)).trans f
@[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b :=
by dsimp [set_value]; simp [swap_apply_left]
end swap
end equiv
instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton
instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton
instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq
instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq
def unique_unique_equiv : unique (unique α) ≃ unique α :=
{ to_fun := λ h, h.default,
inv_fun := λ h, { default := h, uniq := λ _, subsingleton.elim _ _ },
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
def equiv_of_unique_of_unique [unique α] [unique β] : α ≃ β :=
{ to_fun := λ _, default β,
inv_fun := λ _, default α,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
def equiv_punit_of_unique [unique α] : α ≃ punit.{v} :=
equiv_of_unique_of_unique
namespace quot
/-- Quotients are congruent on equivalences under equality of their relation.
An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/
protected def congr {α} {r r' : α → α → Prop} (eq : ∀a b, r a b ↔ r' a b) : quot r ≃ quot r' :=
⟨quot.map r r' (assume a b, (eq a b).1), quot.map r' r (assume a b, (eq a b).2),
by rintros ⟨a⟩; refl, by rintros ⟨a⟩; refl⟩
end quot
namespace quotient
protected def congr {α} {r r' : setoid α} (eq : ∀a b, @setoid.r α r a b ↔ @setoid.r α r' a b) :
quotient r ≃ quotient r' :=
quot.congr eq
end quotient
|
ee83f40cb6af72277c7e1d36a16e0dc5b747925c | 437dc96105f48409c3981d46fb48e57c9ac3a3e4 | /src/data/fintype/card.lean | 9c2400d37354e530ee4274793f80e555a84df8c8 | [
"Apache-2.0"
] | permissive | dan-c-k/mathlib | 08efec79bd7481ee6da9cc44c24a653bff4fbe0d | 96efc220f6225bc7a5ed8349900391a33a38cc56 | refs/heads/master | 1,658,082,847,093 | 1,589,013,201,000 | 1,589,013,201,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,183 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.fintype.basic
import data.nat.choose
import tactic.ring
/-!
Results about "big operations" over a `fintype`, and consequent
results about cardinalities of certain types.
## Implementation note
This content had previously been in `data.fintype`, but was moved here to avoid
requiring `algebra.big_operators` (and hence many other imports) as a
dependency of `fintype`.
-/
universes u v
variables {α : Type*} {β : Type*} {γ : Type*}
open_locale big_operators
namespace fintype
lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = ∑ a : α, 1 :=
finset.card_eq_sum_ones _
section
open finset
variables {ι : Type*} [fintype ι] [decidable_eq ι]
@[to_additive]
lemma prod_extend_by_one [comm_monoid α] (s : finset ι) (f : ι → α) :
∏ i, (if i ∈ s then f i else 1) = ∏ i in s, f i :=
by rw [← prod_filter, filter_mem_eq_inter, univ_inter]
end
section
variables {M : Type*} [fintype α] [comm_monoid M]
@[to_additive]
lemma prod_eq_one (f : α → M) (h : ∀ a, f a = 1) :
(∏ a, f a) = 1 :=
finset.prod_eq_one $ λ a ha, h a
@[to_additive]
lemma prod_congr (f g : α → M) (h : ∀ a, f a = g a) :
(∏ a, f a) = ∏ a, g a :=
finset.prod_congr rfl $ λ a ha, h a
@[to_additive]
lemma prod_unique [unique β] (f : β → M) :
(∏ x, f x) = f (default β) :=
by simp only [finset.prod_singleton, univ_unique, finset.singleton_eq_singleton]
end
end fintype
open finset
theorem fin.prod_univ_succ [comm_monoid β] {n:ℕ} (f : fin n.succ → β) :
univ.prod f = f 0 * univ.prod (λ i:fin n, f i.succ) :=
begin
rw [fin.univ_succ, prod_insert, prod_image],
{ intros x _ y _ hxy, exact fin.succ.inj hxy },
{ simpa using fin.succ_ne_zero }
end
@[simp, to_additive] theorem fin.prod_univ_zero [comm_monoid β] (f : fin 0 → β) : univ.prod f = 1 := rfl
theorem fin.sum_univ_succ [add_comm_monoid β] {n:ℕ} (f : fin n.succ → β) :
univ.sum f = f 0 + univ.sum (λ i:fin n, f i.succ) :=
by apply @fin.prod_univ_succ (multiplicative β)
attribute [to_additive] fin.prod_univ_succ
theorem fin.prod_univ_cast_succ [comm_monoid β] {n:ℕ} (f : fin n.succ → β) :
univ.prod f = univ.prod (λ i:fin n, f i.cast_succ) * f (fin.last n) :=
begin
rw [fin.univ_cast_succ, prod_insert, prod_image, mul_comm],
{ intros x _ y _ hxy, exact fin.cast_succ_inj.mp hxy },
{ simpa using fin.cast_succ_ne_last }
end
theorem fin.sum_univ_cast_succ [add_comm_monoid β] {n:ℕ} (f : fin n.succ → β) :
univ.sum f = univ.sum (λ i:fin n, f i.cast_succ) + f (fin.last n) :=
by apply @fin.prod_univ_cast_succ (multiplicative β)
attribute [to_additive] fin.prod_univ_cast_succ
@[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*)
[fintype α] [∀ a, fintype (β a)] :
fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) :=
card_sigma _ _
-- FIXME ouch, this should be in the main file.
@[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] :
fintype.card (α ⊕ β) = fintype.card α + fintype.card β :=
by rw [sum.fintype, fintype.of_equiv_card]; simp
@[simp] lemma fintype.card_pi_finset [decidable_eq α] [fintype α]
{δ : α → Type*} (t : Π a, finset (δ a)) :
(fintype.pi_finset t).card = finset.univ.prod (λ a, card (t a)) :=
by simp [fintype.pi_finset, card_map]
@[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α]
[f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) :=
fintype.card_pi_finset _
-- FIXME ouch, this should be in the main file.
@[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] :
fintype.card (α → β) = fintype.card β ^ fintype.card α :=
by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl
@[simp] lemma card_vector [fintype α] (n : ℕ) :
fintype.card (vector α n) = fintype.card α ^ n :=
by rw fintype.of_equiv_card; simp
@[simp, to_additive]
lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) :
univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) :=
prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩)
@[to_additive]
lemma finset.range_prod_eq_univ_prod [comm_monoid β] (n : ℕ) (f : ℕ → β) :
(range n).prod f = univ.prod (λ (k : fin n), f k) :=
begin
symmetry,
refine prod_bij (λ k hk, k) _ _ _ _,
{ rintro ⟨k, hk⟩ _, simp * },
{ rintro ⟨k, hk⟩ _, simp * },
{ intros, rwa fin.eq_iff_veq },
{ intros k hk, rw mem_range at hk,
exact ⟨⟨k, hk⟩, mem_univ _, rfl⟩ }
end
/-- Taking a product over `univ.pi t` is the same as taking the product over `fintype.pi_finset t`.
`univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ
in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and
`fintype.pi_finset t` is a `finset (Π a, t a)`. -/
@[to_additive "Taking a sum over `univ.pi t` is the same as taking the sum over
`fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`,
but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and
`fintype.pi_finset t` is a `finset (Π a, t a)`."]
lemma finset.prod_univ_pi [decidable_eq α] [fintype α] [comm_monoid β]
{δ : α → Type*} {t : Π (a : α), finset (δ a)}
(f : (Π (a : α), a ∈ (univ : finset α) → δ a) → β) :
(univ.pi t).prod f = (fintype.pi_finset t).prod (λ x, f (λ a _, x a)) :=
prod_bij (λ x _ a, x a (mem_univ _))
(by simp)
(by simp)
(by simp [function.funext_iff] {contextual := tt})
(λ x hx, ⟨λ a _, x a, by simp * at *⟩)
/-- The product over `univ` of a sum can be written as a sum over the product of sets,
`fintype.pi_finset`. `finset.prod_sum` is an alternative statement when the product is not
over `univ` -/
lemma finset.prod_univ_sum [decidable_eq α] [fintype α] [comm_semiring β] {δ : α → Type u_1}
[Π (a : α), decidable_eq (δ a)] {t : Π (a : α), finset (δ a)}
{f : Π (a : α), δ a → β} :
univ.prod (λ a, (t a).sum (λ b, f a b)) =
(fintype.pi_finset t).sum (λ p, univ.prod (λ x, f x (p x))) :=
by simp only [finset.prod_attach_univ, prod_sum, finset.sum_univ_pi]
/-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a fintype of cardinality `n`
gives `(a + b)^n`. The "good" proof involves expanding along all coordinates using the fact that
`x^n` is multilinear, but multilinear maps are only available now over rings, so we give instead
a proof reducing to the usual binomial theorem to have a result over semirings. -/
lemma fintype.sum_pow_mul_eq_add_pow
(α : Type*) [fintype α] {R : Type*} [comm_semiring R] (a b : R) :
finset.univ.sum (λ (s : finset α), a ^ s.card * b ^ (fintype.card α - s.card)) =
(a + b) ^ (fintype.card α) :=
finset.sum_pow_mul_eq_add_pow _ _ _
lemma fin.sum_pow_mul_eq_add_pow {n : ℕ} {R : Type*} [comm_semiring R] (a b : R) :
finset.univ.sum (λ (s : finset (fin n)), a ^ s.card * b ^ (n - s.card)) =
(a + b) ^ n :=
by simpa using fintype.sum_pow_mul_eq_add_pow (fin n) a b
/-- It is equivalent to sum a function over `fin n` or `finset.range n`. -/
@[to_additive]
lemma fin.prod_univ_eq_prod_range [comm_monoid α] (f : ℕ → α) (n : ℕ) :
finset.univ.prod (λ (i : fin n), f i.val) = (finset.range n).prod f :=
begin
apply finset.prod_bij (λ (a : fin n) ha, a.val),
{ assume a ha, simp [a.2] },
{ assume a ha, refl },
{ assume a b ha hb H, exact (fin.ext_iff _ _).2 H },
{ assume b hb, exact ⟨⟨b, list.mem_range.mp hb⟩, finset.mem_univ _, rfl⟩, }
end
@[to_additive]
lemma finset.prod_equiv [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : β → γ) :
finset.univ.prod (f ∘ e) = finset.univ.prod f :=
begin
apply prod_bij (λ i hi, e i) (λ i hi, mem_univ _) _ (λ a b _ _ h, e.injective h),
{ assume b hb,
rcases e.surjective b with ⟨a, ha⟩,
exact ⟨a, mem_univ _, ha.symm⟩, },
{ simp }
end
@[to_additive] lemma finset.prod_fiberwise [fintype β] [decidable_eq β] [comm_monoid γ]
(s : finset α) (f : α → β) (g : α → γ) :
∏ b : β, ∏ a in s.filter (λ a, f a = b), g a = ∏ a in s, g a :=
begin
classical,
have key : ∏ (b : β), ∏ a in s.filter (λ a, f a = b), g a =
∏ (a : α) in univ.bind (λ (b : β), s.filter (λ a, f a = b)), g a :=
(@prod_bind _ _ β g _ _ finset.univ (λ b : β, s.filter (λ a, f a = b)) _).symm,
{ simp only [key, filter_congr_decidable],
apply finset.prod_congr,
{ ext, simp only [mem_bind, mem_filter, mem_univ, exists_prop_of_true, exists_eq_right'] },
{ intros, refl } },
{ intros x hx y hy H z hz, apply H,
simp only [mem_filter, inf_eq_inter, mem_inter] at hz,
rw [← hz.1.2, ← hz.2.2] }
end
@[to_additive]
lemma fintype.prod_fiberwise [fintype α] [fintype β] [decidable_eq β] [comm_monoid γ]
(f : α → β) (g : α → γ) :
(∏ b : β, ∏ a : {a // f a = b}, g (a : α)) = ∏ a, g a :=
begin
rw [← finset.prod_equiv (equiv.sigma_preimage_equiv f) _, ← univ_sigma_univ, prod_sigma],
refl
end
section
open finset
variables {α₁ : Type*} {α₂ : Type*} {M : Type*} [fintype α₁] [fintype α₂] [comm_monoid M]
@[to_additive]
lemma fintype.prod_sum_type (f : α₁ ⊕ α₂ → M) :
(∏ x, f x) = (∏ a₁, f (sum.inl a₁)) * (∏ a₂, f (sum.inr a₂)) :=
begin
classical,
let s : finset (α₁ ⊕ α₂) := univ.image sum.inr,
rw [← prod_sdiff (subset_univ s),
← @prod_image (α₁ ⊕ α₂) _ _ _ _ _ _ sum.inl,
← @prod_image (α₁ ⊕ α₂) _ _ _ _ _ _ sum.inr],
{ congr, rw finset.ext, rintro (a|a);
{ simp only [mem_image, exists_eq, mem_sdiff, mem_univ, exists_false,
exists_prop_of_true, not_false_iff, and_self, not_true, and_false], } },
all_goals { intros, solve_by_elim [sum.inl.inj, sum.inr.inj], }
end
end
namespace list
lemma prod_take_of_fn [comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) :
((of_fn f).take i).prod = (finset.univ.filter (λ (j : fin n), j.val < i)).prod f :=
begin
have A : ∀ (j : fin n), ¬ (j.val < 0) := λ j, not_lt_bot,
induction i with i IH, { simp [A] },
by_cases h : i < n,
{ have : i < length (of_fn f), by rwa [length_of_fn f],
rw prod_take_succ _ _ this,
have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1))
= ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ _root_.singleton (⟨i, h⟩ : fin n),
by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] },
have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ)
(_root_.singleton (⟨i, h⟩ : fin n)), by simp,
rw [A, finset.prod_union B, IH],
simp },
{ have A : (of_fn f).take i = (of_fn f).take i.succ,
{ rw ← length_of_fn f at h,
have : length (of_fn f) ≤ i := not_lt.mp h,
rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] },
have B : ∀ (j : fin n), (j.val < i.succ) = (j.val < i),
{ assume j,
have : j.val < i := lt_of_lt_of_le j.2 (not_lt.mp h),
simp [this, lt_trans this (nat.lt_succ_self _)] },
simp [← A, B, IH] }
end
-- `to_additive` does not work on `prod_take_of_fn` because of `0 : ℕ` in the proof. Copy-paste the
-- proof instead...
lemma sum_take_of_fn [add_comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) :
((of_fn f).take i).sum = (finset.univ.filter (λ (j : fin n), j.val < i)).sum f :=
begin
have A : ∀ (j : fin n), ¬ (j.val < 0) := λ j, not_lt_bot,
induction i with i IH, { simp [A] },
by_cases h : i < n,
{ have : i < length (of_fn f), by rwa [length_of_fn f],
rw sum_take_succ _ _ this,
have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1))
= ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ _root_.singleton (⟨i, h⟩ : fin n),
by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] },
have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ)
(_root_.singleton (⟨i, h⟩ : fin n)), by simp,
rw [A, finset.sum_union B, IH],
simp },
{ have A : (of_fn f).take i = (of_fn f).take i.succ,
{ rw ← length_of_fn f at h,
have : length (of_fn f) ≤ i := not_lt.mp h,
rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] },
have B : ∀ (j : fin n), (j.val < i.succ) = (j.val < i),
{ assume j,
have : j.val < i := lt_of_lt_of_le j.2 (not_lt.mp h),
simp [this, lt_trans this (nat.lt_succ_self _)] },
simp [← A, B, IH] }
end
attribute [to_additive] prod_take_of_fn
@[to_additive]
lemma prod_of_fn [comm_monoid α] {n : ℕ} {f : fin n → α} :
(of_fn f).prod = finset.univ.prod f :=
begin
convert prod_take_of_fn f n,
{ rw [take_all_of_le (le_of_eq (length_of_fn f))] },
{ have : ∀ (j : fin n), j.val < n := λ j, j.2,
simp [this] }
end
end list
|
acbca6fa567e6d7d5f6566be406801c68033d5f0 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/module/ulift.lean | df0e18071df9443cd98ff7ee65664bf098c41738 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 3,927 | 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 algebra.ring.ulift
import data.equiv.module
/-!
# `ulift` instances for module and multiplicative actions
This file defines instances for module, mul_action and related structures on `ulift` types.
(Recall `ulift α` is just a "copy" of a type `α` in a higher universe.)
We also provide `ulift.module_equiv : ulift M ≃ₗ[R] M`.
-/
namespace ulift
universes u v w
variable {R : Type u}
variable {M : Type v}
variable {N : Type w}
instance has_scalar_left [has_scalar R M] :
has_scalar (ulift R) M :=
⟨λ s x, s.down • x⟩
@[simp] lemma smul_down [has_scalar R M] (s : ulift R) (x : M) : (s • x) = s.down • x := rfl
@[simp]
lemma smul_down' [has_scalar R M] (s : R) (x : ulift M) :
(s • x).down = s • x.down :=
rfl
instance is_scalar_tower [has_scalar R M] [has_scalar M N] [has_scalar R N]
[is_scalar_tower R M N] : is_scalar_tower (ulift R) M N :=
⟨λ x y z, show (x.down • y) • z = x.down • y • z, from smul_assoc _ _ _⟩
instance is_scalar_tower' [has_scalar R M] [has_scalar M N] [has_scalar R N]
[is_scalar_tower R M N] : is_scalar_tower R (ulift M) N :=
⟨λ x y z, show (x • y.down) • z = x • y.down • z, from smul_assoc _ _ _⟩
instance is_scalar_tower'' [has_scalar R M] [has_scalar M N] [has_scalar R N]
[is_scalar_tower R M N] : is_scalar_tower R M (ulift N) :=
⟨λ x y z, show up ((x • y) • z.down) = ⟨x • y • z.down⟩, by rw smul_assoc⟩
instance [has_scalar R M] [has_scalar Rᵐᵒᵖ M] [is_central_scalar R M] :
is_central_scalar R (ulift M) :=
⟨λ r m, congr_arg up $ op_smul_eq_smul r m.down⟩
instance mul_action [monoid R] [mul_action R M] :
mul_action (ulift R) M :=
{ smul := (•),
mul_smul := λ r s f, by { cases r, cases s, simp [mul_smul], },
one_smul := λ f, by { simp [one_smul], } }
instance mul_action' [monoid R] [mul_action R M] :
mul_action R (ulift M) :=
{ smul := (•),
mul_smul := λ r s f, by { cases f, ext, simp [mul_smul], },
one_smul := λ f, by { ext, simp [one_smul], } }
instance distrib_mul_action [monoid R] [add_monoid M] [distrib_mul_action R M] :
distrib_mul_action (ulift R) M :=
{ smul_zero := λ c, by { cases c, simp [smul_zero], },
smul_add := λ c f g, by { cases c, simp [smul_add], },
..ulift.mul_action }
instance distrib_mul_action' [monoid R] [add_monoid M] [distrib_mul_action R M] :
distrib_mul_action R (ulift M) :=
{ smul_zero := λ c, by { ext, simp [smul_zero], },
smul_add := λ c f g, by { ext, simp [smul_add], },
..ulift.mul_action' }
instance mul_distrib_mul_action [monoid R] [monoid M] [mul_distrib_mul_action R M] :
mul_distrib_mul_action (ulift R) M :=
{ smul_one := λ c, by { cases c, simp [smul_one], },
smul_mul := λ c f g, by { cases c, simp [smul_mul'], },
..ulift.mul_action }
instance mul_distrib_mul_action' [monoid R] [monoid M] [mul_distrib_mul_action R M] :
mul_distrib_mul_action R (ulift M) :=
{ smul_one := λ c, by { ext, simp [smul_one], },
smul_mul := λ c f g, by { ext, simp [smul_mul'], },
..ulift.mul_action' }
instance module [semiring R] [add_comm_monoid M] [module R M] :
module (ulift R) M :=
{ add_smul := λ c f g, by { cases c, simp [add_smul], },
zero_smul := λ f, by { simp [zero_smul], },
..ulift.distrib_mul_action }
instance module' [semiring R] [add_comm_monoid M] [module R M] :
module R (ulift M) :=
{ add_smul := by { intros, ext1, apply add_smul },
zero_smul := by { intros, ext1, apply zero_smul } }
/--
The `R`-linear equivalence between `ulift M` and `M`.
-/
def module_equiv [semiring R] [add_comm_monoid M] [module R M] : ulift M ≃ₗ[R] M :=
{ to_fun := ulift.down,
inv_fun := ulift.up,
map_smul' := λ r x, rfl,
map_add' := λ x y, rfl,
left_inv := by tidy,
right_inv := by tidy, }
end ulift
|
b071178807a4dab5187b014dedc5dfa8cd4ce421 | e1440579fb0723caf9edf1ed07aee74bbf4f5ce7 | /lean-experiments/stumps-learnable/src/stump/algorithm_measurable.lean | 0e97303330476875f98c93b93f8df0426fcbd754 | [
"Apache-2.0"
] | permissive | palmskog/coq-proba | 1ecc5b7f399894ea14d6094a31a063280a122099 | f73e2780871e2a3dd83b7ce9d3aed19f499f07e5 | refs/heads/master | 1,599,620,504,720 | 1,572,960,008,000 | 1,572,960,008,000 | 221,326,479 | 0 | 0 | Apache-2.0 | 1,573,598,769,000 | 1,573,598,768,000 | null | UTF-8 | Lean | false | false | 3,676 | lean | /-
Copyright © 2019, Oracle and/or its affiliates. All rights reserved.
-/
import .algorithm_definition
import .setup_measurable
open set
namespace stump
variables (μ: probability_measure ℍ) (target: ℍ) (n: ℕ)
@[simp]
lemma label_sample_measurable: ∀ n: ℕ, measurable (label_sample target n) :=
begin
intro,
apply measurable_map,
apply label_measurable,
end
@[simp]
lemma max_continuous: ∀ n, continuous (max n) :=
begin
intros,
induction n,
{
unfold max,
apply continuous_id,
},
{
unfold max,
simp,
apply continuous_if; intros,
{
unfold rlt at H, simp at H,
have FOO := @frontier_lt_subset_eq nnreal (vec nnreal (nat.succ n_n)) _ _ _ _ (λ x, max n_n x.snd) (λ x, x.fst) _ (continuous_fst),
{
simp at FOO,
have BAR := mem_of_mem_of_subset H FOO, clear FOO,
rw mem_set_of_eq at BAR,
exact eq.symm BAR,
},
{
apply continuous.comp,
assumption,
apply continuous_snd,
},
},
{
apply continuous.comp,
apply continuous_fst,
apply continuous_id,
},
{
apply continuous.comp,
assumption,
apply continuous.comp,
apply continuous_snd,
apply continuous_id,
},
},
end
@[simp]
lemma max_is_measurable: is_measurable {v: vec ℍ (nat.succ n) | rlt (max n v.snd) (v.fst)} :=
begin
dunfold vec,
unfold rlt,
simp,
apply test''',
{
apply continuous.comp,
apply max_continuous,
apply continuous_snd,
},
{
apply continuous_fst,
},
end
@[simp]
lemma max_measurable: ∀ n, measurable (max n) :=
begin
intro n,
induction n,
{
unfold max,
apply measurable_id,
},
{
unfold max,
apply measurable.if,
unfold_coes, apply max_is_measurable,
apply measurable_fst,
apply measurable_id,
apply measurable.comp,
apply n_ih,
apply measurable_snd,
apply measurable_id,
}
end
@[simp]
lemma choose_measurable: measurable (choose n) :=
begin
unfold choose,
apply measurable.comp,
apply max_measurable,
unfold filter,
apply measurable_map,
apply measurable.if,
unfold_coes,
{
have PROD: {a: ℍ × bool | a.snd = tt} = set.prod {x: ℍ | true} {b: bool | b = tt},
{
rw ext_iff, intros,
rw mem_prod_eq,
repeat {rw mem_set_of_eq},
finish,
},
rw PROD,
apply is_measurable_set_prod,
{
rw ← univ_def,
exact is_measurable.univ,
},
fsplit,
},
apply measurable_fst,
apply measurable_id,
apply measurable_const,
end
@[simp]
lemma is_measurable_vec_1:
∀ ε, is_measurable {v: vec (ℍ × bool) n | error μ target (choose n v) > ε} :=
begin
intros,
have PREIM: {v: vec (ℍ × bool) n | error μ target (choose n v) > ε} = (choose n) ⁻¹' {h: ℍ | error μ target h > ε},
simp,
rw PREIM,
apply measurable.preimage; try {simp},
end
@[simp]
lemma is_measurable_vec_2:
∀ ε, is_measurable {v: vec (ℍ × bool) n | error μ target (choose n v) ≤ ε} :=
begin
intros,
have PREIM: {v: vec (ℍ × bool) n | error μ target (choose n v) ≤ ε} = (choose n) ⁻¹' {h: ℍ | error μ target h ≤ ε},
simp,
rw PREIM,
apply measurable.preimage; try {simp},
end
end stump |
93a61711e16581d1835a579adca6c884167b5267 | df561f413cfe0a88b1056655515399c546ff32a5 | /3-function-world/l7.lean | bc3895ea172a89974500473fde69ba94932f7a00 | [] | no_license | nicholaspun/natural-number-game-solutions | 31d5158415c6f582694680044c5c6469032c2a06 | 1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0 | refs/heads/main | 1,675,123,625,012 | 1,607,633,548,000 | 1,607,633,548,000 | 318,933,860 | 3 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 121 | lean | example (P Q F : Type) : (P → Q) → ((Q → F) → (P → F)) :=
begin
intros f g p,
have q : Q := f p,
exact g q,
end |
4e10b352707a9052b94c255614302799311948b1 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /src/Lean/ParserCompiler.lean | e050d044a110b187f8f719b6a74c22fe22c7a03c | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,372 | lean | /-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
/-!
Gadgets for compiling parser declarations into other programs, such as pretty printers.
-/
import Lean.Util.ReplaceExpr
import Lean.Meta.Basic
import Lean.Meta.WHNF
import Lean.ParserCompiler.Attribute
import Lean.Parser.Extension
namespace Lean
namespace ParserCompiler
structure Context (α : Type) :=
(varName : Name)
(categoryAttr : KeyedDeclsAttribute α)
(combinatorAttr : CombinatorAttribute)
def Context.tyName {α} (ctx : Context α) : Name := ctx.categoryAttr.defn.valueTypeName
-- replace all references of `Parser` with `tyName` as a first approximation
def preprocessParserBody {α} (ctx : Context α) (e : Expr) : Expr :=
e.replace fun e => if e.isConstOf `Lean.Parser.Parser then mkConst ctx.tyName else none
section
open Meta
variables {α} (ctx : Context α) (force : Bool := false) in
/--
Translate an expression of type `Parser` into one of type `tyName`, tagging intermediary constants with
`ctx.combinatorAttr`. If `force` is `false`, refuse to do so for imported constants. -/
partial def compileParserExpr (e : Expr) : MetaM Expr := do
let e ← whnfCore e
match e with
| e@(Expr.lam _ _ _ _) => lambdaLetTelescope e fun xs b => compileParserExpr b >>= mkLambdaFVars xs
| e@(Expr.fvar _ _) => pure e
| _ => do
let fn := e.getAppFn
let Expr.const c _ _ ← pure fn
| throwError! "call of unknown parser at '{e}'"
let args := e.getAppArgs
-- call the translated `p` with (a prefix of) the arguments of `e`, recursing for arguments
-- of type `ty` (i.e. formerly `Parser`)
let mkCall (p : Name) := do
let ty ← inferType (mkConst p)
forallTelescope ty fun params _ => do
let mut p := mkConst p
let args := e.getAppArgs
for i in [:Nat.min params.size args.size] do
let param := params[i]
let arg := args[i]
let paramTy ← inferType param
let resultTy ← forallTelescope paramTy fun _ b => pure b
let arg ← if resultTy.isConstOf ctx.tyName then compileParserExpr arg else pure arg
p := mkApp p arg
pure p
let env ← getEnv
match ctx.combinatorAttr.getDeclFor? env c with
| some p => mkCall p
| none =>
let c' := c ++ ctx.varName
let cinfo ← getConstInfo c
let resultTy ← forallTelescope cinfo.type fun _ b => pure b
if resultTy.isConstOf `Lean.Parser.TrailingParser || resultTy.isConstOf `Lean.Parser.Parser then do
-- synthesize a new `[combinatorAttr c]`
let some value ← pure cinfo.value?
| throwError! "don't know how to generate {ctx.varName} for non-definition '{e}'"
unless (env.getModuleIdxFor? c).isNone || force do
throwError! "refusing to generate code for imported parser declaration '{c}'; use `@[runParserAttributeHooks]` on its definition instead."
let value ← compileParserExpr $ preprocessParserBody ctx value
let ty ← forallTelescope cinfo.type fun params _ =>
params.foldrM (init := mkConst ctx.tyName) fun param ty => do
let paramTy ← inferType param;
let paramTy ← forallTelescope paramTy fun _ b => pure $
if b.isConstOf `Lean.Parser.Parser then mkConst ctx.tyName
else b
pure $ mkForall `_ BinderInfo.default paramTy ty
let decl := Declaration.defnDecl {
name := c', lparams := [],
type := ty, value := value, hints := ReducibilityHints.opaque, isUnsafe := false }
let env ← getEnv
let env ← match env.addAndCompile {} decl with
| Except.ok env => pure env
| Except.error kex => do throwError (← liftIO $ (kex.toMessageData {}).toString)
setEnv $ ctx.combinatorAttr.setDeclFor env c c'
mkCall c'
else
-- if this is a generic function, e.g. `AndThen.andthen`, it's easier to just unfold it until we are
-- back to parser combinators
let some e' ← unfoldDefinition? e
| throwError! "don't know how to generate {ctx.varName} for non-parser combinator '{e}'"
compileParserExpr e'
end
open Core
/-- Compile the given declaration into a `[(builtin)categoryAttr declName]` -/
def compileCategoryParser {α} (ctx : Context α) (declName : Name) (builtin : Bool) : AttrM Unit := do
-- This will also tag the declaration as a `[combinatorParenthesizer declName]` in case the parser is used by other parsers.
-- Note that simply having `[(builtin)Parenthesizer]` imply `[combinatorParenthesizer]` is not ideal since builtin
-- attributes are active only in the next stage, while `[combinatorParenthesizer]` is active immediately (since we never
-- call them at compile time but only reference them).
let (Expr.const c' _ _) ← (compileParserExpr ctx (mkConst declName) (force := false)).run'
| unreachable!
-- We assume that for tagged parsers, the kind is equal to the declaration name. This is automatically true for parsers
-- using `parser!` or `syntax`.
let kind := declName
addAttribute c' (if builtin then ctx.categoryAttr.defn.builtinName else ctx.categoryAttr.defn.name) (mkNullNode #[mkIdent kind])
variables {α} (ctx : Context α) in
def compileEmbeddedParsers : ParserDescr → MetaM Unit
| ParserDescr.parser constName => discard $ compileParserExpr ctx (mkConst constName) (force := false)
| ParserDescr.andthen d₁ d₂ => compileEmbeddedParsers d₁ *> compileEmbeddedParsers d₂
| ParserDescr.orelse d₁ d₂ => compileEmbeddedParsers d₁ *> compileEmbeddedParsers d₂
| ParserDescr.optional d => compileEmbeddedParsers d
| ParserDescr.lookahead d => compileEmbeddedParsers d
| ParserDescr.try d => compileEmbeddedParsers d
| ParserDescr.notFollowedBy d => compileEmbeddedParsers d
| ParserDescr.many d => compileEmbeddedParsers d
| ParserDescr.many1 d => compileEmbeddedParsers d
| ParserDescr.sepBy d₁ d₂ _ => compileEmbeddedParsers d₁ *> compileEmbeddedParsers d₂
| ParserDescr.sepBy1 d₁ d₂ _ => compileEmbeddedParsers d₁ *> compileEmbeddedParsers d₂
| ParserDescr.node k prec d => compileEmbeddedParsers d
| ParserDescr.trailingNode k prec d => compileEmbeddedParsers d
| ParserDescr.interpolatedStr d => compileEmbeddedParsers d
| ParserDescr.withPosition d => compileEmbeddedParsers d
| ParserDescr.checkCol _ => pure ()
| ParserDescr.symbol tk => pure ()
| ParserDescr.numLit => pure ()
| ParserDescr.strLit => pure ()
| ParserDescr.charLit => pure ()
| ParserDescr.nameLit => pure ()
| ParserDescr.ident => pure ()
| ParserDescr.nonReservedSymbol tk includeIdent => pure ()
| ParserDescr.noWs => pure ()
| ParserDescr.cat catName prec => pure ()
/-- Precondition: `α` must match `ctx.tyName`. -/
unsafe def registerParserCompiler {α} (ctx : Context α) : IO Unit := do
Parser.registerParserAttributeHook {
postAdd := fun catName constName builtin => do
let info ← getConstInfo constName
if info.type.isConstOf `Lean.ParserDescr || info.type.isConstOf `Lean.TrailingParserDescr then
let d ← evalConstCheck ParserDescr `Lean.ParserDescr constName <|>
evalConstCheck TrailingParserDescr `Lean.TrailingParserDescr constName
compileEmbeddedParsers ctx d $.run'
else
if catName.isAnonymous then
-- `[runBuiltinParserAttributeHooks]` => force compilation even if imported, do not apply `ctx.categoryAttr`.
discard (compileParserExpr ctx (mkConst constName) (force := true)).run'
else
compileCategoryParser ctx constName builtin
}
end ParserCompiler
end Lean
|
e777a50678d2f26ab23b4468c379583b7a949033 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/geometry/manifold/bump_function.lean | d5f65ecc439dc50ed59526427efa56d64112ebe7 | [
"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,448 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.calculus.specific_functions
import geometry.manifold.diffeomorph
import geometry.manifold.instances.real
/-!
# Smooth bump functions on a smooth manifold
In this file we define `smooth_bump_function I c` to be a bundled smooth "bump" function centered at
`c`. It is a structure that consists of two real numbers `0 < r < R` with small enough `R`. We
define a coercion to function for this type, and for `f : smooth_bump_function I c`, the function
`⇑f` written in the extended chart at `c` has the following properties:
* `f x = 1` in the closed euclidean ball of radius `f.r` centered at `c`;
* `f x = 0` outside of the euclidean ball of radius `f.R` centered at `c`;
* `0 ≤ f x ≤ 1` for all `x`.
The actual statements involve (pre)images under `ext_chart_at I f` and are given as lemmas in the
`smooth_bump_function` namespace.
## Tags
manifold, smooth bump function
-/
universes uE uF uH uM
variables
{E : Type uE} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E]
{H : Type uH} [topological_space H] (I : model_with_corners ℝ E H)
{M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M]
open function filter finite_dimensional set
open_locale topological_space manifold classical filter big_operators
noncomputable theory
/-!
### Smooth bump function
In this section we define a structure for a bundled smooth bump function and prove its properties.
-/
/-- Given a smooth manifold modelled on a finite dimensional space `E`,
`f : smooth_bump_function I M` is a smooth function on `M` such that in the extended chart `e` at
`f.c`:
* `f x = 1` in the closed euclidean ball of radius `f.r` centered at `f.c`;
* `f x = 0` outside of the euclidean ball of radius `f.R` centered at `f.c`;
* `0 ≤ f x ≤ 1` for all `x`.
The structure contains data required to construct a function with these properties. The function is
available as `⇑f` or `f x`. Formal statements of the properties listed above involve some
(pre)images under `ext_chart_at I f.c` and are given as lemmas in the `smooth_bump_function`
namespace. -/
structure smooth_bump_function (c : M) extends times_cont_diff_bump (ext_chart_at I c c) :=
(closed_ball_subset :
(euclidean.closed_ball (ext_chart_at I c c) R) ∩ range I ⊆ (ext_chart_at I c).target)
variable {M}
namespace smooth_bump_function
open euclidean (renaming dist -> eudist)
variables {c : M} (f : smooth_bump_function I c) {x : M} {I}
/-- The function defined by `f : smooth_bump_function c`. Use automatic coercion to function
instead. -/
def to_fun : M → ℝ :=
indicator (chart_at H c).source (f.to_times_cont_diff_bump ∘ ext_chart_at I c)
instance : has_coe_to_fun (smooth_bump_function I c) := ⟨_, to_fun⟩
lemma coe_def :
⇑f = indicator (chart_at H c).source (f.to_times_cont_diff_bump ∘ ext_chart_at I c) :=
rfl
lemma R_pos : 0 < f.R := f.to_times_cont_diff_bump.R_pos
lemma ball_subset :
ball (ext_chart_at I c c) f.R ∩ range I ⊆ (ext_chart_at I c).target :=
subset.trans (inter_subset_inter_left _ ball_subset_closed_ball) f.closed_ball_subset
lemma eq_on_source :
eq_on f (f.to_times_cont_diff_bump ∘ ext_chart_at I c) (chart_at H c).source :=
eq_on_indicator
lemma eventually_eq_of_mem_source (hx : x ∈ (chart_at H c).source) :
f =ᶠ[𝓝 x] f.to_times_cont_diff_bump ∘ ext_chart_at I c :=
f.eq_on_source.eventually_eq_of_mem $ is_open.mem_nhds (chart_at H c).open_source hx
lemma one_of_dist_le (hs : x ∈ (chart_at H c).source)
(hd : eudist (ext_chart_at I c x) (ext_chart_at I c c) ≤ f.r) :
f x = 1 :=
by simp only [f.eq_on_source hs, (∘), f.to_times_cont_diff_bump.one_of_mem_closed_ball hd]
lemma support_eq_inter_preimage :
support f =
(chart_at H c).source ∩ (ext_chart_at I c ⁻¹' ball (ext_chart_at I c c) f.R) :=
by rw [coe_def, support_indicator, (∘), support_comp_eq_preimage, ← ext_chart_at_source I,
← (ext_chart_at I c).symm_image_target_inter_eq',
← (ext_chart_at I c).symm_image_target_inter_eq', f.to_times_cont_diff_bump.support_eq]
lemma open_support : is_open (support f) :=
by { rw support_eq_inter_preimage, exact ext_chart_preimage_open_of_open I c is_open_ball }
lemma support_eq_symm_image :
support f = (ext_chart_at I c).symm '' (ball (ext_chart_at I c c) f.R ∩ range I) :=
begin
rw [f.support_eq_inter_preimage, ← ext_chart_at_source I,
← (ext_chart_at I c).symm_image_target_inter_eq', inter_comm],
congr' 1 with y,
exact and.congr_right_iff.2
(λ hy, ⟨λ h, ext_chart_at_target_subset_range _ _ h, λ h, f.ball_subset ⟨hy, h⟩⟩)
end
lemma support_subset_source : support f ⊆ (chart_at H c).source :=
by { rw [f.support_eq_inter_preimage, ← ext_chart_at_source I], exact inter_subset_left _ _ }
lemma image_eq_inter_preimage_of_subset_support {s : set M} (hs : s ⊆ support f) :
ext_chart_at I c '' s =
closed_ball (ext_chart_at I c c) f.R ∩ range I ∩ (ext_chart_at I c).symm ⁻¹' s :=
begin
rw [support_eq_inter_preimage, subset_inter_iff, ← ext_chart_at_source I,
← image_subset_iff] at hs,
cases hs with hse hsf,
apply subset.antisymm,
{ refine subset_inter (subset_inter (subset.trans hsf ball_subset_closed_ball) _) _,
{ rintro _ ⟨x, -, rfl⟩, exact mem_range_self _ },
{ rw [(ext_chart_at I c).image_eq_target_inter_inv_preimage hse],
exact inter_subset_right _ _ } },
{ refine subset.trans (inter_subset_inter_left _ f.closed_ball_subset) _,
rw [(ext_chart_at I c).image_eq_target_inter_inv_preimage hse] }
end
lemma mem_Icc : f x ∈ Icc (0 : ℝ) 1 :=
begin
have : f x = 0 ∨ f x = _, from indicator_eq_zero_or_self _ _ _,
cases this; rw this,
exacts [left_mem_Icc.2 zero_le_one,
⟨f.to_times_cont_diff_bump.nonneg, f.to_times_cont_diff_bump.le_one⟩]
end
lemma nonneg : 0 ≤ f x := f.mem_Icc.1
lemma le_one : f x ≤ 1 := f.mem_Icc.2
lemma eventually_eq_one_of_dist_lt (hs : x ∈ (chart_at H c).source)
(hd : eudist (ext_chart_at I c x) (ext_chart_at I c c) < f.r) :
f =ᶠ[𝓝 x] 1 :=
begin
filter_upwards [is_open.mem_nhds (ext_chart_preimage_open_of_open I c is_open_ball) ⟨hs, hd⟩],
rintro z ⟨hzs, hzd : _ < _⟩,
exact f.one_of_dist_le hzs hzd.le
end
lemma eventually_eq_one : f =ᶠ[𝓝 c] 1 :=
f.eventually_eq_one_of_dist_lt (mem_chart_source _ _) $
by { rw [euclidean.dist, dist_self], exact f.r_pos }
@[simp] lemma eq_one : f c = 1 := f.eventually_eq_one.eq_of_nhds
lemma support_mem_nhds : support f ∈ 𝓝 c :=
f.eventually_eq_one.mono $ λ x hx, by { rw hx, exact one_ne_zero }
lemma closure_support_mem_nhds : closure (support f) ∈ 𝓝 c :=
mem_of_superset f.support_mem_nhds subset_closure
lemma c_mem_support : c ∈ support f := mem_of_mem_nhds f.support_mem_nhds
lemma nonempty_support : (support f).nonempty := ⟨c, f.c_mem_support⟩
lemma compact_symm_image_closed_ball :
is_compact ((ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I)) :=
(compact_ball.inter_right I.closed_range).image_of_continuous_on $
(ext_chart_at_continuous_on_symm _ _).mono f.closed_ball_subset
/-- Given a smooth bump function `f : smooth_bump_function I c`, the closed ball of radius `f.R` is
known to include the support of `f`. These closed balls (in the model normed space `E`) intersected
with `set.range I` form a basis of `𝓝[range I] (ext_chart_at I c c)`. -/
lemma nhds_within_range_basis :
(𝓝[range I] (ext_chart_at I c c)).has_basis (λ f : smooth_bump_function I c, true)
(λ f, closed_ball (ext_chart_at I c c) f.R ∩ range I) :=
begin
refine ((nhds_within_has_basis euclidean.nhds_basis_closed_ball _).restrict_subset
(ext_chart_at_target_mem_nhds_within _ _)).to_has_basis' _ _,
{ rintro R ⟨hR0, hsub⟩,
exact ⟨⟨⟨⟨R / 2, R, half_pos hR0, half_lt_self hR0⟩⟩, hsub⟩, trivial, subset.rfl⟩ },
{ exact λ f _, inter_mem (mem_nhds_within_of_mem_nhds $ closed_ball_mem_nhds f.R_pos)
self_mem_nhds_within }
end
lemma closed_image_of_closed {s : set M} (hsc : is_closed s) (hs : s ⊆ support f) :
is_closed (ext_chart_at I c '' s) :=
begin
rw f.image_eq_inter_preimage_of_subset_support hs,
refine continuous_on.preimage_closed_of_closed
((ext_chart_continuous_on_symm _ _).mono f.closed_ball_subset) _ hsc,
exact is_closed.inter is_closed_closed_ball I.closed_range
end
/-- If `f` is a smooth bump function and `s` closed subset of the support of `f` (i.e., of the open
ball of radius `f.R`), then there exists `0 < r < f.R` such that `s` is a subset of the open ball of
radius `r`. Formally, `s ⊆ e.source ∩ e ⁻¹' (ball (e c) r)`, where `e = ext_chart_at I c`. -/
lemma exists_r_pos_lt_subset_ball {s : set M} (hsc : is_closed s) (hs : s ⊆ support f) :
∃ r (hr : r ∈ Ioo 0 f.R), s ⊆
(chart_at H c).source ∩ ext_chart_at I c ⁻¹' (ball (ext_chart_at I c c) r) :=
begin
set e := ext_chart_at I c,
have : is_closed (e '' s) := f.closed_image_of_closed hsc hs,
rw [support_eq_inter_preimage, subset_inter_iff, ← image_subset_iff] at hs,
rcases euclidean.exists_pos_lt_subset_ball f.R_pos this hs.2 with ⟨r, hrR, hr⟩,
exact ⟨r, hrR, subset_inter hs.1 (image_subset_iff.1 hr)⟩
end
/-- Replace `r` with another value in the interval `(0, f.R)`. -/
def update_r (r : ℝ) (hr : r ∈ Ioo 0 f.R) : smooth_bump_function I c :=
⟨⟨⟨r, f.R, hr.1, hr.2⟩⟩, f.closed_ball_subset⟩
@[simp] lemma update_r_R {r : ℝ} (hr : r ∈ Ioo 0 f.R) : (f.update_r r hr).R = f.R := rfl
@[simp] lemma update_r_r {r : ℝ} (hr : r ∈ Ioo 0 f.R) : (f.update_r r hr).r = r := rfl
@[simp] lemma support_update_r {r : ℝ} (hr : r ∈ Ioo 0 f.R) :
support (f.update_r r hr) = support f :=
by simp only [support_eq_inter_preimage, update_r_R]
instance : inhabited (smooth_bump_function I c) :=
classical.inhabited_of_nonempty nhds_within_range_basis.nonempty
variables [t2_space M]
lemma closed_symm_image_closed_ball :
is_closed ((ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I)) :=
f.compact_symm_image_closed_ball.is_closed
lemma closure_support_subset_symm_image_closed_ball :
closure (support f) ⊆
(ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I) :=
begin
rw support_eq_symm_image,
exact closure_minimal (image_subset _ $ inter_subset_inter_left _ ball_subset_closed_ball)
f.closed_symm_image_closed_ball
end
lemma closure_support_subset_ext_chart_at_source :
closure (support f) ⊆ (ext_chart_at I c).source :=
calc closure (support f)
⊆ (ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I) :
f.closure_support_subset_symm_image_closed_ball
... ⊆ (ext_chart_at I c).symm '' (ext_chart_at I c).target :
image_subset _ f.closed_ball_subset
... = (ext_chart_at I c).source :
(ext_chart_at I c).symm_image_target_eq_source
lemma closure_support_subset_chart_at_source :
closure (support f) ⊆ (chart_at H c).source :=
by simpa only [ext_chart_at_source] using f.closure_support_subset_ext_chart_at_source
lemma compact_closure_support : is_compact (closure $ support f) :=
compact_of_is_closed_subset f.compact_symm_image_closed_ball is_closed_closure
f.closure_support_subset_symm_image_closed_ball
variables (I c)
/-- The closures of supports of smooth bump functions centered at `c` form a basis of `𝓝 c`.
In other words, each of these closures is a neighborhood of `c` and each neighborhood of `c`
includes `closure (support f)` for some `f : smooth_bump_function I c`. -/
lemma nhds_basis_closure_support :
(𝓝 c).has_basis (λ f : smooth_bump_function I c, true) (λ f, closure $ support f) :=
begin
have : (𝓝 c).has_basis (λ f : smooth_bump_function I c, true)
(λ f, (ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I)),
{ rw [← ext_chart_at_symm_map_nhds_within_range I c],
exact nhds_within_range_basis.map _ },
refine this.to_has_basis' (λ f hf, ⟨f, trivial, f.closure_support_subset_symm_image_closed_ball⟩)
(λ f _, f.closure_support_mem_nhds),
end
variable {c}
/-- Given `s ∈ 𝓝 c`, the supports of smooth bump functions `f : smooth_bump_function I c` such that
`closure (support f) ⊆ s` form a basis of `𝓝 c`. In other words, each of these supports is a
neighborhood of `c` and each neighborhood of `c` includes `support f` for some `f :
smooth_bump_function I c` such that `closure (support f) ⊆ s`. -/
lemma nhds_basis_support {s : set M} (hs : s ∈ 𝓝 c) :
(𝓝 c).has_basis (λ f : smooth_bump_function I c, closure (support f) ⊆ s) (λ f, support f) :=
((nhds_basis_closure_support I c).restrict_subset hs).to_has_basis'
(λ f hf, ⟨f, hf.2, subset_closure⟩) (λ f hf, f.support_mem_nhds)
variables [smooth_manifold_with_corners I M] {I}
/-- A smooth bump function is infinitely smooth. -/
protected lemma smooth : smooth I 𝓘(ℝ) f :=
begin
refine times_cont_mdiff_of_support (λ x hx, _),
have : x ∈ (chart_at H c).source := f.closure_support_subset_chart_at_source hx,
refine times_cont_mdiff_at.congr_of_eventually_eq _
(f.eq_on_source.eventually_eq_of_mem $ is_open.mem_nhds (chart_at _ _).open_source this),
exact f.to_times_cont_diff_bump.times_cont_diff_at.times_cont_mdiff_at.comp _
(times_cont_mdiff_at_ext_chart_at' this)
end
protected lemma smooth_at {x} : smooth_at I 𝓘(ℝ) f x := f.smooth.smooth_at
protected lemma continuous : continuous f := f.smooth.continuous
/-- If `f : smooth_bump_function I c` is a smooth bump function and `g : M → G` is a function smooth
on the source of the chart at `c`, then `f • g` is smooth on the whole manifold. -/
lemma smooth_smul {G} [normed_group G] [normed_space ℝ G]
{g : M → G} (hg : smooth_on I 𝓘(ℝ, G) g (chart_at H c).source) :
smooth I 𝓘(ℝ, G) (λ x, f x • g x) :=
begin
apply times_cont_mdiff_of_support (λ x hx, _),
have : x ∈ (chart_at H c).source,
calc x ∈ closure (support (λ x, f x • g x)) : hx
... ⊆ closure (support f) : closure_mono (support_smul_subset_left _ _)
... ⊆ (chart_at _ c).source : f.closure_support_subset_chart_at_source,
exact f.smooth_at.smul ((hg _ this).times_cont_mdiff_at $
is_open.mem_nhds (chart_at _ _).open_source this)
end
end smooth_bump_function
|
37ac438173aa7459ae73922e0df2b6afeab6af75 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/1112.lean | b161d95bbf2eed00ecd3b601222c0352ed546a63 | [
"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 | 129 | lean | mutual
inductive Lift : Bool -> Type -> Type 2
inductive Env : List Bool -> Type 2
| cons : Lift t y -> Env [t]
end
|
4926580686006011cb1a282962148064a8a56de1 | 0bebf71b69ba876e3ff052251728b46e79d4f55b | /differential_geometry_in_hott/lean/algebra_of_smooth_functions.lean | 89812772f6f25262933ed68d7198e9b5c54db28c | [] | no_license | glangmead/writing | 448f4b3880d5478bc0a511c8d7038ab1cd95e0a6 | 296aa7ebc5c880fe1e1b7a594be67113d8cba677 | refs/heads/master | 1,688,939,782,411 | 1,687,865,154,000 | 1,687,865,154,000 | 212,832,461 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,237 | lean | import data.set.basic
import data.equiv.fin
import ring_theory.algebra
import tactic.pi_instances
import topology.basic
import topology.instances.real
import geometry.manifold.real_instances
import geometry.manifold.mfderiv
noncomputable theory
section playground
-- Real-valued functions and their properties (ring, algebra)
def real_functions (α : Type*) := α → ℝ
instance fns_are_ring (α: Type*) : ring (real_functions α) := by pi_instance
instance fns_are_algebra (M : Type*) : algebra ℝ (real_functions M) := {
smul := λ r f m, r * f m,
to_fun := λ r m, r,
commutes' := by {intros; ext; apply mul_comm},
smul_def' := by {intros; ext; refl}, -- smul and to_fun are compatible
map_one' := by {intros; ext; refl},
map_mul' := by {intros; ext; refl},
map_zero' := by {intros; ext; refl},
map_add' := by {intros; ext; refl}
}
-- continuous Real-valued functions and those same properties (ring, algebra)
def cont_real_fns (α: Type*) [tm : topological_space α] := {f : real_functions α // continuous f}
instance cont_fns_are_ring (α: Type*) [tm : topological_space α] : ring (cont_real_fns α) := {
add := λ f g, ⟨f.val + g.val, continuous.add f.property g.property ⟩,
add_assoc := by {intros; apply subtype.eq; apply add_assoc},
zero := ⟨0, continuous_const⟩,
zero_add := by {intros; apply subtype.eq; apply zero_add},
add_zero := by {intros; apply subtype.eq; apply add_zero},
neg := λ f, ⟨-f.val, continuous.neg f.property⟩,
add_left_neg := by {intros; apply subtype.eq; apply add_left_neg},
add_comm := by {intros; apply subtype.eq; apply add_comm},
mul := λ f g, ⟨f.val * g.val, continuous.mul f.property g.property⟩,
mul_assoc := by {intros; apply subtype.eq; apply mul_assoc},
one := ⟨1, continuous_const⟩,
one_mul := by {intros; apply subtype.eq; apply one_mul},
mul_one := by {intros; apply subtype.eq; apply mul_one},
left_distrib := by {intros; apply subtype.eq; apply left_distrib},
right_distrib := by {intros; apply subtype.eq; apply right_distrib},
}
instance cont_fns_are_algebra (α: Type*) [tm : topological_space α] : algebra ℝ (cont_real_fns α) :=
{
smul := λ r f, ⟨λ m, r * f.val m, continuous.mul continuous_const f.property⟩,
to_fun := λ r, ⟨λ m, r, continuous_const⟩,
commutes' := by {intros; apply subtype.eq; ext; apply mul_comm},
smul_def' := by {intros; apply subtype.eq; ext; refl},
map_one' := by {intros; apply subtype.eq; ext; refl},
map_mul' := by {intros; apply subtype.eq; ext; refl},
map_zero' := by {intros; apply subtype.eq; ext; refl},
map_add' := by {intros; apply subtype.eq; ext; refl},
}
-- def euc_to_r : (euclidean_space 1) → ℝ := begin
-- have x : fin 1 := begin
-- have s : punit := punit.star,
-- exact fin_one_equiv.symm s,
-- end,
-- intro f,
-- exact f x,
-- end
-- def r_to_euc : ℝ → (euclidean_space 1) := λ x n, x
def r_model : model_with_corners ℝ ℝ ℝ := {
to_fun := id,
inv_fun := id,
source := set.univ,
target := set.univ,
map_source := by simp,
map_target := by simp,
left_inv := by simp,
right_inv := by simp,
source_eq := by simp,
unique_diff := by { rw set.range_id, exact is_open_univ.unique_diff_on }, -- see model_with_corners_self
continuous_to_fun := continuous_id,
continuous_inv_fun := continuous_id,
}
section smooth
def smooth_real_fns {n : ℕ}
(I : model_with_corners ℝ (euclidean_space n) (euclidean_space n))
(M : Type) [tm: topological_space M] [m: manifold (euclidean_space n) M] [smc: smooth_manifold_with_corners I M] :=
{f : real_functions M // mdifferentiable I r_model f}
instance smooth_fns_are_ring {n : ℕ}
(I : model_with_corners ℝ (euclidean_space n) (euclidean_space n))
(M : Type) [tm: topological_space M] [m: manifold (euclidean_space n) M] [smc: smooth_manifold_with_corners I M]
: ring (smooth_real_fns I M) := {
add := begin
refine λ f g, ⟨f.val + g.val, _⟩,
intro x,
have hcf : continuous_at f.val x := and.left (f.property x),
have hcg : continuous_at g.val x := and.left (g.property x),
have hc : continuous_at (f.val + g.val) x := continuous_at.add hcf hcg,
refine and.intro hc _,
exact differentiable_within_at.add (and.right (f.property x)) (and.right (g.property x)),
end,
mul := begin
refine λ f g, ⟨f.val * g.val, _⟩,
intro x,
have hcf : continuous_at f.val x := and.left (f.property x),
have hcg : continuous_at g.val x := and.left (g.property x),
have hc : continuous_at (f.val * g.val) x := continuous_at.mul hcf hcg,
refine and.intro hc _,
exact differentiable_within_at.mul (and.right (f.property x)) (and.right (g.property x)),
end,
neg := begin
refine λ f, ⟨-f.val, _⟩,
intro x,
have hcf : continuous_at f.val x := and.left (f.property x),
have hc : continuous_at (-f.val) x := continuous_at.neg hcf,
refine and.intro hc _,
exact differentiable_within_at.neg (and.right (f.property x)),
end,
zero := ⟨0, mdifferentiable_const I r_model⟩,
one := ⟨1, mdifferentiable_const I r_model⟩,
add_assoc := by {intros; apply subtype.eq; apply add_assoc},
zero_add := by {intros; apply subtype.eq; apply zero_add},
add_zero := by {intros; apply subtype.eq; apply add_zero},
add_left_neg := by {intros; apply subtype.eq; apply add_left_neg},
add_comm := by {intros; apply subtype.eq; apply add_comm},
mul_assoc := by {intros; apply subtype.eq; apply mul_assoc},
one_mul := by {intros; apply subtype.eq; apply one_mul},
mul_one := by {intros; apply subtype.eq; apply mul_one},
left_distrib := by {intros; apply subtype.eq; apply left_distrib},
right_distrib := by {intros; apply subtype.eq; apply right_distrib},
}
instance smooth_fns_are_algebra {n : ℕ}
(I : model_with_corners ℝ (euclidean_space n) (euclidean_space n))
(M : Type) [tm: topological_space M] [m: manifold (euclidean_space n) M] [smc: smooth_manifold_with_corners I M]
: algebra ℝ (smooth_real_fns I M) :=
{
smul := begin
refine λ r f, ⟨λ m, r * f.val m, _⟩,
intro x,
have hcf : continuous_at f.val x := and.left (f.property x),
have hc : continuous_at (λ m, r * f.val m) x := continuous_at.mul continuous_at_const hcf,
refine and.intro hc _,
exact differentiable_within_at.mul (differentiable_within_at_const r) (and.right (f.property x)),
end,
to_fun := λ r, ⟨λ m, r, mdifferentiable_const I r_model⟩,
commutes' := by {intros; apply subtype.eq; ext; apply mul_comm},
smul_def' := by {intros; apply subtype.eq; ext; refl},
map_one' := by {intros; apply subtype.eq; ext; refl},
map_mul' := by {intros; apply subtype.eq; ext; refl},
map_zero' := by {intros; apply subtype.eq; ext; refl},
map_add' := by {intros; apply subtype.eq; ext; refl},
}
-- instance r_smooth_mfd : smooth_manifold_with_corners r_model ℝ := {}
def ev {n : ℕ}
(I : model_with_corners ℝ (euclidean_space n) (euclidean_space n))
(M : Type) [tm: topological_space M] [m: manifold (euclidean_space n) M] [smc: smooth_manifold_with_corners I M]
: M → smooth_real_fns I M → ℝ := λ x f, f.val x
end smooth
end playground
|
262be960fe4a4bd40e2929a06fa306df79be7422 | b00eb947a9c4141624aa8919e94ce6dcd249ed70 | /stage0/src/Lean/Elab/Syntax.lean | 5615583a9d2d9c8146374d732600d000d5a614ff | [
"Apache-2.0"
] | permissive | gebner/lean4-old | a4129a041af2d4d12afb3a8d4deedabde727719b | ee51cdfaf63ee313c914d83264f91f414a0e3b6e | refs/heads/master | 1,683,628,606,745 | 1,622,651,300,000 | 1,622,654,405,000 | 142,608,821 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 29,560 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Command
import Lean.Parser.Syntax
namespace Lean.Elab.Term
/-
Expand `optional «precedence»` where
«precedence» := leading_parser " : " >> precedenceParser -/
def expandOptPrecedence (stx : Syntax) : MacroM (Option Nat) :=
if stx.isNone then
return none
else
return some (← evalPrec stx[0][1])
private def mkParserSeq (ds : Array Syntax) : TermElabM Syntax := do
if ds.size == 0 then
throwUnsupportedSyntax
else if ds.size == 1 then
pure ds[0]
else
let mut r := ds[0]
for d in ds[1:ds.size] do
r ← `(ParserDescr.binary `andthen $r $d)
return r
structure ToParserDescrContext where
catName : Name
first : Bool
leftRec : Bool -- true iff left recursion is allowed
/- See comment at `Parser.ParserCategory`. -/
behavior : Parser.LeadingIdentBehavior
abbrev ToParserDescrM := ReaderT ToParserDescrContext (StateRefT (Option Nat) TermElabM)
private def markAsTrailingParser (lhsPrec : Nat) : ToParserDescrM Unit := set (some lhsPrec)
@[inline] private def withNotFirst {α} (x : ToParserDescrM α) : ToParserDescrM α :=
withReader (fun ctx => { ctx with first := false }) x
@[inline] private def withNestedParser {α} (x : ToParserDescrM α) : ToParserDescrM α :=
withReader (fun ctx => { ctx with leftRec := false, first := false }) x
def checkLeftRec (stx : Syntax) : ToParserDescrM Bool := do
let ctx ← read
unless ctx.first && stx.getKind == `Lean.Parser.Syntax.cat do
return false
let cat := stx[0].getId.eraseMacroScopes
unless cat == ctx.catName do
return false
let prec? ← liftMacroM <| expandOptPrecedence stx[1]
unless ctx.leftRec do
throwErrorAt stx[3] "invalid occurrence of '{cat}', parser algorithm does not allow this form of left recursion"
markAsTrailingParser (prec?.getD 0)
return true
/--
Given a `stx` of category `syntax`, return a pair `(newStx, lhsPrec?)`,
where `newStx` is of category `term`. After elaboration, `newStx` should have type
`TrailingParserDescr` if `lhsPrec?.isSome`, and `ParserDescr` otherwise. -/
partial def toParserDescr (stx : Syntax) (catName : Name) : TermElabM (Syntax × Option Nat) := do
let env ← getEnv
let behavior := Parser.leadingIdentBehavior env catName
(process stx { catName := catName, first := true, leftRec := true, behavior := behavior }).run none
where
process (stx : Syntax) : ToParserDescrM Syntax := withRef stx do
let kind := stx.getKind
if kind == nullKind then
processSeq stx
else if kind == choiceKind then
process stx[0]
else if kind == `Lean.Parser.Syntax.paren then
process stx[1]
else if kind == `Lean.Parser.Syntax.cat then
processNullaryOrCat stx
else if kind == `Lean.Parser.Syntax.unary then
processUnary stx
else if kind == `Lean.Parser.Syntax.binary then
processBinary stx
else if kind == `Lean.Parser.Syntax.sepBy then
processSepBy stx
else if kind == `Lean.Parser.Syntax.sepBy1 then
processSepBy1 stx
else if kind == `Lean.Parser.Syntax.atom then
processAtom stx
else if kind == `Lean.Parser.Syntax.nonReserved then
processNonReserved stx
else
let stxNew? ← liftM (liftMacroM (expandMacro? stx) : TermElabM _)
match stxNew? with
| some stxNew => process stxNew
| none => throwErrorAt stx "unexpected syntax kind of category `syntax`: {kind}"
/- Sequence (aka NullNode) -/
processSeq (stx : Syntax) := do
let args := stx.getArgs
if (← checkLeftRec stx[0]) then
if args.size == 1 then throwErrorAt stx "invalid atomic left recursive syntax"
let args := args.eraseIdx 0
let args ← args.mapM fun arg => withNestedParser do process arg
mkParserSeq args
else
let args ← args.mapIdxM fun i arg => withReader (fun ctx => { ctx with first := ctx.first && i.val == 0 }) do process arg
mkParserSeq args
/- Resolve the given parser name and return a list of candidates.
Each candidate is a pair `(resolvedParserName, isDescr)`.
`isDescr == true` if the type of `resolvedParserName` is a `ParserDescr`. -/
resolveParserName (parserName : Name) : ToParserDescrM (List (Name × Bool)) := do
try
let candidates ← resolveGlobalConstWithInfos (← getRef) parserName
/- Convert `candidates` in a list of pairs `(c, isDescr)`, where `c` is the parser name,
and `isDescr` is true iff `c` has type `Lean.ParserDescr` or `Lean.TrailingParser` -/
let env ← getEnv
candidates.filterMap fun c =>
match env.find? c with
| none => none
| some info =>
match info.type with
| Expr.const `Lean.Parser.TrailingParser _ _ => (c, false)
| Expr.const `Lean.Parser.Parser _ _ => (c, false)
| Expr.const `Lean.ParserDescr _ _ => (c, true)
| Expr.const `Lean.TrailingParserDescr _ _ => (c, true)
| _ => none
catch _ => return []
ensureNoPrec (stx : Syntax) :=
unless stx[1].isNone do
throwErrorAt stx[1] "unexpected precedence"
processParserCategory (stx : Syntax) := do
let catName := stx[0].getId.eraseMacroScopes
if (← read).first && catName == (← read).catName then
throwErrorAt stx "invalid atomic left recursive syntax"
let prec? ← liftMacroM <| expandOptPrecedence stx[1]
let prec := prec?.getD 0
`(ParserDescr.cat $(quote catName) $(quote prec))
processNullaryOrCat (stx : Syntax) := do
let id := stx[0].getId.eraseMacroScopes
match (← withRef stx[0] <| resolveParserName id) with
| [(c, true)] => ensureNoPrec stx; return mkIdentFrom stx c
| [(c, false)] => ensureNoPrec stx; `(ParserDescr.parser $(quote c))
| cs@(_ :: _ :: _) => throwError "ambiguous parser declaration {cs.map (·.1)}"
| [] =>
if Parser.isParserCategory (← getEnv) id then
processParserCategory stx
else if (← Parser.isParserAlias id) then
ensureNoPrec stx
Parser.ensureConstantParserAlias id
`(ParserDescr.const $(quote id))
else
throwError "unknown parser declaration/category/alias '{id}'"
processUnary (stx : Syntax) := do
let aliasName := (stx[0].getId).eraseMacroScopes
Parser.ensureUnaryParserAlias aliasName
let d ← withNestedParser do process stx[2]
`(ParserDescr.unary $(quote aliasName) $d)
processBinary (stx : Syntax) := do
let aliasName := (stx[0].getId).eraseMacroScopes
Parser.ensureBinaryParserAlias aliasName
let d₁ ← withNestedParser do process stx[2]
let d₂ ← withNestedParser do process stx[4]
`(ParserDescr.binary $(quote aliasName) $d₁ $d₂)
processSepBy (stx : Syntax) := do
let p ← withNestedParser $ process stx[1]
let sep := stx[3]
let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else process stx[4][1]
let allowTrailingSep := !stx[5].isNone
`(ParserDescr.sepBy $p $sep $psep $(quote allowTrailingSep))
processSepBy1 (stx : Syntax) := do
let p ← withNestedParser do process stx[1]
let sep := stx[3]
let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else process stx[4][1]
let allowTrailingSep := !stx[5].isNone
`(ParserDescr.sepBy1 $p $sep $psep $(quote allowTrailingSep))
processAtom (stx : Syntax) := do
match stx[0].isStrLit? with
| some atom =>
/- For syntax categories where initialized with `LeadingIdentBehavior` different from default (e.g., `tactic`), we automatically mark
the first symbol as nonReserved. -/
if (← read).behavior != Parser.LeadingIdentBehavior.default && (← read).first then
`(ParserDescr.nonReservedSymbol $(quote atom) false)
else
`(ParserDescr.symbol $(quote atom))
| none => throwUnsupportedSyntax
processNonReserved (stx : Syntax) := do
match stx[1].isStrLit? with
| some atom => `(ParserDescr.nonReservedSymbol $(quote atom) false)
| none => throwUnsupportedSyntax
end Term
namespace Command
open Lean.Syntax
open Lean.Parser.Term hiding macroArg
open Lean.Parser.Command
private def declareSyntaxCatQuotParser (catName : Name) : CommandElabM Unit := do
if let Name.str _ suffix _ := catName then
let quotSymbol := "`(" ++ suffix ++ "|"
let name := catName ++ `quot
-- TODO(Sebastian): this might confuse the pretty printer, but it lets us reuse the elaborator
let kind := ``Lean.Parser.Term.quot
let cmd ← `(
@[termParser] def $(mkIdent name) : Lean.ParserDescr :=
Lean.ParserDescr.node $(quote kind) $(quote Lean.Parser.maxPrec)
(Lean.ParserDescr.binary `andthen (Lean.ParserDescr.symbol $(quote quotSymbol))
(Lean.ParserDescr.binary `andthen
(Lean.ParserDescr.unary `incQuotDepth (Lean.ParserDescr.cat $(quote catName) 0))
(Lean.ParserDescr.symbol ")"))))
elabCommand cmd
@[builtinCommandElab syntaxCat] def elabDeclareSyntaxCat : CommandElab := fun stx => do
let catName := stx[1].getId
let attrName := catName.appendAfter "Parser"
let env ← getEnv
let env ← liftIO $ Parser.registerParserCategory env attrName catName
setEnv env
declareSyntaxCatQuotParser catName
/--
Auxiliary function for creating declaration names from parser descriptions.
Example:
Given
```
syntax term "+" term : term
syntax "[" sepBy(term, ", ") "]" : term
```
It generates the names `term_+_` and `term[_,]`
-/
partial def mkNameFromParserSyntax (catName : Name) (stx : Syntax) : MacroM Name := do
mkUnusedBaseName <| Name.mkSimple <| appendCatName <| visit stx ""
where
visit (stx : Syntax) (acc : String) : String :=
match stx.isStrLit? with
| some val => acc ++ (val.trim.map fun c => if c.isWhitespace then '_' else c).capitalize
| none =>
match stx with
| Syntax.node k args =>
if k == `Lean.Parser.Syntax.cat then
acc ++ "_"
else
args.foldl (init := acc) fun acc arg => visit arg acc
| Syntax.ident .. => acc
| Syntax.atom .. => acc
| Syntax.missing => acc
appendCatName (str : String) :=
match catName with
| Name.str _ s _ => s ++ str
| _ => str
/- We assume a new syntax can be treated as an atom when it starts and ends with a token.
Here are examples of atom-like syntax.
```
syntax "(" term ")" : term
syntax "[" (sepBy term ",") "]" : term
syntax "foo" : term
```
-/
private partial def isAtomLikeSyntax (stx : Syntax) : Bool :=
let kind := stx.getKind
if kind == nullKind then
isAtomLikeSyntax stx[0] && isAtomLikeSyntax stx[stx.getNumArgs - 1]
else if kind == choiceKind then
isAtomLikeSyntax stx[0] -- see toParserDescr
else if kind == `Lean.Parser.Syntax.paren then
isAtomLikeSyntax stx[1]
else
kind == `Lean.Parser.Syntax.atom
@[builtinCommandElab «syntax»] def elabSyntax : CommandElab := fun stx => do
let `($attrKind:attrKind syntax $[: $prec? ]? $[(name := $name?)]? $[(priority := $prio?)]? $[$ps:stx]* : $catStx) ← pure stx
| throwUnsupportedSyntax
let cat := catStx.getId.eraseMacroScopes
unless (Parser.isParserCategory (← getEnv) cat) do
throwErrorAt catStx "unknown category '{cat}'"
let syntaxParser := mkNullNode ps
-- If the user did not provide an explicit precedence, we assign `maxPrec` to atom-like syntax and `leadPrec` otherwise.
let precDefault := if isAtomLikeSyntax syntaxParser then Parser.maxPrec else Parser.leadPrec
let prec ← match prec? with
| some prec => liftMacroM <| evalPrec prec
| none => precDefault
let name ← match name? with
| some name => pure name.getId
| none => liftMacroM <| mkNameFromParserSyntax cat syntaxParser
let prio ← liftMacroM <| evalOptPrio prio?
let stxNodeKind := (← getCurrNamespace) ++ name
let catParserId := mkIdentFrom stx (cat.appendAfter "Parser")
let (val, lhsPrec?) ← runTermElabM none fun _ => Term.toParserDescr syntaxParser cat
let declName := mkIdentFrom stx name
let d ←
if let some lhsPrec := lhsPrec? then
`(@[$attrKind:attrKind $catParserId:ident $(quote prio):numLit] def $declName : Lean.TrailingParserDescr :=
ParserDescr.trailingNode $(quote stxNodeKind) $(quote prec) $(quote lhsPrec) $val)
else
`(@[$attrKind:attrKind $catParserId:ident $(quote prio):numLit] def $declName : Lean.ParserDescr :=
ParserDescr.node $(quote stxNodeKind) $(quote prec) $val)
trace `Elab fun _ => d
withMacroExpansion stx d <| elabCommand d
/-
def syntaxAbbrev := leading_parser "syntax " >> ident >> " := " >> many1 syntaxParser
-/
@[builtinCommandElab «syntaxAbbrev»] def elabSyntaxAbbrev : CommandElab := fun stx => do
let declName := stx[1]
-- TODO: nonatomic names
let (val, _) ← runTermElabM none $ fun _ => Term.toParserDescr stx[3] Name.anonymous
let stxNodeKind := (← getCurrNamespace) ++ declName.getId
let stx' ← `(def $declName : Lean.ParserDescr := ParserDescr.nodeWithAntiquot $(quote (toString declName.getId)) $(quote stxNodeKind) $val)
withMacroExpansion stx stx' $ elabCommand stx'
private def checkRuleKind (given expected : SyntaxNodeKind) : Bool :=
given == expected || given == expected ++ `antiquot
/-
Remark: `k` is the user provided kind with the current namespace included.
Recall that syntax node kinds contain the current namespace.
-/
def elabMacroRulesAux (attrKind : Syntax) (k : SyntaxNodeKind) (alts : Array Syntax) : CommandElabM Syntax := do
let alts ← alts.mapM fun alt => match alt with
| `(matchAltExpr| | $pats,* => $rhs) => do
let pat := pats.elemsAndSeps[0]
if !pat.isQuot then
throwUnsupportedSyntax
let quoted := getQuotContent pat
let k' := quoted.getKind
if checkRuleKind k' k then
pure alt
else if k' == choiceKind then
match quoted.getArgs.find? fun quotAlt => checkRuleKind quotAlt.getKind k with
| none => throwErrorAt alt "invalid macro_rules alternative, expected syntax node kind '{k}'"
| some quoted =>
let pat := pat.setArg 1 quoted
let pats := pats.elemsAndSeps.set! 0 pat
`(matchAltExpr| | $pats,* => $rhs)
else
throwErrorAt alt "invalid macro_rules alternative, unexpected syntax node kind '{k'}'"
| _ => throwUnsupportedSyntax
`(@[$attrKind:attrKind macro $(Lean.mkIdent k)] def myMacro : Macro :=
fun $alts:matchAlt* | _ => throw Lean.Macro.Exception.unsupportedSyntax)
def inferMacroRulesAltKind : Syntax → CommandElabM SyntaxNodeKind
| `(matchAltExpr| | $pats,* => $rhs) => do
let pat := pats.elemsAndSeps[0]
if !pat.isQuot then
throwUnsupportedSyntax
let quoted := getQuotContent pat
pure quoted.getKind
| _ => throwUnsupportedSyntax
def elabNoKindMacroRulesAux (attrKind : Syntax) (alts : Array Syntax) : CommandElabM Syntax := do
let mut k ← inferMacroRulesAltKind alts[0]
if k.isStr && k.getString! == "antiquot" then
k := k.getPrefix
if k == choiceKind then
throwErrorAt alts[0]
"invalid macro_rules alternative, multiple interpretations for pattern (solution: specify node kind using `macro_rules [<kind>] ...`)"
else
let altsK ← alts.filterM fun alt => return checkRuleKind (← inferMacroRulesAltKind alt) k
let altsNotK ← alts.filterM fun alt => return !checkRuleKind (← inferMacroRulesAltKind alt) k
let defCmd ← elabMacroRulesAux attrKind k altsK
if altsNotK.isEmpty then
pure defCmd
else
`($defCmd:command $attrKind:attrKind macro_rules $altsNotK:matchAlt*)
@[builtinCommandElab «macro_rules»] def elabMacroRules : CommandElab :=
adaptExpander fun stx => match stx with
| `($attrKind:attrKind macro_rules $alts:matchAlt*) =>
elabNoKindMacroRulesAux attrKind alts
| `($attrKind:attrKind macro_rules (kind := $kind) | $x:ident => $rhs) =>
`(@[$attrKind:attrKind macro $kind] def myMacro : Macro := fun $x:ident => $rhs)
| `($attrKind:attrKind macro_rules (kind := $kind) $alts:matchAlt*) =>
do elabMacroRulesAux attrKind ((← getCurrNamespace) ++ kind.getId) alts
| _ => throwUnsupportedSyntax
@[builtinMacro Lean.Parser.Command.mixfix] def expandMixfix : Macro := fun stx =>
withAttrKindGlobal stx fun stx => do
match stx with
| `(infixl $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) =>
let prec1 := quote <| (← evalOptPrec prec) + 1
`(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? lhs$[:$prec]? $op:strLit rhs:$prec1 => $f lhs rhs)
| `(infix $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) =>
let prec1 := quote <| (← evalOptPrec prec) + 1
`(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? lhs:$prec1 $op:strLit rhs:$prec1 => $f lhs rhs)
| `(infixr $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) =>
let prec1 := quote <| (← evalOptPrec prec) + 1
`(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? lhs:$prec1 $op:strLit rhs $[: $prec]? => $f lhs rhs)
| `(prefix $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) =>
`(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op:strLit arg $[: $prec]? => $f arg)
| `(postfix $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) =>
`(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? arg$[:$prec]? $op:strLit => $f arg)
| _ => Macro.throwUnsupported
where
-- set "global" `attrKind`, apply `f`, and restore `attrKind` to result
withAttrKindGlobal stx f := do
let attrKind := stx[0]
let stx := stx.setArg 0 mkAttrKindGlobal
let stx ← f stx
return stx.setArg 0 attrKind
/- Wrap all occurrences of the given `ident` nodes in antiquotations -/
private partial def antiquote (vars : Array Syntax) : Syntax → Syntax
| stx => match stx with
| `($id:ident) =>
if (vars.findIdx? (fun var => var.getId == id.getId)).isSome then
mkAntiquotNode id
else
stx
| _ => match stx with
| Syntax.node k args => Syntax.node k (args.map (antiquote vars))
| stx => stx
/- Convert `notation` command lhs item into a `syntax` command item -/
def expandNotationItemIntoSyntaxItem (stx : Syntax) : MacroM Syntax :=
let k := stx.getKind
if k == `Lean.Parser.Command.identPrec then
pure $ Syntax.node `Lean.Parser.Syntax.cat #[mkIdentFrom stx `term, stx[1]]
else if k == strLitKind then
pure $ Syntax.node `Lean.Parser.Syntax.atom #[stx]
else
Macro.throwUnsupported
def strLitToPattern (stx: Syntax) : MacroM Syntax :=
match stx.isStrLit? with
| some str => pure $ mkAtomFrom stx str
| none => Macro.throwUnsupported
/- Convert `notation` command lhs item into a pattern element -/
def expandNotationItemIntoPattern (stx : Syntax) : MacroM Syntax :=
let k := stx.getKind
if k == `Lean.Parser.Command.identPrec then
mkAntiquotNode stx[0]
else if k == strLitKind then
strLitToPattern stx
else
Macro.throwUnsupported
/-- Try to derive a `SimpleDelab` from a notation.
The notation must be of the form `notation ... => c var_1 ... var_n`
where `c` is a declaration in the current scope and the `var_i` are a permutation of the LHS vars. -/
def mkSimpleDelab (attrKind : Syntax) (vars : Array Syntax) (pat qrhs : Syntax) : OptionT MacroM Syntax := do
match qrhs with
| `($c:ident $args*) =>
let [(c, [])] ← Macro.resolveGlobalName c.getId | failure
guard <| args.all (Syntax.isIdent ∘ getAntiquotTerm)
guard <| args.allDiff
-- replace head constant with (unused) antiquotation so we're not dependent on the exact pretty printing of the head
let qrhs ← `($(mkAntiquotNode (← `(_))) $args*)
`(@[$attrKind:attrKind appUnexpander $(mkIdent c):ident] def unexpand : Lean.PrettyPrinter.Unexpander := fun
| `($qrhs) => `($pat)
| _ => throw ())
| `($c:ident) =>
let [(c, [])] ← Macro.resolveGlobalName c.getId | failure
`(@[$attrKind:attrKind appUnexpander $(mkIdent c):ident] def unexpand : Lean.PrettyPrinter.Unexpander := fun _ => `($pat))
| _ => failure
private def isLocalAttrKind (attrKind : Syntax) : Bool :=
match attrKind with
| `(Parser.Term.attrKind| local) => true
| _ => false
private def expandNotationAux (ref : Syntax)
(currNamespace : Name) (attrKind : Syntax) (prec? : Option Syntax) (name? : Option Syntax) (prio? : Option Syntax) (items : Array Syntax) (rhs : Syntax) : MacroM Syntax := do
let prio ← evalOptPrio prio?
-- build parser
let syntaxParts ← items.mapM expandNotationItemIntoSyntaxItem
let cat := mkIdentFrom ref `term
let name ←
match name? with
| some name => pure name.getId
| none => mkNameFromParserSyntax `term (mkNullNode syntaxParts)
-- build macro rules
let vars := items.filter fun item => item.getKind == `Lean.Parser.Command.identPrec
let vars := vars.map fun var => var[0]
let qrhs := antiquote vars rhs
let patArgs ← items.mapM expandNotationItemIntoPattern
/- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind.
So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/
let fullName := currNamespace ++ name
let pat := Syntax.node fullName patArgs
let stxDecl ← `($attrKind:attrKind syntax $[: $prec?]? (name := $(mkIdent name)) (priority := $(quote prio):numLit) $[$syntaxParts]* : $cat)
let mut macroDecl ← `(macro_rules | `($pat) => ``($qrhs))
if isLocalAttrKind attrKind then
-- Make sure the quotation pre-checker takes section variables into account for local notation.
macroDecl ← `(section set_option quotPrecheck.allowSectionVars true $macroDecl end)
match (← mkSimpleDelab attrKind vars pat qrhs |>.run) with
| some delabDecl => mkNullNode #[stxDecl, macroDecl, delabDecl]
| none => mkNullNode #[stxDecl, macroDecl]
@[builtinMacro Lean.Parser.Command.notation] def expandNotation : Macro
| stx@`($attrKind:attrKind notation $[: $prec? ]? $[(name := $name?)]? $[(priority := $prio?)]? $items* => $rhs) => do
-- trigger scoped checks early and only once
let _ ← toAttributeKind attrKind
expandNotationAux stx (← Macro.getCurrNamespace) attrKind prec? name? prio? items rhs
| _ => Macro.throwUnsupported
/- Convert `macro` argument into a `syntax` command item -/
def expandMacroArgIntoSyntaxItem : Macro
| `(macroArg|$id:ident:$stx) => stx
-- can't match against `$s:strLit%$id` because the latter part would be interpreted as an antiquotation on the token
-- `strLit`.
| `(macroArg|$s:macroArgSymbol) => `(stx|$(s[0]):strLit)
| _ => Macro.throwUnsupported
/- Convert `macro` arg into a pattern element -/
def expandMacroArgIntoPattern (stx : Syntax) : MacroM Syntax := do
match (← expandMacros stx) with
| `(macroArg|$id:ident:optional($stx)) =>
mkSplicePat `optional id "?"
| `(macroArg|$id:ident:many($stx)) =>
mkSplicePat `many id "*"
| `(macroArg|$id:ident:many1($stx)) =>
mkSplicePat `many id "*"
| `(macroArg|$id:ident:sepBy($stx, $sep:strLit $[, $stxsep]? $[, allowTrailingSep]?)) =>
mkSplicePat `sepBy id ((isStrLit? sep).get! ++ "*")
| `(macroArg|$id:ident:sepBy1($stx, $sep:strLit $[, $stxsep]? $[, allowTrailingSep]?)) =>
mkSplicePat `sepBy id ((isStrLit? sep).get! ++ "*")
| `(macroArg|$id:ident:$stx) => mkAntiquotNode id
| `(macroArg|$s:strLit) => strLitToPattern s
-- `"tk"%id` ~> `"tk"%$id`
| `(macroArg|$s:macroArgSymbol) => mkNode `token_antiquot #[← strLitToPattern s[0], mkAtom "%", mkAtom "$", s[1][1]]
| _ => Macro.throwUnsupported
where mkSplicePat kind id suffix :=
mkNullNode #[mkAntiquotSuffixSpliceNode kind (mkAntiquotNode id) suffix]
/- «macro» := leading_parser suppressInsideQuot (Term.attrKind >> "macro " >> optPrecedence >> optNamedName >> optNamedPrio >> macroHead >> many macroArg >> macroTail) -/
@[builtinMacro Lean.Parser.Command.macro] def expandMacro : Macro := fun stx => do
let attrKind := stx[0]
let prec := stx[2].getOptional?
let name? ← expandOptNamedName stx[3]
let prio ← expandOptNamedPrio stx[4]
let head := stx[5]
let args := stx[6].getArgs
let cat := stx[8]
-- build parser
let stxPart ← expandMacroArgIntoSyntaxItem head
let stxParts ← args.mapM expandMacroArgIntoSyntaxItem
let stxParts := #[stxPart] ++ stxParts
-- name
let name ← match name? with
| some name => pure name
| none => mkNameFromParserSyntax cat.getId (mkNullNode stxParts)
-- build macro rules
let patHead ← expandMacroArgIntoPattern head
let patArgs ← args.mapM expandMacroArgIntoPattern
/- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind.
So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/
let pat := Syntax.node ((← Macro.getCurrNamespace) ++ name) (#[patHead] ++ patArgs)
if stx.getArgs.size == 11 then
-- `stx` is of the form `macro $head $args* : $cat => term`
let rhs := stx[10]
let stxCmd ← `(Parser.Command.syntax| $attrKind:attrKind syntax $(prec)? (name := $(mkIdentFrom stx name):ident) (priority := $(quote prio):numLit) $[$stxParts]* : $cat)
let macroRulesCmd ← `(macro_rules | `($pat) => $rhs)
return mkNullNode #[stxCmd, macroRulesCmd]
else
-- `stx` is of the form `macro $head $args* : $cat => `( $body )`
let rhsBody := stx[11]
let stxCmd ← `(Parser.Command.syntax| $attrKind:attrKind syntax $(prec)? (name := $(mkIdentFrom stx name):ident) (priority := $(quote prio):numLit) $[$stxParts]* : $cat)
let macroRulesCmd ← `(macro_rules | `($pat) => `($rhsBody))
return mkNullNode #[stxCmd, macroRulesCmd]
builtin_initialize
registerTraceClass `Elab.syntax
@[inline] def withExpectedType (expectedType? : Option Expr) (x : Expr → TermElabM Expr) : TermElabM Expr := do
Term.tryPostponeIfNoneOrMVar expectedType?
let some expectedType ← pure expectedType?
| throwError "expected type must be known"
x expectedType
/-
def elabTail := try (" : " >> ident) >> darrow >> termParser
def «elab» := leading_parser suppressInsideQuot (Term.attrKind >> "elab " >> optPrecedence >> optNamedName >> optNamedPrio >> elabHead >> many elabArg >> elabTail)
-/
def expandElab (currNamespace : Name) (stx : Syntax) : CommandElabM Syntax := do
let ref := stx
let attrKind := stx[0]
let prec := stx[2].getOptional?
let name? ← liftMacroM <| expandOptNamedName stx[3]
let prio ← liftMacroM <| expandOptNamedPrio stx[4]
let head := stx[5]
let args := stx[6].getArgs
let cat := stx[8]
let expectedTypeSpec := stx[9]
let rhs := stx[11]
let catName := cat.getId
-- build parser
let stxPart ← liftMacroM <| expandMacroArgIntoSyntaxItem head
let stxParts ← liftMacroM <| args.mapM expandMacroArgIntoSyntaxItem
let stxParts := #[stxPart] ++ stxParts
-- name
let name ← match name? with
| some name => pure name
| none => liftMacroM <| mkNameFromParserSyntax cat.getId (mkNullNode stxParts)
-- build pattern for syntax `match`
let patHead ← liftMacroM <| expandMacroArgIntoPattern head
let patArgs ← liftMacroM <| args.mapM expandMacroArgIntoPattern
let pat := Syntax.node (currNamespace ++ name) (#[patHead] ++ patArgs)
let stxCmd ← `(Parser.Command.syntax|
$attrKind:attrKind syntax $(prec)? (name := $(mkIdentFrom stx name):ident) (priority := $(quote prio):numLit) $[$stxParts]* : $cat)
let elabCmd ←
if expectedTypeSpec.hasArgs then
if catName == `term then
let expId := expectedTypeSpec[1]
`(@[termElab $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Term.TermElab :=
fun stx expectedType? => match stx with
| `($pat) => Lean.Elab.Command.withExpectedType expectedType? fun $expId => $rhs
| _ => throwUnsupportedSyntax)
else
throwErrorAt expectedTypeSpec "syntax category '{catName}' does not support expected type specification"
else if catName == `term then
`(@[termElab $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Term.TermElab :=
fun stx _ => match stx with
| `($pat) => $rhs
| _ => throwUnsupportedSyntax)
else if catName == `command then
`(@[commandElab $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Command.CommandElab :=
fun
| `($pat) => $rhs
| _ => throwUnsupportedSyntax)
else if catName == `tactic then
`(@[tactic $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Tactic.Tactic :=
fun
| `(tactic|$pat) => $rhs
| _ => throwUnsupportedSyntax)
else
-- We considered making the command extensible and support new user-defined categories. We think it is unnecessary.
-- If users want this feature, they add their own `elab` macro that uses this one as a fallback.
throwError "unsupported syntax category '{catName}'"
return mkNullNode #[stxCmd, elabCmd]
@[builtinCommandElab «elab»] def elabElab : CommandElab :=
adaptExpander fun stx => do
expandElab (← getCurrNamespace) stx
end Lean.Elab.Command
|
ee9786d8fb8783cefa3ca33b403e95a22158eab5 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/ring_theory/valuation/basic.lean | 0456353ae971e4651375a5a8abe36fead8363ba7 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 28,664 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Johan Commelin, Patrick Massot
-/
import algebra.order.with_zero
import algebra.punit_instances
import ring_theory.ideal.operations
/-!
# The basics of valuation theory.
The basic theory of valuations (non-archimedean norms) on a commutative ring,
following T. Wedhorn's unpublished notes “Adic Spaces” ([wedhorn_adic]).
The definition of a valuation we use here is Definition 1.22 of [wedhorn_adic].
A valuation on a ring `R` is a monoid homomorphism `v` to a linearly ordered
commutative monoid with zero, that in addition satisfies the following two axioms:
* `v 0 = 0`
* `∀ x y, v (x + y) ≤ max (v x) (v y)`
`valuation R Γ₀`is the type of valuations `R → Γ₀`, with a coercion to the underlying
function. If `v` is a valuation from `R` to `Γ₀` then the induced group
homomorphism `units(R) → Γ₀` is called `unit_map v`.
The equivalence "relation" `is_equiv v₁ v₂ : Prop` defined in 1.27 of [wedhorn_adic] is not strictly
speaking a relation, because `v₁ : valuation R Γ₁` and `v₂ : valuation R Γ₂` might
not have the same type. This corresponds in ZFC to the set-theoretic difficulty
that the class of all valuations (as `Γ₀` varies) on a ring `R` is not a set.
The "relation" is however reflexive, symmetric and transitive in the obvious
sense. Note that we use 1.27(iii) of [wedhorn_adic] as the definition of equivalence.
The support of a valuation `v : valuation R Γ₀` is `supp v`. If `J` is an ideal of `R`
with `h : J ⊆ supp v` then the induced valuation
on R / J = `ideal.quotient J` is `on_quot v h`.
## Main definitions
* `valuation R Γ₀`, the type of valuations on `R` with values in `Γ₀`
* `valuation.is_equiv`, the heterogeneous equivalence relation on valuations
* `valuation.supp`, the support of a valuation
* `add_valuation R Γ₀`, the type of additive valuations on `R` with values in a
linearly ordered additive commutative group with a top element, `Γ₀`.
## Implementation Details
`add_valuation R Γ₀` is implemented as `valuation R (multiplicative Γ₀)ᵒᵈ`.
## Notation
In the `discrete_valuation` locale:
* `ℕₘ₀` is a shorthand for `with_zero (multiplicative ℕ)`
* `ℤₘ₀` is a shorthand for `with_zero (multiplicative ℤ)`
## TODO
If ever someone extends `valuation`, we should fully comply to the `fun_like` by migrating the
boilerplate lemmas to `valuation_class`.
-/
open_locale classical big_operators
noncomputable theory
open function ideal
variables {F R : Type*} -- This will be a ring, assumed commutative in some sections
section
variables (F R) (Γ₀ : Type*) [linear_ordered_comm_monoid_with_zero Γ₀] [ring R]
/-- The type of `Γ₀`-valued valuations on `R`.
When you extend this structure, make sure to extend `valuation_class`. -/
@[nolint has_inhabited_instance]
structure valuation extends R →*₀ Γ₀ :=
(map_add_le_max' : ∀ x y, to_fun (x + y) ≤ max (to_fun x) (to_fun y))
/-- `valuation_class F α β` states that `F` is a type of valuations.
You should also extend this typeclass when you extend `valuation`. -/
class valuation_class extends monoid_with_zero_hom_class F R Γ₀ :=
(map_add_le_max (f : F) (x y : R) : f (x + y) ≤ max (f x) (f y))
export valuation_class (map_add_le_max)
instance [valuation_class F R Γ₀] : has_coe_t F (valuation R Γ₀) :=
⟨λ f, { to_fun := f, map_one' := map_one f, map_zero' := map_zero f, map_mul' := map_mul f,
map_add_le_max' := map_add_le_max f }⟩
end
namespace valuation
variables {Γ₀ : Type*}
variables {Γ'₀ : Type*}
variables {Γ''₀ : Type*} [linear_ordered_comm_monoid_with_zero Γ''₀]
section basic
variables [ring R]
section monoid
variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀]
instance : valuation_class (valuation R Γ₀) R Γ₀ :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' },
map_mul := λ f, f.map_mul',
map_one := λ f, f.map_one',
map_zero := λ f, f.map_zero',
map_add_le_max := λ f, f.map_add_le_max' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (valuation R Γ₀) (λ _, R → Γ₀) := fun_like.has_coe_to_fun
@[simp] lemma to_fun_eq_coe (v : valuation R Γ₀) : v.to_fun = v := rfl
@[ext] lemma ext {v₁ v₂ : valuation R Γ₀} (h : ∀ r, v₁ r = v₂ r) : v₁ = v₂ := fun_like.ext _ _ h
variables (v : valuation R Γ₀) {x y z : R}
@[simp, norm_cast] lemma coe_coe : ⇑(v : R →*₀ Γ₀) = v := rfl
@[simp] lemma map_zero : v 0 = 0 := v.map_zero'
@[simp] lemma map_one : v 1 = 1 := v.map_one'
@[simp] lemma map_mul : ∀ x y, v (x * y) = v x * v y := v.map_mul'
@[simp] lemma map_add : ∀ x y, v (x + y) ≤ max (v x) (v y) := v.map_add_le_max'
lemma map_add_le {x y g} (hx : v x ≤ g) (hy : v y ≤ g) : v (x + y) ≤ g :=
le_trans (v.map_add x y) $ max_le hx hy
lemma map_add_lt {x y g} (hx : v x < g) (hy : v y < g) : v (x + y) < g :=
lt_of_le_of_lt (v.map_add x y) $ max_lt hx hy
lemma map_sum_le {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hf : ∀ i ∈ s, v (f i) ≤ g) :
v (∑ i in s, f i) ≤ g :=
begin
refine finset.induction_on s
(λ _, trans_rel_right (≤) v.map_zero zero_le') (λ a s has ih hf, _) hf,
rw finset.forall_mem_insert at hf, rw finset.sum_insert has,
exact v.map_add_le hf.1 (ih hf.2)
end
lemma map_sum_lt {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g ≠ 0)
(hf : ∀ i ∈ s, v (f i) < g) : v (∑ i in s, f i) < g :=
begin
refine finset.induction_on s
(λ _, trans_rel_right (<) v.map_zero (zero_lt_iff.2 hg)) (λ a s has ih hf, _) hf,
rw finset.forall_mem_insert at hf, rw finset.sum_insert has,
exact v.map_add_lt hf.1 (ih hf.2)
end
lemma map_sum_lt' {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : 0 < g)
(hf : ∀ i ∈ s, v (f i) < g) : v (∑ i in s, f i) < g :=
v.map_sum_lt (ne_of_gt hg) hf
@[simp] lemma map_pow : ∀ x (n:ℕ), v (x^n) = (v x)^n :=
v.to_monoid_with_zero_hom.to_monoid_hom.map_pow
/-- Deprecated. Use `fun_like.ext_iff`. -/
lemma ext_iff {v₁ v₂ : valuation R Γ₀} : v₁ = v₂ ↔ ∀ r, v₁ r = v₂ r := fun_like.ext_iff
-- The following definition is not an instance, because we have more than one `v` on a given `R`.
-- In addition, type class inference would not be able to infer `v`.
/-- A valuation gives a preorder on the underlying ring. -/
def to_preorder : preorder R := preorder.lift v
/-- If `v` is a valuation on a division ring then `v(x) = 0` iff `x = 0`. -/
@[simp] lemma zero_iff [nontrivial Γ₀] {K : Type*} [division_ring K]
(v : valuation K Γ₀) {x : K} : v x = 0 ↔ x = 0 :=
v.to_monoid_with_zero_hom.map_eq_zero
lemma ne_zero_iff [nontrivial Γ₀] {K : Type*} [division_ring K]
(v : valuation K Γ₀) {x : K} : v x ≠ 0 ↔ x ≠ 0 :=
v.to_monoid_with_zero_hom.map_ne_zero
theorem unit_map_eq (u : Rˣ) :
(units.map (v : R →* Γ₀) u : Γ₀) = v u := rfl
/-- A ring homomorphism `S → R` induces a map `valuation R Γ₀ → valuation S Γ₀`. -/
def comap {S : Type*} [ring S] (f : S →+* R) (v : valuation R Γ₀) :
valuation S Γ₀ :=
{ to_fun := v ∘ f,
map_add_le_max' := λ x y, by simp only [comp_app, map_add, f.map_add],
.. v.to_monoid_with_zero_hom.comp f.to_monoid_with_zero_hom, }
@[simp]
lemma comap_apply {S : Type*} [ring S] (f : S →+* R) (v : valuation R Γ₀) (s : S) :
v.comap f s = v (f s) := rfl
@[simp] lemma comap_id : v.comap (ring_hom.id R) = v := ext $ λ r, rfl
lemma comap_comp {S₁ : Type*} {S₂ : Type*} [ring S₁] [ring S₂] (f : S₁ →+* S₂) (g : S₂ →+* R) :
v.comap (g.comp f) = (v.comap g).comap f :=
ext $ λ r, rfl
/-- A `≤`-preserving group homomorphism `Γ₀ → Γ'₀` induces a map `valuation R Γ₀ → valuation R Γ'₀`.
-/
def map (f : Γ₀ →*₀ Γ'₀) (hf : monotone f) (v : valuation R Γ₀) :
valuation R Γ'₀ :=
{ to_fun := f ∘ v,
map_add_le_max' := λ r s,
calc f (v (r + s)) ≤ f (max (v r) (v s)) : hf (v.map_add r s)
... = max (f (v r)) (f (v s)) : hf.map_max,
.. monoid_with_zero_hom.comp f v.to_monoid_with_zero_hom }
/-- Two valuations on `R` are defined to be equivalent if they induce the same preorder on `R`. -/
def is_equiv (v₁ : valuation R Γ₀) (v₂ : valuation R Γ'₀) : Prop :=
∀ r s, v₁ r ≤ v₁ s ↔ v₂ r ≤ v₂ s
end monoid
section group
variables [linear_ordered_comm_group_with_zero Γ₀] {R} {Γ₀} (v : valuation R Γ₀) {x y z : R}
@[simp] lemma map_inv {K : Type*} [division_ring K]
(v : valuation K Γ₀) {x : K} : v x⁻¹ = (v x)⁻¹ :=
v.to_monoid_with_zero_hom.map_inv x
@[simp] lemma map_zpow {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} {n : ℤ} :
v (x^n) = (v x)^n :=
v.to_monoid_with_zero_hom.map_zpow x n
lemma map_units_inv (x : Rˣ) : v (x⁻¹ : Rˣ) = (v x)⁻¹ :=
v.to_monoid_with_zero_hom.to_monoid_hom.map_units_inv x
@[simp] lemma map_neg (x : R) : v (-x) = v x :=
v.to_monoid_with_zero_hom.to_monoid_hom.map_neg x
lemma map_sub_swap (x y : R) : v (x - y) = v (y - x) :=
v.to_monoid_with_zero_hom.to_monoid_hom.map_sub_swap x y
lemma map_sub (x y : R) : v (x - y) ≤ max (v x) (v y) :=
calc v (x - y) = v (x + -y) : by rw [sub_eq_add_neg]
... ≤ max (v x) (v $ -y) : v.map_add _ _
... = max (v x) (v y) : by rw map_neg
lemma map_sub_le {x y g} (hx : v x ≤ g) (hy : v y ≤ g) : v (x - y) ≤ g :=
begin
rw sub_eq_add_neg,
exact v.map_add_le hx (le_trans (le_of_eq (v.map_neg y)) hy)
end
lemma map_add_of_distinct_val (h : v x ≠ v y) : v (x + y) = max (v x) (v y) :=
begin
suffices : ¬v (x + y) < max (v x) (v y),
from or_iff_not_imp_right.1 (le_iff_eq_or_lt.1 (v.map_add x y)) this,
intro h',
wlog vyx : v y < v x using x y,
{ apply lt_or_gt_of_ne h.symm },
{ rw max_eq_left_of_lt vyx at h',
apply lt_irrefl (v x),
calc v x = v ((x+y) - y) : by simp
... ≤ max (v $ x + y) (v y) : map_sub _ _ _
... < v x : max_lt h' vyx },
{ apply this h.symm,
rwa [add_comm, max_comm] at h' }
end
lemma map_add_eq_of_lt_right (h : v x < v y) : v (x + y) = v y :=
begin
convert v.map_add_of_distinct_val _,
{ symmetry, rw max_eq_right_iff, exact le_of_lt h },
{ exact ne_of_lt h }
end
lemma map_add_eq_of_lt_left (h : v y < v x) : v (x + y) = v x :=
begin
rw add_comm, exact map_add_eq_of_lt_right _ h,
end
lemma map_eq_of_sub_lt (h : v (y - x) < v x) : v y = v x :=
begin
have := valuation.map_add_of_distinct_val v (ne_of_gt h).symm,
rw max_eq_right (le_of_lt h) at this,
simpa using this
end
lemma map_one_add_of_lt (h : v x < 1) : v (1 + x) = 1 :=
begin
rw ← v.map_one at h,
simpa only [v.map_one] using v.map_add_eq_of_lt_left h
end
lemma map_one_sub_of_lt (h : v x < 1) : v (1 - x) = 1 :=
begin
rw [← v.map_one, ← v.map_neg] at h,
rw sub_eq_add_neg 1 x,
simpa only [v.map_one, v.map_neg] using v.map_add_eq_of_lt_left h
end
/-- The subgroup of elements whose valuation is less than a certain unit.-/
def lt_add_subgroup (v : valuation R Γ₀) (γ : Γ₀ˣ) : add_subgroup R :=
{ carrier := {x | v x < γ},
zero_mem' := by { have h := units.ne_zero γ, contrapose! h, simpa using h },
add_mem' := λ x y x_in y_in, lt_of_le_of_lt (v.map_add x y) (max_lt x_in y_in),
neg_mem' := λ x x_in, by rwa [set.mem_set_of_eq, map_neg] }
end group
end basic -- end of section
namespace is_equiv
variables [ring R]
variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀]
variables {v : valuation R Γ₀}
variables {v₁ : valuation R Γ₀} {v₂ : valuation R Γ'₀} {v₃ : valuation R Γ''₀}
@[refl] lemma refl : v.is_equiv v :=
λ _ _, iff.refl _
@[symm] lemma symm (h : v₁.is_equiv v₂) : v₂.is_equiv v₁ :=
λ _ _, iff.symm (h _ _)
@[trans] lemma trans (h₁₂ : v₁.is_equiv v₂) (h₂₃ : v₂.is_equiv v₃) : v₁.is_equiv v₃ :=
λ _ _, iff.trans (h₁₂ _ _) (h₂₃ _ _)
lemma of_eq {v' : valuation R Γ₀} (h : v = v') : v.is_equiv v' :=
by { subst h }
lemma map {v' : valuation R Γ₀} (f : Γ₀ →*₀ Γ'₀) (hf : monotone f)
(inf : injective f) (h : v.is_equiv v') :
(v.map f hf).is_equiv (v'.map f hf) :=
let H : strict_mono f := hf.strict_mono_of_injective inf in
λ r s,
calc f (v r) ≤ f (v s) ↔ v r ≤ v s : by rw H.le_iff_le
... ↔ v' r ≤ v' s : h r s
... ↔ f (v' r) ≤ f (v' s) : by rw H.le_iff_le
/-- `comap` preserves equivalence. -/
lemma comap {S : Type*} [ring S] (f : S →+* R) (h : v₁.is_equiv v₂) :
(v₁.comap f).is_equiv (v₂.comap f) :=
λ r s, h (f r) (f s)
lemma val_eq (h : v₁.is_equiv v₂) {r s : R} :
v₁ r = v₁ s ↔ v₂ r = v₂ s :=
by simpa only [le_antisymm_iff] using and_congr (h r s) (h s r)
lemma ne_zero (h : v₁.is_equiv v₂) {r : R} :
v₁ r ≠ 0 ↔ v₂ r ≠ 0 :=
begin
have : v₁ r ≠ v₁ 0 ↔ v₂ r ≠ v₂ 0 := not_iff_not_of_iff h.val_eq,
rwa [v₁.map_zero, v₂.map_zero] at this,
end
end is_equiv -- end of namespace
section
lemma is_equiv_of_map_strict_mono [linear_ordered_comm_monoid_with_zero Γ₀]
[linear_ordered_comm_monoid_with_zero Γ'₀] [ring R] {v : valuation R Γ₀} (f : Γ₀ →*₀ Γ'₀)
(H : strict_mono f) :
is_equiv (v.map f (H.monotone)) v :=
λ x y, ⟨H.le_iff_le.mp, λ h, H.monotone h⟩
lemma is_equiv_of_val_le_one [linear_ordered_comm_group_with_zero Γ₀]
[linear_ordered_comm_group_with_zero Γ'₀]
{K : Type*} [division_ring K]
(v : valuation K Γ₀) (v' : valuation K Γ'₀) (h : ∀ {x:K}, v x ≤ 1 ↔ v' x ≤ 1) :
v.is_equiv v' :=
begin
intros x y,
by_cases hy : y = 0, { simp [hy, zero_iff], },
rw show y = 1 * y, by rw one_mul,
rw [← (inv_mul_cancel_right₀ hy x)],
iterate 2 {rw [v.map_mul _ y, v'.map_mul _ y]},
rw [v.map_one, v'.map_one],
split; intro H,
{ apply mul_le_mul_right',
replace hy := v.ne_zero_iff.mpr hy,
replace H := le_of_le_mul_right hy H,
rwa h at H, },
{ apply mul_le_mul_right',
replace hy := v'.ne_zero_iff.mpr hy,
replace H := le_of_le_mul_right hy H,
rwa h, },
end
lemma is_equiv_iff_val_le_one
[linear_ordered_comm_group_with_zero Γ₀]
[linear_ordered_comm_group_with_zero Γ'₀]
{K : Type*} [division_ring K]
(v : valuation K Γ₀) (v' : valuation K Γ'₀) :
v.is_equiv v' ↔ ∀ {x : K}, v x ≤ 1 ↔ v' x ≤ 1 :=
⟨λ h x, by simpa using h x 1, is_equiv_of_val_le_one _ _⟩
lemma is_equiv_iff_val_eq_one
[linear_ordered_comm_group_with_zero Γ₀]
[linear_ordered_comm_group_with_zero Γ'₀]
{K : Type*} [division_ring K]
(v : valuation K Γ₀) (v' : valuation K Γ'₀) :
v.is_equiv v' ↔ ∀ {x : K}, v x = 1 ↔ v' x = 1 :=
begin
split,
{ intros h x,
simpa using @is_equiv.val_eq _ _ _ _ _ _ v v' h x 1 },
{ intros h, apply is_equiv_of_val_le_one, intros x,
split,
{ intros hx,
cases lt_or_eq_of_le hx with hx' hx',
{ have : v (1 + x) = 1,
{ rw ← v.map_one, apply map_add_eq_of_lt_left, simpa },
rw h at this,
rw (show x = (-1) + (1 + x), by simp),
refine le_trans (v'.map_add _ _) _,
simp [this] },
{ rw h at hx', exact le_of_eq hx' } },
{ intros hx,
cases lt_or_eq_of_le hx with hx' hx',
{ have : v' (1 + x) = 1,
{ rw ← v'.map_one, apply map_add_eq_of_lt_left, simpa },
rw ← h at this,
rw (show x = (-1) + (1 + x), by simp),
refine le_trans (v.map_add _ _) _,
simp [this] },
{ rw ← h at hx', exact le_of_eq hx' } } }
end
end
section supp
variables [comm_ring R]
variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀]
variables (v : valuation R Γ₀)
/-- The support of a valuation `v : R → Γ₀` is the ideal of `R` where `v` vanishes. -/
def supp : ideal R :=
{ carrier := {x | v x = 0},
zero_mem' := map_zero v,
add_mem' := λ x y hx hy, le_zero_iff.mp $
calc v (x + y) ≤ max (v x) (v y) : v.map_add x y
... ≤ 0 : max_le (le_zero_iff.mpr hx) (le_zero_iff.mpr hy),
smul_mem' := λ c x hx, calc v (c * x)
= v c * v x : map_mul v c x
... = v c * 0 : congr_arg _ hx
... = 0 : mul_zero _ }
@[simp] lemma mem_supp_iff (x : R) : x ∈ supp v ↔ v x = 0 := iff.rfl
-- @[simp] lemma mem_supp_iff' (x : R) : x ∈ (supp v : set R) ↔ v x = 0 := iff.rfl
/-- The support of a valuation is a prime ideal. -/
instance [nontrivial Γ₀] [no_zero_divisors Γ₀] : ideal.is_prime (supp v) :=
⟨λ (h : v.supp = ⊤), one_ne_zero $ show (1 : Γ₀) = 0,
from calc 1 = v 1 : v.map_one.symm
... = 0 : show (1:R) ∈ supp v, by { rw h, trivial },
λ x y hxy, begin
show v x = 0 ∨ v y = 0,
change v (x * y) = 0 at hxy,
rw [v.map_mul x y] at hxy,
exact eq_zero_or_eq_zero_of_mul_eq_zero hxy
end⟩
lemma map_add_supp (a : R) {s : R} (h : s ∈ supp v) : v (a + s) = v a :=
begin
have aux : ∀ a s, v s = 0 → v (a + s) ≤ v a,
{ intros a' s' h', refine le_trans (v.map_add a' s') (max_le le_rfl _), simp [h'], },
apply le_antisymm (aux a s h),
calc v a = v (a + s + -s) : by simp
... ≤ v (a + s) : aux (a + s) (-s) (by rwa ←ideal.neg_mem_iff at h)
end
/-- If `hJ : J ⊆ supp v` then `on_quot_val hJ` is the induced function on R/J as a function.
Note: it's just the function; the valuation is `on_quot hJ`. -/
def on_quot_val {J : ideal R} (hJ : J ≤ supp v) :
R ⧸ J → Γ₀ :=
λ q, quotient.lift_on' q v $ λ a b h,
calc v a = v (b + -(-a + b)) : by simp
... = v b :
v.map_add_supp b $ (ideal.neg_mem_iff _).2 $ hJ $ quotient_add_group.left_rel_apply.mp h
/-- The extension of valuation v on R to valuation on R/J if J ⊆ supp v -/
def on_quot {J : ideal R} (hJ : J ≤ supp v) :
valuation (R ⧸ J) Γ₀ :=
{ to_fun := v.on_quot_val hJ,
map_zero' := v.map_zero,
map_one' := v.map_one,
map_mul' := λ xbar ybar, quotient.ind₂' v.map_mul xbar ybar,
map_add_le_max' := λ xbar ybar, quotient.ind₂' v.map_add xbar ybar }
@[simp] lemma on_quot_comap_eq {J : ideal R} (hJ : J ≤ supp v) :
(v.on_quot hJ).comap (ideal.quotient.mk J) = v :=
ext $ λ r, rfl
lemma comap_supp {S : Type*} [comm_ring S] (f : S →+* R) :
supp (v.comap f) = ideal.comap f v.supp :=
ideal.ext $ λ x,
begin
rw [mem_supp_iff, ideal.mem_comap, mem_supp_iff],
refl,
end
lemma self_le_supp_comap (J : ideal R) (v : valuation (R ⧸ J) Γ₀) :
J ≤ (v.comap (ideal.quotient.mk J)).supp :=
by { rw [comap_supp, ← ideal.map_le_iff_le_comap], simp }
@[simp] lemma comap_on_quot_eq (J : ideal R) (v : valuation (R ⧸ J) Γ₀) :
(v.comap (ideal.quotient.mk J)).on_quot (v.self_le_supp_comap J) = v :=
ext $ by { rintro ⟨x⟩, refl }
/-- The quotient valuation on R/J has support supp(v)/J if J ⊆ supp v. -/
lemma supp_quot {J : ideal R} (hJ : J ≤ supp v) :
supp (v.on_quot hJ) = (supp v).map (ideal.quotient.mk J) :=
begin
apply le_antisymm,
{ rintro ⟨x⟩ hx,
apply ideal.subset_span,
exact ⟨x, hx, rfl⟩ },
{ rw ideal.map_le_iff_le_comap,
intros x hx, exact hx }
end
lemma supp_quot_supp : supp (v.on_quot le_rfl) = 0 :=
by { rw supp_quot, exact ideal.map_quotient_self _ }
end supp -- end of section
end valuation
section add_monoid
variables (R) [ring R] (Γ₀ : Type*) [linear_ordered_add_comm_monoid_with_top Γ₀]
/-- The type of `Γ₀`-valued additive valuations on `R`. -/
@[nolint has_inhabited_instance]
def add_valuation := valuation R (multiplicative Γ₀ᵒᵈ)
end add_monoid
namespace add_valuation
variables {Γ₀ : Type*} {Γ'₀ : Type*}
section basic
section monoid
variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀]
variables (R) (Γ₀) [ring R]
/-- A valuation is coerced to the underlying function `R → Γ₀`. -/
instance : has_coe_to_fun (add_valuation R Γ₀) (λ _, R → Γ₀) :=
{ coe := λ v, v.to_monoid_with_zero_hom.to_fun }
variables {R} {Γ₀} (v : add_valuation R Γ₀) {x y z : R}
section
variables (f : R → Γ₀) (h0 : f 0 = ⊤) (h1 : f 1 = 0)
variables (hadd : ∀ x y, min (f x) (f y) ≤ f (x + y)) (hmul : ∀ x y, f (x * y) = f x + f y)
/-- An alternate constructor of `add_valuation`, that doesn't reference `multiplicative Γ₀ᵒᵈ` -/
def of : add_valuation R Γ₀ :=
{ to_fun := f,
map_one' := h1,
map_zero' := h0,
map_add_le_max' := hadd,
map_mul' := hmul }
variables {h0} {h1} {hadd} {hmul} {r : R}
@[simp]
theorem of_apply : (of f h0 h1 hadd hmul) r = f r := rfl
/-- The `valuation` associated to an `add_valuation` (useful if the latter is constructed using
`add_valuation.of`). -/
def valuation : valuation R (multiplicative Γ₀ᵒᵈ) := v
@[simp] lemma valuation_apply (r : R) :
v.valuation r = multiplicative.of_add (order_dual.to_dual (v r)) := rfl
end
@[simp] lemma map_zero : v 0 = ⊤ := v.map_zero
@[simp] lemma map_one : v 1 = 0 := v.map_one
@[simp] lemma map_mul : ∀ x y, v (x * y) = v x + v y := v.map_mul
@[simp] lemma map_add : ∀ x y, min (v x) (v y) ≤ v (x + y) := v.map_add
lemma map_le_add {x y g} (hx : g ≤ v x) (hy : g ≤ v y) : g ≤ v (x + y) := v.map_add_le hx hy
lemma map_lt_add {x y g} (hx : g < v x) (hy : g < v y) : g < v (x + y) := v.map_add_lt hx hy
lemma map_le_sum {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hf : ∀ i ∈ s, g ≤ v (f i)) :
g ≤ v (∑ i in s, f i) := v.map_sum_le hf
lemma map_lt_sum {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g ≠ ⊤)
(hf : ∀ i ∈ s, g < v (f i)) : g < v (∑ i in s, f i) := v.map_sum_lt hg hf
lemma map_lt_sum' {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g < ⊤)
(hf : ∀ i ∈ s, g < v (f i)) : g < v (∑ i in s, f i) := v.map_sum_lt' hg hf
@[simp] lemma map_pow : ∀ x (n:ℕ), v (x^n) = n • (v x) := v.map_pow
@[ext] lemma ext {v₁ v₂ : add_valuation R Γ₀} (h : ∀ r, v₁ r = v₂ r) : v₁ = v₂ :=
valuation.ext h
lemma ext_iff {v₁ v₂ : add_valuation R Γ₀} : v₁ = v₂ ↔ ∀ r, v₁ r = v₂ r :=
valuation.ext_iff
-- The following definition is not an instance, because we have more than one `v` on a given `R`.
-- In addition, type class inference would not be able to infer `v`.
/-- A valuation gives a preorder on the underlying ring. -/
def to_preorder : preorder R := preorder.lift v
/-- If `v` is an additive valuation on a division ring then `v(x) = ⊤` iff `x = 0`. -/
@[simp] lemma top_iff [nontrivial Γ₀] {K : Type*} [division_ring K]
(v : add_valuation K Γ₀) {x : K} : v x = ⊤ ↔ x = 0 :=
v.zero_iff
lemma ne_top_iff [nontrivial Γ₀] {K : Type*} [division_ring K]
(v : add_valuation K Γ₀) {x : K} : v x ≠ ⊤ ↔ x ≠ 0 := v.ne_zero_iff
/-- A ring homomorphism `S → R` induces a map `add_valuation R Γ₀ → add_valuation S Γ₀`. -/
def comap {S : Type*} [ring S] (f : S →+* R) (v : add_valuation R Γ₀) :
add_valuation S Γ₀ :=
v.comap f
@[simp] lemma comap_id : v.comap (ring_hom.id R) = v := v.comap_id
lemma comap_comp {S₁ : Type*} {S₂ : Type*} [ring S₁] [ring S₂] (f : S₁ →+* S₂) (g : S₂ →+* R) :
v.comap (g.comp f) = (v.comap g).comap f :=
v.comap_comp f g
/-- A `≤`-preserving, `⊤`-preserving group homomorphism `Γ₀ → Γ'₀` induces a map
`add_valuation R Γ₀ → add_valuation R Γ'₀`.
-/
def map (f : Γ₀ →+ Γ'₀) (ht : f ⊤ = ⊤) (hf : monotone f) (v : add_valuation R Γ₀) :
add_valuation R Γ'₀ :=
v.map
{ to_fun := f,
map_mul' := f.map_add,
map_one' := f.map_zero,
map_zero' := ht } (λ x y h, hf h)
/-- Two additive valuations on `R` are defined to be equivalent if they induce the same
preorder on `R`. -/
def is_equiv (v₁ : add_valuation R Γ₀) (v₂ : add_valuation R Γ'₀) : Prop :=
v₁.is_equiv v₂
end monoid
section group
variables [linear_ordered_add_comm_group_with_top Γ₀] [ring R] (v : add_valuation R Γ₀) {x y z : R}
@[simp] lemma map_inv {K : Type*} [division_ring K]
(v : add_valuation K Γ₀) {x : K} : v x⁻¹ = - (v x) :=
v.map_inv
lemma map_units_inv (x : Rˣ) : v (x⁻¹ : Rˣ) = - (v x) :=
v.map_units_inv x
@[simp] lemma map_neg (x : R) : v (-x) = v x :=
v.map_neg x
lemma map_sub_swap (x y : R) : v (x - y) = v (y - x) :=
v.map_sub_swap x y
lemma map_sub (x y : R) : min (v x) (v y) ≤ v (x - y) :=
v.map_sub x y
lemma map_le_sub {x y g} (hx : g ≤ v x) (hy : g ≤ v y) : g ≤ v (x - y) := v.map_sub_le hx hy
lemma map_add_of_distinct_val (h : v x ≠ v y) : v (x + y) = min (v x) (v y) :=
v.map_add_of_distinct_val h
lemma map_eq_of_lt_sub (h : v x < v (y - x)) : v y = v x :=
v.map_eq_of_sub_lt h
end group
end basic
namespace is_equiv
variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀]
variables [ring R]
variables {Γ''₀ : Type*} [linear_ordered_add_comm_monoid_with_top Γ''₀]
variables {v : add_valuation R Γ₀}
variables {v₁ : add_valuation R Γ₀} {v₂ : add_valuation R Γ'₀} {v₃ : add_valuation R Γ''₀}
@[refl] lemma refl : v.is_equiv v := valuation.is_equiv.refl
@[symm] lemma symm (h : v₁.is_equiv v₂) : v₂.is_equiv v₁ := h.symm
@[trans] lemma trans (h₁₂ : v₁.is_equiv v₂) (h₂₃ : v₂.is_equiv v₃) : v₁.is_equiv v₃ :=
h₁₂.trans h₂₃
lemma of_eq {v' : add_valuation R Γ₀} (h : v = v') : v.is_equiv v' :=
valuation.is_equiv.of_eq h
lemma map {v' : add_valuation R Γ₀} (f : Γ₀ →+ Γ'₀) (ht : f ⊤ = ⊤) (hf : monotone f)
(inf : injective f) (h : v.is_equiv v') :
(v.map f ht hf).is_equiv (v'.map f ht hf) :=
h.map
{ to_fun := f,
map_mul' := f.map_add,
map_one' := f.map_zero,
map_zero' := ht } (λ x y h, hf h) inf
/-- `comap` preserves equivalence. -/
lemma comap {S : Type*} [ring S] (f : S →+* R) (h : v₁.is_equiv v₂) :
(v₁.comap f).is_equiv (v₂.comap f) :=
h.comap f
lemma val_eq (h : v₁.is_equiv v₂) {r s : R} :
v₁ r = v₁ s ↔ v₂ r = v₂ s :=
h.val_eq
lemma ne_top (h : v₁.is_equiv v₂) {r : R} :
v₁ r ≠ ⊤ ↔ v₂ r ≠ ⊤ :=
h.ne_zero
end is_equiv
section supp
variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀]
variables [comm_ring R]
variables (v : add_valuation R Γ₀)
/-- The support of an additive valuation `v : R → Γ₀` is the ideal of `R` where `v x = ⊤` -/
def supp : ideal R := v.supp
@[simp] lemma mem_supp_iff (x : R) : x ∈ supp v ↔ v x = ⊤ := v.mem_supp_iff x
lemma map_add_supp (a : R) {s : R} (h : s ∈ supp v) : v (a + s) = v a :=
v.map_add_supp a h
/-- If `hJ : J ⊆ supp v` then `on_quot_val hJ` is the induced function on R/J as a function.
Note: it's just the function; the valuation is `on_quot hJ`. -/
def on_quot_val {J : ideal R} (hJ : J ≤ supp v) : (R ⧸ J) → Γ₀ := v.on_quot_val hJ
/-- The extension of valuation v on R to valuation on R/J if J ⊆ supp v -/
def on_quot {J : ideal R} (hJ : J ≤ supp v) :
add_valuation (R ⧸ J) Γ₀ :=
v.on_quot hJ
@[simp] lemma on_quot_comap_eq {J : ideal R} (hJ : J ≤ supp v) :
(v.on_quot hJ).comap (ideal.quotient.mk J) = v :=
v.on_quot_comap_eq hJ
lemma comap_supp {S : Type*} [comm_ring S] (f : S →+* R) :
supp (v.comap f) = ideal.comap f v.supp :=
v.comap_supp f
lemma self_le_supp_comap (J : ideal R) (v : add_valuation (R ⧸ J) Γ₀) :
J ≤ (v.comap (ideal.quotient.mk J)).supp :=
v.self_le_supp_comap J
@[simp] lemma comap_on_quot_eq (J : ideal R) (v : add_valuation (R ⧸ J) Γ₀) :
(v.comap (ideal.quotient.mk J)).on_quot (v.self_le_supp_comap J) = v :=
v.comap_on_quot_eq J
/-- The quotient valuation on R/J has support supp(v)/J if J ⊆ supp v. -/
lemma supp_quot {J : ideal R} (hJ : J ≤ supp v) :
supp (v.on_quot hJ) = (supp v).map (ideal.quotient.mk J) :=
v.supp_quot hJ
lemma supp_quot_supp : supp (v.on_quot le_rfl) = 0 :=
v.supp_quot_supp
end supp -- end of section
attribute [irreducible] add_valuation
end add_valuation
section valuation_notation
localized "notation `ℕₘ₀` := with_zero (multiplicative ℕ)" in discrete_valuation
localized "notation `ℤₘ₀` := with_zero (multiplicative ℤ)" in discrete_valuation
end valuation_notation
|
7d356b0bdf417af70cf2f1ab66857c2f462d456b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/group_theory/noncomm_pi_coprod.lean | 602cb46e8853993b1767c34d935a12d034ed519e | [
"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 | 11,451 | lean | /-
Copyright (c) 2022 Joachim Breitner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joachim Breitner
-/
import group_theory.order_of_element
import data.finset.noncomm_prod
import data.fintype.big_operators
import data.nat.gcd.big_operators
import order.sup_indep
/-!
# Canonical homomorphism from a finite family of monoids
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the construction of the canonical homomorphism from a family of monoids.
Given a family of morphisms `ϕ i : N i →* M` for each `i : ι` where elements in the
images of different morphisms commute, we obtain a canonical morphism
`monoid_hom.noncomm_pi_coprod : (Π i, N i) →* M` that coincides with `ϕ`
## Main definitions
* `monoid_hom.noncomm_pi_coprod : (Π i, N i) →* M` is the main homomorphism
* `subgroup.noncomm_pi_coprod : (Π i, H i) →* G` is the specialization to `H i : subgroup G`
and the subgroup embedding.
## Main theorems
* `monoid_hom.noncomm_pi_coprod` coincides with `ϕ i` when restricted to `N i`
* `monoid_hom.noncomm_pi_coprod_mrange`: The range of `monoid_hom.noncomm_pi_coprod` is
`⨆ (i : ι), (ϕ i).mrange`
* `monoid_hom.noncomm_pi_coprod_range`: The range of `monoid_hom.noncomm_pi_coprod` is
`⨆ (i : ι), (ϕ i).range`
* `subgroup.noncomm_pi_coprod_range`: The range of `subgroup.noncomm_pi_coprod` is `⨆ (i : ι), H i`.
* `monoid_hom.injective_noncomm_pi_coprod_of_independent`: in the case of groups, `pi_hom.hom` is
injective if the `ϕ` are injective and the ranges of the `ϕ` are independent.
* `monoid_hom.independent_range_of_coprime_order`: If the `N i` have coprime orders, then the ranges
of the `ϕ` are independent.
* `subgroup.independent_of_coprime_order`: If commuting normal subgroups `H i` have coprime orders,
they are independent.
-/
open_locale big_operators
namespace subgroup
variables {G : Type*} [group G]
/-- `finset.noncomm_prod` is “injective” in `f` if `f` maps into independent subgroups. This
generalizes (one direction of) `subgroup.disjoint_iff_mul_eq_one`. -/
@[to_additive "`finset.noncomm_sum` is “injective” in `f` if `f` maps into independent subgroups.
This generalizes (one direction of) `add_subgroup.disjoint_iff_add_eq_zero`. "]
lemma eq_one_of_noncomm_prod_eq_one_of_independent {ι : Type*} (s : finset ι) (f : ι → G) (comm)
(K : ι → subgroup G) (hind : complete_lattice.independent K) (hmem : ∀ (x ∈ s), f x ∈ K x)
(heq1 : s.noncomm_prod f comm = 1) : ∀ (i ∈ s), f i = 1 :=
begin
classical,
revert heq1,
induction s using finset.induction_on with i s hnmem ih,
{ simp, },
{ have hcomm := comm.mono (finset.coe_subset.2 $ finset.subset_insert _ _),
simp only [finset.forall_mem_insert] at hmem,
have hmem_bsupr: s.noncomm_prod f hcomm ∈ ⨆ (i ∈ (s : set ι)), K i,
{ refine subgroup.noncomm_prod_mem _ _ _,
intros x hx,
have : K x ≤ ⨆ (i ∈ (s : set ι)), K i := le_supr₂ x hx,
exact this (hmem.2 x hx), },
intro heq1,
rw finset.noncomm_prod_insert_of_not_mem _ _ _ _ hnmem at heq1,
have hnmem' : i ∉ (s : set ι), by simpa,
obtain ⟨heq1i : f i = 1, heq1S : s.noncomm_prod f _ = 1⟩ :=
subgroup.disjoint_iff_mul_eq_one.mp (hind.disjoint_bsupr hnmem') hmem.1 hmem_bsupr heq1,
intros i h,
simp only [finset.mem_insert] at h,
rcases h with ⟨rfl | _⟩,
{ exact heq1i },
{ exact ih hcomm hmem.2 heq1S _ h } }
end
end subgroup
section family_of_monoids
variables {M : Type*} [monoid M]
-- We have a family of monoids
-- The fintype assumption is not always used, but declared here, to keep things in order
variables {ι : Type*} [hdec : decidable_eq ι] [fintype ι]
variables {N : ι → Type*} [∀ i, monoid (N i)]
-- And morphisms ϕ into G
variables (ϕ : Π (i : ι), N i →* M)
-- We assume that the elements of different morphism commute
variables (hcomm : pairwise $ λ i j, ∀ x y, commute (ϕ i x) (ϕ j y))
include hcomm
-- We use `f` and `g` to denote elements of `Π (i : ι), N i`
variables (f g : Π (i : ι), N i)
namespace monoid_hom
/-- The canonical homomorphism from a family of monoids. -/
@[to_additive "The canonical homomorphism from a family of additive monoids.
See also `linear_map.lsum` for a linear version without the commutativity assumption."]
def noncomm_pi_coprod : (Π (i : ι), N i) →* M :=
{ to_fun := λ f, finset.univ.noncomm_prod (λ i, ϕ i (f i)) $ λ i _ j _ h, hcomm h _ _,
map_one' := by {apply (finset.noncomm_prod_eq_pow_card _ _ _ _ _).trans (one_pow _), simp},
map_mul' := λ f g,
begin
classical,
convert @finset.noncomm_prod_mul_distrib _ _ _ _ (λ i, ϕ i (f i)) (λ i, ϕ i (g i)) _ _ _,
{ ext i, exact map_mul (ϕ i) (f i) (g i), },
{ rintros i - j - h, exact hcomm h _ _ },
end }
variable {hcomm}
include hdec
@[simp, to_additive]
lemma noncomm_pi_coprod_mul_single (i : ι) (y : N i):
noncomm_pi_coprod ϕ hcomm (pi.mul_single i y) = ϕ i y :=
begin
change finset.univ.noncomm_prod (λ j, ϕ j (pi.mul_single i y j)) _ = ϕ i y,
simp only [←finset.insert_erase (finset.mem_univ i)] {single_pass := tt},
rw finset.noncomm_prod_insert_of_not_mem _ _ _ _ (finset.not_mem_erase i _),
rw pi.mul_single_eq_same,
rw finset.noncomm_prod_eq_pow_card,
{ rw one_pow, exact mul_one _ },
{ intros j hj, simp only [finset.mem_erase] at hj, simp [hj], },
end
omit hcomm
/-- The universal property of `noncomm_pi_coprod` -/
@[to_additive "The universal property of `noncomm_pi_coprod`"]
def noncomm_pi_coprod_equiv :
{ϕ : Π i, N i →* M // pairwise (λ i j, ∀ x y, commute (ϕ i x) (ϕ j y)) }
≃ ((Π i, N i) →* M) :=
{ to_fun := λ ϕ, noncomm_pi_coprod ϕ.1 ϕ.2,
inv_fun := λ f,
⟨ λ i, f.comp (monoid_hom.single N i),
λ i j hij x y, commute.map (pi.mul_single_commute hij x y) f ⟩,
left_inv := λ ϕ, by { ext, simp, },
right_inv := λ f, pi_ext (λ i x, by simp) }
omit hdec
include hcomm
@[to_additive]
lemma noncomm_pi_coprod_mrange : (noncomm_pi_coprod ϕ hcomm).mrange = ⨆ i : ι, (ϕ i).mrange :=
begin
classical,
apply le_antisymm,
{ rintro x ⟨f, rfl⟩,
refine submonoid.noncomm_prod_mem _ _ _ _ _,
intros i hi,
apply submonoid.mem_Sup_of_mem, { use i },
simp, },
{ refine supr_le _,
rintro i x ⟨y, rfl⟩,
refine ⟨pi.mul_single i y, noncomm_pi_coprod_mul_single _ _ _⟩, },
end
end monoid_hom
end family_of_monoids
section family_of_groups
variables {G : Type*} [group G]
variables {ι : Type*} [hdec : decidable_eq ι] [hfin : fintype ι]
variables {H : ι → Type*} [∀ i, group (H i)]
variables (ϕ : Π (i : ι), H i →* G)
variables {hcomm : ∀ (i j : ι), i ≠ j → ∀ (x : H i) (y : H j), commute (ϕ i x) (ϕ j y)}
include hcomm
-- We use `f` and `g` to denote elements of `Π (i : ι), H i`
variables (f g : Π (i : ι), H i)
include hfin
namespace monoid_hom
-- The subgroup version of `noncomm_pi_coprod_mrange`
@[to_additive]
lemma noncomm_pi_coprod_range : (noncomm_pi_coprod ϕ hcomm).range = ⨆ i : ι, (ϕ i).range :=
begin
classical,
apply le_antisymm,
{ rintro x ⟨f, rfl⟩,
refine subgroup.noncomm_prod_mem _ _ _,
intros i hi,
apply subgroup.mem_Sup_of_mem, { use i },
simp, },
{ refine supr_le _,
rintro i x ⟨y, rfl⟩,
refine ⟨pi.mul_single i y, noncomm_pi_coprod_mul_single _ _ _⟩, },
end
@[to_additive]
lemma injective_noncomm_pi_coprod_of_independent
(hind : complete_lattice.independent (λ i, (ϕ i).range))
(hinj : ∀ i, function.injective (ϕ i)) :
function.injective (noncomm_pi_coprod ϕ hcomm):=
begin
classical,
apply (monoid_hom.ker_eq_bot_iff _).mp,
apply eq_bot_iff.mpr,
intros f heq1,
change finset.univ.noncomm_prod (λ i, ϕ i (f i)) _ = 1 at heq1,
change f = 1,
have : ∀ i, i ∈ finset.univ → ϕ i (f i) = 1 :=
subgroup.eq_one_of_noncomm_prod_eq_one_of_independent _ _ _ _ hind (by simp) heq1,
ext i,
apply hinj,
simp [this i (finset.mem_univ i)],
end
variable (hcomm)
omit hfin
@[to_additive]
lemma independent_range_of_coprime_order [finite ι] [Π i, fintype (H i)]
(hcoprime : ∀ i j, i ≠ j → nat.coprime (fintype.card (H i)) (fintype.card (H j))) :
complete_lattice.independent (λ i, (ϕ i).range) :=
begin
casesI nonempty_fintype ι,
classical,
rintros i,
rw disjoint_iff_inf_le,
rintros f ⟨hxi, hxp⟩, dsimp at hxi hxp,
rw [supr_subtype', ← noncomm_pi_coprod_range] at hxp,
rotate, { intros _ _ hj, apply hcomm, exact hj ∘ subtype.ext },
cases hxp with g hgf, cases hxi with g' hg'f,
have hxi : order_of f ∣ fintype.card (H i),
{ rw ← hg'f, exact (order_of_map_dvd _ _).trans order_of_dvd_card_univ },
have hxp : order_of f ∣ ∏ j : {j // j ≠ i}, fintype.card (H j),
{ rw [← hgf, ← fintype.card_pi], exact (order_of_map_dvd _ _).trans order_of_dvd_card_univ },
change f = 1, rw [← pow_one f, ← order_of_dvd_iff_pow_eq_one],
convert ← nat.dvd_gcd hxp hxi, rw ← nat.coprime_iff_gcd_eq_one,
apply nat.coprime_prod_left, intros j _, apply hcoprime, exact j.2,
end
end monoid_hom
end family_of_groups
namespace subgroup
-- We have an family of subgroups
variables {G : Type*} [group G]
variables {ι : Type*} [hdec : decidable_eq ι] [hfin : fintype ι] {H : ι → subgroup G}
-- Elements of `Π (i : ι), H i` are called `f` and `g` here
variables (f g : Π (i : ι), H i)
section commuting_subgroups
-- We assume that the elements of different subgroups commute
variables (hcomm : ∀ (i j : ι), i ≠ j → ∀ (x y : G), x ∈ H i → y ∈ H j → commute x y)
include hcomm
@[to_additive]
lemma commute_subtype_of_commute (i j : ι) (hne : i ≠ j) :
∀ (x : H i) (y : H j), commute ((H i).subtype x) ((H j).subtype y) :=
by { rintros ⟨x, hx⟩ ⟨y, hy⟩, exact hcomm i j hne x y hx hy }
include hfin
/-- The canonical homomorphism from a family of subgroups where elements from different subgroups
commute -/
@[to_additive "The canonical homomorphism from a family of additive subgroups where elements from
different subgroups commute"]
def noncomm_pi_coprod : (Π (i : ι), H i) →* G :=
monoid_hom.noncomm_pi_coprod (λ i, (H i).subtype) (commute_subtype_of_commute hcomm)
variable {hcomm}
include hdec
@[simp, to_additive]
lemma noncomm_pi_coprod_mul_single (i : ι) (y : H i) :
noncomm_pi_coprod hcomm (pi.mul_single i y) = y :=
by apply monoid_hom.noncomm_pi_coprod_mul_single
omit hdec
@[to_additive]
lemma noncomm_pi_coprod_range : (noncomm_pi_coprod hcomm).range = ⨆ i : ι, H i :=
by simp [noncomm_pi_coprod, monoid_hom.noncomm_pi_coprod_range]
@[to_additive]
lemma injective_noncomm_pi_coprod_of_independent (hind : complete_lattice.independent H) :
function.injective (noncomm_pi_coprod hcomm) :=
begin
apply monoid_hom.injective_noncomm_pi_coprod_of_independent,
{ simpa using hind },
{ intro i, exact subtype.coe_injective }
end
variable (hcomm)
omit hfin
@[to_additive]
lemma independent_of_coprime_order [finite ι] [∀ i, fintype (H i)]
(hcoprime : ∀ i j, i ≠ j → nat.coprime (fintype.card (H i)) (fintype.card (H j))) :
complete_lattice.independent H :=
by simpa using monoid_hom.independent_range_of_coprime_order (λ i, (H i).subtype)
(commute_subtype_of_commute hcomm) hcoprime
end commuting_subgroups
end subgroup
|
a5e7cd735422fcd29a14878d07b2c21d28174287 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/metric_space/gromov_hausdorff.lean | 092a76e9be84601083c37a9daff15cdea76f1fbf | [
"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 | 55,918 | 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 set_theory.cardinal.basic
import topology.metric_space.closeds
import topology.metric_space.completion
import topology.metric_space.gromov_hausdorff_realized
import topology.metric_space.kuratowski
/-!
# Gromov-Hausdorff distance
This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces
up to isometry.
We introduce the space of all nonempty compact metric spaces, up to isometry,
called `GH_space`, and endow it with a metric space structure. The distance,
known as the Gromov-Hausdorff distance, is defined as follows: given two
nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance
between all possible isometric embeddings of `X` and `Y` in all metric spaces.
To define properly the Gromov-Hausdorff space, we consider the non-empty
compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type,
and define the distance as the infimum of the Hausdorff distance over all
embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description,
as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an
embedding called the Kuratowski embedding.
To prove that we have a distance, we should show that if spaces can be coupled
to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff
distance is realized, i.e., there is a coupling for which the Hausdorff distance
is exactly the Gromov-Hausdorff distance. This follows from a compactness
argument, essentially following from Arzela-Ascoli.
## Main results
We prove the most important properties of the Gromov-Hausdorff space: it is a polish space,
i.e., it is complete and second countable. We also prove the Gromov compactness criterion.
-/
noncomputable theory
open_locale classical topological_space ennreal
local notation `ℓ_infty_ℝ`:= lp (λ n : ℕ, ℝ) ∞
universes u v w
open classical set function topological_space filter metric quotient
open bounded_continuous_function nat int Kuratowski_embedding
open sum (inl inr)
local attribute [instance] metric_space_sum
namespace Gromov_Hausdorff
section GH_space
/- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient
of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets.
Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty
compact type to `GH_space`. -/
/-- Equivalence relation identifying two nonempty compact sets which are isometric -/
private def isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop :=
λ x y, nonempty (x ≃ᵢ y)
/-- This is indeed an equivalence relation -/
private lemma is_equivalence_isometry_rel : equivalence isometry_rel :=
⟨λ x, ⟨isometric.refl _⟩, λ x y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩
/-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/
instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) :=
setoid.mk isometry_rel is_equivalence_isometry_rel
/-- The Gromov-Hausdorff space -/
definition GH_space : Type := quotient (isometry_rel.setoid)
/-- Map any nonempty compact type to `GH_space` -/
definition to_GH_space (X : Type u) [metric_space X] [compact_space X] [nonempty X] : GH_space :=
⟦nonempty_compacts.Kuratowski_embedding X⟧
instance : inhabited GH_space := ⟨quot.mk _ ⟨⟨{0}, is_compact_singleton⟩, singleton_nonempty _⟩⟩
/-- A metric space representative of any abstract point in `GH_space` -/
@[nolint has_nonempty_instance]
def GH_space.rep (p : GH_space) : Type := (quotient.out p : nonempty_compacts ℓ_infty_ℝ)
lemma eq_to_GH_space_iff {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{p : nonempty_compacts ℓ_infty_ℝ} :
⟦p⟧ = to_GH_space X ↔ ∃ Ψ : X → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p :=
begin
simp only [to_GH_space, quotient.eq],
refine ⟨λ h, _, _⟩,
{ rcases setoid.symm h with ⟨e⟩,
have f := (Kuratowski_embedding.isometry X).isometric_on_range.trans e,
use [λ x, f x, isometry_subtype_coe.comp f.isometry],
rw [range_comp, f.range_eq_univ, set.image_univ, subtype.range_coe],
refl },
{ rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩,
have f := ((Kuratowski_embedding.isometry X).isometric_on_range.symm.trans
isomΨ.isometric_on_range).symm,
have E : (range Ψ ≃ᵢ nonempty_compacts.Kuratowski_embedding X) =
(p ≃ᵢ range (Kuratowski_embedding X)),
by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl },
exact ⟨cast E f⟩ }
end
lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p :=
eq_to_GH_space_iff.2 ⟨λ x, x, isometry_subtype_coe, subtype.range_coe⟩
section
local attribute [reducible] GH_space.rep
instance rep_GH_space_metric_space {p : GH_space} : metric_space p.rep := by apply_instance
instance rep_GH_space_compact_space {p : GH_space} : compact_space p.rep := by apply_instance
instance rep_GH_space_nonempty {p : GH_space} : nonempty p.rep := by apply_instance
end
lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space p.rep = p :=
begin
change to_GH_space (quot.out p : nonempty_compacts ℓ_infty_ℝ) = p,
rw ← eq_to_GH_space,
exact quot.out_eq p
end
/-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are
isometric. -/
lemma to_GH_space_eq_to_GH_space_iff_isometric {X : Type u} [metric_space X] [compact_space X]
[nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] :
to_GH_space X = to_GH_space Y ↔ nonempty (X ≃ᵢ Y) :=
⟨begin
simp only [to_GH_space, quotient.eq],
rintro ⟨e⟩,
have I : ((nonempty_compacts.Kuratowski_embedding X) ≃ᵢ
(nonempty_compacts.Kuratowski_embedding Y))
= ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
have f := (Kuratowski_embedding.isometry X).isometric_on_range,
have g := (Kuratowski_embedding.isometry Y).isometric_on_range.symm,
exact ⟨f.trans $ (cast I e).trans g⟩
end,
begin
rintro ⟨e⟩,
simp only [to_GH_space, quotient.eq],
have f := (Kuratowski_embedding.isometry X).isometric_on_range.symm,
have g := (Kuratowski_embedding.isometry Y).isometric_on_range,
have I : ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))) =
((nonempty_compacts.Kuratowski_embedding X) ≃ᵢ
(nonempty_compacts.Kuratowski_embedding Y)),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
exact ⟨cast I ((f.trans e).trans g)⟩
end⟩
/-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum
Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition,
we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/
instance : has_dist (GH_space) :=
{ dist := λ x y, Inf $
(λ p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ,
Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) '' ({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y}) }
/-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to
the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/
def GH_dist (X : Type u) (Y : Type v) [metric_space X] [nonempty X] [compact_space X]
[metric_space Y] [nonempty Y] [compact_space Y] : ℝ := dist (to_GH_space X) (to_GH_space Y)
lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist p.rep (q.rep) :=
by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep]
/-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance
of isometric copies of the spaces, in any metric space. -/
theorem GH_dist_le_Hausdorff_dist {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y]
{γ : Type w} [metric_space γ] {Φ : X → γ} {Ψ : Y → γ} (ha : isometry Φ) (hb : isometry Ψ) :
GH_dist X Y ≤ Hausdorff_dist (range Φ) (range Ψ) :=
begin
/- For the proof, we want to embed `γ` in `ℓ^∞(ℝ)`, to say that the Hausdorff distance is realized
in `ℓ^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `γ` is not
separable in general. We restrict to the union of the images of `X` and `Y` in `γ`, which is
separable and therefore embeddable in `ℓ^∞(ℝ)`. -/
rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
let s : set γ := (range Φ) ∪ (range Ψ),
let Φ' : X → subtype s := λ y, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩,
let Ψ' : Y → subtype s := λ y, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩,
have IΦ' : isometry Φ' := λ x y, ha x y,
have IΨ' : isometry Ψ' := λ x y, hb x y,
have : is_compact s, from (is_compact_range ha.continuous).union (is_compact_range hb.continuous),
letI : metric_space (subtype s) := by apply_instance,
haveI : compact_space (subtype s) := ⟨is_compact_iff_is_compact_univ.1 ‹is_compact s›⟩,
haveI : nonempty (subtype s) := ⟨Φ' xX⟩,
have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl },
have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl },
have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'),
{ rw [ΦΦ', ΨΨ', range_comp, range_comp],
exact Hausdorff_dist_image (isometry_subtype_coe) },
rw this,
-- Embed `s` in `ℓ^∞(ℝ)` through its Kuratowski embedding
let F := Kuratowski_embedding (subtype s),
have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) =
Hausdorff_dist (range Φ') (range Ψ') := Hausdorff_dist_image (Kuratowski_embedding.isometry _),
rw ← this,
-- Let `A` and `B` be the images of `X` and `Y` under this embedding. They are in `ℓ^∞(ℝ)`, and
-- their Hausdorff distance is the same as in the original space.
let A : nonempty_compacts ℓ_infty_ℝ := ⟨⟨F '' (range Φ'), (is_compact_range IΦ'.continuous).image
(Kuratowski_embedding.isometry _).continuous⟩, (range_nonempty _).image _⟩,
let B : nonempty_compacts ℓ_infty_ℝ := ⟨⟨F '' (range Ψ'), (is_compact_range IΨ'.continuous).image
(Kuratowski_embedding.isometry _).continuous⟩, (range_nonempty _).image _⟩,
have AX : ⟦A⟧ = to_GH_space X,
{ rw eq_to_GH_space_iff,
exact ⟨λ x, F (Φ' x), (Kuratowski_embedding.isometry _).comp IΦ', range_comp _ _⟩ },
have BY : ⟦B⟧ = to_GH_space Y,
{ rw eq_to_GH_space_iff,
exact ⟨λ x, F (Ψ' x), (Kuratowski_embedding.isometry _).comp IΨ', range_comp _ _⟩ },
refine cInf_le ⟨0, _⟩ _,
{ simp only [lower_bounds, mem_image, mem_prod, mem_set_of_eq, prod.exists, and_imp,
forall_exists_index],
assume t _ _ _ _ ht,
rw ← ht,
exact Hausdorff_dist_nonneg },
apply (mem_image _ _ _).2,
existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
simp [AX, BY],
end
/-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance,
essentially by design. -/
lemma Hausdorff_dist_optimal {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] :
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) = GH_dist X Y :=
begin
inhabit X, inhabit Y,
/- we only need to check the inequality `≤`, as the other one follows from the previous lemma.
As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance
in the optimal coupling is smaller than the Hausdorff distance of any coupling.
First, we check this for couplings which already have small Hausdorff distance: in this
case, the induced "distance" on `X ⊕ Y` belongs to the candidates family introduced in the
definition of the optimal coupling, and the conclusion follows from the optimality
of the optimal coupling within this family.
-/
have A : ∀ p q : nonempty_compacts ℓ_infty_ℝ, ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y →
Hausdorff_dist (p : set ℓ_infty_ℝ) q < diam (univ : set X) + 1 + diam (univ : set Y) →
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤
Hausdorff_dist (p : set ℓ_infty_ℝ) q,
{ assume p q hp hq bound,
rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩,
rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩,
have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y),
{ rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
have : ∃ y ∈ range Ψ, dist (Φ xX) y < diam (univ : set X) + 1 + diam (univ : set Y),
{ rw Ψrange,
have : Φ xX ∈ ↑p := Φrange.subst (mem_range_self _),
exact exists_dist_lt_of_Hausdorff_dist_lt this bound
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty
p.is_compact.bounded q.is_compact.bounded) },
rcases this with ⟨y, hy, dy⟩,
rcases mem_range.1 hy with ⟨z, hzy⟩,
rw ← hzy at dy,
have DΦ : diam (range Φ) = diam (univ : set X) := Φisom.diam_range,
have DΨ : diam (range Ψ) = diam (univ : set Y) := Ψisom.diam_range,
calc
diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xX) (Ψ z) + diam (range Ψ) :
diam_union (mem_range_self _) (mem_range_self _)
... ≤ diam (univ : set X) + (diam (univ : set X) + 1 + diam (univ : set Y)) +
diam (univ : set Y) :
by { rw [DΦ, DΨ], apply add_le_add (add_le_add le_rfl (le_of_lt dy)) le_rfl }
... = 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : by ring },
let f : X ⊕ Y → ℓ_infty_ℝ := λ x, match x with | inl y := Φ y | inr z := Ψ z end,
let F : (X ⊕ Y) × (X ⊕ Y) → ℝ := λ p, dist (f p.1) (f p.2),
-- check that the induced "distance" is a candidate
have Fgood : F ∈ candidates X Y,
{ simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero,
and_self, set.mem_set_of_eq],
repeat {split},
{ exact λ x y, calc
F (inl x, inl y) = dist (Φ x) (Φ y) : rfl
... = dist x y : Φisom.dist_eq x y },
{ exact λ x y, calc
F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl
... = dist x y : Ψisom.dist_eq x y },
{ exact λ x y, dist_comm _ _ },
{ exact λ x y z, dist_triangle _ _ _ },
{ exact λ x y, calc
F (x, y) ≤ diam (range Φ ∪ range Ψ) :
begin
have A : ∀ z : X ⊕ Y, f z ∈ range Φ ∪ range Ψ,
{ assume z,
cases z,
{ apply mem_union_left, apply mem_range_self },
{ apply mem_union_right, apply mem_range_self } },
refine dist_le_diam_of_mem _ (A _) (A _),
rw [Φrange, Ψrange],
exact (p ⊔ q).is_compact.bounded,
end
... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : I } },
let Fb := candidates_b_of_candidates F Fgood,
have : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD Fb :=
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood),
refine le_trans this (le_of_forall_le_of_dense (λ r hr, _)),
have I1 : ∀ x : X, (⨅ y, Fb (inl x, inr y)) ≤ r,
{ assume x,
have : f (inl x) ∈ ↑p := Φrange.subst (mem_range_self _),
rcases exists_dist_lt_of_Hausdorff_dist_lt this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty
p.is_compact.bounded q.is_compact.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Ψ, by rwa [← Ψrange] at zq,
rcases mem_range.1 this with ⟨y, hy⟩,
calc (⨅ y, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa only [add_zero] using HD_below_aux1 0) y
... = dist (Φ x) (Ψ y) : rfl
... = dist (f (inl x)) z : by rw hy
... ≤ r : le_of_lt hz },
have I2 : ∀ y : Y, (⨅ x, Fb (inl x, inr y)) ≤ r,
{ assume y,
have : f (inr y) ∈ ↑q := Ψrange.subst (mem_range_self _),
rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty
p.is_compact.bounded q.is_compact.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Φ, by rwa [← Φrange] at zq,
rcases mem_range.1 this with ⟨x, hx⟩,
calc (⨅ x, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa only [add_zero] using HD_below_aux2 0) x
... = dist (Φ x) (Ψ y) : rfl
... = dist z (f (inr y)) : by rw hx
... ≤ r : le_of_lt hz },
simp only [HD, csupr_le I1, csupr_le I2, max_le_iff, and_self] },
/- Get the same inequality for any coupling. If the coupling is quite good, the desired
inequality has been proved above. If it is bad, then the inequality is obvious. -/
have B : ∀ p q : nonempty_compacts ℓ_infty_ℝ, ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y →
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤
Hausdorff_dist (p : set ℓ_infty_ℝ) q,
{ assume p q hp hq,
by_cases h :
Hausdorff_dist (p : set ℓ_infty_ℝ) q < diam (univ : set X) + 1 + diam (univ : set Y),
{ exact A p q hp hq h },
{ calc Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y))
≤ HD (candidates_b_dist X Y) :
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b)
... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : HD_candidates_b_dist_le
... ≤ Hausdorff_dist (p : set ℓ_infty_ℝ) q : not_lt.1 h } },
refine le_antisymm _ _,
{ apply le_cInf,
{ refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ },
{ rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩,
exact B p q hp hq } },
{ exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl X Y) (isometry_optimal_GH_injr X Y) }
end
/-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding
the optimal coupling through its Kuratowski embedding. -/
theorem GH_dist_eq_Hausdorff_dist (X : Type u) [metric_space X] [compact_space X] [nonempty X]
(Y : Type v) [metric_space Y] [compact_space Y] [nonempty Y] :
∃ Φ : X → ℓ_infty_ℝ, ∃ Ψ : Y → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧
GH_dist X Y = Hausdorff_dist (range Φ) (range Ψ) :=
begin
let F := Kuratowski_embedding (optimal_GH_coupling X Y),
let Φ := F ∘ optimal_GH_injl X Y,
let Ψ := F ∘ optimal_GH_injr X Y,
refine ⟨Φ, Ψ, _, _, _⟩,
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl X Y) },
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr X Y) },
{ rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr X Y),
image_univ, ← Hausdorff_dist_optimal],
exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm },
end
/-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/
instance : metric_space GH_space :=
{ dist := dist,
dist_self := λ x, begin
rcases exists_rep x with ⟨y, hy⟩,
refine le_antisymm _ _,
{ apply cInf_le,
{ exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩},
{ simp only [mem_image, mem_prod, mem_set_of_eq, prod.exists],
existsi [y, y],
simpa only [and_self, Hausdorff_dist_self_zero, eq_self_iff_true, and_true]} },
{ apply le_cInf,
{ exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ },
{ rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } },
end,
dist_comm := λ x y, begin
have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) ''
({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y})
= ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) ∘ prod.swap) ''
({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y}),
{ congr, funext, simp only [comp_app, prod.fst_swap, prod.snd_swap], rw Hausdorff_dist_comm },
simp only [dist, A, image_comp, image_swap_prod],
end,
eq_of_dist_eq_zero := λ x y hxy, begin
/- To show that two spaces at zero distance are isometric, we argue that the distance
is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance,
i.e., they coincide. Therefore, the original spaces are isometric. -/
rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩,
rw [← dist_GH_dist, hxy] at DΦΨ,
have : range Φ = range Ψ,
{ have hΦ : is_compact (range Φ) := is_compact_range Φisom.continuous,
have hΨ : is_compact (range Ψ) := is_compact_range Ψisom.continuous,
apply (is_closed.Hausdorff_dist_zero_iff_eq _ _ _).1 (DΦΨ.symm),
{ exact hΦ.is_closed },
{ exact hΨ.is_closed },
{ exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _)
(range_nonempty _) hΦ.bounded hΨ.bounded } },
have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this,
have eΨ := cast T Ψisom.isometric_on_range.symm,
have e := Φisom.isometric_on_range.trans eΨ,
rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric],
exact ⟨e⟩
end,
dist_triangle := λ x y z, begin
/- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling
between `X` and `Y` in a space `γ1`, and an optimal coupling between `Y` and `Z` in a space
`γ2`. Then, glue these metric spaces along `Y`. We get a new space `γ` in which `X` and `Y` are
optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff
distance in `γ` to conclude. -/
let X := x.rep,
let Y := y.rep,
let Z := z.rep,
let γ1 := optimal_GH_coupling X Y,
let γ2 := optimal_GH_coupling Y Z,
let Φ : Y → γ1 := optimal_GH_injr X Y,
have hΦ : isometry Φ := isometry_optimal_GH_injr X Y,
let Ψ : Y → γ2 := optimal_GH_injl Y Z,
have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z,
let γ := glue_space hΦ hΨ,
letI : metric_space γ := metric.metric_space_glue_space hΦ hΨ,
have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) =
(to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) := to_glue_commute hΦ hΨ,
calc dist x z = dist (to_GH_space X) (to_GH_space Z) :
by rw [x.to_GH_space_rep, z.to_GH_space_rep]
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
GH_dist_le_Hausdorff_dist
((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y))
((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z))
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
+ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
begin
refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (range_nonempty _) _ _),
{ exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injl X Y)))).bounded },
{ exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injr X Y)))).bounded }
end
... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y)))
((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y)))
+ Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z)))
((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) :
by simp only [← range_comp, Comm, eq_self_iff_true, add_right_inj]
... = Hausdorff_dist (range (optimal_GH_injl X Y))
(range (optimal_GH_injr X Y))
+ Hausdorff_dist (range (optimal_GH_injl Y Z))
(range (optimal_GH_injr Y Z)) :
by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ),
Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)]
... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) :
by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist]
... = dist x y + dist y z:
by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep]
end }
end GH_space --section
end Gromov_Hausdorff
/-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this
in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/
definition topological_space.nonempty_compacts.to_GH_space {X : Type u} [metric_space X]
(p : nonempty_compacts X) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p
open topological_space
namespace Gromov_Hausdorff
section nonempty_compacts
variables {X : Type u} [metric_space X]
theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts X) :
dist p.to_GH_space q.to_GH_space ≤ dist p q :=
begin
have ha : isometry (coe : p → X) := isometry_subtype_coe,
have hb : isometry (coe : q → X) := isometry_subtype_coe,
have A : dist p q = Hausdorff_dist (p : set X) q := rfl,
have I : ↑p = range (coe : p → X) := subtype.range_coe_subtype.symm,
have J : ↑q = range (coe : q → X) := subtype.range_coe_subtype.symm,
rw [A, I, J],
exact GH_dist_le_Hausdorff_dist ha hb
end
lemma to_GH_space_lipschitz :
lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) :=
lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist
lemma to_GH_space_continuous :
continuous (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) :=
to_GH_space_lipschitz.continuous
end nonempty_compacts
section
/- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their
Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are
`ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff
distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. For this, we construct a suitable
coupling between the two spaces, by gluing them (approximately) along the two matching subsets. -/
variables {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y]
-- we want to ignore these instances in the following theorem
local attribute [instance, priority 10] sum.topological_space sum.uniform_space
/-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and
isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by
`ε₁ + ε₂/2 + ε₃`. -/
theorem GH_dist_le_of_approx_subsets {s : set X} (Φ : s → Y) {ε₁ ε₂ ε₃ : ℝ}
(hs : ∀ x : X, ∃ y ∈ s, dist x y ≤ ε₁) (hs' : ∀ x : Y, ∃ y : s, dist x (Φ y) ≤ ε₃)
(H : ∀ x y : s, |dist x y - dist (Φ x) (Φ y)| ≤ ε₂) :
GH_dist X Y ≤ ε₁ + ε₂ / 2 + ε₃ :=
begin
refine le_of_forall_pos_le_add (λ δ δ0, _),
rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
rcases hs xX with ⟨xs, hxs, Dxs⟩,
have sne : s.nonempty := ⟨xs, hxs⟩,
letI : nonempty s := sne.to_subtype,
have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩),
have : ∀ p q : s, |dist p q - dist (Φ p) (Φ q)| ≤ 2 * (ε₂/2 + δ) := λ p q, calc
|dist p q - dist (Φ p) (Φ q)| ≤ ε₂ : H p q
... ≤ 2 * (ε₂/2 + δ) : by linarith,
-- glue `X` and `Y` along the almost matching subsets
letI : metric_space (X ⊕ Y) :=
glue_metric_approx (λ x:s, (x:X)) (λ x, Φ x) (ε₂/2 + δ) (by linarith) this,
let Fl := @sum.inl X Y,
let Fr := @sum.inr X Y,
have Il : isometry Fl := isometry.of_dist_eq (λ x y, rfl),
have Ir : isometry Fr := isometry.of_dist_eq (λ x y, rfl),
/- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images
in the coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff
distances of `X` and `s` (in the coupling or, equivalently in the original space), of `s` and
`Φ s`, and of `Φ s` and `Y` (in the coupling or, equivalently, in the original space). The first
term is bounded by `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is
bounded by `ε₂/2` as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by
construction of the coupling (in fact `ε₂/2 + δ` where `δ` is an arbitrarily small positive
constant where positivity is used to ensure that the coupling is really a metric space and not a
premetric space on `X ⊕ Y`). -/
have : GH_dist X Y ≤ Hausdorff_dist (range Fl) (range Fr) :=
GH_dist_le_Hausdorff_dist Il Ir,
have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s)
+ Hausdorff_dist (Fl '' s) (range Fr),
{ have B : bounded (range Fl) := (is_compact_range Il.continuous).bounded,
exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (sne.image _) B (B.mono (image_subset_range _ _))) },
have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ))
+ Hausdorff_dist (Fr '' (range Φ)) (range Fr),
{ have B : bounded (range Fr) := (is_compact_range Ir.continuous).bounded,
exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded
((range_nonempty _).image _) (range_nonempty _)
(bounded.mono (image_subset_range _ _) B) B) },
have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁,
{ rw [← image_univ, Hausdorff_dist_image Il],
have : 0 ≤ ε₁ := le_trans dist_nonneg Dxs,
refine Hausdorff_dist_le_of_mem_dist this (λ x hx, hs x)
(λ x hx, ⟨x, mem_univ _, by simpa only [dist_self]⟩) },
have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε₂/2 + δ,
{ refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _,
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩,
rw ← xx',
use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)],
exact le_of_eq (glue_dist_glued_points (λ x:s, (x:X)) Φ (ε₂/2 + δ) ⟨x, x_in_s⟩) },
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩,
rcases mem_range.1 y_in_s' with ⟨x, xy⟩,
use [Fl x, mem_image_of_mem _ x.2],
rw [← yx', ← xy, dist_comm],
exact le_of_eq (glue_dist_glued_points (@subtype.val X s) Φ (ε₂/2 + δ) x) } },
have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃,
{ rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir],
rcases exists_mem_of_nonempty Y with ⟨xY, _⟩,
rcases hs' xY with ⟨xs', Dxs'⟩,
have : 0 ≤ ε₃ := le_trans dist_nonneg Dxs',
refine Hausdorff_dist_le_of_mem_dist this (λ x hx, ⟨x, mem_univ _, by simpa only [dist_self]⟩)
(λ x _, _),
rcases hs' x with ⟨y, Dy⟩,
exact ⟨Φ y, mem_range_self _, Dy⟩ },
linarith
end
end --section
/-- The Gromov-Hausdorff space is second countable. -/
instance : second_countable_topology GH_space :=
begin
refine second_countable_of_countable_discretization (λ δ δpos, _),
let ε := (2/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
have : ∀ p:GH_space, ∃ s : set p.rep, s.finite ∧ (univ ⊆ (⋃x∈s, ball x ε)) :=
λ p, by simpa only [subset_univ, exists_true_left]
using finite_cover_balls_of_compact is_compact_univ εpos,
-- for each `p`, `s p` is a finite `ε`-dense subset of `p` (or rather the metric space
-- `p.rep` representing `p`)
choose s hs using this,
have : ∀ p:GH_space, ∀ t:set p.rep, t.finite → ∃ n:ℕ, ∃ e:equiv t (fin n), true,
{ assume p t ht,
letI : fintype t := finite.fintype ht,
exact ⟨fintype.card t, fintype.equiv_fin t, trivial⟩ },
choose N e hne using this,
-- cardinality of the nice finite subset `s p` of `p.rep`, called `N p`
let N := λ p:GH_space, N p (s p) (hs p).1,
-- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p`
let E := λ p:GH_space, e p (s p) (hs p).1,
-- A function `F` associating to `p : GH_space` the data of all distances between points
-- in the `ε`-dense set `s p`.
let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) :=
λp, ⟨N p, λa b, ⌊ε⁻¹ * dist ((E p).symm a) ((E p).symm b)⌋⟩,
refine ⟨Σ n, fin n → fin n → ℤ, by apply_instance, F, λp q hpq, _⟩,
/- As the target space of F is countable, it suffices to show that two points
`p` and `q` with `F p = F q` are at distance `≤ δ`.
For this, we construct a map `Φ` from `s p ⊆ p.rep` (representing `p`)
to `q.rep` (representing `q`) which is almost an isometry on `s p`, and
with image `s q`. For this, we compose the identification of `s p` with `fin (N p)`
and the inverse of the identification of `s q` with `fin (N q)`. Together with
the fact that `N p = N q`, this constructs `Ψ` between `s p` and `s q`, and then
composing with the canonical inclusion we get `Φ`. -/
have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λ x, Ψ x,
-- Use the almost isometry `Φ` to show that `p.rep` and `q.rep`
-- are within controlled Gromov-Hausdorff distance.
have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε,
{ refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_of_lt hy⟩ },
show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
let i : ℕ := E q ⟨y, ys⟩,
let hi := ((E q) ⟨y, ys⟩).is_lt,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk],
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩,
{ rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y,
{ simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_of_lt hy },
show ∀ x y : s p, |dist x y - dist (Φ x) (Φ y)| ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i : ℕ := E p x,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)), by { simp only [equiv.apply_symm_apply, fin.coe_cast] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j : ℕ := E p y,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)).1,
{ simp only [equiv.apply_symm_apply, fin.val_eq_coe, fin.coe_cast] },
-- Express `dist x y` in terms of `F p`
have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y),
by simp only [F, (E p).symm_apply_apply],
have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y),
by { rw ← this, congr; apply fin.ext_iff.2; refl },
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have : (F q).2 ((E q) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by simp only [F, (E q).symm_apply_apply],
have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by { rw ← this, congr; apply fin.ext_iff.2; [exact i', exact j'] },
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
rw [Ap, Aq] at this,
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)| =
|ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))| : (abs_mul _ _).symm
... = |(ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))| : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
|dist x y - dist (Ψ x) (Ψ y)| = (ε * ε⁻¹) * |dist x y - dist (Ψ x) (Ψ y)| :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)|) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist p.rep (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ : by { simp only [ε], ring }
end
/-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have
a uniformly bounded diameter, and for all `ε` the number of balls of radius `ε` required
to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the
interesting direction that these conditions imply compactness. -/
lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ}
(ulim : tendsto u at_top (𝓝 0))
(hdiam : ∀ p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C)
(hcov : ∀ p ∈ t, ∀ n:ℕ, ∃ s : set (GH_space.rep p),
cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) :
totally_bounded t :=
begin
/- Let `δ>0`, and `ε = δ/5`. For each `p`, we construct a finite subset `s p` of `p`, which
is `ε`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`,
up to `ε`, we will get a map `F` associating to `p` finitely many data, and making it possible to
reconstruct `p` up to `ε`. This is enough to prove total boundedness. -/
refine metric.totally_bounded_of_finite_discretization (λ δ δpos, _),
let ε := (1/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
-- choose `n` for which `u n < ε`
rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩,
have u_le_ε : u n ≤ ε,
{ have := hn n le_rfl,
simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this,
exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) },
-- construct a finite subset `s p` of `p` which is `ε`-dense and has cardinal `≤ K n`
have : ∀ p:GH_space, ∃ s : set p.rep, ∃ N ≤ K n, ∃ E : equiv s (fin N),
p ∈ t → univ ⊆ ⋃x∈s, ball x (u n),
{ assume p,
by_cases hp : p ∉ t,
{ have : nonempty (equiv (∅ : set p.rep) (fin 0)),
{ rw ← fintype.card_eq, simp only [empty_card', fintype.card_fin] },
use [∅, 0, bot_le, choice (this)] },
{ rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩,
rcases cardinal.lt_aleph_0.1 (lt_of_le_of_lt scard (cardinal.nat_lt_aleph_0 _)) with ⟨N, hN⟩,
rw [hN, cardinal.nat_cast_le] at scard,
have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin],
cases quotient.exact this with E,
use [s, N, scard, E],
simp only [scover, implies_true_iff] } },
choose s N hN E hs using this,
-- Define a function `F` taking values in a finite type and associating to `p` enough data
-- to reconstruct it up to `ε`, namely the (discretized) distances between elements of `s p`.
let M := ⌊ε⁻¹ * max C 0⌋₊,
let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) :=
λ p, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩,
λ a b, ⟨min M ⌊ε⁻¹ * dist ((E p).symm a) ((E p).symm b)⌋₊,
( min_le_left _ _).trans_lt (nat.lt_succ_self _) ⟩ ⟩,
refine ⟨_, _, (λ p, F p), _⟩, apply_instance,
-- It remains to show that if `F p = F q`, then `p` and `q` are `ε`-close
rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq,
have Npq : N p = N q := fin.ext_iff.1 (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λ x, Ψ x,
have main : GH_dist p.rep (q.rep) ≤ ε + ε/2 + ε,
{ -- to prove the main inequality, argue that `s p` is `ε`-dense in `p`, and `s q` is `ε`-dense
-- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows
-- from `GH_dist_le_of_approx_subsets`
refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ },
show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
let i : ℕ := E q ⟨y, ys⟩,
let hi := ((E q) ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk],
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩,
by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_trans (le_of_lt hy) u_le_ε },
show ∀ x y : s p, |dist x y - dist (Φ x) (Φ y)| ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i : ℕ := E p x,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)), by { simp only [equiv.apply_symm_apply, fin.coe_cast] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j : ℕ := E p y,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)), by { simp only [equiv.apply_symm_apply, fin.coe_cast] },
-- Express `dist x y` in terms of `F p`
have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ⌊ε⁻¹ * dist x y⌋₊ := calc
((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 :
by { congr; apply fin.ext_iff.2; refl }
... = min M ⌊ε⁻¹ * dist x y⌋₊ :
by simp only [F, (E p).symm_apply_apply]
... = ⌊ε⁻¹ * dist x y⌋₊ :
begin
refine min_eq_right (nat.floor_mono _),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le),
change dist (x : p.rep) y ≤ C,
refine le_trans (dist_le_diam_of_mem is_compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam p pt
end,
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ := calc
((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ψ x)) ((E q) (Ψ y))).1 :
by { congr; apply fin.ext_iff.2; [exact i', exact j'] }
... = min M ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ :
by simp only [F, (E q).symm_apply_apply]
... = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ :
begin
refine min_eq_right (nat.floor_mono _),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le),
change dist (Ψ x : q.rep) (Ψ y) ≤ C,
refine le_trans (dist_le_diam_of_mem is_compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam q qt
end,
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
have : ⌊ε⁻¹ * dist x y⌋ = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋,
{ rw [Ap, Aq] at this,
have D : 0 ≤ ⌊ε⁻¹ * dist x y⌋ :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
have D' : 0 ≤ ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋ :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', int.floor_to_nat,int.floor_to_nat,
this] },
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)| =
|ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))| : (abs_mul _ _).symm
... = |(ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))| : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
|dist x y - dist (Ψ x) (Ψ y)| = (ε * ε⁻¹) * |dist x y - dist (Ψ x) (Ψ y)| :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)|) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist p.rep (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ/2 : by { simp only [ε, one_div], ring }
... < δ : half_lt_self δpos
end
section complete
/- We will show that a sequence `u n` of compact metric spaces satisfying
`dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space.
We need to exhibit the limiting compact metric space. For this, start from
a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)`
for all `n`, in a common metric space. Formally, this is done as follows.
Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space
`Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and
glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an
embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive
limit of the `Y n`, and finally let `Z` be the completion of `Z0`.
The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they
form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its
set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty
compact metric space we are looking for. -/
variables (X : ℕ → Type) [∀ n, metric_space (X n)] [∀ n, compact_space (X n)] [∀ n, nonempty (X n)]
/-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding
of a type `A` in another metric space. -/
structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 :=
(space : Type)
(metric : metric_space space)
(embed : A → space)
(isom : isometry embed)
instance (A : Type) [metric_space A] : inhabited (aux_gluing_struct A) :=
⟨{ space := A,
metric := by apply_instance,
embed := id,
isom := λ x y, rfl }⟩
/-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each
`X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space
at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/
def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n
{ space := X 0,
metric := by apply_instance,
embed := id,
isom := λ x y, rfl }
(λ n Y, by letI : metric_space Y.space := Y.metric; exact
{ space := glue_space Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))),
metric := by apply_instance,
embed := (to_glue_r Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))))
∘ (optimal_GH_injr (X n) (X (n+1))),
isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X (n+1))) })
/-- The Gromov-Hausdorff space is complete. -/
instance : complete_space GH_space :=
begin
have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply pow_pos, norm_num },
-- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other
refine metric.complete_of_convergent_controlled_sequences (λ n, (1/2)^n) this (λ u hu, _),
-- `X n` is a representative of `u n`
let X := λ n, (u n).rep,
-- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n`
let Y := aux_gluing X,
letI : ∀ n, metric_space (Y n).space := λ n, (Y n).metric,
have E : ∀ n : ℕ,
glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space :=
λ n, by { simp only [Y, aux_gluing], refl },
let c := λ n, cast (E n),
have ic : ∀ n, isometry (c n) := λ n x y, rfl,
-- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction
let f : Πn, (Y n).space → (Y n.succ).space :=
λ n, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))),
have I : ∀ n, isometry (f n),
{ assume n,
apply isometry.comp,
{ assume x y, refl },
{ apply to_glue_l_isometry } },
-- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z`
let Z0 := metric.inductive_limit I,
let Z := uniform_space.completion Z0,
let Φ := to_inductive_limit I,
let coeZ := (coe : Z0 → Z),
-- let `X2 n` be the image of `X n` in the space `Z`
let X2 := λ n, range (coeZ ∘ (Φ n) ∘ (Y n).embed),
have isom : ∀ n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed),
{ assume n,
refine uniform_space.completion.coe_isometry.comp _,
exact (to_inductive_limit_isometry _ _).comp (Y n).isom },
-- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between
-- `u n` and `u (n+1)`, therefore bounded by `1/2^n`
have D2 : ∀ n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n,
{ assume n,
have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injl (X n) (X n.succ))),
{ change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))
∘ (optimal_GH_injl (X n) (X n.succ))),
simp only [X2, Φ],
rw [← to_inductive_limit_commute I],
simp only [f],
rw ← to_glue_commute },
rw range_comp at X2n,
have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injr (X n) (X n.succ))), by refl,
rw range_comp at X2nsucc,
rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist],
{ exact hu n n n.succ (le_refl n) (le_succ n) },
{ apply uniform_space.completion.coe_isometry.comp _,
exact (to_inductive_limit_isometry _ _).comp ((ic n).comp (to_glue_r_isometry _ _)) } },
-- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which
-- is a metric space
let X3 : ℕ → nonempty_compacts Z := λ n,
⟨⟨X2 n, is_compact_range (isom n).continuous⟩, range_nonempty _⟩,
-- `X3 n` is a Cauchy sequence by construction, as the successive distances are
-- bounded by `(1/2)^n`
have : cauchy_seq X3,
{ refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λ n, _),
rw one_mul,
exact le_of_lt (D2 n) },
-- therefore, it converges to a limit `L`
rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩,
-- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L`
have M : tendsto (λ n, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) :=
tendsto.comp (to_GH_space_continuous.tendsto _) hL,
-- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`.
have : ∀ n, (X3 n).to_GH_space = u n,
{ assume n,
rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep,
to_GH_space_eq_to_GH_space_iff_isometric],
constructor,
convert (isom n).isometric_on_range.symm, },
-- Finally, we have proved the convergence of `u n`
exact ⟨L.to_GH_space, by simpa only [this] using M⟩
end
end complete--section
end Gromov_Hausdorff --namespace
|
8b8c793816f0a8cd36e298d2b868d8c2f1e4af58 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/order/conditionally_complete_lattice/group.lean | 2f95db0f42273fa845166fbf5975b5ad0dcab8cc | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 1,880 | lean | /-
Copyright (c) 2018 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 order.conditionally_complete_lattice.basic
import algebra.order.group.type_tags
/-!
# Conditionally complete lattices and groups.
-/
section group
variables {α : Type*} {ι : Sort*} {ι' : Sort*}
[nonempty ι] [nonempty ι'] [conditionally_complete_lattice α] [group α]
@[to_additive]
lemma le_mul_cinfi [covariant_class α α (*) (≤)] {a : α} {g : α} {h : ι → α}
(H : ∀ j, a ≤ g * h j) : a ≤ g * infi h :=
inv_mul_le_iff_le_mul.mp $ le_cinfi $ λ hi, inv_mul_le_iff_le_mul.mpr $ H _
@[to_additive]
lemma mul_csupr_le [covariant_class α α (*) (≤)] {a : α} {g : α} {h : ι → α}
(H : ∀ j, g * h j ≤ a) : g * supr h ≤ a :=
@le_mul_cinfi αᵒᵈ _ _ _ _ _ _ _ _ H
@[to_additive]
lemma le_cinfi_mul [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : α}
(H : ∀ i, a ≤ g i * h) : a ≤ infi g * h :=
mul_inv_le_iff_le_mul.mp $ le_cinfi $ λ gi, mul_inv_le_iff_le_mul.mpr $ H _
@[to_additive]
lemma csupr_mul_le [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : α}
(H : ∀ i, g i * h ≤ a) : supr g * h ≤ a :=
@le_cinfi_mul αᵒᵈ _ _ _ _ _ _ _ _ H
@[to_additive]
lemma le_cinfi_mul_cinfi [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)]
{a : α} {g : ι → α} {h : ι' → α} (H : ∀ i j, a ≤ g i * h j) : a ≤ infi g * infi h :=
le_cinfi_mul $ λ i, le_mul_cinfi $ H _
@[to_additive]
lemma csupr_mul_csupr_le [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)]
{a : α} {g : ι → α} {h : ι' → α} (H : ∀ i j, g i * h j ≤ a) : supr g * supr h ≤ a :=
csupr_mul_le $ λ i, mul_csupr_le $ H _
end group
|
e7146513567cd2e81dc0f2af33381f0adeb00859 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/linear_algebra/matrix/nonsingular_inverse.lean | 5cadefd13c9fed62ceb135fb65578ab137df6f12 | [
"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 | 26,164 | lean | /-
Copyright (c) 2019 Tim Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baanen, Lu-Ming Zhang
-/
import linear_algebra.matrix.adjugate
/-!
# Nonsingular inverses
In this file, we define an inverse for square matrices of invertible determinant.
For matrices that are not square or not of full rank, there is a more general notion of
pseudoinverses which we do not consider here.
The definition of inverse used in this file is the adjugate divided by the determinant.
We show that dividing the adjugate by `det A` (if possible), giving a matrix `A⁻¹` (`nonsing_inv`),
will result in a multiplicative inverse to `A`.
Note that there are at least three different inverses in mathlib:
* `A⁻¹` (`has_inv.inv`): alone, this satisfies no properties, although it is usually used in
conjunction with `group` or `group_with_zero`. On matrices, this is defined to be zero when no
inverse exists.
* `⅟A` (`inv_of`): this is only available in the presence of `[invertible A]`, which guarantees an
inverse exists.
* `ring.inverse A`: this is defined on any `monoid_with_zero`, and just like `⁻¹` on matrices, is
defined to be zero when no inverse exists.
We start by working with `invertible`, and show the main results:
* `matrix.invertible_of_det_invertible`
* `matrix.det_invertible_of_invertible`
* `matrix.is_unit_iff_is_unit_det`
* `matrix.mul_eq_one_comm`
After this we define `matrix.has_inv` and show it matches `⅟A` and `ring.inverse A`.
The rest of the results in the file are then about `A⁻¹`
## References
* https://en.wikipedia.org/wiki/Cramer's_rule#Finding_inverse_matrix
## Tags
matrix inverse, cramer, cramer's rule, adjugate
-/
namespace matrix
universes u u' v
variables {m : Type u} {n : Type u'} {α : Type v}
open_locale matrix big_operators
open equiv equiv.perm finset
/-! ### Matrices are `invertible` iff their determinants are -/
section invertible
variables [fintype n] [decidable_eq n] [comm_ring α]
/-- A copy of `inv_of_mul_self` using `⬝` not `*`. -/
protected lemma inv_of_mul_self (A : matrix n n α) [invertible A] : ⅟A ⬝ A = 1 := inv_of_mul_self A
/-- A copy of `mul_inv_of_self` using `⬝` not `*`. -/
protected lemma mul_inv_of_self (A : matrix n n α) [invertible A] : A ⬝ ⅟A = 1 := mul_inv_of_self A
/-- A copy of `inv_of_mul_self_assoc` using `⬝` not `*`. -/
protected lemma inv_of_mul_self_assoc (A : matrix n n α) (B : matrix n m α) [invertible A] :
⅟A ⬝ (A ⬝ B) = B :=
by rw [←matrix.mul_assoc, matrix.inv_of_mul_self, matrix.one_mul]
/-- A copy of `mul_inv_of_self_assoc` using `⬝` not `*`. -/
protected lemma mul_inv_of_self_assoc (A : matrix n n α) (B : matrix n m α) [invertible A] :
A ⬝ (⅟A ⬝ B) = B :=
by rw [←matrix.mul_assoc, matrix.mul_inv_of_self, matrix.one_mul]
/-- A copy of `mul_inv_of_mul_self_cancel` using `⬝` not `*`. -/
protected lemma mul_inv_of_mul_self_cancel (A : matrix m n α) (B : matrix n n α)
[invertible B] : A ⬝ ⅟B ⬝ B = A :=
by rw [matrix.mul_assoc, matrix.inv_of_mul_self, matrix.mul_one]
/-- A copy of `mul_mul_inv_of_self_cancel` using `⬝` not `*`. -/
protected lemma mul_mul_inv_of_self_cancel (A : matrix m n α) (B : matrix n n α)
[invertible B] : A ⬝ B ⬝ ⅟B = A :=
by rw [matrix.mul_assoc, matrix.mul_inv_of_self, matrix.mul_one]
variables (A : matrix n n α) (B : matrix n n α)
/-- If `A.det` has a constructive inverse, produce one for `A`. -/
def invertible_of_det_invertible [invertible A.det] : invertible A :=
{ inv_of := ⅟A.det • A.adjugate,
mul_inv_of_self :=
by rw [mul_smul_comm, matrix.mul_eq_mul, mul_adjugate, smul_smul, inv_of_mul_self, one_smul],
inv_of_mul_self :=
by rw [smul_mul_assoc, matrix.mul_eq_mul, adjugate_mul, smul_smul, inv_of_mul_self, one_smul] }
lemma inv_of_eq [invertible A.det] [invertible A] : ⅟A = ⅟A.det • A.adjugate :=
by { letI := invertible_of_det_invertible A, convert (rfl : ⅟A = _) }
/-- `A.det` is invertible if `A` has a left inverse. -/
def det_invertible_of_left_inverse (h : B ⬝ A = 1) : invertible A.det :=
{ inv_of := B.det,
mul_inv_of_self := by rw [mul_comm, ← det_mul, h, det_one],
inv_of_mul_self := by rw [← det_mul, h, det_one] }
/-- `A.det` is invertible if `A` has a right inverse. -/
def det_invertible_of_right_inverse (h : A ⬝ B = 1) : invertible A.det :=
{ inv_of := B.det,
mul_inv_of_self := by rw [← det_mul, h, det_one],
inv_of_mul_self := by rw [mul_comm, ← det_mul, h, det_one] }
/-- If `A` has a constructive inverse, produce one for `A.det`. -/
def det_invertible_of_invertible [invertible A] : invertible A.det :=
det_invertible_of_left_inverse A (⅟A) (inv_of_mul_self _)
lemma det_inv_of [invertible A] [invertible A.det] : (⅟A).det = ⅟A.det :=
by { letI := det_invertible_of_invertible A, convert (rfl : _ = ⅟A.det) }
/-- Together `matrix.det_invertible_of_invertible` and `matrix.invertible_of_det_invertible` form an
equivalence, although both sides of the equiv are subsingleton anyway. -/
@[simps]
def invertible_equiv_det_invertible : invertible A ≃ invertible A.det :=
{ to_fun := @det_invertible_of_invertible _ _ _ _ _ A,
inv_fun := @invertible_of_det_invertible _ _ _ _ _ A,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
variables {A B}
lemma mul_eq_one_comm : A ⬝ B = 1 ↔ B ⬝ A = 1 :=
suffices ∀ A B, A ⬝ B = 1 → B ⬝ A = 1, from ⟨this A B, this B A⟩, assume A B h,
begin
letI : invertible B.det := det_invertible_of_left_inverse _ _ h,
letI : invertible B := invertible_of_det_invertible B,
calc B ⬝ A = (B ⬝ A) ⬝ (B ⬝ ⅟B) : by rw [matrix.mul_inv_of_self, matrix.mul_one]
... = B ⬝ ((A ⬝ B) ⬝ ⅟B) : by simp only [matrix.mul_assoc]
... = B ⬝ ⅟B : by rw [h, matrix.one_mul]
... = 1 : matrix.mul_inv_of_self B,
end
variables (A B)
/-- We can construct an instance of invertible A if A has a left inverse. -/
def invertible_of_left_inverse (h : B ⬝ A = 1) : invertible A :=
⟨B, h, mul_eq_one_comm.mp h⟩
/-- We can construct an instance of invertible A if A has a right inverse. -/
def invertible_of_right_inverse (h : A ⬝ B = 1) : invertible A :=
⟨B, mul_eq_one_comm.mp h, h⟩
/-- The transpose of an invertible matrix is invertible. -/
instance invertible_transpose [invertible A] : invertible Aᵀ :=
begin
haveI : invertible Aᵀ.det,
by simpa using det_invertible_of_invertible A,
exact invertible_of_det_invertible Aᵀ
end
/-- A matrix is invertible if the transpose is invertible. -/
def invertible__of_invertible_transpose [invertible Aᵀ] : invertible A :=
begin
rw ←transpose_transpose A,
apply_instance
end
/-- A matrix is invertible if the conjugate transpose is invertible. -/
def invertible_of_invertible_conj_transpose [star_ring α] [invertible Aᴴ] :
invertible A :=
begin
rw ←conj_transpose_conj_transpose A,
apply_instance
end
/-- Given a proof that `A.det` has a constructive inverse, lift `A` to `(matrix n n α)ˣ`-/
def unit_of_det_invertible [invertible A.det] : (matrix n n α)ˣ :=
@unit_of_invertible _ _ A (invertible_of_det_invertible A)
/-- When lowered to a prop, `matrix.invertible_equiv_det_invertible` forms an `iff`. -/
lemma is_unit_iff_is_unit_det : is_unit A ↔ is_unit A.det :=
by simp only [← nonempty_invertible_iff_is_unit, (invertible_equiv_det_invertible A).nonempty_congr]
/-! #### Variants of the statements above with `is_unit`-/
lemma is_unit_det_of_invertible [invertible A] : is_unit A.det :=
@is_unit_of_invertible _ _ _ (det_invertible_of_invertible A)
variables {A B}
lemma is_unit_of_left_inverse (h : B ⬝ A = 1) : is_unit A :=
⟨⟨A, B, mul_eq_one_comm.mp h, h⟩, rfl⟩
lemma is_unit_of_right_inverse (h : A ⬝ B = 1) : is_unit A :=
⟨⟨A, B, h, mul_eq_one_comm.mp h⟩, rfl⟩
lemma is_unit_det_of_left_inverse (h : B ⬝ A = 1) : is_unit A.det :=
@is_unit_of_invertible _ _ _ (det_invertible_of_left_inverse _ _ h)
lemma is_unit_det_of_right_inverse (h : A ⬝ B = 1) : is_unit A.det :=
@is_unit_of_invertible _ _ _ (det_invertible_of_right_inverse _ _ h)
lemma det_ne_zero_of_left_inverse [nontrivial α] (h : B ⬝ A = 1) : A.det ≠ 0 :=
(is_unit_det_of_left_inverse h).ne_zero
lemma det_ne_zero_of_right_inverse [nontrivial α] (h : A ⬝ B = 1) : A.det ≠ 0 :=
(is_unit_det_of_right_inverse h).ne_zero
end invertible
variables [fintype n] [decidable_eq n] [comm_ring α]
variables (A : matrix n n α) (B : matrix n n α)
lemma is_unit_det_transpose (h : is_unit A.det) : is_unit Aᵀ.det :=
by { rw det_transpose, exact h, }
/-! ### A noncomputable `has_inv` instance -/
/-- The inverse of a square matrix, when it is invertible (and zero otherwise).-/
noncomputable instance : has_inv (matrix n n α) := ⟨λ A, ring.inverse A.det • A.adjugate⟩
lemma inv_def (A : matrix n n α) : A⁻¹ = ring.inverse A.det • A.adjugate := rfl
lemma nonsing_inv_apply_not_is_unit (h : ¬ is_unit A.det) :
A⁻¹ = 0 :=
by rw [inv_def, ring.inverse_non_unit _ h, zero_smul]
lemma nonsing_inv_apply (h : is_unit A.det) :
A⁻¹ = (↑h.unit⁻¹ : α) • A.adjugate :=
by rw [inv_def, ←ring.inverse_unit h.unit, is_unit.unit_spec]
/-- The nonsingular inverse is the same as `inv_of` when `A` is invertible. -/
@[simp] lemma inv_of_eq_nonsing_inv [invertible A] : ⅟A = A⁻¹ :=
begin
letI := det_invertible_of_invertible A,
rw [inv_def, ring.inverse_invertible, inv_of_eq],
end
/-- Coercing the result of `units.has_inv` is the same as coercing first and applying the
nonsingular inverse. -/
@[simp, norm_cast] lemma coe_units_inv (A : (matrix n n α)ˣ) :
↑(A⁻¹) = (A⁻¹ : matrix n n α) :=
begin
letI := A.invertible,
rw [←inv_of_eq_nonsing_inv, inv_of_units],
end
/-- The nonsingular inverse is the same as the general `ring.inverse`. -/
lemma nonsing_inv_eq_ring_inverse : A⁻¹ = ring.inverse A :=
begin
by_cases h_det : is_unit A.det,
{ casesI (A.is_unit_iff_is_unit_det.mpr h_det).nonempty_invertible,
rw [←inv_of_eq_nonsing_inv, ring.inverse_invertible], },
{ have h := mt A.is_unit_iff_is_unit_det.mp h_det,
rw [ring.inverse_non_unit _ h, nonsing_inv_apply_not_is_unit A h_det], },
end
lemma transpose_nonsing_inv : (A⁻¹)ᵀ = (Aᵀ)⁻¹ :=
by rw [inv_def, inv_def, transpose_smul, det_transpose, adjugate_transpose]
lemma conj_transpose_nonsing_inv [star_ring α] : (A⁻¹)ᴴ = (Aᴴ)⁻¹ :=
by rw [inv_def, inv_def, conj_transpose_smul, det_conj_transpose, adjugate_conj_transpose,
ring.inverse_star]
/-- The `nonsing_inv` of `A` is a right inverse. -/
@[simp] lemma mul_nonsing_inv (h : is_unit A.det) : A ⬝ A⁻¹ = 1 :=
begin
casesI (A.is_unit_iff_is_unit_det.mpr h).nonempty_invertible,
rw [←inv_of_eq_nonsing_inv, matrix.mul_inv_of_self],
end
/-- The `nonsing_inv` of `A` is a left inverse. -/
@[simp] lemma nonsing_inv_mul (h : is_unit A.det) : A⁻¹ ⬝ A = 1 :=
begin
casesI (A.is_unit_iff_is_unit_det.mpr h).nonempty_invertible,
rw [←inv_of_eq_nonsing_inv, matrix.inv_of_mul_self],
end
instance [invertible A] : invertible A⁻¹ :=
by { rw ← inv_of_eq_nonsing_inv, apply_instance }
@[simp] lemma inv_inv_of_invertible [invertible A] : A⁻¹⁻¹ = A :=
by simp only [← inv_of_eq_nonsing_inv, inv_of_inv_of]
@[simp] lemma mul_nonsing_inv_cancel_right (B : matrix m n α) (h : is_unit A.det) :
B ⬝ A ⬝ A⁻¹ = B :=
by simp [matrix.mul_assoc, mul_nonsing_inv A h]
@[simp] lemma mul_nonsing_inv_cancel_left (B : matrix n m α) (h : is_unit A.det) :
A ⬝ (A⁻¹ ⬝ B) = B :=
by simp [←matrix.mul_assoc, mul_nonsing_inv A h]
@[simp] lemma nonsing_inv_mul_cancel_right (B : matrix m n α) (h : is_unit A.det) :
B ⬝ A⁻¹ ⬝ A = B :=
by simp [matrix.mul_assoc, nonsing_inv_mul A h]
@[simp] lemma nonsing_inv_mul_cancel_left (B : matrix n m α) (h : is_unit A.det) :
A⁻¹ ⬝ (A ⬝ B) = B :=
by simp [←matrix.mul_assoc, nonsing_inv_mul A h]
@[simp] lemma mul_inv_of_invertible [invertible A] : A ⬝ A⁻¹ = 1 :=
mul_nonsing_inv A (is_unit_det_of_invertible A)
@[simp] lemma inv_mul_of_invertible [invertible A] : A⁻¹ ⬝ A = 1 :=
nonsing_inv_mul A (is_unit_det_of_invertible A)
@[simp] lemma mul_inv_cancel_right_of_invertible (B : matrix m n α) [invertible A] :
B ⬝ A ⬝ A⁻¹ = B :=
mul_nonsing_inv_cancel_right A B (is_unit_det_of_invertible A)
@[simp] lemma mul_inv_cancel_left_of_invertible (B : matrix n m α) [invertible A] :
A ⬝ (A⁻¹ ⬝ B) = B :=
mul_nonsing_inv_cancel_left A B (is_unit_det_of_invertible A)
@[simp] lemma inv_mul_cancel_right_of_invertible (B : matrix m n α) [invertible A] :
B ⬝ A⁻¹ ⬝ A = B :=
nonsing_inv_mul_cancel_right A B (is_unit_det_of_invertible A)
@[simp] lemma inv_mul_cancel_left_of_invertible (B : matrix n m α) [invertible A] :
A⁻¹ ⬝ (A ⬝ B) = B :=
nonsing_inv_mul_cancel_left A B (is_unit_det_of_invertible A)
lemma inv_mul_eq_iff_eq_mul_of_invertible (A B C : matrix n n α) [invertible A] :
A⁻¹ ⬝ B = C ↔ B = A ⬝ C :=
⟨λ h, by rw [←h, mul_inv_cancel_left_of_invertible],
λ h, by rw [h, inv_mul_cancel_left_of_invertible]⟩
lemma mul_inv_eq_iff_eq_mul_of_invertible (A B C : matrix n n α) [invertible A] :
B ⬝ A⁻¹ = C ↔ B = C ⬝ A :=
⟨λ h, by rw [←h, inv_mul_cancel_right_of_invertible],
λ h, by rw [h, mul_inv_cancel_right_of_invertible]⟩
lemma nonsing_inv_cancel_or_zero :
(A⁻¹ ⬝ A = 1 ∧ A ⬝ A⁻¹ = 1) ∨ A⁻¹ = 0 :=
begin
by_cases h : is_unit A.det,
{ exact or.inl ⟨nonsing_inv_mul _ h, mul_nonsing_inv _ h⟩ },
{ exact or.inr (nonsing_inv_apply_not_is_unit _ h) }
end
lemma det_nonsing_inv_mul_det (h : is_unit A.det) : A⁻¹.det * A.det = 1 :=
by rw [←det_mul, A.nonsing_inv_mul h, det_one]
@[simp] lemma det_nonsing_inv : A⁻¹.det = ring.inverse A.det :=
begin
by_cases h : is_unit A.det,
{ casesI h.nonempty_invertible, letI := invertible_of_det_invertible A,
rw [ring.inverse_invertible, ←inv_of_eq_nonsing_inv, det_inv_of] },
casesI is_empty_or_nonempty n,
{ rw [det_is_empty, det_is_empty, ring.inverse_one] },
{ rw [ring.inverse_non_unit _ h, nonsing_inv_apply_not_is_unit _ h, det_zero ‹_›] },
end
lemma is_unit_nonsing_inv_det (h : is_unit A.det) : is_unit A⁻¹.det :=
is_unit_of_mul_eq_one _ _ (A.det_nonsing_inv_mul_det h)
@[simp] lemma nonsing_inv_nonsing_inv (h : is_unit A.det) : (A⁻¹)⁻¹ = A :=
calc (A⁻¹)⁻¹ = 1 ⬝ (A⁻¹)⁻¹ : by rw matrix.one_mul
... = A ⬝ A⁻¹ ⬝ (A⁻¹)⁻¹ : by rw A.mul_nonsing_inv h
... = A : by { rw [matrix.mul_assoc,
(A⁻¹).mul_nonsing_inv (A.is_unit_nonsing_inv_det h),
matrix.mul_one], }
lemma is_unit_nonsing_inv_det_iff {A : matrix n n α} :
is_unit A⁻¹.det ↔ is_unit A.det :=
by rw [matrix.det_nonsing_inv, is_unit_ring_inverse]
/- `is_unit.invertible` lifts the proposition `is_unit A` to a constructive inverse of `A`. -/
/-- A version of `matrix.invertible_of_det_invertible` with the inverse defeq to `A⁻¹` that is
therefore noncomputable. -/
noncomputable def invertible_of_is_unit_det (h : is_unit A.det) : invertible A :=
⟨A⁻¹, nonsing_inv_mul A h, mul_nonsing_inv A h⟩
/-- A version of `matrix.units_of_det_invertible` with the inverse defeq to `A⁻¹` that is therefore
noncomputable. -/
noncomputable def nonsing_inv_unit (h : is_unit A.det) : (matrix n n α)ˣ :=
@unit_of_invertible _ _ _ (invertible_of_is_unit_det A h)
lemma unit_of_det_invertible_eq_nonsing_inv_unit [invertible A.det] :
unit_of_det_invertible A = nonsing_inv_unit A (is_unit_of_invertible _) :=
by { ext, refl }
variables {A} {B}
/-- If matrix A is left invertible, then its inverse equals its left inverse. -/
lemma inv_eq_left_inv (h : B ⬝ A = 1) : A⁻¹ = B :=
begin
letI := invertible_of_left_inverse _ _ h,
exact inv_of_eq_nonsing_inv A ▸ inv_of_eq_left_inv h,
end
/-- If matrix A is right invertible, then its inverse equals its right inverse. -/
lemma inv_eq_right_inv (h : A ⬝ B = 1) : A⁻¹ = B :=
inv_eq_left_inv (mul_eq_one_comm.2 h)
section inv_eq_inv
variables {C : matrix n n α}
/-- The left inverse of matrix A is unique when existing. -/
lemma left_inv_eq_left_inv (h : B ⬝ A = 1) (g : C ⬝ A = 1) : B = C :=
by rw [←inv_eq_left_inv h, ←inv_eq_left_inv g]
/-- The right inverse of matrix A is unique when existing. -/
lemma right_inv_eq_right_inv (h : A ⬝ B = 1) (g : A ⬝ C = 1) : B = C :=
by rw [←inv_eq_right_inv h, ←inv_eq_right_inv g]
/-- The right inverse of matrix A equals the left inverse of A when they exist. -/
lemma right_inv_eq_left_inv (h : A ⬝ B = 1) (g : C ⬝ A = 1) : B = C :=
by rw [←inv_eq_right_inv h, ←inv_eq_left_inv g]
lemma inv_inj (h : A⁻¹ = B⁻¹) (h' : is_unit A.det) : A = B :=
begin
refine left_inv_eq_left_inv (mul_nonsing_inv _ h') _,
rw h,
refine mul_nonsing_inv _ _,
rwa [←is_unit_nonsing_inv_det_iff, ←h, is_unit_nonsing_inv_det_iff]
end
end inv_eq_inv
variable (A)
@[simp] lemma inv_zero : (0 : matrix n n α)⁻¹ = 0 :=
begin
casesI (subsingleton_or_nontrivial α) with ht ht,
{ simp },
cases (fintype.card n).zero_le.eq_or_lt with hc hc,
{ rw [eq_comm, fintype.card_eq_zero_iff] at hc,
haveI := hc,
ext i,
exact (is_empty.false i).elim },
{ have hn : nonempty n := fintype.card_pos_iff.mp hc,
refine nonsing_inv_apply_not_is_unit _ _,
simp [hn] },
end
noncomputable instance : inv_one_class (matrix n n α) :=
{ inv_one := inv_eq_left_inv (by simp),
..matrix.has_one,
..matrix.has_inv }
lemma inv_smul (k : α) [invertible k] (h : is_unit A.det) : (k • A)⁻¹ = ⅟k • A⁻¹ :=
inv_eq_left_inv (by simp [h, smul_smul])
lemma inv_smul' (k : αˣ) (h : is_unit A.det) : (k • A)⁻¹ = k⁻¹ • A⁻¹ :=
inv_eq_left_inv (by simp [h, smul_smul])
lemma inv_adjugate (A : matrix n n α) (h : is_unit A.det) :
(adjugate A)⁻¹ = h.unit⁻¹ • A :=
begin
refine inv_eq_left_inv _,
rw [smul_mul, mul_adjugate, units.smul_def, smul_smul, h.coe_inv_mul, one_smul]
end
/-- `diagonal v` is invertible if `v` is -/
def diagonal_invertible {α} [non_assoc_semiring α] (v : n → α) [invertible v] :
invertible (diagonal v) :=
invertible.map (diagonal_ring_hom n α) v
lemma inv_of_diagonal_eq {α} [semiring α] (v : n → α) [invertible v] [invertible (diagonal v)] :
⅟(diagonal v) = diagonal (⅟v) :=
by { letI := diagonal_invertible v, convert (rfl : ⅟(diagonal v) = _) }
/-- `v` is invertible if `diagonal v` is -/
def invertible_of_diagonal_invertible (v : n → α) [invertible (diagonal v)] : invertible v :=
{ inv_of := diag (⅟(diagonal v)),
inv_of_mul_self := funext $ λ i, begin
letI : invertible (diagonal v).det := det_invertible_of_invertible _,
rw [inv_of_eq, diag_smul, adjugate_diagonal, diag_diagonal],
dsimp,
rw [mul_assoc, prod_erase_mul _ _ (finset.mem_univ _), ←det_diagonal],
exact mul_inv_of_self _,
end,
mul_inv_of_self := funext $ λ i, begin
letI : invertible (diagonal v).det := det_invertible_of_invertible _,
rw [inv_of_eq, diag_smul, adjugate_diagonal, diag_diagonal],
dsimp,
rw [mul_left_comm, mul_prod_erase _ _ (finset.mem_univ _), ←det_diagonal],
exact mul_inv_of_self _,
end }
/-- Together `matrix.diagonal_invertible` and `matrix.invertible_of_diagonal_invertible` form an
equivalence, although both sides of the equiv are subsingleton anyway. -/
@[simps]
def diagonal_invertible_equiv_invertible (v : n → α) : invertible (diagonal v) ≃ invertible v :=
{ to_fun := @invertible_of_diagonal_invertible _ _ _ _ _ _,
inv_fun := @diagonal_invertible _ _ _ _ _ _,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
/-- When lowered to a prop, `matrix.diagonal_invertible_equiv_invertible` forms an `iff`. -/
@[simp] lemma is_unit_diagonal {v : n → α} : is_unit (diagonal v) ↔ is_unit v :=
by simp only [← nonempty_invertible_iff_is_unit,
(diagonal_invertible_equiv_invertible v).nonempty_congr]
lemma inv_diagonal (v : n → α) : (diagonal v)⁻¹ = diagonal (ring.inverse v) :=
begin
rw nonsing_inv_eq_ring_inverse,
by_cases h : is_unit v,
{ have := is_unit_diagonal.mpr h,
casesI this.nonempty_invertible,
casesI h.nonempty_invertible,
rw [ring.inverse_invertible, ring.inverse_invertible, inv_of_diagonal_eq], },
{ have := is_unit_diagonal.not.mpr h,
rw [ring.inverse_non_unit _ h, pi.zero_def, diagonal_zero, ring.inverse_non_unit _ this] }
end
@[simp] lemma inv_inv_inv (A : matrix n n α) : A⁻¹⁻¹⁻¹ = A⁻¹ :=
begin
by_cases h : is_unit A.det,
{ rw [nonsing_inv_nonsing_inv _ h] },
{ simp [nonsing_inv_apply_not_is_unit _ h] }
end
lemma mul_inv_rev (A B : matrix n n α) : (A ⬝ B)⁻¹ = B⁻¹ ⬝ A⁻¹ :=
begin
simp only [inv_def],
rw [matrix.smul_mul, matrix.mul_smul, smul_smul, det_mul, adjugate_mul_distrib,
ring.mul_inverse_rev],
end
/-- A version of `list.prod_inv_reverse` for `matrix.has_inv`. -/
lemma list_prod_inv_reverse : ∀ l : list (matrix n n α), l.prod⁻¹ = (l.reverse.map has_inv.inv).prod
| [] := by rw [list.reverse_nil, list.map_nil, list.prod_nil, inv_one]
| (A :: Xs) := by rw [list.reverse_cons', list.map_concat, list.prod_concat, list.prod_cons,
matrix.mul_eq_mul, matrix.mul_eq_mul, mul_inv_rev, list_prod_inv_reverse]
/-- One form of **Cramer's rule**. See `matrix.mul_vec_cramer` for a stronger form. -/
@[simp] lemma det_smul_inv_mul_vec_eq_cramer (A : matrix n n α) (b : n → α) (h : is_unit A.det) :
A.det • A⁻¹.mul_vec b = cramer A b :=
begin
rw [cramer_eq_adjugate_mul_vec, A.nonsing_inv_apply h, ← smul_mul_vec_assoc,
smul_smul, h.mul_coe_inv, one_smul]
end
/-- One form of **Cramer's rule**. See `matrix.mul_vec_cramer` for a stronger form. -/
@[simp] lemma det_smul_inv_vec_mul_eq_cramer_transpose
(A : matrix n n α) (b : n → α) (h : is_unit A.det) :
A.det • A⁻¹.vec_mul b = cramer Aᵀ b :=
by rw [← (A⁻¹).transpose_transpose, vec_mul_transpose, transpose_nonsing_inv, ← det_transpose,
Aᵀ.det_smul_inv_mul_vec_eq_cramer _ (is_unit_det_transpose A h)]
/-! ### More results about determinants -/
section det
variables [fintype m] [decidable_eq m]
/-- A variant of `matrix.det_units_conj`. -/
lemma det_conj {M : matrix m m α} (h : is_unit M) (N : matrix m m α) :
det (M ⬝ N ⬝ M⁻¹) = det N :=
by rw [←h.unit_spec, ←coe_units_inv, det_units_conj]
/-- A variant of `matrix.det_units_conj'`. -/
lemma det_conj' {M : matrix m m α} (h : is_unit M) (N : matrix m m α) :
det (M⁻¹ ⬝ N ⬝ M) = det N :=
by rw [←h.unit_spec, ←coe_units_inv, det_units_conj']
/-- Determinant of a 2×2 block matrix, expanded around an invertible top left element in terms of
the Schur complement. -/
lemma det_from_blocks₁₁ (A : matrix m m α) (B : matrix m n α) (C : matrix n m α) (D : matrix n n α)
[invertible A] : (matrix.from_blocks A B C D).det = det A * det (D - C ⬝ (⅟A) ⬝ B) :=
begin
have : from_blocks A B C D =
from_blocks 1 0 (C ⬝ ⅟A) 1 ⬝ from_blocks A 0 0 (D - C ⬝ (⅟A) ⬝ B) ⬝ from_blocks 1 (⅟A ⬝ B) 0 1,
{ simp only [from_blocks_multiply, matrix.mul_zero, matrix.zero_mul, add_zero, zero_add,
matrix.one_mul, matrix.mul_one, matrix.inv_of_mul_self, matrix.mul_inv_of_self_assoc,
matrix.mul_inv_of_mul_self_cancel, matrix.mul_assoc, add_sub_cancel'_right] },
rw [this, det_mul, det_mul, det_from_blocks_zero₂₁, det_from_blocks_zero₂₁,
det_from_blocks_zero₁₂, det_one, det_one, one_mul, one_mul, mul_one],
end
@[simp] lemma det_from_blocks_one₁₁ (B : matrix m n α) (C : matrix n m α) (D : matrix n n α) :
(matrix.from_blocks 1 B C D).det = det (D - C ⬝ B) :=
begin
haveI : invertible (1 : matrix m m α) := invertible_one,
rw [det_from_blocks₁₁, inv_of_one, matrix.mul_one, det_one, one_mul],
end
/-- Determinant of a 2×2 block matrix, expanded around an invertible bottom right element in terms
of the Schur complement. -/
lemma det_from_blocks₂₂ (A : matrix m m α) (B : matrix m n α) (C : matrix n m α) (D : matrix n n α)
[invertible D] : (matrix.from_blocks A B C D).det = det D * det (A - B ⬝ (⅟D) ⬝ C) :=
begin
have : from_blocks A B C D = (from_blocks D C B A).submatrix (sum_comm _ _) (sum_comm _ _),
{ ext i j,
cases i; cases j; refl },
rw [this, det_submatrix_equiv_self, det_from_blocks₁₁],
end
@[simp] lemma det_from_blocks_one₂₂ (A : matrix m m α) (B : matrix m n α) (C : matrix n m α) :
(matrix.from_blocks A B C 1).det = det (A - B ⬝ C) :=
begin
haveI : invertible (1 : matrix n n α) := invertible_one,
rw [det_from_blocks₂₂, inv_of_one, matrix.mul_one, det_one, one_mul],
end
/-- The **Weinstein–Aronszajn identity**. Note the `1` on the LHS is of shape m×m, while the `1` on
the RHS is of shape n×n. -/
lemma det_one_add_mul_comm (A : matrix m n α) (B : matrix n m α) :
det (1 + A ⬝ B) = det (1 + B ⬝ A) :=
calc det (1 + A ⬝ B)
= det (from_blocks 1 (-A) B 1) : by rw [det_from_blocks_one₂₂, matrix.neg_mul, sub_neg_eq_add]
... = det (1 + B ⬝ A) : by rw [det_from_blocks_one₁₁, matrix.mul_neg, sub_neg_eq_add]
/-- Alternate statement of the **Weinstein–Aronszajn identity** -/
lemma det_mul_add_one_comm (A : matrix m n α) (B : matrix n m α) :
det (A ⬝ B + 1) = det (B ⬝ A + 1) :=
by rw [add_comm, det_one_add_mul_comm, add_comm]
lemma det_one_sub_mul_comm (A : matrix m n α) (B : matrix n m α) :
det (1 - A ⬝ B) = det (1 - B ⬝ A) :=
by rw [sub_eq_add_neg, ←matrix.neg_mul, det_one_add_mul_comm, matrix.mul_neg, ←sub_eq_add_neg]
/-- A special case of the **Matrix determinant lemma** for when `A = I`.
TODO: show this more generally. -/
lemma det_one_add_col_mul_row (u v : m → α) : det (1 + col u ⬝ row v) = 1 + v ⬝ᵥ u :=
by rw [det_one_add_mul_comm, det_unique, pi.add_apply, pi.add_apply, matrix.one_apply_eq,
matrix.row_mul_col_apply]
end det
end matrix
|
31102148f0636dad608ce139db583ad1fe507c62 | 92b50235facfbc08dfe7f334827d47281471333b | /library/algebra/ordered_field.lean | eef06d60e9b0da5eed36c316f9d3de772cdefc90 | [
"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 | 17,553 | lean | /-
Copyright (c) 2014 Robert Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Lewis
-/
import algebra.ordered_ring algebra.field
open eq eq.ops
namespace algebra
structure linear_ordered_field [class] (A : Type) extends linear_ordered_ring A, field A
section linear_ordered_field
variable {A : Type}
variables [s : linear_ordered_field A] {a b c d : A}
include s
-- helpers for following
theorem mul_zero_lt_mul_inv_of_pos (H : 0 < a) : a * 0 < a * (1 / a) :=
calc
a * 0 = 0 : mul_zero
... < 1 : zero_lt_one
... = a * a⁻¹ : mul_inv_cancel (ne.symm (ne_of_lt H))
... = a * (1 / a) : inv_eq_one_div
theorem mul_zero_lt_mul_inv_of_neg (H : a < 0) : a * 0 < a * (1 / a) :=
calc
a * 0 = 0 : mul_zero
... < 1 : zero_lt_one
... = a * a⁻¹ : mul_inv_cancel (ne_of_lt H)
... = a * (1 / a) : inv_eq_one_div
theorem div_pos_of_pos (H : 0 < a) : 0 < 1 / a :=
lt_of_mul_lt_mul_left (mul_zero_lt_mul_inv_of_pos H) (le_of_lt H)
theorem div_neg_of_neg (H : a < 0) : 1 / a < 0 :=
gt_of_mul_lt_mul_neg_left (mul_zero_lt_mul_inv_of_neg H) (le_of_lt H)
theorem le_mul_of_ge_one_right (Hb : b ≥ 0) (H : a ≥ 1) : b ≤ b * a :=
mul_one _ ▸ (mul_le_mul_of_nonneg_left H Hb)
theorem lt_mul_of_gt_one_right (Hb : b > 0) (H : a > 1) : b < b * a :=
mul_one _ ▸ (mul_lt_mul_of_pos_left H Hb)
theorem one_le_div_iff_le (Hb : b > 0) : 1 ≤ a / b ↔ b ≤ a :=
have Hb' : b ≠ 0, from ne.symm (ne_of_lt Hb),
iff.intro
(assume H : 1 ≤ a / b,
calc
b = b : refl
... ≤ b * (a / b) : le_mul_of_ge_one_right (le_of_lt Hb) H
... = a : mul_div_cancel' Hb')
(assume H : b ≤ a,
have Hbinv : 1 / b > 0, from div_pos_of_pos Hb, calc
1 = b * (1 / b) : mul_one_div_cancel Hb'
... ≤ a * (1 / b) : mul_le_mul_of_nonneg_right H (le_of_lt Hbinv)
... = a / b : div_eq_mul_one_div)
theorem le_of_one_le_div (Hb : b > 0) (H : 1 ≤ a / b) : b ≤ a :=
(iff.mp (one_le_div_iff_le Hb)) H
theorem one_le_div_of_le (Hb : b > 0) (H : b ≤ a) : 1 ≤ a / b :=
(iff.mp' (one_le_div_iff_le Hb)) H
theorem one_lt_div_iff_lt (Hb : b > 0) : 1 < a / b ↔ b < a :=
have Hb' : b ≠ 0, from ne.symm (ne_of_lt Hb),
iff.intro
(assume H : 1 < a / b,
calc
b < b * (a / b) : lt_mul_of_gt_one_right Hb H
... = a : mul_div_cancel' Hb')
(assume H : b < a,
have Hbinv : 1 / b > 0, from div_pos_of_pos Hb, calc
1 = b * (1 / b) : mul_one_div_cancel Hb'
... < a * (1 / b) : mul_lt_mul_of_pos_right H Hbinv
... = a / b : div_eq_mul_one_div)
theorem lt_of_one_lt_div (Hb : b > 0) (H : 1 < a / b) : b < a :=
(iff.mp (one_lt_div_iff_lt Hb)) H
theorem one_lt_div_of_lt (Hb : b > 0) (H : b < a) : 1 < a / b :=
(iff.mp' (one_lt_div_iff_lt Hb)) H
theorem exists_lt : ∃ x, x < a :=
have H : a - 1 < a, from add_lt_of_le_of_neg (le.refl _) zero_gt_neg_one,
exists.intro _ H
theorem exists_gt : ∃ x, x > a :=
have H : a + 1 > a, from lt_add_of_le_of_pos (le.refl _) zero_lt_one,
exists.intro _ H
-- the following theorems amount to four iffs, for <, ≤, ≥, >.
theorem mul_le_of_le_div (Hc : 0 < c) (H : a ≤ b / c) : a * c ≤ b :=
div_mul_cancel (ne.symm (ne_of_lt Hc)) ▸ mul_le_mul_of_nonneg_right H (le_of_lt Hc)
theorem le_div_of_mul_le (Hc : 0 < c) (H : a * c ≤ b) : a ≤ b / c :=
calc
a = a * c * (1 / c) : mul_mul_div (ne.symm (ne_of_lt Hc))
... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right H (le_of_lt (div_pos_of_pos Hc))
... = b / c : div_eq_mul_one_div
theorem mul_lt_of_lt_div (Hc : 0 < c) (H : a < b / c) : a * c < b :=
div_mul_cancel (ne.symm (ne_of_lt Hc)) ▸ mul_lt_mul_of_pos_right H Hc
theorem lt_div_of_mul_lt (Hc : 0 < c) (H : a * c < b) : a < b / c :=
calc
a = a * c * (1 / c) : mul_mul_div (ne.symm (ne_of_lt Hc))
... < b * (1 / c) : mul_lt_mul_of_pos_right H (div_pos_of_pos Hc)
... = b / c : div_eq_mul_one_div
theorem mul_le_of_ge_div_neg (Hc : c < 0) (H : a ≥ b / c) : a * c ≤ b :=
div_mul_cancel (ne_of_lt Hc) ▸ mul_le_mul_of_nonpos_right H (le_of_lt Hc)
theorem ge_div_of_mul_le_neg (Hc : c < 0) (H : a * c ≤ b) : a ≥ b / c :=
calc
a = a * c * (1 / c) : mul_mul_div (ne_of_lt Hc)
... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right H (le_of_lt (div_neg_of_neg Hc))
... = b / c : div_eq_mul_one_div
theorem mul_lt_of_gt_div_neg (Hc : c < 0) (H : a > b / c) : a * c < b :=
div_mul_cancel (ne_of_lt Hc) ▸ mul_lt_mul_of_neg_right H Hc
theorem gt_div_of_mul_gt_neg (Hc : c < 0) (H : a * c < b) : a > b / c :=
calc
a = a * c * (1 / c) : mul_mul_div (ne_of_lt Hc)
... > b * (1 / c) : mul_lt_mul_of_neg_right H (div_neg_of_neg Hc)
... = b / c : div_eq_mul_one_div
-----
theorem div_le_of_le_mul (Hb : b > 0) (H : a ≤ b * c) : a / b ≤ c :=
calc
a / b = a * (1 / b) : div_eq_mul_one_div
... ≤ (b * c) * (1 / b) : mul_le_mul_of_nonneg_right H (le_of_lt (div_pos_of_pos Hb))
... = (b * c) / b : div_eq_mul_one_div
... = c : mul_div_cancel_left (ne.symm (ne_of_lt Hb))
theorem le_mul_of_div_le (Hc : c > 0) (H : a / c ≤ b) : a ≤ b * c :=
calc
a = a / c * c : div_mul_cancel (ne.symm (ne_of_lt Hc))
... ≤ b * c : mul_le_mul_of_nonneg_right H (le_of_lt Hc)
-- following these in the isabelle file, there are 8 biconditionals for the above with - signs
-- skipping for now
theorem mul_sub_mul_div_mul_neg (Hc : c ≠ 0) (Hd : d ≠ 0) (H : a / c < b / d) :
(a * d - b * c) / (c * d) < 0 :=
have H1 : a / c - b / d < 0, from calc
a / c - b / d < b / d - b / d : sub_lt_sub_right H
... = 0 : sub_self,
calc
0 > a / c - b / d : H1
... = (a * d - c * b) / (c * d) : div_sub_div Hc Hd
... = (a * d - b * c) / (c * d) : mul.comm
theorem mul_sub_mul_div_mul_nonpos (Hc : c ≠ 0) (Hd : d ≠ 0) (H : a / c ≤ b / d) :
(a * d - b * c) / (c * d) ≤ 0 :=
have H1 : a / c - b / d ≤ 0, from calc
a / c - b / d ≤ b / d - b / d : sub_le_sub_right H
... = 0 : sub_self,
calc
0 ≥ a / c - b / d : H1
... = (a * d - c * b) / (c * d) : div_sub_div Hc Hd
... = (a * d - b * c) / (c * d) : mul.comm
theorem div_lt_div_of_mul_sub_mul_div_neg (Hc : c ≠ 0) (Hd : d ≠ 0)
(H : (a * d - b * c) / (c * d) < 0) : a / c < b / d :=
assert H1 : (a * d - c * b) / (c * d) < 0, by rewrite [mul.comm c b]; exact H,
assert H2 : a / c - b / d < 0, by rewrite [div_sub_div Hc Hd]; exact H1,
assert H3 : a / c - b / d + b / d < 0 + b / d, from add_lt_add_right H2 _,
begin rewrite [zero_add at H3, neg_add_cancel_right at H3], exact H3 end
theorem div_le_div_of_mul_sub_mul_div_nonpos (Hc : c ≠ 0) (Hd : d ≠ 0)
(H : (a * d - b * c) / (c * d) ≤ 0) : a / c ≤ b / d :=
assert H1 : (a * d - c * b) / (c * d) ≤ 0, by rewrite [mul.comm c b]; exact H,
assert H2 : a / c - b / d ≤ 0, by rewrite [div_sub_div Hc Hd]; exact H1,
assert H3 : a / c - b / d + b / d ≤ 0 + b / d, from add_le_add_right H2 _,
begin rewrite [zero_add at H3, neg_add_cancel_right at H3], exact H3 end
theorem pos_div_of_pos_of_pos (Ha : 0 < a) (Hb : 0 < b) : 0 < a / b :=
begin
rewrite div_eq_mul_one_div,
apply mul_pos,
exact Ha,
apply div_pos_of_pos,
exact Hb
end
theorem nonneg_div_of_nonneg_of_pos (Ha : 0 ≤ a) (Hb : 0 < b) : 0 ≤ a / b :=
begin
rewrite div_eq_mul_one_div,
apply mul_nonneg,
exact Ha,
apply le_of_lt,
apply div_pos_of_pos,
exact Hb
end
theorem neg_div_of_neg_of_pos (Ha : a < 0) (Hb : 0 < b) : a / b < 0:=
begin
rewrite div_eq_mul_one_div,
apply mul_neg_of_neg_of_pos,
exact Ha,
apply div_pos_of_pos,
exact Hb
end
theorem nonpos_div_of_nonpos_of_pos (Ha : a ≤ 0) (Hb : 0 < b) : a / b ≤ 0 :=
begin
rewrite div_eq_mul_one_div,
apply mul_nonpos_of_nonpos_of_nonneg,
exact Ha,
apply le_of_lt,
apply div_pos_of_pos,
exact Hb
end
theorem neg_div_of_pos_of_neg (Ha : 0 < a) (Hb : b < 0) : a / b < 0 :=
begin
rewrite div_eq_mul_one_div,
apply mul_neg_of_pos_of_neg,
exact Ha,
apply div_neg_of_neg,
exact Hb
end
theorem nonpos_div_of_nonneg_of_neg (Ha : 0 ≤ a) (Hb : b < 0) : a / b ≤ 0 :=
begin
rewrite div_eq_mul_one_div,
apply mul_nonpos_of_nonneg_of_nonpos,
exact Ha,
apply le_of_lt,
apply div_neg_of_neg,
exact Hb
end
theorem pos_div_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a / b :=
begin
rewrite div_eq_mul_one_div,
apply mul_pos_of_neg_of_neg,
exact Ha,
apply div_neg_of_neg,
exact Hb
end
theorem nonneg_div_of_nonpos_of_neg (Ha : a ≤ 0) (Hb : b < 0) : 0 ≤ a / b :=
begin
rewrite div_eq_mul_one_div,
apply mul_nonneg_of_nonpos_of_nonpos,
exact Ha,
apply le_of_lt,
apply div_neg_of_neg,
exact Hb
end
theorem div_lt_div_of_lt_of_pos (H : a < b) (Hc : 0 < c) : a / c < b / c :=
begin
rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div],
exact mul_lt_mul_of_pos_right H (div_pos_of_pos Hc)
end
theorem div_lt_div_of_lt_of_neg (H : b < a) (Hc : c < 0) : a / c < b / c :=
begin
rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div],
exact mul_lt_mul_of_neg_right H (div_neg_of_neg Hc)
end
theorem two_ne_zero : (1 : A) + 1 ≠ 0 :=
ne.symm (ne_of_lt (add_pos zero_lt_one zero_lt_one))
notation 2 := 1 + 1
theorem add_halves : a / 2 + a / 2 = a :=
calc
a / 2 + a / 2 = (a + a) / 2 : by rewrite div_add_div_same
... = (a * 1 + a * 1) / 2 : by rewrite mul_one
... = (a * 2) / 2 : by rewrite left_distrib
... = a : by rewrite [@mul_div_cancel A _ _ _ two_ne_zero]
theorem nonneg_le_nonneg_of_squares_le (Ha : a ≥ 0) (Hb : b ≥ 0) (H : a * a ≤ b * b) : a ≤ b :=
begin
apply le_of_not_gt,
intro Hab,
let Hposa := lt_of_le_of_lt Hb Hab,
let H' := calc
b * b ≤ a * b : mul_le_mul_of_nonneg_right (le_of_lt Hab) Hb
... < a * a : mul_lt_mul_of_pos_left Hab Hposa,
apply (not_le_of_gt H') H
end
theorem div_two : (a + a) / 2 = a :=
symm (iff.mp' (eq_div_iff_mul_eq (ne_of_gt (add_pos zero_lt_one zero_lt_one)))
(by rewrite [left_distrib, *mul_one]))
theorem mul_le_mul_of_mul_div_le (H : a * (b / c) ≤ d) (Hc : c > 0) : b * a ≤ d * c :=
begin
rewrite [-mul_div_assoc at H, mul.comm b],
apply le_mul_of_div_le Hc H
end
end linear_ordered_field
structure discrete_linear_ordered_field [class] (A : Type) extends linear_ordered_field A,
decidable_linear_ordered_comm_ring A :=
(inv_zero : inv zero = zero)
section discrete_linear_ordered_field
variable {A : Type}
variables [s : discrete_linear_ordered_field A] {a b c : A}
include s
theorem dec_eq_of_dec_lt : ∀ x y : A, decidable (x = y) :=
take x y,
decidable.by_cases
(assume H : x < y, decidable.inr (ne_of_lt H))
(assume H : ¬ x < y,
decidable.by_cases
(assume H' : y < x, decidable.inr (ne.symm (ne_of_lt H')))
(assume H' : ¬ y < x,
decidable.inl (le.antisymm (le_of_not_gt H') (le_of_not_gt H))))
definition discrete_linear_ordered_field.to_discrete_field [trans-instance] [reducible] [coercion]
: discrete_field A :=
⦃ discrete_field, s, has_decidable_eq := dec_eq_of_dec_lt⦄
theorem pos_of_div_pos (H : 0 < 1 / a) : 0 < a :=
have H1 : 0 < 1 / (1 / a), from div_pos_of_pos H,
have H2 : 1 / a ≠ 0, from
(assume H3 : 1 / a = 0,
have H4 : 1 / (1 / a) = 0, from H3⁻¹ ▸ div_zero,
absurd H4 (ne.symm (ne_of_lt H1))),
(div_div (ne_zero_of_one_div_ne_zero H2)) ▸ H1
theorem neg_of_div_neg (H : 1 / a < 0) : a < 0 :=
have H1 : 0 < - (1 / a), from neg_pos_of_neg H,
have Ha : a ≠ 0, from ne_zero_of_one_div_ne_zero (ne_of_lt H),
have H2 : 0 < 1 / (-a), from (one_div_neg_eq_neg_one_div Ha)⁻¹ ▸ H1,
have H3 : 0 < -a, from pos_of_div_pos H2,
neg_of_neg_pos H3
-- why is mul_le_mul under ordered_ring namespace?
theorem le_of_div_le (H : 0 < a) (Hl : 1 / a ≤ 1 / b) : b ≤ a :=
have Hb : 0 < b, from pos_of_div_pos (calc
0 < 1 / a : div_pos_of_pos H
... ≤ 1 / b : Hl),
have H' : 1 ≤ a / b, from (calc
1 = a / a : div_self (ne.symm (ne_of_lt H))
... = a * (1 / a) : div_eq_mul_one_div
... ≤ a * (1 / b) : ordered_ring.mul_le_mul_of_nonneg_left Hl (le_of_lt H)
... = a / b : div_eq_mul_one_div
), le_of_one_le_div Hb H'
theorem le_of_div_le_neg (H : b < 0) (Hl : 1 / a ≤ 1 / b) : b ≤ a :=
assert Ha : a ≠ 0, from ne_of_lt (neg_of_div_neg (calc
1 / a ≤ 1 / b : Hl
... < 0 : div_neg_of_neg H)),
have H' : -b > 0, from neg_pos_of_neg H,
have Hl' : - (1 / b) ≤ - (1 / a), from neg_le_neg Hl,
have Hl'' : 1 / - b ≤ 1 / - a, from calc
1 / -b = - (1 / b) : by rewrite [one_div_neg_eq_neg_one_div (ne_of_lt H)]
... ≤ - (1 / a) : Hl'
... = 1 / -a : by rewrite [one_div_neg_eq_neg_one_div Ha],
le_of_neg_le_neg (le_of_div_le H' Hl'')
theorem lt_of_div_lt (H : 0 < a) (Hl : 1 / a < 1 / b) : b < a :=
have Hb : 0 < b, from pos_of_div_pos (calc
0 < 1 / a : div_pos_of_pos H
... < 1 / b : Hl),
have H : 1 < a / b, from (calc
1 = a / a : div_self (ne.symm (ne_of_lt H))
... = a * (1 / a) : div_eq_mul_one_div
... < a * (1 / b) : mul_lt_mul_of_pos_left Hl H
... = a / b : div_eq_mul_one_div),
lt_of_one_lt_div Hb H
theorem lt_of_div_lt_neg (H : b < 0) (Hl : 1 / a < 1 / b) : b < a :=
have H1 : b ≤ a, from le_of_div_le_neg H (le_of_lt Hl),
have Hn : b ≠ a, from
(assume Hn' : b = a,
have Hl' : 1 / a = 1 / b, from Hn' ▸ refl _,
absurd Hl' (ne_of_lt Hl)),
lt_of_le_of_ne H1 Hn
theorem div_lt_div_of_lt (Ha : 0 < a) (H : a < b) : 1 / b < 1 / a :=
lt_of_not_ge
(assume H',
absurd H (not_lt_of_ge (le_of_div_le Ha H')))
theorem div_le_div_of_le (Ha : 0 < a) (H : a ≤ b) : 1 / b ≤ 1 / a :=
le_of_not_gt
(assume H',
absurd H (not_le_of_gt (lt_of_div_lt Ha H')))
theorem div_lt_div_of_lt_neg (Hb : b < 0) (H : a < b) : 1 / b < 1 / a :=
lt_of_not_ge
(assume H',
absurd H (not_lt_of_ge (le_of_div_le_neg Hb H')))
theorem div_le_div_of_le_neg (Hb : b < 0) (H : a ≤ b) : 1 / b ≤ 1 / a :=
le_of_not_gt
(assume H',
absurd H (not_le_of_gt (lt_of_div_lt_neg Hb H')))
theorem one_lt_div (H1 : 0 < a) (H2 : a < 1) : 1 < 1 / a :=
one_div_one ▸ div_lt_div_of_lt H1 H2
theorem one_le_div (H1 : 0 < a) (H2 : a ≤ 1) : 1 ≤ 1 / a :=
one_div_one ▸ div_le_div_of_le H1 H2
theorem neg_one_lt_div_neg (H1 : a < 0) (H2 : -1 < a) : 1 / a < -1 :=
one_div_neg_one_eq_neg_one ▸ div_lt_div_of_lt_neg H1 H2
theorem neg_one_le_div_neg (H1 : a < 0) (H2 : -1 ≤ a) : 1 / a ≤ -1 :=
one_div_neg_one_eq_neg_one ▸ div_le_div_of_le_neg H1 H2
theorem div_lt_div_of_pos_of_lt_of_pos (Hb : 0 < b) (H : b < a) (Hc : 0 < c) : c / a < c / b :=
begin
apply iff.mp (sub_neg_iff_lt _ _),
rewrite [div_eq_mul_one_div, {c / b}div_eq_mul_one_div],
rewrite -mul_sub_left_distrib,
apply mul_neg_of_pos_of_neg,
exact Hc,
apply iff.mp' (sub_neg_iff_lt _ _),
apply div_lt_div_of_lt,
exact Hb, exact H
end
theorem abs_one_div : abs (1 / a) = 1 / abs a :=
if H : a > 0 then
by rewrite [abs_of_pos H, abs_of_pos (div_pos_of_pos H)]
else
(if H' : a < 0 then
by rewrite [abs_of_neg H', abs_of_neg (div_neg_of_neg H'),
-(one_div_neg_eq_neg_one_div (ne_of_lt H'))]
else
have Heq [visible] : a = 0, from eq_of_le_of_ge (le_of_not_gt H) (le_of_not_gt H'),
by rewrite [Heq, div_zero, *abs_zero, div_zero])
theorem ge_sub_of_abs_sub_le_left (H : abs (a - b) ≤ c) : a ≥ b - c :=
if Hz : 0 ≤ a - b then
(calc
a ≥ b : (iff.mp !sub_nonneg_iff_le) Hz
... ≥ b - c : sub_le_of_nonneg _ _ (le.trans !abs_nonneg H))
else
(have Habs : b - a ≤ c, by rewrite [abs_of_neg (lt_of_not_ge Hz) at H, neg_sub at H]; apply H,
have Habs' : b ≤ c + a, from (iff.mp' !le_add_iff_sub_right_le) Habs,
(iff.mp !le_add_iff_sub_left_le) Habs')
theorem ge_sub_of_abs_sub_le_right (H : abs (a - b) ≤ c) : b ≥ a - c :=
ge_sub_of_abs_sub_le_left (!abs_sub ▸ H)
theorem abs_sub_square : abs (a - b) * abs (a - b) = a * a + b * b - 2 * a * b :=
by rewrite [abs_mul_self, *mul_sub_left_distrib, *mul_sub_right_distrib,
sub_add_eq_sub_sub, sub_neg_eq_add, *right_distrib, sub_add_eq_sub_sub, *one_mul,
*add.assoc, {_ + b * b}add.comm, {_ + (b * b + _)}add.comm, mul.comm b a, *add.assoc]
end discrete_linear_ordered_field
end algebra
|
6dcd17afef2fbeb097b170382262148e27d77480 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/data/list/rotate.lean | 0c3af5d7beeada449e5cf2bcd4533d27fc4dea11 | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 21,670 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Yakov Pechersky
-/
import data.list.perm
import data.list.range
/-!
# List rotation
This file proves basic results about `list.rotate`, the list rotation.
## Main declarations
* `is_rotated l₁ l₂`: States that `l₁` is a rotated version of `l₂`.
* `cyclic_permutations l`: The list of all cyclic permutants of `l`, up to the length of `l`.
## Tags
rotated, rotation, permutation, cycle
-/
universe u
variables {α : Type u}
open nat
namespace list
lemma rotate_mod (l : list α) (n : ℕ) : l.rotate (n % l.length) = l.rotate n :=
by simp [rotate]
@[simp] lemma rotate_nil (n : ℕ) : ([] : list α).rotate n = [] := by cases n; simp [rotate]
@[simp] lemma rotate_zero (l : list α) : l.rotate 0 = l := by simp [rotate]
@[simp] lemma rotate'_nil (n : ℕ) : ([] : list α).rotate' n = [] := by cases n; refl
@[simp] lemma rotate'_zero (l : list α) : l.rotate' 0 = l := by cases l; refl
lemma rotate'_cons_succ (l : list α) (a : α) (n : ℕ) :
(a :: l : list α).rotate' n.succ = (l ++ [a]).rotate' n := by simp [rotate']
@[simp] lemma length_rotate' : ∀ (l : list α) (n : ℕ), (l.rotate' n).length = l.length
| [] n := rfl
| (a::l) 0 := rfl
| (a::l) (n+1) := by rw [list.rotate', length_rotate' (l ++ [a]) n]; simp
lemma rotate'_eq_drop_append_take : ∀ {l : list α} {n : ℕ}, n ≤ l.length →
l.rotate' n = l.drop n ++ l.take n
| [] n h := by simp [drop_append_of_le_length h]
| l 0 h := by simp [take_append_of_le_length h]
| (a::l) (n+1) h :=
have hnl : n ≤ l.length, from le_of_succ_le_succ h,
have hnl' : n ≤ (l ++ [a]).length,
by rw [length_append, length_cons, list.length, zero_add];
exact (le_of_succ_le h),
by rw [rotate'_cons_succ, rotate'_eq_drop_append_take hnl', drop, take,
drop_append_of_le_length hnl, take_append_of_le_length hnl];
simp
lemma rotate'_rotate' : ∀ (l : list α) (n m : ℕ), (l.rotate' n).rotate' m = l.rotate' (n + m)
| (a::l) 0 m := by simp
| [] n m := by simp
| (a::l) (n+1) m := by rw [rotate'_cons_succ, rotate'_rotate', add_right_comm, rotate'_cons_succ]
@[simp] lemma rotate'_length (l : list α) : rotate' l l.length = l :=
by rw rotate'_eq_drop_append_take (le_refl _); simp
@[simp] lemma rotate'_length_mul (l : list α) : ∀ n : ℕ, l.rotate' (l.length * n) = l
| 0 := by simp
| (n+1) :=
calc l.rotate' (l.length * (n + 1)) =
(l.rotate' (l.length * n)).rotate' (l.rotate' (l.length * n)).length :
by simp [-rotate'_length, nat.mul_succ, rotate'_rotate']
... = l : by rw [rotate'_length, rotate'_length_mul]
lemma rotate'_mod (l : list α) (n : ℕ) : l.rotate' (n % l.length) = l.rotate' n :=
calc l.rotate' (n % l.length) = (l.rotate' (n % l.length)).rotate'
((l.rotate' (n % l.length)).length * (n / l.length)) : by rw rotate'_length_mul
... = l.rotate' n : by rw [rotate'_rotate', length_rotate', nat.mod_add_div]
lemma rotate_eq_rotate' (l : list α) (n : ℕ) : l.rotate n = l.rotate' n :=
if h : l.length = 0 then by simp [length_eq_zero, *] at *
else by
rw [← rotate'_mod, rotate'_eq_drop_append_take (le_of_lt (nat.mod_lt _ (nat.pos_of_ne_zero h)))];
simp [rotate]
lemma rotate_cons_succ (l : list α) (a : α) (n : ℕ) :
(a :: l : list α).rotate n.succ = (l ++ [a]).rotate n :=
by rw [rotate_eq_rotate', rotate_eq_rotate', rotate'_cons_succ]
@[simp] lemma mem_rotate : ∀ {l : list α} {a : α} {n : ℕ}, a ∈ l.rotate n ↔ a ∈ l
| [] _ n := by simp
| (a::l) _ 0 := by simp
| (a::l) _ (n+1) := by simp [rotate_cons_succ, mem_rotate, or.comm]
@[simp] lemma length_rotate (l : list α) (n : ℕ) : (l.rotate n).length = l.length :=
by rw [rotate_eq_rotate', length_rotate']
lemma rotate_eq_drop_append_take {l : list α} {n : ℕ} : n ≤ l.length →
l.rotate n = l.drop n ++ l.take n :=
by rw rotate_eq_rotate'; exact rotate'_eq_drop_append_take
lemma rotate_eq_drop_append_take_mod {l : list α} {n : ℕ} :
l.rotate n = l.drop (n % l.length) ++ l.take (n % l.length) :=
begin
cases l.length.zero_le.eq_or_lt with hl hl,
{ simp [eq_nil_of_length_eq_zero hl.symm ] },
rw [←rotate_eq_drop_append_take (n.mod_lt hl).le, rotate_mod]
end
@[simp] lemma rotate_append_length_eq (l l' : list α) : (l ++ l').rotate l.length = l' ++ l :=
begin
rw rotate_eq_rotate',
induction l generalizing l',
{ simp, },
{ simp [rotate', l_ih] },
end
lemma rotate_rotate (l : list α) (n m : ℕ) : (l.rotate n).rotate m = l.rotate (n + m) :=
by rw [rotate_eq_rotate', rotate_eq_rotate', rotate_eq_rotate', rotate'_rotate']
@[simp] lemma rotate_length (l : list α) : rotate l l.length = l :=
by rw [rotate_eq_rotate', rotate'_length]
@[simp] lemma rotate_length_mul (l : list α) (n : ℕ) : l.rotate (l.length * n) = l :=
by rw [rotate_eq_rotate', rotate'_length_mul]
lemma prod_rotate_eq_one_of_prod_eq_one [group α] : ∀ {l : list α} (hl : l.prod = 1) (n : ℕ),
(l.rotate n).prod = 1
| [] _ _ := by simp
| (a::l) hl n :=
have n % list.length (a :: l) ≤ list.length (a :: l), from le_of_lt (nat.mod_lt _ dec_trivial),
by rw ← list.take_append_drop (n % list.length (a :: l)) (a :: l) at hl;
rw [← rotate_mod, rotate_eq_drop_append_take this, list.prod_append, mul_eq_one_iff_inv_eq,
← one_mul (list.prod _)⁻¹, ← hl, list.prod_append, mul_assoc, mul_inv_self, mul_one]
lemma rotate_perm (l : list α) (n : ℕ) : l.rotate n ~ l :=
begin
rw rotate_eq_rotate',
induction n with n hn generalizing l,
{ simp },
{ cases l with hd tl,
{ simp },
{ rw rotate'_cons_succ,
exact (hn _).trans (perm_append_singleton _ _) } }
end
@[simp] lemma nodup_rotate {l : list α} {n : ℕ} : nodup (l.rotate n) ↔ nodup l :=
(rotate_perm l n).nodup_iff
@[simp] lemma rotate_eq_nil_iff {l : list α} {n : ℕ} : l.rotate n = [] ↔ l = [] :=
begin
induction n with n hn generalizing l,
{ simp },
{ cases l with hd tl,
{ simp },
{ simp [rotate_cons_succ, hn] } }
end
@[simp] lemma nil_eq_rotate_iff {l : list α} {n : ℕ} : [] = l.rotate n ↔ [] = l :=
by rw [eq_comm, rotate_eq_nil_iff, eq_comm]
@[simp] lemma rotate_singleton (x : α) (n : ℕ) :
[x].rotate n = [x] :=
begin
induction n with n hn,
{ simp },
{ rwa [rotate_cons_succ] }
end
@[simp] lemma rotate_eq_singleton_iff {l : list α} {n : ℕ} {x : α} : l.rotate n = [x] ↔ l = [x] :=
begin
induction n with n hn generalizing l,
{ simp },
{ cases l with hd tl,
{ simp },
{ simp [rotate_cons_succ, hn, append_eq_cons_iff, and_comm] } }
end
@[simp] lemma singleton_eq_rotate_iff {l : list α} {n : ℕ} {x : α} : [x] = l.rotate n ↔ [x] = l :=
by rw [eq_comm, rotate_eq_singleton_iff, eq_comm]
lemma zip_with_rotate_distrib {α β γ : Type*} (f : α → β → γ) (l : list α) (l' : list β) (n : ℕ)
(h : l.length = l'.length) :
(zip_with f l l').rotate n = zip_with f (l.rotate n) (l'.rotate n) :=
begin
rw [rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod,
rotate_eq_drop_append_take_mod, h, zip_with_append, ←zip_with_distrib_drop,
←zip_with_distrib_take, list.length_zip_with, h, min_self],
rw [length_drop, length_drop, h]
end
local attribute [simp] rotate_cons_succ
@[simp] lemma zip_with_rotate_one {β : Type*} (f : α → α → β) (x y : α) (l : list α) :
zip_with f (x :: y :: l) ((x :: y :: l).rotate 1) =
f x y :: zip_with f (y :: l) (l ++ [x]) :=
by simp
lemma nth_le_rotate_one (l : list α) (k : ℕ) (hk : k < (l.rotate 1).length) :
(l.rotate 1).nth_le k hk = l.nth_le ((k + 1) % l.length)
(mod_lt _ (length_rotate l 1 ▸ k.zero_le.trans_lt hk)) :=
begin
cases l with hd tl,
{ simp },
{ have : k ≤ tl.length,
{ refine nat.le_of_lt_succ _,
simpa using hk },
rcases this.eq_or_lt with rfl|hk',
{ simp [nth_le_append_right (le_refl _)] },
{ simpa [nth_le_append _ hk', length_cons, nat.mod_eq_of_lt (nat.succ_lt_succ hk')] } }
end
lemma nth_le_rotate (l : list α) (n k : ℕ) (hk : k < (l.rotate n).length) :
(l.rotate n).nth_le k hk = l.nth_le ((k + n) % l.length)
(mod_lt _ (length_rotate l n ▸ k.zero_le.trans_lt hk)) :=
begin
induction n with n hn generalizing l k,
{ have hk' : k < l.length := by simpa using hk,
simp [nat.mod_eq_of_lt hk'] },
{ simp [nat.succ_eq_add_one, ←rotate_rotate, nth_le_rotate_one, hn l, add_comm, add_left_comm] }
end
/-- A variant of `nth_le_rotate` useful for rewrites. -/
lemma nth_le_rotate' (l : list α) (n k : ℕ) (hk : k < l.length) :
(l.rotate n).nth_le ((l.length - n % l.length + k) % l.length)
((nat.mod_lt _ (k.zero_le.trans_lt hk)).trans_le (length_rotate _ _).ge) = l.nth_le k hk :=
begin
rw nth_le_rotate,
congr,
set m := l.length,
rw [mod_add_mod, add_assoc, add_left_comm, add_comm, add_mod, add_mod _ n],
cases (n % m).zero_le.eq_or_lt with hn hn,
{ simpa [←hn] using nat.mod_eq_of_lt hk },
{ have mpos : 0 < m := k.zero_le.trans_lt hk,
have hm : m - n % m < m := sub_lt_self' mpos hn,
have hn' : n % m < m := nat.mod_lt _ mpos,
simpa [mod_eq_of_lt hm, nat.sub_add_cancel hn'.le] using nat.mod_eq_of_lt hk }
end
lemma rotate_injective (n : ℕ) : function.injective (λ l : list α, l.rotate n) :=
begin
rintros l l' (h : l.rotate n = l'.rotate n),
have hle : l.length = l'.length := (l.length_rotate n).symm.trans (h.symm ▸ l'.length_rotate n),
rw [rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod] at h,
obtain ⟨hd, ht⟩ := append_inj h _,
{ rw [←take_append_drop _ l, ht, hd, take_append_drop] },
{ rw [length_drop, length_drop, hle] }
end
-- possibly easier to find in doc-gen, otherwise not that useful.
lemma rotate_eq_rotate {l l' : list α} {n : ℕ} :
l.rotate n = l'.rotate n ↔ l = l' :=
(rotate_injective n).eq_iff
lemma rotate_eq_iff {l l' : list α} {n : ℕ} :
l.rotate n = l' ↔ l = l'.rotate (l'.length - n % l'.length) :=
begin
rw [←@rotate_eq_rotate _ l _ n, rotate_rotate, ←rotate_mod l', add_mod],
cases l'.length.zero_le.eq_or_lt with hl hl,
{ rw [eq_nil_of_length_eq_zero hl.symm, rotate_nil, rotate_eq_nil_iff] },
{ cases (nat.zero_le (n % l'.length)).eq_or_lt with hn hn,
{ simp [←hn] },
{ rw [mod_eq_of_lt (sub_lt_self' hl hn), nat.sub_add_cancel, mod_self, rotate_zero],
exact (nat.mod_lt _ hl).le } }
end
lemma reverse_rotate (l : list α) (n : ℕ) :
(l.rotate n).reverse = l.reverse.rotate (l.length - (n % l.length)) :=
begin
rw [←length_reverse l, ←rotate_eq_iff],
induction n with n hn generalizing l,
{ simp },
{ cases l with hd tl,
{ simp },
{ rw [rotate_cons_succ, nat.succ_eq_add_one, ←rotate_rotate, hn],
simp } }
end
lemma rotate_reverse (l : list α) (n : ℕ) :
l.reverse.rotate n = (l.rotate (l.length - (n % l.length))).reverse :=
begin
rw [←reverse_reverse l],
simp_rw [reverse_rotate, reverse_reverse, rotate_eq_iff, rotate_rotate, length_rotate,
length_reverse],
rw [←length_reverse l],
set k := n % l.reverse.length with hk,
cases hk' : k with k',
{ simp [-length_reverse, ←rotate_rotate] },
{ cases l with x l,
{ simp },
{ have : k'.succ < (x :: l).length,
{ simp [←hk', hk, nat.mod_lt] },
rw [nat.mod_eq_of_lt, nat.sub_add_cancel, rotate_length],
{ exact sub_le_self' },
{ exact sub_lt_self' (by simp) nat.succ_pos' } } }
end
lemma map_rotate {β : Type*} (f : α → β) (l : list α) (n : ℕ) :
map f (l.rotate n) = (map f l).rotate n :=
begin
induction n with n hn IH generalizing l,
{ simp },
{ cases l with hd tl,
{ simp },
{ simp [hn] } }
end
theorem nodup.rotate_eq_self_iff {l : list α} (hl : l.nodup) {n : ℕ} :
l.rotate n = l ↔ n % l.length = 0 ∨ l = [] :=
begin
split,
{ intro h,
cases l.length.zero_le.eq_or_lt with hl' hl',
{ simp [←length_eq_zero, ←hl'] },
left,
rw nodup_iff_nth_le_inj at hl,
refine hl _ _ (mod_lt _ hl') hl' _,
rw ←nth_le_rotate' _ n,
simp_rw [h, nat.sub_add_cancel (mod_lt _ hl').le, mod_self] },
{ rintro (h|h),
{ rw [←rotate_mod, h],
exact rotate_zero l },
{ simp [h] } }
end
lemma nodup.rotate_congr {l : list α} (hl : l.nodup) (hn : l ≠ []) (i j : ℕ)
(h : l.rotate i = l.rotate j) : i % l.length = j % l.length :=
begin
have hi : i % l.length < l.length := mod_lt _ (length_pos_of_ne_nil hn),
have hj : j % l.length < l.length := mod_lt _ (length_pos_of_ne_nil hn),
refine (nodup_iff_nth_le_inj.mp hl) _ _ hi hj _,
rw [←nth_le_rotate' l i, ←nth_le_rotate' l j],
simp [nat.sub_add_cancel, hi.le, hj.le, h]
end
section is_rotated
variables (l l' : list α)
/-- `is_rotated l₁ l₂` or `l₁ ~r l₂` asserts that `l₁` and `l₂` are cyclic permutations
of each other. This is defined by claiming that `∃ n, l.rotate n = l'`. -/
def is_rotated : Prop := ∃ n, l.rotate n = l'
infixr ` ~r `:1000 := is_rotated
variables {l l'}
@[refl] lemma is_rotated.refl (l : list α) : l ~r l :=
⟨0, by simp⟩
@[symm] lemma is_rotated.symm (h : l ~r l') : l' ~r l :=
begin
obtain ⟨n, rfl⟩ := h,
cases l with hd tl,
{ simp },
{ use (hd :: tl).length * n - n,
rw [rotate_rotate, add_sub_cancel_of_le, rotate_length_mul],
exact nat.le_mul_of_pos_left (by simp) }
end
lemma is_rotated_comm : l ~r l' ↔ l' ~r l :=
⟨is_rotated.symm, is_rotated.symm⟩
@[simp] protected lemma is_rotated.forall (l : list α) (n : ℕ) : l.rotate n ~r l :=
is_rotated.symm ⟨n, rfl⟩
@[trans] lemma is_rotated.trans {l'' : list α} (h : l ~r l') (h' : l' ~r l'') :
l ~r l'' :=
begin
obtain ⟨n, rfl⟩ := h,
obtain ⟨m, rfl⟩ := h',
rw rotate_rotate,
use (n + m)
end
lemma is_rotated.eqv : equivalence (@is_rotated α) :=
mk_equivalence _ is_rotated.refl (λ _ _, is_rotated.symm) (λ _ _ _, is_rotated.trans)
/-- The relation `list.is_rotated l l'` forms a `setoid` of cycles. -/
def is_rotated.setoid (α : Type*) : setoid (list α) :=
{ r := is_rotated, iseqv := is_rotated.eqv }
lemma is_rotated.perm (h : l ~r l') : l ~ l' :=
exists.elim h (λ _ hl, hl ▸ (rotate_perm _ _).symm)
lemma is_rotated.nodup_iff (h : l ~r l') : nodup l ↔ nodup l' :=
h.perm.nodup_iff
lemma is_rotated.mem_iff (h : l ~r l') {a : α} : a ∈ l ↔ a ∈ l' :=
h.perm.mem_iff
@[simp] lemma is_rotated_nil_iff : l ~r [] ↔ l = [] :=
⟨λ ⟨n, hn⟩, by simpa using hn, λ h, h ▸ by refl⟩
@[simp] lemma is_rotated_nil_iff' : [] ~r l ↔ [] = l :=
by rw [is_rotated_comm, is_rotated_nil_iff, eq_comm]
@[simp] lemma is_rotated_singleton_iff {x : α} : l ~r [x] ↔ l = [x] :=
⟨λ ⟨n, hn⟩, by simpa using hn, λ h, h ▸ by refl⟩
@[simp] lemma is_rotated_singleton_iff' {x : α} : [x] ~r l ↔ [x] = l :=
by rw [is_rotated_comm, is_rotated_singleton_iff, eq_comm]
lemma is_rotated_concat (hd : α) (tl : list α) :
(tl ++ [hd]) ~r (hd :: tl) :=
is_rotated.symm ⟨1, by simp⟩
lemma is_rotated_append : (l ++ l') ~r (l' ++ l) :=
⟨l.length, by simp⟩
lemma is_rotated.reverse (h : l ~r l') : l.reverse ~r l'.reverse :=
begin
obtain ⟨n, rfl⟩ := h,
exact ⟨_, (reverse_rotate _ _).symm⟩
end
lemma is_rotated_reverse_comm_iff :
l.reverse ~r l' ↔ l ~r l'.reverse :=
begin
split;
{ intro h,
simpa using h.reverse }
end
@[simp] lemma is_rotated_reverse_iff :
l.reverse ~r l'.reverse ↔ l ~r l' :=
by simp [is_rotated_reverse_comm_iff]
lemma is_rotated_iff_mod : l ~r l' ↔ ∃ n ≤ l.length, l.rotate n = l' :=
begin
refine ⟨λ h, _, λ ⟨n, _, h⟩, ⟨n, h⟩⟩,
obtain ⟨n, rfl⟩ := h,
cases l with hd tl,
{ simp },
{ refine ⟨n % (hd :: tl).length, _, rotate_mod _ _⟩,
refine (nat.mod_lt _ _).le,
simp }
end
lemma is_rotated_iff_mem_map_range : l ~r l' ↔ l' ∈ (list.range (l.length + 1)).map l.rotate :=
begin
simp_rw [mem_map, mem_range, is_rotated_iff_mod],
exact ⟨λ ⟨n, hn, h⟩, ⟨n, nat.lt_succ_of_le hn, h⟩, λ ⟨n, hn, h⟩, ⟨n, nat.le_of_lt_succ hn, h⟩⟩
end
@[congr] theorem is_rotated.map {β : Type*} {l₁ l₂ : list α} (h : l₁ ~r l₂) (f : α → β) :
map f l₁ ~r map f l₂ :=
begin
obtain ⟨n, rfl⟩ := h,
rw map_rotate,
use n
end
/-- List of all cyclic permutations of `l`.
The `cyclic_permutations` of a nonempty list `l` will always contain `list.length l` elements.
This implies that under certain conditions, there are duplicates in `list.cyclic_permutations l`.
The `n`th entry is equal to `l.rotate n`, proven in `list.nth_le_cyclic_permutations`.
The proof that every cyclic permutant of `l` is in the list is `list.mem_cyclic_permutations_iff`.
cyclic_permutations [1, 2, 3, 2, 4] =
[[1, 2, 3, 2, 4], [2, 3, 2, 4, 1], [3, 2, 4, 1, 2],
[2, 4, 1, 2, 3], [4, 1, 2, 3, 2]] -/
def cyclic_permutations : list α → list (list α)
| [] := [[]]
| l@(_ :: _) := init (zip_with (++) (tails l) (inits l))
@[simp] lemma cyclic_permutations_nil : cyclic_permutations ([] : list α) = [[]] := rfl
lemma cyclic_permutations_cons (x : α) (l : list α) :
cyclic_permutations (x :: l) = init (zip_with (++) (tails (x :: l)) (inits (x :: l))) := rfl
lemma cyclic_permutations_of_ne_nil (l : list α) (h : l ≠ []) :
cyclic_permutations l = init (zip_with (++) (tails l) (inits l)) :=
begin
obtain ⟨hd, tl, rfl⟩ := exists_cons_of_ne_nil h,
exact cyclic_permutations_cons _ _,
end
lemma length_cyclic_permutations_cons (x : α) (l : list α) :
length (cyclic_permutations (x :: l)) = length l + 1 :=
by simp [cyclic_permutations_of_ne_nil]
@[simp] lemma length_cyclic_permutations_of_ne_nil (l : list α) (h : l ≠ []) :
length (cyclic_permutations l) = length l :=
by simp [cyclic_permutations_of_ne_nil _ h]
@[simp] lemma nth_le_cyclic_permutations (l : list α) (n : ℕ)
(hn : n < length (cyclic_permutations l)) :
nth_le (cyclic_permutations l) n hn = l.rotate n :=
begin
obtain rfl | h := eq_or_ne l [],
{ simp },
{ rw length_cyclic_permutations_of_ne_nil _ h at hn,
simp [init_eq_take, cyclic_permutations_of_ne_nil _ h, nth_le_take',
rotate_eq_drop_append_take hn.le] }
end
lemma mem_cyclic_permutations_self (l : list α) :
l ∈ cyclic_permutations l :=
begin
cases l with x l,
{ simp },
{ rw mem_iff_nth_le,
refine ⟨0, by simp, _⟩,
simp }
end
lemma length_mem_cyclic_permutations (l : list α) (h : l' ∈ cyclic_permutations l) :
length l' = length l :=
begin
obtain ⟨k, hk, rfl⟩ := nth_le_of_mem h,
simp
end
@[simp] lemma mem_cyclic_permutations_iff {l l' : list α} :
l ∈ cyclic_permutations l' ↔ l ~r l' :=
begin
split,
{ intro h,
obtain ⟨k, hk, rfl⟩ := nth_le_of_mem h,
simp },
{ intro h,
obtain ⟨k, rfl⟩ := h.symm,
rw mem_iff_nth_le,
simp only [exists_prop, nth_le_cyclic_permutations],
cases l' with x l,
{ simp },
{ refine ⟨k % length (x :: l), _, rotate_mod _ _⟩,
simpa using nat.mod_lt _ (zero_lt_succ _) } }
end
@[simp] lemma cyclic_permutations_eq_nil_iff {l : list α} :
cyclic_permutations l = [[]] ↔ l = [] :=
begin
refine ⟨λ h, _, λ h, by simp [h]⟩,
rw [eq_comm, ←is_rotated_nil_iff', ←mem_cyclic_permutations_iff, h, mem_singleton]
end
@[simp] lemma cyclic_permutations_eq_singleton_iff {l : list α} {x : α} :
cyclic_permutations l = [[x]] ↔ l = [x] :=
begin
refine ⟨λ h, _, λ h, by simp [cyclic_permutations, h, init_eq_take]⟩,
rw [eq_comm, ←is_rotated_singleton_iff', ←mem_cyclic_permutations_iff, h, mem_singleton]
end
/-- If a `l : list α` is `nodup l`, then all of its cyclic permutants are distinct. -/
lemma nodup.cyclic_permutations {l : list α} (hn : nodup l) :
nodup (cyclic_permutations l) :=
begin
cases l with x l,
{ simp },
rw nodup_iff_nth_le_inj,
intros i j hi hj h,
simp only [length_cyclic_permutations_cons] at hi hj,
rw [←mod_eq_of_lt hi, ←mod_eq_of_lt hj, ←length_cons x l],
apply hn.rotate_congr,
{ simp },
{ simpa using h }
end
@[simp] lemma cyclic_permutations_rotate (l : list α) (k : ℕ) :
(l.rotate k).cyclic_permutations = l.cyclic_permutations.rotate k :=
begin
have : (l.rotate k).cyclic_permutations.length = length (l.cyclic_permutations.rotate k),
{ cases l,
{ simp },
{ rw length_cyclic_permutations_of_ne_nil;
simp } },
refine ext_le this (λ n hn hn', _),
rw [nth_le_cyclic_permutations, nth_le_rotate, nth_le_cyclic_permutations,
rotate_rotate, ←rotate_mod, add_comm],
cases l;
simp
end
lemma is_rotated.cyclic_permutations {l l' : list α} (h : l ~r l') :
l.cyclic_permutations ~r l'.cyclic_permutations :=
begin
obtain ⟨k, rfl⟩ := h,
exact ⟨k, by simp⟩
end
@[simp] lemma is_rotated_cyclic_permutations_iff {l l' : list α} :
l.cyclic_permutations ~r l'.cyclic_permutations ↔ l ~r l' :=
begin
by_cases hl : l = [],
{ simp [hl, eq_comm] },
have hl' : l.cyclic_permutations.length = l.length := length_cyclic_permutations_of_ne_nil _ hl,
refine ⟨λ h, _, is_rotated.cyclic_permutations⟩,
obtain ⟨k, hk⟩ := h,
refine ⟨k % l.length, _⟩,
have hk' : k % l.length < l.length := mod_lt _ (length_pos_of_ne_nil hl),
rw [←nth_le_cyclic_permutations _ _ (hk'.trans_le hl'.ge), ←nth_le_rotate' _ k],
simp [hk, hl', nat.sub_add_cancel hk'.le]
end
section decidable
variables [decidable_eq α]
instance is_rotated_decidable (l l' : list α) : decidable (l ~r l') :=
decidable_of_iff' _ is_rotated_iff_mem_map_range
instance {l l' : list α} : decidable (@setoid.r _ (is_rotated.setoid α) l l') :=
list.is_rotated_decidable _ _
end decidable
end is_rotated
end list
|
2075d8bc302a3add8cbeffdd539072fe42ad354a | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/hott/ind_tac4.hlean | 55c33a0076b7a9b7b70329afb5d705978751500d | [
"Apache-2.0"
] | permissive | soonhokong/lean | cb8aa01055ffe2af0fb99a16b4cda8463b882cd1 | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | refs/heads/master | 1,611,187,284,081 | 1,450,766,737,000 | 1,476,122,547,000 | 11,513,992 | 2 | 0 | null | 1,401,763,102,000 | 1,374,182,235,000 | C++ | UTF-8 | Lean | false | false | 107 | hlean | import homotopy.circle
open circle
attribute circle.elim_on [recursor 2]
print [recursor] circle.elim_on
|
b2d44ed5f969a40af73764b7b5285dfa52d9986d | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/topology/continuous_function/bounded.lean | 4462c792638b4ddbde50bb4a29e9ec887dbc9df7 | [
"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 | 61,270 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Mario Carneiro, Yury Kudryashov, Heather Macbeth
-/
import analysis.normed_space.lattice_ordered_group
import analysis.normed_space.operator_norm
import analysis.normed_space.star.basic
import data.real.sqrt
import topology.continuous_function.algebra
/-!
# Bounded continuous functions
The type of bounded continuous functions taking values in a metric space, with
the uniform distance.
-/
noncomputable theory
open_locale topological_space classical nnreal
open set filter metric function
universes u v w
variables {F : Type*} {α : Type u} {β : Type v} {γ : Type w}
/-- `α →ᵇ β` is the type of bounded continuous functions `α → β` from a topological space to a
metric space.
When possible, instead of parametrizing results over `(f : α →ᵇ β)`,
you should parametrize over `(F : Type*) [bounded_continuous_map_class F α β] (f : F)`.
When you extend this structure, make sure to extend `bounded_continuous_map_class`. -/
structure bounded_continuous_function (α : Type u) (β : Type v)
[topological_space α] [pseudo_metric_space β] extends continuous_map α β :
Type (max u v) :=
(map_bounded' : ∃ C, ∀ x y, dist (to_fun x) (to_fun y) ≤ C)
localized "infixr (name := bounded_continuous_function)
` →ᵇ `:25 := bounded_continuous_function" in bounded_continuous_function
/-- `bounded_continuous_map_class F α β` states that `F` is a type of bounded continuous maps.
You should also extend this typeclass when you extend `bounded_continuous_function`. -/
class bounded_continuous_map_class (F α β : Type*) [topological_space α] [pseudo_metric_space β]
extends continuous_map_class F α β :=
(map_bounded (f : F) : ∃ C, ∀ x y, dist (f x) (f y) ≤ C)
export bounded_continuous_map_class (map_bounded)
namespace bounded_continuous_function
section basics
variables [topological_space α] [pseudo_metric_space β] [pseudo_metric_space γ]
variables {f g : α →ᵇ β} {x : α} {C : ℝ}
instance : bounded_continuous_map_class (α →ᵇ β) α β :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' },
map_continuous := λ f, f.continuous_to_fun,
map_bounded := λ f, f.map_bounded' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (α →ᵇ β) (λ _, α → β) := fun_like.has_coe_to_fun
instance [bounded_continuous_map_class F α β] : has_coe_t F (α →ᵇ β) :=
⟨λ f, { to_fun := f, continuous_to_fun := map_continuous f, map_bounded' := map_bounded f }⟩
@[simp] lemma coe_to_continuous_fun (f : α →ᵇ β) : (f.to_continuous_map : α → β) = f := rfl
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (h : α →ᵇ β) : α → β := h
initialize_simps_projections bounded_continuous_function (to_continuous_map_to_fun → apply)
protected lemma bounded (f : α →ᵇ β) : ∃C, ∀ x y : α, dist (f x) (f y) ≤ C := f.map_bounded'
protected lemma continuous (f : α →ᵇ β) : continuous f := f.to_continuous_map.continuous
@[ext] lemma ext (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h
lemma bounded_range (f : α →ᵇ β) : bounded (range f) :=
bounded_range_iff.2 f.bounded
lemma bounded_image (f : α →ᵇ β) (s : set α) : bounded (f '' s) :=
f.bounded_range.mono $ image_subset_range _ _
lemma eq_of_empty [is_empty α] (f g : α →ᵇ β) : f = g :=
ext $ is_empty.elim ‹_›
/-- A continuous function with an explicit bound is a bounded continuous function. -/
def mk_of_bound (f : C(α, β)) (C : ℝ) (h : ∀ x y : α, dist (f x) (f y) ≤ C) : α →ᵇ β :=
⟨f, ⟨C, h⟩⟩
@[simp] lemma mk_of_bound_coe {f} {C} {h} : (mk_of_bound f C h : α → β) = (f : α → β) :=
rfl
/-- A continuous function on a compact space is automatically a bounded continuous function. -/
def mk_of_compact [compact_space α] (f : C(α, β)) : α →ᵇ β :=
⟨f, bounded_range_iff.1 (is_compact_range f.continuous).bounded⟩
@[simp] lemma mk_of_compact_apply [compact_space α] (f : C(α, β)) (a : α) :
mk_of_compact f a = f a :=
rfl
/-- If a function is bounded on a discrete space, it is automatically continuous,
and therefore gives rise to an element of the type of bounded continuous functions -/
@[simps] def mk_of_discrete [discrete_topology α] (f : α → β)
(C : ℝ) (h : ∀ x y : α, dist (f x) (f y) ≤ C) : α →ᵇ β :=
⟨⟨f, continuous_of_discrete_topology⟩, ⟨C, h⟩⟩
/-- The uniform distance between two bounded continuous functions -/
instance : has_dist (α →ᵇ β) :=
⟨λf g, Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C}⟩
lemma dist_eq : dist f g = Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C} := rfl
lemma dist_set_exists : ∃ C, 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C :=
begin
rcases f.bounded_range.union g.bounded_range with ⟨C, hC⟩,
refine ⟨max 0 C, le_max_left _ _, λ x, (hC _ _ _ _).trans (le_max_right _ _)⟩;
[left, right]; apply mem_range_self
end
/-- The pointwise distance is controlled by the distance between functions, by definition. -/
lemma dist_coe_le_dist (x : α) : dist (f x) (g x) ≤ dist f g :=
le_cInf dist_set_exists $ λb hb, hb.2 x
/- This lemma will be needed in the proof of the metric space instance, but it will become
useless afterwards as it will be superseded by the general result that the distance is nonnegative
in metric spaces. -/
private lemma dist_nonneg' : 0 ≤ dist f g :=
le_cInf dist_set_exists (λ C, and.left)
/-- The distance between two functions is controlled by the supremum of the pointwise distances -/
lemma dist_le (C0 : (0 : ℝ) ≤ C) : dist f g ≤ C ↔ ∀x:α, dist (f x) (g x) ≤ C :=
⟨λ h x, le_trans (dist_coe_le_dist x) h, λ H, cInf_le ⟨0, λ C, and.left⟩ ⟨C0, H⟩⟩
lemma dist_le_iff_of_nonempty [nonempty α] :
dist f g ≤ C ↔ ∀ x, dist (f x) (g x) ≤ C :=
⟨λ h x, le_trans (dist_coe_le_dist x) h,
λ w, (dist_le (le_trans dist_nonneg (w (nonempty.some ‹_›)))).mpr w⟩
lemma dist_lt_of_nonempty_compact [nonempty α] [compact_space α]
(w : ∀x:α, dist (f x) (g x) < C) : dist f g < C :=
begin
have c : continuous (λ x, dist (f x) (g x)), { continuity, },
obtain ⟨x, -, le⟩ :=
is_compact.exists_forall_ge compact_univ set.univ_nonempty (continuous.continuous_on c),
exact lt_of_le_of_lt (dist_le_iff_of_nonempty.mpr (λ y, le y trivial)) (w x),
end
lemma dist_lt_iff_of_compact [compact_space α] (C0 : (0 : ℝ) < C) :
dist f g < C ↔ ∀x:α, dist (f x) (g x) < C :=
begin
fsplit,
{ intros w x,
exact lt_of_le_of_lt (dist_coe_le_dist x) w, },
{ by_cases h : nonempty α,
{ resetI,
exact dist_lt_of_nonempty_compact, },
{ rintro -,
convert C0,
apply le_antisymm _ dist_nonneg',
rw [dist_eq],
exact cInf_le ⟨0, λ C, and.left⟩ ⟨le_rfl, λ x, false.elim (h (nonempty.intro x))⟩, }, },
end
lemma dist_lt_iff_of_nonempty_compact [nonempty α] [compact_space α] :
dist f g < C ↔ ∀x:α, dist (f x) (g x) < C :=
⟨λ w x, lt_of_le_of_lt (dist_coe_le_dist x) w, dist_lt_of_nonempty_compact⟩
/-- The type of bounded continuous functions, with the uniform distance, is a pseudometric space. -/
instance : pseudo_metric_space (α →ᵇ β) :=
{ dist_self := λ f, le_antisymm ((dist_le le_rfl).2 $ λ x, by simp) dist_nonneg',
dist_comm := λ f g, by simp [dist_eq, dist_comm],
dist_triangle := λ f g h,
(dist_le (add_nonneg dist_nonneg' dist_nonneg')).2 $ λ x,
le_trans (dist_triangle _ _ _) (add_le_add (dist_coe_le_dist _) (dist_coe_le_dist _)) }
/-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/
instance {α β} [topological_space α] [metric_space β] : metric_space (α →ᵇ β) :=
{ eq_of_dist_eq_zero := λ f g hfg, by ext x; exact
eq_of_dist_eq_zero (le_antisymm (hfg ▸ dist_coe_le_dist _) dist_nonneg) }
lemma nndist_eq : nndist f g = Inf {C | ∀ x : α, nndist (f x) (g x) ≤ C} :=
subtype.ext $ dist_eq.trans $ begin
rw [nnreal.coe_Inf, nnreal.coe_image],
simp_rw [mem_set_of_eq, ←nnreal.coe_le_coe, subtype.coe_mk, exists_prop, coe_nndist],
end
lemma nndist_set_exists : ∃ C, ∀ x : α, nndist (f x) (g x) ≤ C :=
subtype.exists.mpr $ dist_set_exists.imp $ λ a ⟨ha, h⟩, ⟨ha, h⟩
lemma nndist_coe_le_nndist (x : α) : nndist (f x) (g x) ≤ nndist f g :=
dist_coe_le_dist x
/-- On an empty space, bounded continuous functions are at distance 0 -/
lemma dist_zero_of_empty [is_empty α] : dist f g = 0 :=
by rw [(ext is_empty_elim : f = g), dist_self]
lemma dist_eq_supr : dist f g = ⨆ x : α, dist (f x) (g x) :=
begin
casesI is_empty_or_nonempty α, { rw [supr_of_empty', real.Sup_empty, dist_zero_of_empty] },
refine (dist_le_iff_of_nonempty.mpr $ le_csupr _).antisymm (csupr_le dist_coe_le_dist),
exact dist_set_exists.imp (λ C hC, forall_range_iff.2 hC.2)
end
lemma nndist_eq_supr : nndist f g = ⨆ x : α, nndist (f x) (g x) :=
subtype.ext $ dist_eq_supr.trans $ by simp_rw [nnreal.coe_supr, coe_nndist]
lemma tendsto_iff_tendsto_uniformly {ι : Type*} {F : ι → (α →ᵇ β)} {f : α →ᵇ β} {l : filter ι} :
tendsto F l (𝓝 f) ↔ tendsto_uniformly (λ i, F i) f l :=
iff.intro
(λ h, tendsto_uniformly_iff.2
(λ ε ε0, (metric.tendsto_nhds.mp h ε ε0).mp (eventually_of_forall $
λ n hn x, lt_of_le_of_lt (dist_coe_le_dist x) (dist_comm (F n) f ▸ hn))))
(λ h, metric.tendsto_nhds.mpr $ λ ε ε_pos,
(h _ (dist_mem_uniformity $ half_pos ε_pos)).mp (eventually_of_forall $
λ n hn, lt_of_le_of_lt ((dist_le (half_pos ε_pos).le).mpr $
λ x, dist_comm (f x) (F n x) ▸ le_of_lt (hn x)) (half_lt_self ε_pos)))
variables (α) {β}
/-- Constant as a continuous bounded function. -/
@[simps {fully_applied := ff}] def const (b : β) : α →ᵇ β :=
⟨continuous_map.const α b, 0, by simp [le_rfl]⟩
variable {α}
lemma const_apply' (a : α) (b : β) : (const α b : α → β) a = b := rfl
/-- If the target space is inhabited, so is the space of bounded continuous functions -/
instance [inhabited β] : inhabited (α →ᵇ β) := ⟨const α default⟩
lemma lipschitz_evalx (x : α) : lipschitz_with 1 (λ f : α →ᵇ β, f x) :=
lipschitz_with.mk_one $ λ f g, dist_coe_le_dist x
theorem uniform_continuous_coe : @uniform_continuous (α →ᵇ β) (α → β) _ _ coe_fn :=
uniform_continuous_pi.2 $ λ x, (lipschitz_evalx x).uniform_continuous
lemma continuous_coe : continuous (λ (f : α →ᵇ β) x, f x) :=
uniform_continuous.continuous uniform_continuous_coe
/-- When `x` is fixed, `(f : α →ᵇ β) ↦ f x` is continuous -/
@[continuity] theorem continuous_eval_const {x : α} : continuous (λ f : α →ᵇ β, f x) :=
(continuous_apply x).comp continuous_coe
/-- The evaluation map is continuous, as a joint function of `u` and `x` -/
@[continuity] theorem continuous_eval : continuous (λ p : (α →ᵇ β) × α, p.1 p.2) :=
continuous_prod_of_continuous_lipschitz _ 1 (λ f, f.continuous) $ lipschitz_evalx
/-- Bounded continuous functions taking values in a complete space form a complete space. -/
instance [complete_space β] : complete_space (α →ᵇ β) :=
complete_of_cauchy_seq_tendsto $ λ (f : ℕ → α →ᵇ β) (hf : cauchy_seq f),
begin
/- We have to show that `f n` converges to a bounded continuous function.
For this, we prove pointwise convergence to define the limit, then check
it is a continuous bounded function, and then check the norm convergence. -/
rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩,
have f_bdd := λx n m N hn hm, le_trans (dist_coe_le_dist x) (b_bound n m N hn hm),
have fx_cau : ∀x, cauchy_seq (λn, f n x) :=
λx, cauchy_seq_iff_le_tendsto_0.2 ⟨b, b0, f_bdd x, b_lim⟩,
choose F hF using λx, cauchy_seq_tendsto_of_complete (fx_cau x),
/- F : α → β, hF : ∀ (x : α), tendsto (λ (n : ℕ), f n x) at_top (𝓝 (F x))
`F` is the desired limit function. Check that it is uniformly approximated by `f N` -/
have fF_bdd : ∀x N, dist (f N x) (F x) ≤ b N :=
λ x N, le_of_tendsto (tendsto_const_nhds.dist (hF x))
(filter.eventually_at_top.2 ⟨N, λn hn, f_bdd x N n N (le_refl N) hn⟩),
refine ⟨⟨⟨F, _⟩, _⟩, _⟩,
{ /- Check that `F` is continuous, as a uniform limit of continuous functions -/
have : tendsto_uniformly (λn x, f n x) F at_top,
{ refine metric.tendsto_uniformly_iff.2 (λ ε ε0, _),
refine ((tendsto_order.1 b_lim).2 ε ε0).mono (λ n hn x, _),
rw dist_comm,
exact lt_of_le_of_lt (fF_bdd x n) hn },
exact this.continuous (eventually_of_forall $ λ N, (f N).continuous) },
{ /- Check that `F` is bounded -/
rcases (f 0).bounded with ⟨C, hC⟩,
refine ⟨C + (b 0 + b 0), λ x y, _⟩,
calc dist (F x) (F y) ≤ dist (f 0 x) (f 0 y) + (dist (f 0 x) (F x) + dist (f 0 y) (F y)) :
dist_triangle4_left _ _ _ _
... ≤ C + (b 0 + b 0) : by mono* },
{ /- Check that `F` is close to `f N` in distance terms -/
refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero (λ _, dist_nonneg) _ b_lim),
exact λ N, (dist_le (b0 _)).2 (λx, fF_bdd x N) }
end
/-- Composition of a bounded continuous function and a continuous function. -/
@[simps { fully_applied := ff }]
def comp_continuous {δ : Type*} [topological_space δ] (f : α →ᵇ β) (g : C(δ, α)) : δ →ᵇ β :=
{ to_continuous_map := f.1.comp g,
map_bounded' := f.map_bounded'.imp (λ C hC x y, hC _ _) }
lemma lipschitz_comp_continuous {δ : Type*} [topological_space δ] (g : C(δ, α)) :
lipschitz_with 1 (λ f : α →ᵇ β, f.comp_continuous g) :=
lipschitz_with.mk_one $ λ f₁ f₂, (dist_le dist_nonneg).2 $ λ x, dist_coe_le_dist (g x)
lemma continuous_comp_continuous {δ : Type*} [topological_space δ] (g : C(δ, α)) :
continuous (λ f : α →ᵇ β, f.comp_continuous g) :=
(lipschitz_comp_continuous g).continuous
/-- Restrict a bounded continuous function to a set. -/
@[simps apply { fully_applied := ff }]
def restrict (f : α →ᵇ β) (s : set α) : s →ᵇ β :=
f.comp_continuous $ (continuous_map.id _).restrict s
/-- Composition (in the target) of a bounded continuous function with a Lipschitz map again
gives a bounded continuous function -/
def comp (G : β → γ) {C : ℝ≥0} (H : lipschitz_with C G)
(f : α →ᵇ β) : α →ᵇ γ :=
⟨⟨λx, G (f x), H.continuous.comp f.continuous⟩,
let ⟨D, hD⟩ := f.bounded in
⟨max C 0 * D, λ x y, calc
dist (G (f x)) (G (f y)) ≤ C * dist (f x) (f y) : H.dist_le_mul _ _
... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left C 0) dist_nonneg
... ≤ max C 0 * D : mul_le_mul_of_nonneg_left (hD _ _) (le_max_right C 0)⟩⟩
/-- The composition operator (in the target) with a Lipschitz map is Lipschitz -/
lemma lipschitz_comp {G : β → γ} {C : ℝ≥0} (H : lipschitz_with C G) :
lipschitz_with C (comp G H : (α →ᵇ β) → α →ᵇ γ) :=
lipschitz_with.of_dist_le_mul $ λ f g,
(dist_le (mul_nonneg C.2 dist_nonneg)).2 $ λ x,
calc dist (G (f x)) (G (g x)) ≤ C * dist (f x) (g x) : H.dist_le_mul _ _
... ≤ C * dist f g : mul_le_mul_of_nonneg_left (dist_coe_le_dist _) C.2
/-- The composition operator (in the target) with a Lipschitz map is uniformly continuous -/
lemma uniform_continuous_comp {G : β → γ} {C : ℝ≥0} (H : lipschitz_with C G) :
uniform_continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) :=
(lipschitz_comp H).uniform_continuous
/-- The composition operator (in the target) with a Lipschitz map is continuous -/
lemma continuous_comp {G : β → γ} {C : ℝ≥0} (H : lipschitz_with C G) :
continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) :=
(lipschitz_comp H).continuous
/-- Restriction (in the target) of a bounded continuous function taking values in a subset -/
def cod_restrict (s : set β) (f : α →ᵇ β) (H : ∀x, f x ∈ s) : α →ᵇ s :=
⟨⟨s.cod_restrict f H, f.continuous.subtype_mk _⟩, f.bounded⟩
section extend
variables {δ : Type*} [topological_space δ] [discrete_topology δ]
/-- A version of `function.extend` for bounded continuous maps. We assume that the domain has
discrete topology, so we only need to verify boundedness. -/
def extend (f : α ↪ δ) (g : α →ᵇ β) (h : δ →ᵇ β) : δ →ᵇ β :=
{ to_fun := extend f g h,
continuous_to_fun := continuous_of_discrete_topology,
map_bounded' :=
begin
rw [← bounded_range_iff, range_extend f.injective, metric.bounded_union],
exact ⟨g.bounded_range, h.bounded_image _⟩
end }
@[simp] lemma extend_apply (f : α ↪ δ) (g : α →ᵇ β) (h : δ →ᵇ β) (x : α) :
extend f g h (f x) = g x :=
extend_apply f.injective _ _ _
@[simp] lemma extend_comp (f : α ↪ δ) (g : α →ᵇ β) (h : δ →ᵇ β) : extend f g h ∘ f = g :=
extend_comp f.injective _ _
lemma extend_apply' {f : α ↪ δ} {x : δ} (hx : x ∉ range f) (g : α →ᵇ β) (h : δ →ᵇ β) :
extend f g h x = h x :=
extend_apply' _ _ _ hx
lemma extend_of_empty [is_empty α] (f : α ↪ δ) (g : α →ᵇ β) (h : δ →ᵇ β) :
extend f g h = h :=
fun_like.coe_injective $ function.extend_of_empty f g h
@[simp] lemma dist_extend_extend (f : α ↪ δ) (g₁ g₂ : α →ᵇ β) (h₁ h₂ : δ →ᵇ β) :
dist (g₁.extend f h₁) (g₂.extend f h₂) =
max (dist g₁ g₂) (dist (h₁.restrict (range f)ᶜ) (h₂.restrict (range f)ᶜ)) :=
begin
refine le_antisymm ((dist_le $ le_max_iff.2 $ or.inl dist_nonneg).2 $ λ x, _) (max_le _ _),
{ rcases em (∃ y, f y = x) with (⟨x, rfl⟩|hx),
{ simp only [extend_apply],
exact (dist_coe_le_dist x).trans (le_max_left _ _) },
{ simp only [extend_apply' hx],
lift x to ((range f)ᶜ : set δ) using hx,
calc dist (h₁ x) (h₂ x) = dist (h₁.restrict (range f)ᶜ x) (h₂.restrict (range f)ᶜ x) : rfl
... ≤ dist (h₁.restrict (range f)ᶜ) (h₂.restrict (range f)ᶜ) : dist_coe_le_dist x
... ≤ _ : le_max_right _ _ } },
{ refine (dist_le dist_nonneg).2 (λ x, _),
rw [← extend_apply f g₁ h₁, ← extend_apply f g₂ h₂],
exact dist_coe_le_dist _ },
{ refine (dist_le dist_nonneg).2 (λ x, _),
calc dist (h₁ x) (h₂ x) = dist (extend f g₁ h₁ x) (extend f g₂ h₂ x) :
by rw [extend_apply' x.coe_prop, extend_apply' x.coe_prop]
... ≤ _ : dist_coe_le_dist _ }
end
lemma isometry_extend (f : α ↪ δ) (h : δ →ᵇ β) :
isometry (λ g : α →ᵇ β, extend f g h) :=
isometry.of_dist_eq $ λ g₁ g₂, by simp [dist_nonneg]
end extend
end basics
section arzela_ascoli
variables [topological_space α] [compact_space α] [pseudo_metric_space β]
variables {f g : α →ᵇ β} {x : α} {C : ℝ}
/- Arzela-Ascoli theorem asserts that, on a compact space, a set of functions sharing
a common modulus of continuity and taking values in a compact set forms a compact
subset for the topology of uniform convergence. In this section, we prove this theorem
and several useful variations around it. -/
/-- First version, with pointwise equicontinuity and range in a compact space -/
theorem arzela_ascoli₁ [compact_space β]
(A : set (α →ᵇ β))
(closed : is_closed A)
(H : ∀ (x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε) :
is_compact A :=
begin
refine compact_of_totally_bounded_is_closed _ closed,
refine totally_bounded_of_finite_discretization (λ ε ε0, _),
rcases exists_between ε0 with ⟨ε₁, ε₁0, εε₁⟩,
let ε₂ := ε₁/2/2,
/- We have to find a finite discretization of `u`, i.e., finite information
that is sufficient to reconstruct `u` up to ε. This information will be
provided by the values of `u` on a sufficiently dense set tα,
slightly translated to fit in a finite ε₂-dense set tβ in the image. Such
sets exist by compactness of the source and range. Then, to check that these
data determine the function up to ε, one uses the control on the modulus of
continuity to extend the closeness on tα to closeness everywhere. -/
have ε₂0 : ε₂ > 0 := half_pos (half_pos ε₁0),
have : ∀x:α, ∃U, x ∈ U ∧ is_open U ∧ ∀ (y z ∈ U) {f : α →ᵇ β},
f ∈ A → dist (f y) (f z) < ε₂ := λ x,
let ⟨U, nhdsU, hU⟩ := H x _ ε₂0,
⟨V, VU, openV, xV⟩ := _root_.mem_nhds_iff.1 nhdsU in
⟨V, xV, openV, λy hy z hz f hf, hU y (VU hy) z (VU hz) f hf⟩,
choose U hU using this,
/- For all x, the set hU x is an open set containing x on which the elements of A
fluctuate by at most ε₂.
We extract finitely many of these sets that cover the whole space, by compactness -/
rcases compact_univ.elim_finite_subcover_image
(λx _, (hU x).2.1) (λx hx, mem_bUnion (mem_univ _) (hU x).1)
with ⟨tα, _, ⟨_⟩, htα⟩,
/- tα : set α, htα : univ ⊆ ⋃x ∈ tα, U x -/
rcases @finite_cover_balls_of_compact β _ _ compact_univ _ ε₂0
with ⟨tβ, _, ⟨_⟩, htβ⟩, resetI,
/- tβ : set β, htβ : univ ⊆ ⋃y ∈ tβ, ball y ε₂ -/
/- Associate to every point `y` in the space a nearby point `F y` in tβ -/
choose F hF using λy, show ∃z∈tβ, dist y z < ε₂, by simpa using htβ (mem_univ y),
/- F : β → β, hF : ∀ (y : β), F y ∈ tβ ∧ dist y (F y) < ε₂ -/
/- Associate to every function a discrete approximation, mapping each point in `tα`
to a point in `tβ` close to its true image by the function. -/
refine ⟨tα → tβ, by apply_instance, λ f a, ⟨F (f a), (hF (f a)).1⟩, _⟩,
rintro ⟨f, hf⟩ ⟨g, hg⟩ f_eq_g,
/- If two functions have the same approximation, then they are within distance ε -/
refine lt_of_le_of_lt ((dist_le $ le_of_lt ε₁0).2 (λ x, _)) εε₁,
obtain ⟨x', x'tα, hx'⟩ : ∃x' ∈ tα, x ∈ U x' := mem_Union₂.1 (htα (mem_univ x)),
calc dist (f x) (g x)
≤ dist (f x) (f x') + dist (g x) (g x') + dist (f x') (g x') : dist_triangle4_right _ _ _ _
... ≤ ε₂ + ε₂ + ε₁/2 : le_of_lt (add_lt_add (add_lt_add _ _) _)
... = ε₁ : by rw [add_halves, add_halves],
{ exact (hU x').2.2 _ hx' _ ((hU x').1) hf },
{ exact (hU x').2.2 _ hx' _ ((hU x').1) hg },
{ have F_f_g : F (f x') = F (g x') :=
(congr_arg (λ f:tα → tβ, (f ⟨x', x'tα⟩ : β)) f_eq_g : _),
calc dist (f x') (g x')
≤ dist (f x') (F (f x')) + dist (g x') (F (f x')) : dist_triangle_right _ _ _
... = dist (f x') (F (f x')) + dist (g x') (F (g x')) : by rw F_f_g
... < ε₂ + ε₂ : add_lt_add (hF (f x')).2 (hF (g x')).2
... = ε₁/2 : add_halves _ }
end
/-- Second version, with pointwise equicontinuity and range in a compact subset -/
theorem arzela_ascoli₂
(s : set β) (hs : is_compact s)
(A : set (α →ᵇ β))
(closed : is_closed A)
(in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s)
(H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε) :
is_compact A :=
/- This version is deduced from the previous one by restricting to the compact type in the target,
using compactness there and then lifting everything to the original space. -/
begin
have M : lipschitz_with 1 coe := lipschitz_with.subtype_coe s,
let F : (α →ᵇ s) → α →ᵇ β := comp coe M,
refine compact_of_is_closed_subset
((_ : is_compact (F ⁻¹' A)).image (continuous_comp M)) closed (λ f hf, _),
{ haveI : compact_space s := is_compact_iff_compact_space.1 hs,
refine arzela_ascoli₁ _ (continuous_iff_is_closed.1 (continuous_comp M) _ closed)
(λ x ε ε0, bex.imp_right (λ U U_nhds hU y hy z hz f hf, _) (H x ε ε0)),
calc dist (f y) (f z) = dist (F f y) (F f z) : rfl
... < ε : hU y hy z hz (F f) hf },
{ let g := cod_restrict s f (λx, in_s f x hf),
rw [show f = F g, by ext; refl] at hf ⊢,
exact ⟨g, hf, rfl⟩ }
end
/-- Third (main) version, with pointwise equicontinuity and range in a compact subset, but
without closedness. The closure is then compact -/
theorem arzela_ascoli [t2_space β]
(s : set β) (hs : is_compact s)
(A : set (α →ᵇ β))
(in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s)
(H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε) :
is_compact (closure A) :=
/- This version is deduced from the previous one by checking that the closure of A, in
addition to being closed, still satisfies the properties of compact range and equicontinuity -/
arzela_ascoli₂ s hs (closure A) is_closed_closure
(λ f x hf, (mem_of_closed' hs.is_closed).2 $ λ ε ε0,
let ⟨g, gA, dist_fg⟩ := metric.mem_closure_iff.1 hf ε ε0 in
⟨g x, in_s g x gA, lt_of_le_of_lt (dist_coe_le_dist _) dist_fg⟩)
(λ x ε ε0, show ∃ U ∈ 𝓝 x,
∀ y z ∈ U, ∀ (f : α →ᵇ β), f ∈ closure A → dist (f y) (f z) < ε,
begin
refine bex.imp_right (λ U U_set hU y hy z hz f hf, _) (H x (ε/2) (half_pos ε0)),
rcases metric.mem_closure_iff.1 hf (ε/2/2) (half_pos (half_pos ε0)) with ⟨g, gA, dist_fg⟩,
replace dist_fg := λ x, lt_of_le_of_lt (dist_coe_le_dist x) dist_fg,
calc dist (f y) (f z) ≤ dist (f y) (g y) + dist (f z) (g z) + dist (g y) (g z) :
dist_triangle4_right _ _ _ _
... < ε/2/2 + ε/2/2 + ε/2 :
add_lt_add (add_lt_add (dist_fg y) (dist_fg z)) (hU y hy z hz g gA)
... = ε : by rw [add_halves, add_halves]
end)
/- To apply the previous theorems, one needs to check the equicontinuity. An important
instance is when the source space is a metric space, and there is a fixed modulus of continuity
for all the functions in the set A -/
lemma equicontinuous_of_continuity_modulus {α : Type u} [pseudo_metric_space α]
(b : ℝ → ℝ) (b_lim : tendsto b (𝓝 0) (𝓝 0))
(A : set (α →ᵇ β))
(H : ∀(x y:α) (f : α →ᵇ β), f ∈ A → dist (f x) (f y) ≤ b (dist x y))
(x:α) (ε : ℝ) (ε0 : 0 < ε) : ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε :=
begin
rcases tendsto_nhds_nhds.1 b_lim ε ε0 with ⟨δ, δ0, hδ⟩,
refine ⟨ball x (δ/2), ball_mem_nhds x (half_pos δ0), λ y hy z hz f hf, _⟩,
have : dist y z < δ := calc
dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _
... < δ/2 + δ/2 : add_lt_add hy hz
... = δ : add_halves _,
calc
dist (f y) (f z) ≤ b (dist y z) : H y z f hf
... ≤ |b (dist y z)| : le_abs_self _
... = dist (b (dist y z)) 0 : by simp [real.dist_eq]
... < ε : hδ (by simpa [real.dist_eq] using this),
end
end arzela_ascoli
section has_one
variables [topological_space α] [pseudo_metric_space β] [has_one β]
@[to_additive] instance : has_one (α →ᵇ β) := ⟨const α 1⟩
@[simp, to_additive] lemma coe_one : ((1 : α →ᵇ β) : α → β) = 1 := rfl
@[simp, to_additive]
lemma mk_of_compact_one [compact_space α] : mk_of_compact (1 : C(α, β)) = 1 := rfl
@[to_additive] lemma forall_coe_one_iff_one (f : α →ᵇ β) : (∀ x, f x = 1) ↔ f = 1 :=
(@fun_like.ext_iff _ _ _ _ f 1).symm
@[simp, to_additive] lemma one_comp_continuous [topological_space γ] (f : C(γ, α)) :
(1 : α →ᵇ β).comp_continuous f = 1 := rfl
end has_one
section has_lipschitz_add
/- In this section, if `β` is an `add_monoid` whose addition operation is Lipschitz, then we show
that the space of bounded continuous functions from `α` to `β` inherits a topological `add_monoid`
structure, by using pointwise operations and checking that they are compatible with the uniform
distance.
Implementation note: The material in this section could have been written for `has_lipschitz_mul`
and transported by `@[to_additive]`. We choose not to do this because this causes a few lemma
names (for example, `coe_mul`) to conflict with later lemma names for normed rings; this is only a
trivial inconvenience, but in any case there are no obvious applications of the multiplicative
version. -/
variables [topological_space α] [pseudo_metric_space β] [add_monoid β]
variables [has_lipschitz_add β]
variables (f g : α →ᵇ β) {x : α} {C : ℝ}
/-- The pointwise sum of two bounded continuous functions is again bounded continuous. -/
instance : has_add (α →ᵇ β) :=
{ add := λ f g,
bounded_continuous_function.mk_of_bound (f.to_continuous_map + g.to_continuous_map)
(↑(has_lipschitz_add.C β) * max (classical.some f.bounded) (classical.some g.bounded))
begin
intros x y,
refine le_trans (lipschitz_with_lipschitz_const_add ⟨f x, g x⟩ ⟨f y, g y⟩) _,
rw prod.dist_eq,
refine mul_le_mul_of_nonneg_left _ (has_lipschitz_add.C β).coe_nonneg,
apply max_le_max,
exact classical.some_spec f.bounded x y,
exact classical.some_spec g.bounded x y,
end }
@[simp] lemma coe_add : ⇑(f + g) = f + g := rfl
lemma add_apply : (f + g) x = f x + g x := rfl
@[simp] lemma mk_of_compact_add [compact_space α] (f g : C(α, β)) :
mk_of_compact (f + g) = mk_of_compact f + mk_of_compact g := rfl
lemma add_comp_continuous [topological_space γ] (h : C(γ, α)) :
(g + f).comp_continuous h = g.comp_continuous h + f.comp_continuous h := rfl
@[simp] lemma coe_nsmul_rec : ∀ n, ⇑(nsmul_rec n f) = n • f
| 0 := by rw [nsmul_rec, zero_smul, coe_zero]
| (n + 1) := by rw [nsmul_rec, succ_nsmul, coe_add, coe_nsmul_rec]
instance has_nat_scalar : has_smul ℕ (α →ᵇ β) :=
{ smul := λ n f,
{ to_continuous_map := n • f.to_continuous_map,
map_bounded' := by simpa [coe_nsmul_rec] using (nsmul_rec n f).map_bounded' } }
@[simp] lemma coe_nsmul (r : ℕ) (f : α →ᵇ β) : ⇑(r • f) = r • f := rfl
@[simp] lemma nsmul_apply (r : ℕ) (f : α →ᵇ β) (v : α) : (r • f) v = r • f v := rfl
instance : add_monoid (α →ᵇ β) :=
fun_like.coe_injective.add_monoid _ coe_zero coe_add (λ _ _, coe_nsmul _ _)
instance : has_lipschitz_add (α →ᵇ β) :=
{ lipschitz_add := ⟨has_lipschitz_add.C β, begin
have C_nonneg := (has_lipschitz_add.C β).coe_nonneg,
rw lipschitz_with_iff_dist_le_mul,
rintros ⟨f₁, g₁⟩ ⟨f₂, g₂⟩,
rw dist_le (mul_nonneg C_nonneg dist_nonneg),
intros x,
refine le_trans (lipschitz_with_lipschitz_const_add ⟨f₁ x, g₁ x⟩ ⟨f₂ x, g₂ x⟩) _,
refine mul_le_mul_of_nonneg_left _ C_nonneg,
apply max_le_max; exact dist_coe_le_dist x,
end⟩ }
/-- Coercion of a `normed_add_group_hom` is an `add_monoid_hom`. Similar to
`add_monoid_hom.coe_fn`. -/
@[simps] def coe_fn_add_hom : (α →ᵇ β) →+ (α → β) :=
{ to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add }
variables (α β)
/-- The additive map forgetting that a bounded continuous function is bounded.
-/
@[simps] def to_continuous_map_add_hom : (α →ᵇ β) →+ C(α, β) :=
{ to_fun := to_continuous_map,
map_zero' := by { ext, simp, },
map_add' := by { intros, ext, simp, }, }
end has_lipschitz_add
section comm_has_lipschitz_add
variables [topological_space α] [pseudo_metric_space β] [add_comm_monoid β] [has_lipschitz_add β]
@[to_additive] instance : add_comm_monoid (α →ᵇ β) :=
{ add_comm := assume f g, by ext; simp [add_comm],
.. bounded_continuous_function.add_monoid }
open_locale big_operators
@[simp] lemma coe_sum {ι : Type*} (s : finset ι) (f : ι → (α →ᵇ β)) :
⇑(∑ i in s, f i) = (∑ i in s, (f i : α → β)) :=
(@coe_fn_add_hom α β _ _ _ _).map_sum f s
lemma sum_apply {ι : Type*} (s : finset ι) (f : ι → (α →ᵇ β)) (a : α) :
(∑ i in s, f i) a = (∑ i in s, f i a) :=
by simp
end comm_has_lipschitz_add
section normed_add_comm_group
/- In this section, if β is a normed group, then we show that the space of bounded
continuous functions from α to β inherits a normed group structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables [topological_space α] [seminormed_add_comm_group β]
variables (f g : α →ᵇ β) {x : α} {C : ℝ}
instance : has_norm (α →ᵇ β) := ⟨λu, dist u 0⟩
lemma norm_def : ∥f∥ = dist f 0 := rfl
/-- The norm of a bounded continuous function is the supremum of `∥f x∥`.
We use `Inf` to ensure that the definition works if `α` has no elements. -/
lemma norm_eq (f : α →ᵇ β) :
∥f∥ = Inf {C : ℝ | 0 ≤ C ∧ ∀ (x : α), ∥f x∥ ≤ C} :=
by simp [norm_def, bounded_continuous_function.dist_eq]
/-- When the domain is non-empty, we do not need the `0 ≤ C` condition in the formula for ∥f∥ as an
`Inf`. -/
lemma norm_eq_of_nonempty [h : nonempty α] : ∥f∥ = Inf {C : ℝ | ∀ (x : α), ∥f x∥ ≤ C} :=
begin
unfreezingI { obtain ⟨a⟩ := h, },
rw norm_eq,
congr,
ext,
simp only [and_iff_right_iff_imp],
exact λ h', le_trans (norm_nonneg (f a)) (h' a),
end
@[simp] lemma norm_eq_zero_of_empty [h : is_empty α] : ∥f∥ = 0 :=
dist_zero_of_empty
lemma norm_coe_le_norm (x : α) : ∥f x∥ ≤ ∥f∥ := calc
∥f x∥ = dist (f x) ((0 : α →ᵇ β) x) : by simp [dist_zero_right]
... ≤ ∥f∥ : dist_coe_le_dist _
lemma dist_le_two_norm' {f : γ → β} {C : ℝ} (hC : ∀ x, ∥f x∥ ≤ C) (x y : γ) :
dist (f x) (f y) ≤ 2 * C :=
calc dist (f x) (f y) ≤ ∥f x∥ + ∥f y∥ : dist_le_norm_add_norm _ _
... ≤ C + C : add_le_add (hC x) (hC y)
... = 2 * C : (two_mul _).symm
/-- Distance between the images of any two points is at most twice the norm of the function. -/
lemma dist_le_two_norm (x y : α) : dist (f x) (f y) ≤ 2 * ∥f∥ :=
dist_le_two_norm' f.norm_coe_le_norm x y
variable {f}
/-- The norm of a function is controlled by the supremum of the pointwise norms -/
lemma norm_le (C0 : (0 : ℝ) ≤ C) : ∥f∥ ≤ C ↔ ∀x:α, ∥f x∥ ≤ C :=
by simpa using @dist_le _ _ _ _ f 0 _ C0
lemma norm_le_of_nonempty [nonempty α]
{f : α →ᵇ β} {M : ℝ} : ∥f∥ ≤ M ↔ ∀ x, ∥f x∥ ≤ M :=
begin
simp_rw [norm_def, ←dist_zero_right],
exact dist_le_iff_of_nonempty,
end
lemma norm_lt_iff_of_compact [compact_space α]
{f : α →ᵇ β} {M : ℝ} (M0 : 0 < M) : ∥f∥ < M ↔ ∀ x, ∥f x∥ < M :=
begin
simp_rw [norm_def, ←dist_zero_right],
exact dist_lt_iff_of_compact M0,
end
lemma norm_lt_iff_of_nonempty_compact [nonempty α] [compact_space α]
{f : α →ᵇ β} {M : ℝ} : ∥f∥ < M ↔ ∀ x, ∥f x∥ < M :=
begin
simp_rw [norm_def, ←dist_zero_right],
exact dist_lt_iff_of_nonempty_compact,
end
variable (f)
/-- Norm of `const α b` is less than or equal to `∥b∥`. If `α` is nonempty,
then it is equal to `∥b∥`. -/
lemma norm_const_le (b : β) : ∥const α b∥ ≤ ∥b∥ :=
(norm_le (norm_nonneg b)).2 $ λ x, le_rfl
@[simp] lemma norm_const_eq [h : nonempty α] (b : β) : ∥const α b∥ = ∥b∥ :=
le_antisymm (norm_const_le b) $ h.elim $ λ x, (const α b).norm_coe_le_norm x
/-- Constructing a bounded continuous function from a uniformly bounded continuous
function taking values in a normed group. -/
def of_normed_add_comm_group {α : Type u} {β : Type v} [topological_space α]
[seminormed_add_comm_group β] (f : α → β) (Hf : continuous f) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) :
α →ᵇ β :=
⟨⟨λn, f n, Hf⟩, ⟨_, dist_le_two_norm' H⟩⟩
@[simp] lemma coe_of_normed_add_comm_group
{α : Type u} {β : Type v} [topological_space α] [seminormed_add_comm_group β]
(f : α → β) (Hf : continuous f) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) :
(of_normed_add_comm_group f Hf C H : α → β) = f := rfl
lemma norm_of_normed_add_comm_group_le {f : α → β} (hfc : continuous f) {C : ℝ} (hC : 0 ≤ C)
(hfC : ∀ x, ∥f x∥ ≤ C) : ∥of_normed_add_comm_group f hfc C hfC∥ ≤ C :=
(norm_le hC).2 hfC
/-- Constructing a bounded continuous function from a uniformly bounded
function on a discrete space, taking values in a normed group -/
def of_normed_add_comm_group_discrete {α : Type u} {β : Type v}
[topological_space α] [discrete_topology α] [seminormed_add_comm_group β]
(f : α → β) (C : ℝ) (H : ∀x, norm (f x) ≤ C) : α →ᵇ β :=
of_normed_add_comm_group f continuous_of_discrete_topology C H
@[simp] lemma coe_of_normed_add_comm_group_discrete {α : Type u} {β : Type v} [topological_space α]
[discrete_topology α] [seminormed_add_comm_group β] (f : α → β) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) :
(of_normed_add_comm_group_discrete f C H : α → β) = f := rfl
/-- Taking the pointwise norm of a bounded continuous function with values in a
`seminormed_add_comm_group` yields a bounded continuous function with values in ℝ. -/
def norm_comp : α →ᵇ ℝ :=
f.comp norm lipschitz_with_one_norm
@[simp] lemma coe_norm_comp : (f.norm_comp : α → ℝ) = norm ∘ f := rfl
@[simp] lemma norm_norm_comp : ∥f.norm_comp∥ = ∥f∥ :=
by simp only [norm_eq, coe_norm_comp, norm_norm]
lemma bdd_above_range_norm_comp : bdd_above $ set.range $ norm ∘ f :=
(real.bounded_iff_bdd_below_bdd_above.mp $ @bounded_range _ _ _ _ f.norm_comp).2
lemma norm_eq_supr_norm : ∥f∥ = ⨆ x : α, ∥f x∥ :=
by simp_rw [norm_def, dist_eq_supr, coe_zero, pi.zero_apply, dist_zero_right]
/-- If `∥(1 : β)∥ = 1`, then `∥(1 : α →ᵇ β)∥ = 1` if `α` is nonempty. -/
instance [nonempty α] [has_one β] [norm_one_class β] : norm_one_class (α →ᵇ β) :=
{ norm_one := by simp only [norm_eq_supr_norm, coe_one, pi.one_apply, norm_one, csupr_const] }
/-- The pointwise opposite of a bounded continuous function is again bounded continuous. -/
instance : has_neg (α →ᵇ β) :=
⟨λf, of_normed_add_comm_group (-f) f.continuous.neg ∥f∥ $ λ x,
trans_rel_right _ (norm_neg _) (f.norm_coe_le_norm x)⟩
/-- The pointwise difference of two bounded continuous functions is again bounded continuous. -/
instance : has_sub (α →ᵇ β) :=
⟨λf g, of_normed_add_comm_group (f - g) (f.continuous.sub g.continuous) (∥f∥ + ∥g∥) $ λ x,
by { simp only [sub_eq_add_neg],
exact le_trans (norm_add_le _ _) (add_le_add (f.norm_coe_le_norm x) $
trans_rel_right _ (norm_neg _) (g.norm_coe_le_norm x)) }⟩
@[simp] lemma coe_neg : ⇑(-f) = -f := rfl
lemma neg_apply : (-f) x = -f x := rfl
@[simp] lemma coe_sub : ⇑(f - g) = f - g := rfl
lemma sub_apply : (f - g) x = f x - g x := rfl
@[simp] lemma mk_of_compact_neg [compact_space α] (f : C(α, β)) :
mk_of_compact (-f) = -mk_of_compact f := rfl
@[simp] lemma mk_of_compact_sub [compact_space α] (f g : C(α, β)) :
mk_of_compact (f - g) = mk_of_compact f - mk_of_compact g := rfl
@[simp] lemma coe_zsmul_rec : ∀ z, ⇑(zsmul_rec z f) = z • f
| (int.of_nat n) := by rw [zsmul_rec, int.of_nat_eq_coe, coe_nsmul_rec, coe_nat_zsmul]
| -[1+ n] := by rw [zsmul_rec, zsmul_neg_succ_of_nat, coe_neg, coe_nsmul_rec]
instance has_int_scalar : has_smul ℤ (α →ᵇ β) :=
{ smul := λ n f,
{ to_continuous_map := n • f.to_continuous_map,
map_bounded' := by simpa using (zsmul_rec n f).map_bounded' } }
@[simp] lemma coe_zsmul (r : ℤ) (f : α →ᵇ β) : ⇑(r • f) = r • f := rfl
@[simp] lemma zsmul_apply (r : ℤ) (f : α →ᵇ β) (v : α) : (r • f) v = r • f v := rfl
instance : add_comm_group (α →ᵇ β) :=
fun_like.coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, coe_nsmul _ _)
(λ _ _, coe_zsmul _ _)
instance : seminormed_add_comm_group (α →ᵇ β) :=
{ dist_eq := λ f g, by simp only [norm_eq, dist_eq, dist_eq_norm, sub_apply] }
instance {α β} [topological_space α] [normed_add_comm_group β] : normed_add_comm_group (α →ᵇ β) :=
{ ..bounded_continuous_function.seminormed_add_comm_group }
lemma nnnorm_def : ∥f∥₊ = nndist f 0 := rfl
lemma nnnorm_coe_le_nnnorm (x : α) : ∥f x∥₊ ≤ ∥f∥₊ := norm_coe_le_norm _ _
lemma nndist_le_two_nnnorm (x y : α) : nndist (f x) (f y) ≤ 2 * ∥f∥₊ := dist_le_two_norm _ _ _
/-- The nnnorm of a function is controlled by the supremum of the pointwise nnnorms -/
lemma nnnorm_le (C : ℝ≥0) : ∥f∥₊ ≤ C ↔ ∀x:α, ∥f x∥₊ ≤ C :=
norm_le C.prop
lemma nnnorm_const_le (b : β) : ∥const α b∥₊ ≤ ∥b∥₊ :=
norm_const_le _
@[simp] lemma nnnorm_const_eq [h : nonempty α] (b : β) : ∥const α b∥₊ = ∥b∥₊ :=
subtype.ext $ norm_const_eq _
lemma nnnorm_eq_supr_nnnorm : ∥f∥₊ = ⨆ x : α, ∥f x∥₊ :=
subtype.ext $ (norm_eq_supr_norm f).trans $ by simp_rw [nnreal.coe_supr, coe_nnnorm]
lemma abs_diff_coe_le_dist : ∥f x - g x∥ ≤ dist f g :=
by { rw dist_eq_norm, exact (f - g).norm_coe_le_norm x }
lemma coe_le_coe_add_dist {f g : α →ᵇ ℝ} : f x ≤ g x + dist f g :=
sub_le_iff_le_add'.1 $ (abs_le.1 $ @dist_coe_le_dist _ _ _ _ f g x).2
lemma norm_comp_continuous_le [topological_space γ] (f : α →ᵇ β) (g : C(γ, α)) :
∥f.comp_continuous g∥ ≤ ∥f∥ :=
((lipschitz_comp_continuous g).dist_le_mul f 0).trans $
by rw [nnreal.coe_one, one_mul, dist_zero_right]
end normed_add_comm_group
section has_bounded_smul
/-!
### `has_bounded_smul` (in particular, topological module) structure
In this section, if `β` is a metric space and a `𝕜`-module whose addition and scalar multiplication
are compatible with the metric structure, then we show that the space of bounded continuous
functions from `α` to `β` inherits a so-called `has_bounded_smul` structure (in particular, a
`has_continuous_mul` structure, which is the mathlib formulation of being a topological module), by
using pointwise operations and checking that they are compatible with the uniform distance. -/
variables {𝕜 : Type*} [pseudo_metric_space 𝕜] [topological_space α] [pseudo_metric_space β]
section has_smul
variables [has_zero 𝕜] [has_zero β] [has_smul 𝕜 β] [has_bounded_smul 𝕜 β]
instance : has_smul 𝕜 (α →ᵇ β) :=
{ smul := λ c f,
{ to_continuous_map := c • f.to_continuous_map,
map_bounded' := let ⟨b, hb⟩ := f.bounded in ⟨dist c 0 * b, λ x y, begin
refine (dist_smul_pair c (f x) (f y)).trans _,
refine mul_le_mul_of_nonneg_left _ dist_nonneg,
exact hb x y
end⟩ } }
@[simp] lemma coe_smul (c : 𝕜) (f : α →ᵇ β) : ⇑(c • f) = λ x, c • (f x) := rfl
lemma smul_apply (c : 𝕜) (f : α →ᵇ β) (x : α) : (c • f) x = c • f x := rfl
instance [has_smul 𝕜ᵐᵒᵖ β] [is_central_scalar 𝕜 β] : is_central_scalar 𝕜 (α →ᵇ β) :=
{ op_smul_eq_smul := λ _ _, ext $ λ _, op_smul_eq_smul _ _ }
instance : has_bounded_smul 𝕜 (α →ᵇ β) :=
{ dist_smul_pair' := λ c f₁ f₂, begin
rw dist_le (mul_nonneg dist_nonneg dist_nonneg),
intros x,
refine (dist_smul_pair c (f₁ x) (f₂ x)).trans _,
exact mul_le_mul_of_nonneg_left (dist_coe_le_dist x) dist_nonneg
end,
dist_pair_smul' := λ c₁ c₂ f, begin
rw dist_le (mul_nonneg dist_nonneg dist_nonneg),
intros x,
refine (dist_pair_smul c₁ c₂ (f x)).trans _,
convert mul_le_mul_of_nonneg_left (dist_coe_le_dist x) dist_nonneg,
simp
end }
end has_smul
section mul_action
variables [monoid_with_zero 𝕜] [has_zero β] [mul_action 𝕜 β] [has_bounded_smul 𝕜 β]
instance : mul_action 𝕜 (α →ᵇ β) := fun_like.coe_injective.mul_action _ coe_smul
end mul_action
section distrib_mul_action
variables [monoid_with_zero 𝕜] [add_monoid β] [distrib_mul_action 𝕜 β] [has_bounded_smul 𝕜 β]
variables [has_lipschitz_add β]
instance : distrib_mul_action 𝕜 (α →ᵇ β) :=
function.injective.distrib_mul_action ⟨_, coe_zero, coe_add⟩ fun_like.coe_injective coe_smul
end distrib_mul_action
section module
variables [semiring 𝕜] [add_comm_monoid β] [module 𝕜 β] [has_bounded_smul 𝕜 β]
variables {f g : α →ᵇ β} {x : α} {C : ℝ}
variables [has_lipschitz_add β]
instance : module 𝕜 (α →ᵇ β) :=
function.injective.module _ ⟨_, coe_zero, coe_add⟩ fun_like.coe_injective coe_smul
variables (𝕜)
/-- The evaluation at a point, as a continuous linear map from `α →ᵇ β` to `β`. -/
def eval_clm (x : α) : (α →ᵇ β) →L[𝕜] β :=
{ to_fun := λ f, f x,
map_add' := λ f g, add_apply _ _,
map_smul' := λ c f, smul_apply _ _ _ }
@[simp] lemma eval_clm_apply (x : α) (f : α →ᵇ β) :
eval_clm 𝕜 x f = f x := rfl
variables (α β)
/-- The linear map forgetting that a bounded continuous function is bounded. -/
@[simps]
def to_continuous_map_linear_map : (α →ᵇ β) →ₗ[𝕜] C(α, β) :=
{ to_fun := to_continuous_map,
map_smul' := λ f g, rfl,
map_add' := λ c f, rfl }
end module
end has_bounded_smul
section normed_space
/-!
### Normed space structure
In this section, if `β` is a normed space, then we show that the space of bounded
continuous functions from `α` to `β` inherits a normed space structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables {𝕜 : Type*}
variables [topological_space α] [seminormed_add_comm_group β]
variables {f g : α →ᵇ β} {x : α} {C : ℝ}
instance [normed_field 𝕜] [normed_space 𝕜 β] : normed_space 𝕜 (α →ᵇ β) := ⟨λ c f, begin
refine norm_of_normed_add_comm_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _,
exact (λ x, trans_rel_right _ (norm_smul _ _)
(mul_le_mul_of_nonneg_left (f.norm_coe_le_norm _) (norm_nonneg _))) end⟩
variables [nontrivially_normed_field 𝕜] [normed_space 𝕜 β]
variables [seminormed_add_comm_group γ] [normed_space 𝕜 γ]
variables (α)
-- TODO does this work in the `has_bounded_smul` setting, too?
/--
Postcomposition of bounded continuous functions into a normed module by a continuous linear map is
a continuous linear map.
Upgraded version of `continuous_linear_map.comp_left_continuous`, similar to
`linear_map.comp_left`. -/
protected def _root_.continuous_linear_map.comp_left_continuous_bounded (g : β →L[𝕜] γ) :
(α →ᵇ β) →L[𝕜] (α →ᵇ γ) :=
linear_map.mk_continuous
{ to_fun := λ f, of_normed_add_comm_group
(g ∘ f)
(g.continuous.comp f.continuous)
(∥g∥ * ∥f∥)
(λ x, (g.le_op_norm_of_le (f.norm_coe_le_norm x))),
map_add' := λ f g, by ext; simp,
map_smul' := λ c f, by ext; simp }
∥g∥
(λ f, norm_of_normed_add_comm_group_le _ (mul_nonneg (norm_nonneg g) (norm_nonneg f)) _)
@[simp] lemma _root_.continuous_linear_map.comp_left_continuous_bounded_apply (g : β →L[𝕜] γ)
(f : α →ᵇ β) (x : α) :
(g.comp_left_continuous_bounded α f) x = g (f x) :=
rfl
end normed_space
section normed_ring
/-!
### Normed ring structure
In this section, if `R` is a normed ring, then we show that the space of bounded
continuous functions from `α` to `R` inherits a normed ring structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables [topological_space α] {R : Type*}
section non_unital
section semi_normed
variables [non_unital_semi_normed_ring R]
instance : has_mul (α →ᵇ R) :=
{ mul := λ f g, of_normed_add_comm_group (f * g) (f.continuous.mul g.continuous) (∥f∥ * ∥g∥) $ λ x,
le_trans (norm_mul_le (f x) (g x)) $
mul_le_mul (f.norm_coe_le_norm x) (g.norm_coe_le_norm x) (norm_nonneg _) (norm_nonneg _) }
@[simp] lemma coe_mul (f g : α →ᵇ R) : ⇑(f * g) = f * g := rfl
lemma mul_apply (f g : α →ᵇ R) (x : α) : (f * g) x = f x * g x := rfl
instance : non_unital_ring (α →ᵇ R) :=
fun_like.coe_injective.non_unital_ring _ coe_zero coe_add coe_mul coe_neg coe_sub
(λ _ _, coe_nsmul _ _) (λ _ _, coe_zsmul _ _)
instance : non_unital_semi_normed_ring (α →ᵇ R) :=
{ norm_mul := λ f g, norm_of_normed_add_comm_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _))
_,
.. bounded_continuous_function.seminormed_add_comm_group }
end semi_normed
instance [non_unital_normed_ring R] : non_unital_normed_ring (α →ᵇ R) :=
{ .. bounded_continuous_function.non_unital_semi_normed_ring,
.. bounded_continuous_function.normed_add_comm_group }
end non_unital
section semi_normed
variables [semi_normed_ring R]
@[simp] lemma coe_npow_rec (f : α →ᵇ R) : ∀ n, ⇑(npow_rec n f) = f ^ n
| 0 := by rw [npow_rec, pow_zero, coe_one]
| (n + 1) := by rw [npow_rec, pow_succ, coe_mul, coe_npow_rec]
instance has_nat_pow : has_pow (α →ᵇ R) ℕ :=
{ pow := λ f n,
{ to_continuous_map := f.to_continuous_map ^ n,
map_bounded' := by simpa [coe_npow_rec] using (npow_rec n f).map_bounded' } }
@[simp] lemma coe_pow (n : ℕ) (f : α →ᵇ R) : ⇑(f ^ n) = f ^ n := rfl
@[simp] lemma pow_apply (n : ℕ) (f : α →ᵇ R) (v : α) : (f ^ n) v = f v ^ n := rfl
instance : has_nat_cast (α →ᵇ R) :=
⟨λ n, bounded_continuous_function.const _ n⟩
@[simp, norm_cast] lemma coe_nat_cast (n : ℕ) : ((n : α →ᵇ R) : α → R) = n := rfl
instance : has_int_cast (α →ᵇ R) :=
⟨λ n, bounded_continuous_function.const _ n⟩
@[simp, norm_cast] lemma coe_int_cast (n : ℤ) : ((n : α →ᵇ R) : α → R) = n := rfl
instance : ring (α →ᵇ R) :=
fun_like.coe_injective.ring _ coe_zero coe_one coe_add coe_mul coe_neg coe_sub
(λ _ _, coe_nsmul _ _)
(λ _ _, coe_zsmul _ _)
(λ _ _, coe_pow _ _)
coe_nat_cast
coe_int_cast
instance : semi_normed_ring (α →ᵇ R) :=
{ ..bounded_continuous_function.non_unital_semi_normed_ring }
end semi_normed
instance [normed_ring R] : normed_ring (α →ᵇ R) :=
{ ..bounded_continuous_function.non_unital_normed_ring }
end normed_ring
section normed_comm_ring
/-!
### Normed commutative ring structure
In this section, if `R` is a normed commutative ring, then we show that the space of bounded
continuous functions from `α` to `R` inherits a normed commutative ring structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables [topological_space α] {R : Type*}
instance [semi_normed_comm_ring R] : comm_ring (α →ᵇ R) :=
{ mul_comm := λ f₁ f₂, ext $ λ x, mul_comm _ _,
.. bounded_continuous_function.ring }
instance [semi_normed_comm_ring R] : semi_normed_comm_ring (α →ᵇ R) :=
{ ..bounded_continuous_function.comm_ring, ..bounded_continuous_function.seminormed_add_comm_group }
instance [normed_comm_ring R] : normed_comm_ring (α →ᵇ R) :=
{ .. bounded_continuous_function.comm_ring, .. bounded_continuous_function.normed_add_comm_group }
end normed_comm_ring
section normed_algebra
/-!
### Normed algebra structure
In this section, if `γ` is a normed algebra, then we show that the space of bounded
continuous functions from `α` to `γ` inherits a normed algebra structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables {𝕜 : Type*} [normed_field 𝕜]
variables [topological_space α] [seminormed_add_comm_group β] [normed_space 𝕜 β]
variables [normed_ring γ] [normed_algebra 𝕜 γ]
variables {f g : α →ᵇ γ} {x : α} {c : 𝕜}
/-- `bounded_continuous_function.const` as a `ring_hom`. -/
def C : 𝕜 →+* (α →ᵇ γ) :=
{ to_fun := λ (c : 𝕜), const α ((algebra_map 𝕜 γ) c),
map_one' := ext $ λ x, (algebra_map 𝕜 γ).map_one,
map_mul' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_mul _ _,
map_zero' := ext $ λ x, (algebra_map 𝕜 γ).map_zero,
map_add' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_add _ _ }
instance : algebra 𝕜 (α →ᵇ γ) :=
{ to_ring_hom := C,
commutes' := λ c f, ext $ λ x, algebra.commutes' _ _,
smul_def' := λ c f, ext $ λ x, algebra.smul_def' _ _,
..bounded_continuous_function.module,
..bounded_continuous_function.ring }
@[simp] lemma algebra_map_apply (k : 𝕜) (a : α) :
algebra_map 𝕜 (α →ᵇ γ) k a = k • 1 :=
by { rw algebra.algebra_map_eq_smul_one, refl, }
instance : normed_algebra 𝕜 (α →ᵇ γ) :=
{ ..bounded_continuous_function.normed_space }
/-!
### Structure as normed module over scalar functions
If `β` is a normed `𝕜`-space, then we show that the space of bounded continuous
functions from `α` to `β` is naturally a module over the algebra of bounded continuous
functions from `α` to `𝕜`. -/
instance has_smul' : has_smul (α →ᵇ 𝕜) (α →ᵇ β) :=
⟨λ (f : α →ᵇ 𝕜) (g : α →ᵇ β), of_normed_add_comm_group (λ x, (f x) • (g x))
(f.continuous.smul g.continuous) (∥f∥ * ∥g∥) (λ x, calc
∥f x • g x∥ ≤ ∥f x∥ * ∥g x∥ : normed_space.norm_smul_le _ _
... ≤ ∥f∥ * ∥g∥ : mul_le_mul (f.norm_coe_le_norm _) (g.norm_coe_le_norm _) (norm_nonneg _)
(norm_nonneg _)) ⟩
instance module' : module (α →ᵇ 𝕜) (α →ᵇ β) :=
module.of_core $
{ smul := (•),
smul_add := λ c f₁ f₂, ext $ λ x, smul_add _ _ _,
add_smul := λ c₁ c₂ f, ext $ λ x, add_smul _ _ _,
mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _,
one_smul := λ f, ext $ λ x, one_smul 𝕜 (f x) }
lemma norm_smul_le (f : α →ᵇ 𝕜) (g : α →ᵇ β) : ∥f • g∥ ≤ ∥f∥ * ∥g∥ :=
norm_of_normed_add_comm_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _
/- TODO: When `normed_module` has been added to `normed_space.basic`, the above facts
show that the space of bounded continuous functions from `α` to `β` is naturally a normed
module over the algebra of bounded continuous functions from `α` to `𝕜`. -/
end normed_algebra
lemma nnreal.upper_bound {α : Type*} [topological_space α]
(f : α →ᵇ ℝ≥0) (x : α) : f x ≤ nndist f 0 :=
begin
have key : nndist (f x) ((0 : α →ᵇ ℝ≥0) x) ≤ nndist f 0,
{ exact @dist_coe_le_dist α ℝ≥0 _ _ f 0 x, },
simp only [coe_zero, pi.zero_apply] at key,
rwa nnreal.nndist_zero_eq_val' (f x) at key,
end
/-!
### Star structures
In this section, if `β` is a normed ⋆-group, then so is the space of bounded
continuous functions from `α` to `β`, by using the star operation pointwise.
If `𝕜` is normed field and a ⋆-ring over which `β` is a normed algebra and a
star module, then the space of bounded continuous functions from `α` to `β`
is a star module.
If `β` is a ⋆-ring in addition to being a normed ⋆-group, then `α →ᵇ β`
inherits a ⋆-ring structure.
In summary, if `β` is a C⋆-algebra over `𝕜`, then so is `α →ᵇ β`; note that
completeness is guaranteed when `β` is complete (see
`bounded_continuous_function.complete`). -/
section normed_add_comm_group
variables {𝕜 : Type*} [normed_field 𝕜] [star_ring 𝕜] [topological_space α]
[seminormed_add_comm_group β] [star_add_monoid β] [normed_star_group β]
variables [normed_space 𝕜 β] [star_module 𝕜 β]
instance : star_add_monoid (α →ᵇ β) :=
{ star := λ f, f.comp star star_normed_add_group_hom.lipschitz,
star_involutive := λ f, ext $ λ x, star_star (f x),
star_add := λ f g, ext $ λ x, star_add (f x) (g x) }
/-- The right-hand side of this equality can be parsed `star ∘ ⇑f` because of the
instance `pi.has_star`. Upon inspecting the goal, one sees `⊢ ⇑(star f) = star ⇑f`.-/
@[simp] lemma coe_star (f : α →ᵇ β) : ⇑(star f) = star f := rfl
@[simp] lemma star_apply (f : α →ᵇ β) (x : α) : star f x = star (f x) := rfl
instance : normed_star_group (α →ᵇ β) :=
{ norm_star := λ f, by simp only [norm_eq, star_apply, norm_star] }
instance : star_module 𝕜 (α →ᵇ β) :=
{ star_smul := λ k f, ext $ λ x, star_smul k (f x) }
end normed_add_comm_group
section cstar_ring
variables [topological_space α]
variables [non_unital_normed_ring β] [star_ring β]
instance [normed_star_group β] : star_ring (α →ᵇ β) :=
{ star_mul := λ f g, ext $ λ x, star_mul (f x) (g x),
..bounded_continuous_function.star_add_monoid }
variable [cstar_ring β]
instance : cstar_ring (α →ᵇ β) :=
{ norm_star_mul_self :=
begin
intro f,
refine le_antisymm _ _,
{ rw [←sq, norm_le (sq_nonneg _)],
dsimp [star_apply],
intro x,
rw [cstar_ring.norm_star_mul_self, ←sq],
refine sq_le_sq' _ _,
{ linarith [norm_nonneg (f x), norm_nonneg f] },
{ exact norm_coe_le_norm f x }, },
{ rw [←sq, ←real.le_sqrt (norm_nonneg _) (norm_nonneg _), norm_le (real.sqrt_nonneg _)],
intro x,
rw [real.le_sqrt (norm_nonneg _) (norm_nonneg _), sq, ←cstar_ring.norm_star_mul_self],
exact norm_coe_le_norm (star f * f) x }
end }
end cstar_ring
section normed_lattice_ordered_group
variables [topological_space α] [normed_lattice_add_comm_group β]
instance : partial_order (α →ᵇ β) := partial_order.lift (λ f, f.to_fun) (by tidy)
/--
Continuous normed lattice group valued functions form a meet-semilattice
-/
instance : semilattice_inf (α →ᵇ β) :=
{ inf := λ f g,
{ to_fun := λ t, f t ⊓ g t,
continuous_to_fun := f.continuous.inf g.continuous,
map_bounded' := begin
obtain ⟨C₁, hf⟩ := f.bounded,
obtain ⟨C₂, hg⟩ := g.bounded,
refine ⟨C₁ + C₂, λ x y, _⟩,
simp_rw normed_add_comm_group.dist_eq at hf hg ⊢,
exact (norm_inf_sub_inf_le_add_norm _ _ _ _).trans (add_le_add (hf _ _) (hg _ _)),
end },
inf_le_left := λ f g, continuous_map.le_def.mpr (λ _, inf_le_left),
inf_le_right := λ f g, continuous_map.le_def.mpr (λ _, inf_le_right),
le_inf := λ f g₁ g₂ w₁ w₂, continuous_map.le_def.mpr (λ _, le_inf (continuous_map.le_def.mp w₁ _)
(continuous_map.le_def.mp w₂ _)),
..bounded_continuous_function.partial_order }
instance : semilattice_sup (α →ᵇ β) :=
{ sup := λ f g,
{ to_fun := λ t, f t ⊔ g t,
continuous_to_fun := f.continuous.sup g.continuous,
map_bounded' := begin
obtain ⟨C₁, hf⟩ := f.bounded,
obtain ⟨C₂, hg⟩ := g.bounded,
refine ⟨C₁ + C₂, λ x y, _⟩,
simp_rw normed_add_comm_group.dist_eq at hf hg ⊢,
exact (norm_sup_sub_sup_le_add_norm _ _ _ _).trans (add_le_add (hf _ _) (hg _ _)),
end },
le_sup_left := λ f g, continuous_map.le_def.mpr (λ _, le_sup_left),
le_sup_right := λ f g, continuous_map.le_def.mpr (λ _, le_sup_right),
sup_le := λ f g₁ g₂ w₁ w₂, continuous_map.le_def.mpr (λ _, sup_le (continuous_map.le_def.mp w₁ _)
(continuous_map.le_def.mp w₂ _)),
..bounded_continuous_function.partial_order }
instance : lattice (α →ᵇ β) :=
{ .. bounded_continuous_function.semilattice_sup, .. bounded_continuous_function.semilattice_inf }
@[simp] lemma coe_fn_sup (f g : α →ᵇ β) : ⇑(f ⊔ g) = f ⊔ g := rfl
@[simp] lemma coe_fn_abs (f : α →ᵇ β) : ⇑|f| = |f| := rfl
instance : normed_lattice_add_comm_group (α →ᵇ β) :=
{ add_le_add_left := begin
intros f g h₁ h t,
simp only [coe_to_continuous_fun, pi.add_apply, add_le_add_iff_left, coe_add,
continuous_map.to_fun_eq_coe],
exact h₁ _,
end,
solid :=
begin
intros f g h,
have i1: ∀ t, ∥f t∥ ≤ ∥g t∥ := λ t, solid (h t),
rw norm_le (norm_nonneg _),
exact λ t, (i1 t).trans (norm_coe_le_norm g t),
end,
..bounded_continuous_function.lattice, }
end normed_lattice_ordered_group
section nonnegative_part
variables [topological_space α]
/-- The nonnegative part of a bounded continuous `ℝ`-valued function as a bounded
continuous `ℝ≥0`-valued function. -/
def nnreal_part (f : α →ᵇ ℝ) : α →ᵇ ℝ≥0 :=
bounded_continuous_function.comp _
(show lipschitz_with 1 real.to_nnreal, from lipschitz_with_pos) f
@[simp] lemma nnreal_part_coe_fun_eq (f : α →ᵇ ℝ) : ⇑(f.nnreal_part) = real.to_nnreal ∘ ⇑f := rfl
/-- The absolute value of a bounded continuous `ℝ`-valued function as a bounded
continuous `ℝ≥0`-valued function. -/
def nnnorm (f : α →ᵇ ℝ) : α →ᵇ ℝ≥0 :=
bounded_continuous_function.comp _
(show lipschitz_with 1 (λ (x : ℝ), ∥x∥₊), from lipschitz_with_one_norm) f
@[simp] lemma nnnorm_coe_fun_eq (f : α →ᵇ ℝ) : ⇑(f.nnnorm) = has_nnnorm.nnnorm ∘ ⇑f := rfl
/-- Decompose a bounded continuous function to its positive and negative parts. -/
lemma self_eq_nnreal_part_sub_nnreal_part_neg (f : α →ᵇ ℝ) :
⇑f = coe ∘ f.nnreal_part - coe ∘ (-f).nnreal_part :=
by { funext x, dsimp, simp only [max_zero_sub_max_neg_zero_eq_self], }
/-- Express the absolute value of a bounded continuous function in terms of its
positive and negative parts. -/
lemma abs_self_eq_nnreal_part_add_nnreal_part_neg (f : α →ᵇ ℝ) :
abs ∘ ⇑f = coe ∘ f.nnreal_part + coe ∘ (-f).nnreal_part :=
by { funext x, dsimp, simp only [max_zero_add_max_neg_zero_eq_abs_self], }
end nonnegative_part
end bounded_continuous_function
|
bf907463ef711b09a50a34792b3f979f6807a8ca | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch5/ex0512.lean | c2d6fe9be8e022827c67ea02baa05157acd919ba | [] | no_license | Ailrun/Theorem_Proving_in_Lean | ae6a23f3c54d62d401314d6a771e8ff8b4132db2 | 2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68 | refs/heads/master | 1,609,838,270,467 | 1,586,846,743,000 | 1,586,846,743,000 | 240,967,761 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 149 | lean | example (p q r : Prop) (hp : p) (hq : q) (hr : r) : p ∧ ((p ∧ q) ∧ r) ∧ (q ∧ r ∧ p) :=
by repeat { any_goals { split <|> assumption} }
|
a5587111b34b39d26b7e72d91f6069f410826c17 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/special_functions/trigonometric/inverse.lean | 072612149aa3dce2276d5b0fd2303f5df4bfb437 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 12,927 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson
-/
import analysis.special_functions.trigonometric.basic
import topology.algebra.order.proj_Icc
/-!
# Inverse trigonometric functions.
See also `analysis.special_functions.trigonometric.arctan` for the inverse tan function.
(This is delayed as it is easier to set up after developing complex trigonometric functions.)
Basic inequalities on trigonometric functions.
-/
noncomputable theory
open_locale classical topological_space filter
open set filter
open_locale real
namespace real
/-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x ≤ π / 2`.
It defaults to `-π / 2` on `(-∞, -1)` and to `π / 2` to `(1, ∞)`. -/
@[pp_nodot] noncomputable def arcsin : ℝ → ℝ :=
coe ∘ Icc_extend (neg_le_self zero_le_one) sin_order_iso.symm
lemma arcsin_mem_Icc (x : ℝ) : arcsin x ∈ Icc (-(π / 2)) (π / 2) := subtype.coe_prop _
@[simp] lemma range_arcsin : range arcsin = Icc (-(π / 2)) (π / 2) :=
by { rw [arcsin, range_comp coe], simp [Icc] }
lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 := (arcsin_mem_Icc x).2
lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x := (arcsin_mem_Icc x).1
lemma arcsin_proj_Icc (x : ℝ) :
arcsin (proj_Icc (-1) 1 (neg_le_self $ @zero_le_one ℝ _) x) = arcsin x :=
by rw [arcsin, function.comp_app, Icc_extend_coe, function.comp_app, Icc_extend]
lemma sin_arcsin' {x : ℝ} (hx : x ∈ Icc (-1 : ℝ) 1) : sin (arcsin x) = x :=
by simpa [arcsin, Icc_extend_of_mem _ _ hx, -order_iso.apply_symm_apply]
using subtype.ext_iff.1 (sin_order_iso.apply_symm_apply ⟨x, hx⟩)
lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x :=
sin_arcsin' ⟨hx₁, hx₂⟩
lemma arcsin_sin' {x : ℝ} (hx : x ∈ Icc (-(π / 2)) (π / 2)) : arcsin (sin x) = x :=
inj_on_sin (arcsin_mem_Icc _) hx $ by rw [sin_arcsin (neg_one_le_sin _) (sin_le_one _)]
lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x :=
arcsin_sin' ⟨hx₁, hx₂⟩
lemma strict_mono_on_arcsin : strict_mono_on arcsin (Icc (-1) 1) :=
(subtype.strict_mono_coe _).comp_strict_mono_on $
sin_order_iso.symm.strict_mono.strict_mono_on_Icc_extend _
lemma monotone_arcsin : monotone arcsin :=
(subtype.mono_coe _).comp $ sin_order_iso.symm.monotone.Icc_extend _
lemma inj_on_arcsin : inj_on arcsin (Icc (-1) 1) := strict_mono_on_arcsin.inj_on
lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) :
arcsin x = arcsin y ↔ x = y :=
inj_on_arcsin.eq_iff ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩
@[continuity]
lemma continuous_arcsin : continuous arcsin :=
continuous_subtype_coe.comp sin_order_iso.symm.continuous.Icc_extend'
lemma continuous_at_arcsin {x : ℝ} : continuous_at arcsin x :=
continuous_arcsin.continuous_at
lemma arcsin_eq_of_sin_eq {x y : ℝ} (h₁ : sin x = y) (h₂ : x ∈ Icc (-(π / 2)) (π / 2)) :
arcsin y = x :=
begin
subst y,
exact inj_on_sin (arcsin_mem_Icc _) h₂ (sin_arcsin' (sin_mem_Icc x))
end
@[simp] lemma arcsin_zero : arcsin 0 = 0 :=
arcsin_eq_of_sin_eq sin_zero ⟨neg_nonpos.2 pi_div_two_pos.le, pi_div_two_pos.le⟩
@[simp] lemma arcsin_one : arcsin 1 = π / 2 :=
arcsin_eq_of_sin_eq sin_pi_div_two $ right_mem_Icc.2 (neg_le_self pi_div_two_pos.le)
lemma arcsin_of_one_le {x : ℝ} (hx : 1 ≤ x) : arcsin x = π / 2 :=
by rw [← arcsin_proj_Icc, proj_Icc_of_right_le _ hx, subtype.coe_mk, arcsin_one]
lemma arcsin_neg_one : arcsin (-1) = -(π / 2) :=
arcsin_eq_of_sin_eq (by rw [sin_neg, sin_pi_div_two]) $
left_mem_Icc.2 (neg_le_self pi_div_two_pos.le)
lemma arcsin_of_le_neg_one {x : ℝ} (hx : x ≤ -1) : arcsin x = -(π / 2) :=
by rw [← arcsin_proj_Icc, proj_Icc_of_le_left _ hx, subtype.coe_mk, arcsin_neg_one]
@[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x :=
begin
cases le_total x (-1) with hx₁ hx₁,
{ rw [arcsin_of_le_neg_one hx₁, neg_neg, arcsin_of_one_le (le_neg.2 hx₁)] },
cases le_total 1 x with hx₂ hx₂,
{ rw [arcsin_of_one_le hx₂, arcsin_of_le_neg_one (neg_le_neg hx₂)] },
refine arcsin_eq_of_sin_eq _ _,
{ rw [sin_neg, sin_arcsin hx₁ hx₂] },
{ exact ⟨neg_le_neg (arcsin_le_pi_div_two _), neg_le.2 (neg_pi_div_two_le_arcsin _)⟩ }
end
lemma arcsin_le_iff_le_sin {x y : ℝ} (hx : x ∈ Icc (-1 : ℝ) 1) (hy : y ∈ Icc (-(π / 2)) (π / 2)) :
arcsin x ≤ y ↔ x ≤ sin y :=
by rw [← arcsin_sin' hy, strict_mono_on_arcsin.le_iff_le hx (sin_mem_Icc _), arcsin_sin' hy]
lemma arcsin_le_iff_le_sin' {x y : ℝ} (hy : y ∈ Ico (-(π / 2)) (π / 2)) :
arcsin x ≤ y ↔ x ≤ sin y :=
begin
cases le_total x (-1) with hx₁ hx₁,
{ simp [arcsin_of_le_neg_one hx₁, hy.1, hx₁.trans (neg_one_le_sin _)] },
cases lt_or_le 1 x with hx₂ hx₂,
{ simp [arcsin_of_one_le hx₂.le, hy.2.not_le, (sin_le_one y).trans_lt hx₂] },
exact arcsin_le_iff_le_sin ⟨hx₁, hx₂⟩ (mem_Icc_of_Ico hy)
end
lemma le_arcsin_iff_sin_le {x y : ℝ} (hx : x ∈ Icc (-(π / 2)) (π / 2)) (hy : y ∈ Icc (-1 : ℝ) 1) :
x ≤ arcsin y ↔ sin x ≤ y :=
by rw [← neg_le_neg_iff, ← arcsin_neg,
arcsin_le_iff_le_sin ⟨neg_le_neg hy.2, neg_le.2 hy.1⟩ ⟨neg_le_neg hx.2, neg_le.2 hx.1⟩,
sin_neg, neg_le_neg_iff]
lemma le_arcsin_iff_sin_le' {x y : ℝ} (hx : x ∈ Ioc (-(π / 2)) (π / 2)) :
x ≤ arcsin y ↔ sin x ≤ y :=
by rw [← neg_le_neg_iff, ← arcsin_neg, arcsin_le_iff_le_sin' ⟨neg_le_neg hx.2, neg_lt.2 hx.1⟩,
sin_neg, neg_le_neg_iff]
lemma arcsin_lt_iff_lt_sin {x y : ℝ} (hx : x ∈ Icc (-1 : ℝ) 1) (hy : y ∈ Icc (-(π / 2)) (π / 2)) :
arcsin x < y ↔ x < sin y :=
not_le.symm.trans $ (not_congr $ le_arcsin_iff_sin_le hy hx).trans not_le
lemma arcsin_lt_iff_lt_sin' {x y : ℝ} (hy : y ∈ Ioc (-(π / 2)) (π / 2)) :
arcsin x < y ↔ x < sin y :=
not_le.symm.trans $ (not_congr $ le_arcsin_iff_sin_le' hy).trans not_le
lemma lt_arcsin_iff_sin_lt {x y : ℝ} (hx : x ∈ Icc (-(π / 2)) (π / 2)) (hy : y ∈ Icc (-1 : ℝ) 1) :
x < arcsin y ↔ sin x < y :=
not_le.symm.trans $ (not_congr $ arcsin_le_iff_le_sin hy hx).trans not_le
lemma lt_arcsin_iff_sin_lt' {x y : ℝ} (hx : x ∈ Ico (-(π / 2)) (π / 2)) :
x < arcsin y ↔ sin x < y :=
not_le.symm.trans $ (not_congr $ arcsin_le_iff_le_sin' hx).trans not_le
lemma arcsin_eq_iff_eq_sin {x y : ℝ} (hy : y ∈ Ioo (-(π / 2)) (π / 2)) :
arcsin x = y ↔ x = sin y :=
by simp only [le_antisymm_iff, arcsin_le_iff_le_sin' (mem_Ico_of_Ioo hy),
le_arcsin_iff_sin_le' (mem_Ioc_of_Ioo hy)]
@[simp] lemma arcsin_nonneg {x : ℝ} : 0 ≤ arcsin x ↔ 0 ≤ x :=
(le_arcsin_iff_sin_le' ⟨neg_lt_zero.2 pi_div_two_pos, pi_div_two_pos.le⟩).trans $ by rw [sin_zero]
@[simp] lemma arcsin_nonpos {x : ℝ} : arcsin x ≤ 0 ↔ x ≤ 0 :=
neg_nonneg.symm.trans $ arcsin_neg x ▸ arcsin_nonneg.trans neg_nonneg
@[simp] lemma arcsin_eq_zero_iff {x : ℝ} : arcsin x = 0 ↔ x = 0 :=
by simp [le_antisymm_iff]
@[simp] lemma zero_eq_arcsin_iff {x} : 0 = arcsin x ↔ x = 0 :=
eq_comm.trans arcsin_eq_zero_iff
@[simp] lemma arcsin_pos {x : ℝ} : 0 < arcsin x ↔ 0 < x :=
lt_iff_lt_of_le_iff_le arcsin_nonpos
@[simp] lemma arcsin_lt_zero {x : ℝ} : arcsin x < 0 ↔ x < 0 :=
lt_iff_lt_of_le_iff_le arcsin_nonneg
@[simp] lemma arcsin_lt_pi_div_two {x : ℝ} : arcsin x < π / 2 ↔ x < 1 :=
(arcsin_lt_iff_lt_sin' (right_mem_Ioc.2 $ neg_lt_self pi_div_two_pos)).trans $
by rw sin_pi_div_two
@[simp] lemma neg_pi_div_two_lt_arcsin {x : ℝ} : -(π / 2) < arcsin x ↔ -1 < x :=
(lt_arcsin_iff_sin_lt' $ left_mem_Ico.2 $ neg_lt_self pi_div_two_pos).trans $
by rw [sin_neg, sin_pi_div_two]
@[simp] lemma arcsin_eq_pi_div_two {x : ℝ} : arcsin x = π / 2 ↔ 1 ≤ x :=
⟨λ h, not_lt.1 $ λ h', (arcsin_lt_pi_div_two.2 h').ne h, arcsin_of_one_le⟩
@[simp] lemma pi_div_two_eq_arcsin {x} : π / 2 = arcsin x ↔ 1 ≤ x :=
eq_comm.trans arcsin_eq_pi_div_two
@[simp] lemma pi_div_two_le_arcsin {x} : π / 2 ≤ arcsin x ↔ 1 ≤ x :=
(arcsin_le_pi_div_two x).le_iff_eq.trans pi_div_two_eq_arcsin
@[simp] lemma arcsin_eq_neg_pi_div_two {x : ℝ} : arcsin x = -(π / 2) ↔ x ≤ -1 :=
⟨λ h, not_lt.1 $ λ h', (neg_pi_div_two_lt_arcsin.2 h').ne' h, arcsin_of_le_neg_one⟩
@[simp] lemma neg_pi_div_two_eq_arcsin {x} : -(π / 2) = arcsin x ↔ x ≤ -1 :=
eq_comm.trans arcsin_eq_neg_pi_div_two
@[simp] lemma arcsin_le_neg_pi_div_two {x} : arcsin x ≤ -(π / 2) ↔ x ≤ -1 :=
(neg_pi_div_two_le_arcsin x).le_iff_eq.trans arcsin_eq_neg_pi_div_two
@[simp] lemma pi_div_four_le_arcsin {x} : π / 4 ≤ arcsin x ↔ sqrt 2 / 2 ≤ x :=
by { rw [← sin_pi_div_four, le_arcsin_iff_sin_le'], have := pi_pos, split; linarith }
lemma maps_to_sin_Ioo : maps_to sin (Ioo (-(π / 2)) (π / 2)) (Ioo (-1) 1) :=
λ x h, by rwa [mem_Ioo, ← arcsin_lt_pi_div_two, ← neg_pi_div_two_lt_arcsin,
arcsin_sin h.1.le h.2.le]
/-- `real.sin` as a `local_homeomorph` between `(-π / 2, π / 2)` and `(-1, 1)`. -/
@[simp] def sin_local_homeomorph : local_homeomorph ℝ ℝ :=
{ to_fun := sin,
inv_fun := arcsin,
source := Ioo (-(π / 2)) (π / 2),
target := Ioo (-1) 1,
map_source' := maps_to_sin_Ioo,
map_target' := λ y hy, ⟨neg_pi_div_two_lt_arcsin.2 hy.1, arcsin_lt_pi_div_two.2 hy.2⟩,
left_inv' := λ x hx, arcsin_sin hx.1.le hx.2.le,
right_inv' := λ y hy, sin_arcsin hy.1.le hy.2.le,
open_source := is_open_Ioo,
open_target := is_open_Ioo,
continuous_to_fun := continuous_sin.continuous_on,
continuous_inv_fun := continuous_arcsin.continuous_on }
lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) :=
cos_nonneg_of_mem_Icc ⟨neg_pi_div_two_le_arcsin _, arcsin_le_pi_div_two _⟩
lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) :=
have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_sq_add_cos_sq (arcsin x),
begin
rw [← eq_sub_iff_add_eq', ← sqrt_inj (sq_nonneg _) (sub_nonneg.2 (sin_sq_le_one (arcsin x))),
sq, sqrt_mul_self (cos_arcsin_nonneg _)] at this,
rw [this, sin_arcsin hx₁ hx₂],
end
/-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`.
If the argument is not between `-1` and `1` it defaults to `π / 2` -/
@[pp_nodot] noncomputable def arccos (x : ℝ) : ℝ :=
π / 2 - arcsin x
lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl
lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x :=
by simp [arccos]
lemma arccos_le_pi (x : ℝ) : arccos x ≤ π :=
by unfold arccos; linarith [neg_pi_div_two_le_arcsin x]
lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x :=
by unfold arccos; linarith [arcsin_le_pi_div_two x]
lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x :=
by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂]
lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x :=
by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp [sub_eq_add_neg]; linarith
lemma strict_anti_on_arccos : strict_anti_on arccos (Icc (-1) 1) :=
λ x hx y hy h, sub_lt_sub_left (strict_mono_on_arcsin hx hy h) _
lemma arccos_inj_on : inj_on arccos (Icc (-1) 1) := strict_anti_on_arccos.inj_on
lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) :
arccos x = arccos y ↔ x = y :=
arccos_inj_on.eq_iff ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩
@[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos]
@[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos]
@[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves]
@[simp] lemma arccos_eq_zero {x} : arccos x = 0 ↔ 1 ≤ x :=
by simp [arccos, sub_eq_zero]
@[simp] lemma arccos_eq_pi_div_two {x} : arccos x = π / 2 ↔ x = 0 :=
by simp [arccos]
@[simp] lemma arccos_eq_pi {x} : arccos x = π ↔ x ≤ -1 :=
by rw [arccos, sub_eq_iff_eq_add, ← sub_eq_iff_eq_add', div_two_sub_self, neg_pi_div_two_eq_arcsin]
lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x :=
by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self, sub_neg_eq_add]
lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) :=
by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂]
@[simp] lemma arccos_le_pi_div_two {x} : arccos x ≤ π / 2 ↔ 0 ≤ x := by simp [arccos]
@[simp] lemma arccos_le_pi_div_four {x} : arccos x ≤ π / 4 ↔ sqrt 2 / 2 ≤ x :=
by { rw [arccos, ← pi_div_four_le_arcsin], split; { intro, linarith } }
@[continuity]
lemma continuous_arccos : continuous arccos := continuous_const.sub continuous_arcsin
end real
|
ddac2f06d840101e0abe22ae0f6595bafc4968a0 | 969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb | /src/category_theory/adjunction/fully_faithful.lean | a1572f5701a6f40c4a929e709194576322ab93a7 | [
"Apache-2.0"
] | permissive | SAAluthwela/mathlib | 62044349d72dd63983a8500214736aa7779634d3 | 83a4b8b990907291421de54a78988c024dc8a552 | refs/heads/master | 1,679,433,873,417 | 1,615,998,031,000 | 1,615,998,031,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,285 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.adjunction.basic
import category_theory.conj
import category_theory.yoneda
open category_theory
namespace category_theory
universes v₁ v₂ u₁ u₂
open category
open opposite
variables {C : Type u₁} [category.{v₁} C]
variables {D : Type u₂} [category.{v₂} D]
variables {L : C ⥤ D} {R : D ⥤ C} (h : L ⊣ R)
/--
If the left adjoint is fully faithful, then the unit is an isomorphism.
See
* Lemma 4.5.13 from [Riehl][riehl2017]
* https://math.stackexchange.com/a/2727177
* https://stacks.math.columbia.edu/tag/07RB (we only prove the forward direction!)
-/
instance unit_is_iso_of_L_fully_faithful [full L] [faithful L] : is_iso (adjunction.unit h) :=
@nat_iso.is_iso_of_is_iso_app _ _ _ _ _ _ (adjunction.unit h) $ λ X,
@yoneda.is_iso _ _ _ _ ((adjunction.unit h).app X)
⟨{ app := λ Y f, L.preimage ((h.hom_equiv (unop Y) (L.obj X)).symm f) },
⟨begin
ext x f, dsimp,
apply L.map_injective,
simp,
end, begin
ext x f, dsimp,
simp only [adjunction.hom_equiv_counit, preimage_comp, preimage_map, category.assoc],
rw ←h.unit_naturality,
simp,
end⟩⟩
/--
If the right adjoint is fully faithful, then the counit is an isomorphism.
See https://stacks.math.columbia.edu/tag/07RB (we only prove the forward direction!)
-/
instance counit_is_iso_of_R_fully_faithful [full R] [faithful R] : is_iso (adjunction.counit h) :=
@nat_iso.is_iso_of_is_iso_app _ _ _ _ _ _ (adjunction.counit h) $ λ X,
@is_iso_of_op _ _ _ _ _ $
@coyoneda.is_iso _ _ _ _ ((adjunction.counit h).app X).op
⟨{ app := λ Y f, R.preimage ((h.hom_equiv (R.obj X) Y) f) },
⟨begin
ext x f, dsimp,
apply R.map_injective,
simp,
end, begin
ext x f, dsimp,
simp only [adjunction.hom_equiv_unit, preimage_comp, preimage_map],
rw ←h.counit_naturality,
simp,
end⟩⟩
-- TODO also prove the converses?
-- def L_full_of_unit_is_iso [is_iso (adjunction.unit h)] : full L := sorry
-- def L_faithful_of_unit_is_iso [is_iso (adjunction.unit h)] : faithful L := sorry
-- def R_full_of_counit_is_iso [is_iso (adjunction.counit h)] : full R := sorry
-- def R_faithful_of_counit_is_iso [is_iso (adjunction.counit h)] : faithful R := sorry
-- TODO also do the statements from Riehl 4.5.13 for full and faithful separately?
universes v₃ v₄ u₃ u₄
variables {C' : Type u₃} [category.{v₃} C']
variables {D' : Type u₄} [category.{v₄} D']
-- TODO: This needs some lemmas describing the produced adjunction, probably in terms of `adj`,
-- `iC` and `iD`.
/--
If `C` is a full subcategory of `C'` and `D` is a full subcategory of `D'`, then we can restrict
an adjunction `L' ⊣ R'` where `L' : C' ⥤ D'` and `R' : D' ⥤ C'` to `C` and `D`.
The construction here is slightly more general, in that `C` is required only to have a full and
faithful "inclusion" functor `iC : C ⥤ C'` (and similarly `iD : D ⥤ D'`) which commute (up to
natural isomorphism) with the proposed restrictions.
-/
def adjunction.restrict_fully_faithful (iC : C ⥤ C') (iD : D ⥤ D') {L' : C' ⥤ D'} {R' : D' ⥤ C'}
(adj : L' ⊣ R') {L : C ⥤ D} {R : D ⥤ C} (comm1 : iC ⋙ L' ≅ L ⋙ iD) (comm2 : iD ⋙ R' ≅ R ⋙ iC)
[full iC] [faithful iC] [full iD] [faithful iD] :
L ⊣ R :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Y,
calc (L.obj X ⟶ Y) ≃ (iD.obj (L.obj X) ⟶ iD.obj Y) : equiv_of_fully_faithful iD
... ≃ (L'.obj (iC.obj X) ⟶ iD.obj Y) : iso.hom_congr (comm1.symm.app X) (iso.refl _)
... ≃ (iC.obj X ⟶ R'.obj (iD.obj Y)) : adj.hom_equiv _ _
... ≃ (iC.obj X ⟶ iC.obj (R.obj Y)) : iso.hom_congr (iso.refl _) (comm2.app Y)
... ≃ (X ⟶ R.obj Y) : (equiv_of_fully_faithful iC).symm,
hom_equiv_naturality_left_symm' := λ X' X Y f g,
begin
apply iD.map_injective,
simpa using (comm1.inv.naturality_assoc f _).symm,
end,
hom_equiv_naturality_right' := λ X Y' Y f g,
begin
apply iC.map_injective,
suffices : R'.map (iD.map g) ≫ comm2.hom.app Y = comm2.hom.app Y' ≫ iC.map (R.map g),
simp [this],
apply comm2.hom.naturality g,
end }
end category_theory
|
088d9d268288fc3ad773e8ff02c223d389b36baa | a4673261e60b025e2c8c825dfa4ab9108246c32e | /src/Lean/Compiler/ImplementedByAttr.lean | 4b2376b90a6b515357f7e308ea522141eec51c8e | [
"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 | 1,513 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Attributes
import Lean.MonadEnv
namespace Lean.Compiler
builtin_initialize implementedByAttr : ParametricAttribute Name ← registerParametricAttribute {
name := `implementedBy,
descr := "name of the Lean (probably unsafe) function that implements opaque constant",
getParam := fun declName stx => do
let decl ← getConstInfo declName
match attrParamSyntaxToIdentifier stx with
| some fnName =>
let fnName ← resolveGlobalConstNoOverload fnName
let fnDecl ← getConstInfo fnName
if decl.type == fnDecl.type then pure fnName
else throwError! "invalid function '{fnName}' type mismatch"
| _ => throwError "expected identifier",
}
@[export lean_get_implemented_by]
def getImplementedBy (env : Environment) (declName : Name) : Option Name :=
implementedByAttr.getParam env declName
def setImplementedBy (env : Environment) (declName : Name) (impName : Name) : Except String Environment :=
implementedByAttr.setParam env declName impName
end Compiler
def setImplementedBy {m} [Monad m] [MonadEnv m] [MonadExceptOf Exception m] [MonadRef m] [AddErrorMessageContext m]
(declName : Name) (impName : Name) : m Unit := do
let env ← getEnv
match Compiler.setImplementedBy env declName impName with
| Except.ok env => setEnv env
| Except.error ex => throwError ex
end Lean
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.