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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5114ebfaa4ec51c1f8b97abcf6a0460cf08ea3ff | 592ee40978ac7604005a4e0d35bbc4b467389241 | /Library/generated/mathscheme-lean/TwoPointed.lean | e2439f9476aec09aeabc13de776dfbae7ed2fc4a | [] | no_license | ysharoda/Deriving-Definitions | 3e149e6641fae440badd35ac110a0bd705a49ad2 | dfecb27572022de3d4aa702cae8db19957523a59 | refs/heads/master | 1,679,127,857,700 | 1,615,939,007,000 | 1,615,939,007,000 | 229,785,731 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,918 | lean | import init.data.nat.basic
import init.data.fin.basic
import data.vector
import .Prelude
open Staged
open nat
open fin
open vector
section TwoPointed
structure TwoPointed (A : Type) : Type :=
(e1 : A)
(e2 : A)
open TwoPointed
structure Sig (AS : Type) : Type :=
(e1S : AS)
(e2S : AS)
structure Product (A : Type) : Type :=
(e1P : (Prod A A))
(e2P : (Prod A A))
structure Hom {A1 : Type} {A2 : Type} (Tw1 : (TwoPointed A1)) (Tw2 : (TwoPointed A2)) : Type :=
(hom : (A1 → A2))
(pres_e1 : (hom (e1 Tw1)) = (e1 Tw2))
(pres_e2 : (hom (e2 Tw1)) = (e2 Tw2))
structure RelInterp {A1 : Type} {A2 : Type} (Tw1 : (TwoPointed A1)) (Tw2 : (TwoPointed A2)) : Type 1 :=
(interp : (A1 → (A2 → Type)))
(interp_e1 : (interp (e1 Tw1) (e1 Tw2)))
(interp_e2 : (interp (e2 Tw1) (e2 Tw2)))
inductive TwoPointedTerm : Type
| e1L : TwoPointedTerm
| e2L : TwoPointedTerm
open TwoPointedTerm
inductive ClTwoPointedTerm (A : Type) : Type
| sing : (A → ClTwoPointedTerm)
| e1Cl : ClTwoPointedTerm
| e2Cl : ClTwoPointedTerm
open ClTwoPointedTerm
inductive OpTwoPointedTerm (n : ℕ) : Type
| v : ((fin n) → OpTwoPointedTerm)
| e1OL : OpTwoPointedTerm
| e2OL : OpTwoPointedTerm
open OpTwoPointedTerm
inductive OpTwoPointedTerm2 (n : ℕ) (A : Type) : Type
| v2 : ((fin n) → OpTwoPointedTerm2)
| sing2 : (A → OpTwoPointedTerm2)
| e1OL2 : OpTwoPointedTerm2
| e2OL2 : OpTwoPointedTerm2
open OpTwoPointedTerm2
def simplifyCl {A : Type} : ((ClTwoPointedTerm A) → (ClTwoPointedTerm A))
| e1Cl := e1Cl
| e2Cl := e2Cl
| (sing x1) := (sing x1)
def simplifyOpB {n : ℕ} : ((OpTwoPointedTerm n) → (OpTwoPointedTerm n))
| e1OL := e1OL
| e2OL := e2OL
| (v x1) := (v x1)
def simplifyOp {n : ℕ} {A : Type} : ((OpTwoPointedTerm2 n A) → (OpTwoPointedTerm2 n A))
| e1OL2 := e1OL2
| e2OL2 := e2OL2
| (v2 x1) := (v2 x1)
| (sing2 x1) := (sing2 x1)
def evalB {A : Type} : ((TwoPointed A) → (TwoPointedTerm → A))
| Tw e1L := (e1 Tw)
| Tw e2L := (e2 Tw)
def evalCl {A : Type} : ((TwoPointed A) → ((ClTwoPointedTerm A) → A))
| Tw (sing x1) := x1
| Tw e1Cl := (e1 Tw)
| Tw e2Cl := (e2 Tw)
def evalOpB {A : Type} {n : ℕ} : ((TwoPointed A) → ((vector A n) → ((OpTwoPointedTerm n) → A)))
| Tw vars (v x1) := (nth vars x1)
| Tw vars e1OL := (e1 Tw)
| Tw vars e2OL := (e2 Tw)
def evalOp {A : Type} {n : ℕ} : ((TwoPointed A) → ((vector A n) → ((OpTwoPointedTerm2 n A) → A)))
| Tw vars (v2 x1) := (nth vars x1)
| Tw vars (sing2 x1) := x1
| Tw vars e1OL2 := (e1 Tw)
| Tw vars e2OL2 := (e2 Tw)
def inductionB {P : (TwoPointedTerm → Type)} : ((P e1L) → ((P e2L) → (∀ (x : TwoPointedTerm) , (P x))))
| pe1l pe2l e1L := pe1l
| pe1l pe2l e2L := pe2l
def inductionCl {A : Type} {P : ((ClTwoPointedTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((P e1Cl) → ((P e2Cl) → (∀ (x : (ClTwoPointedTerm A)) , (P x)))))
| psing pe1cl pe2cl (sing x1) := (psing x1)
| psing pe1cl pe2cl e1Cl := pe1cl
| psing pe1cl pe2cl e2Cl := pe2cl
def inductionOpB {n : ℕ} {P : ((OpTwoPointedTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((P e1OL) → ((P e2OL) → (∀ (x : (OpTwoPointedTerm n)) , (P x)))))
| pv pe1ol pe2ol (v x1) := (pv x1)
| pv pe1ol pe2ol e1OL := pe1ol
| pv pe1ol pe2ol e2OL := pe2ol
def inductionOp {n : ℕ} {A : Type} {P : ((OpTwoPointedTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((P e1OL2) → ((P e2OL2) → (∀ (x : (OpTwoPointedTerm2 n A)) , (P x))))))
| pv2 psing2 pe1ol2 pe2ol2 (v2 x1) := (pv2 x1)
| pv2 psing2 pe1ol2 pe2ol2 (sing2 x1) := (psing2 x1)
| pv2 psing2 pe1ol2 pe2ol2 e1OL2 := pe1ol2
| pv2 psing2 pe1ol2 pe2ol2 e2OL2 := pe2ol2
def stageB : (TwoPointedTerm → (Staged TwoPointedTerm))
| e1L := (Now e1L)
| e2L := (Now e2L)
def stageCl {A : Type} : ((ClTwoPointedTerm A) → (Staged (ClTwoPointedTerm A)))
| (sing x1) := (Now (sing x1))
| e1Cl := (Now e1Cl)
| e2Cl := (Now e2Cl)
def stageOpB {n : ℕ} : ((OpTwoPointedTerm n) → (Staged (OpTwoPointedTerm n)))
| (v x1) := (const (code (v x1)))
| e1OL := (Now e1OL)
| e2OL := (Now e2OL)
def stageOp {n : ℕ} {A : Type} : ((OpTwoPointedTerm2 n A) → (Staged (OpTwoPointedTerm2 n A)))
| (sing2 x1) := (Now (sing2 x1))
| (v2 x1) := (const (code (v2 x1)))
| e1OL2 := (Now e1OL2)
| e2OL2 := (Now e2OL2)
structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type :=
(e1T : (Repr A))
(e2T : (Repr A))
end TwoPointed |
18c8fd300c90b2c83d14f83cba21495c5982233b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/data/nat/basic_auto.lean | 1b13a21c7db73bc810e6f3a4c16823b3873cdf20 | [] | 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 | 5,388 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.logic
universes u
namespace Mathlib
namespace nat
notation:1024 "ℕ" => Mathlib.nat
inductive less_than_or_equal (a : ℕ) : ℕ → Prop where
| refl : less_than_or_equal a a
| step : ∀ {b : ℕ}, less_than_or_equal a b → less_than_or_equal a (Nat.succ b)
protected instance has_le : HasLessEq ℕ := { LessEq := less_than_or_equal }
protected def le (n : ℕ) (m : ℕ) := less_than_or_equal n m
protected def lt (n : ℕ) (m : ℕ) := less_than_or_equal (Nat.succ n) m
protected instance has_lt : HasLess ℕ := { Less := nat.lt }
def pred : ℕ → ℕ := Nat.pred
protected def sub : ℕ → ℕ → ℕ := Nat.sub
protected def mul : ℕ → ℕ → ℕ := Nat.mul
protected instance has_sub : Sub ℕ := { sub := Nat.sub }
protected instance has_mul : Mul ℕ := { mul := Nat.mul }
-- defeq to the instance provided by comm_semiring
protected instance has_dvd : has_dvd ℕ := has_dvd.mk fun (a b : ℕ) => ∃ (c : ℕ), b = a * c
protected instance decidable_eq : DecidableEq ℕ := sorry
def repeat {α : Type u} (f : ℕ → α → α) : ℕ → α → α := sorry
protected instance inhabited : Inhabited ℕ := { default := 0 }
@[simp] theorem nat_zero_eq_zero : 0 = 0 := rfl
/- properties of inequality -/
protected def le_refl (a : ℕ) : a ≤ a := less_than_or_equal.refl
theorem le_succ (n : ℕ) : n ≤ Nat.succ n := less_than_or_equal.step (nat.le_refl n)
theorem succ_le_succ {n : ℕ} {m : ℕ} : n ≤ m → Nat.succ n ≤ Nat.succ m :=
fun (h : n ≤ m) =>
less_than_or_equal._oldrec (nat.le_refl (Nat.succ n))
(fun (a : ℕ) (b : less_than_or_equal n a) => less_than_or_equal.step) h
theorem zero_le (n : ℕ) : 0 ≤ n := sorry
theorem zero_lt_succ (n : ℕ) : 0 < Nat.succ n := succ_le_succ (zero_le n)
def succ_pos (n : ℕ) : 0 < Nat.succ n := zero_lt_succ
theorem not_succ_le_zero (n : ℕ) : Nat.succ n ≤ 0 → False := sorry
theorem not_lt_zero (a : ℕ) : ¬a < 0 := not_succ_le_zero a
theorem pred_le_pred {n : ℕ} {m : ℕ} : n ≤ m → Nat.pred n ≤ Nat.pred m := sorry
theorem le_of_succ_le_succ {n : ℕ} {m : ℕ} : Nat.succ n ≤ Nat.succ m → n ≤ m := pred_le_pred
protected instance decidable_le (a : ℕ) (b : ℕ) : Decidable (a ≤ b) := sorry
protected instance decidable_lt (a : ℕ) (b : ℕ) : Decidable (a < b) :=
nat.decidable_le (Nat.succ a) b
protected theorem eq_or_lt_of_le {a : ℕ} {b : ℕ} (h : a ≤ b) : a = b ∨ a < b :=
less_than_or_equal.cases_on h (Or.inl rfl)
fun (n : ℕ) (h : less_than_or_equal a n) => Or.inr (succ_le_succ h)
theorem lt_succ_of_le {a : ℕ} {b : ℕ} : a ≤ b → a < Nat.succ b := succ_le_succ
@[simp] theorem succ_sub_succ_eq_sub (a : ℕ) (b : ℕ) : Nat.succ a - Nat.succ b = a - b :=
nat.rec_on b ((fun (this : Nat.succ a - 1 = a - 0) => this) (Eq.refl (Nat.succ a - 1)))
fun (b : ℕ) => congr_arg Nat.pred
theorem not_succ_le_self (n : ℕ) : ¬Nat.succ n ≤ n :=
Nat.rec (not_succ_le_zero 0)
(fun (a : ℕ) (b : ¬Nat.succ a ≤ a) (c : Nat.succ (Nat.succ a) ≤ Nat.succ a) =>
b (le_of_succ_le_succ c))
n
protected theorem lt_irrefl (n : ℕ) : ¬n < n := not_succ_le_self n
protected theorem le_trans {n : ℕ} {m : ℕ} {k : ℕ} (h1 : n ≤ m) : m ≤ k → n ≤ k :=
less_than_or_equal._oldrec h1 fun (p : ℕ) (h2 : less_than_or_equal m p) => less_than_or_equal.step
theorem pred_le (n : ℕ) : Nat.pred n ≤ n :=
nat.cases_on n (idRhs (less_than_or_equal (Nat.pred 0) (Nat.pred 0)) less_than_or_equal.refl)
fun (n : ℕ) =>
idRhs (less_than_or_equal (Nat.pred (Nat.succ n)) (Nat.succ n))
(less_than_or_equal.step less_than_or_equal.refl)
theorem pred_lt {n : ℕ} : n ≠ 0 → Nat.pred n < n := sorry
theorem sub_le (a : ℕ) (b : ℕ) : a - b ≤ a :=
nat.rec_on b (nat.le_refl (a - 0)) fun (b₁ : ℕ) => nat.le_trans (pred_le (a - b₁))
theorem sub_lt {a : ℕ} {b : ℕ} : 0 < a → 0 < b → a - b < a := sorry
protected theorem lt_of_lt_of_le {n : ℕ} {m : ℕ} {k : ℕ} : n < m → m ≤ k → n < k := nat.le_trans
/- Basic nat.add lemmas -/
protected theorem zero_add (n : ℕ) : 0 + n = n := sorry
theorem succ_add (n : ℕ) (m : ℕ) : Nat.succ n + m = Nat.succ (n + m) := sorry
theorem add_succ (n : ℕ) (m : ℕ) : n + Nat.succ m = Nat.succ (n + m) := rfl
protected theorem add_zero (n : ℕ) : n + 0 = n := rfl
theorem add_one (n : ℕ) : n + 1 = Nat.succ n := rfl
theorem succ_eq_add_one (n : ℕ) : Nat.succ n = n + 1 := rfl
/- Basic lemmas for comparing numerals -/
protected theorem bit0_succ_eq (n : ℕ) : bit0 (Nat.succ n) = Nat.succ (Nat.succ (bit0 n)) :=
(fun (this : Nat.succ (Nat.succ n + n) = Nat.succ (Nat.succ (n + n))) => this)
(congr_arg Nat.succ (succ_add n n))
protected theorem zero_lt_bit0 {n : ℕ} : n ≠ 0 → 0 < bit0 n := sorry
protected theorem zero_lt_bit1 (n : ℕ) : 0 < bit1 n := zero_lt_succ (bit0 n)
protected theorem bit0_ne_zero {n : ℕ} : n ≠ 0 → bit0 n ≠ 0 := sorry
protected theorem bit1_ne_zero (n : ℕ) : bit1 n ≠ 0 :=
(fun (this : Nat.succ (n + n) ≠ 0) => this) fun (h : Nat.succ (n + n) = 0) => nat.no_confusion h
end Mathlib |
0d93b875e5cbf48cb8cd3d127c0bc816eb3b5b30 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/abelian/basic.lean | 1d0d3e8df9ed45badaa8a48119ee47e9c92f1d21 | [
"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 | 30,104 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel, Johan Commelin, Scott Morrison
-/
import category_theory.limits.constructions.pullbacks
import category_theory.limits.shapes.biproducts
import category_theory.limits.shapes.images
import category_theory.limits.constructions.limits_of_products_and_equalizers
import category_theory.limits.constructions.epi_mono
import category_theory.abelian.non_preadditive
/-!
# Abelian categories
This file contains the definition and basic properties of abelian categories.
There are many definitions of abelian category. Our definition is as follows:
A category is called abelian if it is preadditive,
has a finite products, kernels and cokernels,
and if every monomorphism and epimorphism is normal.
It should be noted that if we also assume coproducts, then preadditivity is
actually a consequence of the other properties, as we show in
`non_preadditive_abelian.lean`. However, this fact is of little practical
relevance, since essentially all interesting abelian categories come with a
preadditive structure. In this way, by requiring preadditivity, we allow the
user to pass in the "native" preadditive structure for the specific category they are
working with.
## Main definitions
* `abelian` is the type class indicating that a category is abelian. It extends `preadditive`.
* `abelian.image f` is `kernel (cokernel.π f)`, and
* `abelian.coimage f` is `cokernel (kernel.ι f)`.
## Main results
* In an abelian category, mono + epi = iso.
* If `f : X ⟶ Y`, then the map `factor_thru_image f : X ⟶ image f` is an epimorphism, and the map
`factor_thru_coimage f : coimage f ⟶ Y` is a monomorphism.
* Factoring through the image and coimage is a strong epi-mono factorisation. This means that
* every abelian category has images. We provide the isomorphism
`image_iso_image : abelian.image f ≅ limits.image f`.
* the canonical morphism `coimage_image_comparison : coimage f ⟶ image f`
is an isomorphism.
* We provide the alternate characterisation of an abelian category as a category with
(co)kernels and finite products, and in which the canonical coimage-image comparison morphism
is always an isomorphism.
* Every epimorphism is a cokernel of its kernel. Every monomorphism is a kernel of its cokernel.
* The pullback of an epimorphism is an epimorphism. The pushout of a monomorphism is a monomorphism.
(This is not to be confused with the fact that the pullback of a monomorphism is a monomorphism,
which is true in any category).
## Implementation notes
The typeclass `abelian` does not extend `non_preadditive_abelian`,
to avoid having to deal with comparing the two `has_zero_morphisms` instances
(one from `preadditive` in `abelian`, and the other a field of `non_preadditive_abelian`).
As a consequence, at the beginning of this file we trivially build
a `non_preadditive_abelian` instance from an `abelian` instance,
and use this to restate a number of theorems,
in each case just reusing the proof from `non_preadditive_abelian.lean`.
We don't show this yet, but abelian categories are finitely complete and finitely cocomplete.
However, the limits we can construct at this level of generality will most likely be less nice than
the ones that can be created in specific applications. For this reason, we adopt the following
convention:
* If the statement of a theorem involves limits, the existence of these limits should be made an
explicit typeclass parameter.
* If a limit only appears in a proof, but not in the statement of a theorem, the limit should not
be a typeclass parameter, but instead be created using `abelian.has_pullbacks` or a similar
definition.
## References
* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]
* [P. Aluffi, *Algebra: Chapter 0*][aluffi2016]
-/
noncomputable theory
open category_theory
open category_theory.preadditive
open category_theory.limits
universes v u
namespace category_theory
variables {C : Type u} [category.{v} C]
variables (C)
/--
A (preadditive) category `C` is called abelian if it has all finite products,
all kernels and cokernels, and if every monomorphism is the kernel of some morphism
and every epimorphism is the cokernel of some morphism.
(This definition implies the existence of zero objects:
finite products give a terminal object, and in a preadditive category
any terminal object is a zero object.)
-/
class abelian extends preadditive C, normal_mono_category C, normal_epi_category C :=
[has_finite_products : has_finite_products C]
[has_kernels : has_kernels C]
[has_cokernels : has_cokernels C]
attribute [instance, priority 100] abelian.has_finite_products
attribute [instance, priority 100] abelian.has_kernels abelian.has_cokernels
end category_theory
open category_theory
/-!
We begin by providing an alternative constructor:
a preadditive category with kernels, cokernels, and finite products,
in which the coimage-image comparison morphism is always an isomorphism,
is an abelian category.
-/
namespace category_theory.abelian
variables {C : Type u} [category.{v} C] [preadditive C]
variables [limits.has_kernels C] [limits.has_cokernels C]
namespace of_coimage_image_comparison_is_iso
/-- The factorisation of a morphism through its abelian image. -/
@[simps]
def image_mono_factorisation {X Y : C} (f : X ⟶ Y) : mono_factorisation f :=
{ I := abelian.image f,
m := kernel.ι _,
m_mono := infer_instance,
e := kernel.lift _ f (cokernel.condition _),
fac' := kernel.lift_ι _ _ _ }
lemma image_mono_factorisation_e' {X Y : C} (f : X ⟶ Y) :
(image_mono_factorisation f).e = cokernel.π _ ≫ abelian.coimage_image_comparison f :=
begin
ext,
simp only [abelian.coimage_image_comparison, image_mono_factorisation_e,
category.assoc, cokernel.π_desc_assoc],
end
/-- If the coimage-image comparison morphism for a morphism `f` is an isomorphism,
we obtain an image factorisation of `f`. -/
def image_factorisation {X Y : C} (f : X ⟶ Y) [is_iso (abelian.coimage_image_comparison f)] :
image_factorisation f :=
{ F := image_mono_factorisation f,
is_image :=
{ lift := λ F, inv (abelian.coimage_image_comparison f) ≫ cokernel.desc _ F.e F.kernel_ι_comp,
lift_fac' := λ F, begin
simp only [image_mono_factorisation_m, is_iso.inv_comp_eq, category.assoc,
abelian.coimage_image_comparison],
ext,
rw [limits.coequalizer.π_desc_assoc, limits.coequalizer.π_desc_assoc, F.fac, kernel.lift_ι]
end } }
instance [has_zero_object C] {X Y : C} (f : X ⟶ Y) [mono f]
[is_iso (abelian.coimage_image_comparison f)] :
is_iso (image_mono_factorisation f).e :=
by { rw image_mono_factorisation_e', exact is_iso.comp_is_iso }
instance [has_zero_object C] {X Y : C} (f : X ⟶ Y) [epi f] :
is_iso (image_mono_factorisation f).m :=
by { dsimp, apply_instance }
variables [∀ {X Y : C} (f : X ⟶ Y), is_iso (abelian.coimage_image_comparison f)]
/-- A category in which coimage-image comparisons are all isomorphisms has images. -/
lemma has_images : has_images C :=
{ has_image := λ X Y f,
{ exists_image := ⟨image_factorisation f⟩ } }
variables [limits.has_finite_products C]
local attribute [instance] limits.has_finite_biproducts.of_has_finite_products
/--
A category with finite products in which coimage-image comparisons are all isomorphisms
is a normal mono category.
-/
def normal_mono_category : normal_mono_category C :=
{ normal_mono_of_mono := λ X Y f m,
{ Z := _,
g := cokernel.π f,
w := by simp,
is_limit := begin
haveI : limits.has_images C := has_images,
haveI : has_equalizers C := preadditive.has_equalizers_of_has_kernels,
haveI : has_zero_object C := limits.has_zero_object_of_has_finite_biproducts _,
have aux : _ := _,
refine is_limit_aux _ (λ A, limit.lift _ _ ≫ inv (image_mono_factorisation f).e) aux _,
{ intros A g hg,
rw [kernel_fork.ι_of_ι] at hg,
rw [← cancel_mono f, hg, ← aux, kernel_fork.ι_of_ι], },
{ intro A,
simp only [kernel_fork.ι_of_ι, category.assoc],
convert limit.lift_π _ _ using 2,
rw [is_iso.inv_comp_eq, eq_comm],
exact (image_mono_factorisation f).fac, },
end }, }
/--
A category with finite products in which coimage-image comparisons are all isomorphisms
is a normal epi category.
-/
def normal_epi_category : normal_epi_category C :=
{ normal_epi_of_epi := λ X Y f m,
{ W := kernel f,
g := kernel.ι _,
w := kernel.condition _,
is_colimit := begin
haveI : limits.has_images C := has_images,
haveI : has_equalizers C := preadditive.has_equalizers_of_has_kernels,
haveI : has_zero_object C := limits.has_zero_object_of_has_finite_biproducts _,
have aux : _ := _,
refine is_colimit_aux _
(λ A, inv (image_mono_factorisation f).m ≫
inv (abelian.coimage_image_comparison f) ≫ colimit.desc _ _)
aux _,
{ intros A g hg,
rw [cokernel_cofork.π_of_π] at hg,
rw [← cancel_epi f, hg, ← aux, cokernel_cofork.π_of_π], },
{ intro A,
simp only [cokernel_cofork.π_of_π, ← category.assoc],
convert colimit.ι_desc _ _ using 2,
rw [is_iso.comp_inv_eq, is_iso.comp_inv_eq, eq_comm, ←image_mono_factorisation_e'],
exact (image_mono_factorisation f).fac, }
end }, }
end of_coimage_image_comparison_is_iso
variables [∀ {X Y : C} (f : X ⟶ Y), is_iso (abelian.coimage_image_comparison f)]
[limits.has_finite_products C]
local attribute [instance] of_coimage_image_comparison_is_iso.normal_mono_category
local attribute [instance] of_coimage_image_comparison_is_iso.normal_epi_category
/--
A preadditive category with kernels, cokernels, and finite products,
in which the coimage-image comparison morphism is always an isomorphism,
is an abelian category.
The Stacks project uses this characterisation at the definition of an abelian category.
See <https://stacks.math.columbia.edu/tag/0109>.
-/
def of_coimage_image_comparison_is_iso : abelian C := {}
end category_theory.abelian
namespace category_theory.abelian
variables {C : Type u} [category.{v} C] [abelian C]
/-- An abelian category has finite biproducts. -/
@[priority 100]
instance has_finite_biproducts : has_finite_biproducts C :=
limits.has_finite_biproducts.of_has_finite_products
@[priority 100]
instance has_binary_biproducts : has_binary_biproducts C :=
limits.has_binary_biproducts_of_finite_biproducts _
@[priority 100]
instance has_zero_object : has_zero_object C :=
has_zero_object_of_has_initial_object
section to_non_preadditive_abelian
/-- Every abelian category is, in particular, `non_preadditive_abelian`. -/
def non_preadditive_abelian : non_preadditive_abelian C := { ..‹abelian C› }
end to_non_preadditive_abelian
section
/-! We now promote some instances that were constructed using `non_preadditive_abelian`. -/
local attribute [instance] non_preadditive_abelian
variables {P Q : C} (f : P ⟶ Q)
/-- The map `p : P ⟶ image f` is an epimorphism -/
instance : epi (abelian.factor_thru_image f) := by apply_instance
instance is_iso_factor_thru_image [mono f] : is_iso (abelian.factor_thru_image f) :=
by apply_instance
/-- The canonical morphism `i : coimage f ⟶ Q` is a monomorphism -/
instance : mono (abelian.factor_thru_coimage f) := by apply_instance
instance is_iso_factor_thru_coimage [epi f] : is_iso (abelian.factor_thru_coimage f) :=
by apply_instance
end
section factor
local attribute [instance] non_preadditive_abelian
variables {P Q : C} (f : P ⟶ Q)
section
lemma mono_of_kernel_ι_eq_zero (h : kernel.ι f = 0) : mono f :=
mono_of_kernel_zero h
lemma epi_of_cokernel_π_eq_zero (h : cokernel.π f = 0) : epi f :=
begin
apply normal_mono_category.epi_of_zero_cokernel _ (cokernel f),
simp_rw ←h,
exact is_colimit.of_iso_colimit (colimit.is_colimit (parallel_pair f 0)) (iso_of_π _)
end
end
section
variables {f}
lemma image_ι_comp_eq_zero {R : C} {g : Q ⟶ R} (h : f ≫ g = 0) : abelian.image.ι f ≫ g = 0 :=
zero_of_epi_comp (abelian.factor_thru_image f) $ by simp [h]
lemma comp_coimage_π_eq_zero {R : C} {g : Q ⟶ R} (h : f ≫ g = 0) : f ≫ abelian.coimage.π g = 0 :=
zero_of_comp_mono (abelian.factor_thru_coimage g) $ by simp [h]
end
/-- Factoring through the image is a strong epi-mono factorisation. -/
@[simps] def image_strong_epi_mono_factorisation : strong_epi_mono_factorisation f :=
{ I := abelian.image f,
m := image.ι f,
m_mono := by apply_instance,
e := abelian.factor_thru_image f,
e_strong_epi := strong_epi_of_epi _ }
/-- Factoring through the coimage is a strong epi-mono factorisation. -/
@[simps] def coimage_strong_epi_mono_factorisation : strong_epi_mono_factorisation f :=
{ I := abelian.coimage f,
m := abelian.factor_thru_coimage f,
m_mono := by apply_instance,
e := coimage.π f,
e_strong_epi := strong_epi_of_epi _ }
end factor
section has_strong_epi_mono_factorisations
/-- An abelian category has strong epi-mono factorisations. -/
@[priority 100] instance : has_strong_epi_mono_factorisations C :=
has_strong_epi_mono_factorisations.mk $ λ X Y f, image_strong_epi_mono_factorisation f
/- In particular, this means that it has well-behaved images. -/
example : has_images C := by apply_instance
example : has_image_maps C := by apply_instance
end has_strong_epi_mono_factorisations
section images
variables {X Y : C} (f : X ⟶ Y)
/--
The coimage-image comparison morphism is always an isomorphism in an abelian category.
See `category_theory.abelian.of_coimage_image_comparison_is_iso` for the converse.
-/
instance : is_iso (coimage_image_comparison f) :=
begin
convert is_iso.of_iso (is_image.iso_ext (coimage_strong_epi_mono_factorisation f).to_mono_is_image
(image_strong_epi_mono_factorisation f).to_mono_is_image),
ext,
change _ = _ ≫ (image_strong_epi_mono_factorisation f).m,
simp [-image_strong_epi_mono_factorisation_to_mono_factorisation_m]
end
/-- There is a canonical isomorphism between the abelian coimage and the abelian image of a
morphism. -/
abbreviation coimage_iso_image : abelian.coimage f ≅ abelian.image f :=
as_iso (coimage_image_comparison f)
/-- There is a canonical isomorphism between the abelian coimage and the categorical image of a
morphism. -/
abbreviation coimage_iso_image' : abelian.coimage f ≅ image f :=
is_image.iso_ext (coimage_strong_epi_mono_factorisation f).to_mono_is_image
(image.is_image f)
/-- There is a canonical isomorphism between the abelian image and the categorical image of a
morphism. -/
abbreviation image_iso_image : abelian.image f ≅ image f :=
is_image.iso_ext (image_strong_epi_mono_factorisation f).to_mono_is_image (image.is_image f)
end images
section cokernel_of_kernel
variables {X Y : C} {f : X ⟶ Y}
local attribute [instance] non_preadditive_abelian
/-- In an abelian category, an epi is the cokernel of its kernel. More precisely:
If `f` is an epimorphism and `s` is some limit kernel cone on `f`, then `f` is a cokernel
of `fork.ι s`. -/
def epi_is_cokernel_of_kernel [epi f] (s : fork f 0) (h : is_limit s) :
is_colimit (cokernel_cofork.of_π f (kernel_fork.condition s)) :=
non_preadditive_abelian.epi_is_cokernel_of_kernel s h
/-- In an abelian category, a mono is the kernel of its cokernel. More precisely:
If `f` is a monomorphism and `s` is some colimit cokernel cocone on `f`, then `f` is a kernel
of `cofork.π s`. -/
def mono_is_kernel_of_cokernel [mono f] (s : cofork f 0) (h : is_colimit s) :
is_limit (kernel_fork.of_ι f (cokernel_cofork.condition s)) :=
non_preadditive_abelian.mono_is_kernel_of_cokernel s h
variables (f)
/-- In an abelian category, any morphism that turns to zero when precomposed with the kernel of an
epimorphism factors through that epimorphism. -/
def epi_desc [epi f] {T : C} (g : X ⟶ T) (hg : kernel.ι f ≫ g = 0) : Y ⟶ T :=
(epi_is_cokernel_of_kernel _ (limit.is_limit _)).desc (cokernel_cofork.of_π _ hg)
@[simp, reassoc]
lemma comp_epi_desc [epi f] {T : C} (g : X ⟶ T) (hg : kernel.ι f ≫ g = 0) :
f ≫ epi_desc f g hg = g :=
(epi_is_cokernel_of_kernel _ (limit.is_limit _)).fac (cokernel_cofork.of_π _ hg)
walking_parallel_pair.one
/-- In an abelian category, any morphism that turns to zero when postcomposed with the cokernel of a
monomorphism factors through that monomorphism. -/
def mono_lift [mono f] {T : C} (g : T ⟶ Y) (hg : g ≫ cokernel.π f = 0) : T ⟶ X :=
(mono_is_kernel_of_cokernel _ (colimit.is_colimit _)).lift (kernel_fork.of_ι _ hg)
@[simp, reassoc]
lemma mono_lift_comp [mono f] {T : C} (g : T ⟶ Y) (hg : g ≫ cokernel.π f = 0) :
mono_lift f g hg ≫ f = g :=
(mono_is_kernel_of_cokernel _ (colimit.is_colimit _)).fac (kernel_fork.of_ι _ hg)
walking_parallel_pair.zero
end cokernel_of_kernel
section
@[priority 100]
instance has_equalizers : has_equalizers C :=
preadditive.has_equalizers_of_has_kernels
/-- Any abelian category has pullbacks -/
@[priority 100]
instance has_pullbacks : has_pullbacks C :=
has_pullbacks_of_has_binary_products_of_has_equalizers C
end
section
@[priority 100]
instance has_coequalizers : has_coequalizers C :=
preadditive.has_coequalizers_of_has_cokernels
/-- Any abelian category has pushouts -/
@[priority 100]
instance has_pushouts : has_pushouts C :=
has_pushouts_of_has_binary_coproducts_of_has_coequalizers C
@[priority 100]
instance has_finite_limits : has_finite_limits C :=
limits.has_finite_limits_of_has_equalizers_and_finite_products
@[priority 100]
instance has_finite_colimits : has_finite_colimits C :=
limits.has_finite_colimits_of_has_coequalizers_and_finite_coproducts
end
namespace pullback_to_biproduct_is_kernel
variables [limits.has_pullbacks C] {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z)
/-! This section contains a slightly technical result about pullbacks and biproducts.
We will need it in the proof that the pullback of an epimorphism is an epimorpism. -/
/-- The canonical map `pullback f g ⟶ X ⊞ Y` -/
abbreviation pullback_to_biproduct : pullback f g ⟶ X ⊞ Y :=
biprod.lift pullback.fst pullback.snd
/-- The canonical map `pullback f g ⟶ X ⊞ Y` induces a kernel cone on the map
`biproduct X Y ⟶ Z` induced by `f` and `g`. A slightly more intuitive way to think of
this may be that it induces an equalizer fork on the maps induced by `(f, 0)` and
`(0, g)`. -/
abbreviation pullback_to_biproduct_fork : kernel_fork (biprod.desc f (-g)) :=
kernel_fork.of_ι (pullback_to_biproduct f g) $
by rw [biprod.lift_desc, comp_neg, pullback.condition, add_right_neg]
/-- The canonical map `pullback f g ⟶ X ⊞ Y` is a kernel of the map induced by
`(f, -g)`. -/
def is_limit_pullback_to_biproduct : is_limit (pullback_to_biproduct_fork f g) :=
fork.is_limit.mk _
(λ s, pullback.lift (fork.ι s ≫ biprod.fst) (fork.ι s ≫ biprod.snd) $
sub_eq_zero.1 $ by rw [category.assoc, category.assoc, ←comp_sub, sub_eq_add_neg, ←comp_neg,
←biprod.desc_eq, kernel_fork.condition s])
(λ s,
begin
ext; rw [fork.ι_of_ι, category.assoc],
{ rw [biprod.lift_fst, pullback.lift_fst] },
{ rw [biprod.lift_snd, pullback.lift_snd] }
end)
(λ s m h, by ext; simp [←h])
end pullback_to_biproduct_is_kernel
namespace biproduct_to_pushout_is_cokernel
variables [limits.has_pushouts C] {W X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z)
/-- The canonical map `Y ⊞ Z ⟶ pushout f g` -/
abbreviation biproduct_to_pushout : Y ⊞ Z ⟶ pushout f g :=
biprod.desc pushout.inl pushout.inr
/-- The canonical map `Y ⊞ Z ⟶ pushout f g` induces a cokernel cofork on the map
`X ⟶ Y ⊞ Z` induced by `f` and `-g`. -/
abbreviation biproduct_to_pushout_cofork : cokernel_cofork (biprod.lift f (-g)) :=
cokernel_cofork.of_π (biproduct_to_pushout f g) $
by rw [biprod.lift_desc, neg_comp, pushout.condition, add_right_neg]
/-- The cofork induced by the canonical map `Y ⊞ Z ⟶ pushout f g` is in fact a colimit cokernel
cofork. -/
def is_colimit_biproduct_to_pushout : is_colimit (biproduct_to_pushout_cofork f g) :=
cofork.is_colimit.mk _
(λ s, pushout.desc (biprod.inl ≫ cofork.π s) (biprod.inr ≫ cofork.π s) $
sub_eq_zero.1 $ by rw [←category.assoc, ←category.assoc, ←sub_comp, sub_eq_add_neg, ←neg_comp,
←biprod.lift_eq, cofork.condition s, zero_comp])
(λ s, by ext; simp)
(λ s m h, by ext; simp [←h] )
end biproduct_to_pushout_is_cokernel
section epi_pullback
variables [limits.has_pullbacks C] {W X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z)
/-- In an abelian category, the pullback of an epimorphism is an epimorphism.
Proof from [aluffi2016, IX.2.3], cf. [borceux-vol2, 1.7.6] -/
instance epi_pullback_of_epi_f [epi f] : epi (pullback.snd : pullback f g ⟶ Y) :=
-- It will suffice to consider some morphism e : Y ⟶ R such that
-- pullback.snd ≫ e = 0 and show that e = 0.
epi_of_cancel_zero _ $ λ R e h,
begin
-- Consider the morphism u := (0, e) : X ⊞ Y⟶ R.
let u := biprod.desc (0 : X ⟶ R) e,
-- The composite pullback f g ⟶ X ⊞ Y ⟶ R is zero by assumption.
have hu : pullback_to_biproduct_is_kernel.pullback_to_biproduct f g ≫ u = 0 := by simpa,
-- pullback_to_biproduct f g is a kernel of (f, -g), so (f, -g) is a
-- cokernel of pullback_to_biproduct f g
have := epi_is_cokernel_of_kernel _
(pullback_to_biproduct_is_kernel.is_limit_pullback_to_biproduct f g),
-- We use this fact to obtain a factorization of u through (f, -g) via some d : Z ⟶ R.
obtain ⟨d, hd⟩ := cokernel_cofork.is_colimit.desc' this u hu,
change Z ⟶ R at d,
change biprod.desc f (-g) ≫ d = u at hd,
-- But then f ≫ d = 0:
have : f ≫ d = 0, calc
f ≫ d = (biprod.inl ≫ biprod.desc f (-g)) ≫ d : by rw biprod.inl_desc
... = biprod.inl ≫ u : by rw [category.assoc, hd]
... = 0 : biprod.inl_desc _ _,
-- But f is an epimorphism, so d = 0...
have : d = 0 := (cancel_epi f).1 (by simpa),
-- ...or, in other words, e = 0.
calc
e = biprod.inr ≫ u : by rw biprod.inr_desc
... = biprod.inr ≫ biprod.desc f (-g) ≫ d : by rw ←hd
... = biprod.inr ≫ biprod.desc f (-g) ≫ 0 : by rw this
... = (biprod.inr ≫ biprod.desc f (-g)) ≫ 0 : by rw ←category.assoc
... = 0 : has_zero_morphisms.comp_zero _ _
end
/-- In an abelian category, the pullback of an epimorphism is an epimorphism. -/
instance epi_pullback_of_epi_g [epi g] : epi (pullback.fst : pullback f g ⟶ X) :=
-- It will suffice to consider some morphism e : X ⟶ R such that
-- pullback.fst ≫ e = 0 and show that e = 0.
epi_of_cancel_zero _ $ λ R e h,
begin
-- Consider the morphism u := (e, 0) : X ⊞ Y ⟶ R.
let u := biprod.desc e (0 : Y ⟶ R),
-- The composite pullback f g ⟶ X ⊞ Y ⟶ R is zero by assumption.
have hu : pullback_to_biproduct_is_kernel.pullback_to_biproduct f g ≫ u = 0 := by simpa,
-- pullback_to_biproduct f g is a kernel of (f, -g), so (f, -g) is a
-- cokernel of pullback_to_biproduct f g
have := epi_is_cokernel_of_kernel _
(pullback_to_biproduct_is_kernel.is_limit_pullback_to_biproduct f g),
-- We use this fact to obtain a factorization of u through (f, -g) via some d : Z ⟶ R.
obtain ⟨d, hd⟩ := cokernel_cofork.is_colimit.desc' this u hu,
change Z ⟶ R at d,
change biprod.desc f (-g) ≫ d = u at hd,
-- But then (-g) ≫ d = 0:
have : (-g) ≫ d = 0, calc
(-g) ≫ d = (biprod.inr ≫ biprod.desc f (-g)) ≫ d : by rw biprod.inr_desc
... = biprod.inr ≫ u : by rw [category.assoc, hd]
... = 0 : biprod.inr_desc _ _,
-- But g is an epimorphism, thus so is -g, so d = 0...
have : d = 0 := (cancel_epi (-g)).1 (by simpa),
-- ...or, in other words, e = 0.
calc
e = biprod.inl ≫ u : by rw biprod.inl_desc
... = biprod.inl ≫ biprod.desc f (-g) ≫ d : by rw ←hd
... = biprod.inl ≫ biprod.desc f (-g) ≫ 0 : by rw this
... = (biprod.inl ≫ biprod.desc f (-g)) ≫ 0 : by rw ←category.assoc
... = 0 : has_zero_morphisms.comp_zero _ _
end
lemma epi_snd_of_is_limit [epi f] {s : pullback_cone f g} (hs : is_limit s) : epi s.snd :=
begin
convert epi_of_epi_fac (is_limit.cone_point_unique_up_to_iso_hom_comp (limit.is_limit _) hs _),
{ refl },
{ exact abelian.epi_pullback_of_epi_f _ _ }
end
lemma epi_fst_of_is_limit [epi g] {s : pullback_cone f g} (hs : is_limit s) : epi s.fst :=
begin
convert epi_of_epi_fac (is_limit.cone_point_unique_up_to_iso_hom_comp (limit.is_limit _) hs _),
{ refl },
{ exact abelian.epi_pullback_of_epi_g _ _ }
end
/-- Suppose `f` and `g` are two morphisms with a common codomain and suppose we have written `g` as
an epimorphism followed by a monomorphism. If `f` factors through the mono part of this
factorization, then any pullback of `g` along `f` is an epimorphism. -/
lemma epi_fst_of_factor_thru_epi_mono_factorization
(g₁ : Y ⟶ W) [epi g₁] (g₂ : W ⟶ Z) [mono g₂] (hg : g₁ ≫ g₂ = g) (f' : X ⟶ W) (hf : f' ≫ g₂ = f)
(t : pullback_cone f g) (ht : is_limit t) : epi t.fst :=
by apply epi_fst_of_is_limit _ _ (pullback_cone.is_limit_of_factors f g g₂ f' g₁ hf hg t ht)
end epi_pullback
section mono_pushout
variables [limits.has_pushouts C] {W X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z)
instance mono_pushout_of_mono_f [mono f] : mono (pushout.inr : Z ⟶ pushout f g) :=
mono_of_cancel_zero _ $ λ R e h,
begin
let u := biprod.lift (0 : R ⟶ Y) e,
have hu : u ≫ biproduct_to_pushout_is_cokernel.biproduct_to_pushout f g = 0 := by simpa,
have := mono_is_kernel_of_cokernel _
(biproduct_to_pushout_is_cokernel.is_colimit_biproduct_to_pushout f g),
obtain ⟨d, hd⟩ := kernel_fork.is_limit.lift' this u hu,
change R ⟶ X at d,
change d ≫ biprod.lift f (-g) = u at hd,
have : d ≫ f = 0, calc
d ≫ f = d ≫ biprod.lift f (-g) ≫ biprod.fst : by rw biprod.lift_fst
... = u ≫ biprod.fst : by rw [←category.assoc, hd]
... = 0 : biprod.lift_fst _ _,
have : d = 0 := (cancel_mono f).1 (by simpa),
calc
e = u ≫ biprod.snd : by rw biprod.lift_snd
... = (d ≫ biprod.lift f (-g)) ≫ biprod.snd : by rw ←hd
... = (0 ≫ biprod.lift f (-g)) ≫ biprod.snd : by rw this
... = 0 ≫ biprod.lift f (-g) ≫ biprod.snd : by rw category.assoc
... = 0 : zero_comp
end
instance mono_pushout_of_mono_g [mono g] : mono (pushout.inl : Y ⟶ pushout f g) :=
mono_of_cancel_zero _ $ λ R e h,
begin
let u := biprod.lift e (0 : R ⟶ Z),
have hu : u ≫ biproduct_to_pushout_is_cokernel.biproduct_to_pushout f g = 0 := by simpa,
have := mono_is_kernel_of_cokernel _
(biproduct_to_pushout_is_cokernel.is_colimit_biproduct_to_pushout f g),
obtain ⟨d, hd⟩ := kernel_fork.is_limit.lift' this u hu,
change R ⟶ X at d,
change d ≫ biprod.lift f (-g) = u at hd,
have : d ≫ (-g) = 0, calc
d ≫ (-g) = d ≫ biprod.lift f (-g) ≫ biprod.snd : by rw biprod.lift_snd
... = u ≫ biprod.snd : by rw [←category.assoc, hd]
... = 0 : biprod.lift_snd _ _,
have : d = 0 := (cancel_mono (-g)).1 (by simpa),
calc
e = u ≫ biprod.fst : by rw biprod.lift_fst
... = (d ≫ biprod.lift f (-g)) ≫ biprod.fst : by rw ←hd
... = (0 ≫ biprod.lift f (-g)) ≫ biprod.fst : by rw this
... = 0 ≫ biprod.lift f (-g) ≫ biprod.fst : by rw category.assoc
... = 0 : zero_comp
end
lemma mono_inr_of_is_colimit [mono f] {s : pushout_cocone f g} (hs : is_colimit s) : mono s.inr :=
begin
convert mono_of_mono_fac
(is_colimit.comp_cocone_point_unique_up_to_iso_hom hs (colimit.is_colimit _) _),
{ refl },
{ exact abelian.mono_pushout_of_mono_f _ _ }
end
lemma mono_inl_of_is_colimit [mono g] {s : pushout_cocone f g} (hs : is_colimit s) : mono s.inl :=
begin
convert mono_of_mono_fac
(is_colimit.comp_cocone_point_unique_up_to_iso_hom hs (colimit.is_colimit _) _),
{ refl },
{ exact abelian.mono_pushout_of_mono_g _ _ }
end
/-- Suppose `f` and `g` are two morphisms with a common domain and suppose we have written `g` as
an epimorphism followed by a monomorphism. If `f` factors through the epi part of this
factorization, then any pushout of `g` along `f` is a monomorphism. -/
lemma mono_inl_of_factor_thru_epi_mono_factorization (f : X ⟶ Y) (g : X ⟶ Z)
(g₁ : X ⟶ W) [epi g₁] (g₂ : W ⟶ Z) [mono g₂] (hg : g₁ ≫ g₂ = g) (f' : W ⟶ Y) (hf : g₁ ≫ f' = f)
(t : pushout_cocone f g) (ht : is_colimit t) : mono t.inl :=
by apply mono_inl_of_is_colimit _ _ (pushout_cocone.is_colimit_of_factors _ _ _ _ _ hf hg t ht)
end mono_pushout
end category_theory.abelian
namespace category_theory.non_preadditive_abelian
variables (C : Type u) [category.{v} C] [non_preadditive_abelian C]
/-- Every non_preadditive_abelian category can be promoted to an abelian category. -/
def abelian : abelian C :=
{ has_finite_products := by apply_instance,
/- We need the `convert`s here because the instances we have are slightly different from the
instances we need: `has_kernels` depends on an instance of `has_zero_morphisms`. In the
case of `non_preadditive_abelian`, this instance is an explicit argument. However, in the case
of `abelian`, the `has_zero_morphisms` instance is derived from `preadditive`. So we need to
transform an instance of "has kernels with non_preadditive_abelian.has_zero_morphisms" to an
instance of "has kernels with non_preadditive_abelian.preadditive.has_zero_morphisms". Luckily,
we have a `subsingleton` instance for `has_zero_morphisms`, so `convert` can immediately close
the goal it creates for the two instances of `has_zero_morphisms`, and the proof is complete. -/
has_kernels := by convert (by apply_instance : limits.has_kernels C),
has_cokernels := by convert (by apply_instance : limits.has_cokernels C),
normal_mono_of_mono := by { introsI, convert normal_mono_of_mono f },
normal_epi_of_epi := by { introsI, convert normal_epi_of_epi f },
..non_preadditive_abelian.preadditive }
end category_theory.non_preadditive_abelian
|
f0413cb0974c5bec11cd483e311000b57d0689f4 | 9b9a16fa2cb737daee6b2785474678b6fa91d6d4 | /src/order/order_iso.lean | 02544e436e616aceeb03841912f2d1835ab5c4bc | [
"Apache-2.0"
] | permissive | johoelzl/mathlib | 253f46daa30b644d011e8e119025b01ad69735c4 | 592e3c7a2dfbd5826919b4605559d35d4d75938f | refs/heads/master | 1,625,657,216,488 | 1,551,374,946,000 | 1,551,374,946,000 | 98,915,829 | 0 | 0 | Apache-2.0 | 1,522,917,267,000 | 1,501,524,499,000 | Lean | UTF-8 | Lean | false | false | 13,004 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import order.basic logic.embedding data.nat.basic
open function
universes u v w
variables {α : Type*} {β : Type*} {γ : Type*}
{r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
structure order_embedding {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ↪ β :=
(ord : ∀ {a b}, r a b ↔ s (to_embedding a) (to_embedding b))
infix ` ≼o `:50 := order_embedding
/-- the induced order on a subtype is an embedding under the natural inclusion. -/
definition subtype.order_embedding {X : Type*} (r : X → X → Prop) (p : X → Prop) :
((subtype.val : subtype p → X) ⁻¹'o r) ≼o r :=
⟨⟨subtype.val,subtype.val_injective⟩,by intros;refl⟩
theorem preimage_equivalence {α β} (f : α → β) {s : β → β → Prop}
(hs : equivalence s) : equivalence (f ⁻¹'o s) :=
⟨λ a, hs.1 _, λ a b h, hs.2.1 h, λ a b c h₁ h₂, hs.2.2 h₁ h₂⟩
namespace order_embedding
instance : has_coe_to_fun (r ≼o s) := ⟨λ _, α → β, λ o, o.to_embedding⟩
theorem ord' : ∀ (f : r ≼o s) {a b}, r a b ↔ s (f a) (f b)
| ⟨f, o⟩ := @o
@[simp] theorem coe_fn_mk (f : α ↪ β) (o) :
(@order_embedding.mk _ _ r s f o : α → β) = f := rfl
@[simp] theorem coe_fn_to_embedding (f : r ≼o s) : (f.to_embedding : α → β) = f := rfl
theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : r ≼o s}, (e₁ : α → β) = e₂ → e₁ = e₂
| ⟨⟨f₁, h₁⟩, o₁⟩ ⟨⟨f₂, h₂⟩, o₂⟩ h := by congr; exact h
@[refl] protected def refl (r : α → α → Prop) : r ≼o r :=
⟨embedding.refl _, λ a b, iff.rfl⟩
@[trans] protected def trans (f : r ≼o s) (g : s ≼o t) : r ≼o t :=
⟨f.1.trans g.1, λ a b, by rw [f.2, g.2]; simp⟩
@[simp] theorem refl_apply (x : α) : order_embedding.refl r x = x := rfl
@[simp] theorem trans_apply (f : r ≼o s) (g : s ≼o t) (a : α) : (f.trans g) a = g (f a) := rfl
/-- An order embedding is also an order embedding between dual orders. -/
def rsymm (f : r ≼o s) : swap r ≼o swap s :=
⟨f.to_embedding, λ a b, f.ord'⟩
/-- If `f` is injective, then it is an order embedding from the
preimage order of `s` to `s`. -/
def preimage (f : α ↪ β) (s : β → β → Prop) : f ⁻¹'o s ≼o s := ⟨f, λ a b, iff.rfl⟩
theorem eq_preimage (f : r ≼o s) : r = f ⁻¹'o s :=
by funext a b; exact propext f.ord'
protected theorem is_irrefl : ∀ (f : r ≼o s) [is_irrefl β s], is_irrefl α r
| ⟨f, o⟩ ⟨H⟩ := ⟨λ a h, H _ (o.1 h)⟩
protected theorem is_refl : ∀ (f : r ≼o s) [is_refl β s], is_refl α r
| ⟨f, o⟩ ⟨H⟩ := ⟨λ a, o.2 (H _)⟩
protected theorem is_symm : ∀ (f : r ≼o s) [is_symm β s], is_symm α r
| ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h, o.2 (H _ _ (o.1 h))⟩
protected theorem is_asymm : ∀ (f : r ≼o s) [is_asymm β s], is_asymm α r
| ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, H _ _ (o.1 h₁) (o.1 h₂)⟩
protected theorem is_antisymm : ∀ (f : r ≼o s) [is_antisymm β s], is_antisymm α r
| ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, f.inj' (H _ _ (o.1 h₁) (o.1 h₂))⟩
protected theorem is_trans : ∀ (f : r ≼o s) [is_trans β s], is_trans α r
| ⟨f, o⟩ ⟨H⟩ := ⟨λ a b c h₁ h₂, o.2 (H _ _ _ (o.1 h₁) (o.1 h₂))⟩
protected theorem is_total : ∀ (f : r ≼o s) [is_total β s], is_total α r
| ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o o).2 (H _ _)⟩
protected theorem is_preorder : ∀ (f : r ≼o s) [is_preorder β s], is_preorder α r
| f H := by exactI {..f.is_refl, ..f.is_trans}
protected theorem is_partial_order : ∀ (f : r ≼o s) [is_partial_order β s], is_partial_order α r
| f H := by exactI {..f.is_preorder, ..f.is_antisymm}
protected theorem is_linear_order : ∀ (f : r ≼o s) [is_linear_order β s], is_linear_order α r
| f H := by exactI {..f.is_partial_order, ..f.is_total}
protected theorem is_strict_order : ∀ (f : r ≼o s) [is_strict_order β s], is_strict_order α r
| f H := by exactI {..f.is_irrefl, ..f.is_trans}
protected theorem is_trichotomous : ∀ (f : r ≼o s) [is_trichotomous β s], is_trichotomous α r
| ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o (or_congr f.inj'.eq_iff.symm o)).2 (H _ _)⟩
protected theorem is_strict_total_order' : ∀ (f : r ≼o s) [is_strict_total_order' β s], is_strict_total_order' α r
| f H := by exactI {..f.is_trichotomous, ..f.is_strict_order}
protected theorem acc (f : r ≼o s) (a : α) : acc s (f a) → acc r a :=
begin
generalize h : f a = b, intro ac,
induction ac with _ H IH generalizing a, subst h,
exact ⟨_, λ a' h, IH (f a') (f.ord'.1 h) _ rfl⟩
end
protected theorem well_founded : ∀ (f : r ≼o s) (h : well_founded s), well_founded r
| f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩
protected theorem is_well_order : ∀ (f : r ≼o s) [is_well_order β s], is_well_order α r
| f H := by exactI {wf := f.well_founded H.wf, ..f.is_strict_total_order'}
/-- It suffices to prove `f` is monotone between strict orders
to show it is an order embedding. -/
def of_monotone [is_trichotomous α r] [is_asymm β s] (f : α → β) (H : ∀ a b, r a b → s (f a) (f b)) : r ≼o s :=
begin
haveI := @is_irrefl_of_is_asymm β s _,
refine ⟨⟨f, λ a b e, _⟩, λ a b, ⟨H _ _, λ h, _⟩⟩,
{ refine ((@trichotomous _ r _ a b).resolve_left _).resolve_right _;
exact λ h, @irrefl _ s _ _ (by simpa [e] using H _ _ h) },
{ refine (@trichotomous _ r _ a b).resolve_right (or.rec (λ e, _) (λ h', _)),
{ subst e, exact irrefl _ h },
{ exact asymm (H _ _ h') h } }
end
@[simp] theorem of_monotone_coe [is_trichotomous α r] [is_asymm β s] (f : α → β) (H) :
(@of_monotone _ _ r s _ _ f H : α → β) = f := rfl
-- If le is preserved by an order embedding of preorders, then lt is too
def lt_embedding_of_le_embedding [preorder α] [preorder β]
(f : (has_le.le : α → α → Prop) ≼o (has_le.le : β → β → Prop)) :
(has_lt.lt : α → α → Prop) ≼o (has_lt.lt : β → β → Prop) :=
{ to_fun := f,
inj := f.inj,
ord := by intros; simp [lt_iff_le_not_le,f.ord] }
theorem nat_lt [is_strict_order α r] (f : ℕ → α) (H : ∀ n:ℕ, r (f n) (f (n+1))) :
((<) : ℕ → ℕ → Prop) ≼o r :=
of_monotone f $ λ a b h, begin
induction b with b IH, {exact (nat.not_lt_zero _ h).elim},
cases nat.lt_succ_iff_lt_or_eq.1 h with h e,
{ exact trans (IH h) (H _) },
{ subst b, apply H }
end
theorem nat_gt [is_strict_order α r] (f : ℕ → α) (H : ∀ n:ℕ, r (f (n+1)) (f n)) :
((>) : ℕ → ℕ → Prop) ≼o r :=
by haveI := is_strict_order.swap r; exact rsymm (nat_lt f H)
theorem well_founded_iff_no_descending_seq [is_strict_order α r] : well_founded r ↔ ¬ nonempty (((>) : ℕ → ℕ → Prop) ≼o r) :=
⟨λ ⟨h⟩ ⟨⟨f, o⟩⟩,
suffices ∀ a, acc r a → ∀ n, a ≠ f n, from this (f 0) (h _) 0 rfl,
λ a ac, begin
induction ac with a _ IH, intros n h, subst a,
exact IH (f (n+1)) (o.1 (nat.lt_succ_self _)) _ rfl
end,
λ N, ⟨λ a, classical.by_contradiction $ λ na,
let ⟨f, h⟩ := classical.axiom_of_choice $
show ∀ x : {a // ¬ acc r a}, ∃ y : {a // ¬ acc r a}, r y.1 x.1,
from λ ⟨x, h⟩, classical.by_contradiction $ λ hn, h $
⟨_, λ y h, classical.by_contradiction $ λ na, hn ⟨⟨y, na⟩, h⟩⟩ in
N ⟨nat_gt (λ n, (f^[n] ⟨a, na⟩).1) $ λ n,
by rw nat.iterate_succ'; apply h⟩⟩⟩
end order_embedding
/-- The inclusion map `fin n → ℕ` is an order embedding. -/
def fin.val.order_embedding (n) : @order_embedding (fin n) ℕ (<) (<) :=
⟨⟨fin.val, @fin.eq_of_veq _⟩, λ a b, iff.rfl⟩
/-- The inclusion map `fin m → fin n` is an order embedding. -/
def fin_fin.order_embedding {m n} (h : m ≤ n) : @order_embedding (fin m) (fin n) (<) (<) :=
⟨⟨λ ⟨x, h'⟩, ⟨x, lt_of_lt_of_le h' h⟩,
λ ⟨a, _⟩ ⟨b, _⟩ h, by congr; injection h⟩,
by intros; cases a; cases b; refl⟩
instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) :=
(fin.val.order_embedding _).is_well_order
/-- An order isomorphism is an equivalence that is also an order embedding. -/
structure order_iso {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ≃ β :=
(ord : ∀ {a b}, r a b ↔ s (to_equiv a) (to_equiv b))
infix ` ≃o `:50 := order_iso
namespace order_iso
def to_order_embedding (f : r ≃o s) : r ≼o s :=
⟨f.to_equiv.to_embedding, f.ord⟩
instance : has_coe (r ≃o s) (r ≼o s) := ⟨to_order_embedding⟩
theorem coe_coe_fn (f : r ≃o s) : ((f : r ≼o s) : α → β) = f := rfl
theorem ord' : ∀ (f : r ≃o s) {a b}, r a b ↔ s (f a) (f b)
| ⟨f, o⟩ := @o
@[simp] theorem coe_fn_mk (f : α ≃ β) (o) :
(@order_iso.mk _ _ r s f o : α → β) = f := rfl
@[simp] theorem coe_fn_to_equiv (f : r ≃o s) : (f.to_equiv : α → β) = f := rfl
theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : r ≃o s}, (e₁ : α → β) = e₂ → e₁ = e₂
| ⟨e₁, o₁⟩ ⟨e₂, o₂⟩ h := by congr; exact equiv.eq_of_to_fun_eq h
@[refl] protected def refl (r : α → α → Prop) : r ≃o r :=
⟨equiv.refl _, λ a b, iff.rfl⟩
@[symm] protected def symm (f : r ≃o s) : s ≃o r :=
⟨f.to_equiv.symm, λ a b, by cases f with f o; rw o; simp⟩
@[trans] protected def trans (f₁ : r ≃o s) (f₂ : s ≃o t) : r ≃o t :=
⟨f₁.to_equiv.trans f₂.to_equiv, λ a b,
by cases f₁ with f₁ o₁; cases f₂ with f₂ o₂; rw [o₁, o₂]; simp⟩
@[simp] theorem coe_fn_symm_mk (f o) : ((@order_iso.mk _ _ r s f o).symm : β → α) = f.symm :=
rfl
@[simp] theorem refl_apply (x : α) : order_iso.refl r x = x := rfl
@[simp] theorem trans_apply : ∀ (f : r ≃o s) (g : s ≃o t) (a : α), (f.trans g) a = g (f a)
| ⟨f₁, o₁⟩ ⟨f₂, o₂⟩ a := equiv.trans_apply _ _ _
@[simp] theorem apply_inverse_apply : ∀ (e : r ≃o s) (x : β), e (e.symm x) = x
| ⟨f₁, o₁⟩ x := by simp
@[simp] theorem inverse_apply_apply : ∀ (e : r ≃o s) (x : α), e.symm (e x) = x
| ⟨f₁, o₁⟩ x := by simp
/-- Any equivalence lifts to an order isomorphism between `s` and its preimage. -/
def preimage (f : α ≃ β) (s : β → β → Prop) : f ⁻¹'o s ≃o s := ⟨f, λ a b, iff.rfl⟩
noncomputable def of_surjective (f : r ≼o s) (H : surjective f) : r ≃o s :=
⟨equiv.of_bijective ⟨f.inj, H⟩, by simp [f.ord']⟩
@[simp] theorem of_surjective_coe (f : r ≼o s) (H) : (of_surjective f H : α → β) = f :=
by delta of_surjective; simp
theorem sum_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂}
(e₁ : @order_iso α₁ α₂ r₁ r₂) (e₂ : @order_iso β₁ β₂ s₁ s₂) :
sum.lex r₁ s₁ ≃o sum.lex r₂ s₂ :=
⟨equiv.sum_congr e₁.to_equiv e₂.to_equiv, λ a b,
by cases e₁ with f hf; cases e₂ with g hg;
cases a; cases b; simp [hf, hg]⟩
theorem prod_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂}
(e₁ : @order_iso α₁ α₂ r₁ r₂) (e₂ : @order_iso β₁ β₂ s₁ s₂) :
prod.lex r₁ s₁ ≃o prod.lex r₂ s₂ :=
⟨equiv.prod_congr e₁.to_equiv e₂.to_equiv, λ a b, begin
cases e₁ with f hf; cases e₂ with g hg,
cases a with a₁ a₂; cases b with b₁ b₂,
suffices : prod.lex r₁ s₁ (a₁, a₂) (b₁, b₂) ↔
prod.lex r₂ s₂ (f a₁, g a₂) (f b₁, g b₂), {simpa [hf, hg]},
split,
{ intro h, cases h with _ _ _ _ h _ _ _ h,
{ left, exact hf.1 h },
{ right, exact hg.1 h } },
{ generalize e : f b₁ = fb₁,
intro h, cases h with _ _ _ _ h _ _ _ h,
{ subst e, left, exact hf.2 h },
{ have := f.bijective.1 e, subst b₁,
right, exact hg.2 h } }
end⟩
end order_iso
/-- A subset `p : set α` embeds into `α` -/
def set_coe_embedding {α : Type*} (p : set α) : p ↪ α := ⟨subtype.val, @subtype.eq _ _⟩
/-- `subrel r p` is the inherited relation on a subset. -/
def subrel (r : α → α → Prop) (p : set α) : p → p → Prop :=
@subtype.val _ p ⁻¹'o r
@[simp] theorem subrel_val (r : α → α → Prop) (p : set α)
{a b} : subrel r p a b ↔ r a.1 b.1 := iff.rfl
namespace subrel
protected def order_embedding (r : α → α → Prop) (p : set α) :
subrel r p ≼o r := ⟨set_coe_embedding _, λ a b, iff.rfl⟩
@[simp] theorem order_embedding_apply (r : α → α → Prop) (p a) :
subrel.order_embedding r p a = a.1 := rfl
instance (r : α → α → Prop) [is_well_order α r]
(p : set α) : is_well_order p (subrel r p) :=
order_embedding.is_well_order (subrel.order_embedding r p)
end subrel
/-- Restrict the codomain of an order embedding -/
def order_embedding.cod_restrict (p : set β) (f : r ≼o s) (H : ∀ a, f a ∈ p) : r ≼o subrel s p :=
⟨f.to_embedding.cod_restrict p H, f.ord⟩
@[simp] theorem order_embedding.cod_restrict_apply (p) (f : r ≼o s) (H a) :
order_embedding.cod_restrict p f H a = ⟨f a, H a⟩ := rfl
|
d50099e412136e296aa97c7b7c3df8c69f6b467d | 5df84495ec6c281df6d26411cc20aac5c941e745 | /src/formal_ml/ennreal.lean | f770bf50096e675ded4d84dafd962781b9251fb9 | [
"Apache-2.0"
] | permissive | eric-wieser/formal-ml | e278df5a8df78aa3947bc8376650419e1b2b0a14 | 630011d19fdd9539c8d6493a69fe70af5d193590 | refs/heads/master | 1,681,491,589,256 | 1,612,642,743,000 | 1,612,642,743,000 | 360,114,136 | 0 | 0 | Apache-2.0 | 1,618,998,189,000 | 1,618,998,188,000 | null | UTF-8 | Lean | false | false | 23,839 | lean | /-
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/
import data.real.ennreal
import formal_ml.nat
import formal_ml.nnreal
import formal_ml.with_top
import formal_ml.lattice
-- ennreal is a canonically_ordered_add_monoid
-- ennreal is not a decidable_linear_ordered_semiring
-- Otherwise (0 < c) → (c * a) ≤ (c * b) → (a ≤ b),
-- but this does not hold for c =⊤, a = 1, b = 0.
-- This is because ennreal is not an ordered_cancel_add_comm_monoid.
-- Nor is it an ordered_cancel_comm_monoid
-- This implies it is also not an ordered_semiring
lemma ennreal_coe_eq_lift {a:ennreal} {b:nnreal}:a = b → (a.to_nnreal = b) :=
begin
intro A1,
have A2:(a.to_nnreal)=(b:ennreal).to_nnreal,
{
rw A1,
},
rw ennreal.to_nnreal_coe at A2,
exact A2,
end
/-
This is one of those complicated inequalities that is probably too rare to justify a
lemma. However, since it shows up, we give it the canonical name and move on.
-/
lemma ennreal_le_to_nnreal_of_ennreal_le_of_ne_top {a:nnreal} {b:ennreal}:
b≠ ⊤ → (a:ennreal) ≤ b → (a ≤ b.to_nnreal) :=
begin
intros A1 A2,
cases b,
{
simp at A1,
exfalso,
apply A1,
},
{
have A3:(b:ennreal) = (some b) := rfl,
rw ← A3,
rw (@ennreal.to_nnreal_coe b),
rw ← ennreal.coe_le_coe,
rw A3,
apply A2,
}
end
lemma ennreal_add_monoid_smul_def{n:ℕ} {c:ennreal}: n •ℕ c = ↑(n) * c :=
begin
induction n,
{
simp,
},
{
simp,
}
end
lemma ennreal_lt_add_ennreal_one (x:nnreal):(x:ennreal) < (1:ennreal) + (x:ennreal) :=
begin
apply ennreal.coe_lt_coe.mpr,
simp,
apply canonically_ordered_semiring.zero_lt_one,
end
lemma ennreal.infi_le {α:Sort*} {f:α → ennreal} {b : ennreal}:
(∀ (ε : nnreal), 0 < ε → b < ⊤ → (∃a, f a ≤ b + ↑ε)) → infi f ≤ b :=
begin
intro A1,
apply @ennreal.le_of_forall_pos_le_add,
intros ε A2 A3,
have A4 := A1 ε A2 A3,
cases A4 with a A4,
apply le_trans _ A4,
apply @infi_le ennreal _ _,
end
lemma ennreal.forall_epsilon_le_iff_le : ∀{a b : ennreal}, (∀ε:nnreal, 0 < ε → b < ⊤ → a ≤ b + ε) ↔ a ≤ b :=
begin
intros a b,
split,
apply ennreal.le_of_forall_pos_le_add,
intros A1 ε B1 B2,
apply le_add_right A1,
end
lemma ennreal.lt_of_add_le_of_pos {x y z:ennreal}:x + y ≤ z → 0 < y → x < ⊤ → x < z :=
begin
cases x;cases y;cases z;try {simp},
{repeat {rw ← ennreal.coe_add},rw ennreal.coe_le_coe,apply nnreal.lt_of_add_le_of_pos},
end
lemma ennreal.iff_infi_le {α:Sort*} {f:α → ennreal} {b : ennreal}:
(∀ (ε : nnreal), 0 < ε → b < ⊤ → (∃a, f a ≤ b + ↑ε)) ↔ infi f ≤ b :=
begin
--intro A1,
--rw ← @ennreal.forall_epsilon_le_iff_le (infi f) b,
split,
apply ennreal.infi_le,
intro A1,
intros ε A2 A3,
apply classical.by_contradiction,
intro A4,
apply not_lt_of_ge A1,
have A5:b + ↑ε ≤ infi f,
{ apply @le_infi ennreal _ _, intro a,
have A5:=(forall_not_of_not_exists A4) a,
simp at A5,
apply le_of_lt A5,
},
apply ennreal.lt_of_add_le_of_pos A5,
simp,apply A2,
apply A3,
end
lemma ennreal.exists_le_infi_add {α:Type*} (f:α → ennreal) [N:nonempty α] {ε:nnreal}:0 < ε → (∃ a, f a ≤ infi f + ε) :=
begin
intros A1,
have A2:infi f ≤ infi f,
{apply le_refl _},
rw ← ennreal.iff_infi_le at A2,
cases (decidable.em (infi f < ⊤)) with A3 A3,
apply A2 ε A1 A3,
simp only [not_lt, top_le_iff] at A3,
--cases N,
have a := classical.choice N,
apply exists.intro a,
rw A3,
simp,
end
lemma ennreal.le_supr {α:Type*} {f:α → ennreal} {b : ennreal}:(∀ (ε : nnreal), 0 < ε → (supr f < ⊤) → (∃a, b ≤ f a + ε)) → b ≤ supr f :=
begin
intro A1,
apply @ennreal.le_of_forall_pos_le_add,
intros ε A2 A3,
have A4 := A1 ε A2 A3,
cases A4 with a A4,
apply le_trans A4,
have A5:=@le_supr ennreal _ _ f a,
apply add_le_add A5,
apply le_refl _,
end
/-This isn't true. Specifically, for any non-finite sets, one can construct a counterexample.
Using ℕ as an example, f:ℕ → ℕ → ennreal := λ a b, if (a < b) then 1 else 0.
lemma ennreal.supr_infi_eq_infi_supr {α β:Type*} [nonempty α] [nonempty β] [partial_order β] {f:α → β → ennreal}:(∀ a:α, monotone (f a)) →
(⨅ (a:α), ⨆ (b:β), f a b )= ( ⨆ (b:β), ⨅ (a:α), f a b) :=
begin
-/
lemma ennreal.not_add_le_of_lt_of_lt_top {a b:ennreal}:
(0 < b) → (a < ⊤) → ¬(a + b) ≤ a :=
begin
intros A1 A2 A3,
have A4:(⊤:ennreal) = none := rfl,
cases a,
{
simp at A2,
apply A2,
},
cases b,
{
rw ←A4 at A3,
rw with_top.add_top at A3,
rw top_le_iff at A3,
simp at A3,
apply A3,
},
simp at A3,
rw ← ennreal.coe_add at A3,
rw ennreal.coe_le_coe at A3,
simp at A1,
apply nnreal.not_add_le_of_lt A1,
apply A3,
end
lemma ennreal.lt_add_of_pos_of_lt_top {a b:ennreal}:
(0 < b) → (a < ⊤) → a < a + b :=
begin
intros A1 A2,
apply lt_of_not_ge,
apply ennreal.not_add_le_of_lt_of_lt_top A1 A2,
end
lemma ennreal.infi_elim {α:Sort*} {f:α → ennreal} {ε:nnreal}:
(0 < ε) → (infi f < ⊤) → (∃a, f a ≤ infi f + ↑ε) :=
begin
intros A1 A2,
have A3:¬(infi f+(ε:ennreal)≤ infi f),
{
apply ennreal.not_add_le_of_lt_of_lt_top _ A2,
simp,
apply A1,
},
apply (@classical.exists_of_not_forall_not α (λ (a : α), f a ≤ infi f + ↑ε)),
intro A4,
apply A3,
apply @le_infi ennreal α _,
intro a,
cases (le_total (infi f + ↑ε) (f a)) with A5 A5,
apply A5,
have A6 := A4 a,
exfalso,
apply A6,
apply A5,
end
lemma ennreal.zero_le {a:ennreal}:0 ≤ a :=
begin
simp,
end
lemma ennreal.sub_top {a:ennreal}:a - ⊤ = 0 :=
begin
simp,
end
lemma ennreal.sub_lt_of_pos_of_pos {a b:ennreal}:(0 < a) →
(0 < b) → (a ≠ ⊤) → (a - b) < a :=
begin
intros A1 A2 A3,
cases a,
{
exfalso,
simp at A3,
apply A3,
},
cases b,
{
rw ennreal.none_eq_top,
rw ennreal.sub_top,
apply A1,
},
simp,
rw ← ennreal.coe_sub,
rw ennreal.coe_lt_coe,
apply nnreal.sub_lt_of_pos_of_pos,
{
simp at A1,
apply A1,
},
{
simp at A2,
apply A2,
},
end
lemma ennreal.Sup_elim {S:set ennreal} {ε:nnreal}:
(0 < ε) → (S.nonempty) → (Sup S ≠ ⊤) → (∃s∈S, (Sup S) - ε ≤ s) :=
begin
intros A1 A2 A3,
cases classical.em (Sup S = 0) with A4 A4,
{
rw A4,
have A5:= set.nonempty_def.mp A2,
cases A5 with s A5,
apply exists.intro s,
apply exists.intro A5,
simp,
},
have A5:(0:ennreal) = ⊥ := rfl,
have B1:(Sup S) - ε < (Sup S),
{
apply ennreal.sub_lt_of_pos_of_pos,
rw A5,
rw bot_lt_iff_ne_bot,
rw ← A5,
apply A4,
simp,
apply A1,
apply A3,
},
rw lt_Sup_iff at B1,
cases B1 with a B1,
cases B1 with B2 B3,
apply exists.intro a,
apply exists.intro B2,
apply le_of_lt B3,
end
lemma ennreal.top_of_infi_top {α:Type*} {g:α → ennreal} {a:α}:((⨅ a', g a') = ⊤) →
(g a = ⊤) :=
begin
intro A1,
rw ← top_le_iff,
rw ← A1,
apply @infi_le ennreal α _,
end
lemma of_infi_lt_top {P:Prop} {H:P→ ennreal}:infi H < ⊤ → P :=
begin
intro A1,
cases (classical.em P) with A2 A2,
{
apply A2,
},
{
exfalso,
unfold infi at A1,
unfold set.range at A1,
have A2:{x : ennreal | ∃ (y : P), H y = x}=∅,
{
ext;split;intro A2A,
simp at A2A,
exfalso,
cases A2A with y A2A,
apply A2,
apply y,
exfalso,
apply A2A,
},
rw A2 at A1,
simp at A1,
apply A1,
},
end
/-
lemma ennreal.add_le_add_left {a b c:ennreal}:
b ≤ c → a + b ≤ a + c :=
begin
intro A1,
cases a,
{
simp,
},
cases b,
{
simp at A1,
subst c,
simp,
},
cases c,
{
simp,
},
simp,
simp at A1,
repeat {rw ← ennreal.coe_add},
rw ennreal.coe_le_coe,
apply @add_le_add_left nnreal _,
apply A1,
end
-/
lemma ennreal.le_of_add_le_add_right
{a b c:ennreal}:(c < ⊤)→
(a + c ≤ b + c) → (a ≤ b) :=
begin
rw add_comm a c,
rw add_comm b c,
apply ennreal.le_of_add_le_add_left
end
lemma ennreal.le_add {a b c:ennreal}:a ≤ b → a ≤ b + c :=
begin
intro A1,
apply @le_add_of_le_of_nonneg ennreal _,
apply A1,
simp,
end
lemma ennreal.add_lt_add_of_lt_of_le_of_lt_top {a b c d:ennreal}:d < ⊤ → c ≤ d → a < b → a + c < b + d :=
begin
intros A1 A2 A3,
rw le_iff_lt_or_eq at A2,
cases A2 with A2 A2,
{
apply ennreal.add_lt_add A3 A2,
},
subst d,
rw with_top.add_lt_add_iff_right,
apply A3,
apply A1,
end
lemma ennreal.le_of_sub_eq_zero {a b:ennreal}:
a - b = 0 → a ≤ b :=
begin
intros A1,
simp at A1,
apply A1,
end
--Used once in hahn.lean.
lemma ennreal.sub_add_sub {a b c:ennreal}:c ≤ b → b ≤ a → (a - b) + (b - c) = a - c :=
begin
cases c;cases b;cases a;try {simp},
repeat {rw ← ennreal.coe_sub <|> rw ← ennreal.coe_add <|> rw ennreal.coe_eq_coe},
apply nnreal.sub_add_sub,
end
-- TODO: everything used below here.
lemma ennreal.inv_as_fraction {c:ennreal}:(1)/(c) = (c)⁻¹ :=
begin
rw div_eq_mul_inv,
rw one_mul,
end
lemma ennreal.add_lt_of_lt_sub {a b c:ennreal}:a < b - c → a + c < b :=
begin
cases a;cases b;cases c;try {simp},
{
repeat {rw ← ennreal.coe_sub
<|> rw ennreal.coe_lt_coe
<|> rw ← ennreal.coe_add},
apply nnreal.add_lt_of_lt_sub,
},
end
lemma ennreal.lt_sub_of_add_lt {a b c:ennreal}: a + c < b → a < b - c :=
begin
--intros AX A1,
cases a;cases b;cases c;try {simp},
{
repeat {rw ← ennreal.coe_sub
<|> rw ennreal.coe_lt_coe
<|> rw ← ennreal.coe_add},
apply nnreal.lt_sub_of_add_lt,
},
end
lemma ennreal.eq_zero_or_zero_lt {x:ennreal}:¬(x=0) → (0 < x) :=
begin
intro A1,
have A2:= @lt_trichotomy ennreal _ x 0,
cases A2,
{
exfalso,
apply @ennreal.not_lt_zero x,
apply A2,
},
cases A2,
{
exfalso,
apply A1,
apply A2,
},
{
apply A2,
},
end
--TODO: everything used below here.
lemma ennreal.sub_eq_of_add_of_not_top_of_le {a b c:ennreal}:a = b + c →
c ≠ ⊤ →
c ≤ a → a - c = b :=
begin
intros A1 A4 A2,
cases c,
{
exfalso,
simp at A4,
apply A4,
},
cases a,
{
simp,
cases b,
{
refl,
},
exfalso,
simp at A1,
rw ← ennreal.coe_add at A1,
apply ennreal.top_ne_coe A1,
},
cases b,
{
simp at A1,
exfalso,
apply A1,
},
{
repeat {rw ennreal.some_eq_coe},
rw ← ennreal.coe_sub,
rw ennreal.coe_eq_coe,
repeat {rw ennreal.some_eq_coe at A1},
rw ← ennreal.coe_add at A1,
rw ennreal.coe_eq_coe at A1,
repeat {rw ennreal.some_eq_coe at A2},
rw ennreal.coe_le_coe at A2,
apply nnreal.sub_eq_of_add_of_le A1 A2,
},
end
lemma ennreal.eq_add_of_sub_eq {a b c:ennreal}:b ≤ a →
a - b = c → a = b + c :=
begin
intros A1 A2,
cases a;cases b,
{
simp,
},
{
cases c,
{
simp,
},
exfalso,
simp at A2,
apply A2,
},
{
exfalso,
apply with_top.not_none_le_some _ A1,
},
simp at A2,
rw ← ennreal.coe_sub at A2,
cases c,
{
exfalso,
simp at A2,
apply A2,
},
{
simp,
rw ← ennreal.coe_add,
rw ennreal.coe_eq_coe,
simp at A2,
simp at A1,
apply nnreal.eq_add_of_sub_eq A1 A2,
},
end
lemma ennreal.sub_lt_sub_of_lt_of_le {a b c d:ennreal}:a < b →
c ≤ d →
d ≤ a →
a - d < b - c :=
begin
intros A1 A2 A3,
have B1:(⊤:ennreal) = none := rfl,
have B2:∀ n:nnreal, (some n) = n,
{
intro n,
refl,
},
cases a,
{
exfalso,
apply @with_top.not_none_lt nnreal _ b A1,
},
cases d,
{
exfalso,
apply @with_top.not_none_le_some nnreal _ a A3,
},
cases c,
{
exfalso,
apply @with_top.not_none_le_some nnreal _ d A2,
},
cases b,
{
simp,
rw ← ennreal.coe_sub,
rw B1,
rw ← B2,
apply with_top.some_lt_none,
},
repeat {rw B2},
repeat {rw ← ennreal.coe_sub},
rw ennreal.coe_lt_coe,
apply nnreal.sub_lt_sub_of_lt_of_le,
repeat {rw B2 at A1},
rw ennreal.coe_lt_coe at A1,
apply A1,
repeat {rw B2 at A2},
rw ennreal.coe_le_coe at A2,
apply A2,
repeat {rw B2 at A3},
rw ennreal.coe_le_coe at A3,
apply A3,
end
lemma ennreal.le_sub_add {a b c:ennreal}:b ≤ c → c ≤ a →
a ≤ a - b + c :=
begin
cases a;cases b;cases c;try {simp},
rw ← ennreal.coe_sub,
rw ← ennreal.coe_add,
rw ennreal.coe_le_coe,
apply nnreal.le_sub_add,
end
lemma ennreal.le_sub_add' {a b:ennreal}:a ≤ a - b + b :=
begin
cases a; cases b; simp,
rw ← ennreal.coe_sub,
rw ← ennreal.coe_add,
rw ennreal.coe_le_coe,
apply nnreal.le_sub_add',
end
lemma ennreal.add_sub_cancel {a b:ennreal}:b < ⊤ → a + b - b = a :=
begin
cases a;cases b;try {simp},
end
lemma ennreal.exists_coe {x:ennreal}:x < ⊤ → ∃ v:nnreal, x = v :=
begin
cases x;try {simp},
end
lemma ennreal.lt_of_add_le_of_le_of_sub_lt {a b c d e:ennreal}:c < ⊤ →
a + b ≤ c → d ≤ b → c - e < a → d < e :=
begin
cases c,simp,
cases a;cases b;cases d;cases e;try {simp},
rw ← ennreal.coe_add,
rw ← ennreal.coe_sub,
rw ennreal.coe_le_coe,
rw ennreal.coe_lt_coe,
apply nnreal.lt_of_add_le_of_le_of_sub_lt,
end
lemma ennreal.coe_sub_lt_self {a:nnreal} {b:ennreal}:
0 < a → 0 < b →
(a:ennreal) - b < (a:ennreal) :=
begin
cases b;simp,
intros A1 A2,
rw ← ennreal.coe_sub,
rw ennreal.coe_lt_coe,
apply nnreal.sub_lt_self A1 A2,
end
lemma ennreal.lt_of_lt_top_of_add_lt_of_pos {a b c:ennreal}:a < ⊤ →
b + c ≤ a →
0 < b →
c < a :=
begin
cases a;simp;
cases b;cases c;simp,
rw ← ennreal.coe_add,
rw ennreal.coe_le_coe,
apply nnreal.lt_of_add_lt_of_pos,
end
/-
ennreal could be a linear_ordered_comm_group_with_zero,
and therefore a ordered_comm_monoid.
HOWEVER, I am not sure how to integrate this.
I am going to just prove the basic results from the class.
NOTE that this is strictly more general than
ennreal.mul_le_mul_left.
-/
lemma ennreal.mul_le_mul_of_le_left {a b c:ennreal}:
a ≤ b → c * a ≤ c * b :=
begin
cases a;cases b;cases c;simp;
try {
cases (classical.em (c=0)) with B1 B1,
{
subst c,
simp,
},
{
have B2:(c:ennreal) * ⊤ = ⊤,
{
rw ennreal.mul_top,
rw if_neg,
intro B2A,
apply B1,
simp at B2A,
apply B2A,
},
rw B2,
{apply le_refl _ <|> simp},
},
},
{
cases (classical.em (b=0)) with B1 B1,
{
subst b,
simp,
},
{
have B2:⊤ * (b:ennreal) = ⊤,
{
rw ennreal.top_mul,
rw if_neg,
intro B2A,
apply B1,
simp at B2A,
apply B2A,
},
rw B2,
simp,
},
},
rw ← ennreal.coe_mul,
rw ← ennreal.coe_mul,
rw ennreal.coe_le_coe,
apply nnreal.mul_le_mul_of_le_left,
end
lemma ennreal.inverse_le_of_le {a b:ennreal}:
a ≤ b →
b⁻¹ ≤ a⁻¹ :=
begin
intros A2,
cases (classical.em (a = 0)) with A1 A1,
{
subst a,
simp,
},
cases b,
{
simp,
},
cases (classical.em (b = 0)) with C1 C1,
{
subst b,
simp at A2,
exfalso,
apply A1,
apply A2,
},
simp,
simp at A2,
have B1: (a⁻¹ * b⁻¹) * a ≤ (a⁻¹ * b⁻¹) * b,
{
apply ennreal.mul_le_mul_of_le_left A2,
},
rw mul_comm a⁻¹ b⁻¹ at B1,
rw mul_assoc at B1,
rw ennreal.inv_mul_cancel at B1,
rw mul_comm (b:ennreal)⁻¹ a⁻¹ at B1,
rw mul_assoc at B1,
rw mul_one at B1,
rw ennreal.inv_mul_cancel at B1,
rw mul_one at B1,
apply A2,
{
simp [C1],
},
{
simp,
},
{
apply A1,
},
{
rw ← lt_top_iff_ne_top,
apply lt_of_le_of_lt A2,
simp,
},
end
lemma ennreal.nat_coe_add {a b:ℕ}:(a:ennreal) + (b:ennreal) =
((@has_add.add nat _ a b):ennreal) :=
begin
simp,
end
lemma ennreal.nat_coe_le_coe {a b:ℕ}:(a:ennreal) ≤ (b:ennreal) ↔ (a ≤ b) :=
begin
have B1:(a:ennreal) = ((a:nnreal):ennreal),
{
simp,
},
have B2:(b:ennreal) = ((b:nnreal):ennreal),
{
simp,
},
rw B1,
rw B2,
rw ennreal.coe_le_coe,
split;intros A1,
{
simp at A1,
apply A1,
},
{
simp,
apply A1,
},
end
------------- from Radon-Nikodym --------
lemma ennreal.inv_mul_eq_inv_mul_inv {a b:ennreal}:(a≠ 0) → (b≠ 0) → (a * b)⁻¹=a⁻¹ * b⁻¹ :=
begin
cases a;simp;cases b;simp,
intros A1 A2,
rw ← ennreal.coe_mul,
repeat {rw ← ennreal.coe_inv},
rw ← ennreal.coe_mul,
rw ennreal.coe_eq_coe,
apply @nnreal.inv_mul_eq_inv_mul_inv a b,
apply A2,
apply A1,
rw ← @nnreal.pos_iff (a * b),
rw nnreal.mul_pos_iff_pos_pos,
repeat {rw canonically_ordered_add_monoid.zero_lt_iff_ne_zero},
apply and.intro A1 A2,
end
lemma ennreal.div_dist {a b c:ennreal}:(b≠ 0) → (c≠ 0) → a/(b * c)=(a/b)/c :=
begin
intros A1 A2,
rw div_eq_mul_inv,
rw ennreal.inv_mul_eq_inv_mul_inv,
rw ← mul_assoc,
repeat {rw div_eq_mul_inv},
apply A1,
apply A2,
end
lemma ennreal.div_eq_zero_iff {a b:ennreal}:a/b=0 ↔ (a = 0) ∨ (b = ⊤) :=
begin
cases a;cases b;split;simp;intros A1;simp;simp at A1,
end
/-
Helper function to lift nnreal.exists_unit_frac_lt_pos to ennreal.
-/
lemma ennreal.exists_unit_frac_lt_pos' {ε:nnreal}:0 < ε → (∃ n:ℕ, (1/((n:ennreal) + 1)) < (ε:ennreal)) :=
begin
intros A1,
-- simp at A1,
have C1:= nnreal.exists_unit_frac_lt_pos A1,
cases C1 with n A1,
apply exists.intro n,
have D1:((1:nnreal):ennreal) = 1 := rfl,
rw ← D1,
have D2:((n:nnreal):ennreal) = (n:ennreal),
{
simp,
},
rw ← D2,
rw ← ennreal.coe_add,
rw ← ennreal.coe_div,
rw ennreal.coe_lt_coe,
apply A1,
simp,
end
lemma ennreal.exists_unit_frac_lt_pos {ε:ennreal}:0 < ε → (∃ n:ℕ, (1/((n:ennreal) + 1)) < ε) :=
begin
cases ε,
{
intros A1,
have B1:(0:nnreal) < (1:nnreal),
{
apply zero_lt_one,
},
have B1:=ennreal.exists_unit_frac_lt_pos' B1,
cases B1 with n B1,
apply exists.intro n,
apply lt_of_lt_of_le B1,
simp,
},
{
intros A1,
simp at A1,
have C1:= ennreal.exists_unit_frac_lt_pos' A1,
apply C1,
},
end
lemma ennreal.zero_of_le_all_unit_frac {x:ennreal}:
(∀ (n:ℕ), (x ≤ 1/((n:ennreal) + 1))) → (x = 0) :=
begin
intros A1,
rw ← not_exists_not at A1,
apply by_contradiction,
intros B1,
apply A1,
have B2:0 < x,
{
rw canonically_ordered_add_monoid.zero_lt_iff_ne_zero,
apply B1,
},
have B3:= ennreal.exists_unit_frac_lt_pos B2,
cases B3 with n B3,
apply exists.intro n,
apply not_le_of_lt,
apply B3,
end
lemma ennreal.unit_frac_pos {n:ℕ}:(1/((n:ennreal) + 1))>0 :=
begin
simp,
end
lemma ennreal.div_eq_top_iff {a b:ennreal}:a/b=⊤ ↔
((a = ⊤)∧(b≠ ⊤) )∨ ((a≠ 0)∧(b=0)):=
begin
rw div_eq_mul_inv,
cases a;cases b;simp,
end
lemma ennreal.unit_frac_ne_top {n:ℕ}:(1/((n:ennreal) + 1))≠ ⊤ :=
begin
intro A1,
rw ennreal.div_eq_top_iff at A1,
simp at A1,
apply A1,
end
lemma lt_eq_le_compl {δ α:Type*}
[linear_order α] {f g : δ → α}:{a | f a < g a} ={a | g a ≤ f a}ᶜ :=
begin
apply set.ext,
intros ω;split;intros A3A;simp;simp at A3A;apply A3A,
end
lemma ennreal.lt_add_self {a b:ennreal}:a < ⊤ → 0 < b → a < a + b :=
begin
cases a;cases b;simp,
intros A1,
rw ← ennreal.coe_add,
rw ennreal.coe_lt_coe,
simp,
apply A1,
end
lemma ennreal.lt_add_pos {x ε:ennreal}: (x < ⊤) → (0 < ε) → (x < x + ε) :=
begin
cases ε; cases x; simp,
rw ← ennreal.coe_add,
rw ennreal.coe_lt_coe,
apply nnreal.lt_add_pos,
end
lemma ennreal.add_pos_le_false {x ε:ennreal}: (x < ⊤) → (0 < ε) → (x + ε ≤ x) → false :=
begin
cases ε; cases x; simp,
rw ← ennreal.coe_add,
rw ennreal.coe_le_coe,
apply nnreal.add_pos_le_false,
end
lemma ennreal.le_of_infi {α:Sort*} {f:α → ennreal} {ε:nnreal}:
((⨅ (a:α), f a) < ⊤) → (0 < ε) → (∃ (a:α), f a ≤ ( (⨅ (a:α), f a) + ε)) :=
begin
intros h1 h2,
have h3:infi f ≤ (⨅ (a:α), f a),
{ apply le_refl _, },
rw ← @ennreal.iff_infi_le α at h3,
apply h3 ε h2 h1,
end
lemma ennreal.infi_prop_le_elim (P:Prop) (x:ennreal):
(⨅ (hp:P), x) < ⊤ → P :=
begin
intro h1,
cases classical.em P with h2 h2,
apply h2,
rw infi_prop_false at h1,
simp at h1,
apply false.elim h1,
apply h2,
end
lemma ennreal.add_pos_of_pos {x y:ennreal}:(0 < y) → (0 < x + y) :=
begin
intros h,
apply lt_of_lt_of_le h,
rw add_comm,
apply ennreal.le_add,
apply le_refl _,
end
--Replace with one_div
lemma ennreal.one_div (x:ennreal):1/x = x⁻¹ := begin
simp,
end
lemma ennreal.coe_infi {α:Sort*} [nonempty α] {f:α → nnreal}:
@coe nnreal ennreal _ (⨅ i, f i) = (⨅ i, @coe nnreal ennreal _ (f i)) := begin
simp only [infi],
rw ennreal.coe_Inf,
apply le_antisymm,
{ simp, intros a, apply @infi_le_of_le ennreal nnreal _ _ _ (f a),
apply @infi_le_of_le ennreal α _ _ _ a,
rw infi_pos, apply le_refl _, refl },
{ simp, intros a, apply @Inf_le ennreal _ _ _,
simp, apply exists.intro a, refl },
apply set.range_nonempty,
end
lemma ennreal.coe_supr {α:Sort*} [nonempty α] {f:α → nnreal}:
(bdd_above (set.range f)) →
@coe nnreal ennreal _ (⨆ i, f i) = (⨆ i, @coe nnreal ennreal _ (f i)) := begin
intros h1,
simp only [supr],
rw ennreal.coe_Sup,
apply le_antisymm,
{ simp, intros a, apply @le_Sup ennreal _ _ _,
simp, apply exists.intro a, refl },
{ simp, intros a, apply @le_supr_of_le ennreal nnreal _ _ _ (f a),
apply @le_supr_of_le ennreal α _ _ _ a,
rw supr_pos, apply le_refl _, refl },
apply h1,
end
/- These are tricky to place, because they depend upon ennreal. -/
lemma nnreal.mul_infi {ι:Sort*} [nonempty ι] {f : ι → nnreal} {x : nnreal} :
x * infi f = ⨅i, x * f i :=
begin
rw ← ennreal.coe_eq_coe,
rw ennreal.coe_mul,
rw ennreal.coe_infi,
rw ennreal.mul_infi,
rw ennreal.coe_infi,
have h1:(λ i, @coe nnreal ennreal _ (x * f i)) = (λ i, (↑ x) * (↑ (f i))),
{ ext1 i, rw ennreal.coe_mul },
rw h1,
simp,
end
lemma nnreal.mul_supr {ι:Sort*} [nonempty ι] {f : ι → nnreal} {x : nnreal}
(h:bdd_above (set.range f)) :
x * supr f = ⨆i, x * f i :=
begin
rw ← ennreal.coe_eq_coe,
rw ennreal.coe_mul,
rw ennreal.coe_supr,
rw ennreal.mul_supr,
rw ennreal.coe_supr,
have h1:(λ i, @coe nnreal ennreal _ (x * f i)) = (λ i, (↑ x) * (↑ (f i))),
{ ext1 i, rw ennreal.coe_mul },
rw h1,
{ simp [bdd_above], rw set.nonempty_def,
simp [bdd_above] at h,
rw set.nonempty_def at h,
cases h with y h,
rw mem_upper_bounds at h,
apply exists.intro (x * y),
rw mem_upper_bounds,
intros z h_z,
simp at h_z,
cases h_z with i h_z,
subst z,
have h_mem:(f i) ∈ set.range f,
{ simp },
have h_z' := h (f i) h_mem,
apply mul_le_mul,
apply le_refl _,
apply h_z',
simp,
simp },
{ apply h },
end
|
82684af4104808f1a0d2a7e5e5af453df9233371 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/ring_theory/fractional_ideal.lean | 82222fef50da7b360fa175e6f7380fb6f74c0923 | [
"Apache-2.0"
] | permissive | mcncm/mathlib | 8d25099344d9d2bee62822cb9ed43aa3e09fa05e | fde3d78cadeec5ef827b16ae55664ef115e66f57 | refs/heads/master | 1,672,743,316,277 | 1,602,618,514,000 | 1,602,618,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 27,490 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import ring_theory.localization
import ring_theory.principal_ideal_domain
/-!
# Fractional ideals
This file defines fractional ideals of an integral domain and proves basic facts about them.
## Main definitions
Let `S` be a submonoid of an integral domain `R`, `P` the localization of `R` at `S`, and `f` the
natural ring hom from `R` to `P`.
* `is_fractional` defines which `R`-submodules of `P` are fractional ideals
* `fractional_ideal f` is the type of fractional ideals in `P`
* `has_coe (ideal R) (fractional_ideal f)` instance
* `comm_semiring (fractional_ideal f)` instance:
the typical ideal operations generalized to fractional ideals
* `lattice (fractional_ideal f)` instance
* `map` is the pushforward of a fractional ideal along an algebra morphism
Let `K` be the localization of `R` at `R \ {0}` and `g` the natural ring hom from `R` to `K`.
* `has_div (fractional_ideal g)` instance:
the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined)
## Main statements
* `mul_left_mono` and `mul_right_mono` state that ideal multiplication is monotone
* `right_inverse_eq` states that `1 / I` is the inverse of `I` if one exists
## Implementation notes
Fractional ideals are considered equal when they contain the same elements,
independent of the denominator `a : R` such that `a I ⊆ R`.
Thus, we define `fractional_ideal` to be the subtype of the predicate `is_fractional`,
instead of having `fractional_ideal` be a structure of which `a` is a field.
Most definitions in this file specialize operations from submodules to fractional ideals,
proving that the result of this operation is fractional if the input is fractional.
Exceptions to this rule are defining `(+) := (⊔)` and `⊥ := 0`,
in order to re-use their respective proof terms.
We can still use `simp` to show `I.1 + J.1 = (I + J).1` and `⊥.1 = 0.1`.
In `ring_theory.localization`, we define a copy of the localization map `f`'s codomain `P`
(`f.codomain`) so that the `R`-algebra instance on `P` can 'know' the map needed to induce
the `R`-algebra structure.
We don't assume that the localization is a field until we need it to define ideal quotients.
When this assumption is needed, we replace `S` with `non_zero_divisors R`, making the localization
a field.
## References
* https://en.wikipedia.org/wiki/Fractional_ideal
## Tags
fractional ideal, fractional ideals, invertible ideal
-/
open localization_map
namespace ring
section defs
variables {R : Type*} [integral_domain R] {S : submonoid R} {P : Type*} [comm_ring P]
(f : localization_map S P)
/-- A submodule `I` is a fractional ideal if `a I ⊆ R` for some `a ≠ 0`. -/
def is_fractional (I : submodule R f.codomain) :=
∃ a ∈ S, ∀ b ∈ I, f.is_integer (f.to_map a * b)
/-- The fractional ideals of a domain `R` are ideals of `R` divided by some `a ∈ R`.
More precisely, let `P` be a localization of `R` at some submonoid `S`,
then a fractional ideal `I ⊆ P` is an `R`-submodule of `P`,
such that there is a nonzero `a : R` with `a I ⊆ R`.
-/
def fractional_ideal :=
{I : submodule R f.codomain // is_fractional f I}
end defs
namespace fractional_ideal
open set
open submodule
variables {R : Type*} [integral_domain R] {S : submonoid R} {P : Type*} [comm_ring P]
{f : localization_map S P}
instance : has_coe (fractional_ideal f) (submodule R f.codomain) := ⟨λ I, I.val⟩
@[simp] lemma val_eq_coe (I : fractional_ideal f) : I.val = I := rfl
@[simp] lemma coe_mk (I : submodule R f.codomain) (hI : is_fractional f I) :
(subtype.mk I hI : submodule R f.codomain) = I := rfl
instance : has_mem P (fractional_ideal f) := ⟨λ x I, x ∈ (I : submodule R f.codomain)⟩
/-- Fractional ideals are equal if their submodules are equal.
Combined with `submodule.ext` this gives that fractional ideals are equal if
they have the same elements.
-/
@[ext]
lemma ext {I J : fractional_ideal f} : (I : submodule R f.codomain) = J → I = J :=
subtype.ext_iff_val.mpr
lemma fractional_of_subset_one (I : submodule R f.codomain)
(h : I ≤ (submodule.span R {1})) :
is_fractional f I :=
begin
use [1, S.one_mem],
intros b hb,
rw [f.to_map.map_one, one_mul],
rw ←submodule.one_eq_span at h,
obtain ⟨b', b'_mem, b'_eq_b⟩ := h hb,
rw (show b = f.to_map b', from b'_eq_b.symm),
exact set.mem_range_self b',
end
instance coe_to_fractional_ideal : has_coe (ideal R) (fractional_ideal f) :=
⟨ λ I, ⟨f.coe_submodule I, fractional_of_subset_one _ $ λ x ⟨y, hy, h⟩,
submodule.mem_span_singleton.2 ⟨y, by rw ←h; exact mul_one _⟩⟩ ⟩
@[simp] lemma coe_coe_ideal (I : ideal R) :
((I : fractional_ideal f) : submodule R f.codomain) = f.coe_submodule I := rfl
@[simp] lemma mem_coe {x : f.codomain} {I : ideal R} :
x ∈ (I : fractional_ideal f) ↔ ∃ (x' ∈ I), f.to_map x' = x :=
⟨ λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩,
λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩ ⟩
instance : has_zero (fractional_ideal f) := ⟨(0 : ideal R)⟩
@[simp] lemma mem_zero_iff {x : P} : x ∈ (0 : fractional_ideal f) ↔ x = 0 :=
⟨ (λ ⟨x', x'_mem_zero, x'_eq_x⟩,
have x'_eq_zero : x' = 0 := x'_mem_zero,
by simp [x'_eq_x.symm, x'_eq_zero]),
(λ hx, ⟨0, rfl, by simp [hx]⟩) ⟩
@[simp] lemma coe_zero : ↑(0 : fractional_ideal f) = (⊥ : submodule R f.codomain) :=
submodule.ext $ λ _, mem_zero_iff
lemma coe_ne_bot_iff_nonzero {I : fractional_ideal f} :
↑I ≠ (⊥ : submodule R f.codomain) ↔ I ≠ 0 :=
⟨ λ h h', h (by simp [h']),
λ h h', h (ext (by simp [h'])) ⟩
instance : inhabited (fractional_ideal f) := ⟨0⟩
instance : has_one (fractional_ideal f) :=
⟨(1 : ideal R)⟩
lemma mem_one_iff {x : P} : x ∈ (1 : fractional_ideal f) ↔ ∃ x' : R, f.to_map x' = x :=
iff.intro (λ ⟨x', _, h⟩, ⟨x', h⟩) (λ ⟨x', h⟩, ⟨x', ⟨x', set.mem_univ _, rfl⟩, h⟩)
lemma coe_mem_one (x : R) : f.to_map x ∈ (1 : fractional_ideal f) :=
mem_one_iff.mpr ⟨x, rfl⟩
lemma one_mem_one : (1 : P) ∈ (1 : fractional_ideal f) :=
mem_one_iff.mpr ⟨1, f.to_map.map_one⟩
@[simp] lemma coe_one : ↑(1 : fractional_ideal f) = f.coe_submodule 1 := rfl
section lattice
/-!
### `lattice` section
Defines the order on fractional ideals as inclusion of their underlying sets,
and ports the lattice structure on submodules to fractional ideals.
-/
instance : partial_order (fractional_ideal f) :=
{ le := λ I J, I.1 ≤ J.1,
le_refl := λ I, le_refl I.1,
le_antisymm := λ ⟨I, hI⟩ ⟨J, hJ⟩ hIJ hJI, by { congr, exact le_antisymm hIJ hJI },
le_trans := λ _ _ _ hIJ hJK, le_trans hIJ hJK }
lemma le_iff {I J : fractional_ideal f} : I ≤ J ↔ (∀ x ∈ I, x ∈ J) := iff.refl _
lemma zero_le (I : fractional_ideal f) : 0 ≤ I :=
begin
intros x hx,
convert submodule.zero_mem _,
simpa using hx
end
instance order_bot : order_bot (fractional_ideal f) :=
{ bot := 0,
bot_le := zero_le,
..fractional_ideal.partial_order }
@[simp] lemma bot_eq_zero : (⊥ : fractional_ideal f) = 0 :=
rfl
lemma eq_zero_iff {I : fractional_ideal f} : I = 0 ↔ (∀ x ∈ I, x = (0 : P)) :=
⟨ (λ h x hx, by simpa [h, mem_zero_iff] using hx),
(λ h, le_bot_iff.mp (λ x hx, mem_zero_iff.mpr (h x hx))) ⟩
lemma fractional_sup (I J : fractional_ideal f) : is_fractional f (I.1 ⊔ J.1) :=
begin
rcases I.2 with ⟨aI, haI, hI⟩,
rcases J.2 with ⟨aJ, haJ, hJ⟩,
use aI * aJ,
use S.mul_mem haI haJ,
intros b hb,
rcases mem_sup.mp hb with
⟨bI, hbI, bJ, hbJ, hbIJ⟩,
rw [←hbIJ, mul_add],
apply is_integer_add,
{ rw [mul_comm aI, f.to_map.map_mul, mul_assoc],
apply is_integer_smul (hI bI hbI), },
{ rw [f.to_map.map_mul, mul_assoc],
apply is_integer_smul (hJ bJ hbJ) }
end
lemma fractional_inf (I J : fractional_ideal f) : is_fractional f (I.1 ⊓ J.1) :=
begin
rcases I.2 with ⟨aI, haI, hI⟩,
use aI,
use haI,
intros b hb,
rcases mem_inf.mp hb with ⟨hbI, hbJ⟩,
exact (hI b hbI)
end
instance lattice : lattice (fractional_ideal f) :=
{ inf := λ I J, ⟨I.1 ⊓ J.1, fractional_inf I J⟩,
sup := λ I J, ⟨I.1 ⊔ J.1, fractional_sup I J⟩,
inf_le_left := λ I J, show I.1 ⊓ J.1 ≤ I.1, from inf_le_left,
inf_le_right := λ I J, show I.1 ⊓ J.1 ≤ J.1, from inf_le_right,
le_inf := λ I J K hIJ hIK, show I.1 ≤ (J.1 ⊓ K.1), from le_inf hIJ hIK,
le_sup_left := λ I J, show I.1 ≤ I.1 ⊔ J.1, from le_sup_left,
le_sup_right := λ I J, show J.1 ≤ I.1 ⊔ J.1, from le_sup_right,
sup_le := λ I J K hIK hJK, show (I.1 ⊔ J.1) ≤ K.1, from sup_le hIK hJK,
..fractional_ideal.partial_order }
instance : semilattice_sup_bot (fractional_ideal f) :=
{ ..fractional_ideal.order_bot, ..fractional_ideal.lattice }
end lattice
section semiring
instance : has_add (fractional_ideal f) := ⟨(⊔)⟩
@[simp]
lemma sup_eq_add (I J : fractional_ideal f) : I ⊔ J = I + J := rfl
@[simp]
lemma coe_add (I J : fractional_ideal f) : (↑(I + J) : submodule R f.codomain) = I + J := rfl
lemma fractional_mul (I J : fractional_ideal f) : is_fractional f (I.1 * J.1) :=
begin
rcases I with ⟨I, aI, haI, hI⟩,
rcases J with ⟨I, aJ, haJ, hJ⟩,
use aI * aJ,
use S.mul_mem haI haJ,
intros b hb,
apply submodule.mul_induction_on hb,
{ intros m hm n hn,
obtain ⟨n', hn'⟩ := hJ n hn,
rw [f.to_map.map_mul, mul_comm m, ←mul_assoc, mul_assoc _ _ n],
erw ←hn', rw mul_assoc,
apply hI,
exact submodule.smul_mem _ _ hm },
{ rw [mul_zero],
exact ⟨0, f.to_map.map_zero⟩ },
{ intros x y hx hy,
rw [mul_add],
apply is_integer_add hx hy },
{ intros r x hx,
show f.is_integer (_ * (f.to_map r * x)),
rw [←mul_assoc, ←f.to_map.map_mul, mul_comm _ r, f.to_map.map_mul, mul_assoc],
apply is_integer_smul hx },
end
instance : has_mul (fractional_ideal f) := ⟨λ I J, ⟨I.1 * J.1, fractional_mul I J⟩⟩
@[simp]
lemma coe_mul (I J : fractional_ideal f) : (↑(I * J) : submodule R f.codomain) = I * J := rfl
lemma mul_left_mono (I : fractional_ideal f) : monotone ((*) I) :=
λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul hx (h hy))
lemma mul_right_mono (I : fractional_ideal f) : monotone (λ J, J * I) :=
λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul (h hx) hy)
instance add_comm_monoid : add_comm_monoid (fractional_ideal f) :=
{ add_assoc := λ I J K, sup_assoc,
add_comm := λ I J, sup_comm,
add_zero := λ I, sup_bot_eq,
zero_add := λ I, bot_sup_eq,
..fractional_ideal.has_zero,
..fractional_ideal.has_add }
instance comm_monoid : comm_monoid (fractional_ideal f) :=
{ mul_assoc := λ I J K, ext (submodule.mul_assoc _ _ _),
mul_comm := λ I J, ext (submodule.mul_comm _ _),
mul_one := λ I, begin
ext,
split; intro h,
{ apply mul_le.mpr _ h,
rintros x hx y ⟨y', y'_mem_R, y'_eq_y⟩,
rw [←y'_eq_y, mul_comm],
exact submodule.smul_mem _ _ hx },
{ have : x * 1 ∈ (I * 1) := mul_mem_mul h one_mem_one,
rwa [mul_one] at this }
end,
one_mul := λ I, begin
ext,
split; intro h,
{ apply mul_le.mpr _ h,
rintros x ⟨x', x'_mem_R, x'_eq_x⟩ y hy,
rw ←x'_eq_x,
exact submodule.smul_mem _ _ hy },
{ have : 1 * x ∈ (1 * I) := mul_mem_mul one_mem_one h,
rwa [one_mul] at this }
end,
..fractional_ideal.has_mul,
..fractional_ideal.has_one }
instance comm_semiring : comm_semiring (fractional_ideal f) :=
{ mul_zero := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx
(λ x hx y hy, by simp [mem_zero_iff.mp hy])
rfl
(λ x y hx hy, by simp [hx, hy])
(λ r x hx, by simp [hx])),
zero_mul := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx
(λ x hx y hy, by simp [mem_zero_iff.mp hx])
rfl
(λ x y hx hy, by simp [hx, hy])
(λ r x hx, by simp [hx])),
left_distrib := λ I J K, ext (mul_add _ _ _),
right_distrib := λ I J K, ext (add_mul _ _ _),
..fractional_ideal.add_comm_monoid,
..fractional_ideal.comm_monoid }
variables {P' : Type*} [comm_ring P'] {f' : localization_map S P'}
variables {P'' : Type*} [comm_ring P''] {f'' : localization_map S P''}
lemma fractional_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) :
is_fractional f' (submodule.map g.to_linear_map I.1) :=
begin
rcases I with ⟨I, a, a_nonzero, hI⟩,
use [a, a_nonzero],
intros b hb,
obtain ⟨b', b'_mem, hb'⟩ := submodule.mem_map.mp hb,
obtain ⟨x, hx⟩ := hI b' b'_mem,
use x,
erw [←g.commutes, hx, g.map_smul, hb'],
refl
end
/-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/
def map (g : f.codomain →ₐ[R] f'.codomain) :
fractional_ideal f → fractional_ideal f' :=
λ I, ⟨submodule.map g.to_linear_map I.1, fractional_map g I⟩
@[simp] lemma coe_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) :
↑(map g I) = submodule.map g.to_linear_map I := rfl
@[simp] lemma mem_map {I : fractional_ideal f} {g : f.codomain →ₐ[R] f'.codomain}
{y : f'.codomain} : y ∈ I.map g ↔ ∃ x, x ∈ I ∧ g x = y :=
submodule.mem_map
variables (I J : fractional_ideal f) (g : f.codomain →ₐ[R] f'.codomain)
@[simp] lemma map_id : I.map (alg_hom.id _ _) = I :=
ext (submodule.map_id I.1)
@[simp] lemma map_comp (g' : f'.codomain →ₐ[R] f''.codomain) :
I.map (g'.comp g) = (I.map g).map g' :=
ext (submodule.map_comp g.to_linear_map g'.to_linear_map I.1)
@[simp] lemma map_coe_ideal (I : ideal R) :
(I : fractional_ideal f).map g = I :=
begin
ext x,
simp only [coe_coe_ideal, mem_coe_submodule],
split,
{ rintro ⟨_, ⟨y, hy, rfl⟩, rfl⟩,
exact ⟨y, hy, (g.commutes y).symm⟩ },
{ rintro ⟨y, hy, rfl⟩,
exact ⟨_, ⟨y, hy, rfl⟩, g.commutes y⟩ },
end
@[simp] lemma map_one :
(1 : fractional_ideal f).map g = 1 :=
map_coe_ideal g 1
@[simp] lemma map_zero :
(0 : fractional_ideal f).map g = 0 :=
map_coe_ideal g 0
@[simp] lemma map_add : (I + J).map g = I.map g + J.map g :=
ext (submodule.map_sup _ _ _)
@[simp] lemma map_mul : (I * J).map g = I.map g * J.map g :=
ext (submodule.map_mul _ _ _)
@[simp] lemma map_map_symm (g : f.codomain ≃ₐ[R] f'.codomain) :
(I.map (g : f.codomain →ₐ[R] f'.codomain)).map (g.symm : f'.codomain →ₐ[R] f.codomain) = I :=
by rw [←map_comp, g.symm_comp, map_id]
@[simp] lemma map_symm_map (I : fractional_ideal f') (g : f.codomain ≃ₐ[R] f'.codomain) :
(I.map (g.symm : f'.codomain →ₐ[R] f.codomain)).map (g : f.codomain →ₐ[R] f'.codomain) = I :=
by rw [←map_comp, g.comp_symm, map_id]
/-- If `g` is an equivalence, `map g` is an isomorphism -/
def map_equiv (g : f.codomain ≃ₐ[R] f'.codomain) :
fractional_ideal f ≃+* fractional_ideal f' :=
{ to_fun := map g,
inv_fun := map g.symm,
map_add' := λ I J, map_add I J _,
map_mul' := λ I J, map_mul I J _,
left_inv := λ I, by { rw [←map_comp, alg_equiv.symm_comp, map_id] },
right_inv := λ I, by { rw [←map_comp, alg_equiv.comp_symm, map_id] } }
@[simp] lemma map_equiv_apply (g : f.codomain ≃ₐ[R] f'.codomain) :
map_equiv g I = map ↑g I := rfl
@[simp] lemma map_equiv_refl :
map_equiv alg_equiv.refl = ring_equiv.refl (fractional_ideal f) :=
ring_equiv.ext (λ x, by simp)
/-- `canonical_equiv f f'` is the canonical equivalence between the fractional
ideals in `f.codomain` and in `f'.codomain` -/
noncomputable def canonical_equiv (f f' : localization_map S P) :
fractional_ideal f ≃+* fractional_ideal f' :=
map_equiv
{ commutes' := λ r, ring_equiv_of_ring_equiv_eq _ _ _,
..ring_equiv_of_ring_equiv f f' (ring_equiv.refl R)
(by rw [ring_equiv.to_monoid_hom_refl, submonoid.map_id]) }
end semiring
section fraction_map
/-!
### `fraction_map` section
This section concerns fractional ideals in the field of fractions,
i.e. the type `fractional_ideal g` when `g` is a `fraction_map R K`.
-/
variables {K K' : Type*} [field K] [field K'] {g : fraction_map R K} {g' : fraction_map R K'}
variables {I J : fractional_ideal g} (h : g.codomain →ₐ[R] g'.codomain)
/-- Nonzero fractional ideals contain a nonzero integer. -/
lemma exists_ne_zero_mem_is_integer (hI : I ≠ 0) :
∃ x ≠ (0 : R), g.to_map x ∈ I :=
begin
obtain ⟨y, y_mem, y_not_mem⟩ := submodule.exists_of_lt (bot_lt_iff_ne_bot.mpr hI),
have y_ne_zero : y ≠ 0 := by simpa using y_not_mem,
obtain ⟨z, ⟨x, hx⟩⟩ := g.exists_integer_multiple y,
refine ⟨x, _, _⟩,
{ rw [ne.def, ← g.to_map_eq_zero_iff, hx],
exact mul_ne_zero (g.to_map_ne_zero_of_mem_non_zero_divisors _) y_ne_zero },
{ rw hx,
exact smul_mem _ _ y_mem }
end
lemma map_ne_zero (hI : I ≠ 0) : I.map h ≠ 0 :=
begin
obtain ⟨x, x_ne_zero, hx⟩ := exists_ne_zero_mem_is_integer hI,
contrapose! x_ne_zero with map_eq_zero,
refine g'.to_map_eq_zero_iff.mp (eq_zero_iff.mp map_eq_zero _ (mem_map.mpr _)),
exact ⟨g.to_map x, hx, h.commutes x⟩,
end
@[simp] lemma map_eq_zero_iff : I.map h = 0 ↔ I = 0 :=
⟨imp_of_not_imp_not _ _ (map_ne_zero _),
λ hI, hI.symm ▸ map_zero h⟩
end fraction_map
section quotient
/-!
### `quotient` section
This section defines the ideal quotient of fractional ideals.
In this section we need that each non-zero `y : R` has an inverse in
the localization, i.e. that the localization is a field. We satisfy this
assumption by taking `S = non_zero_divisors R`, `R`'s localization at which
is a field because `R` is a domain.
-/
open_locale classical
variables {K : Type*} [field K] {g : fraction_map R K}
instance : nontrivial (fractional_ideal g) :=
⟨⟨0, 1, λ h,
have this : (1 : K) ∈ (0 : fractional_ideal g) :=
by rw ←g.to_map.map_one; convert coe_mem_one _,
one_ne_zero (mem_zero_iff.mp this) ⟩⟩
lemma fractional_div_of_nonzero {I J : fractional_ideal g} (h : J ≠ 0) :
is_fractional g (I.1 / J.1) :=
begin
rcases I with ⟨I, aI, haI, hI⟩,
rcases J with ⟨J, aJ, haJ, hJ⟩,
obtain ⟨y, mem_J, not_mem_zero⟩ := exists_of_lt (bot_lt_iff_ne_bot.mpr h),
obtain ⟨y', hy'⟩ := hJ y mem_J,
use (aI * y'),
split,
{ apply (non_zero_divisors R).mul_mem haI (mem_non_zero_divisors_iff_ne_zero.mpr _),
intro y'_eq_zero,
have : g.to_map aJ * y = 0 := by rw [←hy', y'_eq_zero, g.to_map.map_zero],
obtain aJ_zero | y_zero := mul_eq_zero.mp this,
{ have : aJ = 0 := g.to_map.injective_iff.1 g.injective _ aJ_zero,
have : aJ ≠ 0 := mem_non_zero_divisors_iff_ne_zero.mp haJ,
contradiction },
{ exact not_mem_zero (mem_zero_iff.mpr y_zero) } },
intros b hb,
rw [g.to_map.map_mul, mul_assoc, mul_comm _ b, hy'],
exact hI _ (hb _ (submodule.smul_mem _ aJ mem_J)),
end
noncomputable instance fractional_ideal_has_div :
has_div (fractional_ideal g) :=
⟨ λ I J, if h : J = 0 then 0 else ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ ⟩
noncomputable instance : has_inv (fractional_ideal g) := ⟨λ I, 1 / I⟩
lemma inv_eq {I : fractional_ideal g} : I⁻¹ = 1 / I := rfl
@[simp] lemma div_zero {I : fractional_ideal g} :
I / 0 = 0 :=
dif_pos rfl
lemma div_nonzero {I J : fractional_ideal g} (h : J ≠ 0) :
(I / J) = ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ :=
dif_neg h
lemma inv_zero : (0 : fractional_ideal g)⁻¹ = 0 :=
div_zero
lemma inv_nonzero {I : fractional_ideal g} (h : I ≠ 0) :
I⁻¹ = ⟨(1 : fractional_ideal g) / I, fractional_div_of_nonzero h⟩ :=
div_nonzero h
lemma coe_inv_of_nonzero {I : fractional_ideal g} (h : I ≠ 0) :
(↑(I⁻¹) : submodule R g.codomain) = g.coe_submodule 1 / I :=
by { rw inv_nonzero h, refl }
@[simp] lemma div_one {I : fractional_ideal g} : I / 1 = I :=
begin
rw [div_nonzero (@one_ne_zero (fractional_ideal g) _ _)],
ext,
split; intro h,
{ convert mem_div_iff_forall_mul_mem.mp h 1
(g.to_map.map_one ▸ coe_mem_one 1), simp },
{ apply mem_div_iff_forall_mul_mem.mpr,
rintros y ⟨y', _, y_eq_y'⟩,
rw [mul_comm],
convert submodule.smul_mem _ y' h,
rw ←y_eq_y',
refl }
end
lemma ne_zero_of_mul_eq_one (I J : fractional_ideal g) (h : I * J = 1) : I ≠ 0 :=
λ hI, @zero_ne_one (fractional_ideal g) _ _ (by { convert h, simp [hI], })
/-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/
theorem right_inverse_eq (I J : fractional_ideal g) (h : I * J = 1) :
J = I⁻¹ :=
begin
have hI : I ≠ 0 := ne_zero_of_mul_eq_one I J h,
suffices h' : I * (1 / I) = 1,
{ exact (congr_arg units.inv $
@units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) },
rw [div_nonzero hI],
apply le_antisymm,
{ apply submodule.mul_le.mpr _,
intros x hx y hy,
rw [mul_comm],
exact mem_div_iff_forall_mul_mem.mp hy x hx },
rw [←h],
apply mul_left_mono I,
apply submodule.le_div_iff.mpr _,
intros y hy x hx,
rw [mul_comm],
exact mul_mem_mul hx hy
end
theorem mul_inv_cancel_iff {I : fractional_ideal g} :
I * I⁻¹ = 1 ↔ ∃ J, I * J = 1 :=
⟨λ h, ⟨I⁻¹, h⟩, λ ⟨J, hJ⟩, by rwa [←right_inverse_eq I J hJ]⟩
variables {K' : Type*} [field K'] {g' : fraction_map R K'}
@[simp] lemma map_div (I J : fractional_ideal g) (h : g.codomain ≃ₐ[R] g'.codomain) :
(I / J).map (h : g.codomain →ₐ[R] g'.codomain) = I.map h / J.map h :=
begin
by_cases H : J = 0,
{ rw [H, div_zero, map_zero, div_zero] },
{ ext x,
simp [div_nonzero H, div_nonzero (map_ne_zero _ H), submodule.map_div] }
end
@[simp] lemma map_inv (I : fractional_ideal g) (h : g.codomain ≃ₐ[R] g'.codomain) :
(I⁻¹).map (h : g.codomain →ₐ[R] g'.codomain) = (I.map h)⁻¹ :=
by rw [inv_eq, map_div, map_one, inv_eq]
end quotient
section principal_ideal_ring
variables {K : Type*} [field K] {g : fraction_map R K}
open_locale classical
open submodule submodule.is_principal
lemma span_fractional_iff {s : set f.codomain} :
is_fractional f (span R s) ↔ ∃ a ∈ S, ∀ (b : P), b ∈ s → f.is_integer (f.to_map a * b) :=
⟨ λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, h b (subset_span hb)⟩,
λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, span_induction hb
h
(is_integer_smul ⟨0, f.to_map.map_zero⟩)
(λ x y hx hy, by { rw mul_add, exact is_integer_add hx hy })
(λ s x hx, by { rw algebra.mul_smul_comm, exact is_integer_smul hx }) ⟩ ⟩
lemma span_singleton_fractional (x : f.codomain) : is_fractional f (span R {x}) :=
let ⟨a, ha⟩ := f.exists_integer_multiple x in
span_fractional_iff.mpr ⟨ a.1, a.2, λ x hx, (mem_singleton_iff.mp hx).symm ▸ ha⟩
/-- `span_singleton x` is the fractional ideal generated by `x` if `0 ∉ S` -/
def span_singleton (x : f.codomain) : fractional_ideal f :=
⟨span R {x}, span_singleton_fractional x⟩
@[simp] lemma coe_span_singleton (x : f.codomain) :
(span_singleton x : submodule R f.codomain) = span R {x} := rfl
lemma eq_span_singleton_of_principal (I : fractional_ideal f) [is_principal I.1] :
I = span_singleton (generator I.1) :=
ext (span_singleton_generator I.1).symm
lemma is_principal_iff (I : fractional_ideal f) :
is_principal I.1 ↔ ∃ x, I = span_singleton x :=
⟨ λ h, ⟨@generator _ _ _ _ _ I.1 h, @eq_span_singleton_of_principal _ _ _ _ _ _ I h⟩,
λ ⟨x, hx⟩, { principal := ⟨x, trans (congr_arg _ hx) (coe_span_singleton x)⟩ } ⟩
@[simp] lemma span_singleton_zero : span_singleton (0 : f.codomain) = 0 :=
by { ext, simp [submodule.mem_span_singleton, eq_comm] }
lemma span_singleton_eq_zero_iff {y : f.codomain} : span_singleton y = 0 ↔ y = 0 :=
⟨ λ h, span_eq_bot.mp (by simpa using congr_arg subtype.val h : span R {y} = ⊥) y (mem_singleton y),
λ h, by simp [h] ⟩
@[simp] lemma span_singleton_one : span_singleton (1 : f.codomain) = 1 :=
begin
ext,
refine mem_span_singleton.trans ((exists_congr _).trans mem_one_iff.symm),
intro x',
refine eq.congr (mul_one _) rfl,
end
@[simp]
lemma span_singleton_mul_span_singleton (x y : f.codomain) :
span_singleton x * span_singleton y = span_singleton (x * y) :=
begin
ext,
simp_rw [coe_mul, coe_span_singleton, span_mul_span, singleton.is_mul_hom.map_mul]
end
@[simp]
lemma coe_ideal_span_singleton (x : R) :
(↑(span R {x} : ideal R) : fractional_ideal f) = span_singleton (f.to_map x) :=
begin
ext y,
refine mem_coe.trans (iff.trans _ mem_span_singleton.symm),
split,
{ rintros ⟨y', hy', rfl⟩,
obtain ⟨x', rfl⟩ := mem_span_singleton.mp hy',
use x',
rw [smul_eq_mul, f.to_map.map_mul],
refl },
{ rintros ⟨y', rfl⟩,
exact ⟨y' * x, mem_span_singleton.mpr ⟨y', rfl⟩, f.to_map.map_mul _ _⟩ }
end
lemma mem_singleton_mul {x y : f.codomain} {I : fractional_ideal f} :
y ∈ span_singleton x * I ↔ ∃ y' ∈ I, y = x * y' :=
begin
split,
{ intro h,
apply submodule.mul_induction_on h,
{ intros x' hx' y' hy',
obtain ⟨a, ha⟩ := mem_span_singleton.mp hx',
use [a • y', I.1.smul_mem a hy'],
rw [←ha, algebra.mul_smul_comm, algebra.smul_mul_assoc] },
{ exact ⟨0, I.1.zero_mem, (mul_zero x).symm⟩ },
{ rintros _ _ ⟨y, hy, rfl⟩ ⟨y', hy', rfl⟩,
exact ⟨y + y', I.1.add_mem hy hy', (mul_add _ _ _).symm⟩ },
{ rintros r _ ⟨y', hy', rfl⟩,
exact ⟨r • y', I.1.smul_mem r hy', (algebra.mul_smul_comm _ _ _).symm ⟩ } },
{ rintros ⟨y', hy', rfl⟩,
exact mul_mem_mul (mem_span_singleton.mpr ⟨1, one_smul _ _⟩) hy' }
end
lemma mul_generator_self_inv (I : fractional_ideal g)
[submodule.is_principal I.1] (h : I ≠ 0) :
I * span_singleton (generator I.1)⁻¹ = 1 :=
begin
-- Rewrite only the `I` that appears alone.
conv_lhs { congr, rw eq_span_singleton_of_principal I },
rw [span_singleton_mul_span_singleton, mul_inv_cancel, span_singleton_one],
intro generator_I_eq_zero,
apply h,
rw [eq_span_singleton_of_principal I, generator_I_eq_zero, span_singleton_zero]
end
lemma exists_eq_span_singleton_mul (I : fractional_ideal g) :
∃ (a : K) (aI : ideal R), I = span_singleton a * aI :=
begin
obtain ⟨a_inv, nonzero, ha⟩ := I.2,
have nonzero := mem_non_zero_divisors_iff_ne_zero.mp nonzero,
have map_a_nonzero := mt g.to_map_eq_zero_iff.mp nonzero,
use (g.to_map a_inv)⁻¹,
use (span_singleton (g.to_map a_inv) * I).1.comap g.lin_coe,
ext,
refine iff.trans _ mem_singleton_mul.symm,
split,
{ intro hx,
obtain ⟨x', hx'⟩ := ha x hx,
refine ⟨g.to_map x', mem_coe.mpr ⟨x', (mem_singleton_mul.mpr ⟨x, hx, hx'⟩), rfl⟩, _⟩,
erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] },
{ rintros ⟨y, hy, rfl⟩,
obtain ⟨x', hx', rfl⟩ := mem_coe.mp hy,
obtain ⟨y', hy', hx'⟩ := mem_singleton_mul.mp hx',
rw lin_coe_apply at hx',
erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul],
exact hy' }
end
instance is_principal {R} [integral_domain R] [is_principal_ideal_ring R] {f : fraction_map R K}
(I : fractional_ideal f) : (I : submodule R f.codomain).is_principal :=
⟨ begin
obtain ⟨a, aI, ha⟩ := exists_eq_span_singleton_mul I,
have := a * f.to_map (generator aI),
use a * f.to_map (generator aI),
suffices : I = span_singleton (a * f.to_map (generator aI)),
{ exact congr_arg subtype.val this },
conv_lhs { rw [ha, ←span_singleton_generator aI] },
rw [coe_ideal_span_singleton (generator aI), span_singleton_mul_span_singleton]
end ⟩
end principal_ideal_ring
end fractional_ideal
end ring
|
4bfb374e88d2cd8001516feab3695d1151d22f4d | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/as_pattern.lean | 3f45c846057a3b6a964c6a1e194d8275c9daec2d | [
"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 | 1,194 | lean | namespace as_pattern
inductive foo
| a | b | c
inductive bar : foo → Type
| a : bar foo.a
| b : bar foo.b
def basic : list foo → list foo
| x@([_]) := x -- `@[` starts an attribute
| x@_ := x
#print prefix as_pattern.basic.equations
def nested : list foo → list foo
| (x@foo.b :: _) := [x]
| x := x
#print prefix as_pattern.nested.equations
def value : option ℕ → option ℕ
| (some x@2) := some x
| x := x
#print prefix as_pattern.value.equations
def weird_but_ok : ℕ → ℕ
| x@y@z := x+y+z
#print prefix as_pattern.weird_but_ok.equations
def too_many : ℕ → ℕ
| x@_ := x
| x@0 := x
| x@_ := x
| x := x
def too_many2 : ℕ → ℕ
| x@x@0 := x
| x@x := x
def dependent : Π (f : foo), bar f → foo
| x@foo.a bar.a := x
| x@_ bar.b := x
#print prefix as_pattern.dependent.equations
section involved
universe variables u v
inductive imf {A : Type u} {B : Type v} (f : A → B) : B → Type (max 1 u v)
| mk : ∀ (a : A), imf (f a)
definition inv_1 {A : Type u} {B : Type v} (f : A → B) : ∀ (b : B), imf f b → A
| x@.(f w) y@(imf.mk w@a) := w
end involved
def unicode : ℕ → ℕ
| n₁@_ := n₁
end as_pattern
|
fb43c631210f1112c5e72cc889831f2de3e461d8 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/ring_theory/discrete_valuation_ring.lean | 96093bf8d466fd71b99a3e4e259b3bf7eef08037 | [
"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 | 17,295 | lean | /-
Copyright (c) 2020 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard
-/
import ring_theory.principal_ideal_domain
import order.conditionally_complete_lattice
import ring_theory.ideal.local_ring
import ring_theory.multiplicity
import ring_theory.valuation.basic
import linear_algebra.adic_completion
/-!
# Discrete valuation rings
This file defines discrete valuation rings (DVRs) and develops a basic interface
for them.
## Important definitions
There are various definitions of a DVR in the literature; we define a DVR to be a local PID
which is not a field (the first definition in Wikipedia) and prove that this is equivalent
to being a PID with a unique non-zero prime ideal (the definition in Serre's
book "Local Fields").
Let R be an integral domain, assumed to be a principal ideal ring and a local ring.
* `discrete_valuation_ring R` : a predicate expressing that R is a DVR
### Definitions
* `add_val R : add_valuation R enat` : the additive valuation on a DVR.
## Implementation notes
It's a theorem that an element of a DVR is a uniformizer if and only if it's irreducible.
We do not hence define `uniformizer` at all, because we can use `irreducible` instead.
## Tags
discrete valuation ring
-/
open_locale classical
universe u
open ideal local_ring
/-- An integral domain is a *discrete valuation ring* (DVR) if it's a local PID which
is not a field. -/
class discrete_valuation_ring (R : Type u) [comm_ring R] [integral_domain R]
extends is_principal_ideal_ring R, local_ring R : Prop :=
(not_a_field' : maximal_ideal R ≠ ⊥)
namespace discrete_valuation_ring
variables (R : Type u) [comm_ring R] [integral_domain R] [discrete_valuation_ring R]
lemma not_a_field : maximal_ideal R ≠ ⊥ := not_a_field'
variable {R}
open principal_ideal_ring
/-- An element of a DVR is irreducible iff it is a uniformizer, that is, generates the
maximal ideal of R -/
theorem irreducible_iff_uniformizer (ϖ : R) :
irreducible ϖ ↔ maximal_ideal R = ideal.span {ϖ} :=
⟨λ hϖ, (eq_maximal_ideal (is_maximal_of_irreducible hϖ)).symm,
begin
intro h,
have h2 : ¬(is_unit ϖ) := show ϖ ∈ maximal_ideal R,
from h.symm ▸ submodule.mem_span_singleton_self ϖ,
refine ⟨h2, _⟩,
intros a b hab,
by_contra h,
push_neg at h,
obtain ⟨ha : a ∈ maximal_ideal R, hb : b ∈ maximal_ideal R⟩ := h,
rw h at ha hb,
rw mem_span_singleton' at ha hb,
rcases ha with ⟨a, rfl⟩,
rcases hb with ⟨b, rfl⟩,
rw (show a * ϖ * (b * ϖ) = ϖ * (ϖ * (a * b)), by ring) at hab,
have h3 := eq_zero_of_mul_eq_self_right _ hab.symm,
{ apply not_a_field R,
simp [h, h3] },
{ intro hh, apply h2,
refine is_unit_of_dvd_one ϖ _,
use a * b, exact hh.symm }
end⟩
lemma _root_.irreducible.maximal_ideal_eq {ϖ : R} (h : irreducible ϖ) :
maximal_ideal R = ideal.span {ϖ} :=
(irreducible_iff_uniformizer _).mp h
variable (R)
/-- Uniformisers exist in a DVR -/
theorem exists_irreducible : ∃ ϖ : R, irreducible ϖ :=
by {simp_rw [irreducible_iff_uniformizer],
exact (is_principal_ideal_ring.principal $ maximal_ideal R).principal}
/-- Uniformisers exist in a DVR -/
theorem exists_prime : ∃ ϖ : R, prime ϖ :=
(exists_irreducible R).imp (λ _, principal_ideal_ring.irreducible_iff_prime.1)
/-- an integral domain is a DVR iff it's a PID with a unique non-zero prime ideal -/
theorem iff_pid_with_one_nonzero_prime (R : Type u) [comm_ring R] [integral_domain R] :
discrete_valuation_ring R ↔ is_principal_ideal_ring R ∧ ∃! P : ideal R, P ≠ ⊥ ∧ is_prime P :=
begin
split,
{ intro RDVR,
rcases id RDVR with ⟨RPID, Rlocal, Rnotafield⟩,
split, assumption,
resetI,
use local_ring.maximal_ideal R,
split, split,
{ assumption },
{ apply_instance } ,
{ rintro Q ⟨hQ1, hQ2⟩,
obtain ⟨q, rfl⟩ := (is_principal_ideal_ring.principal Q).1,
have hq : q ≠ 0,
{ rintro rfl,
apply hQ1,
simp },
erw span_singleton_prime hq at hQ2,
replace hQ2 := hQ2.irreducible,
rw irreducible_iff_uniformizer at hQ2,
exact hQ2.symm } },
{ rintro ⟨RPID, Punique⟩,
haveI : local_ring R := local_of_unique_nonzero_prime R Punique,
refine {not_a_field' := _},
rcases Punique with ⟨P, ⟨hP1, hP2⟩, hP3⟩,
have hPM : P ≤ maximal_ideal R := le_maximal_ideal (hP2.1),
intro h, rw [h, le_bot_iff] at hPM, exact hP1 hPM }
end
lemma associated_of_irreducible {a b : R} (ha : irreducible a) (hb : irreducible b) :
associated a b :=
begin
rw irreducible_iff_uniformizer at ha hb,
rw [←span_singleton_eq_span_singleton, ←ha, hb],
end
end discrete_valuation_ring
namespace discrete_valuation_ring
variable (R : Type*)
/-- Alternative characterisation of discrete valuation rings. -/
def has_unit_mul_pow_irreducible_factorization [comm_ring R] : Prop :=
∃ p : R, irreducible p ∧ ∀ {x : R}, x ≠ 0 → ∃ (n : ℕ), associated (p ^ n) x
namespace has_unit_mul_pow_irreducible_factorization
variables {R} [comm_ring R] (hR : has_unit_mul_pow_irreducible_factorization R)
include hR
lemma unique_irreducible ⦃p q : R⦄ (hp : irreducible p) (hq : irreducible q) :
associated p q :=
begin
rcases hR with ⟨ϖ, hϖ, hR⟩,
suffices : ∀ {p : R} (hp : irreducible p), associated p ϖ,
{ apply associated.trans (this hp) (this hq).symm, },
clear hp hq p q,
intros p hp,
obtain ⟨n, hn⟩ := hR hp.ne_zero,
have : irreducible (ϖ ^ n) := hn.symm.irreducible hp,
rcases lt_trichotomy n 1 with (H|rfl|H),
{ obtain rfl : n = 0, { clear hn this, revert H n, exact dec_trivial },
simpa only [not_irreducible_one, pow_zero] using this, },
{ simpa only [pow_one] using hn.symm, },
{ obtain ⟨n, rfl⟩ : ∃ k, n = 1 + k + 1 := nat.exists_eq_add_of_lt H,
rw pow_succ at this,
rcases this.is_unit_or_is_unit rfl with H0|H0,
{ exact (hϖ.not_unit H0).elim, },
{ rw [add_comm, pow_succ] at H0,
exact (hϖ.not_unit (is_unit_of_mul_is_unit_left H0)).elim } }
end
variables [integral_domain R]
/-- An integral domain in which there is an irreducible element `p`
such that every nonzero element is associated to a power of `p` is a unique factorization domain.
See `discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization`. -/
theorem to_unique_factorization_monoid : unique_factorization_monoid R :=
let p := classical.some hR in
let spec := classical.some_spec hR in
unique_factorization_monoid.of_exists_prime_factors $ λ x hx,
begin
use multiset.repeat p (classical.some (spec.2 hx)),
split,
{ intros q hq,
have hpq := multiset.eq_of_mem_repeat hq,
rw hpq,
refine ⟨spec.1.ne_zero, spec.1.not_unit, _⟩,
intros a b h,
by_cases ha : a = 0,
{ rw ha, simp only [true_or, dvd_zero], },
by_cases hb : b = 0,
{ rw hb, simp only [or_true, dvd_zero], },
obtain ⟨m, u, rfl⟩ := spec.2 ha,
rw [mul_assoc, mul_left_comm, is_unit.dvd_mul_left _ _ _ (units.is_unit _)] at h,
rw is_unit.dvd_mul_right (units.is_unit _),
by_cases hm : m = 0,
{ simp only [hm, one_mul, pow_zero] at h ⊢, right, exact h },
left,
obtain ⟨m, rfl⟩ := nat.exists_eq_succ_of_ne_zero hm,
rw pow_succ,
apply dvd_mul_of_dvd_left dvd_rfl _ },
{ rw [multiset.prod_repeat], exact (classical.some_spec (spec.2 hx)), }
end
omit hR
lemma of_ufd_of_unique_irreducible [unique_factorization_monoid R]
(h₁ : ∃ p : R, irreducible p)
(h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) :
has_unit_mul_pow_irreducible_factorization R :=
begin
obtain ⟨p, hp⟩ := h₁,
refine ⟨p, hp, _⟩,
intros x hx,
cases wf_dvd_monoid.exists_factors x hx with fx hfx,
refine ⟨fx.card, _⟩,
have H := hfx.2,
rw ← associates.mk_eq_mk_iff_associated at H ⊢,
rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat],
congr' 1,
symmetry,
rw multiset.eq_repeat,
simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true,
multiset.mem_map, exists_imp_distrib],
rintros _ q hq rfl,
rw associates.mk_eq_mk_iff_associated,
apply h₂ (hfx.1 _ hq) hp,
end
end has_unit_mul_pow_irreducible_factorization
lemma aux_pid_of_ufd_of_unique_irreducible
(R : Type u) [comm_ring R] [integral_domain R] [unique_factorization_monoid R]
(h₁ : ∃ p : R, irreducible p)
(h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) :
is_principal_ideal_ring R :=
begin
constructor,
intro I,
by_cases I0 : I = ⊥, { rw I0, use 0, simp only [set.singleton_zero, submodule.span_zero], },
obtain ⟨x, hxI, hx0⟩ : ∃ x ∈ I, x ≠ (0:R) := I.ne_bot_iff.mp I0,
obtain ⟨p, hp, H⟩ :=
has_unit_mul_pow_irreducible_factorization.of_ufd_of_unique_irreducible h₁ h₂,
have ex : ∃ n : ℕ, p ^ n ∈ I,
{ obtain ⟨n, u, rfl⟩ := H hx0,
refine ⟨n, _⟩,
simpa only [units.mul_inv_cancel_right] using I.mul_mem_right ↑u⁻¹ hxI, },
constructor,
use p ^ (nat.find ex),
show I = ideal.span _,
apply le_antisymm,
{ intros r hr,
by_cases hr0 : r = 0,
{ simp only [hr0, submodule.zero_mem], },
obtain ⟨n, u, rfl⟩ := H hr0,
simp only [mem_span_singleton, units.is_unit, is_unit.dvd_mul_right],
apply pow_dvd_pow,
apply nat.find_min',
simpa only [units.mul_inv_cancel_right] using I.mul_mem_right ↑u⁻¹ hr, },
{ erw submodule.span_singleton_le_iff_mem,
exact nat.find_spec ex, },
end
/--
A unique factorization domain with at least one irreducible element
in which all irreducible elements are associated
is a discrete valuation ring.
-/
lemma of_ufd_of_unique_irreducible
{R : Type u} [comm_ring R] [integral_domain R] [unique_factorization_monoid R]
(h₁ : ∃ p : R, irreducible p)
(h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) :
discrete_valuation_ring R :=
begin
rw iff_pid_with_one_nonzero_prime,
haveI PID : is_principal_ideal_ring R := aux_pid_of_ufd_of_unique_irreducible R h₁ h₂,
obtain ⟨p, hp⟩ := h₁,
refine ⟨PID, ⟨ideal.span {p}, ⟨_, _⟩, _⟩⟩,
{ rw submodule.ne_bot_iff,
refine ⟨p, ideal.mem_span_singleton.mpr (dvd_refl p), hp.ne_zero⟩, },
{ rwa [ideal.span_singleton_prime hp.ne_zero,
← unique_factorization_monoid.irreducible_iff_prime], },
{ intro I,
rw ← submodule.is_principal.span_singleton_generator I,
rintro ⟨I0, hI⟩,
apply span_singleton_eq_span_singleton.mpr,
apply h₂ _ hp,
erw [ne.def, span_singleton_eq_bot] at I0,
rwa [unique_factorization_monoid.irreducible_iff_prime, ← ideal.span_singleton_prime I0],
apply_instance, },
end
/--
An integral domain in which there is an irreducible element `p`
such that every nonzero element is associated to a power of `p`
is a discrete valuation ring.
-/
lemma of_has_unit_mul_pow_irreducible_factorization {R : Type u} [comm_ring R] [integral_domain R]
(hR : has_unit_mul_pow_irreducible_factorization R) :
discrete_valuation_ring R :=
begin
letI : unique_factorization_monoid R := hR.to_unique_factorization_monoid,
apply of_ufd_of_unique_irreducible _ hR.unique_irreducible,
unfreezingI { obtain ⟨p, hp, H⟩ := hR, exact ⟨p, hp⟩, },
end
section
variables [comm_ring R] [integral_domain R] [discrete_valuation_ring R]
variable {R}
lemma associated_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) :
∃ (n : ℕ), associated x (ϖ ^ n) :=
begin
have : wf_dvd_monoid R := is_noetherian_ring.wf_dvd_monoid,
cases wf_dvd_monoid.exists_factors x hx with fx hfx,
unfreezingI { use fx.card },
have H := hfx.2,
rw ← associates.mk_eq_mk_iff_associated at H ⊢,
rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_repeat],
congr' 1,
rw multiset.eq_repeat,
simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true,
multiset.mem_map, exists_imp_distrib],
rintros _ _ _ rfl,
rw associates.mk_eq_mk_iff_associated,
refine associated_of_irreducible _ _ hirr,
apply hfx.1,
assumption
end
lemma eq_unit_mul_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) :
∃ (n : ℕ) (u : units R), x = u * ϖ ^ n :=
begin
obtain ⟨n, hn⟩ := associated_pow_irreducible hx hirr,
obtain ⟨u, rfl⟩ := hn.symm,
use [n, u],
apply mul_comm,
end
open submodule.is_principal
lemma ideal_eq_span_pow_irreducible {s : ideal R} (hs : s ≠ ⊥) {ϖ : R} (hirr : irreducible ϖ) :
∃ n : ℕ, s = ideal.span {ϖ ^ n} :=
begin
have gen_ne_zero : generator s ≠ 0,
{ rw [ne.def, ← eq_bot_iff_generator_eq_zero], assumption },
rcases associated_pow_irreducible gen_ne_zero hirr with ⟨n, u, hnu⟩,
use n,
have : span _ = _ := span_singleton_generator s,
rw [← this, ← hnu, span_singleton_eq_span_singleton],
use u
end
lemma unit_mul_pow_congr_pow {p q : R} (hp : irreducible p) (hq : irreducible q)
(u v : units R) (m n : ℕ) (h : ↑u * p ^ m = v * q ^ n) :
m = n :=
begin
have key : associated (multiset.repeat p m).prod (multiset.repeat q n).prod,
{ rw [multiset.prod_repeat, multiset.prod_repeat, associated],
refine ⟨u * v⁻¹, _⟩,
simp only [units.coe_mul],
rw [mul_left_comm, ← mul_assoc, h, mul_right_comm, units.mul_inv, one_mul], },
have := multiset.card_eq_card_of_rel (unique_factorization_monoid.factors_unique _ _ key),
{ simpa only [multiset.card_repeat] },
all_goals
{ intros x hx, replace hx := multiset.eq_of_mem_repeat hx,
unfreezingI { subst hx, assumption } },
end
lemma unit_mul_pow_congr_unit {ϖ : R} (hirr : irreducible ϖ) (u v : units R) (m n : ℕ)
(h : ↑u * ϖ ^ m = v * ϖ ^ n) :
u = v :=
begin
obtain rfl : m = n := unit_mul_pow_congr_pow hirr hirr u v m n h,
rw ← sub_eq_zero at h,
rw [← sub_mul, mul_eq_zero] at h,
cases h,
{ rw sub_eq_zero at h, exact_mod_cast h },
{ apply (hirr.ne_zero (pow_eq_zero h)).elim, }
end
/-!
## The additive valuation on a DVR
-/
open multiplicity
/-- The `enat`-valued additive valuation on a DVR -/
noncomputable def add_val
(R : Type u) [comm_ring R] [integral_domain R] [discrete_valuation_ring R] :
add_valuation R enat :=
add_valuation (classical.some_spec (exists_prime R))
lemma add_val_def (r : R) (u : units R) {ϖ : R} (hϖ : irreducible ϖ) (n : ℕ) (hr : r = u * ϖ ^ n) :
add_val R r = n :=
by rw [add_val, add_valuation_apply, hr,
eq_of_associated_left (associated_of_irreducible R hϖ
(classical.some_spec (exists_prime R)).irreducible),
eq_of_associated_right (associated.symm ⟨u, mul_comm _ _⟩),
multiplicity_pow_self_of_prime (principal_ideal_ring.irreducible_iff_prime.1 hϖ)]
lemma add_val_def' (u : units R) {ϖ : R} (hϖ : irreducible ϖ) (n : ℕ) :
add_val R ((u : R) * ϖ ^ n) = n :=
add_val_def _ u hϖ n rfl
@[simp] lemma add_val_zero : add_val R 0 = ⊤ :=
(add_val R).map_zero
@[simp] lemma add_val_one : add_val R 1 = 0 :=
(add_val R).map_one
@[simp] lemma add_val_uniformizer {ϖ : R} (hϖ : irreducible ϖ) : add_val R ϖ = 1 :=
by simpa only [one_mul, eq_self_iff_true, units.coe_one, pow_one, forall_true_left, nat.cast_one]
using add_val_def ϖ 1 hϖ 1
@[simp] lemma add_val_mul {a b : R} :
add_val R (a * b) = add_val R a + add_val R b :=
(add_val R).map_mul _ _
lemma add_val_pow (a : R) (n : ℕ) : add_val R (a ^ n) = n • add_val R a :=
(add_val R).map_pow _ _
lemma _root_.irreducible.add_val_pow {ϖ : R} (h : irreducible ϖ) (n : ℕ) :
add_val R (ϖ ^ n) = n :=
by rw [add_val_pow, add_val_uniformizer h, nsmul_one]
lemma add_val_eq_top_iff {a : R} : add_val R a = ⊤ ↔ a = 0 :=
begin
have hi := (classical.some_spec (exists_prime R)).irreducible,
split,
{ contrapose,
intro h,
obtain ⟨n, ha⟩ := associated_pow_irreducible h hi,
obtain ⟨u, rfl⟩ := ha.symm,
rw [mul_comm, add_val_def' u hi n],
exact enat.coe_ne_top _ },
{ rintro rfl,
exact add_val_zero }
end
lemma add_val_le_iff_dvd {a b : R} : add_val R a ≤ add_val R b ↔ a ∣ b :=
begin
have hp := classical.some_spec (exists_prime R),
split; intro h,
{ by_cases ha0 : a = 0,
{ rw [ha0, add_val_zero, top_le_iff, add_val_eq_top_iff] at h,
rw h,
apply dvd_zero },
obtain ⟨n, ha⟩ := associated_pow_irreducible ha0 hp.irreducible,
rw [add_val, add_valuation_apply, add_valuation_apply,
multiplicity_le_multiplicity_iff] at h,
exact ha.dvd.trans (h n ha.symm.dvd), },
{ rw [add_val, add_valuation_apply, add_valuation_apply],
exact multiplicity_le_multiplicity_of_dvd_right h }
end
lemma add_val_add {a b : R} :
min (add_val R a) (add_val R b) ≤ add_val R (a + b) :=
(add_val R).map_add _ _
end
instance (R : Type*) [comm_ring R] [integral_domain R] [discrete_valuation_ring R] :
is_Hausdorff (maximal_ideal R) R :=
{ haus' := λ x hx,
begin
obtain ⟨ϖ, hϖ⟩ := exists_irreducible R,
simp only [← ideal.one_eq_top, smul_eq_mul, mul_one, smodeq.zero,
hϖ.maximal_ideal_eq, ideal.span_singleton_pow, ideal.mem_span_singleton,
← add_val_le_iff_dvd, hϖ.add_val_pow] at hx,
rwa [← add_val_eq_top_iff, enat.eq_top_iff_forall_le],
end }
end discrete_valuation_ring
|
91ec8eed70aa2924320a77ba4ff681d2c75703a9 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/check_expr.lean | 67e0946f758bebb7c2a152cb001fd792e2528214 | [
"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 | 141 | lean | import data.list
open sigma list
theorem foo (A : Type) (l : list A): A → A → list A :=
begin
intros [a, b],
check_expr (a::l),
end
|
5991361e6214a800c30d7592164b7303617a6c4b | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /test/matrix.lean | d5006062da3e7abd82a31f9a4b489c06840773b1 | [
"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 | 3,188 | lean | import data.matrix.notation
import linear_algebra.determinant
import group_theory.perm.fin
import tactic.norm_swap
variables {α β : Type} [semiring α] [ring β]
namespace matrix
open_locale matrix
example {a a' b b' c c' d d' : α} :
![![a, b], ![c, d]] + ![![a', b'], ![c', d']] = ![![a + a', b + b'], ![c + c', d + d']] :=
by simp
example {a a' b b' c c' d d' : β} :
![![a, b], ![c, d]] - ![![a', b'], ![c', d']] = ![![a - a', b - b'], ![c - c', d - d']] :=
by simp
example {a a' b b' c c' d d' : α} :
![![a, b], ![c, d]] ⬝ ![![a', b'], ![c', d']] =
![![a * a' + b * c', a * b' + b * d'], ![c * a' + d * c', c * b' + d * d']] :=
by simp
example {a b c d x y : α} :
mul_vec ![![a, b], ![c, d]] ![x, y] = ![a * x + b * y, c * x + d * y] :=
by simp
example {a b c d : α} : minor ![![a, b], ![c, d]] ![1, 0] ![0] = ![![c], ![a]] :=
by { ext, simp }
example {a b c : α} : ![a, b, c] 0 = a := by simp
example {a b c : α} : ![a, b, c] 1 = b := by simp
example {a b c : α} : ![a, b, c] 2 = c := by simp
example {a b c d : α} : ![a, b, c, d] 0 = a := by simp
example {a b c d : α} : ![a, b, c, d] 1 = b := by simp
example {a b c d : α} : ![a, b, c, d] 2 = c := by simp
example {a b c d : α} : ![a, b, c, d] 3 = d := by simp
example {a b c d : α} : ![a, b, c, d] 42 = c := by simp
example {a b c d e : α} : ![a, b, c, d, e] 0 = a := by simp
example {a b c d e : α} : ![a, b, c, d, e] 1 = b := by simp
example {a b c d e : α} : ![a, b, c, d, e] 2 = c := by simp
example {a b c d e : α} : ![a, b, c, d, e] 3 = d := by simp
example {a b c d e : α} : ![a, b, c, d, e] 4 = e := by simp
example {a b c d e : α} : ![a, b, c, d, e] 5 = a := by simp
example {a b c d e : α} : ![a, b, c, d, e] 6 = b := by simp
example {a b c d e : α} : ![a, b, c, d, e] 7 = c := by simp
example {a b c d e : α} : ![a, b, c, d, e] 8 = d := by simp
example {a b c d e : α} : ![a, b, c, d, e] 9 = e := by simp
example {a b c d e : α} : ![a, b, c, d, e] 123 = d := by simp
example {a b c d e : α} : ![a, b, c, d, e] 123456789 = e := by simp
example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 5 = f := by simp
example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 7 = h := by simp
example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 37 = f := by simp
example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 99 = d := by simp
example {α : Type*} [comm_ring α] {a b c d : α} :
matrix.det ![![a, b], ![c, d]] = a * d - b * c :=
begin
-- TODO: can we make this require less steering?
simp [matrix.det_apply', finset.univ_perm_fin_succ, ←finset.univ_product_univ, finset.sum_product,
fin.sum_univ_succ, fin.prod_univ_succ],
ring
end
example {α : Type*} [comm_ring α] (A : matrix (fin 3) (fin 3) α) {a b c d e f g h i : α} :
matrix.det ![![a, b, c], ![d, e, f], ![g, h, i]] =
a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g :=
begin
-- We utilize the `norm_swap` plugin for `norm_num` to reduce swap terms
norm_num [matrix.det_apply', finset.univ_perm_fin_succ, ←finset.univ_product_univ,
finset.sum_product, fin.sum_univ_succ, fin.prod_univ_succ],
ring
end
end matrix
|
ec480981f00d1fee61b942d7b1ab0b521e3033de | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Meta/Match/MatchPatternAttr.lean | bd5367b4e3bdef67394f0d9fecc840a0306769af | [
"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 | 579 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Attributes
namespace Lean
builtin_initialize matchPatternAttr : TagAttribute ←
registerTagAttribute `matchPattern "mark that a definition can be used in a pattern (remark: the dependent pattern matching compiler will unfold the definition)"
@[export lean_has_match_pattern_attribute]
def hasMatchPatternAttribute (env : Environment) (n : Name) : Bool :=
matchPatternAttr.hasTag env n
end Lean
|
a3a3d232392133ea30b751b957a6519538c61217 | 7056dcccc8ffc1e6f9f533f3fed8ef16ff9fcc1e | /src/Init/Lean/Parser/Parser.lean | 995cb7d1949edd7cde14bff4ca8975c0df849a29 | [
"Apache-2.0"
] | permissive | graydon/lean4 | d73f60d0aa60e64e8d15674538bb5921aad5a4d1 | ec9f4b579dc6b4a20407d2735f8ad91de29bfdb5 | refs/heads/master | 1,650,641,753,817 | 1,587,651,832,000 | 1,587,733,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 78,671 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
prelude
import Init.Lean.Data.Trie
import Init.Lean.Data.Position
import Init.Lean.Syntax
import Init.Lean.ToExpr
import Init.Lean.Environment
import Init.Lean.Attributes
import Init.Lean.Message
import Init.Lean.Compiler.InitAttr
namespace Lean
namespace Parser
def isLitKind (k : SyntaxNodeKind) : Bool :=
k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind
abbrev mkAtom (info : SourceInfo) (val : String) : Syntax :=
Syntax.atom info val
abbrev mkIdent (info : SourceInfo) (rawVal : Substring) (val : Name) : Syntax :=
Syntax.ident (some info) rawVal val []
/- Return character after position `pos` -/
def getNext (input : String) (pos : Nat) : Char :=
input.get (input.next pos)
/- Function application precedence.
In the standard lean language, only two tokens have precedence higher that `appPrec`.
- The token `.` has precedence `appPrec+1`. Thus, field accesses like `g (h x).f` are parsed as `g ((h x).f)`,
not `(g (h x)).f`
- The token `[` when not preceded with whitespace has precedence `appPrec+1`. If there is whitespace before
`[`, then its precedence is `appPrec`. Thus, `f a[i]` is parsed as `f (a[i])` where `a[i]` is an "find-like operation"
(e.g., array access, map access, etc.). `f a [i]` is parsed as `(f a) [i]` where `[i]` is a singleton collection
(e.g., a list). -/
def appPrec : Nat := 1024
structure TokenConfig :=
(val : String)
(lbp : Option Nat := none)
(lbpNoWs : Option Nat := none) -- optional left-binding power when there is not whitespace before the token.
namespace TokenConfig
def beq : TokenConfig → TokenConfig → Bool
| ⟨val₁, lbp₁, lbpnws₁⟩, ⟨val₂, lbp₂, lbpnws₂⟩ => val₁ == val₂ && lbp₁ == lbp₂ && lbpnws₁ == lbpnws₂
instance : HasBeq TokenConfig :=
⟨beq⟩
def toStr : TokenConfig → String
| ⟨val, some lbp, some lbpnws⟩ => val ++ ":" ++ toString lbp ++ ":" ++ toString lbpnws
| ⟨val, some lbp, none⟩ => val ++ ":" ++ toString lbp
| ⟨val, none, some lbpnws⟩ => val ++ ":none:" ++ toString lbpnws
| ⟨val, none, none⟩ => val
instance : HasToString TokenConfig := ⟨toStr⟩
end TokenConfig
structure TokenCacheEntry :=
(startPos stopPos : String.Pos := 0)
(token : Syntax := Syntax.missing)
structure ParserCache :=
(tokenCache : TokenCacheEntry := {})
def initCacheForInput (input : String) : ParserCache :=
{ tokenCache := { startPos := input.bsize + 1 /- make sure it is not a valid position -/} }
abbrev TokenTable := Trie TokenConfig
abbrev SyntaxNodeKindSet := PersistentHashMap SyntaxNodeKind Unit
def SyntaxNodeKindSet.insert (s : SyntaxNodeKindSet) (k : SyntaxNodeKind) : SyntaxNodeKindSet :=
s.insert k ()
/-
Input string and related data. Recall that the `FileMap` is a helper structure for mapping
`String.Pos` in the input string to line/column information. -/
structure InputContext :=
(input : String)
(fileName : String)
(fileMap : FileMap)
instance InputContext.inhabited : Inhabited InputContext :=
⟨{ input := "", fileName := "", fileMap := arbitrary _ }⟩
structure ParserContext extends InputContext :=
(rbp : Nat)
(env : Environment)
(tokens : TokenTable)
structure Error :=
(unexpected : String := "")
(expected : List String := [])
namespace Error
instance : Inhabited Error := ⟨{}⟩
private def expectedToString : List String → String
| [] => ""
| [e] => e
| [e1, e2] => e1 ++ " or " ++ e2
| e::es => e ++ ", " ++ expectedToString es
protected def toString (e : Error) : String :=
let unexpected := if e.unexpected == "" then [] else [e.unexpected];
let expected := if e.expected == [] then [] else
let expected := e.expected.toArray.qsort (fun e e' => e < e');
let expected := expected.toList.eraseReps;
["expected " ++ expectedToString expected];
"; ".intercalate $ unexpected ++ expected
instance : HasToString Error := ⟨Error.toString⟩
protected def beq (e₁ e₂ : Error) : Bool :=
e₁.unexpected == e₂.unexpected && e₁.expected == e₂.expected
instance : HasBeq Error := ⟨Error.beq⟩
def merge (e₁ e₂ : Error) : Error :=
match e₂ with
| { unexpected := u, .. } => { unexpected := if u == "" then e₁.unexpected else u, expected := e₁.expected ++ e₂.expected }
end Error
structure ParserState :=
(stxStack : Array Syntax := #[])
(pos : String.Pos := 0)
(cache : ParserCache := {})
(errorMsg : Option Error := none)
namespace ParserState
@[inline] def hasError (s : ParserState) : Bool :=
s.errorMsg != none
@[inline] def stackSize (s : ParserState) : Nat :=
s.stxStack.size
def restore (s : ParserState) (iniStackSz : Nat) (iniPos : Nat) : ParserState :=
{ stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos, .. s}
def setPos (s : ParserState) (pos : Nat) : ParserState :=
{ pos := pos, .. s }
def setCache (s : ParserState) (cache : ParserCache) : ParserState :=
{ cache := cache, .. s }
def pushSyntax (s : ParserState) (n : Syntax) : ParserState :=
{ stxStack := s.stxStack.push n, .. s }
def popSyntax (s : ParserState) : ParserState :=
{ stxStack := s.stxStack.pop, .. s }
def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState :=
{ stxStack := s.stxStack.shrink iniStackSz, .. s }
def next (s : ParserState) (input : String) (pos : Nat) : ParserState :=
{ pos := input.next pos, .. s }
def toErrorMsg (ctx : ParserContext) (s : ParserState) : String :=
match s.errorMsg with
| none => ""
| some msg =>
let pos := ctx.fileMap.toPosition s.pos;
mkErrorStringWithPos ctx.fileName pos.line pos.column (toString msg)
def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ =>
if err != none && stack.size == iniStackSz then
-- If there is an error but there are no new nodes on the stack, we just return `s`
s
else
let newNode := Syntax.node k (stack.extract iniStackSz stack.size);
let stack := stack.shrink iniStackSz;
let stack := stack.push newNode;
⟨stack, pos, cache, err⟩
def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ =>
let newNode := Syntax.node k (stack.extract (iniStackSz - 1) stack.size);
let stack := stack.shrink iniStackSz;
let stack := stack.push newNode;
⟨stack, pos, cache, err⟩
def mkError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩
def mkUnexpectedError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩
def mkEOIError (s : ParserState) : ParserState :=
s.mkUnexpectedError "end of input"
def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩
def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := ex }⟩
def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩
end ParserState
def ParserFn := ParserContext → ParserState → ParserState
instance ParserFn.inhabited : Inhabited ParserFn := ⟨fun _ => id⟩
inductive FirstTokens
| epsilon : FirstTokens
| unknown : FirstTokens
| tokens : List TokenConfig → FirstTokens
| optTokens : List TokenConfig → FirstTokens
namespace FirstTokens
def seq : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => tks
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| tks, _ => tks
def toOptional : FirstTokens → FirstTokens
| tokens tks => optTokens tks
| tks => tks
def merge : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => toOptional tks
| tks, epsilon => toOptional tks
| tokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| tokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => optTokens (s₁ ++ s₂)
| _, _ => unknown
def toStr : FirstTokens → String
| epsilon => "epsilon"
| unknown => "unknown"
| tokens tks => toString tks
| optTokens tks => "?" ++ toString tks
instance : HasToString FirstTokens := ⟨toStr⟩
end FirstTokens
structure ParserInfo :=
(collectTokens : List TokenConfig → List TokenConfig := id)
(collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id)
(firstTokens : FirstTokens := FirstTokens.unknown)
structure Parser :=
(info : ParserInfo := {})
(fn : ParserFn)
instance Parser.inhabited : Inhabited Parser :=
⟨{ fn := fun _ s => s }⟩
abbrev TrailingParser := Parser
@[noinline] def epsilonInfo : ParserInfo :=
{ firstTokens := FirstTokens.epsilon }
@[inline] def checkStackTopFn (p : Syntax → Bool) : ParserFn :=
fun c s =>
if p s.stxStack.back then s
else s.mkUnexpectedError "invalid leading token"
@[inline] def checkStackTop (p : Syntax → Bool) : Parser :=
{ info := epsilonInfo,
fn := checkStackTopFn p }
@[inline] def andthenFn (p q : ParserFn) : ParserFn :=
fun c s =>
let s := p c s;
if s.hasError then s else q c s
@[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.seq q.firstTokens }
@[inline] def andthen (p q : Parser) : Parser :=
{ info := andthenInfo p.info q.info,
fn := andthenFn p.fn q.fn }
instance hashAndthen : HasAndthen Parser :=
⟨andthen⟩
@[inline] def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let s := p c s;
s.mkNode n iniSz
@[inline] def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let s := p c s;
s.mkTrailingNode n iniSz
@[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens,
collectKinds := fun s => (p.collectKinds s).insert n,
firstTokens := p.firstTokens }
@[inline] def node (n : SyntaxNodeKind) (p : Parser) : Parser :=
{ info := nodeInfo n p.info,
fn := nodeFn n p.fn }
@[inline] def leadingNode (n : SyntaxNodeKind) (p : Parser) : Parser :=
node n p
@[inline] def trailingNode (n : SyntaxNodeKind) (p : Parser) : TrailingParser :=
{ info := nodeInfo n p.info,
fn := trailingNodeFn n p.fn }
@[inline] def group (p : Parser) : Parser :=
node nullKind p
def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, some error2⟩ =>
if pos == iniPos then ⟨stack, pos, cache, some (error1.merge error2)⟩
else s
| other => other
@[inline] def orelseFn (p q : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
match s.errorMsg with
| some errorMsg =>
if s.pos == iniPos then
mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos
else
s
| none => s
@[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.merge q.firstTokens }
@[inline] def orelse (p q : Parser) : Parser :=
{ info := orelseInfo p.info q.info,
fn := orelseFn p.fn q.fn }
instance hashOrelse : HasOrelse Parser :=
⟨orelse⟩
@[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo :=
{ collectTokens := info.collectTokens,
collectKinds := info.collectKinds }
@[inline] def tryFn (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
match p c s with
| ⟨stack, _, cache, some msg⟩ => ⟨stack.shrink iniSz, iniPos, cache, some msg⟩
| other => other
@[inline] def try (p : Parser) : Parser :=
{ info := p.info,
fn := tryFn p.fn }
@[inline] def optionalFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s;
s.mkNode nullKind iniSz
@[noinline] def optionaInfo (p : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens,
collectKinds := p.collectKinds,
firstTokens := p.firstTokens.toOptional }
@[inline] def optional (p : Parser) : Parser :=
{ info := optionaInfo p.info,
fn := optionalFn p.fn }
@[inline] def lookaheadFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
if s.hasError then s else s.restore iniSz iniPos
@[inline] def lookahead (p : Parser) : Parser :=
{ info := p.info,
fn := lookaheadFn p.fn }
@[specialize] partial def manyAux (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
if s.hasError then
if iniPos == s.pos then s.restore iniSz iniPos else s
else if iniPos == s.pos then s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything"
else manyAux c s
@[inline] def manyFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let s := manyAux p c s;
s.mkNode nullKind iniSz
@[inline] def many (p : Parser) : Parser :=
{ info := noFirstTokenInfo p.info,
fn := manyFn p.fn }
@[inline] def many1Fn (p : ParserFn) (unboxSingleton : Bool) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let s := andthenFn p (manyAux p) c s;
if s.stackSize - iniSz == 1 && unboxSingleton then
s
else
s.mkNode nullKind iniSz
@[inline] def many1 (p : Parser) (unboxSingleton := false) : Parser :=
{ info := p.info,
fn := many1Fn p.fn unboxSingleton }
@[specialize] private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool)
(iniSz : Nat) (unboxSingleton : Bool) : Bool → ParserFn
| pOpt, c, s =>
let sz := s.stackSize;
let pos := s.pos;
let s := p c s;
if s.hasError then
if s.pos > pos then s
else if pOpt then
let s := s.restore sz pos;
if s.stackSize - iniSz == 2 && unboxSingleton then
s.popSyntax
else
s.mkNode nullKind iniSz
else
-- append `Syntax.missing` to make clear that List is incomplete
let s := s.pushSyntax Syntax.missing;
s.mkNode nullKind iniSz
else
let sz := s.stackSize;
let pos := s.pos;
let s := sep c s;
if s.hasError then
let s := s.restore sz pos;
if s.stackSize - iniSz == 1 && unboxSingleton then
s
else
s.mkNode nullKind iniSz
else
sepByFnAux allowTrailingSep c s
@[specialize] def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
sepByFnAux p sep allowTrailingSep iniSz false true c s
@[specialize] def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) (unboxSingleton : Bool) : ParserFn
| c, s =>
let iniSz := s.stackSize;
sepByFnAux p sep allowTrailingSep iniSz unboxSingleton false c s
@[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds }
@[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds,
firstTokens := p.firstTokens }
@[inline] def sepBy (p sep : Parser) (allowTrailingSep : Bool := false) : Parser :=
{ info := sepByInfo p.info sep.info,
fn := sepByFn allowTrailingSep p.fn sep.fn }
@[inline] def sepBy1 (p sep : Parser) (allowTrailingSep : Bool := false) (unboxSingleton := false) : Parser :=
{ info := sepBy1Info p.info sep.info,
fn := sepBy1Fn allowTrailingSep p.fn sep.fn unboxSingleton }
@[specialize] partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn
| c, s =>
let i := s.pos;
if c.input.atEnd i then s.mkEOIError
else if p (c.input.get i) then s.next c.input i
else s.mkUnexpectedError errorMsg
@[specialize] partial def takeUntilFn (p : Char → Bool) : ParserFn
| c, s =>
let i := s.pos;
if c.input.atEnd i then s
else if p (c.input.get i) then s
else takeUntilFn c (s.next c.input i)
@[specialize] def takeWhileFn (p : Char → Bool) : ParserFn :=
takeUntilFn (fun c => !p c)
@[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn :=
andthenFn (satisfyFn p errorMsg) (takeWhileFn p)
partial def finishCommentBlock : Nat → ParserFn
| nesting, c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let i := input.next i;
if curr == '-' then
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if curr == '/' then -- "-/" end of comment
if nesting == 1 then s.next input i
else finishCommentBlock (nesting-1) c (s.next input i)
else
finishCommentBlock nesting c (s.next input i)
else if curr == '/' then
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i)
else finishCommentBlock nesting c (s.setPos i)
else finishCommentBlock nesting c (s.setPos i)
/- Consume whitespace and comments -/
partial def whitespace : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s
else
let curr := input.get i;
if curr.isWhitespace then whitespace c (s.next input i)
else if curr == '-' then
let i := input.next i;
let curr := input.get i;
if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i)
else s
else if curr == '/' then
let i := input.next i;
let curr := input.get i;
if curr == '-' then
let i := input.next i;
let curr := input.get i;
if curr == '-' then s -- "/--" doc comment is an actual token
else andthenFn (finishCommentBlock 1) whitespace c (s.next input i)
else s
else s
def mkEmptySubstringAt (s : String) (p : Nat) : Substring :=
{str := s, startPos := p, stopPos := p }
private def rawAux (startPos : Nat) (trailingWs : Bool) : ParserFn
| c, s =>
let input := c.input;
let stopPos := s.pos;
let leading := mkEmptySubstringAt input startPos;
let val := input.extract startPos stopPos;
if trailingWs then
let s := whitespace c s;
let stopPos' := s.pos;
let trailing := { Substring . str := input, startPos := stopPos, stopPos := stopPos' };
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val;
s.pushSyntax atom
else
let trailing := mkEmptySubstringAt input stopPos;
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val;
s.pushSyntax atom
/-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/
@[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn
| c, s =>
let startPos := s.pos;
let s := p c s;
if s.hasError then s else rawAux startPos trailingWs c s
@[inline] def chFn (c : Char) (trailingWs := false) : ParserFn :=
rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs
def rawCh (c : Char) (trailingWs := false) : Parser :=
{ fn := chFn c trailingWs }
def hexDigitFn : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let i := input.next i;
if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i
else s.mkUnexpectedError "invalid hexadecimal numeral"
def quotedCharFn : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if curr == '\\' || curr == '\"' || curr == '\'' || curr == 'n' || curr == 't' then
s.next input i
else if curr == 'x' then
andthenFn hexDigitFn hexDigitFn c (s.next input i)
else if curr == 'u' then
andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next input i)
else
s.mkUnexpectedError "invalid escape sequence"
/-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/
def mkNodeToken (n : SyntaxNodeKind) (startPos : Nat) : ParserFn :=
fun c s =>
let input := c.input;
let stopPos := s.pos;
let leading := mkEmptySubstringAt input startPos;
let val := input.extract startPos stopPos;
let s := whitespace c s;
let wsStopPos := s.pos;
let trailing := { Substring . str := input, startPos := stopPos, stopPos := wsStopPos };
let info := { SourceInfo . leading := leading, pos := startPos, trailing := trailing };
s.pushSyntax (mkStxLit n val (some info))
def charLitFnAux (startPos : Nat) : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let s := s.setPos (input.next i);
let s := if curr == '\\' then quotedCharFn c s else s;
if s.hasError then s
else
let i := s.pos;
let curr := input.get i;
let s := s.setPos (input.next i);
if curr == '\'' then mkNodeToken charLitKind startPos c s
else s.mkUnexpectedError "missing end of character literal"
partial def strLitFnAux (startPos : Nat) : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let s := s.setPos (input.next i);
if curr == '\"' then
mkNodeToken strLitKind startPos c s
else if curr == '\\' then andthenFn quotedCharFn strLitFnAux c s
else strLitFnAux c s
def decimalNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhileFn (fun c => c.isDigit) c s;
let input := c.input;
let i := s.pos;
let curr := input.get i;
let s :=
/- TODO(Leo): should we use a different kind for numerals containing decimal points? -/
if curr == '.' then
let i := input.next i;
let curr := input.get i;
if curr.isDigit then
takeWhileFn (fun c => c.isDigit) c (s.setPos i)
else s
else s;
mkNodeToken numLitKind startPos c s
def binNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s;
mkNodeToken numLitKind startPos c s
def octalNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s;
mkNodeToken numLitKind startPos c s
def hexNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" c s;
mkNodeToken numLitKind startPos c s
def numberFnAux : ParserFn :=
fun c s =>
let input := c.input;
let startPos := s.pos;
if input.atEnd startPos then s.mkEOIError
else
let curr := input.get startPos;
if curr == '0' then
let i := input.next startPos;
let curr := input.get i;
if curr == 'b' || curr == 'B' then
binNumberFn startPos c (s.next input i)
else if curr == 'o' || curr == 'O' then
octalNumberFn startPos c (s.next input i)
else if curr == 'x' || curr == 'X' then
hexNumberFn startPos c (s.next input i)
else
decimalNumberFn startPos c (s.setPos i)
else if curr.isDigit then
decimalNumberFn startPos c (s.next input startPos)
else
s.mkError "numeral"
def isIdCont : String → ParserState → Bool
| input, s =>
let i := s.pos;
let curr := input.get i;
if curr == '.' then
let i := input.next i;
if input.atEnd i then
false
else
let curr := input.get i;
isIdFirst curr || isIdBeginEscape curr
else
false
private def isToken (idStartPos idStopPos : Nat) (tk : Option TokenConfig) : Bool :=
match tk with
| none => false
| some tk =>
-- if a token is both a symbol and a valid identifier (i.e. a keyword),
-- we want it to be recognized as a symbol
tk.val.bsize ≥ idStopPos - idStartPos
def mkTokenAndFixPos (startPos : Nat) (tk : Option TokenConfig) : ParserFn :=
fun c s =>
match tk with
| none => s.mkErrorAt "token" startPos
| some tk =>
let input := c.input;
let leading := mkEmptySubstringAt input startPos;
let val := tk.val;
let stopPos := startPos + val.bsize;
let s := s.setPos stopPos;
let s := whitespace c s;
let wsStopPos := s.pos;
let trailing := { Substring . str := input, startPos := stopPos, stopPos := wsStopPos };
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val;
s.pushSyntax atom
def mkIdResult (startPos : Nat) (tk : Option TokenConfig) (val : Name) : ParserFn :=
fun c s =>
let stopPos := s.pos;
if isToken startPos stopPos tk then
mkTokenAndFixPos startPos tk c s
else
let input := c.input;
let rawVal := { Substring . str := input, startPos := startPos, stopPos := stopPos };
let s := whitespace c s;
let trailingStopPos := s.pos;
let leading := mkEmptySubstringAt input startPos;
let trailing := { Substring . str := input, startPos := stopPos, stopPos := trailingStopPos };
let info := { SourceInfo . leading := leading, trailing := trailing, pos := startPos };
let atom := mkIdent info rawVal val;
s.pushSyntax atom
partial def identFnAux (startPos : Nat) (tk : Option TokenConfig) : Name → ParserFn
| r, c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if isIdBeginEscape curr then
let startPart := input.next i;
let s := takeUntilFn isIdEndEscape c (s.setPos startPart);
let stopPart := s.pos;
let s := satisfyFn isIdEndEscape "missing end of escaped identifier" c s;
if s.hasError then s
else
let r := mkNameStr r (input.extract startPart stopPart);
if isIdCont input s then
let s := s.next input s.pos;
identFnAux r c s
else
mkIdResult startPos tk r c s
else if isIdFirst curr then
let startPart := i;
let s := takeWhileFn isIdRest c (s.next input i);
let stopPart := s.pos;
let r := mkNameStr r (input.extract startPart stopPart);
if isIdCont input s then
let s := s.next input s.pos;
identFnAux r c s
else
mkIdResult startPos tk r c s
else
mkTokenAndFixPos startPos tk c s
private def isIdFirstOrBeginEscape (c : Char) : Bool :=
isIdFirst c || isIdBeginEscape c
private def nameLitAux (startPos : Nat) : ParserFn
| c, s =>
let input := c.input;
let s := identFnAux startPos none Name.anonymous c (s.next input startPos);
if s.hasError then
s.mkErrorAt "invalid Name literal" startPos
else
let stx := s.stxStack.back;
match stx with
| Syntax.ident _ rawStr _ _ =>
let s := s.popSyntax;
s.pushSyntax (Syntax.node nameLitKind #[mkAtomFrom stx rawStr.toString])
| _ => s.mkError "invalid Name literal"
private def tokenFnAux : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
let curr := input.get i;
if curr == '\"' then
strLitFnAux i c (s.next input i)
else if curr == '\'' then
charLitFnAux i c (s.next input i)
else if curr.isDigit then
numberFnAux c s
else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then
nameLitAux i c s
else
let (_, tk) := c.tokens.matchPrefix input i;
identFnAux i tk Name.anonymous c s
private def updateCache (startPos : Nat) (s : ParserState) : ParserState :=
match s with
| ⟨stack, pos, cache, none⟩ =>
if stack.size == 0 then s
else
let tk := stack.back;
⟨stack, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩
| other => other
def tokenFn : ParserFn :=
fun c s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let tkc := s.cache.tokenCache;
if tkc.startPos == i then
let s := s.pushSyntax tkc.token;
s.setPos tkc.stopPos
else
let s := tokenFnAux c s;
updateCache i s
def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Option Syntax :=
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError then (s.restore iniSz iniPos, none)
else
let stx := s.stxStack.back;
(s.restore iniSz iniPos, some stx)
@[inline] def peekToken (c : ParserContext) (s : ParserState) : ParserState × Option Syntax :=
let tkc := s.cache.tokenCache;
if tkc.startPos == s.pos then
(s, some tkc.token)
else
peekTokenAux c s
/- Treat keywords as identifiers. -/
def rawIdentFn : ParserFn :=
fun c s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else identFnAux i none Name.anonymous c s
@[inline] def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn :=
fun c s =>
let startPos := s.pos;
let s := tokenFn c s;
if s.hasError then
s.mkErrorsAt expected startPos
else
match s.stxStack.back with
| Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos
| _ => s.mkErrorsAt expected startPos
@[inline] def symbolFnAux (sym : String) (errorMsg : String) : ParserFn :=
satisfySymbolFn (fun s => s == sym) [errorMsg]
def symbolInfo (sym : String) (lbp : Option Nat) : ParserInfo :=
{ collectTokens := fun tks => { val := sym, lbp := lbp } :: tks,
firstTokens := FirstTokens.tokens [ { val := sym, lbp := lbp } ] }
@[inline] def symbolFn (sym : String) : ParserFn :=
symbolFnAux sym ("'" ++ sym ++ "'")
@[inline] def symbolAux (sym : String) (lbp : Option Nat := none) : Parser :=
let sym := sym.trim;
{ info := symbolInfo sym lbp,
fn := symbolFn sym }
@[inline] def symbol (sym : String) (lbp : Nat) : Parser :=
symbolAux sym lbp
/-- Check if the following token is the symbol _or_ identifier `sym`. Useful for
parsing local tokens that have not been added to the token table (but may have
been so by some unrelated code).
For example, the universe `max` Function is parsed using this combinator so that
it can still be used as an identifier outside of universes (but registering it
as a token in a Term Syntax would not break the universe Parser). -/
def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn :=
fun c s =>
let startPos := s.pos;
let s := tokenFn c s;
if s.hasError then s.mkErrorAt errorMsg startPos
else
match s.stxStack.back with
| Syntax.atom _ sym' =>
if sym == sym' then s else s.mkErrorAt errorMsg startPos
| Syntax.ident info rawVal _ _ =>
if sym == rawVal.toString then
let s := s.popSyntax;
s.pushSyntax (Syntax.atom info sym)
else
s.mkErrorAt errorMsg startPos
| _ => s.mkErrorAt errorMsg startPos
@[inline] def nonReservedSymbolFn (sym : String) : ParserFn :=
nonReservedSymbolFnAux sym ("'" ++ sym ++ "'")
def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo :=
{ firstTokens :=
if includeIdent then
FirstTokens.tokens [ { val := sym }, { val := "ident" } ]
else
FirstTokens.tokens [ { val := sym } ] }
@[inline] def nonReservedSymbol (sym : String) (includeIdent := false) : Parser :=
let sym := sym.trim;
{ info := nonReservedSymbolInfo sym includeIdent,
fn := nonReservedSymbolFn sym }
partial def strAux (sym : String) (errorMsg : String) : Nat → ParserFn
| j, c, s =>
if sym.atEnd j then s
else
let i := s.pos;
let input := c.input;
if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg
else strAux (sym.next j) c (s.next input i)
def checkTailWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| some info => info.trailing.stopPos > info.trailing.startPos
| none => false
def checkWsBeforeFn (errorMsg : String) : ParserFn :=
fun c s =>
let prev := s.stxStack.back;
if checkTailWs prev then s else s.mkError errorMsg
def checkWsBefore (errorMsg : String) : Parser :=
{ info := epsilonInfo,
fn := checkWsBeforeFn errorMsg }
def checkTailNoWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| some info => info.trailing.stopPos == info.trailing.startPos
| none => false
private def pickNonNone (stack : Array Syntax) : Syntax :=
match stack.findRev? $ fun stx => !stx.isNone with
| none => Syntax.missing
| some stx => stx
def checkNoWsBeforeFn (errorMsg : String) : ParserFn :=
fun c s =>
let prev := pickNonNone s.stxStack;
if checkTailNoWs prev then s else s.mkError errorMsg
def checkNoWsBefore (errorMsg : String) : Parser :=
{ info := epsilonInfo,
fn := checkNoWsBeforeFn errorMsg }
def symbolNoWsInfo (sym : String) (lbpNoWs : Option Nat) : ParserInfo :=
{ collectTokens := fun tks => { val := sym, lbpNoWs := lbpNoWs } :: tks,
firstTokens := FirstTokens.tokens [ { val := sym, lbpNoWs := lbpNoWs } ] }
@[inline] def symbolNoWsFnAux (sym : String) (errorMsg : String) : ParserFn :=
fun c s =>
let left := s.stxStack.back;
if checkTailNoWs left then
let startPos := s.pos;
let input := c.input;
let s := strAux sym errorMsg 0 c s;
if s.hasError then s
else
let leading := mkEmptySubstringAt input startPos;
let stopPos := startPos + sym.bsize;
let trailing := mkEmptySubstringAt input stopPos;
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } sym;
s.pushSyntax atom
else
s.mkError errorMsg
@[inline] def symbolNoWsFn (sym : String) : ParserFn :=
symbolNoWsFnAux sym ("'" ++ sym ++ "' without whitespaces around it")
/- Similar to `symbol`, but succeeds only if there is no space whitespace after leading term and after `sym`. -/
@[inline] def symbolNoWsAux (sym : String) (lbp : Option Nat) : Parser :=
let sym := sym.trim;
{ info := symbolNoWsInfo sym lbp,
fn := symbolNoWsFn sym }
@[inline] def symbolNoWs (sym : String) (lbp : Nat) : Parser :=
symbolNoWsAux sym lbp
def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn :=
satisfySymbolFn (fun s => s == sym || s == asciiSym) expected
def unicodeSymbolInfo (sym asciiSym : String) (lbp : Option Nat) : ParserInfo :=
{ collectTokens := fun tks => { val := sym, lbp := lbp } :: { val := asciiSym, lbp := lbp } :: tks,
firstTokens := FirstTokens.tokens [ { val := sym, lbp := lbp }, { val := asciiSym, lbp := lbp } ] }
@[inline] def unicodeSymbolFn (sym asciiSym : String) : ParserFn :=
unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"]
@[inline] def unicodeSymbol (sym asciiSym : String) (lbp : Option Nat := none) : Parser :=
let sym := sym.trim;
let asciiSym := asciiSym.trim;
{ info := unicodeSymbolInfo sym asciiSym lbp,
fn := unicodeSymbolFn sym asciiSym }
/- Succeeds if RBP > lower -/
def checkRBPGreaterFn (lower : Nat) (errorMsg : String) : ParserFn :=
fun c s =>
if c.rbp > lower then s.mkUnexpectedError errorMsg
else s
def checkRBPGreater (lower : Nat) (errorMsg : String) : Parser :=
{ info := epsilonInfo,
fn := checkRBPGreaterFn lower errorMsg }
def mkAtomicInfo (k : String) : ParserInfo :=
{ firstTokens := FirstTokens.tokens [ { val := k } ] }
def numLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos else s
@[inline] def numLitNoAntiquot : Parser :=
{ fn := numLitFn,
info := mkAtomicInfo "numLit" }
def strLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos else s
@[inline] def strLitNoAntiquot : Parser :=
{ fn := strLitFn,
info := mkAtomicInfo "strLit" }
def charLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos else s
@[inline] def charLitNoAntiquot : Parser :=
{ fn := charLitFn,
info := mkAtomicInfo "charLit" }
def nameLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos else s
@[inline] def nameLitNoAntiquot : Parser :=
{ fn := nameLitFn,
info := mkAtomicInfo "nameLit" }
def identFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos else s
@[inline] def identNoAntiquot : Parser :=
{ fn := identFn,
info := mkAtomicInfo "ident" }
@[inline] def rawIdentNoAntiquot : Parser :=
{ fn := rawIdentFn }
def identEqFn (id : Name) : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError then
s.mkErrorAt "identifier" iniPos
else match s.stxStack.back with
| Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos else s
| _ => s.mkErrorAt "identifier" iniPos
@[inline] def identEq (id : Name) : Parser :=
{ fn := identEqFn id,
info := mkAtomicInfo "ident" }
def quotedSymbolFn : ParserFn :=
nodeFn `quotedSymbol (andthenFn (andthenFn (chFn '`') (rawFn (takeUntilFn (fun c => c == '`')))) (chFn '`' true))
-- TODO: remove after old frontend is gone
def quotedSymbol : Parser :=
{ fn := quotedSymbolFn }
def unquotedSymbolFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || s.stxStack.back.isIdent || isLitKind s.stxStack.back.getKind then
s.mkErrorAt "symbol" iniPos
else
s
def unquotedSymbol : Parser :=
{ fn := unquotedSymbolFn }
instance stringToParserCoe : HasCoe String Parser :=
⟨symbolAux⟩
namespace ParserState
def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ => ⟨stack.shrink oldStackSize, pos, cache, err⟩
def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack.shrink oldStackSize, oldStopPos, cache, oldError⟩
def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState :=
match s with
| ⟨stack, pos, cache, some err⟩ =>
if oldError == err then s
else ⟨stack.shrink oldStackSize, pos, cache, some (oldError.merge err)⟩
| other => other
def mkLongestNodeAlt (s : ParserState) (startSize : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ =>
if stack.size == startSize then ⟨stack.push Syntax.missing, pos, cache, none⟩ -- parser did not create any node, then we just add `Syntax.missing`
else if stack.size == startSize + 1 then s
else
-- parser created more than one node, combine them into a single node
let node := Syntax.node nullKind (stack.extract startSize stack.size);
let stack := stack.shrink startSize;
⟨stack.push node, pos, cache, none⟩
def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ =>
let node := stack.back;
let stack := stack.shrink startStackSize;
let stack := stack.push node;
⟨stack, pos, cache, none⟩
def replaceLongest (s : ParserState) (startStackSize : Nat) (prevStackSize : Nat) : ParserState :=
let s := s.mkLongestNodeAlt prevStackSize;
s.keepLatest startStackSize
end ParserState
def longestMatchStep (startSize : Nat) (startPos : String.Pos) (p : ParserFn) : ParserFn :=
fun c s =>
let prevErrorMsg := s.errorMsg;
let prevStopPos := s.pos;
let prevSize := s.stackSize;
let s := s.restore prevSize startPos;
let s := p c s;
match prevErrorMsg, s.errorMsg with
| none, none => -- both succeeded
if s.pos > prevStopPos then s.replaceLongest startSize prevSize -- replace
else if s.pos < prevStopPos then s.restore prevSize prevStopPos -- keep prev
else s.mkLongestNodeAlt prevSize -- keep both
| none, some _ => -- prev succeeded, current failed
s.restore prevSize prevStopPos
| some oldError, some _ => -- both failed
if s.pos > prevStopPos then s.keepNewError prevSize
else if s.pos < prevStopPos then s.keepPrevError prevSize prevStopPos prevErrorMsg
else s.mergeErrors prevSize oldError
| some _, none => -- prev failed, current succeeded
let s := s.mkLongestNodeAlt prevSize; -- create successful alternative on the top of the stack
let successNode := s.stxStack.back;
let s := s.shrinkStack startSize; -- restore stack to initial size to make sure (failure) nodes are removed from the stack
s.pushSyntax successNode -- put successNode back on the stack
def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState :=
if !s.hasError && s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s
def longestMatchFnAux (startSize : Nat) (startPos : String.Pos) : List Parser → ParserFn
| [] => fun _ s => longestMatchMkResult startSize s
| p::ps => fun c s =>
let s := longestMatchStep startSize startPos p.fn c s;
longestMatchFnAux ps c s
def longestMatchFn₁ (p : ParserFn) : ParserFn :=
fun c s =>
let startSize := s.stackSize;
let s := p c s;
if s.hasError then s else s.mkLongestNodeAlt startSize
def longestMatchFn : List Parser → ParserFn
| [] => fun _ s => s.mkError "longestMatch: empty list"
| [p] => longestMatchFn₁ p.fn
| p::ps => fun c s =>
let startSize := s.stackSize;
let startPos := s.pos;
let s := p.fn c s;
if s.hasError then
let s := s.shrinkStack startSize;
longestMatchFnAux startSize startPos ps c s
else
let s := s.mkLongestNodeAlt startSize;
longestMatchFnAux startSize startPos ps c s
def anyOfFn : List Parser → ParserFn
| [], _, s => s.mkError "anyOf: empty list"
| [p], c, s => p.fn c s
| p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s
@[inline] def checkColGeFn (col : Nat) (errorMsg : String) : ParserFn :=
fun c s =>
let pos := c.fileMap.toPosition s.pos;
if pos.column ≥ col then s
else s.mkError errorMsg
@[inline] def checkColGe (col : Nat) (errorMsg : String) : Parser :=
{ fn := checkColGeFn col errorMsg }
@[inline] def withPosition (p : Position → Parser) : Parser :=
{ info := (p { line := 1, column := 0 }).info,
fn := fun c s =>
let pos := c.fileMap.toPosition s.pos;
(p pos).fn c s }
@[inline] def many1Indent (p : Parser) (errorMsg : String) : Parser :=
withPosition $ fun pos => many1 (checkColGe pos.column errorMsg >> p)
/-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/
def TokenMap (α : Type) := RBMap Name (List α) Name.quickLt
namespace TokenMap
def insert {α : Type} (map : TokenMap α) (k : Name) (v : α) : TokenMap α :=
match map.find? k with
| none => map.insert k [v]
| some vs => map.insert k (v::vs)
instance {α : Type} : Inhabited (TokenMap α) := ⟨RBMap.empty⟩
instance {α : Type} : HasEmptyc (TokenMap α) := ⟨RBMap.empty⟩
end TokenMap
structure PrattParsingTables :=
(leadingTable : TokenMap Parser := {})
(leadingParsers : List Parser := []) -- for supporting parsers we cannot obtain first token
(trailingTable : TokenMap TrailingParser := {})
(trailingParsers : List TrailingParser := []) -- for supporting parsers such as function application
instance PrattParsingTables.inhabited : Inhabited PrattParsingTables := ⟨{}⟩
/--
Each parser category is implemented using Pratt's parser.
The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`.
Users and plugins may define extra categories.
The field `leadingIdentAsSymbol` specifies how the parsing table
lookup function behaves for identifiers. The function `prattParser`
uses two tables `leadingTable` and `trailingTable`. They map tokens
to parsers. If `leadingIdentAsSymbol == false` and the leading token
is an identifier, then `prattParser` just executes the parsers
associated with the auxiliary token "ident". If
`leadingIdentAsSymbol == true` and the leading token is an
identifier `<foo>`, then `prattParser` combines the parsers
associated with the token `<foo>` with the parsers associated with
the auxiliary token "ident". We use this feature and the
`nonReservedSymbol` parser to implement the `tactic` parsers. We
use this approach to avoid creating a reserved symbol for each
builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users
may still use these symbols as identifiers (e.g., naming a
function). -/
structure ParserCategory :=
(tables : PrattParsingTables) (leadingIdentAsSymbol : Bool)
instance ParserCategory.inhabited : Inhabited ParserCategory := ⟨{ tables := {}, leadingIdentAsSymbol := false }⟩
abbrev ParserCategories := PersistentHashMap Name ParserCategory
def currLbp (left : Syntax) (c : ParserContext) (s : ParserState) : ParserState × Nat :=
let (s, stx?) := peekToken c s;
match stx? with
| some stx@(Syntax.atom _ sym) =>
if sym == "$" && checkTailNoWs stx then (s, appPrec) -- TODO: split `lbpNoWs` into "before" and "after", and set right lbp for '$' in antiquotations
else match c.tokens.matchPrefix sym 0 with
| (_, some tk) => match tk.lbp, tk.lbpNoWs with
| some lbp, none => (s, lbp)
| none, some lbpNoWs => (s, lbpNoWs)
| some lbp, some lbpNoWs => if checkTailNoWs left then (s, lbpNoWs) else (s, lbp)
| none, none => (s, 0)
| _ => (s, 0)
| some (Syntax.ident _ _ _ _) => (s, appPrec)
-- TODO(Leo): add support for associating lbp with syntax node kinds.
| some (Syntax.node k _) =>
if isLitKind k || k == fieldIdxKind then
(s, appPrec)
else
(s, 0)
| _ => (s, 0)
def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (leadingIdentAsSymbol : Bool) : ParserState × List α :=
let (s, stx) := peekToken c s;
let find (n : Name) : ParserState × List α :=
match map.find? n with
| some as => (s, as)
| _ => (s, []);
match stx with
| some (Syntax.atom _ sym) => find (mkNameSimple sym)
| some (Syntax.ident _ _ val _) =>
if leadingIdentAsSymbol then
match map.find? val with
| some as => match map.find? identKind with
| some as' => (s, as ++ as')
| _ => (s, as)
| none => find identKind
else
find identKind
| some (Syntax.node k _) => find k
| _ => (s, [])
abbrev CategoryParserFn := Name → ParserFn
def mkCategoryParserFnRef : IO (IO.Ref CategoryParserFn) :=
IO.mkRef $ fun _ => whitespace
@[init mkCategoryParserFnRef]
constant categoryParserFnRef : IO.Ref CategoryParserFn := arbitrary _
def mkCategoryParserFnExtension : IO (EnvExtension CategoryParserFn) :=
registerEnvExtension $ categoryParserFnRef.get
@[init mkCategoryParserFnExtension]
def categoryParserFnExtension : EnvExtension CategoryParserFn := arbitrary _
def categoryParserFn (catName : Name) : ParserFn :=
fun ctx s => categoryParserFnExtension.getState ctx.env catName ctx s
def categoryParser (catName : Name) (rbp : Nat) : Parser :=
{ fn := fun c s => categoryParserFn catName { rbp := rbp, .. c } s }
-- Define `termParser` here because we need it for antiquotations
@[inline] def termParser (rbp : Nat := 0) : Parser :=
categoryParser `term rbp
/- ============== -/
/- Antiquotations -/
/- ============== -/
def dollarSymbol : Parser := symbol "$" 1
/-- Fail if previous token is immediately followed by ':'. -/
private def noImmediateColon : Parser :=
{ fn := fun c s =>
let prev := s.stxStack.back;
if checkTailNoWs prev then
let input := c.input;
let i := s.pos;
if input.atEnd i then s
else
let curr := input.get i;
if curr == ':' then
s.mkUnexpectedError "unexpected ':'"
else s
else s
}
def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn :=
fun c s => match p c s with
| s'@{ errorMsg := some msg } => { s' with errorMsg := some { msg with expected := [] } }
| s' => s'
def setExpected (expected : List String) (p : Parser) : Parser :=
{ fn := setExpectedFn expected p.fn, info := p.info }
def pushNone : Parser :=
{ fn := fun c s => s.pushSyntax mkNullNode }
-- We support two kinds of antiquotations: `$id` and `$(t)`, where `id` is a term identifier and `t` is a term.
private def antiquotNestedExpr : Parser := node `antiquotNestedExpr ("(" >> termParser >> ")")
private def antiquotExpr : Parser := identNoAntiquot <|> antiquotNestedExpr
/--
Define parser for `$e` (if anonymous == true) and `$e:name`. Both
forms can also be used with an appended `*` to turn them into an
antiquotation "splice". If `kind` is given, it will additionally be checked
when evaluating `match_syntax`. Antiquotations can be escaped as in `$$e`, which
produces the syntax tree for `$e`. -/
def mkAntiquot (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parser :=
let kind := (kind.getD Name.anonymous) ++ `antiquot;
let nameP := checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbolAux ":" >> nonReservedSymbol name;
-- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different
-- antiquotation kind via `noImmediateColon`
let nameP := if anonymous then nameP <|> noImmediateColon >> pushNone >> pushNone else nameP;
-- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error
node kind $ try $
setExpected [] dollarSymbol >>
many (checkNoWsBefore "" >> dollarSymbol) >>
checkNoWsBefore "no space before spliced term" >> antiquotExpr >>
nameP >>
optional (checkNoWsBefore "" >> "*")
def tryAnti (c : ParserContext) (s : ParserState) : Bool :=
let (s, stx?) := peekToken c s;
match stx? with
| some stx@(Syntax.atom _ sym) => sym == "$"
| _ => false
@[inline] def withAntiquotFn (antiquotP p : ParserFn) : ParserFn :=
fun c s => if tryAnti c s then orelseFn antiquotP p c s else p c s
/-- Optimized version of `mkAntiquot ... <|> p`. -/
@[inline] def withAntiquot (antiquotP p : Parser) : Parser :=
{ fn := withAntiquotFn antiquotP.fn p.fn,
info := orelseInfo antiquotP.info p.info }
/- ===================== -/
/- End of Antiquotations -/
/- ===================== -/
def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) : Parser :=
withAntiquot (mkAntiquot name kind false) $ node kind p
def ident : Parser :=
withAntiquot (mkAntiquot "ident" identKind) identNoAntiquot
-- `ident` and `rawIdent` produce the same syntax tree, so we reuse the antiquotation kind name
def rawIdent : Parser :=
withAntiquot (mkAntiquot "ident" identKind) rawIdentNoAntiquot
def numLit : Parser :=
withAntiquot (mkAntiquot "numLit" numLitKind) numLitNoAntiquot
def strLit : Parser :=
withAntiquot (mkAntiquot "strLit" strLitKind) strLitNoAntiquot
def charLit : Parser :=
withAntiquot (mkAntiquot "charLit" charLitKind) charLitNoAntiquot
def nameLit : Parser :=
withAntiquot (mkAntiquot "nameLit" nameLitKind) nameLitNoAntiquot
def categoryParserOfStackFn (offset : Nat) : ParserFn :=
fun ctx s =>
let stack := s.stxStack;
if stack.size < offset + 1 then
s.mkUnexpectedError ("failed to determine parser category using syntax stack, stack is too small")
else
match stack.get! (stack.size - offset - 1) with
| Syntax.ident _ _ catName _ => categoryParserFn catName ctx s
| _ => s.mkUnexpectedError ("failed to determine parser category using syntax stack, the specified element on the stack is not an identifier")
def categoryParserOfStack (offset : Nat) (rbp : Nat := 0) : Parser :=
{ fn := fun c s => categoryParserOfStackFn offset { rbp := rbp, .. c } s }
private def mkResult (s : ParserState) (iniSz : Nat) : ParserState :=
if s.stackSize == iniSz + 1 then s
else s.mkNode nullKind iniSz -- throw error instead?
def leadingParserAux (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let (s, ps) := indexed tables.leadingTable c s leadingIdentAsSymbol;
let ps := tables.leadingParsers ++ ps;
if ps.isEmpty then
s.mkError (toString kind)
else
let s := longestMatchFn ps c s;
mkResult s iniSz
@[inline] def leadingParser (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) (antiquotParser : ParserFn) : ParserFn :=
withAntiquotFn antiquotParser (leadingParserAux kind tables leadingIdentAsSymbol)
def trailingLoopStep (tables : PrattParsingTables) (ps : List Parser) : ParserFn :=
fun c s =>
orelseFn (longestMatchFn ps) (anyOfFn tables.trailingParsers) c s
private def mkTrailingResult (s : ParserState) (iniSz : Nat) : ParserState :=
let s := mkResult s iniSz;
-- Stack contains `[..., left, result]`
-- We must remove `left`
let result := s.stxStack.back;
let s := s.popSyntax.popSyntax;
s.pushSyntax result
partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) : ParserState → ParserState
| s =>
let left := s.stxStack.back;
let (s, lbp) := currLbp left c s;
if c.rbp ≥ lbp then s
else
let iniSz := s.stackSize;
let identAsSymbol := false;
let (s, ps) := indexed tables.trailingTable c s identAsSymbol;
if ps.isEmpty && tables.trailingParsers.isEmpty then
s -- no available trailing parser
else
let s := trailingLoopStep tables ps c s;
if s.hasError then s
else
let s := mkTrailingResult s iniSz;
trailingLoop s
/--
Implements a recursive precedence parser according to Pratt's algorithm.
`antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers.
It should not be added to the regular leading parsers because it would heavily
overlap with antiquotation parsers nested inside them. -/
@[inline] def prattParser (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) (antiquotParser : ParserFn) : ParserFn :=
fun c s =>
let left := s.stxStack.back;
let (s, lbp) := currLbp left c s;
if c.rbp > lbp then s.mkUnexpectedError "unexpected token"
else
let s := leadingParser kind tables leadingIdentAsSymbol antiquotParser c s;
if s.hasError then s
else
trailingLoop tables c s
def mkBuiltinTokenTable : IO (IO.Ref TokenTable) := IO.mkRef {}
@[init mkBuiltinTokenTable] constant builtinTokenTable : IO.Ref TokenTable := arbitrary _
/- Global table with all SyntaxNodeKind's -/
def mkBuiltinSyntaxNodeKindSetRef : IO (IO.Ref SyntaxNodeKindSet) := IO.mkRef {}
@[init mkBuiltinSyntaxNodeKindSetRef] constant builtinSyntaxNodeKindSetRef : IO.Ref SyntaxNodeKindSet := arbitrary _
def mkBuiltinParserCategories : IO (IO.Ref ParserCategories) := IO.mkRef {}
@[init mkBuiltinParserCategories] constant builtinParserCategoriesRef : IO.Ref ParserCategories := arbitrary _
private def throwParserCategoryAlreadyDefined {α} (catName : Name) : ExceptT String Id α :=
throw ("parser category '" ++ toString catName ++ "' has already been defined")
private def addParserCategoryCore (categories : ParserCategories) (catName : Name) (initial : ParserCategory) : Except String ParserCategories :=
if categories.contains catName then
throwParserCategoryAlreadyDefined catName
else
pure $ categories.insert catName initial
/-- All builtin parser categories are Pratt's parsers -/
private def addBuiltinParserCategory (catName : Name) (leadingIdentAsSymbol : Bool) : IO Unit := do
categories ← builtinParserCategoriesRef.get;
categories ← IO.ofExcept $ addParserCategoryCore categories catName { tables := {}, leadingIdentAsSymbol := leadingIdentAsSymbol};
builtinParserCategoriesRef.set categories
inductive ParserExtensionOleanEntry
| token (val : TokenConfig) : ParserExtensionOleanEntry
| kind (val : SyntaxNodeKind) : ParserExtensionOleanEntry
| category (catName : Name) (leadingIdentAsSymbol : Bool)
| parser (catName : Name) (declName : Name) : ParserExtensionOleanEntry
inductive ParserExtensionEntry
| token (val : TokenConfig) : ParserExtensionEntry
| kind (val : SyntaxNodeKind) : ParserExtensionEntry
| category (catName : Name) (leadingIdentAsSymbol : Bool)
| parser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) : ParserExtensionEntry
structure ParserExtensionState :=
(tokens : TokenTable := {})
(kinds : SyntaxNodeKindSet := {})
(categories : ParserCategories := {})
(newEntries : List ParserExtensionOleanEntry := [])
instance ParserExtensionState.inhabited : Inhabited ParserExtensionState := ⟨{}⟩
abbrev ParserExtension := PersistentEnvExtension ParserExtensionOleanEntry ParserExtensionEntry ParserExtensionState
private def ParserExtension.mkInitial : IO ParserExtensionState := do
tokens ← builtinTokenTable.get;
kinds ← builtinSyntaxNodeKindSetRef.get;
categories ← builtinParserCategoriesRef.get;
pure { tokens := tokens, kinds := kinds, categories := categories }
private def mergePrecendences (msgPreamble : String) (sym : String) : Option Nat → Option Nat → Except String (Option Nat)
| none, b => pure b
| a, none => pure a
| some a, some b =>
if a == b then pure $ some a
else
throw $ msgPreamble ++ "precedence mismatch for '" ++ toString sym ++ "', previous: " ++ toString a ++ ", new: " ++ toString b
private def addTokenConfig (tokens : TokenTable) (tk : TokenConfig) : Except String TokenTable := do
if tk.val == "" then throw "invalid empty symbol"
else match tokens.find tk.val with
| none => pure $ tokens.insert tk.val tk
| some oldTk => do
lbp ← mergePrecendences "" tk.val oldTk.lbp tk.lbp;
lbpNoWs ← mergePrecendences "(no whitespace) " tk.val oldTk.lbpNoWs tk.lbpNoWs;
pure $ tokens.insert tk.val { lbp := lbp, lbpNoWs := lbpNoWs, .. tk }
def throwUnknownParserCategory {α} (catName : Name) : ExceptT String Id α :=
throw ("unknown parser category '" ++ toString catName ++ "'")
def addLeadingParser (categories : ParserCategories) (catName : Name) (parserName : Name) (p : Parser) : Except String ParserCategories :=
match categories.find? catName with
| none =>
throwUnknownParserCategory catName
| some cat =>
let addTokens (tks : List TokenConfig) : Except String ParserCategories :=
let tks := tks.map $ fun tk => mkNameSimple tk.val;
let tables := tks.eraseDups.foldl (fun (tables : PrattParsingTables) tk => { leadingTable := tables.leadingTable.insert tk p, .. tables }) cat.tables;
pure $ categories.insert catName { tables := tables, .. cat };
match p.info.firstTokens with
| FirstTokens.tokens tks => addTokens tks
| FirstTokens.optTokens tks => addTokens tks
| _ =>
let tables := { leadingParsers := p :: cat.tables.leadingParsers, .. cat.tables };
pure $ categories.insert catName { tables := tables, .. cat }
private def addTrailingParserAux (tables : PrattParsingTables) (p : TrailingParser) : PrattParsingTables :=
let addTokens (tks : List TokenConfig) : PrattParsingTables :=
let tks := tks.map $ fun tk => mkNameSimple tk.val;
tks.eraseDups.foldl (fun (tables : PrattParsingTables) tk => { trailingTable := tables.trailingTable.insert tk p, .. tables }) tables;
match p.info.firstTokens with
| FirstTokens.tokens tks => addTokens tks
| FirstTokens.optTokens tks => addTokens tks
| _ => { trailingParsers := p :: tables.trailingParsers, .. tables }
def addTrailingParser (categories : ParserCategories) (catName : Name) (p : TrailingParser) : Except String ParserCategories :=
match categories.find? catName with
| none => throwUnknownParserCategory catName
| some cat => pure $ categories.insert catName { tables := addTrailingParserAux cat.tables p, .. cat }
def addParser (categories : ParserCategories) (catName : Name) (declName : Name) (leading : Bool) (p : Parser) : Except String ParserCategories :=
match leading, p with
| true, p => addLeadingParser categories catName declName p
| false, p => addTrailingParser categories catName p
def addParserTokens (tokenTable : TokenTable) (info : ParserInfo) : Except String TokenTable :=
let newTokens := info.collectTokens [];
newTokens.foldlM addTokenConfig tokenTable
private def updateBuiltinTokens (info : ParserInfo) (declName : Name) : IO Unit := do
tokenTable ← builtinTokenTable.swap {};
match addParserTokens tokenTable info with
| Except.ok tokenTable => builtinTokenTable.set tokenTable
| Except.error msg => throw (IO.userError ("invalid builtin parser '" ++ toString declName ++ "', " ++ msg))
def addBuiltinParser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) : IO Unit := do
categories ← builtinParserCategoriesRef.get;
categories ← IO.ofExcept $ addParser categories catName declName leading p;
builtinParserCategoriesRef.set categories;
builtinSyntaxNodeKindSetRef.modify p.info.collectKinds;
updateBuiltinTokens p.info declName
def addBuiltinLeadingParser (catName : Name) (declName : Name) (p : Parser) : IO Unit :=
addBuiltinParser catName declName true p
def addBuiltinTrailingParser (catName : Name) (declName : Name) (p : TrailingParser) : IO Unit :=
addBuiltinParser catName declName false p
private def ParserExtension.addEntry (s : ParserExtensionState) (e : ParserExtensionEntry) : ParserExtensionState :=
match e with
| ParserExtensionEntry.token tk =>
match addTokenConfig s.tokens tk with
| Except.ok tokens => { tokens := tokens, newEntries := ParserExtensionOleanEntry.token tk :: s.newEntries, .. s }
| _ => unreachable!
| ParserExtensionEntry.kind k =>
{ kinds := s.kinds.insert k, newEntries := ParserExtensionOleanEntry.kind k :: s.newEntries, .. s }
| ParserExtensionEntry.category catName leadingIdentAsSymbol =>
if s.categories.contains catName then s
else { categories := s.categories.insert catName { tables := {}, leadingIdentAsSymbol := leadingIdentAsSymbol },
newEntries := ParserExtensionOleanEntry.category catName leadingIdentAsSymbol :: s.newEntries, .. s }
| ParserExtensionEntry.parser catName declName leading parser =>
match addParser s.categories catName declName leading parser with
| Except.ok categories => { categories := categories, newEntries := ParserExtensionOleanEntry.parser catName declName :: s.newEntries, .. s }
| _ => unreachable!
def compileParserDescr (categories : ParserCategories) : ParserDescr → Except String (Parser)
| ParserDescr.andthen d₁ d₂ => andthen <$> compileParserDescr d₁ <*> compileParserDescr d₂
| ParserDescr.orelse d₁ d₂ => orelse <$> compileParserDescr d₁ <*> compileParserDescr d₂
| ParserDescr.optional d => optional <$> compileParserDescr d
| ParserDescr.lookahead d => lookahead <$> compileParserDescr d
| ParserDescr.try d => try <$> compileParserDescr d
| ParserDescr.many d => many <$> compileParserDescr d
| ParserDescr.many1 d => many1 <$> compileParserDescr d
| ParserDescr.sepBy d₁ d₂ => sepBy <$> compileParserDescr d₁ <*> compileParserDescr d₂
| ParserDescr.sepBy1 d₁ d₂ => sepBy1 <$> compileParserDescr d₁ <*> compileParserDescr d₂
| ParserDescr.node k d => node k <$> compileParserDescr d
| ParserDescr.trailingNode k d => trailingNode k <$> compileParserDescr d
| ParserDescr.symbol tk lbp => pure $ symbolAux tk lbp
| ParserDescr.numLit => pure $ numLit
| ParserDescr.strLit => pure $ strLit
| ParserDescr.charLit => pure $ charLit
| ParserDescr.nameLit => pure $ nameLit
| ParserDescr.ident => pure $ ident
| ParserDescr.nonReservedSymbol tk includeIdent => pure $ nonReservedSymbol tk includeIdent
| ParserDescr.parser catName rbp =>
match categories.find? catName with
| some _ => pure $ categoryParser catName rbp
| none => throwUnknownParserCategory catName
unsafe def mkParserOfConstantUnsafe (env : Environment) (categories : ParserCategories) (constName : Name) : Except String (Bool × Parser) :=
match env.find? constName with
| none => throw ("unknow constant '" ++ toString constName ++ "'")
| some info =>
match info.type with
| Expr.const `Lean.Parser.TrailingParser _ _ => do
p ← env.evalConst Parser constName;
pure ⟨false, p⟩
| Expr.const `Lean.Parser.Parser _ _ => do
p ← env.evalConst Parser constName;
pure ⟨true, p⟩
| Expr.const `Lean.ParserDescr _ _ => do
d ← env.evalConst ParserDescr constName;
p ← compileParserDescr categories d;
pure ⟨true, p⟩
| Expr.const `Lean.TrailingParserDescr _ _ => do
d ← env.evalConst TrailingParserDescr constName;
p ← compileParserDescr categories d;
pure ⟨false, p⟩
| _ => throw ("unexpected parser type at '" ++ toString constName ++ "' (`ParserDescr`, `TrailingParserDescr`, `Parser` or `TrailingParser` expected")
@[implementedBy mkParserOfConstantUnsafe]
constant mkParserOfConstant (env : Environment) (categories : ParserCategories) (constName : Name) : Except String (Bool × Parser) :=
arbitrary _
private def ParserExtension.addImported (env : Environment) (es : Array (Array ParserExtensionOleanEntry)) : IO ParserExtensionState := do
s ← ParserExtension.mkInitial;
es.foldlM
(fun s entries =>
entries.foldlM
(fun s entry =>
match entry with
| ParserExtensionOleanEntry.token tk => do
tokens ← IO.ofExcept (addTokenConfig s.tokens tk);
pure { tokens := tokens, .. s }
| ParserExtensionOleanEntry.kind k =>
pure { kinds := s.kinds.insert k, .. s }
| ParserExtensionOleanEntry.category catName leadingIdentAsSymbol => do
categories ← IO.ofExcept (addParserCategoryCore s.categories catName { tables := {}, leadingIdentAsSymbol := leadingIdentAsSymbol});
pure { categories := categories, .. s }
| ParserExtensionOleanEntry.parser catName declName =>
match mkParserOfConstant env s.categories declName with
| Except.ok p =>
match addParser s.categories catName declName p.1 p.2 with
| Except.ok categories => pure { categories := categories, .. s }
| Except.error ex => throw (IO.userError ex)
| Except.error ex => throw (IO.userError ex))
s)
s
def mkParserExtension : IO ParserExtension :=
registerPersistentEnvExtension {
name := `parserExt,
mkInitial := ParserExtension.mkInitial,
addImportedFn := ParserExtension.addImported,
addEntryFn := ParserExtension.addEntry,
exportEntriesFn := fun s => s.newEntries.reverse.toArray,
statsFn := fun s => format "number of local entries: " ++ format s.newEntries.length
}
@[init mkParserExtension]
constant parserExtension : ParserExtension := arbitrary _
def isParserCategory (env : Environment) (catName : Name) : Bool :=
(parserExtension.getState env).categories.contains catName
def addParserCategory (env : Environment) (catName : Name) (leadingIdentAsSymbol : Bool) : Except String Environment := do
if isParserCategory env catName then
throwParserCategoryAlreadyDefined catName
else
pure $ parserExtension.addEntry env $ ParserExtensionEntry.category catName leadingIdentAsSymbol
/-
Return true if in the given category leading identifiers in parsers may be treated as atoms/symbols.
See comment at `ParserCategory`. -/
def leadingIdentAsSymbol (env : Environment) (catName : Name) : Bool :=
match (parserExtension.getState env).categories.find? catName with
| none => false
| some cat => cat.leadingIdentAsSymbol
private def catNameToString : Name → String
| Name.str Name.anonymous s _ => s
| n => n.toString
@[inline] def mkCategoryAntiquotParser (kind : Name) : ParserFn :=
-- allow "anonymous" antiquotations `$x` for the `term` category only
-- TODO: make customizable
-- one good example for a category that should not be anonymous is
-- `index` in `tests/lean/run/bigop.lean`.
let anonAntiquot := kind == `term;
(mkAntiquot (catNameToString kind) none anonAntiquot).fn
def categoryParserFnImpl (catName : Name) : ParserFn :=
fun ctx s =>
let categories := (parserExtension.getState ctx.env).categories;
match categories.find? catName with
| some cat =>
prattParser catName cat.tables cat.leadingIdentAsSymbol (mkCategoryAntiquotParser catName) ctx s
| none => s.mkUnexpectedError ("unknown parser category '" ++ toString catName ++ "'")
@[init] def setCategoryParserFnRef : IO Unit :=
categoryParserFnRef.set categoryParserFnImpl
def addToken (env : Environment) (tk : TokenConfig) : Except String Environment := do
-- Recall that `ParserExtension.addEntry` is pure, and assumes `addTokenConfig` does not fail.
-- So, we must run it here to handle exception.
_ ← addTokenConfig (parserExtension.getState env).tokens tk;
pure $ parserExtension.addEntry env $ ParserExtensionEntry.token tk
def addSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Environment :=
parserExtension.addEntry env $ ParserExtensionEntry.kind k
def isValidSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Bool :=
let kinds := (parserExtension.getState env).kinds;
kinds.contains k || k == choiceKind || k == identKind || isLitKind k
def getSyntaxNodeKinds (env : Environment) : List SyntaxNodeKind := do
let kinds := (parserExtension.getState env).kinds;
kinds.foldl (fun ks k _ => k::ks) []
def getTokenTable (env : Environment) : TokenTable :=
(parserExtension.getState env).tokens
def mkInputContext (input : String) (fileName : String) : InputContext :=
{ input := input,
fileName := fileName,
fileMap := input.toFileMap }
def mkParserContext (env : Environment) (ctx : InputContext) : ParserContext :=
{ rbp := 0,
toInputContext := ctx,
env := env,
tokens := getTokenTable env }
def mkParserState (input : String) : ParserState :=
{ cache := initCacheForInput input }
/- convenience function for testing -/
def runParserCategory (env : Environment) (catName : Name) (input : String) (fileName := "<input>") : Except String Syntax :=
let c := mkParserContext env (mkInputContext input fileName);
let s := mkParserState input;
let s := whitespace c s;
let s := categoryParserFnImpl catName c s;
if s.hasError then
Except.error (s.toErrorMsg c)
else
Except.ok s.stxStack.back
def declareBuiltinParser (env : Environment) (addFnName : Name) (catName : Name) (declName : Name) : IO Environment :=
let name := `_regBuiltinParser ++ declName;
let type := mkApp (mkConst `IO) (mkConst `Unit);
let val := mkAppN (mkConst addFnName) #[toExpr catName, toExpr declName, mkConst declName];
let decl := Declaration.defnDecl { name := name, lparams := [], type := type, value := val, hints := ReducibilityHints.opaque, isUnsafe := false };
match env.addAndCompile {} decl with
-- TODO: pretty print error
| Except.error _ => throw (IO.userError ("failed to emit registration code for builtin parser '" ++ toString declName ++ "'"))
| Except.ok env => IO.ofExcept (setInitAttr env name)
def declareLeadingBuiltinParser (env : Environment) (catName : Name) (declName : Name) : IO Environment :=
declareBuiltinParser env `Lean.Parser.addBuiltinLeadingParser catName declName
def declareTrailingBuiltinParser (env : Environment) (catName : Name) (declName : Name) : IO Environment :=
declareBuiltinParser env `Lean.Parser.addBuiltinTrailingParser catName declName
private def BuiltinParserAttribute.add (attrName : Name) (catName : Name)
(env : Environment) (declName : Name) (args : Syntax) (persistent : Bool) : IO Environment := do
when args.hasArgs $ throw (IO.userError ("invalid attribute '" ++ toString attrName ++ "', unexpected argument"));
unless persistent $ throw (IO.userError ("invalid attribute '" ++ toString attrName ++ "', must be persistent"));
match env.find? declName with
| none => throw $ IO.userError "unknown declaration"
| some decl =>
match decl.type with
| Expr.const `Lean.Parser.TrailingParser _ _ =>
declareTrailingBuiltinParser env catName declName
| Expr.const `Lean.Parser.Parser _ _ =>
declareLeadingBuiltinParser env catName declName
| _ =>
throw (IO.userError ("unexpected parser type at '" ++ toString declName ++ "' (`Parser` or `TrailingParser` expected"))
/-
The parsing tables for builtin parsers are "stored" in the extracted source code.
-/
def registerBuiltinParserAttribute (attrName : Name) (catName : Name) (leadingIdentAsSymbol := false) : IO Unit := do
addBuiltinParserCategory catName leadingIdentAsSymbol;
registerBuiltinAttribute {
name := attrName,
descr := "Builtin parser",
add := BuiltinParserAttribute.add attrName catName,
applicationTime := AttributeApplicationTime.afterCompilation
}
private def ParserAttribute.add (attrName : Name) (catName : Name) (env : Environment) (declName : Name) (args : Syntax) (persistent : Bool) : IO Environment := do
when args.hasArgs $ throw (IO.userError ("invalid attribute '" ++ toString attrName ++ "', unexpected argument"));
let categories := (parserExtension.getState env).categories;
match mkParserOfConstant env categories declName with
| Except.error ex => throw (IO.userError ex)
| Except.ok p => do
let leading := p.1;
let parser := p.2;
let tokens := parser.info.collectTokens [];
env ← tokens.foldlM
(fun env token =>
match addToken env token with
| Except.ok env => pure env
| Except.error msg => throw (IO.userError ("invalid parser '" ++ toString declName ++ "', " ++ msg)))
env;
let kinds := parser.info.collectKinds {};
let env := kinds.foldl (fun env kind _ => addSyntaxNodeKind env kind) env;
match addParser categories catName declName leading parser with
| Except.ok _ => pure $ parserExtension.addEntry env $ ParserExtensionEntry.parser catName declName leading parser
| Except.error ex => throw (IO.userError ex)
def mkParserAttributeImpl (attrName : Name) (catName : Name) : AttributeImpl :=
{ name := attrName,
descr := "parser",
add := ParserAttribute.add attrName catName,
applicationTime := AttributeApplicationTime.afterCompilation }
/- A builtin parser attribute that can be extended by users. -/
def registerBuiltinDynamicParserAttribute (attrName : Name) (catName : Name) : IO Unit := do
registerBuiltinAttribute (mkParserAttributeImpl attrName catName)
@[init] private def registerParserAttributeImplBuilder : IO Unit :=
registerAttributeImplBuilder `parserAttr $ fun args =>
match args with
| [DataValue.ofName attrName, DataValue.ofName catName] => pure $ mkParserAttributeImpl attrName catName
| _ => throw ("invalid parser attribute implementation builder arguments")
def registerParserCategory (env : Environment) (attrName : Name) (catName : Name) (leadingIdentAsSymbol := false) : IO Environment := do
env ← IO.ofExcept $ addParserCategory env catName leadingIdentAsSymbol;
registerAttributeOfBuilder env `parserAttr [DataValue.ofName attrName, DataValue.ofName catName]
-- declare `termParser` here since it is used everywhere via antiquotations
@[init] def regBuiltinTermParserAttr : IO Unit :=
registerBuiltinParserAttribute `builtinTermParser `term
@[init] def regTermParserAttribute : IO Unit :=
registerBuiltinDynamicParserAttribute `termParser `term
def fieldIdxFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let curr := c.input.get iniPos;
if curr.isDigit && curr != '0' then
let s := takeWhileFn (fun c => c.isDigit) c s;
mkNodeToken fieldIdxKind iniPos c s
else
s.mkErrorAt "field index" iniPos
@[inline] def fieldIdx : Parser :=
withAntiquot (mkAntiquot "fieldIdx" `fieldIdx)
{ fn := fieldIdxFn,
info := mkAtomicInfo "fieldIdx" }
end Parser
namespace Syntax
section
variables {β : Type} {m : Type → Type} [Monad m]
@[inline] def foldArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β :=
s.getArgs.foldlM (flip f) b
@[inline] def foldArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run (s.foldArgsM f b)
@[inline] def forArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit :=
s.foldArgsM (fun s _ => f s) ()
@[inline] def foldSepArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β :=
s.getArgs.foldlStepM (flip f) b 2
@[inline] def foldSepArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run (s.foldSepArgsM f b)
@[inline] def forSepArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit :=
s.foldSepArgsM (fun s _ => f s) ()
@[inline] def foldSepRevArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β := do
let args := foldSepArgs s (fun arg (args : Array Syntax) => args.push arg) #[];
args.foldrM f b
@[inline] def foldSepRevArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β := do
Id.run $ foldSepRevArgsM s f b
end
end Syntax
end Lean
section
variables {β : Type} {m : Type → Type} [Monad m]
open Lean
open Lean.Syntax
@[inline] def Array.foldSepByM (args : Array Syntax) (f : Syntax → β → m β) (b : β) : m β :=
args.foldlStepM (flip f) b 2
@[inline] def Array.foldSepBy (args : Array Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run $ args.foldSepByM f b
end
|
ec81c339628e13f66c41ce612353555e27e4712f | 57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5 | /analysis/measure_theory/lebesgue_measure.lean | 9e6f26f0980b686adfc6b46de99d2ede3be8290d | [
"Apache-2.0"
] | permissive | louisanu/mathlib | 11f56f2d40dc792bc05ee2f78ea37d73e98ecbfe | 2bd5e2159d20a8f20d04fc4d382e65eea775ed39 | refs/heads/master | 1,617,706,993,439 | 1,523,163,654,000 | 1,523,163,654,000 | 124,519,997 | 0 | 0 | Apache-2.0 | 1,520,588,283,000 | 1,520,588,283,000 | null | UTF-8 | Lean | false | false | 12,494 | 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
Lebesgue measure on the real line
-/
import analysis.measure_theory.measure_space analysis.measure_theory.borel_space
noncomputable theory
open classical set lattice filter
open ennreal (of_real)
namespace measure_theory
/- "Lebesgue" lebesgue_length of an interval
Important: if `s` is not a interval [a, b) its value is `∞`. This is important to extend this to the
Lebesgue measure. -/
def lebesgue_length (s : set ℝ) : ennreal := ⨅a b (h₁ : a ≤ b) (h₂ : s = Ico a b), of_real (b - a)
@[simp] lemma lebesgue_length_Ico {a b : ℝ} (h : a ≤ b) :
lebesgue_length (Ico a b) = of_real (b - a) :=
le_antisymm
(infi_le_of_le a $ infi_le_of_le b $ infi_le_of_le h $ infi_le_of_le rfl $ le_refl _)
(le_infi $ assume a', le_infi $ assume b', le_infi $ assume h', le_infi $ assume eq,
match Ico_eq_Ico_iff.mp eq with
| or.inl ⟨h₁, h₂⟩ :=
have a = b, from le_antisymm h h₁,
have a' = b', from le_antisymm h' h₂,
by simp *
| or.inr ⟨h₁, h⟩ := by simp *
end)
@[simp] lemma lebesgue_length_empty : lebesgue_length ∅ = 0 :=
have ∅ = Ico 0 (0:ℝ),
from set.ext $ by simp [Ico, not_le],
by rw [this, lebesgue_length_Ico]; simp [le_refl]
lemma le_lebesgue_length {r : ennreal} {s : set ℝ } (h : ∀a b, a ≤ b → s ≠ Ico a b) :
r ≤ lebesgue_length s :=
le_infi $ assume a, le_infi $ assume b, le_infi $ assume hab, le_infi $ assume heq, (h a b hab heq).elim
lemma lebesgue_length_Ico_le_lebesgue_length_Ico {a₁ b₁ a₂ b₂ : ℝ} (ha : a₂ ≤ a₁) (hb : b₁ ≤ b₂) :
lebesgue_length (Ico a₁ b₁) ≤ lebesgue_length (Ico a₂ b₂) :=
(le_total b₁ a₁).elim
(assume : b₁ ≤ a₁, by simp [Ico_eq_empty_iff.mpr this])
(assume h₁ : a₁ ≤ b₁,
have h₂ : a₂ ≤ b₂, from le_trans (le_trans ha h₁) hb,
by simp [h₁, h₂, -sub_eq_add_neg]; exact sub_le_sub hb ha)
lemma lebesgue_length_subadditive {a b : ℝ} {c d : ℕ → ℝ}
(hab : a ≤ b) (hcd : ∀i, c i ≤ d i) (habcd : Ico a b ⊆ (⋃i, Ico (c i) (d i))) :
lebesgue_length (Ico a b) ≤ (∑i, lebesgue_length (Ico (c i) (d i))) :=
let
s := λx, ∑i, lebesgue_length (Ico (c i) (min (d i) x)),
M := {x : ℝ | a ≤ x ∧ x ≤ b ∧ of_real (x - a) ≤ s x }
in
have a ∈ M, by simp [M, le_refl, hab],
have b ∈ upper_bounds M, by simp [upper_bounds, M] {contextual:=tt},
let ⟨x, hx⟩ := exists_supremum_real ‹a ∈ M› ‹b ∈ upper_bounds M› in
have h' : is_lub ((λx, of_real (x - a)) '' M) (of_real (x - a)),
from is_lub_of_is_lub_of_tendsto
(assume x ⟨hx, _, _⟩ y ⟨hy, _, _⟩ h,
have hx : 0 ≤ x - a, by rw [le_sub_iff_add_le]; simp [hx],
have hy : 0 ≤ y - a, by rw [le_sub_iff_add_le]; simp [hy],
by rw [ennreal.of_real_le_of_real_iff hx hy]; from sub_le_sub h (le_refl a))
hx
(ne_empty_iff_exists_mem.mpr ⟨a, ‹_›⟩)
(tendsto.comp (tendsto_sub (tendsto_id' inf_le_left) tendsto_const_nhds) ennreal.tendsto_of_real),
have hax : a ≤ x, from hx.left a ‹a ∈ M›,
have hxb : x ≤ b, from hx.right b ‹b ∈ upper_bounds M›,
have hx_sx : of_real (x - a) ≤ s x,
from h'.right _ $ assume r ⟨y, hy, eq⟩,
have ∀i, lebesgue_length (Ico (c i) (min (d i) y)) ≤ lebesgue_length (Ico (c i) (min (d i) x)),
from assume i,
lebesgue_length_Ico_le_lebesgue_length_Ico (le_refl _) (inf_le_inf (le_refl _) (hx.left _ hy)),
eq ▸ le_trans hy.2.2 $ ennreal.tsum_le_tsum this,
have hxM : x ∈ M,
from ⟨hax, hxb, hx_sx⟩,
have x = b,
from le_antisymm hxb $ not_lt.mp $ assume hxb : x < b,
have ∃k, x ∈ Ico (c k) (d k), by simpa using habcd ⟨hxM.left, hxb⟩,
let ⟨k, hxc, hxd⟩ := this, y := min (d k) b in
have hxy' : x < y, from lt_min hxd hxb,
have hxy : x ≤ y, from le_of_lt hxy',
have of_real (y - a) ≤ s y,
from calc of_real (y - a) = of_real (x - a) + of_real (y - x) :
begin
rw [ennreal.of_real_add],
simp,
repeat { simp [hax, hxy, -sub_eq_add_neg] }
end
... ≤ s x + (∑i, ⨆ h : i = k, of_real (y - x)) :
add_le_add' hx_sx (le_trans (by simp) (@ennreal.le_tsum _ _ k))
... ≤ (∑i, lebesgue_length (Ico (c i) (min (d i) x)) + ⨆ h : i = k, of_real (y - x)) :
by rw [tsum_add]; simp [ennreal.has_sum]
... ≤ s y : ennreal.tsum_le_tsum $ assume i, by_cases
(assume : i = k,
have eq₁ : min (d k) y = y, from min_eq_right $ min_le_left _ _,
have eq₂ : min (d k) x = x, from min_eq_right $ le_of_lt hxd,
have h : c k ≤ y, from le_min (hcd _) (le_trans hxc $ le_of_lt hxb),
have eq: y - x + (x - c k) = y - c k, by rw [add_sub, sub_add_cancel],
by simp [h, hxy, hxc, eq, eq₁, eq₂, this, -sub_eq_add_neg, add_sub_cancel'_right, le_refl])
(assume h : i ≠ k, by simp [h, ennreal.bot_eq_zero];
from lebesgue_length_Ico_le_lebesgue_length_Ico (le_refl _) (inf_le_inf (le_refl _) hxy)),
have ¬ x < y, from not_lt.mpr $ hx.left y ⟨le_trans hax hxy, min_le_right _ _, this⟩,
this hxy',
have hbM : b ∈ M, from this ▸ hxM,
calc lebesgue_length (Ico a b) ≤ s b : by simp [hab]; exact hbM.right.right
... ≤ ∑i, lebesgue_length (Ico (c i) (d i)) : ennreal.tsum_le_tsum $ assume a,
lebesgue_length_Ico_le_lebesgue_length_Ico (le_refl _) (min_le_left _ _)
/-- The Lebesgue outer measure, as an outer measure of ℝ. -/
def lebesgue_outer : outer_measure ℝ :=
outer_measure.of_function lebesgue_length lebesgue_length_empty
lemma lebesgue_outer_Ico {a b : ℝ} (h : a ≤ b) :
lebesgue_outer.measure_of (Ico a b) = of_real (b - a) :=
le_antisymm
(let f : ℕ → set ℝ := λi, nat.rec_on i (Ico a b) (λn s, ∅) in
infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $
calc (∑i, lebesgue_length (f i)) = ({0} : finset ℕ).sum (λi, lebesgue_length (f i)) :
tsum_eq_sum $ by intro i; cases i; simp
... = lebesgue_length (Ico a b) : by simp; refl
... ≤ of_real (b - a) : by simp [h])
(le_infi $ assume f, le_infi $ assume hf, by_cases
(assume : ∀i, ∃p:ℝ×ℝ, p.1 ≤ p.2 ∧ f i = Ico p.1 p.2,
let ⟨cd, hcd⟩ := axiom_of_choice this in
have hcd₁ : ∀i, (cd i).1 ≤ (cd i).2, from assume i, (hcd i).1,
have hcd₂ : ∀i, f i = Ico (cd i).1 (cd i).2, from assume i, (hcd i).2,
calc of_real (b - a) = lebesgue_length (Ico a b) :
by simp [h]
... ≤ (∑i, lebesgue_length (Ico (cd i).1 (cd i).2)) :
lebesgue_length_subadditive h hcd₁ (by simpa [hcd₂] using hf)
... = _ :
by simp [hcd₂])
(assume h,
have ∃i, ∀(c d : ℝ), c ≤ d → f i ≠ Ico c d,
by simpa [classical.not_forall] using h,
let ⟨i, hi⟩ := this in
calc of_real (b - a) ≤ lebesgue_length (f i) : le_lebesgue_length hi
... ≤ (∑i, lebesgue_length (f i)) : ennreal.le_tsum))
lemma lebesgue_outer_is_measurable_Iio {c : ℝ} :
lebesgue_outer.caratheodory.is_measurable (Iio c) :=
outer_measure.caratheodory_is_measurable $ assume t, by_cases
(assume : ∃a b, a ≤ b ∧ t = Ico a b,
let ⟨a, b, hab, ht⟩ := this in
begin
cases le_total a c with hac hca; cases le_total b c with hbc hcb;
simp [*, max_eq_right, max_eq_left, min_eq_left, min_eq_right, le_refl,
-sub_eq_add_neg, sub_add_sub_cancel'],
show of_real (b - a + (b - a)) ≤ of_real (b - a),
rw [ennreal.of_real_of_nonpos],
{ apply zero_le },
{ have : b - a ≤ 0, from sub_nonpos.2 (le_trans hbc hca),
simpa using add_le_add this this }
end)
(assume h, by simp at h; from le_lebesgue_length h)
/-- Lebesgue measure on the Borel sets
The outer Lebesgue measure is the completion of this measure. (TODO: proof this)
-/
def lebesgue : measure_space ℝ :=
lebesgue_outer.to_measure $
calc measure_theory.borel ℝ = measurable_space.generate_from (⋃a:ℚ, {Iio a}) :
borel_eq_generate_from_Iio_rat
... ≤ lebesgue_outer.caratheodory :
measurable_space.generate_from_le $ by simp [lebesgue_outer_is_measurable_Iio] {contextual := tt}
lemma tendsto_of_nat_at_top_at_top : tendsto (coe : ℕ → ℝ) at_top at_top :=
tendsto_infi.2 $ assume r, tendsto_principal.2 $
let ⟨n, hn⟩ := exists_nat_gt r in
mem_at_top_sets.2 ⟨n, λ m h, le_trans (le_of_lt hn) (nat.cast_le.2 h)⟩
lemma lebesgue_Ico {a b : ℝ} : lebesgue (Ico a b) = of_real (b - a) :=
match le_total a b with
| or.inl h :=
begin
rw [lebesgue.measure_eq is_measurable_Ico],
{ exact lebesgue_outer_Ico h },
repeat {apply_instance}
end
| or.inr h :=
have hba : b - a ≤ 0, by simp [-sub_eq_add_neg, h],
have eq : Ico a b = ∅, from Ico_eq_empty_iff.mpr h,
by simp [ennreal.of_real_of_nonpos, *] at *
end
lemma lebesgue_Ioo {a b : ℝ} : lebesgue (Ioo a b) = of_real (b - a) :=
by_cases (assume h : b ≤ a, by simp [h, -sub_eq_add_neg, ennreal.of_real_of_nonpos]) $
assume : ¬ b ≤ a,
have h : a < b, from not_le.mp this,
let s := λn:ℕ, a + (b - a) * (↑(n + 1))⁻¹ in
have tendsto s at_top (nhds (a + (b - a) * 0)),
from tendsto_add tendsto_const_nhds $ tendsto_mul tendsto_const_nhds $
(tendsto_comp_succ_at_top_iff.mpr tendsto_of_nat_at_top_at_top).comp tendsto_inverse_at_top_nhds_0,
have hs : tendsto s at_top (nhds a), by simpa,
have hsm : ∀i j, j ≤ i → s i ≤ s j,
from assume i j hij,
have h₁ : ∀j:ℕ, (0:ℝ) < (j + 1),
from assume j, nat.cast_pos.2 $ add_pos_of_nonneg_of_pos (nat.zero_le j) zero_lt_one,
have h₂ : (↑(j + 1) : ℝ) ≤ ↑(i + 1), from nat.cast_le.2 $ add_le_add hij (le_refl _),
add_le_add (le_refl _) $
mul_le_mul (le_refl _) (inv_le_inv_of_le (h₁ j) h₂) (le_of_lt $ inv_pos $ h₁ i) $
by simp [le_sub_iff_add_le, -sub_eq_add_neg, le_of_lt h],
have has : ∀i, a < s i,
from assume i,
have (0:ℝ) < ↑(i + 1), from nat.cast_pos.2 $ lt_add_of_le_of_pos (nat.zero_le _) zero_lt_one,
(lt_add_iff_pos_right _).mpr $ mul_pos
(by simp [-sub_eq_add_neg, sub_lt_iff, (>), ‹a < b›]) (inv_pos this),
have eq₁ : Ioo a b = (⋃n, Ico (s n) b),
from set.ext $ assume x,
begin
simp [iff_def, Ico, Ioo, -sub_eq_add_neg] {contextual := tt},
constructor,
exact assume hax hxb,
have {a | a < x } ∈ (nhds a).sets, from mem_nhds_sets (is_open_gt' _) hax,
have {n | s n < x} ∈ at_top.sets, from hs this,
let ⟨n, hn⟩ := inhabited_of_mem_sets at_top_ne_bot this in
⟨n, le_of_lt hn⟩,
exact assume i hsx hxb, lt_of_lt_of_le (has i) hsx,
end,
have (⨆i, of_real (b - s i)) = of_real (b - a),
from is_lub_iff_supr_eq.mp $ is_lub_of_mem_nhds
(assume x ⟨i, eq⟩, eq ▸ ennreal.of_real_le_of_real $ sub_le_sub (le_refl _) $ le_of_lt $ has _)
begin
show range (λi, of_real (b - s i)) ∈ (at_top.map (λi, of_real (b - s i))).sets,
rw [← image_univ]; exact image_mem_map univ_mem_sets
end
begin
have : tendsto (λi, of_real (b - s i)) at_top (nhds (of_real (b - a))),
from (tendsto_sub tendsto_const_nhds hs).comp ennreal.tendsto_of_real,
rw [inf_of_le_left this],
exact map_ne_bot at_top_ne_bot
end,
have eq₂ : (⨆i, lebesgue (Ico (s i) b)) = of_real (b - a),
by simp only [lebesgue_Ico, this],
begin
rw [eq₁, measure_Union_eq_supr_nat, eq₂],
show ∀i, is_measurable (Ico (s i) b), from assume i, is_measurable_Ico,
show monotone (λi, Ico (s i) b),
from assume i j hij x hx, ⟨le_trans (hsm _ _ hij) hx.1, hx.2⟩
end
lemma lebesgue_singleton {a : ℝ} : lebesgue {a} = 0 :=
have Ico a (a + 1) \ Ioo a (a + 1) = {a},
from set.ext $ assume a',
begin
simp [iff_def, Ico, Ioo, lt_irrefl, le_refl, zero_lt_one,
le_iff_eq_or_lt, or_imp_distrib] {contextual := tt},
exact assume h₁ h₂,
⟨assume eq, by rw [eq] at h₂; exact (lt_irrefl _ h₂).elim,
assume h₃, (lt_irrefl a' $ lt_trans h₂ h₃).elim⟩
end,
calc lebesgue {a} = lebesgue (Ico a (a + 1) \ Ioo a (a + 1)) :
congr_arg _ this.symm
... = lebesgue (Ico a (a + 1)) - lebesgue (Ioo a (a + 1)) :
measure_sdiff (assume x, and.imp le_of_lt id) is_measurable_Ico is_measurable_Ioo $
by simp [lebesgue_Ico]; exact ennreal.of_real_lt_infty
... = 0 : by simp [lebesgue_Ico, lebesgue_Ioo]
end measure_theory
|
449fcab72ddbc40f5bd8e95ba21af3b45ada9ac7 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/algebra/field.lean | 743511452107bf7a69f24eca06bcfd1d3e9c6d11 | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 10,123 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import algebra.ring logic.basic
open set
universe u
variables {α : Type u}
/-- Core version `division_ring_has_div` erratically requires two instances of `division_ring` -/
-- priority 900 sufficient as core version has custom-set lower priority (100)
@[priority 900] -- see Note [lower instance priority]
instance division_ring_has_div' [division_ring α] : has_div α := ⟨algebra.div⟩
@[priority 100] -- see Note [lower instance priority]
instance division_ring.to_domain [s : division_ring α] : domain α :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h,
classical.by_contradiction $ λ hn,
division_ring.mul_ne_zero (mt or.inl hn) (mt or.inr hn) h
..s }
@[simp] theorem inv_one [division_ring α] : (1⁻¹ : α) = 1 := by rw [inv_eq_one_div, one_div_one]
@[simp] theorem inv_inv' [discrete_field α] (x : α) : x⁻¹⁻¹ = x :=
if h : x = 0
then by rw [h, inv_zero, inv_zero]
else division_ring.inv_inv h
lemma inv_involutive' [discrete_field α] : function.involutive (has_inv.inv : α → α) :=
inv_inv'
namespace units
variables [division_ring α] {a b : α}
/-- Embed an element of a division ring into the unit group.
By combining this function with the operations on units,
or the `/ₚ` operation, it is possible to write a division
as a partial function with three arguments. -/
def mk0 (a : α) (ha : a ≠ 0) : units α :=
⟨a, a⁻¹, mul_inv_cancel ha, inv_mul_cancel ha⟩
@[simp] theorem inv_eq_inv (u : units α) : (↑u⁻¹ : α) = u⁻¹ :=
(mul_left_inj u).1 $ by rw [units.mul_inv, mul_inv_cancel]; apply units.ne_zero
@[simp] theorem mk0_val (ha : a ≠ 0) : (mk0 a ha : α) = a := rfl
@[simp] theorem mk0_inv (ha : a ≠ 0) : ((mk0 a ha)⁻¹ : α) = a⁻¹ := rfl
@[simp] lemma mk0_coe (u : units α) (h : (u : α) ≠ 0) : mk0 (u : α) h = u :=
units.ext rfl
@[simp] lemma mk0_inj {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) :
units.mk0 a ha = units.mk0 b hb ↔ a = b :=
⟨λ h, by injection h, λ h, units.ext h⟩
end units
section division_ring
variables [s : division_ring α] {a b c : α}
include s
lemma div_eq_mul_inv : a / b = a * b⁻¹ := rfl
attribute [simp] div_one zero_div div_self
theorem divp_eq_div (a : α) (u : units α) : a /ₚ u = a / u :=
congr_arg _ $ units.inv_eq_inv _
@[simp] theorem divp_mk0 (a : α) {b : α} (hb : b ≠ 0) :
a /ₚ units.mk0 b hb = a / b :=
divp_eq_div _ _
lemma inv_div (ha : a ≠ 0) (hb : b ≠ 0) : (a / b)⁻¹ = b / a :=
(mul_inv_eq (inv_ne_zero hb) ha).trans $ by rw division_ring.inv_inv hb; refl
lemma inv_div_left (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ / b = (b * a)⁻¹ :=
(mul_inv_eq ha hb).symm
lemma neg_inv (h : a ≠ 0) : - a⁻¹ = (- a)⁻¹ :=
by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div _ h]
lemma division_ring.inv_comm_of_comm (h : a ≠ 0) (H : a * b = b * a) : a⁻¹ * b = b * a⁻¹ :=
begin
have : a⁻¹ * (b * a) * a⁻¹ = a⁻¹ * (a * b) * a⁻¹ :=
congr_arg (λ x:α, a⁻¹ * x * a⁻¹) H.symm,
rwa [mul_assoc, mul_assoc, mul_inv_cancel, mul_one,
← mul_assoc, inv_mul_cancel, one_mul] at this; exact h
end
lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 :=
division_ring.mul_ne_zero ha (inv_ne_zero hb)
lemma div_ne_zero_iff (hb : b ≠ 0) : a / b ≠ 0 ↔ a ≠ 0 :=
⟨mt (λ h, by rw [h, zero_div]), λ ha, div_ne_zero ha hb⟩
lemma div_eq_zero_iff (hb : b ≠ 0) : a / b = 0 ↔ a = 0 :=
by haveI := classical.prop_decidable; exact
not_iff_not.1 (div_ne_zero_iff hb)
lemma add_div (a b c : α) : (a + b) / c = a / c + b / c :=
(div_add_div_same _ _ _).symm
lemma div_right_inj (hc : c ≠ 0) : a / c = b / c ↔ a = b :=
by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_right_inj]
lemma sub_div (a b c : α) : (a - b) / c = a / c - b / c :=
(div_sub_div_same _ _ _).symm
lemma division_ring.inv_inj (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ = b⁻¹ ↔ a = b :=
⟨λ h, by rw [← division_ring.inv_inv ha, ← division_ring.inv_inv hb, h], congr_arg (λx,x⁻¹)⟩
lemma division_ring.inv_eq_iff (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ = b ↔ b⁻¹ = a :=
by rw [← division_ring.inv_inj (inv_ne_zero ha) hb,
eq_comm, division_ring.inv_inv ha]
lemma div_neg (a : α) (hb : b ≠ 0) : a / -b = -(a / b) :=
by rw [← division_ring.neg_div_neg_eq _ (neg_ne_zero.2 hb), neg_neg, neg_div]
lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a :=
⟨λ h, by rw [← h, div_mul_cancel _ hb],
λ h, by rw [← h, mul_div_cancel _ hb]⟩
end division_ring
@[priority 100] -- see Note [lower instance priority]
instance field.to_integral_domain [F : field α] : integral_domain α :=
{ ..F, ..division_ring.to_domain }
section
variables [field α] {a b c d : α}
lemma div_eq_inv_mul : a / b = b⁻¹ * a := mul_comm _ _
lemma inv_add_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) :=
by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb]
lemma inv_sub_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) :=
by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one]
lemma mul_div_right_comm (a b c : α) : (a * b) / c = (a / c) * b :=
(div_mul_eq_mul_div _ _ _).symm
lemma mul_comm_div (a b c : α) : (a / b) * c = a * (c / b) :=
by rw [← mul_div_assoc, mul_div_right_comm]
lemma div_mul_comm (a b c : α) : (a / b) * c = (c / b) * a :=
by rw [div_mul_eq_mul_div, mul_comm, mul_div_right_comm]
lemma mul_div_comm (a b c : α) : a * (b / c) = b * (a / c) :=
by rw [← mul_div_assoc, mul_comm, mul_div_assoc]
lemma field.div_right_comm (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / b) / c = (a / c) / b :=
by rw [field.div_div_eq_div_mul _ hb hc, field.div_div_eq_div_mul _ hc hb, mul_comm]
lemma field.div_div_div_cancel_right (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / c) / (b / c) = a / b :=
by rw [field.div_div_eq_mul_div _ hb hc, div_mul_cancel _ hc]
lemma div_mul_div_cancel (a : α) (hc : c ≠ 0) : (a / c) * (c / b) = a / b :=
by rw [← mul_div_assoc, div_mul_cancel _ hc]
lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b :=
(domain.mul_right_inj (mul_ne_zero' hb hd)).symm.trans $
by rw [← mul_assoc, div_mul_cancel _ hb,
← mul_assoc, mul_right_comm, div_mul_cancel _ hd]
lemma div_eq_iff (hb : b ≠ 0) : a / b = c ↔ a = c * b :=
by simpa using @div_eq_div_iff _ _ a b c 1 hb one_ne_zero
lemma eq_div_iff (hb : b ≠ 0) : c = a / b ↔ c * b = a :=
by simpa using @div_eq_div_iff _ _ c 1 a b one_ne_zero hb
lemma field.div_div_cancel (ha : a ≠ 0) (hb : b ≠ 0) : a / (a / b) = b :=
by rw [div_eq_mul_inv, inv_div ha hb, mul_div_cancel' _ ha]
lemma add_div' (a b c : α) (hc : c ≠ 0) :
b + a / c = (b * c + a) / c :=
by simpa using div_add_div b a one_ne_zero hc
lemma div_add' (a b c : α) (hc : c ≠ 0) :
a / c + b = (a + b * c) / c :=
by simpa using div_add_div b a one_ne_zero hc
end
section
variables [discrete_field α] {a b c : α}
attribute [simp] inv_zero div_zero
lemma div_right_comm (a b c : α) : (a / b) / c = (a / c) / b :=
if b0 : b = 0 then by simp only [b0, div_zero, zero_div] else
if c0 : c = 0 then by simp only [c0, div_zero, zero_div] else
field.div_right_comm _ b0 c0
lemma div_div_div_cancel_right (a b : α) (hc : c ≠ 0) : (a / c) / (b / c) = a / b :=
if b0 : b = 0 then by simp only [b0, div_zero, zero_div] else
field.div_div_div_cancel_right _ b0 hc
lemma div_div_cancel (ha : a ≠ 0) : a / (a / b) = b :=
if b0 : b = 0 then by simp only [b0, div_zero] else
field.div_div_cancel ha b0
@[simp] lemma inv_eq_zero {a : α} : a⁻¹ = 0 ↔ a = 0 :=
classical.by_cases (assume : a = 0, by simp [*])(assume : a ≠ 0, by simp [*, inv_ne_zero])
lemma neg_inv' (a : α) : (-a)⁻¹ = - a⁻¹ :=
begin
by_cases a = 0,
{ rw [h, neg_zero, inv_zero, neg_zero] },
{ rw [neg_inv h] }
end
end
namespace is_ring_hom
open is_ring_hom
section
variables {β : Type*} [division_ring α] [division_ring β]
variables (f : α → β) [is_ring_hom f] {x y : α}
lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 :=
⟨mt $ λ h, h.symm ▸ map_zero f,
λ x0 h, one_ne_zero $ calc
1 = f (x * x⁻¹) : by rw [mul_inv_cancel x0, map_one f]
... = 0 : by rw [map_mul f, h, zero_mul]⟩
lemma map_eq_zero : f x = 0 ↔ x = 0 :=
by haveI := classical.dec; exact not_iff_not.1 (map_ne_zero f)
lemma map_inv' (h : x ≠ 0) : f x⁻¹ = (f x)⁻¹ :=
(domain.mul_left_inj ((map_ne_zero f).2 h)).1 $
by rw [mul_inv_cancel ((map_ne_zero f).2 h), ← map_mul f, mul_inv_cancel h, map_one f]
lemma map_div' (h : y ≠ 0) : f (x / y) = f x / f y :=
(map_mul f).trans $ congr_arg _ $ map_inv' f h
lemma injective : function.injective f :=
(is_add_group_hom.injective_iff _).2
(λ a ha, classical.by_contradiction $ λ ha0,
by simpa [ha, is_ring_hom.map_mul f, is_ring_hom.map_one f, zero_ne_one]
using congr_arg f (mul_inv_cancel ha0))
end
section
variables {β : Type*} [discrete_field α] [discrete_field β]
variables (f : α → β) [is_ring_hom f] {x y : α}
lemma map_inv : f x⁻¹ = (f x)⁻¹ :=
classical.by_cases (by rintro rfl; simp only [map_zero f, inv_zero]) (map_inv' f)
lemma map_div : f (x / y) = f x / f y :=
(map_mul f).trans $ congr_arg _ $ map_inv f
end
end is_ring_hom
section field_simp
mk_simp_attribute field_simps "The simpset `field_simps` is used by the tactic `field_simp` to
reduce an expression in a field to an expression of the form `n / d` where `n` and `d` are
division-free."
lemma mul_div_assoc' {α : Type*} [division_ring α] (a b c : α) : a * (b / c) = (a * b) / c :=
by simp [mul_div_assoc]
lemma neg_div' {α : Type*} [division_ring α] (a b : α) : - (b / a) = (-b) / a :=
by simp [neg_div]
attribute [field_simps] div_add_div_same inv_eq_one_div div_mul_eq_mul_div div_add' add_div'
div_div_eq_div_mul mul_div_assoc' div_eq_div_iff div_eq_iff eq_div_iff mul_ne_zero'
div_div_eq_mul_div neg_div' two_ne_zero
end field_simp
|
d4b337ab5a3773803130986a2e9a6238d0f305f9 | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/measure_theory/bochner_integration.lean | 35e9f72d427eeabd1211bf41f55b734621df1e46 | [
"Apache-2.0"
] | permissive | eric-wieser/mathlib | 42842584f584359bbe1fc8b88b3ff937c8acd72d | d0df6b81cd0920ad569158c06a3fd5abb9e63301 | refs/heads/master | 1,669,546,404,255 | 1,595,254,668,000 | 1,595,254,668,000 | 281,173,504 | 0 | 0 | Apache-2.0 | 1,595,263,582,000 | 1,595,263,581,000 | null | UTF-8 | Lean | false | false | 55,625 | lean | /-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import measure_theory.simple_func_dense
import analysis.normed_space.bounded_linear_maps
import topology.sequences
/-!
# Bochner integral
The Bochner integral extends the definition of the Lebesgue integral to functions that map from a
measure space into a Banach space (complete normed vector space). It is constructed here by
extending the integral on simple functions.
## Main definitions
The Bochner integral is defined following these steps:
1. Define the integral on simple functions of the type `simple_func α E` (notation : `α →ₛ E`)
where `E` is a real normed space.
(See `simple_func.bintegral` and section `bintegral` for details. Also see `simple_func.integral`
for the integral on simple functions of the type `simple_func α ennreal`.)
2. Use `α →ₛ E` to cut out the simple functions from L1 functions, and define integral
on these. The type of simple functions in L1 space is written as `α →₁ₛ[μ] E`.
3. Show that the embedding of `α →₁ₛ[μ] E` into L1 is a dense and uniform one.
4. Show that the integral defined on `α →₁ₛ[μ] E` is a continuous linear map.
5. Define the Bochner integral on L1 functions by extending the integral on integrable simple
functions `α →₁ₛ[μ] E` using `continuous_linear_map.extend`. Define the Bochner integral on functions
as the Bochner integral of its equivalence class in L1 space.
## Main statements
1. Basic properties of the Bochner integral on functions of type `α → E`, where `α` is a measure
space and `E` is a real normed space.
* `integral_zero` : `∫ 0 = 0`
* `integral_add` : `∫ f + g = ∫ f + ∫ g`
* `integral_neg` : `∫ -f = - ∫ f`
* `integral_sub` : `∫ f - g = ∫ f - ∫ g`
* `integral_smul` : `∫ r • f = r • ∫ f`
* `integral_congr_ae` : `∀ᵐ a, f a = g a → ∫ f = ∫ g`
* `norm_integral_le_integral_norm` : `∥∫ f∥ ≤ ∫ ∥f∥`
2. Basic properties of the Bochner integral on functions of type `α → ℝ`, where `α` is a measure
space.
* `integral_nonneg_of_ae` : `∀ᵐ a, 0 ≤ f a → 0 ≤ ∫ f`
* `integral_nonpos_of_nonpos_ae` : `∀ᵐ a, f a ≤ 0 → ∫ f ≤ 0`
* `integral_le_integral_of_le_ae` : `∀ᵐ a, f a ≤ g a → ∫ f ≤ ∫ g`
3. Propositions connecting the Bochner integral with the integral on `ennreal`-valued functions,
which is called `lintegral` and has the notation `∫⁻`.
* `integral_eq_lintegral_max_sub_lintegral_min` : `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, where `f⁺` is the positive
part of `f` and `f⁻` is the negative part of `f`.
* `integral_eq_lintegral_of_nonneg_ae` : `∀ᵐ a, 0 ≤ f a → ∫ f = ∫⁻ f`
4. `tendsto_integral_of_dominated_convergence` : the Lebesgue dominated convergence theorem
## Notes
Some tips on how to prove a proposition if the API for the Bochner integral is not enough so that
you need to unfold the definition of the Bochner integral and go back to simple functions.
See `integral_eq_lintegral_max_sub_lintegral_min` for a complicated example, which proves that
`∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, with the first integral sign being the Bochner integral of a real-valued
function f : α → ℝ, and second and third integral sign being the integral on ennreal-valued
functions (called `lintegral`). The proof of `integral_eq_lintegral_max_sub_lintegral_min` is
scattered in sections with the name `pos_part`.
Here are the usual steps of proving that a property `p`, say `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, holds for all
functions :
1. First go to the `L¹` space.
For example, if you see `ennreal.to_real (∫⁻ a, ennreal.of_real $ ∥f a∥)`, that is the norm of `f` in
`L¹` space. Rewrite using `l1.norm_of_fun_eq_lintegral_norm`.
2. Show that the set `{f ∈ L¹ | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻}` is closed in `L¹` using `is_closed_eq`.
3. Show that the property holds for all simple functions `s` in `L¹` space.
Typically, you need to convert various notions to their `simple_func` counterpart, using lemmas like
`l1.integral_coe_eq_integral`.
4. Since simple functions are dense in `L¹`,
```
univ = closure {s simple}
= closure {s simple | ∫ s = ∫⁻ s⁺ - ∫⁻ s⁻} : the property holds for all simple functions
⊆ closure {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻}
= {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} : closure of a closed set is itself
```
Use `is_closed_property` or `dense_range.induction_on` for this argument.
## Notations
* `α →ₛ E` : simple functions (defined in `measure_theory/integration`)
* `α →₁[μ] E` : functions in L1 space, i.e., equivalence classes of integrable functions (defined in
`measure_theory/l1_space`)
* `α →₁ₛ[μ] E` : simple functions in L1 space, i.e., equivalence classes of integrable simple functions
Note : `ₛ` is typed using `\_s`. Sometimes it shows as a box if font is missing.
## Tags
Bochner integral, simple function, function space, Lebesgue dominated convergence theorem
-/
noncomputable theory
open_locale classical topological_space big_operators
namespace measure_theory
variables {α E : Type*} [measurable_space α] [decidable_linear_order E] [has_zero E]
local infixr ` →ₛ `:25 := simple_func
namespace simple_func
section pos_part
/-- Positive part of a simple function. -/
def pos_part (f : α →ₛ E) : α →ₛ E := f.map (λb, max b 0)
/-- Negative part of a simple function. -/
def neg_part [has_neg E] (f : α →ₛ E) : α →ₛ E := pos_part (-f)
lemma pos_part_map_norm (f : α →ₛ ℝ) : (pos_part f).map norm = pos_part f :=
begin
ext,
rw [map_apply, real.norm_eq_abs, abs_of_nonneg],
rw [pos_part, map_apply],
exact le_max_right _ _
end
lemma neg_part_map_norm (f : α →ₛ ℝ) : (neg_part f).map norm = neg_part f :=
by { rw neg_part, exact pos_part_map_norm _ }
lemma pos_part_sub_neg_part (f : α →ₛ ℝ) : f.pos_part - f.neg_part = f :=
begin
simp only [pos_part, neg_part],
ext,
exact max_zero_sub_eq_self (f a)
end
end pos_part
end simple_func
end measure_theory
namespace measure_theory
open set filter topological_space ennreal emetric
variables {α E F : Type*} [measurable_space α]
local infixr ` →ₛ `:25 := simple_func
namespace simple_func
section integral
/-!
### The Bochner integral of simple functions
Define the Bochner integral of simple functions of the type `α →ₛ β` where `β` is a normed group,
and prove basic property of this integral.
-/
open finset
variables [normed_group E] [normed_group F] {μ : measure α}
/-- For simple functions with a `normed_group` as codomain, being integrable is the same as having
finite volume support. -/
lemma integrable_iff_fin_meas_supp {f : α →ₛ E} {μ : measure α} :
integrable f μ ↔ f.fin_meas_supp μ :=
calc integrable f μ ↔ ∫⁻ x, f.map (coe ∘ nnnorm : E → ennreal) x ∂μ < ⊤ : iff.rfl
... ↔ (f.map (coe ∘ nnnorm : E → ennreal)).lintegral μ < ⊤ : by rw lintegral_eq_lintegral
... ↔ (f.map (coe ∘ nnnorm : E → ennreal)).fin_meas_supp μ : iff.symm $
fin_meas_supp.iff_lintegral_lt_top $ eventually_of_forall $ λ x, coe_lt_top
... ↔ _ : fin_meas_supp.map_iff $ λ b, coe_eq_zero.trans nnnorm_eq_zero
lemma fin_meas_supp.integrable {f : α →ₛ E} (h : f.fin_meas_supp μ) : integrable f μ :=
integrable_iff_fin_meas_supp.2 h
lemma integrable_pair {f : α →ₛ E} {g : α →ₛ F} :
integrable f μ → integrable g μ → integrable (pair f g) μ :=
by simpa only [integrable_iff_fin_meas_supp] using fin_meas_supp.pair
variables [normed_space ℝ F]
/-- Bochner integral of simple functions whose codomain is a real `normed_space`. -/
def integral (μ : measure α) (f : α →ₛ F) : F :=
∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • x
lemma integral_eq_sum_filter (f : α →ₛ F) (μ) :
f.integral μ = ∑ x in f.range.filter (λ x, x ≠ 0), (ennreal.to_real (μ (f ⁻¹' {x}))) • x :=
eq.symm $ sum_filter_of_ne $ λ x _, mt $ λ h0, h0.symm ▸ smul_zero _
/-- Calculate the integral of `g ∘ f : α →ₛ F`, where `f` is an integrable function from `α` to `β`
and `g` is a function from `β` to `F`. We require `g 0 = 0` so that `g ∘ f` is integrable. -/
lemma map_integral (f : α →ₛ E) (g : E → F) (hf : integrable f μ) (hg : g 0 = 0) :
(f.map g).integral μ = ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • (g x) :=
begin
-- We start as in the proof of `map_lintegral`
simp only [integral, range_map],
refine finset.sum_image' _ (assume b hb, _),
rcases mem_range.1 hb with ⟨a, rfl⟩,
rw [map_preimage_singleton, ← sum_measure_preimage_singleton _
(λ _ _, f.is_measurable_preimage _)],
-- Now we use `hf : integrable f μ` to show that `ennreal.to_real` is additive.
by_cases ha : g (f a) = 0,
{ simp only [ha, smul_zero],
refine (sum_eq_zero $ λ x hx, _).symm,
simp only [mem_filter] at hx,
simp [hx.2] },
{ rw [to_real_sum, sum_smul],
{ refine sum_congr rfl (λ x hx, _),
simp only [mem_filter] at hx,
rw [hx.2] },
{ intros x hx,
simp only [mem_filter] at hx,
refine (integrable_iff_fin_meas_supp.1 hf).meas_preimage_singleton_ne_zero _,
exact λ h0, ha (hx.2 ▸ h0.symm ▸ hg) } },
end
/-- `simple_func.integral` and `simple_func.lintegral` agree when the integrand has type
`α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion.
See `integral_eq_lintegral` for a simpler version. -/
lemma integral_eq_lintegral' {f : α →ₛ E} {g : E → ennreal} (hf : integrable f μ) (hg0 : g 0 = 0)
(hgt : ∀b, g b < ⊤):
(f.map (ennreal.to_real ∘ g)).integral μ = ennreal.to_real (∫⁻ a, g (f a) ∂μ) :=
begin
have hf' : f.fin_meas_supp μ := integrable_iff_fin_meas_supp.1 hf,
simp only [← map_apply g f, lintegral_eq_lintegral],
rw [map_integral f _ hf, map_lintegral, ennreal.to_real_sum],
{ refine finset.sum_congr rfl (λb hb, _),
rw [smul_eq_mul, to_real_mul_to_real, mul_comm] },
{ assume a ha,
by_cases a0 : a = 0,
{ rw [a0, hg0, zero_mul], exact with_top.zero_lt_top },
{ apply mul_lt_top (hgt a) (hf'.meas_preimage_singleton_ne_zero a0) } },
{ simp [hg0] }
end
variables [normed_space ℝ E]
lemma integral_congr {f g : α →ₛ E} (hf : integrable f μ) (h : f =ᵐ[μ] g):
f.integral μ = g.integral μ :=
show ((pair f g).map prod.fst).integral μ = ((pair f g).map prod.snd).integral μ, from
begin
have inte := integrable_pair hf (hf.congr h),
rw [map_integral (pair f g) _ inte prod.fst_zero, map_integral (pair f g) _ inte prod.snd_zero],
refine finset.sum_congr rfl (assume p hp, _),
rcases mem_range.1 hp with ⟨a, rfl⟩,
by_cases eq : f a = g a,
{ dsimp only [pair_apply], rw eq },
{ have : μ ((pair f g) ⁻¹' {(f a, g a)}) = 0,
{ refine measure_mono_null (assume a' ha', _) h,
simp only [set.mem_preimage, mem_singleton_iff, pair_apply, prod.mk.inj_iff] at ha',
show f a' ≠ g a',
rwa [ha'.1, ha'.2] },
simp only [this, pair_apply, zero_smul, ennreal.zero_to_real] },
end
/-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type
`α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. -/
lemma integral_eq_lintegral {f : α →ₛ ℝ} (hf : integrable f μ) (h_pos : 0 ≤ᵐ[μ] f) :
f.integral μ = ennreal.to_real (∫⁻ a, ennreal.of_real (f a) ∂μ) :=
begin
have : f =ᵐ[μ] f.map (ennreal.to_real ∘ ennreal.of_real) :=
h_pos.mono (λ a h, (ennreal.to_real_of_real h).symm),
rw [← integral_eq_lintegral' hf],
{ exact integral_congr hf this },
{ exact ennreal.of_real_zero },
{ assume b, rw ennreal.lt_top_iff_ne_top, exact ennreal.of_real_ne_top }
end
lemma integral_add {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) :
integral μ (f + g) = integral μ f + integral μ g :=
calc integral μ (f + g) = ∑ x in (pair f g).range,
ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • (x.fst + x.snd) :
begin
rw [add_eq_map₂, map_integral (pair f g)],
{ exact integrable_pair hf hg },
{ simp only [add_zero, prod.fst_zero, prod.snd_zero] }
end
... = ∑ x in (pair f g).range,
(ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.fst +
ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.snd) :
finset.sum_congr rfl $ assume a ha, smul_add _ _ _
... = ∑ x in (pair f g).range,
ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.fst +
∑ x in (pair f g).range,
ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.snd :
by rw finset.sum_add_distrib
... = ((pair f g).map prod.fst).integral μ + ((pair f g).map prod.snd).integral μ :
begin
rw [map_integral (pair f g), map_integral (pair f g)],
{ exact integrable_pair hf hg }, { refl },
{ exact integrable_pair hf hg }, { refl }
end
... = integral μ f + integral μ g : rfl
lemma integral_neg {f : α →ₛ E} (hf : integrable f μ) : integral μ (-f) = - integral μ f :=
calc integral μ (-f) = integral μ (f.map (has_neg.neg)) : rfl
... = - integral μ f :
begin
rw [map_integral f _ hf neg_zero, integral, ← sum_neg_distrib],
refine finset.sum_congr rfl (λx h, smul_neg _ _),
end
lemma integral_sub {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) :
integral μ (f - g) = integral μ f - integral μ g :=
begin
rw [sub_eq_add_neg, integral_add hf, integral_neg hg, sub_eq_add_neg],
exact hg.neg
end
lemma integral_smul (r : ℝ) {f : α →ₛ E} (hf : integrable f μ) :
integral μ (r • f) = r • integral μ f :=
calc integral μ (r • f) = ∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • r • x :
by rw [smul_eq_map r f, map_integral f _ hf (smul_zero _)]
... = ∑ x in f.range, ((ennreal.to_real (μ (f ⁻¹' {x}))) * r) • x :
finset.sum_congr rfl $ λb hb, by apply smul_smul
... = r • integral μ f :
by simp only [integral, smul_sum, smul_smul, mul_comm]
lemma norm_integral_le_integral_norm (f : α →ₛ E) (hf : integrable f μ) :
∥f.integral μ∥ ≤ (f.map norm).integral μ :=
begin
rw [map_integral f norm hf norm_zero, integral],
calc ∥∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • x∥ ≤
∑ x in f.range, ∥ennreal.to_real (μ (f ⁻¹' {x})) • x∥ :
norm_sum_le _ _
... = ∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • ∥x∥ :
begin
refine finset.sum_congr rfl (λb hb, _),
rw [norm_smul, smul_eq_mul, real.norm_eq_abs, abs_of_nonneg to_real_nonneg]
end
end
lemma integral_add_meas {ν} (f : α →ₛ E) (hf : integrable f (μ + ν)) :
f.integral (μ + ν) = f.integral μ + f.integral ν :=
begin
simp only [integral_eq_sum_filter, ← sum_add_distrib, ← add_smul, measure.add_apply],
refine sum_congr rfl (λ x hx, _),
rw [to_real_add];
refine ne_of_lt ((integrable_iff_fin_meas_supp.1 _).meas_preimage_singleton_ne_zero
(mem_filter.1 hx).2),
exacts [hf.left_of_add_meas, hf.right_of_add_meas]
end
variables [second_countable_topology E] [measurable_space E] [borel_space E]
end integral
end simple_func
namespace l1
open ae_eq_fun
variables
[normed_group E] [second_countable_topology E] [measurable_space E] [borel_space E]
[normed_group F] [second_countable_topology F] [measurable_space F] [borel_space F]
{μ : measure α}
variables (α E μ)
-- We use `Type*` instead of `add_subgroup` because otherwise we loose dot notation.
/-- `l1.simple_func` is a subspace of L1 consisting of equivalence classes of an integrable simple
function. -/
def simple_func : Type* :=
↥({ carrier := {f : α →₁[μ] E | ∃ (s : α →ₛ E), (ae_eq_fun.mk s s.measurable : α →ₘ[μ] E) = f},
zero_mem' := ⟨0, rfl⟩,
add_mem' := λ f g ⟨s, hs⟩ ⟨t, ht⟩,
⟨s + t, by simp only [coe_add, ← hs, ← ht, mk_add_mk, ← simple_func.coe_add]⟩,
neg_mem' := λ f ⟨s, hs⟩, ⟨-s, by simp only [coe_neg, ← hs, neg_mk, ← simple_func.coe_neg]⟩ } :
add_subgroup (α →₁[μ] E))
variables {α E μ}
notation α ` →₁ₛ[`:25 μ `] ` E := measure_theory.l1.simple_func α E μ
namespace simple_func
section instances
/-! Simple functions in L1 space form a `normed_space`. -/
instance : has_coe (α →₁ₛ[μ] E) (α →₁[μ] E) := coe_subtype
instance : has_coe_to_fun (α →₁ₛ[μ] E) := ⟨λ f, α → E, λ f, ⇑(f : α →₁[μ] E)⟩
@[simp, norm_cast] lemma coe_coe (f : α →₁ₛ[μ] E) : ⇑(f : α →₁[μ] E) = f := rfl
protected lemma eq {f g : α →₁ₛ[μ] E} : (f : α →₁[μ] E) = (g : α →₁[μ] E) → f = g := subtype.eq
protected lemma eq' {f g : α →₁ₛ[μ] E} : (f : α →ₘ[μ] E) = (g : α →ₘ[μ] E) → f = g := subtype.eq ∘ subtype.eq
@[norm_cast] protected lemma eq_iff {f g : α →₁ₛ[μ] E} : (f : α →₁[μ] E) = g ↔ f = g :=
subtype.ext_iff.symm
@[norm_cast] protected lemma eq_iff' {f g : α →₁ₛ[μ] E} : (f : α →ₘ[μ] E) = g ↔ f = g :=
iff.intro (simple_func.eq') (congr_arg _)
/-- L1 simple functions forms a `emetric_space`, with the emetric being inherited from L1 space,
i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`.
Not declared as an instance as `α →₁ₛ[μ] β` will only be useful in the construction of the bochner
integral. -/
protected def emetric_space : emetric_space (α →₁ₛ[μ] E) := subtype.emetric_space
/-- L1 simple functions forms a `metric_space`, with the metric being inherited from L1 space,
i.e., `dist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a)`).
Not declared as an instance as `α →₁ₛ[μ] β` will only be useful in the construction of the bochner
integral. -/
protected def metric_space : metric_space (α →₁ₛ[μ] E) := subtype.metric_space
local attribute [instance] simple_func.metric_space simple_func.emetric_space
/-- Functions `α →₁ₛ[μ] E` form an additive commutative group. -/
local attribute [instance, priority 10000]
protected def add_comm_group : add_comm_group (α →₁ₛ[μ] E) := add_subgroup.to_add_comm_group _
instance : inhabited (α →₁ₛ[μ] E) := ⟨0⟩
@[simp, norm_cast] lemma coe_zero : ((0 : α →₁ₛ[μ] E) : α →₁[μ] E) = 0 := rfl
@[simp, norm_cast] lemma coe_add (f g : α →₁ₛ[μ] E) : ((f + g : α →₁ₛ[μ] E) : α →₁[μ] E) = f + g := rfl
@[simp, norm_cast] lemma coe_neg (f : α →₁ₛ[μ] E) : ((-f : α →₁ₛ[μ] E) : α →₁[μ] E) = -f := rfl
@[simp, norm_cast] lemma coe_sub (f g : α →₁ₛ[μ] E) : ((f - g : α →₁ₛ[μ] E) : α →₁[μ] E) = f - g := rfl
@[simp] lemma edist_eq (f g : α →₁ₛ[μ] E) : edist f g = edist (f : α →₁[μ] E) (g : α →₁[μ] E) := rfl
@[simp] lemma dist_eq (f g : α →₁ₛ[μ] E) : dist f g = dist (f : α →₁[μ] E) (g : α →₁[μ] E) := rfl
/-- The norm on `α →₁ₛ[μ] E` is inherited from L1 space. That is, `∥f∥ = ∫⁻ a, edist (f a) 0`.
Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the bochner
integral. -/
protected def has_norm : has_norm (α →₁ₛ[μ] E) := ⟨λf, ∥(f : α →₁[μ] E)∥⟩
local attribute [instance] simple_func.has_norm
lemma norm_eq (f : α →₁ₛ[μ] E) : ∥f∥ = ∥(f : α →₁[μ] E)∥ := rfl
lemma norm_eq' (f : α →₁ₛ[μ] E) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ[μ] E) 0) := rfl
/-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the bochner
integral. -/
protected def normed_group : normed_group (α →₁ₛ[μ] E) :=
normed_group.of_add_dist (λ x, rfl) $ by
{ intros, simp only [dist_eq, coe_add, l1.dist_eq, l1.coe_add], rw edist_add_right }
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E]
/-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the bochner
integral. -/
protected def has_scalar : has_scalar 𝕜 (α →₁ₛ[μ] E) := ⟨λk f, ⟨k • f,
begin
rcases f with ⟨f, ⟨s, hs⟩⟩,
use k • s,
rw [coe_smul, subtype.coe_mk, ← hs], refl
end ⟩⟩
local attribute [instance, priority 10000] simple_func.has_scalar
@[simp, norm_cast] lemma coe_smul (c : 𝕜) (f : α →₁ₛ[μ] E) :
((c • f : α →₁ₛ[μ] E) : α →₁[μ] E) = c • (f : α →₁[μ] E) := rfl
/-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the bochner
integral. -/
protected def semimodule : semimodule 𝕜 (α →₁ₛ[μ] E) :=
{ one_smul := λf, simple_func.eq (by { simp only [coe_smul], exact one_smul _ _ }),
mul_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }),
smul_add := λx f g, simple_func.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }),
smul_zero := λx, simple_func.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }),
add_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact add_smul _ _ _ }),
zero_smul := λf, simple_func.eq (by { simp only [coe_smul], exact zero_smul _ _ }) }
local attribute [instance] simple_func.normed_group simple_func.semimodule
/-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the bochner
integral. -/
protected def normed_space : normed_space 𝕜 (α →₁ₛ[μ] E) :=
⟨ λc f, by { rw [norm_eq, norm_eq, coe_smul, norm_smul] } ⟩
end instances
local attribute [instance] simple_func.normed_group simple_func.normed_space
section of_simple_func
/-- Construct the equivalence class `[f]` of an integrable simple function `f`. -/
@[reducible] def of_simple_func (f : α →ₛ E) (hf : integrable f μ) : (α →₁ₛ[μ] E) :=
⟨l1.of_fun f f.measurable hf, ⟨f, rfl⟩⟩
lemma of_simple_func_eq_of_fun (f : α →ₛ E) (hf : integrable f μ) :
(of_simple_func f hf : α →₁[μ] E) = l1.of_fun f f.measurable hf := rfl
lemma of_simple_func_eq_mk (f : α →ₛ E) (hf : integrable f μ) :
(of_simple_func f hf : α →ₘ[μ] E) = ae_eq_fun.mk f f.measurable := rfl
lemma of_simple_func_zero : of_simple_func (0 : α →ₛ E) (integrable_zero α μ E) = 0 := rfl
lemma of_simple_func_add (f g : α →ₛ E) (hf hg) :
(of_simple_func (f + g) (integrable.add f.measurable hf g.measurable hg) : α →₁ₛ[μ] E) =
of_simple_func f hf + of_simple_func g hg := rfl
lemma of_simple_func_neg (f : α →ₛ E) (hf : integrable f μ) :
of_simple_func (-f) hf.neg = -of_simple_func f hf := rfl
lemma of_simple_func_sub (f g : α →ₛ E) (hf : integrable f μ) (hg) :
of_simple_func (f - g) (hf.sub f.measurable g.measurable hg) =
of_simple_func f hf - of_simple_func g hg := rfl
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E]
lemma of_simple_func_smul (f : α →ₛ E) (hf : integrable f μ) (c : 𝕜) :
of_simple_func (c • f) (hf.smul c) = c • of_simple_func f hf := rfl
lemma norm_of_simple_func (f : α →ₛ E) (hf : integrable f μ) :
∥of_simple_func f hf∥ = ennreal.to_real (∫⁻ a, edist (f a) 0 ∂μ) :=
rfl
end of_simple_func
section to_simple_func
/-- Find a representative of a `l1.simple_func`. -/
def to_simple_func (f : α →₁ₛ[μ] E) : α →ₛ E := classical.some f.2
/-- `f.to_simple_func` is measurable. -/
protected lemma measurable (f : α →₁ₛ[μ] E) : measurable f.to_simple_func :=
f.to_simple_func.measurable
/-- `f.to_simple_func` is integrable. -/
protected lemma integrable (f : α →₁ₛ[μ] E) : integrable f.to_simple_func μ :=
let h := classical.some_spec f.2 in (integrable_mk f.measurable).1 $ h.symm ▸ (f : α →₁[μ] E).2
lemma of_simple_func_to_simple_func (f : α →₁ₛ[μ] E) :
of_simple_func (f.to_simple_func) f.integrable = f :=
by { rw ← simple_func.eq_iff', exact classical.some_spec f.2 }
lemma to_simple_func_of_simple_func (f : α →ₛ E) (hfi : integrable f μ) :
(of_simple_func f hfi).to_simple_func =ᵐ[μ] f :=
by { rw ← mk_eq_mk, exact classical.some_spec (of_simple_func f hfi).2 }
lemma to_simple_func_eq_to_fun (f : α →₁ₛ[μ] E) : f.to_simple_func =ᵐ[μ] f :=
begin
rw [← of_fun_eq_of_fun f.to_simple_func f f.measurable f.integrable
(f : α →₁[μ] E).measurable (f : α →₁[μ] E).integrable, ← l1.eq_iff],
simp only [of_fun_eq_mk, ← coe_coe, mk_to_fun],
exact classical.some_spec f.coe_prop
end
variables (α E)
lemma zero_to_simple_func : (0 : α →₁ₛ[μ] E).to_simple_func =ᵐ[μ] 0 :=
begin
filter_upwards [to_simple_func_eq_to_fun (0 : α →₁ₛ[μ] E), l1.zero_to_fun α E],
assume a,
simp only [mem_set_of_eq],
assume h,
rw h,
assume h,
exact h
end
variables {α E}
lemma add_to_simple_func (f g : α →₁ₛ[μ] E) :
(f + g).to_simple_func =ᵐ[μ] f.to_simple_func + g.to_simple_func :=
begin
filter_upwards [to_simple_func_eq_to_fun (f + g), to_simple_func_eq_to_fun f,
to_simple_func_eq_to_fun g, l1.add_to_fun (f : α →₁[μ] E) g],
assume a,
simp only [mem_set_of_eq, ← coe_coe, coe_add, pi.add_apply],
iterate 4 { assume h, rw h }
end
lemma neg_to_simple_func (f : α →₁ₛ[μ] E) : (-f).to_simple_func =ᵐ[μ] - f.to_simple_func :=
begin
filter_upwards [to_simple_func_eq_to_fun (-f), to_simple_func_eq_to_fun f,
l1.neg_to_fun (f : α →₁[μ] E)],
assume a,
simp only [mem_set_of_eq, pi.neg_apply, coe_neg, ← coe_coe],
repeat { assume h, rw h }
end
lemma sub_to_simple_func (f g : α →₁ₛ[μ] E) :
(f - g).to_simple_func =ᵐ[μ] f.to_simple_func - g.to_simple_func :=
begin
filter_upwards [to_simple_func_eq_to_fun (f - g), to_simple_func_eq_to_fun f,
to_simple_func_eq_to_fun g, l1.sub_to_fun (f : α →₁[μ] E) g],
assume a,
simp only [mem_set_of_eq, coe_sub, pi.sub_apply, ← coe_coe],
repeat { assume h, rw h }
end
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E]
lemma smul_to_simple_func (k : 𝕜) (f : α →₁ₛ[μ] E) :
(k • f).to_simple_func =ᵐ[μ] k • f.to_simple_func :=
begin
filter_upwards [to_simple_func_eq_to_fun (k • f), to_simple_func_eq_to_fun f,
l1.smul_to_fun k (f : α →₁[μ] E)],
assume a,
simp only [mem_set_of_eq, pi.smul_apply, coe_smul, ← coe_coe],
repeat { assume h, rw h }
end
lemma lintegral_edist_to_simple_func_lt_top (f g : α →₁ₛ[μ] E) :
∫⁻ (x : α), edist ((to_simple_func f) x) ((to_simple_func g) x) ∂μ < ⊤ :=
begin
rw lintegral_rw₂ (to_simple_func_eq_to_fun f) (to_simple_func_eq_to_fun g),
exact lintegral_edist_to_fun_lt_top _ _
end
lemma dist_to_simple_func (f g : α →₁ₛ[μ] E) : dist f g =
ennreal.to_real (∫⁻ x, edist (f.to_simple_func x) (g.to_simple_func x) ∂μ) :=
begin
rw [dist_eq, l1.dist_to_fun, ennreal.to_real_eq_to_real],
{ rw lintegral_rw₂, repeat { exact ae_eq_symm (to_simple_func_eq_to_fun _) } },
{ exact l1.lintegral_edist_to_fun_lt_top _ _ },
{ exact lintegral_edist_to_simple_func_lt_top _ _ }
end
lemma norm_to_simple_func (f : α →₁ₛ[μ] E) :
∥f∥ = ennreal.to_real (∫⁻ (a : α), nnnorm ((to_simple_func f) a) ∂μ) :=
calc ∥f∥ = ennreal.to_real (∫⁻x, edist (f.to_simple_func x) ((0 : α →₁ₛ[μ] E).to_simple_func x) ∂μ) :
begin
rw [← dist_zero_right, dist_to_simple_func]
end
... = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x) ∂μ) :
begin
rw lintegral_nnnorm_eq_lintegral_edist,
have : ∫⁻ x, edist ((to_simple_func f) x) ((to_simple_func (0 : α →₁ₛ[μ] E)) x) ∂μ =
∫⁻ x, edist ((to_simple_func f) x) 0 ∂μ,
{ refine lintegral_congr_ae ((zero_to_simple_func α E).mono (λ a h, _)),
rw [h, pi.zero_apply] },
rw [ennreal.to_real_eq_to_real],
{ exact this },
{ exact lintegral_edist_to_simple_func_lt_top _ _ },
{ rw ← this, exact lintegral_edist_to_simple_func_lt_top _ _ }
end
lemma norm_eq_integral (f : α →₁ₛ[μ] E) : ∥f∥ = (f.to_simple_func.map norm).integral μ :=
-- calc ∥f∥ = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x) ∂μ) :
-- by { rw norm_to_simple_func }
-- ... = (f.to_simple_func.map norm).integral μ :
begin
rw [norm_to_simple_func, simple_func.integral_eq_lintegral],
{ simp only [simple_func.map_apply, of_real_norm_eq_coe_nnnorm] },
{ exact f.integrable.norm },
{ exact eventually_of_forall (λ x, norm_nonneg _) }
end
end to_simple_func
section coe_to_l1
protected lemma uniform_continuous : uniform_continuous (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) :=
uniform_continuous_comap
protected lemma uniform_embedding : uniform_embedding (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) :=
uniform_embedding_comap subtype.val_injective
protected lemma uniform_inducing : uniform_inducing (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) :=
simple_func.uniform_embedding.to_uniform_inducing
protected lemma dense_embedding : dense_embedding (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) :=
begin
apply simple_func.uniform_embedding.dense_embedding,
rintros ⟨⟨f, hfm⟩, hfi⟩,
rw mem_closure_iff_seq_limit,
rcases simple_func_sequence_tendsto' hfm ((integrable_mk hfm).1 hfi) with ⟨F, hF⟩,
refine ⟨λ n, ↑(of_simple_func (F n) (hF.1 n)), λ n, mem_range_self _, _⟩,
rw tendsto_iff_edist_tendsto_0,
simpa [edist_mk_mk, ← edist_nndist] using hF.2
end
protected lemma dense_inducing : dense_inducing (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) :=
simple_func.dense_embedding.to_dense_inducing
protected lemma dense_range : dense_range (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) :=
simple_func.dense_inducing.dense
variables (𝕜 : Type*) [normed_field 𝕜] [normed_space 𝕜 E]
variables (α E)
/-- The uniform and dense embedding of L1 simple functions into L1 functions. -/
def coe_to_l1 : (α →₁ₛ[μ] E) →L[𝕜] (α →₁[μ] E) :=
{ to_fun := (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)),
map_add' := λf g, rfl,
map_smul' := λk f, rfl,
cont := l1.simple_func.uniform_continuous.continuous, }
variables {α E 𝕜}
end coe_to_l1
section pos_part
/-- Positive part of a simple function in L1 space. -/
def pos_part (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := ⟨l1.pos_part (f : α →₁[μ] ℝ),
begin
rcases f with ⟨f, s, hsf⟩,
use s.pos_part,
simp only [subtype.coe_mk, l1.coe_pos_part, ← hsf, ae_eq_fun.pos_part_mk, simple_func.pos_part,
simple_func.coe_map]
end ⟩
/-- Negative part of a simple function in L1 space. -/
def neg_part (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := pos_part (-f)
@[norm_cast] lemma coe_pos_part (f : α →₁ₛ[μ] ℝ) : (f.pos_part : α →₁[μ] ℝ) = (f : α →₁[μ] ℝ).pos_part := rfl
@[norm_cast] lemma coe_neg_part (f : α →₁ₛ[μ] ℝ) : (f.neg_part : α →₁[μ] ℝ) = (f : α →₁[μ] ℝ).neg_part := rfl
end pos_part
section simple_func_integral
/-! Define the Bochner integral on `α →₁ₛ[μ] E` and prove basic properties of this integral. -/
variables [normed_space ℝ E]
/-- The Bochner integral over simple functions in l1 space. -/
def integral (f : α →₁ₛ[μ] E) : E := (f.to_simple_func).integral μ
lemma integral_eq_integral (f : α →₁ₛ[μ] E) : integral f = (f.to_simple_func).integral μ := rfl
lemma integral_eq_lintegral {f : α →₁ₛ[μ] ℝ} (h_pos : 0 ≤ᵐ[μ] f.to_simple_func) :
integral f = ennreal.to_real (∫⁻ a, ennreal.of_real (f.to_simple_func a) ∂μ) :=
by rw [integral, simple_func.integral_eq_lintegral f.integrable h_pos]
lemma integral_congr {f g : α →₁ₛ[μ] E} (h : f.to_simple_func =ᵐ[μ] g.to_simple_func) :
integral f = integral g :=
simple_func.integral_congr f.integrable h
lemma integral_add (f g : α →₁ₛ[μ] E) : integral (f + g) = integral f + integral g :=
begin
simp only [integral],
rw ← simple_func.integral_add f.integrable g.integrable,
apply measure_theory.simple_func.integral_congr (f + g).integrable,
apply add_to_simple_func
end
lemma integral_smul (r : ℝ) (f : α →₁ₛ[μ] E) : integral (r • f) = r • integral f :=
begin
simp only [integral],
rw ← simple_func.integral_smul _ f.integrable,
apply measure_theory.simple_func.integral_congr (r • f).integrable,
apply smul_to_simple_func
end
lemma norm_integral_le_norm (f : α →₁ₛ[μ] E) : ∥ integral f ∥ ≤ ∥f∥ :=
begin
rw [integral, norm_eq_integral],
exact f.to_simple_func.norm_integral_le_integral_norm f.integrable
end
/-- The Bochner integral over simple functions in l1 space as a continuous linear map. -/
def integral_clm : (α →₁ₛ[μ] E) →L[ℝ] E :=
linear_map.mk_continuous ⟨integral, integral_add, integral_smul⟩
1 (λf, le_trans (norm_integral_le_norm _) $ by rw one_mul)
local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _
open continuous_linear_map
lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 :=
linear_map.mk_continuous_norm_le _ (zero_le_one) _
section pos_part
lemma pos_part_to_simple_func (f : α →₁ₛ[μ] ℝ) :
f.pos_part.to_simple_func =ᵐ[μ] f.to_simple_func.pos_part :=
begin
have eq : ∀ a, f.to_simple_func.pos_part a = max (f.to_simple_func a) 0 := λa, rfl,
have ae_eq : ∀ᵐ a ∂μ, f.pos_part.to_simple_func a = max (f.to_simple_func a) 0,
{ filter_upwards [to_simple_func_eq_to_fun f.pos_part, pos_part_to_fun (f : α →₁[μ] ℝ),
to_simple_func_eq_to_fun f],
simp only [mem_set_of_eq],
assume a h₁ h₂ h₃,
rw [h₁, ← coe_coe, coe_pos_part, h₂, coe_coe, ← h₃] },
refine ae_eq.mono (assume a h, _),
rw [h, eq]
end
lemma neg_part_to_simple_func (f : α →₁ₛ[μ] ℝ) :
f.neg_part.to_simple_func =ᵐ[μ] f.to_simple_func.neg_part :=
begin
rw [simple_func.neg_part, measure_theory.simple_func.neg_part],
filter_upwards [pos_part_to_simple_func (-f), neg_to_simple_func f],
simp only [mem_set_of_eq],
assume a h₁ h₂,
rw h₁,
show max _ _ = max _ _,
rw h₂,
refl
end
lemma integral_eq_norm_pos_part_sub (f : α →₁ₛ[μ] ℝ) : f.integral = ∥f.pos_part∥ - ∥f.neg_part∥ :=
begin
-- Convert things in `L¹` to their `simple_func` counterpart
have ae_eq₁ : f.to_simple_func.pos_part =ᵐ[μ] (f.pos_part).to_simple_func.map norm,
{ filter_upwards [pos_part_to_simple_func f],
simp only [mem_set_of_eq],
assume a h,
rw [simple_func.map_apply, h],
conv_lhs { rw [← simple_func.pos_part_map_norm, simple_func.map_apply] } },
-- Convert things in `L¹` to their `simple_func` counterpart
have ae_eq₂ : f.to_simple_func.neg_part =ᵐ[μ] (f.neg_part).to_simple_func.map norm,
{ filter_upwards [neg_part_to_simple_func f],
simp only [mem_set_of_eq],
assume a h,
rw [simple_func.map_apply, h],
conv_lhs { rw [← simple_func.neg_part_map_norm, simple_func.map_apply] } },
-- Convert things in `L¹` to their `simple_func` counterpart
have ae_eq : ∀ᵐ a ∂μ, f.to_simple_func.pos_part a - f.to_simple_func.neg_part a =
(f.pos_part).to_simple_func.map norm a - (f.neg_part).to_simple_func.map norm a,
{ filter_upwards [ae_eq₁, ae_eq₂],
simp only [mem_set_of_eq],
assume a h₁ h₂,
rw [h₁, h₂] },
rw [integral, norm_eq_integral, norm_eq_integral, ← simple_func.integral_sub],
{ show f.to_simple_func.integral μ =
((f.pos_part.to_simple_func).map norm - f.neg_part.to_simple_func.map norm).integral μ,
apply measure_theory.simple_func.integral_congr f.integrable,
filter_upwards [ae_eq₁, ae_eq₂],
simp only [mem_set_of_eq],
assume a h₁ h₂, show _ = _ - _,
rw [← h₁, ← h₂],
have := f.to_simple_func.pos_part_sub_neg_part,
conv_lhs {rw ← this},
refl },
{ exact (integrable.max_zero f.integrable).congr ae_eq₁ },
{ exact (integrable.max_zero f.integrable.neg).congr ae_eq₂ }
end
end pos_part
end simple_func_integral
end simple_func
open simple_func
variables [normed_space ℝ E] [normed_space ℝ F] [complete_space E]
section integration_in_l1
local notation `to_l1` := coe_to_l1 α E ℝ
local attribute [instance] simple_func.normed_group simple_func.normed_space
open continuous_linear_map
/-- The Bochner integral in l1 space as a continuous linear map. -/
def integral_clm : (α →₁[μ] E) →L[ℝ] E :=
integral_clm.extend to_l1 simple_func.dense_range simple_func.uniform_inducing
/-- The Bochner integral in l1 space -/
def integral (f : α →₁[μ] E) : E := integral_clm f
lemma integral_eq (f : α →₁[μ] E) : integral f = integral_clm f := rfl
@[norm_cast] lemma simple_func.integral_l1_eq_integral (f : α →₁ₛ[μ] E) :
integral (f : α →₁[μ] E) = f.integral :=
uniformly_extend_of_ind simple_func.uniform_inducing simple_func.dense_range
simple_func.integral_clm.uniform_continuous _
variables (α E)
@[simp] lemma integral_zero : integral (0 : α →₁[μ] E) = 0 :=
map_zero integral_clm
variables {α E}
lemma integral_add (f g : α →₁[μ] E) : integral (f + g) = integral f + integral g :=
map_add integral_clm f g
lemma integral_neg (f : α →₁[μ] E) : integral (-f) = - integral f :=
map_neg integral_clm f
lemma integral_sub (f g : α →₁[μ] E) : integral (f - g) = integral f - integral g :=
map_sub integral_clm f g
lemma integral_smul (r : ℝ) (f : α →₁[μ] E) : integral (r • f) = r • integral f :=
map_smul r integral_clm f
local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _ _
local notation `sIntegral` := @simple_func.integral_clm α E _ _ _ _ _ μ _
lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 :=
calc ∥Integral∥ ≤ (1 : nnreal) * ∥sIntegral∥ :
op_norm_extend_le _ _ _ $ λs, by {rw [nnreal.coe_one, one_mul], refl}
... = ∥sIntegral∥ : one_mul _
... ≤ 1 : norm_Integral_le_one
lemma norm_integral_le (f : α →₁[μ] E) : ∥integral f∥ ≤ ∥f∥ :=
calc ∥integral f∥ = ∥Integral f∥ : rfl
... ≤ ∥Integral∥ * ∥f∥ : le_op_norm _ _
... ≤ 1 * ∥f∥ : mul_le_mul_of_nonneg_right norm_Integral_le_one $ norm_nonneg _
... = ∥f∥ : one_mul _
section pos_part
lemma integral_eq_norm_pos_part_sub (f : α →₁[μ] ℝ) : integral f = ∥pos_part f∥ - ∥neg_part f∥ :=
begin
-- Use `is_closed_property` and `is_closed_eq`
refine @is_closed_property _ _ _ (coe : (α →₁ₛ[μ] ℝ) → (α →₁[μ] ℝ))
(λ f : α →₁[μ] ℝ, integral f = ∥pos_part f∥ - ∥neg_part f∥)
l1.simple_func.dense_range (is_closed_eq _ _) _ f,
{ exact cont _ },
{ refine continuous.sub (continuous_norm.comp l1.continuous_pos_part)
(continuous_norm.comp l1.continuous_neg_part) },
-- Show that the property holds for all simple functions in the `L¹` space.
{ assume s,
norm_cast,
rw [← simple_func.norm_eq, ← simple_func.norm_eq],
exact simple_func.integral_eq_norm_pos_part_sub _}
end
end pos_part
end integration_in_l1
end l1
variables [normed_group E] [second_countable_topology E] [normed_space ℝ E] [complete_space E]
[measurable_space E] [borel_space E]
[normed_group F] [second_countable_topology F] [normed_space ℝ F] [complete_space F]
[measurable_space F] [borel_space F]
/-- The Bochner integral -/
def integral (μ : measure α) (f : α → E) : E :=
if hf : measurable f ∧ integrable f μ
then (l1.of_fun f hf.1 hf.2).integral
else 0
notation `∫` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := integral μ r
notation `∫` binders `, ` r:(scoped:60 f, integral volume f) := r
notation `∫` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := integral (measure.restrict μ s) r
notation `∫` binders ` in ` s `, ` r:(scoped:60 f, integral (measure.restrict volume s) f) := r
section properties
open continuous_linear_map measure_theory.simple_func
variables {f g : α → E} {μ : measure α}
lemma integral_eq (f : α → E) (h₁ : measurable f) (h₂ : integrable f μ) :
∫ a, f a ∂μ = (l1.of_fun f h₁ h₂).integral :=
dif_pos ⟨h₁, h₂⟩
lemma integral_undef (h : ¬ (measurable f ∧ integrable f μ)) : ∫ a, f a ∂μ = 0 :=
dif_neg h
lemma integral_non_integrable (h : ¬ integrable f μ) : ∫ a, f a ∂μ = 0 :=
integral_undef $ not_and_of_not_right _ h
lemma integral_non_measurable (h : ¬ measurable f) : ∫ a, f a ∂μ = 0 :=
integral_undef $ not_and_of_not_left _ h
variables (α E)
local attribute [simp] -- Follows from `integral_const` below
lemma integral_zero : ∫ a : α, (0:E) ∂μ = 0 :=
by rw [integral_eq, l1.of_fun_zero, l1.integral_zero]
variables {α E}
lemma integral_add
(hfm : measurable f) (hfi : integrable f μ) (hgm : measurable g) (hgi : integrable g μ) :
∫ a, f a + g a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ :=
by rw [integral_eq, integral_eq f hfm hfi, integral_eq g hgm hgi, ← l1.integral_add,
← l1.of_fun_add]; refl
lemma integral_neg (f : α → E) : ∫ a, -f a ∂μ = - ∫ a, f a ∂μ :=
begin
by_cases hf : measurable f ∧ integrable f μ,
{ rw [integral_eq f hf.1 hf.2, integral_eq (λa, - f a) hf.1.neg hf.2.neg,
← l1.integral_neg, ← l1.of_fun_neg], refl },
{ rw [integral_undef hf, integral_undef, neg_zero],
exact mt (and.imp measurable.of_neg integrable_neg_iff.1) hf }
end
lemma integral_sub
(hfm : measurable f) (hfi : integrable f μ) (hgm : measurable g) (hgi : integrable g μ) :
∫ a, f a - g a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ :=
by { rw [sub_eq_add_neg, ← integral_neg], exact integral_add hfm hfi hgm.neg hgi.neg }
lemma integral_smul (r : ℝ) (f : α → E) : ∫ a, r • (f a) ∂μ = r • ∫ a, f a ∂μ :=
begin
by_cases hf : measurable f ∧ integrable f μ,
{ rw [integral_eq f hf.1 hf.2, integral_eq (λa, r • (f a)), l1.of_fun_smul, l1.integral_smul] },
{ by_cases hr : r = 0,
{ simp only [hr, measure_theory.integral_zero, zero_smul] },
have hf' : ¬(measurable (λa, r • f a) ∧ integrable (r • f) μ),
{ rwa [measurable_const_smul_iff hr, integrable_smul_iff hr f]; apply_instance },
rw [integral_undef hf, integral_undef hf', smul_zero] }
end
lemma integral_mul_left (r : ℝ) (f : α → ℝ) : ∫ a, r * (f a) ∂μ = r * ∫ a, f a ∂μ :=
integral_smul r f
lemma integral_mul_right (r : ℝ) (f : α → ℝ) : ∫ a, (f a) * r ∂μ = ∫ a, f a ∂μ * r :=
by { simp only [mul_comm], exact integral_mul_left r f }
lemma integral_div (r : ℝ) (f : α → ℝ) : ∫ a, (f a) / r ∂μ = ∫ a, f a ∂μ / r :=
integral_mul_right r⁻¹ f
lemma integral_congr_ae (hfm : measurable f) (hgm : measurable g) (h : f =ᵐ[μ] g) :
∫ a, f a ∂μ = ∫ a, g a ∂μ :=
begin
by_cases hfi : integrable f μ,
{ have hgi : integrable g μ := hfi.congr h,
rw [integral_eq f hfm hfi, integral_eq g hgm hgi, (l1.of_fun_eq_of_fun f g hfm hfi hgm hgi).2 h] },
{ have hgi : ¬ integrable g μ, { rw integrable_congr h at hfi, exact hfi },
rw [integral_non_integrable hfi, integral_non_integrable hgi] },
end
lemma norm_integral_le_lintegral_norm (f : α → E) :
∥∫ a, f a ∂μ∥ ≤ ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) :=
begin
by_cases hf : measurable f ∧ integrable f μ,
{ rw [integral_eq f hf.1 hf.2, ← l1.norm_of_fun_eq_lintegral_norm f hf.1 hf.2],
exact l1.norm_integral_le _ },
{ rw [integral_undef hf, _root_.norm_zero],
exact to_real_nonneg }
end
/-- If `F i → f` in `L1`, then `∫ x, F i x ∂μ → ∫ x, f x∂μ`. -/
lemma tendsto_integral_of_l1 {ι} (f : α → E) (hfm : measurable f) (hfi : integrable f μ)
{F : ι → α → E} {l : filter ι} (hFm : ∀ᶠ i in l, measurable (F i))
(hFi : ∀ᶠ i in l, integrable (F i) μ)
(hF : tendsto (λ i, ∫⁻ x, edist (F i x) (f x) ∂μ) l (𝓝 0)) :
tendsto (λ i, ∫ x, F i x ∂μ) l (𝓝 $ ∫ x, f x ∂μ) :=
begin
rw [tendsto_iff_norm_tendsto_zero],
replace hF : tendsto (λ i, ennreal.to_real $ ∫⁻ x, edist (F i x) (f x) ∂μ) l (𝓝 0) :=
(ennreal.tendsto_to_real zero_ne_top).comp hF,
refine squeeze_zero_norm' (hFm.mp $ hFi.mono $ λ i hFi hFm, _) hF,
simp only [norm_norm, ← integral_sub hFm hFi hfm hfi, edist_dist, dist_eq_norm],
apply norm_integral_le_lintegral_norm
end
/-- Lebesgue dominated convergence theorem provides sufficient conditions under which almost
everywhere convergence of a sequence of functions implies the convergence of their integrals. -/
theorem tendsto_integral_of_dominated_convergence {F : ℕ → α → E} {f : α → E} (bound : α → ℝ)
(F_measurable : ∀ n, measurable (F n))
(f_measurable : measurable f)
(bound_integrable : integrable bound μ)
(h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
tendsto (λn, ∫ a, F n a ∂μ) at_top (𝓝 $ ∫ a, f a ∂μ) :=
begin
/- To show `(∫ a, F n a) --> (∫ f)`, suffices to show `∥∫ a, F n a - ∫ f∥ --> 0` -/
rw tendsto_iff_norm_tendsto_zero,
/- But `0 ≤ ∥∫ a, F n a - ∫ f∥ = ∥∫ a, (F n a - f a) ∥ ≤ ∫ a, ∥F n a - f a∥, and thus we apply the
sandwich theorem and prove that `∫ a, ∥F n a - f a∥ --> 0` -/
have lintegral_norm_tendsto_zero :
tendsto (λn, ennreal.to_real $ ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 0) :=
(tendsto_to_real zero_ne_top).comp
(tendsto_lintegral_norm_of_dominated_convergence
F_measurable f_measurable bound_integrable h_bound h_lim),
-- Use the sandwich theorem
refine squeeze_zero (λ n, norm_nonneg _) _ lintegral_norm_tendsto_zero,
-- Show `∥∫ a, F n a - ∫ f∥ ≤ ∫ a, ∥F n a - f a∥` for all `n`
{ assume n,
have h₁ : integrable (F n) μ := integrable_of_integrable_bound bound_integrable (h_bound _),
have h₂ : integrable f μ := integrable_of_dominated_convergence bound_integrable h_bound h_lim,
rw ← integral_sub (F_measurable _) h₁ f_measurable h₂,
exact norm_integral_le_lintegral_norm _ }
end
/-- Lebesgue dominated convergence theorem for filters with a countable basis -/
lemma tendsto_integral_filter_of_dominated_convergence {ι} {l : filter ι}
{F : ι → α → E} {f : α → E} (bound : α → ℝ)
(hl_cb : l.is_countably_generated)
(hF_meas : ∀ᶠ n in l, measurable (F n))
(f_measurable : measurable f)
(h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a)
(bound_integrable : integrable bound μ)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) :
tendsto (λn, ∫ a, F n a ∂μ) l (𝓝 $ ∫ a, f a ∂μ) :=
begin
rw hl_cb.tendsto_iff_seq_tendsto,
{ intros x xl,
have hxl, { rw tendsto_at_top' at xl, exact xl },
have h := inter_mem_sets hF_meas h_bound,
replace h := hxl _ h,
rcases h with ⟨k, h⟩,
rw ← tendsto_add_at_top_iff_nat k,
refine tendsto_integral_of_dominated_convergence _ _ _ _ _ _,
{ exact bound },
{ intro, refine (h _ _).1, exact nat.le_add_left _ _ },
{ assumption },
{ assumption },
{ intro, refine (h _ _).2, exact nat.le_add_left _ _ },
{ filter_upwards [h_lim],
simp only [mem_set_of_eq],
assume a h_lim,
apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a),
{ assumption },
rw tendsto_add_at_top_iff_nat,
assumption } },
end
/-- The Bochner integral of a real-valued function `f : α → ℝ` is the difference between the
integral of the positive part of `f` and the integral of the negative part of `f`. -/
lemma integral_eq_lintegral_max_sub_lintegral_min {f : α → ℝ}
(hfm : measurable f) (hfi : integrable f μ) : ∫ a, f a ∂μ =
ennreal.to_real (∫⁻ a, (ennreal.of_real $ max (f a) 0) ∂μ) -
ennreal.to_real (∫⁻ a, (ennreal.of_real $ - min (f a) 0) ∂μ) :=
let f₁ : α →₁[μ] ℝ := l1.of_fun f hfm hfi in
-- Go to the `L¹` space
have eq₁ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ max (f a) 0) ∂μ) = ∥l1.pos_part f₁∥ :=
begin
rw l1.norm_eq_norm_to_fun,
congr' 1,
apply lintegral_congr_ae,
filter_upwards [l1.pos_part_to_fun f₁, l1.to_fun_of_fun f hfm hfi],
simp only [mem_set_of_eq],
assume a h₁ h₂,
rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg],
exact le_max_right _ _
end,
-- Go to the `L¹` space
have eq₂ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ -min (f a) 0) ∂μ) = ∥l1.neg_part f₁∥ :=
begin
rw l1.norm_eq_norm_to_fun,
congr' 1,
apply lintegral_congr_ae,
filter_upwards [l1.neg_part_to_fun_eq_min f₁, l1.to_fun_of_fun f hfm hfi],
simp only [mem_set_of_eq],
assume a h₁ h₂,
rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg],
rw [min_eq_neg_max_neg_neg, _root_.neg_neg, neg_zero],
exact le_max_right _ _
end,
begin
rw [eq₁, eq₂, integral, dif_pos],
exact l1.integral_eq_norm_pos_part_sub _,
{ exact ⟨hfm, hfi⟩ }
end
lemma integral_eq_lintegral_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfm : measurable f) :
∫ a, f a ∂μ = ennreal.to_real (∫⁻ a, (ennreal.of_real $ f a) ∂μ) :=
begin
by_cases hfi : integrable f μ,
{ rw integral_eq_lintegral_max_sub_lintegral_min hfm hfi,
have h_min : ∫⁻ a, ennreal.of_real (-min (f a) 0) ∂μ = 0,
{ rw lintegral_eq_zero_iff,
{ refine hf.mono _,
simp only [pi.zero_apply],
assume a h,
simp only [min_eq_right h, neg_zero, ennreal.of_real_zero] },
{ refine measurable_of_real.comp
((measurable.neg measurable_id).comp $ measurable.min hfm measurable_const) } },
have h_max : ∫⁻ a, ennreal.of_real (max (f a) 0) ∂μ = ∫⁻ a, ennreal.of_real (f a) ∂μ,
{ refine lintegral_congr_ae (hf.mono (λ a h, _)),
rw [pi.zero_apply] at h,
rw max_eq_left h },
rw [h_min, h_max, zero_to_real, _root_.sub_zero] },
{ rw integral_non_integrable hfi,
rw [integrable_iff_norm, lt_top_iff_ne_top, ne.def, not_not] at hfi,
have : ∫⁻ (a : α), ennreal.of_real (f a) ∂μ = ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ,
{ apply lintegral_congr_ae,
filter_upwards [hf],
simp only [mem_set_of_eq],
assume a h,
rw [real.norm_eq_abs, abs_of_nonneg h] },
rw [this, hfi], refl }
end
lemma integral_nonneg_of_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ a, f a ∂μ :=
begin
by_cases hfm : measurable f,
{ rw integral_eq_lintegral_of_nonneg_ae hf hfm, exact to_real_nonneg },
{ rw integral_non_measurable hfm }
end
lemma integral_nonpos_of_nonpos_ae {f : α → ℝ} (hf : f ≤ᵐ[μ] 0) : ∫ a, f a ∂μ ≤ 0 :=
begin
have hf : 0 ≤ᵐ[μ] (-f) := hf.mono (assume a h, by rwa [pi.neg_apply, pi.zero_apply, neg_nonneg]),
have : 0 ≤ ∫ a, -f a ∂μ := integral_nonneg_of_ae hf,
rwa [integral_neg, neg_nonneg] at this,
end
lemma integral_mono {f g : α → ℝ} (hfm : measurable f) (hfi : integrable f μ)
(hgm : measurable g) (hgi : integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ :=
le_of_sub_nonneg $ integral_sub hgm hgi hfm hfi ▸
integral_nonneg_of_ae $ h.mono (λ a, sub_nonneg_of_le)
lemma norm_integral_le_integral_norm (f : α → E) : ∥(∫ a, f a ∂μ)∥ ≤ ∫ a, ∥f a∥ ∂μ :=
have le_ae : ∀ᵐ a ∂μ, 0 ≤ ∥f a∥ := eventually_of_forall (λa, norm_nonneg _),
classical.by_cases
( λh : measurable f,
calc ∥∫ a, f a ∂μ∥ ≤ ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) : norm_integral_le_lintegral_norm _
... = ∫ a, ∥f a∥ ∂μ : (integral_eq_lintegral_of_nonneg_ae le_ae $ measurable.norm h).symm )
( λh : ¬measurable f,
begin
rw [integral_non_measurable h, _root_.norm_zero],
exact integral_nonneg_of_ae le_ae
end )
lemma integral_finset_sum {ι} (s : finset ι) {f : ι → α → E}
(hfm : ∀ i, measurable (f i)) (hfi : ∀ i, integrable (f i) μ) :
∫ a, ∑ i in s, f i a ∂μ = ∑ i in s, ∫ a, f i a ∂μ :=
begin
refine finset.induction_on s _ _,
{ simp only [integral_zero, finset.sum_empty] },
{ assume i s his ih,
simp only [his, finset.sum_insert, not_false_iff],
rw [integral_add (hfm _) (hfi _) (s.measurable_sum hfm)
(integrable_finset_sum s hfm hfi), ih] }
end
lemma simple_func.integral_eq_integral (f : α →ₛ E) (hfi : integrable f μ) :
f.integral μ = ∫ x, f x ∂μ :=
begin
rw [integral_eq f f.measurable hfi, ← l1.simple_func.of_simple_func_eq_of_fun,
l1.simple_func.integral_l1_eq_integral, l1.simple_func.integral_eq_integral],
exact simple_func.integral_congr hfi (l1.simple_func.to_simple_func_of_simple_func _ _).symm
end
@[simp] lemma integral_const (c : E) : ∫ x : α, c ∂μ = (μ univ).to_real • c :=
begin
by_cases hμ : μ univ < ⊤,
{ have : integrable (simple_func.const α c) μ := integrable_const.2 (or.inr hμ),
calc ∫ x : α, c ∂μ = (simple_func.const α c).integral μ :
((simple_func.const α c).integral_eq_integral this).symm
... = _ : _,
rw [simple_func.integral],
by_cases ha : nonempty α,
{ resetI, simp [preimage_const_of_mem] },
{ simp [μ.eq_zero_of_not_nonempty ha] } },
{ by_cases hc : c = 0,
{ simp [hc] },
{ have : ¬integrable (λ x : α, c) μ,
{ simp only [integrable_const, not_or_distrib],
exact ⟨hc, hμ⟩ },
simp only [not_lt, top_le_iff] at hμ,
simp [integral_non_integrable, *] } }
end
variable {ν : measure α}
lemma integral_add_meas {f : α → E} (hfm : measurable f) (hfi : integrable f (μ + ν)) :
∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν :=
begin
rcases simple_func_sequence_tendsto' hfm hfi with ⟨F, hFi, hFt⟩,
have hFiμ : ∀ i, integrable (F i) μ := λ i, (hFi i).left_of_add_meas,
have hFiν : ∀ i, integrable (F i) ν := λ i, (hFi i).right_of_add_meas,
simp only [← edist_nndist] at hFt,
have hμν : tendsto (λ i, ∫ x, F i x ∂(μ + ν)) at_top (𝓝 ∫ x, f x ∂(μ + ν)) :=
tendsto_integral_of_l1 _ hfm hfi (eventually_of_forall $ λ i, (F i).measurable)
(eventually_of_forall hFi) hFt,
have hμ : tendsto (λ i, ∫ x, F i x ∂μ) at_top (𝓝 ∫ x, f x ∂μ),
{ refine tendsto_integral_of_l1 _ hfm hfi.left_of_add_meas
(eventually_of_forall $ λ i, (F i).measurable) (eventually_of_forall hFiμ) _,
refine tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds hFt (λ _, zero_le _) _,
exact λ i, lintegral_mono' (measure.le_add_right $ le_refl μ) (le_refl _) },
have hν : tendsto (λ i, ∫ x, F i x ∂ν) at_top (𝓝 ∫ x, f x ∂ν),
{ refine tendsto_integral_of_l1 _ hfm hfi.right_of_add_meas
(eventually_of_forall $ λ i, (F i).measurable) (eventually_of_forall hFiν) _,
refine tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds hFt (λ _, zero_le _) _,
exact λ i, lintegral_mono' (measure.le_add_left $ le_refl ν) (le_refl _) },
apply tendsto_nhds_unique hμν,
simpa only [← simple_func.integral_eq_integral, *, simple_func.integral_add_meas] using hμ.add hν
end
end properties
mk_simp_attribute integral_simps "Simp set for integral rules."
attribute [integral_simps] integral_neg integral_smul l1.integral_add l1.integral_sub
l1.integral_smul l1.integral_neg
attribute [irreducible] integral l1.integral
end measure_theory
|
1c20cc65bcd168e16bef56b5bc68bdf61171ec9a | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/let3.lean | 1987d9cd5088cd6c2aac1a97c6c016c49acaa717 | [
"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 | 750 | lean |
definition p1 := (10, 20, 30)
definition v1 : nat :=
let (a, b, c) := p1 in
a + b + c
definition v2 : nat :=
let ⟨a, b, c⟩ := p1 in
a + b + c
example : v2 = 60 :=
rfl
/-
let with patterns is just syntax sugar for the match convoy pattern.
let (a, b, c) := p1 in
a + b + c
is encoded as
match p1 with
(a, b, c) := a + b + c
end
One limitation is that the expexted type of the let-expression must be known.
TODO(Leo): improve visit_convoy in the elaborator, and remove this restriction.
-/
vm_eval
(let (a, b, c) := p1 in a + b : nat) -- We have to provide the type.
vm_eval
(let (a, b) := p1,
(c, d) := b
in c + d : nat)
definition v3 : nat :=
let (a, b) := p1,
(c, d) := b
in c + d
example : v3 = 50 :=
rfl
|
8396792a7551d20005c842123409cf6805812848 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/natural_transformation_auto.lean | 73c10a7cda71b799d0f684c67fba605e43854459 | [] | 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 | 3,626 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn
Defines natural transformations between functors.
Introduces notations
`τ.app X` for the components of natural transformations,
`F ⟶ G` for the type of natural transformations between functors `F` and `G`,
`σ ≫ τ` for vertical compositions, and
`σ ◫ τ` for horizontal compositions.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.functor
import Mathlib.PostPort
universes v₁ v₂ u₁ u₂ l
namespace Mathlib
namespace category_theory
/--
`nat_trans F G` represents a natural transformation between functors `F` and `G`.
The field `app` provides the components of the natural transformation.
Naturality is expressed by `α.naturality_lemma`.
-/
structure nat_trans {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) (G : C ⥤ D)
where
app : (X : C) → functor.obj F X ⟶ functor.obj G X
naturality' :
autoParam (∀ {X Y : C} (f : X ⟶ Y), functor.map F f ≫ app Y = app X ≫ functor.map G f)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
-- Rather arbitrarily, we say that the 'simpler' form is
@[simp] theorem nat_trans.naturality {C : Type u₁} [category C] {D : Type u₂} [category D]
{F : C ⥤ D} {G : C ⥤ D} (c : nat_trans F G) {X : C} {Y : C} (f : X ⟶ Y) :
functor.map F f ≫ nat_trans.app c Y = nat_trans.app c X ≫ functor.map G f :=
sorry
-- components of natural transfomations moving earlier.
@[simp] theorem nat_trans.naturality_assoc {C : Type u₁} [category C] {D : Type u₂} [category D]
{F : C ⥤ D} {G : C ⥤ D} (c : nat_trans F G) {X : C} {Y : C} (f : X ⟶ Y) {X' : D}
(f' : functor.obj G Y ⟶ X') :
functor.map F f ≫ nat_trans.app c Y ≫ f' = nat_trans.app c X ≫ functor.map G f ≫ f' :=
sorry
theorem congr_app {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : C ⥤ D}
{α : nat_trans F G} {β : nat_trans F G} (h : α = β) (X : C) :
nat_trans.app α X = nat_trans.app β X :=
congr_fun (congr_arg nat_trans.app h) X
namespace nat_trans
/-- `nat_trans.id F` is the identity natural transformation on a functor `F`. -/
protected def id {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) :
nat_trans F F :=
mk fun (X : C) => 𝟙
@[simp] theorem id_app' {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) (X : C) :
app (nat_trans.id F) X = 𝟙 :=
rfl
protected instance inhabited {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) :
Inhabited (nat_trans F F) :=
{ default := nat_trans.id F }
/-- `vcomp α β` is the vertical compositions of natural transformations. -/
def vcomp {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : C ⥤ D} {H : C ⥤ D}
(α : nat_trans F G) (β : nat_trans G H) : nat_trans F H :=
mk fun (X : C) => app α X ≫ app β X
-- functor_category will rewrite (vcomp α β) to (α ≫ β), so this is not a
-- suitable simp lemma. We will declare the variant vcomp_app' there.
theorem vcomp_app {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : C ⥤ D}
{H : C ⥤ D} (α : nat_trans F G) (β : nat_trans G H) (X : C) :
app (vcomp α β) X = app α X ≫ app β X :=
rfl
end Mathlib |
bec6fbddaf29f81102f9bfb4968cf3ce377e71d2 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/seq/computation_auto.lean | e4e6c340a8d7f15aee80cafb4349021d66cfaef5 | [] | 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 | 35,223 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Coinductive formalization of unbounded computations.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.Lean3Lib.data.stream
import Mathlib.tactic.basic
import Mathlib.PostPort
universes u u_1 v w
namespace Mathlib
/-
coinductive computation (α : Type u) : Type u
| return : α → computation α
| think : computation α → computation α
-/
/-- `computation α` is the type of unbounded computations returning `α`.
An element of `computation α` is an infinite sequence of `option α` such
that if `f n = some a` for some `n` then it is constantly `some a` after that. -/
def computation (α : Type u) :=
Subtype fun (f : stream (Option α)) => ∀ {n : ℕ} {a : α}, f n = some a → f (n + 1) = some a
namespace computation
-- constructors
/-- `return a` is the computation that immediately terminates with result `a`. -/
def return {α : Type u} (a : α) : computation α :=
{ val := stream.const (some a), property := sorry }
protected instance has_coe_t {α : Type u} : has_coe_t α (computation α) := has_coe_t.mk return
/-- `think c` is the computation that delays for one "tick" and then performs
computation `c`. -/
def think {α : Type u} (c : computation α) : computation α :=
{ val := none :: subtype.val c, property := sorry }
/-- `thinkN c n` is the computation that delays for `n` ticks and then performs
computation `c`. -/
def thinkN {α : Type u} (c : computation α) : ℕ → computation α := sorry
-- check for immediate result
/-- `head c` is the first step of computation, either `some a` if `c = return a`
or `none` if `c = think c'`. -/
def head {α : Type u} (c : computation α) : Option α := stream.head (subtype.val c)
-- one step of computation
/-- `tail c` is the remainder of computation, either `c` if `c = return a`
or `c'` if `c = think c'`. -/
def tail {α : Type u} (c : computation α) : computation α :=
{ val := stream.tail (subtype.val c), property := sorry }
/-- `empty α` is the computation that never returns, an infinite sequence of
`think`s. -/
def empty (α : Type u_1) : computation α := { val := stream.const none, property := sorry }
protected instance inhabited {α : Type u} : Inhabited (computation α) := { default := empty α }
/-- `run_for c n` evaluates `c` for `n` steps and returns the result, or `none`
if it did not terminate after `n` steps. -/
def run_for {α : Type u} : computation α → ℕ → Option α := subtype.val
/-- `destruct c` is the destructor for `computation α` as a coinductive type.
It returns `inl a` if `c = return a` and `inr c'` if `c = think c'`. -/
def destruct {α : Type u} (c : computation α) : α ⊕ computation α := sorry
/-- `run c` is an unsound meta function that runs `c` to completion, possibly
resulting in an infinite loop in the VM. -/
theorem destruct_eq_ret {α : Type u} {s : computation α} {a : α} :
destruct s = sum.inl a → s = return a :=
sorry
theorem destruct_eq_think {α : Type u} {s : computation α} {s' : computation α} :
destruct s = sum.inr s' → s = think s' :=
sorry
@[simp] theorem destruct_ret {α : Type u} (a : α) : destruct (return a) = sum.inl a := rfl
@[simp] theorem destruct_think {α : Type u} (s : computation α) : destruct (think s) = sum.inr s :=
sorry
@[simp] theorem destruct_empty {α : Type u} : destruct (empty α) = sum.inr (empty α) := rfl
@[simp] theorem head_ret {α : Type u} (a : α) : head (return a) = some a := rfl
@[simp] theorem head_think {α : Type u} (s : computation α) : head (think s) = none := rfl
@[simp] theorem head_empty {α : Type u} : head (empty α) = none := rfl
@[simp] theorem tail_ret {α : Type u} (a : α) : tail (return a) = return a := rfl
@[simp] theorem tail_think {α : Type u} (s : computation α) : tail (think s) = s := sorry
@[simp] theorem tail_empty {α : Type u} : tail (empty α) = empty α := rfl
theorem think_empty {α : Type u} : empty α = think (empty α) := destruct_eq_think destruct_empty
def cases_on {α : Type u} {C : computation α → Sort v} (s : computation α)
(h1 : (a : α) → C (return a)) (h2 : (s : computation α) → C (think s)) : C s :=
(fun (_x : α ⊕ computation α) (H : destruct s = _x) =>
sum.rec (fun (v : α) (H : destruct s = sum.inl v) => eq.mpr sorry (h1 v))
(fun (v : computation α) (H : destruct s = sum.inr v) =>
subtype.cases_on v
(fun (a : stream (Option α))
(s' : ∀ {n : ℕ} {a_1 : α}, a n = some a_1 → a (n + 1) = some a_1)
(H : destruct s = sum.inr { val := a, property := s' }) =>
eq.mpr sorry (h2 { val := a, property := s' }))
H)
_x H)
(destruct s) sorry
def corec.F {α : Type u} {β : Type v} (f : β → α ⊕ β) : α ⊕ β → Option α × (α ⊕ β) := sorry
/-- `corec f b` is the corecursor for `computation α` as a coinductive type.
If `f b = inl a` then `corec f b = return a`, and if `f b = inl b'` then
`corec f b = think (corec f b')`. -/
def corec {α : Type u} {β : Type v} (f : β → α ⊕ β) (b : β) : computation α :=
{ val := stream.corec' sorry (sum.inr b), property := sorry }
/-- left map of `⊕` -/
@[simp] def lmap {α : Type u} {β : Type v} {γ : Type w} (f : α → β) : α ⊕ γ → β ⊕ γ := sorry
/-- right map of `⊕` -/
@[simp] def rmap {α : Type u} {β : Type v} {γ : Type w} (f : β → γ) : α ⊕ β → α ⊕ γ := sorry
@[simp] theorem corec_eq {α : Type u} {β : Type v} (f : β → α ⊕ β) (b : β) :
destruct (corec f b) = rmap (corec f) (f b) :=
sorry
@[simp] def bisim_o {α : Type u} (R : computation α → computation α → Prop) :
α ⊕ computation α → α ⊕ computation α → Prop :=
sorry
def is_bisimulation {α : Type u} (R : computation α → computation α → Prop) :=
∀ {s₁ s₂ : computation α}, R s₁ s₂ → bisim_o R (destruct s₁) (destruct s₂)
theorem eq_of_bisim {α : Type u} (R : computation α → computation α → Prop)
(bisim : is_bisimulation R) {s₁ : computation α} {s₂ : computation α} (r : R s₁ s₂) : s₁ = s₂ :=
sorry
-- It's more of a stretch to use ∈ for this relation, but it
-- asserts that the computation limits to the given value.
protected def mem {α : Type u} (a : α) (s : computation α) := some a ∈ subtype.val s
protected instance has_mem {α : Type u} : has_mem α (computation α) := has_mem.mk computation.mem
theorem le_stable {α : Type u} (s : computation α) {a : α} {m : ℕ} {n : ℕ} (h : m ≤ n) :
subtype.val s m = some a → subtype.val s n = some a :=
sorry
theorem mem_unique {α : Type u} : relator.left_unique has_mem.mem := sorry
/-- `terminates s` asserts that the computation `s` eventually terminates with some value. -/
def terminates {α : Type u} (s : computation α) := ∃ (a : α), a ∈ s
theorem terminates_of_mem {α : Type u} {s : computation α} {a : α} : a ∈ s → terminates s :=
exists.intro a
theorem terminates_def {α : Type u} (s : computation α) :
terminates s ↔ ∃ (n : ℕ), ↥(option.is_some (subtype.val s n)) :=
sorry
theorem ret_mem {α : Type u} (a : α) : a ∈ return a := exists.intro 0 rfl
theorem eq_of_ret_mem {α : Type u} {a : α} {a' : α} (h : a' ∈ return a) : a' = a :=
mem_unique h (ret_mem a)
protected instance ret_terminates {α : Type u} (a : α) : terminates (return a) :=
terminates_of_mem (ret_mem a)
theorem think_mem {α : Type u} {s : computation α} {a : α} : a ∈ s → a ∈ think s := sorry
protected instance think_terminates {α : Type u} (s : computation α) [terminates s] :
terminates (think s) :=
sorry
theorem of_think_mem {α : Type u} {s : computation α} {a : α} : a ∈ think s → a ∈ s := sorry
theorem of_think_terminates {α : Type u} {s : computation α} :
terminates (think s) → terminates s :=
fun (ᾰ : terminates (think s)) =>
Exists.dcases_on ᾰ
fun (ᾰ_w : α) (ᾰ_h : ᾰ_w ∈ think s) =>
idRhs (∃ (a : α), a ∈ s) (Exists.intro ᾰ_w (of_think_mem ᾰ_h))
theorem not_mem_empty {α : Type u} (a : α) : ¬a ∈ empty α := sorry
theorem not_terminates_empty {α : Type u} : ¬terminates (empty α) := sorry
theorem eq_empty_of_not_terminates {α : Type u} {s : computation α} (H : ¬terminates s) :
s = empty α :=
sorry
theorem thinkN_mem {α : Type u} {s : computation α} {a : α} (n : ℕ) : a ∈ thinkN s n ↔ a ∈ s :=
sorry
protected instance thinkN_terminates {α : Type u} (s : computation α) [terminates s] (n : ℕ) :
terminates (thinkN s n) :=
sorry
theorem of_thinkN_terminates {α : Type u} (s : computation α) (n : ℕ) :
terminates (thinkN s n) → terminates s :=
fun (ᾰ : terminates (thinkN s n)) =>
Exists.dcases_on ᾰ
fun (ᾰ_w : α) (ᾰ_h : ᾰ_w ∈ thinkN s n) =>
idRhs (∃ (a : α), a ∈ s) (Exists.intro ᾰ_w (iff.mp (thinkN_mem n) ᾰ_h))
/-- `promises s a`, or `s ~> a`, asserts that although the computation `s`
may not terminate, if it does, then the result is `a`. -/
def promises {α : Type u} (s : computation α) (a : α) := ∀ {a' : α}, a' ∈ s → a = a'
infixl:50 " ~> " => Mathlib.computation.promises
theorem mem_promises {α : Type u} {s : computation α} {a : α} : a ∈ s → s ~> a :=
fun (h : a ∈ s) (a' : α) => mem_unique h
theorem empty_promises {α : Type u} (a : α) : empty α ~> a :=
fun (a' : α) (h : a' ∈ empty α) => absurd h (not_mem_empty a')
/-- `length s` gets the number of steps of a terminating computation -/
def length {α : Type u} (s : computation α) [h : terminates s] : ℕ := nat.find sorry
/-- `get s` returns the result of a terminating computation -/
def get {α : Type u} (s : computation α) [h : terminates s] : α := option.get sorry
theorem get_mem {α : Type u} (s : computation α) [h : terminates s] : get s ∈ s :=
exists.intro (length s) (Eq.symm (option.eq_some_of_is_some (get._proof_2 s)))
theorem get_eq_of_mem {α : Type u} (s : computation α) [h : terminates s] {a : α} :
a ∈ s → get s = a :=
mem_unique (get_mem s)
theorem mem_of_get_eq {α : Type u} (s : computation α) [h : terminates s] {a : α} :
get s = a → a ∈ s :=
fun (h_1 : get s = a) => eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ s)) (Eq.symm h_1))) (get_mem s)
@[simp] theorem get_think {α : Type u} (s : computation α) [h : terminates s] :
get (think s) = get s :=
sorry
@[simp] theorem get_thinkN {α : Type u} (s : computation α) [h : terminates s] (n : ℕ) :
get (thinkN s n) = get s :=
get_eq_of_mem (thinkN s n) (iff.mpr (thinkN_mem n) (get_mem s))
theorem get_promises {α : Type u} (s : computation α) [h : terminates s] : s ~> get s :=
fun (a : α) => get_eq_of_mem s
theorem mem_of_promises {α : Type u} (s : computation α) [h : terminates s] {a : α} (p : s ~> a) :
a ∈ s :=
Exists.dcases_on h fun (a' : α) (h : a' ∈ s) => eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ s)) (p h))) h
theorem get_eq_of_promises {α : Type u} (s : computation α) [h : terminates s] {a : α} :
s ~> a → get s = a :=
get_eq_of_mem s ∘ mem_of_promises s
/-- `results s a n` completely characterizes a terminating computation:
it asserts that `s` terminates after exactly `n` steps, with result `a`. -/
def results {α : Type u} (s : computation α) (a : α) (n : ℕ) := ∃ (h : a ∈ s), length s = n
theorem results_of_terminates {α : Type u} (s : computation α) [T : terminates s] :
results s (get s) (length s) :=
Exists.intro (get_mem s) rfl
theorem results_of_terminates' {α : Type u} (s : computation α) [T : terminates s] {a : α}
(h : a ∈ s) : results s a (length s) :=
eq.mpr (id (Eq._oldrec (Eq.refl (results s a (length s))) (Eq.symm (get_eq_of_mem s h))))
(results_of_terminates s)
theorem results.mem {α : Type u} {s : computation α} {a : α} {n : ℕ} : results s a n → a ∈ s :=
fun (ᾰ : results s a n) =>
Exists.dcases_on ᾰ fun (ᾰ_w : a ∈ s) (ᾰ_h : length s = n) => idRhs (a ∈ s) ᾰ_w
theorem results.terminates {α : Type u} {s : computation α} {a : α} {n : ℕ} (h : results s a n) :
terminates s :=
terminates_of_mem (results.mem h)
theorem results.length {α : Type u} {s : computation α} {a : α} {n : ℕ} [T : terminates s] :
results s a n → length s = n :=
fun (ᾰ : results s a n) =>
Exists.dcases_on ᾰ fun (ᾰ_w : a ∈ s) (ᾰ_h : length s = n) => idRhs (length s = n) ᾰ_h
theorem results.val_unique {α : Type u} {s : computation α} {a : α} {b : α} {m : ℕ} {n : ℕ}
(h1 : results s a m) (h2 : results s b n) : a = b :=
mem_unique (results.mem h1) (results.mem h2)
theorem results.len_unique {α : Type u} {s : computation α} {a : α} {b : α} {m : ℕ} {n : ℕ}
(h1 : results s a m) (h2 : results s b n) : m = n :=
eq.mpr (id (Eq._oldrec (Eq.refl (m = n)) (Eq.symm (results.length h1))))
(eq.mpr (id (Eq._oldrec (Eq.refl (length s = n)) (results.length h2))) (Eq.refl n))
theorem exists_results_of_mem {α : Type u} {s : computation α} {a : α} (h : a ∈ s) :
∃ (n : ℕ), results s a n :=
Exists.intro (length s) (results_of_terminates' s h)
@[simp] theorem get_ret {α : Type u} (a : α) : get (return a) = a :=
get_eq_of_mem (return a) (Exists.intro 0 rfl)
@[simp] theorem length_ret {α : Type u} (a : α) : length (return a) = 0 :=
let h : terminates (return a) := computation.ret_terminates a;
nat.eq_zero_of_le_zero (nat.find_min' (iff.mp (terminates_def (return a)) h) rfl)
theorem results_ret {α : Type u} (a : α) : results (return a) a 0 :=
Exists.intro (ret_mem a) (length_ret a)
@[simp] theorem length_think {α : Type u} (s : computation α) [h : terminates s] :
length (think s) = length s + 1 :=
sorry
theorem results_think {α : Type u} {s : computation α} {a : α} {n : ℕ} (h : results s a n) :
results (think s) a (n + 1) :=
Exists.intro (think_mem (results.mem h))
(eq.mpr (id (Eq._oldrec (Eq.refl (length (think s) = n + 1)) (length_think s)))
(eq.mpr (id (Eq._oldrec (Eq.refl (length s + 1 = n + 1)) (results.length h)))
(Eq.refl (n + 1))))
theorem of_results_think {α : Type u} {s : computation α} {a : α} {n : ℕ}
(h : results (think s) a n) : ∃ (m : ℕ), results s a m ∧ n = m + 1 :=
Exists.intro (length s)
{ left := results_of_terminates' s (of_think_mem (results.mem h)),
right :=
results.len_unique h
(results_think (results_of_terminates' s (of_think_mem (results.mem h)))) }
@[simp] theorem results_think_iff {α : Type u} {s : computation α} {a : α} {n : ℕ} :
results (think s) a (n + 1) ↔ results s a n :=
sorry
theorem results_thinkN {α : Type u} {s : computation α} {a : α} {m : ℕ} (n : ℕ) :
results s a m → results (thinkN s n) a (m + n) :=
sorry
theorem results_thinkN_ret {α : Type u} (a : α) (n : ℕ) : results (thinkN (return a) n) a n :=
eq.mp (Eq._oldrec (Eq.refl (results (thinkN (return a) n) a (0 + n))) (nat.zero_add n))
(results_thinkN n (results_ret a))
@[simp] theorem length_thinkN {α : Type u} (s : computation α) [h : terminates s] (n : ℕ) :
length (thinkN s n) = length s + n :=
results.length (results_thinkN n (results_of_terminates s))
theorem eq_thinkN {α : Type u} {s : computation α} {a : α} {n : ℕ} (h : results s a n) :
s = thinkN (return a) n :=
sorry
theorem eq_thinkN' {α : Type u} (s : computation α) [h : terminates s] :
s = thinkN (return (get s)) (length s) :=
eq_thinkN (results_of_terminates s)
def mem_rec_on {α : Type u} {C : computation α → Sort v} {a : α} {s : computation α} (M : a ∈ s)
(h1 : C (return a)) (h2 : (s : computation α) → C s → C (think s)) : C s :=
eq.mpr sorry
(eq.mpr sorry
(Nat.rec h1 (fun (n : ℕ) (IH : C (thinkN (return a) n)) => h2 (thinkN (return a) n) IH)
(length s)))
def terminates_rec_on {α : Type u} {C : computation α → Sort v} (s : computation α) [terminates s]
(h1 : (a : α) → C (return a)) (h2 : (s : computation α) → C s → C (think s)) : C s :=
mem_rec_on (get_mem s) (h1 (get s)) h2
/-- Map a function on the result of a computation. -/
def map {α : Type u} {β : Type v} (f : α → β) : computation α → computation β := sorry
def bind.G {α : Type u} {β : Type v} : β ⊕ computation β → β ⊕ computation α ⊕ computation β :=
sorry
def bind.F {α : Type u} {β : Type v} (f : α → computation β) :
computation α ⊕ computation β → β ⊕ computation α ⊕ computation β :=
sorry
/-- Compose two computations into a monadic `bind` operation. -/
def bind {α : Type u} {β : Type v} (c : computation α) (f : α → computation β) : computation β :=
corec sorry (sum.inl c)
protected instance has_bind : Bind computation := { bind := bind }
theorem has_bind_eq_bind {α : Type u} {β : Type u} (c : computation α) (f : α → computation β) :
c >>= f = bind c f :=
rfl
/-- Flatten a computation of computations into a single computation. -/
def join {α : Type u} (c : computation (computation α)) : computation α := c >>= id
@[simp] theorem map_ret {α : Type u} {β : Type v} (f : α → β) (a : α) :
map f (return a) = return (f a) :=
rfl
@[simp] theorem map_think {α : Type u} {β : Type v} (f : α → β) (s : computation α) :
map f (think s) = think (map f s) :=
sorry
@[simp] theorem destruct_map {α : Type u} {β : Type v} (f : α → β) (s : computation α) :
destruct (map f s) = lmap f (rmap (map f) (destruct s)) :=
sorry
@[simp] theorem map_id {α : Type u} (s : computation α) : map id s = s := sorry
theorem map_comp {α : Type u} {β : Type v} {γ : Type w} (f : α → β) (g : β → γ)
(s : computation α) : map (g ∘ f) s = map g (map f s) :=
sorry
@[simp] theorem ret_bind {α : Type u} {β : Type v} (a : α) (f : α → computation β) :
bind (return a) f = f a :=
sorry
@[simp] theorem think_bind {α : Type u} {β : Type v} (c : computation α) (f : α → computation β) :
bind (think c) f = think (bind c f) :=
sorry
@[simp] theorem bind_ret {α : Type u} {β : Type v} (f : α → β) (s : computation α) :
bind s (return ∘ f) = map f s :=
sorry
@[simp] theorem bind_ret' {α : Type u} (s : computation α) : bind s return = s :=
eq.mpr (id (Eq._oldrec (Eq.refl (bind s return = s)) (bind_ret (fun (x : α) => x) s)))
(id (eq.mpr (id (Eq._oldrec (Eq.refl (map id s = s)) (map_id s))) (Eq.refl s)))
@[simp] theorem bind_assoc {α : Type u} {β : Type v} {γ : Type w} (s : computation α)
(f : α → computation β) (g : β → computation γ) :
bind (bind s f) g = bind s fun (x : α) => bind (f x) g :=
sorry
theorem results_bind {α : Type u} {β : Type v} {s : computation α} {f : α → computation β} {a : α}
{b : β} {m : ℕ} {n : ℕ} (h1 : results s a m) (h2 : results (f a) b n) :
results (bind s f) b (n + m) :=
sorry
theorem mem_bind {α : Type u} {β : Type v} {s : computation α} {f : α → computation β} {a : α}
{b : β} (h1 : a ∈ s) (h2 : b ∈ f a) : b ∈ bind s f :=
sorry
protected instance terminates_bind {α : Type u} {β : Type v} (s : computation α)
(f : α → computation β) [terminates s] [terminates (f (get s))] : terminates (bind s f) :=
terminates_of_mem (mem_bind (get_mem s) (get_mem (f (get s))))
@[simp] theorem get_bind {α : Type u} {β : Type v} (s : computation α) (f : α → computation β)
[terminates s] [terminates (f (get s))] : get (bind s f) = get (f (get s)) :=
get_eq_of_mem (bind s f) (mem_bind (get_mem s) (get_mem (f (get s))))
@[simp] theorem length_bind {α : Type u} {β : Type v} (s : computation α) (f : α → computation β)
[T1 : terminates s] [T2 : terminates (f (get s))] :
length (bind s f) = length (f (get s)) + length s :=
results.len_unique (results_of_terminates (bind s f))
(results_bind (results_of_terminates s) (results_of_terminates (f (get s))))
theorem of_results_bind {α : Type u} {β : Type v} {s : computation α} {f : α → computation β}
{b : β} {k : ℕ} :
results (bind s f) b k →
∃ (a : α), ∃ (m : ℕ), ∃ (n : ℕ), results s a m ∧ results (f a) b n ∧ k = n + m :=
sorry
theorem exists_of_mem_bind {α : Type u} {β : Type v} {s : computation α} {f : α → computation β}
{b : β} (h : b ∈ bind s f) : ∃ (a : α), ∃ (H : a ∈ s), b ∈ f a :=
sorry
theorem bind_promises {α : Type u} {β : Type v} {s : computation α} {f : α → computation β} {a : α}
{b : β} (h1 : s ~> a) (h2 : f a ~> b) : bind s f ~> b :=
sorry
protected instance monad : Monad computation :=
{ toApplicative :=
{ toFunctor := { map := map, mapConst := fun (α β : Type u_1) => map ∘ function.const β },
toPure := { pure := return },
toSeq :=
{ seq :=
fun (α β : Type u_1) (f : computation (α → β)) (x : computation α) =>
bind f fun (_x : α → β) => map _x x },
toSeqLeft :=
{ seqLeft :=
fun (α β : Type u_1) (a : computation α) (b : computation β) =>
(fun (α β : Type u_1) (f : computation (α → β)) (x : computation α) =>
bind f fun (_x : α → β) => map _x x)
β α (map (function.const β) a) b },
toSeqRight :=
{ seqRight :=
fun (α β : Type u_1) (a : computation α) (b : computation β) =>
(fun (α β : Type u_1) (f : computation (α → β)) (x : computation α) =>
bind f fun (_x : α → β) => map _x x)
β β (map (function.const α id) a) b } },
toBind := { bind := bind } }
protected instance is_lawful_monad : is_lawful_monad computation :=
is_lawful_monad.mk ret_bind bind_assoc
theorem has_map_eq_map {α : Type u} {β : Type u} (f : α → β) (c : computation α) :
f <$> c = map f c :=
rfl
@[simp] theorem return_def {α : Type u} (a : α) : return a = return a := rfl
@[simp] theorem map_ret' {α : Type u_1} {β : Type u_1} (f : α → β) (a : α) :
f <$> return a = return (f a) :=
map_ret
@[simp] theorem map_think' {α : Type u_1} {β : Type u_1} (f : α → β) (s : computation α) :
f <$> think s = think (f <$> s) :=
map_think
theorem mem_map {α : Type u} {β : Type v} (f : α → β) {a : α} {s : computation α} (m : a ∈ s) :
f a ∈ map f s :=
eq.mpr (id (Eq._oldrec (Eq.refl (f a ∈ map f s)) (Eq.symm (bind_ret f s))))
(mem_bind m (ret_mem (f a)))
theorem exists_of_mem_map {α : Type u} {β : Type v} {f : α → β} {b : β} {s : computation α}
(h : b ∈ map f s) : ∃ (a : α), a ∈ s ∧ f a = b :=
sorry
protected instance terminates_map {α : Type u} {β : Type v} (f : α → β) (s : computation α)
[terminates s] : terminates (map f s) :=
eq.mpr (id (Eq._oldrec (Eq.refl (terminates (map f s))) (Eq.symm (bind_ret f s))))
(computation.terminates_bind s (return ∘ f))
theorem terminates_map_iff {α : Type u} {β : Type v} (f : α → β) (s : computation α) :
terminates (map f s) ↔ terminates s :=
sorry
-- Parallel computation
/-- `c₁ <|> c₂` calculates `c₁` and `c₂` simultaneously, returning
the first one that gives a result. -/
def orelse {α : Type u} (c₁ : computation α) (c₂ : computation α) : computation α :=
corec (fun (_x : computation α × computation α) => sorry) (c₁, c₂)
protected instance alternative : alternative computation := alternative.mk empty
@[simp] theorem ret_orelse {α : Type u} (a : α) (c₂ : computation α) :
(return a <|> c₂) = return a :=
sorry
@[simp] theorem orelse_ret {α : Type u} (c₁ : computation α) (a : α) :
(think c₁ <|> return a) = return a :=
sorry
@[simp] theorem orelse_think {α : Type u} (c₁ : computation α) (c₂ : computation α) :
(think c₁ <|> think c₂) = think (c₁ <|> c₂) :=
sorry
@[simp] theorem empty_orelse {α : Type u} (c : computation α) : (empty α <|> c) = c := sorry
@[simp] theorem orelse_empty {α : Type u} (c : computation α) : (c <|> empty α) = c := sorry
/-- `c₁ ~ c₂` asserts that `c₁` and `c₂` either both terminate with the same result,
or both loop forever. -/
def equiv {α : Type u} (c₁ : computation α) (c₂ : computation α) := ∀ (a : α), a ∈ c₁ ↔ a ∈ c₂
infixl:50 " ~ " => Mathlib.computation.equiv
theorem equiv.refl {α : Type u} (s : computation α) : s ~ s := fun (_x : α) => iff.rfl
theorem equiv.symm {α : Type u} {s : computation α} {t : computation α} : s ~ t → t ~ s :=
fun (h : s ~ t) (a : α) => iff.symm (h a)
theorem equiv.trans {α : Type u} {s : computation α} {t : computation α} {u : computation α} :
s ~ t → t ~ u → s ~ u :=
fun (h1 : s ~ t) (h2 : t ~ u) (a : α) => iff.trans (h1 a) (h2 a)
theorem equiv.equivalence {α : Type u} : equivalence equiv :=
{ left := equiv.refl, right := { left := equiv.symm, right := equiv.trans } }
theorem equiv_of_mem {α : Type u} {s : computation α} {t : computation α} {a : α} (h1 : a ∈ s)
(h2 : a ∈ t) : s ~ t :=
fun (a' : α) =>
{ mp := fun (ma : a' ∈ s) => eq.mpr (id (Eq._oldrec (Eq.refl (a' ∈ t)) (mem_unique ma h1))) h2,
mpr :=
fun (ma : a' ∈ t) => eq.mpr (id (Eq._oldrec (Eq.refl (a' ∈ s)) (mem_unique ma h2))) h1 }
theorem terminates_congr {α : Type u} {c₁ : computation α} {c₂ : computation α} (h : c₁ ~ c₂) :
terminates c₁ ↔ terminates c₂ :=
exists_congr h
theorem promises_congr {α : Type u} {c₁ : computation α} {c₂ : computation α} (h : c₁ ~ c₂)
(a : α) : c₁ ~> a ↔ c₂ ~> a :=
forall_congr fun (a' : α) => imp_congr (h a') iff.rfl
theorem get_equiv {α : Type u} {c₁ : computation α} {c₂ : computation α} (h : c₁ ~ c₂)
[terminates c₁] [terminates c₂] : get c₁ = get c₂ :=
get_eq_of_mem c₁ (iff.mpr (h (get c₂)) (get_mem c₂))
theorem think_equiv {α : Type u} (s : computation α) : think s ~ s :=
fun (a : α) => { mp := of_think_mem, mpr := think_mem }
theorem thinkN_equiv {α : Type u} (s : computation α) (n : ℕ) : thinkN s n ~ s :=
fun (a : α) => thinkN_mem n
theorem bind_congr {α : Type u} {β : Type v} {s1 : computation α} {s2 : computation α}
{f1 : α → computation β} {f2 : α → computation β} (h1 : s1 ~ s2) (h2 : ∀ (a : α), f1 a ~ f2 a) :
bind s1 f1 ~ bind s2 f2 :=
sorry
theorem equiv_ret_of_mem {α : Type u} {s : computation α} {a : α} (h : a ∈ s) : s ~ return a :=
equiv_of_mem h (ret_mem a)
/-- `lift_rel R ca cb` is a generalization of `equiv` to relations other than
equality. It asserts that if `ca` terminates with `a`, then `cb` terminates with
some `b` such that `R a b`, and if `cb` terminates with `b` then `ca` terminates
with some `a` such that `R a b`. -/
def lift_rel {α : Type u} {β : Type v} (R : α → β → Prop) (ca : computation α)
(cb : computation β) :=
(∀ {a : α}, a ∈ ca → Exists fun {b : β} => b ∈ cb ∧ R a b) ∧
∀ {b : β}, b ∈ cb → Exists fun {a : α} => a ∈ ca ∧ R a b
theorem lift_rel.swap {α : Type u} {β : Type v} (R : α → β → Prop) (ca : computation α)
(cb : computation β) : lift_rel (function.swap R) cb ca ↔ lift_rel R ca cb :=
and_comm (∀ {a : β}, a ∈ cb → Exists fun {b : α} => b ∈ ca ∧ function.swap R a b)
(∀ {b : α}, b ∈ ca → Exists fun {a : β} => a ∈ cb ∧ function.swap R a b)
theorem lift_eq_iff_equiv {α : Type u} (c₁ : computation α) (c₂ : computation α) :
lift_rel Eq c₁ c₂ ↔ c₁ ~ c₂ :=
sorry
theorem lift_rel.refl {α : Type u} (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) :=
fun (s : computation α) =>
{ left := fun (a : α) (as : a ∈ s) => Exists.intro a { left := as, right := H a },
right := fun (b : α) (bs : b ∈ s) => Exists.intro b { left := bs, right := H b } }
theorem lift_rel.symm {α : Type u} (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) :=
sorry
theorem lift_rel.trans {α : Type u} (R : α → α → Prop) (H : transitive R) :
transitive (lift_rel R) :=
sorry
theorem lift_rel.equiv {α : Type u} (R : α → α → Prop) : equivalence R → equivalence (lift_rel R) :=
sorry
theorem lift_rel.imp {α : Type u} {β : Type v} {R : α → β → Prop} {S : α → β → Prop}
(H : ∀ {a : α} {b : β}, R a b → S a b) (s : computation α) (t : computation β) :
lift_rel R s t → lift_rel S s t :=
sorry
theorem terminates_of_lift_rel {α : Type u} {β : Type v} {R : α → β → Prop} {s : computation α}
{t : computation β} : lift_rel R s t → (terminates s ↔ terminates t) :=
sorry
theorem rel_of_lift_rel {α : Type u} {β : Type v} {R : α → β → Prop} {ca : computation α}
{cb : computation β} : lift_rel R ca cb → ∀ {a : α} {b : β}, a ∈ ca → b ∈ cb → R a b :=
sorry
theorem lift_rel_of_mem {α : Type u} {β : Type v} {R : α → β → Prop} {a : α} {b : β}
{ca : computation α} {cb : computation β} (ma : a ∈ ca) (mb : b ∈ cb) (ab : R a b) :
lift_rel R ca cb :=
sorry
theorem exists_of_lift_rel_left {α : Type u} {β : Type v} {R : α → β → Prop} {ca : computation α}
{cb : computation β} (H : lift_rel R ca cb) {a : α} (h : a ∈ ca) :
Exists fun {b : β} => b ∈ cb ∧ R a b :=
and.left H a h
theorem exists_of_lift_rel_right {α : Type u} {β : Type v} {R : α → β → Prop} {ca : computation α}
{cb : computation β} (H : lift_rel R ca cb) {b : β} (h : b ∈ cb) :
Exists fun {a : α} => a ∈ ca ∧ R a b :=
and.right H b h
theorem lift_rel_def {α : Type u} {β : Type v} {R : α → β → Prop} {ca : computation α}
{cb : computation β} :
lift_rel R ca cb ↔
(terminates ca ↔ terminates cb) ∧ ∀ {a : α} {b : β}, a ∈ ca → b ∈ cb → R a b :=
sorry
theorem lift_rel_bind {α : Type u} {β : Type v} {γ : Type w} {δ : Type u_1} (R : α → β → Prop)
(S : γ → δ → Prop) {s1 : computation α} {s2 : computation β} {f1 : α → computation γ}
{f2 : β → computation δ} (h1 : lift_rel R s1 s2)
(h2 : ∀ {a : α} {b : β}, R a b → lift_rel S (f1 a) (f2 b)) :
lift_rel S (bind s1 f1) (bind s2 f2) :=
sorry
@[simp] theorem lift_rel_return_left {α : Type u} {β : Type v} (R : α → β → Prop) (a : α)
(cb : computation β) : lift_rel R (return a) cb ↔ Exists fun {b : β} => b ∈ cb ∧ R a b :=
sorry
@[simp] theorem lift_rel_return_right {α : Type u} {β : Type v} (R : α → β → Prop)
(ca : computation α) (b : β) :
lift_rel R ca (return b) ↔ Exists fun {a : α} => a ∈ ca ∧ R a b :=
sorry
@[simp] theorem lift_rel_return {α : Type u} {β : Type v} (R : α → β → Prop) (a : α) (b : β) :
lift_rel R (return a) (return b) ↔ R a b :=
sorry
@[simp] theorem lift_rel_think_left {α : Type u} {β : Type v} (R : α → β → Prop)
(ca : computation α) (cb : computation β) : lift_rel R (think ca) cb ↔ lift_rel R ca cb :=
sorry
@[simp] theorem lift_rel_think_right {α : Type u} {β : Type v} (R : α → β → Prop)
(ca : computation α) (cb : computation β) : lift_rel R ca (think cb) ↔ lift_rel R ca cb :=
sorry
theorem lift_rel_mem_cases {α : Type u} {β : Type v} {R : α → β → Prop} {ca : computation α}
{cb : computation β} (Ha : ∀ (a : α), a ∈ ca → lift_rel R ca cb)
(Hb : ∀ (b : β), b ∈ cb → lift_rel R ca cb) : lift_rel R ca cb :=
{ left := fun (a : α) (ma : a ∈ ca) => and.left (Ha a ma) a ma,
right := fun (b : β) (mb : b ∈ cb) => and.right (Hb b mb) b mb }
theorem lift_rel_congr {α : Type u} {β : Type v} {R : α → β → Prop} {ca : computation α}
{ca' : computation α} {cb : computation β} {cb' : computation β} (ha : ca ~ ca')
(hb : cb ~ cb') : lift_rel R ca cb ↔ lift_rel R ca' cb' :=
and_congr
(forall_congr
fun (a : α) => imp_congr (ha a) (exists_congr fun (b : β) => and_congr (hb b) iff.rfl))
(forall_congr
fun (b : β) => imp_congr (hb b) (exists_congr fun (a : α) => and_congr (ha a) iff.rfl))
theorem lift_rel_map {α : Type u} {β : Type v} {γ : Type w} {δ : Type u_1} (R : α → β → Prop)
(S : γ → δ → Prop) {s1 : computation α} {s2 : computation β} {f1 : α → γ} {f2 : β → δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a : α} {b : β}, R a b → S (f1 a) (f2 b)) :
lift_rel S (map f1 s1) (map f2 s2) :=
sorry
theorem map_congr {α : Type u} {β : Type v} (R : α → α → Prop) (S : β → β → Prop)
{s1 : computation α} {s2 : computation α} {f : α → β} (h1 : s1 ~ s2) : map f s1 ~ map f s2 :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (map f s1 ~ map f s2))
(Eq.symm (propext (lift_eq_iff_equiv (map f s1) (map f s2))))))
(lift_rel_map Eq Eq (iff.mpr (lift_eq_iff_equiv s1 s2) h1)
fun (a b : α) => congr_arg fun (a : α) => f a)
@[simp] def lift_rel_aux {α : Type u} {β : Type v} (R : α → β → Prop)
(C : computation α → computation β → Prop) : α ⊕ computation α → β ⊕ computation β → Prop :=
sorry
@[simp] theorem lift_rel_aux.ret_left {α : Type u} {β : Type v} (R : α → β → Prop)
(C : computation α → computation β → Prop) (a : α) (cb : computation β) :
lift_rel_aux R C (sum.inl a) (destruct cb) ↔ Exists fun {b : β} => b ∈ cb ∧ R a b :=
sorry
theorem lift_rel_aux.swap {α : Type u} {β : Type v} (R : α → β → Prop)
(C : computation α → computation β → Prop) (a : α ⊕ computation α) (b : β ⊕ computation β) :
lift_rel_aux (function.swap R) (function.swap C) b a = lift_rel_aux R C a b :=
sorry
@[simp] theorem lift_rel_aux.ret_right {α : Type u} {β : Type v} (R : α → β → Prop)
(C : computation α → computation β → Prop) (b : β) (ca : computation α) :
lift_rel_aux R C (destruct ca) (sum.inl b) ↔ Exists fun {a : α} => a ∈ ca ∧ R a b :=
sorry
theorem lift_rel_rec.lem {α : Type u} {β : Type v} {R : α → β → Prop}
(C : computation α → computation β → Prop)
(H :
∀ {ca : computation α} {cb : computation β},
C ca cb → lift_rel_aux R C (destruct ca) (destruct cb))
(ca : computation α) (cb : computation β) (Hc : C ca cb) (a : α) (ha : a ∈ ca) :
lift_rel R ca cb :=
sorry
theorem lift_rel_rec {α : Type u} {β : Type v} {R : α → β → Prop}
(C : computation α → computation β → Prop)
(H :
∀ {ca : computation α} {cb : computation β},
C ca cb → lift_rel_aux R C (destruct ca) (destruct cb))
(ca : computation α) (cb : computation β) (Hc : C ca cb) : lift_rel R ca cb :=
lift_rel_mem_cases sorry
fun (b : β) (hb : b ∈ cb) => iff.mpr (lift_rel.swap (fun (x : β) (y : α) => R y x) cb ca) sorry
end Mathlib |
34c85480cb744f583154837544f92857cbc33e8b | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/lean/run/CommandExtOverlap.lean | c93741b2a8c46aa63311e0d8723b42d8b05d6299 | [
"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 | 335 | lean | new_frontend
syntax [mycheck] "#check" (sepBy term ",") : command
open Lean
macro_rules [mycheck]
| `(#check $es*) =>
let cmds := es.getSepElems.map $ fun e => Syntax.node `Lean.Parser.Command.check #[Syntax.atom none "#check", e];
pure $ mkNullNode cmds
#check true
#check true, true
#check true, 1, 3, fun (x : Nat) => x + 1
|
e600182dd888717a2a04f546dbb93eba2f57d7f6 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebraic_geometry/morphisms/ring_hom_properties.lean | b9dfba0ca93c5632205d52dcb9ca358c43501f04 | [
"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 | 25,184 | lean | /-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import algebraic_geometry.morphisms.basic
import ring_theory.local_properties
/-!
# Properties of morphisms from properties of ring homs.
We provide the basic framework for talking about properties of morphisms that come from properties
of ring homs. For `P` a property of ring homs, we have two ways of defining a property of scheme
morphisms:
Let `f : X ⟶ Y`,
- `target_affine_locally (affine_and P)`: the preimage of an affine open `U = Spec A` is affine
(`= Spec B`) and `A ⟶ B` satisfies `P`. (TODO)
- `affine_locally P`: For each pair of affine open `U = Spec A ⊆ X` and `V = Spec B ⊆ f ⁻¹' U`,
the ring hom `A ⟶ B` satisfies `P`.
For these notions to be well defined, we require `P` be a sufficient local property. For the former,
`P` should be local on the source (`ring_hom.respects_iso P`, `ring_hom.localization_preserves P`,
`ring_hom.of_localization_span`), and `target_affine_locally (affine_and P)` will be local on
the target. (TODO)
For the latter `P` should be local on the target (`ring_hom.property_is_local P`), and
`affine_locally P` will be local on both the source and the target.
Further more, these properties are stable under compositions (resp. base change) if `P` is. (TODO)
-/
universe u
open category_theory opposite topological_space category_theory.limits algebraic_geometry
variable (P : ∀ {R S : Type u} [comm_ring R] [comm_ring S] (f : by exactI R →+* S), Prop)
namespace ring_hom
include P
variable {P}
lemma respects_iso.basic_open_iff (hP : respects_iso @P) {X Y : Scheme}
[is_affine X] [is_affine Y] (f : X ⟶ Y) (r : Y.presheaf.obj (opposite.op ⊤)) :
P (Scheme.Γ.map (f ∣_ Y.basic_open r).op) ↔
P (@is_localization.away.map (Y.presheaf.obj (opposite.op ⊤)) _
(Y.presheaf.obj (opposite.op $ Y.basic_open r)) _ _
(X.presheaf.obj (opposite.op ⊤)) _ (X.presheaf.obj
(opposite.op $ X.basic_open (Scheme.Γ.map f.op r))) _ _ (Scheme.Γ.map f.op) r _ _) :=
begin
rw [Γ_map_morphism_restrict, hP.cancel_left_is_iso, hP.cancel_right_is_iso,
← (hP.cancel_right_is_iso (f.val.c.app (opposite.op (Y.basic_open r))) (X.presheaf.map
(eq_to_hom (Scheme.preimage_basic_open f r).symm).op)), ← eq_iff_iff],
congr,
delta is_localization.away.map,
refine is_localization.ring_hom_ext (submonoid.powers r) _,
convert (is_localization.map_comp _).symm using 1,
change Y.presheaf.map _ ≫ _ = _ ≫ X.presheaf.map _,
rw f.val.c.naturality_assoc,
erw ← X.presheaf.map_comp,
congr,
end
lemma respects_iso.basic_open_iff_localization (hP : respects_iso @P)
{X Y : Scheme} [is_affine X] [is_affine Y] (f : X ⟶ Y) (r : Y.presheaf.obj (opposite.op ⊤)) :
P (Scheme.Γ.map (f ∣_ Y.basic_open r).op) ↔
P (localization.away_map (Scheme.Γ.map f.op) r) :=
(hP.basic_open_iff _ _).trans (hP.is_localization_away_iff _ _ _ _).symm
lemma respects_iso.of_restrict_morphism_restrict_iff (hP : ring_hom.respects_iso @P)
{X Y : Scheme} [is_affine Y] (f : X ⟶ Y) (r : Y.presheaf.obj (opposite.op ⊤))
(U : opens X.carrier) (hU : is_affine_open U) {V : opens _}
(e : V = (opens.map (X.of_restrict ((opens.map f.1.base).obj _).open_embedding).1.base).obj U) :
P (Scheme.Γ.map ((X.restrict ((opens.map f.1.base).obj _).open_embedding).of_restrict
V.open_embedding ≫ f ∣_ Y.basic_open r).op) ↔
P (localization.away_map (Scheme.Γ.map (X.of_restrict U.open_embedding ≫ f).op) r) :=
begin
subst e,
convert (hP.is_localization_away_iff _ _ _ _).symm,
rotate,
{ apply_instance },
{ apply ring_hom.to_algebra,
refine X.presheaf.map
(@hom_of_le _ _ ((is_open_map.functor _).obj _) ((is_open_map.functor _).obj _) _).op,
rw [opens.le_def],
dsimp,
change coe '' (coe '' set.univ) ⊆ coe '' set.univ,
rw [subtype.coe_image_univ, subtype.coe_image_univ],
exact set.image_preimage_subset _ _ },
{ exact algebraic_geometry.Γ_restrict_is_localization Y r },
{ rw ← U.open_embedding_obj_top at hU,
dsimp [Scheme.Γ_obj_op, Scheme.Γ_map_op, Scheme.restrict],
apply algebraic_geometry.is_localization_of_eq_basic_open _ hU,
rw [opens.open_embedding_obj_top, opens.functor_obj_map_obj],
convert (X.basic_open_res (Scheme.Γ.map f.op r) (hom_of_le le_top).op).symm using 1,
rw [opens.open_embedding_obj_top, opens.open_embedding_obj_top, inf_comm,
Scheme.Γ_map_op, ← Scheme.preimage_basic_open] },
{ apply is_localization.ring_hom_ext (submonoid.powers r) _,
swap, { exact algebraic_geometry.Γ_restrict_is_localization Y r },
rw [is_localization.away.map, is_localization.map_comp, ring_hom.algebra_map_to_algebra,
ring_hom.algebra_map_to_algebra, op_comp, functor.map_comp, op_comp, functor.map_comp],
refine (@category.assoc CommRing _ _ _ _ _ _ _ _).symm.trans _,
refine eq.trans _ (@category.assoc CommRing _ _ _ _ _ _ _ _),
dsimp only [Scheme.Γ_map, quiver.hom.unop_op],
rw [morphism_restrict_c_app, category.assoc, category.assoc, category.assoc],
erw [f.1.c.naturality_assoc, ← X.presheaf.map_comp, ← X.presheaf.map_comp,
← X.presheaf.map_comp],
congr },
end
lemma stable_under_base_change.Γ_pullback_fst
(hP : stable_under_base_change @P) (hP' : respects_iso @P) {X Y S : Scheme}
[is_affine X] [is_affine Y] [is_affine S]
(f : X ⟶ S) (g : Y ⟶ S) (H : P (Scheme.Γ.map g.op)) :
P (Scheme.Γ.map (pullback.fst : pullback f g ⟶ _).op) :=
begin
rw [← preserves_pullback.iso_inv_fst AffineScheme.forget_to_Scheme
(AffineScheme.of_hom f) (AffineScheme.of_hom g), op_comp, functor.map_comp,
hP'.cancel_right_is_iso, AffineScheme.forget_to_Scheme_map],
have := _root_.congr_arg quiver.hom.unop (preserves_pullback.iso_hom_fst AffineScheme.Γ.right_op
(AffineScheme.of_hom f) (AffineScheme.of_hom g)),
simp only [quiver.hom.unop_op, functor.right_op_map, unop_comp] at this,
delta AffineScheme.Γ at this,
simp only [quiver.hom.unop_op, functor.comp_map, AffineScheme.forget_to_Scheme_map,
functor.op_map] at this,
rw [← this, hP'.cancel_right_is_iso,
← pushout_iso_unop_pullback_inl_hom (quiver.hom.unop _) (quiver.hom.unop _),
hP'.cancel_right_is_iso],
exact hP.pushout_inl _ hP' _ _ H
end
end ring_hom
namespace algebraic_geometry
/-- For `P` a property of ring homomorphisms, `source_affine_locally P` holds for `f : X ⟶ Y`
whenever `P` holds for the restriction of `f` on every affine open subset of `X`. -/
def source_affine_locally : affine_target_morphism_property :=
λ X Y f hY, ∀ (U : X.affine_opens), P (Scheme.Γ.map (X.of_restrict U.1.open_embedding ≫ f).op)
/-- For `P` a property of ring homomorphisms, `affine_locally P` holds for `f : X ⟶ Y` if for each
affine open `U = Spec A ⊆ Y` and `V = Spec B ⊆ f ⁻¹' U`, the ring hom `A ⟶ B` satisfies `P`.
Also see `affine_locally_iff_affine_opens_le`. -/
abbreviation affine_locally : morphism_property Scheme :=
target_affine_locally (source_affine_locally @P)
variable {P}
lemma source_affine_locally_respects_iso (h₁ : ring_hom.respects_iso @P) :
(source_affine_locally @P).to_property.respects_iso :=
begin
apply affine_target_morphism_property.respects_iso_mk,
{ introv H U,
rw [← h₁.cancel_right_is_iso _ (Scheme.Γ.map (Scheme.restrict_map_iso e.inv U.1).hom.op),
← functor.map_comp, ← op_comp],
convert H ⟨_, U.prop.map_is_iso e.inv⟩ using 3,
rw [is_open_immersion.iso_of_range_eq_hom, is_open_immersion.lift_fac_assoc,
category.assoc, e.inv_hom_id_assoc],
refl },
{ introv H U,
rw [← category.assoc, op_comp, functor.map_comp, h₁.cancel_left_is_iso],
exact H U }
end
lemma affine_locally_respects_iso (h : ring_hom.respects_iso @P) :
(affine_locally @P).respects_iso :=
target_affine_locally_respects_iso (source_affine_locally_respects_iso h)
lemma affine_locally_iff_affine_opens_le
(hP : ring_hom.respects_iso @P) {X Y : Scheme} (f : X ⟶ Y) :
affine_locally @P f ↔
(∀ (U : Y.affine_opens) (V : X.affine_opens) (e : V.1 ≤ (opens.map f.1.base).obj U.1),
P (f.app_le e)) :=
begin
apply forall_congr,
intro U,
delta source_affine_locally,
simp_rw [op_comp, Scheme.Γ.map_comp, Γ_map_morphism_restrict, category.assoc, Scheme.Γ_map_op,
hP.cancel_left_is_iso],
split,
{ intros H V e,
let U' := (opens.map f.val.base).obj U.1,
have e' : U'.open_embedding.is_open_map.functor.obj ((opens.map U'.inclusion).obj V.1) = V.1,
{ ext1, refine set.image_preimage_eq_inter_range.trans (set.inter_eq_left_iff_subset.mpr _),
convert e, exact subtype.range_coe },
have := H ⟨(opens.map (X.of_restrict (U'.open_embedding)).1.base).obj V.1, _⟩,
erw ← X.presheaf.map_comp at this,
rw [← hP.cancel_right_is_iso _ (X.presheaf.map (eq_to_hom _)), category.assoc,
← X.presheaf.map_comp],
convert this using 1,
{ dsimp only [functor.op, unop_op], rw opens.open_embedding_obj_top, congr' 1, exact e'.symm },
{ apply_instance },
{ apply (is_affine_open_iff_of_is_open_immersion (X.of_restrict _) _).mp,
convert V.2,
apply_instance } },
{ intros H V,
specialize H ⟨_, V.2.image_is_open_immersion (X.of_restrict _)⟩ (subtype.coe_image_subset _ _),
erw ← X.presheaf.map_comp,
rw [← hP.cancel_right_is_iso _ (X.presheaf.map (eq_to_hom _)), category.assoc,
← X.presheaf.map_comp],
convert H,
{ dsimp only [functor.op, unop_op], rw opens.open_embedding_obj_top, refl },
{ apply_instance } }
end
lemma Scheme_restrict_basic_open_of_localization_preserves
(h₁ : ring_hom.respects_iso @P)
(h₂ : ring_hom.localization_preserves @P)
{X Y : Scheme} [is_affine Y] (f : X ⟶ Y) (r : Y.presheaf.obj (op ⊤))
(H : source_affine_locally @P f)
(U : (X.restrict ((opens.map f.1.base).obj $ Y.basic_open r).open_embedding).affine_opens) :
P (Scheme.Γ.map
((X.restrict ((opens.map f.1.base).obj $ Y.basic_open r).open_embedding).of_restrict
U.1.open_embedding ≫ f ∣_ Y.basic_open r).op) :=
begin
specialize H ⟨_, U.2.image_is_open_immersion (X.of_restrict _)⟩,
convert (h₁.of_restrict_morphism_restrict_iff _ _ _ _ _).mpr _ using 1,
swap 5,
{ exact h₂.away r H },
{ apply_instance },
{ exact U.2.image_is_open_immersion _},
{ ext1, exact (set.preimage_image_eq _ subtype.coe_injective).symm }
end
lemma source_affine_locally_is_local
(h₁ : ring_hom.respects_iso @P)
(h₂ : ring_hom.localization_preserves @P)
(h₃ : ring_hom.of_localization_span @P) : (source_affine_locally @P).is_local :=
begin
constructor,
{ exact source_affine_locally_respects_iso h₁ },
{ introv H U,
apply Scheme_restrict_basic_open_of_localization_preserves h₁ h₂; assumption },
{ introv hs hs' U,
resetI,
apply h₃ _ _ hs,
intro r,
have := hs' r ⟨(opens.map (X.of_restrict _).1.base).obj U.1, _⟩,
rwa h₁.of_restrict_morphism_restrict_iff at this,
{ exact U.2 },
{ refl },
{ apply_instance },
{ suffices : ∀ (V = (opens.map f.val.base).obj (Y.basic_open r.val)),
is_affine_open ((opens.map (X.of_restrict V.open_embedding).1.base).obj U.1),
{ exact this _ rfl, },
intros V hV,
rw Scheme.preimage_basic_open at hV,
subst hV,
exact U.2.map_restrict_basic_open (Scheme.Γ.map f.op r.1) } }
end
variables {P} (hP : ring_hom.property_is_local @P)
lemma source_affine_locally_of_source_open_cover_aux
(h₁ : ring_hom.respects_iso @P)
(h₃ : ring_hom.of_localization_span_target @P)
{X Y : Scheme} (f : X ⟶ Y) (U : X.affine_opens)
(s : set (X.presheaf.obj (op U.1))) (hs : ideal.span s = ⊤)
(hs' : ∀ (r : s), P (Scheme.Γ.map (X.of_restrict (X.basic_open r.1).open_embedding ≫ f).op)) :
P (Scheme.Γ.map (X.of_restrict U.1.open_embedding ≫ f).op) :=
begin
apply_fun ideal.map (X.presheaf.map (eq_to_hom U.1.open_embedding_obj_top).op) at hs,
rw [ideal.map_span, ideal.map_top] at hs,
apply h₃ _ _ hs,
rintro ⟨s, r, hr, hs⟩,
have := (@@localization.alg_equiv _ _ _ _ _ (@@algebraic_geometry.Γ_restrict_is_localization
_ U.2 s)).to_ring_equiv.to_CommRing_iso,
refine (h₁.cancel_right_is_iso _ (@@localization.alg_equiv _ _ _ _ _
(@@algebraic_geometry.Γ_restrict_is_localization _ U.2 s))
.to_ring_equiv.to_CommRing_iso.hom).mp _,
subst hs,
rw [CommRing.comp_eq_ring_hom_comp, ← ring_hom.comp_assoc],
erw [is_localization.map_comp, ring_hom.comp_id],
rw [ring_hom.algebra_map_to_algebra, op_comp, functor.map_comp, ← CommRing.comp_eq_ring_hom_comp,
Scheme.Γ_map_op, Scheme.Γ_map_op, Scheme.Γ_map_op, category.assoc],
erw ← X.presheaf.map_comp,
rw [← h₁.cancel_right_is_iso _ (X.presheaf.map (eq_to_hom _))],
convert hs' ⟨r, hr⟩ using 1,
{ erw category.assoc, rw [← X.presheaf.map_comp, op_comp, Scheme.Γ.map_comp,
Scheme.Γ_map_op, Scheme.Γ_map_op], congr },
{ dsimp [functor.op],
conv_lhs { rw opens.open_embedding_obj_top },
conv_rhs { rw opens.open_embedding_obj_top },
erw Scheme.image_basic_open (X.of_restrict U.1.open_embedding),
erw PresheafedSpace.is_open_immersion.of_restrict_inv_app_apply,
rw Scheme.basic_open_res_eq },
{ apply_instance }
end
lemma is_open_immersion_comp_of_source_affine_locally (h₁ : ring_hom.respects_iso @P)
{X Y Z : Scheme} [is_affine X] [is_affine Z] (f : X ⟶ Y) [is_open_immersion f] (g : Y ⟶ Z)
(h₂ : source_affine_locally @P g) :
P (Scheme.Γ.map (f ≫ g).op) :=
begin
rw [← h₁.cancel_right_is_iso _ (Scheme.Γ.map (is_open_immersion.iso_of_range_eq
(Y.of_restrict _) f _).hom.op), ← functor.map_comp, ← op_comp],
convert h₂ ⟨_, range_is_affine_open_of_open_immersion f⟩ using 3,
{ rw [is_open_immersion.iso_of_range_eq_hom, is_open_immersion.lift_fac_assoc] },
{ apply_instance },
{ exact subtype.range_coe },
{ apply_instance }
end
end algebraic_geometry
open algebraic_geometry
namespace ring_hom.property_is_local
variables {P} (hP : ring_hom.property_is_local @P)
include hP
lemma source_affine_locally_of_source_open_cover
{X Y : Scheme} (f : X ⟶ Y) [is_affine Y]
(𝒰 : X.open_cover) [∀ i, is_affine (𝒰.obj i)] (H : ∀ i, P (Scheme.Γ.map (𝒰.map i ≫ f).op)) :
source_affine_locally @P f :=
begin
let S := λ i, (⟨⟨set.range (𝒰.map i).1.base, (𝒰.is_open i).base_open.open_range⟩,
range_is_affine_open_of_open_immersion (𝒰.map i)⟩ : X.affine_opens),
intros U,
apply of_affine_open_cover U,
swap 5, { exact set.range S },
{ intros U r H,
convert hP.stable_under_composition _ _ H _ using 1,
swap,
{ refine X.presheaf.map
(@hom_of_le _ _ ((is_open_map.functor _).obj _) ((is_open_map.functor _).obj _) _).op,
rw [unop_op, unop_op, opens.open_embedding_obj_top, opens.open_embedding_obj_top],
exact X.basic_open_le _ },
{ rw [op_comp, op_comp, functor.map_comp, functor.map_comp],
refine (eq.trans _ (category.assoc _ _ _).symm : _),
congr' 1,
refine eq.trans _ (X.presheaf.map_comp _ _),
change X.presheaf.map _ = _,
congr },
convert hP.holds_for_localization_away _
(X.presheaf.map (eq_to_hom U.1.open_embedding_obj_top).op r),
{ exact (ring_hom.algebra_map_to_algebra _).symm },
{ dsimp [Scheme.Γ],
have := U.2,
rw ← U.1.open_embedding_obj_top at this,
convert is_localization_basic_open this _ using 6;
rw opens.open_embedding_obj_top; exact (Scheme.basic_open_res_eq _ _ _).symm } },
{ introv hs hs',
exact source_affine_locally_of_source_open_cover_aux hP.respects_iso hP.2 _ _ _ hs hs' },
{ rw set.eq_univ_iff_forall,
intro x,
rw set.mem_Union,
exact ⟨⟨_, 𝒰.f x, rfl⟩, 𝒰.covers x⟩ },
{ rintro ⟨_, i, rfl⟩,
specialize H i,
rw ← hP.respects_iso.cancel_right_is_iso _ (Scheme.Γ.map (is_open_immersion.iso_of_range_eq
(𝒰.map i) (X.of_restrict (S i).1.open_embedding) subtype.range_coe.symm).inv.op) at H,
rwa [← Scheme.Γ.map_comp, ← op_comp, is_open_immersion.iso_of_range_eq_inv,
is_open_immersion.lift_fac_assoc] at H }
end
lemma affine_open_cover_tfae {X Y : Scheme.{u}}
[is_affine Y] (f : X ⟶ Y) :
tfae [source_affine_locally @P f,
∃ (𝒰 : Scheme.open_cover.{u} X) [∀ i, is_affine (𝒰.obj i)],
∀ (i : 𝒰.J), P (Scheme.Γ.map (𝒰.map i ≫ f).op),
∀ (𝒰 : Scheme.open_cover.{u} X) [∀ i, is_affine (𝒰.obj i)] (i : 𝒰.J),
P (Scheme.Γ.map (𝒰.map i ≫ f).op),
∀ {U : Scheme} (g : U ⟶ X) [is_affine U] [is_open_immersion g],
P (Scheme.Γ.map (g ≫ f).op)] :=
begin
tfae_have : 1 → 4,
{ intros H U g _ hg,
resetI,
specialize H ⟨⟨_, hg.base_open.open_range⟩,
range_is_affine_open_of_open_immersion g⟩,
rw [← hP.respects_iso.cancel_right_is_iso _ (Scheme.Γ.map (is_open_immersion.iso_of_range_eq
g (X.of_restrict (opens.open_embedding ⟨_, hg.base_open.open_range⟩))
subtype.range_coe.symm).hom.op), ← Scheme.Γ.map_comp, ← op_comp,
is_open_immersion.iso_of_range_eq_hom] at H,
erw is_open_immersion.lift_fac_assoc at H,
exact H },
tfae_have : 4 → 3,
{ intros H 𝒰 _ i, resetI, apply H },
tfae_have : 3 → 2,
{ intro H, refine ⟨X.affine_cover, infer_instance, H _⟩ },
tfae_have : 2 → 1,
{ rintro ⟨𝒰, _, h𝒰⟩,
exactI hP.source_affine_locally_of_source_open_cover f 𝒰 h𝒰 },
tfae_finish
end
lemma open_cover_tfae {X Y : Scheme.{u}} [is_affine Y] (f : X ⟶ Y) :
tfae [source_affine_locally @P f,
∃ (𝒰 : Scheme.open_cover.{u} X), ∀ (i : 𝒰.J), source_affine_locally @P (𝒰.map i ≫ f),
∀ (𝒰 : Scheme.open_cover.{u} X) (i : 𝒰.J), source_affine_locally @P (𝒰.map i ≫ f),
∀ {U : Scheme} (g : U ⟶ X) [is_open_immersion g], source_affine_locally @P (g ≫ f)] :=
begin
tfae_have : 1 → 4,
{ intros H U g hg V,
resetI,
rw (hP.affine_open_cover_tfae f).out 0 3 at H,
haveI : is_affine _ := V.2,
rw ← category.assoc,
apply H },
tfae_have : 4 → 3,
{ intros H 𝒰 _ i, resetI, apply H },
tfae_have : 3 → 2,
{ intro H, refine ⟨X.affine_cover, H _⟩ },
tfae_have : 2 → 1,
{ rintro ⟨𝒰, h𝒰⟩,
rw (hP.affine_open_cover_tfae f).out 0 1,
refine ⟨𝒰.bind (λ _, Scheme.affine_cover _), _, _⟩,
{ intro i, dsimp, apply_instance },
{ intro i,
specialize h𝒰 i.1,
rw (hP.affine_open_cover_tfae (𝒰.map i.fst ≫ f)).out 0 3 at h𝒰,
erw category.assoc,
apply @@h𝒰 _ (show _, from _),
dsimp, apply_instance } },
tfae_finish
end
lemma source_affine_locally_comp_of_is_open_immersion
{X Y Z : Scheme.{u}} [is_affine Z] (f : X ⟶ Y) (g : Y ⟶ Z) [is_open_immersion f]
(H : source_affine_locally @P g) : source_affine_locally @P (f ≫ g) :=
by apply ((hP.open_cover_tfae g).out 0 3).mp H
lemma source_affine_open_cover_iff {X Y : Scheme.{u}} (f : X ⟶ Y)
[is_affine Y] (𝒰 : Scheme.open_cover.{u} X) [∀ i, is_affine (𝒰.obj i)] :
source_affine_locally @P f ↔ (∀ i, P (Scheme.Γ.map (𝒰.map i ≫ f).op)) :=
⟨λ H, let h := ((hP.affine_open_cover_tfae f).out 0 2).mp H in h 𝒰,
λ H, let h := ((hP.affine_open_cover_tfae f).out 1 0).mp in h ⟨𝒰, infer_instance, H⟩⟩
lemma is_local_source_affine_locally :
(source_affine_locally @P).is_local :=
source_affine_locally_is_local hP.respects_iso hP.localization_preserves
(@ring_hom.property_is_local.of_localization_span _ hP)
lemma is_local_affine_locally :
property_is_local_at_target (affine_locally @P) :=
hP.is_local_source_affine_locally.target_affine_locally_is_local
lemma affine_open_cover_iff {X Y : Scheme.{u}} (f : X ⟶ Y)
(𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)]
(𝒰' : ∀ i, Scheme.open_cover.{u} ((𝒰.pullback_cover f).obj i)) [∀ i j, is_affine ((𝒰' i).obj j)] :
affine_locally @P f ↔
(∀ i j, P (Scheme.Γ.map ((𝒰' i).map j ≫ pullback.snd).op)) :=
(hP.is_local_source_affine_locally.affine_open_cover_iff f 𝒰).trans
(forall_congr (λ i, hP.source_affine_open_cover_iff _ (𝒰' i)))
lemma source_open_cover_iff {X Y : Scheme.{u}} (f : X ⟶ Y)
(𝒰 : Scheme.open_cover.{u} X) :
affine_locally @P f ↔ ∀ i, affine_locally @P (𝒰.map i ≫ f) :=
begin
split,
{ intros H i U,
rw morphism_restrict_comp,
delta morphism_restrict,
apply hP.source_affine_locally_comp_of_is_open_immersion,
apply H },
{ intros H U,
haveI : is_affine _ := U.2,
apply ((hP.open_cover_tfae (f ∣_ U.1)).out 1 0).mp,
use 𝒰.pullback_cover (X.of_restrict _),
intro i,
specialize H i U,
rw morphism_restrict_comp at H,
delta morphism_restrict at H,
have := source_affine_locally_respects_iso hP.respects_iso,
rw [category.assoc, affine_cancel_left_is_iso this, ← affine_cancel_left_is_iso
this (pullback_symmetry _ _).hom, pullback_symmetry_hom_comp_snd_assoc] at H,
exact H }
end
lemma affine_locally_of_is_open_immersion (hP : ring_hom.property_is_local @P) {X Y : Scheme}
(f : X ⟶ Y) [hf : is_open_immersion f] : affine_locally @P f :=
begin
intro U,
haveI H : is_affine _ := U.2,
rw ← category.comp_id (f ∣_ U),
apply hP.source_affine_locally_comp_of_is_open_immersion,
rw hP.source_affine_open_cover_iff _ (Scheme.open_cover_of_is_iso (𝟙 _)),
{ intro i, erw [category.id_comp, op_id, Scheme.Γ.map_id],
convert hP.holds_for_localization_away _ (1 : Scheme.Γ.obj _),
{ exact (ring_hom.algebra_map_to_algebra _).symm },
{ apply_instance },
{ refine is_localization.away_of_is_unit_of_bijective _ is_unit_one function.bijective_id } },
{ intro i, exact H }
end
lemma affine_locally_of_comp
(H : ∀ {R S T : Type.{u}} [comm_ring R] [comm_ring S] [comm_ring T], by exactI
∀ (f : R →+* S) (g : S →+* T), P (g.comp f) → P g)
{X Y Z : Scheme} {f : X ⟶ Y} {g : Y ⟶ Z} (h : affine_locally @P (f ≫ g)) :
affine_locally @P f :=
begin
let 𝒰 : ∀ i, ((Z.affine_cover.pullback_cover (f ≫ g)).obj i).open_cover,
{ intro i,
refine Scheme.open_cover.bind _ (λ i, Scheme.affine_cover _),
apply Scheme.open_cover.pushforward_iso _
(pullback_right_pullback_fst_iso g (Z.affine_cover.map i) f).hom,
apply Scheme.pullback.open_cover_of_right,
exact (pullback g (Z.affine_cover.map i)).affine_cover },
haveI h𝒰 : ∀ i j, is_affine ((𝒰 i).obj j), by { dsimp, apply_instance },
let 𝒰' := (Z.affine_cover.pullback_cover g).bind (λ i, Scheme.affine_cover _),
haveI h𝒰' : ∀ i, is_affine (𝒰'.obj i), by { dsimp, apply_instance },
rw hP.affine_open_cover_iff f 𝒰' (λ i, Scheme.affine_cover _),
rw hP.affine_open_cover_iff (f ≫ g) Z.affine_cover 𝒰 at h,
rintros ⟨i, j⟩ k,
dsimp at i j k,
specialize h i ⟨j, k⟩,
dsimp only [Scheme.open_cover.bind_map, Scheme.open_cover.pushforward_iso_obj,
Scheme.pullback.open_cover_of_right_obj, Scheme.open_cover.pushforward_iso_map,
Scheme.pullback.open_cover_of_right_map, Scheme.open_cover.bind_obj,
Scheme.open_cover.pullback_cover_obj, Scheme.open_cover.pullback_cover_map] at h ⊢,
rw [category.assoc, category.assoc, pullback_right_pullback_fst_iso_hom_snd,
pullback.lift_snd_assoc, category.assoc, ← category.assoc, op_comp, functor.map_comp] at h,
exact H _ _ h,
end
lemma affine_locally_stable_under_composition :
(affine_locally @P).stable_under_composition :=
begin
intros X Y S f g hf hg,
let 𝒰 : ∀ i, ((S.affine_cover.pullback_cover (f ≫ g)).obj i).open_cover,
{ intro i,
refine Scheme.open_cover.bind _ (λ i, Scheme.affine_cover _),
apply Scheme.open_cover.pushforward_iso _
(pullback_right_pullback_fst_iso g (S.affine_cover.map i) f).hom,
apply Scheme.pullback.open_cover_of_right,
exact (pullback g (S.affine_cover.map i)).affine_cover },
rw hP.affine_open_cover_iff (f ≫ g) S.affine_cover _,
rotate,
{ exact 𝒰 },
{ intros i j, dsimp at *, apply_instance },
{ rintros i ⟨j, k⟩,
dsimp at i j k,
dsimp only [Scheme.open_cover.bind_map, Scheme.open_cover.pushforward_iso_obj,
Scheme.pullback.open_cover_of_right_obj, Scheme.open_cover.pushforward_iso_map,
Scheme.pullback.open_cover_of_right_map, Scheme.open_cover.bind_obj],
rw [category.assoc, category.assoc, pullback_right_pullback_fst_iso_hom_snd,
pullback.lift_snd_assoc, category.assoc, ← category.assoc, op_comp, functor.map_comp],
apply hP.stable_under_composition,
{ exact (hP.affine_open_cover_iff _ _ _).mp hg _ _ },
{ delta affine_locally at hf,
rw (hP.is_local_source_affine_locally.affine_open_cover_tfae f).out 0 3 at hf,
specialize hf ((pullback g (S.affine_cover.map i)).affine_cover.map j ≫ pullback.fst),
rw (hP.affine_open_cover_tfae (pullback.snd : pullback f ((pullback g (S.affine_cover.map i))
.affine_cover.map j ≫ pullback.fst) ⟶ _)).out 0 3 at hf,
apply hf } }
end
end ring_hom.property_is_local
|
228378543971a2d4e3b5fdb70d9a7d4ca80ec28d | 01f6b345a06ece970e589d4bbc68ee8b9b2cf58a | /src/limsup.lean | 4b023cb132f039b601cfbb929e9f66bc9d5ed43c | [] | no_license | mariainesdff/norm_extensions_journal_submission | 6077acb98a7200de4553e653d81d54fb5d2314c8 | d396130660935464fbc683f9aaf37fff8a890baa | refs/heads/master | 1,686,685,693,347 | 1,684,065,115,000 | 1,684,065,115,000 | 603,823,641 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,057 | lean | /-
Copyright (c) 2023 María Inés de Frutos-Fernández. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: María Inés de Frutos-Fernández
-/
import order.liminf_limsup
import topology.instances.nnreal
/-!
# Limsup
We prove some auxiliary results about limsups, infis, and suprs.
## Main Results
* `ennreal.le_infi_mul_infi` : if `f g : ι → ennreal` take real values, and
`∀ (i j : ι), a ≤ f i * g j`, then `a ≤ infi f * infi g`.
* `ennreal.infi_mul_le_mul_infi` : if `u v : ι → ennreal` take real values and are antitone, then
`infi (u * v) ≤ infi u * infi v`.
* `ennreal.limsup_mul_le` : if `u v : ℕ → ℝ≥0∞` are bounded above by real numbers, then
`filter.limsup (u * v) at_top ≤ filter.limsup u at_top * filter.limsup v at_top`.
* `real.limsup_mul_le` : If `u v : ℕ → ℝ` are nonnegative and bounded above, then
`filter.limsup (u * v) at_top ≤ filter.limsup u at_top * filter.limsup v at_top `.
## Tags
limsup, real, nnreal, ennreal
-/
noncomputable theory
namespace filter
/-- If `u : β → α` is nonnegative and `is_bounded_under has_le.le f u`, then `0 ≤ limsup u f`. -/
lemma limsup_nonneg_of_nonneg {α β : Type*} [has_zero α] [conditionally_complete_linear_order α]
{f : filter β} [hf_ne_bot : f.ne_bot] {u : β → α}
(hfu : is_bounded_under has_le.le f u) (h : 0 ≤ u) : 0 ≤ limsup u f :=
le_limsup_of_frequently_le (frequently_of_forall h) hfu
/-- If `filter.limsup u at_top ≤ x`, then for all `ε > 0`, eventually we have `u a < x + ε`. -/
lemma eventually_lt_add_pos_of_limsup_le {α : Type*} [preorder α] {x : ℝ} {u : α → ℝ}
(hu_bdd : is_bounded_under has_le.le at_top u) (hu : filter.limsup u at_top ≤ x)
{ε : ℝ} (hε : 0 < ε) : ∀ᶠ (a : α) in at_top, u a < x + ε :=
eventually_lt_of_limsup_lt (lt_of_le_of_lt hu (lt_add_of_pos_right x hε)) hu_bdd
/-- If `filter.limsup u at_top ≤ x`, then for all `ε > 0`, there exists a positive natural
number `n` such that `u n < x + ε`. -/
lemma exists_lt_of_limsup_le {x : ℝ} {u : ℕ → ℝ} (hu_bdd : is_bounded_under has_le.le at_top u)
(hu : filter.limsup u at_top ≤ x) {ε : ℝ} (hε : 0 < ε) :
∃ n : pnat, u n < x + ε :=
begin
have h : ∀ᶠ (a : ℕ) in at_top, u a < x + ε := eventually_lt_add_pos_of_limsup_le hu_bdd hu hε,
simp only [eventually_at_top, ge_iff_le] at h,
obtain ⟨n, hn⟩ := h,
exact ⟨⟨n + 1, nat.succ_pos _⟩, hn (n + 1) (nat.le_succ _)⟩,
end
end filter
open filter
open_locale topological_space nnreal ennreal
lemma bdd_above.is_bounded_under {α : Type*} [preorder α] {u : α → ℝ}
(hu_bdd : bdd_above (set.range u)) : is_bounded_under has_le.le at_top u :=
begin
obtain ⟨b, hb⟩ := hu_bdd,
use b,
simp only [mem_upper_bounds, set.mem_range, forall_exists_index,
forall_apply_eq_imp_iff'] at hb,
exact eventually_map.mpr (eventually_of_forall hb)
end
namespace nnreal
lemma coe_limsup {u : ℕ → ℝ} (hu : 0 ≤ u) :
limsup u at_top = (((limsup (λ n, (⟨u n, hu n⟩ : ℝ≥0)) at_top) : ℝ≥0) : ℝ) :=
begin
simp only [limsup_eq],
norm_cast,
apply congr_arg,
ext x,
simp only [set.mem_set_of_eq, set.mem_image],
refine ⟨λ hx, _, λ hx, _⟩,
{ have hx' := hx,
simp only [eventually_at_top, ge_iff_le] at hx',
obtain ⟨N, hN⟩ := hx',
have hx0 : 0 ≤ x := le_trans (hu N) (hN N (le_refl _)),
exact ⟨⟨x, hx0⟩, hx, rfl⟩, },
{ obtain ⟨y, hy, hyx⟩ := hx,
simp_rw [← nnreal.coe_le_coe, nnreal.coe_mk, hyx] at hy,
exact hy }
end
/-- If `u : ℕ → ℝ` is bounded above an nonnegative, it is also bounded above when regarded as
a function to `ℝ≥0`. -/
lemma bdd_above' {u : ℕ → ℝ} (hu0 : 0 ≤ u) (hu_bdd: bdd_above (set.range u)) :
bdd_above (set.range (λ (n : ℕ), (⟨u n, hu0 n⟩ : ℝ≥0))) :=
begin
obtain ⟨B, hB⟩ := hu_bdd,
simp only [mem_upper_bounds, set.mem_range, forall_exists_index, forall_apply_eq_imp_iff'] at hB,
have hB0 : 0 ≤ B := le_trans (hu0 0) (hB 0),
use (⟨B, hB0⟩ : ℝ≥0),
simp only [mem_upper_bounds, set.mem_range, forall_exists_index, subtype.forall,
subtype.mk_le_mk],
rintros x - n hn,
rw ← hn,
exact hB n,
end
lemma eventually_le_of_bdd_above' {u : ℕ → ℝ≥0} (hu : bdd_above (set.range u)) :
{a : ℝ≥0 | ∀ᶠ (n : ℕ) in at_top, u n ≤ a}.nonempty :=
begin
obtain ⟨B, hB⟩ := hu,
simp only [mem_upper_bounds, set.mem_range, forall_exists_index, forall_apply_eq_imp_iff']
at hB,
exact ⟨B, eventually_of_forall hB⟩,
end
end nnreal
namespace ennreal
/-- If `f g : ι → ℝ≥0∞` take real values, and `∀ (i j : ι), a ≤ f i * g j`, then
`a ≤ infi f * infi g`. -/
lemma le_infi_mul_infi {ι : Sort*} [hι : nonempty ι] {a : ℝ≥0∞} {f g : ι → ℝ≥0∞}
(hf : ∀ x, f x ≠ ⊤) (hg : ∀ x, g x ≠ ⊤) (H : ∀ (i j : ι), a ≤ f i * g j) :
a ≤ infi f * infi g :=
begin
have hg' : infi g ≠ ⊤,
{ rw [ne.def, infi_eq_top, not_forall], exact ⟨hι.some, hg hι.some⟩ },
rw infi_mul hg',
refine le_infi _,
intros i,
rw mul_infi (hf i),
exact le_infi (H i),
{ apply_instance },
{ apply_instance },
end
/-- If `u v : ι → ℝ≥0∞` take real values and are antitone, then `infi (u * v) ≤ infi u * infi v`. -/
lemma infi_mul_le_mul_infi {u v : ℕ → ℝ≥0∞} (hu_top : ∀ x, u x ≠ ⊤) (hu : antitone u)
(hv_top : ∀ x, v x ≠ ⊤) (hv : antitone v) : infi (u * v) ≤ infi u * infi v :=
begin
rw infi_le_iff,
intros b hb,
apply le_infi_mul_infi hu_top hv_top,
intros m n,
exact le_trans (hb (max m n)) (mul_le_mul (hu (le_max_left _ _)) (hv (le_max_right _ _))),
end
lemma supr_tail_seq (u : ℕ → ℝ≥0∞) (n : ℕ) :
(⨆ (k : ℕ) (x : n ≤ k), u k) = ⨆ (k : { k : ℕ // n ≤ k}), u k :=
by rw supr_subtype; refl
lemma le_supr_prop (u : ℕ → ℝ≥0∞) {n k : ℕ} (hnk : n ≤ k) :
u k ≤ ⨆ (k : ℕ) (x : n ≤ k), u k :=
begin
refine le_supr_of_le k _,
rw csupr_pos hnk,
exact le_refl _,
end
/-- The function sending `n : ℕ` to `⨆ (k : ℕ) (x : n ≤ k), u k` is antitone. -/
lemma antitone.supr {u : ℕ → ℝ≥0∞} :
antitone (λ (n : ℕ), ⨆ (k : ℕ) (x : n ≤ k), u k) :=
begin
apply antitone_nat_of_succ_le _,
intros n,
rw [supr₂_le_iff],
intros k hk,
exact le_supr_prop u (le_trans (nat.le_succ n) hk),
end
/-- If `u : ℕ → ℝ≥0∞` is bounded above by a real number, then its `supr` is finite. -/
lemma supr_le_top_of_bdd_above {u : ℕ → ℝ≥0∞} {B : ℝ≥0} (hu : ∀ x, u x ≤ B) (n : ℕ):
(⨆ (k : ℕ) (x : n ≤ k), u k) ≠ ⊤ :=
begin
have h_le : (⨆ (k : ℕ) (x : n ≤ k), u k) ≤ B,
{ rw supr_tail_seq,
exact supr_le (λ m, hu m), },
exact ne_top_of_le_ne_top coe_ne_top h_le
end
/-- If `u v : ℕ → ℝ≥0∞` are bounded above by real numbers, then
`filter.limsup (u * v) at_top ≤ filter.limsup u at_top * filter.limsup v at_top`. -/
lemma limsup_mul_le {u v : ℕ → ℝ≥0∞} {Bu Bv : ℝ≥0} (hu : ∀ x, u x ≤ Bu) (hv : ∀ x, v x ≤ Bv) :
filter.limsup (u * v) at_top ≤ filter.limsup u at_top * filter.limsup v at_top :=
begin
have h_le : (⨅ (n : ℕ), ⨆ (i : ℕ) (x : n ≤ i), u i * v i) ≤
(⨅ (n : ℕ), (⨆ (i : ℕ) (x : n ≤ i), u i) *(⨆ (j : ℕ) (x : n ≤ j), v j)),
{ refine infi_mono _,
intros n,
apply supr_le _,
intros k,
apply supr_le _,
intros hk,
exact mul_le_mul (le_supr_prop u hk) (le_supr_prop v hk), },
simp only [filter.limsup_eq_infi_supr_of_nat, ge_iff_le, pi.mul_apply],
exact le_trans h_le (infi_mul_le_mul_infi (supr_le_top_of_bdd_above hu) antitone.supr
(supr_le_top_of_bdd_above hv) antitone.supr),
end
lemma coe_limsup {u : ℕ → ℝ≥0} (hu : bdd_above (set.range u)) :
(((limsup u at_top) : ℝ≥0) : ℝ≥0∞) = limsup (λ n, (u n : ℝ≥0∞)) at_top :=
begin
simp only [limsup_eq],
rw [coe_Inf (nnreal.eventually_le_of_bdd_above' hu), Inf_eq_infi],
simp only [eventually_at_top, ge_iff_le, set.mem_set_of_eq, infi_exists],
{ apply le_antisymm,
{ apply le_infi₂ _,
intros x n,
apply le_infi _,
intro h,
cases x,
{ simp only [none_eq_top, le_top], },
{ simp only [some_eq_coe, coe_le_coe] at h,
exact infi₂_le_of_le x n (infi_le_of_le h (le_refl _)) }},
{ apply le_infi₂ _,
intros x n,
apply le_infi _,
intro h,
refine infi₂_le_of_le x n _,
simp_rw coe_le_coe,
exact infi_le_of_le h (le_refl _) }},
end
lemma coe_limsup' {u : ℕ → ℝ} (hu : bdd_above (set.range u)) (hu0 : 0 ≤ u) :
(limsup (λ n, ((coe : ℝ≥0 → ℝ≥0∞) (⟨u n, hu0 n⟩ : ℝ≥0))) at_top) =
(coe : ℝ≥0 → ℝ≥0∞) (⟨limsup u at_top, limsup_nonneg_of_nonneg hu.is_bounded_under hu0⟩ : ℝ≥0) :=
by rw [← ennreal.coe_limsup (nnreal.bdd_above' hu0 hu), ennreal.coe_eq_coe, ← nnreal.coe_eq,
subtype.coe_mk, nnreal.coe_limsup]
end ennreal
namespace real
/-- If `u v : ℕ → ℝ` are nonnegative and bounded above, then `u * v` is bounded above. -/
lemma range_bdd_above_mul {u v : ℕ → ℝ} (hu : bdd_above (set.range u)) (hu0 : 0 ≤ u)
(hv : bdd_above (set.range v)) (hv0 : 0 ≤ v) : bdd_above (set.range (u * v)) :=
begin
obtain ⟨bu, hbu⟩ := hu,
obtain ⟨bv, hbv⟩ := hv,
use bu*bv,
simp only [mem_upper_bounds, set.mem_range, pi.mul_apply, forall_exists_index,
forall_apply_eq_imp_iff'] at hbu hbv ⊢,
intros n,
exact mul_le_mul (hbu n) (hbv n) (hv0 n) (le_trans (hu0 n) (hbu n)),
end
/-- If `u v : ℕ → ℝ` are nonnegative and bounded above, then
`filter.limsup (u * v) at_top ≤ filter.limsup u at_top * filter.limsup v at_top `.-/
lemma limsup_mul_le {u v : ℕ → ℝ} (hu_bdd : bdd_above (set.range u)) (hu0 : 0 ≤ u)
(hv_bdd : bdd_above (set.range v)) (hv0 : 0 ≤ v) :
filter.limsup (u * v) at_top ≤ filter.limsup u at_top * filter.limsup v at_top :=
begin
have h_bdd : bdd_above (set.range (u * v)),
{ exact range_bdd_above_mul hu_bdd hu0 hv_bdd hv0 },
have hc : ∀ n : ℕ, (⟨u n * v n, (mul_nonneg (hu0 n) (hv0 n))⟩ : ℝ≥0) = ⟨u n, hu0 n⟩*⟨v n, hv0 n⟩,
{ intro n, simp only [nonneg.mk_mul_mk], },
rw [← nnreal.coe_mk _ (limsup_nonneg_of_nonneg h_bdd.is_bounded_under (mul_nonneg hu0 hv0)),
← nnreal.coe_mk _ (limsup_nonneg_of_nonneg hu_bdd.is_bounded_under hu0),
← nnreal.coe_mk _ (limsup_nonneg_of_nonneg hv_bdd.is_bounded_under hv0),
← nnreal.coe_mul, nnreal.coe_le_coe, ← ennreal.coe_le_coe, ennreal.coe_mul],
simp only [← ennreal.coe_limsup', pi.mul_apply, hc, ennreal.coe_mul],
obtain ⟨Bu, hBu⟩ := hu_bdd,
obtain ⟨Bv, hBv⟩ := hv_bdd,
simp only [mem_upper_bounds, set.mem_range, forall_exists_index, forall_apply_eq_imp_iff']
at hBu hBv,
have hBu_0 : 0 ≤ Bu := le_trans (hu0 0) (hBu 0),
have hBu' : ∀ (n : ℕ), (⟨u n, hu0 n⟩ : ℝ≥0) ≤ (⟨Bu, hBu_0⟩ : ℝ≥0),
{ simp only [← nnreal.coe_le_coe, nnreal.coe_mk], exact hBu },
have hBv_0 : 0 ≤ Bv := le_trans (hv0 0) (hBv 0),
have hBv' : ∀ (n : ℕ), (⟨v n, hv0 n⟩ : ℝ≥0) ≤ (⟨Bv, hBv_0⟩ : ℝ≥0),
{ simp only [← nnreal.coe_le_coe, nnreal.coe_mk], exact hBv },
simp_rw ← ennreal.coe_le_coe at hBu' hBv',
exact ennreal.limsup_mul_le hBu' hBv',
end
-- Alternative proof of limsup_mul_le
lemma limsup_mul_le' {u v : ℕ → ℝ} (hu_bdd : bdd_above (set.range u)) (hu0 : 0 ≤ u)
(hv_bdd : bdd_above (set.range v)) (hv0 : 0 ≤ v) :
filter.limsup (u * v) at_top ≤ filter.limsup u at_top * filter.limsup v at_top :=
begin
have h_bdd : bdd_above (set.range (u * v)),
{ exact range_bdd_above_mul hu_bdd hu0 hv_bdd hv0 },
have hc : ∀ n : ℕ, (⟨u n * v n, (mul_nonneg (hu0 n) (hv0 n))⟩ : ℝ≥0) = ⟨u n, hu0 n⟩*⟨v n, hv0 n⟩,
{ intro n, simp only [nonneg.mk_mul_mk], },
rw [nnreal.coe_limsup (mul_nonneg hu0 hv0), nnreal.coe_limsup hu0, nnreal.coe_limsup hv0,
← nnreal.coe_mul, nnreal.coe_le_coe, ← ennreal.coe_le_coe, ennreal.coe_mul,
ennreal.coe_limsup (nnreal.bdd_above' _ h_bdd),
ennreal.coe_limsup (nnreal.bdd_above' hu0 hu_bdd),
ennreal.coe_limsup (nnreal.bdd_above' hv0 hv_bdd)],
simp only [pi.mul_apply, hc, ennreal.coe_mul],
obtain ⟨Bu, hBu⟩ := hu_bdd,
obtain ⟨Bv, hBv⟩ := hv_bdd,
simp only [mem_upper_bounds, set.mem_range, forall_exists_index, forall_apply_eq_imp_iff']
at hBu hBv,
have hBu_0 : 0 ≤ Bu := le_trans (hu0 0) (hBu 0),
have hBu' : ∀ (n : ℕ), (⟨u n, hu0 n⟩ : ℝ≥0) ≤ (⟨Bu, hBu_0⟩ : ℝ≥0),
{ simp only [← nnreal.coe_le_coe, nnreal.coe_mk], exact hBu },
have hBv_0 : 0 ≤ Bv := le_trans (hv0 0) (hBv 0),
have hBv' : ∀ (n : ℕ), (⟨v n, hv0 n⟩ : ℝ≥0) ≤ (⟨Bv, hBv_0⟩ : ℝ≥0),
{ simp only [← nnreal.coe_le_coe, nnreal.coe_mk], exact hBv },
simp_rw ← ennreal.coe_le_coe at hBu' hBv',
exact ennreal.limsup_mul_le hBu' hBv',
end
end real |
86bc68da9411c5ab2871a610d1fd6f8180667678 | ed27983dd289b3bcad416f0b1927105d6ef19db8 | /src/inClassNotes/predicate_logic/and.lean | ae06b4df9c832039ffbb7c4cb1a862735255dcfe | [] | no_license | liuxin-James/complogic-s21 | 0d55b76dbe25024473d31d98b5b83655c365f811 | 13e03e0114626643b44015c654151fb651603486 | refs/heads/master | 1,681,109,264,463 | 1,618,848,261,000 | 1,618,848,261,000 | 337,599,491 | 0 | 0 | null | 1,613,141,619,000 | 1,612,925,555,000 | null | UTF-8 | Lean | false | false | 2,141 | lean | /-
The connective, ∧, in predicate as in
propositional logic builds a proposition
that asserts that each of two propositions
is true. Given propositions P, Q, P ∧ Q
is also a proposition, and we judge it to
be true iff we judge P to be true and we
judge Q to be true. We judge P and Q to
be true iff we have evidence that they
are true, in the form of proofs. Our rule
for constructing evidence for P ∧ Q thus
demands evidence for P and evidence for
Q and yields evidence for P ∧ Q.
-/
#check and
/-
structure and (a b : Prop) : Prop :=
intro :: (left : a) (right : b)
-/
-- A polymorphic product type (in Prop)!
axioms (P Q : Prop) (p : P) (q : Q)
example : P := p
example : Q := q
example : P ∧ Q := and.intro p q
lemma paq : P ∧ Q := ⟨ p, q ⟩
#check paq
#reduce paq
#check @and.elim_left
/-
def and.elim_left {a b : Prop} (h : and a b) : a := h.1
def and.elim_right {a b : Prop} (h : and a b) : b := h.2
-/
#reduce and.elim_left paq
#reduce and.elim_right paq
example : 0 = 0 ∧ 1 = 1 :=
and.intro (eq.refl 0) (eq.refl 1) -- stuck
lemma zzoo : 0 = 0 ∧ 1 = 1 :=
and.intro rfl rfl
#reduce zzoo.right
/-
Proof that and commutes and is
associative (you can regroup at
will, by associativity).
-/
example : P ∧ Q → Q ∧ P :=
λ (h : P ∧ Q), and.intro h.right h.left
/-
And is commutative and associative.
Prove it.
-/
axiom R : Prop
lemma and_assoc_forward : (P ∧ Q) ∧ R → P ∧ (Q ∧ R) :=
λ h,
(and.intro
h.left.left
(and.intro h.left.right h.right)
)
/-
Full proof. and commutes
-/
example : P ∧ Q ↔ Q ∧ P :=
-- proof is pair: forward/backward proofs
iff.intro
-- proof forward
(λ h, ⟨ h.right, h.left ⟩)
-- proof backwards
(λ h, ⟨ h.right, h.left ⟩)
/-
Full proof, modulo reverse direction,
that and is associative.
-/
example : (P ∧ Q) ∧ R ↔ P ∧ (Q ∧ R) :=
iff.intro
(and_assoc_forward)
(_)
example : (P ∧ Q) ∧ R ↔ P ∧ (Q ∧ R) :=
iff.intro
(λ h,
(and.intro
h.left.left
(and.intro h.left.right h.right)
))
(λ h,
and.intro
(and.intro
h.left
h.right.left)
h.right.right
) |
050af46c437502ae4671243923ed67fd6f736b9a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/category/Group/colimits.lean | 7853b3466a1d93c927611492e42d1f259d9a88a4 | [
"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,772 | 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 algebra.category.Group.preadditive
import group_theory.quotient_group
import category_theory.limits.shapes.kernels
import category_theory.concrete_category.elementwise
/-!
# The category of additive commutative groups has all colimits.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`.
It is a very uniform approach, that conceivably could be synthesised directly
by a tactic that analyses the shape of `add_comm_group` and `monoid_hom`.
TODO:
In fact, in `AddCommGroup` there is a much nicer model of colimits as quotients
of finitely supported functions, and we really should implement this as well (or instead).
-/
universes u v
open category_theory
open category_theory.limits
-- [ROBOT VOICE]:
-- You should pretend for now that this file was automatically generated.
-- It follows the same template as colimits in Mon.
namespace AddCommGroup.colimits
/-!
We build the colimit of a diagram in `AddCommGroup` by constructing the
free group on the disjoint union of all the abelian groups in the diagram,
then taking the quotient by the abelian group laws within each abelian group,
and the identifications given by the morphisms in the diagram.
-/
variables {J : Type v} [small_category J] (F : J ⥤ AddCommGroup.{v})
/--
An inductive type representing all group expressions (without relations)
on a collection of types indexed by the objects of `J`.
-/
inductive prequotient
-- There's always `of`
| of : Π (j : J) (x : F.obj j), prequotient
-- Then one generator for each operation
| zero : prequotient
| neg : prequotient → prequotient
| add : prequotient → prequotient → prequotient
instance : inhabited (prequotient F) := ⟨prequotient.zero⟩
open prequotient
/--
The relation on `prequotient` saying when two expressions are equal
because of the abelian group laws, or
because one element is mapped to another by a morphism in the diagram.
-/
inductive relation : prequotient F → prequotient F → Prop
-- Make it an equivalence relation:
| refl : Π (x), relation x x
| symm : Π (x y) (h : relation x y), relation y x
| trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z
-- There's always a `map` relation
| map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' (F.map f x)) (of j x)
-- Then one relation per operation, describing the interaction with `of`
| zero : Π (j), relation (of j 0) zero
| neg : Π (j) (x : F.obj j), relation (of j (-x)) (neg (of j x))
| add : Π (j) (x y : F.obj j), relation (of j (x + y)) (add (of j x) (of j y))
-- Then one relation per argument of each operation
| neg_1 : Π (x x') (r : relation x x'), relation (neg x) (neg x')
| add_1 : Π (x x' y) (r : relation x x'), relation (add x y) (add x' y)
| add_2 : Π (x y y') (r : relation y y'), relation (add x y) (add x y')
-- And one relation per axiom
| zero_add : Π (x), relation (add zero x) x
| add_zero : Π (x), relation (add x zero) x
| add_left_neg : Π (x), relation (add (neg x) x) zero
| add_comm : Π (x y), relation (add x y) (add y x)
| add_assoc : Π (x y z), relation (add (add x y) z) (add x (add y z))
/--
The setoid corresponding to group expressions modulo abelian group relations and identifications.
-/
def colimit_setoid : setoid (prequotient F) :=
{ r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ }
attribute [instance] colimit_setoid
/--
The underlying type of the colimit of a diagram in `AddCommGroup`.
-/
@[derive inhabited]
def colimit_type : Type v := quotient (colimit_setoid F)
instance : add_comm_group (colimit_type F) :=
{ zero :=
begin
exact quot.mk _ zero
end,
neg :=
begin
fapply @quot.lift,
{ intro x,
exact quot.mk _ (neg x) },
{ intros x x' r,
apply quot.sound,
exact relation.neg_1 _ _ r },
end,
add :=
begin
fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)),
{ intro x,
fapply @quot.lift,
{ intro y,
exact quot.mk _ (add x y) },
{ intros y y' r,
apply quot.sound,
exact relation.add_2 _ _ _ r } },
{ intros x x' r,
funext y,
induction y,
dsimp,
apply quot.sound,
{ exact relation.add_1 _ _ _ r },
{ refl } },
end,
zero_add := λ x,
begin
induction x,
dsimp,
apply quot.sound,
apply relation.zero_add,
refl,
end,
add_zero := λ x,
begin
induction x,
dsimp,
apply quot.sound,
apply relation.add_zero,
refl,
end,
add_left_neg := λ x,
begin
induction x,
dsimp,
apply quot.sound,
apply relation.add_left_neg,
refl,
end,
add_comm := λ x y,
begin
induction x,
induction y,
dsimp,
apply quot.sound,
apply relation.add_comm,
refl,
refl,
end,
add_assoc := λ x y z,
begin
induction x,
induction y,
induction z,
dsimp,
apply quot.sound,
apply relation.add_assoc,
refl,
refl,
refl,
end, }
@[simp] lemma quot_zero : quot.mk setoid.r zero = (0 : colimit_type F) := rfl
@[simp] lemma quot_neg (x) :
quot.mk setoid.r (neg x) = (-(quot.mk setoid.r x) : colimit_type F) := rfl
@[simp] lemma quot_add (x y) :
quot.mk setoid.r (add x y) = ((quot.mk setoid.r x) + (quot.mk setoid.r y) : colimit_type F) := rfl
/-- The bundled abelian group giving the colimit of a diagram. -/
def colimit : AddCommGroup := AddCommGroup.of (colimit_type F)
/-- The function from a given abelian group in the diagram to the colimit abelian group. -/
def cocone_fun (j : J) (x : F.obj j) : colimit_type F :=
quot.mk _ (of j x)
/-- The group homomorphism from a given abelian group in the diagram to the colimit abelian
group. -/
def cocone_morphism (j : J) : F.obj j ⟶ colimit F :=
{ to_fun := cocone_fun F j,
map_zero' := by apply quot.sound; apply relation.zero,
map_add' := by intros; apply quot.sound; apply relation.add }
@[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') :
F.map f ≫ (cocone_morphism F j') = cocone_morphism F j :=
begin
ext,
apply quot.sound,
apply relation.map,
end
@[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j):
(cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x :=
by { rw ←cocone_naturality F f, refl }
/-- The cocone over the proposed colimit abelian group. -/
def colimit_cocone : cocone F :=
{ X := colimit F,
ι :=
{ app := cocone_morphism F } }.
/-- The function from the free abelian group on the diagram to the cone point of any other
cocone. -/
@[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X
| (of j x) := (s.ι.app j) x
| zero := 0
| (neg x) := -(desc_fun_lift x)
| (add x y) := desc_fun_lift x + desc_fun_lift y
/-- The function from the colimit abelian group to the cone point of any other cocone. -/
def desc_fun (s : cocone F) : colimit_type F → s.X :=
begin
fapply quot.lift,
{ exact desc_fun_lift F s },
{ intros x y r,
induction r; try { dsimp },
-- refl
{ refl },
-- symm
{ exact r_ih.symm },
-- trans
{ exact eq.trans r_ih_h r_ih_k },
-- map
{ simp, },
-- zero
{ simp, },
-- neg
{ simp, },
-- add
{ simp, },
-- neg_1
{ rw r_ih, },
-- add_1
{ rw r_ih, },
-- add_2
{ rw r_ih, },
-- zero_add
{ rw zero_add, },
-- add_zero
{ rw add_zero, },
-- add_left_neg
{ rw add_left_neg, },
-- add_comm
{ rw add_comm, },
-- add_assoc
{ rw add_assoc, } }
end
/-- The group homomorphism from the colimit abelian group to the cone point of any other cocone. -/
def desc_morphism (s : cocone F) : colimit F ⟶ s.X :=
{ to_fun := desc_fun F s,
map_zero' := rfl,
map_add' := λ x y, by { induction x; induction y; refl }, }
/-- Evidence that the proposed colimit is the colimit. -/
def colimit_cocone_is_colimit : is_colimit (colimit_cocone F) :=
{ desc := λ s, desc_morphism F s,
uniq' := λ s m w,
begin
ext,
induction x,
induction x,
{ have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x,
erw w',
refl, },
{ simp *, },
{ simp *, },
{ simp *, },
refl
end }.
instance has_colimits_AddCommGroup : has_colimits AddCommGroup :=
{ has_colimits_of_shape := λ J 𝒥, by exactI
{ has_colimit := λ F, has_colimit.mk
{ cocone := colimit_cocone F,
is_colimit := colimit_cocone_is_colimit F } } }
end AddCommGroup.colimits
namespace AddCommGroup
open quotient_add_group
/--
The categorical cokernel of a morphism in `AddCommGroup`
agrees with the usual group-theoretical quotient.
-/
noncomputable def cokernel_iso_quotient {G H : AddCommGroup.{u}} (f : G ⟶ H) :
cokernel f ≅ AddCommGroup.of (H ⧸ (add_monoid_hom.range f)) :=
{ hom := cokernel.desc f (mk' _)
(by { ext, apply quotient.sound, apply left_rel_apply.mpr, fsplit, exact -x,
simp only [add_zero, add_monoid_hom.map_neg], }),
inv := quotient_add_group.lift _ (cokernel.π f)
(by { intros x H_1, cases H_1, induction H_1_h,
simp only [cokernel.condition_apply, zero_apply]}),
-- obviously can take care of the next goals, but it is really slow
hom_inv_id' := begin
ext1, simp only [coequalizer_as_cokernel, category.comp_id, cokernel.π_desc_assoc], ext1, refl,
end,
inv_hom_id' := begin
ext x : 2,
simp only [add_monoid_hom.coe_comp, function.comp_app, comp_apply, lift_mk,
cokernel.π_desc_apply, mk'_apply, id_apply],
end, }
end AddCommGroup
|
226dfa22abaa0fbffb564ab7025baa83d0a15328 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/category_theory/limits/opposites.lean | e5db4a11ddf339d4f63b0a0cf6274c5648168d6a | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,526 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Floris van Doorn
-/
import category_theory.limits.shapes.finite_products
import category_theory.limits.shapes.kernels
import category_theory.discrete_category
/-!
# Limits in `C` give colimits in `Cᵒᵖ`.
We also give special cases for (co)products,
but not yet for pullbacks / pushouts or for (co)equalizers.
-/
universes v u
noncomputable theory
open category_theory
open category_theory.functor
open opposite
namespace category_theory.limits
variables {C : Type u} [category.{v} C]
variables {J : Type v} [small_category J]
variable (F : J ⥤ Cᵒᵖ)
/--
If `F.left_op : Jᵒᵖ ⥤ C` has a colimit, we can construct a limit for `F : J ⥤ Cᵒᵖ`.
-/
lemma has_limit_of_has_colimit_left_op [has_colimit F.left_op] : has_limit F :=
has_limit.mk
{ cone := cone_of_cocone_left_op (colimit.cocone F.left_op),
is_limit :=
{ lift := λ s, (colimit.desc F.left_op (cocone_left_op_of_cone s)).op,
fac' := λ s j,
begin
rw [cone_of_cocone_left_op_π_app, colimit.cocone_ι, ←op_comp,
colimit.ι_desc, cocone_left_op_of_cone_ι_app, quiver.hom.op_unop],
refl, end,
uniq' := λ s m w,
begin
-- It's a pity we can't do this automatically.
-- Usually something like this would work by limit.hom_ext,
-- but the opposites get in the way of this firing.
have u := (colimit.is_colimit F.left_op).uniq (cocone_left_op_of_cone s) (m.unop),
convert congr_arg (λ f : _ ⟶ _, f.op) (u _), clear u,
intro j,
rw [cocone_left_op_of_cone_ι_app, colimit.cocone_ι],
convert congr_arg (λ f : _ ⟶ _, f.unop) (w (unop j)), clear w,
rw [cone_of_cocone_left_op_π_app, colimit.cocone_ι, quiver.hom.unop_op],
refl,
end } }
/--
If `C` has colimits of shape `Jᵒᵖ`, we can construct limits in `Cᵒᵖ` of shape `J`.
-/
lemma has_limits_of_shape_op_of_has_colimits_of_shape [has_colimits_of_shape Jᵒᵖ C] :
has_limits_of_shape J Cᵒᵖ :=
{ has_limit := λ F, has_limit_of_has_colimit_left_op F }
local attribute [instance] has_limits_of_shape_op_of_has_colimits_of_shape
/--
If `C` has colimits, we can construct limits for `Cᵒᵖ`.
-/
lemma has_limits_op_of_has_colimits [has_colimits C] : has_limits Cᵒᵖ := {}
/--
If `F.left_op : Jᵒᵖ ⥤ C` has a limit, we can construct a colimit for `F : J ⥤ Cᵒᵖ`.
-/
lemma has_colimit_of_has_limit_left_op [has_limit F.left_op] : has_colimit F :=
has_colimit.mk
{ cocone := cocone_of_cone_left_op (limit.cone F.left_op),
is_colimit :=
{ desc := λ s, (limit.lift F.left_op (cone_left_op_of_cocone s)).op,
fac' := λ s j,
begin
rw [cocone_of_cone_left_op_ι_app, limit.cone_π, ←op_comp,
limit.lift_π, cone_left_op_of_cocone_π_app, quiver.hom.op_unop],
refl, end,
uniq' := λ s m w,
begin
have u := (limit.is_limit F.left_op).uniq (cone_left_op_of_cocone s) (m.unop),
convert congr_arg (λ f : _ ⟶ _, f.op) (u _), clear u,
intro j,
rw [cone_left_op_of_cocone_π_app, limit.cone_π],
convert congr_arg (λ f : _ ⟶ _, f.unop) (w (unop j)), clear w,
rw [cocone_of_cone_left_op_ι_app, limit.cone_π, quiver.hom.unop_op],
refl,
end } }
/--
If `C` has colimits of shape `Jᵒᵖ`, we can construct limits in `Cᵒᵖ` of shape `J`.
-/
lemma has_colimits_of_shape_op_of_has_limits_of_shape [has_limits_of_shape Jᵒᵖ C] :
has_colimits_of_shape J Cᵒᵖ :=
{ has_colimit := λ F, has_colimit_of_has_limit_left_op F }
local attribute [instance] has_colimits_of_shape_op_of_has_limits_of_shape
/--
If `C` has limits, we can construct colimits for `Cᵒᵖ`.
-/
lemma has_colimits_op_of_has_limits [has_limits C] : has_colimits Cᵒᵖ := {}
variables (X : Type v)
/--
If `C` has products indexed by `X`, then `Cᵒᵖ` has coproducts indexed by `X`.
-/
lemma has_coproducts_opposite [has_products_of_shape X C] :
has_coproducts_of_shape X Cᵒᵖ :=
begin
haveI : has_limits_of_shape (discrete X)ᵒᵖ C :=
has_limits_of_shape_of_equivalence (discrete.opposite X).symm,
apply_instance
end
/--
If `C` has coproducts indexed by `X`, then `Cᵒᵖ` has products indexed by `X`.
-/
lemma has_products_opposite [has_coproducts_of_shape X C] :
has_products_of_shape X Cᵒᵖ :=
begin
haveI : has_colimits_of_shape (discrete X)ᵒᵖ C :=
has_colimits_of_shape_of_equivalence (discrete.opposite X).symm,
apply_instance
end
lemma has_finite_coproducts_opposite [has_finite_products C] :
has_finite_coproducts Cᵒᵖ :=
{ out := λ J 𝒟 𝒥, begin
resetI,
haveI : has_limits_of_shape (discrete J)ᵒᵖ C :=
has_limits_of_shape_of_equivalence (discrete.opposite J).symm,
apply_instance,
end }
lemma has_finite_products_opposite [has_finite_coproducts C] :
has_finite_products Cᵒᵖ :=
{ out := λ J 𝒟 𝒥, begin
resetI,
haveI : has_colimits_of_shape (discrete J)ᵒᵖ C :=
has_colimits_of_shape_of_equivalence (discrete.opposite J).symm,
apply_instance,
end }
local attribute [instance] fin_category_opposite
lemma has_finite_colimits_opposite [has_finite_limits C] :
has_finite_colimits Cᵒᵖ :=
{ out := λ J 𝒟 𝒥, by { resetI, apply_instance, }, }
lemma has_finite_limits_opposite [has_finite_colimits C] :
has_finite_limits Cᵒᵖ :=
{ out := λ J 𝒟 𝒥, by { resetI, apply_instance, }, }
end category_theory.limits
|
4bc74fb5408357f475e6e37a4af4bd8195b2afe3 | bb31430994044506fa42fd667e2d556327e18dfe | /src/topology/locally_constant/basic.lean | ffae47b95d1ede28eb7ab44d3425aeb974a2a1d0 | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 19,436 | lean | /-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import topology.subset_properties
import topology.connected
import topology.continuous_function.basic
import algebra.indicator_function
import tactic.tfae
import tactic.fin_cases
/-!
# Locally constant functions
This file sets up the theory of locally constant function from a topological space to a type.
## Main definitions and constructions
* `is_locally_constant f` : a map `f : X → Y` where `X` is a topological space is locally
constant if every set in `Y` has an open preimage.
* `locally_constant X Y` : the type of locally constant maps from `X` to `Y`
* `locally_constant.map` : push-forward of locally constant maps
* `locally_constant.comap` : pull-back of locally constant maps
-/
variables {X Y Z α : Type*} [topological_space X]
open set filter
open_locale topological_space
/-- A function between topological spaces is locally constant if the preimage of any set is open. -/
def is_locally_constant (f : X → Y) : Prop := ∀ s : set Y, is_open (f ⁻¹' s)
namespace is_locally_constant
protected lemma tfae (f : X → Y) :
tfae [is_locally_constant f,
∀ x, ∀ᶠ x' in 𝓝 x, f x' = f x,
∀ x, is_open {x' | f x' = f x},
∀ y, is_open (f ⁻¹' {y}),
∀ x, ∃ (U : set X) (hU : is_open U) (hx : x ∈ U), ∀ x' ∈ U, f x' = f x] :=
begin
tfae_have : 1 → 4, from λ h y, h {y},
tfae_have : 4 → 3, from λ h x, h (f x),
tfae_have : 3 → 2, from λ h x, is_open.mem_nhds (h x) rfl,
tfae_have : 2 → 5,
{ intros h x,
rcases mem_nhds_iff.1 (h x) with ⟨U, eq, hU, hx⟩,
exact ⟨U, hU, hx, eq⟩ },
tfae_have : 5 → 1,
{ intros h s,
refine is_open_iff_forall_mem_open.2 (λ x hx, _),
rcases h x with ⟨U, hU, hxU, eq⟩,
exact ⟨U, λ x' hx', mem_preimage.2 $ (eq x' hx').symm ▸ hx, hU, hxU⟩ },
tfae_finish
end
@[nontriviality] lemma of_discrete [discrete_topology X] (f : X → Y) :
is_locally_constant f :=
λ s, is_open_discrete _
lemma is_open_fiber {f : X → Y} (hf : is_locally_constant f) (y : Y) :
is_open {x | f x = y} :=
hf {y}
lemma is_closed_fiber {f : X → Y} (hf : is_locally_constant f) (y : Y) :
is_closed {x | f x = y} :=
⟨hf {y}ᶜ⟩
lemma is_clopen_fiber {f : X → Y} (hf : is_locally_constant f) (y : Y) :
is_clopen {x | f x = y} :=
⟨is_open_fiber hf _, is_closed_fiber hf _⟩
lemma iff_exists_open (f : X → Y) :
is_locally_constant f ↔ ∀ x, ∃ (U : set X) (hU : is_open U) (hx : x ∈ U), ∀ x' ∈ U, f x' = f x :=
(is_locally_constant.tfae f).out 0 4
lemma iff_eventually_eq (f : X → Y) :
is_locally_constant f ↔ ∀ x, ∀ᶠ y in 𝓝 x, f y = f x :=
(is_locally_constant.tfae f).out 0 1
lemma exists_open {f : X → Y} (hf : is_locally_constant f) (x : X) :
∃ (U : set X) (hU : is_open U) (hx : x ∈ U), ∀ x' ∈ U, f x' = f x :=
(iff_exists_open f).1 hf x
protected lemma eventually_eq {f : X → Y} (hf : is_locally_constant f) (x : X) :
∀ᶠ y in 𝓝 x, f y = f x :=
(iff_eventually_eq f).1 hf x
protected lemma continuous [topological_space Y] {f : X → Y} (hf : is_locally_constant f) :
continuous f :=
⟨λ U hU, hf _⟩
lemma iff_continuous {_ : topological_space Y} [discrete_topology Y] (f : X → Y) :
is_locally_constant f ↔ continuous f :=
⟨is_locally_constant.continuous, λ h s, h.is_open_preimage s (is_open_discrete _)⟩
lemma iff_continuous_bot (f : X → Y) :
is_locally_constant f ↔ @continuous X Y _ ⊥ f :=
iff_continuous f
lemma of_constant (f : X → Y) (h : ∀ x y, f x = f y) :
is_locally_constant f :=
(iff_eventually_eq f).2 $ λ x, eventually_of_forall $ λ x', h _ _
lemma const (y : Y) : is_locally_constant (function.const X y) :=
of_constant _ $ λ _ _, rfl
lemma comp {f : X → Y} (hf : is_locally_constant f) (g : Y → Z) :
is_locally_constant (g ∘ f) :=
λ s, by { rw set.preimage_comp, exact hf _ }
lemma prod_mk {Y'} {f : X → Y} {f' : X → Y'} (hf : is_locally_constant f)
(hf' : is_locally_constant f') :
is_locally_constant (λ x, (f x, f' x)) :=
(iff_eventually_eq _).2 $ λ x, (hf.eventually_eq x).mp $ (hf'.eventually_eq x).mono $
λ x' hf' hf, prod.ext hf hf'
lemma comp₂ {Y₁ Y₂ Z : Type*} {f : X → Y₁} {g : X → Y₂}
(hf : is_locally_constant f) (hg : is_locally_constant g) (h : Y₁ → Y₂ → Z) :
is_locally_constant (λ x, h (f x) (g x)) :=
(hf.prod_mk hg).comp (λ x : Y₁ × Y₂, h x.1 x.2)
lemma comp_continuous [topological_space Y] {g : Y → Z} {f : X → Y}
(hg : is_locally_constant g) (hf : continuous f) :
is_locally_constant (g ∘ f) :=
λ s, by { rw set.preimage_comp, exact hf.is_open_preimage _ (hg _) }
/-- A locally constant function is constant on any preconnected set. -/
lemma apply_eq_of_is_preconnected {f : X → Y} (hf : is_locally_constant f)
{s : set X} (hs : is_preconnected s) {x y : X} (hx : x ∈ s) (hy : y ∈ s) :
f x = f y :=
begin
let U := f ⁻¹' {f y},
suffices : x ∉ Uᶜ, from not_not.1 this,
intro hxV,
specialize hs U Uᶜ (hf {f y}) (hf {f y}ᶜ) _ ⟨y, ⟨hy, rfl⟩⟩ ⟨x, ⟨hx, hxV⟩⟩,
{ simp only [union_compl_self, subset_univ] },
{ simpa only [inter_empty, not_nonempty_empty, inter_compl_self] using hs }
end
lemma apply_eq_of_preconnected_space [preconnected_space X]
{f : X → Y} (hf : is_locally_constant f) (x y : X) :
f x = f y :=
hf.apply_eq_of_is_preconnected is_preconnected_univ trivial trivial
lemma eq_const [preconnected_space X] {f : X → Y} (hf : is_locally_constant f) (x : X) :
f = function.const X (f x) :=
funext $ λ y, hf.apply_eq_of_preconnected_space y x
lemma exists_eq_const [preconnected_space X] [nonempty Y] {f : X → Y} (hf : is_locally_constant f) :
∃ y, f = function.const X y :=
begin
casesI is_empty_or_nonempty X,
{ exact ⟨classical.arbitrary Y, funext $ h.elim⟩ },
{ exact ⟨f (classical.arbitrary X), hf.eq_const _⟩ },
end
lemma iff_is_const [preconnected_space X] {f : X → Y} :
is_locally_constant f ↔ ∀ x y, f x = f y :=
⟨λ h x y, h.apply_eq_of_is_preconnected is_preconnected_univ trivial trivial, of_constant _⟩
lemma range_finite [compact_space X] {f : X → Y} (hf : is_locally_constant f) :
(set.range f).finite :=
begin
letI : topological_space Y := ⊥,
haveI : discrete_topology Y := ⟨rfl⟩,
rw @iff_continuous X Y ‹_› ‹_› at hf,
exact (is_compact_range hf).finite_of_discrete
end
@[to_additive] lemma one [has_one Y] : is_locally_constant (1 : X → Y) := const 1
@[to_additive] lemma inv [has_inv Y] ⦃f : X → Y⦄ (hf : is_locally_constant f) :
is_locally_constant f⁻¹ :=
hf.comp (λ x, x⁻¹)
@[to_additive]
lemma mul [has_mul Y] ⦃f g : X → Y⦄ (hf : is_locally_constant f) (hg : is_locally_constant g) :
is_locally_constant (f * g) :=
hf.comp₂ hg (*)
@[to_additive]
lemma div [has_div Y] ⦃f g : X → Y⦄ (hf : is_locally_constant f) (hg : is_locally_constant g) :
is_locally_constant (f / g) :=
hf.comp₂ hg (/)
/-- If a composition of a function `f` followed by an injection `g` is locally
constant, then the locally constant property descends to `f`. -/
lemma desc {α β : Type*} (f : X → α) (g : α → β)
(h : is_locally_constant (g ∘ f)) (inj : function.injective g) : is_locally_constant f :=
begin
rw (is_locally_constant.tfae f).out 0 3,
intros a,
have : f ⁻¹' {a} = (g ∘ f) ⁻¹' { g a },
{ ext x,
simp only [mem_singleton_iff, function.comp_app, mem_preimage],
exact ⟨λ h, by rw h, λ h, inj h⟩ },
rw this,
apply h,
end
lemma of_constant_on_connected_components [locally_connected_space X] {f : X → Y}
(h : ∀ x, ∀ y ∈ connected_component x, f y = f x) :
is_locally_constant f :=
begin
rw iff_exists_open,
exact λ x, ⟨connected_component x, is_open_connected_component, mem_connected_component, h x⟩,
end
lemma of_constant_on_preconnected_clopens [locally_connected_space X] {f : X → Y}
(h : ∀ U : set X, is_preconnected U → is_clopen U → ∀ x ∈ U, ∀ y ∈ U, f y = f x) :
is_locally_constant f :=
of_constant_on_connected_components (λ x, h (connected_component x)
is_preconnected_connected_component is_clopen_connected_component x mem_connected_component)
end is_locally_constant
/-- A (bundled) locally constant function from a topological space `X` to a type `Y`. -/
structure locally_constant (X Y : Type*) [topological_space X] :=
(to_fun : X → Y)
(is_locally_constant : is_locally_constant to_fun)
namespace locally_constant
instance [inhabited Y] : inhabited (locally_constant X Y) :=
⟨⟨_, is_locally_constant.const default⟩⟩
instance : has_coe_to_fun (locally_constant X Y) (λ _, X → Y) := ⟨locally_constant.to_fun⟩
initialize_simps_projections locally_constant (to_fun → apply)
@[simp] lemma to_fun_eq_coe (f : locally_constant X Y) : f.to_fun = f := rfl
@[simp] lemma coe_mk (f : X → Y) (h) : ⇑(⟨f, h⟩ : locally_constant X Y) = f := rfl
theorem congr_fun {f g : locally_constant X Y} (h : f = g) (x : X) : f x = g x :=
congr_arg (λ h : locally_constant X Y, h x) h
theorem congr_arg (f : locally_constant X Y) {x y : X} (h : x = y) : f x = f y :=
congr_arg (λ x : X, f x) h
theorem coe_injective : @function.injective (locally_constant X Y) (X → Y) coe_fn
| ⟨f, hf⟩ ⟨g, hg⟩ h := have f = g, from h, by subst f
@[simp, norm_cast] theorem coe_inj {f g : locally_constant X Y} : (f : X → Y) = g ↔ f = g :=
coe_injective.eq_iff
@[ext] theorem ext ⦃f g : locally_constant X Y⦄ (h : ∀ x, f x = g x) : f = g :=
coe_injective (funext h)
theorem ext_iff {f g : locally_constant X Y} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, ext h⟩
section codomain_topological_space
variables [topological_space Y] (f : locally_constant X Y)
protected lemma continuous : continuous f := f.is_locally_constant.continuous
/-- We can turn a locally-constant function into a bundled `continuous_map`. -/
def to_continuous_map : C(X, Y) := ⟨f, f.continuous⟩
/-- As a shorthand, `locally_constant.to_continuous_map` is available as a coercion -/
instance : has_coe (locally_constant X Y) C(X, Y) := ⟨to_continuous_map⟩
@[simp] lemma to_continuous_map_eq_coe : f.to_continuous_map = f := rfl
@[simp] lemma coe_continuous_map : ((f : C(X, Y)) : X → Y) = (f : X → Y) := rfl
lemma to_continuous_map_injective :
function.injective (to_continuous_map : locally_constant X Y → C(X, Y)) :=
λ _ _ h, ext (continuous_map.congr_fun h)
end codomain_topological_space
/-- The constant locally constant function on `X` with value `y : Y`. -/
def const (X : Type*) {Y : Type*} [topological_space X] (y : Y) :
locally_constant X Y :=
⟨function.const X y, is_locally_constant.const _⟩
@[simp] lemma coe_const (y : Y) : (const X y : X → Y) = function.const X y := rfl
/-- The locally constant function to `fin 2` associated to a clopen set. -/
def of_clopen {X : Type*} [topological_space X] {U : set X} [∀ x, decidable (x ∈ U)]
(hU : is_clopen U) : locally_constant X (fin 2) :=
{ to_fun := λ x, if x ∈ U then 0 else 1,
is_locally_constant := begin
rw (is_locally_constant.tfae (λ x, if x ∈ U then (0 : fin 2) else 1)).out 0 3,
intros e,
fin_cases e,
{ convert hU.1 using 1,
ext,
simp only [mem_singleton_iff, fin.one_eq_zero_iff, mem_preimage, ite_eq_left_iff,
nat.succ_succ_ne_one],
tauto },
{ rw ← is_closed_compl_iff,
convert hU.2,
ext,
simp }
end }
@[simp] lemma of_clopen_fiber_zero {X : Type*} [topological_space X] {U : set X}
[∀ x, decidable (x ∈ U)] (hU : is_clopen U) : of_clopen hU ⁻¹' ({0} : set (fin 2)) = U :=
begin
ext,
simp only [of_clopen, mem_singleton_iff, fin.one_eq_zero_iff, coe_mk, mem_preimage,
ite_eq_left_iff, nat.succ_succ_ne_one],
tauto,
end
@[simp] lemma of_clopen_fiber_one {X : Type*} [topological_space X] {U : set X}
[∀ x, decidable (x ∈ U)] (hU : is_clopen U) : of_clopen hU ⁻¹' ({1} : set (fin 2)) = Uᶜ :=
begin
ext,
simp only [of_clopen, mem_singleton_iff, coe_mk, fin.zero_eq_one_iff, mem_preimage,
ite_eq_right_iff, mem_compl_iff, nat.succ_succ_ne_one],
tauto,
end
lemma locally_constant_eq_of_fiber_zero_eq {X : Type*} [topological_space X]
(f g : locally_constant X (fin 2)) (h : f ⁻¹' ({0} : set (fin 2)) = g ⁻¹' {0}) : f = g :=
begin
simp only [set.ext_iff, mem_singleton_iff, mem_preimage] at h,
ext1 x,
exact fin.fin_two_eq_of_eq_zero_iff (h x)
end
lemma range_finite [compact_space X] (f : locally_constant X Y) :
(set.range f).finite :=
f.is_locally_constant.range_finite
lemma apply_eq_of_is_preconnected (f : locally_constant X Y) {s : set X} (hs : is_preconnected s)
{x y : X} (hx : x ∈ s) (hy : y ∈ s) :
f x = f y :=
f.is_locally_constant.apply_eq_of_is_preconnected hs hx hy
lemma apply_eq_of_preconnected_space [preconnected_space X] (f : locally_constant X Y) (x y : X) :
f x = f y :=
f.is_locally_constant.apply_eq_of_is_preconnected is_preconnected_univ trivial trivial
lemma eq_const [preconnected_space X] (f : locally_constant X Y) (x : X) :
f = const X (f x) :=
ext $ λ y, apply_eq_of_preconnected_space f _ _
lemma exists_eq_const [preconnected_space X] [nonempty Y] (f : locally_constant X Y) :
∃ y, f = const X y :=
begin
rcases classical.em (nonempty X) with ⟨⟨x⟩⟩|hX,
{ exact ⟨f x, f.eq_const x⟩ },
{ exact ⟨classical.arbitrary Y, ext $ λ x, (hX ⟨x⟩).elim⟩ }
end
/-- Push forward of locally constant maps under any map, by post-composition. -/
def map (f : Y → Z) : locally_constant X Y → locally_constant X Z :=
λ g, ⟨f ∘ g, λ s, by { rw set.preimage_comp, apply g.is_locally_constant }⟩
@[simp] lemma map_apply (f : Y → Z) (g : locally_constant X Y) : ⇑(map f g) = f ∘ g := rfl
@[simp] lemma map_id : @map X Y Y _ id = id := by { ext, refl }
@[simp] lemma map_comp {Y₁ Y₂ Y₃ : Type*} (g : Y₂ → Y₃) (f : Y₁ → Y₂) :
@map X _ _ _ g ∘ map f = map (g ∘ f) := by { ext, refl }
/-- Given a locally constant function to `α → β`, construct a family of locally constant
functions with values in β indexed by α. -/
def flip {X α β : Type*} [topological_space X] (f : locally_constant X (α → β)) (a : α) :
locally_constant X β := f.map (λ f, f a)
/-- If α is finite, this constructs a locally constant function to `α → β` given a
family of locally constant functions with values in β indexed by α. -/
def unflip {X α β : Type*} [fintype α] [topological_space X] (f : α → locally_constant X β) :
locally_constant X (α → β) :=
{ to_fun := λ x a, f a x,
is_locally_constant := begin
rw (is_locally_constant.tfae (λ x a, f a x)).out 0 3,
intros g,
have : (λ (x : X) (a : α), f a x) ⁻¹' {g} = ⋂ (a : α), (f a) ⁻¹' {g a}, by tidy,
rw this,
apply is_open_Inter,
intros a,
apply (f a).is_locally_constant,
end }
@[simp]
lemma unflip_flip {X α β : Type*} [fintype α] [topological_space X]
(f : locally_constant X (α → β)) : unflip f.flip = f := by { ext, refl }
@[simp]
lemma flip_unflip {X α β : Type*} [fintype α] [topological_space X]
(f : α → locally_constant X β) : (unflip f).flip = f := by { ext, refl }
section comap
open_locale classical
variables [topological_space Y]
/-- Pull back of locally constant maps under any map, by pre-composition.
This definition only makes sense if `f` is continuous,
in which case it sends locally constant functions to their precomposition with `f`.
See also `locally_constant.coe_comap`. -/
noncomputable
def comap (f : X → Y) :
locally_constant Y Z → locally_constant X Z :=
if hf : continuous f
then λ g, ⟨g ∘ f, g.is_locally_constant.comp_continuous hf⟩
else
begin
by_cases H : nonempty X,
{ introsI g, exact const X (g $ f $ classical.arbitrary X) },
{ intro g, refine ⟨λ x, (H ⟨x⟩).elim, _⟩,
intro s, rw is_open_iff_nhds, intro x, exact (H ⟨x⟩).elim }
end
@[simp] lemma coe_comap (f : X → Y) (g : locally_constant Y Z) (hf : continuous f) :
⇑(comap f g) = g ∘ f :=
by { rw [comap, dif_pos hf], refl }
@[simp] lemma comap_id : @comap X X Z _ _ id = id :=
by { ext, simp only [continuous_id, id.def, function.comp.right_id, coe_comap] }
lemma comap_comp [topological_space Z]
(f : X → Y) (g : Y → Z) (hf : continuous f) (hg : continuous g) :
@comap _ _ α _ _ f ∘ comap g = comap (g ∘ f) :=
by { ext, simp only [hf, hg, hg.comp hf, coe_comap] }
lemma comap_const (f : X → Y) (y : Y) (h : ∀ x, f x = y) :
(comap f : locally_constant Y Z → locally_constant X Z) =
λ g, ⟨λ x, g y, is_locally_constant.const _⟩ :=
begin
ext, rw coe_comap,
{ simp only [h, coe_mk, function.comp_app] },
{ rw show f = λ x, y, by ext; apply h,
exact continuous_const }
end
end comap
section desc
/-- If a locally constant function factors through an injection, then it factors through a locally
constant function. -/
def desc {X α β : Type*} [topological_space X] {g : α → β} (f : X → α) (h : locally_constant X β)
(cond : g ∘ f = h) (inj : function.injective g) : locally_constant X α :=
{ to_fun := f,
is_locally_constant := is_locally_constant.desc _ g (by { rw cond, exact h.2 }) inj }
@[simp]
lemma coe_desc {X α β : Type*} [topological_space X] (f : X → α) (g : α → β)
(h : locally_constant X β) (cond : g ∘ f = h) (inj : function.injective g) :
⇑(desc f h cond inj) = f := rfl
end desc
section indicator
variables {R : Type*} [has_one R] {U : set X} (f : locally_constant X R)
open_locale classical
/-- Given a clopen set `U` and a locally constant function `f`, `locally_constant.mul_indicator`
returns the locally constant function that is `f` on `U` and `1` otherwise. -/
@[to_additive /-" Given a clopen set `U` and a locally constant function `f`,
`locally_constant.indicator` returns the locally constant function that is `f` on `U` and `0`
otherwise. "-/, simps]
noncomputable def mul_indicator (hU : is_clopen U) :
locally_constant X R :=
{ to_fun := set.mul_indicator U f,
is_locally_constant :=
begin
rw is_locally_constant.iff_exists_open, rintros x,
obtain ⟨V, hV, hx, h'⟩ := (is_locally_constant.iff_exists_open _).1 f.is_locally_constant x,
by_cases x ∈ U,
{ refine ⟨U ∩ V, is_open.inter hU.1 hV, set.mem_inter h hx, _⟩, rintros y hy,
rw set.mem_inter_iff at hy, rw [set.mul_indicator_of_mem hy.1, set.mul_indicator_of_mem h],
apply h' y hy.2, },
{ rw ←set.mem_compl_iff at h, refine ⟨Uᶜ, (is_clopen.compl hU).1, h, _⟩,
rintros y hy, rw set.mem_compl_iff at h, rw set.mem_compl_iff at hy,
simp [h, hy], },
end, }
variables (a : X)
@[to_additive]
theorem mul_indicator_apply_eq_if (hU : is_clopen U) :
mul_indicator f hU a = if a ∈ U then f a else 1 :=
set.mul_indicator_apply U f a
variables {a}
@[to_additive]
theorem mul_indicator_of_mem (hU : is_clopen U) (h : a ∈ U) : f.mul_indicator hU a = f a :=
by{ rw mul_indicator_apply, apply set.mul_indicator_of_mem h, }
@[to_additive]
theorem mul_indicator_of_not_mem (hU : is_clopen U) (h : a ∉ U) : f.mul_indicator hU a = 1 :=
by{ rw mul_indicator_apply, apply set.mul_indicator_of_not_mem h, }
end indicator
end locally_constant
|
695c7efc8358c2228bc476b1279511212adec0dd | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/set_theory/cardinal_ordinal.lean | 3b4e1176c6d97f3f10f078388227ff343ef7dc2f | [
"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 | 38,740 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Floris van Doorn
-/
import set_theory.ordinal_arithmetic
import tactic.linarith
import logic.small
/-!
# Cardinals and ordinals
Relationships between cardinals and ordinals, properties of cardinals that are proved
using ordinals.
## Main definitions
* The function `cardinal.aleph'` gives the cardinals listed by their ordinal
index, and is the inverse of `cardinal.aleph_idx`.
`aleph' n = n`, `aleph' ω = cardinal.omega = ℵ₀`, `aleph' (ω + 1) = ℵ₁`, etc.
It is an order isomorphism between ordinals and cardinals.
* The function `cardinal.aleph` gives the infinite cardinals listed by their
ordinal index. `aleph 0 = cardinal.omega = ℵ₀`, `aleph 1 = ℵ₁` is the first
uncountable cardinal, and so on.
## Main Statements
* `cardinal.mul_eq_max` and `cardinal.add_eq_max` state that the product (resp. sum) of two infinite
cardinals is just their maximum. Several variations around this fact are also given.
* `cardinal.mk_list_eq_mk` : when `α` is infinite, `α` and `list α` have the same cardinality.
* simp lemmas for inequalities between `bit0 a` and `bit1 b` are registered, making `simp`
able to prove inequalities about numeral cardinals.
## Tags
cardinal arithmetic (for infinite cardinals)
-/
noncomputable theory
open function cardinal set equiv
open_locale classical cardinal
universes u v w
namespace cardinal
section using_ordinals
open ordinal
theorem ord_is_limit {c} (co : ω ≤ c) : (ord c).is_limit :=
begin
refine ⟨λ h, omega_ne_zero _, λ a, lt_imp_lt_of_le_imp_le _⟩,
{ rw [← ordinal.le_zero, ord_le] at h,
simpa only [card_zero, nonpos_iff_eq_zero] using le_trans co h },
{ intro h, rw [ord_le] at h ⊢,
rwa [← @add_one_of_omega_le (card a), ← card_succ],
rw [← ord_le, ← le_succ_of_is_limit, ord_le],
{ exact le_trans co h },
{ rw ord_omega, exact omega_is_limit } }
end
/-- The `aleph'` index function, which gives the ordinal index of a cardinal.
(The `aleph'` part is because unlike `aleph` this counts also the
finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`,
`aleph_idx ℵ₁ = ω + 1` and so on.)
In this definition, we register additionally that this function is an initial segment,
i.e., it is order preserving and its range is an initial segment of the ordinals.
For the basic function version, see `aleph_idx`.
For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/
def aleph_idx.initial_seg : @initial_seg cardinal ordinal (<) (<) :=
@rel_embedding.collapse cardinal ordinal (<) (<) _ cardinal.ord.order_embedding.lt_embedding
/-- The `aleph'` index function, which gives the ordinal index of a cardinal.
(The `aleph'` part is because unlike `aleph` this counts also the
finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`,
`aleph_idx ℵ₁ = ω + 1` and so on.)
For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/
def aleph_idx : cardinal → ordinal := aleph_idx.initial_seg
@[simp] theorem aleph_idx.initial_seg_coe :
(aleph_idx.initial_seg : cardinal → ordinal) = aleph_idx := rfl
@[simp] theorem aleph_idx_lt {a b} : aleph_idx a < aleph_idx b ↔ a < b :=
aleph_idx.initial_seg.to_rel_embedding.map_rel_iff
@[simp] theorem aleph_idx_le {a b} : aleph_idx a ≤ aleph_idx b ↔ a ≤ b :=
by rw [← not_lt, ← not_lt, aleph_idx_lt]
theorem aleph_idx.init {a b} : b < aleph_idx a → ∃ c, aleph_idx c = b :=
aleph_idx.initial_seg.init _ _
/-- The `aleph'` index function, which gives the ordinal index of a cardinal.
(The `aleph'` part is because unlike `aleph` this counts also the
finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`,
`aleph_idx ℵ₁ = ω + 1` and so on.)
In this version, we register additionally that this function is an order isomorphism
between cardinals and ordinals.
For the basic function version, see `aleph_idx`. -/
def aleph_idx.rel_iso : @rel_iso cardinal.{u} ordinal.{u} (<) (<) :=
@rel_iso.of_surjective cardinal.{u} ordinal.{u} (<) (<) aleph_idx.initial_seg.{u} $
(initial_seg.eq_or_principal aleph_idx.initial_seg.{u}).resolve_right $
λ ⟨o, e⟩, begin
have : ∀ c, aleph_idx c < o := λ c, (e _).2 ⟨_, rfl⟩,
refine ordinal.induction_on o _ this, introsI α r _ h,
let s := sup.{u u} (λ a:α, inv_fun aleph_idx (ordinal.typein r a)),
apply not_le_of_gt (lt_succ_self s),
have I : injective aleph_idx := aleph_idx.initial_seg.to_embedding.injective,
simpa only [typein_enum, left_inverse_inv_fun I (succ s)] using
le_sup.{u u} (λ a, inv_fun aleph_idx (ordinal.typein r a))
(ordinal.enum r _ (h (succ s))),
end
@[simp] theorem aleph_idx.rel_iso_coe :
(aleph_idx.rel_iso : cardinal → ordinal) = aleph_idx := rfl
@[simp] theorem type_cardinal : @ordinal.type cardinal (<) _ = ordinal.univ.{u (u+1)} :=
by rw ordinal.univ_id; exact quotient.sound ⟨aleph_idx.rel_iso⟩
@[simp] theorem mk_cardinal : #cardinal = univ.{u (u+1)} :=
by simpa only [card_type, card_univ] using congr_arg card type_cardinal
/-- The `aleph'` function gives the cardinals listed by their ordinal
index, and is the inverse of `aleph_idx`.
`aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc.
In this version, we register additionally that this function is an order isomorphism
between ordinals and cardinals.
For the basic function version, see `aleph'`. -/
def aleph'.rel_iso := cardinal.aleph_idx.rel_iso.symm
/-- The `aleph'` function gives the cardinals listed by their ordinal
index, and is the inverse of `aleph_idx`.
`aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. -/
def aleph' : ordinal → cardinal := aleph'.rel_iso
@[simp] theorem aleph'.rel_iso_coe :
(aleph'.rel_iso : ordinal → cardinal) = aleph' := rfl
@[simp] theorem aleph'_lt {o₁ o₂ : ordinal.{u}} : aleph' o₁ < aleph' o₂ ↔ o₁ < o₂ :=
aleph'.rel_iso.map_rel_iff
@[simp] theorem aleph'_le {o₁ o₂ : ordinal.{u}} : aleph' o₁ ≤ aleph' o₂ ↔ o₁ ≤ o₂ :=
le_iff_le_iff_lt_iff_lt.2 aleph'_lt
@[simp] theorem aleph'_aleph_idx (c : cardinal.{u}) : aleph' c.aleph_idx = c :=
cardinal.aleph_idx.rel_iso.to_equiv.symm_apply_apply c
@[simp] theorem aleph_idx_aleph' (o : ordinal.{u}) : (aleph' o).aleph_idx = o :=
cardinal.aleph_idx.rel_iso.to_equiv.apply_symm_apply o
@[simp] theorem aleph'_zero : aleph' 0 = 0 :=
by rw [← nonpos_iff_eq_zero, ← aleph'_aleph_idx 0, aleph'_le];
apply ordinal.zero_le
@[simp] theorem aleph'_succ {o : ordinal.{u}} : aleph' o.succ = (aleph' o).succ :=
le_antisymm
(cardinal.aleph_idx_le.1 $
by rw [aleph_idx_aleph', ordinal.succ_le, ← aleph'_lt, aleph'_aleph_idx];
apply cardinal.lt_succ_self)
(cardinal.succ_le.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _)
@[simp] theorem aleph'_nat : ∀ n : ℕ, aleph' n = n
| 0 := aleph'_zero
| (n+1) := show aleph' (ordinal.succ n) = n.succ,
by rw [aleph'_succ, aleph'_nat, nat_succ]
theorem aleph'_le_of_limit {o : ordinal.{u}} (l : o.is_limit) {c} :
aleph' o ≤ c ↔ ∀ o' < o, aleph' o' ≤ c :=
⟨λ h o' h', le_trans (aleph'_le.2 $ le_of_lt h') h,
λ h, begin
rw [← aleph'_aleph_idx c, aleph'_le, ordinal.limit_le l],
intros x h',
rw [← aleph'_le, aleph'_aleph_idx],
exact h _ h'
end⟩
@[simp] theorem aleph'_omega : aleph' ordinal.omega = ω :=
eq_of_forall_ge_iff $ λ c, begin
simp only [aleph'_le_of_limit omega_is_limit, ordinal.lt_omega, exists_imp_distrib, omega_le],
exact forall_swap.trans (forall_congr $ λ n, by simp only [forall_eq, aleph'_nat]),
end
/-- `aleph'` and `aleph_idx` form an equivalence between `ordinal` and `cardinal` -/
@[simp] def aleph'_equiv : ordinal ≃ cardinal :=
⟨aleph', aleph_idx, aleph_idx_aleph', aleph'_aleph_idx⟩
/-- The `aleph` function gives the infinite cardinals listed by their
ordinal index. `aleph 0 = ω`, `aleph 1 = succ ω` is the first
uncountable cardinal, and so on. -/
def aleph (o : ordinal) : cardinal := aleph' (ordinal.omega + o)
@[simp] theorem aleph_lt {o₁ o₂ : ordinal.{u}} : aleph o₁ < aleph o₂ ↔ o₁ < o₂ :=
aleph'_lt.trans (ordinal.add_lt_add_iff_left _)
@[simp] theorem aleph_le {o₁ o₂ : ordinal.{u}} : aleph o₁ ≤ aleph o₂ ↔ o₁ ≤ o₂ :=
le_iff_le_iff_lt_iff_lt.2 aleph_lt
@[simp] theorem aleph_succ {o : ordinal.{u}} : aleph o.succ = (aleph o).succ :=
by rw [aleph, ordinal.add_succ, aleph'_succ]; refl
@[simp] theorem aleph_zero : aleph 0 = ω :=
by simp only [aleph, add_zero, aleph'_omega]
theorem omega_le_aleph' {o : ordinal} : ω ≤ aleph' o ↔ ordinal.omega ≤ o :=
by rw [← aleph'_omega, aleph'_le]
theorem omega_le_aleph (o : ordinal) : ω ≤ aleph o :=
by rw [aleph, omega_le_aleph']; apply ordinal.le_add_right
theorem ord_aleph_is_limit (o : ordinal) : is_limit (aleph o).ord :=
ord_is_limit $ omega_le_aleph _
theorem exists_aleph {c : cardinal} : ω ≤ c ↔ ∃ o, c = aleph o :=
⟨λ h, ⟨aleph_idx c - ordinal.omega,
by rw [aleph, ordinal.add_sub_cancel_of_le, aleph'_aleph_idx];
rwa [← omega_le_aleph', aleph'_aleph_idx]⟩,
λ ⟨o, e⟩, e.symm ▸ omega_le_aleph _⟩
theorem aleph'_is_normal : is_normal (ord ∘ aleph') :=
⟨λ o, ord_lt_ord.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _,
λ o l a, by simp only [ord_le, aleph'_le_of_limit l]⟩
theorem aleph_is_normal : is_normal (ord ∘ aleph) :=
aleph'_is_normal.trans $ add_is_normal ordinal.omega
theorem succ_omega : succ ω = aleph 1 :=
by rw [← aleph_zero, ← aleph_succ, ordinal.succ_zero]
lemma countable_iff_lt_aleph_one {α : Type*} (s : set α) : countable s ↔ #s < aleph 1 :=
by rw [← succ_omega, lt_succ, mk_set_le_omega]
/-! ### Properties of `mul` -/
/-- If `α` is an infinite type, then `α × α` and `α` have the same cardinality. -/
theorem mul_eq_self {c : cardinal} (h : ω ≤ c) : c * c = c :=
begin
refine le_antisymm _
(by simpa only [mul_one] using
mul_le_mul_left' (one_lt_omega.le.trans h) c),
-- the only nontrivial part is `c * c ≤ c`. We prove it inductively.
refine acc.rec_on (cardinal.wf.apply c) (λ c _,
quotient.induction_on c $ λ α IH ol, _) h,
-- consider the minimal well-order `r` on `α` (a type with cardinality `c`).
rcases ord_eq α with ⟨r, wo, e⟩, resetI,
letI := linear_order_of_STO' r,
haveI : is_well_order α (<) := wo,
-- Define an order `s` on `α × α` by writing `(a, b) < (c, d)` if `max a b < max c d`, or
-- the max are equal and `a < c`, or the max are equal and `a = c` and `b < d`.
let g : α × α → α := λ p, max p.1 p.2,
let f : α × α ↪ ordinal × (α × α) :=
⟨λ p:α×α, (typein (<) (g p), p), λ p q, congr_arg prod.snd⟩,
let s := f ⁻¹'o (prod.lex (<) (prod.lex (<) (<))),
-- this is a well order on `α × α`.
haveI : is_well_order _ s := (rel_embedding.preimage _ _).is_well_order,
/- it suffices to show that this well order is smaller than `r`
if it were larger, then `r` would be a strict prefix of `s`. It would be contained in
`β × β` for some `β` of cardinality `< c`. By the inductive assumption, this set has the
same cardinality as `β` (or it is finite if `β` is finite), so it is `< c`, which is a
contradiction. -/
suffices : type s ≤ type r, {exact card_le_card this},
refine le_of_forall_lt (λ o h, _),
rcases typein_surj s h with ⟨p, rfl⟩,
rw [← e, lt_ord],
refine lt_of_le_of_lt (_ : _ ≤ card (typein (<) (g p)).succ * card (typein (<) (g p)).succ) _,
{ have : {q|s q p} ⊆ (insert (g p) {x | x < (g p)}).prod (insert (g p) {x | x < (g p)}),
{ intros q h,
simp only [s, embedding.coe_fn_mk, order.preimage, typein_lt_typein, prod.lex_def, typein_inj]
at h,
exact max_le_iff.1 (le_iff_lt_or_eq.2 $ h.imp_right and.left) },
suffices H : (insert (g p) {x | r x (g p)} : set α) ≃ ({x | r x (g p)} ⊕ punit),
{ exact ⟨(set.embedding_of_subset _ _ this).trans
((equiv.set.prod _ _).trans (H.prod_congr H)).to_embedding⟩ },
refine (equiv.set.insert _).trans
((equiv.refl _).sum_congr punit_equiv_punit),
apply @irrefl _ r },
cases lt_or_le (card (typein (<) (g p)).succ) ω with qo qo,
{ exact lt_of_lt_of_le (mul_lt_omega qo qo) ol },
{ suffices, {exact lt_of_le_of_lt (IH _ this qo) this},
rw ← lt_ord, apply (ord_is_limit ol).2,
rw [mk_def, e], apply typein_lt_type }
end
end using_ordinals
/-- If `α` and `β` are infinite types, then the cardinality of `α × β` is the maximum
of the cardinalities of `α` and `β`. -/
theorem mul_eq_max {a b : cardinal} (ha : ω ≤ a) (hb : ω ≤ b) : a * b = max a b :=
le_antisymm
(mul_eq_self (le_trans ha (le_max_left a b)) ▸
mul_le_mul' (le_max_left _ _) (le_max_right _ _)) $
max_le
(by simpa only [mul_one] using
mul_le_mul_left' (one_lt_omega.le.trans hb) a)
(by simpa only [one_mul] using
mul_le_mul_right' (one_lt_omega.le.trans ha) b)
@[simp] theorem omega_mul_eq {a : cardinal} (ha : ω ≤ a) : ω * a = a :=
(mul_eq_max le_rfl ha).trans (max_eq_right ha)
@[simp] theorem mul_omega_eq {a : cardinal} (ha : ω ≤ a) : a * ω = a :=
(mul_eq_max ha le_rfl).trans (max_eq_left ha)
theorem mul_lt_of_lt {a b c : cardinal} (hc : ω ≤ c)
(h1 : a < c) (h2 : b < c) : a * b < c :=
lt_of_le_of_lt (mul_le_mul' (le_max_left a b) (le_max_right a b)) $
(lt_or_le (max a b) ω).elim
(λ h, lt_of_lt_of_le (mul_lt_omega h h) hc)
(λ h, by rw mul_eq_self h; exact max_lt h1 h2)
lemma mul_le_max_of_omega_le_left {a b : cardinal} (h : ω ≤ a) : a * b ≤ max a b :=
begin
convert mul_le_mul' (le_max_left a b) (le_max_right a b),
rw [mul_eq_self],
refine le_trans h (le_max_left a b)
end
lemma mul_eq_max_of_omega_le_left {a b : cardinal} (h : ω ≤ a) (h' : b ≠ 0) : a * b = max a b :=
begin
apply le_antisymm, apply mul_le_max_of_omega_le_left h,
cases le_or_gt ω b with hb hb, rw [mul_eq_max h hb],
have : b ≤ a, exact le_trans (le_of_lt hb) h,
rw [max_eq_left this],
convert mul_le_mul_left' (one_le_iff_ne_zero.mpr h') _, rw [mul_one],
end
theorem mul_le_max (a b : cardinal) : a * b ≤ max (max a b) ω :=
begin
by_cases ha0 : a = 0,
{ simp [ha0] },
by_cases hb0 : b = 0,
{ simp [hb0] },
by_cases ha : ω ≤ a,
{ rw [mul_eq_max_of_omega_le_left ha hb0],
exact le_max_left _ _ },
{ by_cases hb : ω ≤ b,
{ rw [mul_comm, mul_eq_max_of_omega_le_left hb ha0, max_comm],
exact le_max_left _ _ },
{ exact le_max_of_le_right (le_of_lt (mul_lt_omega (lt_of_not_ge ha) (lt_of_not_ge hb))) } }
end
lemma mul_eq_left {a b : cardinal} (ha : ω ≤ a) (hb : b ≤ a) (hb' : b ≠ 0) : a * b = a :=
by { rw [mul_eq_max_of_omega_le_left ha hb', max_eq_left hb] }
lemma mul_eq_right {a b : cardinal} (hb : ω ≤ b) (ha : a ≤ b) (ha' : a ≠ 0) : a * b = b :=
by { rw [mul_comm, mul_eq_left hb ha ha'] }
lemma le_mul_left {a b : cardinal} (h : b ≠ 0) : a ≤ b * a :=
by { convert mul_le_mul_right' (one_le_iff_ne_zero.mpr h) _,
rw [one_mul] }
lemma le_mul_right {a b : cardinal} (h : b ≠ 0) : a ≤ a * b :=
by { rw [mul_comm], exact le_mul_left h }
lemma mul_eq_left_iff {a b : cardinal} : a * b = a ↔ ((max ω b ≤ a ∧ b ≠ 0) ∨ b = 1 ∨ a = 0) :=
begin
rw [max_le_iff], split,
{ intro h,
cases (le_or_lt ω a) with ha ha,
{ have : a ≠ 0, { rintro rfl, exact not_lt_of_le ha omega_pos },
left, use ha,
{ rw [← not_lt], intro hb, apply ne_of_gt _ h, refine lt_of_lt_of_le hb (le_mul_left this) },
{ rintro rfl, apply this, rw [_root_.mul_zero] at h, subst h }},
right, by_cases h2a : a = 0, { right, exact h2a },
have hb : b ≠ 0, { rintro rfl, apply h2a, rw [mul_zero] at h, subst h },
left, rw [← h, mul_lt_omega_iff, lt_omega, lt_omega] at ha,
rcases ha with rfl|rfl|⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, contradiction, contradiction,
rw [← ne] at h2a, rw [← one_le_iff_ne_zero] at h2a hb, norm_cast at h2a hb h ⊢,
apply le_antisymm _ hb, rw [← not_lt], intro h2b,
apply ne_of_gt _ h, conv_lhs { rw [← mul_one n] },
rwa [mul_lt_mul_left], apply nat.lt_of_succ_le h2a },
{ rintro (⟨⟨ha, hab⟩, hb⟩|rfl|rfl),
{ rw [mul_eq_max_of_omega_le_left ha hb, max_eq_left hab] },
all_goals {simp}}
end
/-! ### Properties of `add` -/
/-- If `α` is an infinite type, then `α ⊕ α` and `α` have the same cardinality. -/
theorem add_eq_self {c : cardinal} (h : ω ≤ c) : c + c = c :=
le_antisymm
(by simpa only [nat.cast_bit0, nat.cast_one, mul_eq_self h, two_mul] using
mul_le_mul_right' ((nat_lt_omega 2).le.trans h) c)
(self_le_add_left c c)
/-- If `α` is an infinite type, then the cardinality of `α ⊕ β` is the maximum
of the cardinalities of `α` and `β`. -/
theorem add_eq_max {a b : cardinal} (ha : ω ≤ a) : a + b = max a b :=
le_antisymm
(add_eq_self (le_trans ha (le_max_left a b)) ▸
add_le_add (le_max_left _ _) (le_max_right _ _)) $
max_le (self_le_add_right _ _) (self_le_add_left _ _)
theorem add_le_max (a b : cardinal) : a + b ≤ max (max a b) ω :=
begin
by_cases ha : ω ≤ a,
{ rw [add_eq_max ha],
exact le_max_left _ _ },
{ by_cases hb : ω ≤ b,
{ rw [add_comm, add_eq_max hb, max_comm],
exact le_max_left _ _ },
{ exact le_max_of_le_right (le_of_lt (add_lt_omega (lt_of_not_ge ha) (lt_of_not_ge hb))) } }
end
theorem add_lt_of_lt {a b c : cardinal} (hc : ω ≤ c)
(h1 : a < c) (h2 : b < c) : a + b < c :=
lt_of_le_of_lt (add_le_add (le_max_left a b) (le_max_right a b)) $
(lt_or_le (max a b) ω).elim
(λ h, lt_of_lt_of_le (add_lt_omega h h) hc)
(λ h, by rw add_eq_self h; exact max_lt h1 h2)
lemma eq_of_add_eq_of_omega_le {a b c : cardinal} (h : a + b = c) (ha : a < c) (hc : ω ≤ c) :
b = c :=
begin
apply le_antisymm,
{ rw [← h], apply self_le_add_left },
rw[← not_lt], intro hb,
have : a + b < c := add_lt_of_lt hc ha hb,
simpa [h, lt_irrefl] using this
end
lemma add_eq_left {a b : cardinal} (ha : ω ≤ a) (hb : b ≤ a) : a + b = a :=
by { rw [add_eq_max ha, max_eq_left hb] }
lemma add_eq_right {a b : cardinal} (hb : ω ≤ b) (ha : a ≤ b) : a + b = b :=
by { rw [add_comm, add_eq_left hb ha] }
lemma add_eq_left_iff {a b : cardinal} : a + b = a ↔ (max ω b ≤ a ∨ b = 0) :=
begin
rw [max_le_iff], split,
{ intro h, cases (le_or_lt ω a) with ha ha,
{ left, use ha, rw [← not_lt], intro hb, apply ne_of_gt _ h,
exact lt_of_lt_of_le hb (self_le_add_left b a) },
right, rw [← h, add_lt_omega_iff, lt_omega, lt_omega] at ha,
rcases ha with ⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, norm_cast at h ⊢,
rw [← add_right_inj, h, add_zero] },
{ rintro (⟨h1, h2⟩|h3), rw [add_eq_max h1, max_eq_left h2], rw [h3, add_zero] }
end
lemma add_eq_right_iff {a b : cardinal} : a + b = b ↔ (max ω a ≤ b ∨ a = 0) :=
by { rw [add_comm, add_eq_left_iff] }
lemma add_one_eq {a : cardinal} (ha : ω ≤ a) : a + 1 = a :=
have 1 ≤ a, from le_trans (le_of_lt one_lt_omega) ha,
add_eq_left ha this
protected lemma eq_of_add_eq_add_left {a b c : cardinal} (h : a + b = a + c) (ha : a < ω) :
b = c :=
begin
cases le_or_lt ω b with hb hb,
{ have : a < b := lt_of_lt_of_le ha hb,
rw [add_eq_right hb (le_of_lt this), eq_comm] at h,
rw [eq_of_add_eq_of_omega_le h this hb] },
{ have hc : c < ω,
{ rw [← not_le], intro hc,
apply lt_irrefl ω, apply lt_of_le_of_lt (le_trans hc (self_le_add_left _ a)),
rw [← h], apply add_lt_omega ha hb },
rw [lt_omega] at *,
rcases ha with ⟨n, rfl⟩, rcases hb with ⟨m, rfl⟩, rcases hc with ⟨k, rfl⟩,
norm_cast at h ⊢, apply add_left_cancel h }
end
protected lemma eq_of_add_eq_add_right {a b c : cardinal} (h : a + b = c + b) (hb : b < ω) :
a = c :=
by { rw [add_comm a b, add_comm c b] at h, exact cardinal.eq_of_add_eq_add_left h hb }
/-! ### Properties about power -/
theorem pow_le {κ μ : cardinal.{u}} (H1 : ω ≤ κ) (H2 : μ < ω) : κ ^ μ ≤ κ :=
let ⟨n, H3⟩ := lt_omega.1 H2 in
H3.symm ▸ (quotient.induction_on κ (λ α H1, nat.rec_on n
(le_of_lt $ lt_of_lt_of_le (by rw [nat.cast_zero, power_zero];
from one_lt_omega) H1)
(λ n ih, trans_rel_left _
(by { rw [nat.cast_succ, power_add, power_one];
exact mul_le_mul_right' ih _ })
(mul_eq_self H1))) H1)
lemma power_self_eq {c : cardinal} (h : ω ≤ c) : c ^ c = 2 ^ c :=
begin
apply le_antisymm,
{ apply le_trans (power_le_power_right $ le_of_lt $ cantor c), rw [← power_mul, mul_eq_self h] },
{ convert power_le_power_right (le_trans (le_of_lt $ nat_lt_omega 2) h), apply nat.cast_two.symm }
end
lemma prod_eq_two_power {ι : Type u} [infinite ι] {c : ι → cardinal.{v}} (h₁ : ∀ i, 2 ≤ c i)
(h₂ : ∀ i, lift.{u} (c i) ≤ lift.{v} (#ι)) :
prod c = 2 ^ lift.{v} (#ι) :=
begin
rw [← lift_id' (prod c), lift_prod, ← lift_two_power],
apply le_antisymm,
{ refine (prod_le_prod _ _ h₂).trans_eq _,
rw [prod_const, lift_lift, ← lift_power, power_self_eq (omega_le_mk ι), lift_umax.{u v}] },
{ rw [← prod_const', lift_prod],
refine prod_le_prod _ _ (λ i, _),
rw [lift_two, ← lift_two.{u v}, lift_le],
exact h₁ i }
end
lemma power_eq_two_power {c₁ c₂ : cardinal} (h₁ : ω ≤ c₁) (h₂ : 2 ≤ c₂) (h₂' : c₂ ≤ c₁) :
c₂ ^ c₁ = 2 ^ c₁ :=
le_antisymm (power_self_eq h₁ ▸ power_le_power_right h₂') (power_le_power_right h₂)
lemma nat_power_eq {c : cardinal.{u}} (h : ω ≤ c) {n : ℕ} (hn : 2 ≤ n) :
(n : cardinal.{u}) ^ c = 2 ^ c :=
power_eq_two_power h (by assumption_mod_cast) ((nat_lt_omega n).le.trans h)
lemma power_nat_le {c : cardinal.{u}} {n : ℕ} (h : ω ≤ c) : c ^ (n : cardinal.{u}) ≤ c :=
pow_le h (nat_lt_omega n)
lemma power_nat_le_max {c : cardinal.{u}} {n : ℕ} : c ^ (n : cardinal.{u}) ≤ max c ω :=
begin
by_cases hc : ω ≤ c,
{ exact le_max_of_le_left (power_nat_le hc) },
{ exact le_max_of_le_right (le_of_lt (power_lt_omega (lt_of_not_ge hc) (nat_lt_omega _))) }
end
lemma powerlt_omega {c : cardinal} (h : ω ≤ c) : c ^< ω = c :=
begin
apply le_antisymm,
{ rw [powerlt_le], intro c', rw [lt_omega], rintro ⟨n, rfl⟩, apply power_nat_le h },
convert le_powerlt one_lt_omega, rw [power_one]
end
lemma powerlt_omega_le (c : cardinal) : c ^< ω ≤ max c ω :=
begin
cases le_or_gt ω c,
{ rw [powerlt_omega h], apply le_max_left },
rw [powerlt_le], intros c' hc',
refine le_trans (le_of_lt $ power_lt_omega h hc') (le_max_right _ _)
end
/-! ### Computing cardinality of various types -/
theorem mk_list_eq_mk (α : Type u) [infinite α] : #(list α) = #α :=
have H1 : ω ≤ #α := omega_le_mk α,
eq.symm $ le_antisymm ⟨⟨λ x, [x], λ x y H, (list.cons.inj H).1⟩⟩ $
calc #(list α)
= sum (λ n : ℕ, #α ^ (n : cardinal.{u})) : mk_list_eq_sum_pow α
... ≤ sum (λ n : ℕ, #α) : sum_le_sum _ _ $ λ n, pow_le H1 $ nat_lt_omega n
... = #α : by simp [H1]
theorem mk_finset_eq_mk (α : Type u) [infinite α] : #(finset α) = #α :=
eq.symm $ le_antisymm (mk_le_of_injective (λ x y, finset.singleton_inj.1)) $
calc #(finset α) ≤ #(list α) : mk_le_of_surjective list.to_finset_surjective
... = #α : mk_list_eq_mk α
lemma mk_bounded_set_le_of_omega_le (α : Type u) (c : cardinal) (hα : ω ≤ #α) :
#{t : set α // mk t ≤ c} ≤ #α ^ c :=
begin
refine le_trans _ (by rw [←add_one_eq hα]), refine quotient.induction_on c _, clear c, intro β,
fapply mk_le_of_surjective,
{ intro f, use sum.inl ⁻¹' range f,
refine le_trans (mk_preimage_of_injective _ _ (λ x y, sum.inl.inj)) _,
apply mk_range_le },
rintro ⟨s, ⟨g⟩⟩,
use λ y, if h : ∃(x : s), g x = y then sum.inl (classical.some h).val else sum.inr ⟨⟩,
apply subtype.eq, ext,
split,
{ rintro ⟨y, h⟩, dsimp only at h, by_cases h' : ∃ (z : s), g z = y,
{ rw [dif_pos h'] at h, cases sum.inl.inj h, exact (classical.some h').2 },
{ rw [dif_neg h'] at h, cases h }},
{ intro h, have : ∃(z : s), g z = g ⟨x, h⟩, exact ⟨⟨x, h⟩, rfl⟩,
use g ⟨x, h⟩, dsimp only, rw [dif_pos this], congr',
suffices : classical.some this = ⟨x, h⟩, exact congr_arg subtype.val this,
apply g.2, exact classical.some_spec this }
end
lemma mk_bounded_set_le (α : Type u) (c : cardinal) :
#{t : set α // #t ≤ c} ≤ max (#α) ω ^ c :=
begin
transitivity #{t : set (ulift.{u} nat ⊕ α) // #t ≤ c},
{ refine ⟨embedding.subtype_map _ _⟩, apply embedding.image,
use sum.inr, apply sum.inr.inj, intros s hs, exact le_trans mk_image_le hs },
refine le_trans
(mk_bounded_set_le_of_omega_le (ulift.{u} nat ⊕ α) c (self_le_add_right ω (#α))) _,
rw [max_comm, ←add_eq_max]; refl
end
lemma mk_bounded_subset_le {α : Type u} (s : set α) (c : cardinal.{u}) :
#{t : set α // t ⊆ s ∧ #t ≤ c} ≤ max (#s) ω ^ c :=
begin
refine le_trans _ (mk_bounded_set_le s c),
refine ⟨embedding.cod_restrict _ _ _⟩,
use λ t, coe ⁻¹' t.1,
{ rintros ⟨t, ht1, ht2⟩ ⟨t', h1t', h2t'⟩ h, apply subtype.eq, dsimp only at h ⊢,
refine (preimage_eq_preimage' _ _).1 h; rw [subtype.range_coe]; assumption },
rintro ⟨t, h1t, h2t⟩, exact le_trans (mk_preimage_of_injective _ _ subtype.val_injective) h2t
end
/-! ### Properties of `compl` -/
lemma mk_compl_of_omega_le {α : Type*} (s : set α) (h : ω ≤ #α) (h2 : #s < #α) :
#(sᶜ : set α) = #α :=
by { refine eq_of_add_eq_of_omega_le _ h2 h, exact mk_sum_compl s }
lemma mk_compl_finset_of_omega_le {α : Type*} (s : finset α) (h : ω ≤ #α) :
#((↑s)ᶜ : set α) = #α :=
by { apply mk_compl_of_omega_le _ h, exact lt_of_lt_of_le (finset_card_lt_omega s) h }
lemma mk_compl_eq_mk_compl_infinite {α : Type*} {s t : set α} (h : ω ≤ #α) (hs : #s < #α)
(ht : #t < #α) : #(sᶜ : set α) = #(tᶜ : set α) :=
by { rw [mk_compl_of_omega_le s h hs, mk_compl_of_omega_le t h ht] }
lemma mk_compl_eq_mk_compl_finite_lift {α : Type u} {β : Type v} {s : set α} {t : set β}
(hα : #α < ω) (h1 : lift.{(max v w)} (#α) = lift.{(max u w)} (#β))
(h2 : lift.{(max v w)} (#s) = lift.{(max u w)} (#t)) :
lift.{(max v w)} (#(sᶜ : set α)) = lift.{(max u w)} (#(tᶜ : set β)) :=
begin
have hα' := hα, have h1' := h1,
rw [← mk_sum_compl s, ← mk_sum_compl t] at h1,
rw [← mk_sum_compl s, add_lt_omega_iff] at hα,
lift #s to ℕ using hα.1 with n hn,
lift #(sᶜ : set α) to ℕ using hα.2 with m hm,
have : #(tᶜ : set β) < ω,
{ refine lt_of_le_of_lt (mk_subtype_le _) _,
rw [← lift_lt, lift_omega, ← h1', ← lift_omega.{u (max v w)}, lift_lt], exact hα' },
lift #(tᶜ : set β) to ℕ using this with k hk,
simp [nat_eq_lift_eq_iff] at h2, rw [nat_eq_lift_eq_iff.{v (max u w)}] at h2,
simp [h2.symm] at h1 ⊢, norm_cast at h1, simp at h1, exact h1
end
lemma mk_compl_eq_mk_compl_finite {α β : Type u} {s : set α} {t : set β}
(hα : #α < ω) (h1 : #α = #β) (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set β) :=
by { rw [← lift_inj], apply mk_compl_eq_mk_compl_finite_lift hα; rw [lift_inj]; assumption }
lemma mk_compl_eq_mk_compl_finite_same {α : Type*} {s t : set α} (hα : #α < ω)
(h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set α) :=
mk_compl_eq_mk_compl_finite hα rfl h
/-! ### Extending an injection to an equiv -/
theorem extend_function {α β : Type*} {s : set α} (f : s ↪ β)
(h : nonempty ((sᶜ : set α) ≃ ((range f)ᶜ : set β))) :
∃ (g : α ≃ β), ∀ x : s, g x = f x :=
begin
intros, have := h, cases this with g,
let h : α ≃ β := (set.sum_compl (s : set α)).symm.trans
((sum_congr (equiv.of_injective f f.2) g).trans
(set.sum_compl (range f))),
refine ⟨h, _⟩, rintro ⟨x, hx⟩, simp [set.sum_compl_symm_apply_of_mem, hx]
end
theorem extend_function_finite {α β : Type*} {s : set α} (f : s ↪ β)
(hs : #α < ω) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x :=
begin
apply extend_function f,
have := h, cases this with g,
rw [← lift_mk_eq] at h,
rw [←lift_mk_eq, mk_compl_eq_mk_compl_finite_lift hs h],
rw [mk_range_eq_lift], exact f.2
end
theorem extend_function_of_lt {α β : Type*} {s : set α} (f : s ↪ β) (hs : #s < #α)
(h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x :=
begin
cases (le_or_lt ω (#α)) with hα hα,
{ apply extend_function f, have := h, cases this with g, rw [← lift_mk_eq] at h,
cases cardinal.eq.mp (mk_compl_of_omega_le s hα hs) with g2,
cases cardinal.eq.mp (mk_compl_of_omega_le (range f) _ _) with g3,
{ constructor, exact g2.trans (g.trans g3.symm) },
{ rw [← lift_le, ← h], refine le_trans _ (lift_le.mpr hα), simp },
rwa [← lift_lt, ← h, mk_range_eq_lift, lift_lt], exact f.2 },
{ exact extend_function_finite f hα h }
end
section bit
/-!
This section proves inequalities for `bit0` and `bit1`, enabling `simp` to solve inequalities
for numeral cardinals. The complexity of the resulting algorithm is not good, as in some cases
`simp` reduces an inequality to a disjunction of two situations, depending on whether a cardinal
is finite or infinite. Since the evaluation of the branches is not lazy, this is bad. It is good
enough for practical situations, though.
For specific numbers, these inequalities could also be deduced from the corresponding
inequalities of natural numbers using `norm_cast`:
```
example : (37 : cardinal) < 42 :=
by { norm_cast, norm_num }
```
-/
lemma bit0_ne_zero (a : cardinal) : ¬bit0 a = 0 ↔ ¬a = 0 :=
by simp [bit0]
@[simp] lemma bit1_ne_zero (a : cardinal) : ¬bit1 a = 0 :=
by simp [bit1]
@[simp] lemma zero_lt_bit0 (a : cardinal) : 0 < bit0 a ↔ 0 < a :=
by { rw ←not_iff_not, simp [bit0], }
@[simp] lemma zero_lt_bit1 (a : cardinal) : 0 < bit1 a :=
lt_of_lt_of_le zero_lt_one (self_le_add_left _ _)
@[simp] lemma one_le_bit0 (a : cardinal) : 1 ≤ bit0 a ↔ 0 < a :=
⟨λ h, (zero_lt_bit0 a).mp (lt_of_lt_of_le zero_lt_one h),
λ h, le_trans (one_le_iff_pos.mpr h) (self_le_add_left a a)⟩
@[simp] lemma one_le_bit1 (a : cardinal) : 1 ≤ bit1 a :=
self_le_add_left _ _
theorem bit0_eq_self {c : cardinal} (h : ω ≤ c) : bit0 c = c :=
add_eq_self h
@[simp] theorem bit0_lt_omega {c : cardinal} : bit0 c < ω ↔ c < ω :=
by simp [bit0, add_lt_omega_iff]
@[simp] theorem omega_le_bit0 {c : cardinal} : ω ≤ bit0 c ↔ ω ≤ c :=
by { rw ← not_iff_not, simp }
@[simp] theorem bit1_eq_self_iff {c : cardinal} : bit1 c = c ↔ ω ≤ c :=
begin
by_cases h : ω ≤ c,
{ simp only [bit1, bit0_eq_self h, h, eq_self_iff_true, add_one_of_omega_le] },
{ simp only [h, iff_false],
apply ne_of_gt,
rcases lt_omega.1 (not_le.1 h) with ⟨n, rfl⟩,
norm_cast,
dsimp [bit1, bit0],
linarith }
end
@[simp] theorem bit1_lt_omega {c : cardinal} : bit1 c < ω ↔ c < ω :=
by simp [bit1, bit0, add_lt_omega_iff, one_lt_omega]
@[simp] theorem omega_le_bit1 {c : cardinal} : ω ≤ bit1 c ↔ ω ≤ c :=
by { rw ← not_iff_not, simp }
@[simp] lemma bit0_le_bit0 {a b : cardinal} : bit0 a ≤ bit0 b ↔ a ≤ b :=
begin
by_cases ha : ω ≤ a; by_cases hb : ω ≤ b,
{ rw [bit0_eq_self ha, bit0_eq_self hb] },
{ rw bit0_eq_self ha,
have I1 : ¬ (a ≤ b),
{ assume h, apply hb, exact le_trans ha h },
have I2 : ¬ (a ≤ bit0 b),
{ assume h,
have A : bit0 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) },
simp [I1, I2] },
{ rw [bit0_eq_self hb],
simp only [not_le] at ha,
have I1 : a ≤ b := le_of_lt (lt_of_lt_of_le ha hb),
have I2 : bit0 a ≤ b := le_trans (le_of_lt (bit0_lt_omega.2 ha)) hb,
simp [I1, I2] },
{ simp at ha hb,
rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
simp }
end
@[simp] lemma bit0_le_bit1 {a b : cardinal} : bit0 a ≤ bit1 b ↔ a ≤ b :=
begin
by_cases ha : ω ≤ a; by_cases hb : ω ≤ b,
{ rw [bit0_eq_self ha, bit1_eq_self_iff.2 hb], },
{ rw bit0_eq_self ha,
have I1 : ¬ (a ≤ b),
{ assume h, apply hb, exact le_trans ha h },
have I2 : ¬ (a ≤ bit1 b),
{ assume h,
have A : bit1 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) },
simp [I1, I2] },
{ rw [bit1_eq_self_iff.2 hb],
simp only [not_le] at ha,
have I1 : a ≤ b := le_of_lt (lt_of_lt_of_le ha hb),
have I2 : bit0 a ≤ b := le_trans (le_of_lt (bit0_lt_omega.2 ha)) hb,
simp [I1, I2] },
{ simp at ha hb,
rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
simp }
end
@[simp] lemma bit1_le_bit1 {a b : cardinal} : bit1 a ≤ bit1 b ↔ a ≤ b :=
begin
split,
{ assume h,
apply bit0_le_bit1.1 (le_trans (self_le_add_right (bit0 a) 1) h) },
{ assume h,
calc a + a + 1 ≤ a + b + 1 : add_le_add_right (add_le_add_left h a) 1
... ≤ b + b + 1 : add_le_add_right (add_le_add_right h b) 1 }
end
@[simp] lemma bit1_le_bit0 {a b : cardinal} : bit1 a ≤ bit0 b ↔ (a < b ∨ (a ≤ b ∧ ω ≤ a)) :=
begin
by_cases ha : ω ≤ a; by_cases hb : ω ≤ b,
{ simp only [bit1_eq_self_iff.mpr ha, bit0_eq_self hb, ha, and_true],
refine ⟨λ h, or.inr h, λ h, _⟩,
cases h,
{ exact le_of_lt h },
{ exact h } },
{ rw bit1_eq_self_iff.2 ha,
have I1 : ¬ (a ≤ b),
{ assume h, apply hb, exact le_trans ha h },
have I2 : ¬ (a ≤ bit0 b),
{ assume h,
have A : bit0 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) },
simp [I1, I2, le_of_not_ge I1] },
{ rw [bit0_eq_self hb],
simp only [not_le] at ha,
have I1 : a < b := lt_of_lt_of_le ha hb,
have I2 : bit1 a ≤ b := le_trans (le_of_lt (bit1_lt_omega.2 ha)) hb,
simp [I1, I2] },
{ simp at ha hb,
rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
simp [not_le.mpr ha], }
end
@[simp] lemma bit0_lt_bit0 {a b : cardinal} : bit0 a < bit0 b ↔ a < b :=
begin
by_cases ha : ω ≤ a; by_cases hb : ω ≤ b,
{ rw [bit0_eq_self ha, bit0_eq_self hb] },
{ rw bit0_eq_self ha,
have I1 : ¬ (a < b),
{ assume h, apply hb, exact le_trans ha (le_of_lt h) },
have I2 : ¬ (a < bit0 b),
{ assume h,
have A : bit0 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) },
simp [I1, I2] },
{ rw [bit0_eq_self hb],
simp only [not_le] at ha,
have I1 : a < b := lt_of_lt_of_le ha hb,
have I2 : bit0 a < b := lt_of_lt_of_le (bit0_lt_omega.2 ha) hb,
simp [I1, I2] },
{ simp at ha hb,
rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
simp }
end
@[simp] lemma bit1_lt_bit0 {a b : cardinal} : bit1 a < bit0 b ↔ a < b :=
begin
by_cases ha : ω ≤ a; by_cases hb : ω ≤ b,
{ rw [bit1_eq_self_iff.2 ha, bit0_eq_self hb], },
{ rw bit1_eq_self_iff.2 ha,
have I1 : ¬ (a < b),
{ assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) },
have I2 : ¬ (a < bit0 b),
{ assume h,
have A : bit0 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) },
simp [I1, I2] },
{ rw [bit0_eq_self hb],
simp only [not_le] at ha,
have I1 : a < b := (lt_of_lt_of_le ha hb),
have I2 : bit1 a < b := lt_of_lt_of_le (bit1_lt_omega.2 ha) hb,
simp [I1, I2] },
{ simp at ha hb,
rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
simp }
end
@[simp] lemma bit1_lt_bit1 {a b : cardinal} : bit1 a < bit1 b ↔ a < b :=
begin
by_cases ha : ω ≤ a; by_cases hb : ω ≤ b,
{ rw [bit1_eq_self_iff.2 ha, bit1_eq_self_iff.2 hb], },
{ rw bit1_eq_self_iff.2 ha,
have I1 : ¬ (a < b),
{ assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) },
have I2 : ¬ (a < bit1 b),
{ assume h,
have A : bit1 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) },
simp [I1, I2] },
{ rw [bit1_eq_self_iff.2 hb],
simp only [not_le] at ha,
have I1 : a < b := (lt_of_lt_of_le ha hb),
have I2 : bit1 a < b := lt_of_lt_of_le (bit1_lt_omega.2 ha) hb,
simp [I1, I2] },
{ simp at ha hb,
rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
simp }
end
@[simp] lemma bit0_lt_bit1 {a b : cardinal} : bit0 a < bit1 b ↔ (a < b ∨ (a ≤ b ∧ a < ω)) :=
begin
by_cases ha : ω ≤ a; by_cases hb : ω ≤ b,
{ simp [bit0_eq_self ha, bit1_eq_self_iff.2 hb, not_lt.mpr ha] },
{ rw bit0_eq_self ha,
have I1 : ¬ (a < b),
{ assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) },
have I2 : ¬ (a < bit1 b),
{ assume h,
have A : bit1 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) },
simp [I1, I2, not_lt.mpr ha] },
{ rw [bit1_eq_self_iff.2 hb],
simp only [not_le] at ha,
have I1 : a < b := (lt_of_lt_of_le ha hb),
have I2 : bit0 a < b := lt_of_lt_of_le (bit0_lt_omega.2 ha) hb,
simp [I1, I2] },
{ simp at ha hb,
rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
simp only [ha, and_true, nat.bit0_lt_bit1_iff],
refine ⟨λ h, or.inr h, λ h, _⟩,
cases h,
{ exact le_of_lt h },
{ exact h } }
end
lemma one_lt_two : (1 : cardinal) < 2 :=
-- This strategy works generally to prove inequalities between numerals in `cardinality`.
by { norm_cast, norm_num }
@[simp] lemma one_lt_bit0 {a : cardinal} : 1 < bit0 a ↔ 0 < a :=
by simp [← bit1_zero]
@[simp] lemma one_lt_bit1 (a : cardinal) : 1 < bit1 a ↔ 0 < a :=
by simp [← bit1_zero]
@[simp] lemma one_le_one : (1 : cardinal) ≤ 1 :=
le_refl _
end bit
end cardinal
lemma not_injective_of_ordinal {α : Type u} (f : ordinal.{u} → α) :
¬ function.injective f :=
begin
let g : ordinal.{u} → ulift.{u+1} α := λ o, ulift.up (f o),
suffices : ¬ function.injective g,
{ intro hf, exact this (equiv.ulift.symm.injective.comp hf) },
intro hg,
replace hg := cardinal.mk_le_of_injective hg,
rw cardinal.mk_ulift at hg,
have := hg.trans_lt (cardinal.lift_lt_univ _),
rw cardinal.univ_id at this,
exact lt_irrefl _ this
end
lemma not_injective_of_ordinal_of_small {α : Type v} [small.{u} α] (f : ordinal.{u} → α) :
¬ function.injective f :=
begin
intro hf,
apply not_injective_of_ordinal (equiv_shrink α ∘ f),
exact (equiv_shrink _).injective.comp hf,
end
|
eaf5779c62173d48414c65c1804237f6c2ae676b | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/def9.lean | 5a9652d8324cbb2b7ef51dcb4b888cb5f9f496a5 | [
"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 | 93 | lean | lemma ex4 (A : Type) : ∀ (a b : A) (H : a = b), b = a
| .(z) z (eq.refl .(z)) := eq.refl z
|
438ab44adb86f056c260b5e077b29212bd1484c4 | 95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990 | /src/algebra/direct_sum.lean | a17a92343818dcfcf8ecaf43641f147a335cabdc | [
"Apache-2.0"
] | permissive | uniformity1/mathlib | 829341bad9dfa6d6be9adaacb8086a8a492e85a4 | dd0e9bd8f2e5ec267f68e72336f6973311909105 | refs/heads/master | 1,588,592,015,670 | 1,554,219,842,000 | 1,554,219,842,000 | 179,110,702 | 0 | 0 | Apache-2.0 | 1,554,220,076,000 | 1,554,220,076,000 | null | UTF-8 | Lean | false | false | 6,060 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
Direct sum of abelian groups, indexed by a discrete type.
-/
import data.dfinsupp
universes u v w u₁
variables (ι : Type v) [decidable_eq ι] (β : ι → Type w) [Π i, add_comm_group (β i)]
def direct_sum : Type* := Π₀ i, β i
namespace direct_sum
variables {ι β}
instance : add_comm_group (direct_sum ι β) :=
dfinsupp.add_comm_group
variables β
def mk : Π s : finset ι, (Π i : (↑s : set ι), β i.1) → direct_sum ι β :=
dfinsupp.mk
def of : Π i : ι, β i → direct_sum ι β :=
dfinsupp.single
variables {β}
instance mk.is_add_group_hom (s : finset ι) : is_add_group_hom (mk β s) :=
⟨λ _ _, dfinsupp.mk_add⟩
@[simp] lemma mk_zero (s : finset ι) : mk β s 0 = 0 :=
is_add_group_hom.zero _
@[simp] lemma mk_add (s : finset ι) (x y) : mk β s (x + y) = mk β s x + mk β s y :=
is_add_group_hom.add _ x y
@[simp] lemma mk_neg (s : finset ι) (x) : mk β s (-x) = -mk β s x :=
is_add_group_hom.neg _ x
@[simp] lemma mk_sub (s : finset ι) (x y) : mk β s (x - y) = mk β s x - mk β s y :=
is_add_group_hom.sub _ x y
instance of.is_add_group_hom (i : ι) : is_add_group_hom (of β i) :=
⟨λ _ _, dfinsupp.single_add⟩
@[simp] lemma of_zero (i : ι) : of β i 0 = 0 :=
is_add_group_hom.zero _
@[simp] lemma of_add (i : ι) (x y) : of β i (x + y) = of β i x + of β i y :=
is_add_group_hom.add _ x y
@[simp] lemma of_neg (i : ι) (x) : of β i (-x) = -of β i x :=
is_add_group_hom.neg _ x
@[simp] lemma of_sub (i : ι) (x y) : of β i (x - y) = of β i x - of β i y :=
is_add_group_hom.sub _ x y
theorem mk_inj (s : finset ι) : function.injective (mk β s) :=
dfinsupp.mk_inj s
theorem of_inj (i : ι) : function.injective (of β i) :=
λ x y H, congr_fun (mk_inj _ H) ⟨i, by simp [finset.to_set]⟩
@[elab_as_eliminator]
protected theorem induction_on {C : direct_sum ι β → Prop}
(x : direct_sum ι β) (H_zero : C 0)
(H_basic : ∀ (i : ι) (x : β i), C (of β i x))
(H_plus : ∀ x y, C x → C y → C (x + y)) : C x :=
begin
apply dfinsupp.induction x H_zero,
intros i b f h1 h2 ih,
solve_by_elim
end
variables {γ : Type u₁} [add_comm_group γ]
variables (φ : Π i, β i → γ) [Π i, is_add_group_hom (φ i)]
variables (φ)
def to_group (f : direct_sum ι β) : γ :=
quotient.lift_on f (λ x, x.2.to_finset.sum $ λ i, φ i (x.1 i)) $ λ x y H,
begin
have H1 : x.2.to_finset ∩ y.2.to_finset ⊆ x.2.to_finset, from finset.inter_subset_left _ _,
have H2 : x.2.to_finset ∩ y.2.to_finset ⊆ y.2.to_finset, from finset.inter_subset_right _ _,
refine (finset.sum_subset H1 _).symm.trans ((finset.sum_congr rfl _).trans (finset.sum_subset H2 _)),
{ intros i H1 H2, rw finset.mem_inter at H2, rw H i,
simp only [multiset.mem_to_finset] at H1 H2,
rw [(y.3 i).resolve_left (mt (and.intro H1) H2), is_add_group_hom.zero (φ i)] },
{ intros i H1, rw H i },
{ intros i H1 H2, rw finset.mem_inter at H2, rw ← H i,
simp only [multiset.mem_to_finset] at H1 H2,
rw [(x.3 i).resolve_left (mt (λ H3, and.intro H3 H1) H2), is_add_group_hom.zero (φ i)] }
end
variables {φ}
instance to_group.is_add_group_hom : is_add_group_hom (to_group φ) :=
begin
constructor, intros f g,
refine quotient.induction_on f (λ x, _),
refine quotient.induction_on g (λ y, _),
change finset.sum _ _ = finset.sum _ _ + finset.sum _ _,
simp only, conv { to_lhs, congr, skip, funext, rw is_add_group_hom.add (φ i) },
simp only [finset.sum_add_distrib],
congr' 1,
{ refine (finset.sum_subset _ _).symm,
{ intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inl },
{ intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2,
rw [(x.3 i).resolve_left H2, is_add_group_hom.zero (φ i)] } },
{ refine (finset.sum_subset _ _).symm,
{ intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inr },
{ intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2,
rw [(y.3 i).resolve_left H2, is_add_group_hom.zero (φ i)] } }
end
variables (φ)
@[simp] lemma to_group_zero : to_group φ 0 = 0 :=
is_add_group_hom.zero _
@[simp] lemma to_group_add (x y) : to_group φ (x + y) = to_group φ x + to_group φ y :=
is_add_group_hom.add _ x y
@[simp] lemma to_group_neg (x) : to_group φ (-x) = -to_group φ x :=
is_add_group_hom.neg _ x
@[simp] lemma to_group_sub (x y) : to_group φ (x - y) = to_group φ x - to_group φ y :=
is_add_group_hom.sub _ x y
@[simp] lemma to_group_of (i) (x : β i) : to_group φ (of β i x) = φ i x :=
(add_zero _).trans $ congr_arg (φ i) $ show (if H : i ∈ finset.singleton i then x else 0) = x,
from dif_pos $ finset.mem_singleton_self i
variables (ψ : direct_sum ι β → γ) [is_add_group_hom ψ]
theorem to_group.unique (f : direct_sum ι β) : ψ f = to_group (λ i, ψ ∘ of β i) f :=
direct_sum.induction_on f
(by rw [is_add_group_hom.zero ψ, is_add_group_hom.zero (to_group (λ i, ψ ∘ of β i))])
(λ i x, by rw [to_group_of])
(λ x y ihx ihy, by rw [is_add_group_hom.add ψ, is_add_group_hom.add (to_group (λ i, ψ ∘ of β i)), ihx, ihy])
variables (β)
def set_to_set (S T : set ι) (H : S ⊆ T) :
direct_sum S (β ∘ subtype.val) → direct_sum T (β ∘ subtype.val) :=
to_group $ λ i, of (β ∘ @subtype.val _ T) ⟨i.1, H i.2⟩
variables {β}
instance (S T : set ι) (H : S ⊆ T) : is_add_group_hom (set_to_set β S T H) :=
to_group.is_add_group_hom
protected def id (M : Type v) [add_comm_group M] : direct_sum punit (λ _, M) ≃ M :=
{ to_fun := direct_sum.to_group (λ _, id),
inv_fun := of (λ _, M) punit.star,
left_inv := λ x, direct_sum.induction_on x
(by rw [to_group_zero, of_zero])
(λ ⟨⟩ x, by rw [to_group_of]; refl)
(λ x y ihx ihy, by rw [to_group_add, of_add, ihx, ihy]),
right_inv := λ x, to_group_of _ _ _ }
instance : has_coe_to_fun (direct_sum ι β) :=
dfinsupp.has_coe_to_fun
end direct_sum
|
ec7db65283160b35f7213fd04e777498a4ad7606 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/BuiltinCommand.lean | 482a45bec8fa090861175262173923dabc8d7c4b | [
"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 | 20,013 | 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.Util.CollectLevelParams
import Lean.Meta.Reduce
import Lean.Elab.DeclarationRange
import Lean.Elab.Eval
import Lean.Elab.Command
import Lean.Elab.Open
import Lean.Elab.SetOption
import Lean.PrettyPrinter
namespace Lean.Elab.Command
@[builtin_command_elab moduleDoc] def elabModuleDoc : CommandElab := fun stx => do
match stx[1] with
| Syntax.atom _ val =>
let doc := val.extract 0 (val.endPos - ⟨2⟩)
let range ← Elab.getDeclarationRange stx
modifyEnv fun env => addMainModuleDoc env ⟨doc, range⟩
| _ => throwErrorAt stx "unexpected module doc string{indentD stx[1]}"
private def addScope (isNewNamespace : Bool) (isNoncomputable : Bool) (header : String) (newNamespace : Name) : CommandElabM Unit := do
modify fun s => { s with
env := s.env.registerNamespace newNamespace,
scopes := { s.scopes.head! with header := header, currNamespace := newNamespace, isNoncomputable := s.scopes.head!.isNoncomputable || isNoncomputable } :: s.scopes
}
pushScope
if isNewNamespace then
activateScoped newNamespace
private def addScopes (isNewNamespace : Bool) (isNoncomputable : Bool) : Name → CommandElabM Unit
| .anonymous => pure ()
| .str p header => do
addScopes isNewNamespace isNoncomputable p
let currNamespace ← getCurrNamespace
addScope isNewNamespace isNoncomputable header (if isNewNamespace then Name.mkStr currNamespace header else currNamespace)
| _ => throwError "invalid scope"
private def addNamespace (header : Name) : CommandElabM Unit :=
addScopes (isNewNamespace := true) (isNoncomputable := false) header
def withNamespace {α} (ns : Name) (elabFn : CommandElabM α) : CommandElabM α := do
addNamespace ns
let a ← elabFn
modify fun s => { s with scopes := s.scopes.drop ns.getNumParts }
pure a
private def popScopes (numScopes : Nat) : CommandElabM Unit :=
for _ in [0:numScopes] do
popScope
private def checkAnonymousScope : List Scope → Option Name
| { header := "", .. } :: _ => none
| { header := h, .. } :: _ => some h
| _ => some .anonymous -- should not happen
private def checkEndHeader : Name → List Scope → Option Name
| .anonymous, _ => none
| .str p s, { header := h, .. } :: scopes =>
if h == s then
(.str · s) <$> checkEndHeader p scopes
else
some h
| _, _ => some .anonymous -- should not happen
@[builtin_command_elab «namespace»] def elabNamespace : CommandElab := fun stx =>
match stx with
| `(namespace $n) => addNamespace n.getId
| _ => throwUnsupportedSyntax
@[builtin_command_elab «section»] def elabSection : CommandElab := fun stx => do
match stx with
| `(section $header:ident) => addScopes (isNewNamespace := false) (isNoncomputable := false) header.getId
| `(section) => addScope (isNewNamespace := false) (isNoncomputable := false) "" (← getCurrNamespace)
| _ => throwUnsupportedSyntax
@[builtin_command_elab noncomputableSection] def elabNonComputableSection : CommandElab := fun stx => do
match stx with
| `(noncomputable section $header:ident) => addScopes (isNewNamespace := false) (isNoncomputable := true) header.getId
| `(noncomputable section) => addScope (isNewNamespace := false) (isNoncomputable := true) "" (← getCurrNamespace)
| _ => throwUnsupportedSyntax
@[builtin_command_elab «end»] def elabEnd : CommandElab := fun stx => do
let header? := (stx.getArg 1).getOptionalIdent?;
let endSize := match header? with
| none => 1
| some n => n.getNumParts
let scopes ← getScopes
if endSize < scopes.length then
modify fun s => { s with scopes := s.scopes.drop endSize }
popScopes endSize
else -- we keep "root" scope
let n := (← get).scopes.length - 1
modify fun s => { s with scopes := s.scopes.drop n }
popScopes n
throwError "invalid 'end', insufficient scopes"
match header? with
| none =>
if let some name := checkAnonymousScope scopes then
throwError "invalid 'end', name is missing (expected {name})"
| some header =>
if let some name := checkEndHeader header scopes then
addCompletionInfo <| CompletionInfo.endSection stx (scopes.map fun scope => scope.header)
throwError "invalid 'end', name mismatch (expected {if name == `«» then `nothing else name})"
private partial def elabChoiceAux (cmds : Array Syntax) (i : Nat) : CommandElabM Unit :=
if h : i < cmds.size then
let cmd := cmds.get ⟨i, h⟩;
catchInternalId unsupportedSyntaxExceptionId
(elabCommand cmd)
(fun _ => elabChoiceAux cmds (i+1))
else
throwUnsupportedSyntax
@[builtin_command_elab choice] def elabChoice : CommandElab := fun stx =>
elabChoiceAux stx.getArgs 0
@[builtin_command_elab «universe»] def elabUniverse : CommandElab := fun n => do
n[1].forArgsM addUnivLevel
@[builtin_command_elab «init_quot»] def elabInitQuot : CommandElab := fun _ => do
match (← getEnv).addDecl Declaration.quotDecl with
| Except.ok env => setEnv env
| Except.error ex => throwError (ex.toMessageData (← getOptions))
@[builtin_command_elab «export»] def elabExport : CommandElab := fun stx => do
let `(export $ns ($ids*)) := stx | throwUnsupportedSyntax
let nss ← resolveNamespace ns
let currNamespace ← getCurrNamespace
if nss == [currNamespace] then throwError "invalid 'export', self export"
let mut aliases := #[]
for idStx in ids do
let id := idStx.getId
let declName ← resolveNameUsingNamespaces nss idStx
aliases := aliases.push (currNamespace ++ id, declName)
modify fun s => { s with env := aliases.foldl (init := s.env) fun env p => addAlias env p.1 p.2 }
@[builtin_command_elab «open»] def elabOpen : CommandElab
| `(open $decl:openDecl) => do
let openDecls ← elabOpenDecl decl
modifyScope fun scope => { scope with openDecls := openDecls }
| _ => throwUnsupportedSyntax
open Lean.Parser.Term
private def typelessBinder? : Syntax → Option (Array (TSyntax [`ident, `Lean.Parser.Term.hole]) × Bool)
| `(bracketedBinderF|($ids*)) => some (ids, true)
| `(bracketedBinderF|{$ids*}) => some (ids, false)
| _ => none
/-- If `id` is an identifier, return true if `ids` contains `id`. -/
private def containsId (ids : Array (TSyntax [`ident, ``Parser.Term.hole])) (id : TSyntax [`ident, ``Parser.Term.hole]) : Bool :=
id.raw.isIdent && ids.any fun id' => id'.raw.getId == id.raw.getId
/--
Auxiliary method for processing binder annotation update commands: `variable (α)` and `variable {α}`.
The argument `binder` is the binder of the `variable` command.
The method retuns an array containing the "residue", that is, variables that do not correspond to updates.
Recall that a `bracketedBinder` can be of the form `(x y)`.
```
variable {α β : Type}
variable (α γ)
```
The second `variable` command updates the binder annotation for `α`, and returns "residue" `γ`.
-/
private def replaceBinderAnnotation (binder : TSyntax ``Parser.Term.bracketedBinder) : CommandElabM (Array (TSyntax ``Parser.Term.bracketedBinder)) := do
let some (binderIds, explicit) := typelessBinder? binder | return #[binder]
let varDecls := (← getScope).varDecls
let mut varDeclsNew := #[]
let mut binderIds := binderIds
let mut binderIdsIniSize := binderIds.size
let mut modifiedVarDecls := false
for varDecl in varDecls do
let (ids, ty?, explicit') ← match varDecl with
| `(bracketedBinderF|($ids* $[: $ty?]? $(annot?)?)) =>
if annot?.isSome then
for binderId in binderIds do
if containsId ids binderId then
throwErrorAt binderId "cannot update binder annotation of variables with default values/tactics"
pure (ids, ty?, true)
| `(bracketedBinderF|{$ids* $[: $ty?]?}) =>
pure (ids, ty?, false)
| `(bracketedBinderF|[$id : $_]) =>
for binderId in binderIds do
if binderId.raw.isIdent && binderId.raw.getId == id.getId then
throwErrorAt binderId "cannot change the binder annotation of the previously declared local instance `{id.getId}`"
varDeclsNew := varDeclsNew.push varDecl; continue
| _ =>
varDeclsNew := varDeclsNew.push varDecl; continue
if explicit == explicit' then
-- no update, ensure we don't have redundant annotations.
for binderId in binderIds do
if containsId ids binderId then
throwErrorAt binderId "redundant binder annotation update"
varDeclsNew := varDeclsNew.push varDecl
else if binderIds.all fun binderId => !containsId ids binderId then
-- `binderIds` and `ids` are disjoint
varDeclsNew := varDeclsNew.push varDecl
else
let mkBinder (id : TSyntax [`ident, ``Parser.Term.hole]) (explicit : Bool) : CommandElabM (TSyntax ``Parser.Term.bracketedBinder) :=
if explicit then
`(bracketedBinderF| ($id $[: $ty?]?))
else
`(bracketedBinderF| {$id $[: $ty?]?})
for id in ids do
if let some idx := binderIds.findIdx? fun binderId => binderId.raw.isIdent && binderId.raw.getId == id.raw.getId then
binderIds := binderIds.eraseIdx idx
modifiedVarDecls := true
varDeclsNew := varDeclsNew.push (← mkBinder id explicit)
else
varDeclsNew := varDeclsNew.push (← mkBinder id explicit')
if modifiedVarDecls then
modifyScope fun scope => { scope with varDecls := varDeclsNew }
if binderIds.size != binderIdsIniSize then
binderIds.mapM fun binderId =>
if explicit then
`(bracketedBinderF| ($binderId))
else
`(bracketedBinderF| {$binderId})
else
return #[binder]
@[builtin_command_elab «variable»] def elabVariable : CommandElab
| `(variable $binders*) => do
-- Try to elaborate `binders` for sanity checking
runTermElabM fun _ => Term.withAutoBoundImplicit <|
Term.elabBinders binders fun _ => pure ()
for binder in binders do
let binders ← replaceBinderAnnotation binder
-- Remark: if we want to produce error messages when variables shadow existing ones, here is the place to do it.
for binder in binders do
let varUIds ← getBracketedBinderIds binder |>.mapM (withFreshMacroScope ∘ MonadQuotation.addMacroScope)
modifyScope fun scope => { scope with varDecls := scope.varDecls.push binder, varUIds := scope.varUIds ++ varUIds }
| _ => throwUnsupportedSyntax
open Meta
def elabCheckCore (ignoreStuckTC : Bool) : CommandElab
| `(#check%$tk $term) => withoutModifyingEnv <| runTermElabM fun _ => Term.withDeclName `_check do
-- show signature for `#check id`/`#check @id`
if let `($_:ident) := term then
try
for c in (← resolveGlobalConstWithInfos term) do
addCompletionInfo <| .id term c (danglingDot := false) {} none
logInfoAt tk <| .ofPPFormat { pp := fun
| some ctx => ctx.runMetaM <| PrettyPrinter.ppSignature c
| none => return f!"{c}" -- should never happen
}
return
catch _ => pure () -- identifier might not be a constant but constant + projection
let e ← Term.elabTerm term none
Term.synthesizeSyntheticMVarsNoPostponing (ignoreStuckTC := ignoreStuckTC)
let e ← Term.levelMVarToParam (← instantiateMVars e)
let type ← inferType e
if e.isSyntheticSorry then
return
logInfoAt tk m!"{e} : {type}"
| _ => throwUnsupportedSyntax
@[builtin_command_elab Lean.Parser.Command.check] def elabCheck : CommandElab := elabCheckCore (ignoreStuckTC := true)
@[builtin_command_elab Lean.Parser.Command.reduce] def elabReduce : CommandElab
| `(#reduce%$tk $term) => withoutModifyingEnv <| runTermElabM fun _ => Term.withDeclName `_reduce do
let e ← Term.elabTerm term none
Term.synthesizeSyntheticMVarsNoPostponing
let e ← Term.levelMVarToParam (← instantiateMVars e)
-- TODO: add options or notation for setting the following parameters
withTheReader Core.Context (fun ctx => { ctx with options := ctx.options.setBool `smartUnfolding false }) do
let e ← withTransparency (mode := TransparencyMode.all) <| reduce e (skipProofs := false) (skipTypes := false)
logInfoAt tk e
| _ => throwUnsupportedSyntax
def hasNoErrorMessages : CommandElabM Bool := do
return !(← get).messages.hasErrors
def failIfSucceeds (x : CommandElabM Unit) : CommandElabM Unit := do
let resetMessages : CommandElabM MessageLog := do
let s ← get
let messages := s.messages;
modify fun s => { s with messages := {} };
pure messages
let restoreMessages (prevMessages : MessageLog) : CommandElabM Unit := do
modify fun s => { s with messages := prevMessages ++ s.messages.errorsToWarnings }
let prevMessages ← resetMessages
let succeeded ← try
x
hasNoErrorMessages
catch
| ex@(Exception.error _ _) => do logException ex; pure false
| Exception.internal id _ => do logError (← id.getName); pure false
finally
restoreMessages prevMessages
if succeeded then
throwError "unexpected success"
@[builtin_command_elab «check_failure»] def elabCheckFailure : CommandElab
| `(#check_failure $term) => do
failIfSucceeds <| elabCheckCore (ignoreStuckTC := false) (← `(#check $term))
| _ => throwUnsupportedSyntax
private def mkEvalInstCore (evalClassName : Name) (e : Expr) : MetaM Expr := do
let α ← inferType e
let u ← getDecLevel α
let inst := mkApp (Lean.mkConst evalClassName [u]) α
try
synthInstance inst
catch _ =>
-- Put `α` in WHNF and try again
try
let α ← whnf α
synthInstance (mkApp (Lean.mkConst evalClassName [u]) α)
catch _ =>
-- Fully reduce `α` and try again
try
let α ← reduce (skipTypes := false) α
synthInstance (mkApp (Lean.mkConst evalClassName [u]) α)
catch _ =>
throwError "expression{indentExpr e}\nhas type{indentExpr α}\nbut instance{indentExpr inst}\nfailed to be synthesized, this instance instructs Lean on how to display the resulting value, recall that any type implementing the `Repr` class also implements the `{evalClassName}` class"
private def mkRunMetaEval (e : Expr) : MetaM Expr :=
withLocalDeclD `env (mkConst ``Lean.Environment) fun env =>
withLocalDeclD `opts (mkConst ``Lean.Options) fun opts => do
let α ← inferType e
let u ← getDecLevel α
let instVal ← mkEvalInstCore ``Lean.MetaEval e
let e := mkAppN (mkConst ``Lean.runMetaEval [u]) #[α, instVal, env, opts, e]
instantiateMVars (← mkLambdaFVars #[env, opts] e)
private def mkRunEval (e : Expr) : MetaM Expr := do
let α ← inferType e
let u ← getDecLevel α
let instVal ← mkEvalInstCore ``Lean.Eval e
instantiateMVars (mkAppN (mkConst ``Lean.runEval [u]) #[α, instVal, mkSimpleThunk e])
unsafe def elabEvalUnsafe : CommandElab
| `(#eval%$tk $term) => do
let declName := `_eval
let addAndCompile (value : Expr) : TermElabM Unit := do
let value ← Term.levelMVarToParam (← instantiateMVars value)
let type ← inferType value
let us := collectLevelParams {} value |>.params
let value ← instantiateMVars value
let decl := Declaration.defnDecl {
name := declName
levelParams := us.toList
type := type
value := value
hints := ReducibilityHints.opaque
safety := DefinitionSafety.unsafe
}
Term.ensureNoUnassignedMVars decl
addAndCompile decl
-- Elaborate `term`
let elabEvalTerm : TermElabM Expr := do
let e ← Term.elabTerm term none
Term.synthesizeSyntheticMVarsNoPostponing
if (← Term.logUnassignedUsingErrorInfos (← getMVars e)) then throwAbortTerm
if (← isProp e) then
mkDecide e
else
return e
-- Evaluate using term using `MetaEval` class.
let elabMetaEval : CommandElabM Unit := do
-- act? is `some act` if elaborated `term` has type `CommandElabM α`
let act? ← runTermElabM fun _ => Term.withDeclName declName do
let e ← elabEvalTerm
let eType ← instantiateMVars (← inferType e)
if eType.isAppOfArity ``CommandElabM 1 then
let mut stx ← Term.exprToSyntax e
unless (← isDefEq eType.appArg! (mkConst ``Unit)) do
stx ← `($stx >>= fun v => IO.println (repr v))
let act ← Lean.Elab.Term.evalTerm (CommandElabM Unit) (mkApp (mkConst ``CommandElabM) (mkConst ``Unit)) stx
pure <| some act
else
let e ← mkRunMetaEval e
let env ← getEnv
let opts ← getOptions
let act ← try addAndCompile e; evalConst (Environment → Options → IO (String × Except IO.Error Environment)) declName finally setEnv env
let (out, res) ← act env opts -- we execute `act` using the environment
logInfoAt tk out
match res with
| Except.error e => throwError e.toString
| Except.ok env => do setEnv env; pure none
let some act := act? | return ()
act
-- Evaluate using term using `Eval` class.
let elabEval : CommandElabM Unit := runTermElabM fun _ => Term.withDeclName declName do
-- fall back to non-meta eval if MetaEval hasn't been defined yet
-- modify e to `runEval e`
let e ← mkRunEval (← elabEvalTerm)
let env ← getEnv
let act ← try addAndCompile e; evalConst (IO (String × Except IO.Error Unit)) declName finally setEnv env
let (out, res) ← liftM (m := IO) act
logInfoAt tk out
match res with
| Except.error e => throwError e.toString
| Except.ok _ => pure ()
if (← getEnv).contains ``Lean.MetaEval then do
elabMetaEval
else
elabEval
| _ => throwUnsupportedSyntax
@[builtin_command_elab «eval», implemented_by elabEvalUnsafe]
opaque elabEval : CommandElab
@[builtin_command_elab «synth»] def elabSynth : CommandElab := fun stx => do
let term := stx[1]
withoutModifyingEnv <| runTermElabM fun _ => Term.withDeclName `_synth_cmd do
let inst ← Term.elabTerm term none
Term.synthesizeSyntheticMVarsNoPostponing
let inst ← instantiateMVars inst
let val ← synthInstance inst
logInfo val
pure ()
@[builtin_command_elab «set_option»] def elabSetOption : CommandElab := fun stx => do
let options ← Elab.elabSetOption stx[1] stx[2]
modify fun s => { s with maxRecDepth := maxRecDepth.get options }
modifyScope fun scope => { scope with opts := options }
@[builtin_macro Lean.Parser.Command.«in»] def expandInCmd : Macro
| `($cmd₁ in $cmd₂) => `(section $cmd₁:command $cmd₂ end)
| _ => Macro.throwUnsupported
@[builtin_command_elab Parser.Command.addDocString] def elabAddDeclDoc : CommandElab := fun stx => do
match stx with
| `($doc:docComment add_decl_doc $id) =>
let declName ← resolveGlobalConstNoOverloadWithInfo id
if let .none ← findDeclarationRangesCore? declName then
-- this is only relevant for declarations added without a declaration range
-- in particular `Quot.mk` et al which are added by `init_quot`
addAuxDeclarationRanges declName stx id
addDocString declName (← getDocStringText doc)
| _ => throwUnsupportedSyntax
@[builtin_command_elab Parser.Command.exit] def elabExit : CommandElab := fun _ =>
logWarning "using 'exit' to interrupt Lean"
@[builtin_command_elab Parser.Command.import] def elabImport : CommandElab := fun _ =>
throwError "invalid 'import' command, it must be used in the beginning of the file"
@[builtin_command_elab Parser.Command.eoi] def elabEoi : CommandElab := fun _ =>
return
end Lean.Elab.Command
|
802e403d852b4ab84482107feba2f6530d2b9d3f | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/data/bool.lean | 72253feec3c3939e4802b2c5991bf1dc1878b4eb | [
"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 | 7,832 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad
-/
/-!
# booleans
This file proves various trivial lemmas about booleans and their
relation to decidable propositions.
## Notations
This file introduces the notation `!b` for `bnot b`, the boolean "not".
## Tags
bool, boolean, De Morgan
-/
prefix `!`:90 := bnot
namespace bool
-- TODO: duplicate of a lemma in core
theorem coe_sort_tt : coe_sort.{1 1} tt = true := coe_sort_tt
-- TODO: duplicate of a lemma in core
theorem coe_sort_ff : coe_sort.{1 1} ff = false := coe_sort_ff
-- TODO: duplicate of a lemma in core
theorem to_bool_true {h} : @to_bool true h = tt :=
to_bool_true_eq_tt h
-- TODO: duplicate of a lemma in core
theorem to_bool_false {h} : @to_bool false h = ff :=
to_bool_false_eq_ff h
@[simp] theorem to_bool_coe (b:bool) {h} : @to_bool b h = b :=
(show _ = to_bool b, by congr).trans (by cases b; refl)
theorem coe_to_bool (p : Prop) [decidable p] : to_bool p ↔ p := to_bool_iff _
@[simp] lemma of_to_bool_iff {p : Prop} [decidable p] : to_bool p ↔ p :=
⟨of_to_bool_true, _root_.to_bool_true⟩
@[simp] lemma tt_eq_to_bool_iff {p : Prop} [decidable p] : tt = to_bool p ↔ p :=
eq_comm.trans of_to_bool_iff
@[simp] lemma ff_eq_to_bool_iff {p : Prop} [decidable p] : ff = to_bool p ↔ ¬ p :=
eq_comm.trans (to_bool_ff_iff _)
@[simp] theorem to_bool_not (p : Prop) [decidable p] : to_bool (¬ p) = bnot (to_bool p) :=
by by_cases p; simp *
@[simp] theorem to_bool_and (p q : Prop) [decidable p] [decidable q] :
to_bool (p ∧ q) = p && q :=
by by_cases p; by_cases q; simp *
@[simp] theorem to_bool_or (p q : Prop) [decidable p] [decidable q] :
to_bool (p ∨ q) = p || q :=
by by_cases p; by_cases q; simp *
@[simp] theorem to_bool_eq {p q : Prop} [decidable p] [decidable q] :
to_bool p = to_bool q ↔ (p ↔ q) :=
⟨λ h, (coe_to_bool p).symm.trans $ by simp [h], to_bool_congr⟩
lemma not_ff : ¬ ff := by simp
@[simp] theorem default_bool : default bool = ff := rfl
theorem dichotomy (b : bool) : b = ff ∨ b = tt :=
by cases b; simp
@[simp] theorem forall_bool {p : bool → Prop} : (∀ b, p b) ↔ p ff ∧ p tt :=
⟨λ h, by simp [h], λ ⟨h₁, h₂⟩ b, by cases b; assumption⟩
@[simp] theorem exists_bool {p : bool → Prop} : (∃ b, p b) ↔ p ff ∨ p tt :=
⟨λ ⟨b, h⟩, by cases b; [exact or.inl h, exact or.inr h],
λ h, by cases h; exact ⟨_, h⟩⟩
/-- If `p b` is decidable for all `b : bool`, then `∀ b, p b` is decidable -/
instance decidable_forall_bool {p : bool → Prop} [∀ b, decidable (p b)] : decidable (∀ b, p b) :=
decidable_of_decidable_of_iff and.decidable forall_bool.symm
/-- If `p b` is decidable for all `b : bool`, then `∃ b, p b` is decidable -/
instance decidable_exists_bool {p : bool → Prop} [∀ b, decidable (p b)] : decidable (∃ b, p b) :=
decidable_of_decidable_of_iff or.decidable exists_bool.symm
@[simp] theorem cond_ff {α} (t e : α) : cond ff t e = e := rfl
@[simp] theorem cond_tt {α} (t e : α) : cond tt t e = t := rfl
@[simp] theorem cond_to_bool {α} (p : Prop) [decidable p] (t e : α) :
cond (to_bool p) t e = if p then t else e :=
by by_cases p; simp *
@[simp] theorem cond_bnot {α} (b : bool) (t e : α) : cond (!b) t e = cond b e t :=
by cases b; refl
theorem coe_bool_iff : ∀ {a b : bool}, (a ↔ b) ↔ a = b := dec_trivial
theorem eq_tt_of_ne_ff : ∀ {a : bool}, a ≠ ff → a = tt := dec_trivial
theorem eq_ff_of_ne_tt : ∀ {a : bool}, a ≠ tt → a = ff := dec_trivial
theorem bor_comm : ∀ a b, a || b = b || a := dec_trivial
@[simp] theorem bor_assoc : ∀ a b c, (a || b) || c = a || (b || c) := dec_trivial
theorem bor_left_comm : ∀ a b c, a || (b || c) = b || (a || c) := dec_trivial
theorem bor_inl {a b : bool} (H : a) : a || b :=
by simp [H]
theorem bor_inr {a b : bool} (H : b) : a || b :=
by simp [H]
theorem band_comm : ∀ a b, a && b = b && a := dec_trivial
@[simp] theorem band_assoc : ∀ a b c, (a && b) && c = a && (b && c) := dec_trivial
theorem band_left_comm : ∀ a b c, a && (b && c) = b && (a && c) := dec_trivial
theorem band_elim_left : ∀ {a b : bool}, a && b → a := dec_trivial
theorem band_intro : ∀ {a b : bool}, a → b → a && b := dec_trivial
theorem band_elim_right : ∀ {a b : bool}, a && b → b := dec_trivial
@[simp] theorem bnot_false : bnot ff = tt := rfl
@[simp] theorem bnot_true : bnot tt = ff := rfl
theorem eq_tt_of_bnot_eq_ff : ∀ {a : bool}, bnot a = ff → a = tt := dec_trivial
theorem eq_ff_of_bnot_eq_tt : ∀ {a : bool}, bnot a = tt → a = ff := dec_trivial
theorem bxor_comm : ∀ a b, bxor a b = bxor b a := dec_trivial
@[simp] theorem bxor_assoc : ∀ a b c, bxor (bxor a b) c = bxor a (bxor b c) := dec_trivial
theorem bxor_left_comm : ∀ a b c, bxor a (bxor b c) = bxor b (bxor a c) := dec_trivial
@[simp] theorem bxor_bnot_left : ∀ a, bxor (!a) a = tt := dec_trivial
@[simp] theorem bxor_bnot_right : ∀ a, bxor a (!a) = tt := dec_trivial
@[simp] theorem bxor_bnot_bnot : ∀ a b, bxor (!a) (!b) = bxor a b := dec_trivial
@[simp] theorem bxor_ff_left : ∀ a, bxor ff a = a := dec_trivial
@[simp] theorem bxor_ff_right : ∀ a, bxor a ff = a := dec_trivial
lemma bxor_iff_ne : ∀ {x y : bool}, bxor x y = tt ↔ x ≠ y := dec_trivial
/-! ### De Morgan's laws for booleans-/
@[simp] lemma bnot_band : ∀ (a b : bool), !(a && b) = !a || !b := dec_trivial
@[simp] lemma bnot_bor : ∀ (a b : bool), !(a || b) = !a && !b := dec_trivial
lemma bnot_inj : ∀ {a b : bool}, !a = !b → a = b := dec_trivial
instance : linear_order bool :=
{ le := λ a b, a = ff ∨ b = tt,
le_refl := dec_trivial,
le_trans := dec_trivial,
le_antisymm := dec_trivial,
le_total := dec_trivial,
decidable_le := infer_instance,
decidable_eq := infer_instance,
decidable_lt := infer_instance,
max := bor,
max_def := by { funext x y, revert x y, exact dec_trivial },
min := band,
min_def := by { funext x y, revert x y, exact dec_trivial } }
@[simp] lemma ff_le {x : bool} : ff ≤ x := or.intro_left _ rfl
@[simp] lemma le_tt {x : bool} : x ≤ tt := or.intro_right _ rfl
@[simp] lemma ff_lt_tt : ff < tt := lt_of_le_of_ne ff_le ff_ne_tt
lemma le_iff_imp : ∀ {x y : bool}, x ≤ y ↔ (x → y) := dec_trivial
lemma band_le_left : ∀ x y : bool, x && y ≤ x := dec_trivial
lemma band_le_right : ∀ x y : bool, x && y ≤ y := dec_trivial
lemma le_band : ∀ {x y z : bool}, x ≤ y → x ≤ z → x ≤ y && z := dec_trivial
lemma left_le_bor : ∀ x y : bool, x ≤ x || y := dec_trivial
lemma right_le_bor : ∀ x y : bool, y ≤ x || y := dec_trivial
lemma bor_le : ∀ {x y z}, x ≤ z → y ≤ z → x || y ≤ z := dec_trivial
/-- convert a `bool` to a `ℕ`, `false -> 0`, `true -> 1` -/
def to_nat (b : bool) : ℕ :=
cond b 1 0
/-- convert a `ℕ` to a `bool`, `0 -> false`, everything else -> `true` -/
def of_nat (n : ℕ) : bool :=
to_bool (n ≠ 0)
lemma of_nat_le_of_nat {n m : ℕ} (h : n ≤ m) : of_nat n ≤ of_nat m :=
begin
simp [of_nat];
cases nat.decidable_eq n 0;
cases nat.decidable_eq m 0;
simp only [to_bool],
{ subst m, have h := le_antisymm h (nat.zero_le _),
contradiction },
{ left, refl }
end
lemma to_nat_le_to_nat {b₀ b₁ : bool} (h : b₀ ≤ b₁) : to_nat b₀ ≤ to_nat b₁ :=
by cases h; subst h; [cases b₁, cases b₀]; simp [to_nat,nat.zero_le]
lemma of_nat_to_nat (b : bool) : of_nat (to_nat b) = b :=
by cases b; simp only [of_nat,to_nat]; exact dec_trivial
@[simp] lemma injective_iff {α : Sort*} {f : bool → α} : function.injective f ↔ f ff ≠ f tt :=
⟨λ Hinj Heq, ff_ne_tt (Hinj Heq),
λ H x y hxy, by { cases x; cases y, exacts [rfl, (H hxy).elim, (H hxy.symm).elim, rfl] }⟩
end bool
|
dbb3dbafa64cf63a106263ffd73a5708c1f05286 | dd4e652c749fea9ac77e404005cb3470e5f75469 | /src/vector.lean | eed2bca7c5ff7f85deecea93344388483fc6bfbc | [] | no_license | skbaek/cvx | e32822ad5943541539966a37dee162b0a5495f55 | c50c790c9116f9fac8dfe742903a62bdd7292c15 | refs/heads/master | 1,623,803,010,339 | 1,618,058,958,000 | 1,618,058,958,000 | 176,293,135 | 3 | 2 | null | null | null | null | UTF-8 | Lean | false | false | 4,060 | lean | import data.vector .list
variables {α : Type} {k m n : nat}
open tactic
namespace vector
def zero [has_zero α] (m) : vector α m :=
vector.repeat 0 m
instance has_zero [has_zero α] : has_zero (vector α m) := ⟨zero m⟩
lemma zero_succ [has_zero α] {m} :
(0 : vector α (m+1)) = (0 : α)::(0 : vector α m) := rfl
def neg [has_neg α] (v : vector α m) : vector α m :=
⟨v.val.neg, eq.trans (list.length_neg _) v.property⟩
instance has_neg [has_neg α]: has_neg (vector α m) := ⟨neg⟩
lemma val_neg [has_neg α] (v : vector α k) :
(-v).val = list.neg v.val := rfl
def add [has_add α] (v w : vector α k) : vector α k :=
⟨ list.add v.val w.val,
calc (list.add (v.val) (w.val)).length
= max (list.length (v.val)) (list.length (w.val)) : list.length_add
... = v.val.length :
begin
apply max_eq_left (le_of_eq _),
apply eq.trans w.property v.property.symm
end
... = k : v.property ⟩
instance has_add [has_add α] : has_add (vector α k) := ⟨add⟩
lemma val_add [has_add α] (v w : vector α k) :
(v + w).val = list.add v.val w.val := rfl
lemma add_assoc [add_group α] (a b c : vector α m) :
a + b + c = a + (b + c) :=
begin apply subtype.eq, simp only [val_add], apply list.add_assoc end
lemma val_zero_equiv_nil [has_zero α] {m} :
(@zero α _ m).val ≃ [] :=
begin
intro k, simp only [zero, repeat, list.get_nil],
cases list.mem_get_or_get_eq_zero k (list.repeat (0 : α) m),
apply list.eq_of_mem_repeat h, exact h
end
lemma zero_add [add_group α] (a : vector α m) : 0 + a = a :=
begin
apply subtype.eq, simp only [val_add], apply list.eq_of_equiv,
{ apply list.length_add_eq_length_right
(zero m).property a.property },
{ apply list.equiv_trans
(list.add_equiv_add val_zero_equiv_nil list.equiv_refl)
(list.equiv_of_eq list.nil_add) }
end
lemma add_zero [add_group α] (a : vector α m) : a + 0 = a :=
begin
apply subtype.eq, simp only [val_add], apply list.eq_of_equiv,
{ apply list.length_add_eq_length_left
a.property (zero m).property },
{ apply list.equiv_trans
(list.add_equiv_add list.equiv_refl val_zero_equiv_nil)
(list.equiv_of_eq list.add_nil) }
end
lemma add_left_neg [add_group α] (a : vector α m) : -a + a = 0 :=
begin
apply subtype.eq, simp only [val_neg, val_add],
apply list.eq_of_equiv,
{ rw list.length_add_eq_length_left _ a.property,
rw list.length_neg,
apply eq.trans a.property (zero m).property.symm,
rw list.length_neg, apply a.property },
{ apply list.equiv_trans list.add_left_neg
(list.equiv_symm val_zero_equiv_nil) }
end
instance add_group [add_group α] : add_group (vector α m) :=
{ add := add,
add_assoc := add_assoc,
zero := zero m,
zero_add := zero_add,
add_zero := add_zero,
neg := neg,
add_left_neg := add_left_neg }
def dot_prod [ring α] (v w : vector α k) : α :=
list.dot_prod v.val w.val
infix `⬝` := dot_prod
--def zero_dot_prod [ring α] (v : vector α k) : 0 ⬝ v = 0 := sorry
--def dot_prod_zero [ring α] (v : vector α k) : v ⬝ 0 = 0 := sorry
def sum [add_monoid α] : ∀ {k}, vector α k → α
| 0 _ := 0
| (k+1) v := v.head + @sum k v.tail
end vector
/- (mk_meta_vector k) returns the expr of a vector of length k,
where the expr of each entry is a metavariable. -/
meta def mk_meta_vector (αx : expr) : nat → tactic expr
| 0 := to_expr ``(@vector.nil %%αx)
| (k+1) :=
do x ← mk_meta_var αx,
vx ← mk_meta_vector k,
to_expr ``(@vector.cons %%αx %%`(k) %%x %%vx)
/- (vector₂.mk_meta m n) returns the expr of an m × n vector₂,
where the expr of each entry is a metavariable. -/
meta def mk_meta_vector₂ (αx : expr) : nat → nat → tactic expr
| 0 n := to_expr ``(@vector.nil (vector %%αx %%`(n)))
| (m+1) n :=
do v₁x ← mk_meta_vector αx n,
v₂x ← mk_meta_vector₂ m n,
to_expr ``(@vector.cons (vector %%αx %%`(n)) %%`(m) %%v₁x %%v₂x)
def vector₂ (α : Type) (m n : nat) : Type := vector (vector α n) m |
64c46219a31c972d8c047f24dd871556a61e0b7b | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/order/complete_boolean_algebra.lean | f57bcd8473ed8fd5255a7ec9929685d5455fc8e3 | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 5,892 | 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
Theory of complete Boolean algebras.
-/
import order.complete_lattice
set_option old_structure_cmd true
universes u v w
variables {α : Type u} {β : Type v} {ι : Sort w}
/-- A complete distributive lattice is a bit stronger than the name might
suggest; perhaps completely distributive lattice is more descriptive,
as this class includes a requirement that the lattice join
distribute over *arbitrary* infima, and similarly for the dual. -/
class complete_distrib_lattice α extends complete_lattice α :=
(infi_sup_le_sup_Inf : ∀a s, (⨅ b ∈ s, a ⊔ b) ≤ a ⊔ Inf s)
(inf_Sup_le_supr_inf : ∀a s, a ⊓ Sup s ≤ (⨆ b ∈ s, a ⊓ b))
section complete_distrib_lattice
variables [complete_distrib_lattice α] {a b : α} {s t : set α}
instance : complete_distrib_lattice (order_dual α) :=
{ infi_sup_le_sup_Inf := complete_distrib_lattice.inf_Sup_le_supr_inf,
inf_Sup_le_supr_inf := complete_distrib_lattice.infi_sup_le_sup_Inf,
.. order_dual.complete_lattice α }
theorem sup_Inf_eq : a ⊔ Inf s = (⨅ b ∈ s, a ⊔ b) :=
sup_Inf_le_infi_sup.antisymm (complete_distrib_lattice.infi_sup_le_sup_Inf _ _)
theorem Inf_sup_eq : Inf s ⊔ b = (⨅ a ∈ s, a ⊔ b) :=
by simpa only [sup_comm] using @sup_Inf_eq α _ b s
theorem inf_Sup_eq : a ⊓ Sup s = (⨆ b ∈ s, a ⊓ b) :=
(complete_distrib_lattice.inf_Sup_le_supr_inf _ _).antisymm supr_inf_le_inf_Sup
theorem Sup_inf_eq : Sup s ⊓ b = (⨆ a ∈ s, a ⊓ b) :=
by simpa only [inf_comm] using @inf_Sup_eq α _ b s
theorem supr_inf_eq (f : ι → α) (a : α) : (⨆ i, f i) ⊓ a = ⨆ i, f i ⊓ a :=
by rw [supr, Sup_inf_eq, supr_range]
theorem inf_supr_eq (a : α) (f : ι → α) : a ⊓ (⨆ i, f i) = ⨆ i, a ⊓ f i :=
by simpa only [inf_comm] using supr_inf_eq f a
theorem infi_sup_eq (f : ι → α) (a : α) : (⨅ i, f i) ⊔ a = ⨅ i, f i ⊔ a :=
@supr_inf_eq (order_dual α) _ _ _ _
theorem sup_infi_eq (a : α) (f : ι → α) : a ⊔ (⨅ i, f i) = ⨅ i, a ⊔ f i :=
@inf_supr_eq (order_dual α) _ _ _ _
instance pi.complete_distrib_lattice {ι : Type*} {π : ι → Type*}
[∀ i, complete_distrib_lattice (π i)] : complete_distrib_lattice (Π i, π i) :=
{ infi_sup_le_sup_Inf := λ a s i,
by simp only [← sup_infi_eq, complete_lattice.Inf, Inf_apply, ←infi_subtype'', infi_apply,
sup_apply],
inf_Sup_le_supr_inf := λ a s i,
by simp only [complete_lattice.Sup, Sup_apply, supr_apply, inf_apply, inf_supr_eq,
← supr_subtype''],
.. pi.complete_lattice }
theorem Inf_sup_Inf : Inf s ⊔ Inf t = (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) :=
begin
apply le_antisymm,
{ simp only [and_imp, prod.forall, le_infi_iff, set.mem_prod],
intros a b ha hb,
exact sup_le_sup (Inf_le ha) (Inf_le hb) },
{ have : ∀ a ∈ s, (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) ≤ a ⊔ Inf t,
{ assume a ha,
have : (⨅p ∈ set.prod s t, ((p : α × α).1 : α) ⊔ p.2) ≤
(⨅p ∈ prod.mk a '' t, (p : α × α).1 ⊔ p.2),
{ apply infi_le_infi_of_subset,
rintros ⟨x, y⟩,
simp only [and_imp, set.mem_image, prod.mk.inj_iff, set.prod_mk_mem_set_prod_eq,
exists_imp_distrib],
assume x' x't ax x'y,
rw [← x'y, ← ax],
simp [ha, x't] },
rw [infi_image] at this,
simp only at this,
rwa ← sup_Inf_eq at this },
calc (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) ≤ (⨅a∈s, a ⊔ Inf t) : by simp; exact this
... = Inf s ⊔ Inf t : Inf_sup_eq.symm }
end
theorem Sup_inf_Sup : Sup s ⊓ Sup t = (⨆p ∈ set.prod s t, (p : α × α).1 ⊓ p.2) :=
@Inf_sup_Inf (order_dual α) _ _ _
lemma supr_disjoint_iff {f : ι → α} : disjoint (⨆ i, f i) a ↔ ∀ i, disjoint (f i) a :=
by simp only [disjoint_iff, supr_inf_eq, supr_eq_bot]
lemma disjoint_supr_iff {f : ι → α} : disjoint a (⨆ i, f i) ↔ ∀ i, disjoint a (f i) :=
by simpa only [disjoint.comm] using @supr_disjoint_iff _ _ _ a f
end complete_distrib_lattice
@[priority 100] -- see Note [lower instance priority]
instance complete_distrib_lattice.bounded_distrib_lattice [d : complete_distrib_lattice α] :
bounded_distrib_lattice α :=
{ le_sup_inf := λ x y z, by rw [← Inf_pair, ← Inf_pair, sup_Inf_eq, ← Inf_image, set.image_pair],
..d }
/-- A complete boolean algebra is a completely distributive boolean algebra. -/
class complete_boolean_algebra α extends boolean_algebra α, complete_distrib_lattice α
instance pi.complete_boolean_algebra {ι : Type*} {π : ι → Type*}
[∀ i, complete_boolean_algebra (π i)] : complete_boolean_algebra (Π i, π i) :=
{ .. pi.boolean_algebra, .. pi.complete_distrib_lattice }
instance Prop.complete_boolean_algebra : complete_boolean_algebra Prop :=
{ infi_sup_le_sup_Inf := λ p s, iff.mp $
by simp only [forall_or_distrib_left, complete_lattice.Inf, infi_Prop_eq, sup_Prop_eq],
inf_Sup_le_supr_inf := λ p s, iff.mp $
by simp only [complete_lattice.Sup, exists_and_distrib_left, inf_Prop_eq, supr_Prop_eq],
.. Prop.boolean_algebra, .. Prop.complete_lattice }
section complete_boolean_algebra
variables [complete_boolean_algebra α] {a b : α} {s : set α} {f : ι → α}
theorem compl_infi : (infi f)ᶜ = (⨆i, (f i)ᶜ) :=
le_antisymm
(compl_le_of_compl_le $ le_infi $ assume i, compl_le_of_compl_le $ le_supr (compl ∘ f) i)
(supr_le $ assume i, compl_le_compl $ infi_le _ _)
theorem compl_supr : (supr f)ᶜ = (⨅i, (f i)ᶜ) :=
compl_injective (by simp [compl_infi])
theorem compl_Inf : (Inf s)ᶜ = (⨆i∈s, iᶜ) :=
by simp only [Inf_eq_infi, compl_infi]
theorem compl_Sup : (Sup s)ᶜ = (⨅i∈s, iᶜ) :=
by simp only [Sup_eq_supr, compl_supr]
end complete_boolean_algebra
|
c319c64cdfa27174d0432533ce8708d16f1a184a | 471bedbd023d35c9d078c2f936dd577ace7f5813 | /library/init/algebra/functions.lean | 58e69f4a475aba1dd73e9fe926846dd2470bdb56 | [
"Apache-2.0"
] | permissive | lambdaxymox/lean | e06f0fa503666df827edd9867d7f49ca017aae64 | fc13c8c72a15dab71a2c2b31410c2cadc3526bd7 | refs/heads/master | 1,666,785,407,985 | 1,666,153,673,000 | 1,666,153,673,000 | 310,165,986 | 0 | 0 | Apache-2.0 | 1,604,542,096,000 | 1,604,542,095,000 | null | UTF-8 | Lean | false | false | 4,527 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
-/
prelude
import init.algebra.order init.meta
universe u
export linear_order (min max)
section
open decidable tactic
variables {α : Type u} [linear_order α]
lemma min_def (a b : α) : min a b = if a ≤ b then a else b :=
by rw [congr_fun linear_order.min_def a, min_default]
lemma max_def (a b : α) : max a b = if b ≤ a then a else b :=
by rw [congr_fun linear_order.max_def a, max_default]
private meta def min_tac_step : tactic unit :=
solve1 $ intros
>> `[simp only [min_def, max_def]]
>> try `[simp [*, if_pos, if_neg]]
>> try `[apply le_refl]
>> try `[apply le_of_not_le, assumption]
meta def tactic.interactive.min_tac (a b : interactive.parse lean.parser.pexpr) : tactic unit :=
interactive.by_cases (none, ``(%%a ≤ %%b)); min_tac_step
lemma min_le_left (a b : α) : min a b ≤ a :=
by min_tac a b
lemma min_le_right (a b : α) : min a b ≤ b :=
by min_tac a b
lemma le_min {a b c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) : c ≤ min a b :=
by min_tac a b
lemma le_max_left (a b : α) : a ≤ max a b :=
by min_tac b a
lemma le_max_right (a b : α) : b ≤ max a b :=
by min_tac b a
lemma max_le {a b c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) : max a b ≤ c :=
by min_tac b a
lemma eq_min {a b c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) (h₃ : ∀{d}, d ≤ a → d ≤ b → d ≤ c) :
c = min a b :=
le_antisymm (le_min h₁ h₂) (h₃ (min_le_left a b) (min_le_right a b))
lemma min_comm (a b : α) : min a b = min b a :=
eq_min (min_le_right a b) (min_le_left a b) (λ c h₁ h₂, le_min h₂ h₁)
lemma min_assoc (a b c : α) : min (min a b) c = min a (min b c) :=
begin
apply eq_min,
{ apply le_trans, apply min_le_left, apply min_le_left },
{ apply le_min, apply le_trans, apply min_le_left, apply min_le_right, apply min_le_right },
{ intros d h₁ h₂, apply le_min, apply le_min h₁, apply le_trans h₂, apply min_le_left,
apply le_trans h₂, apply min_le_right }
end
lemma min_left_comm : ∀ (a b c : α), min a (min b c) = min b (min a c) :=
left_comm (@min α _) (@min_comm α _) (@min_assoc α _)
@[simp]
lemma min_self (a : α) : min a a = a :=
by min_tac a a
@[ematch]
lemma min_eq_left {a b : α} (h : a ≤ b) : min a b = a :=
begin apply eq.symm, apply eq_min (le_refl _) h, intros, assumption end
@[ematch]
lemma min_eq_right {a b : α} (h : b ≤ a) : min a b = b :=
eq.subst (min_comm b a) (min_eq_left h)
lemma eq_max {a b c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) (h₃ : ∀{d}, a ≤ d → b ≤ d → c ≤ d) : c = max a b :=
le_antisymm (h₃ (le_max_left a b) (le_max_right a b)) (max_le h₁ h₂)
lemma max_comm (a b : α) : max a b = max b a :=
eq_max (le_max_right a b) (le_max_left a b) (λ c h₁ h₂, max_le h₂ h₁)
lemma max_assoc (a b c : α) : max (max a b) c = max a (max b c) :=
begin
apply eq_max,
{ apply le_trans, apply le_max_left a b, apply le_max_left },
{ apply max_le, apply le_trans, apply le_max_right a b, apply le_max_left, apply le_max_right },
{ intros d h₁ h₂, apply max_le, apply max_le h₁, apply le_trans (le_max_left _ _) h₂,
apply le_trans (le_max_right _ _) h₂}
end
lemma max_left_comm : ∀ (a b c : α), max a (max b c) = max b (max a c) :=
left_comm (@max α _) (@max_comm α _) (@max_assoc α _)
@[simp]
lemma max_self (a : α) : max a a = a :=
by min_tac a a
lemma max_eq_left {a b : α} (h : b ≤ a) : max a b = a :=
begin apply eq.symm, apply eq_max (le_refl _) h, intros, assumption end
lemma max_eq_right {a b : α} (h : a ≤ b) : max a b = b :=
eq.subst (max_comm b a) (max_eq_left h)
/- these rely on lt_of_lt -/
lemma min_eq_left_of_lt {a b : α} (h : a < b) : min a b = a :=
min_eq_left (le_of_lt h)
lemma min_eq_right_of_lt {a b : α} (h : b < a) : min a b = b :=
min_eq_right (le_of_lt h)
lemma max_eq_left_of_lt {a b : α} (h : b < a) : max a b = a :=
max_eq_left (le_of_lt h)
lemma max_eq_right_of_lt {a b : α} (h : a < b) : max a b = b :=
max_eq_right (le_of_lt h)
/- these use the fact that it is a linear ordering -/
lemma lt_min {a b c : α} (h₁ : a < b) (h₂ : a < c) : a < min b c :=
or.elim (le_or_gt b c)
(assume h : b ≤ c, by min_tac b c)
(assume h : b > c, by min_tac b c)
lemma max_lt {a b c : α} (h₁ : a < c) (h₂ : b < c) : max a b < c :=
or.elim (le_or_gt a b)
(assume h : a ≤ b, by min_tac b a)
(assume h : a > b, by min_tac b a)
end
|
072aa15b0023e49c46d1f074b266bd8d9d0c3929 | a45212b1526d532e6e83c44ddca6a05795113ddc | /test/ring.lean | 6eb3de57bcd52666d595a8e58ae20e01703679fa | [
"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 | 594 | lean | import tactic.ring data.real.basic
example (x y : ℕ) : x + y = y + x := by ring
example (x y : ℕ) : x + y + y = 2 * y + x := by ring
example (x y : ℕ) : x + id y = y + id x := by ring
example {α} [comm_ring α] (x y : α) : x + y + y - x = 2 * y := by ring
example (x y : ℚ) : x / 2 + x / 2 = x := by ring
example (x y : ℚ) : (x + y) ^ 3 = x ^ 3 + y ^ 3 + 3 * (x * y ^ 2 + x ^ 2 * y) := by ring
example (x y : ℝ) : (x + y) ^ 3 = x ^ 3 + y ^ 3 + 3 * (x * y ^ 2 + x ^ 2 * y) := by ring
example {α} [comm_semiring α] (x : α) : (x + 1) ^ 6 = (1 + x) ^ 6 := by try_for 15000 {ring}
|
45f985db82f462eac82fe140942f5823cc1d20c7 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/probability/martingale/borel_cantelli.lean | cd5664dcbcf35f4b164cdb1bcec32a54679f9084 | [
"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 | 18,830 | lean | /-
Copyright (c) 2022 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying
-/
import probability.martingale.convergence
import probability.martingale.optional_stopping
import probability.martingale.centering
import probability.conditional_expectation
/-!
# Generalized Borel-Cantelli lemma
This file proves Lévy's generalized Borel-Cantelli lemma which is a generalization of the
Borel-Cantelli lemmas. With this generalization, one can easily deduce the Borel-Cantelli lemmas
by choosing appropriate filtrations. This file also contains the one sided martingale bound which
is required to prove the generalized Borel-Cantelli.
## Main results
- `measure_theory.submartingale.bdd_above_iff_exists_tendsto`: the one sided martingale bound: given
a submartingale `f` with uniformly bounded differences, the set for which `f` converges is almost
everywhere equal to the set for which it is bounded.
- `measure_theory.ae_mem_limsup_at_top_iff`: Lévy's generalized Borel-Cantelli:
given a filtration `ℱ` and a sequence of sets `s` such that `s n ∈ ℱ n` for all `n`,
`limsup at_top s` is almost everywhere equal to the set for which `∑ ℙ[s (n + 1)∣ℱ n] = ∞`.
## TODO
Prove the missing second Borel-Cantelli lemma using this generalized version.
-/
open filter
open_locale nnreal ennreal measure_theory probability_theory big_operators topological_space
namespace measure_theory
variables {Ω : Type*} {m0 : measurable_space Ω} {μ : measure Ω}
{ℱ : filtration ℕ m0} {f : ℕ → Ω → ℝ} {ω : Ω}
/-!
### One sided martingale bound
-/
-- TODO: `least_ge` should be defined taking values in `with_top ℕ` once the `stopped_process`
-- refactor is complete
/-- `least_ge f r n` is the stopping time corresponding to the first time `f ≥ r`. -/
noncomputable
def least_ge (f : ℕ → Ω → ℝ) (r : ℝ) (n : ℕ) := hitting f (set.Ici r) 0 n
lemma adapted.is_stopping_time_least_ge (r : ℝ) (n : ℕ) (hf : adapted ℱ f) :
is_stopping_time ℱ (least_ge f r n) :=
hitting_is_stopping_time hf measurable_set_Ici
lemma least_ge_le {i : ℕ} {r : ℝ} (ω : Ω) : least_ge f r i ω ≤ i :=
hitting_le ω
-- The following four lemmas shows `least_ge` behaves like a stopped process. Ideally we should
-- define `least_ge` as a stopping time and take its stopped process. However, we can't do that
-- with our current definition since a stopping time takes only finite indicies. An upcomming
-- refactor should hopefully make it possible to have stopping times taking infinity as a value
lemma least_ge_mono {n m : ℕ} (hnm : n ≤ m) (r : ℝ) (ω : Ω) :
least_ge f r n ω ≤ least_ge f r m ω :=
hitting_mono hnm
lemma least_ge_eq_min (π : Ω → ℕ) (r : ℝ) (ω : Ω)
{n : ℕ} (hπn : ∀ ω, π ω ≤ n) :
least_ge f r (π ω) ω = min (π ω) (least_ge f r n ω) :=
begin
classical,
refine le_antisymm (le_min (least_ge_le _) (least_ge_mono (hπn ω) r ω)) _,
by_cases hle : π ω ≤ least_ge f r n ω,
{ rw [min_eq_left hle, least_ge],
by_cases h : ∃ j ∈ set.Icc 0 (π ω), f j ω ∈ set.Ici r,
{ refine hle.trans (eq.le _),
rw [least_ge, ← hitting_eq_hitting_of_exists (hπn ω) h] },
{ simp only [hitting, if_neg h] } },
{ rw [min_eq_right (not_le.1 hle).le, least_ge, least_ge,
← hitting_eq_hitting_of_exists (hπn ω) _],
rw [not_le, least_ge, hitting_lt_iff _ (hπn ω)] at hle,
exact let ⟨j, hj₁, hj₂⟩ := hle in ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ }
end
lemma stopped_value_stopped_value_least_ge (f : ℕ → Ω → ℝ) (π : Ω → ℕ) (r : ℝ)
{n : ℕ} (hπn : ∀ ω, π ω ≤ n) :
stopped_value (λ i, stopped_value f (least_ge f r i)) π
= stopped_value (stopped_process f (least_ge f r n)) π :=
by { ext1 ω, simp_rw [stopped_process, stopped_value], rw least_ge_eq_min _ _ _ hπn, }
lemma submartingale.stopped_value_least_ge [is_finite_measure μ]
(hf : submartingale f ℱ μ) (r : ℝ) :
submartingale (λ i, stopped_value f (least_ge f r i)) ℱ μ :=
begin
rw submartingale_iff_expected_stopped_value_mono,
{ intros σ π hσ hπ hσ_le_π hπ_bdd,
obtain ⟨n, hπ_le_n⟩ := hπ_bdd,
simp_rw stopped_value_stopped_value_least_ge f σ r (λ i, (hσ_le_π i).trans (hπ_le_n i)),
simp_rw stopped_value_stopped_value_least_ge f π r hπ_le_n,
refine hf.expected_stopped_value_mono _ _ _ (λ ω, (min_le_left _ _).trans (hπ_le_n ω)),
{ exact hσ.min (hf.adapted.is_stopping_time_least_ge _ _), },
{ exact hπ.min (hf.adapted.is_stopping_time_least_ge _ _), },
{ exact λ ω, min_le_min (hσ_le_π ω) le_rfl, }, },
{ exact λ i, strongly_measurable_stopped_value_of_le hf.adapted.prog_measurable_of_nat
(hf.adapted.is_stopping_time_least_ge _ _) least_ge_le, },
{ exact λ i, integrable_stopped_value _ ((hf.adapted.is_stopping_time_least_ge _ _))
(hf.integrable) least_ge_le, },
end
variables {r : ℝ} {R : ℝ≥0}
lemma norm_stopped_value_least_ge_le (hr : 0 ≤ r) (hf0 : f 0 = 0)
(hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) :
∀ᵐ ω ∂μ, stopped_value f (least_ge f r i) ω ≤ r + R :=
begin
filter_upwards [hbdd] with ω hbddω,
change f (least_ge f r i ω) ω ≤ r + R,
by_cases heq : least_ge f r i ω = 0,
{ rw [heq, hf0, pi.zero_apply],
exact add_nonneg hr R.coe_nonneg },
{ obtain ⟨k, hk⟩ := nat.exists_eq_succ_of_ne_zero heq,
rw [hk, add_comm, ← sub_le_iff_le_add],
have := not_mem_of_lt_hitting (hk.symm ▸ k.lt_succ_self : k < least_ge f r i ω) (zero_le _),
simp only [set.mem_union_eq, set.mem_Iic, set.mem_Ici, not_or_distrib, not_le] at this,
exact (sub_lt_sub_left this _).le.trans ((le_abs_self _).trans (hbddω _)) }
end
lemma submartingale.stopped_value_least_ge_snorm_le [is_finite_measure μ]
(hf : submartingale f ℱ μ) (hr : 0 ≤ r) (hf0 : f 0 = 0)
(hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) :
snorm (stopped_value f (least_ge f r i)) 1 μ ≤ 2 * μ set.univ * ennreal.of_real (r + R) :=
begin
refine snorm_one_le_of_le' ((hf.stopped_value_least_ge r).integrable _) _
(norm_stopped_value_least_ge_le hr hf0 hbdd i),
rw ← integral_univ,
refine le_trans _ ((hf.stopped_value_least_ge r).set_integral_le (zero_le _)
measurable_set.univ),
simp_rw [stopped_value, least_ge, hitting_of_le le_rfl, hf0, integral_zero']
end
lemma submartingale.stopped_value_least_ge_snorm_le' [is_finite_measure μ]
(hf : submartingale f ℱ μ) (hr : 0 ≤ r) (hf0 : f 0 = 0)
(hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) :
snorm (stopped_value f (least_ge f r i)) 1 μ ≤
ennreal.to_nnreal (2 * μ set.univ * ennreal.of_real (r + R)) :=
begin
refine (hf.stopped_value_least_ge_snorm_le hr hf0 hbdd i).trans _,
simp [ennreal.coe_to_nnreal (measure_ne_top μ _), ennreal.coe_to_nnreal],
end
/-- This lemma is superceded by `submartingale.bdd_above_iff_exists_tendsto`. -/
lemma submartingale.exists_tendsto_of_abs_bdd_above_aux [is_finite_measure μ]
(hf : submartingale f ℱ μ) (hf0 : f 0 = 0)
(hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) :
∀ᵐ ω ∂μ, bdd_above (set.range $ λ n, f n ω) → ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) :=
begin
have ht : ∀ᵐ ω ∂μ, ∀ i : ℕ, ∃ c, tendsto (λ n, stopped_value f (least_ge f i n) ω) at_top (𝓝 c),
{ rw ae_all_iff,
exact λ i, submartingale.exists_ae_tendsto_of_bdd (hf.stopped_value_least_ge i)
(hf.stopped_value_least_ge_snorm_le' i.cast_nonneg hf0 hbdd) },
filter_upwards [ht] with ω hω hωb,
rw bdd_above at hωb,
obtain ⟨i, hi⟩ := exists_nat_gt hωb.some,
have hib : ∀ n, f n ω < i,
{ intro n,
exact lt_of_le_of_lt ((mem_upper_bounds.1 hωb.some_mem) _ ⟨n, rfl⟩) hi },
have heq : ∀ n, stopped_value f (least_ge f i n) ω = f n ω,
{ intro n,
rw [least_ge, hitting, stopped_value],
simp only,
rw if_neg,
simp only [set.mem_Icc, set.mem_union, set.mem_Ici],
push_neg,
exact λ j _, hib j },
simp only [← heq, hω i],
end
lemma submartingale.bdd_above_iff_exists_tendsto_aux [is_finite_measure μ]
(hf : submartingale f ℱ μ) (hf0 : f 0 = 0)
(hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) :
∀ᵐ ω ∂μ, bdd_above (set.range $ λ n, f n ω) ↔ ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) :=
by filter_upwards [hf.exists_tendsto_of_abs_bdd_above_aux hf0 hbdd] with ω hω using
⟨hω, λ ⟨c, hc⟩, hc.bdd_above_range⟩
/-- One sided martingale bound: If `f` is a submartingale which has uniformly bounded differences,
then for almost every `ω`, `f n ω` is bounded above (in `n`) if and only if it converges. -/
lemma submartingale.bdd_above_iff_exists_tendsto [is_finite_measure μ]
(hf : submartingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) :
∀ᵐ ω ∂μ, bdd_above (set.range $ λ n, f n ω) ↔ ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) :=
begin
set g : ℕ → Ω → ℝ := λ n ω, f n ω - f 0 ω with hgdef,
have hg : submartingale g ℱ μ :=
hf.sub_martingale (martingale_const_fun _ _ (hf.adapted 0) (hf.integrable 0)),
have hg0 : g 0 = 0,
{ ext ω,
simp only [hgdef, sub_self, pi.zero_apply] },
have hgbdd : ∀ᵐ ω ∂μ, ∀ (i : ℕ), |g (i + 1) ω - g i ω| ≤ ↑R,
{ simpa only [sub_sub_sub_cancel_right] },
filter_upwards [hg.bdd_above_iff_exists_tendsto_aux hg0 hgbdd] with ω hω,
convert hω using 1; rw eq_iff_iff,
{ simp only [hgdef],
refine ⟨λ h, _, λ h, _⟩;
obtain ⟨b, hb⟩ := h;
refine ⟨b + |f 0 ω|, λ y hy, _⟩;
obtain ⟨n, rfl⟩ := hy,
{ simp_rw [sub_eq_add_neg],
exact add_le_add (hb ⟨n, rfl⟩) (neg_le_abs_self _) },
{ exact sub_le_iff_le_add.1 (le_trans (sub_le_sub_left (le_abs_self _) _) (hb ⟨n, rfl⟩)) } },
{ simp only [hgdef],
refine ⟨λ h, _, λ h, _⟩;
obtain ⟨c, hc⟩ := h,
{ exact ⟨c - f 0 ω, hc.sub_const _⟩ },
{ refine ⟨c + f 0 ω, _⟩,
have := hc.add_const (f 0 ω),
simpa only [sub_add_cancel] } }
end
/-!
### Lévy's generalization of the Borel-Cantelli lemma
Lévy's generalization of the Borel-Cantelli lemma states that: given a natural number indexed
filtration $(\mathcal{F}_n)$, and a sequence of sets $(s_n)$ such that for all
$n$, $s_n \in \mathcal{F}_n$, $limsup_n s_n$ is almost everywhere equal to the set for which
$\sum_n \mathbb{P}[s_n \mid \mathcal{F}_n] = \infty$.
The proof strategy follows by constructing a martingale satisfying the one sided martingale bound.
In particular, we define
$$
f_n := \sum_{k < n} \mathbf{1}_{s_{n + 1}} - \mathbb{P}[s_{n + 1} \mid \mathcal{F}_n].
$$
Then, as a martingale is both a sub and a super-martingale, the set for which it is unbounded from
above must agree with the set for which it is unbounded from below almost everywhere. Thus, it
can only converge to $\pm \infty$ with probability 0. Thus, by considering
$$
\limsup_n s_n = \{\sum_n \mathbf{1}_{s_n} = \infty\}
$$
almost everywhere, the result follows.
-/
lemma martingale.bdd_above_range_iff_bdd_below_range [is_finite_measure μ]
(hf : martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) :
∀ᵐ ω ∂μ, bdd_above (set.range (λ n, f n ω)) ↔ bdd_below (set.range (λ n, f n ω)) :=
begin
have hbdd' : ∀ᵐ ω ∂μ, ∀ i, |(-f) (i + 1) ω - (-f) i ω| ≤ R,
{ filter_upwards [hbdd] with ω hω i,
erw [← abs_neg, neg_sub, sub_neg_eq_add, neg_add_eq_sub],
exact hω i },
have hup := hf.submartingale.bdd_above_iff_exists_tendsto hbdd,
have hdown := hf.neg.submartingale.bdd_above_iff_exists_tendsto hbdd',
filter_upwards [hup, hdown] with ω hω₁ hω₂,
have : (∃ c, tendsto (λ n, f n ω) at_top (𝓝 c)) ↔ ∃ c, tendsto (λ n, (-f) n ω) at_top (𝓝 c),
{ split; rintro ⟨c, hc⟩,
{ exact ⟨-c, hc.neg⟩ },
{ refine ⟨-c, _⟩,
convert hc.neg,
simp only [neg_neg, pi.neg_apply] } },
rw [hω₁, this, ← hω₂],
split; rintro ⟨c, hc⟩; refine ⟨-c, λ ω hω, _⟩,
{ rw mem_upper_bounds at hc,
refine neg_le.2 (hc _ _),
simpa only [pi.neg_apply, set.mem_range, neg_inj] },
{ rw mem_lower_bounds at hc,
simp_rw [set.mem_range, pi.neg_apply, neg_eq_iff_neg_eq, eq_comm] at hω,
refine le_neg.1 (hc _ _),
simpa only [set.mem_range] }
end
lemma martingale.ae_not_tendsto_at_top_at_top [is_finite_measure μ]
(hf : martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) :
∀ᵐ ω ∂μ, ¬ tendsto (λ n, f n ω) at_top at_top :=
by filter_upwards [hf.bdd_above_range_iff_bdd_below_range hbdd] with ω hω htop using
unbounded_of_tendsto_at_top htop (hω.2 $ bdd_below_range_of_tendsto_at_top_at_top htop)
lemma martingale.ae_not_tendsto_at_top_at_bot [is_finite_measure μ]
(hf : martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) :
∀ᵐ ω ∂μ, ¬ tendsto (λ n, f n ω) at_top at_bot :=
by filter_upwards [hf.bdd_above_range_iff_bdd_below_range hbdd] with ω hω htop using
unbounded_of_tendsto_at_bot htop (hω.1 $ bdd_above_range_of_tendsto_at_top_at_bot htop)
namespace borel_cantelli
/-- Auxiliary definition required to prove Lévy's generalization of the Borel-Cantelli lemmas for
which we will take the martingale part. -/
noncomputable
def process (s : ℕ → set Ω) (n : ℕ) : Ω → ℝ :=
∑ k in finset.range n, (s (k + 1)).indicator 1
variables {s : ℕ → set Ω}
lemma process_zero : process s 0 = 0 :=
by rw [process, finset.range_zero, finset.sum_empty]
lemma adapted_process (hs : ∀ n, measurable_set[ℱ n] (s n)) :
adapted ℱ (process s) :=
λ n, finset.strongly_measurable_sum' _ $ λ k hk, strongly_measurable_one.indicator $
ℱ.mono (finset.mem_range.1 hk) _ $ hs _
lemma martingale_part_process_ae_eq (ℱ : filtration ℕ m0) (μ : measure Ω) (s : ℕ → set Ω) (n : ℕ) :
martingale_part ℱ μ (process s) n =
∑ k in finset.range n, ((s (k + 1)).indicator 1 - μ[(s (k + 1)).indicator 1 | ℱ k]) :=
begin
simp only [martingale_part_eq_sum, process_zero, zero_add],
refine finset.sum_congr rfl (λ k hk, _),
simp only [process, finset.sum_range_succ_sub_sum],
end
lemma predictable_part_process_ae_eq (ℱ : filtration ℕ m0) (μ : measure Ω) (s : ℕ → set Ω) (n : ℕ) :
predictable_part ℱ μ (process s) n =
∑ k in finset.range n, μ[(s (k + 1)).indicator (1 : Ω → ℝ) | ℱ k] :=
begin
have := martingale_part_process_ae_eq ℱ μ s n,
simp_rw [martingale_part, process, finset.sum_sub_distrib] at this,
exact sub_right_injective this,
end
lemma process_difference_le (s : ℕ → set Ω) (ω : Ω) (n : ℕ) :
|process s (n + 1) ω - process s n ω| ≤ (1 : ℝ≥0) :=
begin
rw [nonneg.coe_one, process, process, finset.sum_apply, finset.sum_apply,
finset.sum_range_succ_sub_sum, ← real.norm_eq_abs, norm_indicator_eq_indicator_norm],
refine set.indicator_le' (λ _ _, _) (λ _ _, zero_le_one) _,
rw [pi.one_apply, norm_one]
end
lemma integrable_process (μ : measure Ω) [is_finite_measure μ]
(hs : ∀ n, measurable_set[ℱ n] (s n)) (n : ℕ) :
integrable (process s n) μ :=
integrable_finset_sum' _ $ λ k hk, integrable_on.indicator (integrable_const 1) $ ℱ.le _ _ $ hs _
end borel_cantelli
open borel_cantelli
/-- An a.e. monotone adapted process `f` with uniformly bounded differences converges to `+∞` if
and only if its predictable part also converges to `+∞`. -/
lemma tendsto_sum_indicator_at_top_iff [is_finite_measure μ]
(hfmono : ∀ᵐ ω ∂μ, ∀ n, f n ω ≤ f (n + 1) ω)
(hf : adapted ℱ f) (hint : ∀ n, integrable (f n) μ)
(hbdd : ∀ᵐ ω ∂μ, ∀ n, |f (n + 1) ω - f n ω| ≤ R) :
∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top at_top ↔
tendsto (λ n, predictable_part ℱ μ f n ω) at_top at_top :=
begin
have h₁ := (martingale_martingale_part hf hint).ae_not_tendsto_at_top_at_top
(martingale_part_bdd_difference ℱ hbdd),
have h₂ := (martingale_martingale_part hf hint).ae_not_tendsto_at_top_at_bot
(martingale_part_bdd_difference ℱ hbdd),
have h₃ : ∀ᵐ ω ∂μ, ∀ n, 0 ≤ μ[f (n + 1) - f n | ℱ n] ω,
{ refine ae_all_iff.2 (λ n, condexp_nonneg _),
filter_upwards [ae_all_iff.1 hfmono n] with ω hω using sub_nonneg.2 hω },
filter_upwards [h₁, h₂, h₃, hfmono] with ω hω₁ hω₂ hω₃ hω₄,
split; intro ht,
{ refine tendsto_at_top_at_top_of_monotone' _ _,
{ intros n m hnm,
simp only [predictable_part, finset.sum_apply],
refine finset.sum_mono_set_of_nonneg hω₃ (finset.range_mono hnm) },
rintro ⟨b, hbdd⟩,
rw ← tendsto_neg_at_bot_iff at ht,
simp only [martingale_part, sub_eq_add_neg] at hω₁,
exact hω₁ (tendsto_at_top_add_right_of_le _ (-b)
(tendsto_neg_at_bot_iff.1 ht) $ λ n, neg_le_neg (hbdd ⟨n, rfl⟩)) },
{ refine tendsto_at_top_at_top_of_monotone' (monotone_nat_of_le_succ hω₄) _,
rintro ⟨b, hbdd⟩,
exact hω₂ (tendsto_at_bot_add_left_of_ge _ b (λ n, hbdd ⟨n, rfl⟩) $
tendsto_neg_at_bot_iff.2 ht) },
end
open borel_cantelli
lemma tendsto_sum_indicator_at_top_iff' [is_finite_measure μ]
{s : ℕ → set Ω} (hs : ∀ n, measurable_set[ℱ n] (s n)) :
∀ᵐ ω ∂μ,
tendsto (λ n, ∑ k in finset.range n, (s (k + 1)).indicator (1 : Ω → ℝ) ω) at_top at_top ↔
tendsto (λ n, ∑ k in finset.range n, μ[(s (k + 1)).indicator (1 : Ω → ℝ) | ℱ k] ω)
at_top at_top :=
begin
have := tendsto_sum_indicator_at_top_iff (eventually_of_forall $ λ ω n, _) (adapted_process hs)
(integrable_process μ hs) (eventually_of_forall $ process_difference_le s),
swap,
{ rw [process, process, ← sub_nonneg, finset.sum_apply, finset.sum_apply,
finset.sum_range_succ_sub_sum],
exact set.indicator_nonneg (λ _ _, zero_le_one) _ },
simp_rw [process, predictable_part_process_ae_eq] at this,
simpa using this,
end
/-- **Lévy's generalization of the Borel-Cantelli lemma**: given a sequence of sets `s` and a
filtration `ℱ` such that for all `n`, `s n` is `ℱ n`-measurable, `at_top.limsup s` is almost
everywhere equal to the set for which `∑ k, ℙ(s (k + 1) | ℱ k) = ∞`. -/
theorem ae_mem_limsup_at_top_iff [is_finite_measure μ]
{s : ℕ → set Ω} (hs : ∀ n, measurable_set[ℱ n] (s n)) :
∀ᵐ ω ∂μ, ω ∈ limsup at_top s ↔
tendsto (λ n, ∑ k in finset.range n, μ[(s (k + 1)).indicator (1 : Ω → ℝ) | ℱ k] ω)
at_top at_top :=
(limsup_eq_tendsto_sum_indicator_at_top ℝ s).symm ▸ tendsto_sum_indicator_at_top_iff' hs
end measure_theory
|
136738e9ebc79de40f329c6bb8f7ebeb50c44959 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/equiv/option.lean | fdd45996bf22febafe4678f5eb78464368a7acc1 | [
"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,226 | 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 data.equiv.basic
import control.equiv_functor
/-!
# Equivalences for `option α`
We define `remove_none` which acts to provide a `e : α ≃ β` if given a `f : option α ≃ option β`.
To construct an `f : option α ≃ option β` from `e : α ≃ β` such that
`f none = none` and `f (some x) = some (e x)`, use
`f = equiv_functor.map_equiv option e`.
-/
namespace equiv
variables {α β : Type*} (e : option α ≃ option β)
private def remove_none_aux (x : α) : β :=
if h : (e (some x)).is_some
then option.get h
else option.get $ show (e none).is_some, from
begin
rw ←option.ne_none_iff_is_some,
intro hn,
rw [option.not_is_some_iff_eq_none, ←hn] at h,
simpa only using e.injective h,
end
private lemma remove_none_aux_some {x : α} (h : ∃ x', e (some x) = some x') :
some (remove_none_aux e x) = e (some x) :=
by simp [remove_none_aux, option.is_some_iff_exists.mpr h]
private lemma remove_none_aux_none {x : α} (h : e (some x) = none) :
some (remove_none_aux e x) = e none :=
by simp [remove_none_aux, option.not_is_some_iff_eq_none.mpr h]
private lemma remove_none_aux_inv (x : α) : remove_none_aux e.symm (remove_none_aux e x) = x :=
option.some_injective _ begin
cases h1 : e.symm (some (remove_none_aux e x)); cases h2 : (e (some x)),
{ rw remove_none_aux_none _ h1,
exact (e.eq_symm_apply.mpr h2).symm },
{ rw remove_none_aux_some _ ⟨_, h2⟩ at h1,
simpa using h1, },
{ rw remove_none_aux_none _ h2 at h1,
simpa using h1, },
{ rw remove_none_aux_some _ ⟨_, h1⟩,
rw remove_none_aux_some _ ⟨_, h2⟩,
simp },
end
/-- Given an equivalence between two `option` types, eliminate `none` from that equivalence by
mapping `e.symm none` to `e none`. -/
def remove_none : α ≃ β :=
{ to_fun := remove_none_aux e,
inv_fun := remove_none_aux e.symm,
left_inv := remove_none_aux_inv e,
right_inv := remove_none_aux_inv e.symm, }
@[simp]
lemma remove_none_symm : (remove_none e).symm = remove_none e.symm := rfl
lemma remove_none_some {x : α} (h : ∃ x', e (some x) = some x') :
some (remove_none e x) = e (some x) := remove_none_aux_some e h
lemma remove_none_none {x : α} (h : e (some x) = none) :
some (remove_none e x) = e none := remove_none_aux_none e h
@[simp] lemma option_symm_apply_none_iff : e.symm none = none ↔ e none = none :=
⟨λ h, by simpa using (congr_arg e h).symm, λ h, by simpa using (congr_arg e.symm h).symm⟩
lemma some_remove_none_iff {x : α} :
some (remove_none e x) = e none ↔ e.symm none = some x :=
begin
cases h : e (some x) with a,
{ rw remove_none_none _ h,
simpa using (congr_arg e.symm h).symm },
{ rw remove_none_some _ ⟨a, h⟩,
have := (congr_arg e.symm h),
rw [symm_apply_apply] at this,
simp only [false_iff, apply_eq_iff_eq],
simp [this] }
end
@[simp]
lemma remove_none_map_equiv {α β : Type*} (e : α ≃ β) :
remove_none (equiv_functor.map_equiv option e) = e :=
equiv.ext $ λ x, option.some_injective _ $ remove_none_some _ ⟨e x, by simp [equiv_functor.map]⟩
end equiv
|
57387215b9069da1b041bb3df23720757604db49 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/linear_algebra/ray.lean | 9d9a2801a262fe7c7108bd2ccb5b9470ef044982 | [
"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,395 | lean | /-
Copyright (c) 2021 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import linear_algebra.linear_independent
/-!
# Rays in modules
This file defines rays in modules.
## Main definitions
* `same_ray`: two vectors belong to the same ray if they are proportional with a nonnegative
coefficient.
* `module.ray` is a type for the equivalence class of nonzero vectors in a module with some
common positive multiple.
-/
noncomputable theory
open_locale big_operators
section strict_ordered_comm_semiring
variables (R : Type*) [strict_ordered_comm_semiring R]
variables {M : Type*} [add_comm_monoid M] [module R M]
variables {N : Type*} [add_comm_monoid N] [module R N]
variables (ι : Type*) [decidable_eq ι]
/-- Two vectors are in the same ray if either one of them is zero or some positive multiples of them
are equal (in the typical case over a field, this means one of them is a nonnegative multiple of
the other). -/
def same_ray (v₁ v₂ : M) : Prop :=
v₁ = 0 ∨ v₂ = 0 ∨ ∃ (r₁ r₂ : R), 0 < r₁ ∧ 0 < r₂ ∧ r₁ • v₁ = r₂ • v₂
variables {R}
namespace same_ray
variables {x y z : M}
@[simp] lemma zero_left (y : M) : same_ray R 0 y := or.inl rfl
@[simp] lemma zero_right (x : M) : same_ray R x 0 := or.inr $ or.inl rfl
@[nontriviality] lemma of_subsingleton [subsingleton M] (x y : M) : same_ray R x y :=
by { rw [subsingleton.elim x 0], exact zero_left _ }
@[nontriviality] lemma of_subsingleton' [subsingleton R] (x y : M) : same_ray R x y :=
by { haveI := module.subsingleton R M, exact of_subsingleton x y }
/-- `same_ray` is reflexive. -/
@[refl] lemma refl (x : M) : same_ray R x x :=
begin
nontriviality R,
exact or.inr (or.inr $ ⟨1, 1, zero_lt_one, zero_lt_one, rfl⟩)
end
protected lemma rfl : same_ray R x x := refl _
/-- `same_ray` is symmetric. -/
@[symm] lemma symm (h : same_ray R x y) : same_ray R y x :=
(or.left_comm.1 h).imp_right $ or.imp_right $ λ ⟨r₁, r₂, h₁, h₂, h⟩, ⟨r₂, r₁, h₂, h₁, h.symm⟩
/-- If `x` and `y` are nonzero vectors on the same ray, then there exist positive numbers `r₁ r₂`
such that `r₁ • x = r₂ • y`. -/
lemma exists_pos (h : same_ray R x y) (hx : x ≠ 0) (hy : y ≠ 0) :
∃ r₁ r₂ : R, 0 < r₁ ∧ 0 < r₂ ∧ r₁ • x = r₂ • y :=
(h.resolve_left hx).resolve_left hy
lemma _root_.same_ray_comm : same_ray R x y ↔ same_ray R y x :=
⟨same_ray.symm, same_ray.symm⟩
/-- `same_ray` is transitive unless the vector in the middle is zero and both other vectors are
nonzero. -/
lemma trans (hxy : same_ray R x y) (hyz : same_ray R y z) (hy : y = 0 → x = 0 ∨ z = 0) :
same_ray R x z :=
begin
rcases eq_or_ne x 0 with rfl|hx, { exact zero_left z },
rcases eq_or_ne z 0 with rfl|hz, { exact zero_right x },
rcases eq_or_ne y 0 with rfl|hy, { exact (hy rfl).elim (λ h, (hx h).elim) (λ h, (hz h).elim) },
rcases hxy.exists_pos hx hy with ⟨r₁, r₂, hr₁, hr₂, h₁⟩,
rcases hyz.exists_pos hy hz with ⟨r₃, r₄, hr₃, hr₄, h₂⟩,
refine or.inr (or.inr $ ⟨r₃ * r₁, r₂ * r₄, mul_pos hr₃ hr₁, mul_pos hr₂ hr₄, _⟩),
rw [mul_smul, mul_smul, h₁, ← h₂, smul_comm]
end
/-- A vector is in the same ray as a nonnegative multiple of itself. -/
lemma _root_.same_ray_nonneg_smul_right (v : M) {r : R} (h : 0 ≤ r) : same_ray R v (r • v) :=
or.inr $ h.eq_or_lt.imp (λ h, h ▸ zero_smul R v) $
λ h, ⟨r, 1, h, by { nontriviality R, exact zero_lt_one }, (one_smul _ _).symm⟩
/-- A vector is in the same ray as a positive multiple of itself. -/
lemma _root_.same_ray_pos_smul_right (v : M) {r : R} (h : 0 < r) : same_ray R v (r • v) :=
same_ray_nonneg_smul_right v h.le
/-- A vector is in the same ray as a nonnegative multiple of one it is in the same ray as. -/
lemma nonneg_smul_right {r : R} (h : same_ray R x y) (hr : 0 ≤ r) : same_ray R x (r • y) :=
h.trans (same_ray_nonneg_smul_right y hr) $ λ hy, or.inr $ by rw [hy, smul_zero]
/-- A vector is in the same ray as a positive multiple of one it is in the same ray as. -/
lemma pos_smul_right {r : R} (h : same_ray R x y) (hr : 0 < r) : same_ray R x (r • y) :=
h.nonneg_smul_right hr.le
/-- A nonnegative multiple of a vector is in the same ray as that vector. -/
lemma _root_.same_ray_nonneg_smul_left (v : M) {r : R} (h : 0 ≤ r) : same_ray R (r • v) v :=
(same_ray_nonneg_smul_right v h).symm
/-- A positive multiple of a vector is in the same ray as that vector. -/
lemma _root_.same_ray_pos_smul_left (v : M) {r : R} (h : 0 < r) : same_ray R (r • v) v :=
same_ray_nonneg_smul_left v h.le
/-- A nonnegative multiple of a vector is in the same ray as one it is in the same ray as. -/
lemma nonneg_smul_left {r : R} (h : same_ray R x y) (hr : 0 ≤ r) : same_ray R (r • x) y :=
(h.symm.nonneg_smul_right hr).symm
/-- A positive multiple of a vector is in the same ray as one it is in the same ray as. -/
lemma pos_smul_left {r : R} (h : same_ray R x y) (hr : 0 < r) : same_ray R (r • x) y :=
h.nonneg_smul_left hr.le
/-- If two vectors are on the same ray then they remain so after applying a linear map. -/
lemma map (f : M →ₗ[R] N) (h : same_ray R x y) : same_ray R (f x) (f y) :=
h.imp (λ hx, by rw [hx, map_zero]) $ or.imp (λ hy, by rw [hy, map_zero]) $
λ ⟨r₁, r₂, hr₁, hr₂, h⟩, ⟨r₁, r₂, hr₁, hr₂, by rw [←f.map_smul, ←f.map_smul, h]⟩
/-- The images of two vectors under an injective linear map are on the same ray if and only if the
original vectors are on the same ray. -/
lemma _root_.function.injective.same_ray_map_iff {F : Type*} [linear_map_class F R M N] {f : F}
(hf : function.injective f) : same_ray R (f x) (f y) ↔ same_ray R x y :=
by simp only [same_ray, map_zero, ← hf.eq_iff, map_smul]
/-- The images of two vectors under a linear equivalence are on the same ray if and only if the
original vectors are on the same ray. -/
@[simp] lemma _root_.same_ray_map_iff (e : M ≃ₗ[R] N) : same_ray R (e x) (e y) ↔ same_ray R x y :=
function.injective.same_ray_map_iff (equiv_like.injective e)
/-- If two vectors are on the same ray then both scaled by the same action are also on the same
ray. -/
lemma smul {S : Type*} [monoid S] [distrib_mul_action S M] [smul_comm_class R S M]
(h : same_ray R x y) (s : S) : same_ray R (s • x) (s • y) :=
h.map (s • (linear_map.id : M →ₗ[R] M))
/-- If `x` and `y` are on the same ray as `z`, then so is `x + y`. -/
lemma add_left (hx : same_ray R x z) (hy : same_ray R y z) : same_ray R (x + y) z :=
begin
rcases eq_or_ne x 0 with rfl|hx₀, { rwa zero_add },
rcases eq_or_ne y 0 with rfl|hy₀, { rwa add_zero },
rcases eq_or_ne z 0 with rfl|hz₀, { apply zero_right },
rcases hx.exists_pos hx₀ hz₀ with ⟨rx, rz₁, hrx, hrz₁, Hx⟩,
rcases hy.exists_pos hy₀ hz₀ with ⟨ry, rz₂, hry, hrz₂, Hy⟩,
refine or.inr (or.inr ⟨rx * ry, ry * rz₁ + rx * rz₂, mul_pos hrx hry, _, _⟩),
{ apply_rules [add_pos, mul_pos] },
{ simp only [mul_smul, smul_add, add_smul, ← Hx, ← Hy],
rw smul_comm }
end
/-- If `y` and `z` are on the same ray as `x`, then so is `y + z`. -/
lemma add_right (hy : same_ray R x y) (hz : same_ray R x z) : same_ray R x (y + z) :=
(hy.symm.add_left hz.symm).symm
end same_ray
/-- Nonzero vectors, as used to define rays. This type depends on an unused argument `R` so that
`ray_vector.setoid` can be an instance. -/
@[nolint unused_arguments has_nonempty_instance]
def ray_vector (R M : Type*) [has_zero M] := {v : M // v ≠ 0}
instance ray_vector.has_coe {R M : Type*} [has_zero M] :
has_coe (ray_vector R M) M := coe_subtype
instance {R M : Type*} [has_zero M] [nontrivial M] : nonempty (ray_vector R M) :=
let ⟨x, hx⟩ := exists_ne (0 : M) in ⟨⟨x, hx⟩⟩
variables (R M)
/-- The setoid of the `same_ray` relation for the subtype of nonzero vectors. -/
instance : setoid (ray_vector R M) :=
{ r := λ x y, same_ray R (x : M) y,
iseqv := ⟨λ x, same_ray.refl _, λ x y h, h.symm,
λ x y z hxy hyz, hxy.trans hyz $ λ hy, (y.2 hy).elim⟩ }
/-- A ray (equivalence class of nonzero vectors with common positive multiples) in a module. -/
@[nolint has_nonempty_instance]
def module.ray := quotient (ray_vector.setoid R M)
variables {R M}
/-- Equivalence of nonzero vectors, in terms of same_ray. -/
lemma equiv_iff_same_ray {v₁ v₂ : ray_vector R M} :
v₁ ≈ v₂ ↔ same_ray R (v₁ : M) v₂ :=
iff.rfl
variables (R)
/-- The ray given by a nonzero vector. -/
protected def ray_of_ne_zero (v : M) (h : v ≠ 0) : module.ray R M := ⟦⟨v, h⟩⟧
/-- An induction principle for `module.ray`, used as `induction x using module.ray.ind`. -/
lemma module.ray.ind {C : module.ray R M → Prop}
(h : ∀ v (hv : v ≠ 0), C (ray_of_ne_zero R v hv)) (x : module.ray R M) : C x :=
quotient.ind (subtype.rec $ by exact h) x
variable {R}
instance [nontrivial M] : nonempty (module.ray R M) :=
nonempty.map quotient.mk infer_instance
/-- The rays given by two nonzero vectors are equal if and only if those vectors
satisfy `same_ray`. -/
lemma ray_eq_iff {v₁ v₂ : M} (hv₁ : v₁ ≠ 0) (hv₂ : v₂ ≠ 0) :
ray_of_ne_zero R _ hv₁ = ray_of_ne_zero R _ hv₂ ↔ same_ray R v₁ v₂ :=
quotient.eq
/-- The ray given by a positive multiple of a nonzero vector. -/
@[simp] lemma ray_pos_smul {v : M} (h : v ≠ 0) {r : R} (hr : 0 < r)
(hrv : r • v ≠ 0) : ray_of_ne_zero R (r • v) hrv = ray_of_ne_zero R v h :=
(ray_eq_iff _ _).2 $ same_ray_pos_smul_left v hr
/-- An equivalence between modules implies an equivalence between ray vectors. -/
def ray_vector.map_linear_equiv (e : M ≃ₗ[R] N) : ray_vector R M ≃ ray_vector R N :=
equiv.subtype_equiv e.to_equiv $ λ _, e.map_ne_zero_iff.symm
/-- An equivalence between modules implies an equivalence between rays. -/
def module.ray.map (e : M ≃ₗ[R] N) : module.ray R M ≃ module.ray R N :=
quotient.congr (ray_vector.map_linear_equiv e) $ λ ⟨a, ha⟩ ⟨b, hb⟩, (same_ray_map_iff _).symm
@[simp] lemma module.ray.map_apply (e : M ≃ₗ[R] N) (v : M) (hv : v ≠ 0) :
module.ray.map e (ray_of_ne_zero _ v hv) = ray_of_ne_zero _ (e v) (e.map_ne_zero_iff.2 hv) := rfl
@[simp] lemma module.ray.map_refl : (module.ray.map $ linear_equiv.refl R M) = equiv.refl _ :=
equiv.ext $ module.ray.ind R $ λ _ _, rfl
@[simp] lemma module.ray.map_symm (e : M ≃ₗ[R] N) :
(module.ray.map e).symm = module.ray.map e.symm := rfl
section action
variables {G : Type*} [group G] [distrib_mul_action G M]
/-- Any invertible action preserves the non-zeroness of ray vectors. This is primarily of interest
when `G = Rˣ` -/
instance {R : Type*} : mul_action G (ray_vector R M) :=
{ smul := λ r, (subtype.map ((•) r) $ λ a, (smul_ne_zero_iff_ne _).2),
mul_smul := λ a b m, subtype.ext $ mul_smul a b _,
one_smul := λ m, subtype.ext $ one_smul _ _ }
variables [smul_comm_class R G M]
/-- Any invertible action preserves the non-zeroness of rays. This is primarily of interest when
`G = Rˣ` -/
instance : mul_action G (module.ray R M) :=
{ smul := λ r, quotient.map ((•) r) (λ a b h, h.smul _),
mul_smul := λ a b, quotient.ind $ by exact(λ m, congr_arg quotient.mk $ mul_smul a b _),
one_smul := quotient.ind $ by exact (λ m, congr_arg quotient.mk $ one_smul _ _), }
/-- The action via `linear_equiv.apply_distrib_mul_action` corresponds to `module.ray.map`. -/
@[simp] lemma module.ray.linear_equiv_smul_eq_map (e : M ≃ₗ[R] M) (v : module.ray R M) :
e • v = module.ray.map e v := rfl
@[simp] lemma smul_ray_of_ne_zero (g : G) (v : M) (hv) :
g • ray_of_ne_zero R v hv = ray_of_ne_zero R (g • v) ((smul_ne_zero_iff_ne _).2 hv) := rfl
end action
namespace module.ray
/-- Scaling by a positive unit is a no-op. -/
lemma units_smul_of_pos (u : Rˣ) (hu : 0 < (u : R)) (v : module.ray R M) :
u • v = v :=
begin
induction v using module.ray.ind,
rw [smul_ray_of_ne_zero, ray_eq_iff],
exact same_ray_pos_smul_left _ hu
end
/-- An arbitrary `ray_vector` giving a ray. -/
def some_ray_vector (x : module.ray R M) : ray_vector R M := quotient.out x
/-- The ray of `some_ray_vector`. -/
@[simp] lemma some_ray_vector_ray (x : module.ray R M) :
(⟦x.some_ray_vector⟧ : module.ray R M) = x :=
quotient.out_eq _
/-- An arbitrary nonzero vector giving a ray. -/
def some_vector (x : module.ray R M) : M := x.some_ray_vector
/-- `some_vector` is nonzero. -/
@[simp] lemma some_vector_ne_zero (x : module.ray R M) : x.some_vector ≠ 0 :=
x.some_ray_vector.property
/-- The ray of `some_vector`. -/
@[simp] lemma some_vector_ray (x : module.ray R M) :
ray_of_ne_zero R _ x.some_vector_ne_zero = x :=
(congr_arg _ (subtype.coe_eta _ _) : _).trans x.out_eq
end module.ray
end strict_ordered_comm_semiring
section strict_ordered_comm_ring
variables {R : Type*} [strict_ordered_comm_ring R]
variables {M N : Type*} [add_comm_group M] [add_comm_group N] [module R M] [module R N] {x y : M}
/-- `same_ray.neg` as an `iff`. -/
@[simp] lemma same_ray_neg_iff : same_ray R (-x) (-y) ↔ same_ray R x y :=
by simp only [same_ray, neg_eq_zero, smul_neg, neg_inj]
alias same_ray_neg_iff ↔ same_ray.of_neg same_ray.neg
lemma same_ray_neg_swap : same_ray R (-x) y ↔ same_ray R x (-y) :=
by rw [← same_ray_neg_iff, neg_neg]
lemma eq_zero_of_same_ray_neg_smul_right [no_zero_smul_divisors R M] {r : R} (hr : r < 0)
(h : same_ray R x (r • x)) :
x = 0 :=
begin
rcases h with rfl|h₀|⟨r₁, r₂, hr₁, hr₂, h⟩,
{ refl },
{ simpa [hr.ne] using h₀ },
{ rw [← sub_eq_zero, smul_smul, ← sub_smul, smul_eq_zero] at h,
refine h.resolve_left (ne_of_gt $ sub_pos.2 _),
exact (mul_neg_of_pos_of_neg hr₂ hr).trans hr₁ }
end
/-- If a vector is in the same ray as its negation, that vector is zero. -/
lemma eq_zero_of_same_ray_self_neg [no_zero_smul_divisors R M] (h : same_ray R x (-x)) :
x = 0 :=
begin
nontriviality M, haveI : nontrivial R := module.nontrivial R M,
refine eq_zero_of_same_ray_neg_smul_right (neg_lt_zero.2 (zero_lt_one' R)) _,
rwa [neg_one_smul]
end
namespace ray_vector
/-- Negating a nonzero vector. -/
instance {R : Type*} : has_neg (ray_vector R M) := ⟨λ v, ⟨-v, neg_ne_zero.2 v.prop⟩⟩
/-- Negating a nonzero vector commutes with coercion to the underlying module. -/
@[simp, norm_cast] lemma coe_neg {R : Type*} (v : ray_vector R M) : ↑(-v) = -(v : M) := rfl
/-- Negating a nonzero vector twice produces the original vector. -/
instance {R : Type*} : has_involutive_neg (ray_vector R M) :=
{ neg := has_neg.neg,
neg_neg := λ v, by rw [subtype.ext_iff, coe_neg, coe_neg, neg_neg] }
/-- If two nonzero vectors are equivalent, so are their negations. -/
@[simp] lemma equiv_neg_iff {v₁ v₂ : ray_vector R M} : -v₁ ≈ -v₂ ↔ v₁ ≈ v₂ :=
same_ray_neg_iff
end ray_vector
variables (R)
/-- Negating a ray. -/
instance : has_neg (module.ray R M) :=
⟨quotient.map (λ v, -v) (λ v₁ v₂, ray_vector.equiv_neg_iff.2)⟩
/-- The ray given by the negation of a nonzero vector. -/
@[simp] lemma neg_ray_of_ne_zero (v : M) (h : v ≠ 0) :
-(ray_of_ne_zero R _ h) = ray_of_ne_zero R (-v) (neg_ne_zero.2 h) :=
rfl
namespace module.ray
variables {R}
/-- Negating a ray twice produces the original ray. -/
instance : has_involutive_neg (module.ray R M) :=
{ neg := has_neg.neg,
neg_neg := λ x, quotient.ind (λ a, congr_arg quotient.mk $ neg_neg _) x }
variables {R M}
/-- A ray does not equal its own negation. -/
lemma ne_neg_self [no_zero_smul_divisors R M] (x : module.ray R M) : x ≠ -x :=
begin
induction x using module.ray.ind with x hx,
rw [neg_ray_of_ne_zero, ne.def, ray_eq_iff],
exact mt eq_zero_of_same_ray_self_neg hx
end
lemma neg_units_smul (u : Rˣ) (v : module.ray R M) : (-u) • v = - (u • v) :=
begin
induction v using module.ray.ind,
simp only [smul_ray_of_ne_zero, units.smul_def, units.coe_neg, neg_smul, neg_ray_of_ne_zero]
end
/-- Scaling by a negative unit is negation. -/
lemma units_smul_of_neg (u : Rˣ) (hu : (u : R) < 0) (v : module.ray R M) :
u • v = -v :=
begin
rw [← neg_inj, neg_neg, ← neg_units_smul, units_smul_of_pos],
rwa [units.coe_neg, right.neg_pos_iff]
end
@[simp] protected lemma map_neg (f : M ≃ₗ[R] N) (v : module.ray R M) : map f (-v) = - map f v :=
begin
induction v using module.ray.ind with g hg,
simp,
end
end module.ray
end strict_ordered_comm_ring
section linear_ordered_comm_ring
variables {R : Type*} [linear_ordered_comm_ring R]
variables {M : Type*} [add_comm_group M] [module R M]
/-- `same_ray` follows from membership of `mul_action.orbit` for the `units.pos_subgroup`. -/
lemma same_ray_of_mem_orbit {v₁ v₂ : M} (h : v₁ ∈ mul_action.orbit (units.pos_subgroup R) v₂) :
same_ray R v₁ v₂ :=
begin
rcases h with ⟨⟨r, hr : 0 < (r : R)⟩, (rfl : r • v₂ = v₁)⟩,
exact same_ray_pos_smul_left _ hr
end
/-- Scaling by an inverse unit is the same as scaling by itself. -/
@[simp] lemma units_inv_smul (u : Rˣ) (v : module.ray R M) :
u⁻¹ • v = u • v :=
calc u⁻¹ • v = (u * u) • u⁻¹ • v :
eq.symm $ (u⁻¹ • v).units_smul_of_pos _ $ mul_self_pos.2 u.ne_zero
... = u • v : by rw [mul_smul, smul_inv_smul]
section
variables [no_zero_smul_divisors R M]
@[simp] lemma same_ray_smul_right_iff {v : M} {r : R} :
same_ray R v (r • v) ↔ 0 ≤ r ∨ v = 0 :=
⟨λ hrv, or_iff_not_imp_left.2 $ λ hr, eq_zero_of_same_ray_neg_smul_right (not_le.1 hr) hrv,
or_imp_distrib.2 ⟨same_ray_nonneg_smul_right v, λ h, h.symm ▸ same_ray.zero_left _⟩⟩
/-- A nonzero vector is in the same ray as a multiple of itself if and only if that multiple
is positive. -/
lemma same_ray_smul_right_iff_of_ne {v : M} (hv : v ≠ 0) {r : R} (hr : r ≠ 0) :
same_ray R v (r • v) ↔ 0 < r :=
by simp only [same_ray_smul_right_iff, hv, or_false, hr.symm.le_iff_lt]
@[simp] lemma same_ray_smul_left_iff {v : M} {r : R} : same_ray R (r • v) v ↔ 0 ≤ r ∨ v = 0 :=
same_ray_comm.trans same_ray_smul_right_iff
/-- A multiple of a nonzero vector is in the same ray as that vector if and only if that multiple
is positive. -/
lemma same_ray_smul_left_iff_of_ne {v : M} (hv : v ≠ 0) {r : R} (hr : r ≠ 0) :
same_ray R (r • v) v ↔ 0 < r :=
same_ray_comm.trans (same_ray_smul_right_iff_of_ne hv hr)
@[simp] lemma same_ray_neg_smul_right_iff {v : M} {r : R} :
same_ray R (-v) (r • v) ↔ r ≤ 0 ∨ v = 0 :=
by rw [← same_ray_neg_iff, neg_neg, ← neg_smul, same_ray_smul_right_iff, neg_nonneg]
lemma same_ray_neg_smul_right_iff_of_ne {v : M} {r : R} (hv : v ≠ 0) (hr : r ≠ 0) :
same_ray R (-v) (r • v) ↔ r < 0 :=
by simp only [same_ray_neg_smul_right_iff, hv, or_false, hr.le_iff_lt]
@[simp] lemma same_ray_neg_smul_left_iff {v : M} {r : R} :
same_ray R (r • v) (-v) ↔ r ≤ 0 ∨ v = 0 :=
same_ray_comm.trans same_ray_neg_smul_right_iff
lemma same_ray_neg_smul_left_iff_of_ne {v : M} {r : R} (hv : v ≠ 0) (hr : r ≠ 0) :
same_ray R (r • v) (-v) ↔ r < 0 :=
same_ray_comm.trans $ same_ray_neg_smul_right_iff_of_ne hv hr
@[simp] lemma units_smul_eq_self_iff {u : Rˣ} {v : module.ray R M} :
u • v = v ↔ (0 : R) < u :=
begin
induction v using module.ray.ind with v hv,
simp only [smul_ray_of_ne_zero, ray_eq_iff, units.smul_def,
same_ray_smul_left_iff_of_ne hv u.ne_zero]
end
@[simp] lemma units_smul_eq_neg_iff {u : Rˣ} {v : module.ray R M} :
u • v = -v ↔ ↑u < (0 : R) :=
by rw [← neg_inj, neg_neg, ← module.ray.neg_units_smul, units_smul_eq_self_iff, units.coe_neg,
neg_pos]
/-- Two vectors are in the same ray, or the first is in the same ray as the negation of the
second, if and only if they are not linearly independent. -/
lemma same_ray_or_same_ray_neg_iff_not_linear_independent {x y : M} :
(same_ray R x y ∨ same_ray R x (-y)) ↔ ¬ linear_independent R ![x, y] :=
begin
by_cases hx : x = 0, { simp [hx, λ h : linear_independent R ![0, y], h.ne_zero 0 rfl] },
by_cases hy : y = 0, { simp [hy, λ h : linear_independent R ![x, 0], h.ne_zero 1 rfl] },
simp_rw [fintype.not_linear_independent_iff, fin.sum_univ_two, fin.exists_fin_two],
refine ⟨λ h, _, λ h, _⟩,
{ rcases h with (hx0|hy0|⟨r₁, r₂, hr₁, hr₂, h⟩)|(hx0|hy0|⟨r₁, r₂, hr₁, hr₂, h⟩),
{ exact false.elim (hx hx0) },
{ exact false.elim (hy hy0) },
{ refine ⟨![r₁, -r₂], _⟩, simp [h, hr₁.ne.symm] },
{ exact false.elim (hx hx0) },
{ exact false.elim (hy (neg_eq_zero.1 hy0)) },
{ refine ⟨![r₁, r₂], _⟩, simp [h, hr₁.ne.symm] } },
{ rcases h with ⟨m, hm, hmne⟩,
change m 0 • x + m 1 • y = 0 at hm,
rw add_eq_zero_iff_eq_neg at hm,
rcases lt_trichotomy (m 0) 0 with hm0|hm0|hm0; rcases lt_trichotomy (m 1) 0 with hm1|hm1|hm1,
{ refine or.inr (or.inr (or.inr ⟨-(m 0), -(m 1), left.neg_pos_iff.2 hm0,
left.neg_pos_iff.2 hm1, _⟩)),
simp [hm] },
{ exfalso, simpa [hm1, hx, hm0.ne] using hm },
{ refine or.inl (or.inr (or.inr ⟨-(m 0), m 1, left.neg_pos_iff.2 hm0, hm1, _⟩)),
simp [hm] },
{ exfalso, simpa [hm0, hy, hm1.ne] using hm },
{ refine false.elim (not_and_distrib.2 hmne ⟨hm0, hm1⟩) },
{ exfalso, simpa [hm0, hy, hm1.ne.symm] using hm },
{ refine or.inl (or.inr (or.inr ⟨m 0, -(m 1), hm0, left.neg_pos_iff.2 hm1, _⟩)),
simp [hm] },
{ exfalso, simpa [hm1, hx, hm0.ne.symm] using hm },
{ refine or.inr (or.inr (or.inr ⟨m 0, m 1, hm0, hm1, _⟩)),
simp [hm] } }
end
/-- Two vectors are in the same ray, or they are nonzero and the first is in the same ray as the
negation of the second, if and only if they are not linearly independent. -/
lemma same_ray_or_ne_zero_and_same_ray_neg_iff_not_linear_independent {x y : M} :
(same_ray R x y ∨ x ≠ 0 ∧ y ≠ 0 ∧ same_ray R x (-y)) ↔ ¬ linear_independent R ![x, y] :=
begin
rw ←same_ray_or_same_ray_neg_iff_not_linear_independent,
by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0;
simp [hx, hy]
end
end
end linear_ordered_comm_ring
namespace same_ray
variables {R : Type*} [linear_ordered_field R]
variables {M : Type*} [add_comm_group M] [module R M] {x y v₁ v₂ : M}
lemma exists_pos_left (h : same_ray R x y) (hx : x ≠ 0) (hy : y ≠ 0) :
∃ r : R, 0 < r ∧ r • x = y :=
let ⟨r₁, r₂, hr₁, hr₂, h⟩ := h.exists_pos hx hy in
⟨r₂⁻¹ * r₁, mul_pos (inv_pos.2 hr₂) hr₁, by rw [mul_smul, h, inv_smul_smul₀ hr₂.ne']⟩
lemma exists_pos_right (h : same_ray R x y) (hx : x ≠ 0) (hy : y ≠ 0) :
∃ r : R, 0 < r ∧ x = r • y :=
(h.symm.exists_pos_left hy hx).imp $ λ _, and.imp_right eq.symm
/-- If a vector `v₂` is on the same ray as a nonzero vector `v₁`, then it is equal to `c • v₁` for
some nonnegative `c`. -/
lemma exists_nonneg_left (h : same_ray R x y) (hx : x ≠ 0) : ∃ r : R, 0 ≤ r ∧ r • x = y :=
begin
obtain rfl | hy := eq_or_ne y 0,
{ exact ⟨0, le_rfl, zero_smul _ _⟩ },
{ exact (h.exists_pos_left hx hy).imp (λ _, and.imp_left le_of_lt) }
end
/-- If a vector `v₁` is on the same ray as a nonzero vector `v₂`, then it is equal to `c • v₂` for
some nonnegative `c`. -/
lemma exists_nonneg_right (h : same_ray R x y) (hy : y ≠ 0) : ∃ r : R, 0 ≤ r ∧ x = r • y :=
(h.symm.exists_nonneg_left hy).imp $ λ _, and.imp_right eq.symm
/-- If vectors `v₁` and `v₂` are on the same ray, then for some nonnegative `a b`, `a + b = 1`, we
have `v₁ = a • (v₁ + v₂)` and `v₂ = b • (v₁ + v₂)`. -/
lemma exists_eq_smul_add (h : same_ray R v₁ v₂) :
∃ a b : R, 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ v₁ = a • (v₁ + v₂) ∧ v₂ = b • (v₁ + v₂) :=
begin
rcases h with rfl|rfl|⟨r₁, r₂, h₁, h₂, H⟩,
{ use [0, 1], simp },
{ use [1, 0], simp },
{ have h₁₂ : 0 < r₁ + r₂, from add_pos h₁ h₂,
refine ⟨r₂ / (r₁ + r₂), r₁ / (r₁ + r₂), div_nonneg h₂.le h₁₂.le, div_nonneg h₁.le h₁₂.le,
_, _, _⟩,
{ rw [← add_div, add_comm, div_self h₁₂.ne'] },
{ rw [div_eq_inv_mul, mul_smul, smul_add, ← H, ← add_smul, add_comm r₂,
inv_smul_smul₀ h₁₂.ne'] },
{ rw [div_eq_inv_mul, mul_smul, smul_add, H, ← add_smul, add_comm r₂,
inv_smul_smul₀ h₁₂.ne'] } }
end
/-- If vectors `v₁` and `v₂` are on the same ray, then they are nonnegative multiples of the same
vector. Actually, this vector can be assumed to be `v₁ + v₂`, see `same_ray.exists_eq_smul_add`. -/
lemma exists_eq_smul (h : same_ray R v₁ v₂) :
∃ (u : M) (a b : R), 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ v₁ = a • u ∧ v₂ = b • u :=
⟨v₁ + v₂, h.exists_eq_smul_add⟩
end same_ray
section linear_ordered_field
variables {R : Type*} [linear_ordered_field R]
variables {M : Type*} [add_comm_group M] [module R M] {x y : M}
lemma exists_pos_left_iff_same_ray (hx : x ≠ 0) (hy : y ≠ 0) :
(∃ r : R, 0 < r ∧ r • x = y) ↔ same_ray R x y :=
begin
refine ⟨λ h, _, λ h, h.exists_pos_left hx hy⟩,
rcases h with ⟨r, hr, rfl⟩,
exact same_ray_pos_smul_right x hr
end
lemma exists_pos_left_iff_same_ray_and_ne_zero (hx : x ≠ 0) :
(∃ r : R, 0 < r ∧ r • x = y) ↔ (same_ray R x y ∧ y ≠ 0) :=
begin
split,
{ rintro ⟨r, hr, rfl⟩,
simp [hx, hr.le, hr.ne'] },
{ rintro ⟨hxy, hy⟩,
exact (exists_pos_left_iff_same_ray hx hy).2 hxy }
end
lemma exists_nonneg_left_iff_same_ray (hx : x ≠ 0) :
(∃ r : R, 0 ≤ r ∧ r • x = y) ↔ same_ray R x y :=
begin
refine ⟨λ h, _, λ h, h.exists_nonneg_left hx⟩,
rcases h with ⟨r, hr, rfl⟩,
exact same_ray_nonneg_smul_right x hr
end
lemma exists_pos_right_iff_same_ray (hx : x ≠ 0) (hy : y ≠ 0) :
(∃ r : R, 0 < r ∧ x = r • y) ↔ same_ray R x y :=
by simpa only [same_ray_comm, eq_comm] using exists_pos_left_iff_same_ray hy hx
lemma exists_pos_right_iff_same_ray_and_ne_zero (hy : y ≠ 0) :
(∃ r : R, 0 < r ∧ x = r • y) ↔ (same_ray R x y ∧ x ≠ 0) :=
by simpa only [same_ray_comm, eq_comm] using exists_pos_left_iff_same_ray_and_ne_zero hy
lemma exists_nonneg_right_iff_same_ray (hy : y ≠ 0) :
(∃ r : R, 0 ≤ r ∧ x = r • y) ↔ same_ray R x y :=
by simpa only [same_ray_comm, eq_comm] using exists_nonneg_left_iff_same_ray hy
end linear_ordered_field
|
325807d95e2c754db8b8bd76d7931ab91dec313e | 2bafba05c98c1107866b39609d15e849a4ca2bb8 | /src/week_8/ideas/distrub_mul_action_hom/Z1.lean | 70a256c39e0b76dcd19b3153fa33b88d15dd1b4e | [
"Apache-2.0"
] | permissive | ImperialCollegeLondon/formalising-mathematics | b54c83c94b5c315024ff09997fcd6b303892a749 | 7cf1d51c27e2038d2804561d63c74711924044a1 | refs/heads/master | 1,651,267,046,302 | 1,638,888,459,000 | 1,638,888,459,000 | 331,592,375 | 284 | 24 | Apache-2.0 | 1,669,593,705,000 | 1,611,224,849,000 | Lean | UTF-8 | Lean | false | false | 3,370 | lean | import week_8.ideas.Z1
/-
## The map `φ.Z1 : Z1 G M →+ Z1 G N`.
Let `G` be a group. Or a monoid.
`Z1` is not just the construction of the group of cocycles
associated to a `G`-module `M`. `Z1` is a functor, which
means that we well as sending G-modules to abelian groups,
it also sends morphisms of `G`-modules to morphisms of abelian groups
(a new definition) and satisfies some theorems (the axioms
for a functor).
This file essentially all takes place in the `distrib_mul_hom`
namespace, because we are building more interface for `φ : M →+[G] N`.
We access this interface via dot notation. For example
`φ.Z1` is the group homomorphism `Z1 G M → Z1 G N`. In fact
this is main definition of the file.
### Definition of `φ.Z1 : Z1 G M →+ Z1 G N`
In this file we define the following function:
Given as input `φ : M →+[G] N` a G-module homomorphism,
we define the ouput `φ.Z1`, a group homomorphism `Z1 G M → Z1 G N`.
This is a two step process: first we define the underlying function,
we then prove that it's a group homomorphism.
3) the proof that the construction sending `φ` to `φ.Z1` is
functorial, i.e. sends the identity `id : M →+[G] M` to the identity
and function composition to function composition.
-/
namespace distrib_mul_action_hom
-- The Z1 construction is functorial in the module `M`. Let's construct
-- the relevant function, showing that if `φ : M →+[G] N` then
-- composition induces an additive group homomorphism `Z1 G M → Z1 G N`.
-- Just like `H0` we first define the auxiliary bare function,
-- and then beef it up to an abelian group homomorphism.
variables {G M N : Type} [monoid G]
[add_comm_group M] [distrib_mul_action G M]
[add_comm_group N] [distrib_mul_action G N]
-- note to self: if I change to Z1.coe_fn then I get a weird error
def Z1_coe_fn (φ : M →+[G] N) (f : Z1 G M) : Z1 G N :=
⟨λ g, φ (f g), begin
-- need to prove that this function obtained by composing the cocycle
-- f with the G-module homomorphism φ is also a cocycle.
simp [←φ.map_smul, -map_smul, f.spec]
end⟩
@[norm_cast]
lemma Z1_coe_fn_coe_comp (φ : M →+[G] N) (f : Z1 G M) (g : G) :
(Z1_coe_fn φ f g : N) = φ (f g) := rfl
def Z1 (φ : M →+[G] N) : Z1 G M →+ Z1 G N :=
-- to make a term of type `X →+ Y` (a group homomorphism) from a function
-- `f : X → Y` and
-- a proof that it preserves addition we use the following constructor:
add_monoid_hom.mk'
-- We now throw in the bare function
(Z1_coe_fn φ)
-- (or could try direct definition:)
-- (λ f, ⟨λ g, φ (f g), begin
-- -- need to prove that this function obtained by composing the cocycle
-- -- f with the G-module homomorphism φ is also a cocycle.
-- intros g h,
-- rw ←φ.map_smul,
-- rw f.spec,
-- simp,
-- end⟩)
-- and now the proof that it preserves addition
begin
intros e f,
ext g,
simp [φ.Z1_coe_fn_coe_comp],
end
-- it's a functor
variables {P : Type} [add_comm_group P] [distrib_mul_action G P]
def map_comp (φ: M →+[G] N) (ψ : N →+[G] P) (z : _root_.Z1 G M) :
(ψ.Z1) ((φ.Z1) z) = (ψ.comp φ).Z1 z :=
begin
refl,
end
@[simp] lemma Z1_spec (φ : M →+[G] N) (a : _root_.Z1 G M) (g : G) :
φ.Z1 a g = φ (a g) := rfl
@[simp] lemma Z1_spec' (φ : M →+[G] N) (a : _root_.Z1 G M) (g : G) :
(φ.Z1 a : G → N) = (φ ∘ a) := rfl
end distrib_mul_action_hom
|
8556b55383664f13cc86907c8ddef4e80e30aba8 | ccb7cdf8ebc2d015a000e8e7904952a36b910425 | /src/prop/classes.lean | 20b319328ace06c8306cb3055583424ad0a58bc3 | [] | no_license | cipher1024/lean-pl | f7258bda55606b75e3e39deaf7ce8928ed177d66 | 829680605ac17e91038d793c0188e9614353ca25 | refs/heads/master | 1,592,558,951,987 | 1,565,043,356,000 | 1,565,043,531,000 | 196,661,367 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,741 | lean |
import order.bounded_lattice
import order.complete_lattice
import prop
open lattice
class has_impl (α : Type*) :=
(impl : α → α → α)
-- infixr ` ⇒ `:60 := has_impl.impl
infixr ` ⇒ ` := has_impl.impl
set_option old_structure_cmd true
class heyting_algebra (α : Type*) extends bounded_lattice α, has_impl α :=
(le_impl_iff : ∀ x y z : α, z ≤ (x ⇒ y) ↔ x ⊓ z ≤ y)
class complete_heyting_algebra (α : Type*) extends complete_lattice α, heyting_algebra α
-- (le_impl_iff : ∀ x y z : α, z ≤ (x ⇒ y) ↔ x ⊓ z ≤ y)
variables {α : Type*}
namespace heyting_algebra
variables [heyting_algebra α]
variables {x y z : α}
lemma inf_div_le : x ⊓ (x ⇒ y) ≤ y :=
(le_impl_iff _ _ _).mp (le_refl _)
lemma le_impl (h : x ⊓ z ≤ y) : z ≤ (x ⇒ y) :=
(le_impl_iff _ _ _).mpr h
end heyting_algebra
class residuated_lattice (α : Type*) extends lattice α, monoid α, has_div α, has_sdiff α :=
(le_div_iff : ∀ x y z : α, z ≤ x / y ↔ x * z ≤ y)
(le_sdiff_iff : ∀ x y z : α, z ≤ y \ x ↔ z * x ≤ y)
class comm_residuated_lattice (α : Type*)
extends comm_monoid α, residuated_lattice α
namespace residuated_lattice
end residuated_lattice
class bunched_implication_logic (α : Type*)
extends comm_residuated_lattice α, complete_heyting_algebra α
open separation separation.hProp
-- #exit
instance {value} : complete_lattice (hProp value) :=
pi.complete_lattice
instance {value} : complete_heyting_algebra (hProp value) :=
{ impl := λ x y h, x h → y h,
le_impl_iff := λ x y z, ⟨λ H h ⟨hx,hz⟩, H _ hz hx,λ H, λ h hz hx, H h ⟨hx,hz⟩⟩,
.. separation.hProp.lattice.complete_lattice }
instance {value} : comm_monoid (hProp value) :=
{ mul := and,
mul_assoc := and_assoc,
one := emp,
one_mul := emp_and,
mul_one := and_emp,
mul_comm := and_comm }
instance {value} : comm_residuated_lattice (hProp value) :=
{ div := wand,
sdiff := flip wand,
le_div_iff := λ p q r,
show r ≤ p ⊸ q ↔ p ⊛ r ≤ q,
from (@separation.hProp.and_comm value r p) ▸ sorry,
le_sdiff_iff := λ p q r,
show r ≤ p ⊸ q ↔ r ⊛ p ≤ q,
from (@separation.hProp.and_comm value r p) ▸ sorry,
.. separation.hProp.comm_monoid,
.. separation.hProp.lattice.complete_lattice, }
-- #exit
instance {value} : bunched_implication_logic (hProp value) :=
{ .. separation.hProp.complete_heyting_algebra,
.. separation.hProp.comm_residuated_lattice, }
-- { le := impl,
-- top := True,
-- bot := False,
-- one := emp,
-- mul := hProp.and,
-- div := wand,
-- sdiff := flip wand,
-- inf := p_and,
-- sup := p_or,
-- mul_one := and_emp,
-- one_mul := emp_and,
-- mul_comm := and_comm,
-- mul_assoc := and_assoc,
-- le_Sup := _,
-- sup_le := _,
-- -- le_inf := _
-- }
-- class bunched_impl (α : Type) extends :=
-- universes u v w
-- def Flift (F : Type v → Type w) (α : Type u) : Type* :=
-- Σ β, F β × (β → α)
-- class foldable (F : Type u → Type v) :=
-- (foldl : ∀ {α β : Type u}, (α → β → α) → α → F β → α)
-- variables {F : Type u → Type v} [foldable F]
-- open ulift
-- def Flift.foldl {α β : Type w} (f : α → β → α) (x : α) : Flift F β → α
-- | ⟨γ,y,g⟩ := sorry -- ulift.down $ foldable.foldl.{u v} (λ a b, up $ f (down a) _) (up x) y
-- instance : foldable (Flift.{w} F) :=
-- ⟨ @Flift.foldl F _ ⟩
-- def Flift.mk {α} (x : F α) : Flift F (ulift.{w} α) :=
-- ⟨_, x, up⟩
-- -- set_option pp.implicit true
-- def foldl {α : Type w} {β : Type u} (f : α → β → α) (x : α) (xs : F β) : α :=
-- down $ @foldable.foldl (Flift F) _ _ _ (λ a (b : ulift.{w} β), up $ f (down a) (down b)) (up.{u} x) (Flift.mk.{u} xs)
|
bfdf24e446b2fa59b3f0f3d499803b6277e2deef | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/logic/unique.lean | 53df3e35e7f4cfa2912f576ba2d8997391af3d8e | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 5,561 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import tactic.basic
import logic.is_empty
/-!
# Types with a unique term
In this file we define a typeclass `unique`,
which expresses that a type has a unique term.
In other words, a type that is `inhabited` and a `subsingleton`.
## Main declaration
* `unique`: a typeclass that expresses that a type has a unique term.
## Main statements
* `unique.mk'`: an inhabited subsingleton type is `unique`. This can not be an instance because it
would lead to loops in typeclass inference.
* `function.surjective.unique`: if the domain of a surjective function is `unique`, then its
codomain is `unique` as well.
* `function.injective.subsingleton`: if the codomain of an injective function is `subsingleton`,
then its domain is `subsingleton` as well.
* `function.injective.unique`: if the codomain of an injective function is `subsingleton` and its
domain is `inhabited`, then its domain is `unique`.
## Implementation details
The typeclass `unique α` is implemented as a type,
rather than a `Prop`-valued predicate,
for good definitional properties of the default term.
-/
universes u v w
variables {α : Sort u} {β : Sort v} {γ : Sort w}
/-- `unique α` expresses that `α` is a type with a unique term `default α`.
This is implemented as a type, rather than a `Prop`-valued predicate,
for good definitional properties of the default term. -/
@[ext]
structure unique (α : Sort u) extends inhabited α :=
(uniq : ∀ a:α, a = default)
attribute [class] unique
/-- Given an explicit `a : α` with `[subsingleton α]`, we can construct
a `[unique α]` instance. This is a def because the typeclass search cannot
arbitrarily invent the `a : α` term. Nevertheless, these instances are all
equivalent by `unique.subsingleton.unique`.
See note [reducible non-instances]. -/
@[reducible] def unique_of_subsingleton {α : Sort*} [subsingleton α] (a : α) : unique α :=
{ default := a,
uniq := λ _, subsingleton.elim _ _ }
instance punit.unique : unique punit.{u} :=
{ default := punit.star,
uniq := λ x, punit_eq x _ }
/-- Every provable proposition is unique, as all proofs are equal. -/
def unique_prop {p : Prop} (h : p) : unique p :=
{ default := h, uniq := λ x, rfl }
instance : unique true := unique_prop trivial
lemma fin.eq_zero : ∀ n : fin 1, n = 0
| ⟨n, hn⟩ := fin.eq_of_veq (nat.eq_zero_of_le_zero (nat.le_of_lt_succ hn))
instance {n : ℕ} : inhabited (fin n.succ) := ⟨0⟩
instance inhabited_fin_one_add (n : ℕ) : inhabited (fin (1 + n)) := ⟨⟨0, nat.zero_lt_one_add n⟩⟩
@[simp] lemma fin.default_eq_zero (n : ℕ) : default (fin n.succ) = 0 := rfl
instance fin.unique : unique (fin 1) :=
{ uniq := fin.eq_zero, .. fin.inhabited }
namespace unique
open function
section
variables [unique α]
@[priority 100] -- see Note [lower instance priority]
instance : inhabited α := to_inhabited ‹unique α›
lemma eq_default (a : α) : a = default α := uniq _ a
lemma default_eq (a : α) : default α = a := (uniq _ a).symm
@[priority 100] -- see Note [lower instance priority]
instance : subsingleton α := subsingleton_of_forall_eq _ eq_default
lemma forall_iff {p : α → Prop} : (∀ a, p a) ↔ p (default α) :=
⟨λ h, h _, λ h x, by rwa [unique.eq_default x]⟩
lemma exists_iff {p : α → Prop} : Exists p ↔ p (default α) :=
⟨λ ⟨a, ha⟩, eq_default a ▸ ha, exists.intro (default α)⟩
end
@[ext] protected lemma subsingleton_unique' : ∀ (h₁ h₂ : unique α), h₁ = h₂
| ⟨⟨x⟩, h⟩ ⟨⟨y⟩, _⟩ := by congr; rw [h x, h y]
instance subsingleton_unique : subsingleton (unique α) :=
⟨unique.subsingleton_unique'⟩
/-- Construct `unique` from `inhabited` and `subsingleton`. Making this an instance would create
a loop in the class inheritance graph. -/
def mk' (α : Sort u) [h₁ : inhabited α] [subsingleton α] : unique α :=
{ uniq := λ x, subsingleton.elim _ _, .. h₁ }
end unique
@[simp] lemma pi.default_def {β : Π a : α, Sort v} [Π a, inhabited (β a)] :
default (Π a, β a) = λ a, default (β a) :=
rfl
lemma pi.default_apply {β : Π a : α, Sort v} [Π a, inhabited (β a)] (a : α) :
default (Π a, β a) a = default (β a) :=
rfl
instance pi.unique {β : Π a : α, Sort v} [Π a, unique (β a)] : unique (Π a, β a) :=
{ uniq := λ f, funext $ λ x, unique.eq_default _,
.. pi.inhabited α }
/-- There is a unique function on an empty domain. -/
instance pi.unique_of_is_empty [is_empty α] (β : Π a : α, Sort v) :
unique (Π a, β a) :=
{ default := is_empty_elim,
uniq := λ f, funext is_empty_elim }
namespace function
variable {f : α → β}
/-- If the domain of a surjective function is a singleton,
then the codomain is a singleton as well. -/
protected def surjective.unique (hf : surjective f) [unique α] : unique β :=
{ default := f (default _),
uniq := λ b, let ⟨a, ha⟩ := hf b in ha ▸ congr_arg f (unique.eq_default _) }
/-- If the codomain of an injective function is a subsingleton, then the domain
is a subsingleton as well. -/
protected lemma injective.subsingleton (hf : injective f) [subsingleton β] :
subsingleton α :=
⟨λ x y, hf $ subsingleton.elim _ _⟩
/-- If `α` is inhabited and admits an injective map to a subsingleton type, then `α` is `unique`. -/
protected def injective.unique [inhabited α] [subsingleton β] (hf : injective f) : unique α :=
@unique.mk' _ _ hf.subsingleton
end function
|
dcdd46eed82c9d0d73b22c5d185e44b2c7c74afb | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch2/ex0309.lean | 24075016fda95fee707168ac00d2056ad273d091 | [] | 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 | 21 | lean | #eval 12345 * 54321
|
f4cd1f9a6be18c67f53a9036343f2de8c49e49df | 94e33a31faa76775069b071adea97e86e218a8ee | /src/data/polynomial/unit_trinomial.lean | 48f117061837cf2d3e19a2db6f07dd4c3dd328a7 | [
"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 | 16,190 | lean | /-
Copyright (c) 2022 Thomas Browning. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning
-/
import analysis.complex.polynomial
import data.polynomial.mirror
/-!
# Unit Trinomials
This file defines irreducible trinomials and proves an irreducibility criterion.
## Main definitions
- `polynomial.is_unit_trinomial`
## Main results
- `polynomial.irreducible_of_coprime`: An irreducibility criterion for unit trinomials.
-/
namespace polynomial
open_locale polynomial
open finset
section semiring
variables {R : Type*} [semiring R] (k m n : ℕ) (u v w : R)
/-- Shorthand for a trinomial -/
noncomputable def trinomial := C u * X ^ k + C v * X ^ m + C w * X ^ n
lemma trinomial_def : trinomial k m n u v w = C u * X ^ k + C v * X ^ m + C w * X ^ n := rfl
variables {k m n u v w}
lemma trinomial_leading_coeff' (hkm : k < m) (hmn : m < n) :
(trinomial k m n u v w).coeff n = w :=
by rw [trinomial_def, coeff_add, coeff_add, coeff_C_mul_X_pow, coeff_C_mul_X_pow,
coeff_C_mul_X_pow, if_neg (hkm.trans hmn).ne', if_neg hmn.ne', if_pos rfl, zero_add, zero_add]
lemma trinomial_middle_coeff (hkm : k < m) (hmn : m < n) :
(trinomial k m n u v w).coeff m = v :=
by rw [trinomial_def, coeff_add, coeff_add, coeff_C_mul_X_pow, coeff_C_mul_X_pow,
coeff_C_mul_X_pow, if_neg hkm.ne', if_pos rfl, if_neg hmn.ne, zero_add, add_zero]
lemma trinomial_trailing_coeff' (hkm : k < m) (hmn : m < n) :
(trinomial k m n u v w).coeff k = u :=
by rw [trinomial_def, coeff_add, coeff_add, coeff_C_mul_X_pow, coeff_C_mul_X_pow,
coeff_C_mul_X_pow, if_pos rfl, if_neg hkm.ne, if_neg (hkm.trans hmn).ne, add_zero, add_zero]
lemma trinomial_nat_degree (hkm : k < m) (hmn : m < n) (hw : w ≠ 0) :
(trinomial k m n u v w).nat_degree = n :=
begin
refine nat_degree_eq_of_degree_eq_some (le_antisymm (sup_le (λ i h, _))
(le_degree_of_ne_zero (by rwa trinomial_leading_coeff' hkm hmn))),
replace h := support_trinomial' k m n u v w h,
rw [mem_insert, mem_insert, mem_singleton] at h,
rcases h with rfl | rfl | rfl,
{ exact with_bot.coe_le_coe.mpr (hkm.trans hmn).le },
{ exact with_bot.coe_le_coe.mpr hmn.le },
{ exact le_rfl },
end
lemma trinomial_nat_trailing_degree (hkm : k < m) (hmn : m < n) (hu : u ≠ 0) :
(trinomial k m n u v w).nat_trailing_degree = k :=
begin
refine nat_trailing_degree_eq_of_trailing_degree_eq_some (le_antisymm (le_inf (λ i h, _))
(le_trailing_degree_of_ne_zero (by rwa trinomial_trailing_coeff' hkm hmn))).symm,
replace h := support_trinomial' k m n u v w h,
rw [mem_insert, mem_insert, mem_singleton] at h,
rcases h with rfl | rfl | rfl,
{ exact le_rfl },
{ exact with_top.coe_le_coe.mpr hkm.le },
{ exact with_top.coe_le_coe.mpr (hkm.trans hmn).le },
end
lemma trinomial_leading_coeff (hkm : k < m) (hmn : m < n) (hw : w ≠ 0) :
(trinomial k m n u v w).leading_coeff = w :=
by rw [leading_coeff, trinomial_nat_degree hkm hmn hw, trinomial_leading_coeff' hkm hmn]
lemma trinomial_trailing_coeff (hkm : k < m) (hmn : m < n) (hu : u ≠ 0) :
(trinomial k m n u v w).trailing_coeff = u :=
by rw [trailing_coeff, trinomial_nat_trailing_degree hkm hmn hu, trinomial_trailing_coeff' hkm hmn]
lemma trinomial_monic (hkm : k < m) (hmn : m < n) : (trinomial k m n u v 1).monic :=
begin
casesI subsingleton_or_nontrivial R with h h,
{ apply subsingleton.elim },
{ exact trinomial_leading_coeff hkm hmn one_ne_zero },
end
lemma trinomial_mirror (hkm : k < m) (hmn : m < n) (hu : u ≠ 0) (hw : w ≠ 0) :
(trinomial k m n u v w).mirror = trinomial k (n - m + k) n w v u :=
by rw [mirror, trinomial_nat_trailing_degree hkm hmn hu, reverse, trinomial_nat_degree hkm hmn hw,
trinomial_def, reflect_add, reflect_add, reflect_C_mul_X_pow, reflect_C_mul_X_pow,
reflect_C_mul_X_pow, rev_at_le (hkm.trans hmn).le, rev_at_le hmn.le, rev_at_le le_rfl,
add_mul, add_mul, mul_assoc, mul_assoc, mul_assoc, ←pow_add, ←pow_add, ←pow_add,
nat.sub_add_cancel (hkm.trans hmn).le, nat.sub_self, zero_add, add_comm, add_comm (C u * X ^ n),
←add_assoc, ←trinomial_def]
lemma trinomial_support (hkm : k < m) (hmn : m < n) (hu : u ≠ 0) (hv : v ≠ 0) (hw : w ≠ 0) :
(trinomial k m n u v w).support = {k, m, n} :=
support_trinomial hkm hmn hu hv hw
end semiring
variables (p q : ℤ[X])
/-- A unit trinomial is a trinomial with unit coefficients. -/
def is_unit_trinomial := ∃ {k m n : ℕ} (hkm : k < m) (hmn : m < n) {u v w : units ℤ},
p = trinomial k m n u v w
variables {p q}
namespace is_unit_trinomial
lemma not_is_unit (hp : p.is_unit_trinomial) : ¬ is_unit p :=
begin
obtain ⟨k, m, n, hkm, hmn, u, v, w, rfl⟩ := hp,
exact λ h, ne_zero_of_lt hmn ((trinomial_nat_degree hkm hmn w.ne_zero).symm.trans
(nat_degree_eq_of_degree_eq_some (degree_eq_zero_of_is_unit h))),
end
lemma card_support_eq_three (hp : p.is_unit_trinomial) : p.support.card = 3 :=
begin
obtain ⟨k, m, n, hkm, hmn, u, v, w, rfl⟩ := hp,
exact card_support_trinomial hkm hmn u.ne_zero v.ne_zero w.ne_zero,
end
lemma ne_zero (hp : p.is_unit_trinomial) : p ≠ 0 :=
begin
rintro rfl,
exact nat.zero_ne_bit1 1 hp.card_support_eq_three,
end
lemma coeff_is_unit (hp : p.is_unit_trinomial) {k : ℕ} (hk : k ∈ p.support) :
is_unit (p.coeff k) :=
begin
obtain ⟨k, m, n, hkm, hmn, u, v, w, rfl⟩ := hp,
have := support_trinomial' k m n ↑u ↑v ↑w hk,
rw [mem_insert, mem_insert, mem_singleton] at this,
rcases this with rfl | rfl | rfl,
{ refine ⟨u, by rw trinomial_trailing_coeff' hkm hmn⟩ },
{ refine ⟨v, by rw trinomial_middle_coeff hkm hmn⟩ },
{ refine ⟨w, by rw trinomial_leading_coeff' hkm hmn⟩ },
end
lemma leading_coeff_is_unit (hp : p.is_unit_trinomial) : is_unit p.leading_coeff :=
hp.coeff_is_unit (nat_degree_mem_support_of_nonzero hp.ne_zero)
lemma trailing_coeff_is_unit (hp : p.is_unit_trinomial) : is_unit p.trailing_coeff :=
hp.coeff_is_unit (nat_trailing_degree_mem_support_of_nonzero hp.ne_zero)
end is_unit_trinomial
lemma is_unit_trinomial_iff :
p.is_unit_trinomial ↔ p.support.card = 3 ∧ ∀ k ∈ p.support, is_unit (p.coeff k) :=
begin
refine ⟨λ hp, ⟨hp.card_support_eq_three, λ k, hp.coeff_is_unit⟩, λ hp, _⟩,
obtain ⟨k, m, n, hkm, hmn, x, y, z, hx, hy, hz, rfl⟩ := card_support_eq_three.mp hp.1,
rw [support_trinomial hkm hmn hx hy hz] at hp,
replace hx := hp.2 k (mem_insert_self k {m, n}),
replace hy := hp.2 m (mem_insert_of_mem (mem_insert_self m {n})),
replace hz := hp.2 n (mem_insert_of_mem (mem_insert_of_mem (mem_singleton_self n))),
simp_rw [coeff_add, coeff_C_mul, coeff_X_pow_self, mul_one, coeff_X_pow] at hx hy hz,
rw [if_neg hkm.ne, if_neg (hkm.trans hmn).ne] at hx,
rw [if_neg hkm.ne', if_neg hmn.ne] at hy,
rw [if_neg (hkm.trans hmn).ne', if_neg hmn.ne'] at hz,
simp_rw [mul_zero, zero_add, add_zero] at hx hy hz,
exact ⟨k, m, n, hkm, hmn, hx.unit, hy.unit, hz.unit, rfl⟩,
end
lemma is_unit_trinomial_iff' : p.is_unit_trinomial ↔ (p * p.mirror).coeff
(((p * p.mirror).nat_degree + (p * p.mirror).nat_trailing_degree) / 2) = 3 :=
begin
rw [nat_degree_mul_mirror, nat_trailing_degree_mul_mirror, ←mul_add,
nat.mul_div_right _ zero_lt_two, coeff_mul_mirror],
refine ⟨_, λ hp, _⟩,
{ rintros ⟨k, m, n, hkm, hmn, u, v, w, rfl⟩,
rw [sum_def, trinomial_support hkm hmn u.ne_zero v.ne_zero w.ne_zero,
sum_insert (mt mem_insert.mp (not_or hkm.ne (mt mem_singleton.mp (hkm.trans hmn).ne))),
sum_insert (mt mem_singleton.mp hmn.ne), sum_singleton, trinomial_leading_coeff' hkm hmn,
trinomial_middle_coeff hkm hmn, trinomial_trailing_coeff' hkm hmn],
simp_rw [←units.coe_pow, int.units_sq, units.coe_one, ←add_assoc, bit1, bit0] },
{ have key : ∀ k ∈ p.support, (p.coeff k) ^ 2 = 1 :=
λ k hk, int.sq_eq_one_of_sq_le_three ((single_le_sum
(λ k hk, sq_nonneg (p.coeff k)) hk).trans hp.le) (mem_support_iff.mp hk),
refine is_unit_trinomial_iff.mpr ⟨_, λ k hk, is_unit_of_pow_eq_one _ 2 (key k hk) zero_lt_two⟩,
rw [sum_def, sum_congr rfl key, sum_const, nat.smul_one_eq_coe] at hp,
exact nat.cast_injective hp },
end
lemma is_unit_trinomial_iff'' (h : p * p.mirror = q * q.mirror) :
p.is_unit_trinomial ↔ q.is_unit_trinomial :=
by rw [is_unit_trinomial_iff', is_unit_trinomial_iff', h]
namespace is_unit_trinomial
lemma irreducible_aux1 {k m n : ℕ} (hkm : k < m) (hmn : m < n) (u v w : units ℤ)
(hp : p = trinomial k m n u v w) :
C ↑v * (C ↑u * X ^ (m + n) + C ↑w * X ^ (n - m + k + n)) =
⟨finsupp.filter (set.Ioo (k + n) (n + n)) (p * p.mirror).to_finsupp⟩ :=
begin
have key : n - m + k < n := by rwa [←lt_tsub_iff_right, tsub_lt_tsub_iff_left_of_le hmn.le],
rw [hp, trinomial_mirror hkm hmn u.ne_zero w.ne_zero],
simp_rw [trinomial_def, ←monomial_eq_C_mul_X, add_mul, mul_add, monomial_mul_monomial,
to_finsupp_add, to_finsupp_monomial, finsupp.filter_add],
rw [finsupp.filter_single_of_neg, finsupp.filter_single_of_neg, finsupp.filter_single_of_neg,
finsupp.filter_single_of_neg, finsupp.filter_single_of_neg, finsupp.filter_single_of_pos,
finsupp.filter_single_of_neg, finsupp.filter_single_of_pos, finsupp.filter_single_of_neg],
{ simp only [add_zero, zero_add, of_finsupp_add, of_finsupp_single],
rw [C_mul_monomial, C_mul_monomial, mul_comm ↑v ↑w, add_comm (n - m + k) n] },
{ exact λ h, h.2.ne rfl },
{ refine ⟨_, add_lt_add_left key n⟩,
rwa [add_comm, add_lt_add_iff_left, lt_add_iff_pos_left, tsub_pos_iff_lt] },
{ exact λ h, h.1.ne (add_comm k n) },
{ exact ⟨add_lt_add_right hkm n, add_lt_add_right hmn n⟩ },
{ rw [←add_assoc, add_tsub_cancel_of_le hmn.le, add_comm],
exact λ h, h.1.ne rfl },
{ intro h,
have := h.1,
rw [add_comm, add_lt_add_iff_right] at this,
exact asymm this hmn },
{ exact λ h, h.1.ne rfl },
{ exact λ h, asymm ((add_lt_add_iff_left k).mp h.1) key },
{ exact λ h, asymm ((add_lt_add_iff_left k).mp h.1) (hkm.trans hmn) },
end
lemma irreducible_aux2 {k m m' n : ℕ}
(hkm : k < m) (hmn : m < n) (hkm' : k < m') (hmn' : m' < n)
(u v w : units ℤ)
(hp : p = trinomial k m n u v w) (hq : q = trinomial k m' n u v w)
(h : p * p.mirror = q * q.mirror) :
q = p ∨ q = p.mirror :=
begin
let f : ℤ[X] → ℤ[X] :=
λ p, ⟨finsupp.filter (set.Ioo (k + n) (n + n)) p.to_finsupp⟩,
replace h := congr_arg f h,
replace h := (irreducible_aux1 hkm hmn u v w hp).trans h,
replace h := h.trans (irreducible_aux1 hkm' hmn' u v w hq).symm,
rw (is_unit_C.mpr v.is_unit).mul_right_inj at h,
rw binomial_eq_binomial u.ne_zero w.ne_zero at h,
simp only [add_left_inj, units.eq_iff] at h,
rcases h with ⟨rfl, -⟩ | ⟨rfl, rfl, h⟩ | ⟨-, hm, hm'⟩,
{ exact or.inl (hq.trans hp.symm) },
{ refine or.inr _,
rw [←trinomial_mirror hkm' hmn' u.ne_zero u.ne_zero, eq_comm, mirror_eq_iff] at hp,
exact hq.trans hp },
{ suffices : m = m',
{ rw this at hp,
exact or.inl (hq.trans hp.symm) },
rw [tsub_add_eq_add_tsub hmn.le, eq_tsub_iff_add_eq_of_le, ←two_mul] at hm,
rw [tsub_add_eq_add_tsub hmn'.le, eq_tsub_iff_add_eq_of_le, ←two_mul] at hm',
exact mul_left_cancel₀ two_ne_zero (hm.trans hm'.symm),
exact hmn'.le.trans (nat.le_add_right n k),
exact hmn.le.trans (nat.le_add_right n k) },
end
lemma irreducible_aux3 {k m m' n : ℕ}
(hkm : k < m) (hmn : m < n) (hkm' : k < m') (hmn' : m' < n) (u v w x z : units ℤ)
(hp : p = trinomial k m n u v w) (hq : q = trinomial k m' n x v z)
(h : p * p.mirror = q * q.mirror) :
q = p ∨ q = p.mirror :=
begin
have hmul := congr_arg leading_coeff h,
rw [leading_coeff_mul, leading_coeff_mul, mirror_leading_coeff, mirror_leading_coeff, hp, hq,
trinomial_leading_coeff hkm hmn w.ne_zero, trinomial_leading_coeff hkm' hmn' z.ne_zero,
trinomial_trailing_coeff hkm hmn u.ne_zero,
trinomial_trailing_coeff hkm' hmn' x.ne_zero] at hmul,
have hadd := congr_arg (eval 1) h,
rw [eval_mul, eval_mul, mirror_eval_one, mirror_eval_one, ←sq, ←sq, hp, hq] at hadd,
simp only [eval_add, eval_C_mul, eval_pow, eval_X, one_pow, mul_one, trinomial_def] at hadd,
rw [add_assoc, add_assoc, add_comm ↑u, add_comm ↑x, add_assoc, add_assoc] at hadd,
simp only [add_sq', add_assoc, add_right_inj, ←units.coe_pow, int.units_sq] at hadd,
rw [mul_assoc, hmul, ←mul_assoc, add_right_inj,
mul_right_inj' (show 2 * (v : ℤ) ≠ 0, from mul_ne_zero two_ne_zero v.ne_zero)] at hadd,
replace hadd := (int.is_unit_add_is_unit_eq_is_unit_add_is_unit w.is_unit u.is_unit
z.is_unit x.is_unit).mp hadd,
simp only [units.eq_iff] at hadd,
rcases hadd with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩,
{ exact irreducible_aux2 hkm hmn hkm' hmn' u v w hp hq h },
{ rw [←mirror_inj, trinomial_mirror hkm' hmn' w.ne_zero u.ne_zero] at hq,
rw [mul_comm q, ←q.mirror_mirror, q.mirror.mirror_mirror] at h,
rw [←mirror_inj, or_comm, ←mirror_eq_iff],
exact irreducible_aux2 hkm hmn (lt_add_of_pos_left k (tsub_pos_of_lt hmn'))
((lt_tsub_iff_right).mp ((tsub_lt_tsub_iff_left_of_le hmn'.le).mpr hkm')) u v w hp hq h },
end
lemma irreducible_of_coprime (hp : p.is_unit_trinomial)
(h : ∀ q : ℤ[X], q ∣ p → q ∣ p.mirror → is_unit q) :
irreducible p :=
begin
refine irreducible_of_mirror hp.not_is_unit (λ q hpq, _) h,
have hq : is_unit_trinomial q := (is_unit_trinomial_iff'' hpq).mp hp,
obtain ⟨k, m, n, hkm, hmn, u, v, w, hp⟩ := hp,
obtain ⟨k', m', n', hkm', hmn', x, y, z, hq⟩ := hq,
have hk : k = k',
{ rw [←mul_right_inj' (show 2 ≠ 0, from two_ne_zero),
←trinomial_nat_trailing_degree hkm hmn u.ne_zero, ←hp, ←nat_trailing_degree_mul_mirror, hpq,
nat_trailing_degree_mul_mirror, hq, trinomial_nat_trailing_degree hkm' hmn' x.ne_zero] },
have hn : n = n',
{ rw [←mul_right_inj' (show 2 ≠ 0, from two_ne_zero),
←trinomial_nat_degree hkm hmn w.ne_zero, ←hp, ←nat_degree_mul_mirror, hpq,
nat_degree_mul_mirror, hq, trinomial_nat_degree hkm' hmn' z.ne_zero] },
subst hk,
subst hn,
rcases eq_or_eq_neg_of_sq_eq_sq ↑y ↑v
((int.is_unit_sq y.is_unit).trans (int.is_unit_sq v.is_unit).symm) with h1 | h1,
{ rw h1 at *,
rcases irreducible_aux3 hkm hmn hkm' hmn' u v w x z hp hq hpq with h2 | h2,
{ exact or.inl h2 },
{ exact or.inr (or.inr (or.inl h2)) } },
{ rw h1 at *,
rw trinomial_def at hp,
rw [←neg_inj, neg_add, neg_add, ←neg_mul, ←neg_mul, ←neg_mul, ←C_neg, ←C_neg, ←C_neg] at hp,
rw [←neg_mul_neg, ←mirror_neg] at hpq,
rcases irreducible_aux3 hkm hmn hkm' hmn' (-u) (-v) (-w) x z hp hq hpq with rfl | rfl,
{ exact or.inr (or.inl rfl) },
{ exact or.inr (or.inr (or.inr p.mirror_neg)) } },
end
/-- A unit trinomial is irreducible if it is coprime with its mirror -/
lemma irreducible_of_is_coprime (hp : p.is_unit_trinomial) (h : is_coprime p p.mirror) :
irreducible p :=
irreducible_of_coprime hp (λ q, h.is_unit_of_dvd')
/-- A unit trinomial is irreducible if it has no complex roots in common with its mirror -/
lemma irreducible_of_coprime' (hp : is_unit_trinomial p)
(h : ∀ z : ℂ, ¬ (aeval z p = 0 ∧ aeval z (mirror p) = 0)) : irreducible p :=
begin
refine hp.irreducible_of_coprime (λ q hq hq', _),
suffices : ¬ (0 < q.nat_degree),
{ rcases hq with ⟨p, rfl⟩,
replace hp := hp.leading_coeff_is_unit,
rw leading_coeff_mul at hp,
replace hp := is_unit_of_mul_is_unit_left hp,
rw [not_lt, nat.le_zero_iff] at this,
rwa [eq_C_of_nat_degree_eq_zero this, is_unit_C, ←this] },
intro hq'',
rw nat_degree_pos_iff_degree_pos at hq'',
rw ← degree_map_eq_of_injective (algebra_map ℤ ℂ).injective_int at hq'',
cases complex.exists_root hq'' with z hz,
rw [is_root, eval_map, ←aeval_def] at hz,
refine h z ⟨_, _⟩,
{ cases hq with g' hg',
rw [hg', aeval_mul, hz, zero_mul] },
{ cases hq' with g' hg',
rw [hg', aeval_mul, hz, zero_mul] },
end
-- TODO: Develop more theory (e.g., it suffices to check that `aeval z p ≠ 0` for `z = 0`
-- and `z` a root of unity)
end is_unit_trinomial
end polynomial
|
65d1f6e6742cc407032b98540af2f8380888cb9c | e514e8b939af519a1d5e9b30a850769d058df4e9 | /test/rewrite_search_optimal.lean | 92a8c5e332cee637699f53e4ce611f6fb531acaa | [] | no_license | semorrison/lean-rewrite-search | dca317c5a52e170fb6ffc87c5ab767afb5e3e51a | e804b8f2753366b8957be839908230ee73f9e89f | refs/heads/master | 1,624,051,754,485 | 1,614,160,817,000 | 1,614,160,817,000 | 162,660,605 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 831 | lean | import tactic.rewrite_search
axiom foo : [0] = [1]
axiom bar1 : [1] = [2]
axiom bar2 : [2] = [3]
axiom bar3 : [3] = [4]
axiom bar4 : [4] = [5]
axiom bar5 : [5] = [6]
axiom bar6 : [6] = [7]
axiom baz : [4] = [0]
-- Obviously sub-optimal
example : [0] = [7] :=
begin
-- erw [foo, bar1, bar2, bar3, bar4, bar5, bar6],
rewrite_search_with [foo, bar1, bar2, bar3, bar4, bar5, bar6, baz]
{ optimal := ff, no visualiser, explain := tt },
end
example : [0] = [7] :=
begin
/- `rewrite_search` says -/
erw [foo, bar1, bar2, bar3, bar4, bar5, bar6]
end
-- Obviously optimal
example : [0] = [7] :=
begin
rewrite_search_with [foo, bar1, bar2, bar3, bar4, bar5, bar6, baz]
{ optimal := tt, no visualiser, explain := tt },
end
example : [0] = [7] :=
begin
/- `rewrite_search` says -/
erw [←baz, bar4, bar5, bar6]
end
|
5324f7bf84bf35c570dba45ceb915fd13ba78259 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/ftree.lean | 1a3b861b8ebf857fc82070892a302dac3fd4a705 | [
"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 | 717 | lean | inductive List (T : Type*) : Type* | nil {} : List | cons : T → List → List
namespace explicit
inductive {u₁ u₂} ftree (A : Type u₁) (B : Type u₂) : Type (max 1 u₁ u₂)
| leafa : A → ftree
| leafb : B → ftree
| node : (A → ftree) → (B → ftree) → ftree
end explicit
namespace implicit
inductive ftree (A : Type) (B : Type) : Type
| leafa : ftree
| node : (A → B → ftree) → (B → ftree) → ftree
set_option pp.universes true
check ftree
end implicit
namespace implicit2
inductive ftree (A : Type) (B : Type) : Type
| leafa : A → ftree
| leafb : B → ftree
| node : (List A → ftree) → (B → ftree) → ftree
set_option pp.universes true
check ftree
end implicit2
|
067d4bfcbaa298c8687642b2a9964d6311e6ba97 | 97f752b44fd85ec3f635078a2dd125ddae7a82b6 | /hott/algebra/category/category.hlean | dc0a85f8d4b30db287806df05b18fc7659a50e45 | [
"Apache-2.0"
] | permissive | tectronics/lean | ab977ba6be0fcd46047ddbb3c8e16e7c26710701 | f38af35e0616f89c6e9d7e3eb1d48e47ee666efe | refs/heads/master | 1,532,358,526,384 | 1,456,276,623,000 | 1,456,276,623,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,796 | hlean | /-
Copyright (c) 2014 Jakob von Raumer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jakob von Raumer
-/
import .iso
open iso is_equiv equiv eq is_trunc sigma equiv.ops
/-
A category is a precategory extended by a witness
that the function from paths to isomorphisms is an equivalence.
-/
namespace category
/-
TODO: restructure this. Should is_univalent be a class with as argument
(C : Precategory). Or is that problematic if we want to apply this to cases where e.g.
a b are functors, and we need to synthesize ? : precategory (functor C D).
-/
definition is_univalent [class] {ob : Type} (C : precategory ob) :=
Π(a b : ob), is_equiv (iso_of_eq : a = b → a ≅ b)
definition is_equiv_of_is_univalent [instance] {ob : Type} [C : precategory ob]
[H : is_univalent C] (a b : ob) : is_equiv (iso_of_eq : a = b → a ≅ b) :=
H a b
structure category [class] (ob : Type) extends parent : precategory ob :=
mk' :: (iso_of_path_equiv : is_univalent parent)
-- Remark: category and precategory are classes. So, the structure command
-- does not create a coercion between them automatically.
-- This coercion is needed for definitions such as category_eq_of_equiv
-- without it, we would have to explicitly use category.to_precategory
attribute category.to_precategory [coercion]
attribute category [multiple_instances]
abbreviation iso_of_path_equiv := @category.iso_of_path_equiv
attribute category.iso_of_path_equiv [instance]
definition category.mk [reducible] [unfold 2] {ob : Type} (C : precategory ob)
(H : is_univalent C) : category ob :=
precategory.rec_on C category.mk' H
section basic
variables {ob : Type} [C : category ob]
include C
-- Make iso_of_path_equiv a class instance
attribute iso_of_path_equiv [instance]
definition eq_equiv_iso [constructor] (a b : ob) : (a = b) ≃ (a ≅ b) :=
equiv.mk iso_of_eq _
definition eq_of_iso [reducible] {a b : ob} : a ≅ b → a = b :=
iso_of_eq⁻¹ᶠ
definition iso_of_eq_eq_of_iso {a b : ob} (p : a ≅ b) : iso_of_eq (eq_of_iso p) = p :=
right_inv iso_of_eq p
definition hom_of_eq_eq_of_iso {a b : ob} (p : a ≅ b) : hom_of_eq (eq_of_iso p) = to_hom p :=
ap to_hom !iso_of_eq_eq_of_iso
definition inv_of_eq_eq_of_iso {a b : ob} (p : a ≅ b) : inv_of_eq (eq_of_iso p) = to_inv p :=
ap to_inv !iso_of_eq_eq_of_iso
theorem eq_of_iso_refl {a : ob} : eq_of_iso (iso.refl a) = idp :=
inv_eq_of_eq idp
definition is_trunc_1_ob : is_trunc 1 ob :=
begin
apply is_trunc_succ_intro, intro a b,
fapply is_trunc_is_equiv_closed,
exact (@eq_of_iso _ _ a b),
apply is_equiv_inv,
end
end basic
-- Bundled version of categories
-- we don't use Category.carrier explicitly, but rather use Precategory.carrier (to_Precategory C)
structure Category : Type :=
(carrier : Type)
(struct : category carrier)
attribute Category.struct [instance] [coercion]
definition Category.to_Precategory [constructor] [coercion] [reducible] (C : Category)
: Precategory :=
Precategory.mk (Category.carrier C) _
definition category.Mk [constructor] [reducible] := Category.mk
definition category.MK [constructor] [reducible] (C : Precategory)
(H : is_univalent C) : Category := Category.mk C (category.mk C H)
definition Category.eta (C : Category) : Category.mk C C = C :=
Category.rec (λob c, idp) C
protected definition category.sigma_char.{u v} [constructor] (ob : Type)
: category.{u v} ob ≃ Σ(C : precategory.{u v} ob), is_univalent C :=
begin
fapply equiv.MK,
{ intro x, induction x, constructor, assumption},
{ intro y, induction y with y1 y2, induction y1, constructor, assumption},
{ intro y, induction y with y1 y2, induction y1, reflexivity},
{ intro x, induction x, reflexivity}
end
definition category_eq {ob : Type}
{C D : category ob}
(p : Π{a b}, @hom ob C a b = @hom ob D a b)
(q : Πa b c g f, cast p (@comp ob C a b c g f) = @comp ob D a b c (cast p g) (cast p f))
: C = D :=
begin
apply eq_of_fn_eq_fn !category.sigma_char,
fapply sigma_eq,
{ induction C, induction D, esimp, exact precategory_eq @p q},
{ unfold is_univalent, apply is_prop.elimo},
end
definition category_eq_of_equiv {ob : Type}
{C D : category ob}
(p : Π⦃a b⦄, @hom ob C a b ≃ @hom ob D a b)
(q : Π{a b c} g f, p (@comp ob C a b c g f) = @comp ob D a b c (p g) (p f))
: C = D :=
begin
fapply category_eq,
{ intro a b, exact ua !@p},
{ intros, refine !cast_ua ⬝ !q ⬝ _, unfold [category.to_precategory],
apply ap011 !@category.comp !cast_ua⁻¹ᵖ !cast_ua⁻¹ᵖ},
end
-- TODO: Category_eq[']
end category
|
a79010d2e501d6c1e77446afee799853c7650a65 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/group_theory/index.lean | 2d9fde97d06a97eaec6aba9b46b2f8b274bfbedd | [
"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 | 9,113 | lean | /-
Copyright (c) 2021 Thomas Browning. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning
-/
import group_theory.quotient_group
import set_theory.fincard
/-!
# Index of a Subgroup
In this file we define the index of a subgroup, and prove several divisibility properties.
Several theorems proved in this file are known as Lagrange's theorem.
## Main definitions
- `H.index` : the index of `H : subgroup G` as a natural number,
and returns 0 if the index is infinite.
- `H.relindex K` : the relative index of `H : subgroup G` in `K : subgroup G` as a natural number,
and returns 0 if the relative index is infinite.
# Main results
- `card_mul_index` : `nat.card H * H.index = nat.card G`
- `index_mul_card` : `H.index * fintype.card H = fintype.card G`
- `index_dvd_card` : `H.index ∣ fintype.card G`
- `index_eq_mul_of_le` : If `H ≤ K`, then `H.index = K.index * (H.subgroup_of K).index`
- `index_dvd_of_le` : If `H ≤ K`, then `K.index ∣ H.index`
- `relindex_mul_relindex` : `relindex` is multiplicative in towers
-/
namespace subgroup
open_locale cardinal
variables {G : Type*} [group G] (H K L : subgroup G)
/-- The index of a subgroup as a natural number, and returns 0 if the index is infinite. -/
@[to_additive "The index of a subgroup as a natural number,
and returns 0 if the index is infinite."]
noncomputable def index : ℕ :=
nat.card (G ⧸ H)
/-- The relative index of a subgroup as a natural number,
and returns 0 if the relative index is infinite. -/
@[to_additive "The relative index of a subgroup as a natural number,
and returns 0 if the relative index is infinite."]
noncomputable def relindex : ℕ :=
(H.subgroup_of K).index
@[to_additive] lemma index_comap_of_surjective {G' : Type*} [group G'] {f : G' →* G}
(hf : function.surjective f) : (H.comap f).index = H.index :=
begin
letI := quotient_group.left_rel H,
letI := quotient_group.left_rel (H.comap f),
have key : ∀ x y : G', setoid.r x y ↔ setoid.r (f x) (f y) :=
λ x y, iff_of_eq (congr_arg (∈ H) (by rw [f.map_mul, f.map_inv])),
refine cardinal.to_nat_congr (equiv.of_bijective (quotient.map' f (λ x y, (key x y).mp)) ⟨_, _⟩),
{ simp_rw [←quotient.eq'] at key,
refine quotient.ind' (λ x, _),
refine quotient.ind' (λ y, _),
exact (key x y).mpr },
{ refine quotient.ind' (λ x, _),
obtain ⟨y, hy⟩ := hf x,
exact ⟨y, (quotient.map'_mk' f _ y).trans (congr_arg quotient.mk' hy)⟩ },
end
@[to_additive] lemma index_comap {G' : Type*} [group G'] (f : G' →* G) :
(H.comap f).index = H.relindex f.range :=
eq.trans (congr_arg index (by refl))
((H.subgroup_of f.range).index_comap_of_surjective f.range_restrict_surjective)
variables {H K L}
@[to_additive] lemma relindex_mul_index (h : H ≤ K) : H.relindex K * K.index = H.index :=
((mul_comm _ _).trans (cardinal.to_nat_mul _ _).symm).trans
(congr_arg cardinal.to_nat (equiv.cardinal_eq (quotient_equiv_prod_of_le h))).symm
@[to_additive] lemma index_dvd_of_le (h : H ≤ K) : K.index ∣ H.index :=
dvd_of_mul_left_eq (H.relindex K) (relindex_mul_index h)
@[to_additive] lemma relindex_subgroup_of (hKL : K ≤ L) :
(H.subgroup_of L).relindex (K.subgroup_of L) = H.relindex K :=
((index_comap (H.subgroup_of L) (inclusion hKL)).trans (congr_arg _ (inclusion_range hKL))).symm
variables (H K L)
@[to_additive] lemma relindex_mul_relindex (hHK : H ≤ K) (hKL : K ≤ L) :
H.relindex K * K.relindex L = H.relindex L :=
begin
rw [←relindex_subgroup_of hKL],
exact relindex_mul_index (λ x hx, hHK hx),
end
lemma inf_relindex_right : (H ⊓ K).relindex K = H.relindex K :=
begin
rw [←subgroup_of_map_subtype, relindex, relindex, subgroup_of, comap_map_eq_self_of_injective],
exact subtype.coe_injective,
end
lemma inf_relindex_left : (H ⊓ K).relindex H = K.relindex H :=
by rw [inf_comm, inf_relindex_right]
lemma relindex_inf_mul_relindex : H.relindex (K ⊓ L) * K.relindex L = (H ⊓ K).relindex L :=
by rw [←inf_relindex_right H (K ⊓ L), ←inf_relindex_right K L, ←inf_relindex_right (H ⊓ K) L,
inf_assoc, relindex_mul_relindex (H ⊓ (K ⊓ L)) (K ⊓ L) L inf_le_right inf_le_right]
lemma inf_relindex_eq_relindex_sup [K.normal] : (H ⊓ K).relindex H = K.relindex (H ⊔ K) :=
cardinal.to_nat_congr (quotient_group.quotient_inf_equiv_prod_normal_quotient H K).to_equiv
lemma relindex_eq_relindex_sup [K.normal] : K.relindex H = K.relindex (H ⊔ K) :=
by rw [←inf_relindex_left, inf_relindex_eq_relindex_sup]
variables {H K}
lemma relindex_dvd_of_le_left (hHK : H ≤ K) :
K.relindex L ∣ H.relindex L :=
begin
apply dvd_of_mul_left_eq ((H ⊓ L).relindex (K ⊓ L)),
rw [←inf_relindex_right H L, ←inf_relindex_right K L],
exact relindex_mul_relindex (H ⊓ L) (K ⊓ L) L (inf_le_inf_right L hHK) inf_le_right,
end
variables (H K)
@[simp, to_additive] lemma index_top : (⊤ : subgroup G).index = 1 :=
cardinal.to_nat_eq_one_iff_unique.mpr ⟨quotient_group.subsingleton_quotient_top, ⟨1⟩⟩
@[simp, to_additive] lemma index_bot : (⊥ : subgroup G).index = nat.card G :=
cardinal.to_nat_congr (quotient_group.quotient_bot.to_equiv)
@[to_additive] lemma index_bot_eq_card [fintype G] : (⊥ : subgroup G).index = fintype.card G :=
index_bot.trans nat.card_eq_fintype_card
@[simp, to_additive] lemma relindex_top_left : (⊤ : subgroup G).relindex H = 1 :=
index_top
@[simp, to_additive] lemma relindex_top_right : H.relindex ⊤ = H.index :=
by rw [←relindex_mul_index (show H ≤ ⊤, from le_top), index_top, mul_one]
@[simp, to_additive] lemma relindex_bot_left : (⊥ : subgroup G).relindex H = nat.card H :=
by rw [relindex, bot_subgroup_of, index_bot]
@[to_additive] lemma relindex_bot_left_eq_card [fintype H] :
(⊥ : subgroup G).relindex H = fintype.card H :=
H.relindex_bot_left.trans nat.card_eq_fintype_card
@[simp, to_additive] lemma relindex_bot_right : H.relindex ⊥ = 1 :=
by rw [relindex, subgroup_of_bot_eq_top, index_top]
@[simp, to_additive] lemma relindex_self : H.relindex H = 1 :=
by rw [relindex, subgroup_of_self, index_top]
@[simp, to_additive card_mul_index]
lemma card_mul_index : nat.card H * H.index = nat.card G :=
by { rw [←relindex_bot_left, ←index_bot], exact relindex_mul_index bot_le }
@[to_additive] lemma index_map {G' : Type*} [group G'] (f : G →* G') :
(H.map f).index = (H ⊔ f.ker).index * f.range.index :=
by rw [←comap_map_eq, index_comap, relindex_mul_index (H.map_le_range f)]
@[to_additive] lemma index_map_dvd {G' : Type*} [group G'] {f : G →* G'}
(hf : function.surjective f) : (H.map f).index ∣ H.index :=
begin
rw [index_map, f.range_top_of_surjective hf, index_top, mul_one],
exact index_dvd_of_le le_sup_left,
end
@[to_additive] lemma dvd_index_map {G' : Type*} [group G'] {f : G →* G'}
(hf : f.ker ≤ H) : H.index ∣ (H.map f).index :=
begin
rw [index_map, sup_of_le_left hf],
apply dvd_mul_right,
end
@[to_additive] lemma index_map_eq {G' : Type*} [group G'] {f : G →* G'}
(hf1 : function.surjective f) (hf2 : f.ker ≤ H) : (H.map f).index = H.index :=
nat.dvd_antisymm (H.index_map_dvd hf1) (H.dvd_index_map hf2)
@[to_additive] lemma index_eq_card [fintype (G ⧸ H)] :
H.index = fintype.card (G ⧸ H) :=
nat.card_eq_fintype_card
@[to_additive index_mul_card] lemma index_mul_card [fintype G] [hH : fintype H] :
H.index * fintype.card H = fintype.card G :=
by rw [←relindex_bot_left_eq_card, ←index_bot_eq_card, mul_comm]; exact relindex_mul_index bot_le
@[to_additive] lemma index_dvd_card [fintype G] : H.index ∣ fintype.card G :=
begin
classical,
exact ⟨fintype.card H, H.index_mul_card.symm⟩,
end
variables {H K L}
lemma relindex_eq_zero_of_le_left (hHK : H ≤ K) (hKL : K.relindex L = 0) : H.relindex L = 0 :=
by rw [←inf_relindex_right, ←relindex_mul_relindex (H ⊓ L) (K ⊓ L) L
(inf_le_inf_right L hHK) inf_le_right, inf_relindex_right, hKL, mul_zero]
lemma relindex_eq_zero_of_le_right (hKL : K ≤ L) (hHK : H.relindex K = 0) : H.relindex L = 0 :=
cardinal.to_nat_apply_of_omega_le (le_trans (le_of_not_lt (λ h, cardinal.mk_ne_zero _
((cardinal.cast_to_nat_of_lt_omega h).symm.trans (cardinal.nat_cast_inj.mpr hHK))))
(quotient_subgroup_of_embedding_of_le H hKL).cardinal_le)
lemma relindex_ne_zero_trans (hHK : H.relindex K ≠ 0) (hKL : K.relindex L ≠ 0) :
H.relindex L ≠ 0 :=
λ h, mul_ne_zero (mt (relindex_eq_zero_of_le_right (show K ⊓ L ≤ K, from inf_le_left)) hHK) hKL
((relindex_inf_mul_relindex H K L).trans (relindex_eq_zero_of_le_left inf_le_left h))
@[simp] lemma index_eq_one : H.index = 1 ↔ H = ⊤ :=
⟨λ h, quotient_group.subgroup_eq_top_of_subsingleton H (cardinal.to_nat_eq_one_iff_unique.mp h).1,
λ h, (congr_arg index h).trans index_top⟩
lemma index_ne_zero_of_fintype [hH : fintype (G ⧸ H)] : H.index ≠ 0 :=
by { rw index_eq_card, exact fintype.card_ne_zero }
lemma one_lt_index_of_ne_top [fintype (G ⧸ H)] (hH : H ≠ ⊤) : 1 < H.index :=
nat.one_lt_iff_ne_zero_and_ne_one.mpr ⟨index_ne_zero_of_fintype, mt index_eq_one.mp hH⟩
end subgroup
|
8a9bbc4b100221c2d587c2c1131beacbe6c2ef21 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /test/compute_degree.lean | 495ed2537c49ed6ebc8f0260bc43f22be50384ef | [
"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 | 2,647 | lean | import tactic.compute_degree
open polynomial
open_locale polynomial
variables {R : Type*} [semiring R] {a b c d e : R}
example {p : R[X]} {n : ℕ} {p0 : p.nat_degree = 0} :
(p ^ n).nat_degree ≤ 0 :=
by compute_degree_le
example {p : R[X]} {n : ℕ} {p0 : p.nat_degree = 0} :
(p ^ n).nat_degree ≤ 0 :=
by cases n; compute_degree_le
example {p q r : R[X]} {a b c d e f m n : ℕ} {p0 : p.nat_degree = a} {q0 : q.nat_degree = b}
{r0 : r.nat_degree = c} :
(((q ^ e * p ^ d) ^ m * r ^ f) ^ n).nat_degree ≤ ((b * e + a * d) * m + c * f) * n :=
begin
compute_degree_le,
rw [p0, q0, r0],
end
example {F} [ring F] {p : F[X]} (p0 : p.nat_degree ≤ 0) :
p.nat_degree ≤ 0 :=
begin
success_if_fail_with_msg {compute_degree_le} "Goal did not change",
exact p0,
end
example {F} [ring F] {p q : F[X]} (h : p.nat_degree + 1 ≤ q.nat_degree) :
(- p * X).nat_degree ≤ q.nat_degree :=
by compute_degree_le
example {F} [ring F] {a : F} {n : ℕ} (h : n ≤ 10) :
nat_degree (X ^ n - C a * X ^ 10 : F[X]) ≤ 10 :=
by compute_degree_le
example {F} [ring F] {a : F} {n : ℕ} (h : n ≤ 10) :
nat_degree (X ^ n + C a * X ^ 10 : F[X]) ≤ 10 :=
by compute_degree_le
example (n : ℕ) (h : 1 + n < 11) :
degree (5 * X ^ n + (X * monomial n 1 + X * X) + C a + C a * X ^ 10) ≤ 10 :=
begin
compute_degree_le,
{ exact nat.lt_succ_iff.mp h },
{ exact nat.lt_succ_iff.mp ((lt_one_add n).trans h) },
end
example {n : ℕ} (h : 1 + n < 11) :
degree (X + (X * monomial 2 1 + X * X) ^ 2) ≤ 10 :=
by compute_degree_le
example {m s: ℕ} (ms : m ≤ s) (s1 : 1 ≤ s) : nat_degree (C a * X ^ m + X + 5) ≤ s :=
by compute_degree_le; assumption
example : nat_degree (7 * X : R[X]) ≤ 1 :=
by compute_degree_le
example : (1 : polynomial R).nat_degree ≤ 0 :=
by compute_degree_le
example : nat_degree (monomial 5 c * monomial 1 c + monomial 7 d +
C a * X ^ 0 + C b * X ^ 5 + C c * X ^ 2 + X ^ 10 + C e * X) ≤ 10 :=
by compute_degree_le
example {n : ℕ} : nat_degree (0 * (X ^ 0 + X ^ n) * monomial 5 c * monomial 6 c) ≤ 9 :=
begin
success_if_fail_with_msg {compute_degree_le}
"the given polynomial has a term of expected degree
at least '11'",
rw [zero_mul, zero_mul, zero_mul, nat_degree_zero],
exact nat.zero_le _
end
example : nat_degree (monomial 0 c * (monomial 0 c * C 1) + monomial 0 d + C 1 + C a * X ^ 0) ≤ 0 :=
by compute_degree_le
example {F} [ring F] {n m : ℕ} (n4 : n ≤ 4) (m4 : m ≤ 4) {a : F} :
nat_degree (C a * X ^ n + X ^ m + bit1 1 : F[X]) ≤ 4 :=
by compute_degree_le; assumption
example {F} [ring F] : nat_degree (X ^ 4 + bit1 1 : F[X]) ≤ 4 :=
by compute_degree_le
|
e5e6630b8b97539c429ea680fe2d19b5853d5ea2 | 0179bcdbf094a112437450a02dc2bdc8b2f921d4 | /meta_data.lean | a20ad29db3286ab74b32e9af17d2ef530c0073f1 | [
"CC-BY-4.0"
] | permissive | haselwarter/formalabstracts | cf0c129fc086526cef1bd65d95c6f95a9a7ec5c8 | eab6d94850308df9f09d23f3a9a2f7b5ac5c6c7a | refs/heads/master | 1,609,515,992,248 | 1,500,418,815,000 | 1,500,418,815,000 | 97,696,544 | 0 | 0 | null | 1,500,455,350,000 | 1,500,455,350,000 | null | UTF-8 | Lean | false | false | 5,346 | lean | /- Each fabstract contains a list of results. The following type lists the
various kinds of results. You may read the values as follows:
* `Proof p` -- the paper contains the proof `p`
* `Construction c` -- the paper contains the construction `c`
* `Conjecture C` -- the paper contains the conjecture `C`
Let us take a typical situation: you want to state that the paper
contains a proof of some statement `S`, but you do not want to actually
formalize the proof from the paper. In this case the fabstract would
contain
definition S := ⟨formalization of statement S⟩
unfinished proof_of_S : S :=
{ description := "… describe the proof …",
cite := […] }
⋮
definition fabstract : meta_data := {
…,
results = […, Proof proof_of_S, …]
}
This way, by using `#print axioms fabstract`, you can find out precisely
which bits of the paper have not been formalized in the fabstract. You
can see what `proof_of_S` actually proves by inspecting its type.
Let us take another typical situation: the paper contains a construction
of an object `c` whose type is `T`, which is easy to formalize in Lean.
Then you would do
definition T := ⟨formalization of type T⟩
definition c := ⟨formalization of construction c⟩
⋮
definition fabstract : meta_data := {
…,
results = […, Construction c, …]
}
-/
inductive {u} result : Type (u+1)
| Proof : Π {P : Prop}, P → result
| Construction : Π {A : Type u}, A → result
| Conjecture : Prop → result
/- There will be many citations everywhere, so it is a good idea
to introduce a datatype for them early on. Here are some typical
uses case:
* DOI "10.1000/123456" -- Digital Object Identifier https://doi.org/10.1000/123456
* Arxiv "1234.56789" -- ArXiV entry https://arxiv.org/abs/1234.56789
* URL "…" -- any Uniform Resource Locator
* Reference "…" -- string description of an article, as done traditionally by journals
* Ibidem -- use this if you refer to the primary fabstract source itself
* Item X E -- refer to entry Ein source X, for instance:
* Item (Arxiv "1234.56789") "Theorem 3.4" -- theorem 3.4 in ArXiV 1234.56789
* Item Ibidem "Definition 1.2" -- definition 1.2 in the primary fabstract source
Use your programming skills! For instance, suppose you refer a lot to entries in
Reference "Euclid N.N., Elements (five volumes), 300 B.C., Elsevier"
Then you need not keep writing things like
Item (Reference "Euclid N.N., Elements (five volumes), 300 B.C., Elsevier") "Proposition IV.2"
Item (Reference "Euclid N.N., Elements (five volumes), 300 B.C., Elsevier") "Proposition I.1"
…
Instead, define a shorthand:
definition Elements x :=
Item (Reference "Euclid N.N., Elements (five volumes), 300 B.C., Elsevier") x
and then it is easy:
Elements "IV.2"
Elements "I.1"
-/
inductive cite
| DOI : string → cite -- write evertying starting from the DOI prefix (which is 10)
| Arxiv : string → cite -- write these as Arxiv "1707.04448"
| URL : string → cite
| Reference : string → cite
| Ibidem : cite -- refer to the primary source of a fabstract
| Item : cite → string → cite -- refer to specific item in a source
/-
TODO: This definition forces all the results in a particular fabstract
to lie in the same universe.
Each formal abstract contains an instance of the meta_data structure,
describing the contents. We insist that there be a primary source, since
giving multiple equivalent sources (say a journal paper and the ArXiv version)
makes it impossible to resolve conflicts when they arise. The primary source
is always to be taken as the official one.
-/
structure {u} meta_data : Type (u+1) :=
(description : string) -- short description of the contents
(authors : list string) -- list of authors
(primary : cite) -- primary source (the most official one)
(secondary : list cite) -- auxiliary and alternative sources (such as ArXiv equivalent)
(results : list (result.{u})) -- the list of results
/-
Users will want to assume that a certain objects exist,
without constructing them. These objects could be types (e.g. the
real numbers) or inhabitants of types (e.g. pi : ℝ). When we add
constants like this, we tag them with informal descriptions
(of what the structure is, or how the construction goes)
and references to the literature.
-/
structure unfinished_meta_data :=
(description : string)
(references : list cite := [])
section user_commands
open lean.parser tactic interactive
meta def add_unfinished (nm : name) (tp data : expr ff) : command :=
do eltp ← to_expr tp,
eldt ← to_expr ``(%%data : unfinished_meta_data),
let axm := declaration.ax nm [] eltp,
add_decl axm,
let meta_data_name := nm.append `_meta_data,
add_decl $ mk_definition meta_data_name []
`(unfinished_meta_data) eldt
@[user_command]
meta def unfinished_cmd (meta_info : decl_meta_info) (_ : parse $ tk "unfinished") : lean.parser unit :=
do nm ← ident,
tk ":",
tp ← lean.parser.pexpr 0,
tk ":=",
struct ← lean.parser.pexpr,
add_unfinished nm tp struct
end user_commands
|
c29552703a09d2425d0896cf018d1bc529f33178 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/quadratic_discriminant.lean | 8b13bcb92b84687f8cc10695154ddf113358973a | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 5,771 | lean | /-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import algebra.char_p.invertible
import order.filter.at_top_bot
import tactic.linarith
import tactic.field_simp
import tactic.linear_combination
/-!
# Quadratic discriminants and roots of a quadratic
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the discriminant of a quadratic and gives the solution to a quadratic equation.
## Main definition
- `discrim a b c`: the discriminant of a quadratic `a * x * x + b * x + c` is `b * b - 4 * a * c`.
## Main statements
- `quadratic_eq_zero_iff`: roots of a quadratic can be written as
`(-b + s) / (2 * a)` or `(-b - s) / (2 * a)`, where `s` is a square root of the discriminant.
- `quadratic_ne_zero_of_discrim_ne_sq`: if the discriminant has no square root,
then the corresponding quadratic has no root.
- `discrim_le_zero`: if a quadratic is always non-negative, then its discriminant is non-positive.
- `discrim_le_zero_of_nonpos`, `discrim_lt_zero`, `discrim_lt_zero_of_neg`: versions of this
statement with other inequalities.
## Tags
polynomial, quadratic, discriminant, root
-/
open filter
section ring
variables {R : Type*}
/-- Discriminant of a quadratic -/
def discrim [ring R] (a b c : R) : R := b^2 - 4 * a * c
@[simp] lemma discrim_neg [ring R] (a b c : R) : discrim (-a) (-b) (-c) = discrim a b c :=
by simp [discrim]
variables [comm_ring R] {a b c : R}
lemma discrim_eq_sq_of_quadratic_eq_zero {x : R} (h : a * x * x + b * x + c = 0) :
discrim a b c = (2 * a * x + b) ^ 2 :=
begin
rw [discrim],
linear_combination -4 * a * h
end
/--
A quadratic has roots if and only if its discriminant equals some square.
-/
lemma quadratic_eq_zero_iff_discrim_eq_sq [ne_zero (2 : R)] [no_zero_divisors R]
(ha : a ≠ 0) {x : R} :
a * x * x + b * x + c = 0 ↔ discrim a b c = (2 * a * x + b) ^ 2 :=
begin
refine ⟨discrim_eq_sq_of_quadratic_eq_zero, λ h, _⟩,
rw [discrim] at h,
have ha : 2 * 2 * a ≠ 0 := mul_ne_zero (mul_ne_zero (ne_zero.ne _) (ne_zero.ne _)) ha,
apply mul_left_cancel₀ ha,
linear_combination -h
end
/-- A quadratic has no root if its discriminant has no square root. -/
lemma quadratic_ne_zero_of_discrim_ne_sq (h : ∀ s : R, discrim a b c ≠ s^2) (x : R) :
a * x * x + b * x + c ≠ 0 :=
mt discrim_eq_sq_of_quadratic_eq_zero $ h _
end ring
section field
variables {K : Type*} [field K] [ne_zero (2 : K)] {a b c x : K}
/-- Roots of a quadratic equation. -/
lemma quadratic_eq_zero_iff (ha : a ≠ 0) {s : K} (h : discrim a b c = s * s) (x : K) :
a * x * x + b * x + c = 0 ↔ x = (-b + s) / (2 * a) ∨ x = (-b - s) / (2 * a) :=
begin
rw [quadratic_eq_zero_iff_discrim_eq_sq ha, h, sq, mul_self_eq_mul_self_iff],
field_simp,
apply or_congr,
{ split; intro h'; linear_combination -h' },
{ split; intro h'; linear_combination h' },
end
/-- A quadratic has roots if its discriminant has square roots -/
lemma exists_quadratic_eq_zero (ha : a ≠ 0) (h : ∃ s, discrim a b c = s * s) :
∃ x, a * x * x + b * x + c = 0 :=
begin
rcases h with ⟨s, hs⟩,
use (-b + s) / (2 * a),
rw quadratic_eq_zero_iff ha hs,
simp
end
/-- Root of a quadratic when its discriminant equals zero -/
lemma quadratic_eq_zero_iff_of_discrim_eq_zero (ha : a ≠ 0) (h : discrim a b c = 0) (x : K) :
a * x * x + b * x + c = 0 ↔ x = -b / (2 * a) :=
begin
have : discrim a b c = 0 * 0, by rw [h, mul_zero],
rw [quadratic_eq_zero_iff ha this, add_zero, sub_zero, or_self]
end
end field
section linear_ordered_field
variables {K : Type*} [linear_ordered_field K] {a b c : K}
/-- If a polynomial of degree 2 is always nonnegative, then its discriminant is nonpositive. -/
lemma discrim_le_zero (h : ∀ x : K, 0 ≤ a * x * x + b * x + c) : discrim a b c ≤ 0 :=
begin
rw [discrim, sq],
obtain ha|rfl|ha : a < 0 ∨ a = 0 ∨ 0 < a := lt_trichotomy a 0,
-- if a < 0
{ have : tendsto (λ x, (a * x + b) * x + c) at_top at_bot :=
tendsto_at_bot_add_const_right _ c ((tendsto_at_bot_add_const_right _ b
(tendsto_id.neg_const_mul_at_top ha)).at_bot_mul_at_top tendsto_id),
rcases (this.eventually (eventually_lt_at_bot 0)).exists with ⟨x, hx⟩,
exact false.elim ((h x).not_lt $ by rwa ← add_mul) },
-- if a = 0
{ rcases eq_or_ne b 0 with (rfl|hb),
{ simp },
{ have := h ((-c - 1) / b), rw [mul_div_cancel' _ hb] at this, linarith } },
-- if a > 0
{ have ha' : 0 ≤ 4 * a := mul_nonneg zero_le_four ha.le,
have := h (-b / (2 * a)),
convert neg_nonpos.2 (mul_nonneg ha' (h (-b / (2 * a)))),
field_simp [ha.ne'],
ring }
end
lemma discrim_le_zero_of_nonpos (h : ∀ x : K, a * x * x + b * x + c ≤ 0) : discrim a b c ≤ 0 :=
discrim_neg a b c ▸ discrim_le_zero (by simpa only [neg_mul, ← neg_add, neg_nonneg])
/--
If a polynomial of degree 2 is always positive, then its discriminant is negative,
at least when the coefficient of the quadratic term is nonzero.
-/
lemma discrim_lt_zero (ha : a ≠ 0) (h : ∀ x : K, 0 < a * x * x + b * x + c) : discrim a b c < 0 :=
begin
have : ∀ x : K, 0 ≤ a*x*x + b*x + c := assume x, le_of_lt (h x),
refine lt_of_le_of_ne (discrim_le_zero this) _,
assume h',
have := h (-b / (2 * a)),
have : a * (-b / (2 * a)) * (-b / (2 * a)) + b * (-b / (2 * a)) + c = 0,
{ rw [quadratic_eq_zero_iff_of_discrim_eq_zero ha h' (-b / (2 * a))] },
linarith
end
lemma discrim_lt_zero_of_neg (ha : a ≠ 0) (h : ∀ x : K, a * x * x + b * x + c < 0) :
discrim a b c < 0 :=
discrim_neg a b c ▸ discrim_lt_zero (neg_ne_zero.2 ha) (by simpa only [neg_mul, ← neg_add, neg_pos])
end linear_ordered_field
|
183e75160717a00e3f75dfb406dd26a18342d981 | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/topology/metric_space/basic.lean | f0b72b504d8241d9a15636a471f58651ee93ccfc | [
"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 | 103,835 | lean | /-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
-/
import data.int.interval
import topology.algebra.ordered.compact
import topology.metric_space.emetric_space
/-!
# Metric spaces
This file defines metric spaces. Many definitions and theorems expected
on metric spaces are already introduced on uniform spaces and topological spaces.
For example: open and closed sets, compactness, completeness, continuity and uniform continuity
## Main definitions
* `has_dist α`: Endows a space `α` with a function `dist a b`.
* `pseudo_metric_space α`: A space endowed with a distance function, which can
be zero even if the two elements are non-equal.
* `metric.ball x ε`: The set of all points `y` with `dist y x < ε`.
* `metric.bounded s`: Whether a subset of a `pseudo_metric_space` is bounded.
* `metric_space α`: A `pseudo_metric_space` with the guarantee `dist x y = 0 → x = y`.
Additional useful definitions:
* `nndist a b`: `dist` as a function to the non-negative reals.
* `metric.closed_ball x ε`: The set of all points `y` with `dist y x ≤ ε`.
* `metric.sphere x ε`: The set of all points `y` with `dist y x = ε`.
* `proper_space α`: A `pseudo_metric_space` where all closed balls are compact.
* `metric.diam s` : The `supr` of the distances of members of `s`.
Defined in terms of `emetric.diam`, for better handling of the case when it should be infinite.
TODO (anyone): Add "Main results" section.
## Implementation notes
Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the
theory of `pseudo_metric_space`, where we don't require `dist x y = 0 → x = y` and we specialize
to `metric_space` at the end.
## Tags
metric, pseudo_metric, dist
-/
open set filter topological_space
open_locale uniformity topological_space big_operators filter nnreal ennreal
universes u v w
variables {α : Type u} {β : Type v}
/-- Construct a uniform structure core from a distance function and metric space axioms.
This is a technical construction that can be immediately used to construct a uniform structure
from a distance function and metric space axioms but is also useful when discussing
metrizable topologies, see `pseudo_metric_space.of_metrizable`. -/
def uniform_space.core_of_dist {α : Type*} (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space.core α :=
{ uniformity := (⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε}),
refl := le_infi $ assume ε, le_infi $
by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt},
comp := le_infi $ assume ε, le_infi $ assume h, lift'_le
(mem_infi_of_mem (ε / 2) $ mem_infi_of_mem (div_pos h zero_lt_two) (subset.refl _)) $
have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε,
from assume a b c hac hcb,
calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _
... < ε / 2 + ε / 2 : add_lt_add hac hcb
... = ε : by rw [div_add_div_same, add_self_div_two],
by simpa [comp_rel],
symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h,
tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] }
/-- Construct a uniform structure from a distance function and metric space axioms -/
def uniform_space_of_dist
(dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α :=
uniform_space.of_core (uniform_space.core_of_dist dist dist_self dist_comm dist_triangle)
/-- The distance function (given an ambient metric space on `α`), which returns
a nonnegative real number `dist x y` given `x y : α`. -/
class has_dist (α : Type*) := (dist : α → α → ℝ)
export has_dist (dist)
-- the uniform structure and the emetric space structure are embedded in the metric space structure
-- to avoid instance diamond issues. See Note [forgetful inheritance].
/-- This is an internal lemma used inside the default of `pseudo_metric_space.edist`. -/
private theorem pseudo_metric_space.dist_nonneg' {α} {x y : α} (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z): 0 ≤ dist x y :=
have 2 * dist x y ≥ 0,
from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul]
... ≥ 0 : by rw ← dist_self x; apply dist_triangle,
nonneg_of_mul_nonneg_left this zero_lt_two
/-- This tactic is used to populate `pseudo_metric_space.edist_dist` when the default `edist` is
used. -/
protected meta def pseudo_metric_space.edist_dist_tac : tactic unit :=
tactic.intros >> `[exact (ennreal.of_real_eq_coe_nnreal _).symm <|> control_laws_tac]
/-- Metric space
Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`.
This is enforced in the type class definition, by extending the `uniform_space` structure. When
instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be
filled in by default. In the same way, each metric space induces an emetric space structure.
It is included in the structure, but filled in by default.
-/
class pseudo_metric_space (α : Type u) extends has_dist α : Type u :=
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(edist : α → α → ℝ≥0∞ := λ x y,
@coe (ℝ≥0) _ _ ⟨dist x y, pseudo_metric_space.dist_nonneg' _ ‹_› ‹_› ‹_›⟩)
(edist_dist : ∀ x y : α,
edist x y = ennreal.of_real (dist x y) . pseudo_metric_space.edist_dist_tac)
(to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle)
(uniformity_dist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε} . control_laws_tac)
variables [pseudo_metric_space α]
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_uniform_space' : uniform_space α :=
pseudo_metric_space.to_uniform_space
@[priority 200] -- see Note [lower instance priority]
instance pseudo_metric_space.to_has_edist : has_edist α := ⟨pseudo_metric_space.edist⟩
/-- Construct a pseudo-metric space structure whose underlying topological space structure
(definitionally) agrees which a pre-existing topology which is compatible with a given distance
function. -/
def pseudo_metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) :
pseudo_metric_space α :=
{ dist := dist,
dist_self := dist_self,
dist_comm := dist_comm,
dist_triangle := dist_triangle,
to_uniform_space := { is_open_uniformity := begin
dsimp only [uniform_space.core_of_dist],
intros s,
change is_open s ↔ _,
rw H s,
apply forall_congr, intro x,
apply forall_congr, intro x_in,
erw (has_basis_binfi_principal _ nonempty_Ioi).mem_iff,
{ apply exists_congr, intros ε,
apply exists_congr, intros ε_pos,
simp only [prod.forall, set_of_subset_set_of],
split,
{ rintros h _ y H rfl,
exact h y H },
{ intros h y hxy,
exact h _ _ hxy rfl } },
{ exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp,
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p),
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩ },
{ apply_instance }
end,
..uniform_space.core_of_dist dist dist_self dist_comm dist_triangle },
uniformity_dist := rfl }
@[simp] theorem dist_self (x : α) : dist x x = 0 := pseudo_metric_space.dist_self x
theorem dist_comm (x y : α) : dist x y = dist y x := pseudo_metric_space.dist_comm x y
theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) :=
pseudo_metric_space.edist_dist x y
theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z :=
pseudo_metric_space.dist_triangle x y z
theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y :=
by rw dist_comm z; apply dist_triangle
theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z :=
by rw dist_comm y; apply dist_triangle
lemma dist_triangle4 (x y z w : α) :
dist x w ≤ dist x y + dist y z + dist z w :=
calc dist x w ≤ dist x z + dist z w : dist_triangle x z w
... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (dist_triangle x y z) _
lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) :
dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) :=
by { rw [add_left_comm, dist_comm x₁, ← add_assoc], apply dist_triangle4 }
lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) :
dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ :=
by { rw [add_right_comm, dist_comm y₁], apply dist_triangle4 }
/-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/
lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) :
dist (f m) (f n) ≤ ∑ i in finset.Ico m n, dist (f i) (f (i + 1)) :=
begin
revert n,
apply nat.le_induction,
{ simp only [finset.sum_empty, finset.Ico_self, dist_self] },
{ assume n hn hrec,
calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _
... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _)
... = ∑ i in finset.Ico m (n+1), _ :
by rw [nat.Ico_succ_right_eq_insert_Ico hn, finset.sum_insert, add_comm]; simp }
end
/-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/
lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) :
dist (f 0) (f n) ≤ ∑ i in finset.range n, dist (f i) (f (i + 1)) :=
nat.Ico_zero_eq_range n ▸ dist_le_Ico_sum_dist f (nat.zero_le n)
/-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n)
{d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i :=
le_trans (dist_le_Ico_sum_dist f hmn) $
finset.sum_le_sum $ λ k hk, hd (finset.mem_Ico.1 hk).1 (finset.mem_Ico.1 hk).2
/-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ)
{d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f 0) (f n) ≤ ∑ i in finset.range n, d i :=
nat.Ico_zero_eq_range n ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd)
theorem swap_dist : function.swap (@dist α _) = dist :=
by funext x y; exact dist_comm _ _
theorem abs_dist_sub_le (x y z : α) : |dist x z - dist y z| ≤ dist x y :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add.2 (dist_triangle _ _ _),
sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩
theorem dist_nonneg {x y : α} : 0 ≤ dist x y :=
pseudo_metric_space.dist_nonneg' dist dist_self dist_comm dist_triangle
@[simp] theorem abs_dist {a b : α} : |dist a b| = dist a b :=
abs_of_nonneg dist_nonneg
/-- A version of `has_dist` that takes value in `ℝ≥0`. -/
class has_nndist (α : Type*) := (nndist : α → α → ℝ≥0)
export has_nndist (nndist)
/-- Distance as a nonnegative real number. -/
@[priority 100] -- see Note [lower instance priority]
instance pseudo_metric_space.to_has_nndist : has_nndist α := ⟨λ a b, ⟨dist a b, dist_nonneg⟩⟩
/--Express `nndist` in terms of `edist`-/
lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal :=
by simp [nndist, edist_dist, real.to_nnreal, max_eq_left dist_nonneg, ennreal.of_real]
/--Express `edist` in terms of `nndist`-/
lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) :=
by { simpa only [edist_dist, ennreal.of_real_eq_coe_nnreal dist_nonneg] }
@[simp, norm_cast] lemma coe_nnreal_ennreal_nndist (x y : α) : ↑(nndist x y) = edist x y :=
(edist_nndist x y).symm
@[simp, norm_cast] lemma edist_lt_coe {x y : α} {c : ℝ≥0} :
edist x y < c ↔ nndist x y < c :=
by rw [edist_nndist, ennreal.coe_lt_coe]
@[simp, norm_cast] lemma edist_le_coe {x y : α} {c : ℝ≥0} :
edist x y ≤ c ↔ nndist x y ≤ c :=
by rw [edist_nndist, ennreal.coe_le_coe]
/--In a pseudometric space, the extended distance is always finite-/
lemma edist_lt_top {α : Type*} [pseudo_metric_space α] (x y : α) : edist x y < ⊤ :=
(edist_dist x y).symm ▸ ennreal.of_real_lt_top
/--In a pseudometric space, the extended distance is always finite-/
lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := (edist_lt_top x y).ne
/--`nndist x x` vanishes-/
@[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a)
/--Express `dist` in terms of `nndist`-/
lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl
@[simp, norm_cast] lemma coe_nndist (x y : α) : ↑(nndist x y) = dist x y :=
(dist_nndist x y).symm
@[simp, norm_cast] lemma dist_lt_coe {x y : α} {c : ℝ≥0} :
dist x y < c ↔ nndist x y < c :=
iff.rfl
@[simp, norm_cast] lemma dist_le_coe {x y : α} {c : ℝ≥0} :
dist x y ≤ c ↔ nndist x y ≤ c :=
iff.rfl
/--Express `nndist` in terms of `dist`-/
lemma nndist_dist (x y : α) : nndist x y = real.to_nnreal (dist x y) :=
by rw [dist_nndist, real.to_nnreal_coe]
theorem nndist_comm (x y : α) : nndist x y = nndist y x :=
by simpa only [dist_nndist, nnreal.coe_eq] using dist_comm x y
/--Triangle inequality for the nonnegative distance-/
theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z :=
dist_triangle _ _ _
theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y :=
dist_triangle_left _ _ _
theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z :=
dist_triangle_right _ _ _
/--Express `dist` in terms of `edist`-/
lemma dist_edist (x y : α) : dist x y = (edist x y).to_real :=
by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)]
namespace metric
/- instantiate pseudometric space as a topology -/
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
/-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/
def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε}
@[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl
theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl
theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε :=
dist_nonneg.trans_lt hy
theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε :=
show dist x x < ε, by rw dist_self; assumption
@[simp] lemma nonempty_ball : (ball x ε).nonempty ↔ 0 < ε :=
⟨λ ⟨x, hx⟩, pos_of_mem_ball hx, λ h, ⟨x, mem_ball_self h⟩⟩
@[simp] lemma ball_eq_empty : ball x ε = ∅ ↔ ε ≤ 0 :=
by rw [← not_nonempty_iff_eq_empty, nonempty_ball, not_lt]
@[simp] lemma ball_zero : ball x 0 = ∅ :=
by rw [ball_eq_empty]
lemma ball_eq_ball (ε : ℝ) (x : α) :
uniform_space.ball x {p | dist p.2 p.1 < ε} = metric.ball x ε := rfl
lemma ball_eq_ball' (ε : ℝ) (x : α) :
uniform_space.ball x {p | dist p.1 p.2 < ε} = metric.ball x ε :=
by { ext, simp [dist_comm, uniform_space.ball] }
@[simp] lemma Union_ball_nat (x : α) : (⋃ n : ℕ, ball x n) = univ :=
Union_eq_univ_iff.2 $ λ y, exists_nat_gt (dist y x)
@[simp] lemma Union_ball_nat_succ (x : α) : (⋃ n : ℕ, ball x (n + 1)) = univ :=
Union_eq_univ_iff.2 $ λ y, (exists_nat_gt (dist y x)).imp $ λ n hn,
hn.trans (lt_add_one _)
/-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/
def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε}
@[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl
/-- `sphere x ε` is the set of all points `y` with `dist y x = ε` -/
def sphere (x : α) (ε : ℝ) := {y | dist y x = ε}
@[simp] theorem mem_sphere : y ∈ sphere x ε ↔ dist y x = ε := iff.rfl
theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ dist x y ≤ ε :=
by { rw dist_comm, refl }
theorem mem_closed_ball_self (h : 0 ≤ ε) : x ∈ closed_ball x ε :=
show dist x x ≤ ε, by rw dist_self; assumption
@[simp] lemma nonempty_closed_ball : (closed_ball x ε).nonempty ↔ 0 ≤ ε :=
⟨λ ⟨x, hx⟩, dist_nonneg.trans hx, λ h, ⟨x, mem_closed_ball_self h⟩⟩
@[simp] lemma closed_ball_eq_empty : closed_ball x ε = ∅ ↔ ε < 0 :=
by rw [← not_nonempty_iff_eq_empty, nonempty_closed_ball, not_le]
theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε :=
assume y (hy : _ < _), le_of_lt hy
theorem sphere_subset_closed_ball : sphere x ε ⊆ closed_ball x ε :=
λ y, le_of_eq
lemma ball_disjoint_ball (x y : α) (rx ry : ℝ) (h : rx + ry ≤ dist x y) :
disjoint (ball x rx) (ball y ry) :=
begin
rw disjoint_left,
assume a ax ay,
apply lt_irrefl (dist x y),
calc dist x y ≤ dist x a + dist a y : dist_triangle _ _ _
... < rx + ry : add_lt_add (mem_ball'.1 ax) (mem_ball.1 ay)
... ≤ dist x y : h
end
theorem sphere_disjoint_ball : disjoint (sphere x ε) (ball x ε) :=
λ y ⟨hy₁, hy₂⟩, absurd hy₁ $ ne_of_lt hy₂
@[simp] theorem ball_union_sphere : ball x ε ∪ sphere x ε = closed_ball x ε :=
set.ext $ λ y, (@le_iff_lt_or_eq ℝ _ _ _).symm
@[simp] theorem sphere_union_ball : sphere x ε ∪ ball x ε = closed_ball x ε :=
by rw [union_comm, ball_union_sphere]
@[simp] theorem closed_ball_diff_sphere : closed_ball x ε \ sphere x ε = ball x ε :=
by rw [← ball_union_sphere, set.union_diff_cancel_right sphere_disjoint_ball.symm]
@[simp] theorem closed_ball_diff_ball : closed_ball x ε \ ball x ε = sphere x ε :=
by rw [← ball_union_sphere, set.union_diff_cancel_left sphere_disjoint_ball.symm]
theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε :=
by simp [dist_comm]
theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ :=
λ y (yx : _ < ε₁), lt_of_lt_of_le yx h
lemma ball_subset_ball' (h : ε₁ + dist x y ≤ ε₂) : ball x ε₁ ⊆ ball y ε₂ :=
λ z hz, calc
dist z y ≤ dist z x + dist x y : dist_triangle _ _ _
... < ε₁ + dist x y : add_lt_add_right hz _
... ≤ ε₂ : h
theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball x ε₂ :=
λ y (yx : _ ≤ ε₁), le_trans yx h
lemma closed_ball_subset_closed_ball' (h : ε₁ + dist x y ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball y ε₂ :=
λ z hz, calc
dist z y ≤ dist z x + dist x y : dist_triangle _ _ _
... ≤ ε₁ + dist x y : add_le_add_right hz _
... ≤ ε₂ : h
theorem closed_ball_subset_ball (h : ε₁ < ε₂) :
closed_ball x ε₁ ⊆ ball x ε₂ :=
λ y (yh : dist y x ≤ ε₁), lt_of_le_of_lt yh h
lemma dist_le_add_of_nonempty_closed_ball_inter_closed_ball
(h : (closed_ball x ε₁ ∩ closed_ball y ε₂).nonempty) :
dist x y ≤ ε₁ + ε₂ :=
let ⟨z, hz⟩ := h in calc
dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _
... ≤ ε₁ + ε₂ : add_le_add hz.1 hz.2
lemma dist_lt_add_of_nonempty_closed_ball_inter_ball (h : (closed_ball x ε₁ ∩ ball y ε₂).nonempty) :
dist x y < ε₁ + ε₂ :=
let ⟨z, hz⟩ := h in calc
dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _
... < ε₁ + ε₂ : add_lt_add_of_le_of_lt hz.1 hz.2
lemma dist_lt_add_of_nonempty_ball_inter_closed_ball (h : (ball x ε₁ ∩ closed_ball y ε₂).nonempty) :
dist x y < ε₁ + ε₂ :=
begin
rw inter_comm at h,
rw [add_comm, dist_comm],
exact dist_lt_add_of_nonempty_closed_ball_inter_ball h
end
lemma dist_lt_add_of_nonempty_ball_inter_ball (h : (ball x ε₁ ∩ ball y ε₂).nonempty) :
dist x y < ε₁ + ε₂ :=
dist_lt_add_of_nonempty_closed_ball_inter_ball $
h.mono (inter_subset_inter ball_subset_closed_ball subset.rfl)
@[simp] lemma Union_closed_ball_nat (x : α) : (⋃ n : ℕ, closed_ball x n) = univ :=
Union_eq_univ_iff.2 $ λ y, exists_nat_ge (dist y x)
theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩,
not_lt_of_le (dist_triangle_left x y z)
(lt_of_lt_of_le (add_lt_add h₁ h₂) h)
theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ :=
ball_disjoint $ by rwa [← two_mul, ← le_div_iff' (@zero_lt_two ℝ _ _)]
theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ :=
λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact
lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h)
theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε :=
ball_subset $ by rw sub_self_div_two; exact le_of_lt h
theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε :=
⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩
theorem uniformity_basis_dist :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) :=
begin
rw ← pseudo_metric_space.uniformity_dist.symm,
refine has_basis_binfi_principal _ nonempty_Ioi,
exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp,
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p),
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩
end
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`.
For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`,
and `uniformity_basis_dist_inv_nat_pos`. -/
protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) :
(𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀,
exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ }
end
theorem uniformity_basis_dist_inv_nat_succ :
(𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) :=
metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n)
(λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩)
theorem uniformity_basis_dist_inv_nat_pos :
(𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) :=
metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn)
(λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n, hn.le⟩)
theorem uniformity_basis_dist_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < r ^ n }) :=
metric.mk_uniformity_basis (λ n hn, pow_pos h0 _)
(λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩)
theorem uniformity_basis_dist_lt {R : ℝ} (hR : 0 < R) :
(𝓤 α).has_basis (λ r : ℝ, 0 < r ∧ r < R) (λ r, {p : α × α | dist p.1 p.2 < r}) :=
metric.mk_uniformity_basis (λ r, and.left) $ λ r hr,
⟨min r (R / 2), ⟨lt_min hr (half_pos hR), min_lt_iff.2 $ or.inr (half_lt_self hR)⟩,
min_le_left _ _⟩
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}`
form a basis of `𝓤 α`.
Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor.
More can be easily added if needed in the future. -/
protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) :
(𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
rcases exists_between ε₀ with ⟨ε', hε'⟩,
rcases hf ε' hε'.1 with ⟨i, hi, H⟩,
exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ }
end
/-- Contant size closed neighborhoods of the diagonal form a basis
of the uniformity filter. -/
theorem uniformity_basis_dist_le :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) :=
metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩)
theorem uniformity_basis_dist_le_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 ≤ r ^ n }) :=
metric.mk_uniformity_basis_le (λ n hn, pow_pos h0 _)
(λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩)
theorem mem_uniformity_dist {s : set (α×α)} :
s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) :=
uniformity_basis_dist.mem_uniformity_iff
/-- A constant size neighborhood of the diagonal is an entourage. -/
theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) :
{p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α :=
mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩
theorem uniform_continuous_iff [pseudo_metric_space β] {f : α → β} :
uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε :=
uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist
lemma uniform_continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} :
uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y < δ → dist (f x) (f y) < ε :=
metric.uniformity_basis_dist.uniform_continuous_on_iff metric.uniformity_basis_dist
lemma uniform_continuous_on_iff_le [pseudo_metric_space β] {f : α → β} {s : set α} :
uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y ≤ δ → dist (f x) (f y) ≤ ε :=
metric.uniformity_basis_dist_le.uniform_continuous_on_iff metric.uniformity_basis_dist_le
theorem uniform_embedding_iff [pseudo_metric_space β] {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ :=
uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl
⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0),
⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in
⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩,
λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in
⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩
/-- If a map between pseudometric spaces is a uniform embedding then the distance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y`. -/
theorem controlled_of_uniform_embedding [pseudo_metric_space β] {f : α → β} :
uniform_embedding f →
(∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) :=
begin
assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩
end
theorem totally_bounded_iff {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, H _ (dist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru,
⟨t, ft, h⟩ := H ε ε0 in
⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩
/-- A pseudometric space is totally bounded if one can reconstruct up to any ε>0 any element of the
space from finitely many data. -/
lemma totally_bounded_of_finite_discretization {s : set α}
(H : ∀ε > (0 : ℝ), ∃ (β : Type u) (_ : fintype β) (F : s → β),
∀x y, F x = F y → dist (x:α) y < ε) :
totally_bounded s :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw hs, exact totally_bounded_empty },
rcases hs with ⟨x0, hx0⟩,
haveI : inhabited s := ⟨⟨x0, hx0⟩⟩,
refine totally_bounded_iff.2 (λ ε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
resetI,
let Finv := function.inv_fun F,
refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩,
let x' := Finv (F ⟨x, xs⟩),
have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩,
simp only [set.mem_Union, set.mem_range],
exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩
end
theorem finite_approx_of_totally_bounded {s : set α} (hs : totally_bounded s) :
∀ ε > 0, ∃ t ⊆ s, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
begin
intros ε ε_pos,
rw totally_bounded_iff_subset at hs,
exact hs _ (dist_mem_uniformity ε_pos),
end
/-- Expressing locally uniform convergence on a set using `dist`. -/
lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_locally_uniformly_on F f p s ↔
∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
rcases H ε εpos x hx with ⟨t, ht, Ht⟩,
exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩
end
/-- Expressing uniform convergence on a set using `dist`. -/
lemma tendsto_uniformly_on_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx))
end
/-- Expressing locally uniform convergence using `dist`. -/
lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_locally_uniformly F f p ↔
∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff,
nhds_within_univ, mem_univ, forall_const, exists_prop]
/-- Expressing uniform convergence using `dist`. -/
lemma tendsto_uniformly_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε :=
by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp }
protected lemma cauchy_iff {f : filter α} :
cauchy f ↔ ne_bot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε :=
uniformity_basis_dist.cauchy_iff
theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) :=
nhds_basis_uniformity uniformity_basis_dist
theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s :=
nhds_basis_ball.mem_iff
theorem eventually_nhds_iff {p : α → Prop} :
(∀ᶠ y in 𝓝 x, p y) ↔ ∃ε>0, ∀ ⦃y⦄, dist y x < ε → p y :=
mem_nhds_iff
lemma eventually_nhds_iff_ball {p : α → Prop} :
(∀ᶠ y in 𝓝 x, p y) ↔ ∃ ε>0, ∀ y ∈ ball x ε, p y :=
mem_nhds_iff
theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) :=
nhds_basis_uniformity uniformity_basis_dist_le
theorem nhds_basis_ball_inv_nat_succ :
(𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ
theorem nhds_basis_ball_inv_nat_pos :
(𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos
theorem nhds_basis_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓝 x).has_basis (λ n, true) (λ n:ℕ, ball x (r ^ n)) :=
nhds_basis_uniformity (uniformity_basis_dist_pow h0 h1)
theorem nhds_basis_closed_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓝 x).has_basis (λ n, true) (λ n:ℕ, closed_ball x (r ^ n)) :=
nhds_basis_uniformity (uniformity_basis_dist_le_pow h0 h1)
theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s :=
by simp only [is_open_iff_mem_nhds, mem_nhds_iff]
theorem is_open_ball : is_open (ball x ε) :=
is_open_iff.2 $ λ y, exists_ball_subset_ball
theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x :=
is_open.mem_nhds is_open_ball (mem_ball_self ε0)
theorem closed_ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x :=
mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball
theorem nhds_within_basis_ball {s : set α} :
(𝓝[s] x).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) :=
nhds_within_has_basis nhds_basis_ball s
theorem mem_nhds_within_iff {t : set α} : s ∈ 𝓝[t] x ↔ ∃ε>0, ball x ε ∩ t ⊆ s :=
nhds_within_basis_ball.mem_iff
theorem tendsto_nhds_within_nhds_within [pseudo_metric_space β] {t : set β} {f : α → β} {a b} :
tendsto f (𝓝[s] a) (𝓝[t] b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε :=
(nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $
by simp only [inter_comm, mem_inter_iff, and_imp, mem_ball]
theorem tendsto_nhds_within_nhds [pseudo_metric_space β] {f : α → β} {a b} :
tendsto f (𝓝[s] a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε :=
by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within],
simp only [mem_univ, true_and] }
theorem tendsto_nhds_nhds [pseudo_metric_space β] {f : α → β} {a b} :
tendsto f (𝓝 a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε :=
nhds_basis_ball.tendsto_iff nhds_basis_ball
theorem continuous_at_iff [pseudo_metric_space β] {f : α → β} {a : α} :
continuous_at f a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_at, tendsto_nhds_nhds]
theorem continuous_within_at_iff [pseudo_metric_space β] {f : α → β} {a : α} {s : set α} :
continuous_within_at f s a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_within_at, tendsto_nhds_within_nhds]
theorem continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff]
theorem continuous_iff [pseudo_metric_space β] {f : α → β} :
continuous f ↔
∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds
theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε :=
nhds_basis_ball.tendsto_right_iff
theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔
∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε :=
by rw [continuous_at, tendsto_nhds]
theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔
∀ ε > 0, ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε :=
by rw [continuous_within_at, tendsto_nhds]
theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff']
theorem continuous_iff' [topological_space β] {f : β → α} :
continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds
theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε :=
(at_top_basis.tendsto_iff nhds_basis_ball).trans $
by { simp only [exists_prop, true_and], refl }
/--
A variant of `tendsto_at_top` that
uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...`
-/
theorem tendsto_at_top' [nonempty β] [semilattice_sup β] [no_top_order β] {u : β → α} {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n>N, dist (u n) a < ε :=
(at_top_basis_Ioi.tendsto_iff nhds_basis_ball).trans $
by { simp only [exists_prop, true_and], refl }
lemma is_open_singleton_iff {α : Type*} [pseudo_metric_space α] {x : α} :
is_open ({x} : set α) ↔ ∃ ε > 0, ∀ y, dist y x < ε → y = x :=
by simp [is_open_iff, subset_singleton_iff, mem_ball]
/-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is an open ball
centered at `x` and intersecting `s` only at `x`. -/
lemma exists_ball_inter_eq_singleton_of_mem_discrete [discrete_topology s] {x : α} (hx : x ∈ s) :
∃ ε > 0, metric.ball x ε ∩ s = {x} :=
nhds_basis_ball.exists_inter_eq_singleton_of_mem_discrete hx
/-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is a closed ball
of positive radius centered at `x` and intersecting `s` only at `x`. -/
lemma exists_closed_ball_inter_eq_singleton_of_discrete [discrete_topology s] {x : α} (hx : x ∈ s) :
∃ ε > 0, metric.closed_ball x ε ∩ s = {x} :=
nhds_basis_closed_ball.exists_inter_eq_singleton_of_mem_discrete hx
end metric
open metric
/-Instantiate a pseudometric space as a pseudoemetric space. Before we can state the instance,
we need to show that the uniform structure coming from the edistance and the
distance coincide. -/
/-- Expressing the uniformity in terms of `edist` -/
protected lemma pseudo_metric.uniformity_basis_edist :
(𝓤 α).has_basis (λ ε:ℝ≥0∞, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) :=
⟨begin
intro t,
refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩,
{ use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0],
rintros ⟨a, b⟩,
simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0],
exact Hε },
{ rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩,
rw [ennreal.of_real_pos] at ε0',
refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩,
rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] }
end⟩
theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}) :=
pseudo_metric.uniformity_basis_edist.eq_binfi
/-- A pseudometric space induces a pseudoemetric space -/
@[priority 100] -- see Note [lower instance priority]
instance pseudo_metric_space.to_pseudo_emetric_space : pseudo_emetric_space α :=
{ edist := edist,
edist_self := by simp [edist_dist],
edist_comm := by simp only [edist_dist, dist_comm]; simp,
edist_triangle := assume x y z, begin
simp only [edist_dist, ← ennreal.of_real_add, dist_nonneg],
rw ennreal.of_real_le_of_real_iff _,
{ exact dist_triangle _ _ _ },
{ simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg }
end,
uniformity_edist := metric.uniformity_edist,
..‹pseudo_metric_space α› }
/-- In a pseudometric space, an open ball of infinite radius is the whole space -/
lemma metric.eball_top_eq_univ (x : α) :
emetric.ball x ∞ = set.univ :=
set.eq_univ_iff_forall.mpr (λ y, edist_lt_top y x)
/-- Balls defined using the distance or the edistance coincide -/
@[simp] lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε :=
begin
ext y,
simp only [emetric.mem_ball, mem_ball, edist_dist],
exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg
end
/-- Balls defined using the distance or the edistance coincide -/
@[simp] lemma metric.emetric_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.ball x ε = ball x ε :=
by { convert metric.emetric_ball, simp }
/-- Closed balls defined using the distance or the edistance coincide -/
lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) :
emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε :=
by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h
/-- Closed balls defined using the distance or the edistance coincide -/
@[simp] lemma metric.emetric_closed_ball_nnreal {x : α} {ε : ℝ≥0} :
emetric.closed_ball x ε = closed_ball x ε :=
by { convert metric.emetric_closed_ball ε.2, simp }
@[simp] lemma metric.emetric_ball_top (x : α) : emetric.ball x ⊤ = univ :=
eq_univ_of_forall $ λ y, edist_lt_top _ _
/-- Build a new pseudometric space from an old one where the bundled uniform structure is provably
(but typically non-definitionaly) equal to some given uniform structure.
See Note [forgetful inheritance].
-/
def pseudo_metric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_metric_space α)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space') :
pseudo_metric_space α :=
{ dist := @dist _ m.to_has_dist,
dist_self := dist_self,
dist_comm := dist_comm,
dist_triangle := dist_triangle,
edist := edist,
edist_dist := edist_dist,
to_uniform_space := U,
uniformity_dist := H.trans pseudo_metric_space.uniformity_dist }
/-- One gets a pseudometric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the pseudometric space and the pseudoemetric space. In this definition, the
distance is given separately, to be able to prescribe some expression which is not defeq to the
push-forward of the edistance to reals. -/
def pseudo_emetric_space.to_pseudo_metric_space_of_dist {α : Type u} [e : pseudo_emetric_space α]
(dist : α → α → ℝ)
(edist_ne_top : ∀x y: α, edist x y ≠ ⊤)
(h : ∀x y, dist x y = ennreal.to_real (edist x y)) :
pseudo_metric_space α :=
let m : pseudo_metric_space α :=
{ dist := dist,
dist_self := λx, by simp [h],
dist_comm := λx y, by simp [h, pseudo_emetric_space.edist_comm],
dist_triangle := λx y z, begin
simp only [h],
rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _),
ennreal.to_real_le_to_real (edist_ne_top _ _)],
{ exact edist_triangle _ _ _ },
{ simp [ennreal.add_eq_top, edist_ne_top] }
end,
edist := λx y, edist x y,
edist_dist := λx y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in
m.replace_uniformity $ by { rw [uniformity_pseudoedist, metric.uniformity_edist], refl }
/-- One gets a pseudometric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the pseudometric space and the emetric space. -/
def pseudo_emetric_space.to_pseudo_metric_space {α : Type u} [e : pseudo_emetric_space α]
(h : ∀x y: α, edist x y ≠ ⊤) : pseudo_metric_space α :=
pseudo_emetric_space.to_pseudo_metric_space_of_dist
(λx y, ennreal.to_real (edist x y)) h (λx y, rfl)
/-- A very useful criterion to show that a space is complete is to show that all sequences
which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are
converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to
`0`, which makes it possible to use arguments of converging series, while this is impossible
to do in general for arbitrary Cauchy sequences. -/
theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n)
(H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) →
∃x, tendsto u at_top (𝓝 x)) :
complete_space α :=
begin
-- this follows from the same criterion in emetric spaces. We just need to translate
-- the convergence assumption from `dist` to `edist`
apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)),
{ simp [hB] },
{ assume u Hu,
apply H,
assume N n m hn hm,
rw [← ennreal.of_real_lt_of_real_iff (hB N), ← edist_dist],
exact Hu N n m hn hm }
end
theorem metric.complete_of_cauchy_seq_tendsto :
(∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α :=
emetric.complete_of_cauchy_seq_tendsto
section real
/-- Instantiate the reals as a pseudometric space. -/
noncomputable instance real.pseudo_metric_space : pseudo_metric_space ℝ :=
{ dist := λx y, |x - y|,
dist_self := by simp [abs_zero],
dist_comm := assume x y, abs_sub_comm _ _,
dist_triangle := assume x y z, abs_sub_le _ _ _ }
theorem real.dist_eq (x y : ℝ) : dist x y = |x - y| := rfl
theorem real.nndist_eq (x y : ℝ) : nndist x y = real.nnabs (x - y) := rfl
theorem real.nndist_eq' (x y : ℝ) : nndist x y = real.nnabs (y - x) := nndist_comm _ _
theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = |x| :=
by simp [real.dist_eq]
theorem real.dist_left_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) :
dist x y ≤ dist x z :=
by simpa only [dist_comm x] using abs_sub_left_of_mem_interval h
theorem real.dist_right_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) :
dist y z ≤ dist x z :=
by simpa only [dist_comm _ z] using abs_sub_right_of_mem_interval h
theorem real.dist_le_of_mem_interval {x y x' y' : ℝ} (hx : x ∈ interval x' y')
(hy : y ∈ interval x' y') : dist x y ≤ dist x' y' :=
abs_sub_le_of_subinterval $ interval_subset_interval (by rwa interval_swap) (by rwa interval_swap)
theorem real.dist_le_of_mem_Icc {x y x' y' : ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') :
dist x y ≤ y' - x' :=
by simpa only [real.dist_eq, abs_of_nonpos (sub_nonpos.2 $ hx.1.trans hx.2), neg_sub]
using real.dist_le_of_mem_interval (Icc_subset_interval hx) (Icc_subset_interval hy)
theorem real.dist_le_of_mem_Icc_01 {x y : ℝ} (hx : x ∈ Icc (0:ℝ) 1) (hy : y ∈ Icc (0:ℝ) 1) :
dist x y ≤ 1 :=
by simpa only [sub_zero] using real.dist_le_of_mem_Icc hx hy
instance : order_topology ℝ :=
order_topology_of_nhds_abs $ λ x,
by simp only [nhds_basis_ball.eq_binfi, ball, real.dist_eq, abs_sub_comm]
lemma real.ball_eq (x r : ℝ) : ball x r = Ioo (x - r) (x + r) :=
set.ext $ λ y, by rw [mem_ball, dist_comm, real.dist_eq,
abs_sub_lt_iff, mem_Ioo, ← sub_lt_iff_lt_add', sub_lt]
lemma real.closed_ball_eq {x r : ℝ} : closed_ball x r = Icc (x - r) (x + r) :=
by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq,
abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le]
section metric_ordered
variables [conditionally_complete_linear_order α] [order_topology α]
lemma totally_bounded_Icc (a b : α) : totally_bounded (Icc a b) :=
is_compact_Icc.totally_bounded
lemma totally_bounded_Ico (a b : α) : totally_bounded (Ico a b) :=
totally_bounded_subset Ico_subset_Icc_self (totally_bounded_Icc a b)
lemma totally_bounded_Ioc (a b : α) : totally_bounded (Ioc a b) :=
totally_bounded_subset Ioc_subset_Icc_self (totally_bounded_Icc a b)
lemma totally_bounded_Ioo (a b : α) : totally_bounded (Ioo a b) :=
totally_bounded_subset Ioo_subset_Icc_self (totally_bounded_Icc a b)
end metric_ordered
/-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the
general case. -/
lemma squeeze_zero' {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀ᶠ t in t₀, 0 ≤ f t)
(hft : ∀ᶠ t in t₀, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (𝓝 0) :=
tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds g0 hf hft
/-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le`
and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/
lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t)
(g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) :=
squeeze_zero' (eventually_of_forall hf) (eventually_of_forall hft) g0
theorem metric.uniformity_eq_comap_nhds_zero :
𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) :=
by { ext s,
simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] }
lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) :=
by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff,
prod.map_def]
lemma tendsto_uniformity_iff_dist_tendsto_zero {ι : Type*} {f : ι → α × α} {p : filter ι} :
tendsto f p (𝓤 α) ↔ tendsto (λ x, dist (f x).1 (f x).2) p (𝓝 0) :=
by rw [metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff]
lemma filter.tendsto.congr_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α}
(h₁ : tendsto f₁ p (𝓝 a)) (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) :
tendsto f₂ p (𝓝 a) :=
h₁.congr_uniformity $ tendsto_uniformity_iff_dist_tendsto_zero.2 h
alias filter.tendsto.congr_dist ← tendsto_of_tendsto_of_dist
lemma tendsto_iff_of_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α}
(h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) :
tendsto f₁ p (𝓝 a) ↔ tendsto f₂ p (𝓝 a) :=
uniform.tendsto_congr $ tendsto_uniformity_iff_dist_tendsto_zero.2 h
end real
section cauchy_seq
variables [nonempty β] [semilattice_sup β]
/-- In a pseudometric space, Cauchy sequences are characterized by the fact that, eventually,
the distance between its elements is arbitrarily small -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem metric.cauchy_seq_iff {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε :=
uniformity_basis_dist.cauchy_seq_iff
/-- A variation around the pseudometric characterization of Cauchy sequences -/
theorem metric.cauchy_seq_iff' {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε :=
uniformity_basis_dist.cauchy_seq_iff'
/-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N`
and `b` converges to zero, then `s` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ)
(h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (nhds 0)) :
cauchy_seq s :=
metric.cauchy_seq_iff.2 $ λ ε ε0,
(metric.tendsto_at_top.1 h₀ ε ε0).imp $ λ N hN m n hm hn,
calc dist (s m) (s n) ≤ b N : h m n N hm hn
... ≤ |b N| : le_abs_self _
... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl
... < ε : (hN _ (le_refl N))
/-- A Cauchy sequence on the natural numbers is bounded. -/
theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) :
∃ R > 0, ∀ m n, dist (u m) (u n) < R :=
begin
rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩,
suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R,
{ rcases this with ⟨R, R0, H⟩,
exact ⟨_, add_pos R0 R0, λ m n,
lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ },
let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)),
refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩,
cases le_or_lt N n,
{ exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) },
{ have : _ ≤ R := finset.le_sup (finset.mem_range.2 h),
exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) }
end
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ,
(∀ n, 0 ≤ b n) ∧
(∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧
tendsto b at_top (𝓝 0) :=
⟨λ hs, begin
/- `s` is a 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`.
First, we prove that all these distances are bounded, as otherwise the Sup
would not make sense. -/
let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N},
have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x,
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩,
exact le_of_lt (hR m n) },
have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))),
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) },
-- Prove that it bounds the distances of points in the Cauchy sequence
have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ Sup (S N) :=
λ m n N hm hn, le_cSup (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩,
have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩,
have S0 := λ n, le_cSup (hS n) (S0m n),
-- Prove that it tends to `0`, by using the Cauchy property of `s`
refine ⟨λ N, Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩,
refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _),
rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)],
refine lt_of_le_of_lt (cSup_le ⟨_, S0m _⟩ _) (half_lt_self ε0),
rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩,
exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn'))
end,
λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩
end cauchy_seq
/-- Pseudometric space structure pulled back by a function. -/
def pseudo_metric_space.induced {α β} (f : α → β)
(m : pseudo_metric_space β) : pseudo_metric_space α :=
{ dist := λ x y, dist (f x) (f y),
dist_self := λ x, dist_self _,
dist_comm := λ x y, dist_comm _ _,
dist_triangle := λ x y z, dist_triangle _ _ _,
edist := λ x y, edist (f x) (f y),
edist_dist := λ x y, edist_dist _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_dist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)),
refine λ s, mem_comap.trans _,
split; intro H,
{ rcases H with ⟨r, ru, rs⟩,
rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩,
refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h },
{ rcases H with ⟨ε, ε0, hε⟩,
exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ }
end }
/-- Pull back a pseudometric space structure by a uniform inducing map. This is a version of
`pseudo_metric_space.induced` useful in case if the domain already has a `uniform_space`
structure. -/
def uniform_inducing.comap_pseudo_metric_space {α β} [uniform_space α] [pseudo_metric_space β]
(f : α → β) (h : uniform_inducing f) : pseudo_metric_space α :=
(pseudo_metric_space.induced f ‹_›).replace_uniformity h.comap_uniformity.symm
instance subtype.psudo_metric_space {α : Type*} {p : α → Prop} [t : pseudo_metric_space α] :
pseudo_metric_space (subtype p) :=
pseudo_metric_space.induced coe t
theorem subtype.pseudo_dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl
section nnreal
noncomputable instance : pseudo_metric_space ℝ≥0 := by unfold nnreal; apply_instance
lemma nnreal.dist_eq (a b : ℝ≥0) : dist a b = |(a:ℝ) - b| := rfl
lemma nnreal.nndist_eq (a b : ℝ≥0) :
nndist a b = max (a - b) (b - a) :=
begin
wlog h : a ≤ b,
{ apply nnreal.coe_eq.1,
rw [tsub_eq_zero_iff_le.2 h, max_eq_right (zero_le $ b - a), ← dist_nndist, nnreal.dist_eq,
nnreal.coe_sub h, abs_eq_max_neg, neg_sub],
apply max_eq_right,
linarith [nnreal.coe_le_coe.2 h] },
rwa [nndist_comm, max_comm]
end
end nnreal
section prod
noncomputable instance prod.pseudo_metric_space_max [pseudo_metric_space β] :
pseudo_metric_space (α × β) :=
{ dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2),
dist_self := λ x, by simp,
dist_comm := λ x y, by simp [dist_comm],
dist_triangle := λ x y z, max_le
(le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _)))
(le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))),
edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2),
edist_dist := assume x y, begin
have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h,
rw [edist_dist, edist_dist, ← this.map_max]
end,
uniformity_dist := begin
refine uniformity_prod.trans _,
simp only [uniformity_basis_dist.eq_binfi, comap_infi],
rw ← infi_inf_eq, congr, funext,
rw ← infi_inf_eq, congr, funext,
simp [inf_principal, ext_iff, max_lt_iff]
end,
to_uniform_space := prod.uniform_space }
lemma prod.dist_eq [pseudo_metric_space β] {x y : α × β} :
dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl
theorem ball_prod_same [pseudo_metric_space β] (x : α) (y : β) (r : ℝ) :
(ball x r).prod (ball y r) = ball (x, y) r :=
ext $ λ z, by simp [prod.dist_eq]
theorem closed_ball_prod_same [pseudo_metric_space β] (x : α) (y : β) (r : ℝ) :
(closed_ball x r).prod (closed_ball y r) = closed_ball (x, y) r :=
ext $ λ z, by simp [prod.dist_eq]
end prod
theorem uniform_continuous_dist : uniform_continuous (λp:α×α, dist p.1 p.2) :=
metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0,
begin
suffices,
{ intros p q h, cases p with p₁ p₂, cases q with q₁ q₂,
cases max_lt_iff.1 h with h₁ h₂, clear h,
dsimp at h₁ h₂ ⊢,
rw real.dist_eq,
refine abs_sub_lt_iff.2 ⟨_, _⟩,
{ revert p₁ p₂ q₁ q₂ h₁ h₂, exact this },
{ apply this; rwa dist_comm } },
intros p₁ p₂ q₁ q₂ h₁ h₂,
have := add_lt_add
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1,
rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this
end⟩)
theorem uniform_continuous.dist [uniform_space β] {f g : β → α}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
uniform_continuous (λb, dist (f b) (g b)) :=
uniform_continuous_dist.comp (hf.prod_mk hg)
@[continuity]
theorem continuous_dist : continuous (λp:α×α, dist p.1 p.2) :=
uniform_continuous_dist.continuous
@[continuity]
theorem continuous.dist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) :=
continuous_dist.comp (hf.prod_mk hg : _)
theorem filter.tendsto.dist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) :=
(continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a :=
by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero,
comap_comap, (∘), dist_comm]
lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} :
(tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) :=
by rw [← nhds_comap_dist a, tendsto_comap_iff]
lemma uniform_continuous_nndist : uniform_continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_subtype_mk uniform_continuous_dist _
lemma uniform_continuous.nndist [uniform_space β] {f g : β → α} (hf : uniform_continuous f)
(hg : uniform_continuous g) :
uniform_continuous (λ b, nndist (f b) (g b)) :=
uniform_continuous_nndist.comp (hf.prod_mk hg)
lemma continuous_nndist : continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_nndist.continuous
lemma continuous.nndist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) :=
continuous_nndist.comp (hf.prod_mk hg : _)
theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) :=
(continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
namespace metric
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
theorem is_closed_ball : is_closed (closed_ball x ε) :=
is_closed_le (continuous_id.dist continuous_const) continuous_const
lemma is_closed_sphere : is_closed (sphere x ε) :=
is_closed_eq (continuous_id.dist continuous_const) continuous_const
@[simp] theorem closure_closed_ball : closure (closed_ball x ε) = closed_ball x ε :=
is_closed_ball.closure_eq
theorem closure_ball_subset_closed_ball : closure (ball x ε) ⊆ closed_ball x ε :=
closure_minimal ball_subset_closed_ball is_closed_ball
theorem frontier_ball_subset_sphere : frontier (ball x ε) ⊆ sphere x ε :=
frontier_lt_subset_eq (continuous_id.dist continuous_const) continuous_const
theorem frontier_closed_ball_subset_sphere : frontier (closed_ball x ε) ⊆ sphere x ε :=
frontier_le_subset_eq (continuous_id.dist continuous_const) continuous_const
theorem ball_subset_interior_closed_ball : ball x ε ⊆ interior (closed_ball x ε) :=
interior_maximal ball_subset_closed_ball is_open_ball
/-- ε-characterization of the closure in pseudometric spaces-/
theorem mem_closure_iff {α : Type u} [pseudo_metric_space α] {s : set α} {a : α} :
a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
(mem_closure_iff_nhds_basis nhds_basis_ball).trans $
by simp only [mem_ball, dist_comm]
lemma mem_closure_range_iff {α : Type u} [pseudo_metric_space α] {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε :=
by simp only [mem_closure_iff, exists_range_iff]
lemma mem_closure_range_iff_nat {α : Type u} [pseudo_metric_space α] {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) :=
(mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $
by simp only [mem_ball, dist_comm, exists_range_iff, forall_const]
theorem mem_of_closed' {α : Type u} [pseudo_metric_space α] {s : set α} (hs : is_closed s)
{a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
by simpa only [hs.closure_eq] using @mem_closure_iff _ _ s a
end metric
section pi
open finset
variables {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)]
/-- A finite product of pseudometric spaces is a pseudometric space, with the sup distance. -/
noncomputable instance pseudo_metric_space_pi : pseudo_metric_space (Πb, π b) :=
begin
/- we construct the instance from the pseudoemetric space instance to avoid checking again that
the uniformity is the same as the product uniformity, but we register nevertheless a nice formula
for the distance -/
refine pseudo_emetric_space.to_pseudo_metric_space_of_dist
(λf g, ((sup univ (λb, nndist (f b) (g b)) : ℝ≥0) : ℝ)) _ _,
show ∀ (x y : Π (b : β), π b), edist x y ≠ ⊤,
{ assume x y,
rw ← lt_top_iff_ne_top,
have : (⊥ : ℝ≥0∞) < ⊤ := ennreal.coe_lt_top,
simp [edist_pi_def, finset.sup_lt_iff this, edist_lt_top] },
show ∀ (x y : Π (b : β), π b), ↑(sup univ (λ (b : β), nndist (x b) (y b))) =
ennreal.to_real (sup univ (λ (b : β), edist (x b) (y b))),
{ assume x y,
simp only [edist_nndist],
norm_cast }
end
lemma nndist_pi_def (f g : Πb, π b) : nndist f g = sup univ (λb, nndist (f b) (g b)) :=
subtype.eta _ _
lemma dist_pi_def (f g : Πb, π b) :
dist f g = (sup univ (λb, nndist (f b) (g b)) : ℝ≥0) := rfl
@[simp] lemma dist_pi_const [nonempty β] (a b : α) : dist (λ x : β, a) (λ _, b) = dist a b :=
by simpa only [dist_edist] using congr_arg ennreal.to_real (edist_pi_const a b)
@[simp] lemma nndist_pi_const [nonempty β] (a b : α) :
nndist (λ x : β, a) (λ _, b) = nndist a b := nnreal.eq $ dist_pi_const a b
lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) :
dist f g < r ↔ ∀b, dist (f b) (g b) < r :=
begin
lift r to ℝ≥0 using hr.le,
simp [dist_pi_def, finset.sup_lt_iff (show ⊥ < r, from hr)],
end
lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) :
dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r :=
begin
lift r to ℝ≥0 using hr,
simp [nndist_pi_def]
end
lemma nndist_le_pi_nndist (f g : Πb, π b) (b : β) : nndist (f b) (g b) ≤ nndist f g :=
by { rw [nndist_pi_def], exact finset.le_sup (finset.mem_univ b) }
lemma dist_le_pi_dist (f g : Πb, π b) (b : β) : dist (f b) (g b) ≤ dist f g :=
by simp only [dist_nndist, nnreal.coe_le_coe, nndist_le_pi_nndist f g b]
/-- An open ball in a product space is a product of open balls. See also `metric.ball_pi'`
for a version assuming `nonempty β` instead of `0 < r`. -/
lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) :
ball x r = set.pi univ (λ b, ball (x b) r) :=
by { ext p, simp [dist_pi_lt_iff hr] }
/-- An open ball in a product space is a product of open balls. See also `metric.ball_pi`
for a version assuming `0 < r` instead of `nonempty β`. -/
lemma ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) :
ball x r = set.pi univ (λ b, ball (x b) r) :=
(lt_or_le 0 r).elim (ball_pi x) $ λ hr, by simp [ball_eq_empty.2 hr]
/-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi'`
for a version assuming `nonempty β` instead of `0 ≤ r`. -/
lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) :
closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) :=
by { ext p, simp [dist_pi_le_iff hr] }
/-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi`
for a version assuming `0 ≤ r` instead of `nonempty β`. -/
lemma closed_ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) :
closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) :=
(le_or_lt 0 r).elim (closed_ball_pi x) $ λ hr, by simp [closed_ball_eq_empty.2 hr]
lemma real.dist_le_of_mem_pi_Icc {x y x' y' : β → ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') :
dist x y ≤ dist x' y' :=
begin
refine (dist_pi_le_iff dist_nonneg).2 (λ b, (real.dist_le_of_mem_interval _ _).trans
(dist_le_pi_dist _ _ b)); refine Icc_subset_interval _,
exacts [⟨hx.1 _, hx.2 _⟩, ⟨hy.1 _, hy.2 _⟩]
end
end pi
section compact
/-- Any compact set in a pseudometric space can be covered by finitely many balls of a given
positive radius -/
lemma finite_cover_balls_of_compact {α : Type u} [pseudo_metric_space α] {s : set α}
(hs : is_compact s) {e : ℝ} (he : 0 < e) :
∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e :=
begin
apply hs.elim_finite_subcover_image,
{ simp [is_open_ball] },
{ intros x xs,
simp,
exact ⟨x, ⟨xs, by simpa⟩⟩ }
end
alias finite_cover_balls_of_compact ← is_compact.finite_cover_balls
end compact
section proper_space
open metric
/-- A pseudometric space is proper if all closed balls are compact. -/
class proper_space (α : Type u) [pseudo_metric_space α] : Prop :=
(is_compact_closed_ball : ∀x:α, ∀r, is_compact (closed_ball x r))
/-- In a proper pseudometric space, all spheres are compact. -/
lemma is_compact_sphere {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) :
is_compact (sphere x r) :=
compact_of_is_closed_subset (proper_space.is_compact_closed_ball x r) is_closed_sphere
sphere_subset_closed_ball
/-- In a proper pseudometric space, any sphere is a `compact_space` when considered as a subtype. -/
instance {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) :
compact_space (sphere x r) :=
is_compact_iff_compact_space.mp (is_compact_sphere _ _)
/-- A proper pseudo metric space is sigma compact, and therefore second countable. -/
@[priority 100] -- see Note [lower instance priority]
instance second_countable_of_proper [proper_space α] :
second_countable_topology α :=
begin
-- We already have `sigma_compact_space_of_locally_compact_second_countable`, so we don't
-- add an instance for `sigma_compact_space`.
suffices : sigma_compact_space α, by exactI emetric.second_countable_of_sigma_compact α,
rcases em (nonempty α) with ⟨⟨x⟩⟩|hn,
{ exact ⟨⟨λ n, closed_ball x n, λ n, proper_space.is_compact_closed_ball _ _,
Union_closed_ball_nat _⟩⟩ },
{ exact ⟨⟨λ n, ∅, λ n, is_compact_empty, Union_eq_univ_iff.2 $ λ x, (hn ⟨x⟩).elim⟩⟩ }
end
lemma tendsto_dist_right_cocompact_at_top [proper_space α] (x : α) :
tendsto (λ y, dist y x) (cocompact α) at_top :=
(has_basis_cocompact.tendsto_iff at_top_basis).2 $ λ r hr,
⟨closed_ball x r, proper_space.is_compact_closed_ball x r,
λ y hy, (not_le.1 $ mt mem_closed_ball.2 hy).le⟩
lemma tendsto_dist_left_cocompact_at_top [proper_space α] (x : α) :
tendsto (dist x) (cocompact α) at_top :=
by simpa only [dist_comm] using tendsto_dist_right_cocompact_at_top x
/-- If all closed balls of large enough radius are compact, then the space is proper. Especially
useful when the lower bound for the radius is 0. -/
lemma proper_space_of_compact_closed_ball_of_le
(R : ℝ) (h : ∀x:α, ∀r, R ≤ r → is_compact (closed_ball x r)) :
proper_space α :=
⟨begin
assume x r,
by_cases hr : R ≤ r,
{ exact h x r hr },
{ have : closed_ball x r = closed_ball x R ∩ closed_ball x r,
{ symmetry,
apply inter_eq_self_of_subset_right,
exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) },
rw this,
exact (h x R (le_refl _)).inter_right is_closed_ball }
end⟩
/- A compact pseudometric space is proper -/
@[priority 100] -- see Note [lower instance priority]
instance proper_of_compact [compact_space α] : proper_space α :=
⟨assume x r, is_closed_ball.is_compact⟩
/-- A proper space is locally compact -/
@[priority 100] -- see Note [lower instance priority]
instance locally_compact_of_proper [proper_space α] :
locally_compact_space α :=
locally_compact_space_of_has_basis (λ x, nhds_basis_closed_ball) $
λ x ε ε0, proper_space.is_compact_closed_ball _ _
/-- A proper space is complete -/
@[priority 100] -- see Note [lower instance priority]
instance complete_of_proper [proper_space α] : complete_space α :=
⟨begin
intros f hf,
/- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed
ball (therefore compact by properness) where it is nontrivial. -/
obtain ⟨t, t_fset, ht⟩ : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 :=
(metric.cauchy_iff.1 hf).2 1 zero_lt_one,
rcases hf.1.nonempty_of_mem t_fset with ⟨x, xt⟩,
have : closed_ball x 1 ∈ f := mem_of_superset t_fset (λ y yt, (ht y x yt xt).le),
rcases (compact_iff_totally_bounded_complete.1 (proper_space.is_compact_closed_ball x 1)).2 f hf
(le_principal_iff.2 this) with ⟨y, -, hy⟩,
exact ⟨y, hy⟩
end⟩
/-- A finite product of proper spaces is proper. -/
instance pi_proper_space {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)]
[h : ∀b, proper_space (π b)] : proper_space (Πb, π b) :=
begin
refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _),
rw closed_ball_pi _ hr,
apply is_compact_univ_pi (λb, _),
apply (h b).is_compact_closed_ball
end
variables [proper_space α] {x : α} {r : ℝ} {s : set α}
/-- If a nonempty ball in a proper space includes a closed set `s`, then there exists a nonempty
ball with the same center and a strictly smaller radius that includes `s`. -/
lemma exists_pos_lt_subset_ball (hr : 0 < r) (hs : is_closed s) (h : s ⊆ ball x r) :
∃ r' ∈ Ioo 0 r, s ⊆ ball x r' :=
begin
unfreezingI { rcases eq_empty_or_nonempty s with rfl|hne },
{ exact ⟨r / 2, ⟨half_pos hr, half_lt_self hr⟩, empty_subset _⟩ },
have : is_compact s,
from compact_of_is_closed_subset (proper_space.is_compact_closed_ball x r) hs
(subset.trans h ball_subset_closed_ball),
obtain ⟨y, hys, hy⟩ : ∃ y ∈ s, s ⊆ closed_ball x (dist y x),
from this.exists_forall_ge hne (continuous_id.dist continuous_const).continuous_on,
have hyr : dist y x < r, from h hys,
rcases exists_between hyr with ⟨r', hyr', hrr'⟩,
exact ⟨r', ⟨dist_nonneg.trans_lt hyr', hrr'⟩, subset.trans hy $ closed_ball_subset_ball hyr'⟩
end
/-- If a ball in a proper space includes a closed set `s`, then there exists a ball with the same
center and a strictly smaller radius that includes `s`. -/
lemma exists_lt_subset_ball (hs : is_closed s) (h : s ⊆ ball x r) :
∃ r' < r, s ⊆ ball x r' :=
begin
cases le_or_lt r 0 with hr hr,
{ rw [ball_eq_empty.2 hr, subset_empty_iff] at h, unfreezingI { subst s },
exact (no_bot r).imp (λ r' hr', ⟨hr', empty_subset _⟩) },
{ exact (exists_pos_lt_subset_ball hr hs h).imp (λ r' hr', ⟨hr'.fst.2, hr'.snd⟩) }
end
end proper_space
namespace metric
section second_countable
open topological_space
/-- A pseudometric space is second countable if, for every `ε > 0`, there is a countable set which
is `ε`-dense. -/
lemma second_countable_of_almost_dense_set
(H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) :
second_countable_topology α :=
begin
refine emetric.second_countable_of_almost_dense_set (λ ε ε0, _),
rcases ennreal.lt_iff_exists_nnreal_btwn.1 ε0 with ⟨ε', ε'0, ε'ε⟩,
choose s hsc y hys hyx using H ε' (by exact_mod_cast ε'0),
refine ⟨s, hsc, bUnion_eq_univ_iff.2 (λ x, ⟨y x, hys _, le_trans _ ε'ε.le⟩)⟩,
exact_mod_cast hyx x
end
end second_countable
end metric
lemma lebesgue_number_lemma_of_metric
{s : set α} {ι} {c : ι → set α} (hs : is_compact s)
(hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i :=
let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂,
⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in
⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in
⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩
lemma lebesgue_number_lemma_of_metric_sUnion
{s : set α} {c : set (set α)} (hs : is_compact s)
(hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂
namespace metric
/-- Boundedness of a subset of a pseudometric space. We formulate the definition to work
even in the empty space. -/
def bounded (s : set α) : Prop :=
∃C, ∀x y ∈ s, dist x y ≤ C
section bounded
variables {x : α} {s t : set α} {r : ℝ}
@[simp] lemma bounded_empty : bounded (∅ : set α) :=
⟨0, by simp⟩
lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s :=
⟨λ h _ _, h, λ H,
s.eq_empty_or_nonempty.elim
(λ hs, hs.symm ▸ bounded_empty)
(λ ⟨x, hx⟩, H x hx)⟩
/-- Subsets of a bounded set are also bounded -/
lemma bounded.mono (incl : s ⊆ t) : bounded t → bounded s :=
Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy)
/-- Closed balls are bounded -/
lemma bounded_closed_ball : bounded (closed_ball x r) :=
⟨r + r, λ y z hy hz, begin
simp only [mem_closed_ball] at *,
calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add hy hz
end⟩
/-- Open balls are bounded -/
lemma bounded_ball : bounded (ball x r) :=
bounded_closed_ball.mono ball_subset_closed_ball
/-- Given a point, a bounded subset is included in some ball around this point -/
lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r :=
begin
split; rintro ⟨C, hC⟩,
{ cases s.eq_empty_or_nonempty with h h,
{ subst s, exact ⟨0, by simp⟩ },
{ rcases h with ⟨x, hx⟩,
exact ⟨C + dist x c, λ y hy, calc
dist y c ≤ dist y x + dist x c : dist_triangle _ _ _
... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } },
{ exact bounded_closed_ball.mono hC }
end
lemma bounded.subset_ball (h : bounded s) (c : α) : ∃ r, s ⊆ closed_ball c r :=
(bounded_iff_subset_ball c).1 h
lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) :=
let ⟨C, h⟩ := h in
⟨C, λ a b ha hb, (is_closed_le' C).closure_subset $ map_mem_closure2 continuous_dist ha hb h⟩
alias bounded_closure_of_bounded ← metric.bounded.closure
@[simp] lemma bounded_closure_iff : bounded (closure s) ↔ bounded s :=
⟨λ h, h.mono subset_closure, λ h, h.closure⟩
/-- The union of two bounded sets is bounded iff each of the sets is bounded -/
@[simp] lemma bounded_union :
bounded (s ∪ t) ↔ bounded s ∧ bounded t :=
⟨λh, ⟨h.mono (by simp), h.mono (by simp)⟩,
begin
rintro ⟨hs, ht⟩,
refine bounded_iff_mem_bounded.2 (λ x _, _),
rw bounded_iff_subset_ball x at hs ht ⊢,
rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩,
exact ⟨max Cs Ct, union_subset
(subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _)
(subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩,
end⟩
/-- A finite union of bounded sets is bounded -/
lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) :
bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) :=
finite.induction_on H (by simp) $ λ x I _ _ IH,
by simp [or_imp_distrib, forall_and_distrib, IH]
/-- A totally bounded set is bounded -/
lemma _root_.totally_bounded.bounded {s : set α} (h : totally_bounded s) : bounded s :=
-- We cover the totally bounded set by finitely many balls of radius 1,
-- and then argue that a finite union of bounded sets is bounded
let ⟨t, fint, subs⟩ := (totally_bounded_iff.mp h) 1 zero_lt_one in
bounded.mono subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball
/-- A compact set is bounded -/
lemma _root_.is_compact.bounded {s : set α} (h : is_compact s) : bounded s :=
-- A compact set is totally bounded, thus bounded
h.totally_bounded.bounded
/-- A finite set is bounded -/
lemma bounded_of_finite {s : set α} (h : finite s) : bounded s :=
h.is_compact.bounded
alias bounded_of_finite ← set.finite.bounded
/-- A singleton is bounded -/
lemma bounded_singleton {x : α} : bounded ({x} : set α) :=
bounded_of_finite $ finite_singleton _
/-- Characterization of the boundedness of the range of a function -/
lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C :=
exists_congr $ λ C, ⟨
λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩,
by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩
/-- In a compact space, all sets are bounded -/
lemma bounded_of_compact_space [compact_space α] : bounded s :=
compact_univ.bounded.mono (subset_univ _)
lemma is_compact_of_is_closed_bounded [proper_space α] (hc : is_closed s) (hb : bounded s) :
is_compact s :=
begin
unfreezingI { rcases eq_empty_or_nonempty s with (rfl|⟨x, hx⟩) },
{ exact is_compact_empty },
{ rcases hb.subset_ball x with ⟨r, hr⟩,
exact compact_of_is_closed_subset (proper_space.is_compact_closed_ball x r) hc hr }
end
/-- The Heine–Borel theorem:
In a proper space, a set is compact if and only if it is closed and bounded -/
lemma compact_iff_closed_bounded [t2_space α] [proper_space α] :
is_compact s ↔ is_closed s ∧ bounded s :=
⟨λ h, ⟨h.is_closed, h.bounded⟩, λ h, is_compact_of_is_closed_bounded h.1 h.2⟩
lemma compact_space_iff_bounded_univ [proper_space α] : compact_space α ↔ bounded (univ : set α) :=
⟨@bounded_of_compact_space α _ _, λ hb, ⟨is_compact_of_is_closed_bounded is_closed_univ hb⟩⟩
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α] [order_topology α]
lemma bounded_Icc (a b : α) : bounded (Icc a b) :=
(totally_bounded_Icc a b).bounded
lemma bounded_Ico (a b : α) : bounded (Ico a b) :=
(totally_bounded_Ico a b).bounded
lemma bounded_Ioc (a b : α) : bounded (Ioc a b) :=
(totally_bounded_Ioc a b).bounded
lemma bounded_Ioo (a b : α) : bounded (Ioo a b) :=
(totally_bounded_Ioo a b).bounded
/-- In a pseudo metric space with a conditionally complete linear order such that the order and the
metric structure give the same topology, any order-bounded set is metric-bounded. -/
lemma bounded_of_bdd_above_of_bdd_below {s : set α} (h₁ : bdd_above s) (h₂ : bdd_below s) :
bounded s :=
let ⟨u, hu⟩ := h₁, ⟨l, hl⟩ := h₂ in
bounded.mono (λ x hx, mem_Icc.mpr ⟨hl hx, hu hx⟩) (bounded_Icc l u)
end conditionally_complete_linear_order
end bounded
section diam
variables {s : set α} {x y z : α}
/-- The diameter of a set in a metric space. To get controllable behavior even when the diameter
should be infinite, we express it in terms of the emetric.diameter -/
noncomputable def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s)
/-- The diameter of a set is always nonnegative -/
lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg
lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 :=
by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real]
/-- The empty set has zero diameter -/
@[simp] lemma diam_empty : diam (∅ : set α) = 0 :=
diam_subsingleton subsingleton_empty
/-- A singleton has zero diameter -/
@[simp] lemma diam_singleton : diam ({x} : set α) = 0 :=
diam_subsingleton subsingleton_singleton
-- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x})
lemma diam_pair : diam ({x, y} : set α) = dist x y :=
by simp only [diam, emetric.diam_pair, dist_edist]
-- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x}))
lemma diam_triple :
metric.diam ({x, y, z} : set α) = max (max (dist x y) (dist x z)) (dist y z) :=
begin
simp only [metric.diam, emetric.diam_triple, dist_edist],
rw [ennreal.to_real_max, ennreal.to_real_max];
apply_rules [ne_of_lt, edist_lt_top, max_lt]
end
/-- If the distance between any two points in a set is bounded by some constant `C`,
then `ennreal.of_real C` bounds the emetric diameter of this set. -/
lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
emetric.diam s ≤ ennreal.of_real C :=
emetric.diam_le $
λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy)
/-- If the distance between any two points in a set is bounded by some non-negative constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
diam s ≤ C :=
ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h)
/-- If the distance between any two points in a nonempty set is bounded by some constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ}
(h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C :=
have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx),
diam_le_of_forall_dist_le h₀ h
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) :
dist x y ≤ diam s :=
begin
rw [diam, dist_edist],
rw ennreal.to_real_le_to_real (edist_ne_top _ _) h,
exact emetric.edist_le_diam_of_mem hx hy
end
/-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/
lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ :=
iff.intro
(λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top
(ediam_le_of_forall_dist_le $ λ x hx y hy, hC x y hx hy))
(λ h, ⟨diam s, λ x y hx hy, dist_le_diam_of_mem' h hx hy⟩)
lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ :=
bounded_iff_ediam_ne_top.1 h
lemma ediam_univ_eq_top_iff_noncompact [proper_space α] :
emetric.diam (univ : set α) = ∞ ↔ noncompact_space α :=
by rw [← not_compact_space_iff, compact_space_iff_bounded_univ, bounded_iff_ediam_ne_top, not_not]
@[simp] lemma ediam_univ_of_noncompact [proper_space α] [noncompact_space α] :
emetric.diam (univ : set α) = ∞ :=
ediam_univ_eq_top_iff_noncompact.mpr ‹_›
@[simp] lemma diam_univ_of_noncompact [proper_space α] [noncompact_space α] :
diam (univ : set α) = 0 :=
by simp [diam]
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s :=
dist_le_diam_of_mem' h.ediam_ne_top hx hy
lemma ediam_of_unbounded (h : ¬(bounded s)) : emetric.diam s = ∞ :=
by rwa [bounded_iff_ediam_ne_top, not_not] at h
/-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`.
This lemma makes it possible to avoid side conditions in some situations -/
lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 :=
by rw [diam, ediam_of_unbounded h, ennreal.top_to_real]
/-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/
lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t :=
begin
unfold diam,
rw ennreal.to_real_le_to_real (bounded.mono h ht).ediam_ne_top ht.ediam_ne_top,
exact emetric.diam_mono h
end
/-- The diameter of a union is controlled by the sum of the diameters, and the distance between
any two points in each of the sets. This lemma is true without any side condition, since it is
obviously true if `s ∪ t` is unbounded. -/
lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) :
diam (s ∪ t) ≤ diam s + dist x y + diam t :=
begin
by_cases H : bounded (s ∪ t),
{ have hs : bounded s, from H.mono (subset_union_left _ _),
have ht : bounded t, from H.mono (subset_union_right _ _),
rw [bounded_iff_ediam_ne_top] at H hs ht,
rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add,
ennreal.to_real_le_to_real];
repeat { apply ennreal.add_ne_top.2; split }; try { assumption };
try { apply edist_ne_top },
exact emetric.diam_union xs yt },
{ rw [diam_eq_zero_of_unbounded H],
apply_rules [add_nonneg, diam_nonneg, dist_nonneg] }
end
/-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/
lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t :=
begin
rcases h with ⟨x, ⟨xs, xt⟩⟩,
simpa using diam_union xs xt
end
/-- The diameter of a closed ball of radius `r` is at most `2 r`. -/
lemma diam_closed_ball {r : ℝ} (h : 0 ≤ r) : diam (closed_ball x r) ≤ 2 * r :=
diam_le_of_forall_dist_le (mul_nonneg (le_of_lt zero_lt_two) h) $ λa ha b hb, calc
dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add ha hb
... = 2 * r : by simp [mul_two, mul_comm]
/-- The diameter of a ball of radius `r` is at most `2 r`. -/
lemma diam_ball {r : ℝ} (h : 0 ≤ r) : diam (ball x r) ≤ 2 * r :=
le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h)
end diam
end metric
lemma comap_dist_right_at_top_le_cocompact (x : α) : comap (λ y, dist y x) at_top ≤ cocompact α :=
begin
refine filter.has_basis_cocompact.ge_iff.2 (λ s hs, mem_comap.2 _),
rcases hs.bounded.subset_ball x with ⟨r, hr⟩,
exact ⟨Ioi r, Ioi_mem_at_top r, λ y hy hys, (mem_closed_ball.1 $ hr hys).not_lt hy⟩
end
lemma comap_dist_left_at_top_le_cocompact (x : α) : comap (dist x) at_top ≤ cocompact α :=
by simpa only [dist_comm _ x] using comap_dist_right_at_top_le_cocompact x
lemma comap_dist_right_at_top_eq_cocompact [proper_space α] (x : α) :
comap (λ y, dist y x) at_top = cocompact α :=
(comap_dist_right_at_top_le_cocompact x).antisymm $ (tendsto_dist_right_cocompact_at_top x).le_comap
lemma comap_dist_left_at_top_eq_cocompact [proper_space α] (x : α) :
comap (dist x) at_top = cocompact α :=
(comap_dist_left_at_top_le_cocompact x).antisymm $ (tendsto_dist_left_cocompact_at_top x).le_comap
lemma tendsto_cocompact_of_tendsto_dist_comp_at_top {f : β → α} {l : filter β} (x : α)
(h : tendsto (λ y, dist (f y) x) l at_top) : tendsto f l (cocompact α) :=
by { refine tendsto.mono_right _ (comap_dist_right_at_top_le_cocompact x), rwa tendsto_comap_iff }
namespace int
open metric
/-- Under the coercion from `ℤ` to `ℝ`, inverse images of compact sets are finite. -/
lemma tendsto_coe_cofinite : tendsto (coe : ℤ → ℝ) cofinite (cocompact ℝ) :=
begin
refine tendsto_cocompact_of_tendsto_dist_comp_at_top (0 : ℝ) _,
simp only [filter.tendsto_at_top, eventually_cofinite, not_le, ← mem_ball],
change ∀ r : ℝ, finite (coe ⁻¹' (ball (0 : ℝ) r)),
simp [real.ball_eq, set.finite_Ioo],
end
end int
/-- We now define `metric_space`, extending `pseudo_metric_space`. -/
class metric_space (α : Type u) extends pseudo_metric_space α : Type u :=
(eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y)
/-- Construct a metric space structure whose underlying topological space structure
(definitionally) agrees which a pre-existing topology which is compatible with a given distance
function. -/
def metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s)
(eq_of_dist_eq_zero : ∀ x y : α, dist x y = 0 → x = y) : metric_space α :=
{ eq_of_dist_eq_zero := eq_of_dist_eq_zero,
..pseudo_metric_space.of_metrizable dist dist_self dist_comm dist_triangle H }
variables {γ : Type w} [metric_space γ]
theorem eq_of_dist_eq_zero {x y : γ} : dist x y = 0 → x = y :=
metric_space.eq_of_dist_eq_zero
@[simp] theorem dist_eq_zero {x y : γ} : dist x y = 0 ↔ x = y :=
iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _)
@[simp] theorem zero_eq_dist {x y : γ} : 0 = dist x y ↔ x = y :=
by rw [eq_comm, dist_eq_zero]
theorem dist_ne_zero {x y : γ} : dist x y ≠ 0 ↔ x ≠ y :=
by simpa only [not_iff_not] using dist_eq_zero
@[simp] theorem dist_le_zero {x y : γ} : dist x y ≤ 0 ↔ x = y :=
by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y
@[simp] theorem dist_pos {x y : γ} : 0 < dist x y ↔ x ≠ y :=
by simpa only [not_le] using not_congr dist_le_zero
theorem eq_of_forall_dist_le {x y : γ} (h : ∀ ε > 0, dist x y ≤ ε) : x = y :=
eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h)
/--Deduce the equality of points with the vanishing of the nonnegative distance-/
theorem eq_of_nndist_eq_zero {x y : γ} : nndist x y = 0 → x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero]
/--Characterize the equality of points with the vanishing of the nonnegative distance-/
@[simp] theorem nndist_eq_zero {x y : γ} : nndist x y = 0 ↔ x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero]
@[simp] theorem zero_eq_nndist {x y : γ} : 0 = nndist x y ↔ x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, zero_eq_dist]
namespace metric
variables {x : γ} {s : set γ}
@[simp] lemma closed_ball_zero : closed_ball x 0 = {x} :=
set.ext $ λ y, dist_le_zero
/-- A map between metric spaces is a uniform embedding if and only if the distance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/
theorem uniform_embedding_iff' [metric_space β] {f : γ → β} :
uniform_embedding f ↔
(∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, dist a b < δ → dist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, dist (f a) (f b) < ε → dist a b < δ) :=
begin
split,
{ assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1,
(uniform_embedding_iff.1 h).2.2⟩ },
{ rintros ⟨h₁, h₂⟩,
refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩,
assume x y hxy,
have : dist x y ≤ 0,
{ refine le_of_forall_lt' (λδ δpos, _),
rcases h₂ δ δpos with ⟨ε, εpos, hε⟩,
have : dist (f x) (f y) < ε, by simpa [hxy],
exact hε this },
simpa using this }
end
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_separated : separated_space γ :=
separated_def.2 $ λ x y h, eq_of_forall_dist_le $
λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0))
/-- If a `pseudo_metric_space` is separated, then it is a `metric_space`. -/
def of_t2_pseudo_metric_space {α : Type*} [pseudo_metric_space α]
(h : separated_space α) : metric_space α :=
{ eq_of_dist_eq_zero := λ x y hdist,
begin
refine separated_def.1 h x y (λ s hs, _),
obtain ⟨ε, hε, H⟩ := mem_uniformity_dist.1 hs,
exact H (show dist x y < ε, by rwa [hdist])
end
..‹pseudo_metric_space α› }
/-- A metric space induces an emetric space -/
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_emetric_space : emetric_space γ :=
{ eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h,
..pseudo_metric_space.to_pseudo_emetric_space, }
lemma is_closed_of_pairwise_le_dist {s : set γ} {ε : ℝ} (hε : 0 < ε)
(hs : s.pairwise (λ x y, ε ≤ dist x y)) : is_closed s :=
is_closed_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hs
lemma closed_embedding_of_pairwise_le_dist {α : Type*} [topological_space α] [discrete_topology α]
{ε : ℝ} (hε : 0 < ε) {f : α → γ} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) :
closed_embedding f :=
closed_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf
/-- If `f : β → α` sends any two distinct points to points at distance at least `ε > 0`, then
`f` is a uniform embedding with respect to the discrete uniformity on `β`. -/
lemma uniform_embedding_bot_of_pairwise_le_dist {β : Type*} {ε : ℝ} (hε : 0 < ε) {f : β → α}
(hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : @uniform_embedding _ _ ⊥ (by apply_instance) f :=
uniform_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf
end metric
/-- Build a new metric space from an old one where the bundled uniform structure is provably
(but typically non-definitionaly) equal to some given uniform structure.
See Note [forgetful inheritance].
-/
def metric_space.replace_uniformity {γ} [U : uniform_space γ] (m : metric_space γ)
(H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space') :
metric_space γ :=
{ eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _,
..pseudo_metric_space.replace_uniformity m.to_pseudo_metric_space H, }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. In this definition, the distance
is given separately, to be able to prescribe some expression which is not defeq to the push-forward
of the edistance to reals. -/
def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α]
(dist : α → α → ℝ)
(edist_ne_top : ∀x y: α, edist x y ≠ ⊤)
(h : ∀x y, dist x y = ennreal.to_real (edist x y)) :
metric_space α :=
{ dist := dist,
eq_of_dist_eq_zero := λx y hxy,
by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy,
..pseudo_emetric_space.to_pseudo_metric_space_of_dist dist edist_ne_top h, }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. -/
def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) :
metric_space α :=
emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl)
/-- Metric space structure pulled back by an injective function. Injectivity is necessary to
ensure that `dist x y = 0` only if `x = y`. -/
def metric_space.induced {γ β} (f : γ → β) (hf : function.injective f)
(m : metric_space β) : metric_space γ :=
{ eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h),
..pseudo_metric_space.induced f m.to_pseudo_metric_space }
/-- Pull back a metric space structure by a uniform embedding. This is a version of
`metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/
def uniform_embedding.comap_metric_space {α β} [uniform_space α] [metric_space β] (f : α → β)
(h : uniform_embedding f) : metric_space α :=
(metric_space.induced f h.inj ‹_›).replace_uniformity h.comap_uniformity.symm
instance subtype.metric_space {α : Type*} {p : α → Prop} [t : metric_space α] :
metric_space (subtype p) :=
metric_space.induced coe (λ x y, subtype.ext) t
theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl
instance : metric_space empty :=
{ dist := λ _ _, 0,
dist_self := λ _, rfl,
dist_comm := λ _ _, rfl,
eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _,
dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero, }
instance : metric_space punit :=
{ dist := λ _ _, 0,
dist_self := λ _, rfl,
dist_comm := λ _ _, rfl,
eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _,
dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero, }
section real
/-- Instantiate the reals as a metric space. -/
noncomputable instance real.metric_space : metric_space ℝ :=
{ eq_of_dist_eq_zero := λ x y h, by simpa [dist, sub_eq_zero] using h,
..real.pseudo_metric_space }
end real
section nnreal
noncomputable instance : metric_space ℝ≥0 := subtype.metric_space
end nnreal
section prod
noncomputable instance prod.metric_space_max [metric_space β] : metric_space (γ × β) :=
{ eq_of_dist_eq_zero := λ x y h, begin
cases max_le_iff.1 (le_of_eq h) with h₁ h₂,
exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩
end,
..prod.pseudo_metric_space_max, }
end prod
section pi
open finset
variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)]
/-- A finite product of metric spaces is a metric space, with the sup distance. -/
noncomputable instance metric_space_pi : metric_space (Πb, π b) :=
/- we construct the instance from the emetric space instance to avoid checking again that the
uniformity is the same as the product uniformity, but we register nevertheless a nice formula
for the distance -/
{ eq_of_dist_eq_zero := assume f g eq0,
begin
have eq1 : edist f g = 0 := by simp only [edist_dist, eq0, ennreal.of_real_zero],
have eq2 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq1,
simp only [finset.sup_le_iff] at eq2,
exact (funext $ assume b, edist_le_zero.1 $ eq2 b $ mem_univ b)
end,
..pseudo_metric_space_pi }
end pi
namespace metric
section second_countable
open topological_space
/-- A metric space is second countable if one can reconstruct up to any `ε>0` any element of the
space from countably many data. -/
lemma second_countable_of_countable_discretization {α : Type u} [metric_space α]
(H : ∀ε > (0 : ℝ), ∃ (β : Type*) (_ : encodable β) (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) :
second_countable_topology α :=
begin
cases (univ : set α).eq_empty_or_nonempty with hs hs,
{ haveI : compact_space α := ⟨by rw hs; exact is_compact_empty⟩, by apply_instance },
rcases hs with ⟨x0, hx0⟩,
letI : inhabited α := ⟨x0⟩,
refine second_countable_of_almost_dense_set (λε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
resetI,
let Finv := function.inv_fun F,
refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩,
let x' := Finv (F x),
have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩,
exact ⟨x', mem_range_self _, hF _ _ this.symm⟩
end
end second_countable
end metric
section eq_rel
/-- The canonical equivalence relation on a pseudometric space. -/
def pseudo_metric.dist_setoid (α : Type u) [pseudo_metric_space α] : setoid α :=
setoid.mk (λx y, dist x y = 0)
begin
unfold equivalence,
repeat { split },
{ exact pseudo_metric_space.dist_self },
{ assume x y h, rwa pseudo_metric_space.dist_comm },
{ assume x y z hxy hyz,
refine le_antisymm _ dist_nonneg,
calc dist x z ≤ dist x y + dist y z : pseudo_metric_space.dist_triangle _ _ _
... = 0 + 0 : by rw [hxy, hyz]
... = 0 : by simp }
end
local attribute [instance] pseudo_metric.dist_setoid
/-- The canonical quotient of a pseudometric space, identifying points at distance `0`. -/
@[reducible] definition pseudo_metric_quot (α : Type u) [pseudo_metric_space α] : Type* :=
quotient (pseudo_metric.dist_setoid α)
instance has_dist_metric_quot {α : Type u} [pseudo_metric_space α] :
has_dist (pseudo_metric_quot α) :=
{ dist := quotient.lift₂ (λp q : α, dist p q)
begin
assume x y x' y' hxx' hyy',
have Hxx' : dist x x' = 0 := hxx',
have Hyy' : dist y y' = 0 := hyy',
have A : dist x y ≤ dist x' y' := calc
dist x y ≤ dist x x' + dist x' y : pseudo_metric_space.dist_triangle _ _ _
... = dist x' y : by simp [Hxx']
... ≤ dist x' y' + dist y' y : pseudo_metric_space.dist_triangle _ _ _
... = dist x' y' : by simp [pseudo_metric_space.dist_comm, Hyy'],
have B : dist x' y' ≤ dist x y := calc
dist x' y' ≤ dist x' x + dist x y' : pseudo_metric_space.dist_triangle _ _ _
... = dist x y' : by simp [pseudo_metric_space.dist_comm, Hxx']
... ≤ dist x y + dist y y' : pseudo_metric_space.dist_triangle _ _ _
... = dist x y : by simp [Hyy'],
exact le_antisymm A B
end }
lemma pseudo_metric_quot_dist_eq {α : Type u} [pseudo_metric_space α] (p q : α) :
dist ⟦p⟧ ⟦q⟧ = dist p q := rfl
instance metric_space_quot {α : Type u} [pseudo_metric_space α] :
metric_space (pseudo_metric_quot α) :=
{ dist_self := begin
refine quotient.ind (λy, _),
exact pseudo_metric_space.dist_self _
end,
eq_of_dist_eq_zero := λxc yc, by exact quotient.induction_on₂ xc yc (λx y H, quotient.sound H),
dist_comm :=
λxc yc, quotient.induction_on₂ xc yc (λx y, pseudo_metric_space.dist_comm _ _),
dist_triangle :=
λxc yc zc, quotient.induction_on₃ xc yc zc (λx y z, pseudo_metric_space.dist_triangle _ _ _) }
end eq_rel
|
c9f6f41fdd7fca310f0c0ff2625a203e2b9605f2 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/pfunctor/univariate/M.lean | 7f0b29b916e580151e597f1243bbb8c2674c5cdf | [
"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 | 22,015 | lean | /-
Copyright (c) 2017 Simon Hudon All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import data.pfunctor.univariate.basic
/-!
# M-types
M types are potentially infinite tree-like structures. They are defined
as the greatest fixpoint of a polynomial functor.
-/
universes u v w
open nat function list (hiding head')
variables (F : pfunctor.{u})
local prefix `♯`:0 := cast (by simp [*] <|> cc <|> solve_by_elim)
namespace pfunctor
namespace approx
/-- `cofix_a F n` is an `n` level approximation of a M-type -/
inductive cofix_a : ℕ → Type u
| continue : cofix_a 0
| intro {n} : ∀ a, (F.B a → cofix_a n) → cofix_a (succ n)
/-- default inhabitant of `cofix_a` -/
protected def cofix_a.default [inhabited F.A] : Π n, cofix_a F n
| 0 := cofix_a.continue
| (succ n) := cofix_a.intro default $ λ _, cofix_a.default n
instance [inhabited F.A] {n} : inhabited (cofix_a F n) := ⟨ cofix_a.default F n ⟩
lemma cofix_a_eq_zero : ∀ x y : cofix_a F 0, x = y
| cofix_a.continue cofix_a.continue := rfl
variables {F}
/--
The label of the root of the tree for a non-trivial
approximation of the cofix of a pfunctor.
-/
def head' : Π {n}, cofix_a F (succ n) → F.A
| n (cofix_a.intro i _) := i
/-- for a non-trivial approximation, return all the subtrees of the root -/
def children' : Π {n} (x : cofix_a F (succ n)), F.B (head' x) → cofix_a F n
| n (cofix_a.intro a f) := f
lemma approx_eta {n : ℕ} (x : cofix_a F (n+1)) :
x = cofix_a.intro (head' x) (children' x) :=
by cases x; refl
/-- Relation between two approximations of the cofix of a pfunctor
that state they both contain the same data until one of them is truncated -/
inductive agree : ∀ {n : ℕ}, cofix_a F n → cofix_a F (n+1) → Prop
| continue (x : cofix_a F 0) (y : cofix_a F 1) : agree x y
| intro {n} {a} (x : F.B a → cofix_a F n) (x' : F.B a → cofix_a F (n+1)) :
(∀ i : F.B a, agree (x i) (x' i)) →
agree (cofix_a.intro a x) (cofix_a.intro a x')
/--
Given an infinite series of approximations `approx`,
`all_agree approx` states that they are all consistent with each other.
-/
def all_agree (x : Π n, cofix_a F n) :=
∀ n, agree (x n) (x (succ n))
@[simp]
lemma agree_trival {x : cofix_a F 0} {y : cofix_a F 1} :
agree x y :=
by { constructor }
lemma agree_children {n : ℕ} (x : cofix_a F (succ n)) (y : cofix_a F (succ n+1))
{i j} (h₀ : i == j) (h₁ : agree x y) :
agree (children' x i) (children' y j) :=
begin
cases h₁ with _ _ _ _ _ _ hagree, cases h₀,
apply hagree,
end
/-- `truncate a` turns `a` into a more limited approximation -/
def truncate : ∀ {n : ℕ}, cofix_a F (n+1) → cofix_a F n
| 0 (cofix_a.intro _ _) := cofix_a.continue
| (succ n) (cofix_a.intro i f) := cofix_a.intro i $ truncate ∘ f
lemma truncate_eq_of_agree {n : ℕ} (x : cofix_a F n) (y : cofix_a F (succ n)) (h : agree x y) :
truncate y = x :=
begin
induction n generalizing x y; cases x; cases y,
{ refl },
{ cases h with _ _ _ _ _ h₀ h₁,
cases h,
simp only [truncate, function.comp, true_and, eq_self_iff_true, heq_iff_eq],
ext y, apply n_ih,
apply h₁ }
end
variables {X : Type w}
variables (f : X → F.obj X)
/-- `s_corec f i n` creates an approximation of height `n`
of the final coalgebra of `f` -/
def s_corec : Π (i : X) n, cofix_a F n
| _ 0 := cofix_a.continue
| j (succ n) := cofix_a.intro (f j).1 (λ i, s_corec ((f j).2 i) _)
lemma P_corec (i : X) (n : ℕ) : agree (s_corec f i n) (s_corec f i (succ n)) :=
begin
induction n with n generalizing i,
constructor,
cases h : f i with y g,
constructor,
introv,
apply n_ih,
end
/-- `path F` provides indices to access internal nodes in `corec F` -/
def path (F : pfunctor.{u}) := list F.Idx
instance path.inhabited : inhabited (path F) := ⟨ [] ⟩
open list nat
instance : subsingleton (cofix_a F 0) :=
⟨ by { intros, casesm* cofix_a F 0, refl } ⟩
lemma head_succ' (n m : ℕ) (x : Π n, cofix_a F n) (Hconsistent : all_agree x) :
head' (x (succ n)) = head' (x (succ m)) :=
begin
suffices : ∀ n, head' (x (succ n)) = head' (x 1),
{ simp [this] },
clear m n, intro,
cases h₀ : x (succ n) with _ i₀ f₀,
cases h₁ : x 1 with _ i₁ f₁,
dsimp only [head'],
induction n with n,
{ rw h₁ at h₀, cases h₀, trivial },
{ have H := Hconsistent (succ n),
cases h₂ : x (succ n) with _ i₂ f₂,
rw [h₀,h₂] at H,
apply n_ih (truncate ∘ f₀),
rw h₂,
cases H with _ _ _ _ _ _ hagree,
congr, funext j, dsimp only [comp_app],
rw truncate_eq_of_agree,
apply hagree }
end
end approx
open approx
/-- Internal definition for `M`. It is needed to avoid name clashes
between `M.mk` and `M.cases_on` and the declarations generated for
the structure -/
structure M_intl :=
(approx : ∀ n, cofix_a F n)
(consistent : all_agree approx)
/-- For polynomial functor `F`, `M F` is its final coalgebra -/
def M := M_intl F
lemma M.default_consistent [inhabited F.A] :
Π n, agree (default : cofix_a F n) default
| 0 := agree.continue _ _
| (succ n) := agree.intro _ _ $ λ _, M.default_consistent n
instance M.inhabited [inhabited F.A] : inhabited (M F) :=
⟨ { approx := λ n, default,
consistent := M.default_consistent _ } ⟩
instance M_intl.inhabited [inhabited F.A] : inhabited (M_intl F) :=
show inhabited (M F), by apply_instance
namespace M
lemma ext' (x y : M F) (H : ∀ i : ℕ, x.approx i = y.approx i) : x = y :=
by { cases x, cases y, congr' with n, apply H }
variables {X : Type*}
variables (f : X → F.obj X)
variables {F}
/-- Corecursor for the M-type defined by `F`. -/
protected def corec (i : X) : M F :=
{ approx := s_corec f i,
consistent := P_corec _ _ }
variables {F}
/-- given a tree generated by `F`, `head` gives us the first piece of data
it contains -/
def head (x : M F) :=
head' (x.1 1)
/-- return all the subtrees of the root of a tree `x : M F` -/
def children (x : M F) (i : F.B (head x)) : M F :=
let H := λ n : ℕ, @head_succ' _ n 0 x.1 x.2 in
{ approx := λ n, children' (x.1 _) (cast (congr_arg _ $ by simp only [head,H]; refl) i),
consistent :=
begin
intro,
have P' := x.2 (succ n),
apply agree_children _ _ _ P',
transitivity i,
apply cast_heq,
symmetry,
apply cast_heq,
end }
/-- select a subtree using a `i : F.Idx` or return an arbitrary tree if
`i` designates no subtree of `x` -/
def ichildren [inhabited (M F)] [decidable_eq F.A] (i : F.Idx) (x : M F) : M F :=
if H' : i.1 = head x
then children x (cast (congr_arg _ $ by simp only [head,H']; refl) i.2)
else default
lemma head_succ (n m : ℕ) (x : M F) :
head' (x.approx (succ n)) = head' (x.approx (succ m)) :=
head_succ' n m _ x.consistent
lemma head_eq_head' : Π (x : M F) (n : ℕ),
head x = head' (x.approx $ n+1)
| ⟨x,h⟩ n := head_succ' _ _ _ h
lemma head'_eq_head : Π (x : M F) (n : ℕ),
head' (x.approx $ n+1) = head x
| ⟨x,h⟩ n := head_succ' _ _ _ h
lemma truncate_approx (x : M F) (n : ℕ) :
truncate (x.approx $ n+1) = x.approx n :=
truncate_eq_of_agree _ _ (x.consistent _)
/-- unfold an M-type -/
def dest : M F → F.obj (M F)
| x := ⟨head x,λ i, children x i ⟩
namespace approx
/-- generates the approximations needed for `M.mk` -/
protected def s_mk (x : F.obj $ M F) : Π n, cofix_a F n
| 0 := cofix_a.continue
| (succ n) := cofix_a.intro x.1 (λ i, (x.2 i).approx n)
protected lemma P_mk (x : F.obj $ M F)
: all_agree (approx.s_mk x)
| 0 := by { constructor }
| (succ n) := by { constructor, introv,
apply (x.2 i).consistent }
end approx
/-- constructor for M-types -/
protected def mk (x : F.obj $ M F) : M F :=
{ approx := approx.s_mk x,
consistent := approx.P_mk x }
/-- `agree' n` relates two trees of type `M F` that
are the same up to dept `n` -/
inductive agree' : ℕ → M F → M F → Prop
| trivial (x y : M F) : agree' 0 x y
| step {n : ℕ} {a} (x y : F.B a → M F) {x' y'} :
x' = M.mk ⟨a,x⟩ →
y' = M.mk ⟨a,y⟩ →
(∀ i, agree' n (x i) (y i)) →
agree' (succ n) x' y'
@[simp]
lemma dest_mk (x : F.obj $ M F) :
dest (M.mk x) = x :=
begin
funext i,
dsimp only [M.mk,dest],
cases x with x ch, congr' with i,
cases h : ch i,
simp only [children,M.approx.s_mk,children',cast_eq],
dsimp only [M.approx.s_mk,children'],
congr, rw h,
end
@[simp] lemma mk_dest (x : M F) :
M.mk (dest x) = x :=
begin
apply ext', intro n,
dsimp only [M.mk],
induction n with n,
{ apply subsingleton.elim },
dsimp only [approx.s_mk,dest,head],
cases h : x.approx (succ n) with _ hd ch,
have h' : hd = head' (x.approx 1),
{ rw [← head_succ' n,h,head'], apply x.consistent },
revert ch, rw h', intros, congr,
{ ext a, dsimp only [children],
h_generalize! hh : a == a'',
rw h, intros, cases hh, refl },
end
lemma mk_inj {x y : F.obj $ M F}
(h : M.mk x = M.mk y) : x = y :=
by rw [← dest_mk x,h,dest_mk]
/-- destructor for M-types -/
protected def cases {r : M F → Sort w}
(f : ∀ (x : F.obj $ M F), r (M.mk x)) (x : M F) : r x :=
suffices r (M.mk (dest x)),
by { haveI := classical.prop_decidable,
haveI := inhabited.mk x,
rw [← mk_dest x], exact this },
f _
/-- destructor for M-types -/
protected def cases_on {r : M F → Sort w}
(x : M F) (f : ∀ (x : F.obj $ M F), r (M.mk x)) : r x :=
M.cases f x
/-- destructor for M-types, similar to `cases_on` but also
gives access directly to the root and subtrees on an M-type -/
protected def cases_on' {r : M F → Sort w}
(x : M F) (f : ∀ a f, r (M.mk ⟨a,f⟩)) : r x :=
M.cases_on x (λ ⟨a,g⟩, f a _)
lemma approx_mk (a : F.A) (f : F.B a → M F) (i : ℕ) :
(M.mk ⟨a, f⟩).approx (succ i) = cofix_a.intro a (λ j, (f j).approx i) :=
rfl
@[simp] lemma agree'_refl {n : ℕ} (x : M F) :
agree' n x x :=
by { induction n generalizing x; induction x using pfunctor.M.cases_on';
constructor; try { refl }, intros, apply n_ih }
lemma agree_iff_agree' {n : ℕ} (x y : M F) :
agree (x.approx n) (y.approx $ n+1) ↔ agree' n x y :=
begin
split; intros h,
{ induction n generalizing x y, constructor,
{ induction x using pfunctor.M.cases_on',
induction y using pfunctor.M.cases_on',
simp only [approx_mk] at h, cases h with _ _ _ _ _ _ hagree,
constructor; try { refl },
intro i, apply n_ih, apply hagree } },
{ induction n generalizing x y, constructor,
{ cases h,
induction x using pfunctor.M.cases_on',
induction y using pfunctor.M.cases_on',
simp only [approx_mk],
have h_a_1 := mk_inj ‹M.mk ⟨x_a, x_f⟩ = M.mk ⟨h_a, h_x⟩›, cases h_a_1,
replace h_a_2 := mk_inj ‹M.mk ⟨y_a, y_f⟩ = M.mk ⟨h_a, h_y⟩›, cases h_a_2,
constructor, intro i, apply n_ih, simp * } },
end
@[simp]
lemma cases_mk {r : M F → Sort*} (x : F.obj $ M F) (f : Π (x : F.obj $ M F), r (M.mk x)) :
pfunctor.M.cases f (M.mk x) = f x :=
begin
dsimp only [M.mk,pfunctor.M.cases,dest,head,approx.s_mk,head'],
cases x, dsimp only [approx.s_mk],
apply eq_of_heq,
apply rec_heq_of_heq, congr' with x,
dsimp only [children,approx.s_mk,children'],
cases h : x_snd x, dsimp only [head],
congr' with n, change (x_snd (x)).approx n = _, rw h
end
@[simp]
lemma cases_on_mk {r : M F → Sort*} (x : F.obj $ M F) (f : Π x : F.obj $ M F, r (M.mk x)) :
pfunctor.M.cases_on (M.mk x) f = f x :=
cases_mk x f
@[simp]
lemma cases_on_mk'
{r : M F → Sort*} {a} (x : F.B a → M F) (f : Π a (f : F.B a → M F), r (M.mk ⟨a,f⟩)) :
pfunctor.M.cases_on' (M.mk ⟨a,x⟩) f = f a x :=
cases_mk ⟨_,x⟩ _
/-- `is_path p x` tells us if `p` is a valid path through `x` -/
inductive is_path : path F → M F → Prop
| nil (x : M F) : is_path [] x
| cons (xs : path F) {a} (x : M F) (f : F.B a → M F) (i : F.B a) :
x = M.mk ⟨a,f⟩ →
is_path xs (f i) →
is_path (⟨a,i⟩ :: xs) x
lemma is_path_cons {xs : path F} {a a'} {f : F.B a → M F} {i : F.B a'}
(h : is_path (⟨a',i⟩ :: xs) (M.mk ⟨a,f⟩)) :
a = a' :=
begin
revert h, generalize h : (M.mk ⟨a,f⟩) = x,
intros h', cases h', subst x,
cases mk_inj ‹_›, refl,
end
lemma is_path_cons' {xs : path F} {a} {f : F.B a → M F} {i : F.B a}
(h : is_path (⟨a,i⟩ :: xs) (M.mk ⟨a,f⟩)) :
is_path xs (f i) :=
begin
revert h, generalize h : (M.mk ⟨a,f⟩) = x,
intros h', cases h', subst x,
have := mk_inj ‹_›, cases this, cases this,
assumption,
end
/-- follow a path through a value of `M F` and return the subtree
found at the end of the path if it is a valid path for that value and
return a default tree -/
def isubtree [decidable_eq F.A] [inhabited (M F)] : path F → M F → M F
| [] x := x
| (⟨a, i⟩ :: ps) x :=
pfunctor.M.cases_on' x (λ a' f,
(if h : a = a' then isubtree ps (f $ cast (by rw h) i)
else default : (λ x, M F) (M.mk ⟨a',f⟩)))
/-- similar to `isubtree` but returns the data at the end of the path instead
of the whole subtree -/
def iselect [decidable_eq F.A] [inhabited (M F)] (ps : path F) : M F → F.A :=
λ (x : M F), head $ isubtree ps x
lemma iselect_eq_default [decidable_eq F.A] [inhabited (M F)] (ps : path F) (x : M F)
(h : ¬ is_path ps x) :
iselect ps x = head default :=
begin
induction ps generalizing x,
{ exfalso, apply h, constructor },
{ cases ps_hd with a i,
induction x using pfunctor.M.cases_on',
simp only [iselect,isubtree] at ps_ih ⊢,
by_cases h'' : a = x_a, subst x_a,
{ simp only [dif_pos, eq_self_iff_true, cases_on_mk'],
rw ps_ih, intro h', apply h,
constructor; try { refl }, apply h' },
{ simp * } }
end
@[simp] lemma head_mk (x : F.obj (M F)) :
head (M.mk x) = x.1 :=
eq.symm $
calc x.1
= (dest (M.mk x)).1 : by rw dest_mk
... = head (M.mk x) : by refl
lemma children_mk {a} (x : F.B a → (M F)) (i : F.B (head (M.mk ⟨a,x⟩))) :
children (M.mk ⟨a,x⟩) i = x (cast (by rw head_mk) i) :=
by apply ext'; intro n; refl
@[simp]
lemma ichildren_mk [decidable_eq F.A] [inhabited (M F)] (x : F.obj (M F)) (i : F.Idx) :
ichildren i (M.mk x) = x.iget i :=
by { dsimp only [ichildren,pfunctor.obj.iget],
congr' with h, apply ext',
dsimp only [children',M.mk,approx.s_mk],
intros, refl }
@[simp]
lemma isubtree_cons
[decidable_eq F.A] [inhabited (M F)] (ps : path F) {a} (f : F.B a → M F) {i : F.B a} :
isubtree (⟨_,i⟩ :: ps) (M.mk ⟨a,f⟩) = isubtree ps (f i) :=
by simp only [isubtree,ichildren_mk,pfunctor.obj.iget,dif_pos,isubtree,M.cases_on_mk']; refl
@[simp]
lemma iselect_nil [decidable_eq F.A] [inhabited (M F)] {a} (f : F.B a → M F) :
iselect nil (M.mk ⟨a,f⟩) = a :=
by refl
@[simp]
lemma iselect_cons [decidable_eq F.A] [inhabited (M F)] (ps : path F) {a} (f : F.B a → M F) {i} :
iselect (⟨a,i⟩ :: ps) (M.mk ⟨a,f⟩) = iselect ps (f i) :=
by simp only [iselect,isubtree_cons]
lemma corec_def {X} (f : X → F.obj X) (x₀ : X) :
M.corec f x₀ = M.mk (M.corec f <$> f x₀) :=
begin
dsimp only [M.corec,M.mk],
congr' with n,
cases n with n,
{ dsimp only [s_corec,approx.s_mk], refl, },
{ dsimp only [s_corec,approx.s_mk], cases h : (f x₀),
dsimp only [(<$>),pfunctor.map],
congr, }
end
lemma ext_aux [inhabited (M F)] [decidable_eq F.A] {n : ℕ} (x y z : M F)
(hx : agree' n z x)
(hy : agree' n z y)
(hrec : ∀ (ps : path F),
n = ps.length →
iselect ps x = iselect ps y) :
x.approx (n+1) = y.approx (n+1) :=
begin
induction n with n generalizing x y z,
{ specialize hrec [] rfl,
induction x using pfunctor.M.cases_on', induction y using pfunctor.M.cases_on',
simp only [iselect_nil] at hrec, subst hrec,
simp only [approx_mk, true_and, eq_self_iff_true, heq_iff_eq],
apply subsingleton.elim },
{ cases hx, cases hy,
induction x using pfunctor.M.cases_on', induction y using pfunctor.M.cases_on',
subst z,
iterate 3 { have := mk_inj ‹_›, repeat { cases this } },
simp only [approx_mk, true_and, eq_self_iff_true, heq_iff_eq],
ext i, apply n_ih,
{ solve_by_elim },
{ solve_by_elim },
introv h, specialize hrec (⟨_,i⟩ :: ps) (congr_arg _ h),
simp only [iselect_cons] at hrec, exact hrec }
end
open pfunctor.approx
variables {F}
local attribute [instance, priority 0] classical.prop_decidable
lemma ext [inhabited (M F)]
(x y : M F)
(H : ∀ (ps : path F), iselect ps x = iselect ps y) :
x = y :=
begin
apply ext', intro i,
induction i with i,
{ cases x.approx 0, cases y.approx 0, constructor },
{ apply ext_aux x y x,
{ rw ← agree_iff_agree', apply x.consistent },
{ rw [← agree_iff_agree',i_ih], apply y.consistent },
introv H',
dsimp only [iselect] at H,
cases H',
apply H ps }
end
section bisim
variable (R : M F → M F → Prop)
local infix ` ~ `:50 := R
/-- Bisimulation is the standard proof technique for equality between
infinite tree-like structures -/
structure is_bisimulation : Prop :=
(head : ∀ {a a'} {f f'}, M.mk ⟨a,f⟩ ~ M.mk ⟨a',f'⟩ → a = a')
(tail : ∀ {a} {f f' : F.B a → M F},
M.mk ⟨a,f⟩ ~ M.mk ⟨a,f'⟩ →
(∀ (i : F.B a), f i ~ f' i) )
theorem nth_of_bisim [inhabited (M F)] (bisim : is_bisimulation R) (s₁ s₂) (ps : path F) :
s₁ ~ s₂ →
is_path ps s₁ ∨ is_path ps s₂ →
iselect ps s₁ = iselect ps s₂ ∧
∃ a (f f' : F.B a → M F),
isubtree ps s₁ = M.mk ⟨a,f⟩ ∧
isubtree ps s₂ = M.mk ⟨a,f'⟩ ∧
∀ (i : F.B a), f i ~ f' i :=
begin
intros h₀ hh,
induction s₁ using pfunctor.M.cases_on' with a f,
induction s₂ using pfunctor.M.cases_on' with a' f',
have : a = a' := bisim.head h₀, subst a',
induction ps with i ps generalizing a f f',
{ existsi [rfl,a,f,f',rfl,rfl],
apply bisim.tail h₀ },
cases i with a' i,
have : a = a',
{ cases hh; cases is_path_cons hh; refl },
subst a', dsimp only [iselect] at ps_ih ⊢,
have h₁ := bisim.tail h₀ i,
induction h : (f i) using pfunctor.M.cases_on' with a₀ f₀,
induction h' : (f' i) using pfunctor.M.cases_on' with a₁ f₁,
simp only [h,h',isubtree_cons] at ps_ih ⊢,
rw [h,h'] at h₁,
have : a₀ = a₁ := bisim.head h₁, subst a₁,
apply (ps_ih _ _ _ h₁),
rw [← h,← h'], apply or_of_or_of_imp_of_imp hh is_path_cons' is_path_cons'
end
theorem eq_of_bisim [nonempty (M F)] (bisim : is_bisimulation R) : ∀ s₁ s₂, s₁ ~ s₂ → s₁ = s₂ :=
begin
inhabit (M F),
introv Hr, apply ext,
introv,
by_cases h : is_path ps s₁ ∨ is_path ps s₂,
{ have H := nth_of_bisim R bisim _ _ ps Hr h,
exact H.left },
{ rw not_or_distrib at h, cases h with h₀ h₁,
simp only [iselect_eq_default,*,not_false_iff] }
end
end bisim
universes u' v'
/-- corecursor for `M F` with swapped arguments -/
def corec_on {X : Type*} (x₀ : X) (f : X → F.obj X) : M F :=
M.corec f x₀
variables {P : pfunctor.{u}} {α : Type u}
lemma dest_corec (g : α → P.obj α) (x : α) :
M.dest (M.corec g x) = M.corec g <$> g x :=
by rw [corec_def,dest_mk]
lemma bisim (R : M P → M P → Prop)
(h : ∀ x y, R x y → ∃ a f f',
M.dest x = ⟨a, f⟩ ∧
M.dest y = ⟨a, f'⟩ ∧
∀ i, R (f i) (f' i)) :
∀ x y, R x y → x = y :=
begin
introv h',
haveI := inhabited.mk x.head,
apply eq_of_bisim R _ _ _ h', clear h' x y,
split; introv ih;
rcases h _ _ ih with ⟨ a'', g, g', h₀, h₁, h₂ ⟩; clear h,
{ replace h₀ := congr_arg sigma.fst h₀,
replace h₁ := congr_arg sigma.fst h₁,
simp only [dest_mk] at h₀ h₁,
rw [h₀,h₁], },
{ simp only [dest_mk] at h₀ h₁,
cases h₀, cases h₁,
apply h₂, },
end
theorem bisim' {α : Type*} (Q : α → Prop) (u v : α → M P)
(h : ∀ x, Q x → ∃ a f f',
M.dest (u x) = ⟨a, f⟩ ∧
M.dest (v x) = ⟨a, f'⟩ ∧
∀ i, ∃ x', Q x' ∧ f i = u x' ∧ f' i = v x') :
∀ x, Q x → u x = v x :=
λ x Qx,
let R := λ w z : M P, ∃ x', Q x' ∧ w = u x' ∧ z = v x' in
@M.bisim P R
(λ x y ⟨x', Qx', xeq, yeq⟩,
let ⟨a, f, f', ux'eq, vx'eq, h'⟩ := h x' Qx' in
⟨a, f, f', xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, h'⟩)
_ _ ⟨x, Qx, rfl, rfl⟩
-- for the record, show M_bisim follows from _bisim'
theorem bisim_equiv (R : M P → M P → Prop)
(h : ∀ x y, R x y → ∃ a f f',
M.dest x = ⟨a, f⟩ ∧
M.dest y = ⟨a, f'⟩ ∧
∀ i, R (f i) (f' i)) :
∀ x y, R x y → x = y :=
λ x y Rxy,
let Q : M P × M P → Prop := λ p, R p.fst p.snd in
bisim' Q prod.fst prod.snd
(λ p Qp,
let ⟨a, f, f', hx, hy, h'⟩ := h p.fst p.snd Qp in
⟨a, f, f', hx, hy, λ i, ⟨⟨f i, f' i⟩, h' i, rfl, rfl⟩⟩)
⟨x, y⟩ Rxy
theorem corec_unique (g : α → P.obj α) (f : α → M P)
(hyp : ∀ x, M.dest (f x) = f <$> (g x)) :
f = M.corec g :=
begin
ext x,
apply bisim' (λ x, true) _ _ _ _ trivial,
clear x,
intros x _,
cases gxeq : g x with a f',
have h₀ : M.dest (f x) = ⟨a, f ∘ f'⟩,
{ rw [hyp, gxeq, pfunctor.map_eq] },
have h₁ : M.dest (M.corec g x) = ⟨a, M.corec g ∘ f'⟩,
{ rw [dest_corec, gxeq, pfunctor.map_eq], },
refine ⟨_, _, _, h₀, h₁, _⟩,
intro i,
exact ⟨f' i, trivial, rfl, rfl⟩
end
/-- corecursor where the state of the computation can be sent downstream
in the form of a recursive call -/
def corec₁ {α : Type u} (F : Π X, (α → X) → α → P.obj X) : α → M P :=
M.corec (F _ id)
/-- corecursor where it is possible to return a fully formed value at any point
of the computation -/
def corec' {α : Type u} (F : Π {X : Type u}, (α → X) → α → M P ⊕ P.obj X) (x : α) : M P :=
corec₁
(λ X rec (a : M P ⊕ α),
let y := a >>= F (rec ∘ sum.inr) in
match y with
| sum.inr y := y
| sum.inl y := (rec ∘ sum.inl) <$> M.dest y
end )
(@sum.inr (M P) _ x)
end M
end pfunctor
|
4714be908dacd7967a1aaa5c76b790a698abe6b2 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/field_theory/adjoin.lean | fe37d48fabe22941bc56d842dad4e2ca0de4abcd | [
"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 | 37,060 | lean | /-
Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning, Patrick Lutz
-/
import field_theory.intermediate_field
import field_theory.separable
import ring_theory.tensor_product
/-!
# Adjoining Elements to Fields
In this file we introduce the notion of adjoining elements to fields.
This isn't quite the same as adjoining elements to rings.
For example, `algebra.adjoin K {x}` might not include `x⁻¹`.
## Main results
- `adjoin_adjoin_left`: adjoining S and then T is the same as adjoining `S ∪ T`.
- `bot_eq_top_of_dim_adjoin_eq_one`: if `F⟮x⟯` has dimension `1` over `F` for every `x`
in `E` then `F = E`
## Notation
- `F⟮α⟯`: adjoin a single element `α` to `F`.
-/
open finite_dimensional polynomial
open_locale classical polynomial
namespace intermediate_field
section adjoin_def
variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E)
/-- `adjoin F S` extends a field `F` by adjoining a set `S ⊆ E`. -/
def adjoin : intermediate_field F E :=
{ algebra_map_mem' := λ x, subfield.subset_closure (or.inl (set.mem_range_self x)),
..subfield.closure (set.range (algebra_map F E) ∪ S) }
end adjoin_def
section lattice
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E]
@[simp] lemma adjoin_le_iff {S : set E} {T : intermediate_field F E} : adjoin F S ≤ T ↔ S ≤ T :=
⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subfield.subset_closure) H,
λ H, (@subfield.closure_le E _ (set.range (algebra_map F E) ∪ S) T.to_subfield).mpr
(set.union_subset (intermediate_field.set_range_subset T) H)⟩
lemma gc : galois_connection (adjoin F : set E → intermediate_field F E) coe := λ _ _, adjoin_le_iff
/-- Galois insertion between `adjoin` and `coe`. -/
def gi : galois_insertion (adjoin F : set E → intermediate_field F E) coe :=
{ choice := λ s hs, (adjoin F s).copy s $ le_antisymm (gc.le_u_l s) hs,
gc := intermediate_field.gc,
le_l_u := λ S, (intermediate_field.gc (S : set E) (adjoin F S)).1 $ le_rfl,
choice_eq := λ _ _, copy_eq _ _ _ }
instance : complete_lattice (intermediate_field F E) :=
galois_insertion.lift_complete_lattice intermediate_field.gi
instance : inhabited (intermediate_field F E) := ⟨⊤⟩
lemma coe_bot : ↑(⊥ : intermediate_field F E) = set.range (algebra_map F E) :=
begin
change ↑(subfield.closure (set.range (algebra_map F E) ∪ ∅)) = set.range (algebra_map F E),
simp [←set.image_univ, ←ring_hom.map_field_closure]
end
lemma mem_bot {x : E} : x ∈ (⊥ : intermediate_field F E) ↔ x ∈ set.range (algebra_map F E) :=
set.ext_iff.mp coe_bot x
@[simp] lemma bot_to_subalgebra : (⊥ : intermediate_field F E).to_subalgebra = ⊥ :=
by { ext, rw [mem_to_subalgebra, algebra.mem_bot, mem_bot] }
@[simp] lemma coe_top : ↑(⊤ : intermediate_field F E) = (set.univ : set E) := rfl
@[simp] lemma mem_top {x : E} : x ∈ (⊤ : intermediate_field F E) :=
trivial
@[simp] lemma top_to_subalgebra : (⊤ : intermediate_field F E).to_subalgebra = ⊤ :=
rfl
@[simp] lemma top_to_subfield : (⊤ : intermediate_field F E).to_subfield = ⊤ :=
rfl
@[simp, norm_cast]
lemma coe_inf (S T : intermediate_field F E) : (↑(S ⊓ T) : set E) = S ∩ T := rfl
@[simp]
lemma mem_inf {S T : intermediate_field F E} {x : E} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl
@[simp] lemma inf_to_subalgebra (S T : intermediate_field F E) :
(S ⊓ T).to_subalgebra = S.to_subalgebra ⊓ T.to_subalgebra :=
rfl
@[simp] lemma inf_to_subfield (S T : intermediate_field F E) :
(S ⊓ T).to_subfield = S.to_subfield ⊓ T.to_subfield :=
rfl
@[simp, norm_cast]
lemma coe_Inf (S : set (intermediate_field F E)) : (↑(Inf S) : set E) = Inf (coe '' S) := rfl
@[simp] lemma Inf_to_subalgebra (S : set (intermediate_field F E)) :
(Inf S).to_subalgebra = Inf (to_subalgebra '' S) :=
set_like.coe_injective $ by simp [set.sUnion_image]
@[simp] lemma Inf_to_subfield (S : set (intermediate_field F E)) :
(Inf S).to_subfield = Inf (to_subfield '' S) :=
set_like.coe_injective $ by simp [set.sUnion_image]
@[simp, norm_cast]
lemma coe_infi {ι : Sort*} (S : ι → intermediate_field F E) : (↑(infi S) : set E) = ⋂ i, (S i) :=
by simp [infi]
@[simp] lemma infi_to_subalgebra {ι : Sort*} (S : ι → intermediate_field F E) :
(infi S).to_subalgebra = ⨅ i, (S i).to_subalgebra :=
set_like.coe_injective $ by simp [infi]
@[simp] lemma infi_to_subfield {ι : Sort*} (S : ι → intermediate_field F E) :
(infi S).to_subfield = ⨅ i, (S i).to_subfield :=
set_like.coe_injective $ by simp [infi]
/-- Construct an algebra isomorphism from an equality of intermediate fields -/
@[simps apply]
def equiv_of_eq {S T : intermediate_field F E} (h : S = T) : S ≃ₐ[F] T :=
by refine { to_fun := λ x, ⟨x, _⟩, inv_fun := λ x, ⟨x, _⟩, .. }; tidy
@[simp] lemma equiv_of_eq_symm {S T : intermediate_field F E} (h : S = T) :
(equiv_of_eq h).symm = equiv_of_eq h.symm :=
rfl
@[simp] lemma equiv_of_eq_rfl (S : intermediate_field F E) :
equiv_of_eq (rfl : S = S) = alg_equiv.refl :=
by { ext, refl }
@[simp] lemma equiv_of_eq_trans {S T U : intermediate_field F E} (hST : S = T) (hTU : T = U) :
(equiv_of_eq hST).trans (equiv_of_eq hTU) = equiv_of_eq (trans hST hTU) :=
rfl
variables (F E)
/-- The bottom intermediate_field is isomorphic to the field. -/
noncomputable def bot_equiv : (⊥ : intermediate_field F E) ≃ₐ[F] F :=
(subalgebra.equiv_of_eq _ _ bot_to_subalgebra).trans (algebra.bot_equiv F E)
variables {F E}
@[simp] lemma bot_equiv_def (x : F) :
bot_equiv F E (algebra_map F (⊥ : intermediate_field F E) x) = x :=
alg_equiv.commutes (bot_equiv F E) x
@[simp] lemma bot_equiv_symm (x : F) :
(bot_equiv F E).symm x = algebra_map F _ x :=
rfl
noncomputable instance algebra_over_bot : algebra (⊥ : intermediate_field F E) F :=
(intermediate_field.bot_equiv F E).to_alg_hom.to_ring_hom.to_algebra
lemma coe_algebra_map_over_bot :
(algebra_map (⊥ : intermediate_field F E) F : (⊥ : intermediate_field F E) → F) =
(intermediate_field.bot_equiv F E) :=
rfl
instance is_scalar_tower_over_bot : is_scalar_tower (⊥ : intermediate_field F E) F E :=
is_scalar_tower.of_algebra_map_eq
begin
intro x,
obtain ⟨y, rfl⟩ := (bot_equiv F E).symm.surjective x,
rw [coe_algebra_map_over_bot, (bot_equiv F E).apply_symm_apply, bot_equiv_symm,
is_scalar_tower.algebra_map_apply F (⊥ : intermediate_field F E) E]
end
/-- The top intermediate_field is isomorphic to the field.
This is the intermediate field version of `subalgebra.top_equiv`. -/
@[simps apply] def top_equiv : (⊤ : intermediate_field F E) ≃ₐ[F] E :=
(subalgebra.equiv_of_eq _ _ top_to_subalgebra).trans subalgebra.top_equiv
@[simp] lemma top_equiv_symm_apply_coe (a : E) :
↑((top_equiv.symm) a : (⊤ : intermediate_field F E)) = a := rfl
@[simp] lemma coe_bot_eq_self (K : intermediate_field F E) : ↑(⊥ : intermediate_field K E) = K :=
by { ext, rw [mem_lift2, mem_bot], exact set.ext_iff.mp subtype.range_coe x }
@[simp] lemma coe_top_eq_top (K : intermediate_field F E) :
↑(⊤ : intermediate_field K E) = (⊤ : intermediate_field F E) :=
set_like.ext_iff.mpr $ λ _, mem_lift2.trans (iff_of_true mem_top mem_top)
end lattice
section adjoin_def
variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E)
lemma adjoin_eq_range_algebra_map_adjoin :
(adjoin F S : set E) = set.range (algebra_map (adjoin F S) E) := (subtype.range_coe).symm
lemma adjoin.algebra_map_mem (x : F) : algebra_map F E x ∈ adjoin F S :=
intermediate_field.algebra_map_mem (adjoin F S) x
lemma adjoin.range_algebra_map_subset : set.range (algebra_map F E) ⊆ adjoin F S :=
begin
intros x hx,
cases hx with f hf,
rw ← hf,
exact adjoin.algebra_map_mem F S f,
end
instance adjoin.field_coe : has_coe_t F (adjoin F S) :=
{coe := λ x, ⟨algebra_map F E x, adjoin.algebra_map_mem F S x⟩}
lemma subset_adjoin : S ⊆ adjoin F S :=
λ x hx, subfield.subset_closure (or.inr hx)
instance adjoin.set_coe : has_coe_t S (adjoin F S) :=
{coe := λ x, ⟨x,subset_adjoin F S (subtype.mem x)⟩}
@[mono] lemma adjoin.mono (T : set E) (h : S ⊆ T) : adjoin F S ≤ adjoin F T :=
galois_connection.monotone_l gc h
lemma adjoin_contains_field_as_subfield (F : subfield E) : (F : set E) ⊆ adjoin F S :=
λ x hx, adjoin.algebra_map_mem F S ⟨x, hx⟩
lemma subset_adjoin_of_subset_left {F : subfield E} {T : set E} (HT : T ⊆ F) : T ⊆ adjoin F S :=
λ x hx, (adjoin F S).algebra_map_mem ⟨x, HT hx⟩
lemma subset_adjoin_of_subset_right {T : set E} (H : T ⊆ S) : T ⊆ adjoin F S :=
λ x hx, subset_adjoin F S (H hx)
@[simp] lemma adjoin_empty (F E : Type*) [field F] [field E] [algebra F E] :
adjoin F (∅ : set E) = ⊥ :=
eq_bot_iff.mpr (adjoin_le_iff.mpr (set.empty_subset _))
@[simp] lemma adjoin_univ (F E : Type*) [field F] [field E] [algebra F E] :
adjoin F (set.univ : set E) = ⊤ :=
eq_top_iff.mpr $ subset_adjoin _ _
/-- If `K` is a field with `F ⊆ K` and `S ⊆ K` then `adjoin F S ≤ K`. -/
lemma adjoin_le_subfield {K : subfield E} (HF : set.range (algebra_map F E) ⊆ K)
(HS : S ⊆ K) : (adjoin F S).to_subfield ≤ K :=
begin
apply subfield.closure_le.mpr,
rw set.union_subset_iff,
exact ⟨HF, HS⟩,
end
lemma adjoin_subset_adjoin_iff {F' : Type*} [field F'] [algebra F' E]
{S S' : set E} : (adjoin F S : set E) ⊆ adjoin F' S' ↔
set.range (algebra_map F E) ⊆ adjoin F' S' ∧ S ⊆ adjoin F' S' :=
⟨λ h, ⟨trans (adjoin.range_algebra_map_subset _ _) h, trans (subset_adjoin _ _) h⟩,
λ ⟨hF, hS⟩, subfield.closure_le.mpr (set.union_subset hF hS)⟩
/-- `F[S][T] = F[S ∪ T]` -/
lemma adjoin_adjoin_left (T : set E) : ↑(adjoin (adjoin F S) T) = adjoin F (S ∪ T) :=
begin
rw set_like.ext'_iff,
change ↑(adjoin (adjoin F S) T) = _,
apply set.eq_of_subset_of_subset; rw adjoin_subset_adjoin_iff; split,
{ rintros _ ⟨⟨x, hx⟩, rfl⟩, exact adjoin.mono _ _ _ (set.subset_union_left _ _) hx },
{ exact subset_adjoin_of_subset_right _ _ (set.subset_union_right _ _) },
{ exact subset_adjoin_of_subset_left _ (adjoin.range_algebra_map_subset _ _) },
{ exact set.union_subset
(subset_adjoin_of_subset_left _ (subset_adjoin _ _))
(subset_adjoin _ _) },
end
@[simp] lemma adjoin_insert_adjoin (x : E) :
adjoin F (insert x (adjoin F S : set E)) = adjoin F (insert x S) :=
le_antisymm
(adjoin_le_iff.mpr (set.insert_subset.mpr ⟨subset_adjoin _ _ (set.mem_insert _ _),
adjoin_le_iff.mpr (subset_adjoin_of_subset_right _ _ (set.subset_insert _ _))⟩))
(adjoin.mono _ _ _ (set.insert_subset_insert (subset_adjoin _ _)))
/-- `F[S][T] = F[T][S]` -/
lemma adjoin_adjoin_comm (T : set E) :
↑(adjoin (adjoin F S) T) = (↑(adjoin (adjoin F T) S) : (intermediate_field F E)) :=
by rw [adjoin_adjoin_left, adjoin_adjoin_left, set.union_comm]
lemma adjoin_map {E' : Type*} [field E'] [algebra F E'] (f : E →ₐ[F] E') :
(adjoin F S).map f = adjoin F (f '' S) :=
begin
ext x,
show x ∈ (subfield.closure (set.range (algebra_map F E) ∪ S)).map (f : E →+* E') ↔
x ∈ subfield.closure (set.range (algebra_map F E') ∪ f '' S),
rw [ring_hom.map_field_closure, set.image_union, ← set.range_comp, ← ring_hom.coe_comp,
f.comp_algebra_map],
refl,
end
lemma algebra_adjoin_le_adjoin : algebra.adjoin F S ≤ (adjoin F S).to_subalgebra :=
algebra.adjoin_le (subset_adjoin _ _)
lemma adjoin_eq_algebra_adjoin (inv_mem : ∀ x ∈ algebra.adjoin F S, x⁻¹ ∈ algebra.adjoin F S) :
(adjoin F S).to_subalgebra = algebra.adjoin F S :=
le_antisymm
(show adjoin F S ≤
{ neg_mem' := λ x, (algebra.adjoin F S).neg_mem, inv_mem' := inv_mem, .. algebra.adjoin F S},
from adjoin_le_iff.mpr (algebra.subset_adjoin))
(algebra_adjoin_le_adjoin _ _)
lemma eq_adjoin_of_eq_algebra_adjoin (K : intermediate_field F E)
(h : K.to_subalgebra = algebra.adjoin F S) : K = adjoin F S :=
begin
apply to_subalgebra_injective,
rw h,
refine (adjoin_eq_algebra_adjoin _ _ _).symm,
intros x,
convert K.inv_mem,
rw ← h,
refl
end
@[elab_as_eliminator]
lemma adjoin_induction {s : set E} {p : E → Prop} {x} (h : x ∈ adjoin F s)
(Hs : ∀ x ∈ s, p x) (Hmap : ∀ x, p (algebra_map F E x))
(Hadd : ∀ x y, p x → p y → p (x + y))
(Hneg : ∀ x, p x → p (-x))
(Hinv : ∀ x, p x → p x⁻¹)
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
subfield.closure_induction h (λ x hx, or.cases_on hx (λ ⟨x, hx⟩, hx ▸ Hmap x) (Hs x))
((algebra_map F E).map_one ▸ Hmap 1)
Hadd Hneg Hinv Hmul
/--
Variation on `set.insert` to enable good notation for adjoining elements to fields.
Used to preferentially use `singleton` rather than `insert` when adjoining one element.
-/
--this definition of notation is courtesy of Kyle Miller on zulip
class insert {α : Type*} (s : set α) :=
(insert : α → set α)
@[priority 1000]
instance insert_empty {α : Type*} : insert (∅ : set α) :=
{ insert := λ x, @singleton _ _ set.has_singleton x }
@[priority 900]
instance insert_nonempty {α : Type*} (s : set α) : insert s :=
{ insert := λ x, set.insert x s }
notation K`⟮`:std.prec.max_plus l:(foldr `, ` (h t, insert.insert t h) ∅) `⟯` := adjoin K l
section adjoin_simple
variables (α : E)
lemma mem_adjoin_simple_self : α ∈ F⟮α⟯ :=
subset_adjoin F {α} (set.mem_singleton α)
/-- generator of `F⟮α⟯` -/
def adjoin_simple.gen : F⟮α⟯ := ⟨α, mem_adjoin_simple_self F α⟩
@[simp] lemma adjoin_simple.algebra_map_gen : algebra_map F⟮α⟯ E (adjoin_simple.gen F α) = α := rfl
@[simp] lemma adjoin_simple.is_integral_gen :
is_integral F (adjoin_simple.gen F α) ↔ is_integral F α :=
by { conv_rhs { rw ← adjoin_simple.algebra_map_gen F α },
rw is_integral_algebra_map_iff (algebra_map F⟮α⟯ E).injective,
apply_instance }
lemma adjoin_simple_adjoin_simple (β : E) : ↑F⟮α⟯⟮β⟯ = F⟮α, β⟯ :=
adjoin_adjoin_left _ _ _
lemma adjoin_simple_comm (β : E) : ↑F⟮α⟯⟮β⟯ = (↑F⟮β⟯⟮α⟯ : intermediate_field F E) :=
adjoin_adjoin_comm _ _ _
-- TODO: develop the API for `subalgebra.is_field_of_algebraic` so it can be used here
lemma adjoin_simple_to_subalgebra_of_integral (hα : is_integral F α) :
(F⟮α⟯).to_subalgebra = algebra.adjoin F {α} :=
begin
apply adjoin_eq_algebra_adjoin,
intros x hx,
by_cases x = 0,
{ rw [h, inv_zero], exact subalgebra.zero_mem (algebra.adjoin F {α}) },
let ϕ := alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly F α,
haveI := minpoly.irreducible hα,
suffices : ϕ ⟨x, hx⟩ * (ϕ ⟨x, hx⟩)⁻¹ = 1,
{ convert subtype.mem (ϕ.symm (ϕ ⟨x, hx⟩)⁻¹),
refine inv_eq_of_mul_eq_one_right _,
apply_fun ϕ.symm at this,
rw [alg_equiv.map_one, alg_equiv.map_mul, alg_equiv.symm_apply_apply] at this,
rw [←subsemiring.coe_one, ←this, subsemiring.coe_mul, subtype.coe_mk] },
rw mul_inv_cancel (mt (λ key, _) h),
rw ← ϕ.map_zero at key,
change ↑(⟨x, hx⟩ : algebra.adjoin F {α}) = _,
rw [ϕ.injective key, subalgebra.coe_zero]
end
end adjoin_simple
end adjoin_def
section adjoin_intermediate_field_lattice
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} {S : set E}
@[simp] lemma adjoin_eq_bot_iff : adjoin F S = ⊥ ↔ S ⊆ (⊥ : intermediate_field F E) :=
by { rw [eq_bot_iff, adjoin_le_iff], refl, }
@[simp] lemma adjoin_simple_eq_bot_iff : F⟮α⟯ = ⊥ ↔ α ∈ (⊥ : intermediate_field F E) :=
by { rw adjoin_eq_bot_iff, exact set.singleton_subset_iff }
@[simp] lemma adjoin_zero : F⟮(0 : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (zero_mem ⊥)
@[simp] lemma adjoin_one : F⟮(1 : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (one_mem ⊥)
@[simp] lemma adjoin_int (n : ℤ) : F⟮(n : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n)
@[simp] lemma adjoin_nat (n : ℕ) : F⟮(n : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n)
section adjoin_dim
open finite_dimensional module
variables {K L : intermediate_field F E}
@[simp] lemma dim_eq_one_iff : module.rank F K = 1 ↔ K = ⊥ :=
by rw [← to_subalgebra_eq_iff, ← dim_eq_dim_subalgebra,
subalgebra.dim_eq_one_iff, bot_to_subalgebra]
@[simp] lemma finrank_eq_one_iff : finrank F K = 1 ↔ K = ⊥ :=
by rw [← to_subalgebra_eq_iff, ← finrank_eq_finrank_subalgebra,
subalgebra.finrank_eq_one_iff, bot_to_subalgebra]
@[simp] lemma dim_bot : module.rank F (⊥ : intermediate_field F E) = 1 :=
by rw dim_eq_one_iff
@[simp] lemma finrank_bot : finrank F (⊥ : intermediate_field F E) = 1 :=
by rw finrank_eq_one_iff
lemma dim_adjoin_eq_one_iff : module.rank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) :=
iff.trans dim_eq_one_iff adjoin_eq_bot_iff
lemma dim_adjoin_simple_eq_one_iff : module.rank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) :=
by { rw dim_adjoin_eq_one_iff, exact set.singleton_subset_iff }
lemma finrank_adjoin_eq_one_iff : finrank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) :=
iff.trans finrank_eq_one_iff adjoin_eq_bot_iff
lemma finrank_adjoin_simple_eq_one_iff : finrank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) :=
by { rw [finrank_adjoin_eq_one_iff], exact set.singleton_subset_iff }
/-- If `F⟮x⟯` has dimension `1` over `F` for every `x ∈ E` then `F = E`. -/
lemma bot_eq_top_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) :
(⊥ : intermediate_field F E) = ⊤ :=
begin
ext,
rw iff_true_right intermediate_field.mem_top,
exact dim_adjoin_simple_eq_one_iff.mp (h x),
end
lemma bot_eq_top_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) :
(⊥ : intermediate_field F E) = ⊤ :=
begin
ext,
rw iff_true_right intermediate_field.mem_top,
exact finrank_adjoin_simple_eq_one_iff.mp (h x),
end
lemma subsingleton_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) :
subsingleton (intermediate_field F E) :=
subsingleton_of_bot_eq_top (bot_eq_top_of_dim_adjoin_eq_one h)
lemma subsingleton_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) :
subsingleton (intermediate_field F E) :=
subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_eq_one h)
/-- If `F⟮x⟯` has dimension `≤1` over `F` for every `x ∈ E` then `F = E`. -/
lemma bot_eq_top_of_finrank_adjoin_le_one [finite_dimensional F E]
(h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : (⊥ : intermediate_field F E) = ⊤ :=
begin
apply bot_eq_top_of_finrank_adjoin_eq_one,
exact λ x, by linarith [h x, show 0 < finrank F F⟮x⟯, from finrank_pos],
end
lemma subsingleton_of_finrank_adjoin_le_one [finite_dimensional F E]
(h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : subsingleton (intermediate_field F E) :=
subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_le_one h)
end adjoin_dim
end adjoin_intermediate_field_lattice
section adjoin_integral_element
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E}
variables {K : Type*} [field K] [algebra F K]
lemma minpoly_gen {α : E} (h : is_integral F α) :
minpoly F (adjoin_simple.gen F α) = minpoly F α :=
begin
rw ← adjoin_simple.algebra_map_gen F α at h,
have inj := (algebra_map F⟮α⟯ E).injective,
exact minpoly.eq_of_algebra_map_eq inj ((is_integral_algebra_map_iff inj).mp h)
(adjoin_simple.algebra_map_gen _ _).symm
end
variables (F)
lemma aeval_gen_minpoly (α : E) :
aeval (adjoin_simple.gen F α) (minpoly F α) = 0 :=
begin
ext,
convert minpoly.aeval F α,
conv in (aeval α) { rw [← adjoin_simple.algebra_map_gen F α] },
exact is_scalar_tower.algebra_map_aeval F F⟮α⟯ E _ _
end
/-- algebra isomorphism between `adjoin_root` and `F⟮α⟯` -/
noncomputable def adjoin_root_equiv_adjoin (h : is_integral F α) :
adjoin_root (minpoly F α) ≃ₐ[F] F⟮α⟯ :=
alg_equiv.of_bijective
(adjoin_root.lift_hom (minpoly F α) (adjoin_simple.gen F α) (aeval_gen_minpoly F α))
(begin
set f := adjoin_root.lift _ _ (aeval_gen_minpoly F α : _),
haveI := minpoly.irreducible h,
split,
{ exact ring_hom.injective f },
{ suffices : F⟮α⟯.to_subfield ≤ ring_hom.field_range ((F⟮α⟯.to_subfield.subtype).comp f),
{ exact λ x, Exists.cases_on (this (subtype.mem x)) (λ y hy, ⟨y, subtype.ext hy⟩) },
exact subfield.closure_le.mpr (set.union_subset (λ x hx, Exists.cases_on hx (λ y hy,
⟨y, by { rw [ring_hom.comp_apply, adjoin_root.lift_of], exact hy }⟩))
(set.singleton_subset_iff.mpr ⟨adjoin_root.root (minpoly F α),
by { rw [ring_hom.comp_apply, adjoin_root.lift_root], refl }⟩)) } end)
lemma adjoin_root_equiv_adjoin_apply_root (h : is_integral F α) :
adjoin_root_equiv_adjoin F h (adjoin_root.root (minpoly F α)) =
adjoin_simple.gen F α :=
adjoin_root.lift_root (aeval_gen_minpoly F α)
section power_basis
variables {L : Type*} [field L] [algebra K L]
/-- The elements `1, x, ..., x ^ (d - 1)` form a basis for `K⟮x⟯`,
where `d` is the degree of the minimal polynomial of `x`. -/
noncomputable def power_basis_aux {x : L} (hx : is_integral K x) :
basis (fin (minpoly K x).nat_degree) K K⟮x⟯ :=
(adjoin_root.power_basis (minpoly.ne_zero hx)).basis.map
(adjoin_root_equiv_adjoin K hx).to_linear_equiv
/-- The power basis `1, x, ..., x ^ (d - 1)` for `K⟮x⟯`,
where `d` is the degree of the minimal polynomial of `x`. -/
@[simps]
noncomputable def adjoin.power_basis {x : L} (hx : is_integral K x) :
power_basis K K⟮x⟯ :=
{ gen := adjoin_simple.gen K x,
dim := (minpoly K x).nat_degree,
basis := power_basis_aux hx,
basis_eq_pow := λ i,
by rw [power_basis_aux, basis.map_apply, power_basis.basis_eq_pow,
alg_equiv.to_linear_equiv_apply, alg_equiv.map_pow, adjoin_root.power_basis_gen,
adjoin_root_equiv_adjoin_apply_root] }
lemma adjoin.finite_dimensional {x : L} (hx : is_integral K x) : finite_dimensional K K⟮x⟯ :=
power_basis.finite_dimensional (adjoin.power_basis hx)
lemma adjoin.finrank {x : L} (hx : is_integral K x) :
finite_dimensional.finrank K K⟮x⟯ = (minpoly K x).nat_degree :=
begin
rw power_basis.finrank (adjoin.power_basis hx : _),
refl
end
end power_basis
/-- Algebra homomorphism `F⟮α⟯ →ₐ[F] K` are in bijection with the set of roots
of `minpoly α` in `K`. -/
noncomputable def alg_hom_adjoin_integral_equiv (h : is_integral F α) :
(F⟮α⟯ →ₐ[F] K) ≃ {x // x ∈ ((minpoly F α).map (algebra_map F K)).roots} :=
(adjoin.power_basis h).lift_equiv'.trans ((equiv.refl _).subtype_equiv (λ x,
by rw [adjoin.power_basis_gen, minpoly_gen h, equiv.refl_apply]))
/-- Fintype of algebra homomorphism `F⟮α⟯ →ₐ[F] K` -/
noncomputable def fintype_of_alg_hom_adjoin_integral (h : is_integral F α) :
fintype (F⟮α⟯ →ₐ[F] K) :=
power_basis.alg_hom.fintype (adjoin.power_basis h)
lemma card_alg_hom_adjoin_integral (h : is_integral F α) (h_sep : (minpoly F α).separable)
(h_splits : (minpoly F α).splits (algebra_map F K)) :
@fintype.card (F⟮α⟯ →ₐ[F] K) (fintype_of_alg_hom_adjoin_integral F h) =
(minpoly F α).nat_degree :=
begin
rw alg_hom.card_of_power_basis;
simp only [adjoin.power_basis_dim, adjoin.power_basis_gen, minpoly_gen h, h_sep, h_splits],
end
end adjoin_integral_element
section induction
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E]
/-- An intermediate field `S` is finitely generated if there exists `t : finset E` such that
`intermediate_field.adjoin F t = S`. -/
def fg (S : intermediate_field F E) : Prop := ∃ (t : finset E), adjoin F ↑t = S
lemma fg_adjoin_finset (t : finset E) : (adjoin F (↑t : set E)).fg :=
⟨t, rfl⟩
theorem fg_def {S : intermediate_field F E} : S.fg ↔ ∃ t : set E, set.finite t ∧ adjoin F t = S :=
⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩,
λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩
theorem fg_bot : (⊥ : intermediate_field F E).fg :=
⟨∅, adjoin_empty F E⟩
lemma fg_of_fg_to_subalgebra (S : intermediate_field F E)
(h : S.to_subalgebra.fg) : S.fg :=
begin
cases h with t ht,
exact ⟨t, (eq_adjoin_of_eq_algebra_adjoin _ _ _ ht.symm).symm⟩
end
lemma fg_of_noetherian (S : intermediate_field F E)
[is_noetherian F E] : S.fg :=
S.fg_of_fg_to_subalgebra S.to_subalgebra.fg_of_noetherian
lemma induction_on_adjoin_finset (S : finset E) (P : intermediate_field F E → Prop) (base : P ⊥)
(ih : ∀ (K : intermediate_field F E) (x ∈ S), P K → P ↑K⟮x⟯) : P (adjoin F ↑S) :=
begin
apply finset.induction_on' S,
{ exact base },
{ intros a s h1 _ _ h4,
rw [finset.coe_insert, set.insert_eq, set.union_comm, ←adjoin_adjoin_left],
exact ih (adjoin F s) a h1 h4 }
end
lemma induction_on_adjoin_fg (P : intermediate_field F E → Prop)
(base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯)
(K : intermediate_field F E) (hK : K.fg) : P K :=
begin
obtain ⟨S, rfl⟩ := hK,
exact induction_on_adjoin_finset S P base (λ K x _ hK, ih K x hK),
end
lemma induction_on_adjoin [fd : finite_dimensional F E] (P : intermediate_field F E → Prop)
(base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯)
(K : intermediate_field F E) : P K :=
begin
letI : is_noetherian F E := is_noetherian.iff_fg.2 infer_instance,
exact induction_on_adjoin_fg P base ih K K.fg_of_noetherian
end
end induction
section alg_hom_mk_adjoin_splits
variables (F E K : Type*) [field F] [field E] [field K] [algebra F E] [algebra F K] {S : set E}
/-- Lifts `L → K` of `F → K` -/
def lifts := Σ (L : intermediate_field F E), (L →ₐ[F] K)
variables {F E K}
instance : partial_order (lifts F E K) :=
{ le := λ x y, x.1 ≤ y.1 ∧ (∀ (s : x.1) (t : y.1), (s : E) = t → x.2 s = y.2 t),
le_refl := λ x, ⟨le_refl x.1, λ s t hst, congr_arg x.2 (subtype.ext hst)⟩,
le_trans := λ x y z hxy hyz, ⟨le_trans hxy.1 hyz.1, λ s u hsu, eq.trans
(hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl) (hyz.2 ⟨s, hxy.1 s.mem⟩ u hsu)⟩,
le_antisymm :=
begin
rintros ⟨x1, x2⟩ ⟨y1, y2⟩ ⟨hxy1, hxy2⟩ ⟨hyx1, hyx2⟩,
obtain rfl : x1 = y1 := le_antisymm hxy1 hyx1,
congr,
exact alg_hom.ext (λ s, hxy2 s s rfl),
end }
noncomputable instance : order_bot (lifts F E K) :=
{ bot := ⟨⊥, (algebra.of_id F K).comp (bot_equiv F E).to_alg_hom⟩,
bot_le := λ x, ⟨bot_le, λ s t hst,
begin
cases intermediate_field.mem_bot.mp s.mem with u hu,
rw [show s = (algebra_map F _) u, from subtype.ext hu.symm, alg_hom.commutes],
rw [show t = (algebra_map F _) u, from subtype.ext (eq.trans hu hst).symm, alg_hom.commutes],
end⟩ }
noncomputable instance : inhabited (lifts F E K) := ⟨⊥⟩
lemma lifts.eq_of_le {x y : lifts F E K} (hxy : x ≤ y) (s : x.1) :
x.2 s = y.2 ⟨s, hxy.1 s.mem⟩ := hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl
lemma lifts.exists_max_two {c : set (lifts F E K)} {x y : lifts F E K} (hc : is_chain (≤) c)
(hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) :
∃ z : lifts F E K, z ∈ set.insert ⊥ c ∧ x ≤ z ∧ y ≤ z :=
begin
cases (hc.insert $ λ _ _ _, or.inl bot_le).total hx hy with hxy hyx,
{ exact ⟨y, hy, hxy, le_refl y⟩ },
{ exact ⟨x, hx, le_refl x, hyx⟩ },
end
lemma lifts.exists_max_three {c : set (lifts F E K)} {x y z : lifts F E K} (hc : is_chain (≤) c)
(hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) (hz : z ∈ set.insert ⊥ c) :
∃ w : lifts F E K, w ∈ set.insert ⊥ c ∧ x ≤ w ∧ y ≤ w ∧ z ≤ w :=
begin
obtain ⟨v, hv, hxv, hyv⟩ := lifts.exists_max_two hc hx hy,
obtain ⟨w, hw, hzw, hvw⟩ := lifts.exists_max_two hc hz hv,
exact ⟨w, hw, le_trans hxv hvw, le_trans hyv hvw, hzw⟩,
end
/-- An upper bound on a chain of lifts -/
def lifts.upper_bound_intermediate_field {c : set (lifts F E K)} (hc : is_chain (≤) c) :
intermediate_field F E :=
{ carrier := λ s, ∃ x : (lifts F E K), x ∈ set.insert ⊥ c ∧ (s ∈ x.1 : Prop),
zero_mem' := ⟨⊥, set.mem_insert ⊥ c, zero_mem ⊥⟩,
one_mem' := ⟨⊥, set.mem_insert ⊥ c, one_mem ⊥⟩,
neg_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.neg_mem h⟩⟩ },
inv_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.inv_mem h⟩⟩ },
add_mem' := by
{ rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩,
obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy,
exact ⟨z, hz, z.1.add_mem (hxz.1 ha) (hyz.1 hb)⟩ },
mul_mem' := by
{ rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩,
obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy,
exact ⟨z, hz, z.1.mul_mem (hxz.1 ha) (hyz.1 hb)⟩ },
algebra_map_mem' := λ s, ⟨⊥, set.mem_insert ⊥ c, algebra_map_mem ⊥ s⟩ }
/-- The lift on the upper bound on a chain of lifts -/
noncomputable def lifts.upper_bound_alg_hom {c : set (lifts F E K)} (hc : is_chain (≤) c) :
lifts.upper_bound_intermediate_field hc →ₐ[F] K :=
{ to_fun := λ s, (classical.some s.mem).2 ⟨s, (classical.some_spec s.mem).2⟩,
map_zero' := alg_hom.map_zero _,
map_one' := alg_hom.map_one _,
map_add' := λ s t, begin
obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc
(classical.some_spec s.mem).1 (classical.some_spec t.mem).1
(classical.some_spec (s + t).mem).1,
rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_add],
refl,
end,
map_mul' := λ s t, begin
obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc
(classical.some_spec s.mem).1 (classical.some_spec t.mem).1
(classical.some_spec (s * t).mem).1,
rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_mul],
refl,
end,
commutes' := λ _, alg_hom.commutes _ _ }
/-- An upper bound on a chain of lifts -/
noncomputable def lifts.upper_bound {c : set (lifts F E K)} (hc : is_chain (≤) c) :
lifts F E K :=
⟨lifts.upper_bound_intermediate_field hc, lifts.upper_bound_alg_hom hc⟩
lemma lifts.exists_upper_bound (c : set (lifts F E K)) (hc : is_chain (≤) c) :
∃ ub, ∀ a ∈ c, a ≤ ub :=
⟨lifts.upper_bound hc,
begin
intros x hx,
split,
{ exact λ s hs, ⟨x, set.mem_insert_of_mem ⊥ hx, hs⟩ },
{ intros s t hst,
change x.2 s = (classical.some t.mem).2 ⟨t, (classical.some_spec t.mem).2⟩,
obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc (set.mem_insert_of_mem ⊥ hx)
(classical.some_spec t.mem).1,
rw [lifts.eq_of_le hxz, lifts.eq_of_le hyz],
exact congr_arg z.2 (subtype.ext hst) },
end⟩
/-- Extend a lift `x : lifts F E K` to an element `s : E` whose conjugates are all in `K` -/
noncomputable def lifts.lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s)
(h2 : (minpoly F s).splits (algebra_map F K)) : lifts F E K :=
let h3 : is_integral x.1 s := is_integral_of_is_scalar_tower s h1 in
let key : (minpoly x.1 s).splits x.2.to_ring_hom :=
splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero h1))
((splits_map_iff _ _).mpr (by {convert h2, exact ring_hom.ext (λ y, x.2.commutes y)}))
(minpoly.dvd_map_of_is_scalar_tower _ _ _) in
⟨↑x.1⟮s⟯, (@alg_hom_equiv_sigma F x.1 (↑x.1⟮s⟯ : intermediate_field F E) K _ _ _ _ _ _ _
(intermediate_field.algebra x.1⟮s⟯) (is_scalar_tower.of_algebra_map_eq (λ _, rfl))).inv_fun
⟨x.2, (@alg_hom_adjoin_integral_equiv x.1 _ E _ _ s K _ x.2.to_ring_hom.to_algebra
h3).inv_fun ⟨root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)), by
{ simp_rw [mem_roots (map_ne_zero (minpoly.ne_zero h3)), is_root, ←eval₂_eq_eval_map],
exact map_root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)) }⟩⟩⟩
lemma lifts.le_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s)
(h2 : (minpoly F s).splits (algebra_map F K)) : x ≤ x.lift_of_splits h1 h2 :=
⟨λ z hz, algebra_map_mem x.1⟮s⟯ ⟨z, hz⟩, λ t u htu, eq.symm begin
rw [←(show algebra_map x.1 x.1⟮s⟯ t = u, from subtype.ext htu)],
letI : algebra x.1 K := x.2.to_ring_hom.to_algebra,
exact (alg_hom.commutes _ t),
end⟩
lemma lifts.mem_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s)
(h2 : (minpoly F s).splits (algebra_map F K)) : s ∈ (x.lift_of_splits h1 h2).1 :=
mem_adjoin_simple_self x.1 s
lemma lifts.exists_lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s)
(h2 : (minpoly F s).splits (algebra_map F K)) : ∃ y, x ≤ y ∧ s ∈ y.1 :=
⟨x.lift_of_splits h1 h2, x.le_lifts_of_splits h1 h2, x.mem_lifts_of_splits h1 h2⟩
lemma alg_hom_mk_adjoin_splits
(hK : ∀ s ∈ S, is_integral F (s : E) ∧ (minpoly F s).splits (algebra_map F K)) :
nonempty (adjoin F S →ₐ[F] K) :=
begin
obtain ⟨x : lifts F E K, hx⟩ := zorn_partial_order lifts.exists_upper_bound,
refine ⟨alg_hom.mk (λ s, x.2 ⟨s, adjoin_le_iff.mpr (λ s hs, _) s.mem⟩) x.2.map_one (λ s t,
x.2.map_mul ⟨s, _⟩ ⟨t, _⟩) x.2.map_zero (λ s t, x.2.map_add ⟨s, _⟩ ⟨t, _⟩) x.2.commutes⟩,
rcases (x.exists_lift_of_splits (hK s hs).1 (hK s hs).2) with ⟨y, h1, h2⟩,
rwa hx y h1 at h2
end
lemma alg_hom_mk_adjoin_splits' (hS : adjoin F S = ⊤)
(hK : ∀ x ∈ S, is_integral F (x : E) ∧ (minpoly F x).splits (algebra_map F K)) :
nonempty (E →ₐ[F] K) :=
begin
cases alg_hom_mk_adjoin_splits hK with ϕ,
rw hS at ϕ,
exact ⟨ϕ.comp top_equiv.symm.to_alg_hom⟩,
end
end alg_hom_mk_adjoin_splits
section supremum
lemma le_sup_to_subalgebra {K L : Type*} [field K] [field L] [algebra K L]
(E1 E2 : intermediate_field K L) :
E1.to_subalgebra ⊔ E2.to_subalgebra ≤ (E1 ⊔ E2).to_subalgebra :=
sup_le (show E1 ≤ E1 ⊔ E2, from le_sup_left) (show E2 ≤ E1 ⊔ E2, from le_sup_right)
lemma sup_to_subalgebra {K L : Type*} [field K] [field L] [algebra K L]
(E1 E2 : intermediate_field K L) [h1 : finite_dimensional K E1] [h2 : finite_dimensional K E2] :
(E1 ⊔ E2).to_subalgebra = E1.to_subalgebra ⊔ E2.to_subalgebra :=
begin
let S1 := E1.to_subalgebra,
let S2 := E2.to_subalgebra,
refine le_antisymm (show _ ≤ (S1 ⊔ S2).to_intermediate_field _, from (sup_le (show S1 ≤ _,
from le_sup_left) (show S2 ≤ _, from le_sup_right))) (le_sup_to_subalgebra E1 E2),
suffices : is_field ↥(S1 ⊔ S2),
{ intros x hx,
by_cases hx' : (⟨x, hx⟩ : S1 ⊔ S2) = 0,
{ rw [←subtype.coe_mk x hx, hx', subalgebra.coe_zero, inv_zero],
exact (S1 ⊔ S2).zero_mem },
{ obtain ⟨y, h⟩ := this.mul_inv_cancel hx',
exact (congr_arg (∈ S1 ⊔ S2) $ eq_inv_of_mul_eq_one_right $ subtype.ext_iff.mp h).mp y.2 } },
exact is_field_of_is_integral_of_is_field'
(is_integral_sup.mpr ⟨algebra.is_integral_of_finite K E1, algebra.is_integral_of_finite K E2⟩)
(field.to_is_field K),
end
lemma finite_dimensional_sup {K L : Type*} [field K] [field L] [algebra K L]
(E1 E2 : intermediate_field K L) [h1 : finite_dimensional K E1] [h2 : finite_dimensional K E2] :
finite_dimensional K ↥(E1 ⊔ E2) :=
begin
let g := algebra.tensor_product.product_map E1.val E2.val,
suffices : g.range = (E1 ⊔ E2).to_subalgebra,
{ have h : finite_dimensional K g.range.to_submodule := g.to_linear_map.finite_dimensional_range,
rwa this at h },
rw [algebra.tensor_product.product_map_range, E1.range_val, E2.range_val, sup_to_subalgebra],
end
end supremum
end intermediate_field
section power_basis
variables {K L : Type*} [field K] [field L] [algebra K L]
namespace power_basis
open intermediate_field
/-- `pb.equiv_adjoin_simple` is the equivalence between `K⟮pb.gen⟯` and `L` itself. -/
noncomputable def equiv_adjoin_simple (pb : power_basis K L) :
K⟮pb.gen⟯ ≃ₐ[K] L :=
(adjoin.power_basis pb.is_integral_gen).equiv_of_minpoly pb
(minpoly.eq_of_algebra_map_eq (algebra_map K⟮pb.gen⟯ L).injective
(adjoin.power_basis pb.is_integral_gen).is_integral_gen
(by rw [adjoin.power_basis_gen, adjoin_simple.algebra_map_gen]))
@[simp]
lemma equiv_adjoin_simple_aeval (pb : power_basis K L) (f : K[X]) :
pb.equiv_adjoin_simple (aeval (adjoin_simple.gen K pb.gen) f) = aeval pb.gen f :=
equiv_of_minpoly_aeval _ pb _ f
@[simp]
lemma equiv_adjoin_simple_gen (pb : power_basis K L) :
pb.equiv_adjoin_simple (adjoin_simple.gen K pb.gen) = pb.gen :=
equiv_of_minpoly_gen _ pb _
@[simp]
lemma equiv_adjoin_simple_symm_aeval (pb : power_basis K L) (f : K[X]) :
pb.equiv_adjoin_simple.symm (aeval pb.gen f) = aeval (adjoin_simple.gen K pb.gen) f :=
by rw [equiv_adjoin_simple, equiv_of_minpoly_symm, equiv_of_minpoly_aeval, adjoin.power_basis_gen]
@[simp]
lemma equiv_adjoin_simple_symm_gen (pb : power_basis K L) :
pb.equiv_adjoin_simple.symm pb.gen = (adjoin_simple.gen K pb.gen) :=
by rw [equiv_adjoin_simple, equiv_of_minpoly_symm, equiv_of_minpoly_gen, adjoin.power_basis_gen]
end power_basis
end power_basis
|
3ddce242554c728b53788140531f39af9f67d184 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/monad/limits.lean | 37d516fef5dc968edd75b1da593c2c76cc3f9f8c | [
"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,228 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Bhavik Mehta
-/
import category_theory.monad.adjunction
import category_theory.adjunction.limits
import category_theory.limits.shapes.terminal
/-!
# Limits and colimits in the category of algebras
This file shows that the forgetful functor `forget T : algebra T ⥤ C` for a monad `T : C ⥤ C`
creates limits and creates any colimits which `T` preserves.
This is used to show that `algebra T` has any limits which `C` has, and any colimits which `C` has
and `T` preserves.
This is generalised to the case of a monadic functor `D ⥤ C`.
## TODO
Dualise for the category of coalgebras and comonadic left adjoints.
-/
namespace category_theory
open category
open category_theory.limits
universes v u v₁ v₂ u₁ u₂
-- morphism levels before object levels. See note [category_theory universes].
namespace monad
variables {C : Type u₁} [category.{v₁} C]
variables {T : monad C}
variables {J : Type u} [category.{v} J]
namespace forget_creates_limits
variables (D : J ⥤ algebra T) (c : cone (D ⋙ T.forget)) (t : is_limit c)
/-- (Impl) The natural transformation used to define the new cone -/
@[simps] def γ : (D ⋙ T.forget ⋙ ↑T) ⟶ D ⋙ T.forget := { app := λ j, (D.obj j).a }
/-- (Impl) This new cone is used to construct the algebra structure -/
@[simps π_app] def new_cone : cone (D ⋙ forget T) :=
{ X := T.obj c.X,
π := (functor.const_comp _ _ ↑T).inv ≫ whisker_right c.π T ≫ γ D }
/-- The algebra structure which will be the apex of the new limit cone for `D`. -/
@[simps] def cone_point : algebra T :=
{ A := c.X,
a := t.lift (new_cone D c),
unit' := t.hom_ext $ λ j,
begin
rw [category.assoc, t.fac, new_cone_π_app, ←T.η.naturality_assoc, functor.id_map,
(D.obj j).unit],
dsimp, simp -- See library note [dsimp, simp]
end,
assoc' := t.hom_ext $ λ j,
begin
rw [category.assoc, category.assoc, t.fac (new_cone D c), new_cone_π_app,
←functor.map_comp_assoc, t.fac (new_cone D c), new_cone_π_app, ←T.μ.naturality_assoc,
(D.obj j).assoc, functor.map_comp, category.assoc],
refl,
end }
/-- (Impl) Construct the lifted cone in `algebra T` which will be limiting. -/
@[simps] def lifted_cone : cone D :=
{ X := cone_point D c t,
π := { app := λ j, { f := c.π.app j },
naturality' := λ X Y f, by { ext1, dsimp, erw c.w f, simp } } }
/-- (Impl) Prove that the lifted cone is limiting. -/
@[simps]
def lifted_cone_is_limit : is_limit (lifted_cone D c t) :=
{ lift := λ s,
{ f := t.lift ((forget T).map_cone s),
h' := t.hom_ext $ λ j,
begin
dsimp,
rw [category.assoc, category.assoc, t.fac, new_cone_π_app, ←functor.map_comp_assoc, t.fac,
functor.map_cone_π_app],
apply (s.π.app j).h,
end },
uniq' := λ s m J,
begin
ext1,
apply t.hom_ext,
intro j,
simpa [t.fac ((forget T).map_cone s) j] using congr_arg algebra.hom.f (J j),
end }
end forget_creates_limits
-- Theorem 5.6.5 from [Riehl][riehl2017]
/-- The forgetful functor from the Eilenberg-Moore category creates limits. -/
noncomputable
instance forget_creates_limits : creates_limits_of_size (forget T) :=
{ creates_limits_of_shape := λ J 𝒥, by exactI
{ creates_limit := λ D,
creates_limit_of_reflects_iso (λ c t,
{ lifted_cone := forget_creates_limits.lifted_cone D c t,
valid_lift := cones.ext (iso.refl _) (λ j, (id_comp _).symm),
makes_limit := forget_creates_limits.lifted_cone_is_limit _ _ _ } ) } }
/-- `D ⋙ forget T` has a limit, then `D` has a limit. -/
lemma has_limit_of_comp_forget_has_limit (D : J ⥤ algebra T) [has_limit (D ⋙ forget T)] :
has_limit D :=
has_limit_of_created D (forget T)
namespace forget_creates_colimits
-- Let's hide the implementation details in a namespace
variables {D : J ⥤ algebra T} (c : cocone (D ⋙ forget T)) (t : is_colimit c)
-- We have a diagram D of shape J in the category of algebras, and we assume that we are given a
-- colimit for its image D ⋙ forget T under the forgetful functor, say its apex is L.
-- We'll construct a colimiting coalgebra for D, whose carrier will also be L.
-- To do this, we must find a map TL ⟶ L. Since T preserves colimits, TL is also a colimit.
-- In particular, it is a colimit for the diagram `(D ⋙ forget T) ⋙ T`
-- so to construct a map TL ⟶ L it suffices to show that L is the apex of a cocone for this diagram.
-- In other words, we need a natural transformation from const L to `(D ⋙ forget T) ⋙ T`.
-- But we already know that L is the apex of a cocone for the diagram `D ⋙ forget T`, so it
-- suffices to give a natural transformation `((D ⋙ forget T) ⋙ T) ⟶ (D ⋙ forget T)`:
/--
(Impl)
The natural transformation given by the algebra structure maps, used to construct a cocone `c` with
apex `colimit (D ⋙ forget T)`.
-/
@[simps] def γ : ((D ⋙ forget T) ⋙ ↑T) ⟶ (D ⋙ forget T) := { app := λ j, (D.obj j).a }
/--
(Impl)
A cocone for the diagram `(D ⋙ forget T) ⋙ T` found by composing the natural transformation `γ`
with the colimiting cocone for `D ⋙ forget T`.
-/
@[simps]
def new_cocone : cocone ((D ⋙ forget T) ⋙ ↑T) :=
{ X := c.X,
ι := γ ≫ c.ι }
variables [preserves_colimit (D ⋙ forget T) (T : C ⥤ C)]
/--
(Impl)
Define the map `λ : TL ⟶ L`, which will serve as the structure of the coalgebra on `L`, and
we will show is the colimiting object. We use the cocone constructed by `c` and the fact that
`T` preserves colimits to produce this morphism.
-/
@[reducible]
def lambda : ((T : C ⥤ C).map_cocone c).X ⟶ c.X :=
(is_colimit_of_preserves _ t).desc (new_cocone c)
/-- (Impl) The key property defining the map `λ : TL ⟶ L`. -/
lemma commuting (j : J) :
(T : C ⥤ C).map (c.ι.app j) ≫ lambda c t = (D.obj j).a ≫ c.ι.app j :=
(is_colimit_of_preserves _ t).fac (new_cocone c) j
variables [preserves_colimit ((D ⋙ forget T) ⋙ ↑T) (T : C ⥤ C)]
/--
(Impl)
Construct the colimiting algebra from the map `λ : TL ⟶ L` given by `lambda`. We are required to
show it satisfies the two algebra laws, which follow from the algebra laws for the image of `D` and
our `commuting` lemma.
-/
@[simps] def cocone_point :
algebra T :=
{ A := c.X,
a := lambda c t,
unit' :=
begin
apply t.hom_ext,
intro j,
rw [(show c.ι.app j ≫ T.η.app c.X ≫ _ = T.η.app (D.obj j).A ≫ _ ≫ _,
from T.η.naturality_assoc _ _), commuting, algebra.unit_assoc (D.obj j)],
dsimp, simp -- See library note [dsimp, simp]
end,
assoc' :=
begin
refine (is_colimit_of_preserves _ (is_colimit_of_preserves _ t)).hom_ext (λ j, _),
rw [functor.map_cocone_ι_app, functor.map_cocone_ι_app,
(show (T : C ⥤ C).map ((T : C ⥤ C).map _) ≫ _ ≫ _ = _, from T.μ.naturality_assoc _ _),
←functor.map_comp_assoc, commuting, functor.map_comp, category.assoc, commuting],
apply (D.obj j).assoc_assoc _,
end }
/-- (Impl) Construct the lifted cocone in `algebra T` which will be colimiting. -/
@[simps] def lifted_cocone : cocone D :=
{ X := cocone_point c t,
ι := { app := λ j, { f := c.ι.app j, h' := commuting _ _ _ },
naturality' := λ A B f, by { ext1, dsimp, rw [comp_id], apply c.w } } }
/-- (Impl) Prove that the lifted cocone is colimiting. -/
@[simps]
def lifted_cocone_is_colimit : is_colimit (lifted_cocone c t) :=
{ desc := λ s,
{ f := t.desc ((forget T).map_cocone s),
h' := (is_colimit_of_preserves (T : C ⥤ C) t).hom_ext $ λ j,
begin
dsimp,
rw [←functor.map_comp_assoc, ←category.assoc, t.fac, commuting, category.assoc, t.fac],
apply algebra.hom.h,
end },
uniq' := λ s m J,
by { ext1, apply t.hom_ext, intro j, simpa using congr_arg algebra.hom.f (J j) } }
end forget_creates_colimits
open forget_creates_colimits
-- TODO: the converse of this is true as well
/--
The forgetful functor from the Eilenberg-Moore category for a monad creates any colimit
which the monad itself preserves.
-/
noncomputable
instance forget_creates_colimit (D : J ⥤ algebra T)
[preserves_colimit (D ⋙ forget T) (T : C ⥤ C)]
[preserves_colimit ((D ⋙ forget T) ⋙ ↑T) (T : C ⥤ C)] :
creates_colimit D (forget T) :=
creates_colimit_of_reflects_iso $ λ c t,
{ lifted_cocone :=
{ X := cocone_point c t,
ι :=
{ app := λ j, { f := c.ι.app j, h' := commuting _ _ _ },
naturality' := λ A B f, by { ext1, dsimp, erw [comp_id, c.w] } } },
valid_lift := cocones.ext (iso.refl _) (by tidy),
makes_colimit := lifted_cocone_is_colimit _ _ }
noncomputable
instance forget_creates_colimits_of_shape
[preserves_colimits_of_shape J (T : C ⥤ C)] :
creates_colimits_of_shape J (forget T) :=
{ creates_colimit := λ K, by apply_instance }
noncomputable
instance forget_creates_colimits
[preserves_colimits_of_size.{v u} (T : C ⥤ C)] :
creates_colimits_of_size.{v u} (forget T) :=
{ creates_colimits_of_shape := λ J 𝒥₁, by apply_instance }
/--
For `D : J ⥤ algebra T`, `D ⋙ forget T` has a colimit, then `D` has a colimit provided colimits
of shape `J` are preserved by `T`.
-/
lemma forget_creates_colimits_of_monad_preserves
[preserves_colimits_of_shape J (T : C ⥤ C)] (D : J ⥤ algebra T) [has_colimit (D ⋙ forget T)] :
has_colimit D :=
has_colimit_of_created D (forget T)
end monad
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
variables {J : Type u} [category.{v} J]
instance comp_comparison_forget_has_limit
(F : J ⥤ D) (R : D ⥤ C) [monadic_right_adjoint R] [has_limit (F ⋙ R)] :
has_limit ((F ⋙ monad.comparison (adjunction.of_right_adjoint R)) ⋙ monad.forget _) :=
@has_limit_of_iso _ _ _ _ (F ⋙ R) _ _
(iso_whisker_left F (monad.comparison_forget (adjunction.of_right_adjoint R)).symm)
instance comp_comparison_has_limit
(F : J ⥤ D) (R : D ⥤ C) [monadic_right_adjoint R] [has_limit (F ⋙ R)] :
has_limit (F ⋙ monad.comparison (adjunction.of_right_adjoint R)) :=
monad.has_limit_of_comp_forget_has_limit (F ⋙ monad.comparison (adjunction.of_right_adjoint R))
/-- Any monadic functor creates limits. -/
noncomputable
def monadic_creates_limits (R : D ⥤ C) [monadic_right_adjoint R] :
creates_limits_of_size.{v u} R :=
creates_limits_of_nat_iso (monad.comparison_forget (adjunction.of_right_adjoint R))
/--
The forgetful functor from the Eilenberg-Moore category for a monad creates any colimit
which the monad itself preserves.
-/
noncomputable
def monadic_creates_colimit_of_preserves_colimit (R : D ⥤ C) (K : J ⥤ D)
[monadic_right_adjoint R]
[preserves_colimit (K ⋙ R) (left_adjoint R ⋙ R)]
[preserves_colimit ((K ⋙ R) ⋙ left_adjoint R ⋙ R) (left_adjoint R ⋙ R)] :
creates_colimit K R :=
begin
apply creates_colimit_of_nat_iso (monad.comparison_forget (adjunction.of_right_adjoint R)),
apply category_theory.comp_creates_colimit _ _,
apply_instance,
let i : ((K ⋙ monad.comparison (adjunction.of_right_adjoint R)) ⋙ monad.forget _) ≅ K ⋙ R :=
functor.associator _ _ _ ≪≫
iso_whisker_left K (monad.comparison_forget (adjunction.of_right_adjoint R)),
apply category_theory.monad.forget_creates_colimit _,
{ dsimp,
refine preserves_colimit_of_iso_diagram _ i.symm },
{ dsimp,
refine preserves_colimit_of_iso_diagram _ (iso_whisker_right i (left_adjoint R ⋙ R)).symm },
end
/-- A monadic functor creates any colimits of shapes it preserves. -/
noncomputable
def monadic_creates_colimits_of_shape_of_preserves_colimits_of_shape (R : D ⥤ C)
[monadic_right_adjoint R] [preserves_colimits_of_shape J R] : creates_colimits_of_shape J R :=
begin
have : preserves_colimits_of_shape J (left_adjoint R ⋙ R),
{ apply category_theory.limits.comp_preserves_colimits_of_shape _ _,
apply (adjunction.left_adjoint_preserves_colimits (adjunction.of_right_adjoint R)).1,
apply_instance },
exactI ⟨λ K, monadic_creates_colimit_of_preserves_colimit _ _⟩,
end
/-- A monadic functor creates colimits if it preserves colimits. -/
noncomputable
def monadic_creates_colimits_of_preserves_colimits (R : D ⥤ C) [monadic_right_adjoint R]
[preserves_colimits_of_size.{v u} R] : creates_colimits_of_size.{v u} R :=
{ creates_colimits_of_shape := λ J 𝒥₁,
by exactI monadic_creates_colimits_of_shape_of_preserves_colimits_of_shape _ }
section
lemma has_limit_of_reflective (F : J ⥤ D) (R : D ⥤ C) [has_limit (F ⋙ R)] [reflective R] :
has_limit F :=
by { haveI := monadic_creates_limits.{v u} R, exact has_limit_of_created F R }
/-- If `C` has limits of shape `J` then any reflective subcategory has limits of shape `J`. -/
lemma has_limits_of_shape_of_reflective [has_limits_of_shape J C] (R : D ⥤ C) [reflective R] :
has_limits_of_shape J D :=
{ has_limit := λ F, has_limit_of_reflective F R }
/-- If `C` has limits then any reflective subcategory has limits. -/
lemma has_limits_of_reflective (R : D ⥤ C) [has_limits_of_size.{v u} C] [reflective R] :
has_limits_of_size.{v u} D :=
{ has_limits_of_shape := λ J 𝒥₁, by exactI has_limits_of_shape_of_reflective R }
/-- If `C` has colimits of shape `J` then any reflective subcategory has colimits of shape `J`. -/
lemma has_colimits_of_shape_of_reflective (R : D ⥤ C)
[reflective R] [has_colimits_of_shape J C] : has_colimits_of_shape J D :=
{ has_colimit := λ F,
begin
let c := (left_adjoint R).map_cocone (colimit.cocone (F ⋙ R)),
letI : preserves_colimits_of_shape J _ :=
(adjunction.of_right_adjoint R).left_adjoint_preserves_colimits.1,
let t : is_colimit c := is_colimit_of_preserves (left_adjoint R) (colimit.is_colimit _),
apply has_colimit.mk ⟨_, (is_colimit.precompose_inv_equiv _ _).symm t⟩,
apply (iso_whisker_left F (as_iso (adjunction.of_right_adjoint R).counit) : _) ≪≫ F.right_unitor,
end }
/-- If `C` has colimits then any reflective subcategory has colimits. -/
lemma has_colimits_of_reflective (R : D ⥤ C) [reflective R] [has_colimits_of_size.{v u} C] :
has_colimits_of_size.{v u} D :=
{ has_colimits_of_shape := λ J 𝒥, by exactI has_colimits_of_shape_of_reflective R }
/--
The reflector always preserves terminal objects. Note this in general doesn't apply to any other
limit.
-/
noncomputable def left_adjoint_preserves_terminal_of_reflective (R : D ⥤ C) [reflective R] :
preserves_limits_of_shape (discrete.{v} pempty) (left_adjoint R) :=
{ preserves_limit := λ K, let F := functor.empty.{v} D in
begin
apply preserves_limit_of_iso_diagram _ (functor.empty_ext (F ⋙ R) _),
fsplit, intros c h, haveI : has_limit (F ⋙ R) := ⟨⟨⟨c,h⟩⟩⟩,
haveI : has_limit F := has_limit_of_reflective F R,
apply is_limit_change_empty_cone D (limit.is_limit F),
apply (as_iso ((adjunction.of_right_adjoint R).counit.app _)).symm.trans,
{ apply (left_adjoint R).map_iso, letI := monadic_creates_limits.{v v} R,
let := (category_theory.preserves_limit_of_creates_limit_and_has_limit F R).preserves,
apply (this (limit.is_limit F)).cone_point_unique_up_to_iso h },
apply_instance,
end }
end
end category_theory
|
d797c12761aac259565f7808b22a168cf57b46e2 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/order/complete_lattice.lean | 89bb6e5baaa1f4b4baf49fea0f9ecd1f17e56e1c | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 40,972 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import order.bounds
/-!
# Theory of complete lattices
## Main definitions
* `Sup` and `Inf` are the supremum and the infimum of a set;
* `supr (f : ι → α)` and `infi (f : ι → α)` are indexed supremum and infimum of a function,
defined as `Sup` and `Inf` of the range of this function;
* `class complete_lattice`: a bounded lattice such that `Sup s` is always the least upper boundary
of `s` and `Inf s` is always the greatest lower boundary of `s`;
* `class complete_linear_order`: a linear ordered complete lattice.
## Naming conventions
We use `Sup`/`Inf`/`supr`/`infi` for the corresponding functions in the statement. Sometimes we
also use `bsupr`/`binfi` for "bounded` supremum or infimum, i.e. one of `⨆ i ∈ s, f i`,
`⨆ i (hi : p i), f i`, or more generally `⨆ i (hi : p i), f i hi`.
## Notation
* `⨆ i, f i` : `supr f`, the supremum of the range of `f`;
* `⨅ i, f i` : `infi f`, the infimum of the range of `f`.
-/
set_option old_structure_cmd true
open set
variables {α β β₂ : Type*} {ι ι₂ : Sort*}
/-- class for the `Sup` operator -/
class has_Sup (α : Type*) := (Sup : set α → α)
/-- class for the `Inf` operator -/
class has_Inf (α : Type*) := (Inf : set α → α)
export has_Sup (Sup) has_Inf (Inf)
/-- Supremum of a set -/
add_decl_doc has_Sup.Sup
/-- Infimum of a set -/
add_decl_doc has_Inf.Inf
/-- Indexed supremum -/
def supr [has_Sup α] (s : ι → α) : α := Sup (range s)
/-- Indexed infimum -/
def infi [has_Inf α] (s : ι → α) : α := Inf (range s)
@[priority 50] instance has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩
@[priority 50] instance has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩
notation `⨆` binders `, ` r:(scoped f, supr f) := r
notation `⨅` binders `, ` r:(scoped f, infi f) := r
instance (α) [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩
instance (α) [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A complete lattice is a bounded lattice which
has suprema and infima for every subset. -/
class complete_lattice (α : Type*) extends bounded_lattice α, has_Sup α, has_Inf α :=
(le_Sup : ∀s, ∀a∈s, a ≤ Sup s)
(Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a)
(Inf_le : ∀s, ∀a∈s, Inf s ≤ a)
(le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s)
/-- Create a `complete_lattice` from a `partial_order` and `Inf` function
that returns the greatest lower bound of a set. Usually this constructor provides
poor definitional equalities, so it should be used with
`.. complete_lattice_of_Inf α _`. -/
def complete_lattice_of_Inf (α : Type*) [H1 : partial_order α]
[H2 : has_Inf α] (is_glb_Inf : ∀ s : set α, is_glb s (Inf s)) :
complete_lattice α :=
{ bot := Inf univ,
bot_le := λ x, (is_glb_Inf univ).1 trivial,
top := Inf ∅,
le_top := λ a, (is_glb_Inf ∅).2 $ by simp,
sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x},
inf := λ a b, Inf {a, b},
le_inf := λ a b c hab hac, by { apply (is_glb_Inf _).2, simp [*] },
inf_le_right := λ a b, (is_glb_Inf _).1 $ mem_insert_of_mem _ $ mem_singleton _,
inf_le_left := λ a b, (is_glb_Inf _).1 $ mem_insert _ _,
sup_le := λ a b c hac hbc, (is_glb_Inf _).1 $ by simp [*],
le_sup_left := λ a b, (is_glb_Inf _).2 $ λ x, and.left,
le_sup_right := λ a b, (is_glb_Inf _).2 $ λ x, and.right,
le_Inf := λ s a ha, (is_glb_Inf s).2 ha,
Inf_le := λ s a ha, (is_glb_Inf s).1 ha,
Sup := λ s, Inf (upper_bounds s),
le_Sup := λ s a ha, (is_glb_Inf (upper_bounds s)).2 $ λ b hb, hb ha,
Sup_le := λ s a ha, (is_glb_Inf (upper_bounds s)).1 ha,
.. H1, .. H2 }
/-- Create a `complete_lattice` from a `partial_order` and `Sup` function
that returns the least upper bound of a set. Usually this constructor provides
poor definitional equalities, so it should be used with
`.. complete_lattice_of_Sup α _`. -/
def complete_lattice_of_Sup (α : Type*) [H1 : partial_order α]
[H2 : has_Sup α] (is_lub_Sup : ∀ s : set α, is_lub s (Sup s)) :
complete_lattice α :=
{ top := Sup univ,
le_top := λ x, (is_lub_Sup univ).1 trivial,
bot := Sup ∅,
bot_le := λ x, (is_lub_Sup ∅).2 $ by simp,
sup := λ a b, Sup {a, b},
sup_le := λ a b c hac hbc, (is_lub_Sup _).2 (by simp [*]),
le_sup_left := λ a b, (is_lub_Sup _).1 $ mem_insert _ _,
le_sup_right := λ a b, (is_lub_Sup _).1 $ mem_insert_of_mem _ $ mem_singleton _,
inf := λ a b, Sup {x | x ≤ a ∧ x ≤ b},
le_inf := λ a b c hab hac, (is_lub_Sup _).1 $ by simp [*],
inf_le_left := λ a b, (is_lub_Sup _).2 (λ x, and.left),
inf_le_right := λ a b, (is_lub_Sup _).2 (λ x, and.right),
Inf := λ s, Sup (lower_bounds s),
Sup_le := λ s a ha, (is_lub_Sup s).2 ha,
le_Sup := λ s a ha, (is_lub_Sup s).1 ha,
Inf_le := λ s a ha, (is_lub_Sup (lower_bounds s)).2 (λ b hb, hb ha),
le_Inf := λ s a ha, (is_lub_Sup (lower_bounds s)).1 ha,
.. H1, .. H2 }
/-- A complete linear order is a linear order whose lattice structure is complete. -/
class complete_linear_order (α : Type*) extends complete_lattice α, decidable_linear_order α
end prio
section
variables [complete_lattice α] {s t : set α} {a b : α}
@[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a
theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a
@[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a
theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a
lemma is_lub_Sup (s : set α) : is_lub s (Sup s) := ⟨assume x, le_Sup, assume x, Sup_le⟩
lemma is_lub.Sup_eq (h : is_lub s a) : Sup s = a := (is_lub_Sup s).unique h
lemma is_glb_Inf (s : set α) : is_glb s (Inf s) := ⟨assume a, Inf_le, assume a, le_Inf⟩
lemma is_glb.Inf_eq (h : is_glb s a) : Inf s = a := (is_glb_Inf s).unique h
theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s :=
le_trans h (le_Sup hb)
theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a :=
le_trans (Inf_le hb) h
theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t :=
(is_lub_Sup s).mono (is_lub_Sup t) h
theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s :=
(is_glb_Inf s).mono (is_glb_Inf t) h
@[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) :=
is_lub_le_iff (is_lub_Sup s)
@[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) :=
le_is_glb_iff (is_glb_Inf s)
theorem Inf_le_Sup (hs : s.nonempty) : Inf s ≤ Sup s :=
is_glb_le_is_lub (is_glb_Inf s) (is_lub_Sup s) hs
-- TODO: it is weird that we have to add union_def
theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t :=
((is_lub_Sup s).union (is_lub_Sup t)).Sup_eq
theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t :=
by finish
/-
Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t))
-/
theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t :=
((is_glb_Inf s).union (is_glb_Inf t)).Inf_eq
theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) :=
by finish
/-
le_Inf (assume a ⟨a_s, a_t⟩, sup_le (Inf_le a_s) (Inf_le a_t))
-/
@[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) :=
is_lub_empty.Sup_eq
@[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) :=
(@is_glb_empty α _).Inf_eq
@[simp] theorem Sup_univ : Sup univ = (⊤ : α) :=
(@is_lub_univ α _).Sup_eq
@[simp] theorem Inf_univ : Inf univ = (⊥ : α) :=
is_glb_univ.Inf_eq
-- TODO(Jeremy): get this automatically
@[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s :=
((is_lub_Sup s).insert a).Sup_eq
@[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s :=
((is_glb_Inf s).insert a).Inf_eq
-- We will generalize this to conditionally complete lattices in `cSup_singleton`.
theorem Sup_singleton {a : α} : Sup {a} = a :=
is_lub_singleton.Sup_eq
-- We will generalize this to conditionally complete lattices in `cInf_singleton`.
theorem Inf_singleton {a : α} : Inf {a} = a :=
is_glb_singleton.Inf_eq
theorem Sup_pair {a b : α} : Sup {a, b} = a ⊔ b :=
(@is_lub_pair α _ a b).Sup_eq
theorem Inf_pair {a b : α} : Inf {a, b} = a ⊓ b :=
(@is_glb_pair α _ a b).Inf_eq
@[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) :=
iff.intro
(assume h a ha, top_unique $ h ▸ Inf_le ha)
(assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha)
@[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) :=
iff.intro
(assume h a ha, bot_unique $ h ▸ le_Sup ha)
(assume h, bot_unique $ Sup_le $ assume a ha, le_bot_iff.2 $ h a ha)
end
section complete_linear_order
variables [complete_linear_order α] {s t : set α} {a b : α}
lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) :=
is_glb_lt_iff (is_glb_Inf s)
lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) :=
lt_is_lub_iff (is_lub_Sup s)
lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) :=
iff.intro
(assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb)
(assume h, top_unique $ le_of_not_gt $ assume h',
let ⟨a, ha, h⟩ := h _ h' in
lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h)
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) :=
iff.intro
(assume (h : Inf s = ⊥) b (hb : ⊥ < b), by rwa [←h, Inf_lt_iff] at hb)
(assume h, bot_unique $ le_of_not_gt $ assume h',
let ⟨a, ha, h⟩ := h _ h' in
lt_irrefl a $ lt_of_lt_of_le h (Inf_le ha))
lemma lt_supr_iff {f : ι → α} : a < supr f ↔ (∃i, a < f i) :=
lt_Sup_iff.trans exists_range_iff
lemma infi_lt_iff {f : ι → α} : infi f < a ↔ (∃i, f i < a) :=
Inf_lt_iff.trans exists_range_iff
end complete_linear_order
/- supr & infi -/
section
variables [complete_lattice α] {s t : ι → α} {a b : α}
-- TODO: this declaration gives error when starting smt state
--@[ematch]
theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s :=
le_Sup ⟨i, rfl⟩
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) :=
le_Sup ⟨i, rfl⟩
/- TODO: this version would be more powerful, but, alas, the pattern matcher
doesn't accept it.
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) :=
le_Sup ⟨i, rfl⟩
-/
lemma is_lub_supr : is_lub (range s) (⨆j, s j) := is_lub_Sup _
lemma is_lub.supr_eq (h : is_lub (range s) a) : (⨆j, s j) = a := h.Sup_eq
lemma is_glb_infi : is_glb (range s) (⨅j, s j) := is_glb_Inf _
lemma is_glb.infi_eq (h : is_glb (range s) a) : (⨅j, s j) = a := h.Inf_eq
theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s :=
le_trans h (le_supr _ i)
theorem le_bsupr {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) :
f i hi ≤ ⨆ i hi, f i hi :=
le_supr_of_le i $ le_supr (f i) hi
theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a :=
Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i
theorem bsupr_le {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ a) :
(⨆ i (hi : p i), f i hi) ≤ a :=
supr_le $ λ i, supr_le $ h i
theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t :=
supr_le $ assume i, le_supr_of_le i (h i)
theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t :=
supr_le $ assume j, exists.elim (h j) le_supr_of_le
theorem bsupr_le_bsupr {p : ι → Prop} {f g : Π i (hi : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) :
(⨆ i hi, f i hi) ≤ ⨆ i hi, g i hi :=
bsupr_le $ λ i hi, le_trans (h i hi) (le_bsupr i hi)
theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) :=
supr_le $ le_supr _ ∘ h
@[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) :=
(is_lub_le_iff is_lub_supr).trans forall_range_iff
theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) :=
le_antisymm
(Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h)
(supr_le $ assume b, supr_le $ assume h, le_Sup h)
lemma le_supr_iff : (a ≤ supr s) ↔ (∀ b, (∀ i, s i ≤ b) → a ≤ b) :=
⟨λ h b hb, le_trans h (supr_le hb), λ h, h _ $ λ i, le_supr s i⟩
lemma monotone.le_map_supr [complete_lattice β] {f : α → β} (hf : monotone f) :
(⨆ i, f (s i)) ≤ f (supr s) :=
supr_le $ λ i, hf $ le_supr _ _
lemma monotone.le_map_supr2 [complete_lattice β] {f : α → β} (hf : monotone f)
{ι' : ι → Sort*} (s : Π i, ι' i → α) :
(⨆ i (h : ι' i), f (s i h)) ≤ f (⨆ i (h : ι' i), s i h) :=
calc (⨆ i h, f (s i h)) ≤ (⨆ i, f (⨆ h, s i h)) :
supr_le_supr $ λ i, hf.le_map_supr
... ≤ f (⨆ i (h : ι' i), s i h) : hf.le_map_supr
lemma monotone.le_map_Sup [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) :
(⨆a∈s, f a) ≤ f (Sup s) :=
by rw [Sup_eq_supr]; exact hf.le_map_supr2 _
lemma supr_comp_le {ι' : Sort*} (f : ι' → α) (g : ι → ι') :
(⨆ x, f (g x)) ≤ ⨆ y, f y :=
supr_le_supr2 $ λ x, ⟨_, le_refl _⟩
lemma monotone.supr_comp_eq [preorder β] {f : β → α} (hf : monotone f)
{s : ι → β} (hs : ∀ x, ∃ i, x ≤ s i) :
(⨆ x, f (s x)) = ⨆ y, f y :=
le_antisymm (supr_comp_le _ _) (supr_le_supr2 $ λ x, (hs x).imp $ λ i hi, hf hi)
lemma function.surjective.supr_comp {α : Type*} [has_Sup α] {f : ι → ι₂}
(hf : function.surjective f) (g : ι₂ → α) :
(⨆ x, g (f x)) = ⨆ y, g y :=
by simp only [supr, hf.range_comp]
-- TODO: finish doesn't do well here.
@[congr] theorem supr_congr_Prop {α : Type*} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ :=
begin
have : f₁ ∘ pq.mpr = f₂ := funext f,
rw [← this],
refine (function.surjective.supr_comp (λ h, ⟨pq.1 h, _⟩) f₁).symm,
refl
end
theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i :=
Inf_le ⟨i, rfl⟩
@[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) :=
Inf_le ⟨i, rfl⟩
/- I wanted to see if this would help for infi_comm; it doesn't.
@[ematch] theorem infi_le₂' (s : ι → ι₂ → α) (i : ι) (j : ι₂) : (: ⨅ i j, s i j :) ≤ (: s i j :) :=
begin
transitivity,
apply (infi_le (λ i, ⨅ j, s i j) i),
apply infi_le
end
-/
theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a :=
le_trans (infi_le _ i) h
theorem binfi_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) :
(⨅ i hi, f i hi) ≤ f i hi :=
infi_le_of_le i $ infi_le (f i) hi
theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s :=
le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i
theorem le_binfi {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, a ≤ f i hi) :
a ≤ ⨅ i hi, f i hi :=
le_infi $ λ i, le_infi $ h i
theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t :=
le_infi $ assume i, infi_le_of_le i (h i)
theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t :=
le_infi $ assume j, exists.elim (h j) infi_le_of_le
theorem binfi_le_binfi {p : ι → Prop} {f g : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) :
(⨅ i hi, f i hi) ≤ ⨅ i hi, g i hi :=
le_binfi $ λ i hi, le_trans (binfi_le i hi) (h i hi)
theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) :=
le_infi $ infi_le _ ∘ h
@[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) :=
⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩
theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) :=
le_antisymm
(le_infi $ assume b, le_infi $ assume h, Inf_le h)
(le_Inf $ assume b h, infi_le_of_le b $ infi_le _ h)
lemma monotone.map_infi_le [complete_lattice β] {f : α → β} (hf : monotone f) :
f (infi s) ≤ (⨅ i, f (s i)) :=
le_infi $ λ i, hf $ infi_le _ _
lemma monotone.map_infi2_le [complete_lattice β] {f : α → β} (hf : monotone f)
{ι' : ι → Sort*} (s : Π i, ι' i → α) :
f (⨅ i (h : ι' i), s i h) ≤ (⨅ i (h : ι' i), f (s i h)) :=
calc f (⨅ i (h : ι' i), s i h) ≤ (⨅ i, f (⨅ h, s i h)) : hf.map_infi_le
... ≤ (⨅ i h, f (s i h)) : infi_le_infi $ λ i, hf.map_infi_le
lemma monotone.map_Inf_le [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) :
f (Inf s) ≤ ⨅ a∈s, f a :=
by rw [Inf_eq_infi]; exact hf.map_infi2_le _
lemma le_infi_comp {ι' : Sort*} (f : ι' → α) (g : ι → ι') :
(⨅ y, f y) ≤ ⨅ x, f (g x) :=
infi_le_infi2 $ λ x, ⟨_, le_refl _⟩
lemma monotone.infi_comp_eq [preorder β] {f : β → α} (hf : monotone f)
{s : ι → β} (hs : ∀ x, ∃ i, s i ≤ x) :
(⨅ x, f (s x)) = ⨅ y, f y :=
le_antisymm (infi_le_infi2 $ λ x, (hs x).imp $ λ i hi, hf hi) (le_infi_comp _ _)
lemma function.surjective.infi_comp {α : Type*} [has_Inf α] {f : ι → ι₂}
(hf : function.surjective f) (g : ι₂ → α) :
(⨅ x, g (f x)) = ⨅ y, g y :=
@function.surjective.supr_comp _ _ (order_dual α) _ f hf g
@[congr] theorem infi_congr_Prop {α : Type*} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ :=
@supr_congr_Prop (order_dual α) _ p q f₁ f₂ pq f
-- We will generalize this to conditionally complete lattices in `cinfi_const`.
theorem infi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a :=
by rw [infi, range_const, Inf_singleton]
-- We will generalize this to conditionally complete lattices in `csupr_const`.
theorem supr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a :=
by rw [supr, range_const, Sup_singleton]
@[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ :=
top_unique $ le_infi $ assume i, le_refl _
@[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ :=
bot_unique $ supr_le $ assume i, le_refl _
@[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) :=
iff.intro
(assume eq i, top_unique $ eq ▸ infi_le _ _)
(assume h, top_unique $ le_infi $ assume i, top_le_iff.2 $ h i)
@[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) :=
iff.intro
(assume eq i, bot_unique $ eq ▸ le_supr _ _)
(assume h, bot_unique $ supr_le $ assume i, le_bot_iff.2 $ h i)
@[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp :=
le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _)
@[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ :=
le_antisymm le_top $ le_infi $ assume h, (hp h).elim
@[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp :=
le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _)
@[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ :=
le_antisymm (supr_le $ assume h, (hp h).elim) bot_le
lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) :
(⨆h:p, a h) = (if h : p then a h else ⊥) :=
by by_cases p; simp [h]
lemma supr_eq_if {p : Prop} [decidable p] (a : α) :
(⨆h:p, a) = (if p then a else ⊥) :=
by rw [supr_eq_dif, dif_eq_if]
lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) :
(⨅h:p, a h) = (if h : p then a h else ⊤) :=
by by_cases p; simp [h]
lemma infi_eq_if {p : Prop} [decidable p] (a : α) :
(⨅h:p, a) = (if p then a else ⊤) :=
by rw [infi_eq_dif, dif_eq_if]
-- TODO: should this be @[simp]?
theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i)
(le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j)
/- TODO: this is strange. In the proof below, we get exactly the desired
among the equalities, but close does not get it.
begin
apply @le_antisymm,
simp, intros,
begin [smt]
ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i),
trace_state, close
end
end
-/
-- TODO: should this be @[simp]?
theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) :=
le_antisymm
(supr_le $ assume i, supr_le $ assume j, le_supr_of_le j $ le_supr _ i)
(supr_le $ assume j, supr_le $ assume i, le_supr_of_le i $ le_supr _ j)
@[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
@[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
attribute [ematch] le_refl
theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) :=
le_antisymm
(le_inf
(le_infi $ assume i, infi_le_of_le i inf_le_left)
(le_infi $ assume i, infi_le_of_le i inf_le_right))
(le_infi $ assume i, le_inf
(inf_le_left_of_le $ infi_le _ _)
(inf_le_right_of_le $ infi_le _ _))
/- TODO: here is another example where more flexible pattern matching
might help.
begin
apply @le_antisymm,
safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end
end
-/
lemma infi_inf {f : ι → α} {a : α} (i : ι) : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) :=
le_antisymm
(le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) inf_le_right)
(le_inf (infi_le_infi $ assume i, inf_le_left) (infi_le_of_le i inf_le_right))
lemma inf_infi {f : ι → α} {a : α} (i : ι) : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) :=
by rw [inf_comm, infi_inf i]; simp [inf_comm]
lemma binfi_inf {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} {i : ι} (hi : p i) :
(⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume hi,
le_inf (inf_le_left_of_le $ infi_le_of_le i $ infi_le _ _) inf_le_right)
(le_inf (infi_le_infi $ assume i, infi_le_infi $ assume hi, inf_le_left)
(infi_le_of_le i $ infi_le_of_le hi $ inf_le_right))
theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) :=
le_antisymm
(supr_le $ assume i, sup_le
(le_sup_left_of_le $ le_supr _ _)
(le_sup_right_of_le $ le_supr _ _))
(sup_le
(supr_le $ assume i, le_supr_of_le i le_sup_left)
(supr_le $ assume i, le_supr_of_le i le_sup_right))
/- supr and infi under Prop -/
@[simp] theorem infi_false {s : false → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, false.elim i)
@[simp] theorem supr_false {s : false → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, false.elim i) bot_le
@[simp] theorem infi_true {s : true → α} : infi s = s trivial :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_true {s : true → α} : supr s = s trivial :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
@[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
@[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
/-- The symmetric case of `infi_and`, useful for rewriting into a infimum over a conjunction -/
lemma infi_and' {p q : Prop} {s : p → q → α} :
(⨅ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨅ (h : p ∧ q), s h.1 h.2 :=
by { symmetry, exact infi_and }
theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, s ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
/-- The symmetric case of `supr_and`, useful for rewriting into a supremum over a conjunction -/
lemma supr_and' {p q : Prop} {s : p → q → α} :
(⨆ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨆ (h : p ∧ q), s h.1 h.2 :=
by { symmetry, exact supr_and }
theorem infi_or {p q : Prop} {s : p ∨ q → α} :
infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume i, match i with
| or.inl i := inf_le_left_of_le $ infi_le _ _
| or.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_or {p q : Prop} {s : p ∨ q → α} :
(⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| or.inl i := le_sup_left_of_le $ le_supr _ i
| or.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨or.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨or.inr j, le_refl _⟩))
lemma Sup_range {α : Type*} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl
lemma Inf_range {α : Type*} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl
lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) :=
le_antisymm
(supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i)
(supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _))
lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) :=
le_antisymm
(le_infi $ assume i, infi_le_of_le (f i) $ infi_le (λp, g (f i)) (mem_range_self _))
(le_infi $ assume b, le_infi $ assume ⟨i, (h : f i = b)⟩, h ▸ infi_le _ i)
theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) :=
calc Inf (set.image f s) = (⨅a, ⨅h : ∃b, b ∈ s ∧ f b = a, a) : Inf_eq_infi
... = (⨅a, ⨅b, ⨅h : f b = a ∧ b ∈ s, a) : by simp [and_comm]
... = (⨅a, ⨅b, ⨅h : a = f b, ⨅h : b ∈ s, a) : by simp [infi_and, eq_comm]
... = (⨅b, ⨅a, ⨅h : a = f b, ⨅h : b ∈ s, a) : by rw [infi_comm]
... = (⨅a∈s, f a) : congr_arg infi $ by funext x; rw [infi_infi_eq_left]
theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) :=
calc Sup (set.image f s) = (⨆a, ⨆h : ∃b, b ∈ s ∧ f b = a, a) : Sup_eq_supr
... = (⨆a, ⨆b, ⨆h : f b = a ∧ b ∈ s, a) : by simp [and_comm]
... = (⨆a, ⨆b, ⨆h : a = f b, ⨆h : b ∈ s, a) : by simp [supr_and, eq_comm]
... = (⨆b, ⨆a, ⨆h : a = f b, ⨆h : b ∈ s, a) : by rw [supr_comm]
... = (⨆a∈s, f a) : congr_arg supr $ by funext x; rw [supr_supr_eq_left]
/- supr and infi under set constructions -/
theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ :=
by simp
theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ :=
by simp
theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) :=
by simp
theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) :=
by simp
theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) :=
calc (⨅ x ∈ s ∪ t, f x) = (⨅ x, (⨅h : x∈s, f x) ⊓ (⨅h : x∈t, f x)) : congr_arg infi $ funext $ assume x, infi_or
... = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) : infi_inf_eq
lemma infi_split (f : β → α) (p : β → Prop) :
(⨅ i, f i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), f i) :=
by simpa [classical.em] using @infi_union _ _ _ f {i | p i} {i | ¬ p i}
lemma infi_split_single (f : β → α) (i₀ : β) :
(⨅ i, f i) = f i₀ ⊓ (⨅ i (h : i ≠ i₀), f i) :=
by convert infi_split _ _; simp
theorem infi_le_infi_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) :
(⨅ x ∈ t, f x) ≤ (⨅ x ∈ s, f x) :=
by rw [(union_eq_self_of_subset_left h).symm, infi_union]; exact inf_le_left
theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) :=
calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) : congr_arg supr $ funext $ assume x, supr_or
... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq
lemma supr_split (f : β → α) (p : β → Prop) :
(⨆ i, f i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), f i) :=
by simpa [classical.em] using @supr_union _ _ _ f {i | p i} {i | ¬ p i}
lemma supr_split_single (f : β → α) (i₀ : β) :
(⨆ i, f i) = f i₀ ⊔ (⨆ i (h : i ≠ i₀), f i) :=
by convert supr_split _ _; simp
theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) :
(⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) :=
by rw [(union_eq_self_of_subset_left h).symm, supr_union]; exact le_sup_left
theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) :=
eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left
theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) :=
eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left
theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b :=
by simp
theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b :=
by rw [infi_insert, infi_singleton]
theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b :=
by simp
theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b :=
by rw [supr_insert, supr_singleton]
lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} :
(⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) :=
le_antisymm
(le_infi $ assume b, le_infi $ assume hbt,
infi_le_of_le (f b) $ infi_le (λ_, g (f b)) (mem_image_of_mem f hbt))
(le_infi $ assume c, le_infi $ assume ⟨b, hbt, eq⟩,
eq ▸ infi_le_of_le b $ infi_le (λ_, g (f b)) hbt)
lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} :
(⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) :=
le_antisymm
(supr_le $ assume c, supr_le $ assume ⟨b, hbt, eq⟩,
eq ▸ le_supr_of_le b $ le_supr (λ_, g (f b)) hbt)
(supr_le $ assume b, supr_le $ assume hbt,
le_supr_of_le (f b) $ le_supr (λ_, g (f b)) (mem_image_of_mem f hbt))
/- supr and infi under Type -/
theorem infi_of_empty' (h : ι → false) {s : ι → α} : infi s = ⊤ :=
top_unique (le_infi $ assume i, (h i).elim)
theorem supr_of_empty' (h : ι → false) {s : ι → α} : supr s = ⊥ :=
bot_unique (supr_le $ assume i, (h i).elim)
theorem infi_of_empty (h : ¬nonempty ι) {s : ι → α} : infi s = ⊤ :=
infi_of_empty' (λ i, h ⟨i⟩)
theorem supr_of_empty (h : ¬nonempty ι) {s : ι → α} : supr s = ⊥ :=
supr_of_empty' (λ i, h ⟨i⟩)
@[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ :=
infi_of_empty nonempty_empty
@[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ :=
supr_of_empty nonempty_empty
@[simp] theorem infi_unit {f : unit → α} : (⨅ x, f x) = f () :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_unit {f : unit → α} : (⨆ x, f x) = f () :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff :=
le_antisymm
(supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end)
(sup_le (le_supr _ _) (le_supr _ _))
lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff :=
le_antisymm
(le_inf (infi_le _ _) (infi_le _ _))
(le_infi $ assume b, match b with tt := inf_le_left | ff := inf_le_right end)
theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
lemma infi_subtype' {p : ι → Prop} {f : ∀ i, p i → α} :
(⨅ i (h : p i), f i h) = (⨅ x : subtype p, f x x.property) :=
(@infi_subtype _ _ _ p (λ x, f x.val x.property)).symm
lemma infi_subtype'' {ι} (s : set ι) (f : ι → α) :
(⨅ i : s, f i) = ⨅ (t : ι) (H : t ∈ s), f t :=
infi_subtype
lemma is_glb_binfi {s : set β} {f : β → α} : is_glb (f '' s) (⨅ x ∈ s, f x) :=
by simpa only [range_comp, subtype.range_coe, infi_subtype'] using @is_glb_infi α s _ (f ∘ coe)
theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
lemma supr_subtype' {p : ι → Prop} {f : ∀ i, p i → α} :
(⨆ i (h : p i), f i h) = (⨆ x : subtype p, f x x.property) :=
(@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm
lemma Sup_eq_supr' {s : set α} : Sup s = ⨆ x : s, (x : α) :=
by rw [Sup_eq_supr, supr_subtype']; refl
lemma is_lub_bsupr {s : set β} {f : β → α} : is_lub (f '' s) (⨆ x ∈ s, f x) :=
by simpa only [range_comp, subtype.range_coe, supr_subtype'] using @is_lub_supr α s _ (f ∘ coe)
theorem infi_sigma {p : β → Type*} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_sigma {p : β → Type*} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_prod {γ : Type*} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_prod {γ : Type*} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, f ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
theorem infi_sum {γ : Type*} {f : β ⊕ γ → α} :
(⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume i, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume s, match s with
| sum.inl i := inf_le_left_of_le $ infi_le _ _
| sum.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_sum {γ : Type*} {f : β ⊕ γ → α} :
(⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| sum.inl i := le_sup_left_of_le $ le_supr _ i
| sum.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨sum.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨sum.inr j, le_refl _⟩))
end
section complete_linear_order
variables [complete_linear_order α]
lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) :=
by simp only [← Sup_range, Sup_eq_top, set.exists_range_iff]
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, f i < b) :=
by simp only [← Inf_range, Inf_eq_bot, set.exists_range_iff]
end complete_linear_order
/- Instances -/
instance complete_lattice_Prop : complete_lattice Prop :=
{ Sup := λs, ∃a∈s, a,
le_Sup := assume s a h p, ⟨a, h, p⟩,
Sup_le := assume s a h ⟨b, h', p⟩, h b h' p,
Inf := λs, ∀a:Prop, a∈s → a,
Inf_le := assume s a h p, p a h,
le_Inf := assume s a h p b hb, h b hb p,
.. bounded_distrib_lattice_Prop }
lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl
lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl
lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) :=
le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i)
lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) :=
le_antisymm (λ ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (λ ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩)
instance pi.has_Sup {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] : has_Sup (Π i, β i) :=
⟨λ s i, ⨆ f : s, (f : Π i, β i) i⟩
instance pi.has_Inf {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] : has_Inf (Π i, β i) :=
⟨λ s i, ⨅ f : s, (f : Π i, β i) i⟩
instance pi.complete_lattice {α : Type*} {β : α → Type*} [∀ i, complete_lattice (β i)] :
complete_lattice (Π i, β i) :=
{ Sup := Sup,
Inf := Inf,
le_Sup := λ s f hf i, le_supr (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩,
Inf_le := λ s f hf i, infi_le (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩,
Sup_le := λ s f hf i, supr_le $ λ g, hf g g.2 i,
le_Inf := λ s f hf i, le_infi $ λ g, hf g g.2 i,
.. pi.bounded_lattice }
lemma Inf_apply {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)]
{s : set (Πa, β a)} {a : α} :
(Inf s) a = (⨅ f : s, (f : Πa, β a) a) :=
rfl
lemma infi_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Inf (β i)]
{f : ι → Πa, β a} {a : α} :
(⨅i, f i) a = (⨅i, f i a) :=
by rw [infi, Inf_apply, infi, infi, ← image_eq_range (λ f : Π i, β i, f a) (range f), ← range_comp]
lemma Sup_apply {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] {s : set (Πa, β a)} {a : α} :
(Sup s) a = (⨆f:s, (f : Πa, β a) a) :=
rfl
lemma supr_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Sup (β i)] {f : ι → Πa, β a}
{a : α} :
(⨆i, f i) a = (⨆i, f i a) :=
@infi_apply α (λ i, order_dual (β i)) _ _ f a
section complete_lattice
variables [preorder α] [complete_lattice β]
theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) :=
assume x y h, supr_le $ λ f, le_supr_of_le f $ m_s f f.2 h
theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) :=
assume x y h, le_infi $ λ f, infi_le_of_le f $ m_s f f.2 h
end complete_lattice
namespace order_dual
variable (α)
instance [complete_lattice α] : complete_lattice (order_dual α) :=
{ le_Sup := @complete_lattice.Inf_le α _,
Sup_le := @complete_lattice.le_Inf α _,
Inf_le := @complete_lattice.le_Sup α _,
le_Inf := @complete_lattice.Sup_le α _,
.. order_dual.bounded_lattice α, ..order_dual.has_Sup α, ..order_dual.has_Inf α }
instance [complete_linear_order α] : complete_linear_order (order_dual α) :=
{ .. order_dual.complete_lattice α, .. order_dual.decidable_linear_order α }
end order_dual
namespace prod
variables (α β)
instance [has_Inf α] [has_Inf β] : has_Inf (α × β) :=
⟨λs, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩
instance [has_Sup α] [has_Sup β] : has_Sup (α × β) :=
⟨λs, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩
instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) :=
{ le_Sup := assume s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩,
Sup_le := assume s p h,
⟨ Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).1,
Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).2⟩,
Inf_le := assume s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩,
le_Inf := assume s p h,
⟨ le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).1,
le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).2⟩,
.. prod.bounded_lattice α β,
.. prod.has_Sup α β,
.. prod.has_Inf α β }
end prod
|
00e47d49120e1b6c1d97071a53df9f705651189b | 36938939954e91f23dec66a02728db08a7acfcf9 | /lean4/deps/galois_stdlib/src/Galois/Init/Int.lean | b72e089748177c1221ee580deb5519a0ed8fa840 | [] | no_license | pnwamk/reopt-vcg | f8b56dd0279392a5e1c6aee721be8138e6b558d3 | c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d | refs/heads/master | 1,631,145,017,772 | 1,593,549,019,000 | 1,593,549,143,000 | 254,191,418 | 0 | 0 | null | 1,586,377,077,000 | 1,586,377,077,000 | null | UTF-8 | Lean | false | false | 312 | lean | import Galois.Init.Nat
namespace Int
protected
def pow (v : Int) (n : Nat) : Int
:= (if Nat.bodd n ∧ v < 0 then (-1) else 1) * (Int.ofNat (v.natAbs ^ n))
instance intPow : HasPow Int Nat := ⟨Int.pow⟩
def shiftl (v : Int) (n : Nat) := v * 2 ^ n
def shiftr (v : Int) (n : Nat) := v / 2 ^ n
end Int
|
94c4dbad67b180e3a13734e6a2d2b00beca018d6 | 7d5ad87afb17e514aee234fcf0a24412eed6384f | /src/peano.lean | 4c722f12d68d68032bc0d52087c3d458e680b4e7 | [] | no_license | digama0/flypitch | 764f849eaef59c045dfbeca142a0f827973e70c1 | 2ec14b8da6a3964f09521d17e51f363d255b030f | refs/heads/master | 1,586,980,069,651 | 1,547,078,141,000 | 1,547,078,283,000 | 164,965,135 | 1 | 0 | null | 1,547,082,858,000 | 1,547,082,857,000 | null | UTF-8 | Lean | false | false | 23,482 | lean | import .fol tactic.tidy
open fol
local attribute [instance, priority 0] classical.prop_decidable
--local attribute [instance] classical.prop_decidable
local notation h :: t := dvector.cons h t
local notation `[]` := dvector.nil
local notation `[` l:(foldr `, ` (h t, dvector.cons h t) dvector.nil `]`) := l
namespace peano
section
/-- Given a nat k and a 0-formula ψ, return ψ with ∀' applied k times to it --/
@[simp] def alls {L : Language} : Π n : ℕ, formula L → formula L
--:= nat.iterate all n
| 0 f := f
| (n+1) f := ∀' alls n f
@[simp]def bd_alls' {L : Language} : Π k n : ℕ, bounded_formula L (n + k) → bounded_formula L n
| 0 n f := f
| (k+1) n f := bd_alls' k n (∀' f)
@[simp]def bf_k_plus_zero {L} {k} : bounded_formula L (0 + k) = bounded_formula L k :=
by {convert rfl, rw[zero_add]}
@[simp] def bd_alls {L : Language} : Π n : ℕ, bounded_formula L n → sentence L
| 0 f := f
| (n+1) f := bd_alls n (∀' f) -- bd_alls' (n+1) 0 (f.cast_eqr (zero_add (n+1)))
/-- generalization of bd_alls where we can apply less than n ∀'s--/
def bf_n_of_0_n {L : Language} {n} (ψ : bounded_formula L (0 + n)) : bounded_formula L n :=
by {convert ψ, rw[zero_add]}
def bf_0_n_of_n {L : Language} {n} (ψ : bounded_formula L n) : bounded_formula L (0 + n) :=
by {convert ψ, apply zero_add}
-- set_option pp.all true
-- set_option pp.notation false
@[simp]lemma mpr_lemma {α β: Type*} {p q : α = β} {x : β} : eq.mpr p x = eq.mpr q x := by refl
@[simp]lemma mpr_lemma2 {L} {n m : ℕ} {h : m = n} {h' : bounded_formula L m = bounded_formula L n} {h'' : bounded_formula L (m+1) = bounded_formula L (n+1)} {f : bounded_formula L (n+1)} : ∀' eq.mpr h'' f = eq.mpr h' (∀'f) :=
by tidy
-- lemma obvious3 {L : Language} {n} {ψ : bounded_formula L (n+1)} (p q : bounded_formula L (n - n) = bounded_formula L (n - n)) : eq.mpr p (bd_alls' n n (∀' ψ)) = eq.mpr q (bd_alls' n n (∀' ψ)) :=
-- by apply mpr_lemma -- refl also suffices here
-- lemma obvious4 {L : Language} {n} {ψ : bounded_formula L (n+1)} (p : bounded_formula L (n - n) = bounded_formula L (n - n)) :
-- (bd_alls' n n (∀' ψ)) = eq.mpr p (bd_alls' n n (∀' ψ)) :=
-- begin
-- have : bd_alls' n n (∀' ψ) = eq.mpr rfl (bd_alls' n n (∀' ψ)), by refl,
-- have := obvious3 rfl p, swap, exact ψ, cc
-- end
/- Obviously, bd_alls' n 0 ψ = bd_alls ψ -/
-- bd_alls n ψ = bd_alls' n 0 (by {convert ψ, apply zero_add})
--protected def cast_eqr {n m l} (h : n = m) (f : bounded_preformula L m l) : bounded_preformula L n l :=
--f.cast $ ge_of_eq h
@[simp] lemma alls'_alls {L : Language} : Π n (ψ : bounded_formula L n), bd_alls n ψ = bd_alls' n 0 (ψ.cast_eq (zero_add n).symm) :=
by {intros n ψ, induction n, swap, simp[n_ih (∀' ψ)], tidy}
-- @[simp] lemma alls'_alls {L : Language} : Π n (ψ : bounded_formula L n), bd_alls n ψ = bd_alls' n 0 (by {convert ψ, apply zero_add}) :=
-- begin
-- intros n ψ, induction n with n ih generalizing ψ, refl, simp[ih (∀' ψ)]
-- end
@[simp]lemma alls'_all_commute {L : Language} {n} {k} {f : bounded_formula L (n+k+1)} : (bd_alls' k n (∀' f)) = ∀' bd_alls' k (n+1) (f.cast_eq (by simp))-- by {refine ∀' bd_alls' k (n+1) _, simp, exact f}
:=
by {induction k; dsimp only [bounded_preformula.cast_eq], swap, simp[@k_ih (∀'f)], tidy}
-- @[simp]lemma alls'_all_commute {L : Language} {n} {k} {f : bounded_formula L (n + k + 1)} : bd_alls' k n (∀' f) = ∀' bd_alls' k (n+1) (by {simp, exact f}) :=
-- begin
-- induction k, refl, unfold bd_alls', rw[@k_ih (∀' f),<-mpr_lemma2],
-- simp only [add_comm, eq_self_iff_true, add_right_inj, add_left_comm]
-- end
@[simp]lemma bd_alls'_substmax {L} {n} {f : bounded_formula L (n+1)} {t : closed_term L} : (bd_alls' n 1 (f.cast_eq (by simp)))[t /0] = (bd_alls' n 0 (substmax_bounded_formula (f.cast_eq (by simp)) t)) := by {induction n, {tidy}, have := @n_ih (∀' f), simp[bounded_preformula.cast_eq] at *, exact this}
lemma realize_sentence_bd_alls {L} {n} {f : bounded_formula L n} {S : Structure L} : S ⊨ (bd_alls n f) ↔ (∀ xs : dvector S n, realize_bounded_formula xs f []) :=
begin
induction n,
{tidy, convert a, apply dvector.zero_eq},
{have := @n_ih (∀' f), simp[alls'_alls, alls'_all_commute] at this,
cases this with this_mp this_mpr, split,
intros H xs, cases xs, apply this_mp (by {convert H, tidy}),
intro H, convert this_mpr (by {intros xs x, exact H (x :: xs)}), tidy}
end
@[simp] lemma alls_0 {L : Language} (ψ : formula L) : alls 0 ψ = ψ := by refl
--lemma bd_alls_all_commute {L : Language} : Π n (f : bounded_formula L (n+1)), bd_alls n (∀'f) = ∀' (bd_alls n (f))
-- @[simp] def b_alls_1 {L : Language} {n : ℕ} {f : formula L} (hf : formula_below (n+1) f) : formula_below n $ alls 1 f := begin
-- constructor, assumption
-- end
@[simp] lemma alls_all_commute {L : Language} (f : formula L) {k : ℕ} : (alls k ∀' f) = (∀' alls k f) := by {induction k, refl, dunfold alls, rw[k_ih]}
@[simp] lemma alls_succ_k {L : Language} (f : formula L) {k : ℕ} : alls (k + 1) f = ∀' alls k f := by constructor
-- @[simp] def b_alls_k {L : Language} {n : ℕ} {k: ℕ} : ∀ f : formula L, formula_below (n + k) f → formula_below n (alls k f) :=
-- begin
-- induction k with k ih,
-- intros f hf, exact hf,
-- intros f hf,
-- have H := alls_succ_k,
-- have hf_rw : formula_below (n + nat.succ k) f → formula_below (n+k) ∀'f, by {apply b_alls_1},
-- let hf2 := hf_rw hf,
-- have hooray := ih (∀'f) hf2,
-- rw[alls_all_commute, <-H] at hooray, exact hooray --hooray!!
-- end
/- both b_subst and b_subst2 are consequences of formula_below_subst in fol.lean -/
-- def b_subst {L : Language} {n : ℕ} {f : formula L} (hf : formula_below (n+1) f) {t : term L} (ht : term_below 0 t) : formula_below n (f[t //0]) :=
-- begin
-- have P := @formula_below_subst L 0 n 0 f begin rw[zero_add], exact hf end t,
-- have t' : term_below n t,
-- fapply term_below_of_le,
-- exact 0,
-- exact n.zero_le,
-- exact ht,
-- have Q := P t',
-- simp only [fol.subst_formula, zero_add] at Q, assumption
-- end
-- def b_subst2 {L : Language} {n : ℕ} {f : formula L} (hf : formula_below n f) {t : term L} (ht : term_below n t) : formula_below n (f[t //0]) :=
-- begin
-- have P := @formula_below_subst L 0 n 0 f begin rw[zero_add], fapply formula_below_of_le, exact n, simpa end t,
-- have P' := P ht, simp only [fol.subst_formula, zero_add] at P', assumption
-- end
/- END LEMMAS -/
/- The language of PA -/
inductive peano_functions : ℕ → Type -- thanks Floris!
| zero : peano_functions 0
| succ : peano_functions 1
| plus : peano_functions 2
| mult : peano_functions 2
def L_peano : Language := ⟨peano_functions, λ n, empty⟩
def L_peano_plus {n} (t₁ t₂ : bounded_term L_peano n) : bounded_term L_peano n :=
@bounded_term_of_function L_peano 2 n peano_functions.plus t₁ t₂
def L_peano_mult {n} (t₁ t₂ : bounded_term L_peano n) : bounded_term L_peano n :=
@bounded_term_of_function L_peano 2 n peano_functions.mult t₁ t₂
local infix ` +' `:100 := L_peano_plus
local infix ` ×' `:150 := L_peano_mult
def succ {n} : bounded_term L_peano n → bounded_term L_peano n :=
@bounded_term_of_function L_peano 1 n peano_functions.succ
def zero {n} : bounded_term L_peano n := bd_const peano_functions.zero
def one {n} : bounded_term L_peano n := succ zero
/- For each k : ℕ, return the bounded_term of L_peano corresponding to k-/
@[reducible]def formal_nat {n}: Π k : ℕ, bounded_term L_peano n
| 0 := zero
| (k+1) := succ $ formal_nat k
/- for all x, zero not equal to succ x -/
def p_zero_not_succ : sentence L_peano :=
∀'(zero ≃ succ &0 ⟹ ⊥)
@[reducible]def shallow_zero_not_succ : Prop :=
∀ n : ℕ, 0 = nat.succ n → false
def p_succ_inj : sentence L_peano := ∀' ∀'(succ &1 ≃ succ &0 ⟹ &1 ≃ &0)
@[reducible]def shallow_succ_inj : Prop := ∀ x, ∀ y, nat.succ x = nat.succ y → x = y
def p_zero_is_identity : sentence L_peano := ∀'(&0 +' zero ≃ &0)
@[reducible]def shallow_zero_is_identity : Prop := ∀ x : ℕ, x + 0 = x
/- ∀ x ∀ y, x + succ y = succ( x + y) -/
def p_succ_plus : sentence L_peano := ∀' ∀'(&1 +' succ &0 ≃ succ (&1 +' &0))
@[reducible]def shallow_succ_plus : Prop := ∀ x, ∀ y, x + nat.succ y = nat.succ(x + y)
/- ∀ x, x ⬝ 0 = 0 -/
def p_zero_of_times_zero : sentence L_peano := ∀'(&0 ×' zero ≃ zero)
@[reducible]def shallow_zero_of_times_zero : Prop := ∀ x : ℕ, x * 0 = 0
/- ∀ x y, (x ⬝ succ y = (x ⬝ y) + x -/
def p_times_succ : sentence L_peano := ∀' ∀' (&1 ×' succ &0 ≃ &1 ×' &0 +' &1)
@[reducible]def shallow_times_succ : Prop := ∀ x : ℕ, ∀ y : ℕ, x * (y + 1) = (x * y) + x
/- The induction schema instance at ψ is the following formula (up to the fixed ordering of variables given by the de Bruijn indexing):
letting k+1 be the number of free vars of ψ:
(k ∀'s)[(ψ(...,0) ∧ ∀' (ψ → ψ(...,S(x)))) → ∀' ψ]
-/
def p_induction_schema {n : ℕ} (ψ : bounded_formula L_peano (n+1)) : sentence L_peano :=
bd_alls n (ψ[zero/0] ⊓ ∀' (ψ ⟹ (ψ ↑' 1 # 1)[succ &0/0]) ⟹ ∀' ψ)
@[reducible]def shallow_induction_schema : Π P : set ℕ, Prop := λ P, (P(0) ∧ ∀ x, P x → P (nat.succ x)) → ∀ x, P x
/- The theory of Peano arithmetic -/
def PA : Theory L_peano :=
{p_zero_not_succ, p_succ_inj, p_zero_is_identity, p_succ_plus, p_zero_of_times_zero, p_times_succ} ∪ ⋃ (n : ℕ), (λ(ψ : bounded_formula L_peano (n+1)), p_induction_schema ψ) '' set.univ
@[reducible]def shallow_PA : set Prop :=
{shallow_zero_not_succ, shallow_succ_inj, shallow_zero_is_identity, shallow_succ_plus, shallow_zero_of_times_zero, shallow_times_succ} ∪ (shallow_induction_schema '' (set.univ))
def is_even : bounded_formula L_peano 1 :=
∃' (&0 +' &0 ≃ &1)
def L_peano_structure_of_nat : Structure L_peano :=
begin
refine ⟨ℕ, _, _⟩,
{intros n F, induction F, exact λv, 0,
{intro v, cases v, exact nat.succ v_x},
{intro v, cases v, exact v_x + (v_xs.nth 0 $ by constructor)},
{intro v, cases v, exact v_x * (v_xs.nth 0 $ by constructor)},},
{intro v, intro R, cases R},
end
local notation `ℕ'` := L_peano_structure_of_nat
@[simp]lemma floris {L} {S : Structure L} : ↥S = S.carrier := by refl
example : ℕ' ⊨ p_zero_not_succ := begin
change ∀ x : ℕ', 0 = nat.succ x → false, intros x h, cases h end
@[simp]lemma zero_is_zero : @realize_bounded_term L_peano ℕ' 0 [] 0 zero [] = nat.zero := by refl
@[simp]lemma one_is_one : @realize_bounded_term L_peano ℕ' 0 [] 0 one [] = (nat.succ nat.zero) := by refl
instance has_zero_sort_L_peano_structure_of_nat : has_zero ℕ' := ⟨nat.zero⟩
instance has_zero_L_peano_structure_of_nat : has_zero L_peano_structure_of_nat := ⟨nat.zero⟩
@[simp]lemma formal_nat_realize_term {n} : realize_closed_term ℕ' (formal_nat n) = n :=
by {induction n, refl, tidy}
@[simp] lemma succ_realize_term {n} : realize_closed_term ℕ' (succ $ formal_nat n) = nat.succ n :=
begin
dsimp[realize_closed_term, realize_bounded_term, succ, bounded_term_of_function],
induction n, tidy
end
@[simp]lemma formal_nat_realize_formula {ψ : bounded_formula L_peano 1} (n) : realize_bounded_formula ([(n : ℕ')]) ψ [] ↔ ℕ' ⊨ ψ[(formal_nat n)/0] :=
begin
induction n, all_goals{dsimp[formal_nat], simp[realize_subst_formula0]},
have := @formal_nat_realize_term 0, unfold formal_nat at this, rw[this]
end
@[simp]lemma nat_bd_all {ψ : bounded_formula L_peano 1} : ℕ' ⊨ ∀'ψ ↔ ∀(n : ℕ'), ℕ' ⊨ ψ[(formal_nat n)/0] :=
begin
refine ⟨by {intros H n, induction n, all_goals{dsimp[formal_nat], rw[realize_subst_formula0], tidy}}, _⟩,
intros H n, have := H n, induction n, all_goals{simp only [formal_nat_realize_formula], exact this}
end
lemma shallow_induction (P : set nat) : (P(0) ∧ ∀ x, P x → P (nat.succ x)) → ∀ x, P x :=
λ h, nat.rec h.1 h.2
-- @[simp]lemma subst0_subst0 {L} {n} {f : bounded_formula L (n+1)} {s₁} {s₂} : (f ↑' 1 # 1)[s₁ /0][s₂ /0] = f[s₁[s₂ /0] /0] := sorry -- this probably isn't true with careful lifting
-- @[simp]lemma subst_succ_is_apply {n} {k} : (succ &0)[formal_nat n /0] = @formal_nat k (nat.succ n) :=
-- begin
-- induction n, refl, symmetry, dsimp[formal_nat] at *, rw[<-n_ih],
-- unfold succ bounded_term_of_function formal_nat, tidy, induction n_n, tidy
-- end
-- @[simp]lemma subst_term'_cancel {n} {k} : Π ψ : bounded_formula L_peano (k + 1), (ψ ↑' 1 # 1)[succ &0 /0][formal_nat n /0] = ψ[formal_nat (nat.succ n) /0] := by simp
-- begin
-- -- intros n ψ, unfold subst0_bounded_formula, tidy, -- simp[lift_subst_formula_cancel ψ.fst 0],
-- -- sorry -- looks like here we need a lemma that generalizes lift_subst_formula_cancel to substitutions of terms, or something
-- end
---- oops, i think this is already somewhere in fol.lean
-- /-- Canonical extension of a dvector to a valuation --/
-- def val_of_dvector {α : Type*} [has_zero α] {n} (xs : dvector α n): ℕ' → α :=
-- begin
-- intro k,
-- by_cases nat.lt k n,
-- exact xs.nth k h,
-- exact 0
-- end
-- @[reducible]def dvector.trunc {α : Type*} : ∀ {n m : nat} (h : n ≤ m) (xs : dvector α m), dvector α n
-- | 0 0 _ xs := []
-- | 0 (m+1) _ xs := []
-- | (n+1) 0 _ xs := by {exfalso, cases _x}
-- | (n+1) (m+1) h xs := begin cases xs, convert (xs_x::dvector.trunc _ xs_xs), tidy end
-- @[simp]lemma dvector_trunc_n_n {α : Type*} {n : nat} {h : n ≤ n} {v : dvector α n} : dvector.trunc h v = v := by {induction v, tidy}
-- @[simp]lemma dvector_trunc_0_n {α : Type*} {n : nat} {h : 0 ≤ n} {v : dvector α n} : dvector.trunc h v = [] := by {induction v, tidy}
/-- Given a term t with ≤ n free variables, the realization of t only depends on the nth initial segment of the realizing dvector v. --/
-- lemma realize_closed_term_realize_irrel {L} {S : Structure L} {n n' : nat} {h : n' ≤ n} {t : bounded_term L n'} {v : dvector S n} : realize_bounded_term (dvector.trunc h v) t [] = realize_bounded_term v (t.cast h) [] :=
-- begin
-- revert t, apply bounded_term.rec, {intro k, induction k, induction v, have : n' = 0, by {apply nat.eq_zero_of_le_zero, exact h}, subst this, {tidy}, sorry},
-- tidy, sorry
-- end
-- lemma realize_closed_term_realizer_irrel {L} {S : Structure L} {n} {n'} {h : n' ≤ n} {t : bounded_term L n'} {v : dvector S n} : realize_bounded_term (@dvector.trunc n' n h xs) (t.cast (by simp)) [] = realize_bounded_term [] t [] :=
-- begin
-- induction n,
-- {cases v, revert t, },
-- {sorry},
-- end
-- lemma realize_bounded_formula_subst0_gen {L} {S : Structure L} {n l} (f : bounded_preformula L (n+1) l) {v : dvector S n} {xs : dvector S l} (t : bounded_term L n) : realize_bounded_formula v (f[(t.cast (by refl)) /0]) xs ↔ realize_bounded_formula ((realize_bounded_term v t [])::v) f xs :=
-- begin
-- sorry
-- end
@[simp]lemma subst_falsum {L} {n n' n''} {h : n + n' + 1 = n''} {t : bounded_term L n'} : bd_falsum[t // n // h] = bd_falsum :=
by tidy
@[simp]lemma subst0_falsum {L} {n} {t : bounded_term L n} : bd_falsum[t /0] = bd_falsum :=
by {unfold subst0_bounded_formula, simpa only [subst_falsum]}
-- looks like here we additionally need substitution notation for bounded_term
@[simp]lemma subst_eq {L} {n n' n''} {h : n + n' + 1 = n''} {t₁ t₂ : bounded_term L n''} {t : bounded_term L n'} : (t₁ ≃ t₂)[t // n // h] = subst_bounded_term (t₁.cast_eq h.symm) t ≃ subst_bounded_term (t₂.cast_eq h.symm) t := by tidy -- TODO replace these with the fully expanded versions
@[simp]lemma subst0_eq {L} {n} {t : bounded_term L n} {t₁ t₂ : bounded_term L (n+1)} : (t₁ ≃ t₂)[t /0] = (t₁[t /0] ≃ t₂[t /0]) :=
by {unfold subst0_bounded_formula, simpa only [subst_eq]}
@[simp]lemma subst_imp {L} {n n' n''} {h : n + n' + 1 = n''} {t : bounded_term L n'} {f₁ f₂ : bounded_formula L (n'')} : (f₁ ⟹ f₂)[t // n // h] = (f₁[t // n // h] ⟹ f₂[t // n // h]) := by tidy
@[simp]lemma subst0_imp {L} {n} {t : bounded_term L n} {f₁ f₂ : bounded_formula L (n+1)} : (f₁ ⟹ f₂)[t /0] = f₁[t /0] ⟹ f₂[t /0] :=
by {unfold subst0_bounded_formula, simpa only [subst_imp]}
-- def hewwo : bounded_formula L_peano 1 := &0 ≃ zero
-- #reduce @realize_bounded_formula L_peano L_peano_structure_of_nat _ _ [] ((hewwo[ (succ zero) // 0 // (by simp)]).cast (by {refl})) [] -- sanity check, works as expected
#reduce @fol.subst_bounded_term L_peano 0 0 0 (&0) zero
-- #reduce (&0 : bounded_term L_peano 1)[zero // 0] -- elaborator fails, don't know why
-- this is the suspicious simp lemma--- don't want this
-- @[simp]lemma subst0_all {L} {n} {t : closed_term L} {f : bounded_formula L (n+2)} : (∀' f)[(t.cast (by simp)) /0] = begin apply bd_all, fapply subst_bounded_formula, exact n+2, exact f, exact (t.cast (by simp)), repeat{constructor} end :=
-- begin
-- sorry
-- end
@[simp]lemma subst_all {L} {n n' n''} {h : n + n' + 1 = n''} {t : closed_term L} {f : bounded_formula L (n'' + 1)} :
(∀'f)[t.cast0 n' // n // (by {simp[h]})]
= ∀'(f[(t.cast0 n' : bounded_term L n') // (n+1) // (by {tidy})]).cast_eq (by simp) :=
by tidy
@[simp]lemma subst0_all {L} {n} {t : closed_term L} {f : bounded_formula L (n+2)} :
((∀'f)[t.cast (by simp) /0] : bounded_formula L n) = ∀'((f[t.cast0 n // 1 // (by {simp} : 1 + n + 1 = n + 2)]).cast_eq (by simp)) :=
by tidy
-- {unfold subst0_bounded_formula, simp[@subst_all L n 0 (n+1) (by simp) t f], }
lemma zero_of_lt_one (n : nat) (h : n < 1) : n = 0 :=
by {cases h, refl, cases nat.lt_of_succ_le h_a}
@[simp]lemma realize_bounded_term_subst0 {L} {S : Structure L} {n} (s : bounded_term L (n+1)) {v : dvector S n} (t : closed_term L) : realize_bounded_term v (s[(t.cast (by simp)) /0]) [] = realize_bounded_term ((realize_closed_term S t)::v) s [] :=
begin
revert s, refine bounded_term.rec1 _ _,
{intro k, rcases k with ⟨k_val, k_H⟩, simp,
induction n generalizing k_val, have := zero_of_lt_one k_val (by exact k_H), subst this,
congr, {apply dvector.zero_eq}, {tidy}, cases nat.le_of_lt_succ k_H with H1 H2,
swap, repeat{sorry}
},
{sorry}
end
-- intros, induction n, rw[dvector.zero_eq v],
-- {cases k, tidy,
-- have := zero_of_lt_one k_val (by exact k_is_lt), subst this,
-- congr, unfold subst0_bounded_term, tidy},
-- {
-- -- cases v, have := @n_ih v_xs, sorry
-- }
lemma subst0_bounded_formula_bd_apps_rel {L} {n l} (f : bounded_preformula L (n+1) l)
(t : closed_term L) (ts : dvector (bounded_term L (n+1)) l) :
subst0_bounded_formula (bd_apps_rel f ts) (t.cast (by simp)) =
bd_apps_rel (subst0_bounded_formula f (t.cast (by simp))) (ts.map $ λt', subst0_bounded_term t' (t.cast (by simp))) :=
begin
induction ts generalizing f, refl, simp[bd_apps_rel, ts_ih (bd_apprel f ts_x)], congr, tidy
end
lemma rel_subst0_irrel {L : Language} {n l} {R : L.relations l} {t : bounded_term L n} : (bd_rel R)[t /0] = (bd_rel R) := by tidy
-- lemma realize_bounded_formula_subst_insert {L} {S : Structure L} {n i} (f : bounded_formula L (n+1)) {v : dvector S n} (t : closed_term L) {h_i : i + 0 + 1 = n + 1}: realize_bounded_formula v (begin apply @subst_bounded_formula L i _ (n+1) _ f (by sorry), repeat{constructor} end) [] ↔ realize_bounded_formula (v.insert (realize_closed_term S t) i) f [] :=
-- begin
-- sorry
-- end
-- maybe to finish this, need to generalize over all substitution indices---substitution at n corresponds to an insertion at n, and so on -- can finish by induction on vector length and use substmax
lemma realize_bounded_formula_subst0_gen {L} {S : Structure L} {n} {m} {m'} {h_m : m + m' + 1 = n+1} (f : bounded_formula L (n+1)) {v : dvector S n} (t : closed_term L) : realize_bounded_formula v ((f[t.cast (zero_le m') // m // h_m]).cast_eq (by {tidy})) [] ↔ realize_bounded_formula (dvector.insert (realize_closed_term S t) (m+1) v) f [] :=
begin
revert n f v, refine bounded_formula.rec1 _ _ _ _ _; intros,
{simp, intro a, cases a},
{sorry}, -- this needs term version
{sorry}, -- this needs version for bd_apps_rel
{sorry},
{simp[*, subst_all],}
end
set_option pp.implicit true
/-- realization of a subst0 is the realization with the substituted term prepended to the realizing vector --/
lemma realize_bounded_formula_subst0 {L} {S : Structure L} {n} (f : bounded_formula L (n+1)) {v : dvector S n} (t : closed_term L) : realize_bounded_formula v (f[(t.cast0 n) /0]) [] ↔ realize_bounded_formula ((realize_closed_term S t)::v) f [] :=
begin
revert n f v, refine bounded_formula.rec1 _ _ _ _ _; intros,
{simp},
{simp},
{rw[subst0_bounded_formula_bd_apps_rel], simp[realize_bounded_formula_bd_apps_rel, rel_subst0_irrel]},
{simp*},
{simp, apply forall_congr, clear ih, intro x, have := realize_bounded_formula_subst0_gen f t, tactic.rotate 1,
exact S, exact 0, exact (n+1), {simp},
exact (x::v), simp at this, rw[<-this],
conv {to_lhs, congr, skip, congr, congr,
skip, simp[closed_preterm.cast0]},
apply iff_of_eq, congr' 2, simp,
}
end
-- begin
-- dsimp[closed_term, closed_preterm] at t,
-- have := @realize_bounded_formula_subst0_gen L S n 0 f v [] (t.cast (by simp)),
-- unfold realize_closed_term, rw[<-realize_closed_term_realize_irrel] at this,
-- simp at this, split,
-- -- rest of this lemma relies on rewriting the bounded_preterm.cast t, after which simp[this] should work
-- {intro, apply this.mp, revert a, sorry},
-- {sorry},
-- end
lemma realize_bounded_formula_subst0' {L} {S : Structure L} {n} (f : bounded_formula L (n+1)) {v : dvector S n} (t : bounded_term L 1) (x : S) : realize_bounded_formula (x :: v) ((f ↑' 1 # 1)[(t.cast (by simp)) /0]) [] ↔ realize_bounded_formula ((realize_bounded_term ([x] : dvector S 1) t []) :: v) f [] :=
begin
revert f n v, refine bounded_formula.rec1 _ _ _ _ _; intros,
{tidy},
{sorry}, -- this requires a version of this lemma for terms
{sorry}, -- same issue as the corresponding case above
{sorry}, -- this one should be easy, just need a lemma about commutation with bd_imp
{sorry}, -- same issues as the corresponding case above
end
/- ℕ' satisfies PA induction schema -/
theorem PA_standard_model_induction {index : nat} {ψ : bounded_formula L_peano (index + 1)} : ℕ' ⊨ bd_alls index (ψ[zero /0] ⊓ ∀'(ψ ⟹ (ψ ↑' 1 # 1)[succ &0 /0]) ⟹ ∀' ψ) :=
begin
rw[realize_sentence_bd_alls], intro xs,
simp,
intros H_zero H_ih, apply nat.rec,
{apply (realize_bounded_formula_subst0 ψ zero).mp, apply H_zero},
{intros n H, apply (@realize_bounded_formula_subst0' _ _ _ ψ xs (succ &0) n).mp,
exact H_ih n H}
end
def true_arithmetic := Th ℕ'
lemma true_arithmetic_extends_PA : PA ⊆ true_arithmetic :=
begin
intros f hf, cases hf with not_induct induct,
swap,
{rcases induct with ⟨induction_schemas, ⟨⟨index, h_eq⟩, ih_right⟩⟩,
rw[h_eq] at ih_right, simp[set.range, set.image] at ih_right,
rcases ih_right with ⟨ψ, h_ψ⟩, subst h_ψ, apply PA_standard_model_induction},
{repeat{cases not_induct}, tidy, contradiction}
end
lemma shallow_standard_model : ∀ ψ ∈ shallow_PA, ψ :=
begin
intros x H, cases H,
{repeat{cases H}, tidy, contradiction},
{simp[shallow_induction_schema] at H, rcases H with ⟨y, Hy⟩, subst Hy, exact nat.rec}
end
def PA_standard_model : Model PA := ⟨ℕ', true_arithmetic_extends_PA⟩
end
end peano
|
b4a244ce351580c9e98a26acf6392c223cd4806c | aa2345b30d710f7e75f13157a35845ee6d48c017 | /category_theory/natural_transformation.lean | ba14d425d2172435980521d3d18b06177b0f1916 | [
"Apache-2.0"
] | permissive | CohenCyril/mathlib | 5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe | a12d5a192f5923016752f638d19fc1a51610f163 | refs/heads/master | 1,586,031,957,957 | 1,541,432,824,000 | 1,541,432,824,000 | 156,246,337 | 0 | 0 | Apache-2.0 | 1,541,434,514,000 | 1,541,434,513,000 | null | UTF-8 | Lean | false | false | 4,718 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baumann, Stephen Morgan, Scott Morrison
Defines natural transformations between functors.
Introduces notations
`F ⟹ G` for the type of natural transformations between functors `F` and `G`,
`τ X` (a coercion) for the components of natural transformations,
`σ ⊟ τ` for vertical compositions, and
`σ ◫ τ` for horizontal compositions.
-/
import category_theory.functor
namespace category_theory
universes u₁ v₁ u₂ v₂ u₃ v₃ u₄ v₄
variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D]
include 𝒞 𝒟
/--
`nat_trans F G` represents a natural transformation between functors `F` and `G`.
The field `app` provides the components of the natural transformation, and there is a
coercion available so you can write `α X` for the component of a transformation `α` at an object `X`.
Naturality is expressed by `α.naturality_lemma`.
-/
structure nat_trans (F G : C ⥤ D) : Type (max u₁ v₂) :=
(app : Π X : C, (F X) ⟶ (G X))
(naturality' : ∀ {X Y : C} (f : X ⟶ Y), (F.map f) ≫ (app Y) = (app X) ≫ (G.map f) . obviously)
infixr ` ⟹ `:50 := nat_trans -- type as \==> or ⟹
namespace nat_trans
instance {F G : C ⥤ D} : has_coe_to_fun (F ⟹ G) :=
{ F := λ α, Π X : C, (F X) ⟶ (G X),
coe := λ α, α.app }
@[simp] lemma app_eq_coe {F G : C ⥤ D} (α : F ⟹ G) (X : C) : α.app X = α X := by unfold_coes
@[simp] lemma mk_app {F G : C ⥤ D} (app : Π X : C, (F X) ⟶ (G X)) (naturality) (X : C) :
{ nat_trans . app := app, naturality' := naturality } X = app X := rfl
lemma naturality {F G : C ⥤ D} (α : F ⟹ G) {X Y : C} (f : X ⟶ Y) :
(F.map f) ≫ (α Y) = (α X) ≫ (G.map f) :=
begin
/- `obviously'` says: -/
erw nat_trans.naturality', refl
end
/-- `nat_trans.id F` is the identity natural transformation on a functor `F`. -/
protected def id (F : C ⥤ D) : F ⟹ F :=
{ app := λ X, 𝟙 (F X) }
@[simp] lemma id_app (F : C ⥤ D) (X : C) : (nat_trans.id F) X = 𝟙 (F X) := rfl
open category
open category_theory.functor
section
variables {F G H I : C ⥤ D}
-- We'll want to be able to prove that two natural transformations are equal if they are componentwise equal.
@[extensionality] lemma ext (α β : F ⟹ G) (w : ∀ X : C, α X = β X) : α = β :=
begin
induction α with α_components α_naturality,
induction β with β_components β_naturality,
have hc : α_components = β_components := funext w,
subst hc
end
/-- `vcomp α β` is the vertical compositions of natural transformations. -/
def vcomp (α : F ⟹ G) (β : G ⟹ H) : F ⟹ H :=
{ app := λ X, (α X) ≫ (β X),
naturality' := begin /- `obviously'` says: -/ intros, simp, rw [←assoc, naturality, assoc, ←naturality], end }
notation α `⊟` β:80 := vcomp α β
@[simp] lemma vcomp_app (α : F ⟹ G) (β : G ⟹ H) (X : C) : (α ⊟ β) X = (α X) ≫ (β X) := rfl
@[simp] lemma vcomp_assoc (α : F ⟹ G) (β : G ⟹ H) (γ : H ⟹ I) : (α ⊟ β) ⊟ γ = (α ⊟ (β ⊟ γ)) := by tidy
end
variables {E : Type u₃} [ℰ : category.{u₃ v₃} E]
include ℰ
/-- `hcomp α β` is the horizontal composition of natural transformations. -/
def hcomp {F G : C ⥤ D} {H I : D ⥤ E} (α : F ⟹ G) (β : H ⟹ I) : (F ⋙ H) ⟹ (G ⋙ I) :=
{ app := λ X : C, (β (F X)) ≫ (I.map (α X)),
naturality' := begin
/- `obviously'` says: -/
intros,
dsimp,
simp,
-- Actually, obviously doesn't use exactly this sequence of rewrites, but achieves the same result
rw [← assoc, naturality, assoc],
conv { to_rhs, rw [← map_comp, ← α.naturality, map_comp] }
end }
notation α `◫` β:80 := hcomp α β
@[simp] lemma hcomp_app {F G : C ⥤ D} {H I : D ⥤ E} (α : F ⟹ G) (β : H ⟹ I) (X : C) :
(α ◫ β) X = (β (F X)) ≫ (I.map (α X)) := rfl
-- Note that we don't yet prove a `hcomp_assoc` lemma here: even stating it is painful, because we need to use associativity of functor composition
lemma exchange {F G H : C ⥤ D} {I J K : D ⥤ E} (α : F ⟹ G) (β : G ⟹ H) (γ : I ⟹ J) (δ : J ⟹ K) :
((α ⊟ β) ◫ (γ ⊟ δ)) = ((α ◫ γ) ⊟ (β ◫ δ)) :=
begin
-- `obviously'` says:
ext,
intros,
dsimp,
simp,
-- again, this isn't actually what obviously says, but it achieves the same effect.
conv { to_lhs, congr, skip, rw [←assoc, ←naturality, assoc] }
end
end nat_trans
end category_theory |
2271f9c20947440016e675996dd9acb35e0cc406 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/topology/constructions.lean | 4377c298ec830b6aeca8d77b2deda90bbeac5a4f | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 49,816 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot
Constructions of new topological spaces from old ones: product, sum, subtype, quotient, list, vector
-/
import topology.maps topology.subset_properties topology.separation topology.bases
noncomputable theory
open set filter lattice
local attribute [instance] classical.prop_decidable
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
section prod
open topological_space
variables [topological_space α] [topological_space β] [topological_space γ]
lemma continuous_fst : continuous (@prod.fst α β) :=
continuous_inf_dom_left continuous_induced_dom
lemma continuous_snd : continuous (@prod.snd α β) :=
continuous_inf_dom_right continuous_induced_dom
lemma continuous.prod_mk {f : γ → α} {g : γ → β}
(hf : continuous f) (hg : continuous g) : continuous (λx, prod.mk (f x) (g x)) :=
continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg)
lemma continuous_swap : continuous (prod.swap : α × β → β × α) :=
continuous.prod_mk continuous_snd continuous_fst
lemma is_open_prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) :
is_open (set.prod s t) :=
is_open_inter (continuous_fst s hs) (continuous_snd t ht)
lemma nhds_prod_eq {a : α} {b : β} : nhds (a, b) = filter.prod (nhds a) (nhds b) :=
by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced]
instance [topological_space α] [discrete_topology α] [topological_space β] [discrete_topology β] :
discrete_topology (α × β) :=
⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩,
by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩
lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β}
(ha : s ∈ nhds a) (hb : t ∈ nhds b) : set.prod s t ∈ nhds (a, b) :=
by rw [nhds_prod_eq]; exact prod_mem_prod ha hb
lemma nhds_swap (a : α) (b : β) : nhds (a, b) = (nhds (b, a)).map prod.swap :=
by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl
lemma tendsto_prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β}
(ha : tendsto ma f (nhds a)) (hb : tendsto mb f (nhds b)) :
tendsto (λc, (ma c, mb c)) f (nhds (a, b)) :=
by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb
lemma continuous_within_at.prod {f : α → β} {g : α → γ} {s : set α} {x : α}
(hf : continuous_within_at f s x) (hg : continuous_within_at g s x) :
continuous_within_at (λx, (f x, g x)) s x :=
tendsto_prod_mk_nhds hf hg
lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α}
(hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x :=
tendsto_prod_mk_nhds hf hg
lemma continuous_on.prod {f : α → β} {g : α → γ} {s : set α}
(hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, (f x, g x)) s :=
λx hx, continuous_within_at.prod (hf x hx) (hg x hx)
lemma prod_generate_from_generate_from_eq {s : set (set α)} {t : set (set β)}
(hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) :
@prod.topological_space α β (generate_from s) (generate_from t) =
generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} :=
let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in
le_antisymm
(le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸
@is_open_prod _ _ (generate_from s) (generate_from t) _ _
(generate_open.basic _ hu) (generate_open.basic _ hv))
(le_inf
(coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu,
have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u,
from calc (⋃v∈t, set.prod u v) = set.prod u univ :
set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt}
... = prod.fst ⁻¹' u : by simp [set.prod, preimage],
show G.is_open (prod.fst ⁻¹' u),
from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv,
generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)
(coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv,
have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v,
from calc (⋃u∈s, set.prod u v) = set.prod univ v:
set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt}
... = prod.snd ⁻¹' v : by simp [set.prod, preimage],
show G.is_open (prod.snd ⁻¹' v),
from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu,
generate_open.basic _ ⟨_, hu, _, hv, rfl⟩))
lemma prod_eq_generate_from [tα : topological_space α] [tβ : topological_space β] :
prod.topological_space =
generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} :=
le_antisymm
(le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ is_open_prod hs ht)
(le_inf
(ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩)
(ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩))
lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔
(∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) :=
begin
rw [is_open_iff_nhds],
simp [nhds_prod_eq, mem_prod_iff],
simp [mem_nhds_sets_iff],
exact forall_congr (assume a, ball_congr $ assume b h,
⟨assume ⟨u', ⟨u, us, uo, au⟩, v', ⟨v, vs, vo, bv⟩, h⟩,
⟨u, uo, v, vo, au, bv, subset.trans (set.prod_mono us vs) h⟩,
assume ⟨u, uo, v, vo, au, bv, h⟩,
⟨u, ⟨u, subset.refl u, uo, au⟩, v, ⟨v, subset.refl v, vo, bv⟩, h⟩⟩)
end
lemma closure_prod_eq {s : set α} {t : set β} :
closure (set.prod s t) = set.prod (closure s) (closure t) :=
set.ext $ assume ⟨a, b⟩,
have filter.prod (nhds a) (nhds b) ⊓ principal (set.prod s t) =
filter.prod (nhds a ⊓ principal s) (nhds b ⊓ principal t),
by rw [←prod_inf_prod, prod_principal_principal],
by simp [closure_eq_nhds, nhds_prod_eq, this]; exact prod_neq_bot
lemma mem_closure2 [topological_space α] [topological_space β] [topological_space γ]
{s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β}
(hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t)
(hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) :
f a b ∈ closure u :=
have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩,
show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from
mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb
lemma is_closed_prod [topological_space α] [topological_space β] {s₁ : set α} {s₂ : set β}
(h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) :=
closure_eq_iff_is_closed.mp $ by simp [h₁, h₂, closure_prod_eq, closure_eq_of_is_closed]
lemma dense_range_prod [topological_space δ] {f : α → β} {g : γ → δ} (hf : dense_range f)
(hg : dense_range g) : dense_range (λ p : α × γ, (f p.1, g p.2)) :=
have closure (range $ λ p : α×γ, (f p.1, g p.2)) = set.prod (closure $ range f) (closure $ range g),
by rw [←closure_prod_eq, prod_range_range_eq],
assume ⟨b, d⟩, this.symm ▸ mem_prod.2 ⟨hf _, hg _⟩
protected lemma is_open_map.prod
[topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
{f : α → β} {g : γ → δ}
(hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) :=
begin
rw [is_open_map_iff_nhds_le],
rintros ⟨a, b⟩,
rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq],
exact filter.prod_mono ((is_open_map_iff_nhds_le f).1 hf a) ((is_open_map_iff_nhds_le g).1 hg b)
end
section tube_lemma
def nhds_contain_boxes (s : set α) (t : set β) : Prop :=
∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n),
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n
lemma nhds_contain_boxes.symm {s : set α} {t : set β} :
nhds_contain_boxes s t → nhds_contain_boxes t s :=
assume H n hn hp,
let ⟨u, v, uo, vo, su, tv, p⟩ :=
H (prod.swap ⁻¹' n)
(continuous_swap n hn)
(by rwa [←image_subset_iff, prod.swap, image_swap_prod]) in
⟨v, u, vo, uo, tv, su,
by rwa [←image_subset_iff, prod.swap, image_swap_prod] at p⟩
lemma nhds_contain_boxes.comm {s : set α} {t : set β} :
nhds_contain_boxes s t ↔ nhds_contain_boxes t s :=
iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm
lemma nhds_contain_boxes_of_singleton {x : α} {y : β} :
nhds_contain_boxes ({x} : set α) ({y} : set β) :=
assume n hn hp,
let ⟨u, v, uo, vo, xu, yv, hp'⟩ :=
is_open_prod_iff.mp hn x y (hp $ by simp) in
⟨u, v, uo, vo, by simpa, by simpa, hp'⟩
lemma nhds_contain_boxes_of_compact {s : set α} (hs : compact s) (t : set β)
(H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t :=
assume n hn hp,
have ∀x : subtype s, ∃uv : set α × set β,
is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n,
from assume ⟨x, hx⟩,
have set.prod {x} t ⊆ n, from
subset.trans (prod_mono (by simpa) (subset.refl _)) hp,
let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩,
let ⟨uvs, h⟩ := classical.axiom_of_choice this in
have us_cover : s ⊆ ⋃i, (uvs i).1, from
assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1),
let ⟨s0, _, s0_fin, s0_cover⟩ :=
compact_elim_finite_subcover_image hs (λi _, (h i).1) $
by rw bUnion_univ; exact us_cover in
let u := ⋃(i ∈ s0), (uvs i).1 in
let v := ⋂(i ∈ s0), (uvs i).2 in
have is_open u, from is_open_bUnion (λi _, (h i).1),
have is_open v, from is_open_bInter s0_fin (λi _, (h i).2.1),
have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1),
have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩,
have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx',
let ⟨i,is0,hi⟩ := this in
(h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩,
⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩
lemma generalized_tube_lemma {s : set α} (hs : compact s) {t : set β} (ht : compact t)
{n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) :
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n :=
have _, from
nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $
nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton,
this n hn hp
end tube_lemma
lemma is_closed_diagonal [topological_space α] [t2_space α] : is_closed {p:α×α | p.1 = p.2} :=
is_closed_iff_nhds.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_neq_bot $ assume : nhds a₁ ⊓ nhds a₂ = ⊥, h $
let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ :=
by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in
begin
change t₁ ∈ nhds a₁ at ht₁,
change t₂ ∈ nhds a₂ at ht₂,
rw [nhds_prod_eq, ←empty_in_sets_eq_bot],
apply filter.sets_of_superset,
apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)),
exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩,
show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩
end
lemma is_closed_eq [topological_space α] [t2_space α] [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} :=
continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal
lemma diagonal_eq_range_diagonal_map : {p:α×α | p.1 = p.2} = range (λx, (x,x)) :=
ext $ assume p, iff.intro
(assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩)
(assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx)
lemma prod_subset_compl_diagonal_iff_disjoint {s t : set α} :
set.prod s t ⊆ - {p:α×α | p.1 = p.2} ↔ s ∩ t = ∅ :=
by rw [eq_empty_iff_forall_not_mem, subset_compl_comm,
diagonal_eq_range_diagonal_map, range_subset_iff]; simp
lemma compact_compact_separated [t2_space α] {s t : set α}
(hs : compact s) (ht : compact t) (hst : s ∩ t = ∅) :
∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ :=
by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst;
exact generalized_tube_lemma hs ht is_closed_diagonal hst
lemma closed_of_compact [t2_space α] (s : set α) (hs : compact s) : is_closed s :=
is_open_compl_iff.mpr $ is_open_iff_forall_mem_open.mpr $ assume x hx,
let ⟨u, v, uo, vo, su, xv, uv⟩ :=
compact_compact_separated hs (compact_singleton : compact {x})
(by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in
have v ⊆ -s, from
subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)),
⟨v, this, vo, by simpa using xv⟩
lemma locally_compact_of_compact_nhds [topological_space α] [t2_space α]
(h : ∀ x : α, ∃ s, s ∈ nhds x ∧ compact s) :
locally_compact_space α :=
⟨assume x n hn,
let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in
let ⟨k, kx, kc⟩ := h x in
-- K is compact but not necessarily contained in N.
-- K \ U is again compact and doesn't contain x, so
-- we may find open sets V, W separating x from K \ U.
-- Then K \ W is a compact neighborhood of x contained in U.
let ⟨v, w, vo, wo, xv, kuw, vw⟩ :=
compact_compact_separated compact_singleton (compact_diff kc uo)
(by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in
have wn : -w ∈ nhds x, from
mem_nhds_sets_iff.mpr
⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩,
⟨k - w,
filter.inter_mem_sets kx wn,
subset.trans (diff_subset_comm.mp kuw) un,
compact_diff kc wo⟩⟩
instance locally_compact_of_compact [topological_space α] [t2_space α] [compact_space α] :
locally_compact_space α :=
locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, compact_univ⟩)
-- We can't make this an instance because it could cause an instance loop.
lemma normal_of_compact_t2 [topological_space α] [compact_space α] [t2_space α] : normal_space α :=
begin
refine ⟨assume s t hs ht st, _⟩,
simp only [disjoint_iff],
exact compact_compact_separated (compact_of_closed hs) (compact_of_closed ht) st.eq_bot
end
/- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/
instance [second_countable_topology α] [second_countable_topology β] :
second_countable_topology (α × β) :=
⟨let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := is_open_generated_countable_inter α in
let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := is_open_generated_countable_inter β in
⟨{g | ∃u∈a, ∃v∈b, g = set.prod u v},
have {g | ∃u∈a, ∃v∈b, g = set.prod u v} = (⋃u∈a, ⋃v∈b, {set.prod u v}),
by apply set.ext; simp,
by rw [this]; exact (countable_bUnion ha₁ $ assume u hu, countable_bUnion hb₁ $ by simp),
by rw [ha₅, hb₅, prod_generate_from_generate_from_eq ha₄ hb₄]⟩⟩
lemma compact_prod (s : set α) (t : set β) (ha : compact s) (hb : compact t) : compact (set.prod s t) :=
begin
rw compact_iff_ultrafilter_le_nhds at ha hb ⊢,
intros f hf hfs,
rw le_principal_iff at hfs,
rcases ha (map prod.fst f) (ultrafilter_map hf)
(le_principal_iff.2 (mem_map_sets_iff.2
⟨_, hfs, image_subset_iff.2 (λ s h, h.1)⟩)) with ⟨a, sa, ha⟩,
rcases hb (map prod.snd f) (ultrafilter_map hf)
(le_principal_iff.2 (mem_map_sets_iff.2
⟨_, hfs, image_subset_iff.2 (λ s h, h.2)⟩)) with ⟨b, tb, hb⟩,
rw map_le_iff_le_comap at ha hb,
refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩,
rw nhds_prod_eq, exact le_inf ha hb
end
instance [compact_space α] [compact_space β] : compact_space (α × β) :=
⟨begin
have A : compact (set.prod (univ : set α) (univ : set β)) :=
compact_prod univ univ compact_univ compact_univ,
have : set.prod (univ : set α) (univ : set β) = (univ : set (α × β)) := by simp,
rwa this at A,
end⟩
end prod
section sum
variables [topological_space α] [topological_space β] [topological_space γ]
lemma continuous_inl : continuous (@sum.inl α β) :=
continuous_sup_rng_left continuous_coinduced_rng
lemma continuous_inr : continuous (@sum.inr α β) :=
continuous_sup_rng_right continuous_coinduced_rng
lemma continuous_sum_rec {f : α → γ} {g : β → γ}
(hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) :=
continuous_sup_dom hf hg
lemma embedding_inl : embedding (@sum.inl α β) :=
{ induced := begin
unfold sum.topological_space,
apply le_antisymm,
{ rw ← coinduced_le_iff_le_induced, exact lattice.le_sup_left },
{ intros u hu, existsi (sum.inl '' u),
change
(is_open (sum.inl ⁻¹' (@sum.inl α β '' u)) ∧
is_open (sum.inr ⁻¹' (@sum.inl α β '' u))) ∧
sum.inl ⁻¹' (sum.inl '' u) = u,
have : sum.inl ⁻¹' (@sum.inl α β '' u) = u :=
preimage_image_eq u (λ _ _, sum.inl.inj_iff.mp), rw this,
have : sum.inr ⁻¹' (@sum.inl α β '' u) = ∅ :=
eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, sum.inl_ne_inr h), rw this,
exact ⟨⟨hu, is_open_empty⟩, rfl⟩ }
end,
inj := λ _ _, sum.inl.inj_iff.mp }
lemma embedding_inr : embedding (@sum.inr α β) :=
{ induced := begin
unfold sum.topological_space,
apply le_antisymm,
{ rw ← coinduced_le_iff_le_induced, exact lattice.le_sup_right },
{ intros u hu, existsi (sum.inr '' u),
change
(is_open (sum.inl ⁻¹' (@sum.inr α β '' u)) ∧
is_open (sum.inr ⁻¹' (@sum.inr α β '' u))) ∧
sum.inr ⁻¹' (sum.inr '' u) = u,
have : sum.inl ⁻¹' (@sum.inr α β '' u) = ∅ :=
eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, sum.inr_ne_inl h), rw this,
have : sum.inr ⁻¹' (@sum.inr α β '' u) = u :=
preimage_image_eq u (λ _ _, sum.inr.inj_iff.mp), rw this,
exact ⟨⟨is_open_empty, hu⟩, rfl⟩ }
end,
inj := λ _ _, sum.inr.inj_iff.mp }
instance [topological_space α] [topological_space β] [compact_space α] [compact_space β] :
compact_space (α ⊕ β) :=
⟨begin
have A : compact (@sum.inl α β '' univ) := compact_image compact_univ continuous_inl,
have B : compact (@sum.inr α β '' univ) := compact_image compact_univ continuous_inr,
have C := compact_union_of_compact A B,
have : (@sum.inl α β '' univ) ∪ (@sum.inr α β '' univ) = univ := by ext; cases x; simp,
rwa this at C,
end⟩
end sum
section subtype
variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop}
lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) :=
embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id
lemma embedding_subtype_val : embedding (@subtype.val α p) :=
⟨⟨rfl⟩, subtype.val_injective⟩
lemma continuous_subtype_val : continuous (@subtype.val α p) :=
continuous_induced_dom
lemma continuous_subtype_mk {f : β → α}
(hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) :=
continuous_induced_rng h
lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) :=
continuous_subtype_mk _ continuous_subtype_val
lemma continuous_at_subtype_val [topological_space α] {p : α → Prop} {a : subtype p} :
continuous_at subtype.val a :=
continuous_iff_continuous_at.mp continuous_subtype_val _
lemma map_nhds_subtype_val_eq {a : α} (ha : p a) (h : {a | p a} ∈ nhds a) :
map (@subtype.val α p) (nhds ⟨a, ha⟩) = nhds a :=
map_nhds_induced_eq (by simp [subtype.val_image, h])
lemma nhds_subtype_eq_comap {a : α} {h : p a} :
nhds (⟨a, h⟩ : subtype p) = comap subtype.val (nhds a) :=
nhds_induced _ _
lemma tendsto_subtype_rng [topological_space α] {p : α → Prop} {b : filter β} {f : β → subtype p} :
∀{a:subtype p}, tendsto f b (nhds a) ↔ tendsto (λx, subtype.val (f x)) b (nhds a.val)
| ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff]
lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop}
(c_cover : ∀x:α, ∃i, {x | c i x} ∈ nhds x)
(f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) :
continuous f :=
continuous_iff_continuous_at.mpr $ assume x,
let ⟨i, (c_sets : {x | c i x} ∈ nhds x)⟩ := c_cover x in
let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in
calc map f (nhds x) = map f (map subtype.val (nhds x')) :
congr_arg (map f) (map_nhds_subtype_val_eq _ $ c_sets).symm
... = map (λx:subtype (c i), f x.val) (nhds x') : rfl
... ≤ nhds (f x) : continuous_iff_continuous_at.mp (f_cont i) x'
lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop)
(h_lf : locally_finite (λi, {x | c i x}))
(h_is_closed : ∀i, is_closed {x | c i x})
(h_cover : ∀x, ∃i, c i x)
(f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) :
continuous f :=
continuous_iff_is_closed.mpr $
assume s hs,
have ∀i, is_closed (@subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)),
from assume i,
embedding_is_closed embedding_subtype_val
(by simp [subtype.val_range]; exact h_is_closed i)
(continuous_iff_is_closed.mp (f_cont i) _ hs),
have is_closed (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)),
from is_closed_Union_of_locally_finite
(locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx')
this,
have f ⁻¹' s = (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)),
begin
apply set.ext,
have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s :=
λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩,
λ ⟨i, hi, hx⟩, hx⟩,
simp [and.comm, and.left_comm], simpa [(∘)],
end,
by rwa [this]
lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}:
x ∈ closure s ↔ x.val ∈ closure (subtype.val '' s) :=
closure_induced $ assume x y, subtype.eq
lemma compact_iff_compact_image_of_embedding {s : set α} {f : α → β} (hf : embedding f) :
compact s ↔ compact (f '' s) :=
iff.intro (assume h, compact_image h hf.continuous) $ assume h, begin
rw compact_iff_ultrafilter_le_nhds at ⊢ h,
intros u hu us',
let u' : filter β := map f u,
have : u' ≤ principal (f '' s), begin
rw [map_le_iff_le_comap, comap_principal], convert us',
exact preimage_image_eq _ hf.inj
end,
rcases h u' (ultrafilter_map hu) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩,
refine ⟨a, ha, _⟩,
rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap]
end
lemma compact_iff_compact_in_subtype {s : set {a // p a}} :
compact s ↔ compact (subtype.val '' s) :=
compact_iff_compact_image_of_embedding embedding_subtype_val
lemma compact_iff_compact_univ {s : set α} : compact s ↔ compact (univ : set (subtype s)) :=
by rw [compact_iff_compact_in_subtype, image_univ, subtype.val_range]; refl
lemma compact_iff_compact_space {s : set α} : compact s ↔ compact_space s :=
compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩
end subtype
section quotient
variables [topological_space α] [topological_space β] [topological_space γ]
variables {r : α → α → Prop} {s : setoid α}
lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) :=
⟨quot.exists_rep, rfl⟩
lemma continuous_quot_mk : continuous (@quot.mk α r) :=
continuous_coinduced_rng
lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b)
(h : continuous f) : continuous (quot.lift f hr : quot r → β) :=
continuous_coinduced_dom h
lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) :=
quotient_map_quot_mk
lemma continuous_quotient_mk : continuous (@quotient.mk α s) :=
continuous_coinduced_rng
lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b)
(h : continuous f) : continuous (quotient.lift f hs : quotient s → β) :=
continuous_coinduced_dom h
instance quot.compact_space {r : α → α → Prop} [topological_space α] [compact_space α] :
compact_space (quot r) :=
⟨begin
have : quot.mk r '' univ = univ,
by rw [image_univ, range_iff_surjective]; exact quot.exists_rep,
rw ←this,
exact compact_image compact_univ continuous_quot_mk
end⟩
instance quotient.compact_space {s : setoid α} [topological_space α] [compact_space α] :
compact_space (quotient s) :=
quot.compact_space
end quotient
section pi
variables {ι : Type*} {π : ι → Type*}
open topological_space
lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i}
(h : ∀i, continuous (λa, f a i)) : continuous f :=
continuous_infi_rng $ assume i, continuous_induced_rng $ h i
lemma continuous_apply [∀i, topological_space (π i)] (i : ι) :
continuous (λp:Πi, π i, p i) :=
continuous_infi_dom continuous_induced_dom
lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} :
nhds a = (⨅i, comap (λx, x i) (nhds (a i))) :=
calc nhds a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi
... = (⨅i, comap (λx, x i) (nhds (a i))) : by simp [nhds_induced]
/-- Tychonoff's theorem -/
lemma compact_pi_infinite [∀i, topological_space (π i)] {s : Πi:ι, set (π i)} :
(∀i, compact (s i)) → compact {x : Πi:ι, π i | ∀i, x i ∈ s i} :=
begin
simp [compact_iff_ultrafilter_le_nhds, nhds_pi],
exact assume h f hf hfs,
let p : Πi:ι, filter (π i) := λi, map (λx:Πi:ι, π i, x i) f in
have ∀i:ι, ∃a, a∈s i ∧ p i ≤ nhds a,
from assume i, h i (p i) (ultrafilter_map hf) $
show (λx:Πi:ι, π i, x i) ⁻¹' s i ∈ f.sets,
from mem_sets_of_superset hfs $ assume x (hx : ∀i, x i ∈ s i), hx i,
let ⟨a, ha⟩ := classical.axiom_of_choice this in
⟨a, assume i, (ha i).left, assume i, map_le_iff_le_comap.mp $ (ha i).right⟩
end
lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)}
(hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) :=
by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, continuous_apply a _ $ hs a ha)
lemma pi_eq_generate_from [∀a, topological_space (π a)] :
Pi.topological_space =
generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} :=
le_antisymm
(le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi)
(le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $
⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩)
lemma pi_generate_from_eq {g : Πa, set (set (π a))} :
@Pi.topological_space ι π (λa, generate_from (g a)) =
generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} :=
let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in
begin
rw [pi_eq_generate_from],
refine le_antisymm (generate_from_mono _) (le_generate_from _),
exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩,
{ rintros s ⟨t, i, hi, rfl⟩,
rw [pi_def],
apply is_open_bInter (finset.finite_to_set _),
assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a),
refine le_generate_from _ _ (hi a ha),
exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ }
end
lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) :
@Pi.topological_space ι π (λa, generate_from (g a)) =
generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} :=
let G := {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} in
begin
rw [pi_generate_from_eq],
refine le_antisymm (generate_from_mono _) (le_generate_from _),
exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩,
{ rintros s ⟨t, i, ht, rfl⟩,
apply is_open_iff_forall_mem_open.2 _,
assume f hf,
choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s,
{ assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa },
refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩,
{ simp [pi_if] },
{ refine generate_open.basic _ ⟨_, assume a, _, rfl⟩,
by_cases a ∈ i; simp [*, pi] at * },
{ have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * },
simpa [pi_if, hf] } }
end
instance second_countable_topology_fintype
[fintype ι] [t : ∀a, topological_space (π a)] [sc : ∀a, second_countable_topology (π a)] :
second_countable_topology (∀a, π a) :=
have ∀i, ∃b : set (set (π i)), countable b ∧ ∅ ∉ b ∧ is_topological_basis b, from
assume a, @is_open_generated_countable_inter (π a) _ (sc a),
let ⟨g, hg⟩ := classical.axiom_of_choice this in
have t = (λa, generate_from (g a)), from funext $ assume a, (hg a).2.2.2.2,
begin
constructor,
refine ⟨pi univ '' pi univ g, countable_image _ _, _⟩,
{ suffices : countable {f : Πa, set (π a) | ∀a, f a ∈ g a}, { simpa [pi] },
exact countable_pi (assume i, (hg i).1), },
rw [this, pi_generate_from_eq_fintype],
{ congr' 1, ext f, simp [pi, eq_comm] },
exact assume a, (hg a).2.2.2.1
end
instance pi.compact [∀i:ι, topological_space (π i)] [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) :=
⟨begin
have A : compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} :=
compact_pi_infinite (λi, compact_univ),
have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp,
rwa this at A,
end⟩
end pi
section sigma
variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)]
open lattice
lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) :=
continuous_supr_rng continuous_coinduced_rng
lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) :=
by simp only [is_open_supr_iff, is_open_coinduced]
lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) :=
is_open_sigma_iff
lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) :=
begin
intros s hs,
rw is_open_sigma_iff,
intro j,
classical,
by_cases h : i = j,
{ subst j,
convert hs,
exact set.preimage_image_eq _ injective_sigma_mk },
{ convert is_open_empty,
apply set.eq_empty_of_subset_empty,
rintro x ⟨y, _, hy⟩,
have : i = j, by cc,
contradiction }
end
lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) :=
by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ }
lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) :=
begin
intros s hs,
rw is_closed_sigma_iff,
intro j,
classical,
by_cases h : i = j,
{ subst j,
convert hs,
exact set.preimage_image_eq _ injective_sigma_mk },
{ convert is_closed_empty,
apply set.eq_empty_of_subset_empty,
rintro x ⟨y, _, hy⟩,
have : i = j, by cc,
contradiction }
end
lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) :=
by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ }
lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) :=
closed_embedding_of_continuous_injective_closed
continuous_sigma_mk injective_sigma_mk is_closed_map_sigma_mk
lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) :=
closed_embedding_sigma_mk.1
/-- A map out of a sum type is continuous if its restriction to each summand is. -/
lemma continuous_sigma [topological_space β] {f : sigma σ → β}
(h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f :=
continuous_supr_dom (λ i, continuous_coinduced_dom (h i))
lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)]
{f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) :
continuous (sigma.map f₁ f₂) :=
continuous_sigma $ λ i,
show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)),
from continuous_sigma_mk.comp (hf i)
/-- The sum of embeddings is an embedding. -/
lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)]
{f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) :=
begin
refine ⟨⟨_⟩, injective_sigma_map function.injective_id (λ i, (hf i).inj)⟩,
refine le_antisymm
(continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _,
intros s hs,
replace hs := is_open_sigma_iff.mp hs,
have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s,
{ intro i,
apply is_open_induced_iff.mp,
convert hs i,
exact (hf i).induced.symm },
choose t ht using this,
apply is_open_induced_iff.mpr,
refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩,
ext p,
rcases p with ⟨i, x⟩,
change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s,
rw [←(ht i).2, mem_Union],
split,
{ rintro ⟨j, hj⟩,
rw mem_image at hj,
rcases hj with ⟨y, hy₁, hy₂⟩,
rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩,
replace hy := eq_of_heq hy,
subst y,
exact hy₁ },
{ intro hx,
use i,
rw mem_image,
exact ⟨f i x, hx, rfl⟩ }
end
end sigma
namespace list
variables [topological_space α] [topological_space β]
lemma tendsto_cons' {a : α} {l : list α} :
tendsto (λp:α×list α, list.cons p.1 p.2) ((nhds a).prod (nhds l)) (nhds (a :: l)) :=
by rw [nhds_cons, tendsto, map_prod]; exact le_refl _
lemma tendsto_cons {f : α → β} {g : α → list β}
{a : _root_.filter α} {b : β} {l : list β} (hf : tendsto f a (nhds b)) (hg : tendsto g a (nhds l)) :
tendsto (λa, list.cons (f a) (g a)) a (nhds (b :: l)) :=
tendsto_cons'.comp (tendsto.prod_mk hf hg)
lemma tendsto_cons_iff [topological_space β]
{f : list α → β} {b : _root_.filter β} {a : α} {l : list α} :
tendsto f (nhds (a :: l)) b ↔ tendsto (λp:α×list α, f (p.1 :: p.2)) ((nhds a).prod (nhds l)) b :=
have nhds (a :: l) = ((nhds a).prod (nhds l)).map (λp:α×list α, (p.1 :: p.2)),
begin
simp only
[nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm],
simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm,
end,
by rw [this, filter.tendsto_map'_iff]
lemma tendsto_nhds [topological_space β]
{f : list α → β} {r : list α → _root_.filter β}
(h_nil : tendsto f (pure []) (r []))
(h_cons : ∀l a, tendsto f (nhds l) (r l) → tendsto (λp:α×list α, f (p.1 :: p.2)) ((nhds a).prod (nhds l)) (r (a::l))) :
∀l, tendsto f (nhds l) (r l)
| [] := by rwa [nhds_nil]
| (a::l) := by rw [tendsto_cons_iff]; exact h_cons l a (tendsto_nhds l)
lemma continuous_at_length [topological_space α] :
∀(l : list α), continuous_at list.length l :=
begin
simp only [continuous_at, nhds_discrete],
refine tendsto_nhds _ _,
{ exact tendsto_pure_pure _ _ },
{ assume l a ih,
dsimp only [list.length],
refine tendsto.comp (tendsto_pure_pure (λx, x + 1) _) _,
refine tendsto.comp ih tendsto_snd }
end
lemma tendsto_insert_nth' {a : α} : ∀{n : ℕ} {l : list α},
tendsto (λp:α×list α, insert_nth n p.1 p.2) ((nhds a).prod (nhds l)) (nhds (insert_nth n a l))
| 0 l := tendsto_cons'
| (n+1) [] :=
suffices tendsto (λa, []) (nhds a) (nhds ([] : list α)),
by simpa [nhds_nil, tendsto, map_prod, -filter.pure_def, (∘), insert_nth],
tendsto_const_nhds
| (n+1) (a'::l) :=
have (nhds a).prod (nhds (a' :: l)) =
((nhds a).prod ((nhds a').prod (nhds l))).map (λp:α×α×list α, (p.1, p.2.1 :: p.2.2)),
begin
simp only
[nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm],
simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm
end,
begin
rw [this, tendsto_map'_iff],
exact tendsto_cons
(tendsto_fst.comp tendsto_snd)
((@tendsto_insert_nth' n l).comp (tendsto.prod_mk tendsto_fst (tendsto_snd.comp tendsto_snd)))
end
lemma tendsto_insert_nth {n : ℕ} {a : α} {l : list α} {f : β → α} {g : β → list α}
{b : _root_.filter β} (hf : tendsto f b (nhds a)) (hg : tendsto g b (nhds l)) :
tendsto (λb:β, insert_nth n (f b) (g b)) b (nhds (insert_nth n a l)) :=
tendsto_insert_nth'.comp (tendsto.prod_mk hf hg)
lemma continuous_insert_nth {n : ℕ} : continuous (λp:α×list α, insert_nth n p.1 p.2) :=
continuous_iff_continuous_at.mpr $
assume ⟨a, l⟩, by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth'
lemma tendsto_remove_nth : ∀{n : ℕ} {l : list α},
tendsto (λl, remove_nth l n) (nhds l) (nhds (remove_nth l n))
| _ [] := by rw [nhds_nil]; exact tendsto_pure_nhds _ _
| 0 (a::l) := by rw [tendsto_cons_iff]; exact tendsto_snd
| (n+1) (a::l) :=
begin
rw [tendsto_cons_iff],
dsimp [remove_nth],
exact tendsto_cons tendsto_fst ((@tendsto_remove_nth n l).comp tendsto_snd)
end
lemma continuous_remove_nth {n : ℕ} : continuous (λl : list α, remove_nth l n) :=
continuous_iff_continuous_at.mpr $ assume a, tendsto_remove_nth
end list
namespace vector
open list filter
instance (n : ℕ) [topological_space α] : topological_space (vector α n) :=
by unfold vector; apply_instance
lemma cons_val {n : ℕ} {a : α} : ∀{v : vector α n}, (a :: v).val = a :: v.val
| ⟨l, hl⟩ := rfl
lemma tendsto_cons [topological_space α] {n : ℕ} {a : α} {l : vector α n}:
tendsto (λp:α×vector α n, vector.cons p.1 p.2) ((nhds a).prod (nhds l)) (nhds (a :: l)) :=
by
simp [tendsto_subtype_rng, cons_val];
exact tendsto_cons tendsto_fst (tendsto.comp continuous_at_subtype_val tendsto_snd)
lemma tendsto_insert_nth
[topological_space α] {n : ℕ} {i : fin (n+1)} {a:α} :
∀{l:vector α n}, tendsto (λp:α×vector α n, insert_nth p.1 i p.2)
((nhds a).prod (nhds l)) (nhds (insert_nth a i l))
| ⟨l, hl⟩ :=
begin
rw [insert_nth, tendsto_subtype_rng],
simp [insert_nth_val],
exact list.tendsto_insert_nth tendsto_fst (tendsto.comp continuous_at_subtype_val tendsto_snd : _)
end
lemma continuous_insert_nth' [topological_space α] {n : ℕ} {i : fin (n+1)} :
continuous (λp:α×vector α n, insert_nth p.1 i p.2) :=
continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩,
by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth
lemma continuous_insert_nth [topological_space α] [topological_space β] {n : ℕ} {i : fin (n+1)}
{f : β → α} {g : β → vector α n} (hf : continuous f) (hg : continuous g) :
continuous (λb, insert_nth (f b) i (g b)) :=
continuous_insert_nth'.comp (continuous.prod_mk hf hg)
lemma continuous_at_remove_nth [topological_space α] {n : ℕ} {i : fin (n+1)} :
∀{l:vector α (n+1)}, continuous_at (remove_nth i) l
| ⟨l, hl⟩ :=
-- ∀{l:vector α (n+1)}, tendsto (remove_nth i) (nhds l) (nhds (remove_nth i l))
--| ⟨l, hl⟩ :=
begin
rw [continuous_at, remove_nth, tendsto_subtype_rng],
simp [remove_nth_val],
exact tendsto.comp list.tendsto_remove_nth continuous_at_subtype_val
end
lemma continuous_remove_nth [topological_space α] {n : ℕ} {i : fin (n+1)} :
continuous (remove_nth i : vector α (n+1) → vector α n) :=
continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, continuous_at_remove_nth
end vector
namespace dense_inducing
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
/-- The product of two dense inducings is a dense inducing -/
protected def prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_inducing e₁) (de₂ : dense_inducing e₂) :
dense_inducing (λ(p : α × γ), (e₁ p.1, e₂ p.2)) :=
{ induced := (de₁.to_inducing.prod_mk de₂.to_inducing).induced,
dense := dense_range_prod de₁.dense de₂.dense }
end dense_inducing
namespace dense_embedding
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
/-- The product of two dense embeddings is a dense embedding -/
protected def prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁) (de₂ : dense_embedding e₂) :
dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) :=
{ inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩,
by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩,
..dense_inducing.prod de₁.to_dense_inducing de₂.to_dense_inducing }
def subtype_emb (p : α → Prop) {e : α → β} (de : dense_embedding e) (x : {x // p x}) :
{x // x ∈ closure (e '' {x | p x})} :=
⟨e x.1, subset_closure $ mem_image_of_mem e x.2⟩
protected def subtype (p : α → Prop) {e : α → β} (de : dense_embedding e) :
dense_embedding (de.subtype_emb p) :=
{ dense_embedding .
dense := assume ⟨x, hx⟩, closure_subtype.mpr $
have (λ (x : {x // p x}), e (x.val)) = e ∘ subtype.val, from rfl,
begin
rw ← image_univ,
simp [(image_comp _ _ _).symm, (∘), subtype_emb, -image_univ],
rw [this, image_comp, subtype.val_image],
simp,
assumption
end,
inj := assume ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq $ de.inj $ @@congr_arg subtype.val h,
induced := (induced_iff_nhds_eq _).2 (assume ⟨x, hx⟩,
by simp [subtype_emb, nhds_subtype_eq_comap, de.to_inducing.nhds_eq_comap, comap_comap_comp, (∘)]) }
end dense_embedding
lemma is_closed_property [topological_space α] [topological_space β] {e : α → β} {p : β → Prop}
(he : closure (range e) = univ) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) :
∀b, p b :=
have univ ⊆ {b | p b},
from calc univ = closure (range e) : he.symm
... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h
... = _ : closure_eq_of_is_closed hp,
assume b, this trivial
lemma is_closed_property2 [topological_space α] [topological_space β] {e : α → β} {p : β → β → Prop}
(he : dense_embedding e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) :
∀b₁ b₂, p b₁ b₂ :=
have ∀q:β×β, p q.1 q.2,
from is_closed_property (he.prod he).to_dense_inducing.closure_range hp $ assume a, h _ _,
assume b₁ b₂, this ⟨b₁, b₂⟩
lemma is_closed_property3 [topological_space α] [topological_space β] {e : α → β} {p : β → β → β → Prop}
(he : dense_embedding e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) :
∀b₁ b₂ b₃, p b₁ b₂ b₃ :=
have ∀q:β×β×β, p q.1 q.2.1 q.2.2,
from is_closed_property (he.prod $ he.prod he).to_dense_inducing.closure_range hp $
assume ⟨a₁, a₂, a₃⟩, h _ _ _,
assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩
lemma mem_closure_of_continuous [topological_space α] [topological_space β]
{f : α → β} {a : α} {s : set α} {t : set β}
(hf : continuous f) (ha : a ∈ closure s) (h : ∀a∈s, f a ∈ closure t) :
f a ∈ closure t :=
calc f a ∈ f '' closure s : mem_image_of_mem _ ha
... ⊆ closure (f '' s) : image_closure_subset_closure_image hf
... ⊆ closure (closure t) : closure_mono $ image_subset_iff.mpr $ h
... ⊆ closure t : begin rw [closure_eq_of_is_closed], exact subset.refl _, exact is_closed_closure end
lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ]
{f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ}
(hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t)
(h : ∀a∈s, ∀b∈t, f a b ∈ closure u) :
f a b ∈ closure u :=
have (a,b) ∈ closure (set.prod s t),
by simp [closure_prod_eq, ha, hb],
show f (a, b).1 (a, b).2 ∈ closure u,
from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $
assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
/-- α and β are homeomorph, also called topological isomoph -/
structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β]
extends α ≃ β :=
(continuous_to_fun : continuous to_fun)
(continuous_inv_fun : continuous inv_fun)
infix ` ≃ₜ `:25 := homeomorph
namespace homeomorph
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
instance : has_coe_to_fun (α ≃ₜ β) := ⟨λ_, α → β, λe, e.to_equiv⟩
lemma coe_eq_to_equiv (h : α ≃ₜ β) (a : α) : h a = h.to_equiv a := rfl
protected def refl (α : Type*) [topological_space α] : α ≃ₜ α :=
{ continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. equiv.refl α }
protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ :=
{ continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun,
continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun,
.. equiv.trans h₁.to_equiv h₂.to_equiv }
protected def symm (h : α ≃ₜ β) : β ≃ₜ α :=
{ continuous_to_fun := h.continuous_inv_fun,
continuous_inv_fun := h.continuous_to_fun,
.. h.to_equiv.symm }
protected def continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun
lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id :=
funext $ assume a, h.to_equiv.left_inv a
lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id :=
funext $ assume a, h.to_equiv.right_inv a
lemma range_coe (h : α ≃ₜ β) : range h = univ :=
eq_univ_of_forall $ assume b, ⟨h.symm b, congr_fun h.self_comp_symm b⟩
lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h :=
image_eq_preimage_of_inverse h.symm.to_equiv.left_inv h.symm.to_equiv.right_inv
lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h :=
(image_eq_preimage_of_inverse h.to_equiv.left_inv h.to_equiv.right_inv).symm
lemma induced_eq
{α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) :
tβ.induced h = tα :=
le_antisymm
(calc topological_space.induced ⇑h tβ ≤ _ : induced_mono (coinduced_le_iff_le_induced.1 h.symm.continuous)
... ≤ tα : by rw [induced_compose, symm_comp_self, induced_id] ; exact le_refl _)
(coinduced_le_iff_le_induced.1 h.continuous)
lemma coinduced_eq
{α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) :
tα.coinduced h = tβ :=
le_antisymm
h.continuous
begin
have : (tβ.coinduced h.symm).coinduced h ≤ tα.coinduced h := coinduced_mono h.symm.continuous,
rwa [coinduced_compose, self_comp_symm, coinduced_id] at this,
end
lemma compact_image {s : set α} (h : α ≃ₜ β) : compact (h '' s) ↔ compact s :=
⟨λ hs, by have := compact_image hs h.symm.continuous;
rwa [← image_comp, symm_comp_self, image_id] at this,
λ hs, compact_image hs h.continuous⟩
lemma compact_preimage {s : set β} (h : α ≃ₜ β) : compact (h ⁻¹' s) ↔ compact s :=
by rw ← image_symm; exact h.symm.compact_image
protected lemma embedding (h : α ≃ₜ β) : embedding h :=
⟨⟨h.induced_eq.symm⟩, h.to_equiv.injective⟩
protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h :=
{ dense := assume a, by rw [h.range_coe, closure_univ]; trivial,
inj := h.to_equiv.injective,
induced := (induced_iff_nhds_eq _).2 (assume a, by rw [← nhds_induced, h.induced_eq]) }
protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h :=
begin
assume s,
rw ← h.preimage_symm,
exact h.symm.continuous s
end
protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h :=
begin
assume s,
rw ← h.preimage_symm,
exact continuous_iff_is_closed.1 (h.symm.continuous) _
end
protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h :=
⟨h.to_equiv.surjective, h.coinduced_eq.symm⟩
def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ :=
{ continuous_to_fun :=
continuous.prod_mk (h₁.continuous.comp continuous_fst) (h₂.continuous.comp continuous_snd),
continuous_inv_fun :=
continuous.prod_mk (h₁.symm.continuous.comp continuous_fst) (h₂.symm.continuous.comp continuous_snd),
.. h₁.to_equiv.prod_congr h₂.to_equiv }
section
variables (α β γ)
def prod_comm : α × β ≃ₜ β × α :=
{ continuous_to_fun := continuous.prod_mk continuous_snd continuous_fst,
continuous_inv_fun := continuous.prod_mk continuous_snd continuous_fst,
.. equiv.prod_comm α β }
def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) :=
{ continuous_to_fun :=
continuous.prod_mk (continuous_fst.comp continuous_fst)
(continuous.prod_mk (continuous_snd.comp continuous_fst) continuous_snd),
continuous_inv_fun := continuous.prod_mk
(continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd))
(continuous_snd.comp continuous_snd),
.. equiv.prod_assoc α β γ }
end
end homeomorph
|
9dcf65afc943965c0c1d0ba9e532788b60ed3eeb | 4727251e0cd73359b15b664c3170e5d754078599 | /src/group_theory/specific_groups/alternating.lean | 8e21bef327ee740de71f2c7f8c759691b4f79fca | [
"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 | 15,061 | 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 group_theory.perm.fin
import tactic.interval_cases
/-!
# Alternating Groups
The alternating group on a finite type `α` is the subgroup of the permutation group `perm α`
consisting of the even permutations.
## Main definitions
* `alternating_group α` is the alternating group on `α`, defined as a `subgroup (perm α)`.
## Main results
* `two_mul_card_alternating_group` shows that the alternating group is half as large as
the permutation group it is a subgroup of.
* `closure_three_cycles_eq_alternating` shows that the alternating group is
generated by 3-cycles.
* `alternating_group.is_simple_group_five` shows that the alternating group on `fin 5` is simple.
The proof shows that the normal closure of any non-identity element of this group contains a
3-cycle.
## Tags
alternating group permutation
## TODO
* Show that `alternating_group α` is simple if and only if `fintype.card α ≠ 4`.
-/
open equiv equiv.perm subgroup fintype
variables (α : Type*) [fintype α] [decidable_eq α]
/-- The alternating group on a finite type, realized as a subgroup of `equiv.perm`.
For $A_n$, use `alternating_group (fin n)`. -/
@[derive fintype] def alternating_group : subgroup (perm α) :=
sign.ker
instance [subsingleton α] : unique (alternating_group α) :=
⟨⟨1⟩, λ ⟨p, hp⟩, subtype.eq (subsingleton.elim p _)⟩
variables {α}
lemma alternating_group_eq_sign_ker : alternating_group α = sign.ker := rfl
namespace equiv.perm
@[simp]
lemma mem_alternating_group {f : perm α} :
f ∈ alternating_group α ↔ sign f = 1 :=
sign.mem_ker
lemma prod_list_swap_mem_alternating_group_iff_even_length {l : list (perm α)}
(hl : ∀ g ∈ l, is_swap g) :
l.prod ∈ alternating_group α ↔ even l.length :=
begin
rw [mem_alternating_group, sign_prod_list_swap hl, ← units.coe_eq_one, units.coe_pow,
units.coe_neg_one, neg_one_pow_eq_one_iff_even],
dec_trivial
end
lemma is_three_cycle.mem_alternating_group {f : perm α} (h : is_three_cycle f) :
f ∈ alternating_group α :=
mem_alternating_group.2 h.sign
lemma fin_rotate_bit1_mem_alternating_group {n : ℕ} :
fin_rotate (bit1 n) ∈ alternating_group (fin (bit1 n)) :=
by rw [mem_alternating_group, bit1, sign_fin_rotate, pow_bit0', int.units_mul_self, one_pow]
end equiv.perm
lemma two_mul_card_alternating_group [nontrivial α] :
2 * card (alternating_group α) = card (perm α) :=
begin
let := (quotient_group.quotient_ker_equiv_of_surjective _ (sign_surjective α)).to_equiv,
rw [←fintype.card_units_int, ←fintype.card_congr this],
exact (subgroup.card_eq_card_quotient_mul_card_subgroup _).symm,
end
namespace alternating_group
open equiv.perm
instance normal : (alternating_group α).normal := sign.normal_ker
lemma is_conj_of {σ τ : alternating_group α}
(hc : is_conj (σ : perm α) (τ : perm α)) (hσ : (σ : perm α).support.card + 2 ≤ fintype.card α) :
is_conj σ τ :=
begin
obtain ⟨σ, hσ⟩ := σ,
obtain ⟨τ, hτ⟩ := τ,
obtain ⟨π, hπ⟩ := is_conj_iff.1 hc,
rw [subtype.coe_mk, subtype.coe_mk] at hπ,
cases int.units_eq_one_or (sign π) with h h,
{ rw is_conj_iff,
refine ⟨⟨π, mem_alternating_group.mp h⟩, subtype.val_injective _⟩,
simpa only [subtype.val_eq_coe, subgroup.coe_mul, coe_inv, coe_mk] using hπ },
{ have h2 : 2 ≤ σ.supportᶜ.card,
{ rw [finset.card_compl, le_tsub_iff_left σ.support.card_le_univ],
exact hσ },
obtain ⟨a, ha, b, hb, ab⟩ := finset.one_lt_card.1 h2,
refine is_conj_iff.2 ⟨⟨π * swap a b, _⟩, subtype.val_injective _⟩,
{ rw [mem_alternating_group, monoid_hom.map_mul, h, sign_swap ab, int.units_mul_self] },
{ simp only [←hπ, coe_mk, subgroup.coe_mul, subtype.val_eq_coe],
have hd : disjoint (swap a b) σ,
{ rw [disjoint_iff_disjoint_support, support_swap ab, finset.disjoint_insert_left,
finset.disjoint_singleton_left],
exact ⟨finset.mem_compl.1 ha, finset.mem_compl.1 hb⟩ },
rw [mul_assoc π _ σ, hd.commute.eq, coe_inv, coe_mk],
simp [mul_assoc] } }
end
lemma is_three_cycle_is_conj (h5 : 5 ≤ fintype.card α)
{σ τ : alternating_group α}
(hσ : is_three_cycle (σ : perm α)) (hτ : is_three_cycle (τ : perm α)) :
is_conj σ τ :=
alternating_group.is_conj_of (is_conj_iff_cycle_type_eq.2 (hσ.trans hτ.symm))
(by rwa hσ.card_support)
end alternating_group
namespace equiv.perm
open alternating_group
@[simp]
theorem closure_three_cycles_eq_alternating :
closure {σ : perm α | is_three_cycle σ} = alternating_group α :=
closure_eq_of_le _ (λ σ hσ, mem_alternating_group.2 hσ.sign) $ λ σ hσ, begin
suffices hind : ∀ (n : ℕ) (l : list (perm α)) (hl : ∀ g, g ∈ l → is_swap g)
(hn : l.length = 2 * n), l.prod ∈ closure {σ : perm α | is_three_cycle σ},
{ obtain ⟨l, rfl, hl⟩ := trunc_swap_factors σ,
obtain ⟨n, hn⟩ := (prod_list_swap_mem_alternating_group_iff_even_length hl).1 hσ,
rw ← two_mul at hn,
exact hind n l hl hn },
intro n,
induction n with n ih; intros l hl hn,
{ simp [list.length_eq_zero.1 hn, one_mem] },
rw [nat.mul_succ] at hn,
obtain ⟨a, l, rfl⟩ := l.exists_of_length_succ hn,
rw [list.length_cons, nat.succ_inj'] at hn,
obtain ⟨b, l, rfl⟩ := l.exists_of_length_succ hn,
rw [list.prod_cons, list.prod_cons, ← mul_assoc],
rw [list.length_cons, nat.succ_inj'] at hn,
exact mul_mem (is_swap.mul_mem_closure_three_cycles (hl a (list.mem_cons_self a _))
(hl b (list.mem_cons_of_mem a (l.mem_cons_self b))))
(ih _ (λ g hg, hl g (list.mem_cons_of_mem _ (list.mem_cons_of_mem _ hg))) hn),
end
/-- A key lemma to prove $A_5$ is simple. Shows that any normal subgroup of an alternating group on
at least 5 elements is the entire alternating group if it contains a 3-cycle. -/
lemma is_three_cycle.alternating_normal_closure (h5 : 5 ≤ fintype.card α)
{f : perm α} (hf : is_three_cycle f) :
normal_closure ({⟨f, hf.mem_alternating_group⟩} : set (alternating_group α)) = ⊤ :=
eq_top_iff.2 begin
have hi : function.injective (alternating_group α).subtype := subtype.coe_injective,
refine eq_top_iff.1 (map_injective hi (le_antisymm (map_mono le_top) _)),
rw [← monoid_hom.range_eq_map, subtype_range, normal_closure, monoid_hom.map_closure],
refine (le_of_eq closure_three_cycles_eq_alternating.symm).trans (closure_mono _),
intros g h,
obtain ⟨c, rfl⟩ := is_conj_iff.1 (is_conj_iff_cycle_type_eq.2 (hf.trans h.symm)),
refine ⟨⟨c * f * c⁻¹, h.mem_alternating_group⟩, _, rfl⟩,
rw group.mem_conjugates_of_set_iff,
exact ⟨⟨f, hf.mem_alternating_group⟩, set.mem_singleton _, is_three_cycle_is_conj h5 hf h⟩
end
/-- Part of proving $A_5$ is simple. Shows that the square of any element of $A_5$ with a 3-cycle in
its cycle decomposition is a 3-cycle, so the normal closure of the original element must be
$A_5$. -/
lemma is_three_cycle_sq_of_three_mem_cycle_type_five {g : perm (fin 5)} (h : 3 ∈ cycle_type g) :
is_three_cycle (g * g) :=
begin
obtain ⟨c, g', rfl, hd, hc, h3⟩ := mem_cycle_type_iff.1 h,
simp only [mul_assoc],
rw [hd.commute.eq, ← mul_assoc g'],
suffices hg' : order_of g' ∣ 2,
{ rw [← pow_two, order_of_dvd_iff_pow_eq_one.1 hg', one_mul],
exact (card_support_eq_three_iff.1 h3).is_three_cycle_sq },
rw [← lcm_cycle_type, multiset.lcm_dvd],
intros n hn,
rw le_antisymm (two_le_of_mem_cycle_type hn) (le_trans (le_card_support_of_mem_cycle_type hn) _),
apply le_of_add_le_add_left,
rw [← hd.card_support_mul, h3],
exact (c * g').support.card_le_univ,
end
end equiv.perm
namespace alternating_group
open equiv.perm
lemma nontrivial_of_three_le_card (h3 : 3 ≤ card α) : nontrivial (alternating_group α) :=
begin
haveI := fintype.one_lt_card_iff_nontrivial.1 (lt_trans dec_trivial h3),
rw ← fintype.one_lt_card_iff_nontrivial,
refine lt_of_mul_lt_mul_left _ (le_of_lt nat.prime_two.pos),
rw [two_mul_card_alternating_group, card_perm, ← nat.succ_le_iff],
exact le_trans h3 (card α).self_le_factorial,
end
instance {n : ℕ} : nontrivial (alternating_group (fin (n + 3))) :=
nontrivial_of_three_le_card (by { rw card_fin, exact le_add_left (le_refl 3) })
/-- The normal closure of the 5-cycle `fin_rotate 5` within $A_5$ is the whole group. This will be
used to show that the normal closure of any 5-cycle within $A_5$ is the whole group. -/
lemma normal_closure_fin_rotate_five :
(normal_closure ({⟨fin_rotate 5, fin_rotate_bit1_mem_alternating_group⟩} :
set (alternating_group (fin 5)))) = ⊤ :=
eq_top_iff.2 begin
have h3 : is_three_cycle ((fin.cycle_range 2) * (fin_rotate 5) *
(fin.cycle_range 2)⁻¹ * (fin_rotate 5)⁻¹) := card_support_eq_three_iff.1 dec_trivial,
rw ← h3.alternating_normal_closure (by rw [card_fin]),
refine normal_closure_le_normal _,
rw [set.singleton_subset_iff, set_like.mem_coe],
have h : (⟨fin_rotate 5, fin_rotate_bit1_mem_alternating_group⟩ :
alternating_group (fin 5)) ∈ normal_closure _ :=
set_like.mem_coe.1 (subset_normal_closure (set.mem_singleton _)),
exact mul_mem (subgroup.normal_closure_normal.conj_mem _ h
⟨fin.cycle_range 2, fin.is_three_cycle_cycle_range_two.mem_alternating_group⟩) (inv_mem h),
end
/-- The normal closure of $(04)(13)$ within $A_5$ is the whole group. This will be
used to show that the normal closure of any permutation of cycle type $(2,2)$ is the whole group.
-/
lemma normal_closure_swap_mul_swap_five :
(normal_closure ({⟨swap 0 4 * swap 1 3, mem_alternating_group.2 dec_trivial⟩} :
set (alternating_group (fin 5)))) = ⊤ :=
begin
let g1 := (⟨swap 0 2 * swap 0 1, mem_alternating_group.2 dec_trivial⟩ :
alternating_group (fin 5)),
let g2 := (⟨swap 0 4 * swap 1 3, mem_alternating_group.2 dec_trivial⟩ :
alternating_group (fin 5)),
have h5 : g1 * g2 * g1⁻¹ * g2⁻¹ = ⟨fin_rotate 5, fin_rotate_bit1_mem_alternating_group⟩,
{ rw subtype.ext_iff,
simp only [fin.coe_mk, subgroup.coe_mul, subgroup.coe_inv, fin.coe_mk],
dec_trivial },
rw [eq_top_iff, ← normal_closure_fin_rotate_five],
refine normal_closure_le_normal _,
rw [set.singleton_subset_iff, set_like.mem_coe, ← h5],
have h : g2 ∈ normal_closure {g2} :=
set_like.mem_coe.1 (subset_normal_closure (set.mem_singleton _)),
exact mul_mem (subgroup.normal_closure_normal.conj_mem _ h g1) (inv_mem h),
end
/-- Shows that any non-identity element of $A_5$ whose cycle decomposition consists only of swaps
is conjugate to $(04)(13)$. This is used to show that the normal closure of such a permutation
in $A_5$ is $A_5$. -/
lemma is_conj_swap_mul_swap_of_cycle_type_two {g : perm (fin 5)}
(ha : g ∈ alternating_group (fin 5))
(h1 : g ≠ 1)
(h2 : ∀ n, n ∈ cycle_type (g : perm (fin 5)) → n = 2) :
is_conj (swap 0 4 * swap 1 3) g :=
begin
have h := g.support.card_le_univ,
rw [← sum_cycle_type, multiset.eq_repeat_of_mem h2, multiset.sum_repeat, smul_eq_mul] at h,
rw [← multiset.eq_repeat'] at h2,
have h56 : 5 ≤ 3 * 2 := nat.le_succ 5,
have h := le_of_mul_le_mul_right (le_trans h h56) dec_trivial,
rw [mem_alternating_group, sign_of_cycle_type, h2] at ha,
norm_num at ha,
rw [pow_add, pow_mul, int.units_pow_two,one_mul,
units.ext_iff, units.coe_one, units.coe_pow, units.coe_neg_one,
neg_one_pow_eq_one_iff_even _] at ha,
swap, { dec_trivial },
rw [is_conj_iff_cycle_type_eq, h2],
interval_cases multiset.card g.cycle_type,
{ exact (h1 (card_cycle_type_eq_zero.1 h_1)).elim },
{ contrapose! ha,
simp [h_1] },
{ have h04 : (0 : fin 5) ≠ 4 := dec_trivial,
have h13 : (1 : fin 5) ≠ 3 := dec_trivial,
rw [h_1, disjoint.cycle_type, (is_cycle_swap h04).cycle_type, (is_cycle_swap h13).cycle_type,
card_support_swap h04, card_support_swap h13],
{ refl },
{ rw [disjoint_iff_disjoint_support, support_swap h04, support_swap h13],
dec_trivial } },
{ contrapose! ha,
simp [h_1] }
end
/-- Shows that $A_5$ is simple by taking an arbitrary non-identity element and showing by casework
on its cycle type that its normal closure is all of $A_5$. -/
instance is_simple_group_five : is_simple_group (alternating_group (fin 5)) :=
⟨exists_pair_ne _, λ H, begin
introI Hn,
refine or_not.imp (id) (λ Hb, _),
rw [eq_bot_iff_forall] at Hb,
push_neg at Hb,
obtain ⟨⟨g, gA⟩, gH, g1⟩ : ∃ (x : ↥(alternating_group (fin 5))), x ∈ H ∧ x ≠ 1 := Hb,
-- `g` is a non-identity alternating permutation in a normal subgroup `H` of $A_5$.
rw [← set_like.mem_coe, ← set.singleton_subset_iff] at gH,
refine eq_top_iff.2 (le_trans (ge_of_eq _) (normal_closure_le_normal gH)),
-- It suffices to show that the normal closure of `g` in $A_5$ is $A_5$.
by_cases h2 : ∀ n ∈ g.cycle_type, n = 2,
{ -- If the cycle decomposition of `g` consists entirely of swaps, then the cycle type is $(2,2)$.
-- This means that it is conjugate to $(04)(13)$, whose normal closure is $A_5$.
rw [ne.def, subtype.ext_iff] at g1,
exact (is_conj_swap_mul_swap_of_cycle_type_two gA g1 h2).normal_closure_eq_top_of
normal_closure_swap_mul_swap_five },
push_neg at h2,
obtain ⟨n, ng, n2⟩ : ∃ (n : ℕ), n ∈ g.cycle_type ∧ n ≠ 2 := h2,
-- `n` is the size of a non-swap cycle in the decomposition of `g`.
have n2' : 2 < n := lt_of_le_of_ne (two_le_of_mem_cycle_type ng) n2.symm,
have n5 : n ≤ 5 := le_trans _ g.support.card_le_univ,
-- We check that `2 < n ≤ 5`, so that `interval_cases` has a precise range to check.
swap, { obtain ⟨m, hm⟩ := multiset.exists_cons_of_mem ng,
rw [← sum_cycle_type, hm, multiset.sum_cons],
exact le_add_right le_rfl },
interval_cases n, -- This breaks into cases `n = 3`, `n = 4`, `n = 5`.
{ -- If `n = 3`, then `g` has a 3-cycle in its decomposition, so `g^2` is a 3-cycle.
-- `g^2` is in the normal closure of `g`, so that normal closure must be $A_5$.
rw [eq_top_iff, ← (is_three_cycle_sq_of_three_mem_cycle_type_five ng).alternating_normal_closure
(by rw card_fin )],
refine normal_closure_le_normal _,
rw [set.singleton_subset_iff, set_like.mem_coe],
have h := set_like.mem_coe.1 (subset_normal_closure (set.mem_singleton _)),
exact mul_mem h h },
{ -- The case `n = 4` leads to contradiction, as no element of $A_5$ includes a 4-cycle.
have con := mem_alternating_group.1 gA,
contrapose! con,
rw [sign_of_cycle_type,
cycle_type_of_card_le_mem_cycle_type_add_two dec_trivial ng],
dec_trivial },
{ -- If `n = 5`, then `g` is itself a 5-cycle, conjugate to `fin_rotate 5`.
refine (is_conj_iff_cycle_type_eq.2 _).normal_closure_eq_top_of
normal_closure_fin_rotate_five,
rw [cycle_type_of_card_le_mem_cycle_type_add_two dec_trivial ng, cycle_type_fin_rotate] }
end⟩
end alternating_group
|
88dd9c0282e94da76bbf1719c68f3ecf36e72830 | 6b2a480f27775cba4f3ae191b1c1387a29de586e | /group_rep1/morphism/Reynold_operator.lean | bc617228f967b8cb1971c4c0c084c01d7aab23d6 | [] | no_license | Or7ando/group_representation | a681de2e19d1930a1e1be573d6735a2f0b8356cb | 9b576984f17764ebf26c8caa2a542d248f1b50d2 | refs/heads/master | 1,662,413,107,324 | 1,590,302,389,000 | 1,590,302,389,000 | 258,130,829 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 4,509 | lean | import group_representation
import morphism
import Tools.to_sum
import Tools.sum_group
/-!
* Let `ρ and π` two representations on `M` and `M'`. Let `f : M →ₗ[R] M'` a `linear_map`.
* Let `ℒ f := Σ_{g ∈ G} π g⁻¹ ∘ f ∘ ρ g`, then `ℒ f` is a morphism `ρ ⟶ π`.
* Proof : `∀ t ∈ G, ρ t ∘ ℒ f ∘ π t⁻¹ := ∑ ρ t g⁻¹ ∘ f ∘ π g t = ∑ t'⁻¹ ∘ f ∘ π t'`
# We start to define sum operator on `M →ₗ[R] M'`
* Let `(X : Type u)[fintype X]` and ` φ : X → M→ₗ[R]M'`. We fix a notation for
* `finset.sum finset.univ φ := Σ φ`.
-/
universes u v w w'
open linear_map TEST
/-!
* We illustrate in a first time the name of the function.
-/
namespace Illustration
notation `Σ` := finset.sum (finset.univ)
variables {G : Type u } [group G][fintype G]
{R : Type v}[comm_ring R]
{M : Type w} [add_comm_group M] [module R M]
{M' : Type w'} [add_comm_group M'] [module R M']
(ρ : G → M →ₗ[R]M')
(f : M' →ₗ[R]M')
(g : M →ₗ[R]M)
(x : M)
/-!
Here ` * ` denote the composition of linear application. We have a structure of `add_comm_monoid`
on ` M→ₗ[R]M' ` That ensure `Σ` is well define.
-/
example : f * Σ ρ = Σ (λ s, f * ρ s) := Sum_comp_left ρ f
example : (Σ ρ) * g = Σ (λ s, (ρ s) * g ) := Sum_comp_right ρ g
example : (Σ ρ ) x = Σ (λ g, ρ g x) := Sum_apply ρ x
end Illustration
variables {G : Type u} [group G][fintype G]
{R : Type v}[comm_ring R] --- Commutative ring
namespace Reynold
open Illustration
variables {M : Type w} [add_comm_group M] [module R M]
{M' : Type w'} [add_comm_group M'] [module R M']
(ρ : group_representation G R M)
(π : group_representation G R M')
lemma coersion (s g : G) : (((ρ s * ρ g⁻¹) * ρ g) : M→ₗ[R]M) = linear_map.comp ((ρ s * ρ g⁻¹) : M→ₗ[R] M ) (ρ g : M→ₗ[R]M ) := rfl
/--
We start to define `mixte_conj (f : M→ₗ[R]M')(s : G) : M→ₗ[R] M' := π s⁻¹ * f * ρ s`
-/
def mixte_conj (f : M→ₗ[R]M') : G → M→ₗ[R] M' := λ s, ↑(π s⁻¹) * f * ↑(ρ s)
lemma mixte_conj_ext (f : M→ₗ[R]M')(s : G) : mixte_conj ρ π f s = ↑(π s⁻¹) * f * ↑(ρ s) := rfl
/--
we have `∀ g : G, (π g) (π s⁻¹) * f * ρ s = π (s g⁻¹)⁻¹ * f * ρ (s g⁻¹) * ρ g`
so `π g * mixte_conj s = mixte_conj (s g⁻¹) ρ g`
-/
theorem mixte_conj_mul_left (f : M→ₗ[R]M') (g : G)(s : G):
↑(π g) * (mixte_conj ρ π f s) = (mixte_conj ρ π f (s * g⁻¹)) * ↑(ρ g ) :=
begin
rw mixte_conj_ext, rw mixte_conj_ext,
erw mul_inv_rev, rw inv_inv, rw π.map_mul, rw ρ.map_mul,
erw linear_map.comp_assoc ↑(ρ g), rw ← coersion ρ s g,
rw mul_assoc, rw ← ρ.map_mul , rw inv_mul_self, rw ρ.map_one, rw mul_one, exact rfl,
end
theorem mixte_conj_mul_left_fun (f : M→ₗ[R]M') (g : G) :
(λ s : G, ↑(π g) * (mixte_conj ρ π f s)) = (λ s, (mixte_conj ρ π f (s * g⁻¹)) * ↑(ρ g )) :=
begin
ext,rw mixte_conj_mul_left,
end
--- TO DO : i have to study more the operator.
--- For the organisation : perhaps just give the definition here and
--- To the work in other file ?
/--
The operator `ℒ`
-/
def ℒ (f : M→ₗ[R]M') : M→ₗ[R] M' := finset.sum finset.univ (mixte_conj ρ π f)
/--
*
*
-/
theorem Per (f : M→ₗ[R]M') (g : G) : Σ (mixte_conj ρ π f) = Σ (λ s, mixte_conj ρ π f (s * g⁻¹)) :=
@Sum_equiv G (M→ₗ[R]M') _ g (mixte_conj ρ π f) _ (to_equiv g)
theorem L_is_morphism (f : M→ₗ[R]M') (g : G) : (π g : M'→ₗ[R]M') * (ℒ ρ π f) = (ℒ ρ π f) * (ρ g : M→ₗ[R] M) := begin
unfold ℒ,
erw Sum_comp_left,
rw mixte_conj_mul_left_fun,
rw ← Sum_comp_right,
rw Per ρ π f g,
end
/--
The Reynold opérator.
-/
def ℛ : (M→ₗ[R]M') → (ρ ⟶ π) := λ f, { ℓ := ℒ ρ π f,
commute := begin
intros g, ext x, rw function.comp_apply,
let theo := L_is_morphism ρ π f g,
rw linear_map.ext_iff at theo,
specialize theo x,
rw linear_map.comp_apply at theo,
erw ← theo, exact rfl,
end }
lemma reynold_ext(f : M →ₗ[R]M' ) : (ℛ ρ π f).ℓ = finset.sum finset.univ (mixte_conj ρ π f) := rfl
#check ℛ ρ ρ
end Reynold
namespace more_on_mixte_conj
open Reynold
end more_on_mixte_conj |
777d83188f74616751d4029ae83f24e1ba2ad79d | 618003631150032a5676f229d13a079ac875ff77 | /src/topology/algebra/ring.lean | 4f5d14fbc83b55d5ee829a1840f4bbe4428353bb | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 4,000 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
Theory of topological rings.
-/
import topology.algebra.group
import ring_theory.ideals
open classical set filter topological_space
open_locale classical
section topological_ring
universes u v w
variables (α : Type u) [topological_space α]
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A topological semiring is a semiring where addition and multiplication are continuous. -/
class topological_semiring [semiring α]
extends topological_add_monoid α, topological_monoid α : Prop
end prio
variables [ring α]
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A topological ring is a ring where the ring operations are continuous. -/
class topological_ring extends topological_add_monoid α, topological_monoid α : Prop :=
(continuous_neg : continuous (λa:α, -a))
end prio
variables [t : topological_ring α]
@[priority 100] -- see Note [lower instance priority]
instance topological_ring.to_topological_semiring : topological_semiring α := {..t}
@[priority 100] -- see Note [lower instance priority]
instance topological_ring.to_topological_add_group : topological_add_group α := {..t}
end topological_ring
section topological_comm_ring
variables {α : Type*} [topological_space α] [comm_ring α] [topological_ring α]
def ideal.closure (S : ideal α) : ideal α :=
{ carrier := closure S,
zero := subset_closure S.zero_mem,
add := assume x y hx hy,
mem_closure2 continuous_add hx hy $ assume a b, S.add_mem,
smul := assume c x hx,
have continuous (λx:α, c * x) := continuous_const.mul continuous_id,
mem_closure this hx $ assume a, S.mul_mem_left }
@[simp] lemma ideal.coe_closure (S : ideal α) :
(S.closure : set α) = closure S := rfl
end topological_comm_ring
section topological_ring
variables {α : Type*} [topological_space α] [comm_ring α] (N : ideal α)
open ideal.quotient
instance topological_ring_quotient_topology : topological_space N.quotient :=
by dunfold ideal.quotient submodule.quotient; apply_instance
lemma quotient_ring_saturate {α : Type*} [comm_ring α] (N : ideal α) (s : set α) :
mk N ⁻¹' (mk N '' s) = (⋃ x : N, (λ y, x.1 + y) '' s) :=
begin
ext x,
simp only [mem_preimage, mem_image, mem_Union, ideal.quotient.eq],
split,
{ exact assume ⟨a, a_in, h⟩, ⟨⟨_, N.neg_mem h⟩, a, a_in, by simp⟩ },
{ exact assume ⟨⟨i, hi⟩, a, ha, eq⟩, ⟨a, ha,
by rw [← eq, sub_add_eq_sub_sub_swap, sub_self, zero_sub];
exact N.neg_mem hi⟩ }
end
variable [topological_ring α]
lemma quotient_ring.is_open_map_coe : is_open_map (mk N) :=
begin
assume s s_op,
show is_open (mk N ⁻¹' (mk N '' s)),
rw quotient_ring_saturate N s,
exact is_open_Union (assume ⟨n, _⟩, is_open_map_add_left n s s_op)
end
lemma quotient_ring.quotient_map_coe_coe : quotient_map (λ p : α × α, (mk N p.1, mk N p.2)) :=
begin
apply is_open_map.to_quotient_map,
{ exact (quotient_ring.is_open_map_coe N).prod (quotient_ring.is_open_map_coe N) },
{ exact (continuous_quot_mk.comp continuous_fst).prod_mk
(continuous_quot_mk.comp continuous_snd) },
{ rintro ⟨⟨x⟩, ⟨y⟩⟩,
exact ⟨(x, y), rfl⟩ }
end
instance topological_ring_quotient : topological_ring N.quotient :=
{ continuous_add :=
have cont : continuous (mk N ∘ (λ (p : α × α), p.fst + p.snd)) :=
continuous_quot_mk.comp continuous_add,
(quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).2 cont,
continuous_neg := continuous_quotient_lift _ (continuous_quot_mk.comp continuous_neg),
continuous_mul :=
have cont : continuous (mk N ∘ (λ (p : α × α), p.fst * p.snd)) :=
continuous_quot_mk.comp continuous_mul,
(quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).2 cont }
end topological_ring
|
d30bf41f447aadbfe5edf6dd1f0e12fcd99b0594 | fecda8e6b848337561d6467a1e30cf23176d6ad0 | /src/category_theory/opposites.lean | f2182f2dae62c1562565929edc781e4bb73293ef | [
"Apache-2.0"
] | permissive | spolu/mathlib | bacf18c3d2a561d00ecdc9413187729dd1f705ed | 480c92cdfe1cf3c2d083abded87e82162e8814f4 | refs/heads/master | 1,671,684,094,325 | 1,600,736,045,000 | 1,600,736,045,000 | 297,564,749 | 1 | 0 | null | 1,600,758,368,000 | 1,600,758,367,000 | null | UTF-8 | Lean | false | false | 9,728 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Stephen Morgan, Scott Morrison
-/
import category_theory.types
import category_theory.equivalence
import data.opposite
universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
namespace category_theory
open opposite
variables {C : Type u₁}
section has_hom
variables [has_hom.{v₁} C]
/-- The hom types of the opposite of a category (or graph).
As with the objects, we'll make this irreducible below.
Use `f.op` and `f.unop` to convert between morphisms of C
and morphisms of Cᵒᵖ.
-/
instance has_hom.opposite : has_hom Cᵒᵖ :=
{ hom := λ X Y, unop Y ⟶ unop X }
def has_hom.hom.op {X Y : C} (f : X ⟶ Y) : op Y ⟶ op X := f
def has_hom.hom.unop {X Y : Cᵒᵖ} (f : X ⟶ Y) : unop Y ⟶ unop X := f
attribute [irreducible] has_hom.opposite
lemma has_hom.hom.op_inj {X Y : C} :
function.injective (has_hom.hom.op : (X ⟶ Y) → (op Y ⟶ op X)) :=
λ _ _ H, congr_arg has_hom.hom.unop H
lemma has_hom.hom.unop_inj {X Y : Cᵒᵖ} :
function.injective (has_hom.hom.unop : (X ⟶ Y) → (unop Y ⟶ unop X)) :=
λ _ _ H, congr_arg has_hom.hom.op H
@[simp] lemma has_hom.hom.unop_op {X Y : C} {f : X ⟶ Y} : f.op.unop = f := rfl
@[simp] lemma has_hom.hom.op_unop {X Y : Cᵒᵖ} {f : X ⟶ Y} : f.unop.op = f := rfl
end has_hom
variables [category.{v₁} C]
/--
The opposite category.
See https://stacks.math.columbia.edu/tag/001M.
-/
instance category.opposite : category.{v₁} Cᵒᵖ :=
{ comp := λ _ _ _ f g, (g.unop ≫ f.unop).op,
id := λ X, (𝟙 (unop X)).op }
@[simp] lemma op_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} :
(f ≫ g).op = g.op ≫ f.op := rfl
@[simp] lemma op_id {X : C} : (𝟙 X).op = 𝟙 (op X) := rfl
@[simp] lemma unop_comp {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} :
(f ≫ g).unop = g.unop ≫ f.unop := rfl
@[simp] lemma unop_id {X : Cᵒᵖ} : (𝟙 X).unop = 𝟙 (unop X) := rfl
@[simp] lemma unop_id_op {X : C} : (𝟙 (op X)).unop = 𝟙 X := rfl
@[simp] lemma op_id_unop {X : Cᵒᵖ} : (𝟙 (unop X)).op = 𝟙 X := rfl
/-- The functor from the double-opposite of a category to the underlying category. -/
@[simps]
def op_op : (Cᵒᵖ)ᵒᵖ ⥤ C :=
{ obj := λ X, unop (unop X),
map := λ X Y f, f.unop.unop }
/-- The functor from a category to its double-opposite. -/
@[simps]
def unop_unop : C ⥤ Cᵒᵖᵒᵖ :=
{ obj := λ X, op (op X),
map := λ X Y f, f.op.op }
/-- The double opposite category is equivalent to the original. -/
@[simps]
def op_op_equivalence : Cᵒᵖᵒᵖ ≌ C :=
{ functor := op_op,
inverse := unop_unop,
unit_iso := iso.refl (𝟭 Cᵒᵖᵒᵖ),
counit_iso := iso.refl (unop_unop ⋙ op_op) }
def is_iso_of_op {X Y : C} (f : X ⟶ Y) [is_iso f.op] : is_iso f :=
{ inv := (inv (f.op)).unop,
hom_inv_id' := has_hom.hom.op_inj (by simp),
inv_hom_id' := has_hom.hom.op_inj (by simp) }
namespace functor
section
variables {D : Type u₂} [category.{v₂} D]
variables {C D}
@[simps]
protected definition op (F : C ⥤ D) : Cᵒᵖ ⥤ Dᵒᵖ :=
{ obj := λ X, op (F.obj (unop X)),
map := λ X Y f, (F.map f.unop).op }
@[simps]
protected definition unop (F : Cᵒᵖ ⥤ Dᵒᵖ) : C ⥤ D :=
{ obj := λ X, unop (F.obj (op X)),
map := λ X Y f, (F.map f.op).unop }
/-- The isomorphism between `F.op.unop` and `F`. -/
def op_unop_iso (F : C ⥤ D) : F.op.unop ≅ F :=
nat_iso.of_components (λ X, iso.refl _) (by tidy)
/-- The isomorphism between `F.unop.op` and `F`. -/
def unop_op_iso (F : Cᵒᵖ ⥤ Dᵒᵖ) : F.unop.op ≅ F :=
nat_iso.of_components (λ X, iso.refl _) (by tidy)
variables (C D)
@[simps]
definition op_hom : (C ⥤ D)ᵒᵖ ⥤ (Cᵒᵖ ⥤ Dᵒᵖ) :=
{ obj := λ F, (unop F).op,
map := λ F G α,
{ app := λ X, (α.unop.app (unop X)).op,
naturality' := λ X Y f, has_hom.hom.unop_inj (α.unop.naturality f.unop).symm } }
@[simps]
definition op_inv : (Cᵒᵖ ⥤ Dᵒᵖ) ⥤ (C ⥤ D)ᵒᵖ :=
{ obj := λ F, op F.unop,
map := λ F G α, has_hom.hom.op
{ app := λ X, (α.app (op X)).unop,
naturality' := λ X Y f, has_hom.hom.op_inj $ (α.naturality f.op).symm } }
-- TODO show these form an equivalence
variables {C D}
@[simps]
protected definition left_op (F : C ⥤ Dᵒᵖ) : Cᵒᵖ ⥤ D :=
{ obj := λ X, unop (F.obj (unop X)),
map := λ X Y f, (F.map f.unop).unop }
@[simps]
protected definition right_op (F : Cᵒᵖ ⥤ D) : C ⥤ Dᵒᵖ :=
{ obj := λ X, op (F.obj (op X)),
map := λ X Y f, (F.map f.op).op }
-- TODO show these form an equivalence
instance {F : C ⥤ D} [full F] : full F.op :=
{ preimage := λ X Y f, (F.preimage f.unop).op }
instance {F : C ⥤ D} [faithful F] : faithful F.op :=
{ map_injective' := λ X Y f g h,
has_hom.hom.unop_inj $ by simpa using map_injective F (has_hom.hom.op_inj h) }
/-- If F is faithful then the right_op of F is also faithful. -/
instance right_op_faithful {F : Cᵒᵖ ⥤ D} [faithful F] : faithful F.right_op :=
{ map_injective' := λ X Y f g h, has_hom.hom.op_inj (map_injective F (has_hom.hom.op_inj h)) }
/-- If F is faithful then the left_op of F is also faithful. -/
instance left_op_faithful {F : C ⥤ Dᵒᵖ} [faithful F] : faithful F.left_op :=
{ map_injective' := λ X Y f g h, has_hom.hom.unop_inj (map_injective F (has_hom.hom.unop_inj h)) }
end
end functor
namespace nat_trans
variables {D : Type u₂} [category.{v₂} D]
section
variables {F G : C ⥤ D}
local attribute [semireducible] has_hom.opposite
@[simps] protected definition op (α : F ⟶ G) : G.op ⟶ F.op :=
{ app := λ X, (α.app (unop X)).op,
naturality' := begin tidy, erw α.naturality, refl, end }
@[simp] lemma op_id (F : C ⥤ D) : nat_trans.op (𝟙 F) = 𝟙 (F.op) := rfl
@[simps] protected definition unop (α : F.op ⟶ G.op) : G ⟶ F :=
{ app := λ X, (α.app (op X)).unop,
naturality' :=
begin
intros X Y f,
have := congr_arg has_hom.hom.op (α.naturality f.op),
dsimp at this,
erw this,
refl,
end }
@[simp] lemma unop_id (F : C ⥤ D) : nat_trans.unop (𝟙 F.op) = 𝟙 F := rfl
end
section
variables {F G : C ⥤ Dᵒᵖ}
local attribute [semireducible] has_hom.opposite
protected definition left_op (α : F ⟶ G) : G.left_op ⟶ F.left_op :=
{ app := λ X, (α.app (unop X)).unop,
naturality' := begin tidy, erw α.naturality, refl, end }
@[simp] lemma left_op_app (α : F ⟶ G) (X) :
(nat_trans.left_op α).app X = (α.app (unop X)).unop :=
rfl
protected definition right_op (α : F.left_op ⟶ G.left_op) : G ⟶ F :=
{ app := λ X, (α.app (op X)).op,
naturality' :=
begin
intros X Y f,
have := congr_arg has_hom.hom.op (α.naturality f.op),
dsimp at this,
erw this
end }
@[simp] lemma right_op_app (α : F.left_op ⟶ G.left_op) (X) :
(nat_trans.right_op α).app X = (α.app (op X)).op :=
rfl
end
end nat_trans
namespace iso
variables {X Y : C}
protected definition op (α : X ≅ Y) : op Y ≅ op X :=
{ hom := α.hom.op,
inv := α.inv.op,
hom_inv_id' := has_hom.hom.unop_inj α.inv_hom_id,
inv_hom_id' := has_hom.hom.unop_inj α.hom_inv_id }
@[simp] lemma op_hom {α : X ≅ Y} : α.op.hom = α.hom.op := rfl
@[simp] lemma op_inv {α : X ≅ Y} : α.op.inv = α.inv.op := rfl
end iso
namespace nat_iso
variables {D : Type u₂} [category.{v₂} D]
variables {F G : C ⥤ D}
/-- The natural isomorphism between opposite functors `G.op ≅ F.op` induced by a natural
isomorphism between the original functors `F ≅ G`. -/
protected definition op (α : F ≅ G) : G.op ≅ F.op :=
{ hom := nat_trans.op α.hom,
inv := nat_trans.op α.inv,
hom_inv_id' := begin ext, dsimp, rw ←op_comp, rw α.inv_hom_id_app, refl, end,
inv_hom_id' := begin ext, dsimp, rw ←op_comp, rw α.hom_inv_id_app, refl, end }
@[simp] lemma op_hom (α : F ≅ G) : (nat_iso.op α).hom = nat_trans.op α.hom := rfl
@[simp] lemma op_inv (α : F ≅ G) : (nat_iso.op α).inv = nat_trans.op α.inv := rfl
/-- The natural isomorphism between functors `G ≅ F` induced by a natural isomorphism
between the opposite functors `F.op ≅ G.op`. -/
protected definition unop (α : F.op ≅ G.op) : G ≅ F :=
{ hom := nat_trans.unop α.hom,
inv := nat_trans.unop α.inv,
hom_inv_id' := begin ext, dsimp, rw ←unop_comp, rw α.inv_hom_id_app, refl, end,
inv_hom_id' := begin ext, dsimp, rw ←unop_comp, rw α.hom_inv_id_app, refl, end }
@[simp] lemma unop_hom (α : F.op ≅ G.op) : (nat_iso.unop α).hom = nat_trans.unop α.hom := rfl
@[simp] lemma unop_inv (α : F.op ≅ G.op) : (nat_iso.unop α).inv = nat_trans.unop α.inv := rfl
end nat_iso
/-- The equivalence between arrows of the form `A ⟶ B` and `B.unop ⟶ A.unop`. Useful for building
adjunctions.
Note that this (definitionally) gives variants
```
def op_equiv' (A : C) (B : Cᵒᵖ) : (opposite.op A ⟶ B) ≃ (B.unop ⟶ A) :=
op_equiv _ _
def op_equiv'' (A : Cᵒᵖ) (B : C) : (A ⟶ opposite.op B) ≃ (B ⟶ A.unop) :=
op_equiv _ _
def op_equiv''' (A B : C) : (opposite.op A ⟶ opposite.op B) ≃ (B ⟶ A) :=
op_equiv _ _
```
-/
def op_equiv (A B : Cᵒᵖ) : (A ⟶ B) ≃ (B.unop ⟶ A.unop) :=
{ to_fun := λ f, f.unop,
inv_fun := λ g, g.op,
left_inv := λ _, rfl,
right_inv := λ _, rfl }
-- These two are made by hand rather than by simps because simps generates
-- `(op_equiv _ _).to_fun f = ...` rather than the coercion version.
@[simp]
lemma op_equiv_apply (A B : Cᵒᵖ) (f : A ⟶ B) : op_equiv _ _ f = f.unop :=
rfl
@[simp]
lemma op_equiv_symm_apply (A B : Cᵒᵖ) (f : B.unop ⟶ A.unop) : (op_equiv _ _).symm f = f.op :=
rfl
end category_theory
|
29edbf5db72279860d8bd99a32853ceafce68f8a | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/data/set.lean | 5802358f52df8310a6ad8c37910776a051b6da3d | [] | 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 | 3,622 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.meta.interactive
import Mathlib.Lean3Lib.init.control.lawful
universes u v u_1
namespace Mathlib
def set (α : Type u) :=
α → Prop
def set_of {α : Type u} (p : α → Prop) : set α :=
p
namespace set
protected def mem {α : Type u} (a : α) (s : set α) :=
s a
protected instance has_mem {α : Type u} : has_mem α (set α) :=
has_mem.mk set.mem
protected def subset {α : Type u} (s₁ : set α) (s₂ : set α) :=
∀ {a : α}, a ∈ s₁ → a ∈ s₂
protected instance has_subset {α : Type u} : has_subset (set α) :=
has_subset.mk set.subset
protected def sep {α : Type u} (p : α → Prop) (s : set α) : set α :=
set_of fun (a : α) => a ∈ s ∧ p a
protected instance has_sep {α : Type u} : has_sep α (set α) :=
has_sep.mk set.sep
protected instance has_emptyc {α : Type u} : has_emptyc (set α) :=
has_emptyc.mk fun (a : α) => False
def univ {α : Type u} : set α :=
fun (a : α) => True
protected def insert {α : Type u} (a : α) (s : set α) : set α :=
set_of fun (b : α) => b = a ∨ b ∈ s
protected instance has_insert {α : Type u} : has_insert α (set α) :=
has_insert.mk set.insert
protected instance has_singleton {α : Type u} : has_singleton α (set α) :=
has_singleton.mk fun (a : α) => set_of fun (b : α) => b = a
protected instance is_lawful_singleton {α : Type u} : is_lawful_singleton α (set α) :=
is_lawful_singleton.mk fun (a : α) => funext fun (b : α) => propext (or_false (b = a))
protected def union {α : Type u} (s₁ : set α) (s₂ : set α) : set α :=
set_of fun (a : α) => a ∈ s₁ ∨ a ∈ s₂
protected instance has_union {α : Type u} : has_union (set α) :=
has_union.mk set.union
protected def inter {α : Type u} (s₁ : set α) (s₂ : set α) : set α :=
set_of fun (a : α) => a ∈ s₁ ∧ a ∈ s₂
protected instance has_inter {α : Type u} : has_inter (set α) :=
has_inter.mk set.inter
def compl {α : Type u} (s : set α) : set α :=
set_of fun (a : α) => ¬a ∈ s
protected def diff {α : Type u} (s : set α) (t : set α) : set α :=
has_sep.sep (fun (a : α) => ¬a ∈ t) s
protected instance has_sdiff {α : Type u} : has_sdiff (set α) :=
has_sdiff.mk set.diff
def powerset {α : Type u} (s : set α) : set (set α) :=
set_of fun (t : set α) => t ⊆ s
prefix:100 "𝒫" => Mathlib.set.powerset
def sUnion {α : Type u} (s : set (set α)) : set α :=
set_of fun (t : α) => ∃ (a : set α), ∃ (H : a ∈ s), t ∈ a
prefix:110 "⋃₀" => Mathlib.set.sUnion
def image {α : Type u} {β : Type v} (f : α → β) (s : set α) : set β :=
set_of fun (b : β) => ∃ (a : α), a ∈ s ∧ f a = b
protected instance functor : Functor set :=
{ map := image, mapConst := fun (α β : Type u_1) => image ∘ function.const β }
protected instance is_lawful_functor : is_lawful_functor set :=
is_lawful_functor.mk
(fun (_x : Type u_1) (s : set _x) =>
funext
fun (b : _x) =>
propext
{ mp := fun (_x : Functor.map id s b) => sorry,
mpr := fun (sb : s b) => Exists.intro b { left := sb, right := rfl } })
fun (_x _x_1 _x_2 : Type u_1) (g : _x → _x_1) (h : _x_1 → _x_2) (s : set _x) =>
funext
fun (c : _x_2) =>
propext
{ mp := fun (_x : Functor.map (h ∘ g) s c) => sorry, mpr := fun (_x : Functor.map h (g <$> s) c) => sorry }
|
1daefdf3d4b44f1fe1908c5a1e3de0dfbcd7928f | a7602958ab456501ff85db8cf5553f7bcab201d7 | /Notes/Theorem_Proving_in_Lean/Chapter2/2.2.lean | 4ea1cca51b5f82cb9b933306fdd7ba95224de781 | [] | no_license | enlauren/math-logic | 081e2e737c8afb28dbb337968df95ead47321ba0 | 086b6935543d1841f1db92d0e49add1124054c37 | refs/heads/master | 1,594,506,621,950 | 1,558,634,976,000 | 1,558,634,976,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,670 | lean | -- 2.2 Types as Objects
-- In Lean, types such as ℕ and bool are first-class objects as well,
-- meaning they must have a type.
#check ℕ -- Its type is: |Type|.
-- Therefore we can create our own types:
constant α: Type
constant f: Type → Type
constant g: Type → Type → Type
#check α
#check f α
#check f ℕ
#check g (f ℕ) α
-- Above, saying `constant α: Type` actually created a new type α for us.
-- We can use this type as follows:
constant m: α
constant alpha_only_fn: α → α
#check alpha_only_fn m
-- #check alpha_only_fn α -- This will not work though.
-- We cannot write, for example: `alpha_only_fn α`, because α is the
-- Type that the function accepts, therefore we cannot give it the
-- actual type itself, we have to give it something _of type_ α. This
-- is like doing the following:
-- #check bool && bool
-- The above commented out line does not work because `&&` is expecting
-- something of type |bool|, not the type itself. Bool is of type |Type|,
-- so technically there is a mismatch.
--------------------------------------------------------
-- Given any |Type| α, `list α` denotes a list of type α.
#check list ℕ
#check list α
-- What type is |Type|?
#check Type
#check Type 233
#check list (Type 233)
-- Lean has an infinite hierarchy of types, each expanding in magnitude!
constant DomType: Type 11
#check DomType -- A very powerful/general type, encapsulating Types 0-10.
#check list -- Output means that whenever the given argument has a type
-- of Type n, the expression `list α` is also of type Type n.
#check list α -- It makes sense. α's type is |Type|, and so is `list α`. |
171e448b6a5cce2c16b50d38750e8140e2310977 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/localized.lean | 9567958e8adba0f004713a33b0859f445e5a2239 | [
"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 | 4,530 | lean | /-
Copyright (c) 2019 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import tactic.core
/-!
# Localized notation
This consists of two user-commands which allow you to declare notation and commands localized to a
locale.
See the tactic doc entry below for more information.
The code is inspired by code from Gabriel Ebner from the
[hott3 repository](https://github.com/gebner/hott3).
-/
open lean lean.parser interactive tactic native
@[user_attribute]
meta def localized_attr : user_attribute (rb_lmap name string) unit := {
name := "_localized",
descr := "(interal) attribute that flags localized commands",
cache_cfg := ⟨λ ns, (do dcls ← ns.mmap (λ n, mk_const n >>= eval_expr (name × string)),
return $ rb_lmap.of_list dcls), []⟩
}
/-- Get all commands in the given locale and return them as a list of strings -/
meta def get_localized (ns : list name) : tactic (list string) :=
do m ← localized_attr.get_cache,
ns.mfoldl (λ l nm, match m.find nm with
| [] := fail format!"locale {nm} does not exist"
| new_l := return $ l.append new_l
end) []
/-- Execute all commands in the given locale -/
@[user_command] meta def open_locale_cmd (_ : parse $ tk "open_locale") : parser unit :=
do ns ← many ident,
cmds ← get_localized ns,
cmds.mmap' emit_code_here
/-- Add a new command to a locale and execute it right now.
The new command is added as a declaration to the environment with name `_localized_decl.<number>`.
This declaration has attribute `_localized` and as value a name-string pair. -/
@[user_command] meta def localized_cmd (_ : parse $ tk "localized") : parser unit :=
do cmd ← parser.pexpr, cmd ← i_to_expr cmd, cmd ← eval_expr string cmd,
let cmd := "local " ++ cmd,
emit_code_here cmd,
tk "in",
nm ← ident,
env ← get_env,
let dummy_decl_name := mk_num_name `_localized_decl
((string.hash (cmd ++ nm.to_string) + env.fingerprint) % unsigned_sz),
add_decl (declaration.defn dummy_decl_name [] `(name × string)
(reflect (⟨nm, cmd⟩ : name × string)) (reducibility_hints.regular 1 tt) ff),
localized_attr.set dummy_decl_name unit.star tt
/--
This consists of two user-commands which allow you to declare notation and commands localized to a
locale.
* Declare notation which is localized to a locale using:
```lean
localized "infix ` ⊹ `:60 := my_add" in my.add
```
* After this command it will be available in the same section/namespace/file, just as if you wrote
`local infix ` ⊹ `:60 := my_add`
* You can open it in other places. The following command will declare the notation again as local
notation in that section/namespace/file:
```lean
open_locale my.add
```
* More generally, the following will declare all localized notation in the specified locales.
```lean
open_locale locale1 locale2 ...
```
* You can also declare other localized commands, like local attributes
```lean
localized "attribute [simp] le_refl" in le
```
* To see all localized commands in a given locale, run:
```lean
run_cmd print_localized_commands [`my.add].
```
* To see a list of all locales with localized commands, run:
```lean
run_cmd do
m ← localized_attr.get_cache,
tactic.trace m.keys -- change to `tactic.trace m.to_list` to list all the commands in each locale
```
* Warning: You have to give full names of all declarations used in localized notation,
so that the localized notation also works when the appropriate namespaces are not opened.
-/
add_tactic_doc
{ name := "localized notation",
category := doc_category.cmd,
decl_names := [`localized_cmd, `open_locale_cmd],
tags := ["notation", "type classes"] }
/-- Print all commands in a given locale -/
meta def print_localized_commands (ns : list name) : tactic unit :=
do cmds ← get_localized ns, cmds.mmap' trace
-- you can run `open_locale classical` to get the decidability of all propositions, and downgrade
-- the priority of decidability instances that make Lean run through all the algebraic hierarchy
-- whenever it wants to solve a decidability question
localized "attribute [instance, priority 9] classical.prop_decidable" in classical
localized "attribute [instance, priority 8] eq.decidable decidable_eq_of_decidable_le" in classical
localized "postfix `?`:9001 := optional" in parser
localized "postfix *:9001 := lean.parser.many" in parser
|
d95fbb5d4760b454f1b3767dff46a39f7a6d279f | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/nat/sqrt.lean | 98b405ff80774c64be0689743ef8b9f1016f6ab9 | [
"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 | 9,605 | 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, Johannes Hölzl, Mario Carneiro
-/
import data.int.basic
/-!
# Square root of natural numbers
This file defines an efficient binary implementation of the square root function that returns the
unique `r` such that `r * r ≤ n < (r + 1) * (r + 1)`. It takes advantage of the binary
representation by replacing the multiplication by 2 appearing in
`(a + b)^2 = a^2 + 2 * a * b + b^2` by a bitmask manipulation.
## Reference
See [Wikipedia, *Methods of computing square roots*]
[https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)].
-/
namespace nat
theorem sqrt_aux_dec {b} (h : b ≠ 0) : shiftr b 2 < b :=
begin
simp only [shiftr_eq_div_pow],
apply (nat.div_lt_iff_lt_mul' (dec_trivial : 0 < 4)).2,
have := nat.mul_lt_mul_of_pos_left
(dec_trivial : 1 < 4) (nat.pos_of_ne_zero h),
rwa mul_one at this
end
/-- Auxiliary function for `nat.sqrt`. See e.g.
<https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)> -/
def sqrt_aux : ℕ → ℕ → ℕ → ℕ
| b r n := if b0 : b = 0 then r else
let b' := shiftr b 2 in
have b' < b, from sqrt_aux_dec b0,
match (n - (r + b : ℕ) : ℤ) with
| (n' : ℕ) := sqrt_aux b' (div2 r + b) n'
| _ := sqrt_aux b' (div2 r) n
end
/-- `sqrt n` is the square root of a natural number `n`. If `n` is not a
perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/
@[pp_nodot] def sqrt (n : ℕ) : ℕ :=
match size n with
| 0 := 0
| succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n
end
theorem sqrt_aux_0 (r n) : sqrt_aux 0 r n = r :=
by rw sqrt_aux; simp
local attribute [simp] sqrt_aux_0
theorem sqrt_aux_1 {r n b} (h : b ≠ 0) {n'} (h₂ : r + b + n' = n) :
sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r + b) n' :=
by rw sqrt_aux; simp only [h, h₂.symm, int.coe_nat_add, if_false];
rw [add_comm _ (n':ℤ), add_sub_cancel, sqrt_aux._match_1]
theorem sqrt_aux_2 {r n b} (h : b ≠ 0) (h₂ : n < r + b) :
sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r) n :=
begin
rw sqrt_aux; simp only [h, h₂, if_false],
cases int.eq_neg_succ_of_lt_zero
(sub_lt_zero.2 (int.coe_nat_lt_coe_nat_of_lt h₂)) with k e,
rw [e, sqrt_aux._match_1]
end
private def is_sqrt (n q : ℕ) : Prop := q*q ≤ n ∧ n < (q+1)*(q+1)
local attribute [-simp] mul_eq_mul_left_iff mul_eq_mul_right_iff
private lemma sqrt_aux_is_sqrt_lemma (m r n : ℕ)
(h₁ : r*r ≤ n)
(m') (hm : shiftr (2^m * 2^m) 2 = m')
(H1 : n < (r + 2^m) * (r + 2^m) →
is_sqrt n (sqrt_aux m' (r * 2^m) (n - r * r)))
(H2 : (r + 2^m) * (r + 2^m) ≤ n →
is_sqrt n (sqrt_aux m' ((r + 2^m) * 2^m) (n - (r + 2^m) * (r + 2^m)))) :
is_sqrt n (sqrt_aux (2^m * 2^m) ((2*r)*2^m) (n - r*r)) :=
begin
have b0 :=
have b0:_, from ne_of_gt (pow_pos (show 0 < 2, from dec_trivial) m),
nat.mul_ne_zero b0 b0,
have lb : n - r * r < 2 * r * 2^m + 2^m * 2^m ↔
n < (r+2^m)*(r+2^m),
{ rw [tsub_lt_iff_right h₁],
simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc,
add_comm, add_assoc, add_left_comm] },
have re : div2 (2 * r * 2^m) = r * 2^m,
{ rw [div2_val, mul_assoc,
nat.mul_div_cancel_left _ (dec_trivial:2>0)] },
cases lt_or_ge n ((r+2^m)*(r+2^m)) with hl hl,
{ rw [sqrt_aux_2 b0 (lb.2 hl), hm, re], apply H1 hl },
{ cases le.dest hl with n' e,
rw [@sqrt_aux_1 (2 * r * 2^m) (n-r*r) (2^m * 2^m) b0 (n - (r + 2^m) * (r + 2^m)),
hm, re, ← right_distrib],
{ apply H2 hl },
apply eq.symm, apply tsub_eq_of_eq_add_rev,
rw [← add_assoc, (_ : r*r + _ = _)],
exact (add_tsub_cancel_of_le hl).symm,
simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_assoc] },
end
private lemma sqrt_aux_is_sqrt (n) : ∀ m r,
r*r ≤ n → n < (r + 2^(m+1)) * (r + 2^(m+1)) →
is_sqrt n (sqrt_aux (2^m * 2^m) (2*r*2^m) (n - r*r))
| 0 r h₁ h₂ := by apply sqrt_aux_is_sqrt_lemma 0 r n h₁ 0 rfl;
intro h; simp; [exact ⟨h₁, h⟩, exact ⟨h, h₂⟩]
| (m+1) r h₁ h₂ := begin
apply sqrt_aux_is_sqrt_lemma
(m+1) r n h₁ (2^m * 2^m)
(by simp [shiftr, pow_succ, div2_val, mul_comm, mul_left_comm];
repeat {rw @nat.mul_div_cancel_left _ 2 dec_trivial});
intro h,
{ have := sqrt_aux_is_sqrt m r h₁ h,
simpa [pow_succ, mul_comm, mul_assoc] },
{ rw [pow_succ', mul_two, ← add_assoc] at h₂,
have := sqrt_aux_is_sqrt m (r + 2^(m+1)) h h₂,
rwa show (r + 2^(m + 1)) * 2^(m+1) = 2 * (r + 2^(m + 1)) * 2^m,
by simp [pow_succ, mul_comm, mul_left_comm] }
end
private lemma sqrt_is_sqrt (n : ℕ) : is_sqrt n (sqrt n) :=
begin
generalize e : size n = s, cases s with s; simp [e, sqrt],
{ rw [size_eq_zero.1 e, is_sqrt], exact dec_trivial },
{ have := sqrt_aux_is_sqrt n (div2 s) 0 (zero_le _),
simp [show 2^div2 s * 2^div2 s = shiftl 1 (bit0 (div2 s)), by
{ generalize: div2 s = x,
change bit0 x with x+x,
rw [one_shiftl, pow_add] }] at this,
apply this,
rw [← pow_add, ← mul_two], apply size_le.1,
rw e, apply (@div_lt_iff_lt_mul _ _ 2 dec_trivial).1,
rw [div2_val], apply lt_succ_self }
end
theorem sqrt_le (n : ℕ) : sqrt n * sqrt n ≤ n :=
(sqrt_is_sqrt n).left
theorem sqrt_le' (n : ℕ) : (sqrt n) ^ 2 ≤ n :=
eq.trans_le (sq (sqrt n)) (sqrt_le n)
theorem lt_succ_sqrt (n : ℕ) : n < succ (sqrt n) * succ (sqrt n) :=
(sqrt_is_sqrt n).right
theorem lt_succ_sqrt' (n : ℕ) : n < (succ (sqrt n)) ^ 2 :=
trans_rel_left (λ i j, i < j) (lt_succ_sqrt n) (sq (succ (sqrt n))).symm
theorem sqrt_le_add (n : ℕ) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n :=
by rw ← succ_mul; exact le_of_lt_succ (lt_succ_sqrt n)
theorem le_sqrt {m n : ℕ} : m ≤ sqrt n ↔ m*m ≤ n :=
⟨λ h, le_trans (mul_self_le_mul_self h) (sqrt_le n),
λ h, le_of_lt_succ $ mul_self_lt_mul_self_iff.2 $
lt_of_le_of_lt h (lt_succ_sqrt n)⟩
theorem le_sqrt' {m n : ℕ} : m ≤ sqrt n ↔ m ^ 2 ≤ n :=
by simpa only [pow_two] using le_sqrt
theorem sqrt_lt {m n : ℕ} : sqrt m < n ↔ m < n*n :=
lt_iff_lt_of_le_iff_le le_sqrt
theorem sqrt_lt' {m n : ℕ} : sqrt m < n ↔ m < n ^ 2 :=
lt_iff_lt_of_le_iff_le le_sqrt'
theorem sqrt_le_self (n : ℕ) : sqrt n ≤ n :=
le_trans (le_mul_self _) (sqrt_le n)
theorem sqrt_le_sqrt {m n : ℕ} (h : m ≤ n) : sqrt m ≤ sqrt n :=
le_sqrt.2 (le_trans (sqrt_le _) h)
@[simp] lemma sqrt_zero : sqrt 0 = 0 :=
by rw [sqrt, size_zero, sqrt._match_1]
theorem sqrt_eq_zero {n : ℕ} : sqrt n = 0 ↔ n = 0 :=
⟨λ h, nat.eq_zero_of_le_zero $ le_of_lt_succ $ (@sqrt_lt n 1).1 $
by rw [h]; exact dec_trivial,
by { rintro rfl, simp }⟩
theorem eq_sqrt {n q} : q = sqrt n ↔ q*q ≤ n ∧ n < (q+1)*(q+1) :=
⟨λ e, e.symm ▸ sqrt_is_sqrt n,
λ ⟨h₁, h₂⟩, le_antisymm (le_sqrt.2 h₁) (le_of_lt_succ $ sqrt_lt.2 h₂)⟩
theorem eq_sqrt' {n q} : q = sqrt n ↔ q ^ 2 ≤ n ∧ n < (q+1) ^ 2 :=
by simpa only [pow_two] using eq_sqrt
theorem le_three_of_sqrt_eq_one {n : ℕ} (h : sqrt n = 1) : n ≤ 3 :=
le_of_lt_succ $ (@sqrt_lt n 2).1 $
by rw [h]; exact dec_trivial
theorem sqrt_lt_self {n : ℕ} (h : 1 < n) : sqrt n < n :=
sqrt_lt.2 $ by
have := nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h);
rwa [mul_one] at this
theorem sqrt_pos {n : ℕ} : 0 < sqrt n ↔ 0 < n := le_sqrt
theorem sqrt_add_eq (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n*n + a) = n :=
le_antisymm
(le_of_lt_succ $ sqrt_lt.2 $ by rw [succ_mul, mul_succ, add_succ, add_assoc];
exact lt_succ_of_le (nat.add_le_add_left h _))
(le_sqrt.2 $ nat.le_add_right _ _)
theorem sqrt_add_eq' (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n ^ 2 + a) = n :=
(congr_arg (λ i, sqrt (i + a)) (sq n)).trans (sqrt_add_eq n h)
theorem sqrt_eq (n : ℕ) : sqrt (n*n) = n :=
sqrt_add_eq n (zero_le _)
theorem sqrt_eq' (n : ℕ) : sqrt (n ^ 2) = n :=
sqrt_add_eq' n (zero_le _)
theorem sqrt_succ_le_succ_sqrt (n : ℕ) : sqrt n.succ ≤ n.sqrt.succ :=
le_of_lt_succ $ sqrt_lt.2 $ lt_succ_of_le $ succ_le_succ $
le_trans (sqrt_le_add n) $ add_le_add_right
(by refine add_le_add
(nat.mul_le_mul_right _ _) _; exact nat.le_add_right _ 2) _
theorem exists_mul_self (x : ℕ) :
(∃ n, n * n = x) ↔ sqrt x * sqrt x = x :=
⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq], λ h, ⟨sqrt x, h⟩⟩
theorem exists_mul_self' (x : ℕ) :
(∃ n, n ^ 2 = x) ↔ (sqrt x) ^ 2 = x :=
by simpa only [pow_two] using exists_mul_self x
theorem sqrt_mul_sqrt_lt_succ (n : ℕ) : sqrt n * sqrt n < n + 1 :=
lt_succ_iff.mpr (sqrt_le _)
theorem sqrt_mul_sqrt_lt_succ' (n : ℕ) : (sqrt n) ^ 2 < n + 1 :=
lt_succ_iff.mpr (sqrt_le' _)
theorem succ_le_succ_sqrt (n : ℕ) : n + 1 ≤ (sqrt n + 1) * (sqrt n + 1) :=
le_of_pred_lt (lt_succ_sqrt _)
theorem succ_le_succ_sqrt' (n : ℕ) : n + 1 ≤ (sqrt n + 1) ^ 2 :=
le_of_pred_lt (lt_succ_sqrt' _)
/-- There are no perfect squares strictly between m² and (m+1)² -/
theorem not_exists_sq {n m : ℕ} (hl : m * m < n) (hr : n < (m + 1) * (m + 1)) :
¬ ∃ t, t * t = n :=
begin
rintro ⟨t, rfl⟩,
have h1 : m < t, from nat.mul_self_lt_mul_self_iff.mpr hl,
have h2 : t < m + 1, from nat.mul_self_lt_mul_self_iff.mpr hr,
exact (not_lt_of_ge $ le_of_lt_succ h2) h1
end
theorem not_exists_sq' {n m : ℕ} (hl : m ^ 2 < n) (hr : n < (m + 1) ^ 2) :
¬ ∃ t, t ^ 2 = n :=
by simpa only [pow_two]
using not_exists_sq (by simpa only [pow_two] using hl) (by simpa only [pow_two] using hr)
end nat
|
020d5d144d54cd0e46ab00bae08fe7d76be8ad21 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/cody2.lean | c4a984daf5e801c2d4cb9bd9bacd416b14813eb1 | [
"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 | 439 | lean | definition subsets (P : Type) := P → Prop.
section
parameter A : Type.
parameter r : A → subsets A.
parameter i : subsets A → A.
parameter retract {P : subsets A} {a : A} : r (i P) a = P a.
definition delta (a:A) : Prop := ¬ (r a a).
local notation `δ` := delta.
theorem delta_aux : ¬ (δ (i delta))
:= assume H : δ (i delta),
H (eq.subst (symm (@retract delta (i delta))) H)
#check delta_aux.
end
|
5f28915751796d29cbdeb16c74536286111fc695 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/init/meta/simp_tactic.lean | 42c9686cb53d7856a0f656e25dc5c01a33f18b37 | [
"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 | 4,330 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.tactic
namespace tactic
open list nat
meta_constant simp_lemmas : Type
/- Create a data-structure containing a simp lemma for every constant in the first list of
attributes, and a congr lemma for every constant in the second list of attributes.
Lemmas with type `<lhs> <eqv_rel> <rhs>` are indexed using the head-symbol of `<lhs>`,
computed with respect to the given transparency setting. -/
meta_constant mk_simp_lemmas_core : transparency → list name → list name → tactic simp_lemmas
/- Create an empty simp_lemmas. That is, it ignores the lemmas marked with the [simp] attribute. -/
meta_constant mk_empty_simp_lemmas : tactic simp_lemmas
/- (simp_lemmas_insert_core m lemmas id lemma priority) adds the given lemma to the set simp_lemmas. -/
meta_constant simp_lemmas_insert_core : transparency → simp_lemmas → expr → tactic simp_lemmas
meta_definition mk_simp_lemmas : tactic simp_lemmas :=
mk_simp_lemmas_core reducible [`simp] [`congr]
meta_definition simp_lemmas_add_extra : transparency → simp_lemmas → list expr → tactic simp_lemmas
| m sls [] := return sls
| m sls (l::ls) := do
new_sls ← simp_lemmas_insert_core m sls l,
simp_lemmas_add_extra m new_sls ls
/- Simplify the given expression using [simp] and [congr] lemmas.
The first argument is a tactic to be used to discharge proof obligations.
The second argument is the name of the relation to simplify over.
The third argument is a list of additional expressions to be considered as simp rules.
The fourth argument is the expression to be simplified.
The result is the simplified expression along with a proof that the new
expression is equivalent to the old one.
Fails if no simplifications can be performed. -/
meta_constant simplify_core : tactic unit → name → simp_lemmas → expr → tactic (expr × expr)
meta_definition simplify (prove_fn : tactic unit) (extra_lemmas : list expr) (e : expr) : tactic (expr × expr) :=
do simp_lemmas ← mk_simp_lemmas,
new_lemmas ← simp_lemmas_add_extra reducible simp_lemmas extra_lemmas,
e_type ← infer_type e >>= whnf,
simplify_core prove_fn `eq new_lemmas e
meta_definition simplify_goal (prove_fn : tactic unit) (extra_lemmas : list expr) : tactic unit :=
do (new_target, Heq) ← target >>= simplify prove_fn extra_lemmas,
assert `Htarget new_target, swap,
Ht ← get_local `Htarget,
mk_app `eq.mpr [Heq, Ht] >>= exact
meta_definition simp : tactic unit :=
simplify_goal failed [] >> try triv
meta_definition simp_using (Hs : list expr) : tactic unit :=
simplify_goal failed Hs >> try triv
private meta_definition is_equation : expr → bool
| (expr.pi n bi d b) := is_equation b
| e := match (expr.is_eq e) with (some a) := tt | none := ff end
private meta_definition collect_eqs : list expr → tactic (list expr)
| [] := return []
| (H :: Hs) := do
Eqs ← collect_eqs Hs,
Htype ← infer_type H >>= whnf,
return $ if is_equation Htype = tt then H :: Eqs else Eqs
/- Simplify target using all hypotheses in the local context. -/
meta_definition simp_using_hs : tactic unit :=
local_context >>= collect_eqs >>= simp_using
meta_definition simp_core_at (prove_fn : tactic unit) (extra_lemmas : list expr) (H : expr) : tactic unit :=
do when (expr.is_local_constant H = ff) (fail "tactic simp_at failed, the given expression is not a hypothesis"),
Htype ← infer_type H,
(new_Htype, Heq) ← simplify prove_fn extra_lemmas Htype,
assert (expr.local_pp_name H) new_Htype,
mk_app `eq.mp [Heq, H] >>= exact,
try $ clear H
meta_definition simp_at : expr → tactic unit :=
simp_core_at failed []
meta_definition simp_at_using (Hs : list expr) : expr → tactic unit :=
simp_core_at failed Hs
meta_definition simp_at_using_hs (H : expr) : tactic unit :=
do Hs ← local_context >>= collect_eqs,
simp_core_at failed (filter (ne H) Hs) H
meta_definition mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic unit :=
do (lhs, rhs) ← target >>= match_eq,
(new_rhs, Heq) ← simp_ext lhs,
unify rhs new_rhs,
exact Heq
end tactic
|
51b1e16b2a5d19f76b4aad060ef2360c71edd931 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/meta/float.lean | 21e3ed2ac476e1b168f387fbd224db8adbed84f9 | [] | 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 | 149 | lean | /- Authors: E.W.Ayers -/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.data.default
namespace Mathlib
namespace native
namespace float
|
0ee6919b9fab2f14500022cff4905319658c627c | e5af0662f9ce01ee71f473a50929b138e7f9ef33 | /even_and_odd.lean | cdca5fa45d9f5231c2603e730a299c6a9e6cbec9 | [] | no_license | cygnusx251/Computers-and-Mathematics | 3a5182ac3b7efa5cd110b74473f5953f9d4ff24e | de8a7b92ac99c7d506ccab87fc913e577be69ff5 | refs/heads/main | 1,676,401,846,067 | 1,610,164,573,000 | 1,610,164,573,000 | 327,054,950 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,726 | lean | import tactic
/-
The theory of even and odd numbers
-/
def even (n : ℕ) : Prop := ∃ d, n = 2 * d
def odd (n : ℕ) : Prop := ∃ d, n = 2 * d + 1
/-
see https://www.codewars.com/kata/5e998b42dcf07b0001581def/lean
for a completely different approach (inductive definitions)
-/
/- ## interaction with 0 -/
lemma even_zero : even 0 :=
begin
unfold even,
use 0,
ring,
end
/- ## interaction with succ -/
lemma even_add_one {n : ℕ} : even n → odd (n + 1) := sorry
lemma odd_add_one {n : ℕ} : odd n → even (n + 1) :=
begin
intro h,
rw odd at h,
cases h with e he,
unfold even,
use (e+1),
rw he,
ring,
end
/- ## interaction with add -/
theorem odd_add_odd {n m : ℕ} (hn : odd n) (hm : odd m) :
even (n + m) := sorry
theorem odd_add_even {n m : ℕ} (hn : odd n) (hm : even m) :
odd (n + m) := sorry
theorem even_add_odd {n m : ℕ} (hn : even n) (hm : odd m) :
odd (n + m) := sorry
theorem even_add_even {n m : ℕ} (hn : even n) (hm : even m) :
even (n + m) := sorry
/- ## interaction with one -/
theorem odd_one : odd 1 := sorry
/- ## interaction with mul -/
theorem even_mul_even {n m : ℕ} (hn : even n) (hm : even m) :
even (n * m) := sorry
theorem even_mul_odd {n m : ℕ} (hn : even n) (hm : odd m) :
even (n * m) := sorry
theorem odd_mul_even {n m : ℕ} (hn : odd n) (hm : even m) :
even (n * m) := sorry
theorem odd_mul_odd {n m : ℕ} (hn : odd n) (hm : odd m) :
odd (n * m) := sorry
/- ## interaction with each other -/
lemma odd_or_even (n : ℕ) : odd n ∨ even n := sorry
-- hard?
lemma not_odd_and_even {n : ℕ} : ¬ (odd n ∧ even n) := sorry
|
f6274161e45104fe25c67ea9aac95d51818bf55b | a959f48a0621edea632487cf2130bbf70d301e05 | /src/tactic/refine.lean | a966f3ffc7f96909aca16107b661973094181cd9 | [] | no_license | cipher1024/lean-differential-topology | cf441b36af9fdb022f10afff6a2fdc5aa4afa379 | 1938b0a5d9e89faff89dac4bc51598698cae6dbb | refs/heads/master | 1,619,477,568,536 | 1,527,790,354,000 | 1,527,790,354,000 | 124,159,851 | 0 | 0 | null | 1,520,385,485,000 | 1,520,385,485,000 | null | UTF-8 | Lean | false | false | 3,389 | lean |
import data.dlist
section util
universes u v
def dlist.join {α} : list (dlist α) → dlist α
| [] := dlist.empty
| (x :: xs) := x ++ dlist.join xs
variables {m : Type u → Type v} [applicative m]
def mmap₂
{α₁ α₂ φ : Type u}
(f : α₁ → α₂ → m φ)
: Π (ma₁ : list α₁) (ma₂: list α₂), m (list φ)
| (x :: xs) (y :: ys) := (::) <$> f x y <*> mmap₂ xs ys
| _ _ := pure []
end util
namespace tactic
open interactive interactive.types lean.parser
tactic.interactive (itactic)
tactic nat applicative
meta def var_names : expr → list name
| (expr.pi n _ _ b) := n :: var_names b
| _ := []
meta def drop_binders : expr → tactic expr
| (expr.pi n bi t b) := b.instantiate_var <$> mk_local' n bi t >>= drop_binders
| e := pure e
meta def subobject_names (struct_n : name) : tactic (list name × list name) :=
do env ← get_env,
[c] ← pure $ env.constructors_of struct_n | fail "too many constructors",
vs ← var_names <$> (mk_const c >>= infer_type),
fields ← env.structure_fields struct_n,
return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs)
meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n :=
do (so,fs) ← subobject_names struct_n,
ts ← so.mmap (λ n, do
e ← mk_const (n.update_prefix struct_n) >>= infer_type >>= drop_binders,
expanded_field_list' $ e.get_app_fn.const_name),
return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)
open functor function
meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) :=
dlist.to_list <$> expanded_field_list' struct_n
meta def mk_mvar_list : ℕ → tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n
namespace interactive
open functor
meta def refine_struct (e : parse texpr) (ph : parse $ optional $ tk "with" *> ident) : tactic unit :=
do str ← e.get_structure_instance_info,
tgt ← target,
let struct_n : name := tgt.get_app_fn.const_name,
exp_fields ← expanded_field_list struct_n,
let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names),
let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names),
vs ← mk_mvar_list missing_f.length,
e' ← to_expr $ pexpr.mk_structure_instance
{ struct := some struct_n
, field_names := str.field_names ++ missing_f.map prod.snd
, field_values := str.field_values ++ vs.map to_pexpr },
tactic.exact e',
gs ← with_enable_tags (
mmap₂ (λ (n : name × name) v, do
set_goals [v],
try (interactive.unfold (provided.map $ λ ⟨s,f⟩, f.update_prefix s) (loc.ns [none])),
apply_auto_param
<|> apply_opt_param
<|> (set_main_tag [`_field,n.2,n.1]),
get_goals)
missing_f vs),
set_goals gs.join,
return ()
meta def get_current_field : tactic name :=
do [_,field,str] ← get_main_tag,
expr.const_name <$> resolve_name (field.update_prefix str)
meta def let_field : tactic unit :=
get_current_field
>>= mk_const
>>= pose `field none
>> return ()
meta def have_field : tactic unit :=
get_current_field
>>= mk_const
>>= note `field none
>> return ()
meta def apply_field : tactic unit :=
get_current_field >>= applyc
end interactive
end tactic
|
c6e7203a2b2e2bcdf5283f368d32dddda4d9530b | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/order/filter/pointwise.lean | 0759bcb0ef67f925c533ed9344aeb4e853e00022 | [
"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 | 35,610 | lean | /-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Yaël Dillies
-/
import data.set.pointwise.smul
import order.filter.n_ary
import order.filter.ultrafilter
/-!
# Pointwise operations on filters
This file defines pointwise operations on filters. This is useful because usual algebraic operations
distribute over pointwise operations. For example,
* `(f₁ * f₂).map m = f₁.map m * f₂.map m`
* `𝓝 (x * y) = 𝓝 x * 𝓝 y`
## Main declarations
* `0` (`filter.has_zero`): Pure filter at `0 : α`, or alternatively principal filter at `0 : set α`.
* `1` (`filter.has_one`): Pure filter at `1 : α`, or alternatively principal filter at `1 : set α`.
* `f + g` (`filter.has_add`): Addition, filter generated by all `s + t` where `s ∈ f` and `t ∈ g`.
* `f * g` (`filter.has_mul`): Multiplication, filter generated by all `s * t` where `s ∈ f` and
`t ∈ g`.
* `-f` (`filter.has_neg`): Negation, filter of all `-s` where `s ∈ f`.
* `f⁻¹` (`filter.has_inv`): Inversion, filter of all `s⁻¹` where `s ∈ f`.
* `f - g` (`filter.has_sub`): Subtraction, filter generated by all `s - t` where `s ∈ f` and
`t ∈ g`.
* `f / g` (`filter.has_div`): Division, filter generated by all `s / t` where `s ∈ f` and `t ∈ g`.
* `f +ᵥ g` (`filter.has_vadd`): Scalar addition, filter generated by all `s +ᵥ t` where `s ∈ f` and
`t ∈ g`.
* `f -ᵥ g` (`filter.has_vsub`): Scalar subtraction, filter generated by all `s -ᵥ t` where `s ∈ f`
and `t ∈ g`.
* `f • g` (`filter.has_smul`): Scalar multiplication, filter generated by all `s • t` where
`s ∈ f` and `t ∈ g`.
* `a +ᵥ f` (`filter.has_vadd_filter`): Translation, filter of all `a +ᵥ s` where `s ∈ f`.
* `a • f` (`filter.has_smul_filter`): Scaling, filter of all `a • s` where `s ∈ f`.
For `α` a semigroup/monoid, `filter α` is a semigroup/monoid.
As an unfortunate side effect, this means that `n • f`, where `n : ℕ`, is ambiguous between
pointwise scaling and repeated pointwise addition. See note [pointwise nat action].
## Implementation notes
We put all instances in the locale `pointwise`, so that these instances are not available by
default. Note that we do not mark them as reducible (as argued by note [reducible non-instances])
since we expect the locale to be open whenever the instances are actually used (and making the
instances reducible changes the behavior of `simp`.
## Tags
filter multiplication, filter addition, pointwise addition, pointwise multiplication,
-/
open function set
open_locale filter pointwise
variables {F α β γ δ ε : Type*}
namespace filter
/-! ### `0`/`1` as filters -/
section has_one
variables [has_one α] {f : filter α} {s : set α}
/-- `1 : filter α` is defined as the filter of sets containing `1 : α` in locale `pointwise`. -/
@[to_additive "`0 : filter α` is defined as the filter of sets containing `0 : α` in locale
`pointwise`."]
protected def has_one : has_one (filter α) := ⟨pure 1⟩
localized "attribute [instance] filter.has_one filter.has_zero" in pointwise
@[simp, to_additive] lemma mem_one : s ∈ (1 : filter α) ↔ (1 : α) ∈ s := mem_pure
@[to_additive] lemma one_mem_one : (1 : set α) ∈ (1 : filter α) := mem_pure.2 one_mem_one
@[simp, to_additive] lemma pure_one : pure 1 = (1 : filter α) := rfl
@[simp, to_additive] lemma principal_one : 𝓟 1 = (1 : filter α) := principal_singleton _
@[to_additive] lemma one_ne_bot : (1 : filter α).ne_bot := filter.pure_ne_bot
@[simp, to_additive] protected lemma map_one' (f : α → β) : (1 : filter α).map f = pure (f 1) := rfl
@[simp, to_additive] lemma le_one_iff : f ≤ 1 ↔ (1 : set α) ∈ f := le_pure_iff
@[to_additive] protected lemma ne_bot.le_one_iff (h : f.ne_bot) : f ≤ 1 ↔ f = 1 := h.le_pure_iff
@[simp, to_additive] lemma eventually_one {p : α → Prop} : (∀ᶠ x in 1, p x) ↔ p 1 := eventually_pure
@[simp, to_additive] lemma tendsto_one {a : filter β} {f : β → α} :
tendsto f a 1 ↔ ∀ᶠ x in a, f x = 1 :=
tendsto_pure
/-- `pure` as a `one_hom`. -/
@[to_additive "`pure` as a `zero_hom`."]
def pure_one_hom : one_hom α (filter α) := ⟨pure, pure_one⟩
@[simp, to_additive] lemma coe_pure_one_hom : (pure_one_hom : α → filter α) = pure := rfl
@[simp, to_additive] lemma pure_one_hom_apply (a : α) : pure_one_hom a = pure a := rfl
variables [has_one β]
@[simp, to_additive]
protected lemma map_one [one_hom_class F α β] (φ : F) : map φ 1 = 1 :=
by rw [filter.map_one', map_one, pure_one]
end has_one
/-! ### Filter negation/inversion -/
section has_inv
variables [has_inv α] {f g : filter α} {s : set α} {a : α}
/-- The inverse of a filter is the pointwise preimage under `⁻¹` of its sets. -/
@[to_additive "The negation of a filter is the pointwise preimage under `-` of its sets."]
instance : has_inv (filter α) := ⟨map has_inv.inv⟩
@[simp, to_additive] protected lemma map_inv : f.map has_inv.inv = f⁻¹ := rfl
@[to_additive] lemma mem_inv : s ∈ f⁻¹ ↔ has_inv.inv ⁻¹' s ∈ f := iff.rfl
@[to_additive] protected lemma inv_le_inv (hf : f ≤ g) : f⁻¹ ≤ g⁻¹ := map_mono hf
@[simp, to_additive] lemma inv_pure : (pure a : filter α)⁻¹ = pure a⁻¹ := rfl
@[simp, to_additive] lemma inv_eq_bot_iff : f⁻¹ = ⊥ ↔ f = ⊥ := map_eq_bot_iff
@[simp, to_additive] lemma ne_bot_inv_iff : f⁻¹.ne_bot ↔ ne_bot f := map_ne_bot_iff _
@[to_additive] lemma ne_bot.inv : f.ne_bot → f⁻¹.ne_bot := λ h, h.map _
end has_inv
section has_involutive_inv
variables [has_involutive_inv α] {f : filter α} {s : set α}
@[to_additive] lemma inv_mem_inv (hs : s ∈ f) : s⁻¹ ∈ f⁻¹ := by rwa [mem_inv, inv_preimage, inv_inv]
/-- Inversion is involutive on `filter α` if it is on `α`. -/
@[to_additive "Negation is involutive on `filter α` if it is on `α`."]
protected def has_involutive_inv : has_involutive_inv (filter α) :=
{ inv_inv := λ f, map_map.trans $ by rw [inv_involutive.comp_self, map_id],
..filter.has_inv }
end has_involutive_inv
/-! ### Filter addition/multiplication -/
section has_mul
variables [has_mul α] [has_mul β] {f f₁ f₂ g g₁ g₂ h : filter α} {s t : set α} {a b : α}
/-- The filter `f * g` is generated by `{s * t | s ∈ f, t ∈ g}` in locale `pointwise`. -/
@[to_additive "The filter `f + g` is generated by `{s + t | s ∈ f, t ∈ g}` in locale `pointwise`."]
protected def has_mul : has_mul (filter α) :=
/- This is defeq to `map₂ (*) f g`, but the hypothesis unfolds to `t₁ * t₂ ⊆ s` rather than all the
way to `set.image2 (*) t₁ t₂ ⊆ s`. -/
⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ * t₂ ⊆ s}, ..map₂ (*) f g }⟩
localized "attribute [instance] filter.has_mul filter.has_add" in pointwise
@[simp, to_additive] lemma map₂_mul : map₂ (*) f g = f * g := rfl
@[to_additive] lemma mem_mul : s ∈ f * g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ * t₂ ⊆ s := iff.rfl
@[to_additive] lemma mul_mem_mul : s ∈ f → t ∈ g → s * t ∈ f * g := image2_mem_map₂
@[simp, to_additive] lemma bot_mul : ⊥ * g = ⊥ := map₂_bot_left
@[simp, to_additive] lemma mul_bot : f * ⊥ = ⊥ := map₂_bot_right
@[simp, to_additive] lemma mul_eq_bot_iff : f * g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff
@[simp, to_additive] lemma mul_ne_bot_iff : (f * g).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff
@[to_additive] lemma ne_bot.mul : ne_bot f → ne_bot g → ne_bot (f * g) := ne_bot.map₂
@[to_additive] lemma ne_bot.of_mul_left : (f * g).ne_bot → f.ne_bot := ne_bot.of_map₂_left
@[to_additive] lemma ne_bot.of_mul_right : (f * g).ne_bot → g.ne_bot := ne_bot.of_map₂_right
@[simp, to_additive] lemma pure_mul : pure a * g = g.map ((*) a) := map₂_pure_left
@[simp, to_additive] lemma mul_pure : f * pure b = f.map (* b) := map₂_pure_right
@[simp, to_additive] lemma pure_mul_pure : (pure a : filter α) * pure b = pure (a * b) := map₂_pure
@[simp, to_additive] lemma le_mul_iff : h ≤ f * g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s * t ∈ h :=
le_map₂_iff
@[to_additive] instance covariant_mul : covariant_class (filter α) (filter α) (*) (≤) :=
⟨λ f g h, map₂_mono_left⟩
@[to_additive] instance covariant_swap_mul : covariant_class (filter α) (filter α) (swap (*)) (≤) :=
⟨λ f g h, map₂_mono_right⟩
@[to_additive]
protected lemma map_mul [mul_hom_class F α β] (m : F) : (f₁ * f₂).map m = f₁.map m * f₂.map m :=
map_map₂_distrib $ map_mul m
/-- `pure` operation as a `mul_hom`. -/
@[to_additive "The singleton operation as an `add_hom`."]
def pure_mul_hom : α →ₙ* filter α := ⟨pure, λ a b, pure_mul_pure.symm⟩
@[simp, to_additive] lemma coe_pure_mul_hom : (pure_mul_hom : α → filter α) = pure := rfl
@[simp, to_additive] lemma pure_mul_hom_apply (a : α) : pure_mul_hom a = pure a := rfl
end has_mul
/-! ### Filter subtraction/division -/
section div
variables [has_div α] {f f₁ f₂ g g₁ g₂ h : filter α} {s t : set α} {a b : α}
/-- The filter `f / g` is generated by `{s / t | s ∈ f, t ∈ g}` in locale `pointwise`. -/
@[to_additive "The filter `f - g` is generated by `{s - t | s ∈ f, t ∈ g}` in locale `pointwise`."]
protected def has_div : has_div (filter α) :=
/- This is defeq to `map₂ (/) f g`, but the hypothesis unfolds to `t₁ / t₂ ⊆ s` rather than all the
way to `set.image2 (/) t₁ t₂ ⊆ s`. -/
⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ / t₂ ⊆ s}, ..map₂ (/) f g }⟩
localized "attribute [instance] filter.has_div filter.has_sub" in pointwise
@[simp, to_additive] lemma map₂_div : map₂ (/) f g = f / g := rfl
@[to_additive] lemma mem_div : s ∈ f / g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ / t₂ ⊆ s := iff.rfl
@[to_additive] lemma div_mem_div : s ∈ f → t ∈ g → s / t ∈ f / g := image2_mem_map₂
@[simp, to_additive] lemma bot_div : ⊥ / g = ⊥ := map₂_bot_left
@[simp, to_additive] lemma div_bot : f / ⊥ = ⊥ := map₂_bot_right
@[simp, to_additive] lemma div_eq_bot_iff : f / g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff
@[simp, to_additive] lemma div_ne_bot_iff : (f / g).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff
@[to_additive] lemma ne_bot.div : ne_bot f → ne_bot g → ne_bot (f / g) := ne_bot.map₂
@[to_additive] lemma ne_bot.of_div_left : (f / g).ne_bot → f.ne_bot := ne_bot.of_map₂_left
@[to_additive] lemma ne_bot.of_div_right : (f / g).ne_bot → g.ne_bot := ne_bot.of_map₂_right
@[simp, to_additive] lemma pure_div : pure a / g = g.map ((/) a) := map₂_pure_left
@[simp, to_additive] lemma div_pure : f / pure b = f.map (/ b) := map₂_pure_right
@[simp, to_additive] lemma pure_div_pure : (pure a : filter α) / pure b = pure (a / b) := map₂_pure
@[to_additive] protected lemma div_le_div : f₁ ≤ f₂ → g₁ ≤ g₂ → f₁ / g₁ ≤ f₂ / g₂ := map₂_mono
@[to_additive] protected lemma div_le_div_left : g₁ ≤ g₂ → f / g₁ ≤ f / g₂ := map₂_mono_left
@[to_additive] protected lemma div_le_div_right : f₁ ≤ f₂ → f₁ / g ≤ f₂ / g := map₂_mono_right
@[simp, to_additive] protected lemma le_div_iff :
h ≤ f / g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s / t ∈ h :=
le_map₂_iff
@[to_additive] instance covariant_div : covariant_class (filter α) (filter α) (/) (≤) :=
⟨λ f g h, map₂_mono_left⟩
@[to_additive] instance covariant_swap_div : covariant_class (filter α) (filter α) (swap (/)) (≤) :=
⟨λ f g h, map₂_mono_right⟩
end div
open_locale pointwise
/-- Repeated pointwise addition (not the same as pointwise repeated addition!) of a `filter`. See
Note [pointwise nat action].-/
protected def has_nsmul [has_zero α] [has_add α] : has_smul ℕ (filter α) := ⟨nsmul_rec⟩
/-- Repeated pointwise multiplication (not the same as pointwise repeated multiplication!) of a
`filter`. See Note [pointwise nat action]. -/
@[to_additive]
protected def has_npow [has_one α] [has_mul α] : has_pow (filter α) ℕ := ⟨λ s n, npow_rec n s⟩
/-- Repeated pointwise addition/subtraction (not the same as pointwise repeated
addition/subtraction!) of a `filter`. See Note [pointwise nat action]. -/
protected def has_zsmul [has_zero α] [has_add α] [has_neg α] : has_smul ℤ (filter α) :=
⟨zsmul_rec⟩
/-- Repeated pointwise multiplication/division (not the same as pointwise repeated
multiplication/division!) of a `filter`. See Note [pointwise nat action]. -/
@[to_additive] protected def has_zpow [has_one α] [has_mul α] [has_inv α] : has_pow (filter α) ℤ :=
⟨λ s n, zpow_rec n s⟩
localized "attribute [instance] filter.has_nsmul filter.has_npow filter.has_zsmul filter.has_zpow"
in pointwise
/-- `filter α` is a `semigroup` under pointwise operations if `α` is.-/
@[to_additive "`filter α` is an `add_semigroup` under pointwise operations if `α` is."]
protected def semigroup [semigroup α] : semigroup (filter α) :=
{ mul := (*),
mul_assoc := λ f g h, map₂_assoc mul_assoc }
/-- `filter α` is a `comm_semigroup` under pointwise operations if `α` is. -/
@[to_additive "`filter α` is an `add_comm_semigroup` under pointwise operations if `α` is."]
protected def comm_semigroup [comm_semigroup α] : comm_semigroup (filter α) :=
{ mul_comm := λ f g, map₂_comm mul_comm,
..filter.semigroup }
section mul_one_class
variables [mul_one_class α] [mul_one_class β]
/-- `filter α` is a `mul_one_class` under pointwise operations if `α` is. -/
@[to_additive "`filter α` is an `add_zero_class` under pointwise operations if `α` is."]
protected def mul_one_class : mul_one_class (filter α) :=
{ one := 1,
mul := (*),
one_mul := λ f, by simp only [←pure_one, ←map₂_mul, map₂_pure_left, one_mul, map_id'],
mul_one := λ f, by simp only [←pure_one, ←map₂_mul, map₂_pure_right, mul_one, map_id'] }
localized "attribute [instance] filter.semigroup filter.add_semigroup filter.comm_semigroup
filter.add_comm_semigroup filter.mul_one_class filter.add_zero_class" in pointwise
/-- If `φ : α →* β` then `map_monoid_hom φ` is the monoid homomorphism
`filter α →* filter β` induced by `map φ`. -/
@[to_additive "If `φ : α →+ β` then `map_add_monoid_hom φ` is the monoid homomorphism
`filter α →+ filter β` induced by `map φ`."]
def map_monoid_hom [monoid_hom_class F α β] (φ : F) : filter α →* filter β :=
{ to_fun := map φ,
map_one' := filter.map_one φ,
map_mul' := λ _ _, filter.map_mul φ }
-- The other direction does not hold in general
@[to_additive]
lemma comap_mul_comap_le [mul_hom_class F α β] (m : F) {f g : filter β} :
f.comap m * g.comap m ≤ (f * g).comap m :=
λ s ⟨t, ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩, mt⟩,
⟨m ⁻¹' t₁, m ⁻¹' t₂, ⟨t₁, ht₁, subset.rfl⟩, ⟨t₂, ht₂, subset.rfl⟩,
(preimage_mul_preimage_subset _).trans $ (preimage_mono t₁t₂).trans mt⟩
@[to_additive]
lemma tendsto.mul_mul [mul_hom_class F α β] (m : F) {f₁ g₁ : filter α} {f₂ g₂ : filter β} :
tendsto m f₁ f₂ → tendsto m g₁ g₂ → tendsto m (f₁ * g₁) (f₂ * g₂) :=
λ hf hg, (filter.map_mul m).trans_le $ mul_le_mul' hf hg
/-- `pure` as a `monoid_hom`. -/
@[to_additive "`pure` as an `add_monoid_hom`."]
def pure_monoid_hom : α →* filter α := { ..pure_mul_hom, ..pure_one_hom }
@[simp, to_additive] lemma coe_pure_monoid_hom : (pure_monoid_hom : α → filter α) = pure := rfl
@[simp, to_additive] lemma pure_monoid_hom_apply (a : α) : pure_monoid_hom a = pure a := rfl
end mul_one_class
section monoid
variables [monoid α] {f g : filter α} {s : set α} {a : α} {m n : ℕ}
/-- `filter α` is a `monoid` under pointwise operations if `α` is. -/
@[to_additive "`filter α` is an `add_monoid` under pointwise operations if `α` is."]
protected def monoid : monoid (filter α) :=
{ ..filter.mul_one_class, ..filter.semigroup, ..filter.has_npow }
localized "attribute [instance] filter.monoid filter.add_monoid" in pointwise
@[to_additive] lemma pow_mem_pow (hs : s ∈ f) : ∀ n : ℕ, s ^ n ∈ f ^ n
| 0 := by { rw pow_zero, exact one_mem_one }
| (n + 1) := by { rw pow_succ, exact mul_mem_mul hs (pow_mem_pow _) }
@[simp, to_additive nsmul_bot] lemma bot_pow {n : ℕ} (hn : n ≠ 0) : (⊥ : filter α) ^ n = ⊥ :=
by rw [←tsub_add_cancel_of_le (nat.succ_le_of_lt $ nat.pos_of_ne_zero hn), pow_succ, bot_mul]
@[to_additive] lemma mul_top_of_one_le (hf : 1 ≤ f) : f * ⊤ = ⊤ :=
begin
refine top_le_iff.1 (λ s, _),
simp only [mem_mul, mem_top, exists_and_distrib_left, exists_eq_left],
rintro ⟨t, ht, hs⟩,
rwa [mul_univ_of_one_mem (mem_one.1 $ hf ht), univ_subset_iff] at hs,
end
@[to_additive] lemma top_mul_of_one_le (hf : 1 ≤ f) : ⊤ * f = ⊤ :=
begin
refine top_le_iff.1 (λ s, _),
simp only [mem_mul, mem_top, exists_and_distrib_left, exists_eq_left],
rintro ⟨t, ht, hs⟩,
rwa [univ_mul_of_one_mem (mem_one.1 $ hf ht), univ_subset_iff] at hs,
end
@[simp, to_additive] lemma top_mul_top : (⊤ : filter α) * ⊤ = ⊤ := mul_top_of_one_le le_top
--TODO: `to_additive` trips up on the `1 : ℕ` used in the pattern-matching.
lemma nsmul_top {α : Type*} [add_monoid α] : ∀ {n : ℕ}, n ≠ 0 → n • (⊤ : filter α) = ⊤
| 0 := λ h, (h rfl).elim
| 1 := λ _, one_nsmul _
| (n + 2) := λ _, by { rw [succ_nsmul, nsmul_top n.succ_ne_zero, top_add_top] }
@[to_additive nsmul_top] lemma top_pow : ∀ {n : ℕ}, n ≠ 0 → (⊤ : filter α) ^ n = ⊤
| 0 := λ h, (h rfl).elim
| 1 := λ _, pow_one _
| (n + 2) := λ _, by { rw [pow_succ, top_pow n.succ_ne_zero, top_mul_top] }
@[to_additive] protected lemma _root_.is_unit.filter : is_unit a → is_unit (pure a : filter α) :=
is_unit.map (pure_monoid_hom : α →* filter α)
end monoid
/-- `filter α` is a `comm_monoid` under pointwise operations if `α` is. -/
@[to_additive "`filter α` is an `add_comm_monoid` under pointwise operations if `α` is."]
protected def comm_monoid [comm_monoid α] : comm_monoid (filter α) :=
{ ..filter.mul_one_class, ..filter.comm_semigroup }
open_locale pointwise
section division_monoid
variables [division_monoid α] {f g : filter α}
@[to_additive]
protected lemma mul_eq_one_iff : f * g = 1 ↔ ∃ a b, f = pure a ∧ g = pure b ∧ a * b = 1 :=
begin
refine ⟨λ hfg, _, _⟩,
{ obtain ⟨t₁, t₂, h₁, h₂, h⟩ : (1 : set α) ∈ f * g := hfg.symm.subst one_mem_one,
have hfg : (f * g).ne_bot := hfg.symm.subst one_ne_bot,
rw [(hfg.nonempty_of_mem $ mul_mem_mul h₁ h₂).subset_one_iff, set.mul_eq_one_iff] at h,
obtain ⟨a, b, rfl, rfl, h⟩ := h,
refine ⟨a, b, _, _, h⟩,
{ rwa [←hfg.of_mul_left.le_pure_iff, le_pure_iff] },
{ rwa [←hfg.of_mul_right.le_pure_iff, le_pure_iff] } },
{ rintro ⟨a, b, rfl, rfl, h⟩,
rw [pure_mul_pure, h, pure_one] }
end
/-- `filter α` is a division monoid under pointwise operations if `α` is. -/
@[to_additive "`filter α` is a subtraction monoid under pointwise
operations if `α` is."]
protected def division_monoid : division_monoid (filter α) :=
{ mul_inv_rev := λ s t, map_map₂_antidistrib mul_inv_rev,
inv_eq_of_mul := λ s t h, begin
obtain ⟨a, b, rfl, rfl, hab⟩ := filter.mul_eq_one_iff.1 h,
rw [inv_pure, inv_eq_of_mul_eq_one_right hab],
end,
div_eq_mul_inv := λ f g, map_map₂_distrib_right div_eq_mul_inv,
..filter.monoid, ..filter.has_involutive_inv, ..filter.has_div, ..filter.has_zpow }
@[to_additive] lemma is_unit_iff : is_unit f ↔ ∃ a, f = pure a ∧ is_unit a :=
begin
split,
{ rintro ⟨u, rfl⟩,
obtain ⟨a, b, ha, hb, h⟩ := filter.mul_eq_one_iff.1 u.mul_inv,
refine ⟨a, ha, ⟨a, b, h, pure_injective _⟩, rfl⟩,
rw [←pure_mul_pure, ←ha, ←hb],
exact u.inv_mul },
{ rintro ⟨a, rfl, ha⟩,
exact ha.filter }
end
end division_monoid
/-- `filter α` is a commutative division monoid under pointwise operations if `α` is. -/
@[to_additive subtraction_comm_monoid "`filter α` is a commutative subtraction monoid under
pointwise operations if `α` is."]
protected def division_comm_monoid [division_comm_monoid α] : division_comm_monoid (filter α) :=
{ ..filter.division_monoid, ..filter.comm_semigroup }
/-- `filter α` has distributive negation if `α` has. -/
protected def has_distrib_neg [has_mul α] [has_distrib_neg α] : has_distrib_neg (filter α) :=
{ neg_mul := λ _ _, map₂_map_left_comm neg_mul,
mul_neg := λ _ _, map_map₂_right_comm mul_neg,
..filter.has_involutive_neg }
localized "attribute [instance] filter.comm_monoid filter.add_comm_monoid filter.division_monoid
filter.subtraction_monoid filter.division_comm_monoid filter.subtraction_comm_monoid
filter.has_distrib_neg" in pointwise
section distrib
variables [distrib α] {f g h : filter α}
/-!
Note that `filter α` is not a `distrib` because `f * g + f * h` has cross terms that `f * (g + h)`
lacks.
-/
lemma mul_add_subset : f * (g + h) ≤ f * g + f * h := map₂_distrib_le_left mul_add
lemma add_mul_subset : (f + g) * h ≤ f * h + g * h := map₂_distrib_le_right add_mul
end distrib
section mul_zero_class
variables [mul_zero_class α] {f g : filter α}
/-! Note that `filter` is not a `mul_zero_class` because `0 * ⊥ ≠ 0`. -/
lemma ne_bot.mul_zero_nonneg (hf : f.ne_bot) : 0 ≤ f * 0 :=
le_mul_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨a, ha⟩ := hf.nonempty_of_mem h₁ in ⟨_, _, ha, h₂, mul_zero _⟩
lemma ne_bot.zero_mul_nonneg (hg : g.ne_bot) : 0 ≤ 0 * g :=
le_mul_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨b, hb⟩ := hg.nonempty_of_mem h₂ in ⟨_, _, h₁, hb, zero_mul _⟩
end mul_zero_class
section group
variables [group α] [division_monoid β] [monoid_hom_class F α β] (m : F) {f g f₁ g₁ : filter α}
{f₂ g₂ : filter β}
/-! Note that `filter α` is not a group because `f / f ≠ 1` in general -/
@[simp, to_additive] protected lemma one_le_div_iff : 1 ≤ f / g ↔ ¬ disjoint f g :=
begin
refine ⟨λ h hfg, _, _⟩,
{ obtain ⟨s, hs, t, ht, hst⟩ := hfg.le_bot (mem_bot : ∅ ∈ ⊥),
exact set.one_mem_div_iff.1 (h $ div_mem_div hs ht) (disjoint_iff.2 hst.symm) },
{ rintro h s ⟨t₁, t₂, h₁, h₂, hs⟩,
exact hs (set.one_mem_div_iff.2 $ λ ht, h $ disjoint_of_disjoint_of_mem ht h₁ h₂) }
end
@[to_additive] lemma not_one_le_div_iff : ¬ 1 ≤ f / g ↔ disjoint f g :=
filter.one_le_div_iff.not_left
@[to_additive] lemma ne_bot.one_le_div (h : f.ne_bot) : 1 ≤ f / f :=
begin
rintro s ⟨t₁, t₂, h₁, h₂, hs⟩,
obtain ⟨a, ha₁, ha₂⟩ := set.not_disjoint_iff.1 (h.not_disjoint h₁ h₂),
rw [mem_one, ←div_self' a],
exact hs (set.div_mem_div ha₁ ha₂),
end
@[to_additive] lemma is_unit_pure (a : α) : is_unit (pure a : filter α) := (group.is_unit a).filter
@[simp] lemma is_unit_iff_singleton : is_unit f ↔ ∃ a, f = pure a :=
by simp only [is_unit_iff, group.is_unit, and_true]
include β
@[to_additive] lemma map_inv' : f⁻¹.map m = (f.map m)⁻¹ := semiconj.filter_map (map_inv m) f
@[to_additive] lemma tendsto.inv_inv : tendsto m f₁ f₂ → tendsto m f₁⁻¹ f₂⁻¹ :=
λ hf, (filter.map_inv' m).trans_le $ filter.inv_le_inv hf
@[to_additive] protected lemma map_div : (f / g).map m = f.map m / g.map m :=
map_map₂_distrib $ map_div m
@[to_additive]
lemma tendsto.div_div : tendsto m f₁ f₂ → tendsto m g₁ g₂ → tendsto m (f₁ / g₁) (f₂ / g₂) :=
λ hf hg, (filter.map_div m).trans_le $ filter.div_le_div hf hg
end group
open_locale pointwise
section group_with_zero
variables [group_with_zero α] {f g : filter α}
lemma ne_bot.div_zero_nonneg (hf : f.ne_bot) : 0 ≤ f / 0 :=
filter.le_div_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨a, ha⟩ := hf.nonempty_of_mem h₁ in
⟨_, _, ha, h₂, div_zero _⟩
lemma ne_bot.zero_div_nonneg (hg : g.ne_bot) : 0 ≤ 0 / g :=
filter.le_div_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨b, hb⟩ := hg.nonempty_of_mem h₂ in
⟨_, _, h₁, hb, zero_div _⟩
end group_with_zero
/-! ### Scalar addition/multiplication of filters -/
section smul
variables [has_smul α β] {f f₁ f₂ : filter α} {g g₁ g₂ h : filter β} {s : set α} {t : set β}
{a : α} {b : β}
/-- The filter `f • g` is generated by `{s • t | s ∈ f, t ∈ g}` in locale `pointwise`. -/
@[to_additive filter.has_vadd
"The filter `f +ᵥ g` is generated by `{s +ᵥ t | s ∈ f, t ∈ g}` in locale `pointwise`."]
protected def has_smul : has_smul (filter α) (filter β) :=
/- This is defeq to `map₂ (•) f g`, but the hypothesis unfolds to `t₁ • t₂ ⊆ s` rather than all the
way to `set.image2 (•) t₁ t₂ ⊆ s`. -/
⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ • t₂ ⊆ s}, ..map₂ (•) f g }⟩
localized "attribute [instance] filter.has_smul filter.has_vadd" in pointwise
@[simp, to_additive] lemma map₂_smul : map₂ (•) f g = f • g := rfl
@[to_additive] lemma mem_smul : t ∈ f • g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ • t₂ ⊆ t := iff.rfl
@[to_additive] lemma smul_mem_smul : s ∈ f → t ∈ g → s • t ∈ f • g := image2_mem_map₂
@[simp, to_additive] lemma bot_smul : (⊥ : filter α) • g = ⊥ := map₂_bot_left
@[simp, to_additive] lemma smul_bot : f • (⊥ : filter β) = ⊥ := map₂_bot_right
@[simp, to_additive] lemma smul_eq_bot_iff : f • g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff
@[simp, to_additive] lemma smul_ne_bot_iff : (f • g).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff
@[to_additive] lemma ne_bot.smul : ne_bot f → ne_bot g → ne_bot (f • g) := ne_bot.map₂
@[to_additive] lemma ne_bot.of_smul_left : (f • g).ne_bot → f.ne_bot := ne_bot.of_map₂_left
@[to_additive] lemma ne_bot.of_smul_right : (f • g).ne_bot → g.ne_bot := ne_bot.of_map₂_right
@[simp, to_additive] lemma pure_smul : (pure a : filter α) • g = g.map ((•) a) := map₂_pure_left
@[simp, to_additive] lemma smul_pure : f • pure b = f.map (• b) := map₂_pure_right
@[simp, to_additive] lemma pure_smul_pure :
(pure a : filter α) • (pure b : filter β) = pure (a • b) := map₂_pure
@[to_additive] lemma smul_le_smul : f₁ ≤ f₂ → g₁ ≤ g₂ → f₁ • g₁ ≤ f₂ • g₂ := map₂_mono
@[to_additive] lemma smul_le_smul_left : g₁ ≤ g₂ → f • g₁ ≤ f • g₂ := map₂_mono_left
@[to_additive] lemma smul_le_smul_right : f₁ ≤ f₂ → f₁ • g ≤ f₂ • g := map₂_mono_right
@[simp, to_additive] lemma le_smul_iff : h ≤ f • g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s • t ∈ h :=
le_map₂_iff
@[to_additive] instance covariant_smul : covariant_class (filter α) (filter β) (•) (≤) :=
⟨λ f g h, map₂_mono_left⟩
end smul
/-! ### Scalar subtraction of filters -/
section vsub
variables [has_vsub α β] {f f₁ f₂ g g₁ g₂ : filter β} {h : filter α} {s t : set β} {a b : β}
include α
/-- The filter `f -ᵥ g` is generated by `{s -ᵥ t | s ∈ f, t ∈ g}` in locale `pointwise`. -/
protected def has_vsub : has_vsub (filter α) (filter β) :=
/- This is defeq to `map₂ (-ᵥ) f g`, but the hypothesis unfolds to `t₁ -ᵥ t₂ ⊆ s` rather than all
the way to `set.image2 (-ᵥ) t₁ t₂ ⊆ s`. -/
⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ -ᵥ t₂ ⊆ s}, ..map₂ (-ᵥ) f g }⟩
localized "attribute [instance] filter.has_vsub" in pointwise
@[simp] lemma map₂_vsub : map₂ (-ᵥ) f g = f -ᵥ g := rfl
lemma mem_vsub {s : set α} : s ∈ f -ᵥ g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ -ᵥ t₂ ⊆ s := iff.rfl
lemma vsub_mem_vsub : s ∈ f → t ∈ g → s -ᵥ t ∈ f -ᵥ g := image2_mem_map₂
@[simp] lemma bot_vsub : (⊥ : filter β) -ᵥ g = ⊥ := map₂_bot_left
@[simp] lemma vsub_bot : f -ᵥ (⊥ : filter β) = ⊥ := map₂_bot_right
@[simp] lemma vsub_eq_bot_iff : f -ᵥ g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff
@[simp] lemma vsub_ne_bot_iff : (f -ᵥ g : filter α).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff
lemma ne_bot.vsub : ne_bot f → ne_bot g → ne_bot (f -ᵥ g) := ne_bot.map₂
lemma ne_bot.of_vsub_left : (f -ᵥ g : filter α).ne_bot → f.ne_bot := ne_bot.of_map₂_left
lemma ne_bot.of_vsub_right : (f -ᵥ g : filter α).ne_bot → g.ne_bot := ne_bot.of_map₂_right
@[simp] lemma pure_vsub : (pure a : filter β) -ᵥ g = g.map ((-ᵥ) a) := map₂_pure_left
@[simp] lemma vsub_pure : f -ᵥ pure b = f.map (-ᵥ b) := map₂_pure_right
@[simp] lemma pure_vsub_pure : (pure a : filter β) -ᵥ pure b = (pure (a -ᵥ b) : filter α) :=
map₂_pure
lemma vsub_le_vsub : f₁ ≤ f₂ → g₁ ≤ g₂ → f₁ -ᵥ g₁ ≤ f₂ -ᵥ g₂ := map₂_mono
lemma vsub_le_vsub_left : g₁ ≤ g₂ → f -ᵥ g₁ ≤ f -ᵥ g₂ := map₂_mono_left
lemma vsub_le_vsub_right : f₁ ≤ f₂ → f₁ -ᵥ g ≤ f₂ -ᵥ g := map₂_mono_right
@[simp] lemma le_vsub_iff : h ≤ f -ᵥ g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s -ᵥ t ∈ h := le_map₂_iff
end vsub
/-! ### Translation/scaling of filters -/
section smul
variables [has_smul α β] {f f₁ f₂ : filter β} {s : set β} {a : α}
/-- `a • f` is the map of `f` under `a •` in locale `pointwise`. -/
@[to_additive filter.has_vadd_filter
"`a +ᵥ f` is the map of `f` under `a +ᵥ` in locale `pointwise`."]
protected def has_smul_filter : has_smul α (filter β) := ⟨λ a, map ((•) a)⟩
localized "attribute [instance] filter.has_smul_filter filter.has_vadd_filter" in pointwise
@[simp, to_additive] lemma map_smul : map (λ b, a • b) f = a • f := rfl
@[to_additive] lemma mem_smul_filter : s ∈ a • f ↔ (•) a ⁻¹' s ∈ f := iff.rfl
@[to_additive] lemma smul_set_mem_smul_filter : s ∈ f → a • s ∈ a • f := image_mem_map
@[simp, to_additive] lemma smul_filter_bot : a • (⊥ : filter β) = ⊥ := map_bot
@[simp, to_additive] lemma smul_filter_eq_bot_iff : a • f = ⊥ ↔ f = ⊥ := map_eq_bot_iff
@[simp, to_additive] lemma smul_filter_ne_bot_iff : (a • f).ne_bot ↔ f.ne_bot := map_ne_bot_iff _
@[to_additive] lemma ne_bot.smul_filter : f.ne_bot → (a • f).ne_bot := λ h, h.map _
@[to_additive] lemma ne_bot.of_smul_filter : (a • f).ne_bot → f.ne_bot := ne_bot.of_map
@[to_additive] lemma smul_filter_le_smul_filter (hf : f₁ ≤ f₂) : a • f₁ ≤ a • f₂ :=
map_mono hf
@[to_additive] instance covariant_smul_filter : covariant_class α (filter β) (•) (≤) :=
⟨λ f, map_mono⟩
end smul
open_locale pointwise
@[to_additive]
instance smul_comm_class_filter [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] :
smul_comm_class α β (filter γ) :=
⟨λ _ _ _, map_comm (funext $ smul_comm _ _) _⟩
@[to_additive]
instance smul_comm_class_filter' [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] :
smul_comm_class α (filter β) (filter γ) :=
⟨λ a f g, map_map₂_distrib_right $ smul_comm a⟩
@[to_additive]
instance smul_comm_class_filter'' [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] :
smul_comm_class (filter α) β (filter γ) :=
by haveI := smul_comm_class.symm α β γ; exact smul_comm_class.symm _ _ _
@[to_additive]
instance smul_comm_class [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] :
smul_comm_class (filter α) (filter β) (filter γ) :=
⟨λ f g h, map₂_left_comm smul_comm⟩
@[to_additive]
instance is_scalar_tower [has_smul α β] [has_smul α γ] [has_smul β γ] [is_scalar_tower α β γ] :
is_scalar_tower α β (filter γ) :=
⟨λ a b f, by simp only [←map_smul, map_map, smul_assoc]⟩
@[to_additive]
instance is_scalar_tower' [has_smul α β] [has_smul α γ] [has_smul β γ] [is_scalar_tower α β γ] :
is_scalar_tower α (filter β) (filter γ) :=
⟨λ a f g, by { refine (map_map₂_distrib_left $ λ _ _, _).symm, exact (smul_assoc a _ _).symm }⟩
@[to_additive]
instance is_scalar_tower'' [has_smul α β] [has_smul α γ] [has_smul β γ] [is_scalar_tower α β γ] :
is_scalar_tower (filter α) (filter β) (filter γ) :=
⟨λ f g h, map₂_assoc smul_assoc⟩
@[to_additive] instance is_central_scalar [has_smul α β] [has_smul αᵐᵒᵖ β] [is_central_scalar α β] :
is_central_scalar α (filter β) :=
⟨λ a f, congr_arg (λ m, map m f) $ by exact funext (λ _, op_smul_eq_smul _ _)⟩
/-- A multiplicative action of a monoid `α` on a type `β` gives a multiplicative action of
`filter α` on `filter β`. -/
@[to_additive "An additive action of an additive monoid `α` on a type `β` gives an additive action
of `filter α` on `filter β`"]
protected def mul_action [monoid α] [mul_action α β] : mul_action (filter α) (filter β) :=
{ one_smul := λ f, map₂_pure_left.trans $ by simp_rw [one_smul, map_id'],
mul_smul := λ f g h, map₂_assoc mul_smul }
/-- A multiplicative action of a monoid on a type `β` gives a multiplicative action on `filter β`.
-/
@[to_additive "An additive action of an additive monoid on a type `β` gives an additive action on
`filter β`."]
protected def mul_action_filter [monoid α] [mul_action α β] : mul_action α (filter β) :=
{ mul_smul := λ a b f, by simp only [←map_smul, map_map, function.comp, ←mul_smul],
one_smul := λ f, by simp only [←map_smul, one_smul, map_id'] }
localized "attribute [instance] filter.mul_action filter.add_action filter.mul_action_filter
filter.add_action_filter" in pointwise
/-- A distributive multiplicative action of a monoid on an additive monoid `β` gives a distributive
multiplicative action on `filter β`. -/
protected def distrib_mul_action_filter [monoid α] [add_monoid β] [distrib_mul_action α β] :
distrib_mul_action α (filter β) :=
{ smul_add := λ _ _ _, map_map₂_distrib $ smul_add _,
smul_zero := λ _, (map_pure _ _).trans $ by rw [smul_zero, pure_zero] }
/-- A multiplicative action of a monoid on a monoid `β` gives a multiplicative action on `set β`. -/
protected def mul_distrib_mul_action_filter [monoid α] [monoid β] [mul_distrib_mul_action α β] :
mul_distrib_mul_action α (set β) :=
{ smul_mul := λ _ _ _, image_image2_distrib $ smul_mul' _,
smul_one := λ _, image_singleton.trans $ by rw [smul_one, singleton_one] }
localized "attribute [instance] filter.distrib_mul_action_filter
filter.mul_distrib_mul_action_filter" in pointwise
section smul_with_zero
variables [has_zero α] [has_zero β] [smul_with_zero α β] {f : filter α} {g : filter β}
/-!
Note that we have neither `smul_with_zero α (filter β)` nor `smul_with_zero (filter α) (filter β)`
because `0 * ⊥ ≠ 0`.
-/
lemma ne_bot.smul_zero_nonneg (hf : f.ne_bot) : 0 ≤ f • (0 : filter β) :=
le_smul_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨a, ha⟩ := hf.nonempty_of_mem h₁ in
⟨_, _, ha, h₂, smul_zero _⟩
lemma ne_bot.zero_smul_nonneg (hg : g.ne_bot) : 0 ≤ (0 : filter α) • g :=
le_smul_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨b, hb⟩ := hg.nonempty_of_mem h₂ in ⟨_, _, h₁, hb, zero_smul _ _⟩
lemma zero_smul_filter_nonpos : (0 : α) • g ≤ 0 :=
begin
refine λ s hs, mem_smul_filter.2 _,
convert univ_mem,
refine eq_univ_iff_forall.2 (λ a, _),
rwa [mem_preimage, zero_smul],
end
lemma zero_smul_filter (hg : g.ne_bot) : (0 : α) • g = 0 :=
zero_smul_filter_nonpos.antisymm $ le_map_iff.2 $ λ s hs, begin
simp_rw [set.image_eta, zero_smul, (hg.nonempty_of_mem hs).image_const],
exact zero_mem_zero,
end
end smul_with_zero
end filter
|
f2cef9ba78fc5dda1a0d0149d1a7a64142cb98bd | b561a44b48979a98df50ade0789a21c79ee31288 | /stage0/src/Lean/Elab/Do.lean | 32a46ecf739e59d4bd77228b5b95da212d85e866 | [
"Apache-2.0"
] | permissive | 3401ijk/lean4 | 97659c475ebd33a034fed515cb83a85f75ccfb06 | a5b1b8de4f4b038ff752b9e607b721f15a9a4351 | refs/heads/master | 1,693,933,007,651 | 1,636,424,845,000 | 1,636,424,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 70,567 | 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.Term
import Lean.Elab.BindersUtil
import Lean.Elab.PatternVar
import Lean.Elab.Quotation.Util
import Lean.Parser.Do
-- HACK: avoid code explosion until heuristics are improved
set_option compiler.reuse false
namespace Lean.Elab.Term
open Lean.Parser.Term
open Meta
private def getDoSeqElems (doSeq : Syntax) : List Syntax :=
if doSeq.getKind == ``Lean.Parser.Term.doSeqBracketed then
doSeq[1].getArgs.toList.map fun arg => arg[0]
else if doSeq.getKind == ``Lean.Parser.Term.doSeqIndent then
doSeq[0].getArgs.toList.map fun arg => arg[0]
else
[]
private def getDoSeq (doStx : Syntax) : Syntax :=
doStx[1]
@[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ =>
throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression"
/-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/
private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool :=
k == ``Lean.Parser.Term.do ||
k == ``Lean.Parser.Term.doSeqIndent ||
k == ``Lean.Parser.Term.doSeqBracketed ||
k == ``Lean.Parser.Term.termReturn ||
k == ``Lean.Parser.Term.termUnless ||
k == ``Lean.Parser.Term.termTry ||
k == ``Lean.Parser.Term.termFor
/-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/
private def letDeclArgHasBinders (letDeclArg : Syntax) : Bool :=
let k := letDeclArg.getKind
if k == ``Lean.Parser.Term.letPatDecl then
false
else if k == ``Lean.Parser.Term.letEqnsDecl then
true
else if k == ``Lean.Parser.Term.letIdDecl then
-- letIdLhs := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType
let binders := letDeclArg[1]
binders.getNumArgs > 0
else
false
/-- Return `true` if the given `letDecl` contains binders. -/
private def letDeclHasBinders (letDecl : Syntax) : Bool :=
letDeclArgHasBinders letDecl[0]
/-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/
private def liftMethodForbiddenBinder (stx : Syntax) : Bool :=
let k := stx.getKind
if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts ||
k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec then
-- It is never ok to lift over this kind of binder
true
-- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not
else if k == ``Lean.Parser.Term.let then
letDeclHasBinders stx[1]
else if k == ``Lean.Parser.Term.doLet then
letDeclHasBinders stx[2]
else if k == ``Lean.Parser.Term.doLetArrow then
letDeclArgHasBinders stx[2]
else
false
private partial def hasLiftMethod : Syntax → Bool
| Syntax.node _ k args =>
if liftMethodDelimiter k then false
-- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a
-- bit slower
else if k == ``Lean.Parser.Term.liftMethod then true
else args.any hasLiftMethod
| _ => false
structure ExtractMonadResult where
m : Expr
α : Expr
expectedType : Expr
isPure : Bool -- `true` when it is a pure `do` block. That is, Lean implicitly inserted the `Id` Monad.
private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do
let u ← getDecLevel type
let id := Lean.mkConst ``Id [u]
pure { m := id, α := type, expectedType := mkApp id type, isPure := true }
private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do
match expectedType? with
| none => throwError "invalid 'do' notation, expected type is not available"
| some expectedType =>
let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do
match type with
| Expr.app m α _ =>
try
let bindInstType ← mkAppM ``Bind #[m]
let _ ← Meta.synthInstance bindInstType
return some { m := m, α := α, expectedType := expectedType, isPure := false }
catch _ =>
return none
| _ =>
return none
let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do
match (← extractStep? type) with
| some r => return r
| none =>
let typeNew ← whnfCore type
if typeNew != type then
extract? typeNew
else
if typeNew.getAppFn.isMVar then throwError "invalid 'do' notation, expected type is not available"
match (← unfoldDefinition? typeNew) with
| some typeNew => extract? typeNew
| none => return none
match (← extract? expectedType) with
| some r => return r
| none => mkIdBindFor expectedType
namespace Do
/- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/
structure Alt (σ : Type) where
ref : Syntax
vars : Array Name
patterns : Syntax
rhs : σ
deriving Inhabited
/-
Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`).
We convert `Code` into a `Syntax` term representing the:
- `do`-block, or
- the visitor argument for the `forIn` combinator.
We say the following constructors are terminals:
- `break`: for interrupting a `for x in s`
- `continue`: for interrupting the current iteration of a `for x in s`
- `return e`: for returning `e` as the result for the whole `do` computation block
- `action a`: for executing action `a` as a terminal
- `ite`: if-then-else
- `match`: pattern matching
- `jmp` a goto to a join-point
We say the terminals `break`, `continue`, `action`, and `return` are "exit points"
Note that, `return e` is not equivalent to `action (pure e)`. Here is an example:
```
def f (x : Nat) : IO Unit := do
if x == 0 then
return ()
IO.println "hello"
```
Executing `#eval f 0` will not print "hello". Now, consider
```
def g (x : Nat) : IO Unit := do
if x == 0 then
pure ()
IO.println "hello"
```
The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`.
- `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`).
The field `stx` is the actual `doElem`,
`vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block.
`vars` is an array since we have declarations such as `let (a, b) := s`.
- `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`).
- `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow.
- `seq a k` executes action `a`, ignores its result, and then executes `k`.
We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`.
A code block `C` is well-formed if
- For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and
`ps.size == as.size` -/
inductive Code where
| decl (xs : Array Name) (doElem : Syntax) (k : Code)
| reassign (xs : Array Name) (doElem : Syntax) (k : Code)
/- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/
| joinpoint (name : Name) (params : Array (Name × Bool)) (body : Code) (k : Code)
| seq (action : Syntax) (k : Code)
| action (action : Syntax)
| «break» (ref : Syntax)
| «continue» (ref : Syntax)
| «return» (ref : Syntax) (val : Syntax)
/- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/
| ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code)
| «match» (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code))
| jmp (ref : Syntax) (jpName : Name) (args : Array Syntax)
deriving Inhabited
/- A code block, and the collection of variables updated by it. -/
structure CodeBlock where
code : Code
uvars : NameSet := {} -- set of variables updated by `code`
private def nameSetToArray (s : NameSet) : Array Name :=
s.fold (fun (xs : Array Name) x => xs.push x) #[]
private def varsToMessageData (vars : Array Name) : MessageData :=
MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " "
partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData :=
let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName
let rec loop : Code → MessageData
| Code.decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}"
| Code.reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}"
| Code.joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}"
| Code.seq e k => m!"{e}\n{loop k}"
| Code.action e => e
| Code.ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}"
| Code.jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}"
| Code.«break» _ => m!"break {us}"
| Code.«continue» _ => m!"continue {us}"
| Code.«return» _ v => m!"return {v} {us}"
| Code.«match» _ _ ds t alts =>
m!"match {ds} with"
++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}"
loop codeBlock.code
/- Return true if the give code contains an exit point that satisfies `p` -/
partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool :=
let rec loop : Code → Bool
| Code.decl _ _ k => loop k
| Code.reassign _ _ k => loop k
| Code.joinpoint _ _ b k => loop b || loop k
| Code.seq _ k => loop k
| Code.ite _ _ _ _ t e => loop t || loop e
| Code.«match» _ _ _ _ alts => alts.any (loop ·.rhs)
| Code.jmp _ _ _ => false
| c => p c
loop c
def hasExitPoint (c : Code) : Bool :=
hasExitPointPred c fun c => true
def hasReturn (c : Code) : Bool :=
hasExitPointPred c fun
| Code.«return» _ _ => true
| _ => false
def hasTerminalAction (c : Code) : Bool :=
hasExitPointPred c fun
| Code.«action» _ => true
| _ => false
def hasBreakContinue (c : Code) : Bool :=
hasExitPointPred c fun
| Code.«break» _ => true
| Code.«continue» _ => true
| _ => false
def hasBreakContinueReturn (c : Code) : Bool :=
hasExitPointPred c fun
| Code.«break» _ => true
| Code.«continue» _ => true
| Code.«return» _ _ => true
| _ => false
def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do
let y ← `(y)
let yName := y.getId
let doElem ← `(doElem| let y ← $e:term)
-- Add elaboration hint for producing sane error message
let y ← `(ensure_expected_type% "type mismatch, result value" $y)
let k ← mkCont y
pure $ Code.decl #[yName] doElem k
/- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/
partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code :=
let rec loop : Code → MacroM Code
| Code.decl xs stx k => do Code.decl xs stx (← loop k)
| Code.reassign xs stx k => do Code.reassign xs stx (← loop k)
| Code.joinpoint n ps b k => do Code.joinpoint n ps (← loop b) (← loop k)
| Code.seq e k => do Code.seq e (← loop k)
| Code.ite ref x? h c t e => do Code.ite ref x? h c (← loop t) (← loop e)
| Code.«match» ref g ds t alts => do Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) })
| Code.action e => mkAuxDeclFor e fun y =>
let ref := e
-- We jump to `jp` with xs **and** y
let jmpArgs := xs.map $ mkIdentFrom ref
let jmpArgs := jmpArgs.push y
pure $ Code.jmp ref jp jmpArgs
| c => pure c
loop code
structure JPDecl where
name : Name
params : Array (Name × Bool)
body : Code
def attachJP (jpDecl : JPDecl) (k : Code) : Code :=
Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k
def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code :=
jpDecls.foldr attachJP k
def mkFreshJP (ps : Array (Name × Bool)) (body : Code) : TermElabM JPDecl := do
let ps ←
if ps.isEmpty then
let y ← mkFreshUserName `y
pure #[(y, false)]
else
pure ps
-- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by
-- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp`
-- We will remove this hack when we re-implement the compiler frontend in Lean.
let name ← mkFreshUserName `_do_jp
pure { name := name, params := ps, body := body }
def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl :=
mkFreshJP (xs.map fun x => (x, true)) body
def addFreshJP (ps : Array (Name × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do
let jp ← mkFreshJP ps body
modify fun (jps : Array JPDecl) => jps.push jp
pure jp.name
def insertVars (rs : NameSet) (xs : Array Name) : NameSet :=
xs.foldl (·.insert ·) rs
def eraseVars (rs : NameSet) (xs : Array Name) : NameSet :=
xs.foldl (·.erase ·) rs
def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet :=
match x? with
| none => rs
| some x => rs.insert x
/- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/
def mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do
let xs := nameSetToArray rs
let jp ← addFreshJP (xs.map fun x => (x, true)) c
if xs.isEmpty then
let unit ← ``(Unit.unit)
return Code.jmp ref jp #[unit]
else
return Code.jmp ref jp (xs.map $ mkIdentFrom ref)
/- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value.
The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh`
is a fresh variable created by this method. -/
def mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do
let xs := nameSetToArray rs
let args := xs.map $ mkIdentFrom ref
let args := args.push val
let yFresh ← mkFreshUserName `y
let ps := xs.map fun x => (x, true)
let ps := ps.push (yFresh, false)
let jpBody ← liftMacroM $ mkJPBody (mkIdentFrom ref yFresh)
let jp ← addFreshJP ps jpBody
pure $ Code.jmp ref jp args
/- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/
partial def pullExitPointsAux : NameSet → Code → StateRefT (Array JPDecl) TermElabM Code
| rs, Code.decl xs stx k => do Code.decl xs stx (← pullExitPointsAux (eraseVars rs xs) k)
| rs, Code.reassign xs stx k => do Code.reassign xs stx (← pullExitPointsAux (insertVars rs xs) k)
| rs, Code.joinpoint j ps b k => do Code.joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k)
| rs, Code.seq e k => do Code.seq e (← pullExitPointsAux rs k)
| rs, Code.ite ref x? o c t e => do Code.ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e)
| rs, Code.«match» ref g ds t alts => do
Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) })
| rs, c@(Code.jmp _ _ _) => pure c
| rs, Code.«break» ref => mkSimpleJmp ref rs (Code.«break» ref)
| rs, Code.«continue» ref => mkSimpleJmp ref rs (Code.«continue» ref)
| rs, Code.«return» ref val => mkJmp ref rs val (fun y => pure $ Code.«return» ref y)
| rs, Code.action e =>
-- We use `mkAuxDeclFor` because `e` is not pure.
mkAuxDeclFor e fun y =>
let ref := e
mkJmp ref rs y (fun yFresh => do pure $ Code.action (← ``(Pure.pure $yFresh)))
/-
Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock.
When a new variable is not already in the collection, but is shadowed by some declaration in `c`,
we create auxiliary join points to make sure we preserve the semantics of the code block.
Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it
with the reassignment `x := x + 1`. We first use `pullExitPoints` to create
```
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
and then we add the reassignment
```
x := x + 1
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
Note that we created a fresh variable `x!1` to avoid accidental name capture.
As another example, consider
```
print x;
let x := 10
y := y + 1;
return x;
```
We transform it into
```
let jp (y x!1) := return x!1;
print x;
let x := 10
y := y + 1;
jmp jp y x
```
and then we add the reassignment as in the previous example.
We need to include `y` in the jump, because each exit point is implicitly returning the set of
update variables.
We implement the method as follows. Let `us` be `c.uvars`, then
1- for each `return _ y` in `c`, we create a join point
`let j (us y!1) := return y!1`
and replace the `return _ y` with `jmp us y`
2- for each `break`, we create a join point
`let j (us) := break`
and replace the `break` with `jmp us`.
3- Same as 2 for `continue`.
-/
def pullExitPoints (c : Code) : TermElabM Code := do
if hasExitPoint c then
let (c, jpDecls) ← (pullExitPointsAux {} c).run #[]
pure $ attachJPs jpDecls c
else
pure c
partial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code :=
let rec update : Code → TermElabM Code
| Code.joinpoint j ps b k => do Code.joinpoint j ps (← update b) (← update k)
| Code.seq e k => do Code.seq e (← update k)
| c@(Code.«match» ref g ds t alts) => do
if alts.any fun alt => alt.vars.any fun x => ws.contains x then
-- If a pattern variable is shadowing a variable in ws, we `pullExitPoints`
pullExitPoints c
else
Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) })
| Code.ite ref none o c t e => do Code.ite ref none o c (← update t) (← update e)
| c@(Code.ite ref (some h) o cond t e) => do
if ws.contains h then
-- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints`
pullExitPoints c
else
Code.ite ref (some h) o cond (← update t) (← update e)
| Code.reassign xs stx k => do Code.reassign xs stx (← update k)
| c@(Code.decl xs stx k) => do
if xs.any fun x => ws.contains x then
-- One the declared variables is shadowing a variable in `ws`
pullExitPoints c
else
Code.decl xs stx (← update k)
| c => pure c
update c
/-
Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`.
We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`.
See discussion at `pullExitPoints`.
-/
partial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do
if ws.any fun x => !c.uvars.contains x then
-- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed)
pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws }
else
pure { c with uvars := ws }
private def union (s₁ s₂ : NameSet) : NameSet :=
s₁.fold (·.insert ·) s₂
/-
Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables.
Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`.
We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws`
-/
def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do
let ws := union c₁.uvars c₂.uvars
let c₁ ← extendUpdatedVars c₁ ws
let c₂ ← extendUpdatedVars c₂ ws
pure (c₁, c₂)
/-
Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`.
We remove `x` from the collection of updated varibles.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `let (x, y) := t`
-/
def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := {
code := Code.decl xs stx c.code,
uvars := eraseVars c.uvars xs
}
/-
Extending code blocks with reassignments: `x : t := v` and `x : t ← v`.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `(x, y) ← t`
-/
def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do
let us := c.uvars
let ws := insertVars us xs
-- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`.
-- See discussion at `pullExitPoints`
let code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code
pure { code := Code.reassign xs stx code, uvars := ws }
def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock :=
{ c with code := Code.seq action c.code }
def mkTerminalAction (action : Syntax) : CodeBlock :=
{ code := Code.action action }
def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock :=
{ code := Code.«return» ref val }
def mkBreak (ref : Syntax) : CodeBlock :=
{ code := Code.«break» ref }
def mkContinue (ref : Syntax) : CodeBlock :=
{ code := Code.«continue» ref }
def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do
let x? := if optIdent.isNone then none else some optIdent[0].getId
let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch
pure {
code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code,
uvars := thenBranch.uvars,
}
private def mkUnit : MacroM Syntax :=
``((⟨⟩ : PUnit))
private def mkPureUnit : MacroM Syntax :=
``(pure PUnit.unit)
def mkPureUnitAction : MacroM CodeBlock := do
mkTerminalAction (← mkPureUnit)
def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do
let thenBranch ← mkPureUnitAction
pure { c with code := Code.ite (← getRef) none mkNullNode cond thenBranch.code c.code }
def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do
-- nary version of homogenize
let ws := alts.foldl (union · ·.rhs.uvars) {}
let alts ← alts.mapM fun alt => do
let rhs ← extendUpdatedVars alt.rhs ws
pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code }
pure { code := Code.«match» ref genParam discrs optType alts, uvars := ws }
/- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`.
This method assumes `terminal` is a terminal -/
def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do
unless hasTerminalAction terminal.code do
throwErrorAt kRef "'do' element is unreachable"
let (terminal, k) ← homogenize terminal k
let xs := nameSetToArray k.uvars
let y ← match y? with | some y => pure y | none => mkFreshUserName `y
let ps := xs.map fun x => (x, true)
let ps := ps.push (y, false)
let jpDecl ← mkFreshJP ps k.code
let jp := jpDecl.name
let terminal ← liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs
pure { code := attachJP jpDecl terminal, uvars := k.uvars }
def getLetIdDeclVar (letIdDecl : Syntax) : Name :=
letIdDecl[0].getId
-- support both regular and syntax match
def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) :=
getPatternVarNames <$> getPatternVars pattern <|>
Array.map Syntax.getId <$> Quotation.getPatternVars pattern
def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) :=
getPatternVarNames <$> getPatternsVars patterns <|>
Array.map Syntax.getId <$> Quotation.getPatternsVars patterns
def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do
let pattern := letPatDecl[0]
getPatternVarsEx pattern
def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name :=
letEqnsDecl[0].getId
def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do
let arg := letDecl[0]
if arg.getKind == ``Lean.Parser.Term.letIdDecl then
pure #[getLetIdDeclVar arg]
else if arg.getKind == ``Lean.Parser.Term.letPatDecl then
getLetPatDeclVars arg
else if arg.getKind == ``Lean.Parser.Term.letEqnsDecl then
pure #[getLetEqnsDeclVar arg]
else
throwError "unexpected kind of let declaration"
def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) :=
-- leading_parser "let " >> optional "mut " >> letDecl
getLetDeclVars doLet[2]
def getDoHaveVar (doHave : Syntax) : Name :=
/-
`leading_parser "have " >> Term.haveDecl`
where
```
haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic)
optIdent := optional (try (ident >> " : "))
```
-/
let optIdent := doHave[1][0]
if optIdent.isNone then
`this
else
optIdent[0].getId
def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do
-- letRecDecls is an array of `(group (optional attributes >> letDecl))`
let letRecDecls := doLetRec[1][0].getSepArgs
let letDecls := letRecDecls.map fun p => p[2]
let mut allVars := #[]
for letDecl in letDecls do
let vars ← getLetDeclVars letDecl
allVars := allVars ++ vars
pure allVars
-- ident >> optType >> leftArrow >> termParser
def getDoIdDeclVar (doIdDecl : Syntax) : Name :=
doIdDecl[0].getId
-- termParser >> leftArrow >> termParser >> optional (" | " >> termParser)
def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do
let pattern := doPatDecl[0]
getPatternVarsEx pattern
-- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl)
def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do
let decl := doLetArrow[2]
if decl.getKind == ``Lean.Parser.Term.doIdDecl then
pure #[getDoIdDeclVar decl]
else if decl.getKind == ``Lean.Parser.Term.doPatDecl then
getDoPatDeclVars decl
else
throwError "unexpected kind of 'do' declaration"
def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do
let arg := doReassign[0]
if arg.getKind == ``Lean.Parser.Term.letIdDecl then
pure #[getLetIdDeclVar arg]
else if arg.getKind == ``Lean.Parser.Term.letPatDecl then
getLetPatDeclVars arg
else
throwError "unexpected kind of reassignment"
def mkDoSeq (doElems : Array Syntax) : Syntax :=
mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]]
def mkSingletonDoSeq (doElem : Syntax) : Syntax :=
mkDoSeq #[doElem]
/-
If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s. -/
private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with
| `(doElem|if $p:doIfProp then $t else $e) => pure none
| `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do
let mut e := e?.getD (← `(doSeq|pure PUnit.unit))
let mut eIsSeq := true
for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do
e ← if eIsSeq then e else `(doSeq|$e:doElem)
e ← withRef cond <| match cond with
| `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e)
| `(doIfCond|let $pat ← $d) => `(doElem| match%$i ← $d with | $pat:term => $t | _ => $e)
| `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e)
| _ => `(doElem| if%$i $(Syntax.missing) then $t else $e)
eIsSeq := false
return some e
| _ => pure none
structure DoIfView where
ref : Syntax
optIdent : Syntax
cond : Syntax
thenBranch : Syntax
elseBranch : Syntax
/- This method assumes `expandDoIf?` is not applicable. -/
private def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do
pure {
ref := doIf,
optIdent := doIf[1][0],
cond := doIf[1][1],
thenBranch := doIf[3],
elseBranch := doIf[5][1]
}
/-
We use `MProd` instead of `Prod` to group values when expanding the
`do` notation. `MProd` is a universe monomorphic product.
The motivation is to generate simpler universe constraints in code
that was not written by the user.
Note that we are not restricting the macro power since the
`Bind.bind` combinator already forces values computed by monadic
actions to be in the same universe.
-/
private def mkTuple (elems : Array Syntax) : MacroM Syntax := do
if elems.size == 0 then
mkUnit
else if elems.size == 1 then
pure elems[0]
else
(elems.extract 0 (elems.size - 1)).foldrM
(fun elem tuple => ``(MProd.mk $elem $tuple))
(elems.back)
/- Return `some action` if `doElem` is a `doExpr <action>`-/
def isDoExpr? (doElem : Syntax) : Option Syntax :=
if doElem.getKind == ``Lean.Parser.Term.doExpr then
some doElem[0]
else
none
/--
Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term
```
let a_1 := x.1
let x := x.2
let a_2 := x.1
let x := x.2
...
let a_n := x.1
let a_{n+1} := x.2
body
```
Special cases
- `uvars := #[]` => `body`
- `uvars := #[a]` => `let a := x; body`
We use this method when expanding the `for-in` notation.
-/
private def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do
if uvars.size == 0 then
return body
else if uvars.size == 1 then
`(let $(← mkIdentFromRef uvars[0]):ident := $x; $body)
else
destruct uvars.toList x body
where
destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do
match as with
| [a, b] => `(let $(← mkIdentFromRef a):ident := $x.1; let $(← mkIdentFromRef b):ident := $x.2; $body)
| a :: as => withFreshMacroScope do
let rest ← destruct as (← `(x)) body
`(let $(← mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest)
| _ => unreachable!
/-
The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term.
We use this method to convert
1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of
`CodeBlock` never contains `break` nor `continue`. Moreover, the collection
of updated variables is not packed into the result.
Thus, we have two kinds of exit points
- `Code.action e` which is converted into `e`
- `Code.return _ e` which is converted into `pure e`
We use `Kind.regular` for this case.
2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate
a `Syntax` term representing a function for the `xs.forIn` combinator.
a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term
has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type
of the tuple of variables reassigned by `b`.
We use `Kind.forInWithReturn` for this case
b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated
`Syntax` term has type `m (ForInStep σ)`.
We use `Kind.forIn` for this case.
3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`).
The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`,
`Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information.
For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`,
**and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and
`σ` is the type of the tuple of reassigned variables.
The type `DoResult α β σ` is usedf for code blocks that exit with
`Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values.
We don't use `DoResult α β σ` for all cases because:
a) The elaborator would not be able to infer all type parameters without extra annotations. For example,
if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`.
b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`),
but we don't want to consider "unreachable" cases.
We do not distinguish between cases that contain `break`, but not `continue`, and vice versa.
When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`,
and `b/c` for a code block that contains `Code.break _` or `Code.continue _`.
- `a`: `Kind.regular`, type `m (α × σ)`
- `r`: `Kind.regular`, type `m (α × σ)`
Note that the code that pattern matches on the result will behave differently in this case.
It produces `return a` for this case, and `pure a` for the previous one.
- `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)`
- `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)`
- `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)`
- `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)`
Again the code that pattern matches on the result will behave differently in this case and
the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for
this case, and `pure a` for the previous case.
- `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)`
Here is the recipe for adding new combinators with nested `do`s.
Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α`
1- Convert `doSeq` into `codeBlock : CodeBlock`
2- Create term `term` using `mkNestedTerm code m uvars a r bc` where
`code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`,
`m` is a `Syntax` representing the Monad, and
`a` is true if `code` contains `Code.action _`,
`r` is true if `code` contains `Code.return _ _`,
`bc` is true if `code` contains `Code.break _` or `Code.continue _`.
Remark: for combinators such as `repeat` that take a single `doSeq`, all
arguments, but `m`, are extracted from `codeBlock`.
3- Create the term `repeat $term`
4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc`
-/
namespace ToTerm
inductive Kind where
| regular
| forIn
| forInWithReturn
| nestedBC
| nestedPR
| nestedSBC
| nestedPRBC
instance : Inhabited Kind := ⟨Kind.regular⟩
def Kind.isRegular : Kind → Bool
| Kind.regular => true
| _ => false
structure Context where
m : Syntax -- Syntax to reference the monad associated with the do notation.
uvars : Array Name
kind : Kind
abbrev M := ReaderT Context MacroM
def mkUVarTuple : M Syntax := do
let ctx ← read
let uvarIdents ← ctx.uvars.mapM mkIdentFromRef
mkTuple uvarIdents
def returnToTerm (val : Syntax) : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| Kind.regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u))
| Kind.forIn => ``(Pure.pure (ForInStep.done $u))
| Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u)))
| Kind.nestedBC => unreachable!
| Kind.nestedPR => ``(Pure.pure (DoResultPR.«return» $val $u))
| Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«pureReturn» $val $u))
| Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«return» $val $u))
def continueToTerm : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| Kind.regular => unreachable!
| Kind.forIn => ``(Pure.pure (ForInStep.yield $u))
| Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u)))
| Kind.nestedBC => ``(Pure.pure (DoResultBC.«continue» $u))
| Kind.nestedPR => unreachable!
| Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«continue» $u))
| Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«continue» $u))
def breakToTerm : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| Kind.regular => unreachable!
| Kind.forIn => ``(Pure.pure (ForInStep.done $u))
| Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u)))
| Kind.nestedBC => ``(Pure.pure (DoResultBC.«break» $u))
| Kind.nestedPR => unreachable!
| Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«break» $u))
| Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«break» $u))
def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| Kind.regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u))
| Kind.forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u))
| Kind.forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u)))
| Kind.nestedBC => unreachable!
| Kind.nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u)))
| Kind.nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u)))
| Kind.nestedPRBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u)))
def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do
if action.getKind == ``Lean.Parser.Term.doDbgTrace then
let msg := action[1]
`(dbg_trace $msg; $k)
else if action.getKind == ``Lean.Parser.Term.doAssert then
let cond := action[1]
`(assert! $cond; $k)
else
let action ← withRef action ``(($action : $((←read).m) PUnit))
``(Bind.bind $action (fun (_ : PUnit) => $k))
def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do
let kind := decl.getKind
if kind == ``Lean.Parser.Term.doLet then
let letDecl := decl[2]
`(let $letDecl:letDecl; $k)
else if kind == ``Lean.Parser.Term.doLetRec then
let letRecToken := decl[0]
let letRecDecls := decl[1]
pure $ mkNode ``Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k]
else if kind == ``Lean.Parser.Term.doLetArrow then
let arg := decl[2]
let ref := arg
if arg.getKind == ``Lean.Parser.Term.doIdDecl then
let id := arg[0]
let type := expandOptType id arg[1]
let doElem := arg[3]
-- `doElem` must be a `doExpr action`. See `doLetArrowToCode`
match isDoExpr? doElem with
| some action =>
let action ← withRef action `(($action : $((← read).m) $type))
``(Bind.bind $action (fun ($id:ident : $type) => $k))
| none => Macro.throwErrorAt decl "unexpected kind of 'do' declaration"
else
Macro.throwErrorAt decl "unexpected kind of 'do' declaration"
else if kind == ``Lean.Parser.Term.doHave then
-- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser`
let args := decl.getArgs
let args := args ++ #[mkNullNode /- optional ';' -/, k]
pure $ mkNode `Lean.Parser.Term.«have» args
else
Macro.throwErrorAt decl "unexpected kind of 'do' declaration"
def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do
let kind := reassign.getKind
if kind == ``Lean.Parser.Term.doReassign then
-- doReassign := leading_parser (letIdDecl <|> letPatDecl)
let arg := reassign[0]
if arg.getKind == ``Lean.Parser.Term.letIdDecl then
-- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >> " := " >> termParser
let x := arg[0]
let val := arg[4]
let newVal ← `(ensure_type_of% $x $(quote "invalid reassignment, value") $val)
let arg := arg.setArg 4 newVal
let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]
`(let $letDecl:letDecl; $k)
else
-- TODO: ensure the types did not change
let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]
`(let $letDecl:letDecl; $k)
else
-- Note that `doReassignArrow` is expanded by `doReassignArrowToCode
Macro.throwErrorAt reassign "unexpected kind of 'do' reassignment"
def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do
if optIdent.isNone then
``(if $cond then $thenBranch else $elseBranch)
else
let h := optIdent[0]
``(if $h:ident : $cond then $thenBranch else $elseBranch)
def mkJoinPoint (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do
let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(type_of% $(← mkIdentFromRef id)) else `(_)
let ps ← ps.mapM fun ⟨id, useTypeOf⟩ => mkIdentFromRef id
/-
We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`.
By elaborating `$k` first, we "learn" more about `$body`'s type.
For example, consider the following example `do` expression
```
def f (x : Nat) : IO Unit := do
if x > 0 then
IO.println "x is not zero" -- Error is here
IO.mkRef true
```
it is expanded into
```
def f (x : Nat) : IO Unit := do
let jp (u : Unit) : IO _ :=
IO.mkRef true;
if x > 0 then
IO.println "not zero"
jp ()
else
jp ()
```
If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`.
Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`.
Then, we get the expected type mismatch error at `IO.mkRef true`. -/
`(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k)
def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax :=
Syntax.mkApp (mkIdentFrom ref j) args
partial def toTerm : Code → M Syntax
| Code.«return» ref val => withRef ref <| returnToTerm val
| Code.«continue» ref => withRef ref continueToTerm
| Code.«break» ref => withRef ref breakToTerm
| Code.action e => actionTerminalToTerm e
| Code.joinpoint j ps b k => do mkJoinPoint j ps (← toTerm b) (← toTerm k)
| Code.jmp ref j args => pure $ mkJmp ref j args
| Code.decl _ stx k => do declToTerm stx (← toTerm k)
| Code.reassign _ stx k => do reassignToTerm stx (← toTerm k)
| Code.seq stx k => do seqToTerm stx (← toTerm k)
| Code.ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e)
| Code.«match» ref genParam discrs optType alts => do
let mut termAlts := #[]
for alt in alts do
let rhs ← toTerm alt.rhs
let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", alt.patterns, mkAtomFrom alt.ref "=>", rhs]
termAlts := termAlts.push termAlt
let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts]
pure $ mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", genParam, discrs, optType, mkAtomFrom ref "with", termMatchAlts]
def run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do
let term ← toTerm code { m := m, kind := kind, uvars := uvars }
pure term
/- Given
- `a` is true if the code block has a `Code.action _` exit point
- `r` is true if the code block has a `Code.return _ _` exit point
- `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point
generate Kind. See comment at the beginning of the `ToTerm` namespace. -/
def mkNestedKind (a r bc : Bool) : Kind :=
match a, r, bc with
| true, false, false => Kind.regular
| false, true, false => Kind.regular
| false, false, true => Kind.nestedBC
| true, true, false => Kind.nestedPR
| true, false, true => Kind.nestedSBC
| false, true, true => Kind.nestedSBC
| true, true, true => Kind.nestedPRBC
| false, false, false => unreachable!
def mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do
ToTerm.run code m uvars (mkNestedKind a r bc)
/- Given a term `term` produced by `ToTerm.run`, pattern match on its result.
See comment at the beginning of the `ToTerm` namespace.
- `a` is true if the code block has a `Code.action _` exit point
- `r` is true if the code block has a `Code.return _ _` exit point
- `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point
The result is a sequence of `doElem` -/
def matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do
let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo)
let u ← mkTuple (← uvars.mapM mkIdentFromRef)
match a, r, bc with
| true, false, false =>
if uvars.isEmpty then
toDoElems (← `(do $term:term))
else
toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1))
| false, true, false =>
if uvars.isEmpty then
toDoElems (← `(do let r ← $term:term; return r))
else
toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1))
| false, false, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultBC.«break» u => $u:term := u; break
| DoResultBC.«continue» u => $u:term := u; continue)
| true, true, false => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultPR.«pure» a u => $u:term := u; pure a
| DoResultPR.«return» b u => $u:term := u; return b)
| true, false, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultSBC.«pureReturn» a u => $u:term := u; pure a
| DoResultSBC.«break» u => $u:term := u; break
| DoResultSBC.«continue» u => $u:term := u; continue)
| false, true, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultSBC.«pureReturn» a u => $u:term := u; return a
| DoResultSBC.«break» u => $u:term := u; break
| DoResultSBC.«continue» u => $u:term := u; continue)
| true, true, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultPRBC.«pure» a u => $u:term := u; pure a
| DoResultPRBC.«return» a u => $u:term := u; return a
| DoResultPRBC.«break» u => $u:term := u; break
| DoResultPRBC.«continue» u => $u:term := u; continue)
| false, false, false => unreachable!
end ToTerm
def isMutableLet (doElem : Syntax) : Bool :=
let kind := doElem.getKind
(kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet)
&&
!doElem[1].isNone
namespace ToCodeBlock
structure Context where
ref : Syntax
m : Syntax -- Syntax representing the monad associated with the do notation.
mutableVars : NameSet := {}
insideFor : Bool := false
abbrev M := ReaderT Context TermElabM
def withNewMutableVars {α} (newVars : Array Name) (mutable : Bool) (x : M α) : M α :=
withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x
def checkReassignable (xs : Array Name) : M Unit := do
let throwInvalidReassignment (x : Name) : M Unit :=
throwError "'{x.simpMacroScopes}' cannot be reassigned"
let ctx ← read
for x in xs do
unless ctx.mutableVars.contains x do
throwInvalidReassignment x
def checkNotShadowingMutable (xs : Array Name) : M Unit := do
let throwInvalidShadowing (x : Name) : M Unit :=
throwError "mutable variable '{x.simpMacroScopes}' cannot be shadowed"
let ctx ← read
for x in xs do
if ctx.mutableVars.contains x then
throwInvalidShadowing x
def withFor {α} (x : M α) : M α :=
withReader (fun ctx => { ctx with insideFor := true }) x
structure ToForInTermResult where
uvars : Array Name
term : Syntax
def mkForInBody (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do
let ctx ← read
let uvars := forInBody.uvars
let uvars := nameSetToArray uvars
let term ← liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn)
pure ⟨uvars, term⟩
def ensureInsideFor : M Unit :=
unless (← read).insideFor do
throwError "invalid 'do' element, it must be inside 'for'"
def ensureEOS (doElems : List Syntax) : M Unit :=
unless doElems.isEmpty do
throwError "must be last element in a 'do' sequence"
private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax → StateT (List Syntax) M Syntax
| stx@(Syntax.node i k args) =>
if liftMethodDelimiter k then
return stx
else if k == ``Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do
if inBinder then
throwErrorAt stx "cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`"
let term := args[1]
let term ← expandLiftMethodAux inQuot inBinder term
let auxDoElem ← `(doElem| let a ← $term:term)
modify fun s => s ++ [auxDoElem]
`(a)
else do
let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot
let inBinder := inBinder || (!inQuot && liftMethodForbiddenBinder stx)
let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder)
return Syntax.node i k args
| stx => pure stx
def expandLiftMethod (doElem : Syntax) : M (List Syntax × Syntax) := do
if !hasLiftMethod doElem then
pure ([], doElem)
else
let (doElem, doElemsNew) ← (expandLiftMethodAux false false doElem).run []
pure (doElemsNew, doElem)
def checkLetArrowRHS (doElem : Syntax) : M Unit := do
let kind := doElem.getKind
if kind == ``Lean.Parser.Term.doLetArrow ||
kind == ``Lean.Parser.Term.doLet ||
kind == ``Lean.Parser.Term.doLetRec ||
kind == ``Lean.Parser.Term.doHave ||
kind == ``Lean.Parser.Term.doReassign ||
kind == ``Lean.Parser.Term.doReassignArrow then
throwErrorAt doElem "invalid kind of value '{kind}' in an assignment"
/- Generate `CodeBlock` for `doReturn` which is of the form
```
"return " >> optional termParser
```
`doElems` is only used for sanity checking. -/
def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do
ensureEOS doElems
let argOpt := doReturn[1]
let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0]
return mkReturn (← getRef) arg
structure Catch where
x : Syntax
optType : Syntax
codeBlock : CodeBlock
def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet :=
let ws := tryCode.uvars
let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws
let ws := match finallyCode? with
| none => ws
| some c => union c.uvars ws
ws
def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool :=
p tryCode.code ||
catches.any (fun «catch» => p «catch».codeBlock.code) ||
match finallyCode? with
| none => false
| some finallyCode => p finallyCode.code
mutual
/- "Concatenate" `c` with `doSeqToCode doElems` -/
partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock :=
match doElems with
| [] => pure c
| nextDoElem :: _ => do
let k ← doSeqToCode doElems
let ref := nextDoElem
concat c ref none k
/- Generate `CodeBlock` for `doLetArrow; doElems`
`doLetArrow` is of the form
```
"let " >> optional "mut " >> (doIdDecl <|> doPatDecl)
```
where
```
def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser
def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser)
```
-/
partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do
let ref := doLetArrow
let decl := doLetArrow[2]
if decl.getKind == ``Lean.Parser.Term.doIdDecl then
let y := decl[0].getId
checkNotShadowingMutable #[y]
let doElem := decl[3]
let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems)
match isDoExpr? doElem with
| some action => pure $ mkVarDeclCore #[y] doLetArrow k
| none =>
checkLetArrowRHS doElem
let c ← doSeqToCode [doElem]
match doElems with
| [] => pure c
| kRef::_ => concat c kRef y k
else if decl.getKind == ``Lean.Parser.Term.doPatDecl then
let pattern := decl[0]
let doElem := decl[2]
let optElse := decl[3]
if optElse.isNone then withFreshMacroScope do
let auxDo ←
if isMutableLet doLetArrow then
`(do let discr ← $doElem; let mut $pattern:term := discr)
else
`(do let discr ← $doElem; let $pattern:term := discr)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else
if isMutableLet doLetArrow then
throwError "'mut' is currently not supported in let-decls with 'else' case"
let contSeq := mkDoSeq doElems.toArray
let elseSeq := mkSingletonDoSeq optElse[1]
let auxDo ← `(do let discr ← $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
else
throwError "unexpected kind of 'do' declaration"
/- Generate `CodeBlock` for `doReassignArrow; doElems`
`doReassignArrow` is of the form
```
(doIdDecl <|> doPatDecl)
```
-/
partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do
let ref := doReassignArrow
let decl := doReassignArrow[0]
if decl.getKind == ``Lean.Parser.Term.doIdDecl then
let doElem := decl[3]
let y := decl[0]
let auxDo ← `(do let r ← $doElem; $y:ident := r)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else if decl.getKind == ``Lean.Parser.Term.doPatDecl then
let pattern := decl[0]
let doElem := decl[2]
let optElse := decl[3]
if optElse.isNone then withFreshMacroScope do
let auxDo ← `(do let discr ← $doElem; $pattern:term := discr)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else
throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported"
else
throwError "unexpected kind of 'do' reassignment"
/- Generate `CodeBlock` for `doIf; doElems`
`doIf` is of the form
```
"if " >> optIdent >> termParser >> " then " >> doSeq
>> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq))
>> optional (" else " >> doSeq)
``` -/
partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do
let view ← liftMacroM $ mkDoIfView doIf
let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch)
let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch)
let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch
concatWith ite doElems
/- Generate `CodeBlock` for `doUnless; doElems`
`doUnless` is of the form
```
"unless " >> termParser >> "do " >> doSeq
``` -/
partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do
let ref := doUnless
let cond := doUnless[1]
let doSeq := doUnless[3]
let body ← doSeqToCode (getDoSeqElems doSeq)
let unlessCode ← liftMacroM <| mkUnless cond body
concatWith unlessCode doElems
/- Generate `CodeBlock` for `doFor; doElems`
`doFor` is of the form
```
def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser
def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq
```
-/
partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do
let doForDecls := doFor[1].getSepArgs
if doForDecls.size > 1 then
/-
Expand
```
for x in xs, y in ys do
body
```
into
```
let s := toStream ys
for x in xs do
match Stream.next? s with
| none => break
| some (y, s') =>
s := s'
body
```
-/
-- Extract second element
let doForDecl := doForDecls[1]
let y := doForDecl[0]
let ys := doForDecl[2]
let doForDecls := doForDecls.eraseIdx 1
let body := doFor[3]
withFreshMacroScope do
let toStreamFn ← withRef ys ``(toStream)
let auxDo ←
`(do let mut s := $toStreamFn:ident $ys
for $doForDecls:doForDecl,* do
match Stream.next? s with
| none => break
| some ($y, s') =>
s := s'
do $body)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else withRef doFor do
let x := doForDecls[0][0]
withRef x <| checkNotShadowingMutable (← getPatternVarsEx x)
let xs := doForDecls[0][2]
let forElems := getDoSeqElems doFor[3]
let forInBodyCodeBlock ← withFor (doSeqToCode forElems)
let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock
let uvarsTuple ← liftMacroM do mkTuple (← uvars.mapM mkIdentFromRef)
if hasReturn forInBodyCodeBlock.code then
let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody
let forInTerm ← `(for_in% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody)
let auxDo ← `(do let r ← $forInTerm:term;
$uvarsTuple:term := r.2;
match r.1 with
| none => Pure.pure (ensure_expected_type% "type mismatch, 'for'" PUnit.unit)
| some a => return ensure_expected_type% "type mismatch, 'for'" a)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else
let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody
let forInTerm ← `(for_in% $(xs) $uvarsTuple fun $x r => $forInBody)
if doElems.isEmpty then
let auxDo ← `(do let r ← $forInTerm:term;
$uvarsTuple:term := r;
Pure.pure (ensure_expected_type% "type mismatch, 'for'" PUnit.unit))
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
else
let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
/-- Generate `CodeBlock` for `doMatch; doElems` -/
partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do
let ref := doMatch
let genParam := doMatch[1]
let discrs := doMatch[2]
let optType := doMatch[3]
let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt`
let alts ← matchAlts.mapM fun matchAlt => do
let patterns := matchAlt[1]
let vars ← getPatternsVarsEx patterns.getSepArgs
withRef patterns <| checkNotShadowingMutable vars
let rhs := matchAlt[3]
let rhs ← doSeqToCode (getDoSeqElems rhs)
pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock }
let matchCode ← mkMatch ref genParam discrs optType alts
concatWith matchCode doElems
/--
Generate `CodeBlock` for `doTry; doElems`
```
def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally
def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq
def doCatchMatch := leading_parser "catch " >> doMatchAlts
def doFinally := leading_parser "finally " >> doSeq
```
-/
partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do
let ref := doTry
let tryCode ← doSeqToCode (getDoSeqElems doTry[1])
let optFinally := doTry[3]
let catches ← doTry[2].getArgs.mapM fun catchStx => do
if catchStx.getKind == ``Lean.Parser.Term.doCatch then
let x := catchStx[1]
if x.isIdent then
withRef x <| checkNotShadowingMutable #[x.getId]
let optType := catchStx[2]
let c ← doSeqToCode (getDoSeqElems catchStx[4])
pure { x := x, optType := optType, codeBlock := c : Catch }
else if catchStx.getKind == ``Lean.Parser.Term.doCatchMatch then
let matchAlts := catchStx[1]
let x ← `(ex)
let auxDo ← `(do match ex with $matchAlts)
let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo))
pure { x := x, codeBlock := c, optType := mkNullNode : Catch }
else
throwError "unexpected kind of 'catch'"
let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1])
if catches.isEmpty && finallyCode?.isNone then
throwError "invalid 'try', it must have a 'catch' or 'finally'"
let ctx ← read
let ws := getTryCatchUpdatedVars tryCode catches finallyCode?
let uvars := nameSetToArray ws
let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction
let r := tryCatchPred tryCode catches finallyCode? hasReturn
let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue
let toTerm (codeBlock : CodeBlock) : M Syntax := do
let codeBlock ← liftM $ extendUpdatedVars codeBlock ws
liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc
let term ← toTerm tryCode
let term ← catches.foldlM
(fun term «catch» => do
let catchTerm ← toTerm «catch».codeBlock
if catch.optType.isNone then
``(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm))
else
let type := «catch».optType[1]
``(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm)))
term
let term ← match finallyCode? with
| none => pure term
| some finallyCode => withRef optFinally do
unless finallyCode.uvars.isEmpty do
throwError "'finally' currently does not support reassignments"
if hasBreakContinueReturn finallyCode.code then
throwError "'finally' currently does 'return', 'break', nor 'continue'"
let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular
``(tryFinally $term $finallyTerm)
let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc
doSeqToCode (doElemsNew ++ doElems)
partial def doSeqToCode : List Syntax → M CodeBlock
| [] => do liftMacroM mkPureUnitAction
| doElem::doElems => withIncRecDepth <| withRef doElem do
checkMaxHeartbeats "'do'-expander"
match (← liftMacroM <| expandMacro? doElem) with
| some doElem => doSeqToCode (doElem::doElems)
| none =>
match (← liftMacroM <| expandDoIf? doElem) with
| some doElem => doSeqToCode (doElem::doElems)
| none =>
let (liftedDoElems, doElem) ← expandLiftMethod doElem
if !liftedDoElems.isEmpty then
doSeqToCode (liftedDoElems ++ [doElem] ++ doElems)
else
let ref := doElem
let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems
let k := doElem.getKind
if k == ``Lean.Parser.Term.doLet then
let vars ← getDoLetVars doElem
checkNotShadowingMutable vars
mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems)
else if k == ``Lean.Parser.Term.doHave then
let var := getDoHaveVar doElem
checkNotShadowingMutable #[var]
mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems)
else if k == ``Lean.Parser.Term.doLetRec then
let vars ← getDoLetRecVars doElem
checkNotShadowingMutable vars
mkVarDeclCore vars doElem <$> (doSeqToCode doElems)
else if k == ``Lean.Parser.Term.doReassign then
let vars ← getDoReassignVars doElem
checkReassignable vars
let k ← doSeqToCode doElems
mkReassignCore vars doElem k
else if k == ``Lean.Parser.Term.doLetArrow then
doLetArrowToCode doElem doElems
else if k == ``Lean.Parser.Term.doReassignArrow then
doReassignArrowToCode doElem doElems
else if k == ``Lean.Parser.Term.doIf then
doIfToCode doElem doElems
else if k == ``Lean.Parser.Term.doUnless then
doUnlessToCode doElem doElems
else if k == ``Lean.Parser.Term.doFor then withFreshMacroScope do
doForToCode doElem doElems
else if k == ``Lean.Parser.Term.doMatch then
doMatchToCode doElem doElems
else if k == ``Lean.Parser.Term.doTry then
doTryToCode doElem doElems
else if k == ``Lean.Parser.Term.doBreak then
ensureInsideFor
ensureEOS doElems
return mkBreak ref
else if k == ``Lean.Parser.Term.doContinue then
ensureInsideFor
ensureEOS doElems
return mkContinue ref
else if k == ``Lean.Parser.Term.doReturn then
doReturnToCode doElem doElems
else if k == ``Lean.Parser.Term.doDbgTrace then
return mkSeq doElem (← doSeqToCode doElems)
else if k == ``Lean.Parser.Term.doAssert then
return mkSeq doElem (← doSeqToCode doElems)
else if k == ``Lean.Parser.Term.doNested then
let nestedDoSeq := doElem[1]
doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems)
else if k == ``Lean.Parser.Term.doExpr then
let term := doElem[0]
if doElems.isEmpty then
return mkTerminalAction term
else
return mkSeq term (← doSeqToCode doElems)
else
throwError "unexpected do-element of kind {doElem.getKind}:\n{doElem}"
end
def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock :=
(doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m }
end ToCodeBlock
/- Create a synthetic metavariable `?m` and assign `m` to it.
We use `?m` to refer to `m` when expanding the `do` notation. -/
private def mkMonadAlias (m : Expr) : TermElabM Syntax := do
let result ← `(?m)
let mType ← inferType m
let mvar ← elabTerm result mType
assignExprMVar mvar.mvarId! m
pure result
private partial def ensureArrowNotUsed (stx : Syntax) : MacroM Unit := do
/- We expand macros here because we stop the search at nested `do`s
So, we also want to stop the search at macros that expand `do ...`.
Hopefully this is not a performance bottleneck in practice. -/
let stx ← expandMacros stx
stx.getArgs.forM go
where
go (stx : Syntax) : MacroM Unit :=
match stx with
| Syntax.node i k args => do
if k == ``Parser.Term.liftMethod || k == ``Parser.Term.doLetArrow || k == ``Parser.Term.doReassignArrow || k == ``Parser.Term.doIfLetBind then
Macro.throwErrorAt stx "`←` and `<-` are not allowed in pure `do` blocks, i.e., blocks where Lean implicitly used the `Id` monad"
unless k == ``Parser.Term.do do
args.forM go
| _ => pure ()
@[builtinTermElab «do»] def elabDo : TermElab := fun stx expectedType? => do
tryPostponeIfNoneOrMVar expectedType?
let bindInfo ← extractBind expectedType?
if bindInfo.isPure then
liftMacroM <| ensureArrowNotUsed stx
let m ← mkMonadAlias bindInfo.m
let codeBlock ← ToCodeBlock.run stx m
let stxNew ← liftMacroM $ ToTerm.run codeBlock.code m
trace[Elab.do] stxNew
withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType
end Do
builtin_initialize registerTraceClass `Elab.do
private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do
let stx := stx.setKind newKind
withRef stx `(do $stx:doElem)
@[builtinMacro Lean.Parser.Term.termFor]
def expandTermFor : Macro := toDoElem ``Lean.Parser.Term.doFor
@[builtinMacro Lean.Parser.Term.termTry]
def expandTermTry : Macro := toDoElem ``Lean.Parser.Term.doTry
@[builtinMacro Lean.Parser.Term.termUnless]
def expandTermUnless : Macro := toDoElem ``Lean.Parser.Term.doUnless
@[builtinMacro Lean.Parser.Term.termReturn]
def expandTermReturn : Macro := toDoElem ``Lean.Parser.Term.doReturn
end Lean.Elab.Term
|
e514c4ecaa40a475e81062e314c421b9bd774b87 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/lean/macroscopes.lean | 7361395c346efc040ee7cbeee45ae4554e15b3ee | [
"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 | 1,114 | lean | open Lean
def check (b : Bool) : IO Unit :=
unless b $ throw $ IO.userError "check failed"
def test1 : IO Unit := do
let x := `x;
let x := addMacroScope `main x 1;
IO.println $ x;
let v := extractMacroScopes x;
let x := { name := `y, .. v }.review;
IO.println $ x;
let v := extractMacroScopes x;
let x := { name := `x, .. v }.review;
IO.println $ x;
let x := addMacroScope `main x 2;
IO.println $ x;
let v := extractMacroScopes x;
let x := { name := `y, .. v }.review;
IO.println $ x;
let v := extractMacroScopes x;
let x := { name := `x, .. v }.review;
IO.println $ x;
let x := addMacroScope `main x 3;
IO.println $ x;
let x := addMacroScope `foo x 4;
IO.println $ x;
let x := addMacroScope `foo x 5;
let v := extractMacroScopes x;
check (v.mainModule == `foo);
IO.println $ x;
let x := addMacroScope `bla.bla x 6;
IO.println $ x;
let v := extractMacroScopes x;
check (v.mainModule == `bla.bla);
let x := addMacroScope `bla.bla x 7;
IO.println $ x;
let v := extractMacroScopes x;
let x := { name := `y, .. v }.review;
IO.println $ x;
let x := { name := `z.w, .. v }.review;
IO.println $ x;
pure ()
#eval test1
|
1afb111bffb9722fec72da616111d33536dc6d8e | 205f0fc16279a69ea36e9fd158e3a97b06834ce2 | /EXAMS/exam2-key.lean | 8adef334bd33ba81aa69d80f8f55f0763bab8766 | [] | no_license | kevinsullivan/cs-dm-lean | b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124 | a06a94e98be77170ca1df486c8189338b16cf6c6 | refs/heads/master | 1,585,948,743,595 | 1,544,339,346,000 | 1,544,339,346,000 | 155,570,767 | 1 | 3 | null | 1,541,540,372,000 | 1,540,995,993,000 | Lean | UTF-8 | Lean | false | false | 5,077 | lean | /-
EXAM 2 ANSWER KEY AND GRADING RUBRIC
This is the answer key and grading
rubric for CS2102 Fall 2018 Exam 2.
There are acceptable ways to have
answered some of the questions on
the exam, so correct answers need
not literally match those provided
here.
#1. 5 points each, no partial credit
#2. 10 points for the proposition and
10 points for the proof, with partial
credit of 5 points for a proof that is
correct but for minor issues, e.g., a
misplaced comma.
#3. 20 points, no partial credit
#4. 10 points for a right proposition,
10 points for the proof, with 5 points
for a proof that's substantially right
and suffering only from minor issues,
e.g., a misplaced colon or something.
#5. 10 free points plus 10 points for
the proof, with 3 points for using exists
elim correctly, 3 for using exists intro
correctly, 3 for using forall elimination
correctly (applying the proof of the ∀
to w), and 1 more for getting it all
right.
-/
/- ******************************* -/
/-
This exam focuses on assessing your
ability to write and prove propositions
in predicate logic, with an emphasis on
predicates, disjunctions, and existentially
quantified propositions. There are three
parts:
A: Predicates [20 points in 4 parts]
B: Disjuctions [40 points in 2 parts]
C. Existentials [40 point in 2 parts]
-/
/- ******************************** -/
/- *** A. PREDICATES [20 points] ***-/
/- ******************************** -/
/-
1a. Define a function called isOdd that
takes an argument, n : ℕ, and returns a
proposition that asserts that n is odd.
The function will thus be a predicate on
values of type ℕ. Hint: a number is odd
if it's one more than an even number.
-/
def isOdd(n:ℕ) :=
∃ m, 2 * m + 1 = n
-- We will accept an answer that uses mod
/-
1b. To test your predicate, use "example"
to write and prove isOdd(15).
-/
example : isOdd 15 :=
⟨ 7, rfl ⟩
-- an answer using mod will be just rfl
/-
1c. Define isSmall : ℕ → Prop, to be a
predicate that is true exactly when the
argument, n, is such that n = 0 ∨ n = 1
∨ n = 2 ∨ n = 3 ∨ n = 4 ∨ n = 5. (Don't
try to rewrite this proposition as an
inequality; just use it as is.)
-/
def isSmall (n: ℕ) : Prop :=
n = 0 ∨ n = 1 ∨ n = 2 ∨ n = 3 ∨ n = 4 ∨ n = 5
/-
1d. Define a predicate, isBoth(n:ℕ) that
is true exacly when n satisfies both the
isOdd and isSmall predicates. Use isOdd
and isSmall in your answer.
-/
def isBoth (n: ℕ ): Prop :=
isOdd n ∧ isSmall n
/- ******************* -/
/- *** DISJUNCTIONS ***-/
/- ******************* -/
/-
2. [20 Points]
Jane walks to school or she carries
her lunch. In either case, she uses
a bag. If she walks, she uses a bag for
her books. If she carries her lunch, she
uses a bag to carry her food. So if she
walks, she uses a bag, and if she carries
her lunch, she uses a bag. From the fact
that she walks or carries her lunch, and
from the added facts that in either case
she uses a bag, we can conclude that she
uses a bag.
Using Walks, Carries, and Bag as names
of propositions, write a Lean example
that asserts the following proposition;
then prove it.
If Walks, Carries, and Bag are
propositions, then if (Walks ∨ Carries)
is true, and then if (Walks implies Bag)
is true, and then if (Carries implies Bag)
is true, then Bag is true.
Here's a start.
example : ∀ (Walks Carries Bag : Prop), ...
-/
example: ∀ Walks Carries Bag : Prop,
Walks ∨ Carries →
(Walks → Bag) →
(Carries → Bag) →
Bag :=
begin
intros Walks Carries Bag,
intros wc wb cb,
apply or.elim wc wb cb
end
-- It's ok with shorter names (W, C, B)
/-
3. [20 Points]
Prove the following proposition.
-/
example :
∀ (P Q R : Prop),
(P ∧ Q) → (Q ∨ R) → (P ∨ R) :=
begin
intros P Q R pq qr,
apply or.inl pq.left
end
/- *********************** -/
/- *** C. EXISTENTIALS ***-/
/- *********************** -/
/-
4. [20 points]
Referring to the isBoth predicate you
defined in question #1, state and prove
the proposition that there *exists* a
number, n, that satisfies isBoth. Remember that you can use the unfold
tactic to expand the name of a predicate
in a goal. Use "example" to state the
proposition.
-/
example : ∃ n : ℕ, isBoth n :=
begin
apply exists.intro 3,
unfold isBoth,
apply and.intro,
apply exists.intro 1, apply rfl,
unfold isSmall,
right, right, right, left, apply rfl,
end
/-
5. [20 points]
Suppose that Heavy and Round are
predicates on values of any type, T.
Prove the proposition that if every
t : T is Heavy (satisfies the Heavy
predicate) and if there exists some
t : T that is Round (satisfies the
Round predicate) then there exists
some t : T is both Heavy and Round
(satisfies the conjunction of the
two properties).
-/
example :
∀ T : Type, ∀ (Heavy Round : T → Prop),
(∀ t, Heavy t) → (∃ t, Round t) →
(∃ t, Heavy t ∧ Round t) :=
begin
intros T H R,
assume all_h exists_r,
apply exists.elim exists_r,
intros w rw,
apply exists.intro w,
apply and.intro (all_h w) rw,
end
|
f0d11c49b9bcbbf5c80c7521d4ab0df848934909 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/nat/multiplicity.lean | ba4717738eae5c4967b06a12b9f8f6d92a03e772 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 11,044 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import algebra.big_operators.intervals
import algebra.geom_sum
import data.nat.bitwise
import data.nat.log
import data.nat.parity
import ring_theory.multiplicity
/-!
# Natural number multiplicity
This file contains lemmas about the multiplicity function (the maximum prime power dividing a
number) when applied to naturals, in particular calculating it for factorials and binomial
coefficients.
## Multiplicity calculations
* `nat.multiplicity_factorial`: Legendre's Theorem. The multiplicity of `p` in `n!` is
`n/p + ... + n/p^b` for any `b` such that `n/p^(b + 1) = 0`.
* `nat.multiplicity_factorial_mul`: The multiplicity of `p` in `(p * n)!` is `n` more than that of
`n!`.
* `nat.multiplicity_choose`: The multiplicity of `p` in `n.choose k` is the number of carries when
`k` and`n - k` are added in base `p`.
## Other declarations
* `nat.multiplicity_eq_card_pow_dvd`: The multiplicity of `m` in `n` is the number of positive
natural numbers `i` such that `m ^ i` divides `n`.
* `nat.multiplicity_two_factorial_lt`: The multiplicity of `2` in `n!` is strictly less than `n`.
* `nat.prime.multiplicity_something`: Specialization of `multiplicity.something` to a prime in the
naturals. Avoids having to provide `p ≠ 1` and other trivialities, along with translating between
`prime` and `nat.prime`.
## Tags
Legendre, p-adic
-/
open finset nat multiplicity
open_locale big_operators nat
namespace nat
/-- The multiplicity of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i`
divides `n`. This set is expressed by filtering `Ico 1 b` where `b` is any bound greater than
`log m n`. -/
lemma multiplicity_eq_card_pow_dvd {m n b : ℕ} (hm : m ≠ 1) (hn : 0 < n) (hb : log m n < b):
multiplicity m n = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card :=
calc
multiplicity m n = ↑(Ico 1 $ ((multiplicity m n).get (finite_nat_iff.2 ⟨hm, hn⟩) + 1)).card
: by simp
... = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card
: congr_arg coe $ congr_arg card $ finset.ext $ λ i,
begin
rw [mem_filter, mem_Ico, mem_Ico, lt_succ_iff, ←@part_enat.coe_le_coe i, part_enat.coe_get,
←pow_dvd_iff_le_multiplicity, and.right_comm],
refine (and_iff_left_of_imp (λ h, _)).symm,
cases m,
{ rw [zero_pow, zero_dvd_iff] at h,
exact (hn.ne' h.2).elim,
{ exact h.1 } },
exact ((pow_le_iff_le_log (succ_lt_succ $ nat.pos_of_ne_zero $ succ_ne_succ.1 hm) hn).1 $
le_of_dvd hn h.2).trans_lt hb,
end
namespace prime
lemma multiplicity_one {p : ℕ} (hp : p.prime) : multiplicity p 1 = 0 :=
multiplicity.one_right (prime_iff.mp hp).not_unit
lemma multiplicity_mul {p m n : ℕ} (hp : p.prime) :
multiplicity p (m * n) = multiplicity p m + multiplicity p n :=
multiplicity.mul $ prime_iff.mp hp
lemma multiplicity_pow {p m n : ℕ} (hp : p.prime) :
multiplicity p (m ^ n) = n • (multiplicity p m) :=
multiplicity.pow $ prime_iff.mp hp
lemma multiplicity_self {p : ℕ} (hp : p.prime) : multiplicity p p = 1 :=
multiplicity_self (prime_iff.mp hp).not_unit hp.ne_zero
lemma multiplicity_pow_self {p n : ℕ} (hp : p.prime) : multiplicity p (p ^ n) = n :=
multiplicity_pow_self hp.ne_zero (prime_iff.mp hp).not_unit n
/-- **Legendre's Theorem**
The multiplicity of a prime in `n!` is the sum of the quotients `n / p ^ i`. This sum is expressed
over the finset `Ico 1 b` where `b` is any bound greater than `log p n`. -/
lemma multiplicity_factorial {p : ℕ} (hp : p.prime) :
∀ {n b : ℕ}, log p n < b → multiplicity p n! = (∑ i in Ico 1 b, n / p ^ i : ℕ)
| 0 b hb := by simp [Ico, hp.multiplicity_one]
| (n+1) b hb :=
calc multiplicity p (n+1)! = multiplicity p n! + multiplicity p (n+1) :
by rw [factorial_succ, hp.multiplicity_mul, add_comm]
... = (∑ i in Ico 1 b, n / p ^ i : ℕ) + ((finset.Ico 1 b).filter (λ i, p ^ i ∣ n+1)).card :
by rw [multiplicity_factorial ((log_mono_right $ le_succ _).trans_lt hb),
← multiplicity_eq_card_pow_dvd hp.ne_one (succ_pos _) hb]
... = (∑ i in Ico 1 b, (n / p ^ i + if p^i ∣ n+1 then 1 else 0) : ℕ) :
by { rw [sum_add_distrib, sum_boole], simp }
... = (∑ i in Ico 1 b, (n + 1) / p ^ i : ℕ) :
congr_arg coe $ finset.sum_congr rfl $ λ _ _, (succ_div _ _).symm
/-- The multiplicity of `p` in `(p * (n + 1))!` is one more than the sum
of the multiplicities of `p` in `(p * n)!` and `n + 1`. -/
lemma multiplicity_factorial_mul_succ {n p : ℕ} (hp : p.prime) :
multiplicity p (p * (n + 1))! = multiplicity p (p * n)! + multiplicity p (n + 1) + 1 :=
begin
have hp' := prime_iff.mp hp,
have h0 : 2 ≤ p := hp.two_le,
have h1 : 1 ≤ p * n + 1 := nat.le_add_left _ _,
have h2 : p * n + 1 ≤ p * (n + 1), linarith,
have h3 : p * n + 1 ≤ p * (n + 1) + 1, linarith,
have hm : multiplicity p (p * n)! ≠ ⊤,
{ rw [ne.def, eq_top_iff_not_finite, not_not, finite_nat_iff],
exact ⟨hp.ne_one, factorial_pos _⟩ },
revert hm,
have h4 : ∀ m ∈ Ico (p * n + 1) (p * (n + 1)), multiplicity p m = 0,
{ intros m hm, apply multiplicity_eq_zero_of_not_dvd,
rw [← not_dvd_iff_between_consec_multiples _ (pos_iff_ne_zero.mpr hp.ne_zero)],
rw [mem_Ico] at hm,
exact ⟨n, lt_of_succ_le hm.1, hm.2⟩ },
simp_rw [← prod_Ico_id_eq_factorial, multiplicity.finset.prod hp', ← sum_Ico_consecutive _ h1 h3,
add_assoc], intro h,
rw [part_enat.add_left_cancel_iff h, sum_Ico_succ_top h2, multiplicity.mul hp',
hp.multiplicity_self, sum_congr rfl h4, sum_const_zero, zero_add,
add_comm (1 : part_enat)]
end
/-- The multiplicity of `p` in `(p * n)!` is `n` more than that of `n!`. -/
lemma multiplicity_factorial_mul {n p : ℕ} (hp : p.prime) :
multiplicity p (p * n)! = multiplicity p n! + n :=
begin
induction n with n ih,
{ simp },
{ simp only [succ_eq_add_one, multiplicity.mul, hp, prime_iff.mp hp, ih,
multiplicity_factorial_mul_succ, ←add_assoc, nat.cast_one, nat.cast_add, factorial_succ],
congr' 1,
rw [add_comm, add_assoc] }
end
/-- A prime power divides `n!` iff it is at most the sum of the quotients `n / p ^ i`.
This sum is expressed over the set `Ico 1 b` where `b` is any bound greater than `log p n` -/
lemma pow_dvd_factorial_iff {p : ℕ} {n r b : ℕ} (hp : p.prime) (hbn : log p n < b) :
p ^ r ∣ n! ↔ r ≤ ∑ i in Ico 1 b, n / p ^ i :=
by rw [← part_enat.coe_le_coe, ← hp.multiplicity_factorial hbn, ← pow_dvd_iff_le_multiplicity]
lemma multiplicity_factorial_le_div_pred {p : ℕ} (hp : p.prime) (n : ℕ) :
multiplicity p n! ≤ (n/(p - 1) : ℕ) :=
begin
rw [hp.multiplicity_factorial (lt_succ_self _), part_enat.coe_le_coe],
exact nat.geom_sum_Ico_le hp.two_le _ _,
end
lemma multiplicity_choose_aux {p n b k : ℕ} (hp : p.prime) (hkn : k ≤ n) :
∑ i in finset.Ico 1 b, n / p ^ i =
∑ i in finset.Ico 1 b, k / p ^ i + ∑ i in finset.Ico 1 b, (n - k) / p ^ i +
((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card :=
calc ∑ i in finset.Ico 1 b, n / p ^ i
= ∑ i in finset.Ico 1 b, (k + (n - k)) / p ^ i :
by simp only [add_tsub_cancel_of_le hkn]
... = ∑ i in finset.Ico 1 b, (k / p ^ i + (n - k) / p ^ i +
if p ^ i ≤ k % p ^ i + (n - k) % p ^ i then 1 else 0) :
by simp only [nat.add_div (pow_pos hp.pos _)]
... = _ : by simp [sum_add_distrib, sum_boole]
/-- The multiplicity of `p` in `choose n k` is the number of carries when `k` and `n - k`
are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b`
is any bound greater than `log p n`. -/
lemma multiplicity_choose {p n k b : ℕ} (hp : p.prime) (hkn : k ≤ n) (hnb : log p n < b) :
multiplicity p (choose n k) =
((Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card :=
have h₁ : multiplicity p (choose n k) + multiplicity p (k! * (n - k)!) =
((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card +
multiplicity p (k! * (n - k)!),
begin
rw [← hp.multiplicity_mul, ← mul_assoc, choose_mul_factorial_mul_factorial hkn,
hp.multiplicity_factorial hnb, hp.multiplicity_mul,
hp.multiplicity_factorial ((log_mono_right hkn).trans_lt hnb),
hp.multiplicity_factorial (lt_of_le_of_lt (log_mono_right tsub_le_self) hnb),
multiplicity_choose_aux hp hkn],
simp [add_comm],
end,
(part_enat.add_right_cancel_iff
(part_enat.ne_top_iff_dom.2 $
by exact finite_nat_iff.2
⟨ne_of_gt hp.one_lt, mul_pos (factorial_pos k) (factorial_pos (n - k))⟩)).1
h₁
/-- A lower bound on the multiplicity of `p` in `choose n k`. -/
lemma multiplicity_le_multiplicity_choose_add {p : ℕ} (hp : p.prime) : ∀ (n k : ℕ),
multiplicity p n ≤ multiplicity p (choose n k) + multiplicity p k
| _ 0 := by simp
| 0 (_+1) := by simp
| (n+1) (k+1) :=
begin
rw ← hp.multiplicity_mul,
refine multiplicity_le_multiplicity_of_dvd_right _,
rw [← succ_mul_choose_eq],
exact dvd_mul_right _ _
end
lemma multiplicity_choose_prime_pow {p n k : ℕ} (hp : p.prime)
(hkn : k ≤ p ^ n) (hk0 : 0 < k) :
multiplicity p (choose (p ^ n) k) + multiplicity p k = n :=
le_antisymm
(have hdisj : disjoint
((Ico 1 n.succ).filter (λ i, p ^ i ≤ k % p ^ i + (p ^ n - k) % p ^ i))
((Ico 1 n.succ).filter (λ i, p ^ i ∣ k)),
by simp [disjoint_right, *, dvd_iff_mod_eq_zero, nat.mod_lt _ (pow_pos hp.pos _)]
{contextual := tt},
begin
rw [multiplicity_choose hp hkn (lt_succ_self _),
multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) hk0
(lt_succ_of_le (log_mono_right hkn)),
← nat.cast_add, part_enat.coe_le_coe, log_pow hp.one_lt,
← card_disjoint_union hdisj, filter_union_right],
have filter_le_Ico := (Ico 1 n.succ).card_filter_le _,
rwa card_Ico 1 n.succ at filter_le_Ico,
end)
(by rw [← hp.multiplicity_pow_self];
exact multiplicity_le_multiplicity_choose_add hp _ _)
end prime
lemma multiplicity_two_factorial_lt : ∀ {n : ℕ} (h : n ≠ 0), multiplicity 2 n! < n :=
begin
have h2 := prime_iff.mp prime_two,
refine binary_rec _ _,
{ contradiction },
{ intros b n ih h,
by_cases hn : n = 0,
{ subst hn, simp at h, simp [h, one_right h2.not_unit] },
have : multiplicity 2 (2 * n)! < (2 * n : ℕ),
{ rw [prime_two.multiplicity_factorial_mul],
refine (part_enat.add_lt_add_right (ih hn) (part_enat.coe_ne_top _)).trans_le _,
rw [two_mul], norm_cast },
cases b,
{ simpa [bit0_eq_two_mul n] },
{ suffices : multiplicity 2 (2 * n + 1) + multiplicity 2 (2 * n)! < ↑(2 * n) + 1,
{ simpa [succ_eq_add_one, multiplicity.mul, h2, prime_two, nat.bit1_eq_succ_bit0,
bit0_eq_two_mul n] },
rw [multiplicity_eq_zero_of_not_dvd (two_not_dvd_two_mul_add_one n), zero_add],
refine this.trans _, exact_mod_cast lt_succ_self _ }}
end
end nat
|
81c0e5fed918aff82428b7f30570c01a914ffaa2 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/have2.lean | 71ca1ed2d53f51d01d9cca65c0981f53187109db | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 174 | lean | abbreviation Prop : Type.{1} := Type.{0}
variables a b c : Prop
axiom Ha : a
axiom Hb : b
axiom Hc : c
check have H1 [fact] : a, from Ha,
have H2 : a, from H1,
H2 |
666bb88249eca58e2955db9452b382ecbd19769c | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/e12.lean | 1be243c38c21b2b2121ceed95a11bf1178ad8af9 | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 956 | lean | precedence `+`:65
namespace nat
variable nat : Type.{1}
variable add : nat → nat → nat
infixl + := add
end
namespace int
using nat (nat)
variable int : Type.{1}
variable add : int → int → int
infixl + := add
variable of_nat : nat → int
coercion of_nat
end
variables n m : nat.nat
variables i j : int.int
section
using [notation] nat
using [notation] int
using [decls] nat
using [decls] int
check n+m
check i+j
-- check i+n -- Error
end
namespace int
using [decls] nat (nat)
-- Here is a possible trick for this kind of configuration
definition add_ni (a : nat) (b : int) := (of_nat a) + b
definition add_in (a : int) (b : nat) := a + (of_nat b)
infixl + := add_ni
infixl + := add_in
end
section
using [notation] nat
using [notation] int
using [declarations] nat
using [declarations] int
check n+m
check i+n
check n+i
end
section
using nat
using int
check n+m
check i+n
end |
b42e34951323e15dd329dedca8a865c758e5c8e4 | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/data/part.lean | 1504168230125bf2014f9435b0ff13ef6bbc497e | [
"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 | 16,843 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Jeremy Avigad, Simon Hudon
-/
import data.equiv.basic
import data.set.basic
/-!
# Partial values of a type
This file defines `part α`, the partial values of a type.
`o : part α` carries a proposition `o.dom`, its domain, along with a function `get : o.dom → α`, its
value. The rule is then that every partial value has a value but, to access it, you need to provide
a proof of the domain.
`part α` behaves the same as `option α` except that `o : option α` is decidably `none` or `some a`
for some `a : α`, while the domain of `o : part α` doesn't have to be decidable. That means you can
translate back and forth between a partial value with a decidable domain and an option, and
`option α` and `part α` are classically equivalent. In general, `part α` is bigger than `option α`.
In current mathlib, `part ℕ`, aka `enat`, is used to move decidability of the order to decidability
of `enat.find` (which is the smallest natural satisfying a predicate, or `∞` if there's none).
## Main declarations
`option`-like declarations:
* `part.none`: The partial value whose domain is `false`.
* `part.some a`: The partial value whose domain is `true` and whose value is `a`.
* `part.of_option`: Converts an `option α` to a `part α` by sending `none` to `none` and `some a` to
`some a`.
* `part.to_option`: Converts a `part α` with a decidable domain to an `option α`.
* `part.equiv_option`: Classical equivalence between `part α` and `option α`.
Monadic structure:
* `part.bind`: `o.bind f` has value `(f (o.get _)).get _` (`f o` morally) and is defined when `o`
and `f (o.get _)` are defined.
* `part.map`: Maps the value and keeps the same domain.
Other:
* `part.restrict`: `part.restrict p o` replaces the domain of `o : part α` by `p : Prop` so long as
`p → o.dom`.
* `part.assert`: `assert p f` appends `p` to the domains of the values of a partial function.
* `part.unwrap`: Gets the value of a partial value regardless of its domain. Unsound.
## Notation
For `a : α`, `o : part α`, `a ∈ o` means that `o` is defined and equal to `a`. Formally, it means
`o.dom` and `o.get _ = a`.
-/
/-- `part α` is the type of "partial values" of type `α`. It
is similar to `option α` except the domain condition can be an
arbitrary proposition, not necessarily decidable. -/
structure {u} part (α : Type u) : Type u :=
(dom : Prop)
(get : dom → α)
namespace part
variables {α : Type*} {β : Type*} {γ : Type*}
/-- Convert a `part α` with a decidable domain to an option -/
def to_option (o : part α) [decidable o.dom] : option α :=
if h : dom o then some (o.get h) else none
/-- `part` extensionality -/
theorem ext' : ∀ {o p : part α}
(H1 : o.dom ↔ p.dom)
(H2 : ∀h₁ h₂, o.get h₁ = p.get h₂), o = p
| ⟨od, o⟩ ⟨pd, p⟩ H1 H2 := have t : od = pd, from propext H1,
by cases t; rw [show o = p, from funext $ λp, H2 p p]
/-- `part` eta expansion -/
@[simp] theorem eta : Π (o : part α), (⟨o.dom, λ h, o.get h⟩ : part α) = o
| ⟨h, f⟩ := rfl
/-- `a ∈ o` means that `o` is defined and equal to `a` -/
protected def mem (a : α) (o : part α) : Prop := ∃ h, o.get h = a
instance : has_mem α (part α) := ⟨part.mem⟩
theorem mem_eq (a : α) (o : part α) : (a ∈ o) = (∃ h, o.get h = a) :=
rfl
theorem dom_iff_mem : ∀ {o : part α}, o.dom ↔ ∃ y, y ∈ o
| ⟨p, f⟩ := ⟨λh, ⟨f h, h, rfl⟩, λ⟨_, h, rfl⟩, h⟩
theorem get_mem {o : part α} (h) : get o h ∈ o := ⟨_, rfl⟩
/-- `part` extensionality -/
@[ext]
theorem ext {o p : part α} (H : ∀ a, a ∈ o ↔ a ∈ p) : o = p :=
ext' ⟨λ h, ((H _).1 ⟨h, rfl⟩).fst,
λ h, ((H _).2 ⟨h, rfl⟩).fst⟩ $
λ a b, ((H _).2 ⟨_, rfl⟩).snd
/-- The `none` value in `part` has a `false` domain and an empty function. -/
def none : part α := ⟨false, false.rec _⟩
instance : inhabited (part α) := ⟨none⟩
@[simp] theorem not_mem_none (a : α) : a ∉ @none α := λ h, h.fst
/-- The `some a` value in `part` has a `true` domain and the
function returns `a`. -/
def some (a : α) : part α := ⟨true, λ_, a⟩
theorem mem_unique : ∀ {a b : α} {o : part α}, a ∈ o → b ∈ o → a = b
| _ _ ⟨p, f⟩ ⟨h₁, rfl⟩ ⟨h₂, rfl⟩ := rfl
theorem mem.left_unique : relator.left_unique ((∈) : α → part α → Prop) :=
λ a o b, mem_unique
theorem get_eq_of_mem {o : part α} {a} (h : a ∈ o) (h') : get o h' = a :=
mem_unique ⟨_, rfl⟩ h
protected theorem subsingleton (o : part α) : set.subsingleton {a | a ∈ o} :=
λ a ha b hb, mem_unique ha hb
@[simp] theorem get_some {a : α} (ha : (some a).dom) : get (some a) ha = a := rfl
theorem mem_some (a : α) : a ∈ some a := ⟨trivial, rfl⟩
@[simp] theorem mem_some_iff {a b} : b ∈ (some a : part α) ↔ b = a :=
⟨λ⟨h, e⟩, e.symm, λ e, ⟨trivial, e.symm⟩⟩
theorem eq_some_iff {a : α} {o : part α} : o = some a ↔ a ∈ o :=
⟨λ e, e.symm ▸ mem_some _,
λ ⟨h, e⟩, e ▸ ext' (iff_true_intro h) (λ _ _, rfl)⟩
theorem eq_none_iff {o : part α} : o = none ↔ ∀ a, a ∉ o :=
⟨λ e, e.symm ▸ not_mem_none, λ h, ext (by simpa)⟩
theorem eq_none_iff' {o : part α} : o = none ↔ ¬ o.dom :=
⟨λ e, e.symm ▸ id, λ h, eq_none_iff.2 (λ a h', h h'.fst)⟩
@[simp] lemma some_ne_none (x : α) : some x ≠ none :=
by { intro h, change none.dom, rw [← h], trivial }
@[simp] lemma none_ne_some (x : α) : none ≠ some x :=
(some_ne_none x).symm
lemma ne_none_iff {o : part α} : o ≠ none ↔ ∃ x, o = some x :=
begin
split,
{ rw [ne, eq_none_iff', not_not], exact λ h, ⟨o.get h, eq_some_iff.2 (get_mem h)⟩ },
{ rintro ⟨x, rfl⟩, apply some_ne_none }
end
lemma eq_none_or_eq_some (o : part α) : o = none ∨ ∃ x, o = some x :=
or_iff_not_imp_left.2 ne_none_iff.1
@[simp] lemma some_inj {a b : α} : part.some a = some b ↔ a = b :=
function.injective.eq_iff (λ a b h, congr_fun (eq_of_heq (part.mk.inj h).2) trivial)
@[simp] lemma some_get {a : part α} (ha : a.dom) :
part.some (part.get a ha) = a :=
eq.symm (eq_some_iff.2 ⟨ha, rfl⟩)
lemma get_eq_iff_eq_some {a : part α} {ha : a.dom} {b : α} :
a.get ha = b ↔ a = some b :=
⟨λ h, by simp [h.symm], λ h, by simp [h]⟩
lemma get_eq_get_of_eq (a : part α) (ha : a.dom) {b : part α} (h : a = b) :
a.get ha = b.get (h ▸ ha) :=
by { congr, exact h }
lemma get_eq_iff_mem {o : part α} {a : α} (h : o.dom) : o.get h = a ↔ a ∈ o :=
⟨λ H, ⟨h, H⟩, λ ⟨h', H⟩, H⟩
lemma eq_get_iff_mem {o : part α} {a : α} (h : o.dom) : a = o.get h ↔ a ∈ o :=
eq_comm.trans (get_eq_iff_mem h)
@[simp] lemma none_to_option [decidable (@none α).dom] : (none : part α).to_option = option.none :=
dif_neg id
@[simp] lemma some_to_option (a : α) [decidable (some a).dom] :
(some a).to_option = option.some a :=
dif_pos trivial
instance none_decidable : decidable (@none α).dom := decidable.false
instance some_decidable (a : α) : decidable (some a).dom := decidable.true
/-- Retrieves the value of `a : part α` if it exists, and return the provided default value
otherwise. -/
def get_or_else (a : part α) [decidable a.dom] (d : α) :=
if ha : a.dom then a.get ha else d
@[simp] lemma get_or_else_none (d : α) [decidable (none : part α).dom] : get_or_else none d = d :=
dif_neg id
@[simp] lemma get_or_else_some (a : α) (d : α) [decidable (some a).dom] :
get_or_else (some a) d = a :=
dif_pos trivial
@[simp] theorem mem_to_option {o : part α} [decidable o.dom] {a : α} :
a ∈ to_option o ↔ a ∈ o :=
begin
unfold to_option,
by_cases h : o.dom; simp [h],
{ exact ⟨λ h, ⟨_, h⟩, λ ⟨_, h⟩, h⟩ },
{ exact mt Exists.fst h }
end
/-- Converts an `option α` into a `part α`. -/
def of_option : option α → part α
| option.none := none
| (option.some a) := some a
@[simp] theorem mem_of_option {a : α} : ∀ {o : option α}, a ∈ of_option o ↔ a ∈ o
| option.none := ⟨λ h, h.fst.elim, λ h, option.no_confusion h⟩
| (option.some b) := ⟨λ h, congr_arg option.some h.snd,
λ h, ⟨trivial, option.some.inj h⟩⟩
@[simp] theorem of_option_dom {α} : ∀ (o : option α), (of_option o).dom ↔ o.is_some
| option.none := by simp [of_option, none]
| (option.some a) := by simp [of_option]
theorem of_option_eq_get {α} (o : option α) : of_option o = ⟨_, @option.get _ o⟩ :=
part.ext' (of_option_dom o) $ λ h₁ h₂, by cases o; [cases h₁, refl]
instance : has_coe (option α) (part α) := ⟨of_option⟩
@[simp] theorem mem_coe {a : α} {o : option α} :
a ∈ (o : part α) ↔ a ∈ o := mem_of_option
@[simp] theorem coe_none : (@option.none α : part α) = none := rfl
@[simp] theorem coe_some (a : α) : (option.some a : part α) = some a := rfl
@[elab_as_eliminator] protected lemma induction_on {P : part α → Prop}
(a : part α) (hnone : P none) (hsome : ∀ a : α, P (some a)) : P a :=
(classical.em a.dom).elim
(λ h, part.some_get h ▸ hsome _)
(λ h, (eq_none_iff'.2 h).symm ▸ hnone)
instance of_option_decidable : ∀ o : option α, decidable (of_option o).dom
| option.none := part.none_decidable
| (option.some a) := part.some_decidable a
@[simp] theorem to_of_option (o : option α) : to_option (of_option o) = o :=
by cases o; refl
@[simp] theorem of_to_option (o : part α) [decidable o.dom] : of_option (to_option o) = o :=
ext $ λ a, mem_of_option.trans mem_to_option
/-- `part α` is (classically) equivalent to `option α`. -/
noncomputable def equiv_option : part α ≃ option α :=
by haveI := classical.dec; exact
⟨λ o, to_option o, of_option, λ o, of_to_option o,
λ o, eq.trans (by dsimp; congr) (to_of_option o)⟩
/-- We give `part α` the order where everything is greater than `none`. -/
instance : order_bot (part α) :=
{ le := λ x y, ∀ i, i ∈ x → i ∈ y,
le_refl := λ x y, id,
le_trans := λ x y z f g i, g _ ∘ f _,
le_antisymm := λ x y f g, part.ext $ λ z, ⟨f _, g _⟩,
bot := none,
bot_le := by { introv x, rintro ⟨⟨_⟩,_⟩, } }
instance : preorder (part α) :=
by apply_instance
lemma le_total_of_le_of_le {x y : part α} (z : part α) (hx : x ≤ z) (hy : y ≤ z) :
x ≤ y ∨ y ≤ x :=
begin
rcases part.eq_none_or_eq_some x with h | ⟨b, h₀⟩,
{ rw h, left, apply order_bot.bot_le _ },
right, intros b' h₁,
rw part.eq_some_iff at h₀,
replace hx := hx _ h₀, replace hy := hy _ h₁,
replace hx := part.mem_unique hx hy, subst hx,
exact h₀
end
/-- `assert p f` is a bind-like operation which appends an additional condition
`p` to the domain and uses `f` to produce the value. -/
def assert (p : Prop) (f : p → part α) : part α :=
⟨∃ h : p, (f h).dom, λha, (f ha.fst).get ha.snd⟩
/-- The bind operation has value `g (f.get)`, and is defined when all the
parts are defined. -/
protected def bind (f : part α) (g : α → part β) : part β :=
assert (dom f) (λb, g (f.get b))
/-- The map operation for `part` just maps the value and maintains the same domain. -/
@[simps] def map (f : α → β) (o : part α) : part β :=
⟨o.dom, f ∘ o.get⟩
theorem mem_map (f : α → β) {o : part α} :
∀ {a}, a ∈ o → f a ∈ map f o
| _ ⟨h, rfl⟩ := ⟨_, rfl⟩
@[simp] theorem mem_map_iff (f : α → β) {o : part α} {b} :
b ∈ map f o ↔ ∃ a ∈ o, f a = b :=
⟨match b with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩, rfl⟩ end,
λ ⟨a, h₁, h₂⟩, h₂ ▸ mem_map f h₁⟩
@[simp] theorem map_none (f : α → β) :
map f none = none := eq_none_iff.2 $ λ a, by simp
@[simp] theorem map_some (f : α → β) (a : α) : map f (some a) = some (f a) :=
eq_some_iff.2 $ mem_map f $ mem_some _
theorem mem_assert {p : Prop} {f : p → part α}
: ∀ {a} (h : p), a ∈ f h → a ∈ assert p f
| _ x ⟨h, rfl⟩ := ⟨⟨x, h⟩, rfl⟩
@[simp] theorem mem_assert_iff {p : Prop} {f : p → part α} {a} :
a ∈ assert p f ↔ ∃ h : p, a ∈ f h :=
⟨match a with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩⟩ end,
λ ⟨a, h⟩, mem_assert _ h⟩
lemma assert_pos {p : Prop} {f : p → part α} (h : p) :
assert p f = f h :=
begin
dsimp [assert],
cases h' : f h,
simp only [h', h, true_and, iff_self, exists_prop_of_true, eq_iff_iff],
apply function.hfunext,
{ simp only [h,h',exists_prop_of_true] },
{ cc }
end
lemma assert_neg {p : Prop} {f : p → part α} (h : ¬ p) :
assert p f = none :=
begin
dsimp [assert,none], congr,
{ simp only [h, not_false_iff, exists_prop_of_false] },
{ apply function.hfunext,
{ simp only [h, not_false_iff, exists_prop_of_false] },
cc },
end
theorem mem_bind {f : part α} {g : α → part β} :
∀ {a b}, a ∈ f → b ∈ g a → b ∈ f.bind g
| _ _ ⟨h, rfl⟩ ⟨h₂, rfl⟩ := ⟨⟨h, h₂⟩, rfl⟩
@[simp] theorem mem_bind_iff {f : part α} {g : α → part β} {b} :
b ∈ f.bind g ↔ ∃ a ∈ f, b ∈ g a :=
⟨match b with _, ⟨⟨h₁, h₂⟩, rfl⟩ := ⟨_, ⟨_, rfl⟩, ⟨_, rfl⟩⟩ end,
λ ⟨a, h₁, h₂⟩, mem_bind h₁ h₂⟩
@[simp] theorem bind_none (f : α → part β) :
none.bind f = none := eq_none_iff.2 $ λ a, by simp
@[simp] theorem bind_some (a : α) (f : α → part β) :
(some a).bind f = f a := ext $ by simp
theorem bind_of_mem {o : part α} {a : α} (h : a ∈ o) (f : α → part β) :
o.bind f = f a :=
by rw [eq_some_iff.2 h, bind_some]
theorem bind_some_eq_map (f : α → β) (x : part α) :
x.bind (some ∘ f) = map f x :=
ext $ by simp [eq_comm]
theorem bind_assoc {γ} (f : part α) (g : α → part β) (k : β → part γ) :
(f.bind g).bind k = f.bind (λ x, (g x).bind k) :=
ext $ λ a, by simp; exact
⟨λ ⟨_, ⟨_, h₁, h₂⟩, h₃⟩, ⟨_, h₁, _, h₂, h₃⟩,
λ ⟨_, h₁, _, h₂, h₃⟩, ⟨_, ⟨_, h₁, h₂⟩, h₃⟩⟩
@[simp] theorem bind_map {γ} (f : α → β) (x) (g : β → part γ) :
(map f x).bind g = x.bind (λ y, g (f y)) :=
by rw [← bind_some_eq_map, bind_assoc]; simp
@[simp] theorem map_bind {γ} (f : α → part β) (x : part α) (g : β → γ) :
map g (x.bind f) = x.bind (λ y, map g (f y)) :=
by rw [← bind_some_eq_map, bind_assoc]; simp [bind_some_eq_map]
theorem map_map (g : β → γ) (f : α → β) (o : part α) :
map g (map f o) = map (g ∘ f) o :=
by rw [← bind_some_eq_map, bind_map, bind_some_eq_map]
instance : monad part :=
{ pure := @some,
map := @map,
bind := @part.bind }
instance : is_lawful_monad part :=
{ bind_pure_comp_eq_map := @bind_some_eq_map,
id_map := λ β f, by cases f; refl,
pure_bind := @bind_some,
bind_assoc := @bind_assoc }
theorem map_id' {f : α → α} (H : ∀ (x : α), f x = x) (o) : map f o = o :=
by rw [show f = id, from funext H]; exact id_map o
@[simp] theorem bind_some_right (x : part α) : x.bind some = x :=
by rw [bind_some_eq_map]; simp [map_id']
@[simp] theorem pure_eq_some (a : α) : pure a = some a := rfl
@[simp] theorem ret_eq_some (a : α) : return a = some a := rfl
@[simp] theorem map_eq_map {α β} (f : α → β) (o : part α) :
f <$> o = map f o := rfl
@[simp] theorem bind_eq_bind {α β} (f : part α) (g : α → part β) :
f >>= g = f.bind g := rfl
lemma bind_le {α} (x : part α) (f : α → part β) (y : part β) :
x >>= f ≤ y ↔ (∀ a, a ∈ x → f a ≤ y) :=
begin
split; intro h,
{ intros a h' b, replace h := h b,
simp only [and_imp, exists_prop, bind_eq_bind, mem_bind_iff, exists_imp_distrib] at h,
apply h _ h' },
{ intros b h',
simp only [exists_prop, bind_eq_bind, mem_bind_iff] at h',
rcases h' with ⟨a,h₀,h₁⟩, apply h _ h₀ _ h₁ },
end
instance : monad_fail part :=
{ fail := λ_ _, none, ..part.monad }
/-- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when
`p` implies `o` is defined. -/
def restrict (p : Prop) (o : part α) (H : p → o.dom) : part α :=
⟨p, λh, o.get (H h)⟩
@[simp]
theorem mem_restrict (p : Prop) (o : part α) (h : p → o.dom) (a : α) :
a ∈ restrict p o h ↔ p ∧ a ∈ o :=
begin
dsimp [restrict, mem_eq], split,
{ rintro ⟨h₀, h₁⟩, exact ⟨h₀, ⟨_, h₁⟩⟩ },
rintro ⟨h₀, h₁, h₂⟩, exact ⟨h₀, h₂⟩
end
/-- `unwrap o` gets the value at `o`, ignoring the condition. This function is unsound. -/
meta def unwrap (o : part α) : α := o.get undefined
theorem assert_defined {p : Prop} {f : p → part α} :
∀ (h : p), (f h).dom → (assert p f).dom := exists.intro
theorem bind_defined {f : part α} {g : α → part β} :
∀ (h : f.dom), (g (f.get h)).dom → (f.bind g).dom := assert_defined
@[simp] theorem bind_dom {f : part α} {g : α → part β} :
(f.bind g).dom ↔ ∃ h : f.dom, (g (f.get h)).dom := iff.rfl
end part
|
d9b9b6231be8c6ca4c5b7b542dd6710a3c9b6a54 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Elab/PreDefinition/Structural/Eqns.lean | 707814cbe836273a264c10ea5c8a974243f3ec77 | [
"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 | 3,912 | 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.Eqns
import Lean.Meta.Tactic.Split
import Lean.Meta.Tactic.Simp.Main
import Lean.Meta.Tactic.Apply
import Lean.Elab.PreDefinition.Basic
import Lean.Elab.PreDefinition.Eqns
import Lean.Elab.PreDefinition.Structural.Basic
namespace Lean.Elab
open Meta
open Eqns
namespace Structural
structure EqnInfo extends EqnInfoCore where
recArgPos : Nat
deriving Inhabited
private partial def mkProof (declName : Name) (type : Expr) : MetaM Expr := do
trace[Elab.definition.structural.eqns] "proving: {type}"
withNewMCtxDepth do
let main ← mkFreshExprSyntheticOpaqueMVar type
let (_, mvarId) ← main.mvarId!.intros
unless (← tryURefl mvarId) do -- catch easy cases
go (← deltaLHS mvarId)
instantiateMVars main
where
go (mvarId : MVarId) : MetaM Unit := do
trace[Elab.definition.structural.eqns] "step\n{MessageData.ofGoal mvarId}"
if (← tryURefl mvarId) then
return ()
else if (← tryContradiction mvarId) then
return ()
else if let some mvarId ← simpMatch? mvarId then
go mvarId
else if let some mvarId ← simpIf? mvarId then
go mvarId
else if let some mvarId ← whnfReducibleLHS? mvarId then
go mvarId
else match (← simpTargetStar mvarId {}) with
| TacticResultCNM.closed => return ()
| TacticResultCNM.modified mvarId => go mvarId
| TacticResultCNM.noChange =>
if let some mvarId ← deltaRHS? mvarId declName then
go mvarId
else if let some mvarIds ← casesOnStuckLHS? mvarId then
mvarIds.forM go
else if let some mvarIds ← splitTarget? mvarId then
mvarIds.forM go
else
throwError "failed to generate equational theorem for '{declName}'\n{MessageData.ofGoal mvarId}"
def mkEqns (info : EqnInfo) : MetaM (Array Name) :=
withOptions (tactic.hygienic.set · false) do
let eqnTypes ← withNewMCtxDepth <| lambdaTelescope info.value fun xs body => do
let us := info.levelParams.map mkLevelParam
let target ← mkEq (mkAppN (Lean.mkConst info.declName us) xs) body
let goal ← mkFreshExprSyntheticOpaqueMVar target
mkEqnTypes #[info.declName] goal.mvarId!
let baseName := mkPrivateName (← getEnv) info.declName
let mut thmNames := #[]
for i in [: eqnTypes.size] do
let type := eqnTypes[i]!
trace[Elab.definition.structural.eqns] "{eqnTypes[i]!}"
let name := baseName ++ (`_eq).appendIndexAfter (i+1)
thmNames := thmNames.push name
let value ← mkProof info.declName type
let (type, value) ← removeUnusedEqnHypotheses type value
addDecl <| Declaration.thmDecl {
name, type, value
levelParams := info.levelParams
}
return thmNames
builtin_initialize eqnInfoExt : MapDeclarationExtension EqnInfo ← mkMapDeclarationExtension `structEqInfo
def registerEqnsInfo (preDef : PreDefinition) (recArgPos : Nat) : CoreM Unit := do
modifyEnv fun env => eqnInfoExt.insert env preDef.declName { preDef with recArgPos }
def getEqnsFor? (declName : Name) : MetaM (Option (Array Name)) := do
if let some info := eqnInfoExt.find? (← getEnv) declName then
mkEqns info
else
return none
def getUnfoldFor? (declName : Name) : MetaM (Option Name) := do
let env ← getEnv
Eqns.getUnfoldFor? declName fun _ => eqnInfoExt.find? env declName |>.map (·.toEqnInfoCore)
@[export lean_get_structural_rec_arg_pos]
def getStructuralRecArgPosImp? (declName : Name) : CoreM (Option Nat) := do
let some info := eqnInfoExt.find? (← getEnv) declName | return none
return some info.recArgPos
builtin_initialize
registerGetEqnsFn getEqnsFor?
registerGetUnfoldEqnFn getUnfoldFor?
registerTraceClass `Elab.definition.structural.eqns
end Structural
end Lean.Elab
|
e66daa17437b84802bdde6c1f6e3e620dc0f728d | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/236c.lean | 217bc8bba8813ebd4315686ae4b09c110f94a78e | [
"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 | 273 | lean | constant foo_rec (n : ℕ) (k : Type) [has_one k] : Prop
lemma stupid (k : Type) [has_one k] (n : ℕ) :
foo_rec nat.zero k ↔ foo_rec nat.zero k :=
by simp only [nat.nat_zero_eq_zero]
open tactic
#eval do
cgr ← mk_congr_lemma_simp `(foo_rec),
type_check cgr.proof
|
eb2d07818fcd2c1dec1f3457c15d01aa712a23e6 | 36c7a18fd72e5b57229bd8ba36493daf536a19ce | /library/data/matrix.lean | d8910f0dbdf88c47489652912999d847434d2e99 | [
"Apache-2.0"
] | permissive | YHVHvx/lean | 732bf0fb7a298cd7fe0f15d82f8e248c11db49e9 | 038369533e0136dd395dc252084d3c1853accbf2 | refs/heads/master | 1,610,701,080,210 | 1,449,128,595,000 | 1,449,128,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,284 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
Matrices
-/
import algebra.ring data.fin data.fintype
open algebra fin nat
definition matrix [reducible] (A : Type) (m n : nat) := fin m → fin n → A
namespace matrix
variables {A B C : Type} {m n p : nat}
definition val [reducible] (M : matrix A m n) (i : fin m) (j : fin n) : A :=
M i j
namespace ops
notation M `[` i `, ` j `]` := val M i j
end ops
open ops
protected lemma ext {M N : matrix A m n} (h : ∀ i j, M[i,j] = N[i, j]) : M = N :=
funext (λ i, funext (λ j, h i j))
protected lemma has_decidable_eq [h : decidable_eq A] (m n : nat) : decidable_eq (matrix A m n) :=
_
definition to_matrix (f : fin m → fin n → A) : matrix A m n :=
f
definition map (f : A → B) (M : matrix A m n) : matrix B m n :=
λ i j, f (M[i,j])
definition map₂ (f : A → B → C) (M : matrix A m n) (N : matrix B m n) : matrix C m n :=
λ i j, f (M[i, j]) (N[i,j])
definition transpose (M : matrix A m n) : matrix A n m :=
λ i j, M[j, i]
definition symmetric (M : matrix A n n) :=
transpose M = M
section
variable [r : comm_ring A]
include r
definition identity (n : nat) : matrix A n n :=
λ i j, if i = j then 1 else 0
definition I {n : nat} : matrix A n n :=
identity n
protected definition zero (m n : nat) : matrix A m n :=
λ i j, 0
protected definition add (M : matrix A m n) (N : matrix A m n) : matrix A m n :=
λ i j, M[i, j] + N[i, j]
protected definition sub (M : matrix A m n) (N : matrix A m n) : matrix A m n :=
λ i j, M[i, j] - N[i, j]
protected definition mul (M : matrix A m n) (N : matrix A n p) : matrix A m p :=
λ i j, fin.foldl has_add.add 0 (λ k : fin n, M[i,k] * N[k,j])
definition smul (a : A) (M : matrix A m n) : matrix A m n :=
λ i j, a * M[i, j]
definition matrix_has_zero [reducible] [instance] (m n : nat) : has_zero (matrix A m n) :=
has_zero.mk (matrix.zero m n)
definition matrix_has_one [reducible] [instance] (n : nat) : has_one (matrix A n n) :=
has_one.mk (identity n)
definition matrix_has_add [reducible] [instance] (m n : nat) : has_add (matrix A m n) :=
has_add.mk matrix.add
definition matrix_has_mul [reducible] [instance] (n : nat) : has_mul (matrix A n n) :=
has_mul.mk matrix.mul
infix ` × ` := mul
infix `⬝` := smul
lemma add_zero (M : matrix A m n) : M + 0 = M :=
matrix.ext (λ i j, !algebra.add_zero)
lemma zero_add (M : matrix A m n) : 0 + M = M :=
matrix.ext (λ i j, !algebra.zero_add)
lemma add.comm (M : matrix A m n) (N : matrix A m n) : M + N = N + M :=
matrix.ext (λ i j, !algebra.add.comm)
lemma add.assoc (M : matrix A m n) (N : matrix A m n) (P : matrix A m n) : (M + N) + P = M + (N + P) :=
matrix.ext (λ i j, !algebra.add.assoc)
definition is_diagonal (M : matrix A n n) :=
∀ i j, i = j ∨ M[i, j] = 0
definition is_zero (M : matrix A m n) :=
∀ i j, M[i, j] = 0
definition is_upper_triangular (M : matrix A n n) :=
∀ i j : fin n, i > j → M[i, j] = 0
definition is_lower_triangular (M : matrix A n n) :=
∀ i j : fin n, i < j → M[i, j] = 0
definition inverse (M : matrix A n n) (N : matrix A n n) :=
M * N = I ∧ N * M = I
definition invertible (M : matrix A n n) :=
∃ N, inverse M N
end
end matrix
|
4d3382f172ce5c81d0658b5b595f7ad3a91b0853 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/category_theory/monad/basic.lean | 6553049eaac8d9e184103219e995b6708a2b1e1c | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 952 | 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.functor_category
namespace category_theory
open category
universes v₁ u₁ -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {C : Type u₁} [𝒞 : category.{v₁} C]
include 𝒞
class monad (T : C ⥤ C) :=
(η : 𝟭 _ ⟶ T)
(μ : T ⋙ T ⟶ T)
(assoc' : ∀ X : C, T.map (nat_trans.app μ X) ≫ μ.app _ = μ.app (T.obj X) ≫ μ.app _ . obviously)
(left_unit' : ∀ X : C, η.app (T.obj X) ≫ μ.app _ = 𝟙 _ . obviously)
(right_unit' : ∀ X : C, T.map (η.app X) ≫ μ.app _ = 𝟙 _ . obviously)
restate_axiom monad.assoc'
restate_axiom monad.left_unit'
restate_axiom monad.right_unit'
attribute [simp] monad.left_unit monad.right_unit
notation `η_` := monad.η
notation `μ_` := monad.μ
end category_theory
|
d2cae3ec32272893c3bf6fb443d053975ca1e7c8 | 6e9cd8d58e550c481a3b45806bd34a3514c6b3e0 | /src/ring_theory/localization.lean | 7fa6709f56cab537ba3b5b2784d2370dd1290bfe | [
"Apache-2.0"
] | permissive | sflicht/mathlib | 220fd16e463928110e7b0a50bbed7b731979407f | 1b2048d7195314a7e34e06770948ee00f0ac3545 | refs/heads/master | 1,665,934,056,043 | 1,591,373,803,000 | 1,591,373,803,000 | 269,815,267 | 0 | 0 | Apache-2.0 | 1,591,402,068,000 | 1,591,402,067,000 | null | UTF-8 | Lean | false | false | 28,713 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston
-/
import data.equiv.ring
import tactic.ring_exp
import ring_theory.ideal_operations
import group_theory.monoid_localization
/-!
# Localizations of commutative rings
We characterize the localization of a commutative ring `R` at a submonoid `M` up to
isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a
ring homomorphism `f : R →+* S` satisfying 3 properties:
1. For all `y ∈ M`, `f y` is a unit;
2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`;
3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`.
Given such a localization map `f : R →+* S`, we can define the surjection
`localization_map.mk'` sending `(x, y) : R × M` to `f x * (f y)⁻¹`, and
`localization_map.lift`, the homomorphism from `S` induced by a homomorphism from `R` which maps
elements of `M` to invertible elements of the codomain. Similarly, given commutative rings
`P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism
`g : R →+* P` such that `g(M) ⊆ T` induces a homomorphism of localizations,
`localization_map.map`, from `S` to `Q`.
We show the localization as a quotient type, defined in `group_theory.monoid_localization` as
`submonoid.localization`, is a `comm_ring` and that the natural ring hom
`of : R →+* localization M` is a localization map.
We prove some lemmas about the `R`-algebra structure of `S`.
When `R` is an integral domain, we define `fraction_map R K` as an abbreviation for
`localization (non_zero_divisors R) K`, the natural map to `R`'s field of fractions.
We show that a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}`
is a field.
## Implementation notes
In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one
structure with an isomorphic one; one way around this is to isolate a predicate characterizing
a structure up to isomorphism, and reason about things that satisfy the predicate.
A ring localization map is defined to be a localization map of the underlying `comm_monoid` (a
`submonoid.localization_map`) which is also a ring hom. To prove most lemmas about a
`localization_map` `f` in this file we invoke the corresponding proof for the underlying
`comm_monoid` localization map `f.to_localization_map`, which can be found in
`group_theory.monoid_localization` and the namespace `submonoid.localization_map`.
To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for
this structure.
To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas.
These show the quotient map `mk : R → M → localization M` equals the surjection
`localization_map.mk'` induced by the map `of : localization_map M (localization M)`
(where `of` establishes the localization as a quotient type satisfies the characteristic
predicate). The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file,
which are about the `localization_map.mk'` induced by any localization map.
We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the
`R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure.
## Tags
localization, ring localization, commutative ring localization, characteristic predicate,
commutative ring, field of fractions
-/
variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S]
{P : Type*} [comm_ring P]
open function
set_option old_structure_cmd true
/-- The type of ring homomorphisms satisfying the characteristic predicate: if `f : R →+* S`
satisfies this predicate, then `S` is isomorphic to the localization of `R` at `M`.
We later define an instance coercing a localization map `f` to its codomain `S` so
that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra
structure. -/
@[nolint has_inhabited_instance] structure localization_map
extends ring_hom R S, submonoid.localization_map M S
/-- The ring hom underlying a `localization_map`. -/
add_decl_doc localization_map.to_ring_hom
/-- The `comm_monoid` `localization_map` underlying a `comm_ring` `localization_map`.
See `group_theory.monoid_localization` for its definition. -/
add_decl_doc localization_map.to_localization_map
variables {M S}
namespace ring_hom
/-- Makes a localization map from a `comm_ring` hom satisfying the characteristic predicate. -/
def to_localization_map (f : R →+* S) (H1 : ∀ y : M, is_unit (f y))
(H2 : ∀ z, ∃ x : R × M, z * f x.2 = f x.1) (H3 : ∀ x y, f x = f y ↔ ∃ c : M, x * c = y * c) :
localization_map M S :=
{ map_units' := H1,
surj' := H2,
eq_iff_exists' := H3,
.. f }
end ring_hom
/-- Makes a `comm_ring` localization map from an additive `comm_monoid` localization map of
`comm_ring`s. -/
def submonoid.localization_map.to_ring_localization
(f : submonoid.localization_map M S)
(h : ∀ x y, f.to_map (x + y) = f.to_map x + f.to_map y) :
localization_map M S :=
{ ..ring_hom.mk' f.to_monoid_hom h, ..f }
namespace localization_map
variables (f : localization_map M S)
/-- Short for `to_ring_hom`; used for applying a localization map as a function. -/
abbreviation to_map := f.to_ring_hom
lemma map_units (y : M) : is_unit (f.to_map y) := f.6 y
lemma surj (z) : ∃ x : R × M, z * f.to_map x.2 = f.to_map x.1 := f.7 z
lemma eq_iff_exists {x y} : f.to_map x = f.to_map y ↔ ∃ c : M, x * c = y * c := f.8 x y
@[ext] lemma ext {f g : localization_map M S}
(h : ∀ x, f.to_map x = g.to_map x) : f = g :=
begin
cases f, cases g,
simp only [] at *,
exact funext h
end
lemma ext_iff {f g : localization_map M S} : f = g ↔ ∀ x, f.to_map x = g.to_map x :=
⟨λ h x, h ▸ rfl, ext⟩
lemma to_map_injective : injective (@localization_map.to_map _ _ M S _) :=
λ _ _ h, ext $ ring_hom.ext_iff.1 h
/-- Given `a : S`, `S` a localization of `R`, `is_integer a` iff `a` is in the image of
the localization map from `R` to `S`. -/
def is_integer (a : S) : Prop := a ∈ set.range f.to_map
variables {f}
lemma is_integer_add {a b} (ha : f.is_integer a) (hb : f.is_integer b) :
f.is_integer (a + b) :=
begin
rcases ha with ⟨a', ha⟩,
rcases hb with ⟨b', hb⟩,
use a' + b',
rw [f.to_map.map_add, ha, hb]
end
lemma is_integer_mul {a b} (ha : f.is_integer a) (hb : f.is_integer b) :
f.is_integer (a * b) :=
begin
rcases ha with ⟨a', ha⟩,
rcases hb with ⟨b', hb⟩,
use a' * b',
rw [f.to_map.map_mul, ha, hb]
end
lemma is_integer_smul {a : R} {b} (hb : f.is_integer b) :
f.is_integer (f.to_map a * b) :=
begin
rcases hb with ⟨b', hb⟩,
use a * b',
rw [←hb, f.to_map.map_mul]
end
variables (f)
/-- Each element `a : S` has an `M`-multiple which is an integer.
This version multiplies `a` on the right, matching the argument order in `localization_map.surj`.
-/
lemma exists_integer_multiple' (a : S) :
∃ (b : M), is_integer f (a * f.to_map b) :=
let ⟨⟨num, denom⟩, h⟩ := f.surj a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩
/-- Each element `a : S` has an `M`-multiple which is an integer.
This version multiplies `a` on the left, matching the argument order in the `has_scalar` instance.
-/
lemma exists_integer_multiple (a : S) :
∃ (b : M), is_integer f (f.to_map b * a) :=
by { simp_rw mul_comm _ a, apply exists_integer_multiple' }
/-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such
that `z * f y = f x` (so this lemma is true by definition). -/
lemma sec_spec {f : localization_map M S} (z : S) :
z * f.to_map (f.to_localization_map.sec z).2 = f.to_map (f.to_localization_map.sec z).1 :=
classical.some_spec $ f.surj z
/-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such
that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/
lemma sec_spec' {f : localization_map M S} (z : S) :
f.to_map (f.to_localization_map.sec z).1 = f.to_map (f.to_localization_map.sec z).2 * z :=
by rw [mul_comm, sec_spec]
lemma map_right_cancel {x y} {c : M} (h : f.to_map (c * x) = f.to_map (c * y)) :
f.to_map x = f.to_map y :=
f.to_localization_map.map_right_cancel h
lemma map_left_cancel {x y} {c : M} (h : f.to_map (x * c) = f.to_map (y * c)) :
f.to_map x = f.to_map y :=
f.to_localization_map.map_left_cancel h
lemma eq_zero_of_fst_eq_zero {z x} {y : M}
(h : z * f.to_map y = f.to_map x) (hx : x = 0) : z = 0 :=
by rw [hx, f.to_map.map_zero] at h;
exact (is_unit.mul_left_eq_zero_iff_eq_zero (f.map_units y)).1 h
/-- Given a localization map `f : R →+* S`, the surjection sending `(x, y) : R × M` to
`f x * (f y)⁻¹`. -/
noncomputable def mk' (f : localization_map M S) (x : R) (y : M) : S :=
f.to_localization_map.mk' x y
@[simp] lemma mk'_sec (z : S) :
f.mk' (f.to_localization_map.sec z).1 (f.to_localization_map.sec z).2 = z :=
f.to_localization_map.mk'_sec _
lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) :
f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ :=
f.to_localization_map.mk'_mul _ _ _ _
lemma mk'_one (x) : f.mk' x (1 : M) = f.to_map x :=
f.to_localization_map.mk'_one _
lemma mk'_spec (x) (y : M) :
f.mk' x y * f.to_map y = f.to_map x :=
f.to_localization_map.mk'_spec _ _
lemma mk'_spec' (x) (y : M) :
f.to_map y * f.mk' x y = f.to_map x :=
f.to_localization_map.mk'_spec' _ _
theorem eq_mk'_iff_mul_eq {x} {y : M} {z} :
z = f.mk' x y ↔ z * f.to_map y = f.to_map x :=
f.to_localization_map.eq_mk'_iff_mul_eq
theorem mk'_eq_iff_eq_mul {x} {y : M} {z} :
f.mk' x y = z ↔ f.to_map x = z * f.to_map y :=
f.to_localization_map.mk'_eq_iff_eq_mul
lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} :
f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.to_map (x₁ * y₂) = f.to_map (x₂ * y₁) :=
f.to_localization_map.mk'_eq_iff_eq
protected lemma eq {a₁ b₁} {a₂ b₂ : M} :
f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c :=
f.to_localization_map.eq
lemma eq_iff_eq (g : localization_map M P) {x y} :
f.to_map x = f.to_map y ↔ g.to_map x = g.to_map y :=
f.to_localization_map.eq_iff_eq g.to_localization_map
lemma mk'_eq_iff_mk'_eq (g : localization_map M P) {x₁ x₂}
{y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ :=
f.to_localization_map.mk'_eq_iff_mk'_eq g.to_localization_map
lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) :
f.mk' a₁ a₂ = f.mk' b₁ b₂ :=
f.to_localization_map.mk'_eq_of_eq H
@[simp] lemma mk'_self {x : R} {hx : x ∈ M} : f.mk' x ⟨x, hx⟩ = 1 :=
f.to_localization_map.mk'_self' _ hx
@[simp] lemma mk'_self' {x : M} : f.mk' x x = 1 :=
f.to_localization_map.mk'_self _
@[simp] lemma mk'_self'' {x : M} : f.mk' x.1 x = 1 :=
f.mk'_self'
lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) :
f.to_map x * f.mk' y z = f.mk' (x * y) z :=
f.to_localization_map.mul_mk'_eq_mk'_of_mul _ _ _
lemma mk'_eq_mul_mk'_one (x : R) (y : M) :
f.mk' x y = f.to_map x * f.mk' 1 y :=
(f.to_localization_map.mul_mk'_one_eq_mk' _ _).symm
@[simp] lemma mk'_mul_cancel_left (x : R) (y : M) :
f.mk' (y * x) y = f.to_map x :=
f.to_localization_map.mk'_mul_cancel_left _ _
lemma mk'_mul_cancel_right (x : R) (y : M) :
f.mk' (x * y) y = f.to_map x :=
f.to_localization_map.mk'_mul_cancel_right _ _
lemma is_unit_comp (j : S →+* P) (y : M) :
is_unit (j.comp f.to_map y) :=
f.to_localization_map.is_unit_comp j.to_monoid_hom _
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/
lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : f.to_map x = f.to_map y) :
g x = g y :=
@submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _
f.to_localization_map g.to_monoid_hom hg _ _ h
lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) :
f.mk' (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = f.mk' x₁ y₁ + f.mk' x₂ y₂ :=
f.mk'_eq_iff_eq_mul.2 $ eq.symm
begin
rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, ←eq_sub_iff_add_eq, mk'_eq_iff_eq_mul,
mul_comm _ (f.to_map _), mul_sub, eq_sub_iff_add_eq, ←eq_sub_iff_add_eq', ←mul_assoc,
←f.to_map.map_mul, mul_mk'_eq_mk'_of_mul, mk'_eq_iff_eq_mul],
simp only [f.to_map.map_add, submonoid.coe_mul, f.to_map.map_mul],
ring_exp,
end
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from
`S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that
`z = f x * (f y)⁻¹`. -/
noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P :=
ring_hom.mk' (@submonoid.localization_map.lift _ _ _ _ _ _ _
f.to_localization_map g.to_monoid_hom hg) $
begin
intros x y,
rw [f.to_localization_map.lift_spec, mul_comm, add_mul, ←sub_eq_iff_eq_add, eq_comm,
f.to_localization_map.lift_spec_mul, mul_comm _ (_ - _), sub_mul, eq_sub_iff_add_eq',
←eq_sub_iff_add_eq, mul_assoc, f.to_localization_map.lift_spec_mul],
show g _ * (g _ * g _) = g _ * (g _ * g _ - g _ * g _),
repeat {rw ←g.map_mul},
rw [←g.map_sub, ←g.map_mul],
apply f.eq_of_eq hg,
erw [f.to_map.map_mul, sec_spec', mul_sub, f.to_map.map_sub],
simp only [f.to_map.map_mul, sec_spec'],
ring_exp,
end
variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y))
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from
`S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/
lemma lift_mk' (x y) :
f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.mrestrict M) hg y)⁻¹ :=
f.to_localization_map.lift_mk' _ _ _
lemma lift_mk'_spec (x v) (y : M) :
f.lift hg (f.mk' x y) = v ↔ g x = g y * v :=
f.to_localization_map.lift_mk'_spec _ _ _ _
@[simp] lemma lift_eq (x : R) :
f.lift hg (f.to_map x) = g x :=
f.to_localization_map.lift_eq _ _
lemma lift_eq_iff {x y : R × M} :
f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) :=
f.to_localization_map.lift_eq_iff _
@[simp] lemma lift_comp : (f.lift hg).comp f.to_map = g :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_comp _
@[simp] lemma lift_of_comp (j : S →+* P) :
f.lift (f.is_unit_comp j) = j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_of_comp j.to_monoid_hom
lemma epic_of_localization_map {j k : S →+* P}
(h : ∀ a, j.comp f.to_map a = k.comp f.to_map a) : j = k :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.epic_of_localization_map
_ _ _ _ _ _ _ f.to_localization_map j.to_monoid_hom k.to_monoid_hom h
lemma lift_unique {j : S →+* P}
(hj : ∀ x, j (f.to_map x) = g x) : f.lift hg = j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique
_ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg j.to_monoid_hom hj
@[simp] lemma lift_id (x) : f.lift f.map_units x = x :=
f.to_localization_map.lift_id _
/-- Given two localization maps `f : R →+* S, k : R →+* P` for a submonoid `M ⊆ R`,
the hom from `P` to `S` induced by `f` is left inverse to the hom from `S` to `P`
induced by `k`. -/
@[simp] lemma lift_left_inverse {k : localization_map M S} (z : S) :
k.lift f.map_units (f.lift k.map_units z) = z :=
f.to_localization_map.lift_left_inverse _
lemma lift_surjective_iff :
surjective (f.lift hg) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 :=
f.to_localization_map.lift_surjective_iff hg
lemma lift_injective_iff :
injective (f.lift hg) ↔ ∀ x y, f.to_map x = f.to_map y ↔ g x = g y :=
f.to_localization_map.lift_injective_iff hg
variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q]
(k : localization_map T Q)
/-- Given a `comm_ring` homomorphism `g : R →+* P` where for submonoids `M ⊆ R, T ⊆ P` we have
`g(M) ⊆ T`, the induced ring homomorphism from the localization of `R` at `M` to the
localization of `P` at `T`: if `f : R →+* S` and `k : P →+* Q` are localization maps for `M`
and `T` respectively, we send `z : S` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : R × M` are
such that `z = f x * (f y)⁻¹`. -/
noncomputable def map : S →+* Q :=
@lift _ _ _ _ _ _ _ f (k.to_map.comp g) $ λ y, k.map_units ⟨g y, hy y⟩
variables {k}
lemma map_eq (x) :
f.map hy k (f.to_map x) = k.to_map (g x) :=
f.lift_eq (λ y, k.map_units ⟨g y, hy y⟩) x
@[simp] lemma map_comp :
(f.map hy k).comp f.to_map = k.to_map.comp g :=
f.lift_comp $ λ y, k.map_units ⟨g y, hy y⟩
lemma map_mk' (x) (y : M) :
f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ :=
@submonoid.localization_map.map_mk' _ _ _ _ _ _ _ f.to_localization_map
g.to_monoid_hom _ hy _ _ k.to_localization_map _ _
@[simp] lemma map_id (z : S) :
f.map (λ y, show ring_hom.id R y ∈ M, from y.2) f z = z :=
f.lift_id _
/-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition
of the induced maps equals the map of localizations induced by `l ∘ g`. -/
lemma map_comp_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W]
(j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) :
(k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.map_comp_map _ _ _ _ _ _ _
f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map
_ _ _ _ _ j.to_localization_map l.to_monoid_hom hl
/-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition
of the induced maps equals the map of localizations induced by `l ∘ g`. -/
lemma map_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W]
(j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) (x) :
k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x :=
by rw ←f.map_comp_map hy j hl; refl
/-- Given localization maps `f : R →+* S, k : P →+* Q` for submonoids `M, T` respectively, an
isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations
`S ≃+* Q`. -/
noncomputable def ring_equiv_of_ring_equiv (k : localization_map T Q) (h : R ≃+* P)
(H : M.map h.to_monoid_hom = T) :
S ≃+* Q :=
(f.to_localization_map.mul_equiv_of_mul_equiv k.to_localization_map H).to_ring_equiv $
(@lift _ _ _ _ _ _ _ f (k.to_map.comp h.to_ring_hom)
(λ y, k.map_units ⟨(h y), H ▸ set.mem_image_of_mem h y.2⟩)).map_add
@[simp] lemma ring_equiv_of_ring_equiv_eq_map_apply {j : R ≃+* P}
(H : M.map j.to_monoid_hom = T) (x) :
f.ring_equiv_of_ring_equiv k j H x =
f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl
lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) :
(f.ring_equiv_of_ring_equiv k j H).to_monoid_hom =
f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl
@[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) :
f.ring_equiv_of_ring_equiv k j H (f.to_map x) = k.to_map (j x) :=
f.to_localization_map.mul_equiv_of_mul_equiv_eq H _
lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x y) :
f.ring_equiv_of_ring_equiv k j H (f.mk' x y) =
k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ :=
f.to_localization_map.mul_equiv_of_mul_equiv_mk' H _ _
end localization_map
namespace localization
variables {M}
instance : has_add (localization M) :=
⟨λ z w, con.lift_on₂ z w
(λ x y : R × M, mk ((x.2 : R) * y.1 + y.2 * x.1) (x.2 * y.2)) $
λ r1 r2 r3 r4 h1 h2, (con.eq _).2
begin
rw r_eq_r' at h1 h2 ⊢,
cases h1 with t₅ ht₅,
cases h2 with t₆ ht₆,
use t₆ * t₅,
calc ((r1.2 : R) * r2.1 + r2.2 * r1.1) * (r3.2 * r4.2) * (t₆ * t₅) =
(r2.1 * r4.2 * t₆) * (r1.2 * r3.2 * t₅) + (r1.1 * r3.2 * t₅) * (r2.2 * r4.2 * t₆) : by ring
... = (r3.2 * r4.1 + r4.2 * r3.1) * (r1.2 * r2.2) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring
end⟩
instance : has_neg (localization M) :=
⟨λ z, con.lift_on z (λ x : R × M, mk (-x.1) x.2) $
λ r1 r2 h, (con.eq _).2
begin
rw r_eq_r' at h ⊢,
cases h with t ht,
use t,
rw [neg_mul_eq_neg_mul_symm, neg_mul_eq_neg_mul_symm, ht],
ring,
end⟩
instance : has_zero (localization M) :=
⟨mk 0 1⟩
private meta def tac := `[{
intros,
refine quotient.sound' (r_of_eq _),
simp only [prod.snd_mul, prod.fst_mul, submonoid.coe_mul],
ring }]
instance : comm_ring (localization M) :=
{ zero := 0,
one := 1,
add := (+),
mul := (*),
add_assoc := λ m n k, quotient.induction_on₃' m n k (by tac),
zero_add := λ y, quotient.induction_on' y (by tac),
add_zero := λ y, quotient.induction_on' y (by tac),
neg := has_neg.neg,
add_left_neg := λ y, quotient.induction_on' y (by tac),
add_comm := λ y z, quotient.induction_on₂' z y (by tac),
left_distrib := λ m n k, quotient.induction_on₃' m n k (by tac),
right_distrib := λ m n k, quotient.induction_on₃' m n k (by tac),
..localization.comm_monoid M }
variables (M)
/-- Natural hom sending `x : R`, `R` a `comm_ring`, to the equivalence class of
`(x, 1)` in the localization of `R` at a submonoid. -/
def of : localization_map M (localization M) :=
(localization.monoid_of M).to_ring_localization $
λ x y, (con.eq _).2 $ r_of_eq $ by simp [add_comm]
variables {M}
lemma monoid_of_eq_of (x) : (monoid_of M).to_map x = (of M).to_map x := rfl
lemma mk_one_eq_of (x) : mk x 1 = (of M).to_map x := rfl
lemma mk_eq_mk'_apply (x y) : mk x y = (of M).mk' x y :=
mk_eq_monoid_of_mk'_apply _ _
@[simp] lemma mk_eq_mk' : mk = (of M).mk' :=
mk_eq_monoid_of_mk'
variables (f : localization_map M S)
/-- Given a localization map `f : R →+* S` for a submonoid `M`, we get an isomorphism
between the localization of `R` at `M` as a quotient type and `S`. -/
noncomputable def ring_equiv_of_quotient :
localization M ≃+* S :=
(mul_equiv_of_quotient f.to_localization_map).to_ring_equiv $
((of M).lift f.map_units).map_add
variables {f}
@[simp] lemma ring_equiv_of_quotient_apply (x) :
ring_equiv_of_quotient f x = (of M).lift f.map_units x := rfl
@[simp] lemma ring_equiv_of_quotient_mk' (x y) :
ring_equiv_of_quotient f ((of M).mk' x y) = f.mk' x y :=
mul_equiv_of_quotient_mk' _ _
lemma ring_equiv_of_quotient_mk (x y) :
ring_equiv_of_quotient f (mk x y) = f.mk' x y :=
mul_equiv_of_quotient_mk _ _
@[simp] lemma ring_equiv_of_quotient_of (x) :
ring_equiv_of_quotient f ((of M).to_map x) = f.to_map x :=
mul_equiv_of_quotient_monoid_of _
@[simp] lemma ring_equiv_of_quotient_symm_mk' (x y) :
(ring_equiv_of_quotient f).symm (f.mk' x y) = (of M).mk' x y :=
mul_equiv_of_quotient_symm_mk' _ _
lemma ring_equiv_of_quotient_symm_mk (x y) :
(ring_equiv_of_quotient f).symm (f.mk' x y) = mk x y :=
mul_equiv_of_quotient_symm_mk _ _
@[simp] lemma ring_equiv_of_quotient_symm_of (x) :
(ring_equiv_of_quotient f).symm (f.to_map x) = (of M).to_map x :=
mul_equiv_of_quotient_symm_monoid_of _
end localization
variables {M}
namespace localization_map
/-!
### `algebra` section
Defines the `R`-algebra instance on a copy of `S` carrying the data of the localization map
`f` needed to induce the `R`-algebra structure. -/
variables (f : localization_map M S)
/-- We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that
the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra
structure. -/
@[reducible, nolint unused_arguments] def codomain (f : localization_map M S) := S
/-- We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the
`R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/
instance : algebra R f.codomain := f.to_map.to_algebra
@[simp] lemma of_id (a : R) :
(algebra.of_id R f.codomain) a = f.to_map a :=
rfl
variables (f)
/-- Localization map `f` from `R` to `S` as an `R`-linear map. -/
def lin_coe : R →ₗ[R] f.codomain :=
{ to_fun := f.to_map,
add := f.to_map.map_add,
smul := f.to_map.map_mul }
variables {f}
instance coe_submodules : has_coe (ideal R) (submodule R f.codomain) :=
⟨λ I, submodule.map f.lin_coe I⟩
lemma mem_coe (I : ideal R) {x : S} :
x ∈ (I : submodule R f.codomain) ↔ ∃ y : R, y ∈ I ∧ f.to_map y = x :=
iff.rfl
@[simp] lemma lin_coe_apply {x} : f.lin_coe x = f.to_map x := rfl
end localization_map
variables (R)
/-- The submonoid of non-zero-divisors of a `comm_ring` `R`. -/
def non_zero_divisors : submonoid R :=
{ carrier := {x | ∀ z, z * x = 0 → z = 0},
one_mem' := λ z hz, by rwa mul_one at hz,
mul_mem' := λ x₁ x₂ hx₁ hx₂ z hz,
have z * x₁ * x₂ = 0, by rwa mul_assoc,
hx₁ z $ hx₂ (z * x₁) this }
lemma eq_zero_of_ne_zero_of_mul_eq_zero {A : Type*} [integral_domain A]
{x y : A} (hnx : x ≠ 0) (hxy : y * x = 0) :
y = 0 := or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx
lemma mem_non_zero_divisors_iff_ne_zero {A : Type*} [integral_domain A] {x : A} :
x ∈ non_zero_divisors A ↔ x ≠ 0 :=
⟨λ hm hz, zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm,
λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx⟩
variables (K : Type*)
/-- Localization map from an integral domain `R` to its field of fractions. -/
@[reducible] def fraction_map [comm_ring K] := localization_map (non_zero_divisors R) K
namespace fraction_map
open localization_map
variables {R K}
lemma to_map_eq_zero_iff [comm_ring K] (φ : fraction_map R K) {x : R} :
x = 0 ↔ φ.to_map x = 0 :=
begin
rw ← φ.to_map.map_zero,
split; intro h,
{ rw h },
{ cases φ.eq_iff_exists.mp h with c hc,
rw zero_mul at hc,
exact c.2 x hc }
end
protected theorem injective [comm_ring K] (φ : fraction_map R K) :
injective φ.to_map :=
φ.to_map.injective_iff.2 (λ _ h, φ.to_map_eq_zero_iff.mpr h)
variables {A : Type*} [integral_domain A]
local attribute [instance] classical.dec_eq
/-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an
integral domain. -/
def to_integral_domain [comm_ring K] (φ : fraction_map A K) : integral_domain K :=
{ eq_zero_or_eq_zero_of_mul_eq_zero :=
begin
intros z w h,
cases φ.surj z with x hx,
cases φ.surj w with y hy,
have : z * w * φ.to_map y.2 * φ.to_map x.2 = φ.to_map x.1 * φ.to_map y.1, by
rw [mul_assoc z, hy, ←hx]; ac_refl,
erw h at this,
rw [zero_mul, zero_mul, ←φ.to_map.map_mul] at this,
cases eq_zero_or_eq_zero_of_mul_eq_zero (φ.to_map_eq_zero_iff.mpr this.symm) with H H,
{ exact or.inl (φ.eq_zero_of_fst_eq_zero hx H) },
{ exact or.inr (φ.eq_zero_of_fst_eq_zero hy H) },
end,
zero_ne_one := by erw [←φ.to_map.map_zero, ←φ.to_map.map_one];
exact λ h, zero_ne_one (φ.injective h),
..(infer_instance : comm_ring K) }
/-- The inverse of an element in the field of fractions of an integral domain. -/
protected noncomputable def inv [comm_ring K] (φ : fraction_map A K) (z : K) : K :=
if h : z = 0 then 0 else
φ.mk' (φ.to_localization_map.sec z).2 ⟨(φ.to_localization_map.sec z).1,
mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $ φ.eq_zero_of_fst_eq_zero (sec_spec z) h0⟩
protected lemma mul_inv_cancel [comm_ring K] (φ : fraction_map A K) (x : K) (hx : x ≠ 0) :
x * φ.inv x = 1 :=
show x * dite _ _ _ = 1, by rw [dif_neg hx,
←is_unit.mul_left_inj (φ.map_units ⟨(φ.to_localization_map.sec x).1,
mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, hx $ φ.eq_zero_of_fst_eq_zero (sec_spec x) h0⟩),
one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (φ.mk'_sec x).symm
/-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a
field. -/
noncomputable def to_field [comm_ring K] (φ : fraction_map A K) : field K :=
{ inv := φ.inv,
mul_inv_cancel := φ.mul_inv_cancel,
inv_zero := dif_pos rfl, ..φ.to_integral_domain }
end fraction_map
|
2818a241de2835c43985af5ea03a818ce8e48f08 | c062f1c97fdef9ac746f08754e7d766fd6789aa9 | /tools/super/intuit.lean | 2bd1205cedf3f843605dc6bdf8a82f4287539baf | [] | no_license | emberian/library_dev | 00c7a985b21bdebe912f4127a363f2874e1e7555 | f3abd7db0238edc18a397540e361a1da2f51503c | refs/heads/master | 1,624,153,474,804 | 1,490,147,180,000 | 1,490,147,180,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,587 | lean | import tools.super.clausifier tools.super.cdcl tools.super.trim
open tactic super expr monad
-- Intuitionistic propositional prover based on
-- SAT Modulo Intuitionistic Implications, Claessen and Rosen, LPAR 2015
namespace intuit
meta def check_model (intuit : tactic unit) : cdcl.solver (option cdcl.proof_term) :=
do s ← state_t.read, monad_lift $ do
hyps ← return $ s↣trail↣for (λe, e↣hyp),
subgoal ← mk_meta_var s↣local_false,
goals ← get_goals,
set_goals [subgoal],
for' s↣trail (λe,
if e↣phase then do
name ← get_unused_name `model (some 1),
assertv name e↣hyp↣local_type e↣hyp
else
return ()),
is_solved ← first (do
e ← s↣trail,
guard ¬e↣phase,
guard e↣var↣is_pi,
a ← option.to_monad $ s↣vars↣find e↣var↣binding_domain,
b ← option.to_monad $ s↣vars↣find e↣var↣binding_body,
guard $ a↣phase = ff ∧ b↣phase = ff,
return $ do
apply e↣hyp,
intuit,
now, return tt) <|> return ff,
set_goals goals,
if is_solved then do
proof ← instantiate_mvars subgoal,
proof' ← trim proof, -- gets rid of the unnecessary asserts
return $ some proof'
else
return none
lemma imp1 {F a b} : b → ((a → b) → F) → F := λhb habf, habf (λha, hb)
lemma imp2 {a b} : a → (a → b) → b := λha hab, hab ha
meta def solve : unit → tactic unit | () := with_trim $ do
as_refutation,
local_false ← target, clauses ← clauses_of_context,
clauses ← get_clauses_intuit clauses,
vars ← return $ list.nub (do c ← clauses, l ← c↣get_lits, [l↣formula]),
imp_axs ← sequence (do
v ← vars, guard v↣is_pi,
a ← return v↣binding_domain, b ← return v↣binding_body,
pr ← [mk_mapp ``intuit.imp1 [some local_false, some a, some b],
mk_mapp ``intuit.imp2 [some a, some b]],
[pr >>= clause.of_proof local_false]),
clauses ← return $ imp_axs ++ clauses,
result ← cdcl.solve (check_model (solve ())) local_false clauses,
match result with
| (cdcl.result.sat interp) :=
let interp' := do e ← interp↣to_list, [if e↣2 = tt then e↣1 else (```(not)) e↣1] in
do pp_interp ← pp interp',
fail (to_fmt "satisfying assignment: " ++ pp_interp)
| (cdcl.result.unsat proof) := exact proof
end
end intuit
meta def intuit : tactic unit := intuit.solve ()
example (a b) : a → (a → b) → b := by intuit
example (a b c) : (a → c) → (c → b) → ((a → b) → a) → a := by intuit
example (a b) : a ∨ ¬a → ((a → b) → a) → a := by intuit
def compose {a b c} : (a → b) → (b → c) → (a → c) := by intuit
|
17d2464f0cbc1a7b0f1f5c17e812b502fd6b03bc | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/mvar3.lean | 448f85ed4dea8f949a9738dbba3e98a1e5fc708f | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,864 | lean | import Lean.MetavarContext
new_frontend
open Lean
def mkLambdaTest (mctx : MetavarContext) (ngen : NameGenerator) (lctx : LocalContext) (xs : Array Expr) (e : Expr)
: Except MetavarContext.MkBinding.Exception (MetavarContext × NameGenerator × Expr) :=
match MetavarContext.mkLambda xs e lctx { mctx := mctx, ngen := ngen } with
| EStateM.Result.ok e s => Except.ok (s.mctx, s.ngen, e)
| EStateM.Result.error e s => Except.error e
def check (b : Bool) : IO Unit :=
«unless» b (throw $ IO.userError "error")
def f := mkConst `f
def g := mkConst `g
def a := mkConst `a
def b := mkConst `b
def c := mkConst `c
def b0 := mkBVar 0
def b1 := mkBVar 1
def b2 := mkBVar 2
def u := mkLevelParam `u
def typeE := mkSort levelOne
def natE := mkConst `Nat
def boolE := mkConst `Bool
def vecE := mkConst `Vec [levelZero]
def α := mkFVar `α
def x := mkFVar `x
def y := mkFVar `y
def z := mkFVar `z
def w := mkFVar `w
def m1 := mkMVar `m1
def m2 := mkMVar `m2
def m3 := mkMVar `m3
def bi := BinderInfo.default
def arrow (d b : Expr) := mkForall `_ bi d b
def lctx1 : LocalContext := {}
def lctx2 := lctx1.mkLocalDecl `α `α typeE
def lctx3 := lctx2.mkLocalDecl `x `x m1
def lctx4 := lctx3.mkLocalDecl `y `y (arrow natE m2)
def mctx1 : MetavarContext := {}
def mctx2 := mctx1.addExprMVarDecl `m1 `m1 lctx2 #[] typeE
def mctx3 := mctx2.addExprMVarDecl `m2 `m2 lctx3 #[] natE
def mctx4 := mctx3.addExprMVarDecl `m3 `m3 lctx3 #[] natE
def mctx4' := mctx3.addExprMVarDecl `m3 `m3 lctx3 #[] natE MetavarKind.syntheticOpaque
def R1 :=
match mkLambdaTest mctx4 {namePrefix := `n} lctx4 #[α, x, y] $ mkAppN f #[m3, x] with
| Except.ok s => s
| Except.error e => panic! (toString e)
def e1 := R1.2.2
def mctx5 := R1.1
def sortNames (xs : List Name) : List Name :=
(xs.toArray.qsort Name.lt).toList
def sortNamePairs {α} [Inhabited α] (xs : List (Name × α)) : List (Name × α) :=
(xs.toArray.qsort (fun a b => Name.lt a.1 b.1)).toList
#eval toString $ sortNames $ mctx5.decls.toList.map Prod.fst
#eval toString $ sortNamePairs $ mctx5.eAssignment.toList
#eval e1
#eval check (!e1.hasFVar)
def R2 :=
match mkLambdaTest mctx4' {namePrefix := `n} lctx4 #[α, x, y] $ mkAppN f #[m3, y] with
| Except.ok s => s
| Except.error e => panic! (toString e)
def e2 := R2.2.2
def mctx6 := R2.1
#eval toString $ sortNames $ mctx6.decls.toList.map Prod.fst
#eval toString $ sortNamePairs $ mctx6.eAssignment.toList
-- ?n.2 was delayed assigned because ?m.3 is synthetic
#eval toString $ sortNames $ mctx6.dAssignment.toList.map Prod.fst
#eval e2
#print "assigning ?m1 and ?n.1"
def R3 :=
let mctx := mctx6.assignExpr `m3 x;
let mctx := mctx.assignExpr (mkNameNum `n 1) (mkLambda `_ bi typeE natE);
-- ?n.2 is instantiated because we have the delayed assignment `?n.2 α x := ?m1`
(mctx.instantiateMVars e2)
def e3 := R3.1
def mctx7 := R3.2
#eval e3
|
3237a261559cb06b84b3103773731d7eff41e84c | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/run_tactic1.lean | 08d1820e7c1fbb3b783422ba1a688a93c348770e | [
"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 | 727 | lean | open tactic
run_command tactic.trace "hello world"
run_command do
N ← to_expr `(nat),
v ← to_expr `(10),
add_decl (declaration.defn `val10 [] N v reducibility_hints.opaque tt)
vm_eval val10
example : val10 = 10 := rfl
meta_definition mk_defs : nat → command
| 0 := skip
| (n+1) := do
N ← to_expr `(nat),
v ← expr_of_nat n,
add_decl (declaration.defn (name.append_after `val n) [] N v reducibility_hints.opaque tt),
mk_defs n
run_command mk_defs 10
example : val_1 = 1 := rfl
example : val_2 = 2 := rfl
example : val_3 = 3 := rfl
example : val_4 = 4 := rfl
example : val_5 = 5 := rfl
example : val_6 = 6 := rfl
example : val_7 = 7 := rfl
example : val_8 = 8 := rfl
example : val_9 = 9 := rfl
|
654ecb1e973698064d621add31649a1d8a9b9108 | 2f2aa789c57653a0a047d209e0401875a9427cfc | /src/homework/practice_2.lean | 590d76fe155f1c5af0dd48592418db8127243f86 | [] | no_license | AlexFetea/cs2120f21 | dc288aa4a907b116555758b7f63c37aa14f952ae | a2cf406a33e66aac2287341b1c3e9954db9b36ab | refs/heads/main | 1,693,910,053,038 | 1,636,678,382,000 | 1,636,678,382,000 | 399,946,831 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,362 | lean | /-
Prove the following simple logical conjectures.
Give a formal and an English proof of each one.
Your English language proofs should be complete
in the sense that they identify all the axioms
and/or theorems that you use.
-/
example : true := true.intro
example : false := _ -- trick question? why?
example : ∀ (P : Prop), P ∨ P ↔ P :=
begin
assume P,
apply iff.intro _ _,
-- forward
assume porp,
apply or.elim porp,
-- left disjunct is true
assume p,
exact p,
-- right disjunct is true
assume p,
exact p,
-- backwards
assume p,
exact or.intro_left P p,
end
example : ∀ (P : Prop), P ∧ P ↔ P :=
begin
end
example : ∀ (P Q : Prop), P ∨ Q ↔ Q ∨ P :=
begin
end
example : ∀ (P Q : Prop), P ∧ Q ↔ Q ∧ P :=
begin
end
example : ∀ (P Q R : Prop), P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) :=
begin
end
example : ∀ (P Q R : Prop), P ∨ (Q ∧ R) ↔ (P ∨ Q) ∧ (P ∨ R) :=
begin
end
example : ∀ (P Q : Prop), P ∧ (P ∨ Q) ↔ P :=
begin
end
example : ∀ (P Q : Prop), P ∨ (P ∧ Q) ↔ P :=
begin
end
example : ∀ (P : Prop), P ∨ true ↔ true :=
begin
end
example : ∀ (P : Prop), P ∨ false ↔ P :=
begin
end
example : ∀ (P : Prop), P ∧ true ↔ P :=
begin
end
example : ∀ (P : Prop), P ∧ false ↔ false :=
begin
end
|
6502e3cb851dac6f074e601177f85b1f4e6e77eb | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/linear_algebra/finsupp.lean | cdb53e5b3bffad21354d4e9941cb0944487eaf0d | [
"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 | 25,611 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
-/
import data.finsupp.basic
import linear_algebra.basic
/-!
# Properties of the semimodule `α →₀ M`
Given an `R`-semimodule `M`, the `R`-semimodule structure on `α →₀ M` is defined in
`data.finsupp.basic`.
In this file we define `finsupp.supported s` to be the set `{f : α →₀ M | f.support ⊆ s}`
interpreted as a submodule of `α →₀ M`. We also define `linear_map` versions of various maps:
* `finsupp.lsingle a : M →ₗ[R] ι →₀ M`: `finsupp.single a` as a linear map;
* `finsupp.lapply a : (ι →₀ M) →ₗ[R] M`: the map `λ f, f a` as a linear map;
* `finsupp.lsubtype_domain (s : set α) : (α →₀ M) →ₗ[R] (s →₀ M)`: restriction to a subtype as a
linear map;
* `finsupp.restrict_dom`: `finsupp.filter` as a linear map to `finsupp.supported s`;
* `finsupp.lsum`: `finsupp.sum` or `finsupp.lift_add_hom` as a `linear_map`;
* `finsupp.total α M R (v : ι → M)`: sends `l : ι → R` to the linear combination of `v i` with
coefficients `l i`;
* `finsupp.total_on`: a restricted version of `finsupp.total` with domain `finsupp.supported R R s`
and codomain `submodule.span R (v '' s)`;
* `finsupp.supported_equiv_finsupp`: a linear equivalence between the functions `α →₀ M` supported
on `s` and the functions `s →₀ M`;
* `finsupp.lmap_domain`: a linear map version of `finsupp.map_domain`;
* `finsupp.dom_lcongr`: a `linear_equiv` version of `finsupp.dom_congr`;
* `finsupp.congr`: if the sets `s` and `t` are equivalent, then `supported M R s` is equivalent to
`supported M R t`;
* `finsupp.lcongr`: a `linear_equiv`alence between `α →₀ M` and `β →₀ N` constructed using `e : α ≃
β` and `e' : M ≃ₗ[R] N`.
## Tags
function with finite support, semimodule, linear algebra
-/
noncomputable theory
open set linear_map submodule
open_locale classical big_operators
namespace finsupp
variables {α : Type*} {M : Type*} {N : Type*} {R : Type*} {S : Type*}
variables [semiring R] [semiring S] [add_comm_monoid M] [semimodule R M]
variables [add_comm_monoid N] [semimodule R N]
/-- Interpret `finsupp.single a` as a linear map. -/
def lsingle (a : α) : M →ₗ[R] (α →₀ M) :=
{ map_smul' := assume a b, (smul_single _ _ _).symm, ..finsupp.single_add_hom a }
/-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. -/
lemma lhom_ext ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a b, φ (single a b) = ψ (single a b)) :
φ = ψ :=
linear_map.to_add_monoid_hom_injective $ add_hom_ext h
/-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere.
We formulate this fact using equality of linear maps `φ.comp (lsingle a)` and `ψ.comp (lsingle a)`
so that the `ext` tactic can apply a type-specific extensionality lemma to prove equality of these
maps. E.g., if `M = R`, then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/
@[ext] lemma lhom_ext' ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a, φ.comp (lsingle a) = ψ.comp (lsingle a)) :
φ = ψ :=
lhom_ext $ λ a, linear_map.congr_fun (h a)
/-- Interpret `λ (f : α →₀ M), f a` as a linear map. -/
def lapply (a : α) : (α →₀ M) →ₗ[R] M :=
{ map_smul' := assume a b, rfl, ..finsupp.apply_add_hom a }
section lsubtype_domain
variables (s : set α)
/-- Interpret `finsupp.subtype_domain s` as a linear map. -/
def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) :=
⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩
lemma lsubtype_domain_apply (f : α →₀ M) :
(lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl
end lsubtype_domain
@[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b :=
rfl
@[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a :=
rfl
@[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).ker = ⊥ :=
ker_eq_bot_of_injective (single_injective a)
lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) :
(⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) ≤ (⨅a∈t, ker (lapply a)) :=
begin
refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _),
simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi],
assume b hb a₂ h₂,
have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩,
exact single_eq_of_ne this
end
lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ M) →ₗ[R] M)) ≤ ⊥ :=
begin
simp only [le_def', mem_infi, mem_ker, mem_bot, lapply_apply],
exact assume a h, finsupp.ext h
end
lemma supr_lsingle_range : (⨆a, (lsingle a : M →ₗ[R] (α →₀ M)).range) = ⊤ :=
begin
refine (eq_top_iff.2 $ le_def'.2 $ assume f _, _),
rw [← sum_single f],
refine sum_mem _ (assume a ha, submodule.mem_supr_of_mem a $ set.mem_image_of_mem _ trivial)
end
lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) :
disjoint (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) (⨆a∈t, (lsingle a).range) :=
begin
refine disjoint.mono
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right)
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right)
(le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot),
classical,
by_cases his : i ∈ s,
{ by_cases hit : i ∈ t,
{ exact (hs ⟨his, hit⟩).elim },
exact inf_le_right_of_le (infi_le_of_le i $ infi_le _ hit) },
exact inf_le_left_of_le (infi_le_of_le i $ infi_le _ his)
end
lemma span_single_image (s : set M) (a : α) :
submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a) :=
by rw ← span_image; refl
variables (M R)
/-- `finsupp.supported M R s` is the `R`-submodule of all `p : α →₀ M` such that `p.support ⊆ s`. -/
def supported (s : set α) : submodule R (α →₀ M) :=
begin
refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩,
{ simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply],
assume h ha, exact (ha rfl).elim },
{ assume p q hp hq,
refine subset.trans
(subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq),
rw [finset.coe_union] },
{ assume a p hp,
refine subset.trans (finset.coe_subset.2 support_smul) hp }
end
variables {M}
lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s :=
iff.rfl
lemma mem_supported' {s : set α} (p : α →₀ M) :
p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 :=
by haveI := classical.dec_pred (λ (x : α), x ∈ s);
simp [mem_supported, set.subset_def, not_imp_comm]
lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) :
single a b ∈ supported M R s :=
set.subset.trans support_single_subset (finset.singleton_subset_set_iff.2 h)
lemma supported_eq_span_single (s : set α) :
supported R R s = span R ((λ i, single i 1) '' s) :=
begin
refine (span_eq_of_le _ _ (le_def'.2 $ λ l hl, _)).symm,
{ rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp },
{ rw ← l.sum_single,
refine sum_mem _ (λ i il, _),
convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _,
{ simp },
apply subset_span,
apply set.mem_image_of_mem _ (hl il) }
end
variables (M R)
/-- Interpret `finsupp.filter s` as a linear map from `α →₀ M` to `supported M R s`. -/
def restrict_dom (s : set α) : (α →₀ M) →ₗ supported M R s :=
linear_map.cod_restrict _
{ to_fun := filter (∈ s),
map_add' := λ l₁ l₂, filter_add,
map_smul' := λ a l, filter_smul }
(λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l)
variables {M R}
section
@[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) :
((restrict_dom M R s : (α →₀ M) →ₗ supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl
end
theorem restrict_dom_comp_subtype (s : set α) :
(restrict_dom M R s).comp (submodule.subtype _) = linear_map.id :=
begin
ext l a,
by_cases a ∈ s; simp [h],
exact ((mem_supported' R l.1).1 l.2 a h).symm
end
theorem range_restrict_dom (s : set α) :
(restrict_dom M R s).range = ⊤ :=
begin
have := linear_map.range_comp (submodule.subtype _) (restrict_dom M R s),
rw [restrict_dom_comp_subtype, linear_map.range_id] at this,
exact eq_top_mono (submodule.map_mono le_top) this.symm
end
theorem supported_mono {s t : set α} (st : s ⊆ t) :
supported M R s ≤ supported M R t :=
λ l h, set.subset.trans h st
@[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ :=
eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $
by ext; simp [*, mem_supported'] at *
@[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ :=
eq_top_iff.2 $ λ l _, set.subset_univ _
theorem supported_Union {δ : Type*} (s : δ → set α) :
supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) :=
begin
refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _),
haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)),
suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤
⨆ i, supported M R (s i),
{ rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this },
rw [range_le_iff_comap, eq_top_iff],
rintro l ⟨⟩,
apply finsupp.induction l, {exact zero_mem _},
refine λ x a l hl a0, add_mem _ _,
by_cases (∃ i, x ∈ s i); simp [h],
{ cases h with i hi,
exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) }
end
theorem supported_union (s t : set α) :
supported M R (s ∪ t) = supported M R s ⊔ supported M R t :=
by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl
theorem supported_Inter {ι : Type*} (s : ι → set α) :
supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) :=
submodule.ext $ λ x, by simp [mem_supported, subset_Inter_iff]
theorem supported_inter (s t : set α) :
supported M R (s ∩ t) = supported M R s ⊓ supported M R t :=
by rw [set.inter_eq_Inter, supported_Inter, infi_bool_eq]; refl
theorem disjoint_supported_supported {s t : set α} (h : disjoint s t) :
disjoint (supported M R s) (supported M R t) :=
disjoint_iff.2 $ by rw [← supported_inter, disjoint_iff_inter_eq_empty.1 h, supported_empty]
theorem disjoint_supported_supported_iff [nontrivial M] {s t : set α} :
disjoint (supported M R s) (supported M R t) ↔ disjoint s t :=
begin
refine ⟨λ h x hx, _, disjoint_supported_supported⟩,
rcases exists_ne (0 : M) with ⟨y, hy⟩,
have := h ⟨single_mem_supported R y hx.1, single_mem_supported R y hx.2⟩,
rw [mem_bot, single_eq_zero] at this,
exact hy this
end
/-- Interpret `finsupp.restrict_support_equiv` as a linear equivalence between
`supported M R s` and `s →₀ M`. -/
def supported_equiv_finsupp (s : set α) : (supported M R s) ≃ₗ[R] (s →₀ M) :=
begin
let F : (supported M R s) ≃ (s →₀ M) := restrict_support_equiv s M,
refine F.to_linear_equiv _,
have : (F : (supported M R s) → (↥s →₀ M)) = ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp
(submodule.subtype (supported M R s))) := rfl,
rw this,
exact linear_map.is_linear _
end
section lsum
variables (S) [semimodule S N] [smul_comm_class R S N]
/-- Lift a family of linear maps `M →ₗ[R] N` indexed by `x : α` to a linear map from `α →₀ M` to
`N` using `finsupp.sum`. This is an upgraded version of `finsupp.lift_add_hom`.
See note [bundled maps over different rings] for why separate `R` and `S` semirings are used.
-/
def lsum : (α → M →ₗ[R] N) ≃ₗ[S] ((α →₀ M) →ₗ[R] N) :=
{ to_fun := λ F, {
to_fun := λ d, d.sum (λ i, F i),
map_add' := (lift_add_hom (λ x, (F x).to_add_monoid_hom)).map_add,
map_smul' := λ c f, by simp [sum_smul_index', smul_sum] },
inv_fun := λ F x, F.comp (lsingle x),
left_inv := λ F, by { ext x y, simp },
right_inv := λ F, by { ext x y, simp },
map_add' := λ F G, by { ext x y, simp },
map_smul' := λ F G, by { ext x y, simp } }
@[simp] lemma coe_lsum (f : α → M →ₗ[R] N) : (lsum S f : (α →₀ M) → N) = λ d, d.sum (λ i, f i) :=
rfl
theorem lsum_apply (f : α → M →ₗ[R] N) (l : α →₀ M) :
finsupp.lsum S f l = l.sum (λ b, f b) := rfl
theorem lsum_single (f : α → M →ₗ[R] N) (i : α) (m : M) :
finsupp.lsum S f (finsupp.single i m) = f i m :=
finsupp.sum_single_index (f i).map_zero
theorem lsum_symm_apply (f : (α →₀ M) →ₗ[R] N) (x : α) :
(lsum S).symm f x = f.comp (lsingle x) := rfl
end lsum
section
variables (M) (R) (X : Type*)
/--
A slight rearrangement from `lsum` gives us
the bijection underlying the free-forgetful adjunction for R-modules.
-/
noncomputable def lift : (X → M) ≃+ ((X →₀ R) →ₗ[R] M) :=
(add_equiv.arrow_congr (equiv.refl X) (ring_lmap_equiv_self R M ℕ).to_add_equiv.symm).trans
(lsum _ : _ ≃ₗ[ℕ] _).to_add_equiv
@[simp]
lemma lift_symm_apply (f) (x) : ((lift M R X).symm f) x = f (single x 1) :=
rfl
@[simp]
lemma lift_apply (f) (g) :
((lift M R X) f) g = g.sum (λ x r, r • f x) :=
rfl
end
section lmap_domain
variables {α' : Type*} {α'' : Type*} (M R)
/-- Interpret `finsupp.map_domain` as a linear map. -/
def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) :=
⟨map_domain f, assume a b, map_domain_add, map_domain_smul⟩
@[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) :
(lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl
@[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id :=
linear_map.ext $ λ l, map_domain_id
theorem lmap_domain_comp (f : α → α') (g : α' → α'') :
lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) :=
linear_map.ext $ λ l, map_domain_comp
theorem supported_comap_lmap_domain (f : α → α') (s : set α') :
supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) :=
λ l (hl : ↑l.support ⊆ f ⁻¹' s),
show ↑(map_domain f l).support ⊆ s, begin
rw [← set.image_subset_iff, ← finset.coe_image] at hl,
exact set.subset.trans map_domain_support hl
end
theorem lmap_domain_supported [nonempty α] (f : α → α') (s : set α) :
(supported M R s).map (lmap_domain M R f) = supported M R (f '' s) :=
begin
inhabit α,
refine le_antisymm (map_le_iff_le_comap.2 $
le_trans (supported_mono $ set.subset_preimage_image _ _)
(supported_comap_lmap_domain _ _ _ _)) _,
intros l hl,
refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ α →₀ M) l, λ x hx, _, _⟩,
{ rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩,
exact function.inv_fun_on_mem (by simpa using hl hc) },
{ rw [← linear_map.comp_apply, ← lmap_domain_comp],
refine (map_domain_congr $ λ c hc, _).trans map_domain_id,
exact function.inv_fun_on_eq (by simpa using hl hc) }
end
theorem lmap_domain_disjoint_ker (f : α → α') {s : set α}
(H : ∀ a b ∈ s, f a = f b → a = b) :
disjoint (supported M R s) (lmap_domain M R f).ker :=
begin
rintro l ⟨h₁, h₂⟩,
rw [mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂,
simp, ext x,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases xs : x ∈ s,
{ have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl},
rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this,
{ simpa [finsupp.single_apply] },
{ intros y hy xy, simp [mt (H _ _ (h₁ hy) xs) xy] },
{ simp {contextual := tt} } },
{ by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) }
end
end lmap_domain
section total
variables (α) {α' : Type*} (M) {M' : Type*} (R)
[add_comm_monoid M'] [semimodule R M']
(v : α → M) {v' : α' → M'}
/-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and
evaluates this linear combination. -/
protected def total : (α →₀ R) →ₗ[R] M := finsupp.lsum ℕ (λ i, linear_map.id.smul_right (v i))
variables {α M v}
theorem total_apply (l : α →₀ R) :
finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl
theorem total_apply_of_mem_supported {l : α →₀ R} {s : finset α}
(hs : l ∈ supported R R (↑s : set α)) :
finsupp.total α M R v l = s.sum (λ i, l i • v i) :=
finset.sum_subset hs $ λ x _ hxg, show l x • v x = 0, by rw [not_mem_support_iff.1 hxg, zero_smul]
@[simp] theorem total_single (c : R) (a : α) :
finsupp.total α M R v (single a c) = c • (v a) :=
by simp [total_apply, sum_single_index]
theorem total_unique [unique α] (l : α →₀ R) (v) :
finsupp.total α M R v l = l (default α) • v (default α) :=
by rw [← total_single, ← unique_single l]
theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ :=
begin
apply range_eq_top.2,
intros x,
apply exists.elim (h x),
exact λ i hi, ⟨single i 1, by simp [hi]⟩
end
lemma range_total : (finsupp.total α M R v).range = span R (range v) :=
begin
ext x,
split,
{ intros hx,
rw [linear_map.mem_range] at hx,
rcases hx with ⟨l, hl⟩,
rw ← hl,
rw finsupp.total_apply,
unfold finsupp.sum,
apply sum_mem (span R (range v)),
exact λ i hi, submodule.smul_mem _ _ (subset_span (mem_range_self i)) },
{ apply span_le.2,
intros x hx,
rcases hx with ⟨i, hi⟩,
rw [mem_coe, linear_map.mem_range],
use finsupp.single i 1,
simp [hi] }
end
theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) :
(finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) :=
by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h]
theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) :
(finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply]
theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ R) :
(finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
begin
have : map_domain f l = emb_domain ⟨f, hf⟩ l,
{ rw emb_domain_eq_map_domain ⟨f, hf⟩,
refl },
rw this,
apply total_emb_domain R ⟨f, hf⟩ l
end
theorem span_eq_map_total (s : set α):
span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) :=
begin
apply span_eq_of_le,
{ intros x hx,
rw set.mem_image at hx,
apply exists.elim hx,
intros i hi,
exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ },
{ refine map_le_iff_le_comap.2 (λ z hz, _),
have : ∀i, z i • v i ∈ span R (v '' s),
{ intro c,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases c ∈ s,
{ exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) },
{ simp [(finsupp.mem_supported' R _).1 hz _ h] } },
refine sum_mem _ _, simp [this] }
end
theorem mem_span_iff_total {s : set α} {x : M} :
x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x :=
by rw span_eq_map_total; simp
variables (α) (M) (v)
/-- `finsupp.total_on M v s` interprets `p : α →₀ R` as a linear combination of a
subset of the vectors in `v`, mapping it to the span of those vectors.
The subset is indicated by a set `s : set α` of indices.
-/
protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) :=
linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $
λ ⟨l, hl⟩, (mem_span_iff_total _).2 ⟨l, hl, rfl⟩
variables {α} {M} {v}
theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ :=
by rw [finsupp.total_on, linear_map.range, linear_map.map_cod_restrict,
← linear_map.range_le_iff_comap, range_subtype, map_top, linear_map.range_comp, range_subtype];
exact le_of_eq (span_eq_map_total _ _)
theorem total_comp (f : α' → α) :
(finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) :=
begin
ext l,
simp [total_apply],
rw sum_map_domain_index; simp [add_smul],
end
lemma total_comap_domain
(f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' ↑l.support)) :
finsupp.total α M R v (finsupp.comap_domain f l hf) =
(l.support.preimage f hf).sum (λ i, (l (f i)) • (v i)) :=
by rw finsupp.total_apply; refl
lemma total_on_finset
{s : finset α} {f : α → R} (g : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s):
finsupp.total α M R g (finsupp.on_finset s f hf) =
finset.sum s (λ (x : α), f x • g x) :=
begin
simp only [finsupp.total_apply, finsupp.sum, finsupp.on_finset_apply, finsupp.support_on_finset],
rw finset.sum_filter_of_ne,
intros x hx h,
contrapose! h,
simp [h],
end
end total
/-- An equivalence of domains induces a linear equivalence of finitely supported functions. -/
protected def dom_lcongr {α₁ α₂ : Type*} (e : α₁ ≃ α₂) :
(α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) :=
(finsupp.dom_congr e : (α₁ →₀ M) ≃+ (α₂ →₀ M)).to_linear_equiv (lmap_domain M R e).map_smul
@[simp] theorem dom_lcongr_single {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (i : α₁) (m : M) :
(finsupp.dom_lcongr e : _ ≃ₗ[R] _) (finsupp.single i m) = finsupp.single (e i) m :=
by simp [finsupp.dom_lcongr, finsupp.dom_congr, map_domain_single]
/-- An equivalence of sets induces a linear equivalence of `finsupp`s supported on those sets. -/
noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) :
supported M R s ≃ₗ[R] supported M R t :=
begin
haveI := classical.dec_pred (λ x, x ∈ s),
haveI := classical.dec_pred (λ x, x ∈ t),
refine linear_equiv.trans (finsupp.supported_equiv_finsupp s)
(linear_equiv.trans _ (finsupp.supported_equiv_finsupp t).symm),
exact finsupp.dom_lcongr e
end
/-- An equivalence of domain and a linear equivalence of codomain induce a linear equivalence of the
corresponding finitely supported functions. -/
def lcongr {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (ι →₀ M) ≃ₗ[R] (κ →₀ N) :=
(finsupp.dom_lcongr e₁).trans
{ to_fun := map_range e₂ e₂.map_zero,
inv_fun := map_range e₂.symm e₂.symm.map_zero,
left_inv := λ f, finsupp.induction f (by simp_rw map_range_zero) $ λ a b f ha hb ih,
by rw [map_range_add e₂.map_add, map_range_add e₂.symm.map_add,
map_range_single, map_range_single, e₂.symm_apply_apply, ih],
right_inv := λ f, finsupp.induction f (by simp_rw map_range_zero) $ λ a b f ha hb ih,
by rw [map_range_add e₂.symm.map_add, map_range_add e₂.map_add,
map_range_single, map_range_single, e₂.apply_symm_apply, ih],
map_add' := map_range_add e₂.map_add,
map_smul' := λ c f, finsupp.induction f
(by rw [smul_zero, map_range_zero, smul_zero]) $ λ a b f ha hb ih,
by rw [smul_add, smul_single, map_range_add e₂.map_add, map_range_single, e₂.map_smul, ih,
map_range_add e₂.map_add, smul_add, map_range_single, smul_single] }
@[simp] theorem lcongr_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N)
(i : ι) (m : M) : lcongr e₁ e₂ (finsupp.single i m) = finsupp.single (e₁ i) (e₂ m) :=
by simp [lcongr]
end finsupp
variables {R : Type*} {M : Type*} {N : Type*}
variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N]
lemma linear_map.map_finsupp_total
(f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) :
f (finsupp.total ι M R g l) = finsupp.total ι N R (f ∘ g) l :=
by simp only [finsupp.total_apply, finsupp.total_apply, finsupp.sum, f.map_sum, f.map_smul]
lemma submodule.exists_finset_of_mem_supr
{ι : Sort*} (p : ι → submodule R M) {m : M} (hm : m ∈ ⨆ i, p i) :
∃ s : finset ι, m ∈ ⨆ i ∈ s, p i :=
begin
obtain ⟨f, hf, rfl⟩ : ∃ f ∈ finsupp.supported R R (⋃ i, ↑(p i)), finsupp.total M M R id f = m,
{ have aux : (id : M → M) '' (⋃ (i : ι), ↑(p i)) = (⋃ (i : ι), ↑(p i)) := set.image_id _,
rwa [supr_eq_span, ← aux, finsupp.mem_span_iff_total R] at hm },
let t : finset M := f.support,
have ht : ∀ x : {x // x ∈ t}, ∃ i, ↑x ∈ p i,
{ intros x,
rw finsupp.mem_supported at hf,
specialize hf x.2,
rwa set.mem_Union at hf },
choose g hg using ht,
let s : finset ι := finset.univ.image g,
use s,
simp only [mem_supr, supr_le_iff],
assume N hN,
rw [finsupp.total_apply, finsupp.sum, ← submodule.mem_coe],
apply N.sum_mem,
assume x hx,
apply submodule.smul_mem,
let i : ι := g ⟨x, hx⟩,
have hi : i ∈ s, { rw finset.mem_image, exact ⟨⟨x, hx⟩, finset.mem_univ _, rfl⟩ },
exact hN i hi (hg _),
end
lemma mem_span_finset {s : finset M} {x : M} :
x ∈ span R (↑s : set M) ↔ ∃ f : M → R, ∑ i in s, f i • i = x :=
⟨λ hx, let ⟨v, hvs, hvx⟩ := (finsupp.mem_span_iff_total _).1
(show x ∈ span R (id '' (↑s : set M)), by rwa set.image_id) in
⟨v, hvx ▸ (finsupp.total_apply_of_mem_supported _ hvs).symm⟩,
λ ⟨f, hf⟩, hf ▸ sum_mem _ (λ i hi, smul_mem _ _ $ subset_span hi)⟩
|
fdfc3e6f5e5ecc08329535e7272ed20a8645c96a | 75bd9c50a345718d735a7533c007cf45f9da9a83 | /src/ring_theory/polynomial/basic.lean | df2aa3d49b801cf9bfa62a31433803afc33955d1 | [
"Apache-2.0"
] | permissive | jtbarker/mathlib | a1a3b1ddc16179826260578410746756ef18032c | 392d3e376b44265ef2dedbd92231d3177acc1fd0 | refs/heads/master | 1,671,246,411,096 | 1,600,801,712,000 | 1,600,801,712,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 23,567 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
Ring-theoretic supplement of data.polynomial.
Main result: Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring.
-/
import algebra.char_p
import data.mv_polynomial.comm_ring
import data.mv_polynomial.equiv
import data.polynomial.field_division
import ring_theory.principal_ideal_domain
noncomputable theory
local attribute [instance, priority 100] classical.prop_decidable
universes u v w
namespace polynomial
instance {R : Type u} [semiring R] (p : ℕ) [h : char_p R p] : char_p (polynomial R) p :=
let ⟨h⟩ := h in ⟨λ n, by rw [← C.map_nat_cast, ← C_0, C_inj, h]⟩
variables (R : Type u) [comm_ring R]
/-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/
def degree_le (n : with_bot ℕ) : submodule R (polynomial R) :=
⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker
/-- The `R`-submodule of `R[X]` consisting of polynomials of degree < `n`. -/
def degree_lt (n : ℕ) : submodule R (polynomial R) :=
⨅ k : ℕ, ⨅ h : k ≥ n, (lcoeff R k).ker
variable {R}
theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} :
f ∈ degree_le R n ↔ degree f ≤ n :=
by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl
@[mono] theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n) :
degree_le R m ≤ degree_le R n :=
λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H)
theorem degree_le_eq_span_X_pow {n : ℕ} :
degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, X^n) : finset (polynomial R)) :=
begin
apply le_antisymm,
{ intros p hp, replace hp := mem_degree_le.1 hp,
rw [← finsupp.sum_single p, finsupp.sum],
refine submodule.sum_mem _ (λ k hk, _),
show monomial _ _ ∈ _,
have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk),
rw [single_eq_C_mul_X, C_mul'],
refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $
finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) },
rw [submodule.span_le, finset.coe_image, set.image_subset_iff],
intros k hk, apply mem_degree_le.2,
apply le_trans (degree_X_pow_le _) (with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk)
end
theorem mem_degree_lt {n : ℕ} {f : polynomial R} :
f ∈ degree_lt R n ↔ degree f < n :=
by { simp_rw [degree_lt, submodule.mem_infi, linear_map.mem_ker, degree,
finset.sup_lt_iff (with_bot.bot_lt_coe n), finsupp.mem_support_iff, with_bot.some_eq_coe,
with_bot.coe_lt_coe, lt_iff_not_ge', ne, not_imp_not], refl }
@[mono] theorem degree_lt_mono {m n : ℕ} (H : m ≤ n) :
degree_lt R m ≤ degree_lt R n :=
λ f hf, mem_degree_lt.2 (lt_of_lt_of_le (mem_degree_lt.1 hf) $ with_bot.coe_le_coe.2 H)
theorem degree_lt_eq_span_X_pow {n : ℕ} :
degree_lt R n = submodule.span R ↑((finset.range n).image (λ n, X^n) : finset (polynomial R)) :=
begin
apply le_antisymm,
{ intros p hp, replace hp := mem_degree_lt.1 hp,
rw [← finsupp.sum_single p, finsupp.sum],
refine submodule.sum_mem _ (λ k hk, _),
show monomial _ _ ∈ _,
have := with_bot.coe_lt_coe.1 ((finset.sup_lt_iff $ with_bot.bot_lt_coe n).1 hp k hk),
rw [single_eq_C_mul_X, C_mul'],
refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $
finset.mem_image.2 ⟨_, finset.mem_range.2 this, rfl⟩) },
rw [submodule.span_le, finset.coe_image, set.image_subset_iff],
intros k hk, apply mem_degree_lt.2,
exact lt_of_le_of_lt (degree_X_pow_le _) (with_bot.coe_lt_coe.2 $ finset.mem_range.1 hk)
end
/-- Given a polynomial, return the polynomial whose coefficients are in
the ring closure of the original coefficients. -/
def restriction (p : polynomial R) : polynomial (ring.closure (↑p.frange : set R)) :=
⟨p.support, λ i, ⟨p.to_fun i,
if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem
else ring.subset_closure $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩,
λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩
@[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} : ↑(coeff (restriction p) n) = coeff p n := rfl
@[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} : (coeff (restriction p) n).1 = coeff p n := rfl
@[simp] theorem map_restriction (p : polynomial R) : p.restriction.map (algebra_map _ _) = p :=
ext $ λ n, by rw [coeff_map, algebra.is_subring_algebra_map_apply, coeff_restriction]
@[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree := rfl
@[simp] theorem nat_degree_restriction {p : polynomial R} : (restriction p).nat_degree = p.nat_degree := rfl
@[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p :=
⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩
@[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 := rfl
@[simp] theorem restriction_one : restriction (1 : polynomial R) = 1 :=
ext $ λ i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl
variables {S : Type v} [ring S] {f : R →+* S} {x : S}
theorem eval₂_restriction {p : polynomial R} :
eval₂ f x p = eval₂ (f.comp (is_subring.subtype _)) x p.restriction :=
by { dsimp only [eval₂_eq_sum], refl, }
section to_subring
variables (p : polynomial R) (T : set R) [is_subring T]
/-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`,
return the corresponding polynomial whose coefficients are in `T. -/
def to_subring (hp : ↑p.frange ⊆ T) : polynomial T :=
⟨p.support, λ i, ⟨p.to_fun i,
if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem
else hp $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩,
λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩
variables (hp : ↑p.frange ⊆ T)
include hp
@[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n := rfl
@[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n := rfl
@[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree := rfl
@[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree := rfl
@[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p :=
⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩
omit hp
@[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (set.empty_subset _) = 0 := rfl
@[simp] theorem to_subring_one : to_subring (1 : polynomial R) T
(set.subset.trans (finset.coe_subset.2 finsupp.frange_single)
(finset.singleton_subset_set_iff.2 is_submonoid.one_mem)) = 1 :=
ext $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl
@[simp] theorem map_to_subring : (p.to_subring T hp).map (is_subring.subtype T) = p :=
ext $ λ n, coeff_map _ _
end to_subring
variables (T : set R) [is_subring T]
/-- Given a polynomial whose coefficients are in some subring, return
the corresponding polynomial whose coefificents are in the ambient ring. -/
def of_subring (p : polynomial T) : polynomial R :=
⟨p.support, subtype.val ∘ p.to_fun,
λ n, finsupp.mem_support_iff.trans (not_iff_not_of_iff
⟨λ h, congr_arg subtype.val h, λ h, subtype.eq h⟩)⟩
@[simp] theorem frange_of_subring {p : polynomial T} :
↑(p.of_subring T).frange ⊆ T :=
λ y H, let ⟨hy, x, hx⟩ := finsupp.mem_frange.1 H in hx ▸ (p.to_fun x).2
end polynomial
variables {R : Type u} {σ : Type v} {M : Type w} [comm_ring R] [add_comm_group M] [module R M]
namespace ideal
open polynomial
/-- The push-forward of an ideal `I` of `R` to `polynomial R` via inclusion
is exactly the set of polynomials whose coefficients are in `I` -/
theorem mem_map_C_iff {I : ideal R} {f : polynomial R} :
f ∈ (ideal.map C I : ideal (polynomial R)) ↔ ∀ n : ℕ, f.coeff n ∈ I :=
begin
split,
{ intros hf,
apply submodule.span_induction hf,
{ intros f hf n,
cases (set.mem_image _ _ _).mp hf with x hx,
rw [← hx.right, coeff_C],
by_cases (n = 0),
{ simpa [h] using hx.left },
{ simp [h] } },
{ simp },
{ exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] },
{ refine λ f g hg n, _,
rw [smul_eq_mul, coeff_mul],
exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } },
{ intros hf,
rw ← sum_monomial_eq f,
refine (map C I : ideal (polynomial R)).sum_mem (λ n hn, _),
simp [single_eq_C_mul_X],
rw mul_comm,
exact (map C I : ideal (polynomial R)).smul_mem _ (mem_map_of_mem (hf n)) }
end
lemma quotient_map_C_eq_zero {I : ideal R} :
∀ a ∈ I, ((quotient.mk (map C I : ideal (polynomial R))).comp C) a = 0 :=
begin
intros a ha,
rw [ring_hom.comp_apply, quotient.eq_zero_iff_mem],
exact mem_map_of_mem ha,
end
lemma eval₂_C_mk_eq_zero {I : ideal R} :
∀ f ∈ (map C I : ideal (polynomial R)), eval₂_ring_hom (C.comp (quotient.mk I)) X f = 0 :=
begin
intros a ha,
rw ← sum_monomial_eq a,
dsimp,
rw eval₂_sum (C.comp (quotient.mk I)) a monomial X,
refine finset.sum_eq_zero (λ n hn, _),
dsimp,
rw eval₂_monomial (C.comp (quotient.mk I)) X,
refine mul_eq_zero_of_left (polynomial.ext (λ m, _)) (X ^ n),
erw coeff_C,
by_cases h : m = 0,
{ simpa [h] using quotient.eq_zero_iff_mem.2 ((mem_map_C_iff.1 ha) n) },
{ simp [h] }
end
/-- If `I` is an ideal of `R`, then the ring polynomials over the quotient ring `I.quotient` is
isomorphic to the quotient of `polynomial R` by the ideal `map C I`,
where `map C I` contains exactly the polynomials whose coefficients all lie in `I` -/
def polynomial_quotient_equiv_quotient_polynomial {I : ideal R} :
polynomial (I.quotient) ≃+* (map C I : ideal (polynomial R)).quotient :=
{ to_fun := eval₂_ring_hom
(quotient.lift I ((quotient.mk (map C I : ideal (polynomial R))).comp C) quotient_map_C_eq_zero)
((quotient.mk (map C I : ideal (polynomial R)) X)),
inv_fun := quotient.lift (map C I : ideal (polynomial R))
(eval₂_ring_hom (C.comp (quotient.mk I)) X) eval₂_C_mk_eq_zero,
map_mul' := λ f g, by simp,
map_add' := λ f g, by simp,
left_inv := begin
intro f,
apply polynomial.induction_on' f,
{ simp_intros p q hp hq,
rw [hp, hq] },
{ rintros n ⟨x⟩,
simp [monomial_eq_smul_X, C_mul'] }
end,
right_inv := begin
rintro ⟨f⟩,
apply polynomial.induction_on' f,
{ simp_intros p q hp hq,
rw [hp, hq] },
{ intros n a,
simp [monomial_eq_smul_X, ← C_mul' a (X ^ n)] },
end,
}
/-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/
def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) :=
{ carrier := I.carrier,
zero_mem' := I.zero_mem,
add_mem' := λ _ _, I.add_mem,
smul_mem' := λ c x H, by rw [← C_mul']; exact submodule.smul_mem _ _ H }
variables {I : ideal (polynomial R)}
theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl
variables (I)
/-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I`
consisting of polynomials of degree ≤ `n`. -/
def degree_le (n : with_bot ℕ) : submodule R (polynomial R) :=
degree_le R n ⊓ I.of_polynomial
/-- Given an ideal `I` of `R[X]`, make the ideal in `R` of
leading coefficients of polynomials in `I` with degree ≤ `n`. -/
def leading_coeff_nth (n : ℕ) : ideal R :=
(I.degree_le n).map $ lcoeff R n
theorem mem_leading_coeff_nth (n : ℕ) (x) :
x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x :=
begin
simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf, mem_degree_le],
split,
{ rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩,
cases lt_or_eq_of_le hpdeg with hpdeg hpdeg,
{ refine ⟨0, I.zero_mem, bot_le, _⟩,
rw [leading_coeff_zero, eq_comm],
exact coeff_eq_zero_of_degree_lt hpdeg },
{ refine ⟨p, hpI, le_of_eq hpdeg, _⟩,
rw [leading_coeff, nat_degree, hpdeg], refl } },
{ rintro ⟨p, hpI, hpdeg, rfl⟩,
have : nat_degree p + (n - nat_degree p) = n,
{ exact nat.add_sub_cancel' (nat_degree_le_of_degree_le hpdeg) },
refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right hpI⟩, _⟩,
{ apply le_trans (degree_mul_le _ _) _,
apply le_trans (add_le_add (degree_le_nat_degree) (degree_X_pow_le _)) _,
rw [← with_bot.coe_add, this],
exact le_refl _ },
{ rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } }
end
theorem mem_leading_coeff_nth_zero (x) :
x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I :=
(mem_leading_coeff_nth _ _ _).trans
⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff,
nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg),
← eq_C_of_degree_le_zero hpdeg],
λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩
theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) :
I.leading_coeff_nth m ≤ I.leading_coeff_nth n :=
begin
intros r hr,
simp only [submodule.mem_coe, mem_leading_coeff_nth] at hr ⊢,
rcases hr with ⟨p, hpI, hpdeg, rfl⟩,
refine ⟨p * X ^ (n - m), I.mul_mem_right hpI, _, leading_coeff_mul_X_pow⟩,
refine le_trans (degree_mul_le _ _) _,
refine le_trans (add_le_add hpdeg (degree_X_pow_le _)) _,
rw [← with_bot.coe_add, nat.add_sub_cancel' H],
exact le_refl _
end
/-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the
leading coefficients in `I`. -/
def leading_coeff : ideal R :=
⨆ n : ℕ, I.leading_coeff_nth n
theorem mem_leading_coeff (x) :
x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x :=
begin
rw [leading_coeff, submodule.mem_supr_of_directed],
simp only [mem_leading_coeff_nth],
{ split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ },
rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ },
intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _),
I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩
end
theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) :
submodule.fg (I.degree_le n) :=
is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _
⟨_, degree_le_eq_span_X_pow.symm⟩) _
end ideal
/-- Hilbert basis theorem: a polynomial ring over a noetherian ring is a noetherian ring. -/
protected theorem polynomial.is_noetherian_ring [is_noetherian_ring R] :
is_noetherian_ring (polynomial R) :=
⟨assume I : ideal (polynomial R),
let L := I.leading_coeff in
let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance))
(set.range I.leading_coeff_nth) ⟨_, ⟨0, rfl⟩⟩ in
have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _,
let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in
have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N)
(λ h, HN ▸ I.leading_coeff_nth_mono h)
(λ h x hx, classical.by_contradiction $ λ hxm,
have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min
(well_founded_submodule_gt _ _) _ _ _; exact ⟨k, rfl⟩,
this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩),
have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)),
from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _)
(λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ hf),
⟨s, le_antisymm (ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $ begin
change I ≤ ideal.span ↑s,
intros p hp, generalize hn : p.nat_degree = k,
induction k using nat.strong_induction_on with k ih generalizing p,
cases le_or_lt k N,
{ subst k, refine hs2 ⟨polynomial.mem_degree_le.2
(le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ },
{ have hp0 : p ≠ 0,
{ rintro rfl, cases hn, exact nat.not_lt_zero _ h },
have : (0 : R) ≠ 1,
{ intro h, apply hp0, ext i, refine (mul_one _).symm.trans _,
rw [← h, mul_zero], refl },
haveI : nontrivial R := ⟨⟨0, 1, this⟩⟩,
have : p.leading_coeff ∈ I.leading_coeff_nth N,
{ rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2
⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) },
rw I.mem_leading_coeff_nth at this,
rcases this with ⟨q, hq, hdq, hlqp⟩,
have hq0 : q ≠ 0,
{ intro H, rw [← polynomial.leading_coeff_eq_zero] at H,
rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H },
have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree,
{ rw [polynomial.degree_mul', polynomial.degree_X_pow],
rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0],
rw [← with_bot.coe_add, nat.add_sub_cancel', hn],
{ refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) },
rw [polynomial.leading_coeff_X_pow, mul_one],
exact mt polynomial.leading_coeff_eq_zero.1 hq0 },
have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff,
{ rw [← hlqp, polynomial.leading_coeff_mul_X_pow] },
have := polynomial.degree_sub_lt h1 hp0 h2,
rw [polynomial.degree_eq_nat_degree hp0] at this,
rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)),
refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _),
{ by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0,
{ rw hpq, exact ideal.zero_mem _ },
refine ih _ _ (I.sub_mem hp (I.mul_mem_right hq)) rfl,
rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this },
exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ }
end⟩⟩
attribute [instance] polynomial.is_noetherian_ring
namespace polynomial
theorem exists_irreducible_of_degree_pos {R : Type u} [integral_domain R] [is_noetherian_ring R]
{f : polynomial R} (hf : 0 < f.degree) : ∃ g, irreducible g ∧ g ∣ f :=
wf_dvd_monoid.exists_irreducible_factor
(λ huf, ne_of_gt hf $ degree_eq_zero_of_is_unit huf)
(λ hf0, not_lt_of_lt hf $ hf0.symm ▸ (@degree_zero R _).symm ▸ with_bot.bot_lt_coe _)
theorem exists_irreducible_of_nat_degree_pos {R : Type u} [integral_domain R] [is_noetherian_ring R]
{f : polynomial R} (hf : 0 < f.nat_degree) : ∃ g, irreducible g ∧ g ∣ f :=
exists_irreducible_of_degree_pos $ by { contrapose! hf, exact nat_degree_le_of_degree_le hf }
theorem exists_irreducible_of_nat_degree_ne_zero {R : Type u} [integral_domain R] [is_noetherian_ring R]
{f : polynomial R} (hf : f.nat_degree ≠ 0) : ∃ g, irreducible g ∧ g ∣ f :=
exists_irreducible_of_nat_degree_pos $ nat.pos_of_ne_zero hf
lemma linear_independent_powers_iff_eval₂
(f : M →ₗ[R] M) (v : M) :
linear_independent R (λ n : ℕ, (f ^ n) v)
↔ ∀ (p : polynomial R), polynomial.aeval f p v = 0 → p = 0 :=
begin
rw linear_independent_iff,
simp only [finsupp.total_apply, aeval_endomorphism],
refl
end
end polynomial
namespace mv_polynomial
lemma is_noetherian_ring_fin_0 [is_noetherian_ring R] :
is_noetherian_ring (mv_polynomial (fin 0) R) :=
is_noetherian_ring_of_ring_equiv R
((mv_polynomial.pempty_ring_equiv R).symm.trans
(mv_polynomial.ring_equiv_of_equiv _ fin_zero_equiv'.symm))
theorem is_noetherian_ring_fin [is_noetherian_ring R] :
∀ {n : ℕ}, is_noetherian_ring (mv_polynomial (fin n) R)
| 0 := is_noetherian_ring_fin_0
| (n+1) :=
@is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ _ _
(mv_polynomial.fin_succ_equiv _ n).symm
(@polynomial.is_noetherian_ring (mv_polynomial (fin n) R) _ (is_noetherian_ring_fin))
/-- The multivariate polynomial ring in finitely many variables over a noetherian ring
is itself a noetherian ring. -/
instance is_noetherian_ring [fintype σ] [is_noetherian_ring R] :
is_noetherian_ring (mv_polynomial σ R) :=
trunc.induction_on (fintype.equiv_fin σ) $ λ e,
@is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _
(mv_polynomial.ring_equiv_of_equiv _ e.symm) is_noetherian_ring_fin
lemma is_integral_domain_fin_zero (R : Type u) [comm_ring R] (hR : is_integral_domain R) :
is_integral_domain (mv_polynomial (fin 0) R) :=
ring_equiv.is_integral_domain R hR
((ring_equiv_of_equiv R fin_zero_equiv').trans (mv_polynomial.pempty_ring_equiv R))
/-- Auxilliary lemma:
Multivariate polynomials over an integral domain
with variables indexed by `fin n` form an integral domain.
This fact is proven inductively,
and then used to prove the general case without any finiteness hypotheses.
See `mv_polynomial.integral_domain` for the general case. -/
lemma is_integral_domain_fin (R : Type u) [comm_ring R] (hR : is_integral_domain R) :
∀ (n : ℕ), is_integral_domain (mv_polynomial (fin n) R)
| 0 := is_integral_domain_fin_zero R hR
| (n+1) :=
ring_equiv.is_integral_domain
(polynomial (mv_polynomial (fin n) R))
(is_integral_domain_fin n).polynomial
(mv_polynomial.fin_succ_equiv _ n)
lemma is_integral_domain_fintype (R : Type u) (σ : Type v) [comm_ring R] [fintype σ]
(hR : is_integral_domain R) : is_integral_domain (mv_polynomial σ R) :=
trunc.induction_on (fintype.equiv_fin σ) $ λ e,
@ring_equiv.is_integral_domain _ (mv_polynomial (fin $ fintype.card σ) R) _ _
(mv_polynomial.is_integral_domain_fin _ hR _)
(ring_equiv_of_equiv R e)
/-- Auxilliary definition:
Multivariate polynomials in finitely many variables over an integral domain form an integral domain.
This fact is proven by transport of structure from the `mv_polynomial.integral_domain_fin`,
and then used to prove the general case without finiteness hypotheses.
See `mv_polynomial.integral_domain` for the general case. -/
def integral_domain_fintype (R : Type u) (σ : Type v) [integral_domain R] [fintype σ] :
integral_domain (mv_polynomial σ R) :=
@is_integral_domain.to_integral_domain _ _ $ mv_polynomial.is_integral_domain_fintype R σ $
integral_domain.to_is_integral_domain R
protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {R : Type u} [integral_domain R] {σ : Type v}
(p q : mv_polynomial σ R) (h : p * q = 0) : p = 0 ∨ q = 0 :=
begin
obtain ⟨s, p, rfl⟩ := exists_finset_rename p,
obtain ⟨t, q, rfl⟩ := exists_finset_rename q,
have : rename (subtype.map id (finset.subset_union_left s t) : {x // x ∈ s} → {x // x ∈ s ∪ t}) p *
rename (subtype.map id (finset.subset_union_right s t) : {x // x ∈ t} → {x // x ∈ s ∪ t}) q = 0,
{ apply rename_injective _ subtype.val_injective, simpa using h },
letI := mv_polynomial.integral_domain_fintype R {x // x ∈ (s ∪ t)},
rw mul_eq_zero at this,
cases this; [left, right],
all_goals { simpa using congr_arg (rename subtype.val) this }
end
/-- The multivariate polynomial ring over an integral domain is an integral domain. -/
instance {R : Type u} {σ : Type v} [integral_domain R] :
integral_domain (mv_polynomial σ R) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := mv_polynomial.eq_zero_or_eq_zero_of_mul_eq_zero,
exists_pair_ne := ⟨0, 1, λ H,
begin
have : eval₂ (ring_hom.id _) (λ s, (0:R)) (0 : mv_polynomial σ R) =
eval₂ (ring_hom.id _) (λ s, (0:R)) (1 : mv_polynomial σ R),
{ congr, exact H },
simpa,
end⟩,
.. (by apply_instance : comm_ring (mv_polynomial σ R)) }
end mv_polynomial
|
9899c843a16b04b99835dfcb7ad069c6806c729a | 367134ba5a65885e863bdc4507601606690974c1 | /src/meta/rb_map.lean | f243c764744ffce68b547a4874b34dfa5b4ff416 | [
"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 | 7,704 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Robert Y. Lewis
-/
import data.option.defs
import data.list.defs
/-!
# rb_map
This file defines additional operations on native rb_maps and rb_sets.
These structures are defined in core in `init.meta.rb_map`. They are meta objects,
and are generally the most efficient dictionary structures to use for pure metaprogramming right now.
-/
namespace native
/-! ### Declarations about `rb_set` -/
namespace rb_set
meta instance {key} [has_lt key] [decidable_rel ((<) : key → key → Prop)] :
inhabited (rb_set key) :=
⟨mk_rb_set⟩
/-- `filter s P` returns the subset of elements of `s` satisfying `P`. -/
meta def filter {key} (s : rb_set key) (P : key → bool) : rb_set key :=
s.fold s (λ a m, if P a then m else m.erase a)
/-- `mfilter s P` returns the subset of elements of `s` satisfying `P`,
where the check `P` is monadic. -/
meta def mfilter {m} [monad m] {key} (s : rb_set key) (P : key → m bool) : m (rb_set key) :=
s.fold (pure s) (λ a m,
do x ← m,
mcond (P a) (pure x) (pure $ x.erase a))
/-- `union s t` returns an rb_set containing every element that appears in either `s` or `t`. -/
meta def union {key} (s t : rb_set key) : rb_set key :=
s.fold t (λ a t, t.insert a)
/--
`of_list_core empty l` turns a list of keys into an `rb_set`.
It takes a user_provided `rb_set` to use for the base case.
This can be used to pre-seed the set with additional elements,
and/or to use a custom comparison operator.
-/
meta def of_list_core {key} (base : rb_set key) : list key → rb_map key unit
| [] := base
| (x::xs) := rb_set.insert (of_list_core xs) x
/--
`of_list l` transforms a list `l : list key` into an `rb_set`,
inferring an order on the type `key`.
-/
meta def of_list {key} [has_lt key] [decidable_rel ((<) : key → key → Prop)] :
list key → rb_set key :=
of_list_core mk_rb_set
/--
`sdiff s1 s2` returns the set of elements that are in `s1` but not in `s2`.
It does so by folding over `s2`. If `s1` is significantly smaller than `s2`,
it may be worth it to reverse the fold.
-/
meta def sdiff {α} (s1 s2 : rb_set α) : rb_set α :=
s2.fold s1 $ λ v s, s.erase v
/--
`insert_list s l` inserts each element of `l` into `s`.
-/
meta def insert_list {key} (s : rb_set key) (l : list key) : rb_set key :=
l.foldl rb_set.insert s
end rb_set
/-! ### Declarations about `rb_map` -/
namespace rb_map
meta instance {key data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] :
inhabited (rb_map key data) :=
⟨mk_rb_map⟩
/-- `find_def default m k` returns the value corresponding to `k` in `m`, if it exists.
Otherwise it returns `default`. -/
meta def find_def {key value} (default : value) (m : rb_map key value) (k : key) :=
(m.find k).get_or_else default
/-- `ifind m key` returns the value corresponding to `key` in `m`, if it exists.
Otherwise it returns the default value of `value`. -/
meta def ifind {key value} [inhabited value] (m : rb_map key value) (k : key) : value :=
(m.find k).iget
/-- `zfind m key` returns the value corresponding to `key` in `m`, if it exists.
Otherwise it returns 0. -/
meta def zfind {key value} [has_zero value] (m : rb_map key value) (k : key) : value :=
(m.find k).get_or_else 0
/-- Returns the pointwise sum of `m1` and `m2`, treating nonexistent values as 0. -/
meta def add {key value} [has_add value] [has_zero value] [decidable_eq value]
(m1 m2 : rb_map key value) : rb_map key value :=
m1.fold m2
(λ n v m,
let nv := v + m2.zfind n in
if nv = 0 then m.erase n else m.insert n nv)
variables {m : Type → Type*} [monad m]
open function
/-- `mfilter P s` filters `s` by the monadic predicate `P` on keys and values. -/
meta def mfilter {key val} [has_lt key] [decidable_rel ((<) : key → key → Prop)]
(P : key → val → m bool) (s : rb_map key val) : m (rb_map.{0 0} key val) :=
rb_map.of_list <$> s.to_list.mfilter (uncurry P)
/-- `mmap f s` maps the monadic function `f` over values in `s`. -/
meta def mmap {key val val'} [has_lt key] [decidable_rel ((<) : key → key → Prop)]
(f : val → m val') (s : rb_map key val) : m (rb_map.{0 0} key val') :=
rb_map.of_list <$> s.to_list.mmap (λ ⟨a,b⟩, prod.mk a <$> f b)
/-- `scale b m` multiplies every value in `m` by `b`. -/
meta def scale {key value} [has_lt key] [decidable_rel ((<) : key → key → Prop)] [has_mul value]
(b : value) (m : rb_map key value) : rb_map key value :=
m.map ((*) b)
section
open format prod
variables {key : Type} {data : Type} [has_to_tactic_format key] [has_to_tactic_format data]
private meta def pp_key_data (k : key) (d : data) (first : bool) : tactic format :=
do fk ← tactic.pp k, fd ← tactic.pp d, return $
(if first then to_fmt "" else to_fmt "," ++ line) ++ fk ++ space ++ to_fmt "←" ++ space ++ fd
meta instance : has_to_tactic_format (rb_map key data) :=
⟨λ m, do
(fmt, _) ← fold m (return (to_fmt "", tt))
(λ k d p, do p ← p, pkd ← pp_key_data k d (snd p), return (fst p ++ pkd, ff)),
return $ group $ to_fmt "⟨" ++ nest 1 fmt ++ to_fmt "⟩"⟩
end
end rb_map
/-! ### Declarations about `rb_lmap` -/
namespace rb_lmap
meta instance (key : Type) [has_lt key] [decidable_rel ((<) : key → key → Prop)] (data : Type) :
inhabited (rb_lmap key data) :=
⟨rb_lmap.mk _ _⟩
/-- Construct a rb_lmap from a list of key-data pairs -/
protected meta def of_list {key : Type} {data : Type} [has_lt key]
[decidable_rel ((<) : key → key → Prop)] : list (key × data) → rb_lmap key data
| [] := rb_lmap.mk key data
| ((k, v)::ls) := (of_list ls).insert k v
/-- Returns the list of values of an `rb_lmap`. -/
protected meta def values {key data} (m : rb_lmap key data) : list data :=
m.fold [] (λ _, (++))
end rb_lmap
end native
/-! ### Declarations about `name_set` -/
namespace name_set
meta instance : inhabited name_set := ⟨mk_name_set⟩
/-- `filter P s` returns the subset of elements of `s` satisfying `P`. -/
meta def filter (P : name → bool) (s : name_set) : name_set :=
s.fold s (λ a m, if P a then m else m.erase a)
/-- `mfilter P s` returns the subset of elements of `s` satisfying `P`,
where the check `P` is monadic. -/
meta def mfilter {m} [monad m] (P : name → m bool) (s : name_set) : m name_set :=
s.fold (pure s) (λ a m,
do x ← m,
mcond (P a) (pure x) (pure $ x.erase a))
/-- `mmap f s` maps the monadic function `f` over values in `s`. -/
meta def mmap {m} [monad m] (f : name → m name) (s : name_set) : m name_set :=
s.fold (pure mk_name_set) (λ a m,
do x ← m,
b ← f a,
(pure $ x.insert b))
/-- `insert_list s l` inserts every element of `l` into `s`. -/
meta def insert_list (s : name_set) (l : list name) : name_set :=
l.foldr (λ n s', s'.insert n) s
/--
`local_list_to_name_set lcs` is the set of unique names of the local
constants `lcs`. If any of the `lcs` are not local constants, the returned set
will contain bogus names.
-/
meta def local_list_to_name_set (lcs : list expr) : name_set :=
lcs.foldl (λ ns h, ns.insert h.local_uniq_name) mk_name_set
end name_set
/-! ### Declarations about `name_map` -/
namespace name_map
meta instance {data : Type} : inhabited (name_map data) :=
⟨mk_name_map⟩
end name_map
/-! ### Declarations about `expr_set` -/
namespace expr_set
/--
`local_set_to_name_set lcs` is the set of unique names of the local constants
`lcs`. If any of the `lcs` are not local constants, the returned set will
contain bogus names.
-/
meta def local_set_to_name_set (lcs : expr_set) : name_set :=
lcs.fold mk_name_set $ λ h ns, ns.insert h.local_uniq_name
end expr_set
|
bab24d489a848c38208c2b4be7e023cf3cf08b05 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/matrix/notation.lean | f82cd6f7c1009750e77aa611246e5de35c9368ad | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 15,839 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen, Eric Wieser
-/
import data.matrix.basic
import data.fin.vec_notation
import tactic.fin_cases
import algebra.big_operators.fin
/-!
# Matrix and vector notation
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file includes `simp` lemmas for applying operations in `data.matrix.basic` to values built out
of the matrix notation `![a, b] = vec_cons a (vec_cons b vec_empty)` defined in
`data.fin.vec_notation`.
This also provides the new notation `!![a, b; c, d] = matrix.of ![![a, b], ![c, d]]`.
This notation also works for empty matrices; `!![,,,] : matrix (fin 0) (fin 3)` and
`!![;;;] : matrix (fin 3) (fin 0)`.
## Implementation notes
The `simp` lemmas require that one of the arguments is of the form `vec_cons _ _`.
This ensures `simp` works with entries only when (some) entries are already given.
In other words, this notation will only appear in the output of `simp` if it
already appears in the input.
## Notations
This file provide notation `!![a, b; c, d]` for matrices, which corresponds to
`matrix.of ![![a, b], ![c, d]]`.
A parser for `a, b; c, d`-style strings is provided as `matrix.entry_parser`, while
`matrix.notation` provides the hook for the `!!` notation.
Note that in lean 3 the pretty-printer will not show `!!` notation, instead showing the version
with `of ![![...]]`.
## Examples
Examples of usage can be found in the `test/matrix.lean` file.
-/
namespace matrix
universe u
variables {α : Type u} {o n m : ℕ} {m' n' o' : Type*}
open_locale matrix
/-- Matrices can be reflected whenever their entries can. We insert an `@id (matrix m' n' α)` to
prevent immediate decay to a function. -/
meta instance matrix.reflect [reflected_univ.{u}] [reflected_univ.{u_1}] [reflected_univ.{u_2}]
[reflected _ α] [reflected _ m'] [reflected _ n']
[h : has_reflect (m' → n' → α)] : has_reflect (matrix m' n' α) :=
λ m, (by reflect_name : reflected _ @id.{(max u_1 u_2 u) + 1}).subst₂
((by reflect_name : reflected _ @matrix.{u_1 u_2 u}).subst₃ `(_) `(_) `(_)) $
by { dunfold matrix, exact h m }
section parser
open lean
open lean.parser
open interactive
open interactive.types
/-- Parse the entries of a matrix -/
meta def entry_parser {α : Type} (p : parser α) :
parser (Σ m n, fin m → fin n → α) :=
do
-- a list of lists if the matrix has at least one row, or the number of columns if the matrix has
-- zero rows.
let p : parser (list (list α) ⊕ ℕ) :=
(sum.inl <$> (
(pure [] <* tk ";").repeat_at_least 1 <|> -- empty rows
(sep_by_trailing (tk ";") $ sep_by_trailing (tk ",") p)) <|>
(sum.inr <$> list.length <$> many (tk ","))), -- empty columns
which ← p,
match which with
| (sum.inl l) := do
h :: tl ← pure l,
let n := h.length,
l : list (vector α n) ← l.mmap (λ row,
if h : row.length = n then
pure (⟨row, h⟩ : vector α n)
else
interaction_monad.fail "Rows must be of equal length"),
pure ⟨l.length, n, λ i j, (l.nth_le _ i.prop).nth j⟩
| (sum.inr n) :=
pure ⟨0, n, fin_zero_elim⟩
end
-- Lean can't find this instance without some help. We only need it available in `Type 0`, and it is
-- a massive amount of effort to make it universe-polymorphic.
@[instance] meta def sigma_sigma_fin_matrix_has_reflect {α : Type}
[has_reflect α] [reflected _ α] :
has_reflect (Σ (m n : ℕ), fin m → fin n → α) :=
@sigma.reflect.{0 0} _ _ ℕ (λ m, Σ n, fin m → fin n → α) _ _ _ $ λ i,
@sigma.reflect.{0 0} _ _ ℕ _ _ _ _ (λ j, infer_instance)
/-- `!![a, b; c, d]` notation for matrices indexed by `fin m` and `fin n`. See the module docstring
for details. -/
@[user_notation]
meta def «notation» (_ : parse $ tk "!![")
(val : parse (entry_parser (parser.pexpr 1) <* tk "]")) : parser pexpr :=
do
let ⟨m, n, entries⟩ := val,
let entry_vals := pi_fin.to_pexpr (pi_fin.to_pexpr ∘ entries),
pure (``(@matrix.of (fin %%`(m)) (fin %%`(n)) _).app entry_vals)
end parser
variables (a b : ℕ)
/-- Use `![...]` notation for displaying a `fin`-indexed matrix, for example:
```
#eval !![1, 2; 3, 4] + !![3, 4; 5, 6] -- !![4, 6; 8, 10]
```
-/
instance [has_repr α] : has_repr (matrix (fin m) (fin n) α) :=
{ repr := λ f,
"!![" ++ (string.intercalate "; " $ (list.fin_range m).map $ λ i,
string.intercalate ", " $ (list.fin_range n).map (λ j, repr (f i j))) ++ "]" }
@[simp] lemma cons_val' (v : n' → α) (B : fin m → n' → α) (i j) :
vec_cons v B i j = vec_cons (v j) (λ i, B i j) i :=
by { refine fin.cases _ _ i; simp }
@[simp] lemma head_val' (B : fin m.succ → n' → α) (j : n') :
vec_head (λ i, B i j) = vec_head B j := rfl
@[simp] lemma tail_val' (B : fin m.succ → n' → α) (j : n') :
vec_tail (λ i, B i j) = λ i, vec_tail B i j :=
by { ext, simp [vec_tail] }
section dot_product
variables [add_comm_monoid α] [has_mul α]
@[simp] lemma dot_product_empty (v w : fin 0 → α) :
dot_product v w = 0 := finset.sum_empty
@[simp] lemma cons_dot_product (x : α) (v : fin n → α) (w : fin n.succ → α) :
dot_product (vec_cons x v) w = x * vec_head w + dot_product v (vec_tail w) :=
by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail]
@[simp] lemma dot_product_cons (v : fin n.succ → α) (x : α) (w : fin n → α) :
dot_product v (vec_cons x w) = vec_head v * x + dot_product (vec_tail v) w :=
by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail]
@[simp] lemma cons_dot_product_cons (x : α) (v : fin n → α) (y : α) (w : fin n → α) :
dot_product (vec_cons x v) (vec_cons y w) = x * y + dot_product v w :=
by simp
end dot_product
section col_row
@[simp] lemma col_empty (v : fin 0 → α) : col v = vec_empty :=
empty_eq _
@[simp] lemma col_cons (x : α) (u : fin m → α) :
col (vec_cons x u) = vec_cons (λ _, x) (col u) :=
by { ext i j, refine fin.cases _ _ i; simp [vec_head, vec_tail] }
@[simp] lemma row_empty : row (vec_empty : fin 0 → α) = λ _, vec_empty :=
by { ext, refl }
@[simp] lemma row_cons (x : α) (u : fin m → α) :
row (vec_cons x u) = λ _, vec_cons x u :=
by { ext, refl }
end col_row
section transpose
@[simp] lemma transpose_empty_rows (A : matrix m' (fin 0) α) : Aᵀ = of ![] := empty_eq _
@[simp] lemma transpose_empty_cols (A : matrix (fin 0) m' α) : Aᵀ = of (λ i, ![]) :=
funext (λ i, empty_eq _)
@[simp] lemma cons_transpose (v : n' → α) (A : matrix (fin m) n' α) :
(of (vec_cons v A))ᵀ = of (λ i, vec_cons (v i) (Aᵀ i)) :=
by { ext i j, refine fin.cases _ _ j; simp }
@[simp] lemma head_transpose (A : matrix m' (fin n.succ) α) :
vec_head (of.symm Aᵀ) = vec_head ∘ (of.symm A) :=
rfl
@[simp] lemma tail_transpose (A : matrix m' (fin n.succ) α) :
vec_tail (of.symm Aᵀ) = (vec_tail ∘ A)ᵀ :=
by { ext i j, refl }
end transpose
section mul
variables [semiring α]
@[simp] lemma empty_mul [fintype n'] (A : matrix (fin 0) n' α) (B : matrix n' o' α) :
A ⬝ B = of ![] :=
empty_eq _
@[simp] lemma empty_mul_empty (A : matrix m' (fin 0) α) (B : matrix (fin 0) o' α) :
A ⬝ B = 0 :=
rfl
@[simp] lemma mul_empty [fintype n'] (A : matrix m' n' α) (B : matrix n' (fin 0) α) :
A ⬝ B = of (λ _, ![]) :=
funext (λ _, empty_eq _)
lemma mul_val_succ [fintype n']
(A : matrix (fin m.succ) n' α) (B : matrix n' o' α) (i : fin m) (j : o') :
(A ⬝ B) i.succ j = (of (vec_tail (of.symm A)) ⬝ B) i j := rfl
@[simp] lemma cons_mul [fintype n'] (v : n' → α) (A : fin m → n' → α) (B : matrix n' o' α) :
of (vec_cons v A) ⬝ B = of (vec_cons (vec_mul v B) (of.symm (of A ⬝ B))) :=
by { ext i j, refine fin.cases _ _ i, { refl }, simp [mul_val_succ], }
end mul
section vec_mul
variables [semiring α]
@[simp] lemma empty_vec_mul (v : fin 0 → α) (B : matrix (fin 0) o' α) :
vec_mul v B = 0 :=
rfl
@[simp] lemma vec_mul_empty [fintype n'] (v : n' → α) (B : matrix n' (fin 0) α) :
vec_mul v B = ![] :=
empty_eq _
@[simp] lemma cons_vec_mul (x : α) (v : fin n → α) (B : fin n.succ → o' → α) :
vec_mul (vec_cons x v) (of B) = x • (vec_head B) + vec_mul v (of $ vec_tail B) :=
by { ext i, simp [vec_mul] }
@[simp] lemma vec_mul_cons (v : fin n.succ → α) (w : o' → α) (B : fin n → o' → α) :
vec_mul v (of $ vec_cons w B) = vec_head v • w + vec_mul (vec_tail v) (of B) :=
by { ext i, simp [vec_mul] }
@[simp] lemma cons_vec_mul_cons (x : α) (v : fin n → α) (w : o' → α) (B : fin n → o' → α) :
vec_mul (vec_cons x v) (of $ vec_cons w B) = x • w + vec_mul v (of B) :=
by simp
end vec_mul
section mul_vec
variables [semiring α]
@[simp] lemma empty_mul_vec [fintype n'] (A : matrix (fin 0) n' α) (v : n' → α) :
mul_vec A v = ![] :=
empty_eq _
@[simp] lemma mul_vec_empty (A : matrix m' (fin 0) α) (v : fin 0 → α) :
mul_vec A v = 0 :=
rfl
@[simp] lemma cons_mul_vec [fintype n'] (v : n' → α) (A : fin m → n' → α) (w : n' → α) :
mul_vec (of $ vec_cons v A) w = vec_cons (dot_product v w) (mul_vec (of A) w) :=
by { ext i, refine fin.cases _ _ i; simp [mul_vec] }
@[simp] lemma mul_vec_cons {α} [comm_semiring α] (A : m' → (fin n.succ) → α) (x : α)
(v : fin n → α) :
mul_vec (of A) (vec_cons x v) = (x • vec_head ∘ A) + mul_vec (of (vec_tail ∘ A)) v :=
by { ext i, simp [mul_vec, mul_comm] }
end mul_vec
section vec_mul_vec
variables [semiring α]
@[simp] lemma empty_vec_mul_vec (v : fin 0 → α) (w : n' → α) :
vec_mul_vec v w = ![] :=
empty_eq _
@[simp] lemma vec_mul_vec_empty (v : m' → α) (w : fin 0 → α) :
vec_mul_vec v w = λ _, ![] :=
funext (λ i, empty_eq _)
@[simp] lemma cons_vec_mul_vec (x : α) (v : fin m → α) (w : n' → α) :
vec_mul_vec (vec_cons x v) w = vec_cons (x • w) (vec_mul_vec v w) :=
by { ext i, refine fin.cases _ _ i; simp [vec_mul_vec] }
@[simp] lemma vec_mul_vec_cons (v : m' → α) (x : α) (w : fin n → α) :
vec_mul_vec v (vec_cons x w) = λ i, v i • vec_cons x w :=
by { ext i j, rw [vec_mul_vec_apply, pi.smul_apply, smul_eq_mul] }
end vec_mul_vec
section smul
variables [semiring α]
@[simp] lemma smul_mat_empty {m' : Type*} (x : α) (A : fin 0 → m' → α) : x • A = ![] := empty_eq _
@[simp] lemma smul_mat_cons (x : α) (v : n' → α) (A : fin m → n' → α) :
x • vec_cons v A = vec_cons (x • v) (x • A) :=
by { ext i, refine fin.cases _ _ i; simp }
end smul
section submatrix
@[simp] lemma submatrix_empty (A : matrix m' n' α) (row : fin 0 → m') (col : o' → n') :
submatrix A row col = ![] :=
empty_eq _
@[simp] lemma submatrix_cons_row (A : matrix m' n' α) (i : m') (row : fin m → m') (col : o' → n') :
submatrix A (vec_cons i row) col = vec_cons (λ j, A i (col j)) (submatrix A row col) :=
by { ext i j, refine fin.cases _ _ i; simp [submatrix] }
/-- Updating a row then removing it is the same as removing it. -/
@[simp] lemma submatrix_update_row_succ_above (A : matrix (fin m.succ) n' α)
(v : n' → α) (f : o' → n') (i : fin m.succ) :
(A.update_row i v).submatrix i.succ_above f = A.submatrix i.succ_above f :=
ext $ λ r s, (congr_fun (update_row_ne (fin.succ_above_ne i r) : _ = A _) (f s) : _)
/-- Updating a column then removing it is the same as removing it. -/
@[simp] lemma submatrix_update_column_succ_above (A : matrix m' (fin n.succ) α)
(v : m' → α) (f : o' → m') (i : fin n.succ) :
(A.update_column i v).submatrix f i.succ_above = A.submatrix f i.succ_above :=
ext $ λ r s, update_column_ne (fin.succ_above_ne i s)
end submatrix
section vec2_and_vec3
section one
variables [has_zero α] [has_one α]
lemma one_fin_two : (1 : matrix (fin 2) (fin 2) α) = !![1, 0; 0, 1] :=
by { ext i j, fin_cases i; fin_cases j; refl }
lemma one_fin_three : (1 : matrix (fin 3) (fin 3) α) = !![1, 0, 0; 0, 1, 0; 0, 0, 1] :=
by { ext i j, fin_cases i; fin_cases j; refl }
end one
lemma eta_fin_two (A : matrix (fin 2) (fin 2) α) : A = !![A 0 0, A 0 1; A 1 0, A 1 1] :=
by { ext i j, fin_cases i; fin_cases j; refl }
lemma eta_fin_three (A : matrix (fin 3) (fin 3) α) :
A = !![A 0 0, A 0 1, A 0 2;
A 1 0, A 1 1, A 1 2;
A 2 0, A 2 1, A 2 2] :=
by { ext i j, fin_cases i; fin_cases j; refl }
lemma mul_fin_two [add_comm_monoid α] [has_mul α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁₁ b₁₂ b₂₁ b₂₂ : α) :
!![a₁₁, a₁₂;
a₂₁, a₂₂] ⬝ !![b₁₁, b₁₂;
b₂₁, b₂₂] = !![a₁₁ * b₁₁ + a₁₂ * b₂₁, a₁₁ * b₁₂ + a₁₂ * b₂₂;
a₂₁ * b₁₁ + a₂₂ * b₂₁, a₂₁ * b₁₂ + a₂₂ * b₂₂] :=
begin
ext i j,
fin_cases i; fin_cases j; simp [matrix.mul, dot_product, fin.sum_univ_succ]
end
lemma mul_fin_three [add_comm_monoid α] [has_mul α]
(a₁₁ a₁₂ a₁₃ a₂₁ a₂₂ a₂₃ a₃₁ a₃₂ a₃₃ b₁₁ b₁₂ b₁₃ b₂₁ b₂₂ b₂₃ b₃₁ b₃₂ b₃₃ : α) :
!![a₁₁, a₁₂, a₁₃;
a₂₁, a₂₂, a₂₃;
a₃₁, a₃₂, a₃₃] ⬝ !![b₁₁, b₁₂, b₁₃;
b₂₁, b₂₂, b₂₃;
b₃₁, b₃₂, b₃₃] =
!![a₁₁*b₁₁ + a₁₂*b₂₁ + a₁₃*b₃₁, a₁₁*b₁₂ + a₁₂*b₂₂ + a₁₃*b₃₂, a₁₁*b₁₃ + a₁₂*b₂₃ + a₁₃*b₃₃;
a₂₁*b₁₁ + a₂₂*b₂₁ + a₂₃*b₃₁, a₂₁*b₁₂ + a₂₂*b₂₂ + a₂₃*b₃₂, a₂₁*b₁₃ + a₂₂*b₂₃ + a₂₃*b₃₃;
a₃₁*b₁₁ + a₃₂*b₂₁ + a₃₃*b₃₁, a₃₁*b₁₂ + a₃₂*b₂₂ + a₃₃*b₃₂, a₃₁*b₁₃ + a₃₂*b₂₃ + a₃₃*b₃₃] :=
begin
ext i j,
fin_cases i; fin_cases j; simp [matrix.mul, dot_product, fin.sum_univ_succ, ←add_assoc],
end
lemma vec2_eq {a₀ a₁ b₀ b₁ : α} (h₀ : a₀ = b₀) (h₁ : a₁ = b₁) :
![a₀, a₁] = ![b₀, b₁] :=
by subst_vars
lemma vec3_eq {a₀ a₁ a₂ b₀ b₁ b₂ : α} (h₀ : a₀ = b₀) (h₁ : a₁ = b₁) (h₂ : a₂ = b₂) :
![a₀, a₁, a₂] = ![b₀, b₁, b₂] :=
by subst_vars
lemma vec2_add [has_add α] (a₀ a₁ b₀ b₁ : α) :
![a₀, a₁] + ![b₀, b₁] = ![a₀ + b₀, a₁ + b₁] :=
by rw [cons_add_cons, cons_add_cons, empty_add_empty]
lemma vec3_add [has_add α] (a₀ a₁ a₂ b₀ b₁ b₂ : α) :
![a₀, a₁, a₂] + ![b₀, b₁, b₂] = ![a₀ + b₀, a₁ + b₁, a₂ + b₂] :=
by rw [cons_add_cons, cons_add_cons, cons_add_cons, empty_add_empty]
lemma smul_vec2 {R : Type*} [has_smul R α] (x : R) (a₀ a₁ : α) :
x • ![a₀, a₁] = ![x • a₀, x • a₁] :=
by rw [smul_cons, smul_cons, smul_empty]
lemma smul_vec3 {R : Type*} [has_smul R α] (x : R) (a₀ a₁ a₂ : α) :
x • ![a₀, a₁, a₂] = ![x • a₀, x • a₁, x • a₂] :=
by rw [smul_cons, smul_cons, smul_cons, smul_empty]
variables [add_comm_monoid α] [has_mul α]
lemma vec2_dot_product' {a₀ a₁ b₀ b₁ : α} :
![a₀, a₁] ⬝ᵥ ![b₀, b₁] = a₀ * b₀ + a₁ * b₁ :=
by rw [cons_dot_product_cons, cons_dot_product_cons, dot_product_empty, add_zero]
@[simp] lemma vec2_dot_product (v w : fin 2 → α) :
v ⬝ᵥ w = v 0 * w 0 + v 1 * w 1 :=
vec2_dot_product'
lemma vec3_dot_product' {a₀ a₁ a₂ b₀ b₁ b₂ : α} :
![a₀, a₁, a₂] ⬝ᵥ ![b₀, b₁, b₂] = a₀ * b₀ + a₁ * b₁ + a₂ * b₂ :=
by rw [cons_dot_product_cons, cons_dot_product_cons, cons_dot_product_cons,
dot_product_empty, add_zero, add_assoc]
@[simp] lemma vec3_dot_product (v w : fin 3 → α) :
v ⬝ᵥ w = v 0 * w 0 + v 1 * w 1 + v 2 * w 2 :=
vec3_dot_product'
end vec2_and_vec3
end matrix
|
cdc46d85266212e0dabb6f4d041d8ee6dd6fcb95 | e953c38599905267210b87fb5d82dcc3e52a4214 | /hott/types/sum.hlean | f35f21793682c1f19f1315d3c918243a39c14bfa | [
"Apache-2.0"
] | permissive | c-cube/lean | 563c1020bff98441c4f8ba60111fef6f6b46e31b | 0fb52a9a139f720be418dafac35104468e293b66 | refs/heads/master | 1,610,753,294,113 | 1,440,451,356,000 | 1,440,499,588,000 | 41,748,334 | 0 | 0 | null | 1,441,122,656,000 | 1,441,122,656,000 | null | UTF-8 | Lean | false | false | 6,139 | 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
Theorems about sums/coproducts/disjoint unions
-/
open lift eq is_equiv equiv equiv.ops prod prod.ops is_trunc sigma bool
namespace sum
universe variables u v
variables {A : Type.{u}} {B : Type.{v}} (z z' : A + B)
protected definition eta : sum.rec inl inr z = z :=
by induction z; all_goals reflexivity
protected definition code [unfold 3 4] : A + B → A + B → Type.{max u v}
| code (inl a) (inl a') := lift.{u v} (a = a')
| code (inr b) (inr b') := lift.{v u} (b = b')
| code _ _ := lift empty
protected definition decode [unfold 3 4] : Π(z z' : A + B), sum.code z z' → z = z'
| decode (inl a) (inl a') := λc, ap inl (down c)
| decode (inl a) (inr b') := λc, empty.elim (down c) _
| decode (inr b) (inl a') := λc, empty.elim (down c) _
| decode (inr b) (inr b') := λc, ap inr (down c)
variables {z z'}
protected definition encode [unfold 3 4 5] (p : z = z') : sum.code z z' :=
by induction p; induction z; all_goals exact up idp
variables (z z')
definition sum_eq_equiv : (z = z') ≃ sum.code z z' :=
equiv.MK sum.encode
!sum.decode
abstract begin
intro c, induction z with a b, all_goals induction z' with a' b',
all_goals (esimp at *; induction c with c),
all_goals induction c, -- c either has type empty or a path
all_goals reflexivity
end end
abstract begin
intro p, induction p, induction z, all_goals reflexivity
end end
section
variables {a a' : A} {b b' : B}
definition eq_of_inl_eq_inl [unfold 5] (p : inl a = inl a' :> A + B) : a = a' :=
down (sum.encode p)
definition eq_of_inr_eq_inr [unfold 5] (p : inr b = inr b' :> A + B) : b = b' :=
down (sum.encode p)
definition empty_of_inl_eq_inr (p : inl a = inr b) : empty := down (sum.encode p)
definition empty_of_inr_eq_inl (p : inr b = inl a) : empty := down (sum.encode p)
definition sum_transport {P Q : A → Type} (p : a = a') (z : P a + Q a)
: p ▸ z = sum.rec (λa, inl (p ▸ a)) (λb, inr (p ▸ b)) z :=
by induction p; induction z; all_goals reflexivity
end
variables {A' B' : Type} (f : A → A') (g : B → B')
definition sum_functor [unfold 7] : A + B → A' + B'
| sum_functor (inl a) := inl (f a)
| sum_functor (inr b) := inr (g b)
definition is_equiv_sum_functor [Hf : is_equiv f] [Hg : is_equiv g] : is_equiv (sum_functor f g) :=
adjointify (sum_functor f g)
(sum_functor f⁻¹ g⁻¹)
abstract begin
intro z, induction z,
all_goals (esimp; (apply ap inl | apply ap inr); apply right_inv)
end end
abstract begin
intro z, induction z,
all_goals (esimp; (apply ap inl | apply ap inr); apply right_inv)
end end
definition sum_equiv_sum_of_is_equiv [Hf : is_equiv f] [Hg : is_equiv g] : A + B ≃ A' + B' :=
equiv.mk _ (is_equiv_sum_functor f g)
definition sum_equiv_sum (f : A ≃ A') (g : B ≃ B') : A + B ≃ A' + B' :=
equiv.mk _ (is_equiv_sum_functor f g)
definition sum_equiv_sum_left (g : B ≃ B') : A + B ≃ A + B' :=
sum_equiv_sum equiv.refl g
definition sum_equiv_sum_right (f : A ≃ A') : A + B ≃ A' + B :=
sum_equiv_sum f equiv.refl
definition flip : A + B → B + A
| flip (inl a) := inr a
| flip (inr b) := inl b
definition sum_comm_equiv (A B : Type) : A + B ≃ B + A :=
begin
fapply equiv.MK,
exact flip,
exact flip,
all_goals (intro z; induction z; all_goals reflexivity)
end
-- definition sum_assoc_equiv (A B C : Type) : A + (B + C) ≃ (A + B) + C :=
-- begin
-- fapply equiv.MK,
-- all_goals try (intro z; induction z with u v;
-- all_goals try induction u; all_goals try induction v),
-- all_goals try (repeat (apply inl | apply inr | assumption); now),
-- end
definition sum_empty_equiv (A : Type) : A + empty ≃ A :=
begin
fapply equiv.MK,
intro z, induction z, assumption, contradiction,
exact inl,
intro a, reflexivity,
intro z, induction z, reflexivity, contradiction
end
definition sum_rec_unc {P : A + B → Type} (fg : (Πa, P (inl a)) × (Πb, P (inr b))) : Πz, P z :=
sum.rec fg.1 fg.2
definition is_equiv_sum_rec (P : A + B → Type)
: is_equiv (sum_rec_unc : (Πa, P (inl a)) × (Πb, P (inr b)) → Πz, P z) :=
begin
apply adjointify sum_rec_unc (λf, (λa, f (inl a), λb, f (inr b))),
intro f, apply eq_of_homotopy, intro z, focus (induction z; all_goals reflexivity),
intro h, induction h with f g, reflexivity
end
definition equiv_sum_rec (P : A + B → Type) : (Πa, P (inl a)) × (Πb, P (inr b)) ≃ Πz, P z :=
equiv.mk _ !is_equiv_sum_rec
definition imp_prod_imp_equiv_sum_imp (A B C : Type) : (A → C) × (B → C) ≃ (A + B → C) :=
!equiv_sum_rec
definition is_trunc_sum (n : trunc_index) [HA : is_trunc (n.+2) A] [HB : is_trunc (n.+2) B]
: is_trunc (n.+2) (A + B) :=
begin
apply is_trunc_succ_intro, intro z z',
apply is_trunc_equiv_closed_rev, apply sum_eq_equiv,
induction z with a b, all_goals induction z' with a' b', all_goals esimp,
all_goals exact _,
end
/- Sums are equivalent to dependent sigmas where the first component is a bool. -/
definition sum_of_sigma_bool {A B : Type} (v : Σ(b : bool), bool.rec A B b) : A + B :=
by induction v with b x; induction b; exact inl x; exact inr x
definition sigma_bool_of_sum {A B : Type} (z : A + B) : Σ(b : bool), bool.rec A B b :=
by induction z with a b; exact ⟨ff, a⟩; exact ⟨tt, b⟩
definition sum_equiv_sigma_bool (A B : Type) : A + B ≃ Σ(b : bool), bool.rec A B b :=
equiv.MK sigma_bool_of_sum
sum_of_sigma_bool
begin intro v, induction v with b x, induction b, all_goals reflexivity end
begin intro z, induction z with a b, all_goals reflexivity end
end sum
|
7435700db3519ef68e48d399ddcc140eb60ac644 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/order/pilex_auto.lean | 34a4ff44c83745c606880599fa438e3bd3c405d0 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,548 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.ordered_pi
import Mathlib.order.well_founded
import Mathlib.algebra.order_functions
import Mathlib.PostPort
universes u_1 u_2
namespace Mathlib
/-- The lexicographic relation on `Π i : ι, β i`, where `ι` is ordered by `r`,
and each `β i` is ordered by `s`. -/
def pi.lex {ι : Type u_1} {β : ι → Type u_2} (r : ι → ι → Prop) (s : {i : ι} → β i → β i → Prop)
(x : (i : ι) → β i) (y : (i : ι) → β i) :=
∃ (i : ι), (∀ (j : ι), r j i → x j = y j) ∧ s (x i) (y i)
/-- The cartesian product of an indexed family, equipped with the lexicographic order. -/
def pilex (α : Type u_1) (β : α → Type u_2) := (a : α) → β a
protected instance pilex.has_lt {ι : Type u_1} {β : ι → Type u_2} [HasLess ι]
[(a : ι) → HasLess (β a)] : HasLess (pilex ι β) :=
{ Less := pi.lex Less fun (_x : ι) => Less }
protected instance pilex.inhabited {ι : Type u_1} {β : ι → Type u_2} [(a : ι) → Inhabited (β a)] :
Inhabited (pilex ι β) :=
eq.mpr sorry (pi.inhabited ι)
protected instance pilex.partial_order {ι : Type u_1} {β : ι → Type u_2} [linear_order ι]
[(a : ι) → partial_order (β a)] : partial_order (pilex ι β) :=
(fun (lt_not_symm : ∀ {x y : pilex ι β}, ¬(x < y ∧ y < x)) =>
partial_order.mk (fun (x y : pilex ι β) => x < y ∨ x = y) Less sorry sorry sorry)
sorry
/-- `pilex` is a linear order if the original order is well-founded.
This cannot be an instance, since it depends on the well-foundedness of `<`. -/
protected def pilex.linear_order {ι : Type u_1} {β : ι → Type u_2} [linear_order ι]
(wf : well_founded Less) [(a : ι) → linear_order (β a)] : linear_order (pilex ι β) :=
linear_order.mk partial_order.le partial_order.lt sorry sorry sorry sorry
(classical.dec_rel LessEq) Mathlib.decidable_eq_of_decidable_le
Mathlib.decidable_lt_of_decidable_le
protected instance pilex.ordered_add_comm_group {ι : Type u_1} {β : ι → Type u_2} [linear_order ι]
[(a : ι) → ordered_add_comm_group (β a)] : ordered_add_comm_group (pilex ι β) :=
ordered_add_comm_group.mk add_comm_group.add sorry add_comm_group.zero sorry sorry
add_comm_group.neg add_comm_group.sub sorry sorry partial_order.le partial_order.lt sorry sorry
sorry sorry
end Mathlib |
c3f57c0708d31331c79bb7f3f1a68a541ffa933f | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/polynomial/monic.lean | fcc459d3a46e57c47fe885c658a2a1975052173f | [] | 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 | 5,698 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.polynomial.reverse
import Mathlib.algebra.associated
import Mathlib.tactic.omega.default
import Mathlib.PostPort
universes u v y
namespace Mathlib
/-!
# Theory of monic polynomials
We give several tools for proving that polynomials are monic, e.g.
`monic_mul`, `monic_map`.
-/
namespace polynomial
theorem monic.as_sum {R : Type u} [semiring R] {p : polynomial R} (hp : monic p) : p = X ^ nat_degree p + finset.sum (finset.range (nat_degree p)) fun (i : ℕ) => coe_fn C (coeff p i) * X ^ i := sorry
theorem ne_zero_of_monic_of_zero_ne_one {R : Type u} [semiring R] {p : polynomial R} (hp : monic p) (h : 0 ≠ 1) : p ≠ 0 := sorry
theorem ne_zero_of_ne_zero_of_monic {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (hp : p ≠ 0) (hq : monic q) : q ≠ 0 := sorry
theorem monic_map {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) (hp : monic p) : monic (map f p) := sorry
theorem monic_mul_C_of_leading_coeff_mul_eq_one {R : Type u} [semiring R] {p : polynomial R} [nontrivial R] {b : R} (hp : leading_coeff p * b = 1) : monic (p * coe_fn C b) := sorry
theorem monic_of_degree_le {R : Type u} [semiring R] {p : polynomial R} (n : ℕ) (H1 : degree p ≤ ↑n) (H2 : coeff p n = 1) : monic p := sorry
theorem monic_X_pow_add {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} (H : degree p ≤ ↑n) : monic (X ^ (n + 1) + p) := sorry
theorem monic_X_add_C {R : Type u} [semiring R] (x : R) : monic (X + coe_fn C x) :=
pow_one X ▸ monic_X_pow_add degree_C_le
theorem monic_mul {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (hp : monic p) (hq : monic q) : monic (p * q) := sorry
theorem monic_pow {R : Type u} [semiring R] {p : polynomial R} (hp : monic p) (n : ℕ) : monic (p ^ n) := sorry
theorem monic_add_of_left {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (hp : monic p) (hpq : degree q < degree p) : monic (p + q) :=
eq.mpr (id (Eq._oldrec (Eq.refl (monic (p + q))) (monic.equations._eqn_1 (p + q))))
(eq.mpr (id (Eq._oldrec (Eq.refl (leading_coeff (p + q) = 1)) (add_comm p q)))
(eq.mpr (id (Eq._oldrec (Eq.refl (leading_coeff (q + p) = 1)) (leading_coeff_add_of_degree_lt hpq))) hp))
theorem monic_add_of_right {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (hq : monic q) (hpq : degree p < degree q) : monic (p + q) :=
eq.mpr (id (Eq._oldrec (Eq.refl (monic (p + q))) (monic.equations._eqn_1 (p + q))))
(eq.mpr (id (Eq._oldrec (Eq.refl (leading_coeff (p + q) = 1)) (leading_coeff_add_of_degree_lt hpq))) hq)
namespace monic
@[simp] theorem degree_eq_zero_iff_eq_one {R : Type u} [semiring R] {p : polynomial R} (hp : monic p) : nat_degree p = 0 ↔ p = 1 := sorry
theorem nat_degree_mul {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (hp : monic p) (hq : monic q) : nat_degree (p * q) = nat_degree p + nat_degree q := sorry
theorem next_coeff_mul {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (hp : monic p) (hq : monic q) : next_coeff (p * q) = next_coeff p + next_coeff q := sorry
end monic
theorem monic_prod_of_monic {R : Type u} {ι : Type y} [comm_semiring R] (s : finset ι) (f : ι → polynomial R) (hs : ∀ (i : ι), i ∈ s → monic (f i)) : monic (finset.prod s fun (i : ι) => f i) :=
finset.prod_induction (fun (x : ι) => f x) monic monic_mul monic_one hs
theorem is_unit_C {R : Type u} [comm_semiring R] {x : R} : is_unit (coe_fn C x) ↔ is_unit x := sorry
theorem eq_one_of_is_unit_of_monic {R : Type u} [comm_semiring R] {p : polynomial R} (hm : monic p) (hpu : is_unit p) : p = 1 := sorry
theorem monic.next_coeff_prod {R : Type u} {ι : Type y} [comm_semiring R] (s : finset ι) (f : ι → polynomial R) (h : ∀ (i : ι), i ∈ s → monic (f i)) : next_coeff (finset.prod s fun (i : ι) => f i) = finset.sum s fun (i : ι) => next_coeff (f i) := sorry
theorem monic_X_sub_C {R : Type u} [ring R] (x : R) : monic (X - coe_fn C x) := sorry
theorem monic_X_pow_sub {R : Type u} [ring R] {p : polynomial R} {n : ℕ} (H : degree p ≤ ↑n) : monic (X ^ (n + 1) - p) := sorry
/-- `X ^ n - a` is monic. -/
theorem monic_X_pow_sub_C {R : Type u} [ring R] (a : R) {n : ℕ} (h : n ≠ 0) : monic (X ^ n - coe_fn C a) := sorry
theorem monic_sub_of_left {R : Type u} [ring R] {p : polynomial R} {q : polynomial R} (hp : monic p) (hpq : degree q < degree p) : monic (p - q) :=
eq.mpr (id (Eq._oldrec (Eq.refl (monic (p - q))) (sub_eq_add_neg p q)))
(monic_add_of_left hp (eq.mpr (id (Eq._oldrec (Eq.refl (degree (-q) < degree p)) (degree_neg q))) hpq))
theorem monic_sub_of_right {R : Type u} [ring R] {p : polynomial R} {q : polynomial R} (hq : leading_coeff q = -1) (hpq : degree p < degree q) : monic (p - q) := sorry
theorem leading_coeff_of_injective {R : Type u} {S : Type v} [ring R] [semiring S] {f : R →+* S} (hf : function.injective ⇑f) (p : polynomial R) : leading_coeff (map f p) = coe_fn f (leading_coeff p) := sorry
theorem monic_of_injective {R : Type u} {S : Type v} [ring R] [semiring S] {f : R →+* S} (hf : function.injective ⇑f) {p : polynomial R} (hp : monic (map f p)) : monic p := sorry
@[simp] theorem not_monic_zero {R : Type u} [semiring R] [nontrivial R] : ¬monic 0 := sorry
theorem ne_zero_of_monic {R : Type u} [semiring R] [nontrivial R] {p : polynomial R} (h : monic p) : p ≠ 0 :=
fun (h₁ : p = 0) => not_monic_zero (h₁ ▸ h)
|
537b4f5ff917043bd3ae24dd592f4d4fb1130474 | ee8cdbabf07f77e7be63a449b8483ce308d37218 | /lean/src/valid/mathd-algebra-51.lean | 940be87a4865cf68f49f922f9d540fb9e547eb73 | [
"MIT",
"Apache-2.0"
] | permissive | zeta1999/miniF2F | 6d66c75d1c18152e224d07d5eed57624f731d4b7 | c1ba9629559c5273c92ec226894baa0c1ce27861 | refs/heads/main | 1,681,897,460,642 | 1,620,646,361,000 | 1,620,646,361,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 295 | lean | /-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng
-/
import data.real.basic
example (a b : ℝ) (h₀ : 0 < a ∧ 0 < b) (h₁ : a + b = 35) (h₂ : a = (2/5) * b) : b - a = 15 :=
begin
linarith,
end
|
302d46f4e95f0c90eafbf560baf4620cce3d1164 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/algebra/add_torsor.lean | baf94974eb81f4f8d2134dac533f46f253b348c8 | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 14,885 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Yury Kudryashov.
-/
import algebra.group.prod
import algebra.group.type_tags
import algebra.group.pi
import data.equiv.basic
import data.set.finite
/-!
# Torsors of additive group actions
This file defines torsors of additive group actions.
## Notations
The group elements are referred to as acting on points. This file
defines the notation `+ᵥ` for adding a group element to a point and
`-ᵥ` for subtracting two points to produce a group element.
## Implementation notes
Affine spaces are the motivating example of torsors of additive group
actions. It may be appropriate to refactor in terms of the general
definition of group actions, via `to_additive`, when there is a use
for multiplicative torsors (currently mathlib only develops the theory
of group actions for multiplicative group actions). The variable `G`
is an explicit rather than implicit argument to lemmas because
otherwise the elaborator sometimes has problems inferring appropriate
types and type class instances.
## References
* https://en.wikipedia.org/wiki/Principal_homogeneous_space
* https://en.wikipedia.org/wiki/Affine_space
-/
/-- Type class for the `+ᵥ` notation. -/
class has_vadd (G : Type*) (P : Type*) :=
(vadd : G → P → P)
/-- Type class for the `-ᵥ` notation. -/
class has_vsub (G : out_param Type*) (P : Type*) :=
(vsub : P → P → G)
infix ` +ᵥ `:65 := has_vadd.vadd
infix ` -ᵥ `:65 := has_vsub.vsub
section prio
set_option default_priority 100 -- see Note [default priority]
set_option old_structure_cmd true
/-- Type class for additive monoid actions. -/
class add_action (G : Type*) (P : Type*) [add_monoid G] extends has_vadd G P :=
(zero_vadd' : ∀ p : P, (0 : G) +ᵥ p = p)
(vadd_assoc' : ∀ (g1 g2 : G) (p : P), g1 +ᵥ (g2 +ᵥ p) = (g1 + g2) +ᵥ p)
/-- An `add_torsor G P` gives a structure to the nonempty type `P`,
acted on by an `add_group G` with a transitive and free action given
by the `+ᵥ` operation and a corresponding subtraction given by the
`-ᵥ` operation. In the case of a vector space, it is an affine
space. -/
class add_torsor (G : out_param Type*) (P : Type*) [out_param $ add_group G]
extends add_action G P, has_vsub G P :=
[nonempty : nonempty P]
(vsub_vadd' : ∀ (p1 p2 : P), (p1 -ᵥ p2 : G) +ᵥ p2 = p1)
(vadd_vsub' : ∀ (g : G) (p : P), g +ᵥ p -ᵥ p = g)
attribute [instance, priority 100, nolint dangerous_instance] add_torsor.nonempty
end prio
/-- An `add_group G` is a torsor for itself. -/
@[nolint instance_priority]
instance add_group_is_add_torsor (G : Type*) [add_group G] :
add_torsor G G :=
{ vadd := has_add.add,
vsub := has_sub.sub,
zero_vadd' := zero_add,
vadd_assoc' := λ a b c, (add_assoc a b c).symm,
vsub_vadd' := sub_add_cancel,
vadd_vsub' := add_sub_cancel }
/-- Simplify addition for a torsor for an `add_group G` over
itself. -/
@[simp] lemma vadd_eq_add {G : Type*} [add_group G] (g1 g2 : G) : g1 +ᵥ g2 = g1 + g2 :=
rfl
/-- Simplify subtraction for a torsor for an `add_group G` over
itself. -/
@[simp] lemma vsub_eq_sub {G : Type*} [add_group G] (g1 g2 : G) : g1 -ᵥ g2 = g1 - g2 :=
rfl
section general
variables (G : Type*) {P : Type*} [add_monoid G] [A : add_action G P]
include A
/-- Adding the zero group element to a point gives the same point. -/
@[simp] lemma zero_vadd (p : P) : (0 : G) +ᵥ p = p :=
add_action.zero_vadd' p
variables {G}
/-- Adding two group elements to a point produces the same result as
adding their sum. -/
lemma vadd_assoc (g1 g2 : G) (p : P) : g1 +ᵥ (g2 +ᵥ p) = (g1 + g2) +ᵥ p :=
add_action.vadd_assoc' g1 g2 p
end general
section comm
variables (G : Type*) {P : Type*} [add_comm_monoid G] [A : add_action G P]
include A
/-- Adding two group elements to a point produces the same result in either
order. -/
lemma vadd_comm (p : P) (g1 g2 : G) : g1 +ᵥ (g2 +ᵥ p) = g2 +ᵥ (g1 +ᵥ p) :=
by rw [vadd_assoc, vadd_assoc, add_comm]
end comm
section group
variables {G : Type*} {P : Type*} [add_group G] [A : add_action G P]
include A
/-- If the same group element added to two points produces equal results,
those points are equal. -/
lemma vadd_left_cancel {p1 p2 : P} (g : G) (h : g +ᵥ p1 = g +ᵥ p2) : p1 = p2 :=
begin
have h2 : -g +ᵥ (g +ᵥ p1) = -g +ᵥ (g +ᵥ p2), { rw h },
rwa [vadd_assoc, vadd_assoc, add_left_neg, zero_vadd, zero_vadd] at h2
end
@[simp] lemma vadd_left_cancel_iff {p₁ p₂ : P} (g : G) :
g +ᵥ p₁ = g +ᵥ p₂ ↔ p₁ = p₂ :=
⟨vadd_left_cancel g, λ h, h ▸ rfl⟩
variables (P)
/-- Adding the group element `g` to a point is an injective function. -/
lemma vadd_left_injective (g : G) : function.injective ((+ᵥ) g : P → P) :=
λ p1 p2, vadd_left_cancel g
end group
section general
variables {G : Type*} {P : Type*} [add_group G] [T : add_torsor G P]
include T
/-- Adding the result of subtracting from another point produces that
point. -/
@[simp] lemma vsub_vadd (p1 p2 : P) : p1 -ᵥ p2 +ᵥ p2 = p1 :=
add_torsor.vsub_vadd' p1 p2
/-- Adding a group element then subtracting the original point
produces that group element. -/
@[simp] lemma vadd_vsub (g : G) (p : P) : g +ᵥ p -ᵥ p = g :=
add_torsor.vadd_vsub' g p
/-- If the same point added to two group elements produces equal
results, those group elements are equal. -/
lemma vadd_right_cancel {g1 g2 : G} (p : P) (h : g1 +ᵥ p = g2 +ᵥ p) : g1 = g2 :=
by rw [←vadd_vsub g1, h, vadd_vsub]
@[simp] lemma vadd_right_cancel_iff {g1 g2 : G} (p : P) : g1 +ᵥ p = g2 +ᵥ p ↔ g1 = g2 :=
⟨vadd_right_cancel p, λ h, h ▸ rfl⟩
/-- Adding a group element to the point `p` is an injective
function. -/
lemma vadd_right_injective (p : P) : function.injective ((+ᵥ p) : G → P) :=
λ g1 g2, vadd_right_cancel p
/-- Adding a group element to a point, then subtracting another point,
produces the same result as subtracting the points then adding the
group element. -/
lemma vadd_vsub_assoc (g : G) (p1 p2 : P) : g +ᵥ p1 -ᵥ p2 = g + (p1 -ᵥ p2) :=
begin
apply vadd_right_cancel p2,
rw [vsub_vadd, ←vadd_assoc, vsub_vadd]
end
/-- Subtracting a point from itself produces 0. -/
@[simp] lemma vsub_self (p : P) : p -ᵥ p = (0 : G) :=
by rw [←zero_add (p -ᵥ p), ←vadd_vsub_assoc, vadd_vsub]
/-- If subtracting two points produces 0, they are equal. -/
lemma eq_of_vsub_eq_zero {p1 p2 : P} (h : p1 -ᵥ p2 = (0 : G)) : p1 = p2 :=
by rw [←vsub_vadd p1 p2, h, zero_vadd]
/-- Subtracting two points produces 0 if and only if they are
equal. -/
@[simp] lemma vsub_eq_zero_iff_eq {p1 p2 : P} : p1 -ᵥ p2 = (0 : G) ↔ p1 = p2 :=
iff.intro eq_of_vsub_eq_zero (λ h, h ▸ vsub_self _)
/-- Cancellation adding the results of two subtractions. -/
@[simp] lemma vsub_add_vsub_cancel (p1 p2 p3 : P) : p1 -ᵥ p2 + (p2 -ᵥ p3) = (p1 -ᵥ p3) :=
begin
apply vadd_right_cancel p3,
rw [←vadd_assoc, vsub_vadd, vsub_vadd, vsub_vadd]
end
/-- Subtracting two points in the reverse order produces the negation
of subtracting them. -/
@[simp] lemma neg_vsub_eq_vsub_rev (p1 p2 : P) : -(p1 -ᵥ p2) = (p2 -ᵥ p1) :=
begin
refine neg_eq_of_add_eq_zero (vadd_right_cancel p1 _),
rw [vsub_add_vsub_cancel, vsub_self],
end
/-- Subtracting the result of adding a group element produces the same result
as subtracting the points and subtracting that group element. -/
lemma vsub_vadd_eq_vsub_sub (p1 p2 : P) (g : G) : p1 -ᵥ (g +ᵥ p2) = (p1 -ᵥ p2) - g :=
by rw [←add_right_inj (p2 -ᵥ p1 : G), vsub_add_vsub_cancel, ←neg_vsub_eq_vsub_rev, vadd_vsub,
←add_sub_assoc, ←neg_vsub_eq_vsub_rev, neg_add_self, zero_sub]
/-- Cancellation subtracting the results of two subtractions. -/
@[simp] lemma vsub_sub_vsub_cancel_right (p1 p2 p3 : P) :
(p1 -ᵥ p3) - (p2 -ᵥ p3) = (p1 -ᵥ p2) :=
by rw [←vsub_vadd_eq_vsub_sub, vsub_vadd]
/-- Convert between an equality with adding a group element to a point
and an equality of a subtraction of two points with a group
element. -/
lemma eq_vadd_iff_vsub_eq (p1 : P) (g : G) (p2 : P) : p1 = g +ᵥ p2 ↔ p1 -ᵥ p2 = g :=
⟨λ h, h.symm ▸ vadd_vsub _ _, λ h, h ▸ (vsub_vadd _ _).symm⟩
/-- The pairwise differences of a set of points. -/
def vsub_set (s : set P) : set G := set.image2 (-ᵥ) s s
/-- `vsub_set` of an empty set. -/
@[simp] lemma vsub_set_empty : vsub_set (∅ : set P) = ∅ :=
set.image2_empty_left
/-- `vsub_set` of a single point. -/
@[simp] lemma vsub_set_singleton (p : P) : vsub_set ({p} : set P) = {(0:G)} :=
by simp [vsub_set]
/-- `vsub_set` of a finite set is finite. -/
lemma vsub_set_finite_of_finite {s : set P} (h : set.finite s) : set.finite (vsub_set s) :=
h.image2 _ h
/-- Each pairwise difference is in the `vsub_set`. -/
lemma vsub_mem_vsub_set {p1 p2 : P} {s : set P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) :
(p1 -ᵥ p2) ∈ vsub_set s :=
set.mem_image2_of_mem hp1 hp2
/-- `vsub_set` is contained in `vsub_set` of a larger set. -/
lemma vsub_set_mono {s1 s2 : set P} (h : s1 ⊆ s2) : vsub_set s1 ⊆ vsub_set s2 :=
set.image2_subset h h
@[simp] lemma vadd_vsub_vadd_cancel_right (v₁ v₂ : G) (p : P) :
(v₁ +ᵥ p) -ᵥ (v₂ +ᵥ p) = v₁ - v₂ :=
by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, vsub_self, add_zero]
/-- If the same point subtracted from two points produces equal
results, those points are equal. -/
lemma vsub_left_cancel {p1 p2 p : P} (h : p1 -ᵥ p = p2 -ᵥ p) : p1 = p2 :=
by rwa [←sub_eq_zero, vsub_sub_vsub_cancel_right, vsub_eq_zero_iff_eq] at h
/-- The same point subtracted from two points produces equal results
if and only if those points are equal. -/
@[simp] lemma vsub_left_cancel_iff {p1 p2 p : P} : (p1 -ᵥ p) = p2 -ᵥ p ↔ p1 = p2 :=
⟨vsub_left_cancel, λ h, h ▸ rfl⟩
/-- Subtracting the point `p` is an injective function. -/
lemma vsub_left_injective (p : P) : function.injective ((-ᵥ p) : P → G) :=
λ p2 p3, vsub_left_cancel
/-- If subtracting two points from the same point produces equal
results, those points are equal. -/
lemma vsub_right_cancel {p1 p2 p : P} (h : p -ᵥ p1 = p -ᵥ p2) : p1 = p2 :=
begin
refine vadd_left_cancel (p -ᵥ p2) _,
rw [vsub_vadd, ← h, vsub_vadd]
end
/-- Subtracting two points from the same point produces equal results
if and only if those points are equal. -/
@[simp] lemma vsub_right_cancel_iff {p1 p2 p : P} : p -ᵥ p1 = p -ᵥ p2 ↔ p1 = p2 :=
⟨vsub_right_cancel, λ h, h ▸ rfl⟩
/-- Subtracting a point from the point `p` is an injective
function. -/
lemma vsub_right_injective (p : P) : function.injective ((-ᵥ) p : P → G) :=
λ p2 p3, vsub_right_cancel
end general
section comm
variables {G : Type*} {P : Type*} [add_comm_group G] [add_torsor G P]
/-- Cancellation subtracting the results of two subtractions. -/
@[simp] lemma vsub_sub_vsub_cancel_left (p1 p2 p3 : P) :
(p3 -ᵥ p2 : G) - (p3 -ᵥ p1) = (p1 -ᵥ p2) :=
by rw [sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm, vsub_add_vsub_cancel]
@[simp] lemma vadd_vsub_vadd_cancel_left (v : G) (p1 p2 : P) :
(v +ᵥ p1) -ᵥ (v +ᵥ p2) = p1 -ᵥ p2 :=
by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub_cancel']
lemma vsub_vadd_comm (p1 p2 p3 : P) : (p1 -ᵥ p2 : G) +ᵥ p3 = p3 -ᵥ p2 +ᵥ p1 :=
begin
rw [←@vsub_eq_zero_iff_eq G, vadd_vsub_assoc, vsub_vadd_eq_vsub_sub],
simp
end
end comm
namespace prod
variables {G : Type*} {P : Type*} {G' : Type*} {P' : Type*} [add_group G] [add_group G']
[add_torsor G P] [add_torsor G' P']
instance : add_torsor (G × G') (P × P') :=
{ vadd := λ v p, (v.1 +ᵥ p.1, v.2 +ᵥ p.2),
zero_vadd' := λ p, by simp,
vadd_assoc' := by simp [vadd_assoc],
vsub := λ p₁ p₂, (p₁.1 -ᵥ p₂.1, p₁.2 -ᵥ p₂.2),
nonempty := prod.nonempty,
vsub_vadd' := λ p₁ p₂, show (p₁.1 -ᵥ p₂.1 +ᵥ p₂.1, _) = p₁, by simp,
vadd_vsub' := λ v p, show (v.1 +ᵥ p.1 -ᵥ p.1, v.2 +ᵥ p.2 -ᵥ p.2) =v, by simp }
@[simp] lemma fst_vadd (v : G × G') (p : P × P') : (v +ᵥ p).1 = v.1 +ᵥ p.1 := rfl
@[simp] lemma snd_vadd (v : G × G') (p : P × P') : (v +ᵥ p).2 = v.2 +ᵥ p.2 := rfl
@[simp] lemma mk_vadd_mk (v : G) (v' : G') (p : P) (p' : P') :
(v, v') +ᵥ (p, p') = (v +ᵥ p, v' +ᵥ p') := rfl
@[simp] lemma fst_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').1 = p₁.1 -ᵥ p₂.1 := rfl
@[simp] lemma snd_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').2 = p₁.2 -ᵥ p₂.2 := rfl
@[simp] lemma mk_vsub_mk (p₁ p₂ : P) (p₁' p₂' : P') :
((p₁, p₁') -ᵥ (p₂, p₂') : G × G') = (p₁ -ᵥ p₂, p₁' -ᵥ p₂') := rfl
end prod
namespace pi
universes u v w
variables {I : Type u} {fg : I → Type v} [∀ i, add_group (fg i)] {fp : I → Type w}
open add_action add_torsor
/-- A product of `add_torsor`s is an `add_torsor`. -/
instance [T : ∀ i, add_torsor (fg i) (fp i)] : add_torsor (Π i, fg i) (Π i, fp i) :=
{
vadd := λ g p, λ i, g i +ᵥ p i,
zero_vadd' := λ p, funext $ λ i, zero_vadd (fg i) (p i),
vadd_assoc' := λ g₁ g₂ p, funext $ λ i, vadd_assoc (g₁ i) (g₂ i) (p i),
vsub := λ p₁ p₂, λ i, p₁ i -ᵥ p₂ i,
nonempty := ⟨λ i, classical.choice (T i).nonempty⟩,
vsub_vadd' := λ p₁ p₂, funext $ λ i, vsub_vadd (p₁ i) (p₂ i),
vadd_vsub' := λ g p, funext $ λ i, vadd_vsub (g i) (p i) }
/-- Addition in a product of `add_torsor`s. -/
@[simp] lemma vadd_apply [T : ∀ i, add_torsor (fg i) (fp i)] (x : Π i, fg i) (y : Π i, fp i)
{i : I} : (x +ᵥ y) i = x i +ᵥ y i
:= rfl
end pi
namespace equiv
variables (G : Type*) {P : Type*} [add_group G] [add_torsor G P]
open add_action add_torsor
/-- `v ↦ v +ᵥ p` as an equivalence. -/
def vadd_const (p : P) : G ≃ P :=
{ to_fun := λ v, v +ᵥ p,
inv_fun := λ p', p' -ᵥ p,
left_inv := λ v, vadd_vsub _ _,
right_inv := λ p', vsub_vadd _ _ }
@[simp] lemma coe_vadd_const (p : P) : ⇑(vadd_const G p) = λ v, v+ᵥ p := rfl
@[simp] lemma coe_vadd_const_symm (p : P) : ⇑(vadd_const G p).symm = λ p', p' -ᵥ p := rfl
variables {G} (P)
/-- The permutation given by `p ↦ v +ᵥ p`. -/
def const_vadd (v : G) : equiv.perm P :=
{ to_fun := (+ᵥ) v,
inv_fun := (+ᵥ) (-v),
left_inv := λ p, by simp [vadd_assoc],
right_inv := λ p, by simp [vadd_assoc] }
@[simp] lemma coe_const_vadd (v : G) : ⇑(const_vadd P v) = (+ᵥ) v := rfl
variable (G)
@[simp] lemma const_vadd_zero : const_vadd P (0:G) = 1 := ext $ zero_vadd G
variable {G}
@[simp] lemma const_vadd_add (v₁ v₂ : G) :
const_vadd P (v₁ + v₂) = const_vadd P v₁ * const_vadd P v₂ :=
ext $ λ p, (vadd_assoc v₁ v₂ p).symm
/-- `equiv.const_vadd` as a homomorphism from `multiplicative G` to `equiv.perm P` -/
def const_vadd_hom : multiplicative G →* equiv.perm P :=
{ to_fun := λ v, const_vadd P v.to_add,
map_one' := const_vadd_zero G P,
map_mul' := const_vadd_add P }
end equiv
|
f2fbd9597c131336dad83da700fc138a14fe129e | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/ring_theory/integral_closure.lean | e5a626879033ab088f42f354d1771867dd579b26 | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 25,888 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import ring_theory.adjoin.basic
import ring_theory.polynomial.scale_roots
import ring_theory.polynomial.tower
/-!
# Integral closure of a subring.
If A is an R-algebra then `a : A` is integral over R if it is a root of a monic polynomial
with coefficients in R. Enough theory is developed to prove that integral elements
form a sub-R-algebra of A.
## Main definitions
Let `R` be a `comm_ring` and let `A` be an R-algebra.
* `ring_hom.is_integral_elem (f : R →+* A) (x : A)` : `x` is integral with respect to the map `f`,
* `is_integral (x : A)` : `x` is integral over `R`, i.e., is a root of a monic polynomial with
coefficients in `R`.
* `integral_closure R A` : the integral closure of `R` in `A`, regarded as a sub-`R`-algebra of `A`.
-/
open_locale classical
open_locale big_operators
open polynomial submodule
section ring
variables {R S A : Type*}
variables [comm_ring R] [ring A] [ring S] (f : R →+* S)
/-- An element `x` of `A` is said to be integral over `R` with respect to `f`
if it is a root of a monic polynomial `p : polynomial R` evaluated under `f` -/
def ring_hom.is_integral_elem (f : R →+* A) (x : A) :=
∃ p : polynomial R, monic p ∧ eval₂ f x p = 0
/-- A ring homomorphism `f : R →+* A` is said to be integral
if every element `A` is integral with respect to the map `f` -/
def ring_hom.is_integral (f : R →+* A) :=
∀ x : A, f.is_integral_elem x
variables [algebra R A] (R)
/-- An element `x` of an algebra `A` over a commutative ring `R` is said to be *integral*,
if it is a root of some monic polynomial `p : polynomial R`.
Equivalently, the element is integral over `R` with respect to the induced `algebra_map` -/
def is_integral (x : A) : Prop :=
(algebra_map R A).is_integral_elem x
variable (A)
/-- An algebra is integral if every element of the extension is integral over the base ring -/
def algebra.is_integral : Prop :=
(algebra_map R A).is_integral
variables {R A}
lemma ring_hom.is_integral_map {x : R} : f.is_integral_elem (f x) :=
⟨X - C x, monic_X_sub_C _, by simp⟩
theorem is_integral_algebra_map {x : R} : is_integral R (algebra_map R A x) :=
(algebra_map R A).is_integral_map
theorem is_integral_of_noetherian (H : is_noetherian R A) (x : A) :
is_integral R x :=
begin
let leval : @linear_map R (polynomial R) A _ _ _ _ _ := (aeval x).to_linear_map,
let D : ℕ → submodule R A := λ n, (degree_le R n).map leval,
let M := well_founded.min (is_noetherian_iff_well_founded.1 H)
(set.range D) ⟨_, ⟨0, rfl⟩⟩,
have HM : M ∈ set.range D := well_founded.min_mem _ _ _,
cases HM with N HN,
have HM : ¬M < D (N+1) := well_founded.not_lt_min
(is_noetherian_iff_well_founded.1 H) (set.range D) _ ⟨N+1, rfl⟩,
rw ← HN at HM,
have HN2 : D (N+1) ≤ D N := classical.by_contradiction (λ H, HM
(lt_of_le_not_le (map_mono (degree_le_mono
(with_bot.coe_le_coe.2 (nat.le_succ N)))) H)),
have HN3 : leval (X^(N+1)) ∈ D N,
{ exact HN2 (mem_map_of_mem (mem_degree_le.2 (degree_X_pow_le _))) },
rcases HN3 with ⟨p, hdp, hpe⟩,
refine ⟨X^(N+1) - p, monic_X_pow_sub (mem_degree_le.1 hdp), _⟩,
show leval (X ^ (N + 1) - p) = 0,
rw [linear_map.map_sub, hpe, sub_self]
end
theorem is_integral_of_submodule_noetherian (S : subalgebra R A)
(H : is_noetherian R S.to_submodule) (x : A) (hx : x ∈ S) :
is_integral R x :=
begin
suffices : is_integral R (show S, from ⟨x, hx⟩),
{ rcases this with ⟨p, hpm, hpx⟩,
replace hpx := congr_arg S.val hpx,
refine ⟨p, hpm, eq.trans _ hpx⟩,
simp only [aeval_def, eval₂, finsupp.sum],
rw S.val.map_sum,
refine finset.sum_congr rfl (λ n hn, _),
rw [S.val.map_mul, S.val.map_pow, S.val.commutes, S.val_apply, subtype.coe_mk], },
refine is_integral_of_noetherian H ⟨x, hx⟩
end
end ring
section
variables {R A B S : Type*}
variables [comm_ring R] [comm_ring A] [comm_ring B] [comm_ring S]
variables [algebra R A] [algebra R B] (f : R →+* S)
theorem is_integral_alg_hom (f : A →ₐ[R] B) {x : A} (hx : is_integral R x) : is_integral R (f x) :=
let ⟨p, hp, hpx⟩ :=
hx in ⟨p, hp, by rw [← aeval_def, aeval_alg_hom_apply, aeval_def, hpx, f.map_zero]⟩
theorem is_integral_of_is_scalar_tower [algebra A B] [is_scalar_tower R A B]
(x : B) (hx : is_integral R x) : is_integral A x :=
let ⟨p, hp, hpx⟩ := hx in
⟨p.map $ algebra_map R A, monic_map _ hp,
by rw [← aeval_def, ← is_scalar_tower.aeval_apply, aeval_def, hpx]⟩
section
local attribute [instance] subset.comm_ring algebra.of_is_subring
theorem is_integral_of_subring {x : A} (T : set R) [is_subring T]
(hx : is_integral T x) : is_integral R x :=
is_integral_of_is_scalar_tower x hx
lemma is_integral_algebra_map_iff [algebra A B] [is_scalar_tower R A B]
{x : A} (hAB : function.injective (algebra_map A B)) :
is_integral R (algebra_map A B x) ↔ is_integral R x :=
begin
split; rintros ⟨f, hf, hx⟩; use [f, hf],
{ exact is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero R A B hAB hx },
{ rw [is_scalar_tower.algebra_map_eq R A B, ← hom_eval₂, hx, ring_hom.map_zero] }
end
theorem is_integral_iff_is_integral_closure_finite {r : A} :
is_integral R r ↔ ∃ s : set R, s.finite ∧ is_integral (ring.closure s) r :=
begin
split; intro hr,
{ rcases hr with ⟨p, hmp, hpr⟩,
refine ⟨_, set.finite_mem_finset _, p.restriction, subtype.eq hmp, _⟩,
erw [← aeval_def, is_scalar_tower.aeval_apply _ R, map_restriction, aeval_def, hpr] },
rcases hr with ⟨s, hs, hsr⟩,
exact is_integral_of_subring _ hsr
end
end
theorem fg_adjoin_singleton_of_integral (x : A) (hx : is_integral R x) :
(algebra.adjoin R ({x} : set A)).to_submodule.fg :=
begin
rcases hx with ⟨f, hfm, hfx⟩,
existsi finset.image ((^) x) (finset.range (nat_degree f + 1)),
apply le_antisymm,
{ rw span_le, intros s hs, rw finset.mem_coe at hs,
rcases finset.mem_image.1 hs with ⟨k, hk, rfl⟩, clear hk,
exact is_submonoid.pow_mem (algebra.subset_adjoin (set.mem_singleton _)) },
intros r hr, change r ∈ algebra.adjoin R ({x} : set A) at hr,
rw algebra.adjoin_singleton_eq_range at hr,
rcases (aeval x).mem_range.mp hr with ⟨p, rfl⟩,
rw ← mod_by_monic_add_div p hfm,
rw ← aeval_def at hfx,
rw [alg_hom.map_add, alg_hom.map_mul, hfx, zero_mul, add_zero],
have : degree (p %ₘ f) ≤ degree f := degree_mod_by_monic_le p hfm,
generalize_hyp : p %ₘ f = q at this ⊢,
rw [← sum_C_mul_X_eq q, aeval_def, eval₂_sum, finsupp.sum],
refine sum_mem _ (λ k hkq, _),
rw [eval₂_mul, eval₂_C, eval₂_pow, eval₂_X, ← algebra.smul_def],
refine smul_mem _ _ (subset_span _),
rw finset.mem_coe, refine finset.mem_image.2 ⟨_, _, rfl⟩,
rw [finset.mem_range, nat.lt_succ_iff], refine le_of_not_lt (λ hk, _),
rw [degree_le_iff_coeff_zero] at this,
rw [finsupp.mem_support_iff] at hkq, apply hkq, apply this,
exact lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 hk)
end
theorem fg_adjoin_of_finite {s : set A} (hfs : s.finite)
(his : ∀ x ∈ s, is_integral R x) : (algebra.adjoin R s).to_submodule.fg :=
set.finite.induction_on hfs (λ _, ⟨{1}, submodule.ext $ λ x,
by { erw [algebra.adjoin_empty, finset.coe_singleton, ← one_eq_span, one_eq_map_top,
map_top, linear_map.mem_range, algebra.mem_bot], refl }⟩)
(λ a s has hs ih his, by rw [← set.union_singleton, algebra.adjoin_union_coe_submodule]; exact
fg_mul _ _ (ih $ λ i hi, his i $ set.mem_insert_of_mem a hi)
(fg_adjoin_singleton_of_integral _ $ his a $ set.mem_insert a s)) his
theorem is_integral_of_mem_of_fg (S : subalgebra R A)
(HS : S.to_submodule.fg) (x : A) (hx : x ∈ S) : is_integral R x :=
begin
cases HS with y hy,
obtain ⟨lx, hlx1, hlx2⟩ :
∃ (l : A →₀ R) (H : l ∈ finsupp.supported R R ↑y), (finsupp.total A A R id) l = x,
{ rwa [←(@finsupp.mem_span_iff_total A A R _ _ _ id ↑y x), set.image_id ↑y, hy] },
have hyS : ∀ {p}, p ∈ y → p ∈ S := λ p hp, show p ∈ S.to_submodule,
by { rw ← hy, exact subset_span hp },
have : ∀ (jk : (↑(y.product y) : set (A × A))), jk.1.1 * jk.1.2 ∈ S.to_submodule :=
λ jk, S.mul_mem (hyS (finset.mem_product.1 jk.2).1) (hyS (finset.mem_product.1 jk.2).2),
rw [← hy, ← set.image_id ↑y] at this, simp only [finsupp.mem_span_iff_total] at this,
choose ly hly1 hly2,
let S₀ : set R := ring.closure ↑(lx.frange ∪ finset.bUnion finset.univ (finsupp.frange ∘ ly)),
refine is_integral_of_subring S₀ _,
letI : comm_ring S₀ := @subtype.comm_ring _ _ _ ring.closure.is_subring,
letI : algebra S₀ A := algebra.of_is_subring _,
have :
span S₀ (insert 1 ↑y : set A) * span S₀ (insert 1 ↑y : set A) ≤ span S₀ (insert 1 ↑y : set A),
{ rw span_mul_span, refine span_le.2 (λ z hz, _),
rcases set.mem_mul.1 hz with ⟨p, q, rfl | hp, hq, rfl⟩,
{ rw one_mul, exact subset_span hq },
rcases hq with rfl | hq,
{ rw mul_one, exact subset_span (or.inr hp) },
erw ← hly2 ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩,
rw [finsupp.total_apply, finsupp.sum],
refine (span S₀ (insert 1 ↑y : set A)).sum_mem (λ t ht, _),
have : ly ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩ t ∈ S₀ :=
ring.subset_closure (finset.mem_union_right _ $ finset.mem_bUnion.2
⟨⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, finset.mem_univ _,
finsupp.mem_frange.2 ⟨finsupp.mem_support_iff.1 ht, _, rfl⟩⟩),
change (⟨_, this⟩ : S₀) • t ∈ _, exact smul_mem _ _ (subset_span $ or.inr $ hly1 _ ht) },
haveI : is_subring (span S₀ (insert 1 ↑y : set A) : set A) :=
{ one_mem := subset_span $ or.inl rfl,
mul_mem := λ p q hp hq, this $ mul_mem_mul hp hq,
zero_mem := (span S₀ (insert 1 ↑y : set A)).zero_mem,
add_mem := λ _ _, (span S₀ (insert 1 ↑y : set A)).add_mem,
neg_mem := λ _, (span S₀ (insert 1 ↑y : set A)).neg_mem },
have : span S₀ (insert 1 ↑y : set A) = (algebra.adjoin S₀ (↑y : set A)).to_submodule,
{ refine le_antisymm (span_le.2 $ set.insert_subset.2
⟨(algebra.adjoin S₀ ↑y).one_mem, algebra.subset_adjoin⟩) (λ z hz, _),
rw [subalgebra.mem_to_submodule, algebra.mem_adjoin_iff] at hz, rw ← set_like.mem_coe,
refine ring.closure_subset (set.union_subset (set.range_subset_iff.2 $ λ t, _)
(λ t ht, subset_span $ or.inr ht)) hz,
rw algebra.algebra_map_eq_smul_one,
exact smul_mem (span S₀ (insert 1 ↑y : set A)) _ (subset_span $ or.inl rfl) },
haveI : is_noetherian_ring ↥S₀ := is_noetherian_ring_closure _ (finset.finite_to_set _),
refine is_integral_of_submodule_noetherian (algebra.adjoin S₀ ↑y)
(is_noetherian_of_fg_of_noetherian _ ⟨insert 1 y, by rw [finset.coe_insert, this]⟩) _ _,
rw [← hlx2, finsupp.total_apply, finsupp.sum], refine subalgebra.sum_mem _ (λ r hr, _),
have : lx r ∈ S₀ := ring.subset_closure (finset.mem_union_left _ (finset.mem_image_of_mem _ hr)),
change (⟨_, this⟩ : S₀) • r ∈ _,
rw finsupp.mem_supported at hlx1,
exact subalgebra.smul_mem _ (algebra.subset_adjoin $ hlx1 hr) _
end
lemma ring_hom.is_integral_of_mem_closure {x y z : S}
(hx : f.is_integral_elem x) (hy : f.is_integral_elem y)
(hz : z ∈ ring.closure ({x, y} : set S)) :
f.is_integral_elem z :=
begin
letI : algebra R S := f.to_algebra,
have := fg_mul _ _ (fg_adjoin_singleton_of_integral x hx) (fg_adjoin_singleton_of_integral y hy),
rw [← algebra.adjoin_union_coe_submodule, set.singleton_union] at this,
exact is_integral_of_mem_of_fg (algebra.adjoin R {x, y}) this z
(algebra.mem_adjoin_iff.2 $ ring.closure_mono (set.subset_union_right _ _) hz),
end
theorem is_integral_of_mem_closure {x y z : A}
(hx : is_integral R x) (hy : is_integral R y)
(hz : z ∈ ring.closure ({x, y} : set A)) :
is_integral R z :=
(algebra_map R A).is_integral_of_mem_closure hx hy hz
lemma ring_hom.is_integral_zero : f.is_integral_elem 0 :=
f.map_zero ▸ f.is_integral_map
theorem is_integral_zero : is_integral R (0:A) :=
(algebra_map R A).is_integral_zero
lemma ring_hom.is_integral_one : f.is_integral_elem 1 :=
f.map_one ▸ f.is_integral_map
theorem is_integral_one : is_integral R (1:A) :=
(algebra_map R A).is_integral_one
lemma ring_hom.is_integral_add {x y : S}
(hx : f.is_integral_elem x) (hy : f.is_integral_elem y) :
f.is_integral_elem (x + y) :=
f.is_integral_of_mem_closure hx hy (is_add_submonoid.add_mem
(ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl)))
theorem is_integral_add {x y : A}
(hx : is_integral R x) (hy : is_integral R y) :
is_integral R (x + y) :=
(algebra_map R A).is_integral_add hx hy
lemma ring_hom.is_integral_neg {x : S}
(hx : f.is_integral_elem x) : f.is_integral_elem (-x) :=
f.is_integral_of_mem_closure hx hx (is_add_subgroup.neg_mem
(ring.subset_closure (or.inl rfl)))
theorem is_integral_neg {x : A}
(hx : is_integral R x) : is_integral R (-x) :=
(algebra_map R A).is_integral_neg hx
lemma ring_hom.is_integral_sub {x y : S}
(hx : f.is_integral_elem x) (hy : f.is_integral_elem y) : f.is_integral_elem (x - y) :=
by simpa only [sub_eq_add_neg] using f.is_integral_add hx (f.is_integral_neg hy)
theorem is_integral_sub {x y : A}
(hx : is_integral R x) (hy : is_integral R y) : is_integral R (x - y) :=
(algebra_map R A).is_integral_sub hx hy
lemma ring_hom.is_integral_mul {x y : S}
(hx : f.is_integral_elem x) (hy : f.is_integral_elem y) : f.is_integral_elem (x * y) :=
f.is_integral_of_mem_closure hx hy (is_submonoid.mul_mem
(ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl)))
theorem is_integral_mul {x y : A}
(hx : is_integral R x) (hy : is_integral R y) : is_integral R (x * y) :=
(algebra_map R A).is_integral_mul hx hy
variables (R A)
/-- The integral closure of R in an R-algebra A. -/
def integral_closure : subalgebra R A :=
{ carrier := { r | is_integral R r },
zero_mem' := is_integral_zero,
one_mem' := is_integral_one,
add_mem' := λ _ _, is_integral_add,
mul_mem' := λ _ _, is_integral_mul,
algebra_map_mem' := λ x, is_integral_algebra_map }
theorem mem_integral_closure_iff_mem_fg {r : A} :
r ∈ integral_closure R A ↔ ∃ M : subalgebra R A, M.to_submodule.fg ∧ r ∈ M :=
⟨λ hr, ⟨algebra.adjoin R {r}, fg_adjoin_singleton_of_integral _ hr, algebra.subset_adjoin rfl⟩,
λ ⟨M, Hf, hrM⟩, is_integral_of_mem_of_fg M Hf _ hrM⟩
variables {R} {A}
/-- Mapping an integral closure along an `alg_equiv` gives the integral closure. -/
lemma integral_closure_map_alg_equiv (f : A ≃ₐ[R] B) :
(integral_closure R A).map (f : A →ₐ[R] B) = integral_closure R B :=
begin
ext y,
rw subalgebra.mem_map,
split,
{ rintros ⟨x, hx, rfl⟩,
exact is_integral_alg_hom f hx },
{ intro hy,
use [f.symm y, is_integral_alg_hom (f.symm : B →ₐ[R] A) hy],
simp }
end
lemma integral_closure.is_integral (x : integral_closure R A) : is_integral R x :=
let ⟨p, hpm, hpx⟩ := x.2 in ⟨p, hpm, subtype.eq $
by rwa [← aeval_def, subtype.val_eq_coe, ← subalgebra.val_apply, aeval_alg_hom_apply] at hpx⟩
lemma ring_hom.is_integral_of_is_integral_mul_unit (x y : S) (r : R) (hr : f r * y = 1)
(hx : f.is_integral_elem (x * y)) : f.is_integral_elem x :=
begin
obtain ⟨p, ⟨p_monic, hp⟩⟩ := hx,
refine ⟨scale_roots p r, ⟨(monic_scale_roots_iff r).2 p_monic, _⟩⟩,
convert scale_roots_eval₂_eq_zero f hp,
rw [mul_comm x y, ← mul_assoc, hr, one_mul],
end
theorem is_integral_of_is_integral_mul_unit {x y : A} {r : R} (hr : algebra_map R A r * y = 1)
(hx : is_integral R (x * y)) : is_integral R x :=
(algebra_map R A).is_integral_of_is_integral_mul_unit x y r hr hx
/-- Generalization of `is_integral_of_mem_closure` bootstrapped up from that lemma -/
lemma is_integral_of_mem_closure' (G : set A) (hG : ∀ x ∈ G, is_integral R x) :
∀ x ∈ (subring.closure G), is_integral R x :=
λ x hx, subring.closure_induction hx hG is_integral_zero is_integral_one
(λ _ _, is_integral_add) (λ _, is_integral_neg) (λ _ _, is_integral_mul)
lemma is_integral_of_mem_closure'' {S : Type*} [comm_ring S] {f : R →+* S} (G : set S)
(hG : ∀ x ∈ G, f.is_integral_elem x) : ∀ x ∈ (subring.closure G), f.is_integral_elem x :=
λ x hx, @is_integral_of_mem_closure' R S _ _ f.to_algebra G hG x hx
end
section algebra
open algebra
variables {R A B S T : Type*}
variables [comm_ring R] [comm_ring A] [comm_ring B] [comm_ring S] [comm_ring T]
variables [algebra A B] [algebra R B] (f : R →+* S) (g : S →+* T)
lemma is_integral_trans_aux (x : B) {p : polynomial A} (pmonic : monic p) (hp : aeval x p = 0) :
is_integral (adjoin R (↑(p.map $ algebra_map A B).frange : set B)) x :=
begin
generalize hS : (↑(p.map $ algebra_map A B).frange : set B) = S,
have coeffs_mem : ∀ i, (p.map $ algebra_map A B).coeff i ∈ adjoin R S,
{ intro i, by_cases hi : (p.map $ algebra_map A B).coeff i = 0,
{ rw hi, exact subalgebra.zero_mem _ },
rw ← hS, exact subset_adjoin (finsupp.mem_frange.2 ⟨hi, i, rfl⟩) },
obtain ⟨q, hq⟩ : ∃ q : polynomial (adjoin R S), q.map (algebra_map (adjoin R S) B) =
(p.map $ algebra_map A B),
{ rw ← set.mem_range, exact (polynomial.mem_map_range _).2 (λ i, ⟨⟨_, coeffs_mem i⟩, rfl⟩) },
use q,
split,
{ suffices h : (q.map (algebra_map (adjoin R S) B)).monic,
{ refine monic_of_injective _ h,
exact subtype.val_injective },
{ rw hq, exact monic_map _ pmonic } },
{ convert hp using 1,
replace hq := congr_arg (eval x) hq,
convert hq using 1; symmetry; apply eval_map },
end
variables [algebra R A] [is_scalar_tower R A B]
/-- If A is an R-algebra all of whose elements are integral over R,
and x is an element of an A-algebra that is integral over A, then x is integral over R.-/
lemma is_integral_trans (A_int : is_integral R A) (x : B) (hx : is_integral A x) :
is_integral R x :=
begin
rcases hx with ⟨p, pmonic, hp⟩,
let S : set B := ↑(p.map $ algebra_map A B).frange,
refine is_integral_of_mem_of_fg (adjoin R (S ∪ {x})) _ _ (subset_adjoin $ or.inr rfl),
refine fg_trans (fg_adjoin_of_finite (finset.finite_to_set _) (λ x hx, _)) _,
{ rw [finset.mem_coe, finsupp.mem_frange] at hx, rcases hx with ⟨_, i, rfl⟩,
show is_integral R ((p.map $ algebra_map A B).coeff i), rw coeff_map,
convert is_integral_alg_hom (is_scalar_tower.to_alg_hom R A B) (A_int _) },
{ apply fg_adjoin_singleton_of_integral,
exact is_integral_trans_aux _ pmonic hp }
end
/-- If A is an R-algebra all of whose elements are integral over R,
and B is an A-algebra all of whose elements are integral over A,
then all elements of B are integral over R.-/
lemma algebra.is_integral_trans (hA : is_integral R A) (hB : is_integral A B) : is_integral R B :=
λ x, is_integral_trans hA x (hB x)
lemma ring_hom.is_integral_trans (hf : f.is_integral) (hg : g.is_integral) :
(g.comp f).is_integral :=
@algebra.is_integral_trans R S T _ _ _ g.to_algebra (g.comp f).to_algebra f.to_algebra
(@is_scalar_tower.of_algebra_map_eq R S T _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra
(ring_hom.comp_apply g f)) hf hg
lemma ring_hom.is_integral_of_surjective (hf : function.surjective f) : f.is_integral :=
λ x, (hf x).rec_on (λ y hy, (hy ▸ f.is_integral_map : f.is_integral_elem x))
lemma is_integral_of_surjective (h : function.surjective (algebra_map R A)) : is_integral R A :=
(algebra_map R A).is_integral_of_surjective h
/-- If `R → A → B` is an algebra tower with `A → B` injective,
then if the entire tower is an integral extension so is `R → A` -/
lemma is_integral_tower_bot_of_is_integral (H : function.injective (algebra_map A B))
{x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x :=
begin
rcases h with ⟨p, ⟨hp, hp'⟩⟩,
refine ⟨p, ⟨hp, _⟩⟩,
rw [is_scalar_tower.algebra_map_eq R A B, ← eval₂_map,
eval₂_hom, ← ring_hom.map_zero (algebra_map A B)] at hp',
rw [eval₂_eq_eval_map],
exact H hp',
end
lemma ring_hom.is_integral_tower_bot_of_is_integral (hg : function.injective g)
(hfg : (g.comp f).is_integral) : f.is_integral :=
λ x,
@is_integral_tower_bot_of_is_integral R S T _ _ _ g.to_algebra (g.comp f).to_algebra f.to_algebra
(@is_scalar_tower.of_algebra_map_eq R S T _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra
(ring_hom.comp_apply g f)) hg x (hfg (g x))
lemma is_integral_tower_bot_of_is_integral_field {R A B : Type*} [comm_ring R] [field A]
[comm_ring B] [nontrivial B] [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B]
{x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x :=
is_integral_tower_bot_of_is_integral (algebra_map A B).injective h
lemma ring_hom.is_integral_elem_of_is_integral_elem_comp {x : T}
(h : (g.comp f).is_integral_elem x) : g.is_integral_elem x :=
let ⟨p, ⟨hp, hp'⟩⟩ := h in ⟨p.map f, monic_map f hp, by rwa ← eval₂_map at hp'⟩
lemma ring_hom.is_integral_tower_top_of_is_integral (h : (g.comp f).is_integral) : g.is_integral :=
λ x, ring_hom.is_integral_elem_of_is_integral_elem_comp f g (h x)
/-- If `R → A → B` is an algebra tower,
then if the entire tower is an integral extension so is `A → B`. -/
lemma is_integral_tower_top_of_is_integral {x : B} (h : is_integral R x) : is_integral A x :=
begin
rcases h with ⟨p, ⟨hp, hp'⟩⟩,
refine ⟨p.map (algebra_map R A), ⟨monic_map (algebra_map R A) hp, _⟩⟩,
rw [is_scalar_tower.algebra_map_eq R A B, ← eval₂_map] at hp',
exact hp',
end
lemma ring_hom.is_integral_quotient_of_is_integral {I : ideal S} (hf : f.is_integral) :
(ideal.quotient_map I f le_rfl).is_integral :=
begin
rintros ⟨x⟩,
obtain ⟨p, ⟨p_monic, hpx⟩⟩ := hf x,
refine ⟨p.map (ideal.quotient.mk _), ⟨monic_map _ p_monic, _⟩⟩,
simpa only [hom_eval₂, eval₂_map] using congr_arg (ideal.quotient.mk I) hpx
end
lemma is_integral_quotient_of_is_integral {I : ideal A} (hRA : is_integral R A) :
is_integral (I.comap (algebra_map R A)).quotient I.quotient :=
(algebra_map R A).is_integral_quotient_of_is_integral hRA
lemma is_integral_quotient_map_iff {I : ideal S} :
(ideal.quotient_map I f le_rfl).is_integral ↔
((ideal.quotient.mk I).comp f : R →+* I.quotient).is_integral :=
begin
let g := ideal.quotient.mk (I.comap f),
have := ideal.quotient_map_comp_mk le_rfl,
refine ⟨λ h, _, λ h, ring_hom.is_integral_tower_top_of_is_integral g _ (this ▸ h)⟩,
refine this ▸ ring_hom.is_integral_trans g (ideal.quotient_map I f le_rfl) _ h,
exact ring_hom.is_integral_of_surjective g ideal.quotient.mk_surjective,
end
/-- If the integral extension `R → S` is injective, and `S` is a field, then `R` is also a field. -/
lemma is_field_of_is_integral_of_is_field {R S : Type*} [integral_domain R] [integral_domain S]
[algebra R S] (H : is_integral R S) (hRS : function.injective (algebra_map R S))
(hS : is_field S) : is_field R :=
begin
refine ⟨⟨0, 1, zero_ne_one⟩, mul_comm, λ a ha, _⟩,
-- Let `a_inv` be the inverse of `algebra_map R S a`,
-- then we need to show that `a_inv` is of the form `algebra_map R S b`.
obtain ⟨a_inv, ha_inv⟩ := hS.mul_inv_cancel (λ h, ha (hRS (trans h (ring_hom.map_zero _).symm))),
-- Let `p : polynomial R` be monic with root `a_inv`,
-- and `q` be `p` with coefficients reversed (so `q(a) = q'(a) * a + 1`).
-- We claim that `q(a) = 0`, so `-q'(a)` is the inverse of `a`.
obtain ⟨p, p_monic, hp⟩ := H a_inv,
use -∑ (i : ℕ) in finset.range p.nat_degree, (p.coeff i) * a ^ (p.nat_degree - i - 1),
-- `q(a) = 0`, because multiplying everything with `a_inv^n` gives `p(a_inv) = 0`.
-- TODO: this could be a lemma for `polynomial.reverse`.
have hq : ∑ (i : ℕ) in finset.range (p.nat_degree + 1), (p.coeff i) * a ^ (p.nat_degree - i) = 0,
{ apply (algebra_map R S).injective_iff.mp hRS,
have a_inv_ne_zero : a_inv ≠ 0 := right_ne_zero_of_mul (mt ha_inv.symm.trans one_ne_zero),
refine (mul_eq_zero.mp _).resolve_right (pow_ne_zero p.nat_degree a_inv_ne_zero),
rw [eval₂_eq_sum_range] at hp,
rw [ring_hom.map_sum, finset.sum_mul],
refine (finset.sum_congr rfl (λ i hi, _)).trans hp,
rw [ring_hom.map_mul, mul_assoc],
congr,
have : a_inv ^ p.nat_degree = a_inv ^ (p.nat_degree - i) * a_inv ^ i,
{ rw [← pow_add a_inv, nat.sub_add_cancel (nat.le_of_lt_succ (finset.mem_range.mp hi))] },
rw [ring_hom.map_pow, this, ← mul_assoc, ← mul_pow, ha_inv, one_pow, one_mul] },
-- Since `q(a) = 0` and `q(a) = q'(a) * a + 1`, we have `a * -q'(a) = 1`.
-- TODO: we could use a lemma for `polynomial.div_X` here.
rw [finset.sum_range_succ_comm, p_monic.coeff_nat_degree, one_mul, nat.sub_self, pow_zero,
add_eq_zero_iff_eq_neg, eq_comm] at hq,
rw [mul_comm, ← neg_mul_eq_neg_mul, finset.sum_mul],
convert hq using 2,
refine finset.sum_congr rfl (λ i hi, _),
have : 1 ≤ p.nat_degree - i := nat.le_sub_left_of_add_le (finset.mem_range.mp hi),
rw [mul_assoc, ← pow_succ', nat.sub_add_cancel this]
end
end algebra
section
local attribute [instance] subset.comm_ring algebra.of_is_subring
theorem integral_closure_idem {R : Type*} {A : Type*} [comm_ring R] [comm_ring A] [algebra R A] :
integral_closure (integral_closure R A : set A) A = ⊥ :=
eq_bot_iff.2 $ λ x hx, algebra.mem_bot.2
⟨⟨x, @is_integral_trans _ _ _ _ _ _ _ _ (integral_closure R A).algebra
_ integral_closure.is_integral x hx⟩, rfl⟩
end
section integral_domain
variables {R S : Type*} [comm_ring R] [integral_domain S] [algebra R S]
instance : integral_domain (integral_closure R S) :=
infer_instance
end integral_domain
|
78f4391e89dbde4140223fffc48ae7b186971cbf | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/order/positive/ring.lean | 32bb2e3103b14903e21df71331953e6ae47cc66d | [
"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 | 4,735 | lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import algebra.order.ring.defs
import algebra.ring.inj_surj
/-!
# Algebraic structures on the set of positive numbers
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define various instances (`add_semigroup`, `ordered_comm_monoid` etc) on the
type `{x : R // 0 < x}`. In each case we try to require the weakest possible typeclass
assumptions on `R` but possibly, there is a room for improvements.
-/
open function
namespace positive
variables {M R K : Type*}
section add_basic
variables [add_monoid M] [preorder M] [covariant_class M M (+) (<)]
instance : has_add {x : M // 0 < x} := ⟨λ x y, ⟨x + y, add_pos x.2 y.2⟩⟩
@[simp, norm_cast] lemma coe_add (x y : {x : M // 0 < x}) : ↑(x + y) = (x + y : M) := rfl
instance : add_semigroup {x : M // 0 < x} := subtype.coe_injective.add_semigroup _ coe_add
instance {M : Type*} [add_comm_monoid M] [preorder M] [covariant_class M M (+) (<)] :
add_comm_semigroup {x : M // 0 < x} :=
subtype.coe_injective.add_comm_semigroup _ coe_add
instance {M : Type*} [add_left_cancel_monoid M] [preorder M] [covariant_class M M (+) (<)] :
add_left_cancel_semigroup {x : M // 0 < x} :=
subtype.coe_injective.add_left_cancel_semigroup _ coe_add
instance {M : Type*} [add_right_cancel_monoid M] [preorder M] [covariant_class M M (+) (<)] :
add_right_cancel_semigroup {x : M // 0 < x} :=
subtype.coe_injective.add_right_cancel_semigroup _ coe_add
instance covariant_class_add_lt : covariant_class {x : M // 0 < x} {x : M // 0 < x} (+) (<) :=
⟨λ x y z hyz, subtype.coe_lt_coe.1 $ add_lt_add_left hyz _⟩
instance covariant_class_swap_add_lt [covariant_class M M (swap (+)) (<)] :
covariant_class {x : M // 0 < x} {x : M // 0 < x} (swap (+)) (<) :=
⟨λ x y z hyz, subtype.coe_lt_coe.1 $ add_lt_add_right hyz _⟩
instance contravariant_class_add_lt [contravariant_class M M (+) (<)] :
contravariant_class {x : M // 0 < x} {x : M // 0 < x} (+) (<) :=
⟨λ x y z h, subtype.coe_lt_coe.1 $ lt_of_add_lt_add_left h⟩
instance contravariant_class_swap_add_lt [contravariant_class M M (swap (+)) (<)] :
contravariant_class {x : M // 0 < x} {x : M // 0 < x} (swap (+)) (<) :=
⟨λ x y z h, subtype.coe_lt_coe.1 $ lt_of_add_lt_add_right h⟩
instance contravariant_class_add_le [contravariant_class M M (+) (≤)] :
contravariant_class {x : M // 0 < x} {x : M // 0 < x} (+) (≤) :=
⟨λ x y z h, subtype.coe_le_coe.1 $ le_of_add_le_add_left h⟩
instance contravariant_class_swap_add_le [contravariant_class M M (swap (+)) (≤)] :
contravariant_class {x : M // 0 < x} {x : M // 0 < x} (swap (+)) (≤) :=
⟨λ x y z h, subtype.coe_le_coe.1 $ le_of_add_le_add_right h⟩
end add_basic
instance covariant_class_add_le [add_monoid M] [partial_order M] [covariant_class M M (+) (<)] :
covariant_class {x : M // 0 < x} {x : M // 0 < x} (+) (≤) :=
⟨λ x, strict_mono.monotone $ λ _ _ h, add_lt_add_left h _⟩
section mul
variables [strict_ordered_semiring R]
instance : has_mul {x : R // 0 < x} := ⟨λ x y, ⟨x * y, mul_pos x.2 y.2⟩⟩
@[simp] lemma coe_mul (x y : {x : R // 0 < x}) : ↑(x * y) = (x * y : R) := rfl
instance : has_pow {x : R // 0 < x} ℕ := ⟨λ x n, ⟨x ^ n, pow_pos x.2 n⟩⟩
@[simp] lemma coe_pow (x : {x : R // 0 < x}) (n : ℕ) : ↑(x ^ n) = (x ^ n : R) := rfl
instance : semigroup {x : R // 0 < x} := subtype.coe_injective.semigroup coe coe_mul
instance : distrib {x : R // 0 < x} := subtype.coe_injective.distrib _ coe_add coe_mul
instance [nontrivial R] : has_one {x : R // 0 < x} := ⟨⟨1, one_pos⟩⟩
@[simp] lemma coe_one [nontrivial R] : ((1 : {x : R // 0 < x}) : R) = 1 := rfl
instance [nontrivial R] : monoid {x : R // 0 < x} :=
subtype.coe_injective.monoid _ coe_one coe_mul coe_pow
end mul
section mul_comm
instance [strict_ordered_comm_semiring R] [nontrivial R] : ordered_comm_monoid {x : R // 0 < x} :=
{ mul_le_mul_left := λ x y hxy c, subtype.coe_le_coe.1 $ mul_le_mul_of_nonneg_left hxy c.2.le,
.. subtype.partial_order _,
.. subtype.coe_injective.comm_monoid (coe : {x : R // 0 < x} → R) coe_one coe_mul coe_pow }
/-- If `R` is a nontrivial linear ordered commutative semiring, then `{x : R // 0 < x}` is a linear
ordered cancellative commutative monoid. -/
instance [linear_ordered_comm_semiring R] : linear_ordered_cancel_comm_monoid {x : R // 0 < x} :=
{ le_of_mul_le_mul_left := λ a b c h, subtype.coe_le_coe.1 $ (mul_le_mul_left a.2).1 h,
.. subtype.linear_order _, .. positive.subtype.ordered_comm_monoid }
end mul_comm
end positive
|
35bcc29ab5b0c0d23f5dd2486813b9b9f25cbcba | 1b8f093752ba748c5ca0083afef2959aaa7dace5 | /src/category_theory/adjunctions/comparisons.lean | b9882860332ecd78d7b841264a752d594cdb52cf | [] | no_license | khoek/lean-category-theory | 7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386 | 63dcb598e9270a3e8b56d1769eb4f825a177cd95 | refs/heads/master | 1,585,251,725,759 | 1,539,344,445,000 | 1,539,344,445,000 | 145,281,070 | 0 | 0 | null | 1,534,662,376,000 | 1,534,662,376,000 | null | UTF-8 | Lean | false | false | 4,971 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan, Scott Morrison
import category_theory.adjunctions
import category_theory.adjunctions.hom_adjunction
-- FIXME why do we need this here?
@[obviously] meta def obviously_3 := tactic.tidy { tactics := extended_tidy_tactics }
open category_theory
namespace category_theory.adjunctions
universes u v u₁ v₁ u₂ v₂ u₃ v₃ u₄ v₄
-- TODO If these are really necessary, move them to category_theory/products.lean
section
variables {A : Type u₁} [𝒜 : category.{u₁ v₁} A] {B : Type u₂} [ℬ : category.{u₂ v₂} B] {C : Type u₃} [𝒞 : category.{u₃ v₃} C] {D : Type u₄} [𝒟 : category.{u₄ v₄} D]
include 𝒜 ℬ 𝒞 𝒟
@[simp,search] lemma prod_obj' (F : A ⥤ B) (G : C ⥤ D) (a : A) (c : C) : (functor.prod F G).obj (a, c) = (F a, G c) := rfl
@[simp,search] lemma prod_app' {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟹ G) (β : H ⟹ I) (a : A) (c : C) : (nat_trans.prod α β).app (a, c) = (α a, β c) := rfl
end
variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₁} [𝒟 : category.{u₁ v₁} D]
include 𝒞 𝒟
variables {L : C ⥤ D} {R : D ⥤ C}
@[reducible] private def Adjunction_to_HomAdjunction_morphism (A : L ⊣ R)
: ((functor.prod L.op (functor.id D)) ⋙ (functor.hom D)) ⟹
(functor.prod (functor.id (Cᵒᵖ)) R) ⋙ (functor.hom C) :=
{ app := λ P,
-- We need to construct the map from D.Hom (L P.1) P.2 to C.Hom P.1 (R P.2)
λ f, (A.unit P.1) ≫ (R.map f) }
@[reducible] private def Adjunction_to_HomAdjunction_inverse (A : L ⊣ R)
: (functor.prod (functor.id (Cᵒᵖ)) R) ⋙ (functor.hom C) ⟹
((functor.prod L.op (functor.id D)) ⋙ (functor.hom D)) :=
{ app := λ P,
-- We need to construct the map back to D.Hom (L P.1) P.2 from C.Hom P.1 (R P.2)
λ f, (L.map f) ≫ (A.counit P.2) }
def Adjunction_to_HomAdjunction (A : L ⊣ R) : hom_adjunction L R :=
{ hom := Adjunction_to_HomAdjunction_morphism A,
inv := Adjunction_to_HomAdjunction_inverse A }
@[simp,search] lemma mate_of_L (A : hom_adjunction L R) {X Y : C} (f : X ⟶ Y) : (((A.hom) (X, L X)) (𝟙 (L X))) ≫
(R.map (L.map f))
= ((A.hom) (X, L Y)) (L.map f) :=
begin
have p := @nat_trans.naturality _ _ _ _ _ _ A.hom (X, L X) (X, L Y) (𝟙 X, L.map f),
have q := congr_fun p (L.map (𝟙 X)),
obviously,
erw category_theory.functor.map_id at q, -- FIXME why doesn't simp do this
obviously,
end
@[simp,search] lemma mate_of_L' (A : hom_adjunction L R) {X Y : C} (f : X ⟶ Y) : f ≫ (((A.hom) (Y, L Y)) (𝟙 (L Y)))
= ((A.hom) (X, L Y)) (L.map f) :=
begin
have p := @nat_trans.naturality _ _ _ _ _ _ A.hom (Y, L Y) (X, L Y) (f, 𝟙 (L Y)),
have q := congr_fun p (L.map (𝟙 Y)),
obviously,
end
@[simp,search] lemma mate_of_R (A : hom_adjunction L R) {X Y : D} (f : X ⟶ Y) : (L.map (R.map f)) ≫ (((A.inv) (R Y, Y)) (𝟙 (R Y)))
= ((A.inv) (R X, Y)) (R.map f) :=
begin
have p := @nat_trans.naturality _ _ _ _ _ _ A.inv (R Y, Y) (R X, Y) (R.map f, 𝟙 Y),
have q := congr_fun p (R.map (𝟙 Y)),
tidy,
end
@[simp,search] lemma mate_of_R' (A : hom_adjunction L R) {X Y : D} (f : X ⟶ Y) : (((A.inv) (R X, X)) (𝟙 (R X))) ≫ f =
((A.inv) (R X, Y)) (R.map f) :=
begin
have p := @nat_trans.naturality _ _ _ _ _ _ A.inv (R X, X) (R X, Y) (𝟙 (R X), f),
have q := congr_fun p (R.map (𝟙 X)),
obviously,
end
private def counit_from_HomAdjunction (A : hom_adjunction L R) : (R ⋙ L) ⟹ (functor.id _) :=
{ app := λ X : D, (A.inv (R X, X)) (𝟙 (R X)) }
private def unit_from_HomAdjunction (A : hom_adjunction L R) : (functor.id _) ⟹ (L ⋙ R) :=
{ app := λ X : C, (A.hom (X, L X)) (𝟙 (L X)) }
-- PROJECT
-- def HomAdjunction_to_Adjunction {L : C ⥤ D} {R : D ⥤ C} (A : hom_adjunction L R) : L ⊣ R :=
-- {
-- unit := unit_from_HomAdjunction A,
-- counit := counit_from_HomAdjunction A,
-- triangle_1 := begin
-- tidy,
-- -- have p1 := A.witness_2,
-- -- have p2 := congr_arg NaturalTransformation.components p1,
-- -- have p3 := congr_fun p2 (((R +> X) : C), L +> (R +> X)),
-- -- have p4 := congr_fun p3 (𝟙 (R +> X)),
-- -- tidy,
-- sorry
-- end,
-- triangle_2 := sorry
-- }
-- def Adjunctions_agree (L : C ⥤ D) (R : D ⥤ C) : equiv (L ⊣ R) (hom_adjunction L R) :=
-- { to_fun := Adjunction_to_HomAdjunction,
-- inv_fun := HomAdjunction_to_Adjunction,
-- left_inv := begin sorry end,
-- right_inv := begin
-- sorry,
-- -- this is just another lemma about mates; perhaps the same as the one we use above.
-- end }
end category_theory.adjunctions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.