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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d9648ddac8fa3eb0753942b6ef293f50691cc53c | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/playground/opts.lean | 0c449a9f3dea14a332a4769313ff4be0a2177b23 | [
"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 | 911 | lean | import init.lean.options
open Lean
@[init] def initRegopt1 : IO Unit :=
registerOption `myNatOpt {defValue := DataValue.ofNat 0, descr := "my Nat option" }
@[init] def initRegopt2 : IO Unit :=
registerOption `myBoolOpt {defValue := DataValue.ofBool true, descr := "my Bool option" }
@[init] def initRegopt3 : IO Unit :=
registerOption `myStringOpt {defValue := DataValue.ofString "", descr := "my String option" }
@[init] def initRegopt4 : IO Unit :=
registerOption `myIntOpt {defValue := DataValue.ofInt 0, descr := "my Int option" }
def main : IO Unit :=
do getOptionDescr `myNatOpt >>= IO.println,
getOptionDescr `myBoolOpt >>= IO.println,
getOptionDescr `myIntOpt >>= IO.println,
let os : Options := {},
os β setOptionFromString os "myNatOpt = 100",
IO.println (os.getNat `myNatOpt),
os β setOptionFromString os "myIntOpt = -20",
IO.println (os.getInt `myIntOpt),
pure ()
|
09cae4951fcce4626b95da46cfc9e0f1b5d5e5a9 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/algebra/subalgebra/basic.lean | 39a8100e375747d3d8918697aeeda2254dba7f6a | [
"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 | 44,505 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import algebra.algebra.basic
import data.set.Union_lift
/-!
# Subalgebras over Commutative Semiring
In this file we define `subalgebra`s and the usual operations on them (`map`, `comap'`).
More lemmas about `adjoin` can be found in `ring_theory.adjoin`.
-/
universes u u' v w w'
open_locale big_operators
set_option old_structure_cmd true
/-- A subalgebra is a sub(semi)ring that includes the range of `algebra_map`. -/
structure subalgebra (R : Type u) (A : Type v)
[comm_semiring R] [semiring A] [algebra R A] extends subsemiring A : Type v :=
(algebra_map_mem' : β r, algebra_map R A r β carrier)
(zero_mem' := (algebra_map R A).map_zero βΈ algebra_map_mem' 0)
(one_mem' := (algebra_map R A).map_one βΈ algebra_map_mem' 1)
/-- Reinterpret a `subalgebra` as a `subsemiring`. -/
add_decl_doc subalgebra.to_subsemiring
namespace subalgebra
variables {R' : Type u'} {R : Type u} {A : Type v} {B : Type w} {C : Type w'}
variables [comm_semiring R]
variables [semiring A] [algebra R A] [semiring B] [algebra R B] [semiring C] [algebra R C]
include R
instance : set_like (subalgebra R A) A :=
{ coe := subalgebra.carrier,
coe_injective' := Ξ» p q h, by cases p; cases q; congr' }
instance : subsemiring_class (subalgebra R A) A :=
{ add_mem := add_mem',
mul_mem := mul_mem',
one_mem := one_mem',
zero_mem := zero_mem' }
@[simp]
lemma mem_carrier {s : subalgebra R A} {x : A} : x β s.carrier β x β s := iff.rfl
@[ext] theorem ext {S T : subalgebra R A} (h : β x : A, x β S β x β T) : S = T := set_like.ext h
@[simp] lemma mem_to_subsemiring {S : subalgebra R A} {x} : x β S.to_subsemiring β x β S := iff.rfl
@[simp] lemma coe_to_subsemiring (S : subalgebra R A) : (βS.to_subsemiring : set A) = S := rfl
theorem to_subsemiring_injective :
function.injective (to_subsemiring : subalgebra R A β subsemiring A) :=
Ξ» S T h, ext $ Ξ» x, by rw [β mem_to_subsemiring, β mem_to_subsemiring, h]
theorem to_subsemiring_inj {S U : subalgebra R A} : S.to_subsemiring = U.to_subsemiring β S = U :=
to_subsemiring_injective.eq_iff
/-- Copy of a subalgebra with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (S : subalgebra R A) (s : set A) (hs : s = βS) : subalgebra R A :=
{ carrier := s,
add_mem' := hs.symm βΈ S.add_mem',
mul_mem' := hs.symm βΈ S.mul_mem',
algebra_map_mem' := hs.symm βΈ S.algebra_map_mem' }
@[simp] lemma coe_copy (S : subalgebra R A) (s : set A) (hs : s = βS) :
(S.copy s hs : set A) = s := rfl
lemma copy_eq (S : subalgebra R A) (s : set A) (hs : s = βS) : S.copy s hs = S :=
set_like.coe_injective hs
variables (S : subalgebra R A)
theorem algebra_map_mem (r : R) : algebra_map R A r β S :=
S.algebra_map_mem' r
theorem srange_le : (algebra_map R A).srange β€ S.to_subsemiring :=
Ξ» x β¨r, hrβ©, hr βΈ S.algebra_map_mem r
theorem range_subset : set.range (algebra_map R A) β S :=
Ξ» x β¨r, hrβ©, hr βΈ S.algebra_map_mem r
theorem range_le : set.range (algebra_map R A) β€ S :=
S.range_subset
theorem smul_mem {x : A} (hx : x β S) (r : R) : r β’ x β S :=
(algebra.smul_def r x).symm βΈ mul_mem (S.algebra_map_mem r) hx
protected theorem one_mem : (1 : A) β S := one_mem S
protected theorem mul_mem {x y : A} (hx : x β S) (hy : y β S) : x * y β S := mul_mem hx hy
protected theorem pow_mem {x : A} (hx : x β S) (n : β) : x ^ n β S := pow_mem hx n
protected theorem zero_mem : (0 : A) β S := zero_mem S
protected theorem add_mem {x y : A} (hx : x β S) (hy : y β S) : x + y β S := add_mem hx hy
protected theorem nsmul_mem {x : A} (hx : x β S) (n : β) : n β’ x β S := nsmul_mem hx n
protected theorem coe_nat_mem (n : β) : (n : A) β S := coe_nat_mem S n
protected theorem list_prod_mem {L : list A} (h : β x β L, x β S) : L.prod β S := list_prod_mem h
protected theorem list_sum_mem {L : list A} (h : β x β L, x β S) : L.sum β S := list_sum_mem h
protected theorem multiset_sum_mem {m : multiset A} (h : β x β m, x β S) : m.sum β S :=
multiset_sum_mem m h
protected theorem sum_mem {ΞΉ : Type w} {t : finset ΞΉ} {f : ΞΉ β A} (h : β x β t, f x β S) :
β x in t, f x β S :=
sum_mem h
protected theorem multiset_prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) {m : multiset A} (h : β x β m, x β S) : m.prod β S :=
multiset_prod_mem m h
protected theorem prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) {ΞΉ : Type w} {t : finset ΞΉ} {f : ΞΉ β A}
(h : β x β t, f x β S) : β x in t, f x β S :=
prod_mem h
instance {R A : Type*} [comm_ring R] [ring A] [algebra R A] : subring_class (subalgebra R A) A :=
{ neg_mem := Ξ» S x hx, neg_one_smul R x βΈ S.smul_mem hx _,
.. subalgebra.subsemiring_class }
protected theorem neg_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x : A} (hx : x β S) : -x β S :=
neg_mem hx
protected theorem sub_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x y : A} (hx : x β S) (hy : y β S) : x - y β S :=
sub_mem hx hy
protected theorem zsmul_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x : A} (hx : x β S) (n : β€) : n β’ x β S :=
zsmul_mem hx n
protected theorem coe_int_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) (n : β€) : (n : A) β S :=
coe_int_mem S n
/-- The projection from a subalgebra of `A` to an additive submonoid of `A`. -/
def to_add_submonoid {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
(S : subalgebra R A) : add_submonoid A :=
S.to_subsemiring.to_add_submonoid
/-- The projection from a subalgebra of `A` to a submonoid of `A`. -/
def to_submonoid {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
(S : subalgebra R A) : submonoid A :=
S.to_subsemiring.to_submonoid
/-- A subalgebra over a ring is also a `subring`. -/
def to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) :
subring A :=
{ neg_mem' := Ξ» _, S.neg_mem,
.. S.to_subsemiring }
@[simp] lemma mem_to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} {x} : x β S.to_subring β x β S := iff.rfl
@[simp] lemma coe_to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
(S : subalgebra R A) : (βS.to_subring : set A) = S := rfl
theorem to_subring_injective {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] :
function.injective (to_subring : subalgebra R A β subring A) :=
Ξ» S T h, ext $ Ξ» x, by rw [β mem_to_subring, β mem_to_subring, h]
theorem to_subring_inj {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S U : subalgebra R A} : S.to_subring = U.to_subring β S = U :=
to_subring_injective.eq_iff
instance : inhabited S := β¨(0 : S.to_subsemiring)β©
section
/-! `subalgebra`s inherit structure from their `subsemiring` / `semiring` coercions. -/
instance to_semiring {R A}
[comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) :
semiring S := S.to_subsemiring.to_semiring
instance to_comm_semiring {R A}
[comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) :
comm_semiring S := S.to_subsemiring.to_comm_semiring
instance to_ring {R A}
[comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) :
ring S := S.to_subring.to_ring
instance to_comm_ring {R A}
[comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) :
comm_ring S := S.to_subring.to_comm_ring
instance to_ordered_semiring {R A}
[comm_semiring R] [ordered_semiring A] [algebra R A] (S : subalgebra R A) :
ordered_semiring S := S.to_subsemiring.to_ordered_semiring
instance to_ordered_comm_semiring {R A}
[comm_semiring R] [ordered_comm_semiring A] [algebra R A] (S : subalgebra R A) :
ordered_comm_semiring S := S.to_subsemiring.to_ordered_comm_semiring
instance to_ordered_ring {R A}
[comm_ring R] [ordered_ring A] [algebra R A] (S : subalgebra R A) :
ordered_ring S := S.to_subring.to_ordered_ring
instance to_ordered_comm_ring {R A}
[comm_ring R] [ordered_comm_ring A] [algebra R A] (S : subalgebra R A) :
ordered_comm_ring S := S.to_subring.to_ordered_comm_ring
instance to_linear_ordered_semiring {R A}
[comm_semiring R] [linear_ordered_semiring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_semiring S := S.to_subsemiring.to_linear_ordered_semiring
/-! There is no `linear_ordered_comm_semiring`. -/
instance to_linear_ordered_ring {R A}
[comm_ring R] [linear_ordered_ring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_ring S := S.to_subring.to_linear_ordered_ring
instance to_linear_ordered_comm_ring {R A}
[comm_ring R] [linear_ordered_comm_ring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_comm_ring S := S.to_subring.to_linear_ordered_comm_ring
end
/-- Convert a `subalgebra` to `submodule` -/
def to_submodule : submodule R A :=
{ carrier := S,
zero_mem' := (0:S).2,
add_mem' := Ξ» x y hx hy, (β¨x, hxβ© + β¨y, hyβ© : S).2,
smul_mem' := Ξ» c x hx, (algebra.smul_def c x).symm βΈ
(β¨algebra_map R A c, S.range_le β¨c, rflβ©β© * β¨x, hxβ©:S).2 }
@[simp] lemma mem_to_submodule {x} : x β S.to_submodule β x β S := iff.rfl
@[simp] lemma coe_to_submodule (S : subalgebra R A) : (βS.to_submodule : set A) = S := rfl
theorem to_submodule_injective :
function.injective (to_submodule : subalgebra R A β submodule R A) :=
Ξ» S T h, ext $ Ξ» x, by rw [β mem_to_submodule, β mem_to_submodule, h]
theorem to_submodule_inj {S U : subalgebra R A} : S.to_submodule = U.to_submodule β S = U :=
to_submodule_injective.eq_iff
section
/-! `subalgebra`s inherit structure from their `submodule` coercions. -/
instance module' [semiring R'] [has_scalar R' R] [module R' A] [is_scalar_tower R' R A] :
module R' S :=
S.to_submodule.module'
instance : module R S := S.module'
instance [semiring R'] [has_scalar R' R] [module R' A] [is_scalar_tower R' R A] :
is_scalar_tower R' R S :=
S.to_submodule.is_scalar_tower
instance algebra' [comm_semiring R'] [has_scalar R' R] [algebra R' A]
[is_scalar_tower R' R A] : algebra R' S :=
{ commutes' := Ξ» c x, subtype.eq $ algebra.commutes _ _,
smul_def' := Ξ» c x, subtype.eq $ algebra.smul_def _ _,
.. (algebra_map R' A).cod_srestrict S.to_subsemiring $ Ξ» x, begin
rw [algebra.algebra_map_eq_smul_one, βsmul_one_smul R x (1 : A),
βalgebra.algebra_map_eq_smul_one],
exact algebra_map_mem S _,
end }
instance : algebra R S := S.algebra'
end
instance no_zero_smul_divisors_bot [no_zero_smul_divisors R A] : no_zero_smul_divisors R S :=
β¨Ξ» c x h,
have c = 0 β¨ (x : A) = 0,
from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h),
this.imp_right (@subtype.ext_iff _ _ x 0).mprβ©
protected lemma coe_add (x y : S) : (β(x + y) : A) = βx + βy := rfl
protected lemma coe_mul (x y : S) : (β(x * y) : A) = βx * βy := rfl
protected lemma coe_zero : ((0 : S) : A) = 0 := rfl
protected lemma coe_one : ((1 : S) : A) = 1 := rfl
protected lemma coe_neg {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} (x : S) : (β(-x) : A) = -βx := rfl
protected lemma coe_sub {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} (x y : S) : (β(x - y) : A) = βx - βy := rfl
@[simp, norm_cast] lemma coe_smul [semiring R'] [has_scalar R' R] [module R' A]
[is_scalar_tower R' R A] (r : R') (x : S) : (β(r β’ x) : A) = r β’ βx := rfl
@[simp, norm_cast] lemma coe_algebra_map [comm_semiring R'] [has_scalar R' R] [algebra R' A]
[is_scalar_tower R' R A] (r : R') :
β(algebra_map R' S r) = algebra_map R' A r := rfl
protected lemma coe_pow (x : S) (n : β) : (β(x^n) : A) = (βx)^n := submonoid_class.coe_pow x n
protected lemma coe_eq_zero {x : S} : (x : A) = 0 β x = 0 := add_submonoid_class.coe_eq_zero
protected lemma coe_eq_one {x : S} : (x : A) = 1 β x = 1 := submonoid_class.coe_eq_one
-- todo: standardize on the names these morphisms
-- compare with submodule.subtype
/-- Embedding of a subalgebra into the algebra. -/
def val : S ββ[R] A :=
by refine_struct { to_fun := (coe : S β A) }; intros; refl
@[simp] lemma coe_val : (S.val : S β A) = coe := rfl
lemma val_apply (x : S) : S.val x = (x : A) := rfl
@[simp] lemma to_subsemiring_subtype : S.to_subsemiring.subtype = (S.val : S β+* A) :=
rfl
@[simp] lemma to_subring_subtype {R A : Type*} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) : S.to_subring.subtype = (S.val : S β+* A) :=
rfl
/-- Linear equivalence between `S : submodule R A` and `S`. Though these types are equal,
we define it as a `linear_equiv` to avoid type equalities. -/
def to_submodule_equiv (S : subalgebra R A) : S.to_submodule ββ[R] S :=
linear_equiv.of_eq _ _ rfl
/-- Transport a subalgebra via an algebra homomorphism. -/
def map (S : subalgebra R A) (f : A ββ[R] B) : subalgebra R B :=
{ algebra_map_mem' := Ξ» r, f.commutes r βΈ set.mem_image_of_mem _ (S.algebra_map_mem r),
.. S.to_subsemiring.map (f : A β+* B) }
lemma map_mono {Sβ Sβ : subalgebra R A} {f : A ββ[R] B} :
Sβ β€ Sβ β Sβ.map f β€ Sβ.map f :=
set.image_subset f
lemma map_injective {Sβ Sβ : subalgebra R A} (f : A ββ[R] B)
(hf : function.injective f) (ih : Sβ.map f = Sβ.map f) : Sβ = Sβ :=
ext $ set.ext_iff.1 $ set.image_injective.2 hf $ set.ext $ set_like.ext_iff.mp ih
@[simp] lemma map_id (S : subalgebra R A) : S.map (alg_hom.id R A) = S :=
set_like.coe_injective $ set.image_id _
lemma map_map (S : subalgebra R A) (g : B ββ[R] C) (f : A ββ[R] B) :
(S.map f).map g = S.map (g.comp f) :=
set_like.coe_injective $ set.image_image _ _ _
lemma mem_map {S : subalgebra R A} {f : A ββ[R] B} {y : B} :
y β map S f β β x β S, f x = y :=
subsemiring.mem_map
lemma map_to_submodule {S : subalgebra R A} {f : A ββ[R] B} :
(S.map f).to_submodule = S.to_submodule.map f.to_linear_map :=
set_like.coe_injective rfl
lemma map_to_subsemiring {S : subalgebra R A} {f : A ββ[R] B} :
(S.map f).to_subsemiring = S.to_subsemiring.map f.to_ring_hom :=
set_like.coe_injective rfl
@[simp] lemma coe_map (S : subalgebra R A) (f : A ββ[R] B) :
(S.map f : set B) = f '' S :=
rfl
/-- Preimage of a subalgebra under an algebra homomorphism. -/
def comap' (S : subalgebra R B) (f : A ββ[R] B) : subalgebra R A :=
{ algebra_map_mem' := Ξ» r, show f (algebra_map R A r) β S,
from (f.commutes r).symm βΈ S.algebra_map_mem r,
.. S.to_subsemiring.comap (f : A β+* B) }
theorem map_le {S : subalgebra R A} {f : A ββ[R] B} {U : subalgebra R B} :
map S f β€ U β S β€ comap' U f :=
set.image_subset_iff
lemma gc_map_comap (f : A ββ[R] B) : galois_connection (Ξ» S, map S f) (Ξ» S, comap' S f) :=
Ξ» S U, map_le
@[simp] lemma mem_comap (S : subalgebra R B) (f : A ββ[R] B) (x : A) :
x β S.comap' f β f x β S :=
iff.rfl
@[simp, norm_cast] lemma coe_comap (S : subalgebra R B) (f : A ββ[R] B) :
(S.comap' f : set A) = f β»ΒΉ' (S : set B) :=
rfl
instance no_zero_divisors {R A : Type*} [comm_semiring R] [semiring A] [no_zero_divisors A]
[algebra R A] (S : subalgebra R A) : no_zero_divisors S :=
S.to_subsemiring.no_zero_divisors
instance is_domain {R A : Type*} [comm_ring R] [ring A] [is_domain A] [algebra R A]
(S : subalgebra R A) : is_domain S :=
subring.is_domain S.to_subring
end subalgebra
namespace submodule
variables {R A : Type*} [comm_semiring R] [semiring A] [algebra R A]
variables (p : submodule R A)
/-- A submodule containing `1` and closed under multiplication is a subalgebra. -/
def to_subalgebra (p : submodule R A) (h_one : (1 : A) β p)
(h_mul : β x y, x β p β y β p β x * y β p) : subalgebra R A :=
{ mul_mem' := h_mul,
algebra_map_mem' := Ξ» r, begin
rw algebra.algebra_map_eq_smul_one,
exact p.smul_mem _ h_one,
end,
..p}
@[simp] lemma mem_to_subalgebra {p : submodule R A} {h_one h_mul} {x} :
x β p.to_subalgebra h_one h_mul β x β p := iff.rfl
@[simp] lemma coe_to_subalgebra (p : submodule R A) (h_one h_mul) :
(p.to_subalgebra h_one h_mul : set A) = p := rfl
@[simp] lemma to_subalgebra_mk (s : set A) (h0 hadd hsmul h1 hmul) :
(submodule.mk s hadd h0 hsmul : submodule R A).to_subalgebra h1 hmul =
subalgebra.mk s @hmul h1 @hadd h0
(Ξ» r, by { rw algebra.algebra_map_eq_smul_one, exact hsmul r h1 }) := rfl
@[simp] lemma to_subalgebra_to_submodule (p : submodule R A) (h_one h_mul) :
(p.to_subalgebra h_one h_mul).to_submodule = p :=
set_like.coe_injective rfl
@[simp] lemma _root_.subalgebra.to_submodule_to_subalgebra (S : subalgebra R A) :
S.to_submodule.to_subalgebra S.one_mem (Ξ» _ _, S.mul_mem) = S :=
set_like.coe_injective rfl
end submodule
namespace alg_hom
variables {R' : Type u'} {R : Type u} {A : Type v} {B : Type w} {C : Type w'}
variables [comm_semiring R]
variables [semiring A] [algebra R A] [semiring B] [algebra R B] [semiring C] [algebra R C]
variables (Ο : A ββ[R] B)
/-- Range of an `alg_hom` as a subalgebra. -/
protected def range (Ο : A ββ[R] B) : subalgebra R B :=
{ algebra_map_mem' := Ξ» r, β¨algebra_map R A r, Ο.commutes rβ©,
.. Ο.to_ring_hom.srange }
@[simp] lemma mem_range (Ο : A ββ[R] B) {y : B} :
y β Ο.range β β x, Ο x = y := ring_hom.mem_srange
theorem mem_range_self (Ο : A ββ[R] B) (x : A) : Ο x β Ο.range := Ο.mem_range.2 β¨x, rflβ©
@[simp] lemma coe_range (Ο : A ββ[R] B) : (Ο.range : set B) = set.range Ο :=
by { ext, rw [set_like.mem_coe, mem_range], refl }
theorem range_comp (f : A ββ[R] B) (g : B ββ[R] C) : (g.comp f).range = f.range.map g :=
set_like.coe_injective (set.range_comp g f)
theorem range_comp_le_range (f : A ββ[R] B) (g : B ββ[R] C) : (g.comp f).range β€ g.range :=
set_like.coe_mono (set.range_comp_subset_range f g)
/-- Restrict the codomain of an algebra homomorphism. -/
def cod_restrict (f : A ββ[R] B) (S : subalgebra R B) (hf : β x, f x β S) : A ββ[R] S :=
{ commutes' := Ξ» r, subtype.eq $ f.commutes r,
.. ring_hom.cod_srestrict (f : A β+* B) S.to_subsemiring hf }
@[simp] lemma val_comp_cod_restrict (f : A ββ[R] B) (S : subalgebra R B) (hf : β x, f x β S) :
S.val.comp (f.cod_restrict S hf) = f :=
alg_hom.ext $ Ξ» _, rfl
@[simp] lemma coe_cod_restrict (f : A ββ[R] B) (S : subalgebra R B) (hf : β x, f x β S) (x : A) :
β(f.cod_restrict S hf x) = f x := rfl
theorem injective_cod_restrict (f : A ββ[R] B) (S : subalgebra R B) (hf : β x, f x β S) :
function.injective (f.cod_restrict S hf) β function.injective f :=
β¨Ξ» H x y hxy, H $ subtype.eq hxy, Ξ» H x y hxy, H (congr_arg subtype.val hxy : _)β©
/-- Restrict the codomain of a alg_hom `f` to `f.range`.
This is the bundled version of `set.range_factorization`. -/
@[reducible] def range_restrict (f : A ββ[R] B) : A ββ[R] f.range :=
f.cod_restrict f.range f.mem_range_self
/-- The equalizer of two R-algebra homomorphisms -/
def equalizer (Ο Ο : A ββ[R] B) : subalgebra R A :=
{ carrier := {a | Ο a = Ο a},
add_mem' := Ξ» x y (hx : Ο x = Ο x) (hy : Ο y = Ο y),
by rw [set.mem_set_of_eq, Ο.map_add, Ο.map_add, hx, hy],
mul_mem' := Ξ» x y (hx : Ο x = Ο x) (hy : Ο y = Ο y),
by rw [set.mem_set_of_eq, Ο.map_mul, Ο.map_mul, hx, hy],
algebra_map_mem' := Ξ» x,
by rw [set.mem_set_of_eq, alg_hom.commutes, alg_hom.commutes] }
@[simp] lemma mem_equalizer (Ο Ο : A ββ[R] B) (x : A) :
x β Ο.equalizer Ο β Ο x = Ο x := iff.rfl
/-- The range of a morphism of algebras is a fintype, if the domain is a fintype.
Note that this instance can cause a diamond with `subtype.fintype` if `B` is also a fintype. -/
instance fintype_range [fintype A] [decidable_eq B] (Ο : A ββ[R] B) : fintype Ο.range :=
set.fintype_range Ο
end alg_hom
namespace alg_equiv
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
/-- Restrict an algebra homomorphism with a left inverse to an algebra isomorphism to its range.
This is a computable alternative to `alg_equiv.of_injective`. -/
def of_left_inverse
{g : B β A} {f : A ββ[R] B} (h : function.left_inverse g f) :
A ββ[R] f.range :=
{ to_fun := f.range_restrict,
inv_fun := g β f.range.val,
left_inv := h,
right_inv := Ξ» x, subtype.ext $
let β¨x', hx'β© := f.mem_range.mp x.prop in
show f (g x) = x, by rw [βhx', h x'],
..f.range_restrict }
@[simp] lemma of_left_inverse_apply
{g : B β A} {f : A ββ[R] B} (h : function.left_inverse g f) (x : A) :
β(of_left_inverse h x) = f x := rfl
@[simp] lemma of_left_inverse_symm_apply
{g : B β A} {f : A ββ[R] B} (h : function.left_inverse g f) (x : f.range) :
(of_left_inverse h).symm x = g x := rfl
/-- Restrict an injective algebra homomorphism to an algebra isomorphism -/
noncomputable def of_injective (f : A ββ[R] B) (hf : function.injective f) :
A ββ[R] f.range :=
of_left_inverse (classical.some_spec hf.has_left_inverse)
@[simp] lemma of_injective_apply (f : A ββ[R] B) (hf : function.injective f) (x : A) :
β(of_injective f hf x) = f x := rfl
/-- Restrict an algebra homomorphism between fields to an algebra isomorphism -/
noncomputable def of_injective_field {E F : Type*} [division_ring E] [semiring F]
[nontrivial F] [algebra R E] [algebra R F] (f : E ββ[R] F) : E ββ[R] f.range :=
of_injective f f.to_ring_hom.injective
/-- Given an equivalence `e : A ββ[R] B` of `R`-algebras and a subalgebra `S` of `A`,
`subalgebra_map` is the induced equivalence between `S` and `S.map e` -/
@[simps] def subalgebra_map (e : A ββ[R] B) (S : subalgebra R A) :
S ββ[R] (S.map e.to_alg_hom) :=
{ commutes' := Ξ» r, by { ext, simp },
..e.to_ring_equiv.subsemiring_map S.to_subsemiring }
end alg_equiv
namespace algebra
variables (R : Type u) {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
/-- The minimal subalgebra that includes `s`. -/
def adjoin (s : set A) : subalgebra R A :=
{ algebra_map_mem' := Ξ» r, subsemiring.subset_closure $ or.inl β¨r, rflβ©,
.. subsemiring.closure (set.range (algebra_map R A) βͺ s) }
variables {R}
protected lemma gc : galois_connection (adjoin R : set A β subalgebra R A) coe :=
Ξ» s S, β¨Ξ» H, le_trans (le_trans (set.subset_union_right _ _) subsemiring.subset_closure) H,
Ξ» H, show subsemiring.closure (set.range (algebra_map R A) βͺ s) β€ S.to_subsemiring,
from subsemiring.closure_le.2 $ set.union_subset S.range_subset Hβ©
/-- Galois insertion between `adjoin` and `coe`. -/
protected def gi : galois_insertion (adjoin R : set A β subalgebra R A) coe :=
{ choice := Ξ» s hs, (adjoin R s).copy s $ le_antisymm (algebra.gc.le_u_l s) hs,
gc := algebra.gc,
le_l_u := Ξ» S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_rfl,
choice_eq := Ξ» _ _, subalgebra.copy_eq _ _ _ }
instance : complete_lattice (subalgebra R A) :=
galois_insertion.lift_complete_lattice algebra.gi
@[simp]
lemma coe_top : (β(β€ : subalgebra R A) : set A) = set.univ := rfl
@[simp] lemma mem_top {x : A} : x β (β€ : subalgebra R A) :=
set.mem_univ x
@[simp] lemma top_to_submodule : (β€ : subalgebra R A).to_submodule = β€ := rfl
@[simp] lemma top_to_subsemiring : (β€ : subalgebra R A).to_subsemiring = β€ := rfl
@[simp] lemma top_to_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A] :
(β€ : subalgebra R A).to_subring = β€ := rfl
@[simp] lemma to_submodule_eq_top {S : subalgebra R A} : S.to_submodule = β€ β S = β€ :=
subalgebra.to_submodule_injective.eq_iff' top_to_submodule
@[simp] lemma to_subsemiring_eq_top {S : subalgebra R A} : S.to_subsemiring = β€ β S = β€ :=
subalgebra.to_subsemiring_injective.eq_iff' top_to_subsemiring
@[simp] lemma to_subring_eq_top {R A : Type*} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} : S.to_subring = β€ β S = β€ :=
subalgebra.to_subring_injective.eq_iff' top_to_subring
lemma mem_sup_left {S T : subalgebra R A} : β {x : A}, x β S β x β S β T :=
show S β€ S β T, from le_sup_left
lemma mem_sup_right {S T : subalgebra R A} : β {x : A}, x β T β x β S β T :=
show T β€ S β T, from le_sup_right
lemma mul_mem_sup {S T : subalgebra R A} {x y : A} (hx : x β S) (hy : y β T) :
x * y β S β T :=
(S β T).mul_mem (mem_sup_left hx) (mem_sup_right hy)
lemma map_sup (f : A ββ[R] B) (S T : subalgebra R A) : (S β T).map f = S.map f β T.map f :=
(subalgebra.gc_map_comap f).l_sup
@[simp, norm_cast]
lemma coe_inf (S T : subalgebra R A) : (β(S β T) : set A) = S β© T := rfl
@[simp]
lemma mem_inf {S T : subalgebra R A} {x : A} : x β S β T β x β S β§ x β T := iff.rfl
@[simp] lemma inf_to_submodule (S T : subalgebra R A) :
(S β T).to_submodule = S.to_submodule β T.to_submodule := rfl
@[simp] lemma inf_to_subsemiring (S T : subalgebra R A) :
(S β T).to_subsemiring = S.to_subsemiring β T.to_subsemiring := rfl
@[simp, norm_cast]
lemma coe_Inf (S : set (subalgebra R A)) : (β(Inf S) : set A) = β s β S, βs := Inf_image
lemma mem_Inf {S : set (subalgebra R A)} {x : A} : x β Inf S β β p β S, x β p :=
by simp only [β set_like.mem_coe, coe_Inf, set.mem_Interβ]
@[simp] lemma Inf_to_submodule (S : set (subalgebra R A)) :
(Inf S).to_submodule = Inf (subalgebra.to_submodule '' S) :=
set_like.coe_injective $ by simp
@[simp] lemma Inf_to_subsemiring (S : set (subalgebra R A)) :
(Inf S).to_subsemiring = Inf (subalgebra.to_subsemiring '' S) :=
set_like.coe_injective $ by simp
@[simp, norm_cast]
lemma coe_infi {ΞΉ : Sort*} {S : ΞΉ β subalgebra R A} : (β(β¨
i, S i) : set A) = β i, S i :=
by simp [infi]
lemma mem_infi {ΞΉ : Sort*} {S : ΞΉ β subalgebra R A} {x : A} : (x β β¨
i, S i) β β i, x β S i :=
by simp only [infi, mem_Inf, set.forall_range_iff]
@[simp] lemma infi_to_submodule {ΞΉ : Sort*} (S : ΞΉ β subalgebra R A) :
(β¨
i, S i).to_submodule = β¨
i, (S i).to_submodule :=
set_like.coe_injective $ by simp
instance : inhabited (subalgebra R A) := β¨β₯β©
theorem mem_bot {x : A} : x β (β₯ : subalgebra R A) β x β set.range (algebra_map R A) :=
suffices (of_id R A).range = (β₯ : subalgebra R A),
by { rw [β this, βset_like.mem_coe, alg_hom.coe_range], refl },
le_bot_iff.mp (Ξ» x hx, subalgebra.range_le _ ((of_id R A).coe_range βΈ hx))
theorem to_submodule_bot : (β₯ : subalgebra R A).to_submodule = R β 1 :=
by { ext x, simp [mem_bot, -set.singleton_one, submodule.mem_span_singleton, algebra.smul_def] }
@[simp] theorem coe_bot : ((β₯ : subalgebra R A) : set A) = set.range (algebra_map R A) :=
by simp [set.ext_iff, algebra.mem_bot]
theorem eq_top_iff {S : subalgebra R A} :
S = β€ β β x : A, x β S :=
β¨Ξ» h x, by rw h; exact mem_top, Ξ» h, by ext x; exact β¨Ξ» _, mem_top, Ξ» _, h xβ©β©
@[simp] theorem range_id : (alg_hom.id R A).range = β€ :=
set_like.coe_injective set.range_id
@[simp] theorem map_top (f : A ββ[R] B) : subalgebra.map (β€ : subalgebra R A) f = f.range :=
set_like.coe_injective set.image_univ
@[simp] theorem map_bot (f : A ββ[R] B) : subalgebra.map (β₯ : subalgebra R A) f = β₯ :=
set_like.coe_injective $
by simp only [β set.range_comp, (β), algebra.coe_bot, subalgebra.coe_map, f.commutes]
@[simp] theorem comap_top (f : A ββ[R] B) : subalgebra.comap' (β€ : subalgebra R B) f = β€ :=
eq_top_iff.2 $ Ξ» x, mem_top
/-- `alg_hom` to `β€ : subalgebra R A`. -/
def to_top : A ββ[R] (β€ : subalgebra R A) :=
(alg_hom.id R A).cod_restrict β€ (Ξ» _, mem_top)
theorem surjective_algebra_map_iff :
function.surjective (algebra_map R A) β (β€ : subalgebra R A) = β₯ :=
β¨Ξ» h, eq_bot_iff.2 $ Ξ» y _, let β¨x, hxβ© := h y in hx βΈ subalgebra.algebra_map_mem _ _,
Ξ» h y, algebra.mem_bot.1 $ eq_bot_iff.1 h (algebra.mem_top : y β _)β©
theorem bijective_algebra_map_iff {R A : Type*} [field R] [semiring A] [nontrivial A]
[algebra R A] :
function.bijective (algebra_map R A) β (β€ : subalgebra R A) = β₯ :=
β¨Ξ» h, surjective_algebra_map_iff.1 h.2,
Ξ» h, β¨(algebra_map R A).injective, surjective_algebra_map_iff.2 hβ©β©
/-- The bottom subalgebra is isomorphic to the base ring. -/
noncomputable def bot_equiv_of_injective (h : function.injective (algebra_map R A)) :
(β₯ : subalgebra R A) ββ[R] R :=
alg_equiv.symm $ alg_equiv.of_bijective (algebra.of_id R _)
β¨Ξ» x y hxy, h (congr_arg subtype.val hxy : _),
Ξ» β¨y, hyβ©, let β¨x, hxβ© := algebra.mem_bot.1 hy in β¨x, subtype.eq hxβ©β©
/-- The bottom subalgebra is isomorphic to the field. -/
@[simps symm_apply]
noncomputable def bot_equiv (F R : Type*) [field F] [semiring R] [nontrivial R] [algebra F R] :
(β₯ : subalgebra F R) ββ[F] F :=
bot_equiv_of_injective (ring_hom.injective _)
end algebra
namespace subalgebra
open algebra
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
variables (S : subalgebra R A)
/-- The top subalgebra is isomorphic to the algebra.
This is the algebra version of `submodule.top_equiv`. -/
@[simps] def top_equiv : (β€ : subalgebra R A) ββ[R] A :=
alg_equiv.of_alg_hom (subalgebra.val β€) to_top rfl $ alg_hom.ext $ Ξ» _, subtype.ext rfl
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_subsingleton [subsingleton A] : subsingleton (subalgebra R A) :=
β¨Ξ» B C, ext (Ξ» x, by { simp only [subsingleton.elim x 0, zero_mem B, zero_mem C] })β©
/--
For performance reasons this is not an instance. If you need this instance, add
```
local attribute [instance] alg_hom.subsingleton subalgebra.subsingleton_of_subsingleton
```
in the section that needs it.
-/
-- TODO[gh-6025]: make this an instance once safe to do so
lemma _root_.alg_hom.subsingleton [subsingleton (subalgebra R A)] : subsingleton (A ββ[R] B) :=
β¨Ξ» f g, alg_hom.ext $ Ξ» a,
have a β (β₯ : subalgebra R A) := subsingleton.elim (β€ : subalgebra R A) β₯ βΈ mem_top,
let β¨x, hxβ© := set.mem_range.mp (mem_bot.mp this) in
hx βΈ (f.commutes _).trans (g.commutes _).symmβ©
-- TODO[gh-6025]: make this an instance once safe to do so
lemma _root_.alg_equiv.subsingleton_left [subsingleton (subalgebra R A)] :
subsingleton (A ββ[R] B) :=
begin
haveI : subsingleton (A ββ[R] B) := alg_hom.subsingleton,
exact β¨Ξ» f g, alg_equiv.ext
(Ξ» x, alg_hom.ext_iff.mp (subsingleton.elim f.to_alg_hom g.to_alg_hom) x)β©,
end
-- TODO[gh-6025]: make this an instance once safe to do so
lemma _root_.alg_equiv.subsingleton_right [subsingleton (subalgebra R B)] :
subsingleton (A ββ[R] B) :=
begin
haveI : subsingleton (B ββ[R] A) := alg_equiv.subsingleton_left,
exact β¨Ξ» f g, eq.trans (alg_equiv.symm_symm _).symm
(by rw [subsingleton.elim f.symm g.symm, alg_equiv.symm_symm])β©
end
lemma range_val : S.val.range = S :=
ext $ set.ext_iff.1 $ S.val.coe_range.trans subtype.range_val
instance : unique (subalgebra R R) :=
{ uniq :=
begin
intro S,
refine le_antisymm (Ξ» r hr, _) bot_le,
simp only [set.mem_range, mem_bot, id.map_eq_self, exists_apply_eq_apply, default],
end
.. algebra.subalgebra.inhabited }
/-- The map `S β T` when `S` is a subalgebra contained in the subalgebra `T`.
This is the subalgebra version of `submodule.of_le`, or `subring.inclusion` -/
def inclusion {S T : subalgebra R A} (h : S β€ T) : S ββ[R] T :=
{ to_fun := set.inclusion h,
map_one' := rfl,
map_add' := Ξ» _ _, rfl,
map_mul' := Ξ» _ _, rfl,
map_zero' := rfl,
commutes' := Ξ» _, rfl }
lemma inclusion_injective {S T : subalgebra R A} (h : S β€ T) :
function.injective (inclusion h) :=
Ξ» _ _, subtype.ext β subtype.mk.inj
@[simp] lemma inclusion_self {S : subalgebra R A}:
inclusion (le_refl S) = alg_hom.id R S :=
alg_hom.ext $ Ξ» x, subtype.ext rfl
@[simp] lemma inclusion_mk {S T : subalgebra R A} (h : S β€ T) (x : A) (hx : x β S) :
inclusion h β¨x, hxβ© = β¨x, h hxβ© := rfl
lemma inclusion_right {S T : subalgebra R A} (h : S β€ T) (x : T)
(m : (x : A) β S) : inclusion h β¨x, mβ© = x := subtype.ext rfl
@[simp] lemma inclusion_inclusion {S T U : subalgebra R A} (hst : S β€ T) (htu : T β€ U)
(x : S) : inclusion htu (inclusion hst x) = inclusion (le_trans hst htu) x :=
subtype.ext rfl
@[simp] lemma coe_inclusion {S T : subalgebra R A} (h : S β€ T) (s : S) :
(inclusion h s : A) = s := rfl
/-- Two subalgebras that are equal are also equivalent as algebras.
This is the `subalgebra` version of `linear_equiv.of_eq` and `equiv.set.of_eq`. -/
@[simps apply]
def equiv_of_eq (S T : subalgebra R A) (h : S = T) : S ββ[R] T :=
{ to_fun := Ξ» x, β¨x, h βΈ x.2β©,
inv_fun := Ξ» x, β¨x, h.symm βΈ x.2β©,
map_mul' := Ξ» _ _, rfl,
commutes' := Ξ» _, rfl,
.. linear_equiv.of_eq _ _ (congr_arg to_submodule h) }
@[simp] lemma equiv_of_eq_symm (S T : subalgebra R A) (h : S = T) :
(equiv_of_eq S T h).symm = equiv_of_eq T S h.symm :=
rfl
@[simp] lemma equiv_of_eq_rfl (S : subalgebra R A) :
equiv_of_eq S S rfl = alg_equiv.refl :=
by { ext, refl }
@[simp] lemma equiv_of_eq_trans (S T U : subalgebra R A) (hST : S = T) (hTU : T = U) :
(equiv_of_eq S T hST).trans (equiv_of_eq T U hTU) = equiv_of_eq S U (trans hST hTU) :=
rfl
section prod
variables (Sβ : subalgebra R B)
/-- The product of two subalgebras is a subalgebra. -/
def prod : subalgebra R (A Γ B) :=
{ carrier := (S : set A) ΓΛ’ (Sβ : set B),
algebra_map_mem' := Ξ» r, β¨algebra_map_mem _ _, algebra_map_mem _ _β©,
.. S.to_subsemiring.prod Sβ.to_subsemiring }
@[simp] lemma coe_prod :
(prod S Sβ : set (A Γ B)) = (S : set A) ΓΛ’ (Sβ : set B):= rfl
lemma prod_to_submodule :
(S.prod Sβ).to_submodule = S.to_submodule.prod Sβ.to_submodule := rfl
@[simp] lemma mem_prod {S : subalgebra R A} {Sβ : subalgebra R B} {x : A Γ B} :
x β prod S Sβ β x.1 β S β§ x.2 β Sβ := set.mem_prod
@[simp] lemma prod_top : (prod β€ β€ : subalgebra R (A Γ B)) = β€ :=
by ext; simp
lemma prod_mono {S T : subalgebra R A} {Sβ Tβ : subalgebra R B} :
S β€ T β Sβ β€ Tβ β prod S Sβ β€ prod T Tβ := set.prod_mono
@[simp] lemma prod_inf_prod {S T : subalgebra R A} {Sβ Tβ : subalgebra R B} :
S.prod Sβ β T.prod Tβ = (S β T).prod (Sβ β Tβ) :=
set_like.coe_injective set.prod_inter_prod
end prod
section supr_lift
variables {ΞΉ : Type*}
lemma coe_supr_of_directed [nonempty ΞΉ] {S : ΞΉ β subalgebra R A}
(dir : directed (β€) S) : β(supr S) = β i, (S i : set A) :=
let K : subalgebra R A :=
{ carrier := β i, (S i),
mul_mem' := Ξ» x y hx hy,
let β¨i, hiβ© := set.mem_Union.1 hx in
let β¨j, hjβ© := set.mem_Union.1 hy in
let β¨k, hik, hjkβ© := dir i j in
set.mem_Union.2 β¨k, subalgebra.mul_mem (S k) (hik hi) (hjk hj)β© ,
add_mem' := Ξ» x y hx hy,
let β¨i, hiβ© := set.mem_Union.1 hx in
let β¨j, hjβ© := set.mem_Union.1 hy in
let β¨k, hik, hjkβ© := dir i j in
set.mem_Union.2 β¨k, subalgebra.add_mem (S k) (hik hi) (hjk hj)β©,
algebra_map_mem' := Ξ» r, let i := @nonempty.some ΞΉ infer_instance in
set.mem_Union.2 β¨i, subalgebra.algebra_map_mem _ _β© } in
have supr S = K,
from le_antisymm (supr_le (Ξ» i, set.subset_Union (Ξ» i, β(S i)) i))
(set_like.coe_subset_coe.1
(set.Union_subset (Ξ» i, set_like.coe_subset_coe.2 (le_supr _ _)))),
this.symm βΈ rfl
/-- Define an algebra homomorphism on a directed supremum of subalgebras by defining
it on each subalgebra, and proving that it agrees on the intersection of subalgebras. -/
noncomputable def supr_lift [nonempty ΞΉ]
(K : ΞΉ β subalgebra R A)
(dir : directed (β€) K)
(f : Ξ i, K i ββ[R] B)
(hf : β (i j : ΞΉ) (h : K i β€ K j), f i = (f j).comp (inclusion h))
(T : subalgebra R A) (hT : T = supr K) :
β₯T ββ[R] B :=
by subst hT; exact
{ to_fun := set.Union_lift (Ξ» i, β(K i)) (Ξ» i x, f i x)
(Ξ» i j x hxi hxj,
let β¨k, hik, hjkβ© := dir i j in
begin
rw [hf i k hik, hf j k hjk],
refl
end) β(supr K)
(by rw coe_supr_of_directed dir; refl),
map_one' := set.Union_lift_const _ (Ξ» _, 1) (Ξ» _, rfl) _ (by simp),
map_zero' := set.Union_lift_const _ (Ξ» _, 0) (Ξ» _, rfl) _ (by simp),
map_mul' := set.Union_lift_binary (coe_supr_of_directed dir) dir _
(Ξ» _, (*)) (Ξ» _ _ _, rfl) _ (by simp),
map_add' := set.Union_lift_binary (coe_supr_of_directed dir) dir _
(Ξ» _, (+)) (Ξ» _ _ _, rfl) _ (by simp),
commutes' := Ξ» r, set.Union_lift_const _ (Ξ» _, algebra_map _ _ r)
(Ξ» _, rfl) _ (Ξ» i, by erw [alg_hom.commutes (f i)]) }
variables [nonempty ΞΉ] {K : ΞΉ β subalgebra R A} {dir : directed (β€) K}
{f : Ξ i, K i ββ[R] B}
{hf : β (i j : ΞΉ) (h : K i β€ K j), f i = (f j).comp (inclusion h)}
{T : subalgebra R A} {hT : T = supr K}
@[simp] lemma supr_lift_inclusion {i : ΞΉ} (x : K i) (h : K i β€ T) :
supr_lift K dir f hf T hT (inclusion h x) = f i x :=
by subst T; exact set.Union_lift_inclusion _ _
@[simp] lemma supr_lift_comp_inclusion {i : ΞΉ} (h : K i β€ T) :
(supr_lift K dir f hf T hT).comp (inclusion h) = f i :=
by ext; simp
@[simp] lemma supr_lift_mk {i : ΞΉ} (x : K i) (hx : (x : A) β T) :
supr_lift K dir f hf T hT β¨x, hxβ© = f i x :=
by subst hT; exact set.Union_lift_mk x hx
lemma supr_lift_of_mem {i : ΞΉ} (x : T) (hx : (x : A) β K i) :
supr_lift K dir f hf T hT x = f i β¨x, hxβ© :=
by subst hT; exact set.Union_lift_of_mem x hx
end supr_lift
/-! ## Actions by `subalgebra`s
These are just copies of the definitions about `subsemiring` starting from
`subring.mul_action`.
-/
section actions
variables {Ξ± Ξ² : Type*}
/-- The action by a subalgebra is the action by the underlying algebra. -/
instance [has_scalar A Ξ±] (S : subalgebra R A) : has_scalar S Ξ± := S.to_subsemiring.has_scalar
lemma smul_def [has_scalar A Ξ±] {S : subalgebra R A} (g : S) (m : Ξ±) : g β’ m = (g : A) β’ m := rfl
instance smul_comm_class_left
[has_scalar A Ξ²] [has_scalar Ξ± Ξ²] [smul_comm_class A Ξ± Ξ²] (S : subalgebra R A) :
smul_comm_class S Ξ± Ξ² :=
S.to_subsemiring.smul_comm_class_left
instance smul_comm_class_right
[has_scalar Ξ± Ξ²] [has_scalar A Ξ²] [smul_comm_class Ξ± A Ξ²] (S : subalgebra R A) :
smul_comm_class Ξ± S Ξ² :=
S.to_subsemiring.smul_comm_class_right
/-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/
instance is_scalar_tower_left
[has_scalar Ξ± Ξ²] [has_scalar A Ξ±] [has_scalar A Ξ²] [is_scalar_tower A Ξ± Ξ²] (S : subalgebra R A) :
is_scalar_tower S Ξ± Ξ² :=
S.to_subsemiring.is_scalar_tower
instance [has_scalar A Ξ±] [has_faithful_scalar A Ξ±] (S : subalgebra R A) :
has_faithful_scalar S Ξ± :=
S.to_subsemiring.has_faithful_scalar
/-- The action by a subalgebra is the action by the underlying algebra. -/
instance [mul_action A Ξ±] (S : subalgebra R A) : mul_action S Ξ± :=
S.to_subsemiring.mul_action
/-- The action by a subalgebra is the action by the underlying algebra. -/
instance [add_monoid Ξ±] [distrib_mul_action A Ξ±] (S : subalgebra R A) : distrib_mul_action S Ξ± :=
S.to_subsemiring.distrib_mul_action
/-- The action by a subalgebra is the action by the underlying algebra. -/
instance [has_zero Ξ±] [smul_with_zero A Ξ±] (S : subalgebra R A) : smul_with_zero S Ξ± :=
S.to_subsemiring.smul_with_zero
/-- The action by a subalgebra is the action by the underlying algebra. -/
instance [has_zero Ξ±] [mul_action_with_zero A Ξ±] (S : subalgebra R A) : mul_action_with_zero S Ξ± :=
S.to_subsemiring.mul_action_with_zero
/-- The action by a subalgebra is the action by the underlying algebra. -/
instance module_left [add_comm_monoid Ξ±] [module A Ξ±] (S : subalgebra R A) : module S Ξ± :=
S.to_subsemiring.module
/-- The action by a subalgebra is the action by the underlying algebra. -/
instance to_algebra {R A : Type*} [comm_semiring R] [comm_semiring A] [semiring Ξ±]
[algebra R A] [algebra A Ξ±] (S : subalgebra R A) : algebra S Ξ± :=
algebra.of_subsemiring S.to_subsemiring
lemma algebra_map_eq {R A : Type*} [comm_semiring R] [comm_semiring A] [semiring Ξ±]
[algebra R A] [algebra A Ξ±] (S : subalgebra R A) :
algebra_map S Ξ± = (algebra_map A Ξ±).comp S.val := rfl
@[simp] lemma srange_algebra_map {R A : Type*} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) :
(algebra_map S A).srange = S.to_subsemiring :=
by rw [algebra_map_eq, algebra.id.map_eq_id, ring_hom.id_comp, β to_subsemiring_subtype,
subsemiring.srange_subtype]
@[simp] lemma range_algebra_map {R A : Type*} [comm_ring R] [comm_ring A]
[algebra R A] (S : subalgebra R A) :
(algebra_map S A).range = S.to_subring :=
by rw [algebra_map_eq, algebra.id.map_eq_id, ring_hom.id_comp, β to_subring_subtype,
subring.range_subtype]
instance no_zero_smul_divisors_top [no_zero_divisors A] (S : subalgebra R A) :
no_zero_smul_divisors S A :=
β¨Ξ» c x h,
have (c : A) = 0 β¨ x = 0,
from eq_zero_or_eq_zero_of_mul_eq_zero h,
this.imp_left (@subtype.ext_iff _ _ c 0).mprβ©
end actions
section center
lemma _root_.set.algebra_map_mem_center (r : R) : algebra_map R A r β set.center A :=
by simp [algebra.commutes, set.mem_center_iff]
variables (R A)
/-- The center of an algebra is the set of elements which commute with every element. They form a
subalgebra. -/
def center : subalgebra R A :=
{ algebra_map_mem' := set.algebra_map_mem_center,
.. subsemiring.center A }
lemma coe_center : (center R A : set A) = set.center A := rfl
@[simp] lemma center_to_subsemiring :
(center R A).to_subsemiring = subsemiring.center A :=
rfl
@[simp] lemma center_to_subring (R A : Type*) [comm_ring R] [ring A] [algebra R A] :
(center R A).to_subring = subring.center A :=
rfl
@[simp] lemma center_eq_top (A : Type*) [comm_semiring A] [algebra R A] : center R A = β€ :=
set_like.coe_injective (set.center_eq_univ A)
variables {R A}
instance : comm_semiring (center R A) := subsemiring.center.comm_semiring
instance {A : Type*} [ring A] [algebra R A] : comm_ring (center R A) := subring.center.comm_ring
lemma mem_center_iff {a : A} : a β center R A β β (b : A), b*a = a*b := iff.rfl
end center
section centralizer
@[simp]
lemma _root_.set.algebra_map_mem_centralizer
{s : set A} (r : R) : algebra_map R A r β s.centralizer :=
Ξ» a h, (algebra.commutes _ _).symm
variables (R)
/-- The centralizer of a set as a subalgebra. -/
def centralizer (s : set A) : subalgebra R A :=
{ algebra_map_mem' := set.algebra_map_mem_centralizer,
..subsemiring.centralizer s, }
@[simp, norm_cast]
lemma coe_centralizer (s : set A) : (centralizer R s : set A) = s.centralizer := rfl
lemma mem_centralizer_iff {s : set A} {z : A} :
z β centralizer R s β β g β s, g * z = z * g :=
iff.rfl
lemma centralizer_le (s t : set A) (h : s β t) :
centralizer R t β€ centralizer R s :=
set.centralizer_subset h
@[simp]
lemma centralizer_univ : centralizer R set.univ = center R A :=
set_like.ext' (set.centralizer_univ A)
end centralizer
end subalgebra
section nat
variables {R : Type*} [semiring R]
/-- A subsemiring is a `β`-subalgebra. -/
def subalgebra_of_subsemiring (S : subsemiring R) : subalgebra β R :=
{ algebra_map_mem' := Ξ» i, coe_nat_mem S i,
.. S }
@[simp] lemma mem_subalgebra_of_subsemiring {x : R} {S : subsemiring R} :
x β subalgebra_of_subsemiring S β x β S :=
iff.rfl
end nat
section int
variables {R : Type*} [ring R]
/-- A subring is a `β€`-subalgebra. -/
def subalgebra_of_subring (S : subring R) : subalgebra β€ R :=
{ algebra_map_mem' := Ξ» i, int.induction_on i S.zero_mem
(Ξ» i ih, S.add_mem ih S.one_mem)
(Ξ» i ih, show ((-i - 1 : β€) : R) β S, by { rw [int.cast_sub, int.cast_one],
exact S.sub_mem ih S.one_mem }),
.. S }
variables {S : Type*} [semiring S]
@[simp] lemma mem_subalgebra_of_subring {x : R} {S : subring R} :
x β subalgebra_of_subring S β x β S :=
iff.rfl
end int
|
54fc51cbb420e123d1b48188fca3f6a730fa2293 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/run/meta_level1.lean | fd5bd761f27145b3cfc0f8504ae4866daf65703a | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 973 | lean | import system.io
open io
variable [io.interface]
#eval do pp (level.max (level.succ level.zero) (level.param `foo)), put_str "\n"
#eval level.normalize (level.succ (level.max (level.max level.zero (level.succ level.zero)) (level.param `lβ)))
#eval level.imax (level.mvar `m) (level.of_nat 10)
#eval if level.zero = level.zero then "eq" else "neq"
#eval level.occurs (level.param `l2) (level.max (level.param `l1) (level.param `l2))
#eval level.occurs (level.param `l3) (level.max (level.param `l1) (level.param `l2))
#eval level.eqv (level.max (level.param `l1) (level.param `l2)) (level.max (level.param `l2) (level.param `l1))
#eval level.eqv (level.max (level.param `l1) (level.param `l2)) (level.max (level.param `l2) (level.param `l2))
#eval level.has_param (level.max (level.param `l1) (level.param `l2)) `l1
#eval level.has_param (level.max (level.param `l1) (level.param `l2)) `l2
#eval level.has_param (level.max (level.param `l1) (level.param `l2)) `l3
|
134619c4130461ca21bb12a795173fef6786dd6b | 6094e25ea0b7699e642463b48e51b2ead6ddc23f | /tests/lean/run/cases_bug.lean | 98ab7452a9240d451051bfce4d7e14274d57d289 | [
"Apache-2.0"
] | permissive | gbaz/lean | a7835c4e3006fbbb079e8f8ffe18aacc45adebfb | a501c308be3acaa50a2c0610ce2e0d71becf8032 | refs/heads/master | 1,611,198,791,433 | 1,451,339,111,000 | 1,451,339,111,000 | 48,713,797 | 0 | 0 | null | 1,451,338,939,000 | 1,451,338,939,000 | null | UTF-8 | Lean | false | false | 137 | lean | import logic.cast
theorem cast_heq : β {A B : Type} (H : A = B) (a : A), cast H a == a
| A A (eq.refl A) a := heq.of_eq (cast_refl a)
|
5d0412313e75b5a61b6d371a2ad2eb684962ecb4 | 50b3917f95cf9fe84639812ea0461b38f8f0dbe1 | /canonical_isomorphism/reid_barton.lean | f0c5ce81635a4a256887fdcdf321f8bb33aec95c | [] | no_license | roro47/xena | 6389bcd7dcf395656a2c85cfc90a4366e9b825bb | 237910190de38d6ff43694ffe3a9b68f79363e6c | refs/heads/master | 1,598,570,061,948 | 1,570,052,567,000 | 1,570,052,567,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,578 | lean | import data.equiv
import analysis.topology.topological_space
universes u v w
class transportable (f : Type u β Type v) :=
(on_equiv : Ξ {Ξ± Ξ² : Type u} (e : equiv Ξ± Ξ²), equiv (f Ξ±) (f Ξ²))
(on_refl : Ξ (Ξ± : Type u), on_equiv (equiv.refl Ξ±) = equiv.refl (f Ξ±))
(on_trans : Ξ {Ξ± Ξ² Ξ³ : Type u} (d : equiv Ξ± Ξ²) (e : equiv Ξ² Ξ³),
on_equiv (equiv.trans d e) = equiv.trans (on_equiv d) (on_equiv e))
def transport (f : Type u β Type v) [transportable f]
{Ξ± Ξ² : Type u} (e : equiv Ξ± Ξ²) :
equiv (f Ξ±) (f Ξ²) :=
transportable.on_equiv f e
class transportable2 {g : Type u β Type v} [transportable g] (f : Ξ Ξ± : Type u, g Ξ± β Type w) :=
(on_equiv : Ξ {Ξ± Ξ² : Type u} {x : g Ξ±} (e : equiv Ξ± Ξ²), equiv (f Ξ± x) (f Ξ² (transport g e x)))
/-
(on_refl : ...)
(on_trans : ...)
-/
def transport2 {g : Type u β Type v} [transportable g]
(f : Ξ Ξ± : Type u, g Ξ± β Type w) [transportable2 f]
{Ξ± Ξ² : Type u} {x : g Ξ±} (e : equiv Ξ± Ξ²) :
equiv (f Ξ± x) (f Ξ² (transport g e x)) :=
transportable2.on_equiv f e
-- autogenerate these
instance : transportable topological_space := sorry
instance : transportable2 t1_space := sorry
def is_homeomorphism {Ξ± Ξ² : Type u} [tΞ± : topological_space Ξ±] [tΞ² : topological_space Ξ²] (e : Ξ± β Ξ²) :=
tΞ² = transport topological_space e tΞ±
def homeomorphism_respects_t1 {Ξ± Ξ² : Type u} [tΞ± : topological_space Ξ±] [tΞ² : topological_space Ξ²]
(e : Ξ± β Ξ²) (h : is_homeomorphism e) :
t1_space Ξ± β t1_space Ξ² :=
by unfold is_homeomorphism at h; rw h; exact transport2 t1_space e
|
780b9f329cc7c8be5b2bb9a6f6030cf8e9b01c66 | 6b45072eb2b3db3ecaace2a7a0241ce81f815787 | /data/list/set.lean | 5170b6f215cec800725a1ebb3d9c46818e1a468b | [] | no_license | avigad/library_dev | 27b47257382667b5eb7e6476c4f5b0d685dd3ddc | 9d8ac7c7798ca550874e90fed585caad030bbfac | refs/heads/master | 1,610,452,468,791 | 1,500,712,839,000 | 1,500,713,478,000 | 69,311,142 | 1 | 0 | null | 1,474,942,903,000 | 1,474,942,902,000 | null | UTF-8 | Lean | false | false | 31,495 | lean | /-
Copyright (c) 2015 Leonardo de Moura. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad
Set-like operations on lists.
-/
import data.list.basic data.list.comb .basic .comb
open nat function decidable
universe variables uu vv
variables {Ξ± : Type uu} {Ξ² : Type vv}
namespace list
section insert
variable [decidable_eq Ξ±]
@[simp]
theorem insert_nil (a : Ξ±) : insert a nil = [a] := rfl
theorem insert.def (a : Ξ±) (l : list Ξ±) : insert a l = if a β l then l else concat l a := rfl
@[simp]
theorem insert_of_mem {a : Ξ±} {l : list Ξ±} (h : a β l) : insert a l = l :=
by rw [insert.def, if_pos h]
@[simp]
theorem insert_of_not_mem {a : Ξ±} {l : list Ξ±} (h : a β l) : insert a l = concat l a :=
by rw [insert.def, if_neg h]
@[simp]
theorem mem_insert_self (a : Ξ±) (l : list Ξ±) : a β insert a l :=
by by_cases a β l with h; simp [h]
@[simp]
theorem mem_insert_of_mem {a b : Ξ±} {l : list Ξ±} (h : a β l) : a β insert b l :=
by by_cases b β l with h'; simp [h, h']
theorem eq_or_mem_of_mem_insert {a b : Ξ±} {l : list Ξ±} (h : a β insert b l) : a = b β¨ a β l :=
if h' : b β l then
begin simp [h'] at h, simp [h] end
else
begin simp [h'] at h, assumption end
@[simp]
theorem mem_insert_iff (a b : Ξ±) (l : list Ξ±) : a β insert b l β a = b β¨ a β l :=
iff.intro eq_or_mem_of_mem_insert
(Ξ» h, or.elim h (begin intro h', simp [h'] end) mem_insert_of_mem)
@[simp]
theorem length_insert_of_mem {a : Ξ±} [decidable_eq Ξ±] {l : list Ξ±} (h : a β l) :
length (insert a l) = length l :=
by simp [h]
@[simp]
theorem length_insert_of_not_mem {a : Ξ±} [decidable_eq Ξ±] {l : list Ξ±} (h : a β l) :
length (insert a l) = length l + 1 :=
by simp [h]
theorem forall_mem_insert_of_forall_mem {p : Ξ± β Prop} {a : Ξ±} {l : list Ξ±}
(hβ : p a) (hβ : β x β l, p x) :
β x β insert a l, p x :=
if h : a β l then begin simp [h], exact hβ end
else begin simp [h], intros b hb, cases hb with hβ hβ, {rw hβ, assumption}, exact hβ _ hβ end
end insert
section erase
variable [decidable_eq Ξ±]
@[simp]
lemma erase_nil (a : Ξ±) : [].erase a = [] :=
rfl
lemma erase_cons (a b : Ξ±) (l : list Ξ±) : (b :: l).erase a = if b = a then l else b :: l.erase a :=
rfl
@[simp]
lemma erase_cons_head (a : Ξ±) (l : list Ξ±) : (a :: l).erase a = l :=
by simp [erase_cons, if_pos]
@[simp]
lemma erase_cons_tail {a b : Ξ±} (l : list Ξ±) (h : b β a) : (b::l).erase a = b :: l.erase a :=
by simp [erase_cons, if_neg, h]
@[simp]
lemma length_erase_of_mem {a : Ξ±} : β{l:list Ξ±}, a β l β length (l.erase a) = pred (length l)
| [] h := rfl
| [x] h := begin simp at h, simp [h] end
| (x::y::xs) h := if h' : x = a then
by simp [h', one_add]
else
have ainyxs : a β y::xs, from or_resolve_right h $ by cc,
by simp [h', length_erase_of_mem ainyxs, one_add]
@[simp]
lemma erase_of_not_mem {a : Ξ±} : β{l : list Ξ±}, a β l β l.erase a = l
| [] h := rfl
| (x::xs) h :=
have anex : x β a, from Ξ» aeqx : x = a, absurd (or.inl aeqx.symm) h,
have aninxs : a β xs, from Ξ» ainxs : a β xs, absurd (or.inr ainxs) h,
by simp [anex, erase_of_not_mem aninxs]
lemma erase_append_left {a : Ξ±} : β {lβ:list Ξ±} (lβ), a β lβ β (lβ++lβ).erase a = lβ.erase a ++ lβ
| [] lβ h := absurd h (not_mem_nil a)
| (x::xs) lβ h := if h' : x = a then by simp [h']
else
have a β xs, from mem_of_ne_of_mem (assume h, h' h.symm) h,
by simp [erase_append_left lβ this, h']
lemma erase_append_right {a : Ξ±} : β{lβ : list Ξ±} (lβ), a β lβ β (lβ++lβ).erase a = lβ ++ lβ.erase a
| [] lβ h := rfl
| (x::xs) lβ h := if h' : x = a then begin simp [h'] at h, contradiction end
else
have a β xs, from not_mem_of_not_mem_cons h,
by simp [erase_append_right lβ this, h']
lemma erase_sublist (a : Ξ±) : β(l : list Ξ±), l.erase a <+ l
| [] := sublist.refl nil
| (x :: xs) := if h : x = a then
by simp [h]
else
begin simp [h], apply cons_sublist_cons, apply erase_sublist xs end
lemma erase_subset (a : Ξ±) (l : list Ξ±) : l.erase a β l :=
subset_of_sublist (erase_sublist a l)
theorem mem_erase_of_ne_of_mem {a b : Ξ±} : β {l : list Ξ±}, a β b β a β l β a β l.erase b
| [] aneb anil := begin simp at anil, contradiction end
| (c :: l) aneb acl := if h : c = b then
begin simp [h, aneb] at acl, simp [h, acl] end
else
begin
simp [h], simp at acl, cases acl with h' h',
{ simp [h'] },
simp [mem_erase_of_ne_of_mem aneb h']
end
theorem mem_of_mem_erase {a b : Ξ±} : β{l:list Ξ±}, a β l.erase b β a β l
| [] h := begin simp at h, contradiction end
| (c :: l) h := if h' : c = b then
begin simp [h'] at h, simp [h] end
else
begin
simp [h'] at h, cases h with h'' h'',
{ simp [h''] },
simp [mem_of_mem_erase h'']
end
end erase
/- disjoint -/
section disjoint
def disjoint (lβ lβ : list Ξ±) : Prop := β β¦aβ¦, (a β lβ β a β lβ β false)
lemma disjoint_left {lβ lβ : list Ξ±} : disjoint lβ lβ β β {a}, a β lβ β a β lβ :=
Ξ» d, d
lemma disjoint_right {lβ lβ : list Ξ±} : disjoint lβ lβ β β {a}, a β lβ β a β lβ :=
Ξ» d a iβ iβ, d iβ iβ
lemma disjoint.comm {lβ lβ : list Ξ±} : disjoint lβ lβ β disjoint lβ lβ :=
Ξ» d a iβ iβ, d iβ iβ
lemma disjoint_of_subset_left {lβ lβ l : list Ξ±} : lβ β l β disjoint l lβ β disjoint lβ lβ :=
Ξ» ss d x xinlβ, d (ss xinlβ)
lemma disjoint_of_subset_right {lβ lβ l : list Ξ±} : lβ β l β disjoint lβ l β disjoint lβ lβ :=
Ξ» ss d x xinl xinlβ, d xinl (ss xinlβ)
lemma disjoint_of_disjoint_cons_left {a : Ξ±} {lβ lβ} : disjoint (a::lβ) lβ β disjoint lβ lβ :=
disjoint_of_subset_left (list.subset_cons _ _)
lemma disjoint_of_disjoint_cons_right {a : Ξ±} {lβ lβ} : disjoint lβ (a::lβ) β disjoint lβ lβ :=
disjoint_of_subset_right (list.subset_cons _ _)
lemma disjoint_nil_left (l : list Ξ±) : disjoint [] l :=
Ξ» a ab, absurd ab (not_mem_nil a)
lemma disjoint_nil_right (l : list Ξ±) : disjoint l [] :=
disjoint.comm (disjoint_nil_left l)
lemma disjoint_cons_of_not_mem_of_disjoint {a : Ξ±} {lβ lβ : list Ξ±} :
a β lβ β disjoint lβ lβ β disjoint (a::lβ) lβ :=
Ξ» nainlβ d x (xinalβ : x β a::lβ),
or.elim (eq_or_mem_of_mem_cons xinalβ)
(Ξ» xeqa : x = a, eq.symm xeqa βΈ nainlβ)
(Ξ» xinlβ : x β lβ, disjoint_left d xinlβ)
lemma disjoint_append_of_disjoint_left {lβ lβ l : list Ξ±} :
disjoint lβ l β disjoint lβ l β disjoint (lβ++lβ) l :=
Ξ» dβ dβ x h, or.elim (mem_or_mem_of_mem_append h) (@dβ x) (@dβ x)
lemma disjoint_of_disjoint_append_left_left {lβ lβ l : list Ξ±} : disjoint (lβ++lβ) l β disjoint lβ l :=
disjoint_of_subset_left (list.subset_append_left _ _)
lemma disjoint_of_disjoint_append_left_right {lβ lβ l : list Ξ±} : disjoint (lβ++lβ) l β disjoint lβ l :=
disjoint_of_subset_left (list.subset_append_right _ _)
lemma disjoint_of_disjoint_append_right_left {lβ lβ l : list Ξ±} : disjoint l (lβ++lβ) β disjoint l lβ :=
disjoint_of_subset_right (list.subset_append_left _ _)
lemma disjoint_of_disjoint_append_right_right {lβ lβ l : list Ξ±} : disjoint l (lβ++lβ) β disjoint l lβ :=
disjoint_of_subset_right (list.subset_append_right _ _)
end disjoint
/- upto -/
def upto : nat β list nat
| 0 := []
| (n+1) := n :: upto n
@[simp]
theorem upto_nil : upto 0 = nil := rfl
@[simp]
theorem upto_succ (n : nat) : upto (succ n) = n :: upto n := rfl
@[simp]
theorem length_upto : β n, length (upto n) = n
| 0 := rfl
| (succ n) := begin rw [upto_succ, length_cons, length_upto] end
theorem upto_ne_nil_of_ne_zero {n : β} (h : n β 0) : upto n β nil :=
assume : upto n = nil,
have upto n = upto 0, from upto_nil βΈ this,
have n = 0, from calc
n = length (upto n) : by rw length_upto
... = length (upto 0) : by rw this
... = 0 : by rw length_upto,
h this
theorem lt_of_mem_upto : β β¦n iβ¦, i β upto n β i < n
| 0 := assume i imem, absurd imem (not_mem_nil _)
| (succ n) := assume i imem,
or.elim (eq_or_mem_of_mem_cons imem)
(Ξ» h, begin rw h, apply lt_succ_self end)
(Ξ» h, lt.trans (lt_of_mem_upto h) (lt_succ_self n))
theorem mem_upto_succ_of_mem_upto {n i : nat} : i β upto n β i β upto (succ n) :=
assume i, mem_cons_of_mem _ i
theorem mem_upto_of_lt : β β¦n i : natβ¦, i < n β i β upto n
| 0 := Ξ» i h, absurd h (not_lt_zero i)
| (succ n) := Ξ» i h,
begin
cases nat.lt_or_eq_of_le (le_of_lt_succ h) with ilt ieq,
{ apply mem_upto_succ_of_mem_upto, apply mem_upto_of_lt ilt },
simp [ieq]
end
lemma upto_step : β (n : nat), upto (succ n) = (map succ (upto n)) ++ [0]
| 0 := rfl
| (succ n) := by simp [(upto_step n)^.symm]
/- union -/
section union
variable [decidable_eq Ξ±]
@[simp]
theorem union_nil (l : list Ξ±) : l βͺ [] = l := rfl
@[simp]
theorem union_cons (lβ lβ : list Ξ±) (a : Ξ±) : lβ βͺ (a :: lβ) = insert a lβ βͺ lβ := rfl
theorem mem_or_mem_of_mem_union : β {lβ lβ : list Ξ±} {a : Ξ±}, a β lβ βͺ lβ β a β lβ β¨ a β lβ
| lβ [] a h := begin simp at h, simp [h] end
| lβ (b :: lβ) a h :=
if h' : b β lβ then
begin
simp at h,
cases mem_or_mem_of_mem_union h with hβ hβ,
{ simp at hβ, cases hβ with hβ hβ, simp [hβ], simp [hβ] },
simp [hβ]
end
else
begin
simp [union_cons] at h,
cases mem_or_mem_of_mem_union h with hβ hβ,
{ simp at hβ, cases hβ with hβ hβ, repeat { simp [hβ] } },
simp [hβ]
end
theorem mem_union_left {a : Ξ±} {lβ : list Ξ±} (h : a β lβ) (lβ : list Ξ±) : a β lβ βͺ lβ :=
begin
induction lβ with b lβ ih generalizing lβ,
{ simp [h] },
{ apply ih, simp [h] }
end
theorem mem_union_right {a : Ξ±} (lβ : list Ξ±) {lβ : list Ξ±} (h : a β lβ) : a β lβ βͺ lβ :=
begin
induction lβ with b lβ ih generalizing lβ,
{ simp at h, contradiction },
simp, simp at h,
cases h with hβ hβ,
{ subst hβ, apply mem_union_left, simp },
apply ih hβ
end
@[simp]
theorem mem_union_iff (a : Ξ±) (lβ lβ : list Ξ±) : a β lβ βͺ lβ β a β lβ β¨ a β lβ :=
iff.intro mem_or_mem_of_mem_union (Ξ» h, or.elim h (Ξ» h', mem_union_left h' lβ) (mem_union_right lβ))
theorem forall_mem_union {p : Ξ± β Prop} {lβ lβ : list Ξ±} (hβ : β x β lβ, p x) (hβ : β x β lβ, p x) :
β x β lβ βͺ lβ, p x :=
begin
intro x, simp, intro h, cases h,
{ apply hβ, assumption },
apply hβ, assumption
end
theorem forall_mem_of_forall_mem_union_left {p : Ξ± β Prop} {lβ lβ : list Ξ±}
(h : β x β lβ βͺ lβ, p x) :
β x β lβ, p x :=
begin intros x xlβ, apply h, apply mem_union_left xlβ end
theorem forall_mem_of_forall_mem_union_right {p : Ξ± β Prop} {lβ lβ : list Ξ±}
(h : β x β lβ βͺ lβ, p x) :
β x β lβ, p x :=
begin intros x xlβ, apply h, apply mem_union_right lβ xlβ end
end union
/- inter -/
section inter
variable [decidable_eq Ξ±]
@[simp]
theorem inter_nil (l : list Ξ±) : [] β© l = [] := rfl
@[simp]
theorem inter_cons_of_mem {a : Ξ±} (lβ : list Ξ±) {lβ : list Ξ±} (h : a β lβ) :
(a::lβ) β© lβ = a :: (lβ β© lβ) :=
if_pos h
@[simp]
theorem inter_cons_of_not_mem {a : Ξ±} (lβ : list Ξ±) {lβ : list Ξ±} (h : a β lβ) :
(a::lβ) β© lβ = lβ β© lβ :=
if_neg h
theorem mem_of_mem_inter_left : β {lβ lβ : list Ξ±} {a : Ξ±}, a β lβ β© lβ β a β lβ
| [] lβ a i := absurd i (not_mem_nil a)
| (b::lβ) lβ a i := by_cases
(Ξ» binlβ : b β lβ,
have aux : a β b :: lβ β© lβ, begin rw [inter_cons_of_mem _ binlβ] at i, exact i end,
or.elim (eq_or_mem_of_mem_cons aux)
(Ξ» aeqb : a = b, begin rw [aeqb], apply mem_cons_self end)
(Ξ» aini, mem_cons_of_mem _ (mem_of_mem_inter_left aini)))
(Ξ» nbinlβ : b β lβ,
have ainlβ : a β lβ,
begin rw [inter_cons_of_not_mem _ nbinlβ] at i, exact (mem_of_mem_inter_left i) end,
mem_cons_of_mem _ ainlβ)
theorem mem_of_mem_inter_right : β {lβ lβ : list Ξ±} {a : Ξ±}, a β lβ β© lβ β a β lβ
| [] lβ a i := absurd i (not_mem_nil _)
| (b::lβ) lβ a i := by_cases
(Ξ» binlβ : b β lβ,
have aux : a β b :: lβ β© lβ, begin rw [inter_cons_of_mem _ binlβ] at i, exact i end,
or.elim (eq_or_mem_of_mem_cons aux)
(Ξ» aeqb : a = b, begin rw [aeqb], exact binlβ end)
(Ξ» aini : a β lβ β© lβ, mem_of_mem_inter_right aini))
(Ξ» nbinlβ : b β lβ,
begin rw [inter_cons_of_not_mem _ nbinlβ] at i, exact (mem_of_mem_inter_right i) end)
theorem mem_inter_of_mem_of_mem : β {lβ lβ : list Ξ±} {a : Ξ±}, a β lβ β a β lβ β a β lβ β© lβ
| [] lβ a iβ iβ := absurd iβ (not_mem_nil _)
| (b::lβ) lβ a iβ iβ := by_cases
(Ξ» binlβ : b β lβ,
or.elim (eq_or_mem_of_mem_cons iβ)
(Ξ» aeqb : a = b,
begin rw [inter_cons_of_mem _ binlβ, aeqb], apply mem_cons_self end)
(Ξ» ainlβ : a β lβ,
begin
rw [inter_cons_of_mem _ binlβ],
apply mem_cons_of_mem,
exact (mem_inter_of_mem_of_mem ainlβ iβ)
end))
(Ξ» nbinlβ : b β lβ,
or.elim (eq_or_mem_of_mem_cons iβ)
(Ξ» aeqb : a = b,
begin rw aeqb at iβ, exact absurd iβ nbinlβ end)
(Ξ» ainlβ : a β lβ,
begin rw [inter_cons_of_not_mem _ nbinlβ], exact (mem_inter_of_mem_of_mem ainlβ iβ) end))
@[simp]
theorem mem_inter_iff (a : Ξ±) (lβ lβ : list Ξ±) : a β lβ β© lβ β a β lβ β§ a β lβ :=
iff.intro
(Ξ» h, and.intro (mem_of_mem_inter_left h) (mem_of_mem_inter_right h))
(Ξ» h, mem_inter_of_mem_of_mem h^.left h^.right)
theorem inter_eq_nil_of_disjoint : β {lβ lβ : list Ξ±}, disjoint lβ lβ β lβ β© lβ = []
| [] lβ d := rfl
| (a::lβ) lβ d :=
have aux_eq : lβ β© lβ = [], from inter_eq_nil_of_disjoint (disjoint_of_disjoint_cons_left d),
have nainlβ : a β lβ, from disjoint_left d (mem_cons_self _ _),
by rw [inter_cons_of_not_mem _ nainlβ, aux_eq]
theorem forall_mem_inter_of_forall_left {p : Ξ± β Prop} {lβ : list Ξ±} (h : β x β lβ, p x)
(lβ : list Ξ±) :
β x, x β lβ β© lβ β p x :=
Ξ» x xlβlβ, h x (mem_of_mem_inter_left xlβlβ)
theorem forall_mem_inter_of_forall_right {p : Ξ± β Prop} (lβ : list Ξ±) {lβ : list Ξ±}
(h : β x β lβ, p x) :
β x, x β lβ β© lβ β p x :=
Ξ» x xlβlβ, h x (mem_of_mem_inter_right xlβlβ)
end inter
/- no duplicates predicate -/
inductive nodup {Ξ± : Type uu} : list Ξ± β Prop
| ndnil : nodup []
| ndcons : β {a : Ξ±} {l : list Ξ±}, a β l β nodup l β nodup (a::l)
section nodup
open nodup
theorem nodup_nil : @nodup Ξ± [] :=
ndnil
theorem nodup_cons {a : Ξ±} {l : list Ξ±} : a β l β nodup l β nodup (a::l) :=
Ξ» i n, ndcons i n
theorem nodup_singleton (a : Ξ±) : nodup [a] :=
nodup_cons (not_mem_nil a) nodup_nil
theorem nodup_of_nodup_cons : β {a : Ξ±} {l : list Ξ±}, nodup (a::l) β nodup l
| a xs (ndcons i n) := n
theorem not_mem_of_nodup_cons : β {a : Ξ±} {l : list Ξ±}, nodup (a::l) β a β l
| a xs (ndcons i n) := i
theorem not_nodup_cons_of_mem {a : Ξ±} {l : list Ξ±} : a β l β Β¬ nodup (a :: l) :=
Ξ» ainl d, absurd ainl (not_mem_of_nodup_cons d)
theorem nodup_of_sublist : Ξ {lβ lβ : list Ξ±}, lβ <+ lβ β nodup lβ β nodup lβ
| ._ ._ sublist.slnil h := h
| ._ ._ (sublist.cons lβ lβ a s) (ndcons i n) := nodup_of_sublist s n
| ._ ._ (sublist.cons2 lβ lβ a s) (ndcons i n) :=
ndcons (Ξ»h, i (subset_of_sublist s h)) (nodup_of_sublist s n)
theorem not_nodup_cons_of_not_nodup {a : Ξ±} {l : list Ξ±} : Β¬ nodup l β Β¬ nodup (a :: l) :=
mt nodup_of_nodup_cons
theorem nodup_of_nodup_append_left {lβ lβ : list Ξ±} : nodup (lβ++lβ) β nodup lβ :=
nodup_of_sublist (sublist_append_left lβ lβ)
theorem nodup_of_nodup_append_right : β {lβ lβ : list Ξ±}, nodup (lβ++lβ) β nodup lβ
| [] lβ n := n
| (x::xs) lβ n := nodup_of_nodup_append_right (nodup_of_nodup_cons n)
theorem disjoint_of_nodup_append : β {lβ lβ : list Ξ±}, nodup (lβ++lβ) β disjoint lβ lβ
| [] lβ d := disjoint_nil_left lβ
| (x::xs) lβ d :=
have nodup (x::(xs++lβ)), from d,
have x β xs++lβ, from not_mem_of_nodup_cons this,
have nxinlβ : x β lβ, from not_mem_of_not_mem_append_right this,
assume a, assume : a β x::xs,
or.elim (eq_or_mem_of_mem_cons this)
(assume : a = x, eq.symm this βΈ nxinlβ)
(assume ainxs : a β xs,
have nodup (x::(xs++lβ)), from d,
have nodup (xs++lβ), from nodup_of_nodup_cons this,
have disjoint xs lβ, from disjoint_of_nodup_append this,
disjoint_left this ainxs)
theorem nodup_append_of_nodup_of_nodup_of_disjoint :
β {lβ lβ : list Ξ±}, nodup lβ β nodup lβ β disjoint lβ lβ β nodup (lβ++lβ)
| [] lβ dβ dβ dsj := begin rw [nil_append], exact dβ end
| (x::xs) lβ dβ dβ dsj :=
have ndxs : nodup xs, from nodup_of_nodup_cons dβ,
have disjoint xs lβ, from disjoint_of_disjoint_cons_left dsj,
have ndxslβ : nodup (xs++lβ), from nodup_append_of_nodup_of_nodup_of_disjoint ndxs dβ this,
have nxinxs : x β xs, from not_mem_of_nodup_cons dβ,
have x β lβ, from disjoint_left dsj (mem_cons_self x xs),
have x β xs++lβ, from not_mem_append nxinxs this,
nodup_cons this ndxslβ
theorem nodup_app_comm {lβ lβ : list Ξ±} (d : nodup (lβ++lβ)) : nodup (lβ++lβ) :=
have dβ : nodup lβ, from nodup_of_nodup_append_left d,
have dβ : nodup lβ, from nodup_of_nodup_append_right d,
have dsj : disjoint lβ lβ, from disjoint_of_nodup_append d,
nodup_append_of_nodup_of_nodup_of_disjoint dβ dβ (disjoint.comm dsj)
theorem nodup_head {a : Ξ±} {lβ lβ : list Ξ±} (d : nodup (lβ++(a::lβ))) : nodup (a::(lβ++lβ)) :=
have dβ : nodup (a::(lβ++lβ)), from nodup_app_comm d,
have dβ : nodup (lβ++lβ), from nodup_of_nodup_cons dβ,
have dβ : nodup (lβ++lβ), from nodup_app_comm dβ,
have nain : a β lβ++lβ, from not_mem_of_nodup_cons dβ,
have nainβ : a β lβ, from not_mem_of_not_mem_append_left nain,
have nainβ : a β lβ, from not_mem_of_not_mem_append_right nain,
nodup_cons (not_mem_append nainβ nainβ) dβ
theorem nodup_middle {a : Ξ±} {lβ lβ : list Ξ±} (d : nodup (a::(lβ++lβ))) : nodup (lβ++(a::lβ)) :=
have dβ : nodup (lβ++lβ), from nodup_of_nodup_cons d,
have nain : a β lβ++lβ, from not_mem_of_nodup_cons d,
have disj : disjoint lβ lβ, from disjoint_of_nodup_append dβ,
have dβ : nodup lβ, from nodup_of_nodup_append_left dβ,
have dβ : nodup lβ, from nodup_of_nodup_append_right dβ,
have nainβ : a β lβ, from not_mem_of_not_mem_append_right nain,
have nainβ : a β lβ, from not_mem_of_not_mem_append_left nain,
have dβ : nodup (a::lβ), from nodup_cons nainβ dβ,
have disjβ : disjoint lβ (a::lβ), from disjoint.comm (disjoint_cons_of_not_mem_of_disjoint nainβ
(disjoint.comm disj)),
nodup_append_of_nodup_of_nodup_of_disjoint dβ dβ disjβ
theorem nodup_map {f : Ξ± β Ξ²} (inj : injective f) : β {l : list Ξ±}, nodup l β nodup (map f l)
| [] n := begin apply nodup_nil end
| (x::xs) n :=
have nxinxs : x β xs, from not_mem_of_nodup_cons n,
have ndxs : nodup xs, from nodup_of_nodup_cons n,
have ndmfxs : nodup (map f xs), from nodup_map ndxs,
have nfxinm : f x β map f xs, from
Ξ» ab : f x β map f xs,
match (exists_of_mem_map ab) with
| β¨(y : Ξ±), (yinxs : y β xs), (fyfx : f y = f x)β© :=
have yeqx : y = x, from inj fyfx,
begin subst y, contradiction end
end,
nodup_cons nfxinm ndmfxs
theorem nodup_erase_of_nodup [decidable_eq Ξ±] (a : Ξ±) : β {l}, nodup l β nodup (l.erase a)
| [] n := nodup_nil
| (b::l) n := by_cases
(Ξ» aeqb : b = a, begin rw [aeqb, erase_cons_head], exact (nodup_of_nodup_cons n) end)
(Ξ» aneb : b β a,
have nbinl : b β l, from not_mem_of_nodup_cons n,
have ndl : nodup l, from nodup_of_nodup_cons n,
have ndeal : nodup (l.erase a), from nodup_erase_of_nodup ndl,
have nbineal : b β l.erase a, from Ξ» i, absurd (erase_subset _ _ i) nbinl,
have aux : nodup (b :: l.erase a), from nodup_cons nbineal ndeal,
begin rw [erase_cons_tail _ aneb], exact aux end)
theorem mem_erase_of_nodup [decidable_eq Ξ±] (a : Ξ±) : β {l}, nodup l β a β l.erase a
| [] n := (not_mem_nil _)
| (b::l) n :=
have ndl : nodup l, from nodup_of_nodup_cons n,
have naineal : a β l.erase a, from mem_erase_of_nodup ndl,
have nbinl : b β l, from not_mem_of_nodup_cons n,
by_cases
(Ξ» aeqb : b = a, begin rw [aeqb.symm, erase_cons_head], exact nbinl end)
(Ξ» aneb : b β a,
have aux : a β b :: l.erase a, from
assume ainbeal : a β b :: l.erase a, or.elim (eq_or_mem_of_mem_cons ainbeal)
(Ξ» aeqb : a = b, absurd aeqb.symm aneb)
(Ξ» aineal : a β l.erase a, absurd aineal naineal),
begin rw [erase_cons_tail _ aneb], exact aux end)
def erase_dup [decidable_eq Ξ±] : list Ξ± β list Ξ±
| [] := []
| (x :: xs) := if x β xs then erase_dup xs else x :: erase_dup xs
theorem erase_dup_nil [decidable_eq Ξ±] : erase_dup [] = ([] : list Ξ±) := rfl
theorem erase_dup_cons_of_mem [decidable_eq Ξ±] {a : Ξ±} {l : list Ξ±} :
a β l β erase_dup (a::l) = erase_dup l :=
assume ainl, calc
erase_dup (a::l) = if a β l then erase_dup l else a :: erase_dup l : rfl
... = erase_dup l : if_pos ainl
theorem erase_dup_cons_of_not_mem [decidable_eq Ξ±] {a : Ξ±} {l : list Ξ±} :
a β l β erase_dup (a::l) = a :: erase_dup l :=
assume nainl, calc
erase_dup (a::l) = if a β l then erase_dup l else a :: erase_dup l : rfl
... = a :: erase_dup l : if_neg nainl
theorem mem_erase_dup [decidable_eq Ξ±] {a : Ξ±} : β {l : list Ξ±}, a β l β a β erase_dup l
| [] h := absurd h (not_mem_nil _)
| (b::l) h := by_cases
(Ξ» binl : b β l, or.elim (eq_or_mem_of_mem_cons h)
(Ξ» aeqb : a = b,
begin rw [erase_dup_cons_of_mem binl], rw βaeqb at binl, exact (mem_erase_dup binl) end)
(Ξ» ainl : a β l,
begin rw [erase_dup_cons_of_mem binl], exact (mem_erase_dup ainl) end))
(Ξ» nbinl : b β l, or.elim (eq_or_mem_of_mem_cons h)
(Ξ» aeqb : a = b,
begin rw [erase_dup_cons_of_not_mem nbinl, aeqb], apply mem_cons_self end)
(Ξ» ainl : a β l,
begin rw [erase_dup_cons_of_not_mem nbinl], exact (or.inr (mem_erase_dup ainl)) end))
theorem erase_dup_sublist [decidable_eq Ξ±] : β (l : list Ξ±), erase_dup l <+ l
| [] := sublist.slnil
| (b::l) := if h : b β l then
by simp[erase_dup, h]; exact sublist_cons_of_sublist _ (erase_dup_sublist l)
else
by simp[erase_dup, h]; exact cons_sublist_cons _ (erase_dup_sublist l)
theorem mem_of_mem_erase_dup [decidable_eq Ξ±] {a : Ξ±} : β {l : list Ξ±}, a β erase_dup l β a β l
| [] h := begin rw [erase_dup_nil] at h, exact h end
| (b::l) h := by_cases
(Ξ» binl : b β l,
have hβ : a β erase_dup l,
begin rw [erase_dup_cons_of_mem binl] at h, exact h end,
or.inr (mem_of_mem_erase_dup hβ))
(Ξ» nbinl : b β l,
have hβ : a β b :: erase_dup l,
begin rw [erase_dup_cons_of_not_mem nbinl] at h, exact h end,
or.elim (eq_or_mem_of_mem_cons hβ)
(Ξ» aeqb : a = b, begin rw aeqb, apply mem_cons_self end)
(Ξ» ainel : a β erase_dup l, or.inr (mem_of_mem_erase_dup ainel)))
@[simp]
theorem mem_erase_dup_iff [decidable_eq Ξ±] (a : Ξ±) (l : list Ξ±) : a β erase_dup l β a β l :=
iff.intro mem_of_mem_erase_dup mem_erase_dup
theorem erase_dup_sub [decidable_eq Ξ±] (l : list Ξ±) : erase_dup l β l :=
Ξ» a i, mem_of_mem_erase_dup i
theorem sub_erase_dup [decidable_eq Ξ±] (l : list Ξ±) : l β erase_dup l :=
Ξ» a i, mem_erase_dup i
theorem nodup_erase_dup [decidable_eq Ξ±] : β l : list Ξ±, nodup (erase_dup l)
| [] := begin rw erase_dup_nil, exact nodup_nil end
| (a::l) := by_cases
(Ξ» ainl : a β l, begin rw [erase_dup_cons_of_mem ainl], exact (nodup_erase_dup l) end)
(Ξ» nainl : a β l,
have r : nodup (erase_dup l), from nodup_erase_dup l,
have nin : a β erase_dup l, from
assume ab : a β erase_dup l, absurd (mem_of_mem_erase_dup ab) nainl,
begin rw [erase_dup_cons_of_not_mem nainl], exact (nodup_cons nin r) end)
theorem erase_dup_eq_of_nodup [decidable_eq Ξ±] : β {l : list Ξ±}, nodup l β erase_dup l = l
| [] d := rfl
| (a::l) d :=
have nainl : a β l, from not_mem_of_nodup_cons d,
have dl : nodup l, from nodup_of_nodup_cons d,
by rw [erase_dup_cons_of_not_mem nainl, erase_dup_eq_of_nodup dl]
attribute [instance]
def decidable_nodup [decidable_eq Ξ±] : β (l : list Ξ±), decidable (nodup l)
| [] := is_true nodup_nil
| (a::l) :=
if h : a β l then
is_false (not_nodup_cons_of_mem h)
else
match (decidable_nodup l) with
| (is_true nd) := is_true (nodup_cons h nd)
| (is_false d) := is_false (not_nodup_cons_of_not_nodup d)
end
private def dgen (a : Ξ±) : β l, nodup l β nodup (map (Ξ» b : Ξ², (a, b)) l)
| [] h := nodup_nil
| (x::l) h :=
have dl : nodup l, from nodup_of_nodup_cons h,
have dm : nodup (map (Ξ» b : Ξ², (a, b)) l), from dgen l dl,
have nxin : x β l, from not_mem_of_nodup_cons h,
have npin : (a, x) β map (Ξ» b, (a, b)) l, from
assume pin, absurd (mem_of_mem_map_pairβ pin) nxin,
nodup_cons npin dm
theorem nodup_product : β {lβ : list Ξ±} {lβ : list Ξ²}, nodup lβ β nodup lβ β nodup (product lβ lβ)
| [] lβ nβ nβ := nodup_nil
| (a::lβ) lβ nβ nβ :=
have nainlβ : a β lβ, from not_mem_of_nodup_cons nβ,
have nβ : nodup lβ, from nodup_of_nodup_cons nβ,
have nβ : nodup (product lβ lβ), from nodup_product nβ nβ,
have dm : nodup (map (Ξ» b : Ξ², (a, b)) lβ), from dgen a lβ nβ,
have dsj : disjoint (map (Ξ» b : Ξ², (a, b)) lβ) (product lβ lβ), from
Ξ» p : Ξ± Γ Ξ², match p with
| (aβ, bβ) :=
Ξ» (iβ : (aβ, bβ) β map (Ξ» b, (a, b)) lβ) (iβ : (aβ, bβ) β product lβ lβ),
have aβinlβ : aβ β lβ, from mem_of_mem_product_left iβ,
have aβ = a, from eq_of_mem_map_pairβ iβ,
have a β lβ, begin rw βthis, assumption end,
absurd this nainlβ
end,
nodup_append_of_nodup_of_nodup_of_disjoint dm nβ dsj
theorem nodup_filter (p : Ξ± β Prop) [decidable_pred p] :
β {l : list Ξ±}, nodup l β nodup (filter p l)
| [] nd := nodup_nil
| (a::l) nd :=
have nainl : a β l, from not_mem_of_nodup_cons nd,
have ndl : nodup l, from nodup_of_nodup_cons nd,
have ndf : nodup (filter p l), from nodup_filter ndl,
have nainf : a β filter p l, from
assume ainf, absurd (mem_of_mem_filter ainf) nainl,
by_cases
(Ξ» pa : p a, begin rw [filter_cons_of_pos _ pa], exact (nodup_cons nainf ndf) end)
(Ξ» npa : Β¬ p a, begin rw [filter_cons_of_neg _ npa], exact ndf end)
lemma dmap_nodup_of_dinj {p : Ξ± β Prop} [h : decidable_pred p] {f : Ξ a, p a β Ξ²} (pdi : dinj p f) :
β {l : list Ξ±}, nodup l β nodup (dmap p f l)
| [] := assume P, nodup.ndnil
| (a::l) := assume Pnodup,
if pa : p a then
begin
rw [dmap_cons_of_pos pa],
apply nodup_cons,
apply (not_mem_dmap_of_dinj_of_not_mem pdi pa),
exact not_mem_of_nodup_cons Pnodup,
exact dmap_nodup_of_dinj (nodup_of_nodup_cons Pnodup)
end
else
begin
rw [dmap_cons_of_neg pa],
exact dmap_nodup_of_dinj (nodup_of_nodup_cons Pnodup)
end
theorem nodup_concat {a : Ξ±} {l : list Ξ±} (h : a β l) (h' : nodup l) : nodup (concat l a) :=
begin
revert h, induction l with b l ih,
{ intro hβ, apply nodup_singleton },
intro hβ, rw [concat_cons], apply nodup_cons,
{ simp, intro hβ, apply hβ, simp, cases hβ with hβ hβ, simp [hβ],
exact absurd hβ (not_mem_of_nodup_cons h') },
apply ih,
{ apply nodup_of_nodup_cons h' },
intro hβ, apply hβ, exact mem_cons_of_mem _ hβ
end
theorem nodup_insert [decidable_eq Ξ±] {a : Ξ±} {l : list Ξ±} (h : nodup l) : nodup (insert a l) :=
if h' : a β l then by simp [h', h]
else begin rw [insert_of_not_mem h'], apply nodup_concat, repeat {assumption} end
theorem nodup_upto : β n, nodup (upto n)
| 0 := nodup_nil
| (n+1) :=
have d : nodup (upto n), from nodup_upto n,
have n : n β upto n, from
assume i : n β upto n, absurd (lt_of_mem_upto i) (nat.lt_irrefl n),
nodup_cons n d
theorem nodup_union_of_nodup_of_nodup [decidable_eq Ξ±] {lβ lβ : list Ξ±}
(hβ : nodup lβ) (hβ : nodup lβ) :
nodup (lβ βͺ lβ) :=
begin
induction lβ with a lβ ih generalizing lβ,
{ exact hβ },
simp,
apply ih,
{ apply nodup_of_nodup_cons hβ },
apply nodup_insert hβ
end
theorem nodup_inter_of_nodup [decidable_eq Ξ±] : β {lβ : list Ξ±} (lβ), nodup lβ β nodup (lβ β© lβ)
| [] lβ d := nodup_nil
| (a::lβ) lβ d :=
have dβ : nodup lβ, from nodup_of_nodup_cons d,
have dβ : nodup (lβ β© lβ), from nodup_inter_of_nodup _ dβ,
have nainlβ : a β lβ, from not_mem_of_nodup_cons d,
have naini : a β lβ β© lβ, from Ξ» i, absurd (mem_of_mem_inter_left i) nainlβ,
by_cases
(Ξ» ainlβ : a β lβ, begin rw [inter_cons_of_mem _ ainlβ], exact (nodup_cons naini dβ) end)
(Ξ» nainlβ : a β lβ, begin rw [inter_cons_of_not_mem _ nainlβ], exact dβ end)
end nodup
end list
|
2052f711e1c8d025ffcf5a001cf3f3db2eb89cfb | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/data/int/basic.lean | 1d85d71b9bb49da4837477394518eb75ef62583f | [
"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 | 53,748 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
The integers, with addition, multiplication, and subtraction.
-/
import data.nat.basic
import algebra.order_functions
open nat
namespace int
instance : inhabited β€ := β¨int.zeroβ©
instance : nontrivial β€ :=
β¨β¨0, 1, int.zero_ne_oneβ©β©
instance : comm_ring int :=
{ add := int.add,
add_assoc := int.add_assoc,
zero := int.zero,
zero_add := int.zero_add,
add_zero := int.add_zero,
neg := int.neg,
add_left_neg := int.add_left_neg,
add_comm := int.add_comm,
mul := int.mul,
mul_assoc := int.mul_assoc,
one := int.one,
one_mul := int.one_mul,
mul_one := int.mul_one,
sub := int.sub,
left_distrib := int.distrib_left,
right_distrib := int.distrib_right,
mul_comm := int.mul_comm }
/-! ### Extra instances to short-circuit type class resolution -/
-- instance : has_sub int := by apply_instance -- This is in core
instance : add_comm_monoid int := by apply_instance
instance : add_monoid int := by apply_instance
instance : monoid int := by apply_instance
instance : comm_monoid int := by apply_instance
instance : comm_semigroup int := by apply_instance
instance : semigroup int := by apply_instance
instance : add_comm_semigroup int := by apply_instance
instance : add_semigroup int := by apply_instance
instance : comm_semiring int := by apply_instance
instance : semiring int := by apply_instance
instance : ring int := by apply_instance
instance : distrib int := by apply_instance
instance : linear_ordered_comm_ring int :=
{ add_le_add_left := @int.add_le_add_left,
mul_pos := @int.mul_pos,
zero_le_one := le_of_lt int.zero_lt_one,
.. int.comm_ring, .. int.linear_order, .. int.nontrivial }
instance : linear_ordered_add_comm_group int :=
by apply_instance
@[simp] lemma add_neg_one (i : β€) : i + -1 = i - 1 := rfl
theorem abs_eq_nat_abs : β a : β€, abs a = nat_abs a
| (n : β) := abs_of_nonneg $ coe_zero_le _
| -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _
theorem nat_abs_abs (a : β€) : nat_abs (abs a) = nat_abs a :=
by rw [abs_eq_nat_abs]; refl
theorem sign_mul_abs (a : β€) : sign a * abs a = a :=
by rw [abs_eq_nat_abs, sign_mul_nat_abs]
@[simp] lemma default_eq_zero : default β€ = 0 := rfl
meta instance : has_to_format β€ := β¨Ξ» z, to_string zβ©
meta instance : has_reflect β€ := by tactic.mk_has_reflect_instance
attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ
attribute [simp] int.of_nat_eq_coe int.bodd
@[simp] theorem add_def {a b : β€} : int.add a b = a + b := rfl
@[simp] theorem mul_def {a b : β€} : int.mul a b = a * b := rfl
@[simp] lemma neg_succ_not_nonneg (n : β) : 0 β€ -[1+ n] β false :=
by { simp only [not_le, iff_false], exact int.neg_succ_lt_zero n, }
@[simp] lemma neg_succ_not_pos (n : β) : 0 < -[1+ n] β false :=
by simp only [not_lt, iff_false]
@[simp] lemma neg_succ_sub_one (n : β) : -[1+ n] - 1 = -[1+ (n+1)] := rfl
@[simp] theorem coe_nat_mul_neg_succ (m n : β) : (m : β€) * -[1+ n] = -(m * succ n) := rfl
@[simp] theorem neg_succ_mul_coe_nat (m n : β) : -[1+ m] * n = -(succ m * n) := rfl
@[simp] theorem neg_succ_mul_neg_succ (m n : β) : -[1+ m] * -[1+ n] = succ m * succ n := rfl
@[simp, norm_cast]
theorem coe_nat_le {m n : β} : (βm : β€) β€ βn β m β€ n := coe_nat_le_coe_nat_iff m n
@[simp, norm_cast]
theorem coe_nat_lt {m n : β} : (βm : β€) < βn β m < n := coe_nat_lt_coe_nat_iff m n
@[simp, norm_cast]
theorem coe_nat_inj' {m n : β} : (βm : β€) = βn β m = n := int.coe_nat_eq_coe_nat_iff m n
@[simp] theorem coe_nat_pos {n : β} : (0 : β€) < n β 0 < n :=
by rw [β int.coe_nat_zero, coe_nat_lt]
@[simp] theorem coe_nat_eq_zero {n : β} : (n : β€) = 0 β n = 0 :=
by rw [β int.coe_nat_zero, coe_nat_inj']
theorem coe_nat_ne_zero {n : β} : (n : β€) β 0 β n β 0 :=
not_congr coe_nat_eq_zero
@[simp] lemma coe_nat_nonneg (n : β) : 0 β€ (n : β€) := coe_nat_le.2 (nat.zero_le _)
lemma coe_nat_ne_zero_iff_pos {n : β} : (n : β€) β 0 β 0 < n :=
β¨Ξ» h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h),
Ξ» h, (ne_of_lt (coe_nat_lt.2 h)).symmβ©
lemma coe_nat_succ_pos (n : β) : 0 < (n.succ : β€) := int.coe_nat_pos.2 (succ_pos n)
@[simp, norm_cast] theorem coe_nat_abs (n : β) : abs (n : β€) = n :=
abs_of_nonneg (coe_nat_nonneg n)
/-! ### succ and pred -/
/-- Immediate successor of an integer: `succ n = n + 1` -/
def succ (a : β€) := a + 1
/-- Immediate predecessor of an integer: `pred n = n - 1` -/
def pred (a : β€) := a - 1
theorem nat_succ_eq_int_succ (n : β) : (nat.succ n : β€) = int.succ n := rfl
theorem pred_succ (a : β€) : pred (succ a) = a := add_sub_cancel _ _
theorem succ_pred (a : β€) : succ (pred a) = a := sub_add_cancel _ _
theorem neg_succ (a : β€) : -succ a = pred (-a) := neg_add _ _
theorem succ_neg_succ (a : β€) : succ (-succ a) = -a :=
by rw [neg_succ, succ_pred]
theorem neg_pred (a : β€) : -pred a = succ (-a) :=
by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg]
theorem pred_neg_pred (a : β€) : pred (-pred a) = -a :=
by rw [neg_pred, pred_succ]
theorem pred_nat_succ (n : β) : pred (nat.succ n) = n := pred_succ n
theorem neg_nat_succ (n : β) : -(nat.succ n : β€) = pred (-n) := neg_succ n
theorem succ_neg_nat_succ (n : β) : succ (-nat.succ n) = -n := succ_neg_succ n
theorem lt_succ_self (a : β€) : a < succ a :=
lt_add_of_pos_right _ zero_lt_one
theorem pred_self_lt (a : β€) : pred a < a :=
sub_lt_self _ zero_lt_one
theorem add_one_le_iff {a b : β€} : a + 1 β€ b β a < b := iff.rfl
theorem lt_add_one_iff {a b : β€} : a < b + 1 β a β€ b :=
@add_le_add_iff_right _ _ a b 1
@[simp] lemma succ_coe_nat_pos (n : β) : 0 < (n : β€) + 1 :=
lt_add_one_iff.mpr (by simp)
@[norm_cast] lemma coe_pred_of_pos (n : β) (h : 0 < n) : ((n - 1 : β) : β€) = (n : β€) - 1 :=
by { cases n, cases h, simp, }
lemma le_add_one {a b : β€} (h : a β€ b) : a β€ b + 1 :=
le_of_lt (int.lt_add_one_iff.mpr h)
theorem sub_one_lt_iff {a b : β€} : a - 1 < b β a β€ b :=
sub_lt_iff_lt_add.trans lt_add_one_iff
theorem le_sub_one_iff {a b : β€} : a β€ b - 1 β a < b :=
le_sub_iff_add_le
@[simp] lemma eq_zero_iff_abs_lt_one {a : β€} : abs a < 1 β a = 0 :=
β¨Ξ» a0, let β¨hn, hpβ© := abs_lt.mp a0 in (le_of_lt_add_one (by exact hp)).antisymm hn,
Ξ» a0, (abs_eq_zero.mpr a0).le.trans_lt zero_lt_oneβ©
@[elab_as_eliminator] protected lemma induction_on {p : β€ β Prop}
(i : β€) (hz : p 0) (hp : βi : β, p i β p (i + 1)) (hn : βi : β, p (-i) β p (-i - 1)) : p i :=
begin
induction i,
{ induction i,
{ exact hz },
{ exact hp _ i_ih } },
{ have : βn:β, p (- n),
{ intro n, induction n,
{ simp [hz] },
{ convert hn _ n_ih using 1, simp [sub_eq_neg_add] } },
exact this (i + 1) }
end
/-- Inductively define a function on `β€` by defining it at `b`, for the `succ` of a number greater
than `b`, and the `pred` of a number less than `b`. -/
protected def induction_on' {C : β€ β Sort*} (z : β€) (b : β€) :
C b β (β k, b β€ k β C k β C (k + 1)) β (β k β€ b, C k β C (k - 1)) β C z :=
Ξ» H0 Hs Hp,
begin
rw βsub_add_cancel z b,
induction (z - b) with n n,
{ induction n with n ih, { rwa [of_nat_zero, zero_add] },
rw [of_nat_succ, add_assoc, add_comm 1 b, βadd_assoc],
exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih },
{ induction n with n ih,
{ rw [neg_succ_of_nat_eq, βof_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub],
exact Hp _ (le_refl _) H0 },
{ rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, βneg_succ_of_nat_coe, sub_add_eq_add_sub],
exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } }
end
/-! ### nat abs -/
attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one
theorem nat_abs_add_le (a b : β€) : nat_abs (a + b) β€ nat_abs a + nat_abs b :=
begin
have : β (a b : β), nat_abs (sub_nat_nat a (nat.succ b)) β€ nat.succ (a + b),
{ refine (Ξ» a b : β, sub_nat_nat_elim a b.succ
(Ξ» m n i, n = b.succ β nat_abs i β€ (m + b).succ) _ _ rfl);
intros i n e,
{ subst e, rw [add_comm _ i, add_assoc],
exact nat.le_add_right i (b.succ + b).succ },
{ apply succ_le_succ,
rw [β succ.inj e, β add_assoc, add_comm],
apply nat.le_add_right } },
cases a; cases b with b b; simp [nat_abs, nat.succ_add];
try {refl}; [skip, rw add_comm a b]; apply this
end
theorem nat_abs_neg_of_nat (n : β) : nat_abs (neg_of_nat n) = n :=
by cases n; refl
theorem nat_abs_mul (a b : β€) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) :=
by cases a; cases b;
simp only [β int.mul_def, int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs]
lemma nat_abs_mul_nat_abs_eq {a b : β€} {c : β} (h : a * b = (c : β€)) :
a.nat_abs * b.nat_abs = c :=
by rw [β nat_abs_mul, h, nat_abs_of_nat]
@[simp] lemma nat_abs_mul_self' (a : β€) : (nat_abs a * nat_abs a : β€) = a * a :=
by rw [β int.coe_nat_mul, nat_abs_mul_self]
theorem neg_succ_of_nat_eq' (m : β) : -[1+ m] = -m - 1 :=
by simp [neg_succ_of_nat_eq, sub_eq_neg_add]
lemma nat_abs_ne_zero_of_ne_zero {z : β€} (hz : z β 0) : z.nat_abs β 0 :=
Ξ» h, hz $ int.eq_zero_of_nat_abs_eq_zero h
@[simp] lemma nat_abs_eq_zero {a : β€} : a.nat_abs = 0 β a = 0 :=
β¨int.eq_zero_of_nat_abs_eq_zero, Ξ» h, h.symm βΈ rflβ©
lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : β€} (wβ : 0 β€ a) (wβ : a < b) :
a.nat_abs < b.nat_abs :=
begin
lift b to β using le_trans wβ (le_of_lt wβ),
lift a to β using wβ,
simpa using wβ,
end
lemma nat_abs_eq_nat_abs_iff {a b : β€} : a.nat_abs = b.nat_abs β a = b β¨ a = -b :=
begin
split; intro h,
{ cases int.nat_abs_eq a with hβ hβ; cases int.nat_abs_eq b with hβ hβ;
rw [hβ, hβ]; simp [h], },
{ cases h; rw h, rw int.nat_abs_neg, },
end
lemma nat_abs_eq_iff_mul_self_eq {a b : β€} : a.nat_abs = b.nat_abs β a * a = b * b :=
begin
rw [β abs_eq_iff_mul_self_eq, abs_eq_nat_abs, abs_eq_nat_abs],
exact int.coe_nat_inj'.symm
end
lemma nat_abs_lt_iff_mul_self_lt {a b : β€} : a.nat_abs < b.nat_abs β a * a < b * b :=
begin
rw [β abs_lt_iff_mul_self_lt, abs_eq_nat_abs, abs_eq_nat_abs],
exact int.coe_nat_lt.symm
end
lemma nat_abs_le_iff_mul_self_le {a b : β€} : a.nat_abs β€ b.nat_abs β a * a β€ b * b :=
begin
rw [β abs_le_iff_mul_self_le, abs_eq_nat_abs, abs_eq_nat_abs],
exact int.coe_nat_le.symm
end
lemma nat_abs_eq_iff_sq_eq {a b : β€} : a.nat_abs = b.nat_abs β a ^ 2 = b ^ 2 :=
by { rw [pow_two, pow_two], exact nat_abs_eq_iff_mul_self_eq }
lemma nat_abs_lt_iff_sq_lt {a b : β€} : a.nat_abs < b.nat_abs β a ^ 2 < b ^ 2 :=
by { rw [pow_two, pow_two], exact nat_abs_lt_iff_mul_self_lt }
lemma nat_abs_le_iff_sq_le {a b : β€} : a.nat_abs β€ b.nat_abs β a ^ 2 β€ b ^ 2 :=
by { rw [pow_two, pow_two], exact nat_abs_le_iff_mul_self_le }
/-! ### `/` -/
@[simp] theorem of_nat_div (m n : β) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl
@[simp, norm_cast] theorem coe_nat_div (m n : β) : ((m / n : β) : β€) = m / n := rfl
theorem neg_succ_of_nat_div (m : β) {b : β€} (H : 0 < b) :
-[1+m] / b = -(m / b + 1) :=
match b, eq_succ_of_zero_lt H with ._, β¨n, rflβ© := rfl end
@[simp] protected theorem div_neg : β (a b : β€), a / -b = -(a / b)
| (m : β) 0 := show of_nat (m / 0) = -(m / 0 : β), by rw nat.div_zero; refl
| (m : β) (n+1:β) := rfl
| 0 -[1+ n] := rfl
| (m+1:β) -[1+ n] := (neg_neg _).symm
| -[1+ m] 0 := rfl
| -[1+ m] (n+1:β) := rfl
| -[1+ m] -[1+ n] := rfl
theorem div_of_neg_of_pos {a b : β€} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, β¨m, rflβ©, β¨n, rflβ© :=
by change (- -[1+ m] : β€) with (m+1 : β€); rw add_sub_cancel; refl
end
protected theorem div_nonneg {a b : β€} (Ha : 0 β€ a) (Hb : 0 β€ b) : 0 β€ a / b :=
match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with
| ._, ._, β¨m, rflβ©, β¨n, rflβ© := coe_zero_le _
end
protected theorem div_nonpos {a b : β€} (Ha : 0 β€ a) (Hb : b β€ 0) : a / b β€ 0 :=
nonpos_of_neg_nonneg $ by rw [β int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb)
theorem div_neg' {a b : β€} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, β¨m, rflβ©, β¨n, rflβ© := neg_succ_lt_zero _
end
-- Will be generalized to Euclidean domains.
protected theorem zero_div : β (b : β€), 0 / b = 0
| 0 := rfl
| (n+1:β) := rfl
| -[1+ n] := rfl
local attribute [simp] -- Will be generalized to Euclidean domains.
protected theorem div_zero : β (a : β€), a / 0 = 0
| 0 := rfl
| (n+1:β) := rfl
| -[1+ n] := rfl
@[simp] protected theorem div_one : β (a : β€), a / 1 = a
| 0 := rfl
| (n+1:β) := congr_arg of_nat (nat.div_one _)
| -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _)
theorem div_eq_zero_of_lt {a b : β€} (H1 : 0 β€ a) (H2 : a < b) : a / b = 0 :=
match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with
| ._, ._, β¨m, rflβ©, β¨n, rflβ©, H2 :=
congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2
end
theorem div_eq_zero_of_lt_abs {a b : β€} (H1 : 0 β€ a) (H2 : a < abs b) : a / b = 0 :=
match b, abs b, abs_eq_nat_abs b, H2 with
| (n : β), ._, rfl, H2 := div_eq_zero_of_lt H1 H2
| -[1+ n], ._, rfl, H2 := neg_injective $ by rw [β int.div_neg]; exact div_eq_zero_of_lt H1 H2
end
protected theorem add_mul_div_right (a b : β€) {c : β€} (H : c β 0) :
(a + b * c) / c = a / c + b :=
have β {k n : β} {a : β€}, (a + n * k.succ) / k.succ = a / k.succ + n, from
Ξ» k n a, match a with
| (m : β) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos
| -[1+ m] := show ((n * k.succ:β) - m.succ : β€) / k.succ =
n - (m / k.succ + 1 : β), begin
cases lt_or_ge m (n*k.succ) with h h,
{ rw [β int.coe_nat_sub h,
β int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)],
apply congr_arg of_nat,
rw [mul_comm, nat.mul_sub_div], rwa mul_comm },
{ change (β(n * nat.succ k) - (m + 1) : β€) / β(nat.succ k) =
βn - ((m / nat.succ k : β) + 1),
rw [β sub_sub, β sub_sub, β neg_sub (m:β€), β neg_sub _ (n:β€),
β int.coe_nat_sub h,
β int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h),
β neg_succ_of_nat_coe', β neg_succ_of_nat_coe'],
{ apply congr_arg neg_succ_of_nat,
rw [mul_comm, nat.sub_mul_div], rwa mul_comm } }
end
end,
have β {a b c : β€}, 0 < c β (a + b * c) / c = a / c + b, from
Ξ» a b c H, match c, eq_succ_of_zero_lt H, b with
| ._, β¨k, rflβ©, (n : β) := this
| ._, β¨k, rflβ©, -[1+ n] :=
show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from
eq_sub_of_add_eq $ by rw [β this, sub_add_cancel]
end,
match lt_trichotomy c 0 with
| or.inl hlt := neg_inj.1 $ by rw [β int.div_neg, neg_add, β int.div_neg, β neg_mul_neg];
apply this (neg_pos_of_neg hlt)
| or.inr (or.inl heq) := absurd heq H
| or.inr (or.inr hgt) := this hgt
end
protected theorem add_mul_div_left (a : β€) {b : β€} (c : β€) (H : b β 0) :
(a + b * c) / b = a / b + c :=
by rw [mul_comm, int.add_mul_div_right _ _ H]
protected theorem add_div_of_dvd_right {a b c : β€} (H : c β£ b) :
(a + b) / c = a / c + b / c :=
begin
by_cases h1 : c = 0,
{ simp [h1] },
cases H with k hk,
rw hk,
change c β 0 at h1,
rw [mul_comm c k, int.add_mul_div_right _ _ h1, βzero_add (k * c), int.add_mul_div_right _ _ h1,
int.zero_div, zero_add]
end
protected theorem add_div_of_dvd_left {a b c : β€} (H : c β£ a) :
(a + b) / c = a / c + b / c :=
by rw [add_comm, int.add_div_of_dvd_right H, add_comm]
@[simp] protected theorem mul_div_cancel (a : β€) {b : β€} (H : b β 0) : a * b / b = a :=
by have := int.add_mul_div_right 0 a H;
rwa [zero_add, int.zero_div, zero_add] at this
@[simp] protected theorem mul_div_cancel_left {a : β€} (b : β€) (H : a β 0) : a * b / a = b :=
by rw [mul_comm, int.mul_div_cancel _ H]
@[simp] protected theorem div_self {a : β€} (H : a β 0) : a / a = 1 :=
by have := int.mul_div_cancel 1 H; rwa one_mul at this
/-! ### mod -/
theorem of_nat_mod (m n : nat) : (m % n : β€) = of_nat (m % n) := rfl
@[simp, norm_cast] theorem coe_nat_mod (m n : β) : (β(m % n) : β€) = βm % βn := rfl
theorem neg_succ_of_nat_mod (m : β) {b : β€} (bpos : 0 < b) :
-[1+m] % b = b - 1 - m % b :=
by rw [sub_sub, add_comm]; exact
match b, eq_succ_of_zero_lt bpos with ._, β¨n, rflβ© := rfl end
@[simp] theorem mod_neg : β (a b : β€), a % -b = a % b
| (m : β) n := @congr_arg β β€ _ _ (Ξ» i, β(m % i)) (nat_abs_neg _)
| -[1+ m] n := @congr_arg β β€ _ _ (Ξ» i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _)
@[simp] theorem mod_abs (a b : β€) : a % (abs b) = a % b :=
abs_by_cases (Ξ» i, a % i = a % b) rfl (mod_neg _ _)
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem zero_mod (b : β€) : 0 % b = 0 :=
congr_arg of_nat $ nat.zero_mod _
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem mod_zero : β (a : β€), a % 0 = a
| (m : β) := congr_arg of_nat $ nat.mod_zero _
| -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem mod_one : β (a : β€), a % 1 = 0
| (m : β) := congr_arg of_nat $ nat.mod_one _
| -[1+ m] := show (1 - (m % 1).succ : β€) = 0, by rw nat.mod_one; refl
theorem mod_eq_of_lt {a b : β€} (H1 : 0 β€ a) (H2 : a < b) : a % b = a :=
match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with
| ._, ._, β¨m, rflβ©, β¨n, rflβ©, H2 :=
congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2)
end
theorem mod_nonneg : β (a : β€) {b : β€}, b β 0 β 0 β€ a % b
| (m : β) n H := coe_zero_le _
| -[1+ m] n H :=
sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H)
theorem mod_lt_of_pos (a : β€) {b : β€} (H : 0 < b) : a % b < b :=
match a, b, eq_succ_of_zero_lt H with
| (m : β), ._, β¨n, rflβ© := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _))
| -[1+ m], ._, β¨n, rflβ© := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _)
end
theorem mod_lt (a : β€) {b : β€} (H : b β 0) : a % b < abs b :=
by rw [β mod_abs]; exact mod_lt_of_pos _ (abs_pos.2 H)
theorem mod_add_div_aux (m n : β) : (n - (m % n + 1) - (n * (m / n) + n) : β€) = -[1+ m] :=
begin
rw [β sub_sub, neg_succ_of_nat_coe, sub_sub (n:β€)],
apply eq_neg_of_eq_neg,
rw [neg_sub, sub_sub_self, add_right_comm],
exact @congr_arg β β€ _ _ (Ξ»i, (i + 1 : β€)) (nat.mod_add_div _ _).symm
end
theorem mod_add_div : β (a b : β€), a % b + b * (a / b) = a
| (m : β) 0 := congr_arg of_nat (nat.mod_add_div _ _)
| (m : β) (n+1:β) := congr_arg of_nat (nat.mod_add_div _ _)
| 0 -[1+ n] := rfl
| (m+1:β) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : β) : β€) = _,
by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _)
| -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl
| -[1+ m] (n+1:β) := mod_add_div_aux m n.succ
| -[1+ m] -[1+ n] := mod_add_div_aux m n.succ
theorem div_add_mod (a b : β€) : b * (a / b) + a % b = a :=
(add_comm _ _).trans (mod_add_div _ _)
lemma mod_add_div' (m k : β€) : m % k + (m / k) * k = m :=
by { rw mul_comm, exact mod_add_div _ _ }
lemma div_add_mod' (m k : β€) : (m / k) * k + m % k = m :=
by { rw mul_comm, exact div_add_mod _ _ }
theorem mod_def (a b : β€) : a % b = a - b * (a / b) :=
eq_sub_of_add_eq (mod_add_div _ _)
@[simp] theorem add_mul_mod_self {a b c : β€} : (a + b * c) % c = a % c :=
if cz : c = 0 then by rw [cz, mul_zero, add_zero] else
by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz,
mul_add, mul_comm, add_sub_add_right_eq_sub]
@[simp] theorem add_mul_mod_self_left (a b c : β€) : (a + b * c) % b = a % b :=
by rw [mul_comm, add_mul_mod_self]
@[simp] theorem add_mod_self {a b : β€} : (a + b) % b = a % b :=
by have := add_mul_mod_self_left a b 1; rwa mul_one at this
@[simp] theorem add_mod_self_left {a b : β€} : (a + b) % a = b % a :=
by rw [add_comm, add_mod_self]
@[simp] theorem mod_add_mod (m n k : β€) : (m % n + k) % n = (m + k) % n :=
by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm;
rwa [add_right_comm, mod_add_div] at this
@[simp] theorem add_mod_mod (m n k : β€) : (m + n % k) % k = (m + n) % k :=
by rw [add_comm, mod_add_mod, add_comm]
lemma add_mod (a b n : β€) : (a + b) % n = ((a % n) + (b % n)) % n :=
by rw [add_mod_mod, mod_add_mod]
theorem add_mod_eq_add_mod_right {m n k : β€} (i : β€) (H : m % n = k % n) :
(m + i) % n = (k + i) % n :=
by rw [β mod_add_mod, β mod_add_mod k, H]
theorem add_mod_eq_add_mod_left {m n k : β€} (i : β€) (H : m % n = k % n) :
(i + m) % n = (i + k) % n :=
by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm]
theorem mod_add_cancel_right {m n k : β€} (i) : (m + i) % n = (k + i) % n β
m % n = k % n :=
β¨Ξ» H, by have := add_mod_eq_add_mod_right (-i) H;
rwa [add_neg_cancel_right, add_neg_cancel_right] at this,
add_mod_eq_add_mod_right _β©
theorem mod_add_cancel_left {m n k i : β€} :
(i + m) % n = (i + k) % n β m % n = k % n :=
by rw [add_comm, add_comm i, mod_add_cancel_right]
theorem mod_sub_cancel_right {m n k : β€} (i) : (m - i) % n = (k - i) % n β
m % n = k % n :=
mod_add_cancel_right _
theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : β€} : m % n = k % n β (m - k) % n = 0 :=
(mod_sub_cancel_right k).symm.trans $ by simp
@[simp] theorem mul_mod_left (a b : β€) : (a * b) % b = 0 :=
by rw [β zero_add (a * b), add_mul_mod_self, zero_mod]
@[simp] theorem mul_mod_right (a b : β€) : (a * b) % a = 0 :=
by rw [mul_comm, mul_mod_left]
lemma mul_mod (a b n : β€) : (a * b) % n = ((a % n) * (b % n)) % n :=
begin
conv_lhs {
rw [βmod_add_div a n, βmod_add_div' b n, right_distrib, left_distrib, left_distrib,
mul_assoc, mul_assoc, βleft_distrib n _ _, add_mul_mod_self_left, β mul_assoc,
add_mul_mod_self] }
end
@[simp] lemma neg_mod_two (i : β€) : (-i) % 2 = i % 2 :=
begin
apply int.mod_eq_mod_iff_mod_sub_eq_zero.mpr,
convert int.mul_mod_right 2 (-i),
simp only [two_mul, sub_eq_add_neg]
end
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem mod_self {a : β€} : a % a = 0 :=
by have := mul_mod_left 1 a; rwa one_mul at this
@[simp] theorem mod_mod_of_dvd (n : int) {m k : int} (h : m β£ k) : n % k % m = n % m :=
begin
conv { to_rhs, rw βmod_add_div n k },
rcases h with β¨t, rflβ©, rw [mul_assoc, add_mul_mod_self_left]
end
@[simp] theorem mod_mod (a b : β€) : a % b % b = a % b :=
by conv {to_rhs, rw [β mod_add_div a b, add_mul_mod_self_left]}
lemma sub_mod (a b n : β€) : (a - b) % n = ((a % n) - (b % n)) % n :=
begin
apply (mod_add_cancel_right b).mp,
rw [sub_add_cancel, β add_mod_mod, sub_add_cancel, mod_mod]
end
/-! ### properties of `/` and `%` -/
@[simp] theorem mul_div_mul_of_pos {a : β€} (b c : β€) (H : 0 < a) : a * b / (a * c) = b / c :=
suffices β (m k : β) (b : β€), (m.succ * b / (m.succ * k) : β€) = b / k, from
match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with
| ._, β¨m, rflβ©, ._, β¨k, or.inl rflβ© := this _ _ _
| ._, β¨m, rflβ©, ._, β¨k, or.inr rflβ© :=
by rw [β neg_mul_eq_mul_neg, int.div_neg, int.div_neg];
apply congr_arg has_neg.neg; apply this
end,
Ξ» m k b, match b, k with
| (n : β), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos)
| -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero]
| -[1+ n], k+1 := congr_arg neg_succ_of_nat $
show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin
apply nat.div_eq_of_lt_le,
{ refine le_trans _ (nat.le_add_right _ _),
rw [β nat.mul_div_mul _ _ m.succ_pos],
apply nat.div_mul_le_self },
{ change m.succ * n.succ β€ _,
rw [mul_left_comm],
apply nat.mul_le_mul_left,
apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1,
apply nat.lt_succ_self }
end
end
@[simp] theorem mul_div_mul_of_pos_left (a : β€) {b : β€} (c : β€) (H : 0 < b) :
a * b / (c * b) = a / c :=
by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H]
@[simp] theorem mul_mod_mul_of_pos {a : β€} (b c : β€) (H : 0 < a) : a * b % (a * c) = a * (b % c) :=
by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc]
theorem lt_div_add_one_mul_self (a : β€) {b : β€} (H : 0 < b) : a < (a / b + 1) * b :=
by { rw [add_mul, one_mul, mul_comm, β sub_lt_iff_lt_add', β mod_def],
exact mod_lt_of_pos _ H }
theorem abs_div_le_abs : β (a b : β€), abs (a / b) β€ abs a :=
suffices β (a : β€) (n : β), abs (a / n) β€ abs a, from
Ξ» a b, match b, eq_coe_or_neg b with
| ._, β¨n, or.inl rflβ© := this _ _
| ._, β¨n, or.inr rflβ© := by rw [int.div_neg, abs_neg]; apply this
end,
Ξ» a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact
coe_nat_le_coe_nat_of_le (match a, n with
| (m : β), n := nat.div_le_self _ _
| -[1+ m], 0 := nat.zero_le _
| -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _)
end)
theorem div_le_self {a : β€} (b : β€) (Ha : 0 β€ a) : a / b β€ a :=
by have := le_trans (le_abs_self _) (abs_div_le_abs a b);
rwa [abs_of_nonneg Ha] at this
theorem mul_div_cancel_of_mod_eq_zero {a b : β€} (H : a % b = 0) : b * (a / b) = a :=
by have := mod_add_div a b; rwa [H, zero_add] at this
theorem div_mul_cancel_of_mod_eq_zero {a b : β€} (H : a % b = 0) : a / b * b = a :=
by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H]
lemma mod_two_eq_zero_or_one (n : β€) : n % 2 = 0 β¨ n % 2 = 1 :=
have h : n % 2 < 2 := abs_of_nonneg (show 0 β€ (2 : β€), from dec_trivial) βΈ int.mod_lt _ dec_trivial,
have hβ : 0 β€ n % 2 := int.mod_nonneg _ dec_trivial,
match (n % 2), h, hβ with
| (0 : β) := Ξ» _ _, or.inl rfl
| (1 : β) := Ξ» _ _, or.inr rfl
| (k + 2 : β) := Ξ» h _, absurd h dec_trivial
| -[1+ a] := Ξ» _ hβ, absurd hβ dec_trivial
end
/-! ### dvd -/
@[norm_cast] theorem coe_nat_dvd {m n : β} : (βm : β€) β£ βn β m β£ n :=
β¨Ξ» β¨a, aeβ©, m.eq_zero_or_pos.elim
(Ξ»m0, by simp [m0] at ae; simp [ae, m0])
(Ξ»m0l, by {
cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left β€ _ m a
(by simp [ae.symm]) (by simpa using m0l)) with k e,
subst a, exact β¨k, int.coe_nat_inj aeβ© }),
Ξ» β¨k, eβ©, dvd.intro k $ by rw [e, int.coe_nat_mul]β©
theorem coe_nat_dvd_left {n : β} {z : β€} : (βn : β€) β£ z β n β£ z.nat_abs :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem coe_nat_dvd_right {n : β} {z : β€} : z β£ (βn : β€) β z.nat_abs β£ n :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem dvd_antisymm {a b : β€} (H1 : 0 β€ a) (H2 : 0 β€ b) : a β£ b β b β£ a β a = b :=
begin
rw [β abs_of_nonneg H1, β abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs],
rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'],
apply nat.dvd_antisymm
end
theorem dvd_of_mod_eq_zero {a b : β€} (H : b % a = 0) : a β£ b :=
β¨b / a, (mul_div_cancel_of_mod_eq_zero H).symmβ©
theorem mod_eq_zero_of_dvd : β {a b : β€}, a β£ b β b % a = 0
| a ._ β¨c, rflβ© := mul_mod_right _ _
theorem dvd_iff_mod_eq_zero (a b : β€) : a β£ b β b % a = 0 :=
β¨mod_eq_zero_of_dvd, dvd_of_mod_eq_zeroβ©
/-- If `a % b = c` then `b` divides `a - c`. -/
lemma dvd_sub_of_mod_eq {a b c : β€} (h : a % b = c) : b β£ a - c :=
begin
have hx : a % b % b = c % b, { rw h },
rw [mod_mod, βmod_sub_cancel_right c, sub_self, zero_mod] at hx,
exact dvd_of_mod_eq_zero hx
end
theorem nat_abs_dvd {a b : β€} : (a.nat_abs : β€) β£ b β a β£ b :=
(nat_abs_eq a).elim (Ξ» e, by rw β e) (Ξ» e, by rw [β neg_dvd_iff_dvd, β e])
theorem dvd_nat_abs {a b : β€} : a β£ b.nat_abs β a β£ b :=
(nat_abs_eq b).elim (Ξ» e, by rw β e) (Ξ» e, by rw [β dvd_neg_iff_dvd, β e])
instance decidable_dvd : @decidable_rel β€ (β£) :=
assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm
protected theorem div_mul_cancel {a b : β€} (H : b β£ a) : a / b * b = a :=
div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H)
protected theorem mul_div_cancel' {a b : β€} (H : a β£ b) : a * (b / a) = b :=
by rw [mul_comm, int.div_mul_cancel H]
protected theorem mul_div_assoc (a : β€) : β {b c : β€}, c β£ b β (a * b) / c = a * (b / c)
| ._ c β¨d, rflβ© := if cz : c = 0 then by simp [cz] else
by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz]
protected theorem mul_div_assoc' (b : β€) {a c : β€} (h : c β£ a) : a * b / c = a / c * b :=
by rw [mul_comm, int.mul_div_assoc _ h, mul_comm]
theorem div_dvd_div : β {a b c : β€} (H1 : a β£ b) (H2 : b β£ c), b / a β£ c / a
| a ._ ._ β¨b, rflβ© β¨c, rflβ© := if az : a = 0 then by simp [az] else
by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az];
apply dvd_mul_right
protected theorem eq_mul_of_div_eq_right {a b c : β€} (H1 : b β£ a) (H2 : a / b = c) :
a = b * c :=
by rw [β H2, int.mul_div_cancel' H1]
protected theorem div_eq_of_eq_mul_right {a b c : β€} (H1 : b β 0) (H2 : a = b * c) :
a / b = c :=
by rw [H2, int.mul_div_cancel_left _ H1]
protected theorem eq_div_of_mul_eq_right {a b c : β€} (H1 : a β 0) (H2 : a * b = c) :
b = c / a :=
eq.symm $ int.div_eq_of_eq_mul_right H1 H2.symm
protected theorem div_eq_iff_eq_mul_right {a b c : β€} (H : b β 0) (H' : b β£ a) :
a / b = c β a = b * c :=
β¨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right Hβ©
protected theorem div_eq_iff_eq_mul_left {a b c : β€} (H : b β 0) (H' : b β£ a) :
a / b = c β a = c * b :=
by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H'
protected theorem eq_mul_of_div_eq_left {a b c : β€} (H1 : b β£ a) (H2 : a / b = c) :
a = c * b :=
by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2]
protected theorem div_eq_of_eq_mul_left {a b c : β€} (H1 : b β 0) (H2 : a = c * b) :
a / b = c :=
int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2])
theorem neg_div_of_dvd : β {a b : β€} (H : b β£ a), -a / b = -(a / b)
| ._ b β¨c, rflβ© := if bz : b = 0 then by simp [bz] else
by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz]
lemma sub_div_of_dvd {a b c : β€} (hcb : c β£ b) : (a - b) / c = a / c - b / c :=
begin
rw [sub_eq_add_neg, sub_eq_add_neg, int.add_div_of_dvd_right ((dvd_neg c b).mpr hcb)],
congr,
exact neg_div_of_dvd hcb,
end
lemma sub_div_of_dvd_sub {a b c : β€} (hcab : c β£ (a - b)) : (a - b) / c = a / c - b / c :=
by rw [eq_sub_iff_add_eq, β int.add_div_of_dvd_left hcab, sub_add_cancel]
theorem div_sign : β a b, a / sign b = a * sign b
| a (n+1:β) := by unfold sign; simp
| a 0 := by simp [sign]
| a -[1+ n] := by simp [sign]
@[simp] theorem sign_mul : β a b, sign (a * b) = sign a * sign b
| a 0 := by simp
| 0 b := by simp
| (m+1:β) (n+1:β) := rfl
| (m+1:β) -[1+ n] := rfl
| -[1+ m] (n+1:β) := rfl
| -[1+ m] -[1+ n] := rfl
protected theorem sign_eq_div_abs (a : β€) : sign a = a / (abs a) :=
if az : a = 0 then by simp [az] else
(int.div_eq_of_eq_mul_left (mt abs_eq_zero.1 az)
(sign_mul_abs _).symm).symm
theorem mul_sign : β (i : β€), i * sign i = nat_abs i
| (n+1:β) := mul_one _
| 0 := mul_zero _
| -[1+ n] := mul_neg_one _
theorem le_of_dvd {a b : β€} (bpos : 0 < b) (H : a β£ b) : a β€ b :=
match a, b, eq_succ_of_zero_lt bpos, H with
| (m : β), ._, β¨n, rflβ©, H := coe_nat_le_coe_nat_of_le $
nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H
| -[1+ m], ._, β¨n, rflβ©, _ :=
le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _)
end
theorem eq_one_of_dvd_one {a : β€} (H : 0 β€ a) (H' : a β£ 1) : a = 1 :=
match a, eq_coe_of_zero_le H, H' with
| ._, β¨n, rflβ©, H' := congr_arg coe $
nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H'
end
theorem eq_one_of_mul_eq_one_right {a b : β€} (H : 0 β€ a) (H' : a * b = 1) : a = 1 :=
eq_one_of_dvd_one H β¨b, H'.symmβ©
theorem eq_one_of_mul_eq_one_left {a b : β€} (H : 0 β€ b) (H' : a * b = 1) : b = 1 :=
eq_one_of_mul_eq_one_right H (by rw [mul_comm, H'])
lemma of_nat_dvd_of_dvd_nat_abs {a : β} : β {z : β€} (haz : a β£ z.nat_abs), βa β£ z
| (int.of_nat _) haz := int.coe_nat_dvd.2 haz
| -[1+k] haz :=
begin
change βa β£ -(k+1 : β€),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
exact haz
end
lemma dvd_nat_abs_of_of_nat_dvd {a : β} : β {z : β€} (haz : βa β£ z), a β£ z.nat_abs
| (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz)
| -[1+k] haz :=
have haz' : (βa:β€) β£ (β(k+1):β€), from dvd_of_dvd_neg haz,
int.coe_nat_dvd.1 haz'
lemma pow_dvd_of_le_of_pow_dvd {p m n : β} {k : β€} (hmn : m β€ n) (hdiv : β(p ^ n) β£ k) :
β(p ^ m) β£ k :=
begin
induction k,
{ apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1 hdiv },
{ change -[1+k] with -(β(k+1) : β€),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1,
apply dvd_of_dvd_neg,
exact hdiv }
end
lemma dvd_of_pow_dvd {p k : β} {m : β€} (hk : 1 β€ k) (hpk : β(p^k) β£ m) : βp β£ m :=
by rw βpow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk
/-- If `n > 0` then `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)`
for some `k`. -/
lemma exists_lt_and_lt_iff_not_dvd (m : β€) {n : β€} (hn : 0 < n) :
(β k, n * k < m β§ m < n * (k + 1)) β Β¬ n β£ m :=
begin
split,
{ rintro β¨k, h1k, h2kβ© β¨l, rflβ©, rw [mul_lt_mul_left hn] at h1k h2k,
rw [lt_add_one_iff, β not_lt] at h2k, exact h2k h1k },
{ intro h, rw [dvd_iff_mod_eq_zero, β ne.def] at h,
have := (mod_nonneg m hn.ne.symm).lt_of_ne h.symm,
simp only [β mod_add_div m n] {single_pass := tt},
refine β¨m / n, lt_add_of_pos_left _ this, _β©,
rw [add_comm _ (1 : β€), left_distrib, mul_one], exact add_lt_add_right (mod_lt_of_pos _ hn) _ }
end
/-! ### `/` and ordering -/
protected theorem div_mul_le (a : β€) {b : β€} (H : b β 0) : a / b * b β€ a :=
le_of_sub_nonneg $ by rw [mul_comm, β mod_def]; apply mod_nonneg _ H
protected theorem div_le_of_le_mul {a b c : β€} (H : 0 < c) (H' : a β€ b * c) : a / c β€ b :=
le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H
protected theorem mul_lt_of_lt_div {a b c : β€} (H : 0 < c) (H3 : a < b / c) : a * c < b :=
lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3)
protected theorem mul_le_of_le_div {a b c : β€} (H1 : 0 < c) (H2 : a β€ b / c) : a * c β€ b :=
le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1))
protected theorem le_div_of_mul_le {a b c : β€} (H1 : 0 < c) (H2 : a * c β€ b) : a β€ b / c :=
le_of_lt_add_one $ lt_of_mul_lt_mul_right
(lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1)
protected theorem le_div_iff_mul_le {a b c : β€} (H : 0 < c) : a β€ b / c β a * c β€ b :=
β¨int.mul_le_of_le_div H, int.le_div_of_mul_le Hβ©
protected theorem div_le_div {a b c : β€} (H : 0 < c) (H' : a β€ b) : a / c β€ b / c :=
int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H')
protected theorem div_lt_of_lt_mul {a b c : β€} (H : 0 < c) (H' : a < b * c) : a / c < b :=
lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H')
protected theorem lt_mul_of_div_lt {a b c : β€} (H1 : 0 < c) (H2 : a / c < b) : a < b * c :=
lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2)
protected theorem div_lt_iff_lt_mul {a b c : β€} (H : 0 < c) : a / c < b β a < b * c :=
β¨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul Hβ©
protected theorem le_mul_of_div_le {a b c : β€} (H1 : 0 β€ b) (H2 : b β£ a) (H3 : a / b β€ c) :
a β€ c * b :=
by rw [β int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1
protected theorem lt_div_of_mul_lt {a b c : β€} (H1 : 0 β€ b) (H2 : b β£ c) (H3 : a * b < c) :
a < c / b :=
lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3)
protected theorem lt_div_iff_mul_lt {a b : β€} (c : β€) (H : 0 < c) (H' : c β£ b) :
a < b / c β a * c < b :=
β¨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'β©
theorem div_pos_of_pos_of_dvd {a b : β€} (H1 : 0 < a) (H2 : 0 β€ b) (H3 : b β£ a) : 0 < a / b :=
int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul)
theorem div_eq_div_of_mul_eq_mul {a b c d : β€} (H2 : d β£ c) (H3 : b β 0)
(H4 : d β 0) (H5 : a * d = b * c) :
a / b = c / d :=
int.div_eq_of_eq_mul_right H3 $
by rw [β int.mul_div_assoc _ H2]; exact
(int.div_eq_of_eq_mul_left H4 H5.symm).symm
theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : β€} (hb : b β 0) (hbc : b β£ c)
(h : b * a = c * d) : a = c / b * d :=
begin
cases hbc with k hk,
subst hk,
rw [int.mul_div_cancel_left _ hb],
rw mul_assoc at h,
apply mul_left_cancel' hb h
end
/-- If an integer with larger absolute value divides an integer, it is
zero. -/
lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : β€} (w : a β£ b) (h : nat_abs b < nat_abs a) :
b = 0 :=
begin
rw [βnat_abs_dvd, βdvd_nat_abs, coe_nat_dvd] at w,
rw βnat_abs_eq_zero,
exact eq_zero_of_dvd_of_lt w h
end
lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : β€} (wβ : 0 β€ a) (wβ : a < b) (h : b β£ a) : a = 0 :=
eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt wβ wβ)
/-- If two integers are congruent to a sufficiently large modulus,
they are equal. -/
lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : β€} (h1 : a % b = c)
(h2 : nat_abs (a - c) < nat_abs b) :
a = c :=
eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2)
theorem of_nat_add_neg_succ_of_nat_of_lt {m n : β}
(h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = (n - m).succ,
apply succ_sub,
apply le_of_lt_succ h,
simp [*, sub_nat_nat]
end
theorem of_nat_add_neg_succ_of_nat_of_ge {m n : β}
(h : n.succ β€ m) : of_nat m + -[1+n] = of_nat (m - n.succ) :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = 0,
apply sub_eq_zero_of_le h,
simp [*, sub_nat_nat]
end
@[simp] theorem neg_add_neg (m n : β) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl
/-! ### to_nat -/
theorem to_nat_eq_max : β (a : β€), (to_nat a : β€) = max a 0
| (n : β) := (max_eq_left (coe_zero_le n)).symm
| -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm
@[simp] lemma to_nat_zero : (0 : β€).to_nat = 0 := rfl
@[simp] lemma to_nat_one : (1 : β€).to_nat = 1 := rfl
@[simp] theorem to_nat_of_nonneg {a : β€} (h : 0 β€ a) : (to_nat a : β€) = a :=
by rw [to_nat_eq_max, max_eq_left h]
@[simp] lemma to_nat_sub_of_le (a b : β€) (h : b β€ a) : (to_nat (a + -b) : β€) = a + - b :=
int.to_nat_of_nonneg (sub_nonneg_of_le h)
@[simp] theorem to_nat_coe_nat (n : β) : to_nat βn = n := rfl
@[simp] lemma to_nat_coe_nat_add_one {n : β} : ((n : β€) + 1).to_nat = n + 1 := rfl
theorem le_to_nat (a : β€) : a β€ to_nat a :=
by rw [to_nat_eq_max]; apply le_max_left
@[simp] theorem to_nat_le {a : β€} {n : β} : to_nat a β€ n β a β€ n :=
by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff];
exact and_iff_left (coe_zero_le _)
@[simp] theorem lt_to_nat {n : β} {a : β€} : n < to_nat a β (n : β€) < a :=
le_iff_le_iff_lt_iff_lt.1 to_nat_le
theorem to_nat_le_to_nat {a b : β€} (h : a β€ b) : to_nat a β€ to_nat b :=
by rw to_nat_le; exact le_trans h (le_to_nat b)
theorem to_nat_lt_to_nat {a b : β€} (hb : 0 < b) : to_nat a < to_nat b β a < b :=
β¨Ξ» h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end,
Ξ» h, begin rw lt_to_nat, cases a, exact h, exact hb endβ©
theorem lt_of_to_nat_lt {a b : β€} (h : to_nat a < to_nat b) : a < b :=
(to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h
lemma to_nat_add {a b : β€} (ha : 0 β€ a) (hb : 0 β€ b) :
(a + b).to_nat = a.to_nat + b.to_nat :=
begin
lift a to β using ha,
lift b to β using hb,
norm_cast,
end
lemma to_nat_add_one {a : β€} (h : 0 β€ a) : (a + 1).to_nat = a.to_nat + 1 :=
to_nat_add h (zero_le_one)
@[simp]
lemma pred_to_nat : β (i : β€), (i - 1).to_nat = i.to_nat - 1
| (0:β) := rfl
| (n+1:β) := by simp
| -[1+ n] := rfl
@[simp]
lemma to_nat_pred_coe_of_pos {i : β€} (h : 0 < i) : ((i.to_nat - 1 : β) : β€) = i - 1 :=
by simp [h, le_of_lt h] with push_cast
/-- If `n : β`, then `int.to_nat' n = some n`, if `n : β€` is negative, then `int.to_nat' n = none`.
-/
def to_nat' : β€ β option β
| (n : β) := some n
| -[1+ n] := none
theorem mem_to_nat' : β (a : β€) (n : β), n β to_nat' a β a = n
| (m : β) n := option.some_inj.trans coe_nat_inj'.symm
| -[1+ m] n := by split; intro h; cases h
lemma to_nat_zero_of_neg : β {z : β€}, z < 0 β z.to_nat = 0
| (-[1+n]) _ := rfl
| (int.of_nat n) h := (not_le_of_gt h $ int.of_nat_nonneg n).elim
/-! ### units -/
@[simp] theorem units_nat_abs (u : units β€) : nat_abs u = 1 :=
units.ext_iff.1 $ nat.units_eq_one β¨nat_abs u, nat_abs βuβ»ΒΉ,
by rw [β nat_abs_mul, units.mul_inv]; refl,
by rw [β nat_abs_mul, units.inv_mul]; reflβ©
theorem units_eq_one_or (u : units β€) : u = 1 β¨ u = -1 :=
by simpa only [units.ext_iff, units_nat_abs] using nat_abs_eq u
lemma units_inv_eq_self (u : units β€) : uβ»ΒΉ = u :=
(units_eq_one_or u).elim (Ξ» h, h.symm βΈ rfl) (Ξ» h, h.symm βΈ rfl)
@[simp] lemma units_mul_self (u : units β€) : u * u = 1 :=
(units_eq_one_or u).elim (Ξ» h, h.symm βΈ rfl) (Ξ» h, h.symm βΈ rfl)
-- `units.coe_mul` is a "wrong turn" for the simplifier, this undoes it and simplifies further
@[simp] lemma units_coe_mul_self (u : units β€) : (u * u : β€) = 1 :=
by rw [βunits.coe_mul, units_mul_self, units.coe_one]
@[simp] lemma neg_one_pow_ne_zero {n : β} : (-1 : β€)^n β 0 :=
pow_ne_zero _ (abs_pos.mp trivial)
/-! ### bitwise ops -/
@[simp] lemma bodd_zero : bodd 0 = ff := rfl
@[simp] lemma bodd_one : bodd 1 = tt := rfl
lemma bodd_two : bodd 2 = ff := rfl
@[simp, norm_cast] lemma bodd_coe (n : β) : int.bodd n = nat.bodd n := rfl
@[simp] lemma bodd_sub_nat_nat (m n : β) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd :=
by apply sub_nat_nat_elim m n (Ξ» m n i, bodd i = bxor m.bodd n.bodd); intros;
simp; cases i.bodd; simp
@[simp] lemma bodd_neg_of_nat (n : β) : bodd (neg_of_nat n) = n.bodd :=
by cases n; simp; refl
@[simp] lemma bodd_neg (n : β€) : bodd (-n) = bodd n :=
by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe]
@[simp] lemma bodd_add (m n : β€) : bodd (m + n) = bxor (bodd m) (bodd n) :=
by cases m with m m; cases n with n n; unfold has_add.add;
simp [int.add, -of_nat_eq_coe, bool.bxor_comm]
@[simp] lemma bodd_mul (m n : β€) : bodd (m * n) = bodd m && bodd n :=
by cases m with m m; cases n with n n;
simp [β int.mul_def, int.mul, -of_nat_eq_coe, bool.bxor_comm]
theorem bodd_add_div2 : β n, cond (bodd n) 1 0 + 2 * div2 n = n
| (n : β) :=
by rw [show (cond (bodd n) 1 0 : β€) = (cond (bodd n) 1 0 : β),
by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2
| -[1+ n] := begin
refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2),
dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul],
{ change -[1+ 2 * nat.div2 n] = _, rw zero_add },
{ rw [zero_add, add_comm], refl }
end
theorem div2_val : β n, div2 n = n / 2
| (n : β) := congr_arg of_nat n.div2_val
| -[1+ n] := congr_arg neg_succ_of_nat n.div2_val
lemma bit0_val (n : β€) : bit0 n = 2 * n := (two_mul _).symm
lemma bit1_val (n : β€) : bit1 n = 2 * n + 1 := congr_arg (+(1:β€)) (bit0_val _)
lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 :=
by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val }
lemma bit_decomp (n : β€) : bit (bodd n) (div2 n) = n :=
(bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _
/-- Defines a function from `β€` conditionally, if it is defined for odd and even integers separately
using `bit`. -/
def {u} bit_cases_on {C : β€ β Sort u} (n) (h : β b n, C (bit b n)) : C n :=
by rw [β bit_decomp n]; apply h
@[simp] lemma bit_zero : bit ff 0 = 0 := rfl
@[simp] lemma bit_coe_nat (b) (n : β) : bit b n = nat.bit b n :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bit_neg_succ (b) (n : β) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bodd_bit (b n) : bodd (bit b n) = b :=
by rw bit_val; simp; cases b; cases bodd n; refl
@[simp] lemma bodd_bit0 (n : β€) : bodd (bit0 n) = ff := bodd_bit ff n
@[simp] lemma bodd_bit1 (n : β€) : bodd (bit1 n) = tt := bodd_bit tt n
@[simp] lemma div2_bit (b n) : div2 (bit b n) = n :=
begin
rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:β€) = 0), zero_add],
cases b, all_goals {exact dec_trivial}
end
lemma bit0_ne_bit1 (m n : β€) : bit0 m β bit1 n :=
mt (congr_arg bodd) $ by simp
lemma bit1_ne_bit0 (m n : β€) : bit1 m β bit0 n :=
(bit0_ne_bit1 _ _).symm
lemma bit1_ne_zero (m : β€) : bit1 m β 0 :=
by simpa only [bit0_zero] using bit1_ne_bit0 m 0
@[simp] lemma test_bit_zero (b) : β n, test_bit (bit b n) 0 = b
| (n : β) := by rw [bit_coe_nat]; apply nat.test_bit_zero
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero];
clear test_bit_zero; cases b; refl
@[simp] lemma test_bit_succ (m b) : β n, test_bit (bit b n) (nat.succ m) = test_bit n m
| (n : β) := by rw [bit_coe_nat]; apply nat.test_bit_succ
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ]
private meta def bitwise_tac : tactic unit := `[
funext m,
funext n,
cases m with m m; cases n with n n; try {refl},
all_goals {
apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat,
try {dsimp [nat.land, nat.ldiff, nat.lor]},
try {rw [
show nat.bitwise (Ξ» a b, a && bnot b) n m =
nat.bitwise (Ξ» a b, b && bnot a) m n, from
congr_fun (congr_fun (@nat.bitwise_swap (Ξ» a b, b && bnot a) rfl) n) m]},
apply congr_arg (Ξ» f, nat.bitwise f m n),
funext a,
funext b,
cases a; cases b; refl
},
all_goals {unfold nat.land nat.ldiff nat.lor}
]
theorem bitwise_or : bitwise bor = lor := by bitwise_tac
theorem bitwise_and : bitwise band = land := by bitwise_tac
theorem bitwise_diff : bitwise (Ξ» a b, a && bnot b) = ldiff := by bitwise_tac
theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac
@[simp] lemma bitwise_bit (f : bool β bool β bool) (a m b n) :
bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) :=
begin
cases m with m m; cases n with n n;
repeat { rw [β int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ };
unfold bitwise nat_bitwise bnot;
[ induction h : f ff ff,
induction h : f ff tt,
induction h : f tt ff,
induction h : f tt tt ],
all_goals {
unfold cond, rw nat.bitwise_bit,
repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } },
all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl }
end
@[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) :=
by rw [β bitwise_or, bitwise_bit]
@[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) :=
by rw [β bitwise_and, bitwise_bit]
@[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) :=
by rw [β bitwise_diff, bitwise_bit]
@[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) :=
by rw [β bitwise_xor, bitwise_bit]
@[simp] lemma lnot_bit (b) : β n, lnot (bit b n) = bit (bnot b) (lnot n)
| (n : β) := by simp [lnot]
| -[1+ n] := by simp [lnot]
@[simp] lemma test_bit_bitwise (f : bool β bool β bool) (m n k) :
test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) :=
begin
induction k with k IH generalizing m n;
apply bit_cases_on m; intros a m';
apply bit_cases_on n; intros b n';
rw bitwise_bit,
{ simp [test_bit_zero] },
{ simp [test_bit_succ, IH] }
end
@[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k :=
by rw [β bitwise_or, test_bit_bitwise]
@[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k :=
by rw [β bitwise_and, test_bit_bitwise]
@[simp]
lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) :=
by rw [β bitwise_diff, test_bit_bitwise]
@[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) :=
by rw [β bitwise_xor, test_bit_bitwise]
@[simp] lemma test_bit_lnot : β n k, test_bit (lnot n) k = bnot (test_bit n k)
| (n : β) k := by simp [lnot, test_bit]
| -[1+ n] k := by simp [lnot, test_bit]
lemma shiftl_add : β (m : β€) (n : β) (k : β€), shiftl m (n + k) = shiftl (shiftl m n) k
| (m : β) n (k:β) := congr_arg of_nat (nat.shiftl_add _ _ _)
| -[1+ m] n (k:β) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _)
| (m : β) n -[1+k] := sub_nat_nat_elim n k.succ
(Ξ» n k i, shiftl βm i = nat.shiftr (nat.shiftl m n) k)
(Ξ» i n, congr_arg coe $
by rw [β nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right)
(Ξ» i n, congr_arg coe $
by rw [add_assoc, nat.shiftr_add, β nat.shiftl_sub, nat.sub_self]; refl)
| -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ
(Ξ» n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k])
(Ξ» i n, congr_arg neg_succ_of_nat $
by rw [β nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right)
(Ξ» i n, congr_arg neg_succ_of_nat $
by rw [add_assoc, nat.shiftr_add, β nat.shiftl'_sub, nat.sub_self]; refl)
lemma shiftl_sub (m : β€) (n : β) (k : β€) : shiftl m (n - k) = shiftr (shiftl m n) k :=
shiftl_add _ _ _
@[simp] lemma shiftl_neg (m n : β€) : shiftl m (-n) = shiftr m n := rfl
@[simp] lemma shiftr_neg (m n : β€) : shiftr m (-n) = shiftl m n := by rw [β shiftl_neg, neg_neg]
@[simp] lemma shiftl_coe_nat (m n : β) : shiftl m n = nat.shiftl m n := rfl
@[simp] lemma shiftr_coe_nat (m n : β) : shiftr m n = nat.shiftr m n := by cases n; refl
@[simp] lemma shiftl_neg_succ (m n : β) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl
@[simp]
lemma shiftr_neg_succ (m n : β) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl
lemma shiftr_add : β (m : β€) (n k : β), shiftr m (n + k) = shiftr (shiftr m n) k
| (m : β) n k := by rw [shiftr_coe_nat, shiftr_coe_nat,
β int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add]
| -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ,
β int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add]
lemma shiftl_eq_mul_pow : β (m : β€) (n : β), shiftl m n = m * β(2 ^ n)
| (m : β) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _)
| -[1+ m] n := @congr_arg β β€ _ _ (Ξ»i, -i) (nat.shiftl'_tt_eq_mul_pow _ _)
lemma shiftr_eq_div_pow : β (m : β€) (n : β), shiftr m n = m / β(2 ^ n)
| (m : β) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _)
| -[1+ m] n := begin
rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl,
exact coe_nat_lt_coe_nat_of_lt (pow_pos dec_trivial _)
end
lemma one_shiftl (n : β) : shiftl 1 n = (2 ^ n : β) :=
congr_arg coe (nat.one_shiftl _)
@[simp] lemma zero_shiftl : β n : β€, shiftl 0 n = 0
| (n : β) := congr_arg coe (nat.zero_shiftl _)
| -[1+ n] := congr_arg coe (nat.zero_shiftr _)
@[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _
/-! ### Least upper bound property for integers -/
section classical
open_locale classical
theorem exists_least_of_bdd {P : β€ β Prop}
(Hbdd : β b : β€, β z : β€, P z β b β€ z)
(Hinh : β z : β€, P z) : β lb : β€, P lb β§ (β z : β€, P z β lb β€ z) :=
let β¨b, Hbβ© := Hbdd in
have EX : β n : β, P (b + n), from
let β¨elt, Heltβ© := Hinh in
match elt, le.dest (Hb _ Helt), Helt with
| ._, β¨n, rflβ©, Hn := β¨n, Hnβ©
end,
β¨b + (nat.find EX : β€), nat.find_spec EX, Ξ» z h,
match z, le.dest (Hb _ h), h with
| ._, β¨n, rflβ©, h := add_le_add_left
(int.coe_nat_le.2 $ nat.find_min' _ h) _
endβ©
theorem exists_greatest_of_bdd {P : β€ β Prop}
(Hbdd : β b : β€, β z : β€, P z β z β€ b)
(Hinh : β z : β€, P z) : β ub : β€, P ub β§ (β z : β€, P z β z β€ ub) :=
have Hbdd' : β (b : β€), β (z : β€), P (-z) β b β€ z, from
let β¨b, Hbβ© := Hbdd in β¨-b, Ξ» z h, neg_le.1 (Hb _ h)β©,
have Hinh' : β z : β€, P (-z), from
let β¨elt, Heltβ© := Hinh in β¨-elt, by rw [neg_neg]; exact Heltβ©,
let β¨lb, Plb, alβ© := exists_least_of_bdd Hbdd' Hinh' in
β¨-lb, Plb, Ξ» z h, le_neg.1 $ al _ $ by rwa neg_negβ©
end classical
end int
attribute [irreducible] int.nonneg
|
143c897ce9c8a4096f8675be7cf6c119bdc92ff0 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1236.lean | 3d6001f94bc93a083af84b8b239583db2477db70 | [
"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 | 38 | lean | example: x β€ x * 2 := by simp_arith
|
9e8c5b1ef51b835abd734139124fc70d6d8d067c | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/subobject/lattice.lean | 126de21d00991b6bdd980ce55eaac0001d025f40 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 23,988 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Scott Morrison
-/
import category_theory.subobject.factor_thru
import category_theory.subobject.well_powered
/-!
# The lattice of subobjects
We provide the `semilattice_inf` with `order_top (subobject X)` instance when `[has_pullback C]`,
and the `semilattice_sup (subobject X)` instance when `[has_images C] [has_binary_coproducts C]`.
-/
universes vβ vβ uβ uβ
noncomputable theory
open category_theory category_theory.category category_theory.limits
variables {C : Type uβ} [category.{vβ} C] {X Y Z : C}
variables {D : Type uβ} [category.{vβ} D]
namespace category_theory
namespace mono_over
section has_top
instance {X : C} : has_top (mono_over X) :=
{ top := mk' (π _) }
instance {X : C} : inhabited (mono_over X) := β¨β€β©
/-- The morphism to the top object in `mono_over X`. -/
def le_top (f : mono_over X) : f βΆ β€ :=
hom_mk f.arrow (comp_id _)
@[simp] lemma top_left (X : C) : ((β€ : mono_over X) : C) = X := rfl
@[simp] lemma top_arrow (X : C) : (β€ : mono_over X).arrow = π X := rfl
/-- `map f` sends `β€ : mono_over X` to `β¨X, fβ© : mono_over Y`. -/
def map_top (f : X βΆ Y) [mono f] : (map f).obj β€ β
mk' f :=
iso_of_both_ways (hom_mk (π _) rfl) (hom_mk (π _) (by simp [id_comp f]))
section
variable [has_pullbacks C]
/-- The pullback of the top object in `mono_over Y`
is (isomorphic to) the top object in `mono_over X`. -/
def pullback_top (f : X βΆ Y) : (pullback f).obj β€ β
β€ :=
iso_of_both_ways (le_top _) (hom_mk (pullback.lift f (π _) (by tidy)) (pullback.lift_snd _ _ _))
/-- There is a morphism from `β€ : mono_over A` to the pullback of a monomorphism along itself;
as the category is thin this is an isomorphism. -/
def top_le_pullback_self {A B : C} (f : A βΆ B) [mono f] :
(β€ : mono_over A) βΆ (pullback f).obj (mk' f) :=
hom_mk _ (pullback.lift_snd _ _ rfl)
/-- The pullback of a monomorphism along itself is isomorphic to the top object. -/
def pullback_self {A B : C} (f : A βΆ B) [mono f] :
(pullback f).obj (mk' f) β
β€ :=
iso_of_both_ways (le_top _) (top_le_pullback_self _)
end
end has_top
section has_bot
variables [has_initial C] [initial_mono_class C]
instance {X : C} : has_bot (mono_over X) :=
{ bot := mk' (initial.to X) }
@[simp] lemma bot_left (X : C) : ((β₯ : mono_over X) : C) = β₯_ C := rfl
@[simp] lemma bot_arrow {X : C} : (β₯ : mono_over X).arrow = initial.to X := rfl
/-- The (unique) morphism from `β₯ : mono_over X` to any other `f : mono_over X`. -/
def bot_le {X : C} (f : mono_over X) : β₯ βΆ f :=
hom_mk (initial.to _) (by simp)
/-- `map f` sends `β₯ : mono_over X` to `β₯ : mono_over Y`. -/
def map_bot (f : X βΆ Y) [mono f] : (map f).obj β₯ β
β₯ :=
iso_of_both_ways (hom_mk (initial.to _) (by simp)) (hom_mk (π _) (by simp))
end has_bot
section zero_order_bot
variables [has_zero_object C]
open_locale zero_object
/-- The object underlying `β₯ : subobject B` is (up to isomorphism) the zero object. -/
def bot_coe_iso_zero {B : C} : ((β₯ : mono_over B) : C) β
0 :=
initial_is_initial.unique_up_to_iso has_zero_object.zero_is_initial
@[simp] lemma bot_arrow_eq_zero [has_zero_morphisms C] {B : C} : (β₯ : mono_over B).arrow = 0 :=
zero_of_source_iso_zero _ bot_coe_iso_zero
end zero_order_bot
section inf
variables [has_pullbacks C]
/--
When `[has_pullbacks C]`, `mono_over A` has "intersections", functorial in both arguments.
As `mono_over A` is only a preorder, this doesn't satisfy the axioms of `semilattice_inf`,
but we reuse all the names from `semilattice_inf` because they will be used to construct
`semilattice_inf (subobject A)` shortly.
-/
@[simps]
def inf {A : C} : mono_over A β₯€ mono_over A β₯€ mono_over A :=
{ obj := Ξ» f, pullback f.arrow β map f.arrow,
map := Ξ» fβ fβ k,
{ app := Ξ» g,
begin
apply hom_mk _ _,
apply pullback.lift pullback.fst (pullback.snd β« k.left) _,
rw [pullback.condition, assoc, w k],
dsimp,
rw [pullback.lift_snd_assoc, assoc, w k],
end } }.
/-- A morphism from the "infimum" of two objects in `mono_over A` to the first object. -/
def inf_le_left {A : C} (f g : mono_over A) :
(inf.obj f).obj g βΆ f :=
hom_mk _ rfl
/-- A morphism from the "infimum" of two objects in `mono_over A` to the second object. -/
def inf_le_right {A : C} (f g : mono_over A) :
(inf.obj f).obj g βΆ g :=
hom_mk _ pullback.condition
/-- A morphism version of the `le_inf` axiom. -/
def le_inf {A : C} (f g h : mono_over A) :
(h βΆ f) β (h βΆ g) β (h βΆ (inf.obj f).obj g) :=
begin
intros kβ kβ,
refine hom_mk (pullback.lift kβ.left kβ.left _) _,
rw [w kβ, w kβ],
erw [pullback.lift_snd_assoc, w kβ],
end
end inf
section sup
variables [has_images C] [has_binary_coproducts C]
/-- When `[has_images C] [has_binary_coproducts C]`, `mono_over A` has a `sup` construction,
which is functorial in both arguments,
and which on `subobject A` will induce a `semilattice_sup`. -/
def sup {A : C} : mono_over A β₯€ mono_over A β₯€ mono_over A :=
curry_obj ((forget A).prod (forget A) β uncurry.obj over.coprod β image)
/-- A morphism version of `le_sup_left`. -/
def le_sup_left {A : C} (f g : mono_over A) :
f βΆ (sup.obj f).obj g :=
begin
refine hom_mk (coprod.inl β« factor_thru_image _) _,
erw [category.assoc, image.fac, coprod.inl_desc],
refl,
end
/-- A morphism version of `le_sup_right`. -/
def le_sup_right {A : C} (f g : mono_over A) :
g βΆ (sup.obj f).obj g :=
begin
refine hom_mk (coprod.inr β« factor_thru_image _) _,
erw [category.assoc, image.fac, coprod.inr_desc],
refl,
end
/-- A morphism version of `sup_le`. -/
def sup_le {A : C} (f g h : mono_over A) :
(f βΆ h) β (g βΆ h) β ((sup.obj f).obj g βΆ h) :=
begin
intros kβ kβ,
refine hom_mk _ _,
apply image.lift β¨_, h.arrow, coprod.desc kβ.left kβ.left, _β©,
{ dsimp,
ext1,
{ simp [w kβ] },
{ simp [w kβ] } },
{ apply image.lift_fac }
end
end sup
end mono_over
namespace subobject
section order_top
instance order_top {X : C} : order_top (subobject X) :=
{ top := quotient.mk' β€,
le_top :=
begin
refine quotient.ind' (Ξ» f, _),
exact β¨mono_over.le_top fβ©,
end }
instance {X : C} : inhabited (subobject X) := β¨β€β©
lemma top_eq_id (B : C) : (β€ : subobject B) = subobject.mk (π B) := rfl
lemma underlying_iso_top_hom {B : C} :
(underlying_iso (π B)).hom = (β€ : subobject B).arrow :=
by { convert underlying_iso_hom_comp_eq_mk (π B), simp only [comp_id], }
instance top_arrow_is_iso {B : C} : is_iso ((β€ : subobject B).arrow) :=
by { rw βunderlying_iso_top_hom, apply_instance, }
@[simp, reassoc]
lemma underlying_iso_inv_top_arrow {B : C} :
(underlying_iso _).inv β« (β€ : subobject B).arrow = π B :=
underlying_iso_arrow _
@[simp]
lemma map_top (f : X βΆ Y) [mono f] : (map f).obj β€ = subobject.mk f :=
quotient.sound' β¨mono_over.map_top fβ©
lemma top_factors {A B : C} (f : A βΆ B) : (β€ : subobject B).factors f :=
β¨f, comp_id _β©
lemma is_iso_iff_mk_eq_top {X Y : C} (f : X βΆ Y) [mono f] : is_iso f β mk f = β€ :=
β¨Ξ» _, by exactI mk_eq_mk_of_comm _ _ (as_iso f) (category.comp_id _), Ξ» h,
by { rw [βof_mk_le_mk_comp h.le, category.comp_id], exact is_iso.of_iso (iso_of_mk_eq_mk _ _ h) }β©
lemma is_iso_arrow_iff_eq_top {Y : C} (P : subobject Y) : is_iso P.arrow β P = β€ :=
by rw [is_iso_iff_mk_eq_top, mk_arrow]
instance is_iso_top_arrow {Y : C} : is_iso (β€ : subobject Y).arrow :=
by rw is_iso_arrow_iff_eq_top
lemma mk_eq_top_of_is_iso {X Y : C} (f : X βΆ Y) [is_iso f] : mk f = β€ :=
(is_iso_iff_mk_eq_top f).mp infer_instance
lemma eq_top_of_is_iso_arrow {Y : C} (P : subobject Y) [is_iso P.arrow] : P = β€ :=
(is_iso_arrow_iff_eq_top P).mp infer_instance
section
variables [has_pullbacks C]
lemma pullback_top (f : X βΆ Y) : (pullback f).obj β€ = β€ :=
quotient.sound' β¨mono_over.pullback_top fβ©
lemma pullback_self {A B : C} (f : A βΆ B) [mono f] :
(pullback f).obj (mk f) = β€ :=
quotient.sound' β¨mono_over.pullback_self fβ©
end
end order_top
section order_bot
variables [has_initial C] [initial_mono_class C]
instance order_bot {X : C} : order_bot (subobject X) :=
{ bot := quotient.mk' β₯,
bot_le :=
begin
refine quotient.ind' (Ξ» f, _),
exact β¨mono_over.bot_le fβ©,
end }
lemma bot_eq_initial_to {B : C} : (β₯ : subobject B) = subobject.mk (initial.to B) := rfl
/-- The object underlying `β₯ : subobject B` is (up to isomorphism) the initial object. -/
def bot_coe_iso_initial {B : C} : ((β₯ : subobject B) : C) β
β₯_ C := underlying_iso _
lemma map_bot (f : X βΆ Y) [mono f] : (map f).obj β₯ = β₯ :=
quotient.sound' β¨mono_over.map_bot fβ©
end order_bot
section zero_order_bot
variables [has_zero_object C]
open_locale zero_object
/-- The object underlying `β₯ : subobject B` is (up to isomorphism) the zero object. -/
def bot_coe_iso_zero {B : C} : ((β₯ : subobject B) : C) β
0 :=
bot_coe_iso_initial βͺβ« initial_is_initial.unique_up_to_iso has_zero_object.zero_is_initial
variables [has_zero_morphisms C]
lemma bot_eq_zero {B : C} : (β₯ : subobject B) = subobject.mk (0 : 0 βΆ B) :=
mk_eq_mk_of_comm _ _ (initial_is_initial.unique_up_to_iso has_zero_object.zero_is_initial) (by simp)
@[simp] lemma bot_arrow {B : C} : (β₯ : subobject B).arrow = 0 :=
zero_of_source_iso_zero _ bot_coe_iso_zero
lemma bot_factors_iff_zero {A B : C} (f : A βΆ B) : (β₯ : subobject B).factors f β f = 0 :=
β¨by { rintro β¨h, rflβ©, simp }, by { rintro rfl, exact β¨0, by simpβ©, }β©
lemma mk_eq_bot_iff_zero {f : X βΆ Y} [mono f] : subobject.mk f = β₯ β f = 0 :=
β¨Ξ» h, by simpa [h, bot_factors_iff_zero] using mk_factors_self f,
Ξ» h, mk_eq_mk_of_comm _ _ ((iso_zero_of_mono_eq_zero h).trans has_zero_object.zero_iso_initial)
(by simp [h])β©
end zero_order_bot
section functor
variable (C)
/-- Sending `X : C` to `subobject X` is a contravariant functor `Cα΅α΅ β₯€ Type`. -/
@[simps]
def functor [has_pullbacks C] : Cα΅α΅ β₯€ Type (max uβ vβ) :=
{ obj := Ξ» X, subobject X.unop,
map := Ξ» X Y f, (pullback f.unop).obj,
map_id' := Ξ» X, funext pullback_id,
map_comp' := Ξ» X Y Z f g, funext (pullback_comp _ _) }
end functor
section semilattice_inf_top
variables [has_pullbacks C]
/-- The functorial infimum on `mono_over A` descends to an infimum on `subobject A`. -/
def inf {A : C} : subobject A β₯€ subobject A β₯€ subobject A :=
thin_skeleton.mapβ mono_over.inf
lemma inf_le_left {A : C} (f g : subobject A) :
(inf.obj f).obj g β€ f :=
quotient.induction_onβ' f g (Ξ» a b, β¨mono_over.inf_le_left _ _β©)
lemma inf_le_right {A : C} (f g : subobject A) :
(inf.obj f).obj g β€ g :=
quotient.induction_onβ' f g (Ξ» a b, β¨mono_over.inf_le_right _ _β©)
lemma le_inf {A : C} (h f g : subobject A) :
h β€ f β h β€ g β h β€ (inf.obj f).obj g :=
quotient.induction_onβ' h f g
begin
rintros f g h β¨kβ© β¨lβ©,
exact β¨mono_over.le_inf _ _ _ k lβ©,
end
instance {B : C} : semilattice_inf (subobject B) :=
{ inf := Ξ» m n, (inf.obj m).obj n,
inf_le_left := inf_le_left,
inf_le_right := inf_le_right,
le_inf := le_inf,
..subobject.partial_order _ }
lemma factors_left_of_inf_factors {A B : C} {X Y : subobject B} {f : A βΆ B}
(h : (X β Y).factors f) : X.factors f :=
factors_of_le _ (inf_le_left _ _) h
lemma factors_right_of_inf_factors {A B : C} {X Y : subobject B} {f : A βΆ B}
(h : (X β Y).factors f) : Y.factors f :=
factors_of_le _ (inf_le_right _ _) h
@[simp]
lemma inf_factors {A B : C} {X Y : subobject B} (f : A βΆ B) :
(X β Y).factors f β X.factors f β§ Y.factors f :=
β¨Ξ» h, β¨factors_left_of_inf_factors h, factors_right_of_inf_factors hβ©,
begin
revert X Y,
refine quotient.indβ' _,
rintro X Y β¨β¨gβ, rflβ©, β¨gβ, hgββ©β©,
exact β¨_, pullback.lift_snd_assoc _ _ hgβ _β©,
endβ©
lemma inf_arrow_factors_left {B : C} (X Y : subobject B) : X.factors (X β Y).arrow :=
(factors_iff _ _).mpr β¨of_le (X β Y) X (inf_le_left X Y), by simpβ©
lemma inf_arrow_factors_right {B : C} (X Y : subobject B) : Y.factors (X β Y).arrow :=
(factors_iff _ _).mpr β¨of_le (X β Y) Y (inf_le_right X Y), by simpβ©
@[simp]
lemma finset_inf_factors {I : Type*} {A B : C} {s : finset I} {P : I β subobject B}
(f : A βΆ B) :
(s.inf P).factors f β β i β s, (P i).factors f :=
begin
classical,
apply finset.induction_on s,
{ simp [top_factors] },
{ intros i s nm ih, simp [ih] },
end
-- `i` is explicit here because often we'd like to defer a proof of `m`
lemma finset_inf_arrow_factors {I : Type*} {B : C} (s : finset I) (P : I β subobject B)
(i : I) (m : i β s) : (P i).factors (s.inf P).arrow :=
begin
revert i m,
classical,
apply finset.induction_on s,
{ rintro _ β¨β©, },
{ intros i s nm ih j m,
rw [finset.inf_insert],
simp only [finset.mem_insert] at m, rcases m with (rfl|m),
{ rw βfactor_thru_arrow _ _ (inf_arrow_factors_left _ _),
exact factors_comp_arrow _, },
{ rw βfactor_thru_arrow _ _ (inf_arrow_factors_right _ _),
apply factors_of_factors_right,
exact ih _ m, } },
end
lemma inf_eq_map_pullback' {A : C} (fβ : mono_over A) (fβ : subobject A) :
(subobject.inf.obj (quotient.mk' fβ)).obj fβ =
(subobject.map fβ.arrow).obj ((subobject.pullback fβ.arrow).obj fβ) :=
begin
apply quotient.induction_on' fβ,
intro fβ,
refl,
end
lemma inf_eq_map_pullback {A : C} (fβ : mono_over A) (fβ : subobject A) :
(quotient.mk' fβ β fβ : subobject A) = (map fβ.arrow).obj ((pullback fβ.arrow).obj fβ) :=
inf_eq_map_pullback' fβ fβ
lemma prod_eq_inf {A : C} {fβ fβ : subobject A} [has_binary_product fβ fβ] :
(fβ β¨― fβ) = fβ β fβ :=
le_antisymm
(_root_.le_inf (limits.prod.fst).le (limits.prod.snd).le)
((prod.lift (_root_.inf_le_left.hom) (_root_.inf_le_right.hom))).le
lemma inf_def {B : C} (m m' : subobject B) :
m β m' = (inf.obj m).obj m' := rfl
/-- `β` commutes with pullback. -/
lemma inf_pullback {X Y : C} (g : X βΆ Y) (fβ fβ) :
(pullback g).obj (fβ β fβ) = (pullback g).obj fβ β (pullback g).obj fβ :=
begin
revert fβ,
apply quotient.ind',
intro fβ,
erw [inf_def, inf_def, inf_eq_map_pullback', inf_eq_map_pullback', β pullback_comp,
β map_pullback pullback.condition (pullback_is_pullback fβ.arrow g),
β pullback_comp, pullback.condition],
refl,
end
/-- `β` commutes with map. -/
lemma inf_map {X Y : C} (g : Y βΆ X) [mono g] (fβ fβ) :
(map g).obj (fβ β fβ) = (map g).obj fβ β (map g).obj fβ :=
begin
revert fβ,
apply quotient.ind',
intro fβ,
erw [inf_def, inf_def, inf_eq_map_pullback',
inf_eq_map_pullback', β map_comp],
dsimp,
rw [pullback_comp, pullback_map_self],
end
end semilattice_inf_top
section semilattice_sup
variables [has_images C] [has_binary_coproducts C]
/-- The functorial supremum on `mono_over A` descends to an supremum on `subobject A`. -/
def sup {A : C} : subobject A β₯€ subobject A β₯€ subobject A :=
thin_skeleton.mapβ mono_over.sup
instance {B : C} : semilattice_sup (subobject B) :=
{ sup := Ξ» m n, (sup.obj m).obj n,
le_sup_left := Ξ» m n, quotient.induction_onβ' m n (Ξ» a b, β¨mono_over.le_sup_left _ _β©),
le_sup_right := Ξ» m n, quotient.induction_onβ' m n (Ξ» a b, β¨mono_over.le_sup_right _ _β©),
sup_le := Ξ» m n k, quotient.induction_onβ' m n k (Ξ» a b c β¨iβ© β¨jβ©, β¨mono_over.sup_le _ _ _ i jβ©),
..subobject.partial_order B }
lemma sup_factors_of_factors_left {A B : C} {X Y : subobject B} {f : A βΆ B} (P : X.factors f) :
(X β Y).factors f :=
factors_of_le f le_sup_left P
lemma sup_factors_of_factors_right {A B : C} {X Y : subobject B} {f : A βΆ B} (P : Y.factors f) :
(X β Y).factors f :=
factors_of_le f le_sup_right P
variables [has_initial C] [initial_mono_class C]
lemma finset_sup_factors {I : Type*} {A B : C} {s : finset I} {P : I β subobject B}
{f : A βΆ B} (h : β i β s, (P i).factors f) :
(s.sup P).factors f :=
begin
classical,
revert h,
apply finset.induction_on s,
{ rintro β¨_, β¨β¨β©, _β©β©, },
{ rintros i s nm ih β¨j, β¨m, hβ©β©,
simp only [finset.sup_insert],
simp at m, rcases m with (rfl|m),
{ exact sup_factors_of_factors_left h, },
{ exact sup_factors_of_factors_right (ih β¨j, β¨m, hβ©β©), }, },
end
end semilattice_sup
section lattice
instance [has_initial C] [initial_mono_class C] {B : C} : bounded_order (subobject B) :=
{ ..subobject.order_top,
..subobject.order_bot }
variables [has_pullbacks C] [has_images C] [has_binary_coproducts C]
instance {B : C} : lattice (subobject B) :=
{ ..subobject.semilattice_inf,
..subobject.semilattice_sup }
end lattice
section Inf
variables [well_powered C]
/--
The "wide cospan" diagram, with a small indexing type, constructed from a set of subobjects.
(This is just the diagram of all the subobjects pasted together, but using `well_powered C`
to make the diagram small.)
-/
def wide_cospan {A : C} (s : set (subobject A)) :
wide_pullback_shape (equiv_shrink _ '' s) β₯€ C :=
wide_pullback_shape.wide_cospan A
(Ξ» j : equiv_shrink _ '' s, (((equiv_shrink (subobject A)).symm j) : C))
(Ξ» j, ((equiv_shrink (subobject A)).symm j).arrow)
@[simp] lemma wide_cospan_map_term {A : C} (s : set (subobject A)) (j) :
(wide_cospan s).map (wide_pullback_shape.hom.term j) =
((equiv_shrink (subobject A)).symm j).arrow :=
rfl
/-- Auxiliary construction of a cone for `le_Inf`. -/
def le_Inf_cone {A : C} (s : set (subobject A)) (f : subobject A) (k : Ξ (g β s), f β€ g) :
cone (wide_cospan s) :=
wide_pullback_shape.mk_cone f.arrow
(Ξ» j, underlying.map (hom_of_le (k _ (by { rcases j with β¨-, β¨g, β¨m, rflβ©β©β©, simpa using m, }))))
(by tidy)
@[simp] lemma le_Inf_cone_Ο_app_none
{A : C} (s : set (subobject A)) (f : subobject A) (k : Ξ (g β s), f β€ g) :
(le_Inf_cone s f k).Ο.app none = f.arrow :=
rfl
variables [has_wide_pullbacks.{vβ} C]
/--
The limit of `wide_cospan s`. (This will be the supremum of the set of subobjects.)
-/
def wide_pullback {A : C} (s : set (subobject A)) : C :=
limits.limit (wide_cospan s)
/--
The inclusion map from `wide_pullback s` to `A`
-/
def wide_pullback_ΞΉ {A : C} (s : set (subobject A)) :
wide_pullback s βΆ A :=
limits.limit.Ο (wide_cospan s) none
instance wide_pullback_ΞΉ_mono {A : C} (s : set (subobject A)) :
mono (wide_pullback_ΞΉ s) :=
β¨Ξ» W u v h, limit.hom_ext (Ξ» j, begin
cases j,
{ exact h, },
{ apply (cancel_mono ((equiv_shrink (subobject A)).symm j).arrow).1,
rw [assoc, assoc],
erw limit.w (wide_cospan s) (wide_pullback_shape.hom.term j),
exact h, },
end)β©
/--
When `[well_powered C]` and `[has_wide_pullbacks C]`, `subobject A` has arbitrary infimums.
-/
def Inf {A : C} (s : set (subobject A)) : subobject A :=
subobject.mk (wide_pullback_ΞΉ s)
lemma Inf_le {A : C} (s : set (subobject A)) (f β s) :
Inf s β€ f :=
begin
fapply le_of_comm,
{ refine (underlying_iso _).hom β«
(limits.limit.Ο
(wide_cospan s)
(some β¨equiv_shrink _ f, set.mem_image_of_mem (equiv_shrink (subobject A)) Hβ©)) β« _,
apply eq_to_hom,
apply (congr_arg (Ξ» X : subobject A, (X : C))),
exact (equiv.symm_apply_apply _ _), },
{ dsimp [Inf],
simp only [category.comp_id, category.assoc, βunderlying_iso_hom_comp_eq_mk,
subobject.arrow_congr, congr_arg_mpr_hom_left, iso.cancel_iso_hom_left],
convert limit.w (wide_cospan s) (wide_pullback_shape.hom.term _), },
end.
lemma le_Inf {A : C} (s : set (subobject A)) (f : subobject A) (k : Ξ (g β s), f β€ g) :
f β€ Inf s :=
begin
fapply le_of_comm,
{ exact limits.limit.lift _ (le_Inf_cone s f k) β« (underlying_iso _).inv, },
{ dsimp [Inf, wide_pullback_ΞΉ],
simp, },
end
instance {B : C} : complete_semilattice_Inf (subobject B) :=
{ Inf := Inf,
Inf_le := Inf_le,
le_Inf := le_Inf,
..subobject.partial_order B }
end Inf
section Sup
variables [well_powered C] [has_coproducts.{vβ} C]
/--
The univesal morphism out of the coproduct of a set of subobjects,
after using `[well_powered C]` to reindex by a small type.
-/
def small_coproduct_desc {A : C} (s : set (subobject A)) : _ βΆ A :=
limits.sigma.desc (Ξ» j : equiv_shrink _ '' s, ((equiv_shrink (subobject A)).symm j).arrow)
variables [has_images C]
/-- When `[well_powered C] [has_images C] [has_coproducts C]`,
`subobject A` has arbitrary supremums. -/
def Sup {A : C} (s : set (subobject A)) : subobject A :=
subobject.mk (image.ΞΉ (small_coproduct_desc s))
lemma le_Sup {A : C} (s : set (subobject A)) (f β s) :
f β€ Sup s :=
begin
fapply le_of_comm,
{ dsimp [Sup],
refine _ β« factor_thru_image _ β« (underlying_iso _).inv,
refine _ β« sigma.ΞΉ _ β¨equiv_shrink _ f, (by simpa [set.mem_image] using H)β©,
exact eq_to_hom (congr_arg (Ξ» X : subobject A, (X : C)) (equiv.symm_apply_apply _ _).symm), },
{ dsimp [Sup, small_coproduct_desc],
simp, dsimp, simp, },
end
lemma symm_apply_mem_iff_mem_image {Ξ± Ξ² : Type*} (e : Ξ± β Ξ²) (s : set Ξ±) (x : Ξ²) :
e.symm x β s β x β e '' s :=
β¨Ξ» h, β¨e.symm x, h, by simpβ©, by { rintro β¨a, m, rflβ©, simpa using m, }β©
lemma Sup_le {A : C} (s : set (subobject A)) (f : subobject A) (k : Ξ (g β s), g β€ f) :
Sup s β€ f :=
begin
fapply le_of_comm,
{ dsimp [Sup],
refine (underlying_iso _).hom β« image.lift β¨_, f.arrow, _, _β©,
{ refine sigma.desc _,
rintro β¨g, mβ©,
refine underlying.map (hom_of_le (k _ _)),
simpa [symm_apply_mem_iff_mem_image] using m, },
{ ext j, rcases j with β¨j, mβ©, dsimp [small_coproduct_desc], simp, dsimp, simp, }, },
{ dsimp [Sup],
simp, },
end
instance {B : C} : complete_semilattice_Sup (subobject B) :=
{ Sup := Sup,
le_Sup := le_Sup,
Sup_le := Sup_le,
..subobject.partial_order B }
end Sup
section complete_lattice
variables [well_powered C] [has_wide_pullbacks.{vβ} C] [has_images C] [has_coproducts.{vβ} C]
[initial_mono_class C]
local attribute [instance] has_smallest_coproducts_of_has_coproducts
instance {B : C} : complete_lattice (subobject B) :=
{ ..subobject.semilattice_inf,
..subobject.semilattice_sup,
..subobject.bounded_order,
..subobject.complete_semilattice_Inf,
..subobject.complete_semilattice_Sup, }
end complete_lattice
section zero_object
variables [has_zero_morphisms C] [has_zero_object C]
open_locale zero_object
/-- A nonzero object has nontrivial subobject lattice. -/
lemma nontrivial_of_not_is_zero {X : C} (h : Β¬ is_zero X) : nontrivial (subobject X) :=
β¨β¨mk (0 : 0 βΆ X), mk (π X), Ξ» w, h (is_zero.of_iso (is_zero_zero C) (iso_of_mk_eq_mk _ _ w).symm)β©β©
end zero_object
section subobject_subobject
/-- The subobject lattice of a subobject `Y` is order isomorphic to the interval `set.Iic Y`. -/
def subobject_order_iso {X : C} (Y : subobject X) : subobject (Y : C) βo set.Iic Y :=
{ to_fun := Ξ» Z, β¨subobject.mk (Z.arrow β« Y.arrow),
set.mem_Iic.mpr (le_of_comm ((underlying_iso _).hom β« Z.arrow) (by simp))β©,
inv_fun := Ξ» Z, subobject.mk (of_le _ _ Z.2),
left_inv := Ξ» Z, mk_eq_of_comm _ (underlying_iso _) (by { ext, simp, }),
right_inv := Ξ» Z, subtype.ext (mk_eq_of_comm _ (underlying_iso _)
(by { dsimp, simp [βiso.eq_inv_comp], })),
map_rel_iff' := Ξ» W Z,
β¨Ξ» h, le_of_comm
((underlying_iso _).inv β« of_le _ _ (subtype.mk_le_mk.mp h) β« (underlying_iso _).hom)
(by { ext, simp, }),
Ξ» h, subtype.mk_le_mk.mpr
(le_of_comm ((underlying_iso _).hom β« of_le _ _ h β« (underlying_iso _).inv) (by simp))β©, }
end subobject_subobject
end subobject
end category_theory
|
8bd2a9e048149ce7977a257195b03d5a599b1a74 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/algebra/group_power/lemmas.lean | fe2b21f7fbd85f9891fd2686803003c637dcbd40 | [
"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 | 33,109 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis
-/
import algebra.group_power.basic
import algebra.invertible
import algebra.opposites
import data.list.basic
import data.int.cast
import data.equiv.basic
import data.equiv.mul_add
/-!
# Lemmas about power operations on monoids and groups
This file contains lemmas about `monoid.pow`, `group.pow`, `nsmul`, `gsmul`
which require additional imports besides those available in `.basic`.
-/
universes u v w x y z uβ uβ
variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z}
{R : Type uβ} {S : Type uβ}
/-!
### (Additive) monoid
-/
section monoid
variables [monoid M] [monoid N] [add_monoid A] [add_monoid B]
@[simp] theorem nsmul_one [has_one A] : β n : β, n β’ (1 : A) = n :=
add_monoid_hom.eq_nat_cast
β¨Ξ» n, n β’ (1 : A), zero_nsmul _, Ξ» _ _, add_nsmul _ _ _β©
(one_nsmul _)
@[simp, norm_cast] lemma units.coe_pow (u : units M) (n : β) : ((u ^ n : units M) : M) = u ^ n :=
(units.coe_hom M).map_pow u n
instance invertible_pow (m : M) [invertible m] (n : β) : invertible (m ^ n) :=
{ inv_of := β
m ^ n,
inv_of_mul_self := by rw [β (commute_inv_of m).symm.mul_pow, inv_of_mul_self, one_pow],
mul_inv_of_self := by rw [β (commute_inv_of m).mul_pow, mul_inv_of_self, one_pow] }
lemma inv_of_pow (m : M) [invertible m] (n : β) [invertible (m ^ n)] :
β
(m ^ n) = β
m ^ n :=
@invertible_unique M _ (m ^ n) (m ^ n) rfl βΉ_βΊ (invertible_pow m n)
lemma is_unit.pow {m : M} (n : β) : is_unit m β is_unit (m ^ n) :=
Ξ» β¨u, huβ©, β¨u ^ n, by simp *β©
lemma is_unit_pos_pow_iff {M : Type*} [comm_monoid M] {m : M} {n : β} (h : 0 < n) :
is_unit (m ^ n) β is_unit m :=
begin
obtain β¨p, rflβ© := nat.exists_eq_succ_of_ne_zero h.ne',
refine β¨Ξ» h, _, is_unit.pow _β©,
obtain β¨β¨k, k', hk, hk'β©, hβ© := h,
rw [units.coe_mk] at h,
refine β¨β¨m, m ^ p * k', _, _β©, _β©,
{ rw [βmul_assoc, βpow_succ, βh, hk] },
{ rw [mul_right_comm, βpow_succ', βh, hk] },
{ exact units.coe_mk _ _ _ _ }
end
/-- If `x ^ n.succ = 1` then `x` has an inverse, `x^n`. -/
def invertible_of_pow_succ_eq_one (x : M) (n : β) (hx : x ^ n.succ = 1) :
invertible x :=
β¨x ^ n, (pow_succ' x n).symm.trans hx, (pow_succ x n).symm.trans hxβ©
/-- If `x ^ n = 1` then `x` has an inverse, `x^(n - 1)`. -/
def invertible_of_pow_eq_one (x : M) (n : β) (hx : x ^ n = 1) (hn : 0 < n) :
invertible x :=
begin
apply invertible_of_pow_succ_eq_one x (n - 1),
convert hx,
exact nat.sub_add_cancel (nat.succ_le_of_lt hn),
end
lemma is_unit_of_pow_eq_one (x : M) (n : β) (hx : x ^ n = 1) (hn : 0 < n) :
is_unit x :=
begin
haveI := invertible_of_pow_eq_one x n hx hn,
exact is_unit_of_invertible x
end
end monoid
section group
variables [group G] [group H] [add_group A] [add_group B]
open int
local attribute [ematch] le_of_lt
open nat
theorem gsmul_one [has_one A] (n : β€) : n β’ (1 : A) = n :=
by cases n; simp
lemma gpow_add_one (a : G) : β n : β€, a ^ (n + 1) = a ^ n * a
| (of_nat n) := by simp [β int.coe_nat_succ, pow_succ']
| -[1+0] := by simp [int.neg_succ_of_nat_eq]
| -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, gpow_neg, neg_add, neg_add_cancel_right, gpow_neg,
β int.coe_nat_succ, gpow_coe_nat, gpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev,
inv_mul_cancel_right]
theorem add_one_gsmul : β (a : A) (i : β€), (i + 1) β’ a = i β’ a + a :=
@gpow_add_one (multiplicative A) _
lemma gpow_sub_one (a : G) (n : β€) : a ^ (n - 1) = a ^ n * aβ»ΒΉ :=
calc a ^ (n - 1) = a ^ (n - 1) * a * aβ»ΒΉ : (mul_inv_cancel_right _ _).symm
... = a^n * aβ»ΒΉ : by rw [β gpow_add_one, sub_add_cancel]
lemma gpow_add (a : G) (m n : β€) : a ^ (m + n) = a ^ m * a ^ n :=
begin
induction n using int.induction_on with n ihn n ihn,
case hz : { simp },
{ simp only [β add_assoc, gpow_add_one, ihn, mul_assoc] },
{ rw [gpow_sub_one, β mul_assoc, β ihn, β gpow_sub_one, add_sub_assoc] }
end
lemma mul_self_gpow (b : G) (m : β€) : b*b^m = b^(m+1) :=
by { conv_lhs {congr, rw β gpow_one b }, rw [β gpow_add, add_comm] }
lemma mul_gpow_self (b : G) (m : β€) : b^m*b = b^(m+1) :=
by { conv_lhs {congr, skip, rw β gpow_one b }, rw [β gpow_add, add_comm] }
theorem add_gsmul : β (a : A) (i j : β€), (i + j) β’ a = i β’ a + j β’ a :=
@gpow_add (multiplicative A) _
lemma gpow_sub (a : G) (m n : β€) : a ^ (m - n) = a ^ m * (a ^ n)β»ΒΉ :=
by rw [sub_eq_add_neg, gpow_add, gpow_neg]
lemma sub_gsmul (m n : β€) (a : A) : (m - n) β’ a = m β’ a - n β’ a :=
by simpa only [sub_eq_add_neg] using @gpow_sub (multiplicative A) _ _ _ _
theorem gpow_one_add (a : G) (i : β€) : a ^ (1 + i) = a * a ^ i :=
by rw [gpow_add, gpow_one]
theorem one_add_gsmul : β (a : A) (i : β€), (1 + i) β’ a = a + i β’ a :=
@gpow_one_add (multiplicative A) _
theorem gpow_mul_comm (a : G) (i j : β€) : a ^ i * a ^ j = a ^ j * a ^ i :=
by rw [β gpow_add, β gpow_add, add_comm]
theorem gsmul_add_comm : β (a : A) (i j : β€), i β’ a + j β’ a = j β’ a + i β’ a :=
@gpow_mul_comm (multiplicative A) _
theorem gpow_mul (a : G) (m n : β€) : a ^ (m * n) = (a ^ m) ^ n :=
int.induction_on n (by simp) (Ξ» n ihn, by simp [mul_add, gpow_add, ihn])
(Ξ» n ihn, by simp only [mul_sub, gpow_sub, ihn, mul_one, gpow_one])
theorem gsmul_mul' : β (a : A) (m n : β€), (m * n) β’ a = n β’ (m β’ a) :=
@gpow_mul (multiplicative A) _
theorem gpow_mul' (a : G) (m n : β€) : a ^ (m * n) = (a ^ n) ^ m :=
by rw [mul_comm, gpow_mul]
theorem mul_gsmul (a : A) (m n : β€) : (m * n) β’ a = m β’ (n β’ a) :=
by rw [mul_comm, gsmul_mul']
theorem gpow_bit0 (a : G) (n : β€) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _
theorem bit0_gsmul (a : A) (n : β€) : bit0 n β’ a = n β’ a + n β’ a :=
@gpow_bit0 (multiplicative A) _ _ _
theorem gpow_bit1 (a : G) (n : β€) : a ^ bit1 n = a ^ n * a ^ n * a :=
by rw [bit1, gpow_add, gpow_bit0, gpow_one]
theorem bit1_gsmul : β (a : A) (n : β€), bit1 n β’ a = n β’ a + n β’ a + a :=
@gpow_bit1 (multiplicative A) _
@[simp] theorem monoid_hom.map_gpow (f : G β* H) (a : G) (n : β€) : f (a ^ n) = f a ^ n :=
by cases n; simp
@[simp] theorem add_monoid_hom.map_gsmul (f : A β+ B) (a : A) (n : β€) : f (n β’ a) = n β’ f a :=
f.to_multiplicative.map_gpow a n
@[simp, norm_cast] lemma units.coe_gpow (u : units G) (n : β€) : ((u ^ n : units G) : G) = u ^ n :=
(units.coe_hom G).map_gpow u n
end group
section ordered_add_comm_group
variables [ordered_add_comm_group A]
/-! Lemmas about `gsmul` under ordering, placed here (rather than in `algebra.group_power.order`
with their friends) because they require facts from `data.int.basic`-/
open int
lemma gsmul_pos {a : A} (ha : 0 < a) {k : β€} (hk : (0:β€) < k) : 0 < k β’ a :=
begin
lift k to β using int.le_of_lt hk,
rw gsmul_coe_nat,
apply nsmul_pos ha,
exact coe_nat_pos.mp hk,
end
theorem gsmul_le_gsmul {a : A} {n m : β€} (ha : 0 β€ a) (h : n β€ m) : n β’ a β€ m β’ a :=
calc n β’ a = n β’ a + 0 : (add_zero _).symm
... β€ n β’ a + (m - n) β’ a : add_le_add_left (gsmul_nonneg ha (sub_nonneg.mpr h)) _
... = m β’ a : by { rw [β add_gsmul], simp }
theorem gsmul_lt_gsmul {a : A} {n m : β€} (ha : 0 < a) (h : n < m) : n β’ a < m β’ a :=
calc n β’ a = n β’ a + 0 : (add_zero _).symm
... < n β’ a + (m - n) β’ a : add_lt_add_left (gsmul_pos ha (sub_pos.mpr h)) _
... = m β’ a : by { rw [β add_gsmul], simp }
lemma abs_nsmul {Ξ± : Type*} [linear_ordered_add_comm_group Ξ±] (n : β) (a : Ξ±) :
abs (n β’ a) = n β’ abs a :=
begin
cases le_total a 0 with hneg hpos,
{ rw [abs_of_nonpos hneg, β abs_neg, β neg_nsmul, abs_of_nonneg],
exact nsmul_nonneg (neg_nonneg.mpr hneg) n },
{ rw [abs_of_nonneg hpos, abs_of_nonneg],
exact nsmul_nonneg hpos n }
end
lemma abs_gsmul {Ξ± : Type*} [linear_ordered_add_comm_group Ξ±] (n : β€) (a : Ξ±) :
abs (n β’ a) = (abs n) β’ abs a :=
begin
by_cases n0 : 0 β€ n,
{ lift n to β using n0,
simp only [abs_nsmul, coe_nat_abs, gsmul_coe_nat] },
{ lift (- n) to β using int.le_of_lt (neg_pos.mpr (not_le.mp n0)) with m h,
rw [β abs_neg (n β’ a), β neg_gsmul, β abs_neg n, β h, gsmul_coe_nat, coe_nat_abs,
gsmul_coe_nat],
exact abs_nsmul m _ },
end
lemma abs_add_eq_add_abs_le {Ξ± : Type*} [linear_ordered_add_comm_group Ξ±] {a b : Ξ±} (hle : a β€ b) :
abs (a + b) = abs a + abs b β (0 β€ a β§ 0 β€ b β¨ a β€ 0 β§ b β€ 0) :=
begin
by_cases a0 : 0 β€ a; by_cases b0 : 0 β€ b,
{ simp [a0, b0, abs_of_nonneg, add_nonneg a0 b0] },
{ exact (lt_irrefl (0 : Ξ±) (a0.trans_lt (hle.trans_lt (not_le.mp b0)))).elim },
any_goals { simp [(not_le.mp a0).le, (not_le.mp b0).le, abs_of_nonpos, add_nonpos, add_comm] },
obtain F := (not_le.mp a0),
have : (abs (a + b) = -a + b β b β€ 0) β (abs (a + b) =
abs a + abs b β 0 β€ a β§ 0 β€ b β¨ a β€ 0 β§ b β€ 0),
{ simp [a0, b0, abs_of_neg, abs_of_nonneg, F, F.le] },
refine this.mp β¨Ξ» h, _, Ξ» h, by simp only [le_antisymm h b0, abs_of_neg F, add_zero]β©,
by_cases ba : a + b β€ 0,
{ refine le_of_eq (eq_zero_of_neg_eq _),
rwa [abs_of_nonpos ba, neg_add_rev, add_comm, add_right_inj] at h },
{ refine (lt_irrefl (0 : Ξ±) _).elim,
rw [abs_of_pos (not_le.mp ba), add_left_inj] at h,
rwa eq_zero_of_neg_eq h.symm at F }
end
lemma abs_add_eq_add_abs_iff {Ξ± : Type*} [linear_ordered_add_comm_group Ξ±] (a b : Ξ±) :
abs (a + b) = abs a + abs b β (0 β€ a β§ 0 β€ b β¨ a β€ 0 β§ b β€ 0) :=
begin
by_cases ab : a β€ b,
{ exact abs_add_eq_add_abs_le ab },
{ rw [add_comm a, add_comm (abs _), abs_add_eq_add_abs_le ((not_le.mp ab).le), and.comm,
@and.comm (b β€ 0 ) _] }
end
end ordered_add_comm_group
section linear_ordered_add_comm_group
variable [linear_ordered_add_comm_group A]
theorem gsmul_le_gsmul_iff {a : A} {n m : β€} (ha : 0 < a) : n β’ a β€ m β’ a β n β€ m :=
begin
refine β¨Ξ» h, _, gsmul_le_gsmul $ le_of_lt haβ©,
by_contra H,
exact lt_irrefl _ (lt_of_lt_of_le (gsmul_lt_gsmul ha (not_le.mp H)) h)
end
theorem gsmul_lt_gsmul_iff {a : A} {n m : β€} (ha : 0 < a) : n β’ a < m β’ a β n < m :=
begin
refine β¨Ξ» h, _, gsmul_lt_gsmul haβ©,
by_contra H,
exact lt_irrefl _ (lt_of_le_of_lt (gsmul_le_gsmul (le_of_lt ha) $ not_lt.mp H) h)
end
theorem nsmul_le_nsmul_iff {a : A} {n m : β} (ha : 0 < a) : n β’ a β€ m β’ a β n β€ m :=
begin
refine β¨Ξ» h, _, nsmul_le_nsmul $ le_of_lt haβ©,
by_contra H,
exact lt_irrefl _ (lt_of_lt_of_le (nsmul_lt_nsmul ha (not_le.mp H)) h)
end
theorem nsmul_lt_nsmul_iff {a : A} {n m : β} (ha : 0 < a) : n β’ a < m β’ a β n < m :=
begin
refine β¨Ξ» h, _, nsmul_lt_nsmul haβ©,
by_contra H,
exact lt_irrefl _ (lt_of_le_of_lt (nsmul_le_nsmul (le_of_lt ha) $ not_lt.mp H) h)
end
end linear_ordered_add_comm_group
@[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : β) :
((n β’ a : A) : with_bot A) = n β’ a :=
add_monoid_hom.map_nsmul β¨(coe : A β with_bot A), with_bot.coe_zero, with_bot.coe_addβ© a n
theorem nsmul_eq_mul' [semiring R] (a : R) (n : β) : n β’ a = a * n :=
by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero],
rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]]
@[simp] theorem nsmul_eq_mul [semiring R] (n : β) (a : R) : n β’ a = n * a :=
by rw [nsmul_eq_mul', (n.cast_commute a).eq]
theorem mul_nsmul_left [semiring R] (a b : R) (n : β) : n β’ (a * b) = a * (n β’ b) :=
by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc]
theorem mul_nsmul_assoc [semiring R] (a b : R) (n : β) : n β’ (a * b) = n β’ a * b :=
by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc]
@[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : β) : (β(n ^ m) : R) = βn ^ m :=
begin
induction m with m ih,
{ rw [pow_zero, pow_zero], exact nat.cast_one },
{ rw [pow_succ', pow_succ', nat.cast_mul, ih] }
end
@[simp, norm_cast] theorem int.coe_nat_pow (n m : β) : ((n ^ m : β) : β€) = n ^ m :=
by induction m with m ih; [exact int.coe_nat_one, rw [pow_succ', pow_succ', int.coe_nat_mul, ih]]
theorem int.nat_abs_pow (n : β€) (k : β) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k :=
by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, pow_succ', ih]]
-- The next four lemmas allow us to replace multiplication by a numeral with a `gsmul` expression.
-- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`.
lemma bit0_mul [ring R] {n r : R} : bit0 n * r = (2 : β€) β’ (n * r) :=
by { dsimp [bit0], rw [add_mul, add_gsmul, one_gsmul], }
lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = (2 : β€) β’ (r * n) :=
by { dsimp [bit0], rw [mul_add, add_gsmul, one_gsmul], }
lemma bit1_mul [ring R] {n r : R} : bit1 n * r = (2 : β€) β’ (n * r) + r :=
by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], }
lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = (2 : β€) β’ (r * n) + r :=
by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], }
@[simp] theorem gsmul_eq_mul [ring R] (a : R) : β (n : β€), n β’ a = n * a
| (n : β) := by { rw [gsmul_coe_nat, nsmul_eq_mul], refl }
| -[1+ n] := by simp [nat.cast_succ, neg_add_rev, int.cast_neg_succ_of_nat, add_mul]
theorem gsmul_eq_mul' [ring R] (a : R) (n : β€) : n β’ a = a * n :=
by rw [gsmul_eq_mul, (n.cast_commute a).eq]
theorem mul_gsmul_left [ring R] (a b : R) (n : β€) : n β’ (a * b) = a * (n β’ b) :=
by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc]
theorem mul_gsmul_assoc [ring R] (a b : R) (n : β€) : n β’ (a * b) = n β’ a * b :=
by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc]
lemma gsmul_int_int (a b : β€) : a β’ b = a * b := by simp
lemma gsmul_int_one (n : β€) : n β’ 1 = n := by simp
@[simp, norm_cast] theorem int.cast_pow [ring R] (n : β€) (m : β) : (β(n ^ m) : R) = βn ^ m :=
begin
induction m with m ih,
{ rw [pow_zero, pow_zero, int.cast_one] },
{ rw [pow_succ, pow_succ, int.cast_mul, ih] }
end
lemma neg_one_pow_eq_pow_mod_two [ring R] {n : β} : (-1 : R) ^ n = (-1) ^ (n % 2) :=
by rw [β nat.mod_add_div n 2, pow_add, pow_mul]; simp [sq]
section ordered_semiring
variable [ordered_semiring R]
/-- Bernoulli's inequality. This version works for semirings but requires
additional hypotheses `0 β€ a * a` and `0 β€ (1 + a) * (1 + a)`. -/
theorem one_add_mul_le_pow' {a : R} (Hsq : 0 β€ a * a) (Hsq' : 0 β€ (1 + a) * (1 + a))
(H : 0 β€ 2 + a) :
β (n : β), 1 + (n : R) * a β€ (1 + a) ^ n
| 0 := by simp
| 1 := by simp
| (n+2) :=
have 0 β€ (n : R) * (a * a * (2 + a)) + a * a,
from add_nonneg (mul_nonneg n.cast_nonneg (mul_nonneg Hsq H)) Hsq,
calc 1 + (β(n + 2) : R) * a β€ 1 + β(n + 2) * a + (n * (a * a * (2 + a)) + a * a) :
(le_add_iff_nonneg_right _).2 this
... = (1 + a) * (1 + a) * (1 + n * a) :
by { simp [add_mul, mul_add, bit0, mul_assoc, (n.cast_commute (_ : R)).left_comm],
ac_refl }
... β€ (1 + a) * (1 + a) * (1 + a)^n :
mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) Hsq'
... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc]
private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : β) :
β k : β, a ^ (i + k + 1) < a ^ i
| 0 :=
begin
rw [βone_mul (a^i), add_zero, pow_succ],
exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one
end
| (k+1) :=
begin
rw [βone_mul (a^i), pow_succ],
apply mul_lt_mul ha _ _ zero_le_one,
{ apply le_of_lt, apply pow_lt_pow_of_lt_one_aux },
{ show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h }
end
private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 β€ a) (ha : a β€ 1) (i : β) :
β k : β, a ^ (i + k) β€ a ^ i
| 0 := by simp
| (k+1) := by { rw [βadd_assoc, βone_mul (a^i), pow_succ],
exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one }
lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1)
{i j : β} (hij : i < j) : a ^ j < a ^ i :=
let β¨k, hkβ© := nat.exists_eq_add_of_lt hij in
by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _
lemma pow_lt_pow_iff_of_lt_one {a : R} {n m : β} (hpos : 0 < a) (h : a < 1) :
a ^ m < a ^ n β n < m :=
begin
have : strict_mono (Ξ» (n : order_dual β), a ^ (id n : β)) := Ξ» m n, pow_lt_pow_of_lt_one hpos h,
exact this.lt_iff_lt
end
lemma pow_le_pow_of_le_one {a : R} (h : 0 β€ a) (ha : a β€ 1)
{i j : β} (hij : i β€ j) : a ^ j β€ a ^ i :=
let β¨k, hkβ© := nat.exists_eq_add_of_le hij in
by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _
lemma pow_le_one {x : R} : β (n : β) (h0 : 0 β€ x) (h1 : x β€ 1), x ^ n β€ 1
| 0 h0 h1 := by rw [pow_zero]
| (n+1) h0 h1 := by { rw [pow_succ], exact mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) }
end ordered_semiring
section linear_ordered_semiring
variables [linear_ordered_semiring R]
lemma sign_cases_of_C_mul_pow_nonneg {C r : R} (h : β n : β, 0 β€ C * r ^ n) :
C = 0 β¨ (0 < C β§ 0 β€ r) :=
begin
have : 0 β€ C, by simpa only [pow_zero, mul_one] using h 0,
refine this.eq_or_lt.elim (Ξ» h, or.inl h.symm) (Ξ» hC, or.inr β¨hC, _β©),
refine nonneg_of_mul_nonneg_left _ hC,
simpa only [pow_one] using h 1
end
end linear_ordered_semiring
section linear_ordered_ring
variables [linear_ordered_ring R] {a : R} {n : β}
@[simp] lemma abs_pow (a : R) (n : β) : abs (a ^ n) = abs a ^ n :=
(pow_abs a n).symm
@[simp] theorem pow_bit1_neg_iff : a ^ bit1 n < 0 β a < 0 :=
β¨Ξ» h, not_le.1 $ Ξ» h', not_le.2 h $ pow_nonneg h' _,
Ξ» h, by { rw [bit1, pow_succ], exact mul_neg_of_neg_of_pos h (pow_bit0_pos h.ne _)}β©
@[simp] theorem pow_bit1_nonneg_iff : 0 β€ a ^ bit1 n β 0 β€ a :=
le_iff_le_iff_lt_iff_lt.2 pow_bit1_neg_iff
@[simp] theorem pow_bit1_nonpos_iff : a ^ bit1 n β€ 0 β a β€ 0 :=
by simp only [le_iff_lt_or_eq, pow_bit1_neg_iff, pow_eq_zero_iff (bit1_pos (zero_le n))]
@[simp] theorem pow_bit1_pos_iff : 0 < a ^ bit1 n β 0 < a :=
lt_iff_lt_of_le_iff_le pow_bit1_nonpos_iff
theorem pow_even_nonneg (a : R) (hn : even n) : 0 β€ a ^ n :=
by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_nonneg a k
theorem pow_even_pos (ha : a β 0) (hn : even n) : 0 < a ^ n :=
by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_pos ha k
theorem pow_odd_nonneg (ha : 0 β€ a) (hn : odd n) : 0 β€ a ^ n :=
by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_nonneg_iff.mpr ha
theorem pow_odd_pos (ha : 0 < a) (hn : odd n) : 0 < a ^ n :=
by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_pos_iff.mpr ha
theorem pow_odd_nonpos (ha : a β€ 0) (hn : odd n) : a ^ n β€ 0:=
by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_nonpos_iff.mpr ha
theorem pow_odd_neg (ha : a < 0) (hn : odd n) : a ^ n < 0:=
by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_neg_iff.mpr ha
lemma pow_even_abs (a : R) {p : β} (hp : even p) :
abs a ^ p = a ^ p :=
begin
rw [βabs_pow, abs_eq_self],
exact pow_even_nonneg _ hp
end
@[simp] lemma pow_bit0_abs (a : R) (p : β) :
abs a ^ bit0 p = a ^ bit0 p :=
pow_even_abs _ (even_bit0 _)
lemma strict_mono_pow_bit1 (n : β) : strict_mono (Ξ» a : R, a ^ bit1 n) :=
begin
intros a b hab,
cases le_total a 0 with ha ha,
{ cases le_or_lt b 0 with hb hb,
{ rw [β neg_lt_neg_iff, β neg_pow_bit1, β neg_pow_bit1],
exact pow_lt_pow_of_lt_left (neg_lt_neg hab) (neg_nonneg.2 hb) (bit1_pos (zero_le n)) },
{ exact (pow_bit1_nonpos_iff.2 ha).trans_lt (pow_bit1_pos_iff.2 hb) } },
{ exact pow_lt_pow_of_lt_left hab ha (bit1_pos (zero_le n)) }
end
/-- Bernoulli's inequality for `n : β`, `-2 β€ a`. -/
theorem one_add_mul_le_pow (H : -2 β€ a) (n : β) : 1 + (n : R) * a β€ (1 + a) ^ n :=
one_add_mul_le_pow' (mul_self_nonneg _) (mul_self_nonneg _) (neg_le_iff_add_nonneg'.1 H) _
/-- Bernoulli's inequality reformulated to estimate `a^n`. -/
theorem one_add_mul_sub_le_pow (H : -1 β€ a) (n : β) : 1 + (n : R) * (a - 1) β€ a ^ n :=
have -2 β€ a - 1, by rwa [bit0, neg_add, β sub_eq_add_neg, sub_le_sub_iff_right],
by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n
end linear_ordered_ring
/-- Bernoulli's inequality reformulated to estimate `(n : K)`. -/
theorem nat.cast_le_pow_sub_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a)
(n : β) :
(n : K) β€ (a ^ n - 1) / (a - 1) :=
(le_div_iff (sub_pos.2 H)).2 $ le_sub_left_of_add_le $
one_add_mul_sub_le_pow ((neg_le_self $ @zero_le_one K _).trans H.le) _
/-- For any `a > 1` and a natural `n` we have `n β€ a ^ n / (a - 1)`. See also
`nat.cast_le_pow_sub_div_sub` for a stronger inequality with `a ^ n - 1` in the numerator. -/
theorem nat.cast_le_pow_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : β) :
(n : K) β€ a ^ n / (a - 1) :=
(n.cast_le_pow_sub_div_sub H).trans $ div_le_div_of_le (sub_nonneg.2 H.le)
(sub_le_self _ zero_le_one)
namespace int
lemma units_sq (u : units β€) : u ^ 2 = 1 :=
(sq u).symm βΈ units_mul_self u
alias int.units_sq β int.units_pow_two
lemma units_pow_eq_pow_mod_two (u : units β€) (n : β) : u ^ n = u ^ (n % 2) :=
by conv {to_lhs, rw β nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_sq, one_pow, mul_one]
@[simp] lemma nat_abs_sq (x : β€) : (x.nat_abs ^ 2 : β€) = x ^ 2 :=
by rw [sq, int.nat_abs_mul_self', sq]
alias int.nat_abs_sq β int.nat_abs_pow_two
lemma abs_le_self_sq (a : β€) : (int.nat_abs a : β€) β€ a ^ 2 :=
by { rw [β int.nat_abs_sq a, sq], norm_cast, apply nat.le_mul_self }
alias int.abs_le_self_sq β int.abs_le_self_pow_two
lemma le_self_sq (b : β€) : b β€ b ^ 2 := le_trans (le_nat_abs) (abs_le_self_sq _)
alias int.le_self_sq β int.le_self_pow_two
lemma pow_right_injective {x : β€} (h : 1 < x.nat_abs) : function.injective ((^) x : β β β€) :=
begin
suffices : function.injective (nat_abs β ((^) x : β β β€)),
{ exact function.injective.of_comp this },
convert nat.pow_right_injective h,
ext n,
rw [function.comp_app, nat_abs_pow]
end
end int
variables (M G A)
/-- Monoid homomorphisms from `multiplicative β` are defined by the image
of `multiplicative.of_add 1`. -/
def powers_hom [monoid M] : M β (multiplicative β β* M) :=
{ to_fun := Ξ» x, β¨Ξ» n, x ^ n.to_add, by { convert pow_zero x, exact to_add_one },
Ξ» m n, pow_add x m nβ©,
inv_fun := Ξ» f, f (multiplicative.of_add 1),
left_inv := pow_one,
right_inv := Ξ» f, monoid_hom.ext $ Ξ» n, by { simp [β f.map_pow, β of_add_nsmul] } }
/-- Monoid homomorphisms from `multiplicative β€` are defined by the image
of `multiplicative.of_add 1`. -/
def gpowers_hom [group G] : G β (multiplicative β€ β* G) :=
{ to_fun := Ξ» x, β¨Ξ» n, x ^ n.to_add, gpow_zero x, Ξ» m n, gpow_add x m nβ©,
inv_fun := Ξ» f, f (multiplicative.of_add 1),
left_inv := gpow_one,
right_inv := Ξ» f, monoid_hom.ext $ Ξ» n, by { simp [β f.map_gpow, β of_add_gsmul ] } }
/-- Additive homomorphisms from `β` are defined by the image of `1`. -/
def multiples_hom [add_monoid A] : A β (β β+ A) :=
{ to_fun := Ξ» x, β¨Ξ» n, n β’ x, zero_nsmul x, Ξ» m n, add_nsmul _ _ _β©,
inv_fun := Ξ» f, f 1,
left_inv := one_nsmul,
right_inv := Ξ» f, add_monoid_hom.ext_nat $ one_nsmul (f 1) }
/-- Additive homomorphisms from `β€` are defined by the image of `1`. -/
def gmultiples_hom [add_group A] : A β (β€ β+ A) :=
{ to_fun := Ξ» x, β¨Ξ» n, n β’ x, zero_gsmul x, Ξ» m n, add_gsmul _ _ _β©,
inv_fun := Ξ» f, f 1,
left_inv := one_gsmul,
right_inv := Ξ» f, add_monoid_hom.ext_int $ one_gsmul (f 1) }
variables {M G A}
@[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative β) :
powers_hom M x n = x ^ n.to_add := rfl
@[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative β β* M) :
(powers_hom M).symm f = f (multiplicative.of_add 1) := rfl
@[simp] lemma gpowers_hom_apply [group G] (x : G) (n : multiplicative β€) :
gpowers_hom G x n = x ^ n.to_add := rfl
@[simp] lemma gpowers_hom_symm_apply [group G] (f : multiplicative β€ β* G) :
(gpowers_hom G).symm f = f (multiplicative.of_add 1) := rfl
@[simp] lemma multiples_hom_apply [add_monoid A] (x : A) (n : β) :
multiples_hom A x n = n β’ x := rfl
@[simp] lemma multiples_hom_symm_apply [add_monoid A] (f : β β+ A) :
(multiples_hom A).symm f = f 1 := rfl
@[simp] lemma gmultiples_hom_apply [add_group A] (x : A) (n : β€) :
gmultiples_hom A x n = n β’ x := rfl
@[simp] lemma gmultiples_hom_symm_apply [add_group A] (f : β€ β+ A) :
(gmultiples_hom A).symm f = f 1 := rfl
lemma monoid_hom.apply_mnat [monoid M] (f : multiplicative β β* M) (n : multiplicative β) :
f n = (f (multiplicative.of_add 1)) ^ n.to_add :=
by rw [β powers_hom_symm_apply, β powers_hom_apply, equiv.apply_symm_apply]
@[ext] lemma monoid_hom.ext_mnat [monoid M] β¦f g : multiplicative β β* Mβ¦
(h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g :=
monoid_hom.ext $ Ξ» n, by rw [f.apply_mnat, g.apply_mnat, h]
lemma monoid_hom.apply_mint [group M] (f : multiplicative β€ β* M) (n : multiplicative β€) :
f n = (f (multiplicative.of_add 1)) ^ n.to_add :=
by rw [β gpowers_hom_symm_apply, β gpowers_hom_apply, equiv.apply_symm_apply]
/-! `monoid_hom.ext_mint` is defined in `data.int.cast` -/
lemma add_monoid_hom.apply_nat [add_monoid M] (f : β β+ M) (n : β) :
f n = n β’ (f 1) :=
by rw [β multiples_hom_symm_apply, β multiples_hom_apply, equiv.apply_symm_apply]
/-! `add_monoid_hom.ext_nat` is defined in `data.nat.cast` -/
lemma add_monoid_hom.apply_int [add_group M] (f : β€ β+ M) (n : β€) :
f n = n β’ (f 1) :=
by rw [β gmultiples_hom_symm_apply, β gmultiples_hom_apply, equiv.apply_symm_apply]
/-! `add_monoid_hom.ext_int` is defined in `data.int.cast` -/
variables (M G A)
/-- If `M` is commutative, `powers_hom` is a multiplicative equivalence. -/
def powers_mul_hom [comm_monoid M] : M β* (multiplicative β β* M) :=
{ map_mul' := Ξ» a b, monoid_hom.ext $ by simp [mul_pow],
..powers_hom M}
/-- If `M` is commutative, `gpowers_hom` is a multiplicative equivalence. -/
def gpowers_mul_hom [comm_group G] : G β* (multiplicative β€ β* G) :=
{ map_mul' := Ξ» a b, monoid_hom.ext $ by simp [mul_gpow],
..gpowers_hom G}
/-- If `M` is commutative, `multiples_hom` is an additive equivalence. -/
def multiples_add_hom [add_comm_monoid A] : A β+ (β β+ A) :=
{ map_add' := Ξ» a b, add_monoid_hom.ext $ by simp [nsmul_add],
..multiples_hom A}
/-- If `M` is commutative, `gmultiples_hom` is an additive equivalence. -/
def gmultiples_add_hom [add_comm_group A] : A β+ (β€ β+ A) :=
{ map_add' := Ξ» a b, add_monoid_hom.ext $ by simp [gsmul_add],
..gmultiples_hom A}
variables {M G A}
@[simp] lemma powers_mul_hom_apply [comm_monoid M] (x : M) (n : multiplicative β) :
powers_mul_hom M x n = x ^ n.to_add := rfl
@[simp] lemma powers_mul_hom_symm_apply [comm_monoid M] (f : multiplicative β β* M) :
(powers_mul_hom M).symm f = f (multiplicative.of_add 1) := rfl
@[simp] lemma gpowers_mul_hom_apply [comm_group G] (x : G) (n : multiplicative β€) :
gpowers_mul_hom G x n = x ^ n.to_add := rfl
@[simp] lemma gpowers_mul_hom_symm_apply [comm_group G] (f : multiplicative β€ β* G) :
(gpowers_mul_hom G).symm f = f (multiplicative.of_add 1) := rfl
@[simp] lemma multiples_add_hom_apply [add_comm_monoid A] (x : A) (n : β) :
multiples_add_hom A x n = n β’ x := rfl
@[simp] lemma multiples_add_hom_symm_apply [add_comm_monoid A] (f : β β+ A) :
(multiples_add_hom A).symm f = f 1 := rfl
@[simp] lemma gmultiples_add_hom_apply [add_comm_group A] (x : A) (n : β€) :
gmultiples_add_hom A x n = n β’ x := rfl
@[simp] lemma gmultiples_add_hom_symm_apply [add_comm_group A] (f : β€ β+ A) :
(gmultiples_add_hom A).symm f = f 1 := rfl
/-!
### Commutativity (again)
Facts about `semiconj_by` and `commute` that require `gpow` or `gsmul`, or the fact that integer
multiplication equals semiring multiplication.
-/
namespace semiconj_by
section
variables [semiring R] {a x y : R}
@[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : β) :
semiconj_by a ((n : R) * x) (n * y) :=
semiconj_by.mul_right (nat.commute_cast _ _) h
@[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : β) : semiconj_by ((n : R) * a) x y :=
semiconj_by.mul_left (nat.cast_commute _ _) h
@[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : β) :
semiconj_by ((m : R) * a) (n * x) (n * y) :=
(h.cast_nat_mul_left m).cast_nat_mul_right n
end
variables [monoid M] [group G] [ring R]
@[simp] lemma units_gpow_right {a : M} {x y : units M} (h : semiconj_by a x y) :
β m : β€, semiconj_by a (β(x^m)) (β(y^m))
| (n : β) := by simp only [gpow_coe_nat, units.coe_pow, h, pow_right]
| -[1+n] := by simp only [gpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right]
variables {a b x y x' y' : R}
@[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : β€) :
semiconj_by a ((m : β€) * x) (m * y) :=
semiconj_by.mul_right (int.commute_cast _ _) h
@[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : β€) : semiconj_by ((m : R) * a) x y :=
semiconj_by.mul_left (int.cast_commute _ _) h
@[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : β€) :
semiconj_by ((m : R) * a) (n * x) (n * y) :=
(h.cast_int_mul_left m).cast_int_mul_right n
end semiconj_by
namespace commute
section
variables [semiring R] {a b : R}
@[simp] theorem cast_nat_mul_right (h : commute a b) (n : β) : commute a ((n : R) * b) :=
h.cast_nat_mul_right n
@[simp] theorem cast_nat_mul_left (h : commute a b) (n : β) : commute ((n : R) * a) b :=
h.cast_nat_mul_left n
@[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : β) :
commute ((m : R) * a) (n * b) :=
h.cast_nat_mul_cast_nat_mul m n
@[simp] theorem self_cast_nat_mul (n : β) : commute a (n * a) :=
(commute.refl a).cast_nat_mul_right n
@[simp] theorem cast_nat_mul_self (n : β) : commute ((n : R) * a) a :=
(commute.refl a).cast_nat_mul_left n
@[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : β) : commute ((m : R) * a) (n * a) :=
(commute.refl a).cast_nat_mul_cast_nat_mul m n
end
variables [monoid M] [group G] [ring R]
@[simp] lemma units_gpow_right {a : M} {u : units M} (h : commute a u) (m : β€) :
commute a (β(u^m)) :=
h.units_gpow_right m
@[simp] lemma units_gpow_left {u : units M} {a : M} (h : commute βu a) (m : β€) :
commute (β(u^m)) a :=
(h.symm.units_gpow_right m).symm
variables {a b : R}
@[simp] lemma cast_int_mul_right (h : commute a b) (m : β€) : commute a (m * b) :=
h.cast_int_mul_right m
@[simp] lemma cast_int_mul_left (h : commute a b) (m : β€) : commute ((m : R) * a) b :=
h.cast_int_mul_left m
lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : β€) : commute ((m : R) * a) (n * b) :=
h.cast_int_mul_cast_int_mul m n
variables (a) (m n : β€)
@[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n
@[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n
theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) :=
(commute.refl a).cast_int_mul_cast_int_mul m n
end commute
section multiplicative
open multiplicative
@[simp] lemma nat.to_add_pow (a : multiplicative β) (b : β) : to_add (a ^ b) = to_add a * b :=
begin
induction b with b ih,
{ erw [pow_zero, to_add_one, mul_zero] },
{ simp [*, pow_succ, add_comm, nat.mul_succ] }
end
@[simp] lemma nat.of_add_mul (a b : β) : of_add (a * b) = of_add a ^ b :=
(nat.to_add_pow _ _).symm
@[simp] lemma int.to_add_pow (a : multiplicative β€) (b : β) : to_add (a ^ b) = to_add a * b :=
by induction b; simp [*, mul_add, pow_succ, add_comm]
@[simp] lemma int.to_add_gpow (a : multiplicative β€) (b : β€) : to_add (a ^ b) = to_add a * b :=
int.induction_on b (by simp)
(by simp [gpow_add, mul_add] {contextual := tt})
(by simp [gpow_add, mul_add, sub_eq_add_neg, -int.add_neg_one] {contextual := tt})
@[simp] lemma int.of_add_mul (a b : β€) : of_add (a * b) = of_add a ^ b :=
(int.to_add_gpow _ _).symm
end multiplicative
namespace units
variables [monoid M]
lemma conj_pow (u : units M) (x : M) (n : β) : (βu * x * β(uβ»ΒΉ))^n = u * x^n * β(uβ»ΒΉ) :=
(divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm
lemma conj_pow' (u : units M) (x : M) (n : β) : (β(uβ»ΒΉ) * x * u)^n = β(uβ»ΒΉ) * x^n * u:=
(uβ»ΒΉ).conj_pow x n
end units
namespace opposite
variables [monoid M]
/-- Moving to the opposite monoid commutes with taking powers. -/
@[simp] lemma op_pow (x : M) (n : β) : op (x ^ n) = (op x) ^ n :=
begin
induction n with n h,
{ simp },
{ rw [pow_succ', op_mul, h, pow_succ] }
end
@[simp] lemma unop_pow (x : Mα΅α΅) (n : β) : unop (x ^ n) = (unop x) ^ n :=
begin
induction n with n h,
{ simp },
{ rw [pow_succ', unop_mul, h, pow_succ] }
end
end opposite
|
b1e2c515e80b2b3dfffc73311ca8754b2562d400 | 618003631150032a5676f229d13a079ac875ff77 | /src/data/pequiv.lean | c55c856a1958da599d139298c10a7484fc0bae4e | [
"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 | 11,179 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.set.lattice
universes u v w x
/-- A `pequiv` is a partial equivalence, a representation of a bijection between a subset
of `Ξ±` and a subset of `Ξ²` -/
structure pequiv (Ξ± : Type u) (Ξ² : Type v) :=
(to_fun : Ξ± β option Ξ²)
(inv_fun : Ξ² β option Ξ±)
(inv : β (a : Ξ±) (b : Ξ²), a β inv_fun b β b β to_fun a)
infixr ` β. `:25 := pequiv
namespace pequiv
variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} {Ξ΄ : Type x}
open function option
instance : has_coe_to_fun (Ξ± β. Ξ²) := β¨_, to_funβ©
@[simp] lemma coe_mk_apply (fβ : Ξ± β option Ξ²) (fβ : Ξ² β option Ξ±) (h) (x : Ξ±) :
(pequiv.mk fβ fβ h : Ξ± β option Ξ²) x = fβ x := rfl
@[ext] lemma ext : β {f g : Ξ± β. Ξ²} (h : β x, f x = g x), f = g
| β¨fβ, fβ, hfβ© β¨gβ, gβ, hgβ© h :=
have h : fβ = gβ, from funext h,
have β b, fβ b = gβ b,
begin
subst h,
assume b,
have hf := Ξ» a, hf a b,
have hg := Ξ» a, hg a b,
cases h : gβ b with a,
{ simp only [h, option.not_mem_none, false_iff] at hg,
simp only [hg, iff_false] at hf,
rwa [option.eq_none_iff_forall_not_mem] },
{ rw [β option.mem_def, hf, β hg, h, option.mem_def] }
end,
by simp [*, funext_iff]
lemma ext_iff {f g : Ξ± β. Ξ²} : f = g β β x, f x = g x :=
β¨congr_fun β congr_arg _, extβ©
@[refl] protected def refl (Ξ± : Type*) : Ξ± β. Ξ± :=
{ to_fun := some,
inv_fun := some,
inv := Ξ» _ _, eq_comm }
@[symm] protected def symm (f : Ξ± β. Ξ²) : Ξ² β. Ξ± :=
{ to_fun := f.2,
inv_fun := f.1,
inv := Ξ» _ _, (f.inv _ _).symm }
lemma mem_iff_mem (f : Ξ± β. Ξ²) : β {a : Ξ±} {b : Ξ²}, a β f.symm b β b β f a := f.3
lemma eq_some_iff (f : Ξ± β. Ξ²) : β {a : Ξ±} {b : Ξ²}, f.symm b = some a β f a = some b := f.3
@[trans] protected def trans (f : Ξ± β. Ξ²) (g : Ξ² β. Ξ³) : pequiv Ξ± Ξ³ :=
{ to_fun := Ξ» a, (f a).bind g,
inv_fun := Ξ» a, (g.symm a).bind f.symm,
inv := Ξ» a b, by simp [*, and.comm, eq_some_iff f, eq_some_iff g] at * }
@[simp] lemma refl_apply (a : Ξ±) : pequiv.refl Ξ± a = some a := rfl
@[simp] lemma symm_refl : (pequiv.refl Ξ±).symm = pequiv.refl Ξ± := rfl
@[simp] lemma symm_symm (f : Ξ± β. Ξ²) : f.symm.symm = f := by cases f; refl
lemma symm_injective : function.injective (@pequiv.symm Ξ± Ξ²) :=
left_inverse.injective symm_symm
lemma trans_assoc (f : Ξ± β. Ξ²) (g : Ξ² β. Ξ³) (h : Ξ³ β. Ξ΄) :
(f.trans g).trans h = f.trans (g.trans h) :=
ext (Ξ» _, option.bind_assoc _ _ _)
lemma mem_trans (f : Ξ± β. Ξ²) (g : Ξ² β. Ξ³) (a : Ξ±) (c : Ξ³) :
c β f.trans g a β β b, b β f a β§ c β g b := option.bind_eq_some'
lemma trans_eq_some (f : Ξ± β. Ξ²) (g : Ξ² β. Ξ³) (a : Ξ±) (c : Ξ³) :
f.trans g a = some c β β b, f a = some b β§ g b = some c := option.bind_eq_some'
lemma trans_eq_none (f : Ξ± β. Ξ²) (g : Ξ² β. Ξ³) (a : Ξ±) :
f.trans g a = none β (β b c, b β f a β¨ c β g b) :=
by simp only [eq_none_iff_forall_not_mem, mem_trans]; push_neg; tauto
@[simp] lemma refl_trans (f : Ξ± β. Ξ²) : (pequiv.refl Ξ±).trans f = f :=
by ext; dsimp [pequiv.trans]; refl
@[simp] lemma trans_refl (f : Ξ± β. Ξ²) : f.trans (pequiv.refl Ξ²) = f :=
by ext; dsimp [pequiv.trans]; simp
protected lemma inj (f : Ξ± β. Ξ²) {aβ aβ : Ξ±} {b : Ξ²} (hβ : b β f aβ) (hβ : b β f aβ) : aβ = aβ :=
by rw β mem_iff_mem at *; cases h : f.symm b; simp * at *
lemma injective_of_forall_ne_is_some (f : Ξ± β. Ξ²) (aβ : Ξ±)
(h : β (aβ : Ξ±), aβ β aβ β is_some (f aβ)) : injective f :=
has_left_inverse.injective
β¨Ξ» b, option.rec_on b aβ (Ξ» b', option.rec_on (f.symm b') aβ id),
Ξ» x, begin
classical,
cases hfx : f x,
{ have : x = aβ, from not_imp_comm.1 (h x) (hfx.symm βΈ by simp), simp [this] },
{ simp only [hfx], rw [(eq_some_iff f).2 hfx], refl }
endβ©
lemma injective_of_forall_is_some {f : Ξ± β. Ξ²}
(h : β (a : Ξ±), is_some (f a)) : injective f :=
(classical.em (nonempty Ξ±)).elim
(Ξ» hn, injective_of_forall_ne_is_some f (classical.choice hn)
(Ξ» a _, h a))
(Ξ» hn x, (hn β¨xβ©).elim)
section of_set
variables (s : set Ξ±) [decidable_pred s]
def of_set (s : set Ξ±) [decidable_pred s] : Ξ± β. Ξ± :=
{ to_fun := Ξ» a, if a β s then some a else none,
inv_fun := Ξ» a, if a β s then some a else none,
inv := Ξ» a b, by split_ifs; finish [eq_comm] }
lemma mem_of_set_self_iff {s : set Ξ±} [decidable_pred s] {a : Ξ±} : a β of_set s a β a β s :=
by dsimp [of_set]; split_ifs; simp *
lemma mem_of_set_iff {s : set Ξ±} [decidable_pred s] {a b : Ξ±} : a β of_set s b β a = b β§ a β s :=
by dsimp [of_set]; split_ifs; split; finish
@[simp] lemma of_set_eq_some_iff {s : set Ξ±} {h : decidable_pred s} {a b : Ξ±} :
of_set s b = some a β a = b β§ a β s := mem_of_set_iff
@[simp] lemma of_set_eq_some_self_iff {s : set Ξ±} {h : decidable_pred s} {a : Ξ±} :
of_set s a = some a β a β s := mem_of_set_self_iff
@[simp] lemma of_set_symm : (of_set s).symm = of_set s := rfl
@[simp] lemma of_set_univ : of_set set.univ = pequiv.refl Ξ± :=
by ext; dsimp [of_set]; simp [eq_comm]
@[simp] lemma of_set_eq_refl {s : set Ξ±} [decidable_pred s] :
of_set s = pequiv.refl Ξ± β s = set.univ :=
β¨Ξ» h, begin
rw [set.eq_univ_iff_forall],
intro,
rw [β mem_of_set_self_iff, h],
exact rfl
end, Ξ» h, by simp only [of_set_univ.symm, h]; congrβ©
end of_set
lemma symm_trans_rev (f : Ξ± β. Ξ²) (g : Ξ² β. Ξ³) : (f.trans g).symm = g.symm.trans f.symm := rfl
lemma trans_symm (f : Ξ± β. Ξ²) : f.trans f.symm = of_set {a | (f a).is_some} :=
begin
ext,
dsimp [pequiv.trans],
simp only [eq_some_iff f, option.is_some_iff_exists, option.mem_def, bind_eq_some', of_set_eq_some_iff],
split,
{ rintros β¨b, hbβ, hbββ©,
exact β¨pequiv.inj _ hbβ hbβ, b, hbββ© },
{ simp {contextual := tt} }
end
lemma symm_trans (f : Ξ± β. Ξ²) : f.symm.trans f = of_set {b | (f.symm b).is_some} :=
symm_injective $ by simp [symm_trans_rev, trans_symm, -symm_symm]
lemma trans_symm_eq_iff_forall_is_some {f : Ξ± β. Ξ²} :
f.trans f.symm = pequiv.refl Ξ± β β a, is_some (f a) :=
by rw [trans_symm, of_set_eq_refl, set.eq_univ_iff_forall]; refl
instance : has_bot (Ξ± β. Ξ²) :=
β¨{ to_fun := Ξ» _, none,
inv_fun := Ξ» _, none,
inv := by simp }β©
@[simp] lemma bot_apply (a : Ξ±) : (β₯ : Ξ± β. Ξ²) a = none := rfl
@[simp] lemma symm_bot : (β₯ : Ξ± β. Ξ²).symm = β₯ := rfl
@[simp] lemma trans_bot (f : Ξ± β. Ξ²) : f.trans (β₯ : Ξ² β. Ξ³) = β₯ :=
by ext; dsimp [pequiv.trans]; simp
@[simp] lemma bot_trans (f : Ξ² β. Ξ³) : (β₯ : Ξ± β. Ξ²).trans f = β₯ :=
by ext; dsimp [pequiv.trans]; simp
lemma is_some_symm_get (f : Ξ± β. Ξ²) {a : Ξ±} (h : is_some (f a)) :
is_some (f.symm (option.get h)) :=
is_some_iff_exists.2 β¨a, by rw [f.eq_some_iff, some_get]β©
section single
variables [decidable_eq Ξ±] [decidable_eq Ξ²] [decidable_eq Ξ³]
def single (a : Ξ±) (b : Ξ²) : Ξ± β. Ξ² :=
{ to_fun := Ξ» x, if x = a then some b else none,
inv_fun := Ξ» x, if x = b then some a else none,
inv := Ξ» _ _, by simp; split_ifs; cc }
lemma mem_single (a : Ξ±) (b : Ξ²) : b β single a b a := if_pos rfl
lemma mem_single_iff (aβ aβ : Ξ±) (bβ bβ : Ξ²) : bβ β single aβ bβ aβ β aβ = aβ β§ bβ = bβ :=
by dsimp [single]; split_ifs; simp [*, eq_comm]
@[simp] lemma symm_single (a : Ξ±) (b : Ξ²) : (single a b).symm = single b a := rfl
@[simp] lemma single_apply (a : Ξ±) (b : Ξ²) : single a b a = some b := if_pos rfl
lemma single_apply_of_ne {aβ aβ : Ξ±} (h : aβ β aβ) (b : Ξ²) : single aβ b aβ = none := if_neg h.symm
lemma single_trans_of_mem (a : Ξ±) {b : Ξ²} {c : Ξ³} {f : Ξ² β. Ξ³} (h : c β f b) :
(single a b).trans f = single a c :=
begin
ext,
dsimp [single, pequiv.trans],
split_ifs; simp * at *
end
lemma trans_single_of_mem {a : Ξ±} {b : Ξ²} (c : Ξ³) {f : Ξ± β. Ξ²} (h : b β f a) :
f.trans (single b c) = single a c :=
symm_injective $ single_trans_of_mem _ ((mem_iff_mem f).2 h)
@[simp] lemma single_trans_single (a : Ξ±) (b : Ξ²) (c : Ξ³) : (single a b).trans (single b c) = single a c :=
single_trans_of_mem _ (mem_single _ _)
@[simp] lemma single_subsingleton_eq_refl [subsingleton Ξ±] (a b : Ξ±) : single a b = pequiv.refl Ξ± :=
begin
ext i j,
dsimp [single],
rw [if_pos (subsingleton.elim i a), subsingleton.elim i j, subsingleton.elim b j]
end
lemma trans_single_of_eq_none {b : Ξ²} (c : Ξ³) {f : Ξ΄ β. Ξ²} (h : f.symm b = none) :
f.trans (single b c) = β₯ :=
begin
ext,
simp only [eq_none_iff_forall_not_mem, option.mem_def, f.eq_some_iff] at h,
dsimp [pequiv.trans, single],
simp,
intros,
split_ifs;
simp * at *
end
lemma single_trans_of_eq_none (a : Ξ±) {b : Ξ²} {f : Ξ² β. Ξ΄} (h : f b = none) :
(single a b).trans f = β₯ :=
symm_injective $ trans_single_of_eq_none _ h
lemma single_trans_single_of_ne {bβ bβ : Ξ²} (h : bβ β bβ) (a : Ξ±) (c : Ξ³) :
(single a bβ).trans (single bβ c) = β₯ :=
single_trans_of_eq_none _ (single_apply_of_ne h.symm _)
end single
section order
instance : partial_order (Ξ± β. Ξ²) :=
{ le := Ξ» f g, β (a : Ξ±) (b : Ξ²), b β f a β b β g a,
le_refl := Ξ» _ _ _, id,
le_trans := Ξ» f g h fg gh a b, (gh a b) β (fg a b),
le_antisymm := Ξ» f g fg gf, ext begin
assume a,
cases h : g a with b,
{ exact eq_none_iff_forall_not_mem.2
(Ξ» b hb, option.not_mem_none b $ h βΈ fg a b hb) },
{ exact gf _ _ h }
end }
lemma le_def {f g : Ξ± β. Ξ²} : f β€ g β (β (a : Ξ±) (b : Ξ²), b β f a β b β g a) := iff.rfl
instance : order_bot (Ξ± β. Ξ²) :=
{ bot_le := Ξ» _ _ _ h, (not_mem_none _ h).elim,
..pequiv.partial_order,
..pequiv.has_bot }
instance [decidable_eq Ξ±] [decidable_eq Ξ²] : semilattice_inf_bot (Ξ± β. Ξ²) :=
{ inf := Ξ» f g,
{ to_fun := Ξ» a, if f a = g a then f a else none,
inv_fun := Ξ» b, if f.symm b = g.symm b then f.symm b else none,
inv := Ξ» a b, begin
have := @mem_iff_mem _ _ f a b,
have := @mem_iff_mem _ _ g a b,
split_ifs; finish
end },
inf_le_left := Ξ» _ _ _ _, by simp; split_ifs; cc,
inf_le_right := Ξ» _ _ _ _, by simp; split_ifs; cc,
le_inf := Ξ» f g h fg gh a b, begin
have := fg a b,
have := gh a b,
simp [le_def],
split_ifs; finish
end,
..pequiv.order_bot }
end order
end pequiv
namespace equiv
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*}
def to_pequiv (f : Ξ± β Ξ²) : Ξ± β. Ξ² :=
{ to_fun := some β f,
inv_fun := some β f.symm,
inv := by simp [equiv.eq_symm_apply, eq_comm] }
@[simp] lemma to_pequiv_refl : (equiv.refl Ξ±).to_pequiv = pequiv.refl Ξ± := rfl
lemma to_pequiv_trans (f : Ξ± β Ξ²) (g : Ξ² β Ξ³) : (f.trans g).to_pequiv =
f.to_pequiv.trans g.to_pequiv := rfl
lemma to_pequiv_symm (f : Ξ± β Ξ²) : f.symm.to_pequiv = f.to_pequiv.symm := rfl
lemma to_pequiv_apply (f : Ξ± β Ξ²) (x : Ξ±) : f.to_pequiv x = some (f x) := rfl
end equiv
|
63aeff132dba56536088ce6147b28e9e0053dbbb | a047a4718edfa935d17231e9e6ecec8c7b701e05 | /src/algebra/pi_instances.lean | 9730afaef7073655d93188b87d83f7c477316864 | [
"Apache-2.0"
] | permissive | utensil-contrib/mathlib | bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767 | b91909e77e219098a2f8cc031f89d595fe274bd2 | refs/heads/master | 1,668,048,976,965 | 1,592,442,701,000 | 1,592,442,701,000 | 273,197,855 | 0 | 0 | null | 1,592,472,812,000 | 1,592,472,811,000 | null | UTF-8 | Lean | false | false | 18,424 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
-/
import algebra.module
import ring_theory.subring
import ring_theory.prod
open_locale big_operators
/-!
# Pi instances for algebraic structures
-/
namespace pi
universes u v w
variable {I : Type u} -- The indexing type
variable {f : I β Type v} -- The family of types already equipped with instances
variables (x y : Ξ i, f i) (i : I)
instance has_zero [β i, has_zero $ f i] : has_zero (Ξ i : I, f i) := β¨Ξ» i, 0β©
@[simp] lemma zero_apply [β i, has_zero $ f i] : (0 : Ξ i, f i) i = 0 := rfl
instance has_one [β i, has_one $ f i] : has_one (Ξ i : I, f i) := β¨Ξ» i, 1β©
@[simp] lemma one_apply [β i, has_one $ f i] : (1 : Ξ i, f i) i = 1 := rfl
attribute [to_additive] pi.has_one
attribute [to_additive] pi.one_apply
instance has_add [β i, has_add $ f i] : has_add (Ξ i : I, f i) := β¨Ξ» x y, Ξ» i, x i + y iβ©
@[simp] lemma add_apply [β i, has_add $ f i] : (x + y) i = x i + y i := rfl
instance has_mul [β i, has_mul $ f i] : has_mul (Ξ i : I, f i) := β¨Ξ» x y, Ξ» i, x i * y iβ©
@[simp] lemma mul_apply [β i, has_mul $ f i] : (x * y) i = x i * y i := rfl
attribute [to_additive] pi.has_mul
attribute [to_additive] pi.mul_apply
instance has_inv [β i, has_inv $ f i] : has_inv (Ξ i : I, f i) := β¨Ξ» x, Ξ» i, (x i)β»ΒΉβ©
@[simp] lemma inv_apply [β i, has_inv $ f i] : xβ»ΒΉ i = (x i)β»ΒΉ := rfl
instance has_neg [β i, has_neg $ f i] : has_neg (Ξ i : I, f i) := β¨Ξ» x, Ξ» i, -(x i)β©
@[simp] lemma neg_apply [β i, has_neg $ f i] : (-x) i = -x i := rfl
attribute [to_additive] pi.has_inv
attribute [to_additive] pi.inv_apply
instance has_scalar {Ξ± : Type*} [β i, has_scalar Ξ± $ f i] : has_scalar Ξ± (Ξ i : I, f i) := β¨Ξ» s x, Ξ» i, s β’ (x i)β©
@[simp] lemma smul_apply {Ξ± : Type*} [β i, has_scalar Ξ± $ f i] (s : Ξ±) : (s β’ x) i = s β’ x i := rfl
instance semigroup [β i, semigroup $ f i] : semigroup (Ξ i : I, f i) := by pi_instance
instance comm_semigroup [β i, comm_semigroup $ f i] : comm_semigroup (Ξ i : I, f i) := by pi_instance
instance monoid [β i, monoid $ f i] : monoid (Ξ i : I, f i) := by pi_instance
instance comm_monoid [β i, comm_monoid $ f i] : comm_monoid (Ξ i : I, f i) := by pi_instance
instance group [β i, group $ f i] : group (Ξ i : I, f i) := by pi_instance
instance comm_group [β i, comm_group $ f i] : comm_group (Ξ i : I, f i) := by pi_instance
instance add_semigroup [β i, add_semigroup $ f i] : add_semigroup (Ξ i : I, f i) := by pi_instance
instance add_comm_semigroup [β i, add_comm_semigroup $ f i] : add_comm_semigroup (Ξ i : I, f i) := by pi_instance
instance add_monoid [β i, add_monoid $ f i] : add_monoid (Ξ i : I, f i) := by pi_instance
instance add_comm_monoid [β i, add_comm_monoid $ f i] : add_comm_monoid (Ξ i : I, f i) := by pi_instance
instance add_group [β i, add_group $ f i] : add_group (Ξ i : I, f i) := by pi_instance
instance add_comm_group [β i, add_comm_group $ f i] : add_comm_group (Ξ i : I, f i) := by pi_instance
instance semiring [β i, semiring $ f i] : semiring (Ξ i : I, f i) := by pi_instance
instance ring [β i, ring $ f i] : ring (Ξ i : I, f i) := by pi_instance
instance comm_ring [β i, comm_ring $ f i] : comm_ring (Ξ i : I, f i) := by pi_instance
instance mul_action (Ξ±) {m : monoid Ξ±} [β i, mul_action Ξ± $ f i] :
@mul_action Ξ± (Ξ i : I, f i) m :=
{ smul := Ξ» c f i, c β’ f i,
mul_smul := Ξ» r s f, funext $ Ξ» i, mul_smul _ _ _,
one_smul := Ξ» f, funext $ Ξ» i, one_smul Ξ± _ }
instance distrib_mul_action (Ξ±) {m : monoid Ξ±} {n : β i, add_monoid $ f i} [β i, distrib_mul_action Ξ± $ f i] :
@distrib_mul_action Ξ± (Ξ i : I, f i) m (@pi.add_monoid I f n) :=
{ smul_zero := Ξ» c, funext $ Ξ» i, smul_zero _,
smul_add := Ξ» c f g, funext $ Ξ» i, smul_add _ _ _,
..pi.mul_action _ }
variables (I f)
instance semimodule (Ξ±) {r : semiring Ξ±} {m : β i, add_comm_monoid $ f i} [β i, semimodule Ξ± $ f i] :
@semimodule Ξ± (Ξ i : I, f i) r (@pi.add_comm_monoid I f m) :=
{ add_smul := Ξ» c f g, funext $ Ξ» i, add_smul _ _ _,
zero_smul := Ξ» f, funext $ Ξ» i, zero_smul Ξ± _,
..pi.distrib_mul_action _ }
variables {I f}
instance left_cancel_semigroup [β i, left_cancel_semigroup $ f i] :
left_cancel_semigroup (Ξ i : I, f i) :=
by pi_instance
instance add_left_cancel_semigroup [β i, add_left_cancel_semigroup $ f i] :
add_left_cancel_semigroup (Ξ i : I, f i) :=
by pi_instance
instance right_cancel_semigroup [β i, right_cancel_semigroup $ f i] :
right_cancel_semigroup (Ξ i : I, f i) :=
by pi_instance
instance add_right_cancel_semigroup [β i, add_right_cancel_semigroup $ f i] :
add_right_cancel_semigroup (Ξ i : I, f i) :=
by pi_instance
instance ordered_cancel_comm_monoid [β i, ordered_cancel_add_comm_monoid $ f i] :
ordered_cancel_add_comm_monoid (Ξ i : I, f i) :=
by pi_instance
instance ordered_add_comm_group [β i, ordered_add_comm_group $ f i] :
ordered_add_comm_group (Ξ i : I, f i) :=
{ add_le_add_left := Ξ» x y hxy c i, add_le_add_left (hxy i) _,
..pi.add_comm_group,
..pi.partial_order }
attribute [to_additive add_semigroup] pi.semigroup
attribute [to_additive add_comm_semigroup] pi.comm_semigroup
attribute [to_additive add_monoid] pi.monoid
attribute [to_additive add_comm_monoid] pi.comm_monoid
attribute [to_additive add_group] pi.group
attribute [to_additive add_comm_group] pi.comm_group
attribute [to_additive add_left_cancel_semigroup] pi.left_cancel_semigroup
attribute [to_additive add_right_cancel_semigroup] pi.right_cancel_semigroup
@[simp] lemma sub_apply [β i, add_group $ f i] : (x - y) i = x i - y i := rfl
@[to_additive]
lemma list_prod_apply {Ξ± : Type*} {Ξ² : Ξ± β Type*} [βa, monoid (Ξ² a)] (a : Ξ±) :
β (l : list (Ξ a, Ξ² a)), l.prod a = (l.map (Ξ»f:Ξ a, Ξ² a, f a)).prod
| [] := rfl
| (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l]
@[to_additive]
lemma multiset_prod_apply {Ξ± : Type*} {Ξ² : Ξ± β Type*} [βa, comm_monoid (Ξ² a)] (a : Ξ±)
(s : multiset (Ξ a, Ξ² a)) : s.prod a = (s.map (Ξ»f:Ξ a, Ξ² a, f a)).prod :=
quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end
@[to_additive]
lemma finset_prod_apply {Ξ± : Type*} {Ξ² : Ξ± β Type*} {Ξ³} [βa, comm_monoid (Ξ² a)] (a : Ξ±)
(s : finset Ξ³) (g : Ξ³ β Ξ a, Ξ² a) : (β c in s, g c) a = β c in s, g c a :=
show (s.val.map g).prod a = (s.val.map (Ξ»c, g c a)).prod,
by rw [multiset_prod_apply, multiset.map_map]
/-- A family of ring homomorphisms `f a : Ξ³ β+* Ξ² a` defines a ring homomorphism
`pi.ring_hom f : Ξ³ β+* Ξ a, Ξ² a` given by `pi.ring_hom f x b = f b x`. -/
protected def ring_hom
{Ξ± : Type u} {Ξ² : Ξ± β Type v} [R : Ξ a : Ξ±, semiring (Ξ² a)]
{Ξ³ : Type w} [semiring Ξ³] (f : Ξ a : Ξ±, Ξ³ β+* Ξ² a) :
Ξ³ β+* Ξ a, Ξ² a :=
{ to_fun := Ξ» x b, f b x,
map_add' := Ξ» x y, funext $ Ξ» z, (f z).map_add x y,
map_mul' := Ξ» x y, funext $ Ξ» z, (f z).map_mul x y,
map_one' := funext $ Ξ» z, (f z).map_one,
map_zero' := funext $ Ξ» z, (f z).map_zero }
instance is_ring_hom_pi
{Ξ± : Type u} {Ξ² : Ξ± β Type v} [R : Ξ a : Ξ±, ring (Ξ² a)]
{Ξ³ : Type w} [ring Ξ³]
(f : Ξ a : Ξ±, Ξ³ β Ξ² a) [Rh : Ξ a : Ξ±, is_ring_hom (f a)] :
is_ring_hom (Ξ» x b, f b x) :=
(show Ξ³ β+* Ξ a, Ξ² a, from pi.ring_hom (Ξ» a, ring_hom.of (f a))).is_ring_hom
-- Note that we only define `single` here for dependent functions with additive fibres.
section
variables [decidable_eq I]
variables [Ξ i, has_zero (f i)]
/-- The function supported at `i`, with value `x` there. -/
def single (i : I) (x : f i) : Ξ i, f i :=
Ξ» i', if h : i' = i then (by { subst h, exact x }) else 0
@[simp]
lemma single_eq_same (i : I) (x : f i) : single i x i = x :=
begin
dsimp [single],
split_ifs,
{ refl, },
{ exfalso, exact h rfl, }
end
@[simp]
lemma single_eq_of_ne {i i' : I} (h : i' β i) (x : f i) : single i x i' = 0 :=
begin
dsimp [single],
split_ifs with h',
{ exfalso, exact h h', },
{ refl, }
end
end
end pi
section
universes u v
variable {I : Type u} -- The indexing type
variable (f : I β Type v) -- The family of types already equipped with instances
variables [Ξ i, monoid (f i)]
/-- Evaluation of functions into an indexed collection of monoids at a point is a monoid
homomorphism. -/
@[to_additive "Evaluation of functions into an indexed collection of additive monoids at a point
is an additive monoid homomorphism."]
def monoid_hom.apply (i : I) : (Ξ i, f i) β* f i :=
{ to_fun := Ξ» g, g i,
map_one' := rfl,
map_mul' := Ξ» x y, rfl, }
@[simp, to_additive]
lemma monoid_hom.apply_apply (i : I) (g : Ξ i, f i) : (monoid_hom.apply f i) g = g i := rfl
end
section
universes u v
variable {I : Type u} -- The indexing type
variable (f : I β Type v) -- The family of types already equipped with instances
variables [Ξ i, semiring (f i)]
/-- Evaluation of functions into an indexed collection of monoids at a point is a monoid homomorphism. -/
def ring_hom.apply (i : I) : (Ξ i, f i) β+* f i :=
{ ..(monoid_hom.apply f i),
..(add_monoid_hom.apply f i) }
@[simp]
lemma ring_hom.apply_apply (i : I) (g : Ξ i, f i) : (ring_hom.apply f i) g = g i := rfl
end
section
variables {I : Type*} (Z : I β Type*)
variables [Ξ i, comm_monoid (Z i)]
@[simp, to_additive]
lemma finset.prod_apply {Ξ³ : Type*} {s : finset Ξ³} (h : Ξ³ β (Ξ i, Z i)) (i : I) :
(β g in s, h g) i = β g in s, h g i :=
begin
classical,
induction s using finset.induction_on with b s nmem ih,
{ simp only [finset.prod_empty], refl },
{ simp only [nmem, finset.prod_insert, not_false_iff],
rw pi.mul_apply (h b) _ i,
rw ih, }
end
end
section
-- As we only defined `single` into `add_monoid`, we only prove the `finset.sum` version here.
variables {I : Type*} [decidable_eq I] {Z : I β Type*}
variables [Ξ i, add_comm_monoid (Z i)]
lemma finset.univ_sum_single [fintype I] (f : Ξ i, Z i) :
β i, pi.single i (f i) = f :=
begin
ext a,
rw [finset.sum_apply, finset.sum_eq_single a],
{ simp, },
{ intros b _ h, simp [h.symm], },
{ intro h, exfalso, simpa using h, },
end
end
section
open pi
variables {I : Type*} [decidable_eq I]
variable (f : I β Type*)
section
variables [Ξ i, add_monoid (f i)]
/-- The additive monoid homomorphism including a single additive monoid
into a dependent family of additive monoids, as functions supported at a point. -/
def add_monoid_hom.single (i : I) : f i β+ Ξ i, f i :=
{ to_fun := Ξ» x, single i x,
map_zero' :=
begin
ext i', by_cases h : i' = i,
{ subst h, simp only [single_eq_same], refl, },
{ simp only [h, single_eq_of_ne, ne.def, not_false_iff], refl, },
end,
map_add' := Ξ» x y,
begin
ext i', by_cases h : i' = i,
-- FIXME in the next two `simp only`s,
-- it would be really nice to not have to provide the arguments to `add_apply`.
{ subst h, simp only [single_eq_same, add_apply (single i' x) (single i' y) i'], },
{ simp only [h, add_zero, single_eq_of_ne, add_apply (single i x) (single i y) i', ne.def, not_false_iff], },
end, }
@[simp]
lemma add_monoid_hom.single_apply {i : I} (x : f i) : (add_monoid_hom.single f i) x = single i x := rfl
end
section
variables {f}
variables [Ξ i, add_comm_monoid (f i)]
@[ext]
lemma add_monoid_hom.functions_ext [fintype I] (G : Type*) [add_comm_monoid G] (g h : (Ξ i, f i) β+ G)
(w : β (i : I) (x : f i), g (single i x) = h (single i x)) : g = h :=
begin
ext k,
rw [βfinset.univ_sum_single k, add_monoid_hom.map_sum, add_monoid_hom.map_sum],
apply finset.sum_congr rfl,
intros,
apply w,
end
end
section
variables {f}
variables [Ξ i, semiring (f i)]
-- it is somewhat unfortunate that we can't easily use `add_monoid_hom.functions_ext` here
@[ext]
lemma ring_hom.functions_ext [fintype I] (G : Type*) [semiring G] (g h : (Ξ i, f i) β+* G)
(w : β (i : I) (x : f i), g (single i x) = h (single i x)) : g = h :=
begin
ext k,
rw [βfinset.univ_sum_single k, ring_hom.map_sum, ring_hom.map_sum],
apply finset.sum_congr rfl,
intros,
apply w,
end
end
end
namespace prod
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ξ΄ : Type*} {p q : Ξ± Γ Ξ²}
@[to_additive is_add_monoid_hom]
lemma fst.is_monoid_hom [monoid Ξ±] [monoid Ξ²] : is_monoid_hom (prod.fst : Ξ± Γ Ξ² β Ξ±) :=
{ map_mul := Ξ» _ _, rfl, map_one := rfl }
@[to_additive is_add_monoid_hom]
lemma snd.is_monoid_hom [monoid Ξ±] [monoid Ξ²] : is_monoid_hom (prod.snd : Ξ± Γ Ξ² β Ξ²) :=
{ map_mul := Ξ» _ _, rfl, map_one := rfl }
@[to_additive is_add_group_hom]
lemma fst.is_group_hom [group Ξ±] [group Ξ²] : is_group_hom (prod.fst : Ξ± Γ Ξ² β Ξ±) :=
{ map_mul := Ξ» _ _, rfl }
@[to_additive is_add_group_hom]
lemma snd.is_group_hom [group Ξ±] [group Ξ²] : is_group_hom (prod.snd : Ξ± Γ Ξ² β Ξ²) :=
{ map_mul := Ξ» _ _, rfl }
attribute [instance] fst.is_monoid_hom fst.is_add_monoid_hom snd.is_monoid_hom snd.is_add_monoid_hom
fst.is_group_hom fst.is_add_group_hom snd.is_group_hom snd.is_add_group_hom
@[to_additive]
lemma fst_prod [comm_monoid Ξ±] [comm_monoid Ξ²] {t : finset Ξ³} {f : Ξ³ β Ξ± Γ Ξ²} :
(β c in t, f c).1 = β c in t, (f c).1 :=
(monoid_hom.fst Ξ± Ξ²).map_prod f t
@[to_additive]
lemma snd_prod [comm_monoid Ξ±] [comm_monoid Ξ²] {t : finset Ξ³} {f : Ξ³ β Ξ± Γ Ξ²} :
(β c in t, f c).2 = β c in t, (f c).2 :=
(monoid_hom.snd Ξ± Ξ²).map_prod f t
instance fst.is_semiring_hom [semiring Ξ±] [semiring Ξ²] : is_semiring_hom (prod.fst : Ξ± Γ Ξ² β Ξ±) :=
(ring_hom.fst Ξ± Ξ²).is_semiring_hom
instance snd.is_semiring_hom [semiring Ξ±] [semiring Ξ²] : is_semiring_hom (prod.snd : Ξ± Γ Ξ² β Ξ²) :=
(ring_hom.snd Ξ± Ξ²).is_semiring_hom
instance fst.is_ring_hom [ring Ξ±] [ring Ξ²] : is_ring_hom (prod.fst : Ξ± Γ Ξ² β Ξ±) :=
(ring_hom.fst Ξ± Ξ²).is_ring_hom
instance snd.is_ring_hom [ring Ξ±] [ring Ξ²] : is_ring_hom (prod.snd : Ξ± Γ Ξ² β Ξ²) :=
(ring_hom.snd Ξ± Ξ²).is_ring_hom
/-- Left injection function for the inner product
From a vector space (and also group and module) perspective the product is the same as the sum of
two vector spaces. `inl` and `inr` provide the corresponding injection functions.
-/
def inl [has_zero Ξ²] (a : Ξ±) : Ξ± Γ Ξ² := (a, 0)
/-- Right injection function for the inner product -/
def inr [has_zero Ξ±] (b : Ξ²) : Ξ± Γ Ξ² := (0, b)
lemma injective_inl [has_zero Ξ²] : function.injective (inl : Ξ± β Ξ± Γ Ξ²) :=
assume x y h, (prod.mk.inj_iff.mp h).1
lemma injective_inr [has_zero Ξ±] : function.injective (inr : Ξ² β Ξ± Γ Ξ²) :=
assume x y h, (prod.mk.inj_iff.mp h).2
@[simp] lemma inl_eq_inl [has_zero Ξ²] {aβ aβ : Ξ±} : (inl aβ : Ξ± Γ Ξ²) = inl aβ β aβ = aβ :=
iff.intro (assume h, injective_inl h) (assume h, h βΈ rfl)
@[simp] lemma inr_eq_inr [has_zero Ξ±] {bβ bβ : Ξ²} : (inr bβ : Ξ± Γ Ξ²) = inr bβ β bβ = bβ :=
iff.intro (assume h, injective_inr h) (assume h, h βΈ rfl)
@[simp] lemma inl_eq_inr [has_zero Ξ±] [has_zero Ξ²] {a : Ξ±} {b : Ξ²} :
inl a = inr b β a = 0 β§ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma inr_eq_inl [has_zero Ξ±] [has_zero Ξ²] {a : Ξ±} {b : Ξ²} :
inr b = inl a β a = 0 β§ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma fst_inl [has_zero Ξ²] (a : Ξ±) : (inl a : Ξ± Γ Ξ²).1 = a := rfl
@[simp] lemma snd_inl [has_zero Ξ²] (a : Ξ±) : (inl a : Ξ± Γ Ξ²).2 = 0 := rfl
@[simp] lemma fst_inr [has_zero Ξ±] (b : Ξ²) : (inr b : Ξ± Γ Ξ²).1 = 0 := rfl
@[simp] lemma snd_inr [has_zero Ξ±] (b : Ξ²) : (inr b : Ξ± Γ Ξ²).2 = b := rfl
instance [has_scalar Ξ± Ξ²] [has_scalar Ξ± Ξ³] : has_scalar Ξ± (Ξ² Γ Ξ³) := β¨Ξ»a p, (a β’ p.1, a β’ p.2)β©
@[simp] theorem smul_fst [has_scalar Ξ± Ξ²] [has_scalar Ξ± Ξ³]
(a : Ξ±) (x : Ξ² Γ Ξ³) : (a β’ x).1 = a β’ x.1 := rfl
@[simp] theorem smul_snd [has_scalar Ξ± Ξ²] [has_scalar Ξ± Ξ³]
(a : Ξ±) (x : Ξ² Γ Ξ³) : (a β’ x).2 = a β’ x.2 := rfl
@[simp] theorem smul_mk [has_scalar Ξ± Ξ²] [has_scalar Ξ± Ξ³]
(a : Ξ±) (b : Ξ²) (c : Ξ³) : a β’ (b, c) = (a β’ b, a β’ c) := rfl
instance {r : semiring Ξ±} [add_comm_monoid Ξ²] [add_comm_monoid Ξ³]
[semimodule Ξ± Ξ²] [semimodule Ξ± Ξ³] : semimodule Ξ± (Ξ² Γ Ξ³) :=
{ smul_add := assume a pβ pβ, mk.inj_iff.mpr β¨smul_add _ _ _, smul_add _ _ _β©,
add_smul := assume a pβ pβ, mk.inj_iff.mpr β¨add_smul _ _ _, add_smul _ _ _β©,
mul_smul := assume aβ aβ p, mk.inj_iff.mpr β¨mul_smul _ _ _, mul_smul _ _ _β©,
one_smul := assume β¨b, cβ©, mk.inj_iff.mpr β¨one_smul _ _, one_smul _ _β©,
zero_smul := assume β¨b, cβ©, mk.inj_iff.mpr β¨zero_smul _ _, zero_smul _ _β©,
smul_zero := assume a, mk.inj_iff.mpr β¨smul_zero _, smul_zero _β©,
.. prod.has_scalar }
section substructures
variables (s : set Ξ±) (t : set Ξ²)
@[to_additive is_add_submonoid]
instance [monoid Ξ±] [monoid Ξ²] [is_submonoid s] [is_submonoid t] :
is_submonoid (s.prod t) :=
{ one_mem := by rw set.mem_prod; split; apply is_submonoid.one_mem,
mul_mem := by intros; rw set.mem_prod at *; split; apply is_submonoid.mul_mem; tauto }
@[to_additive prod.is_add_subgroup.prod]
instance is_subgroup.prod [group Ξ±] [group Ξ²] [is_subgroup s] [is_subgroup t] :
is_subgroup (s.prod t) :=
{ inv_mem := by intros; rw set.mem_prod at *; split; apply is_subgroup.inv_mem; tauto,
.. prod.is_submonoid s t }
instance is_subring.prod [ring Ξ±] [ring Ξ²] [is_subring s] [is_subring t] :
is_subring (s.prod t) :=
{ .. prod.is_submonoid s t, .. prod.is_add_subgroup.prod s t }
end substructures
end prod
namespace finset
@[to_additive prod_mk_sum]
lemma prod_mk_prod {Ξ± Ξ² Ξ³ : Type*} [comm_monoid Ξ±] [comm_monoid Ξ²] (s : finset Ξ³)
(f : Ξ³ β Ξ±) (g : Ξ³ β Ξ²) : (β x in s, f x, β x in s, g x) = β x in s, (f x, g x) :=
by haveI := classical.dec_eq Ξ³; exact
finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt})
end finset
|
2d1250929def5d63ebfbc80e009bc34a993b4dfa | 8b9cc39aef95580045a98cd3aac5961a7611e7b8 | /src/__old_polytope.lean | 56fa0826ab5320cbd5b5e051626f877ae94e40b3 | [] | no_license | vihdzp/polytope | de2202d393ca744cd879f3a316784dc67607af8f | c2c6ed3ace5fa6af0fac0c923bdf44a2d8c76a49 | refs/heads/master | 1,688,255,728,556 | 1,627,359,324,000 | 1,627,359,324,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,137 | lean | import order.bounded_lattice set_theory.cardinal data.subtype
open_locale cardinal
universe u
section
parameters {Ξ± : Type u} [partial_order Ξ±]
-- A chain is a subset of faces where every pair of elements is related.
def is_chain (faces chain : set Ξ±) : Prop :=
chain β faces β§ β faceβ faceβ β chain, faceβ β€ faceβ β¨ faceβ β€ faceβ
namespace is_chain
-- The empty set is a chain.
lemma empty_chain (faces : set Ξ±) : is_chain faces β
:=
β¨set.empty_subset faces, Ξ» _ _ h, absurd h $ set.not_mem_empty _β©
-- A single face forms a chain.
lemma chain_single (faces : set Ξ±) (face β faces) : is_chain faces {face} :=
β¨set.singleton_subset_iff.mpr βΉ_βΊ, Ξ» _ _ (hβ : _ = _) (hβ : _ = _), by rw [hβ, hβ]; tautoβ©
-- A chain from the empty set is the empty set.
lemma no_faces (chain : set Ξ±) : is_chain β
chain β chain = β
:=
β¨Ξ» h, eq_bot_iff.mpr h.left, Ξ» h, by rw h; apply empty_chainβ©
end is_chain
-- A flag is a maximal chain.
def is_flag (faces chain : set Ξ±) : Prop :=
is_chain faces chain β§ Β¬ β chain', is_chain faces chain' β chain β chain'
-- A section is a set of faces bounded by two others.
def section_of {faces : set Ξ±} (faceβ faceβ β faces) : faceβ β€ faceβ β set Ξ± :=
Ξ» _, {face β faces | faceβ β€ face β§ face β€ faceβ}
section section_of
lemma section_single (faces : set Ξ±) (face β faces) : section_of face face βΉ_βΊ βΉ_βΊ (le_refl _) = {face} :=
set.ext
(Ξ» face',
β¨(Ξ» hf, begin
cases hf with _ _,
finish,
end),
(Ξ» h, begin
induction h,
fconstructor,
exact H,
tauto,
end)β©)
#check set.Ioo
-- add lemmas about section_of {x} _ _ = {x}
end section_of
theorem is_flag.imp_is_chain {faces chain : set Ξ±} : is_flag faces chain β is_chain faces chain :=
and.left
def chains (faces : set Ξ±) : set (set Ξ±) :=
{chain | is_chain faces chain}
def flags (faces : set Ξ±) : set (set Ξ±) :=
{chain | is_flag faces chain}
theorem flags_sub_chains (faces : set Ξ±) : flags faces β chains faces :=
Ξ» _, is_flag.imp_is_chain
def is_rank_of_face {faces : set Ξ±} (face β faces) (c : cardinal) : Prop :=
β chain β chains faces, face β chain β (β face' β chain, face' β€ face) β # chain = c + 1
def proper_faces (faces : set Ξ±) : set Ξ± :=
{face β faces | β faceβ faceβ β faces, faceβ < face β§ face < faceβ}
def connected (faces : set Ξ±) : Prop :=
β faceβ faceβ β proper_faces faces, β chain β chains faces, faceβ β chain β§ faceβ β chain
def strongly_connected (faces : set Ξ±) : Prop :=
β faceβ faceβ β faces, faceβ β€ faceβ β connected (section_of faceβ faceβ βΉ_βΊ βΉ_βΊ βΉ_βΊ)
end
structure abstract_polytope (Ξ± : Type u) [partial_order Ξ±] :=
(faces : set Ξ±)
(has_bot : β face β faces, β face' β faces, face β€ face')
(has_top : β face β faces, β face' β faces, face' β€ face)
(flags_same_card : β c, β flag β flags faces, # (flag : set Ξ±) = c)
(is_scon : strongly_connected faces)
(diamond : β (faceβ faceβ β faces) c, faceβ < faceβ β is_rank_of_face faceβ βΉ_βΊ c β is_rank_of_face faceβ βΉ_βΊ (c + 2) β
β dβ dβ β faces, dβ β dβ β§ {face β faces | faceβ < face β§ face < faceβ} = {dβ, dβ})
namespace abstract_polytope
def nullitope (Ξ± : Type u) [partial_order Ξ±] [inhabited Ξ±] : abstract_polytope Ξ± :=
let x := arbitrary Ξ± in
β¨
{x},
β¨x, rfl, Ξ» _ h, le_of_eq $ eq.symm hβ©,
β¨x, rfl, Ξ» _ h, ge_of_eq $ eq.symm hβ©,
β¨1, Ξ» chain (h : _ β§ _), begin
rcases h with β¨β¨hll, _β©, hβ©,
rw set.subset_singleton_iff at hll,
push_neg at h,
sorry,
endβ©,
begin
rintros _ _ hβ hβ hle _ _ hfβ,
rw set.mem_singleton_iff at hβ hβ,
cases hβ, cases hβ,
rcases hfβ with β¨_, _, _, _, _, β¨hltl, htlrβ©β©,
sorry,
end,
begin
intros _ _ hβ hβ c hlt,
rw set.mem_singleton_iff at hβ hβ,
rw [hβ, hβ] at hlt,
exact absurd hlt (asymm hlt)
end,
β©
end abstract_polytope
|
44457e051b4ad18cc3779c12e06b44ec24e43316 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/order/semiconj_Sup.lean | a9dc15f5e92d609f5458c3b09a43b3d5786e1040 | [
"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 | 5,657 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury G. Kudryashov
-/
import order.conditionally_complete_lattice
import logic.function.conjugate
import order.ord_continuous
import data.equiv.mul_add
/-!
# Semiconjugate by `Sup`
In this file we prove two facts about semiconjugate (families of) functions.
First, if an order isomorphism `fa : Ξ± β Ξ±` is semiconjugate to an order embedding `fb : Ξ² β Ξ²` by
`g : Ξ± β Ξ²`, then `fb` is semiconjugate to `fa` by `y β¦ Sup {x | g x β€ y}`, see
`semiconj.symm_adjoint`.
Second, consider two actions `fβ fβ : G β Ξ± β Ξ±` of a group on a complete lattice by order
isomorphisms. Then the map `x β¦ β¨ g : G, (fβ g)β»ΒΉ (fβ g x)` semiconjugates each `fβ g'` to `fβ g'`,
see `function.Sup_div_semiconj`. In the case of a conditionally complete lattice, a similar
statement holds true under an additional assumption that each set `{(fβ g)β»ΒΉ (fβ g x) | g : G}` is
bounded above, see `function.cSup_div_semiconj`.
The lemmas come from [Γtienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie
bornee][ghys87:groupes], Proposition 2.1 and 5.4 respectively. In the paper they are formulated for
homeomorphisms of the circle, so in order to apply results from this file one has to lift these
homeomorphisms to the real line first.
-/
variables {Ξ± : Type*} {Ξ² : Type*}
open set
/-- We say that `g : Ξ² β Ξ±` is an order right adjoint function for `f : Ξ± β Ξ²` if it sends each `y`
to a least upper bound for `{x | f x β€ y}`. If `Ξ±` is a partial order, and `f : Ξ± β Ξ²` has
a right adjoint, then this right adjoint is unique. -/
def is_order_right_adjoint [preorder Ξ±] [preorder Ξ²] (f : Ξ± β Ξ²) (g : Ξ² β Ξ±) :=
β y, is_lub {x | f x β€ y} (g y)
lemma is_order_right_adjoint_Sup [complete_lattice Ξ±] [preorder Ξ²] (f : Ξ± β Ξ²) :
is_order_right_adjoint f (Ξ» y, Sup {x | f x β€ y}) :=
Ξ» y, is_lub_Sup _
lemma is_order_right_adjoint_cSup [conditionally_complete_lattice Ξ±] [preorder Ξ²] (f : Ξ± β Ξ²)
(hne : β y, β x, f x β€ y) (hbdd : β y, β b, β x, f x β€ y β x β€ b) :
is_order_right_adjoint f (Ξ» y, Sup {x | f x β€ y}) :=
Ξ» y, is_lub_cSup (hne y) (hbdd y)
lemma is_order_right_adjoint.unique [partial_order Ξ±] [preorder Ξ²] {f : Ξ± β Ξ²} {gβ gβ : Ξ² β Ξ±}
(hβ : is_order_right_adjoint f gβ) (hβ : is_order_right_adjoint f gβ) :
gβ = gβ :=
funext $ Ξ» y, (hβ y).unique (hβ y)
lemma is_order_right_adjoint.right_mono [preorder Ξ±] [preorder Ξ²] {f : Ξ± β Ξ²} {g : Ξ² β Ξ±}
(h : is_order_right_adjoint f g) :
monotone g :=
Ξ» yβ yβ hy, (h yβ).mono (h yβ) $ Ξ» x hx, le_trans hx hy
namespace function
/-- If an order automorphism `fa` is semiconjugate to an order embedding `fb` by a function `g`
and `g'` is an order right adjoint of `g` (i.e. `g' y = Sup {x | f x β€ y}`), then `fb` is
semiconjugate to `fa` by `g'`.
This is a version of Proposition 2.1 from [Γtienne Ghys, Groupes d'homeomorphismes du cercle et
cohomologie bornee][ghys87:groupes]. -/
lemma semiconj.symm_adjoint [partial_order Ξ±] [preorder Ξ²]
{fa : ((β€) : Ξ± β Ξ± β Prop) βo ((β€) : Ξ± β Ξ± β Prop)}
{fb : ((β€) : Ξ² β Ξ² β Prop) βΌo ((β€) : Ξ² β Ξ² β Prop)} {g : Ξ± β Ξ²}
(h : function.semiconj g fa fb) {g' : Ξ² β Ξ±} (hg' : is_order_right_adjoint g g') :
function.semiconj g' fb fa :=
begin
refine Ξ» y, (hg' _).unique _,
rw [β @image_preimage_eq _ _ _ {x | g x β€ fb y} fa.surjective, preimage_set_of_eq],
simp only [h.eq, β fb.ord, fa.left_ord_continuous (hg' _)]
end
variable {G : Type*}
lemma semiconj_of_is_lub [partial_order Ξ±] [group G]
(fβ fβ : G β* ((β€) : Ξ± β Ξ± β Prop) βo ((β€) : Ξ± β Ξ± β Prop)) {h : Ξ± β Ξ±}
(H : β x, is_lub (range (Ξ» g', (fβ g')β»ΒΉ (fβ g' x))) (h x)) (g : G) :
function.semiconj h (fβ g) (fβ g) :=
begin
refine Ξ» y, (H _).unique _,
have := (fβ g).left_ord_continuous (H y),
rw [β range_comp, β (equiv.mul_right g).surjective.range_comp _] at this,
simpa [(β)] using this
end
/-- Consider two actions `fβ fβ : G β Ξ± β Ξ±` of a group on a complete lattice by order
isomorphisms. Then the map `x β¦ β¨ g : G, (fβ g)β»ΒΉ (fβ g x)` semiconjugates each `fβ g'` to `fβ g'`.
This is a version of Proposition 5.4 from [Γtienne Ghys, Groupes d'homeomorphismes du cercle et
cohomologie bornee][ghys87:groupes]. -/
lemma Sup_div_semiconj [complete_lattice Ξ±] [group G]
(fβ fβ : G β* ((β€) : Ξ± β Ξ± β Prop) βo ((β€) : Ξ± β Ξ± β Prop)) (g : G) :
function.semiconj (Ξ» x, β¨ g' : G, (fβ g')β»ΒΉ (fβ g' x)) (fβ g) (fβ g) :=
semiconj_of_is_lub fβ fβ (Ξ» x, is_lub_supr) _
/-- Consider two actions `fβ fβ : G β Ξ± β Ξ±` of a group on a conditionally complete lattice by order
isomorphisms. Suppose that each set $s(x)=\{f_1(g)^{-1} (f_2(g)(x)) | g \in G\}$ is bounded above.
Then the map `x β¦ Sup s(x)` semiconjugates each `fβ g'` to `fβ g'`.
This is a version of Proposition 5.4 from [Γtienne Ghys, Groupes d'homeomorphismes du cercle et
cohomologie bornee][ghys87:groupes]. -/
lemma cSup_div_semiconj [conditionally_complete_lattice Ξ±] [group G]
(fβ fβ : G β* ((β€) : Ξ± β Ξ± β Prop) βo ((β€) : Ξ± β Ξ± β Prop))
(hbdd : β x, bdd_above (range $ Ξ» g, (fβ g)β»ΒΉ (fβ g x))) (g : G) :
function.semiconj (Ξ» x, β¨ g' : G, (fβ g')β»ΒΉ (fβ g' x)) (fβ g) (fβ g) :=
semiconj_of_is_lub fβ fβ (Ξ» x, is_lub_cSup (range_nonempty _) (hbdd x)) _
end function
|
70f9317bcd2f12feda19570f1e86ad6f5452bfb9 | 34c1747a946aa0941114ffca77a3b7c1e4cfb686 | /src/sheaves/presheaf_extension.lean | 57f6c1c989903ab12fac43f760e4df19e9f50194 | [] | no_license | martrik/lean-scheme | 2b9edd63550c4579a451f793ab289af9fc79a16d | 033dc47192ba4c61e4e771701f5e29f8007e6332 | refs/heads/master | 1,588,866,287,405 | 1,554,922,682,000 | 1,554,922,682,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,574 | lean | /-
Presheaf (of types) extension.
https://stacks.math.columbia.edu/tag/009N
-/
import topology.opens
import sheaves.presheaf
import sheaves.presheaf_of_rings_on_basis
import sheaves.stalk_on_basis
universe u
open topological_space
section presheaf_extension
variables {Ξ± : Type u} [T : topological_space Ξ±]
variables {B : set (opens Ξ±)} {HB : opens.is_basis B}
-- F defined in the whole space to F defined on the basis.
def presheaf_to_presheaf_on_basis
(F : presheaf Ξ±) : presheaf_on_basis Ξ± HB :=
{ F := Ξ» U BU, F U,
res := Ξ» U V BU BV HVU, F.res U V HVU,
Hid := Ξ» U BU, F.Hid U,
Hcomp := Ξ» U V W BU BV BW, F.Hcomp U V W }
-- F defined on the bases extended to the whole space.
@[reducible] def presheaf_on_basis_to_presheaf
(F : presheaf_on_basis Ξ± HB) : presheaf Ξ± :=
{ F := Ξ» U, {s : Ξ (x β U), stalk_on_basis F x //
β (x β U), β (V) (BV : V β B) (Hx : x β V) (Ο : F BV),
β (y β U β© V), s y = Ξ» _, β¦{U := V, BU := BV, Hx := H.2, s := Ο}β§},
res := Ξ» U W HWU FU,
{ val := Ξ» x HxW, (FU.val x $ HWU HxW),
property := Ξ» x HxW,
begin
rcases (FU.property x (HWU HxW)) with β¨V, β¨BV, β¨HxV, β¨Ο, HFVβ©β©β©β©,
use [V, BV, HxV, Ο],
rintros y β¨HyW, HyVβ©,
rw (HFV y β¨HWU HyW, HyVβ©),
end },
Hid := Ξ» U, funext $ Ξ» x, subtype.eq rfl,
Hcomp := Ξ» U V W HWV HVU, funext $ Ξ» x, subtype.eq rfl}
notation F `βββ`:1 := presheaf_on_basis_to_presheaf F
end presheaf_extension
|
e8544786f507939f747a68546cd025a5bfc489d4 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/ind6.lean | 611dfc7cbeee928fa6d1ef75afcddb31d387ac63 | [
"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 | 301 | lean | inductive tree.{u} (A : Type.{u}) : Type.{max u 1} :=
| node : A β forest.{u} A β tree.{u} A
with forest.{u} (A : Type.{u}) : Type.{max u 1} :=
| nil : forest.{u} A
| cons : tree.{u} A β forest.{u} A β forest.{u} A
check tree.{1}
check forest.{1}
check tree_rec.{1 1}
check forest_rec.{1 1}
|
0f4e2c3eb5dbd4aa06727a603cbfbaab47c296da | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/bugNatLitDiscrTree.lean | 05741f8a7fad4d46b2a52f84cecbec966035d080 | [
"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 | 793 | lean | def f' (n : Nat) : Option { r : Nat // r β€ n } :=
match n with
| 0 => some β¨0, Nat.le_refl _β©
| n+1 => match f' n with
| some β¨m, hββ© =>
have : m < n+1 := Nat.lt_of_le_of_lt hβ (Nat.lt_succ_self _)
match f' m with
| some β¨r, hββ© => some β¨r, Nat.le_trans hβ (Nat.le_trans hβ (Nat.le_succ _))β©
| none => none
| none => none
theorem f'_ne_none (n : Nat) : f' n β none := by
match n with
| 0 => simp (config := { decide := false }) [f']; done
| n+1 =>
simp [f']
have ihβ := f'_ne_none n
split
next m hβ he =>
have : m < n+1 := Nat.lt_of_le_of_lt hβ (Nat.lt_succ_self _)
have ihβ := f'_ne_none m
split
next => simp
next h => contradiction
next => contradiction
|
0e4f6892c0c722fd0bf3804f33e363be41a5cd46 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /stage0/src/Lean/PrettyPrinter.lean | 472f010027c0fe5417c1ae284990ec76667d519f | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 3,373 | lean | /-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Lean.PrettyPrinter.Delaborator
import Lean.PrettyPrinter.Parenthesizer
import Lean.PrettyPrinter.Formatter
import Lean.Parser.Module
import Lean.ParserCompiler
namespace Lean
def PPContext.runCoreM {Ξ± : Type} (ppCtx : PPContext) (x : CoreM Ξ±) : IO Ξ± :=
Prod.fst <$> x.toIO { options := ppCtx.opts, currNamespace := ppCtx.currNamespace, openDecls := ppCtx.openDecls } { env := ppCtx.env }
def PPContext.runMetaM {Ξ± : Type} (ppCtx : PPContext) (x : MetaM Ξ±) : IO Ξ± :=
ppCtx.runCoreM <| x.run' { lctx := ppCtx.lctx } { mctx := ppCtx.mctx }
namespace PrettyPrinter
def ppTerm (stx : Syntax) : CoreM Format := do
let opts β getOptions
let stx := (sanitizeSyntax stx).run' { options := opts }
parenthesizeTerm stx >>= formatTerm
def ppExpr (currNamespace : Name) (openDecls : List OpenDecl) (e : Expr) : MetaM Format := do
let lctx β getLCtx
let opts β getOptions
let lctx := lctx.sanitizeNames.run' { options := opts }
Meta.withLCtx lctx #[] do
let stx β delab currNamespace openDecls e
ppTerm stx
@[export lean_pp_expr]
def ppExprLegacy (env : Environment) (mctx : MetavarContext) (lctx : LocalContext) (opts : Options) (e : Expr) : IO Format :=
Prod.fst <$> ((ppExpr Name.anonymous [] e).run' { lctx := lctx } { mctx := mctx }).toIO { options := opts } { env := env }
def ppCommand (stx : Syntax) : CoreM Format :=
parenthesizeCommand stx >>= formatCommand
def ppModule (stx : Syntax) : CoreM Format := do
parenthesize Lean.Parser.Module.module.parenthesizer stx >>= format Lean.Parser.Module.module.formatter
private partial def noContext : MessageData β MessageData
| MessageData.withContext ctx msg => noContext msg
| MessageData.withNamingContext ctx msg => MessageData.withNamingContext ctx (noContext msg)
| MessageData.nest n msg => MessageData.nest n (noContext msg)
| MessageData.group msg => MessageData.group (noContext msg)
| MessageData.compose msgβ msgβ => MessageData.compose (noContext msgβ) (noContext msgβ)
| MessageData.tagged tag msg => MessageData.tagged tag (noContext msg)
| MessageData.node msgs => MessageData.node (msgs.map noContext)
| msg => msg
-- strip context (including environments with registered pretty printers) to prevent infinite recursion when pretty printing pretty printer error
private def withoutContext {m} [MonadExcept Exception m] (x : m Format) : m Format :=
tryCatch x fun
| Exception.error ref msg => throw $ Exception.error ref (noContext msg)
| ex => throw ex
builtin_initialize
ppFnsRef.set {
ppExpr := fun ctx e => ctx.runMetaM $ withoutContext $ ppExpr ctx.currNamespace ctx.openDecls e,
ppTerm := fun ctx stx => ctx.runCoreM $ withoutContext $ ppTerm stx,
ppGoal := fun ctx mvarId => ctx.runMetaM $ withoutContext $ Meta.ppGoal mvarId
}
builtin_initialize
registerTraceClass `PrettyPrinter
@[builtinInit]
unsafe def registerParserCompilers : IO Unit := do
ParserCompiler.registerParserCompiler β¨`parenthesizer, parenthesizerAttribute, combinatorParenthesizerAttributeβ©
ParserCompiler.registerParserCompiler β¨`formatter, formatterAttribute, combinatorFormatterAttributeβ©
end PrettyPrinter
end Lean
|
0b4c445c2dfd50832ed3898b1610ce81807e7e66 | bb31430994044506fa42fd667e2d556327e18dfe | /src/field_theory/subfield.lean | 1f66d94ff24e0a610be0a9f53ca6b40a718c8d00 | [
"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 | 27,725 | 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 algebra.algebra.basic
import algebra.order.field.inj_surj
/-!
# Subfields
Let `K` be a field. This file defines the "bundled" subfield type `subfield K`, a type
whose terms correspond to subfields of `K`. This is the preferred way to talk
about subfields in mathlib. Unbundled subfields (`s : set K` and `is_subfield s`)
are not in this file, and they will ultimately be deprecated.
We prove that subfields are a complete lattice, and that you can `map` (pushforward) and
`comap` (pull back) them along ring homomorphisms.
We define the `closure` construction from `set R` to `subfield R`, sending a subset of `R`
to the subfield it generates, and prove that it is a Galois insertion.
## Main definitions
Notation used here:
`(K : Type u) [field K] (L : Type u) [field L] (f g : K β+* L)`
`(A : subfield K) (B : subfield L) (s : set K)`
* `subfield R` : the type of subfields of a ring `R`.
* `instance : complete_lattice (subfield R)` : the complete lattice structure on the subfields.
* `subfield.closure` : subfield closure of a set, i.e., the smallest subfield that includes the set.
* `subfield.gi` : `closure : set M β subfield M` and coercion `coe : subfield M β set M`
form a `galois_insertion`.
* `comap f B : subfield K` : the preimage of a subfield `B` along the ring homomorphism `f`
* `map f A : subfield L` : the image of a subfield `A` along the ring homomorphism `f`.
* `prod A B : subfield (K Γ L)` : the product of subfields
* `f.field_range : subfield B` : the range of the ring homomorphism `f`.
* `eq_locus_field f g : subfield K` : given ring homomorphisms `f g : K β+* R`,
the subfield of `K` where `f x = g x`
## Implementation notes
A subfield is implemented as a subring which is is closed under `β»ΒΉ`.
Lattice inclusion (e.g. `β€` and `β`) is used rather than set notation (`β` and `β©`), although
`β` is defined as membership of a subfield's underlying set.
## Tags
subfield, subfields
-/
open_locale big_operators
universes u v w
variables {K : Type u} {L : Type v} {M : Type w} [field K] [field L] [field M]
/-- `subfield_class S K` states `S` is a type of subsets `s β K` closed under field operations. -/
class subfield_class (S : Type*) (K : out_param $ Type*) [field K] [set_like S K]
extends subring_class S K, inv_mem_class S K : Prop
namespace subfield_class
variables (S : Type*) [set_like S K] [h : subfield_class S K]
include h
/-- A subfield contains `1`, products and inverses.
Be assured that we're not actually proving that subfields are subgroups:
`subgroup_class` is really an abbreviation of `subgroup_with_or_without_zero_class`.
-/
@[priority 100] -- See note [lower instance priority]
instance subfield_class.to_subgroup_class : subgroup_class S K := { .. h }
variables {S}
lemma coe_rat_mem (s : S) (x : β) : (x : K) β s :=
by simpa only [rat.cast_def] using div_mem (coe_int_mem s x.num) (coe_nat_mem s x.denom)
instance (s : S) : has_rat_cast s :=
β¨Ξ» x, β¨βx, coe_rat_mem s xβ©β©
@[simp] lemma coe_rat_cast (s : S) (x : β) : ((x : s) : K) = x := rfl
lemma rat_smul_mem (s : S) (a : β) (x : s) : (a β’ x : K) β s :=
by simpa only [rat.smul_def] using mul_mem (coe_rat_mem s a) x.prop
instance (s : S) : has_smul β s :=
β¨Ξ» a x, β¨a β’ x, rat_smul_mem s a xβ©β©
@[simp] lemma coe_rat_smul (s : S) (a : β) (x : s) : (β(a β’ x) : K) = a β’ x := rfl
variables (S)
/-- A subfield inherits a field structure -/
@[priority 75] -- Prefer subclasses of `field` over subclasses of `subfield_class`.
instance to_field (s : S) : field s :=
subtype.coe_injective.field (coe : s β K)
rfl rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl)
(Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _, rfl) (Ξ» _, rfl)
omit h
/-- A subfield of a `linear_ordered_field` is a `linear_ordered_field`. -/
@[priority 75] -- Prefer subclasses of `field` over subclasses of `subfield_class`.
instance to_linear_ordered_field {K} [linear_ordered_field K] [set_like S K]
[subfield_class S K] (s : S) :
linear_ordered_field s :=
subtype.coe_injective.linear_ordered_field coe
rfl rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl)
(Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl)
(Ξ» _ _, rfl)
end subfield_class
set_option old_structure_cmd true
/-- `subfield R` is the type of subfields of `R`. A subfield of `R` is a subset `s` that is a
multiplicative submonoid and an additive subgroup. Note in particular that it shares the
same 0 and 1 as R. -/
structure subfield (K : Type u) [field K] extends subring K :=
(inv_mem' : β x β carrier, xβ»ΒΉ β carrier)
/-- Reinterpret a `subfield` as a `subring`. -/
add_decl_doc subfield.to_subring
namespace subfield
/-- The underlying `add_subgroup` of a subfield. -/
def to_add_subgroup (s : subfield K) : add_subgroup K :=
{ ..s.to_subring.to_add_subgroup }
/-- The underlying submonoid of a subfield. -/
def to_submonoid (s : subfield K) : submonoid K :=
{ ..s.to_subring.to_submonoid }
instance : set_like (subfield K) K :=
β¨subfield.carrier, Ξ» p q h, by cases p; cases q; congr'β©
instance : subfield_class (subfield K) K :=
{ add_mem := add_mem',
zero_mem := zero_mem',
neg_mem := neg_mem',
mul_mem := mul_mem',
one_mem := one_mem',
inv_mem := inv_mem' }
@[simp]
lemma mem_carrier {s : subfield K} {x : K} : x β s.carrier β x β s := iff.rfl
@[simp]
lemma mem_mk {S : set K} {x : K} (hβ hβ hβ hβ hβ
hβ) :
x β (β¨S, hβ, hβ, hβ, hβ, hβ
, hββ© : subfield K) β x β S := iff.rfl
@[simp] lemma coe_set_mk (S : set K) (hβ hβ hβ hβ hβ
hβ) :
((β¨S, hβ, hβ, hβ, hβ, hβ
, hββ© : subfield K) : set K) = S := rfl
@[simp]
lemma mk_le_mk {S S' : set K} (hβ hβ hβ hβ hβ
hβ hβ' hβ' hβ' hβ' hβ
' hβ') :
(β¨S, hβ, hβ, hβ, hβ, hβ
, hββ© : subfield K) β€ (β¨S', hβ', hβ', hβ', hβ', hβ
', hβ'β© : subfield K) β
S β S' :=
iff.rfl
/-- Two subfields are equal if they have the same elements. -/
@[ext] theorem ext {S T : subfield K} (h : β x, x β S β x β T) : S = T := set_like.ext h
/-- Copy of a subfield with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (S : subfield K) (s : set K) (hs : s = βS) : subfield K :=
{ carrier := s,
inv_mem' := hs.symm βΈ S.inv_mem',
..S.to_subring.copy s hs }
@[simp] lemma coe_copy (S : subfield K) (s : set K) (hs : s = βS) :
(S.copy s hs : set K) = s := rfl
lemma copy_eq (S : subfield K) (s : set K) (hs : s = βS) : S.copy s hs = S :=
set_like.coe_injective hs
@[simp] lemma coe_to_subring (s : subfield K) : (s.to_subring : set K) = s :=
rfl
@[simp] lemma mem_to_subring (s : subfield K) (x : K) :
x β s.to_subring β x β s := iff.rfl
end subfield
/-- A `subring` containing inverses is a `subfield`. -/
def subring.to_subfield (s : subring K) (hinv : β x β s, xβ»ΒΉ β s) : subfield K :=
{ inv_mem' := hinv
..s }
namespace subfield
variables (s t : subfield K)
section derived_from_subfield_class
/-- A subfield contains the field's 1. -/
protected theorem one_mem : (1 : K) β s := one_mem s
/-- A subfield contains the field's 0. -/
protected theorem zero_mem : (0 : K) β s := zero_mem s
/-- A subfield is closed under multiplication. -/
protected theorem mul_mem {x y : K} : x β s β y β s β x * y β s := mul_mem
/-- A subfield is closed under addition. -/
protected theorem add_mem {x y : K} : x β s β y β s β x + y β s := add_mem
/-- A subfield is closed under negation. -/
protected theorem neg_mem {x : K} : x β s β -x β s := neg_mem
/-- A subfield is closed under subtraction. -/
protected theorem sub_mem {x y : K} : x β s β y β s β x - y β s := sub_mem
/-- A subfield is closed under inverses. -/
protected theorem inv_mem {x : K} : x β s β xβ»ΒΉ β s := inv_mem
/-- A subfield is closed under division. -/
protected theorem div_mem {x y : K} : x β s β y β s β x / y β s := div_mem
/-- Product of a list of elements in a subfield is in the subfield. -/
protected lemma list_prod_mem {l : list K} : (β x β l, x β s) β l.prod β s := list_prod_mem
/-- Sum of a list of elements in a subfield is in the subfield. -/
protected lemma list_sum_mem {l : list K} : (β x β l, x β s) β l.sum β s := list_sum_mem
/-- Product of a multiset of elements in a subfield is in the subfield. -/
protected lemma multiset_prod_mem (m : multiset K) : (β a β m, a β s) β m.prod β s :=
multiset_prod_mem m
/-- Sum of a multiset of elements in a `subfield` is in the `subfield`. -/
protected lemma multiset_sum_mem (m : multiset K) : (β a β m, a β s) β m.sum β s :=
multiset_sum_mem m
/-- Product of elements of a subfield indexed by a `finset` is in the subfield. -/
protected lemma prod_mem {ΞΉ : Type*} {t : finset ΞΉ} {f : ΞΉ β K} (h : β c β t, f c β s) :
β i in t, f i β s :=
prod_mem h
/-- Sum of elements in a `subfield` indexed by a `finset` is in the `subfield`. -/
protected lemma sum_mem {ΞΉ : Type*} {t : finset ΞΉ} {f : ΞΉ β K} (h : β c β t, f c β s) :
β i in t, f i β s :=
sum_mem h
protected lemma pow_mem {x : K} (hx : x β s) (n : β) : x^n β s := pow_mem hx n
protected lemma zsmul_mem {x : K} (hx : x β s) (n : β€) : n β’ x β s := zsmul_mem hx n
protected lemma coe_int_mem (n : β€) : (n : K) β s := coe_int_mem s n
lemma zpow_mem {x : K} (hx : x β s) (n : β€) : x^n β s :=
begin
cases n,
{ simpa using s.pow_mem hx n },
{ simpa [pow_succ] using s.inv_mem (s.mul_mem hx (s.pow_mem hx n)) },
end
instance : ring s := s.to_subring.to_ring
instance : has_div s := β¨Ξ» x y, β¨x / y, s.div_mem x.2 y.2β©β©
instance : has_inv s := β¨Ξ» x, β¨xβ»ΒΉ, s.inv_mem x.2β©β©
instance : has_pow s β€ := β¨Ξ» x z, β¨x ^ z, s.zpow_mem x.2 zβ©β©
/-- A subfield inherits a field structure -/
instance to_field : field s :=
subtype.coe_injective.field (coe : s β K)
rfl rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl)
(Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _, rfl) (Ξ» _, rfl)
/-- A subfield of a `linear_ordered_field` is a `linear_ordered_field`. -/
instance to_linear_ordered_field {K} [linear_ordered_field K] (s : subfield K) :
linear_ordered_field s :=
subtype.coe_injective.linear_ordered_field coe
rfl rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl)
(Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _, rfl) (Ξ» _, rfl) (Ξ» _, rfl) (Ξ» _ _, rfl)
(Ξ» _ _, rfl)
@[simp, norm_cast] lemma coe_add (x y : s) : (β(x + y) : K) = βx + βy := rfl
@[simp, norm_cast] lemma coe_sub (x y : s) : (β(x - y) : K) = βx - βy := rfl
@[simp, norm_cast] lemma coe_neg (x : s) : (β(-x) : K) = -βx := rfl
@[simp, norm_cast] lemma coe_mul (x y : s) : (β(x * y) : K) = βx * βy := rfl
@[simp, norm_cast] lemma coe_div (x y : s) : (β(x / y) : K) = βx / βy := rfl
@[simp, norm_cast] lemma coe_inv (x : s) : (β(xβ»ΒΉ) : K) = (βx)β»ΒΉ := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : s) : K) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : s) : K) = 1 := rfl
end derived_from_subfield_class
/-- The embedding from a subfield of the field `K` to `K`. -/
def subtype (s : subfield K) : s β+* K :=
{ to_fun := coe,
.. s.to_submonoid.subtype, .. s.to_add_subgroup.subtype }
instance to_algebra : algebra s K := ring_hom.to_algebra s.subtype
@[simp] theorem coe_subtype : βs.subtype = coe := rfl
lemma to_subring.subtype_eq_subtype (F : Type*) [field F] (S : subfield F) :
S.to_subring.subtype = S.subtype := rfl
/-! # Partial order -/
variables (s t)
@[simp] lemma mem_to_submonoid {s : subfield K} {x : K} : x β s.to_submonoid β x β s := iff.rfl
@[simp] lemma coe_to_submonoid : (s.to_submonoid : set K) = s := rfl
@[simp] lemma mem_to_add_subgroup {s : subfield K} {x : K} :
x β s.to_add_subgroup β x β s := iff.rfl
@[simp] lemma coe_to_add_subgroup : (s.to_add_subgroup : set K) = s := rfl
/-! # top -/
/-- The subfield of `K` containing all elements of `K`. -/
instance : has_top (subfield K) :=
β¨{ inv_mem' := Ξ» x _, subring.mem_top x, .. (β€ : subring K)}β©
instance : inhabited (subfield K) := β¨β€β©
@[simp] lemma mem_top (x : K) : x β (β€ : subfield K) := set.mem_univ x
@[simp] lemma coe_top : ((β€ : subfield K) : set K) = set.univ := rfl
/-- The ring equiv between the top element of `subfield K` and `K`. -/
@[simps]
def top_equiv : (β€ : subfield K) β+* K := subsemiring.top_equiv
/-! # comap -/
variables (f : K β+* L)
/-- The preimage of a subfield along a ring homomorphism is a subfield. -/
def comap (s : subfield L) : subfield K :=
{ inv_mem' := Ξ» x hx, show f (xβ»ΒΉ) β s, by { rw map_invβ f, exact s.inv_mem hx },
.. s.to_subring.comap f }
@[simp] lemma coe_comap (s : subfield L) : (s.comap f : set K) = f β»ΒΉ' s := rfl
@[simp]
lemma mem_comap {s : subfield L} {f : K β+* L} {x : K} : x β s.comap f β f x β s := iff.rfl
lemma comap_comap (s : subfield M) (g : L β+* M) (f : K β+* L) :
(s.comap g).comap f = s.comap (g.comp f) :=
rfl
/-! # map -/
/-- The image of a subfield along a ring homomorphism is a subfield. -/
def map (s : subfield K) : subfield L :=
{ inv_mem' := by { rintros _ β¨x, hx, rflβ©, exact β¨xβ»ΒΉ, s.inv_mem hx, map_invβ f xβ© },
.. s.to_subring.map f }
@[simp] lemma coe_map : (s.map f : set L) = f '' s := rfl
@[simp] lemma mem_map {f : K β+* L} {s : subfield K} {y : L} :
y β s.map f β β x β s, f x = y :=
set.mem_image_iff_bex
lemma map_map (g : L β+* M) (f : K β+* L) : (s.map f).map g = s.map (g.comp f) :=
set_like.ext' $ set.image_image _ _ _
lemma map_le_iff_le_comap {f : K β+* L} {s : subfield K} {t : subfield L} :
s.map f β€ t β s β€ t.comap f :=
set.image_subset_iff
lemma gc_map_comap (f : K β+* L) : galois_connection (map f) (comap f) :=
Ξ» S T, map_le_iff_le_comap
end subfield
namespace ring_hom
variables (g : L β+* M) (f : K β+* L)
/-! # range -/
/-- The range of a ring homomorphism, as a subfield of the target. See Note [range copy pattern]. -/
def field_range : subfield L :=
((β€ : subfield K).map f).copy (set.range f) set.image_univ.symm
@[simp] lemma coe_field_range : (f.field_range : set L) = set.range f := rfl
@[simp] lemma mem_field_range {f : K β+* L} {y : L} : y β f.field_range β β x, f x = y := iff.rfl
lemma field_range_eq_map : f.field_range = subfield.map f β€ :=
by { ext, simp }
lemma map_field_range : f.field_range.map g = (g.comp f).field_range :=
by simpa only [field_range_eq_map] using (β€ : subfield K).map_map g f
/-- The range of a morphism of fields is a fintype, if the domain is a fintype.
Note that this instance can cause a diamond with `subtype.fintype` if `L` is also a fintype.-/
instance fintype_field_range [fintype K] [decidable_eq L] (f : K β+* L) : fintype f.field_range :=
set.fintype_range f
end ring_hom
namespace subfield
/-! # inf -/
/-- The inf of two subfields is their intersection. -/
instance : has_inf (subfield K) :=
β¨Ξ» s t,
{ inv_mem' := Ξ» x hx, subring.mem_inf.mpr
β¨s.inv_mem (subring.mem_inf.mp hx).1,
t.inv_mem (subring.mem_inf.mp hx).2β©,
.. s.to_subring β t.to_subring }β©
@[simp] lemma coe_inf (p p' : subfield K) : ((p β p' : subfield K) : set K) = p β© p' := rfl
@[simp] lemma mem_inf {p p' : subfield K} {x : K} : x β p β p' β x β p β§ x β p' := iff.rfl
instance : has_Inf (subfield K) :=
β¨Ξ» S,
{ inv_mem' := begin
rintros x hx,
apply subring.mem_Inf.mpr,
rintro _ β¨p, p_mem, rflβ©,
exact p.inv_mem (subring.mem_Inf.mp hx p.to_subring β¨p, p_mem, rflβ©),
end,
.. Inf (subfield.to_subring '' S) }β©
@[simp, norm_cast] lemma coe_Inf (S : set (subfield K)) :
((Inf S : subfield K) : set K) = β s β S, βs :=
show ((Inf (subfield.to_subring '' S) : subring K) : set K) = β s β S, βs,
begin
ext x,
rw [subring.coe_Inf, set.mem_Inter, set.mem_Inter],
exact β¨Ξ» h s s' β¨s_mem, s'_eqβ©, h s.to_subring _ β¨β¨s, s_mem, rflβ©, s'_eqβ©,
Ξ» h s s' β¨β¨s'', s''_mem, s_eqβ©, (s'_eq : βs = s')β©,
h s'' _ β¨s''_mem, by simp [βs_eq, β s'_eq]β©β©
end
lemma mem_Inf {S : set (subfield K)} {x : K} : x β Inf S β β p β S, x β p :=
subring.mem_Inf.trans
β¨Ξ» h p hp, h p.to_subring β¨p, hp, rflβ©,
Ξ» h p β¨p', hp', p_eqβ©, p_eq βΈ h p' hp'β©
@[simp] lemma Inf_to_subring (s : set (subfield K)) :
(Inf s).to_subring = β¨
t β s, subfield.to_subring t :=
begin
ext x,
rw [mem_to_subring, mem_Inf],
erw subring.mem_Inf,
exact β¨Ξ» h p β¨p', hpβ©, hp βΈ subring.mem_Inf.mpr (Ξ» p β¨hp', hpβ©, hp βΈ h _ hp'),
Ξ» h p hp, h p.to_subring β¨p, subring.ext (Ξ» x,
β¨Ξ» hx, subring.mem_Inf.mp hx _ β¨hp, rflβ©,
Ξ» hx, subring.mem_Inf.mpr (Ξ» p' β¨hp, p'_eqβ©, p'_eq βΈ hx)β©)β©β©
end
lemma is_glb_Inf (S : set (subfield K)) : is_glb S (Inf S) :=
begin
refine is_glb.of_image (Ξ» s t, show (s : set K) β€ t β s β€ t, from set_like.coe_subset_coe) _,
convert is_glb_binfi,
exact coe_Inf _
end
/-- Subfields of a ring form a complete lattice. -/
instance : complete_lattice (subfield K) :=
{ top := β€,
le_top := Ξ» s x hx, trivial,
inf := (β),
inf_le_left := Ξ» s t x, and.left,
inf_le_right := Ξ» s t x, and.right,
le_inf := Ξ» s tβ tβ hβ hβ x hx, β¨hβ hx, hβ hxβ©,
.. complete_lattice_of_Inf (subfield K) is_glb_Inf }
/-! # subfield closure of a subset -/
/-- The `subfield` generated by a set. -/
def closure (s : set K) : subfield K :=
{ carrier := { (x / y) | (x β subring.closure s) (y β subring.closure s) },
zero_mem' := β¨0, subring.zero_mem _, 1, subring.one_mem _, div_one _β©,
one_mem' := β¨1, subring.one_mem _, 1, subring.one_mem _, div_one _β©,
neg_mem' := Ξ» x β¨y, hy, z, hz, x_eqβ©, β¨-y, subring.neg_mem _ hy, z, hz, x_eq βΈ neg_div _ _β©,
inv_mem' := Ξ» x β¨y, hy, z, hz, x_eqβ©, β¨z, hz, y, hy, x_eq βΈ (inv_div _ _).symmβ©,
add_mem' := Ξ» x y x_mem y_mem, begin
obtain β¨nx, hnx, dx, hdx, rflβ© := id x_mem,
obtain β¨ny, hny, dy, hdy, rflβ© := id y_mem,
by_cases hx0 : dx = 0, { rwa [hx0, div_zero, zero_add] },
by_cases hy0 : dy = 0, { rwa [hy0, div_zero, add_zero] },
exact β¨nx * dy + dx * ny,
subring.add_mem _ (subring.mul_mem _ hnx hdy) (subring.mul_mem _ hdx hny),
dx * dy, subring.mul_mem _ hdx hdy,
(div_add_div nx ny hx0 hy0).symmβ©
end,
mul_mem' := Ξ» x y x_mem y_mem, begin
obtain β¨nx, hnx, dx, hdx, rflβ© := id x_mem,
obtain β¨ny, hny, dy, hdy, rflβ© := id y_mem,
exact β¨nx * ny, subring.mul_mem _ hnx hny,
dx * dy, subring.mul_mem _ hdx hdy,
(div_mul_div_comm _ _ _ _).symmβ©
end }
lemma mem_closure_iff {s : set K} {x} :
x β closure s β β (y β subring.closure s) (z β subring.closure s), y / z = x := iff.rfl
lemma subring_closure_le (s : set K) : subring.closure s β€ (closure s).to_subring :=
Ξ» x hx, β¨x, hx, 1, subring.one_mem _, div_one xβ©
/-- The subfield generated by a set includes the set. -/
@[simp] lemma subset_closure {s : set K} : s β closure s :=
set.subset.trans subring.subset_closure (subring_closure_le s)
lemma not_mem_of_not_mem_closure {s : set K} {P : K} (hP : P β closure s) : P β s :=
Ξ» h, hP (subset_closure h)
lemma mem_closure {x : K} {s : set K} : x β closure s β β S : subfield K, s β S β x β S :=
β¨Ξ» β¨y, hy, z, hz, x_eqβ© t le, x_eq βΈ
t.div_mem
(subring.mem_closure.mp hy t.to_subring le)
(subring.mem_closure.mp hz t.to_subring le),
Ξ» h, h (closure s) subset_closureβ©
/-- A subfield `t` includes `closure s` if and only if it includes `s`. -/
@[simp]
lemma closure_le {s : set K} {t : subfield K} : closure s β€ t β s β t :=
β¨set.subset.trans subset_closure, Ξ» h x hx, mem_closure.mp hx t hβ©
/-- Subfield closure of a set is monotone in its argument: if `s β t`,
then `closure s β€ closure t`. -/
lemma closure_mono β¦s t : set Kβ¦ (h : s β t) : closure s β€ closure t :=
closure_le.2 $ set.subset.trans h subset_closure
lemma closure_eq_of_le {s : set K} {t : subfield K} (hβ : s β t) (hβ : t β€ closure s) :
closure s = t :=
le_antisymm (closure_le.2 hβ) hβ
/-- An induction principle for closure membership. If `p` holds for `1`, and all elements
of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all
elements of the closure of `s`. -/
@[elab_as_eliminator]
lemma closure_induction {s : set K} {p : K β Prop} {x} (h : x β closure s)
(Hs : β x β s, p x) (H1 : p 1)
(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 :=
(@closure_le _ _ _ β¨p, Hmul, H1,
Hadd, @add_neg_self K _ 1 βΈ Hadd _ _ H1 (Hneg _ H1), Hneg, Hinvβ©).2 Hs h
variable (K)
/-- `closure` forms a Galois insertion with the coercion to set. -/
protected def gi : galois_insertion (@closure K _) coe :=
{ choice := Ξ» s _, closure s,
gc := Ξ» s t, closure_le,
le_l_u := Ξ» s, subset_closure,
choice_eq := Ξ» s h, rfl }
variable {K}
/-- Closure of a subfield `S` equals `S`. -/
lemma closure_eq (s : subfield K) : closure (s : set K) = s := (subfield.gi K).l_u_eq s
@[simp] lemma closure_empty : closure (β
: set K) = β₯ := (subfield.gi K).gc.l_bot
@[simp] lemma closure_univ : closure (set.univ : set K) = β€ := @coe_top K _ βΈ closure_eq β€
lemma closure_union (s t : set K) : closure (s βͺ t) = closure s β closure t :=
(subfield.gi K).gc.l_sup
lemma closure_Union {ΞΉ} (s : ΞΉ β set K) : closure (β i, s i) = β¨ i, closure (s i) :=
(subfield.gi K).gc.l_supr
lemma closure_sUnion (s : set (set K)) : closure (ββ s) = β¨ t β s, closure t :=
(subfield.gi K).gc.l_Sup
lemma map_sup (s t : subfield K) (f : K β+* L) : (s β t).map f = s.map f β t.map f :=
(gc_map_comap f).l_sup
lemma map_supr {ΞΉ : Sort*} (f : K β+* L) (s : ΞΉ β subfield K) :
(supr s).map f = β¨ i, (s i).map f :=
(gc_map_comap f).l_supr
lemma comap_inf (s t : subfield L) (f : K β+* L) : (s β t).comap f = s.comap f β t.comap f :=
(gc_map_comap f).u_inf
lemma comap_infi {ΞΉ : Sort*} (f : K β+* L) (s : ΞΉ β subfield L) :
(infi s).comap f = β¨
i, (s i).comap f :=
(gc_map_comap f).u_infi
@[simp] lemma map_bot (f : K β+* L) : (β₯ : subfield K).map f = β₯ :=
(gc_map_comap f).l_bot
@[simp] lemma comap_top (f : K β+* L) : (β€ : subfield L).comap f = β€ :=
(gc_map_comap f).u_top
/-- The underlying set of a non-empty directed Sup of subfields is just a union of the subfields.
Note that this fails without the directedness assumption (the union of two subfields is
typically not a subfield) -/
lemma mem_supr_of_directed {ΞΉ} [hΞΉ : nonempty ΞΉ] {S : ΞΉ β subfield K} (hS : directed (β€) S)
{x : K} : x β (β¨ i, S i) β β i, x β S i :=
begin
refine β¨_, Ξ» β¨i, hiβ©, (set_like.le_def.1 $ le_supr S i) hiβ©,
suffices : x β closure (β i, (S i : set K)) β β i, x β S i,
by simpa only [closure_Union, closure_eq],
refine Ξ» hx, closure_induction hx (Ξ» x, set.mem_Union.mp) _ _ _ _ _,
{ exact hΞΉ.elim (Ξ» i, β¨i, (S i).one_memβ©) },
{ rintros x y β¨i, hiβ© β¨j, hjβ©,
obtain β¨k, hki, hkjβ© := hS i j,
exact β¨k, (S k).add_mem (hki hi) (hkj hj)β© },
{ rintros x β¨i, hiβ©,
exact β¨i, (S i).neg_mem hiβ© },
{ rintros x β¨i, hiβ©,
exact β¨i, (S i).inv_mem hiβ© },
{ rintros x y β¨i, hiβ© β¨j, hjβ©,
obtain β¨k, hki, hkjβ© := hS i j,
exact β¨k, (S k).mul_mem (hki hi) (hkj hj)β© }
end
lemma coe_supr_of_directed {ΞΉ} [hΞΉ : nonempty ΞΉ] {S : ΞΉ β subfield K} (hS : directed (β€) S) :
((β¨ i, S i : subfield K) : set K) = β i, β(S i) :=
set.ext $ Ξ» x, by simp [mem_supr_of_directed hS]
lemma mem_Sup_of_directed_on {S : set (subfield K)} (Sne : S.nonempty)
(hS : directed_on (β€) S) {x : K} :
x β Sup S β β s β S, x β s :=
begin
haveI : nonempty S := Sne.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk]
end
lemma coe_Sup_of_directed_on {S : set (subfield K)} (Sne : S.nonempty) (hS : directed_on (β€) S) :
(β(Sup S) : set K) = β s β S, βs :=
set.ext $ Ξ» x, by simp [mem_Sup_of_directed_on Sne hS]
end subfield
namespace ring_hom
variables {s : subfield K}
open subfield
/-- Restriction of a ring homomorphism to its range interpreted as a subfield. -/
def range_restrict_field (f : K β+* L) : K β+* f.field_range :=
f.srange_restrict
@[simp] lemma coe_range_restrict_field (f : K β+* L) (x : K) :
(f.range_restrict_field x : L) = f x := rfl
/-- The subfield of elements `x : R` such that `f x = g x`, i.e.,
the equalizer of f and g as a subfield of R -/
def eq_locus_field (f g : K β+* L) : subfield K :=
{ inv_mem' := Ξ» x (hx : f x = g x), show f xβ»ΒΉ = g xβ»ΒΉ, by rw [map_invβ f, map_invβ g, hx],
carrier := {x | f x = g x}, .. (f : K β+* L).eq_locus g }
/-- If two ring homomorphisms are equal on a set, then they are equal on its subfield closure. -/
lemma eq_on_field_closure {f g : K β+* L} {s : set K} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s β€ f.eq_locus_field g, from closure_le.2 h
lemma eq_of_eq_on_subfield_top {f g : K β+* L} (h : set.eq_on f g (β€ : subfield K)) :
f = g :=
ext $ Ξ» x, h trivial
lemma eq_of_eq_on_of_field_closure_eq_top {s : set K} (hs : closure s = β€) {f g : K β+* L}
(h : s.eq_on f g) : f = g :=
eq_of_eq_on_subfield_top $ hs βΈ eq_on_field_closure h
lemma field_closure_preimage_le (f : K β+* L) (s : set L) :
closure (f β»ΒΉ' s) β€ (closure s).comap f :=
closure_le.2 $ Ξ» x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx
/-- The image under a ring homomorphism of the subfield generated by a set equals
the subfield generated by the image of the set. -/
lemma map_field_closure (f : K β+* L) (s : set K) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _)
(field_closure_preimage_le _ _))
(closure_le.2 $ set.image_subset _ subset_closure)
end ring_hom
namespace subfield
open ring_hom
/-- The ring homomorphism associated to an inclusion of subfields. -/
def inclusion {S T : subfield K} (h : S β€ T) : S β+* T :=
S.subtype.cod_restrict _ (Ξ» x, h x.2)
@[simp] lemma field_range_subtype (s : subfield K) : s.subtype.field_range = s :=
set_like.ext' $ (coe_srange _).trans subtype.range_coe
end subfield
namespace ring_equiv
variables {s t : subfield K}
/-- Makes the identity isomorphism from a proof two subfields of a multiplicative
monoid are equal. -/
def subfield_congr (h : s = t) : s β+* t :=
{ map_mul' := Ξ» _ _, rfl, map_add' := Ξ» _ _, rfl, ..equiv.set_congr $ set_like.ext'_iff.1 h }
end ring_equiv
namespace subfield
variables {s : set K}
lemma closure_preimage_le (f : K β+* L) (s : set L) :
closure (f β»ΒΉ' s) β€ (closure s).comap f :=
closure_le.2 $ Ξ» x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx
end subfield
|
55efa6060036121cd5196f0252f84deef49ac60a | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /docs/tutorial/category_theory/intro.lean | 4687fb0be94bb3776d09d1276929a6a1b2d7139b | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 9,135 | lean | import category_theory.functor_category -- this transitively imports
-- category_theory.category
-- category_theory.functor
-- category_theory.natural_transformation
/-!
# An introduction to category theory in Lean
This is an introduction to the basic usage of category theory (in the mathematical sense) in Lean.
We cover how the basic theory of categories, functors and natural transformations is set up in Lean.
Most of the below is not hard to read off from the files `category_theory/category.lean`,
`category_theory/functor.lean` and `category_theory/natural_transformation.lean`.
## Overview
A category is a collection of objects, and a collection of morphisms (also known as arrows) between
the objects. The objects and morphisms have some extra structure and satisfy some axioms -- see the
[definition on Wikipedia](https://en.wikipedia.org/wiki/Category_%28mathematics%29#Definition) for
details.
One important thing to note is that a morphism in an abstract category may not be an actual function
between two types. In particular, there is new notation `βΆ` , typed as `\h` or `\hom` in VS Code,
for a morphism. Nevertheless, in most of the "concrete" categories like `Top` and `Ab`, it is still
possible to write `f x` when `x : X` and `f : X βΆ Y` is a morphism, as there is an automatic
coercion from morphisms to functions. (If the coercion doesn't fire automatically, sometimes it is
necessary to write `(f : X β Y) x`.)
In some fonts the `βΆ` morphism arrow can be virtually indistinguishable from the standard function
arrow `β` . You may want to install the [Deja Vu Sans Mono](https://dejavu-fonts.github.io/) and put
that at the beginning of the `Font Family` setting in VSCode, to get a nice readable font with
excellent unicode coverage.
Another point of confusion can be universe issues. Following Lean's conventions for universe
polymorphism, the objects of a category might live in one universe `u` and the morphisms in another
universe `v`. Note that in many categories showing up in "set-theoretic mathematics", the morphisms
between two objects often form a set, but the objects themselves may or may not form a set. In Lean
this corresponds to the two possibilities `u=v` and `u=v+1`, known as `small_category` and
`large_category` respectively. In order to avoid proving the same statements for both small and
large categories, we usually stick to the general polymorphic situation with `u` and `v` independent
universes, and we do this below.
## Getting started with categories
The structure of a category on a type `C` in Lean is done using typeclasses; terms of `C` then
correspond to objects in the category. The convention in the category theory library is to use
universes prefixed with `u` (e.g. `u`, `uβ`, `uβ`) for the objects, and universes prefixed with `v`
for morphisms. Thus we have `C : Type u`, and if `X : C` and `Y : C` then morphisms `X βΆ Y : Type v`
(note the non-standard arrow).
We set this up as follows:
-/
open category_theory
section category
variables (C : Type*) [category C]
variables {W X Y Z : C}
variables (f : W βΆ X) (g : X βΆ Y) (h : Y βΆ Z)
/-!
This says "let `C` be a category, let `W`, `X`, `Y`, `Z` be objects of `C`, and let `f : W βΆ X`, `g
: X βΆ Y` and `h : Y βΆ Z` be morphisms in `C` (with the specified source and targets)".
Note that we sometimes need to explicitly tell Lean the universe that the morphisms live in,
by writing `category.{v} C`, because Lean cannot guess this from `C` alone.
However just writing `category C` is often fine: this allows a "free" universe level.
The order in which universes are introduced at the top of the file matters:
we put the universes for morphisms first (typically `v`, `vβ` and so on),
and then universes for objects (typically `u`, `uβ` and so on).
This ensures that in any new definition we make the universe variables for morphisms come first,
so that they can be explicitly specified while still allowing the universe levels of the
objects to be inferred automatically.
## Basic notation
In categories one has morphisms between objects, such as the identity morphism from an object to
itself. One can compose morphisms, and there are standard facts about the composition of a morphism
with the identity morphism, and the fact that morphism composition is associative. In Lean all of
this looks like the following:
-/
-- The identity morphism from `X` to `X` (remember that this is the `\h` arrow):
example : X βΆ X := π X -- type `π` as `\bb1`
-- Function composition `h β g`, a morphism from `X` to `Z`:
example : X βΆ Z := g β« h
/-
Note in particular the order! The "maps on the right" convention was chosen; `g β« h` means "`g` then
`h`". Type `β«` with `\gg` in VS Code. Here are the theorems which ensure that we have a category.
-/
open category_theory.category
example : π X β« g = g := id_comp g
example : g β« π Y = g := comp_id g
example : (f β« g) β« h = f β« (g β« h) := assoc f g h
example : (f β« g) β« h = f β« g β« h := assoc f g h -- note \gg is right associative
-- All four examples above can also be proved with `simp`.
-- Monomorphisms and epimorphisms are predicates on morphisms and are implemented as typeclasses.
variables (f' : W βΆ X) (h' : Y βΆ Z)
example [mono g] : f β« g = f' β« g β f = f' := mono.right_cancellation f f'
example [epi g] : g β« h = g β« h' β h = h' := epi.left_cancellation h h'
end category -- end of section
/-!
## Getting started with functors
A functor is a map between categories. It is implemented as a structure. The notation for a functor
from `C` to `D` is `C β₯€ D`. Type `\func` in VS Code for the symbol. Here we demonstrate how to
evaluate functors on objects and on morphisms, how to show functors preserve the identity morphism
and composition of morphisms, how to compose functors, and show the notation `π` for the identity
functor.
-/
section functor
variables (C : Type*) [category C]
variables (D : Type*) [category D]
variables (E : Type*) [category E]
variables {X Y Z : C} (f : X βΆ Y) (g : Y βΆ Z)
-- functors
variables (F : C β₯€ D) (G : D β₯€ E)
example : D := F.obj X -- functor F on objects
example : F.obj Y βΆ F.obj Z := F.map g -- functor F on morphisms
-- A functor sends identity objects to identity objects
example : F.map (π X) = π (F.obj X) := F.map_id X
-- and preserves compositions
example : F.map (f β« g) = (F.map f) β« (F.map g) := F.map_comp f g
-- The identity functor is `π`, which you can write as `\sb1`.
example : C β₯€ C := π C
-- The identity functor is (definitionally) the identity on objects and morphisms:
example : (π C).obj X = X := category_theory.functor.id_obj X
example : (π C).map f = f := category_theory.functor.id_map f
-- Composition of functors; note order:
example : C β₯€ E := F β G -- typeset with `\ggg`
-- Composition of the identity either way does nothing:
example : F β π D = F := F.comp_id
example : π C β F = F := F.id_comp
-- Composition of functors definitionally does the right thing on objects and morphisms:
example : (F β G).obj X = G.obj (F.obj X) := F.comp_obj G X -- or rfl
example : (F β G).map f = G.map (F.map f) := rfl -- or F.comp_map G X Y f
end functor -- end of section
/-!
One can also check that associativity of composition of functors is definitionally true,
although we've observed that relying on this can result in slow proofs. (One should
rather use the natural isomorphisms provided in `src/category_theory/whiskering.lean`.)
## Getting started with natural transformations
A natural transformation is a morphism between functors. If `F` and `G` are functors from `C` to `D`
then a natural transformation is a map `F X βΆ G X` for each object `X : C` plus the theorem that if
`f : X βΆ Y` is a morphism then the two routes from `F X` to `G Y` are the same. One might imagine
that this is now another layer of notation, but fortunately the `category_theory.functor_category`
import gives the type of functors from `C` to `D` a category structure, which means that we can just
use morphism notation for natural transformations.
-/
section nat_trans
variables {C : Type*} [category C] {D : Type*} [category D]
variables (X Y : C)
variable (f : X βΆ Y)
variables (F G H : C β₯€ D)
variables (Ξ± : F βΆ G) (Ξ² : G βΆ H) -- natural transformations (note it's the usual `\hom` arrow here)
-- Composition of natural transformations is just composition of morphisms:
example : F βΆ H := Ξ± β« Ξ²
-- Applying natural transformation to an object:
example (X : C) : F.obj X βΆ G.obj X := Ξ±.app X
/- The diagram coming from g and Ξ±
F(f)
F X ---> F Y
| |
|Ξ±(X) |Ξ±(Y)
v v
G X ---> G Y
G(f)
commutes.
-/
example : F.map f β« Ξ±.app Y = (Ξ±.app X) β« G.map f := Ξ±.naturality f
end nat_trans -- section
/-!
## What next?
There are several lean files in the [category theory docs directory of
mathlib](https://github.com/leanprover-community/mathlib/tree/master/docs/tutorial/category_theory)
which give further examples of using the category theory library in Lean.
-/
|
8d29f50751867ebf4c8fbe1a695d6f2bcb861a9e | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/number_theory/cyclotomic/basic.lean | f323dcc6e0948852b87139c83adbccbbd2d2dcf5 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 27,260 | lean | /-
Copyright (c) 2021 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
-/
import ring_theory.polynomial.cyclotomic.basic
import number_theory.number_field
import algebra.char_p.algebra
import field_theory.galois
/-!
# Cyclotomic extensions
Let `A` and `B` be commutative rings with `algebra A B`. For `S : set β+`, we define a class
`is_cyclotomic_extension S A B` expressing the fact that `B` is obtained from `A` by adding `n`-th
primitive roots of unity, for all `n β S`.
## Main definitions
* `is_cyclotomic_extension S A B` : means that `B` is obtained from `A` by adding `n`-th primitive
roots of unity, for all `n β S`.
* `cyclotomic_field`: given `n : β+` and a field `K`, we define `cyclotomic n K` as the splitting
field of `cyclotomic n K`. If `n` is nonzero in `K`, it has the instance
`is_cyclotomic_extension {n} K (cyclotomic_field n K)`.
* `cyclotomic_ring` : if `A` is a domain with fraction field `K` and `n : β+`, we define
`cyclotomic_ring n A K` as the `A`-subalgebra of `cyclotomic_field n K` generated by the roots of
`X ^ n - 1`. If `n` is nonzero in `A`, it has the instance
`is_cyclotomic_extension {n} A (cyclotomic_ring n A K)`.
## Main results
* `is_cyclotomic_extension.trans` : if `is_cyclotomic_extension S A B` and
`is_cyclotomic_extension T B C`, then `is_cyclotomic_extension (S βͺ T) A C` if
`no_zero_smul_divisors B C` and `nontrivial C`.
* `is_cyclotomic_extension.union_right` : given `is_cyclotomic_extension (S βͺ T) A B`, then
`is_cyclotomic_extension T (adjoin A { b : B | β a : β+, a β S β§ b ^ (a : β) = 1 }) B`.
* `is_cyclotomic_extension.union_right` : given `is_cyclotomic_extension T A B` and `S β T`, then
`is_cyclotomic_extension S A (adjoin A { b : B | β a : β+, a β S β§ b ^ (a : β) = 1 })`.
* `is_cyclotomic_extension.finite` : if `S` is finite and `is_cyclotomic_extension S A B`, then
`B` is a finite `A`-algebra.
* `is_cyclotomic_extension.number_field` : a finite cyclotomic extension of a number field is a
number field.
* `is_cyclotomic_extension.splitting_field_X_pow_sub_one` : if `is_cyclotomic_extension {n} K L`,
then `L` is the splitting field of `X ^ n - 1`.
* `is_cyclotomic_extension.splitting_field_cyclotomic` : if `is_cyclotomic_extension {n} K L`,
then `L` is the splitting field of `cyclotomic n K`.
## Implementation details
Our definition of `is_cyclotomic_extension` is very general, to allow rings of any characteristic
and infinite extensions, but it will mainly be used in the case `S = {n}` and for integral domains.
All results are in the `is_cyclotomic_extension` namespace.
Note that some results, for example `is_cyclotomic_extension.trans`,
`is_cyclotomic_extension.finite`, `is_cyclotomic_extension.number_field`,
`is_cyclotomic_extension.finite_dimensional`, `is_cyclotomic_extension.is_galois` and
`cyclotomic_field.algebra_base` are lemmas, but they can be made local instances. Some of them are
included in the `cyclotomic` locale.
-/
open polynomial algebra finite_dimensional module set
open_locale big_operators
universes u v w z
variables (n : β+) (S T : set β+) (A : Type u) (B : Type v) (K : Type w) (L : Type z)
variables [comm_ring A] [comm_ring B] [algebra A B]
variables [field K] [field L] [algebra K L]
noncomputable theory
/-- Given an `A`-algebra `B` and `S : set β+`, we define `is_cyclotomic_extension S A B` requiring
that there is a `a`-th primitive root of unity in `B` for all `a β S` and that `B` is generated
over `A` by the roots of `X ^ n - 1`. -/
@[mk_iff] class is_cyclotomic_extension : Prop :=
(exists_prim_root {a : β+} (ha : a β S) : β r : B, is_primitive_root r a)
(adjoin_roots : β (x : B), x β adjoin A { b : B | β a : β+, a β S β§ b ^ (a : β) = 1 })
namespace is_cyclotomic_extension
section basic
/-- A reformulation of `is_cyclotomic_extension` that uses `β€`. -/
lemma iff_adjoin_eq_top : is_cyclotomic_extension S A B β
(β (a : β+), a β S β β r : B, is_primitive_root r a) β§
(adjoin A { b : B | β a : β+, a β S β§ b ^ (a : β) = 1 } = β€) :=
β¨Ξ» h, β¨h.exists_prim_root, algebra.eq_top_iff.2 h.adjoin_rootsβ©,
Ξ» h, β¨h.1, algebra.eq_top_iff.1 h.2β©β©
/-- A reformulation of `is_cyclotomic_extension` in the case `S` is a singleton. -/
lemma iff_singleton : is_cyclotomic_extension {n} A B β
(β r : B, is_primitive_root r n) β§
(β x, x β adjoin A { b : B | b ^ (n : β) = 1 }) :=
by simp [is_cyclotomic_extension_iff]
/-- If `is_cyclotomic_extension β
A B`, then the image of `A` in `B` equals `B`. -/
lemma empty [h : is_cyclotomic_extension β
A B] : (β₯ : subalgebra A B) = β€ :=
by simpa [algebra.eq_top_iff, is_cyclotomic_extension_iff] using h
/-- If `is_cyclotomic_extension {1} A B`, then the image of `A` in `B` equals `B`. -/
lemma singleton_one [h : is_cyclotomic_extension {1} A B] : (β₯ : subalgebra A B) = β€ :=
algebra.eq_top_iff.2 (Ξ» x, by simpa [adjoin_singleton_one]
using ((is_cyclotomic_extension_iff _ _ _).1 h).2 x)
/-- Transitivity of cyclotomic extensions. -/
lemma trans (C : Type w) [comm_ring C] [nontrivial C] [algebra A C] [algebra B C]
[is_scalar_tower A B C] [hS : is_cyclotomic_extension S A B]
[hT : is_cyclotomic_extension T B C] [no_zero_smul_divisors B C] :
is_cyclotomic_extension (S βͺ T) A C :=
begin
refine β¨Ξ» n hn, _, Ξ» x, _β©,
{ cases hn,
{ obtain β¨b, hbβ© := ((is_cyclotomic_extension_iff _ _ _).1 hS).1 hn,
refine β¨algebra_map B C b, _β©,
exact hb.map_of_injective (no_zero_smul_divisors.algebra_map_injective B C) },
{ exact ((is_cyclotomic_extension_iff _ _ _).1 hT).1 hn } },
{ refine adjoin_induction (((is_cyclotomic_extension_iff _ _ _).1 hT).2 x) (Ξ» c β¨n, hnβ©,
subset_adjoin β¨n, or.inr hn.1, hn.2β©) (Ξ» b, _) (Ξ» x y hx hy, subalgebra.add_mem _ hx hy)
(Ξ» x y hx hy, subalgebra.mul_mem _ hx hy),
{ let f := is_scalar_tower.to_alg_hom A B C,
have hb : f b β (adjoin A { b : B | β (a : β+), a β S β§ b ^ (a : β) = 1 }).map f :=
β¨b, ((is_cyclotomic_extension_iff _ _ _).1 hS).2 b, rflβ©,
rw [is_scalar_tower.to_alg_hom_apply, β adjoin_image] at hb,
refine adjoin_mono (Ξ» y hy, _) hb,
obtain β¨bβ, β¨β¨n, hnβ©, hββ©β© := hy,
exact β¨n, β¨mem_union_left T hn.1, by rw [β hβ, β alg_hom.map_pow, hn.2, alg_hom.map_one]β©β© } }
end
@[nontriviality] lemma subsingleton_iff [subsingleton B] :
is_cyclotomic_extension S A B β S = {} β¨ S = {1} :=
begin
split,
{ rintro β¨hprim, -β©,
rw βsubset_singleton_iff_eq,
intros t ht,
obtain β¨ΞΆ, hΞΆβ© := hprim ht,
rw [mem_singleton_iff, βpnat.coe_eq_one_iff],
exact_mod_cast hΞΆ.unique (is_primitive_root.of_subsingleton ΞΆ) },
{ rintro (rfl|rfl),
{ refine β¨Ξ» _ h, h.elim, Ξ» x, by convert (mem_top : x β β€)β© },
{ rw iff_singleton,
refine β¨β¨0, is_primitive_root.of_subsingleton 0β©, Ξ» x, by convert (mem_top : x β β€)β© } }
end
/-- If `B` is a cyclotomic extension of `A` given by roots of unity of order in `S βͺ T`, then `B`
is a cyclotomic extension of `adjoin A { b : B | β a : β+, a β S β§ b ^ (a : β) = 1 } ` given by
roots of unity of order in `T`. -/
lemma union_right [h : is_cyclotomic_extension (S βͺ T) A B] :
is_cyclotomic_extension T (adjoin A { b : B | β a : β+, a β S β§ b ^ (a : β) = 1 }) B :=
begin
have : { b : B | β (n : β+), n β S βͺ T β§ b ^ (n : β) = 1 } =
{ b : B | β (n : β+), n β S β§ b ^ (n : β) = 1 } βͺ
{ b : B | β (n : β+), n β T β§ b ^ (n : β) = 1 },
{ refine le_antisymm (Ξ» x hx, _) (Ξ» x hx, _),
{ rcases hx with β¨n, hnβ | hnβ, hnpowβ©,
{ left, exact β¨n, hnβ, hnpowβ© },
{ right, exact β¨n, hnβ, hnpowβ© } },
{ rcases hx with β¨n, hnβ© | β¨n, hnβ©,
{ exact β¨n, or.inl hn.1, hn.2β© },
{ exact β¨n, or.inr hn.1, hn.2β© } } },
refine β¨Ξ» n hn, ((is_cyclotomic_extension_iff _ _ _).1 h).1 (mem_union_right S hn), Ξ» b, _β©,
replace h := ((is_cyclotomic_extension_iff _ _ _).1 h).2 b,
rwa [this, adjoin_union_eq_adjoin_adjoin, subalgebra.mem_restrict_scalars] at h
end
/-- If `B` is a cyclotomic extension of `A` given by roots of unity of order in `T` and `S β T`,
then `adjoin A { b : B | β a : β+, a β S β§ b ^ (a : β) = 1 }` is a cyclotomic extension of `B`
given by roots of unity of order in `S`. -/
lemma union_left [h : is_cyclotomic_extension T A B] (hS : S β T) :
is_cyclotomic_extension S A (adjoin A { b : B | β a : β+, a β S β§ b ^ (a : β) = 1 }) :=
begin
refine β¨Ξ» n hn, _, Ξ» b, _β©,
{ obtain β¨b, hbβ© := ((is_cyclotomic_extension_iff _ _ _).1 h).1 (hS hn),
refine β¨β¨b, subset_adjoin β¨n, hn, hb.pow_eq_oneβ©β©, _β©,
rwa [β is_primitive_root.coe_submonoid_class_iff, subtype.coe_mk] },
{ convert mem_top,
rw [β adjoin_adjoin_coe_preimage, preimage_set_of_eq],
norm_cast }
end
@[protected]
lemma ne_zero [h : is_cyclotomic_extension {n} A B] [is_domain B] : ne_zero ((n : β) : B) :=
begin
obtain β¨β¨r, hrβ©, -β© := (iff_singleton n A B).1 h,
exact hr.ne_zero'
end
@[protected]
lemma ne_zero' [is_cyclotomic_extension {n} A B] [is_domain B] : ne_zero ((n : β) : A) :=
begin
apply ne_zero.nat_of_ne_zero (algebra_map A B),
exact ne_zero n A B,
end
end basic
section fintype
lemma finite_of_singleton [is_domain B] [h : is_cyclotomic_extension {n} A B] : finite A B :=
begin
classical,
rw [module.finite_def, β top_to_submodule, β ((iff_adjoin_eq_top _ _ _).1 h).2],
refine fg_adjoin_of_finite _ (Ξ» b hb, _),
{ simp only [mem_singleton_iff, exists_eq_left],
have : {b : B | b ^ (n : β) = 1} = (nth_roots n (1 : B)).to_finset :=
set.ext (Ξ» x, β¨Ξ» h, by simpa using h, Ξ» h, by simpa using hβ©),
rw [this],
exact (nth_roots βn 1).to_finset.finite_to_set },
{ simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq] at hb,
refine β¨X ^ (n : β) - 1, β¨monic_X_pow_sub_C _ n.pos.ne.symm, by simp [hb]β©β© }
end
/-- If `S` is finite and `is_cyclotomic_extension S A B`, then `B` is a finite `A`-algebra. -/
lemma finite [is_domain B] [hβ : fintype S] [hβ : is_cyclotomic_extension S A B] : finite A B :=
begin
unfreezingI {revert hβ A B},
refine set.finite.induction_on (set.finite.intro hβ) (Ξ» A B, _) (Ξ» n S hn hS H A B, _),
{ introsI _ _ _ _ _,
refine module.finite_def.2 β¨({1} : finset B), _β©,
simp [β top_to_submodule, β empty, to_submodule_bot] },
{ introsI _ _ _ _ h,
haveI : is_cyclotomic_extension S A (adjoin A { b : B | β (n : β+),
n β S β§ b ^ (n : β) = 1 }) := union_left _ (insert n S) _ _ (subset_insert n S),
haveI := H A (adjoin A { b : B | β (n : β+), n β S β§ b ^ (n : β) = 1 }),
haveI : finite (adjoin A { b : B | β (n : β+), n β S β§ b ^ (n : β) = 1 }) B,
{ rw [β union_singleton] at h,
letI := @union_right S {n} A B _ _ _ h,
exact finite_of_singleton n _ _ },
exact finite.trans (adjoin A { b : B | β (n : β+), n β S β§ b ^ (n : β) = 1 }) _ }
end
/-- A cyclotomic finite extension of a number field is a number field. -/
lemma number_field [h : number_field K] [fintype S] [is_cyclotomic_extension S K L] :
number_field L :=
{ to_char_zero := char_zero_of_injective_algebra_map (algebra_map K L).injective,
to_finite_dimensional := @finite.trans _ K L _ _ _ _
(@algebra_rat L _ (char_zero_of_injective_algebra_map (algebra_map K L).injective)) _ _
h.to_finite_dimensional (finite S K L) }
localized "attribute [instance] is_cyclotomic_extension.number_field" in cyclotomic
/-- A finite cyclotomic extension of an integral noetherian domain is integral -/
lemma integral [is_domain B] [is_noetherian_ring A] [fintype S] [is_cyclotomic_extension S A B] :
algebra.is_integral A B :=
is_integral_of_noetherian $ is_noetherian_of_fg_of_noetherian' $ (finite S A B).out
/-- If `S` is finite and `is_cyclotomic_extension S K A`, then `finite_dimensional K A`. -/
lemma finite_dimensional (C : Type z) [fintype S] [comm_ring C] [algebra K C] [is_domain C]
[is_cyclotomic_extension S K C] : finite_dimensional K C :=
finite S K C
localized "attribute [instance] is_cyclotomic_extension.finite_dimensional" in cyclotomic
end fintype
section
variables {A B}
lemma adjoin_roots_cyclotomic_eq_adjoin_nth_roots [decidable_eq B] [is_domain B] {ΞΆ : B}
{n : β+} (hΞΆ : is_primitive_root ΞΆ n) :
adjoin A β((map (algebra_map A B) (cyclotomic n A)).roots.to_finset) =
adjoin A {b : B | β (a : β+), a β ({n} : set β+) β§ b ^ (a : β) = 1} :=
begin
simp only [mem_singleton_iff, exists_eq_left, map_cyclotomic],
refine le_antisymm (adjoin_mono (Ξ» x hx, _)) (adjoin_le (Ξ» x hx, _)),
{ simp only [multiset.mem_to_finset, finset.mem_coe,
map_cyclotomic, mem_roots (cyclotomic_ne_zero n B)] at hx,
simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq],
rw is_root_of_unity_iff n.pos,
exact β¨n, nat.mem_divisors_self n n.ne_zero, hxβ© },
{ simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq] at hx,
obtain β¨i, hin, rflβ© := hΞΆ.eq_pow_of_pow_eq_one hx n.pos,
refine set_like.mem_coe.2 (subalgebra.pow_mem _ (subset_adjoin _) _),
rwa [finset.mem_coe, multiset.mem_to_finset, mem_roots $ cyclotomic_ne_zero n B],
exact hΞΆ.is_root_cyclotomic n.pos }
end
lemma adjoin_roots_cyclotomic_eq_adjoin_root_cyclotomic {n : β+} [decidable_eq B] [is_domain B]
{ΞΆ : B} (hΞΆ : is_primitive_root ΞΆ n) :
adjoin A (((map (algebra_map A B) (cyclotomic n A)).roots.to_finset) : set B) = adjoin A ({ΞΆ}) :=
begin
refine le_antisymm (adjoin_le (Ξ» x hx, _)) (adjoin_mono (Ξ» x hx, _)),
{ suffices hx : x ^ βn = 1,
obtain β¨i, hin, rflβ© := hΞΆ.eq_pow_of_pow_eq_one hx n.pos,
exact set_like.mem_coe.2 (subalgebra.pow_mem _ (subset_adjoin $ mem_singleton ΞΆ) _),
rw is_root_of_unity_iff n.pos,
refine β¨n, nat.mem_divisors_self n n.ne_zero, _β©,
rwa [finset.mem_coe, multiset.mem_to_finset,
map_cyclotomic, mem_roots $ cyclotomic_ne_zero n B] at hx },
{ simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq] at hx,
simpa only [hx, multiset.mem_to_finset, finset.mem_coe, map_cyclotomic,
mem_roots (cyclotomic_ne_zero n B)] using hΞΆ.is_root_cyclotomic n.pos }
end
lemma adjoin_primitive_root_eq_top {n : β+} [is_domain B] [h : is_cyclotomic_extension {n} A B]
{ΞΆ : B} (hΞΆ : is_primitive_root ΞΆ n) : adjoin A ({ΞΆ} : set B) = β€ :=
begin
classical,
rw βadjoin_roots_cyclotomic_eq_adjoin_root_cyclotomic hΞΆ,
rw adjoin_roots_cyclotomic_eq_adjoin_nth_roots hΞΆ,
exact ((iff_adjoin_eq_top {n} A B).mp h).2,
end
variable (A)
lemma _root_.is_primitive_root.adjoin_is_cyclotomic_extension {ΞΆ : B} {n : β+}
(h : is_primitive_root ΞΆ n) : is_cyclotomic_extension {n} A (adjoin A ({ΞΆ} : set B)) :=
{ exists_prim_root := Ξ» i hi,
begin
rw [set.mem_singleton_iff] at hi,
refine β¨β¨ΞΆ, subset_adjoin $ set.mem_singleton ΞΆβ©, _β©,
rwa [β is_primitive_root.coe_submonoid_class_iff, subtype.coe_mk, hi],
end,
adjoin_roots := Ξ» x,
begin
refine adjoin_induction' (Ξ» b hb, _) (Ξ» a, _) (Ξ» bβ bβ hbβ hbβ, _) (Ξ» bβ bβ hbβ hbβ, _) x,
{ rw [set.mem_singleton_iff] at hb,
refine subset_adjoin _,
simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq, hb],
rw [β subalgebra.coe_eq_one, subalgebra.coe_pow, set_like.coe_mk],
exact ((is_primitive_root.iff_def ΞΆ n).1 h).1 },
{ exact subalgebra.algebra_map_mem _ _ },
{ exact subalgebra.add_mem _ hbβ hbβ },
{ exact subalgebra.mul_mem _ hbβ hbβ }
end }
end
section field
variables {n S}
/-- A cyclotomic extension splits `X ^ n - 1` if `n β S`.-/
lemma splits_X_pow_sub_one [H : is_cyclotomic_extension S K L] (hS : n β S) :
splits (algebra_map K L) (X ^ (n : β) - 1) :=
begin
rw [β splits_id_iff_splits, polynomial.map_sub, polynomial.map_one,
polynomial.map_pow, polynomial.map_X],
obtain β¨z, hzβ© := ((is_cyclotomic_extension_iff _ _ _).1 H).1 hS,
exact X_pow_sub_one_splits hz,
end
/-- A cyclotomic extension splits `cyclotomic n K` if `n β S` and `ne_zero (n : K)`.-/
lemma splits_cyclotomic [is_cyclotomic_extension S K L] (hS : n β S) :
splits (algebra_map K L) (cyclotomic n K) :=
begin
refine splits_of_splits_of_dvd _ (X_pow_sub_C_ne_zero n.pos _)
(splits_X_pow_sub_one K L hS) _,
use (β (i : β) in (n : β).proper_divisors, polynomial.cyclotomic i K),
rw [(eq_cyclotomic_iff n.pos _).1 rfl, ring_hom.map_one],
end
variables (n S)
section singleton
variables [is_cyclotomic_extension {n} K L]
/-- If `is_cyclotomic_extension {n} K L`, then `L` is the splitting field of `X ^ n - 1`. -/
lemma splitting_field_X_pow_sub_one : is_splitting_field K L (X ^ (n : β) - 1) :=
{ splits := splits_X_pow_sub_one K L (mem_singleton n),
adjoin_roots :=
begin
rw [β ((iff_adjoin_eq_top {n} K L).1 infer_instance).2],
congr,
refine set.ext (Ξ» x, _),
simp only [polynomial.map_pow, mem_singleton_iff, multiset.mem_to_finset, exists_eq_left,
mem_set_of_eq, polynomial.map_X, polynomial.map_one, finset.mem_coe, polynomial.map_sub],
rwa [β ring_hom.map_one C, mem_roots (@X_pow_sub_C_ne_zero L _ _ _ n.pos _), is_root.def,
eval_sub, eval_pow, eval_C, eval_X, sub_eq_zero]
end }
localized "attribute [instance] is_cyclotomic_extension.splitting_field_X_pow_sub_one" in cyclotomic
include n
lemma is_galois : is_galois K L :=
begin
letI := splitting_field_X_pow_sub_one n K L,
exact is_galois.of_separable_splitting_field (X_pow_sub_one_separable_iff.2 ((ne_zero' n K L).1))
end
localized "attribute [instance] is_cyclotomic_extension.is_galois" in cyclotomic
/-- If `is_cyclotomic_extension {n} K L`, then `L` is the splitting field of `cyclotomic n K`. -/
lemma splitting_field_cyclotomic : is_splitting_field K L (cyclotomic n K) :=
{ splits := splits_cyclotomic K L (mem_singleton n),
adjoin_roots :=
begin
rw [β ((iff_adjoin_eq_top {n} K L).1 infer_instance).2],
letI := classical.dec_eq L,
obtain β¨ΞΆ, hΞΆβ© := @is_cyclotomic_extension.exists_prim_root {n} K L _ _ _ _ _ (mem_singleton n),
exact adjoin_roots_cyclotomic_eq_adjoin_nth_roots hΞΆ
end }
localized "attribute [instance] is_cyclotomic_extension.splitting_field_cyclotomic" in cyclotomic
end singleton
end field
end is_cyclotomic_extension
section cyclotomic_field
/-- Given `n : β+` and a field `K`, we define `cyclotomic_field n K` as the
splitting field of `cyclotomic n K`. If `n` is nonzero in `K`, it has
the instance `is_cyclotomic_extension {n} K (cyclotomic_field n K)`. -/
@[derive [field, algebra K, inhabited]]
def cyclotomic_field : Type w := (cyclotomic n K).splitting_field
namespace cyclotomic_field
instance [char_zero K] : char_zero (cyclotomic_field n K) :=
char_zero_of_injective_algebra_map ((algebra_map K _).injective)
instance is_cyclotomic_extension [ne_zero ((n : β) : K)] :
is_cyclotomic_extension {n} K (cyclotomic_field n K) :=
{ exists_prim_root := Ξ» a han,
begin
rw mem_singleton_iff at han,
subst a,
obtain β¨r, hrβ© := exists_root_of_splits (algebra_map K (cyclotomic_field n K))
(splitting_field.splits _) (degree_cyclotomic_pos n K (n.pos)).ne',
refine β¨r, _β©,
haveI := ne_zero.of_no_zero_smul_divisors K (cyclotomic_field n K) n,
rwa [β eval_map, β is_root.def, map_cyclotomic, is_root_cyclotomic_iff] at hr
end,
adjoin_roots :=
begin
rw [βalgebra.eq_top_iff, βsplitting_field.adjoin_roots, eq_comm],
letI := classical.dec_eq (cyclotomic_field n K),
obtain β¨ΞΆ, hΞΆβ© := exists_root_of_splits _ (splitting_field.splits (cyclotomic n K))
(degree_cyclotomic_pos n _ n.pos).ne',
haveI : ne_zero ((n : β) : (cyclotomic_field n K)) :=
ne_zero.nat_of_injective (algebra_map K _).injective,
rw [evalβ_eq_eval_map, map_cyclotomic, β is_root.def, is_root_cyclotomic_iff] at hΞΆ,
exact is_cyclotomic_extension.adjoin_roots_cyclotomic_eq_adjoin_nth_roots hΞΆ,
end }
end cyclotomic_field
end cyclotomic_field
section is_domain
variables [is_domain A] [algebra A K] [is_fraction_ring A K]
section cyclotomic_ring
/-- If `K` is the fraction field of `A`, the `A`-algebra structure on `cyclotomic_field n K`.
This is not an instance since it causes diamonds when `A = β€`. -/
@[nolint unused_arguments]
def cyclotomic_field.algebra_base : algebra A (cyclotomic_field n K) :=
((algebra_map K (cyclotomic_field n K)).comp (algebra_map A K)).to_algebra
local attribute [instance] cyclotomic_field.algebra_base
instance cyclotomic_field.no_zero_smul_divisors : no_zero_smul_divisors A (cyclotomic_field n K) :=
no_zero_smul_divisors.of_algebra_map_injective $ function.injective.comp
(no_zero_smul_divisors.algebra_map_injective _ _) $ is_fraction_ring.injective A K
/-- If `A` is a domain with fraction field `K` and `n : β+`, we define `cyclotomic_ring n A K` as
the `A`-subalgebra of `cyclotomic_field n K` generated by the roots of `X ^ n - 1`. If `n`
is nonzero in `A`, it has the instance `is_cyclotomic_extension {n} A (cyclotomic_ring n A K)`. -/
@[derive [comm_ring, is_domain, inhabited]]
def cyclotomic_ring : Type w := adjoin A { b : (cyclotomic_field n K) | b ^ (n : β) = 1 }
namespace cyclotomic_ring
/-- The `A`-algebra structure on `cyclotomic_ring n A K`.
This is not an instance since it causes diamonds when `A = β€`. -/
def algebra_base : algebra A (cyclotomic_ring n A K) := (adjoin A _).algebra
local attribute [instance] cyclotomic_ring.algebra_base
instance : no_zero_smul_divisors A (cyclotomic_ring n A K) := (adjoin A _).no_zero_smul_divisors_bot
lemma algebra_base_injective : function.injective $ algebra_map A (cyclotomic_ring n A K) :=
no_zero_smul_divisors.algebra_map_injective _ _
instance : algebra (cyclotomic_ring n A K) (cyclotomic_field n K) :=
(adjoin A _).to_algebra
lemma adjoin_algebra_injective :
function.injective $ algebra_map (cyclotomic_ring n A K) (cyclotomic_field n K) :=
subtype.val_injective
instance : no_zero_smul_divisors (cyclotomic_ring n A K) (cyclotomic_field n K) :=
no_zero_smul_divisors.of_algebra_map_injective (adjoin_algebra_injective n A K)
instance : is_scalar_tower A (cyclotomic_ring n A K) (cyclotomic_field n K) :=
is_scalar_tower.subalgebra' _ _ _ _
instance is_cyclotomic_extension [ne_zero ((n : β) : A)] :
is_cyclotomic_extension {n} A (cyclotomic_ring n A K) :=
{ exists_prim_root := Ξ» a han,
begin
rw mem_singleton_iff at han,
subst a,
haveI := ne_zero.of_no_zero_smul_divisors A K n,
haveI := ne_zero.of_no_zero_smul_divisors A (cyclotomic_field n K) n,
obtain β¨ΞΌ, hΞΌβ© := let h := (cyclotomic_field.is_cyclotomic_extension n K).exists_prim_root
in h $ mem_singleton n,
refine β¨β¨ΞΌ, subset_adjoin _β©, _β©,
{ apply (is_root_of_unity_iff n.pos (cyclotomic_field n K)).mpr,
refine β¨n, nat.mem_divisors_self _ n.ne_zero, _β©,
rwa [β is_root_cyclotomic_iff] at hΞΌ },
{ rwa [β is_primitive_root.coe_submonoid_class_iff, subtype.coe_mk] }
end,
adjoin_roots := Ξ» x,
begin
refine adjoin_induction' (Ξ» y hy, _) (Ξ» a, _) (Ξ» y z hy hz, _) (Ξ» y z hy hz, _) x,
{ refine subset_adjoin _,
simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq],
rwa [β subalgebra.coe_eq_one, subalgebra.coe_pow, subtype.coe_mk] },
{ exact subalgebra.algebra_map_mem _ a },
{ exact subalgebra.add_mem _ hy hz },
{ exact subalgebra.mul_mem _ hy hz },
end }
instance [ne_zero ((n : β) : A)] :
is_fraction_ring (cyclotomic_ring n A K) (cyclotomic_field n K) :=
{ map_units := Ξ» β¨x, hxβ©, begin
rw is_unit_iff_ne_zero,
apply map_ne_zero_of_mem_non_zero_divisors,
apply adjoin_algebra_injective,
exact hx
end,
surj := Ξ» x,
begin
letI : ne_zero ((n : β) : K) := ne_zero.nat_of_injective (is_fraction_ring.injective A K),
refine algebra.adjoin_induction (((is_cyclotomic_extension.iff_singleton n K _).1
(cyclotomic_field.is_cyclotomic_extension n K)).2 x) (Ξ» y hy, _) (Ξ» k, _) _ _,
{ exact β¨β¨β¨y, subset_adjoin hyβ©, 1β©, by simpaβ© },
{ have : is_localization (non_zero_divisors A) K := infer_instance,
replace := this.surj,
obtain β¨β¨z, wβ©, hwβ© := this k,
refine β¨β¨algebra_map A _ z, algebra_map A _ w, map_mem_non_zero_divisors _
(algebra_base_injective n A K) w.2β©, _β©,
letI : is_scalar_tower A K (cyclotomic_field n K) :=
is_scalar_tower.of_algebra_map_eq (congr_fun rfl),
rw [set_like.coe_mk, β is_scalar_tower.algebra_map_apply,
β is_scalar_tower.algebra_map_apply, @is_scalar_tower.algebra_map_apply A K _ _ _ _ _
(_root_.cyclotomic_field.algebra n K) _ _ w, β ring_hom.map_mul, hw,
β is_scalar_tower.algebra_map_apply] },
{ rintro y z β¨a, haβ© β¨b, hbβ©,
refine β¨β¨a.1 * b.2 + b.1 * a.2, a.2 * b.2, mul_mem_non_zero_divisors.2 β¨a.2.2, b.2.2β©β©, _β©,
rw [set_like.coe_mk, ring_hom.map_mul, add_mul, β mul_assoc, ha,
mul_comm ((algebra_map _ _) βa.2), β mul_assoc, hb],
simp },
{ rintro y z β¨a, haβ© β¨b, hbβ©,
refine β¨β¨a.1 * b.1, a.2 * b.2, mul_mem_non_zero_divisors.2 β¨a.2.2, b.2.2β©β©, _β©,
rw [set_like.coe_mk, ring_hom.map_mul, mul_comm ((algebra_map _ _) βa.2), mul_assoc,
β mul_assoc z, hb, β mul_comm ((algebra_map _ _) βa.2), β mul_assoc, ha],
simp }
end,
eq_iff_exists := Ξ» x y, β¨Ξ» h, β¨1, by rw adjoin_algebra_injective n A K hβ©,
Ξ» β¨c, hcβ©, by rw mul_right_cancelβ (non_zero_divisors.ne_zero c.prop) hcβ© }
lemma eq_adjoin_primitive_root {ΞΌ : (cyclotomic_field n K)} (h : is_primitive_root ΞΌ n) :
cyclotomic_ring n A K = adjoin A ({ΞΌ} : set ((cyclotomic_field n K))) :=
begin
letI := classical.prop_decidable,
rw [βis_cyclotomic_extension.adjoin_roots_cyclotomic_eq_adjoin_root_cyclotomic h,
is_cyclotomic_extension.adjoin_roots_cyclotomic_eq_adjoin_nth_roots h],
simp [cyclotomic_ring]
end
end cyclotomic_ring
end cyclotomic_ring
end is_domain
section is_alg_closed
variables [is_alg_closed K]
/-- Algebraically closed fields are `S`-cyclotomic extensions over themselves if
`ne_zero ((a : β) : K))` for all `a β S`. -/
lemma is_alg_closed.is_cyclotomic_extension (h : β a β S, ne_zero ((a : β) : K)) :
is_cyclotomic_extension S K K :=
begin
refine β¨Ξ» a ha, _, algebra.eq_top_iff.mp $ subsingleton.elim _ _ β©,
obtain β¨r, hrβ© := is_alg_closed.exists_aeval_eq_zero K _ (degree_cyclotomic_pos a K a.pos).ne',
refine β¨r, _β©,
haveI := h a ha,
rwa [coe_aeval_eq_eval, β is_root.def, is_root_cyclotomic_iff] at hr,
end
instance is_alg_closed_of_char_zero.is_cyclotomic_extension [char_zero K] :
β S, is_cyclotomic_extension S K K :=
Ξ» S, is_alg_closed.is_cyclotomic_extension S K (Ξ» a ha, infer_instance)
end is_alg_closed
|
10c430760e3a64a1d81e9d86165351f796bd328a | bdb33f8b7ea65f7705fc342a178508e2722eb851 | /analysis/measure_theory/lebesgue_measure.lean | 47f50ddfb9dd4d3aee25fbfcc756cf8c7f185791 | [
"Apache-2.0"
] | permissive | rwbarton/mathlib | 939ae09bf8d6eb1331fc2f7e067d39567e10e33d | c13c5ea701bb1eec057e0a242d9f480a079105e9 | refs/heads/master | 1,584,015,335,862 | 1,524,142,167,000 | 1,524,142,167,000 | 130,614,171 | 0 | 0 | Apache-2.0 | 1,548,902,667,000 | 1,524,437,371,000 | Lean | UTF-8 | Lean | false | false | 9,040 | lean | /-
Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes HΓΆlzl
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)
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 :=
by rw [β (Ico_self : Ico 0 (0:β) = β
), lebesgue_length_Ico'];
simp [le_refl]
@[simp] lemma lebesgue_length_Ico {a b : β} :
lebesgue_length (Ico a b) = of_real (b - a) :=
(le_total a b).elim lebesgue_length_Ico' $ Ξ» h,
by rw [ennreal.of_real_of_nonpos (sub_nonpos.2 h), Ico_eq_empty h]; simp
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_subadditive {a b : β} {c d : β β β}
(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))) :=
(le_total b a).elim (Ξ» h, by rw [Ico_eq_empty h]; simp) $ Ξ» hab,
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, by simp; exact
ennreal.of_real_le_of_real (add_le_add_right (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];
from ennreal.of_real_le_of_real (add_le_add_right (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,
by simp; exact ennreal.of_real_le_of_real (add_le_add_right (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 : β} :
lebesgue_outer.measure_of (Ico a b) = of_real (b - a) :=
le_antisymm
(by rw β lebesgue_length_Ico; apply outer_measure.of_function_le)
(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
... β€ (βi, lebesgue_length (Ico (cd i).1 (cd i).2)) :
lebesgue_length_subadditive 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)β©
@[simp] lemma lebesgue_Ico {a b : β} : lebesgue (Ico a b) = of_real (b - a) :=
by rw [lebesgue.measure_eq is_measurable_Ico]; exact lebesgue_outer_Ico
@[simp] lemma lebesgue_Ioo {a b : β} : lebesgue (Ioo a b) = of_real (b - a) :=
begin
cases le_total b a with ba ab,
{ rw ennreal.of_real_of_nonpos (sub_nonpos.2 ba), simp [ba] },
refine (eq_of_le_of_forall_ge_of_dense _ (Ξ» r h, _)).symm,
{ rw β lebesgue_Ico,
exact measure_mono Ioo_subset_Ico_self },
rcases ennreal.lt_iff_exists_of_real.1 h with β¨c, c0, rfl, _β©,
replace h := (ennreal.of_real_lt_of_real_iff c0 (sub_nonneg.2 ab)).1 h,
rw β show lebesgue (Ico (b - c) b) = of_real c,
by simp [-sub_eq_add_neg, sub_sub_cancel],
exact measure_mono (Ico_subset_Ioo_left $ lt_sub.1 h)
end
lemma lebesgue_singleton {a : β} : lebesgue {a} = 0 :=
by rw [β Ico_sdiff_Ioo_eq_singleton (lt_add_one a),
@measure_sdiff β _ _ _ _ Ioo_subset_Ico_self is_measurable_Ico is_measurable_Ioo];
simp; exact ennreal.of_real_lt_infty
end measure_theory
|
83a54efb2f25ffb0c302e781804013ebfe11bfdf | a721fe7446524f18ba361625fc01033d9c8b7a78 | /src/principia/real/add.lean | 2df8e176aedfc0a97d7d291d90dd77623f66a5ea | [] | no_license | Sterrs/leaning | 8fd80d1f0a6117a220bb2e57ece639b9a63deadc | 3901cc953694b33adda86cb88ca30ba99594db31 | refs/heads/master | 1,627,023,822,744 | 1,616,515,221,000 | 1,616,515,221,000 | 245,512,190 | 2 | 0 | null | 1,616,429,050,000 | 1,583,527,118,000 | Lean | UTF-8 | Lean | false | false | 4,177 | lean | import .basic
namespace hidden
open myring
open ordered_myring
open myfield
open ordered_myfield
namespace cau_seq
-- We have to prove that it actually gives a cau_seq
def add : cau_seq β cau_seq β cau_seq :=
Ξ» f g, β¨Ξ» n, f.val n + g.val n,
begin
have hf := f.property,
have hg := g.property,
dsimp only [is_cau_seq] at *,
intros Ξ΅ hΞ΅,
have hfΞ΅ := hf (Ξ΅ / 2) (half_pos hΞ΅),
have hgΞ΅ := hg (Ξ΅ / 2) (half_pos hΞ΅),
clear hf hg,
cases hfΞ΅ with M hM,
cases hgΞ΅ with N hN,
existsi mynat.max M N,
intros m n hm hn,
have : f.val n + g.val n - (f.val m + g.val m) = (f.val n - f.val m) + (g.val n - g.val m),
rw [sub_def, neg_distr],
have : f.val n + g.val n + (-f.val m + -g.val m) = (f.val n + -f.val m) + (g.val n + -g.val m),
ac_refl,
rw this, clear this,
rw [βsub_def, βsub_def],
rw this, clear this,
have : abs (f.val n - f.val m + (g.val n - g.val m)) β€
abs (f.val n - f.val m) + abs (g.val n - g.val m),
apply triangle_ineq,
apply le_lt_chain (abs (f.val n - f.val m) + abs (g.val n - g.val m)),
assumption,
have hNβ := hN m n (mynat.max_le_cancel_right hm) (mynat.max_le_cancel_right hn),
have hMβ := hM m n (mynat.max_le_cancel_left hm) (mynat.max_le_cancel_left hn),
clear this hM hN,
have := lt_comb hMβ hNβ,
rw [div_def, βmul_add, βone_div, half_plus_half (myrat.two_nzero), mul_one] at this,
assumption,
endβ©
instance: has_add cau_seq := β¨addβ©
theorem add_val {a b : cau_seq} {n : mynat} : (a + b).val n = a.val n + b.val n := rfl
end cau_seq
namespace real
open cau_seq
def add : real β real β real :=
quotient.liftβ (Ξ» f g, β¦f + gβ§)
begin
intros a x b y hab hxy,
dsimp only [],
rw cau_seq.class_equiv,
rw cau_seq.setoid_equiv at *,
dsimp only [cau_seq.equivalent] at *,
intros Ξ΅ hΞ΅,
cases hab (Ξ΅ / 2) (half_pos hΞ΅) with M hM,
cases hxy (Ξ΅ / 2) (half_pos hΞ΅) with N hN,
existsi mynat.max M N,
intros n hn,
have hMn := hM n (mynat.max_le_cancel_left hn),
have hNn := hN n (mynat.max_le_cancel_right hn),
clear hM hN hxy hab,
have h := lt_comb hMn hNn,
rw half_plus_half at h,
rw [cau_seq.add_val, cau_seq.add_val, sub_def, neg_distr],
have : a.val n + x.val n + (-b.val n + -y.val n) = a.val n + -b.val n + (x.val n + -y.val n),
ac_refl,
rw this, clear this,
apply le_lt_chain (abs (a.val n - b.val n) + abs (x.val n - y.val n)),
rw [sub_def, sub_def],
from @triangle_ineq _ _ (a.val n + -b.val n) (x.val n + -y.val n),
assumption,
from myrat.two_nzero,
end
instance : has_add real := β¨addβ©
theorem add_eq_cls {x y : real} {f g : cau_seq}: x = β¦fβ§ β y = β¦gβ§ β x + y = β¦f + gβ§ :=
Ξ» hxf hyg, by rw [hxf, hyg]; refl
theorem add_assoc (x y z : real) : x + y + z = x + (y + z) :=
begin
cases quotient.exists_rep x with f hf, subst hf,
cases quotient.exists_rep y with g hg, subst hg,
cases quotient.exists_rep z with h hh, subst hh,
repeat { rw [add_eq_cls rfl rfl] },
apply seq_eq_imp_real_eq rfl rfl,
intro n,
repeat { rw add_val, },
ac_refl,
end
@[simp] theorem add_zero (x : real) : x + 0 = x :=
begin
cases quotient.exists_rep x with f hf, subst hf,
rw [real_zero, coe_def],
rw add_eq_cls rfl rfl,
apply seq_eq_imp_real_eq rfl rfl,
intro n,
rw add_val,
dsimp only [],
rw add_zero,
end
@[simp] theorem add_neg (x : real) : x + -x = 0 :=
begin
cases quotient.exists_rep x with f hf, subst hf,
rw [neg_eq_cls rfl, add_eq_cls rfl rfl],
rw real_zero,
apply seq_eq_imp_real_eq rfl rfl,
intro n,
dsimp only [],
rw [add_val, neg_val, βsub_def, sub_self],
end
theorem coe_add (a b : myrat) : β(a + b) = βa + (βb : real) :=
begin
repeat { rw coe_def, },
rw add_eq_cls rfl rfl,
rw cau_seq.class_equiv,
apply seq_eq_impl_cau_seq_equiv,
intros n,
rw cau_seq.add_val,
end
theorem real_two : (2 : real) = β(2 : myrat) :=
begin
change 1 + (1 : real) = β(1 + (1 : myrat)),
rw coe_add,
rw real_one,
end
theorem two_nzero : (2 : real) β 0 :=
begin
rw [real_two, real_zero],
assume water,
rw eq_iff_coe_eq at water,
exact myrat.two_nzero water,
end
end real
end hidden
|
55875fc292cfa3f7f5aab82163784e3c6013f020 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /stage0/src/Lean/Elab/Do.lean | 8fb99f4956233162c01e3d39247b88ffd841ca45 | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 69,665 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
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
hasBindInst : Expr
expectedType : Expr
private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do
let u β getDecLevel type
let id := Lean.mkConst `Id [u]
let idBindVal := Lean.mkConst `Id.hasBind [u]
pure { m := id, hasBindInst := idBindVal, Ξ± := type, expectedType := mkApp id type }
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 bindInstVal β Meta.synthInstance bindInstType
return some { m := m, hasBindInst := bindInstVal, Ξ± := Ξ±, expectedType := expectedType }
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 β `(ensureExpectedType% "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 ref 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 β `(ensureTypeOf% $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
``(ite $cond $thenBranch $elseBranch)
else
let h := optIdent[0]
``(dite $cond (fun $h => $thenBranch) (fun $h => $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 `(typeOf% $(β 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) MacroM Syntax
| stx@(Syntax.node k args) =>
if liftMethodDelimiter k then
return stx
else if k == `Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do
if inBinder then
Macro.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 k args
| stx => pure stx
def expandLiftMethod (doElem : Syntax) : MacroM (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 β `(forIn% $(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 (ensureExpectedType% "type mismatch, 'for'" PUnit.unit)
| some a => return ensureExpectedType% "type mismatch, 'for'" a)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else
let forInBody β liftMacroM <| destructTuple uvars (β `(r)) forInBody
let forInTerm β `(forIn% $(xs) $uvarsTuple fun $x r => $forInBody)
if doElems.isEmpty then
let auxDo β `(do let r β $forInTerm:term;
$uvarsTuple:term := r;
Pure.pure (ensureExpectedType% "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) β liftM (liftMacroM <| expandLiftMethod doElem : TermElabM _)
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 := 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
@[builtinTermElab Β«doΒ»]
def elabDo : TermElab := fun stx expectedType? => do
tryPostponeIfNoneOrMVar expectedType?
let bindInfo β extractBind expectedType?
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
|
e1c1455ad2493c5281a4a03b3f5c794df57c0bf6 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/convolution.lean | 01acc85d1edd3a6557f67aa5b52a8c63c3019b61 | [
"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 | 51,992 | lean | /-
Copyright (c) 2022 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import measure_theory.group.integration
import measure_theory.group.prod
import measure_theory.function.locally_integrable
import analysis.calculus.specific_functions
import analysis.calculus.parametric_integral
/-!
# Convolution of functions
This file defines the convolution on two functions, i.e. `x β¦ β« f(t)g(x - t) βt`.
In the general case, these functions can be vector-valued, and have an arbitrary (additive)
group as domain. We use a continuous bilinear operation `L` on these function values as
"multiplication". The domain must be equipped with a Haar measure `ΞΌ`
(though many individual results have weaker conditions on `ΞΌ`).
For many applications we can take `L = lsmul β β` or `L = mul β β`.
We also define `convolution_exists` and `convolution_exists_at` to state that the convolution is
well-defined (everywhere or at a single point). These conditions are needed for pointwise
computations (e.g. `convolution_exists_at.distrib_add`), but are generally not stong enough for any
local (or global) properties of the convolution. For this we need stronger assumptions on `f`
and/or `g`, and generally if we impose stronger conditions on one of the functions, we can impose
weaker conditions on the other.
We have proven many of the properties of the convolution assuming one of these functions
has compact support (in which case the other function only needs to be locally integrable).
We still need to prove the properties for other pairs of conditions (e.g. both functions are
rapidly decreasing)
# Design Decisions
We use a bilinear map `L` to "multiply" the two functions in the integrand.
This generality has several advantages
* This allows us to compute the total derivative of the convolution, in case the functions are
multivariate. The total derivative is again a convolution, but where the codomains of the
functions can be higher-dimensional. See `has_compact_support.has_fderiv_at_convolution_right`.
* This allows us to use `@[to_additive]` everywhere (which would not be possible if we would use
`mul`/`smul` in the integral, since `@[to_additive]` will incorrectly also try to additivize
those definitions).
* We need to support the case where at least one of the functions is vector-valued, but if we use
`smul` to multiply the functions, that would be an asymmetric definition.
# Main Definitions
* `convolution f g L ΞΌ x = (f β[L, ΞΌ] g) x = β« t, L (f t) (g (x - t)) βΞΌ` is the convolution of
`f` and `g` w.r.t. the continuous bilinear map `L` and measure `ΞΌ`.
* `convolution_exists_at f g x L ΞΌ` states that the convolution `(f β[L, ΞΌ] g) x` is well-defined
(i.e. the integral exists).
* `convolution_exists f g L ΞΌ` states that the convolution `f β[L, ΞΌ] g` is well-defined at each
point.
# Main Results
* `has_compact_support.has_fderiv_at_convolution_right` and
`has_compact_support.has_fderiv_at_convolution_left`: we can compute the total derivative
of the convolution as a convolution with the total derivative of the right (left) function.
* `has_compact_support.cont_diff_convolution_right` and
`has_compact_support.cont_diff_convolution_left`: the convolution is `πβΏ` if one of the functions
is `πβΏ` with compact support and the other function in locally integrable.
* `convolution_tendsto_right`: Given a sequence of nonnegative normalized functions whose support
tends to a small neighborhood around `0`, the convolution tends to the right argument.
This is specialized to bump functions in `cont_diff_bump_of_inner.convolution_tendsto_right`.
# Notation
The following notations are localized in the locale `convolution`:
* `f β[L, ΞΌ] g` for the convolution. Note: you have to use parentheses to apply the convolution
to an argument: `(f β[L, ΞΌ] g) x`.
* `f β[L] g := f β[L, volume] g`
* `f β g := f β[lsmul β β] g`
# To do
* Existence and (uniform) continuity of the convolution if
one of the maps is in `β^p` and the other in `β^q` with `1 / p + 1 / q = 1`.
This might require a generalization of `measure_theory.mem_βp.smul` where `smul` is generalized
to a continuous bilinear map.
(see e.g. [Fremlin, *Measure Theory* (volume 2)][fremlin_vol2], 255K)
* The convolution is a `ae_strongly_measurable` function
(see e.g. [Fremlin, *Measure Theory* (volume 2)][fremlin_vol2], 255I).
* Prove properties about the convolution if both functions are rapidly decreasing.
* Use `@[to_additive]` everywhere
-/
open set function filter measure_theory measure_theory.measure topological_space
open continuous_linear_map metric
open_locale pointwise topological_space nnreal filter
variables {π G E E' E'' F F' F'' : Type*}
variables [normed_add_comm_group E] [normed_add_comm_group E'] [normed_add_comm_group E'']
[normed_add_comm_group F] {f f' : G β E} {g g' : G β E'} {x x' : G} {y y' : E}
section nontrivially_normed_field
variables [nontrivially_normed_field π]
variables [normed_space π E] [normed_space π E'] [normed_space π E''] [normed_space π F]
variables (L : E βL[π] E' βL[π] F)
section no_measurability
variables [add_group G] [topological_space G]
lemma has_compact_support.convolution_integrand_bound_right (hcg : has_compact_support g)
(hg : continuous g) {x t : G} {s : set G} (hx : x β s) :
βL (f t) (g (x - t))β β€ (- tsupport g + s).indicator (Ξ» t, βLβ * βf tβ * (β¨ i, βg iβ)) t :=
begin
refine le_indicator (Ξ» t ht, _) (Ξ» t ht, _) t,
{ refine (L.le_op_normβ _ _).trans _,
exact mul_le_mul_of_nonneg_left
(le_csupr (hg.norm.bdd_above_range_of_has_compact_support hcg.norm) $ x - t)
(mul_nonneg (norm_nonneg _) (norm_nonneg _)) },
{ have : x - t β support g,
{ refine mt (Ξ» hxt, _) ht, refine β¨_, _, set.neg_mem_neg.mpr (subset_closure hxt), hx, _β©,
rw [neg_sub, sub_add_cancel] },
rw [nmem_support.mp this, (L _).map_zero, norm_zero] }
end
lemma continuous.convolution_integrand_fst [has_continuous_sub G] (hg : continuous g) (t : G) :
continuous (Ξ» x, L (f t) (g (x - t))) :=
L.continuousβ.compβ continuous_const $ hg.comp $ continuous_id.sub continuous_const
lemma has_compact_support.convolution_integrand_bound_left (hcf : has_compact_support f)
(hf : continuous f) {x t : G} {s : set G} (hx : x β s) :
βL (f (x - t)) (g t)β β€ (- tsupport f + s).indicator (Ξ» t, βLβ * (β¨ i, βf iβ) * βg tβ) t :=
by { convert hcf.convolution_integrand_bound_right L.flip hf hx,
simp_rw [L.op_norm_flip, mul_right_comm] }
end no_measurability
section measurability
variables [measurable_space G] {ΞΌ Ξ½ : measure G}
/-- The convolution of `f` and `g` exists at `x` when the function `t β¦ L (f t) (g (x - t))` is
integrable. There are various conditions on `f` and `g` to prove this. -/
def convolution_exists_at [has_sub G] (f : G β E) (g : G β E') (x : G) (L : E βL[π] E' βL[π] F)
(ΞΌ : measure G . volume_tac) : Prop :=
integrable (Ξ» t, L (f t) (g (x - t))) ΞΌ
/-- The convolution of `f` and `g` exists when the function `t β¦ L (f t) (g (x - t))` is integrable
for all `x : G`. There are various conditions on `f` and `g` to prove this. -/
def convolution_exists [has_sub G] (f : G β E) (g : G β E') (L : E βL[π] E' βL[π] F)
(ΞΌ : measure G . volume_tac) : Prop :=
β x : G, convolution_exists_at f g x L ΞΌ
section convolution_exists
variables {L}
lemma convolution_exists_at.integrable [has_sub G] {x : G} (h : convolution_exists_at f g x L ΞΌ) :
integrable (Ξ» t, L (f t) (g (x - t))) ΞΌ :=
h
variables (L)
section group
variables [add_group G]
variables [has_measurable_addβ G] [has_measurable_neg G]
lemma measure_theory.ae_strongly_measurable.convolution_integrand' [sigma_finite Ξ½]
(hf : ae_strongly_measurable f Ξ½)
(hg : ae_strongly_measurable g $ map (Ξ» (p : G Γ G), p.1 - p.2) (ΞΌ.prod Ξ½)) :
ae_strongly_measurable (Ξ» p : G Γ G, L (f p.2) (g (p.1 - p.2))) (ΞΌ.prod Ξ½) :=
L.ae_strongly_measurable_compβ hf.snd $ hg.comp_measurable measurable_sub
lemma measure_theory.ae_strongly_measurable.convolution_integrand_snd'
(hf : ae_strongly_measurable f ΞΌ) {x : G}
(hg : ae_strongly_measurable g $ map (Ξ» t, x - t) ΞΌ) :
ae_strongly_measurable (Ξ» t, L (f t) (g (x - t))) ΞΌ :=
L.ae_strongly_measurable_compβ hf $ hg.comp_measurable $ measurable_id.const_sub x
lemma measure_theory.ae_strongly_measurable.convolution_integrand_swap_snd'
{x : G} (hf : ae_strongly_measurable f $ map (Ξ» t, x - t) ΞΌ)
(hg : ae_strongly_measurable g ΞΌ) : ae_strongly_measurable (Ξ» t, L (f (x - t)) (g t)) ΞΌ :=
L.ae_strongly_measurable_compβ (hf.comp_measurable $ measurable_id.const_sub x) hg
/-- A sufficient condition to prove that `f β[L, ΞΌ] g` exists.
We assume that the integrand has compact support and `g` is bounded on this support (note that
both properties hold if `g` is continuous with compact support). We also require that `f` is
integrable on the support of the integrand, and that both functions are strongly measurable.
Note: we could weaken the measurability condition to hold only for `ΞΌ.restrict s`. -/
lemma bdd_above.convolution_exists_at' {xβ : G}
{s : set G} (hbg : bdd_above ((Ξ» i, βg iβ) '' ((Ξ» t, - t + xβ) β»ΒΉ' s)))
(hs : measurable_set s) (h2s : support (Ξ» t, L (f t) (g (xβ - t))) β s)
(hf : integrable_on f s ΞΌ)
(hmf : ae_strongly_measurable f ΞΌ)
(hmg : ae_strongly_measurable g $ map (Ξ» t, xβ - t) ΞΌ) :
convolution_exists_at f g xβ L ΞΌ :=
begin
set s' := (Ξ» t, - t + xβ) β»ΒΉ' s,
have : βα΅ (t : G) βΞΌ,
βL (f t) (g (xβ - t))β β€ s.indicator (Ξ» t, βLβ * βf tβ * β¨ i : s', βg iβ) t,
{ refine eventually_of_forall _,
refine le_indicator (Ξ» t ht, _) (Ξ» t ht, _),
{ refine (L.le_op_normβ _ _).trans _,
refine mul_le_mul_of_nonneg_left
(le_csupr_set hbg $ mem_preimage.mpr _)
(mul_nonneg (norm_nonneg _) (norm_nonneg _)),
rwa [neg_sub, sub_add_cancel] },
{ have : t β support (Ξ» t, L (f t) (g (xβ - t))) := mt (Ξ» h, h2s h) ht,
rw [nmem_support.mp this, norm_zero] } },
refine integrable.mono' _ _ this,
{ rw [integrable_indicator_iff hs], exact (hf.norm.const_mul _).mul_const _ },
{ exact hmf.convolution_integrand_snd' L hmg }
end
/-- If `βfβ *[ΞΌ] βgβ` exists, then `f *[L, ΞΌ] g` exists. -/
lemma convolution_exists_at.of_norm' {xβ : G}
(h : convolution_exists_at (Ξ» x, βf xβ) (Ξ» x, βg xβ) xβ (mul β β) ΞΌ)
(hmf : ae_strongly_measurable f ΞΌ)
(hmg : ae_strongly_measurable g $ map (Ξ» t, xβ - t) ΞΌ) :
convolution_exists_at f g xβ L ΞΌ :=
begin
refine (h.const_mul βLβ).mono' (hmf.convolution_integrand_snd' L hmg)
(eventually_of_forall $ Ξ» x, _),
rw [mul_apply', β mul_assoc],
apply L.le_op_normβ,
end
section left
variables [sigma_finite ΞΌ] [is_add_right_invariant ΞΌ]
lemma measure_theory.ae_strongly_measurable.convolution_integrand_snd
(hf : ae_strongly_measurable f ΞΌ) (hg : ae_strongly_measurable g ΞΌ)
(x : G) : ae_strongly_measurable (Ξ» t, L (f t) (g (x - t))) ΞΌ :=
hf.convolution_integrand_snd' L $ hg.mono' $
(quasi_measure_preserving_sub_left_of_right_invariant ΞΌ x).absolutely_continuous
lemma measure_theory.ae_strongly_measurable.convolution_integrand_swap_snd
(hf : ae_strongly_measurable f ΞΌ) (hg : ae_strongly_measurable g ΞΌ)
(x : G) : ae_strongly_measurable (Ξ» t, L (f (x - t)) (g t)) ΞΌ :=
(hf.mono' (quasi_measure_preserving_sub_left_of_right_invariant ΞΌ x).absolutely_continuous)
.convolution_integrand_swap_snd' L hg
/-- If `βfβ *[ΞΌ] βgβ` exists, then `f *[L, ΞΌ] g` exists. -/
lemma convolution_exists_at.of_norm {xβ : G}
(h : convolution_exists_at (Ξ» x, βf xβ) (Ξ» x, βg xβ) xβ (mul β β) ΞΌ)
(hmf : ae_strongly_measurable f ΞΌ)
(hmg : ae_strongly_measurable g ΞΌ) :
convolution_exists_at f g xβ L ΞΌ :=
h.of_norm' L hmf $ hmg.mono'
(quasi_measure_preserving_sub_left_of_right_invariant ΞΌ xβ).absolutely_continuous
end left
section right
variables [sigma_finite ΞΌ] [is_add_right_invariant ΞΌ] [sigma_finite Ξ½]
lemma measure_theory.ae_strongly_measurable.convolution_integrand
(hf : ae_strongly_measurable f Ξ½) (hg : ae_strongly_measurable g ΞΌ) :
ae_strongly_measurable (Ξ» p : G Γ G, L (f p.2) (g (p.1 - p.2))) (ΞΌ.prod Ξ½) :=
hf.convolution_integrand' L $ hg.mono'
(quasi_measure_preserving_sub_of_right_invariant ΞΌ Ξ½).absolutely_continuous
lemma measure_theory.integrable.convolution_integrand (hf : integrable f Ξ½) (hg : integrable g ΞΌ) :
integrable (Ξ» p : G Γ G, L (f p.2) (g (p.1 - p.2))) (ΞΌ.prod Ξ½) :=
begin
have h_meas : ae_strongly_measurable (Ξ» (p : G Γ G), L (f p.2) (g (p.1 - p.2))) (ΞΌ.prod Ξ½) :=
hf.ae_strongly_measurable.convolution_integrand L hg.ae_strongly_measurable,
have h2_meas : ae_strongly_measurable (Ξ» (y : G), β« (x : G), βL (f y) (g (x - y))β βΞΌ) Ξ½ :=
h_meas.prod_swap.norm.integral_prod_right',
simp_rw [integrable_prod_iff' h_meas],
refine β¨eventually_of_forall (Ξ» t, (L (f t)).integrable_comp (hg.comp_sub_right t)), _β©,
refine integrable.mono' _ h2_meas (eventually_of_forall $
Ξ» t, (_ : _ β€ βLβ * βf tβ * β« x, βg (x - t)β βΞΌ)),
{ simp_rw [integral_sub_right_eq_self (Ξ» t, β g t β)],
exact (hf.norm.const_mul _).mul_const _ },
{ simp_rw [β integral_mul_left],
rw [real.norm_of_nonneg],
{ exact integral_mono_of_nonneg (eventually_of_forall $ Ξ» t, norm_nonneg _)
((hg.comp_sub_right t).norm.const_mul _) (eventually_of_forall $ Ξ» t, L.le_op_normβ _ _) },
exact integral_nonneg (Ξ» x, norm_nonneg _) }
end
lemma measure_theory.integrable.ae_convolution_exists (hf : integrable f Ξ½) (hg : integrable g ΞΌ) :
βα΅ x βΞΌ, convolution_exists_at f g x L Ξ½ :=
((integrable_prod_iff $ hf.ae_strongly_measurable.convolution_integrand L
hg.ae_strongly_measurable).mp $ hf.convolution_integrand L hg).1
end right
variables [topological_space G] [topological_add_group G] [borel_space G]
[second_countable_topology G] [sigma_compact_space G]
lemma has_compact_support.convolution_exists_at {xβ : G}
(h : has_compact_support (Ξ» t, L (f t) (g (xβ - t)))) (hf : locally_integrable f ΞΌ)
(hg : continuous g) : convolution_exists_at f g xβ L ΞΌ :=
((((homeomorph.neg G).trans $ homeomorph.add_right xβ).is_compact_preimage.mpr h).bdd_above_image
hg.norm.continuous_on).convolution_exists_at' L is_closed_closure.measurable_set subset_closure
(hf h) hf.ae_strongly_measurable hg.ae_strongly_measurable
lemma has_compact_support.convolution_exists_right
(hcg : has_compact_support g) (hf : locally_integrable f ΞΌ) (hg : continuous g) :
convolution_exists f g L ΞΌ :=
begin
intro xβ,
refine has_compact_support.convolution_exists_at L _ hf hg,
refine (hcg.comp_homeomorph (homeomorph.sub_left xβ)).mono _,
refine Ξ» t, mt (Ξ» ht : g (xβ - t) = 0, _),
simp_rw [ht, (L _).map_zero]
end
lemma has_compact_support.convolution_exists_left_of_continuous_right
(hcf : has_compact_support f) (hf : locally_integrable f ΞΌ) (hg : continuous g) :
convolution_exists f g L ΞΌ :=
begin
intro xβ,
refine has_compact_support.convolution_exists_at L _ hf hg,
refine hcf.mono _,
refine Ξ» t, mt (Ξ» ht : f t = 0, _),
simp_rw [ht, L.map_zeroβ]
end
end group
section comm_group
variables [add_comm_group G]
section measurable_group
variables [has_measurable_addβ G] [has_measurable_neg G] [is_add_left_invariant ΞΌ]
/-- A sufficient condition to prove that `f β[L, ΞΌ] g` exists.
We assume that the integrand has compact support and `g` is bounded on this support (note that
both properties hold if `g` is continuous with compact support). We also require that `f` is
integrable on the support of the integrand, and that both functions are strongly measurable.
This is a variant of `bdd_above.convolution_exists_at'` in an abelian group with a left-invariant
measure. This allows us to state the boundedness and measurability of `g` in a more natural way. -/
lemma bdd_above.convolution_exists_at [sigma_finite ΞΌ] {xβ : G}
{s : set G} (hbg : bdd_above ((Ξ» i, βg iβ) '' ((Ξ» t, xβ - t) β»ΒΉ' s)))
(hs : measurable_set s) (h2s : support (Ξ» t, L (f t) (g (xβ - t))) β s)
(hf : integrable_on f s ΞΌ)
(hmf : ae_strongly_measurable f ΞΌ)
(hmg : ae_strongly_measurable g ΞΌ) :
convolution_exists_at f g xβ L ΞΌ :=
begin
refine bdd_above.convolution_exists_at' L _ hs h2s hf hmf _,
{ simp_rw [β sub_eq_neg_add, hbg] },
{ exact hmg.mono'
(quasi_measure_preserving_sub_left_of_right_invariant ΞΌ xβ).absolutely_continuous }
end
variables {L} [is_neg_invariant ΞΌ]
lemma convolution_exists_at_flip :
convolution_exists_at g f x L.flip ΞΌ β convolution_exists_at f g x L ΞΌ :=
by simp_rw [convolution_exists_at, β integrable_comp_sub_left (Ξ» t, L (f t) (g (x - t))) x,
sub_sub_cancel, flip_apply]
lemma convolution_exists_at.integrable_swap (h : convolution_exists_at f g x L ΞΌ) :
integrable (Ξ» t, L (f (x - t)) (g t)) ΞΌ :=
by { convert h.comp_sub_left x, simp_rw [sub_sub_self] }
lemma convolution_exists_at_iff_integrable_swap :
convolution_exists_at f g x L ΞΌ β integrable (Ξ» t, L (f (x - t)) (g t)) ΞΌ :=
convolution_exists_at_flip.symm
end measurable_group
variables [topological_space G] [topological_add_group G] [borel_space G]
[second_countable_topology G] [is_add_left_invariant ΞΌ] [is_neg_invariant ΞΌ]
[sigma_compact_space G]
lemma has_compact_support.convolution_exists_left
(hcf : has_compact_support f) (hf : continuous f) (hg : locally_integrable g ΞΌ) :
convolution_exists f g L ΞΌ :=
Ξ» xβ, convolution_exists_at_flip.mp $ hcf.convolution_exists_right L.flip hg hf xβ
lemma has_compact_support.convolution_exists_right_of_continuous_left
(hcg : has_compact_support g) (hf : continuous f) (hg : locally_integrable g ΞΌ) :
convolution_exists f g L ΞΌ :=
Ξ» xβ, convolution_exists_at_flip.mp $
hcg.convolution_exists_left_of_continuous_right L.flip hg hf xβ
end comm_group
end convolution_exists
variables [normed_space β F] [complete_space F]
/-- The convolution of two functions `f` and `g` with respect to a continuous bilinear map `L` and
measure `ΞΌ`. It is defined to be `(f β[L, ΞΌ] g) x = β« t, L (f t) (g (x - t)) βΞΌ`. -/
noncomputable def convolution [has_sub G] (f : G β E) (g : G β E') (L : E βL[π] E' βL[π] F)
(ΞΌ : measure G . volume_tac) : G β F :=
Ξ» x, β« t, L (f t) (g (x - t)) βΞΌ
localized "notation (name := convolution) f ` β[`:67 L:67 `, ` ΞΌ:67 `] `:0 g:66 :=
convolution f g L ΞΌ" in convolution
localized "notation (name := convolution.volume) f ` β[`:67 L:67 `]`:0 g:66 :=
convolution f g L measure_theory.measure_space.volume" in convolution
localized "notation (name := convolution.lsmul) f ` β `:67 g:66 :=
convolution f g (continuous_linear_map.lsmul β β) measure_theory.measure_space.volume"
in convolution
lemma convolution_def [has_sub G] : (f β[L, ΞΌ] g) x = β« t, L (f t) (g (x - t)) βΞΌ := rfl
/-- The definition of convolution where the bilinear operator is scalar multiplication.
Note: it often helps the elaborator to give the type of the convolution explicitly. -/
lemma convolution_lsmul [has_sub G] {f : G β π} {g : G β F} :
(f β[lsmul π π, ΞΌ] g : G β F) x = β« t, f t β’ g (x - t) βΞΌ := rfl
/-- The definition of convolution where the bilinear operator is multiplication. -/
lemma convolution_mul [has_sub G] [normed_space β π] [complete_space π] {f : G β π} {g : G β π} :
(f β[mul π π, ΞΌ] g) x = β« t, f t * g (x - t) βΞΌ := rfl
section group
variables {L} [add_group G]
lemma smul_convolution [smul_comm_class β π F]
{y : π} : (y β’ f) β[L, ΞΌ] g = y β’ (f β[L, ΞΌ] g) :=
by { ext, simp only [pi.smul_apply, convolution_def, β integral_smul, L.map_smulβ] }
lemma convolution_smul [smul_comm_class β π F]
{y : π} : f β[L, ΞΌ] (y β’ g) = y β’ (f β[L, ΞΌ] g) :=
by { ext, simp only [pi.smul_apply, convolution_def, β integral_smul, (L _).map_smul] }
@[simp] lemma zero_convolution : 0 β[L, ΞΌ] g = 0 :=
by { ext, simp_rw [convolution_def, pi.zero_apply, L.map_zeroβ, integral_zero] }
@[simp] lemma convolution_zero : f β[L, ΞΌ] 0 = 0 :=
by { ext, simp_rw [convolution_def, pi.zero_apply, (L _).map_zero, integral_zero] }
lemma convolution_exists_at.distrib_add {x : G} (hfg : convolution_exists_at f g x L ΞΌ)
(hfg' : convolution_exists_at f g' x L ΞΌ) :
(f β[L, ΞΌ] (g + g')) x = (f β[L, ΞΌ] g) x + (f β[L, ΞΌ] g') x :=
by simp only [convolution_def, (L _).map_add, pi.add_apply, integral_add hfg hfg']
lemma convolution_exists.distrib_add (hfg : convolution_exists f g L ΞΌ)
(hfg' : convolution_exists f g' L ΞΌ) : f β[L, ΞΌ] (g + g') = f β[L, ΞΌ] g + f β[L, ΞΌ] g' :=
by { ext, exact (hfg x).distrib_add (hfg' x) }
lemma convolution_exists_at.add_distrib {x : G} (hfg : convolution_exists_at f g x L ΞΌ)
(hfg' : convolution_exists_at f' g x L ΞΌ) :
((f + f') β[L, ΞΌ] g) x = (f β[L, ΞΌ] g) x + (f' β[L, ΞΌ] g) x :=
by simp only [convolution_def, L.map_addβ, pi.add_apply, integral_add hfg hfg']
lemma convolution_exists.add_distrib (hfg : convolution_exists f g L ΞΌ)
(hfg' : convolution_exists f' g L ΞΌ) : (f + f') β[L, ΞΌ] g = f β[L, ΞΌ] g + f' β[L, ΞΌ] g :=
by { ext, exact (hfg x).add_distrib (hfg' x) }
variables (L)
lemma convolution_congr [has_measurable_addβ G] [has_measurable_neg G]
[sigma_finite ΞΌ] [is_add_right_invariant ΞΌ] (h1 : f =α΅[ΞΌ] f') (h2 : g =α΅[ΞΌ] g') :
f β[L, ΞΌ] g = f' β[L, ΞΌ] g' :=
begin
ext x,
apply integral_congr_ae,
exact (h1.prod_mk $ h2.comp_tendsto
(quasi_measure_preserving_sub_left_of_right_invariant ΞΌ x).tendsto_ae).fun_comp βΏ(Ξ» x y, L x y)
end
lemma support_convolution_subset_swap : support (f β[L, ΞΌ] g) β support g + support f :=
begin
intros x h2x,
by_contra hx,
apply h2x,
simp_rw [set.mem_add, not_exists, not_and_distrib, nmem_support] at hx,
rw [convolution_def],
convert integral_zero G F,
ext t,
rcases hx (x - t) t with h|h|h,
{ rw [h, (L _).map_zero] },
{ rw [h, L.map_zeroβ] },
{ exact (h $ sub_add_cancel x t).elim }
end
section
variables [has_measurable_addβ G] [has_measurable_neg G] [sigma_finite ΞΌ] [is_add_right_invariant ΞΌ]
lemma measure_theory.integrable.integrable_convolution (hf : integrable f ΞΌ) (hg : integrable g ΞΌ) :
integrable (f β[L, ΞΌ] g) ΞΌ :=
(hf.convolution_integrand L hg).integral_prod_left
end
variables [topological_space G]
variables [topological_add_group G]
lemma has_compact_support.convolution [t2_space G] (hcf : has_compact_support f)
(hcg : has_compact_support g) : has_compact_support (f β[L, ΞΌ] g) :=
is_compact_of_is_closed_subset (hcg.is_compact.add hcf) is_closed_closure $ closure_minimal
((support_convolution_subset_swap L).trans $ add_subset_add subset_closure subset_closure)
(hcg.is_compact.add hcf).is_closed
variables [borel_space G] [second_countable_topology G]
/-- The convolution is continuous if one function is locally integrable and the other has compact
support and is continuous. -/
lemma has_compact_support.continuous_convolution_right [locally_compact_space G] [t2_space G]
(hcg : has_compact_support g) (hf : locally_integrable f ΞΌ)
(hg : continuous g) : continuous (f β[L, ΞΌ] g) :=
begin
refine continuous_iff_continuous_at.mpr (Ξ» xβ, _),
obtain β¨K, hK, h2Kβ© := exists_compact_mem_nhds xβ,
let K' := - tsupport g + K,
have hK' : is_compact K' := hcg.neg.add hK,
have : βαΆ x in π xβ, βα΅ (t : G) βΞΌ,
βL (f t) (g (x - t))β β€ K'.indicator (Ξ» t, βLβ * βf tβ * (β¨ i, βg iβ)) t :=
eventually_of_mem h2K (Ξ» x hx, eventually_of_forall $
Ξ» t, hcg.convolution_integrand_bound_right L hg hx),
refine continuous_at_of_dominated _ this _ _,
{ exact eventually_of_forall
(Ξ» x, hf.ae_strongly_measurable.convolution_integrand_snd' L hg.ae_strongly_measurable) },
{ rw [integrable_indicator_iff hK'.measurable_set],
exact ((hf hK').norm.const_mul _).mul_const _ },
{ exact eventually_of_forall (Ξ» t, (L.continuousβ.compβ continuous_const $
hg.comp $ continuous_id.sub $ by apply continuous_const).continuous_at) }
end
/-- The convolution is continuous if one function is integrable and the other is bounded and
continuous. -/
lemma bdd_above.continuous_convolution_right_of_integrable
(hbg : bdd_above (range (Ξ» x, βg xβ))) (hf : integrable f ΞΌ) (hg : continuous g) :
continuous (f β[L, ΞΌ] g) :=
begin
refine continuous_iff_continuous_at.mpr (Ξ» xβ, _),
have : βαΆ x in π xβ, βα΅ (t : G) βΞΌ,
βL (f t) (g (x - t))β β€ βLβ * βf tβ * (β¨ i, βg iβ),
{ refine eventually_of_forall (Ξ» x, eventually_of_forall $ Ξ» t, _),
refine (L.le_op_normβ _ _).trans _,
exact mul_le_mul_of_nonneg_left (le_csupr hbg $ x - t)
(mul_nonneg (norm_nonneg _) (norm_nonneg _)) },
refine continuous_at_of_dominated _ this _ _,
{ exact eventually_of_forall
(Ξ» x, hf.ae_strongly_measurable.convolution_integrand_snd' L hg.ae_strongly_measurable) },
{ exact (hf.norm.const_mul _).mul_const _ },
{ exact eventually_of_forall (Ξ» t, (L.continuousβ.compβ continuous_const $
hg.comp $ continuous_id.sub $ by apply continuous_const).continuous_at) }
end
/-- A version of `has_compact_support.continuous_convolution_right` that works if `G` is
not locally compact but requires that `g` is integrable. -/
lemma has_compact_support.continuous_convolution_right_of_integrable
(hcg : has_compact_support g) (hf : integrable f ΞΌ) (hg : continuous g) :
continuous (f β[L, ΞΌ] g) :=
(hg.norm.bdd_above_range_of_has_compact_support hcg.norm).continuous_convolution_right_of_integrable
L hf hg
end group
section comm_group
variables [add_comm_group G]
lemma support_convolution_subset : support (f β[L, ΞΌ] g) β support f + support g :=
(support_convolution_subset_swap L).trans (add_comm _ _).subset
variables [is_add_left_invariant ΞΌ] [is_neg_invariant ΞΌ]
section measurable
variables [has_measurable_neg G]
variables [has_measurable_add G]
variable (L)
/-- Commutativity of convolution -/
lemma convolution_flip : g β[L.flip, ΞΌ] f = f β[L, ΞΌ] g :=
begin
ext1 x,
simp_rw [convolution_def],
rw [β integral_sub_left_eq_self _ ΞΌ x],
simp_rw [sub_sub_self, flip_apply]
end
/-- The symmetric definition of convolution. -/
lemma convolution_eq_swap : (f β[L, ΞΌ] g) x = β« t, L (f (x - t)) (g t) βΞΌ :=
by { rw [β convolution_flip], refl }
/-- The symmetric definition of convolution where the bilinear operator is scalar multiplication. -/
lemma convolution_lsmul_swap {f : G β π} {g : G β F}:
(f β[lsmul π π, ΞΌ] g : G β F) x = β« t, f (x - t) β’ g t βΞΌ :=
convolution_eq_swap _
/-- The symmetric definition of convolution where the bilinear operator is multiplication. -/
lemma convolution_mul_swap [normed_space β π] [complete_space π] {f : G β π} {g : G β π} :
(f β[mul π π, ΞΌ] g) x = β« t, f (x - t) * g t βΞΌ :=
convolution_eq_swap _
/-- The convolution of two even functions is also even. -/
lemma convolution_neg_of_neg_eq (h1 : βα΅ x βΞΌ, f (-x) = f x) (h2 : βα΅ x βΞΌ, g (-x) = g x) :
(f β[L, ΞΌ] g) (-x) = (f β[L, ΞΌ] g) x :=
calc β« (t : G), (L (f t)) (g (-x - t)) βΞΌ
= β« (t : G), (L (f (-t))) (g (x + t)) βΞΌ :
begin
apply integral_congr_ae,
filter_upwards [h1, (eventually_add_left_iff ΞΌ x).2 h2] with t ht h't,
simp_rw [ht, β h't, neg_add'],
end
... = β« (t : G), (L (f t)) (g (x - t)) βΞΌ :
by { rw β integral_neg_eq_self, simp only [neg_neg, β sub_eq_add_neg] }
end measurable
variables [topological_space G]
variables [topological_add_group G]
variables [borel_space G]
variables [second_countable_topology G]
lemma has_compact_support.continuous_convolution_left [locally_compact_space G] [t2_space G]
(hcf : has_compact_support f) (hf : continuous f) (hg : locally_integrable g ΞΌ) :
continuous (f β[L, ΞΌ] g) :=
by { rw [β convolution_flip], exact hcf.continuous_convolution_right L.flip hg hf }
lemma bdd_above.continuous_convolution_left_of_integrable
(hbf : bdd_above (range (Ξ» x, βf xβ))) (hf : continuous f) (hg : integrable g ΞΌ) :
continuous (f β[L, ΞΌ] g) :=
by { rw [β convolution_flip], exact hbf.continuous_convolution_right_of_integrable L.flip hg hf }
/-- A version of `has_compact_support.continuous_convolution_left` that works if `G` is
not locally compact but requires that `g` is integrable. -/
lemma has_compact_support.continuous_convolution_left_of_integrable
(hcf : has_compact_support f) (hf : continuous f) (hg : integrable g ΞΌ) :
continuous (f β[L, ΞΌ] g) :=
by { rw [β convolution_flip], exact hcf.continuous_convolution_right_of_integrable L.flip hg hf }
end comm_group
section normed_add_comm_group
variables [seminormed_add_comm_group G]
/-- Compute `(f β g) xβ` if the support of the `f` is within `metric.ball 0 R`, and `g` is constant
on `metric.ball xβ R`.
We can simplify the RHS further if we assume `f` is integrable, but also if `L = (β’)` or more
generally if `L` has a `antilipschitz_with`-condition. -/
lemma convolution_eq_right' {xβ : G} {R : β}
(hf : support f β ball (0 : G) R)
(hg : β x β ball xβ R, g x = g xβ) : (f β[L, ΞΌ] g) xβ = β« t, L (f t) (g xβ) βΞΌ :=
begin
have h2 : β t, L (f t) (g (xβ - t)) = L (f t) (g xβ),
{ intro t, by_cases ht : t β support f,
{ have h2t := hf ht,
rw [mem_ball_zero_iff] at h2t,
specialize hg (xβ - t),
rw [sub_eq_add_neg, add_mem_ball_iff_norm, norm_neg, β sub_eq_add_neg] at hg,
rw [hg h2t] },
{ rw [nmem_support] at ht,
simp_rw [ht, L.map_zeroβ] } },
simp_rw [convolution_def, h2],
end
variables [borel_space G] [second_countable_topology G]
variables [is_add_left_invariant ΞΌ] [sigma_finite ΞΌ]
/-- Approximate `(f β g) xβ` if the support of the `f` is bounded within a ball, and `g` is near
`g xβ` on a ball with the same radius around `xβ`. See `dist_convolution_le` for a special case.
We can simplify the second argument of `dist` further if we add some extra type-classes on `E`
and `π` or if `L` is scalar multiplication. -/
lemma dist_convolution_le' {xβ : G} {R Ξ΅ : β} {zβ : E'}
(hΞ΅ : 0 β€ Ξ΅)
(hif : integrable f ΞΌ)
(hf : support f β ball (0 : G) R)
(hmg : ae_strongly_measurable g ΞΌ)
(hg : β x β ball xβ R, dist (g x) zβ β€ Ξ΅) :
dist ((f β[L, ΞΌ] g : G β F) xβ) (β« t, L (f t) zβ βΞΌ) β€ βLβ * β« x, βf xβ βΞΌ * Ξ΅ :=
begin
have hfg : convolution_exists_at f g xβ L ΞΌ,
{ refine bdd_above.convolution_exists_at L _ metric.is_open_ball.measurable_set
(subset_trans _ hf) hif.integrable_on hif.ae_strongly_measurable hmg,
swap, { refine Ξ» t, mt (Ξ» ht : f t = 0, _), simp_rw [ht, L.map_zeroβ] },
rw [bdd_above_def],
refine β¨βzββ + Ξ΅, _β©,
rintro _ β¨x, hx, rflβ©,
refine norm_le_norm_add_const_of_dist_le (hg x _),
rwa [mem_ball_iff_norm, norm_sub_rev, β mem_ball_zero_iff] },
have h2 : β t, dist (L (f t) (g (xβ - t))) (L (f t) zβ) β€ βL (f t)β * Ξ΅,
{ intro t, by_cases ht : t β support f,
{ have h2t := hf ht,
rw [mem_ball_zero_iff] at h2t,
specialize hg (xβ - t),
rw [sub_eq_add_neg, add_mem_ball_iff_norm, norm_neg, β sub_eq_add_neg] at hg,
refine ((L (f t)).dist_le_op_norm _ _).trans _,
exact mul_le_mul_of_nonneg_left (hg h2t) (norm_nonneg _) },
{ rw [nmem_support] at ht,
simp_rw [ht, L.map_zeroβ, L.map_zero, norm_zero, zero_mul, dist_self] } },
simp_rw [convolution_def],
simp_rw [dist_eq_norm] at h2 β’,
rw [β integral_sub hfg.integrable], swap, { exact (L.flip zβ).integrable_comp hif },
refine (norm_integral_le_of_norm_le ((L.integrable_comp hif).norm.mul_const Ξ΅)
(eventually_of_forall h2)).trans _,
rw [integral_mul_right],
refine mul_le_mul_of_nonneg_right _ hΞ΅,
have h3 : β t, βL (f t)β β€ βLβ * βf tβ,
{ intros t,
exact L.le_op_norm (f t) },
refine (integral_mono (L.integrable_comp hif).norm (hif.norm.const_mul _) h3).trans_eq _,
rw [integral_mul_left]
end
variables [normed_space β E] [normed_space β E'] [complete_space E']
/-- Approximate `f β g` if the support of the `f` is bounded within a ball, and `g` is near `g xβ`
on a ball with the same radius around `xβ`.
This is a special case of `dist_convolution_le'` where `L` is `(β’)`, `f` has integral 1 and `f` is
nonnegative. -/
lemma dist_convolution_le {f : G β β} {xβ : G} {R Ξ΅ : β} {zβ : E'}
(hΞ΅ : 0 β€ Ξ΅)
(hf : support f β ball (0 : G) R)
(hnf : β x, 0 β€ f x)
(hintf : β« x, f x βΞΌ = 1)
(hmg : ae_strongly_measurable g ΞΌ)
(hg : β x β ball xβ R, dist (g x) zβ β€ Ξ΅) :
dist ((f β[lsmul β β, ΞΌ] g : G β E') xβ) zβ β€ Ξ΅ :=
begin
have hif : integrable f ΞΌ,
{ by_contra hif, exact zero_ne_one ((integral_undef hif).symm.trans hintf) },
convert (dist_convolution_le' _ hΞ΅ hif hf hmg hg).trans _,
{ simp_rw [lsmul_apply, integral_smul_const, hintf, one_smul] },
{ simp_rw [real.norm_of_nonneg (hnf _), hintf, mul_one],
exact (mul_le_mul_of_nonneg_right op_norm_lsmul_le hΞ΅).trans_eq (one_mul Ξ΅) }
end
/-- `(Ο i β g i) (k i)` tends to `zβ` as `i` tends to some filter `l` if
* `Ο` is a sequence of nonnegative functions with integral `1` as `i` tends to `l`;
* The support of `Ο` tends to small neighborhoods around `(0 : G)` as `i` tends to `l`;
* `g i` is `mu`-a.e. strongly measurable as `i` tends to `l`;
* `g i x` tends to `zβ` as `(i, x)` tends to `l ΓαΆ π xβ`;
* `k i` tends to `xβ`.
See also `cont_diff_bump_of_inner.convolution_tendsto_right`.
-/
lemma convolution_tendsto_right
{ΞΉ} {g : ΞΉ β G β E'} {l : filter ΞΉ} {xβ : G} {zβ : E'}
{Ο : ΞΉ β G β β} {k : ΞΉ β G}
(hnΟ : βαΆ i in l, β x, 0 β€ Ο i x)
(hiΟ : βαΆ i in l, β« x, Ο i x βΞΌ = 1) -- todo: we could weaken this to "the integral tends to 1"
(hΟ : tendsto (Ξ» n, support (Ο n)) l (π 0).small_sets)
(hmg : βαΆ i in l, ae_strongly_measurable (g i) ΞΌ)
(hcg : tendsto (uncurry g) (l ΓαΆ π xβ) (π zβ))
(hk : tendsto k l (π xβ)) :
tendsto (Ξ» i : ΞΉ, (Ο i β[lsmul β β, ΞΌ] g i : G β E') (k i)) l (π zβ) :=
begin
simp_rw [tendsto_small_sets_iff] at hΟ,
rw [metric.tendsto_nhds] at hcg β’,
simp_rw [metric.eventually_prod_nhds_iff] at hcg,
intros Ξ΅ hΞ΅,
have h2Ξ΅ : 0 < Ξ΅ / 3 := div_pos hΞ΅ (by norm_num),
obtain β¨p, hp, Ξ΄, hΞ΄, hgΞ΄β© := hcg _ h2Ξ΅,
dsimp only [uncurry] at hgΞ΄,
have h2k := hk.eventually (ball_mem_nhds xβ $ half_pos hΞ΄),
have h2Ο := (hΟ (ball (0 : G) _) $ ball_mem_nhds _ (half_pos hΞ΄)),
filter_upwards [hp, h2k, h2Ο, hnΟ, hiΟ, hmg] with i hpi hki hΟi hnΟi hiΟi hmgi,
have hgi : dist (g i (k i)) zβ < Ξ΅ / 3 := hgΞ΄ hpi (hki.trans $ half_lt_self hΞ΄),
have h1 : β x' β ball (k i) (Ξ΄ / 2), dist (g i x') (g i (k i)) β€ Ξ΅ / 3 + Ξ΅ / 3,
{ intros x' hx',
refine (dist_triangle_right _ _ _).trans (add_le_add (hgΞ΄ hpi _).le hgi.le),
exact ((dist_triangle _ _ _).trans_lt (add_lt_add hx'.out hki)).trans_eq (add_halves Ξ΄) },
have := dist_convolution_le (add_pos h2Ξ΅ h2Ξ΅).le hΟi hnΟi hiΟi hmgi h1,
refine ((dist_triangle _ _ _).trans_lt (add_lt_add_of_le_of_lt this hgi)).trans_eq _,
field_simp, ring_nf
end
end normed_add_comm_group
namespace cont_diff_bump_of_inner
variables {n : ββ}
variables [normed_space β E']
variables [inner_product_space β G]
variables [complete_space E']
variables {a : G} {Ο : cont_diff_bump_of_inner (0 : G)}
/-- If `Ο` is a bump function, compute `(Ο β g) xβ` if `g` is constant on `metric.ball xβ Ο.R`. -/
lemma convolution_eq_right {xβ : G}
(hg : β x β ball xβ Ο.R, g x = g xβ) : (Ο β[lsmul β β, ΞΌ] g : G β E') xβ = integral ΞΌ Ο β’ g xβ :=
by simp_rw [convolution_eq_right' _ Ο.support_eq.subset hg, lsmul_apply, integral_smul_const]
variables [borel_space G]
variables [is_locally_finite_measure ΞΌ] [is_open_pos_measure ΞΌ]
variables [finite_dimensional β G]
/-- If `Ο` is a normed bump function, compute `Ο β g` if `g` is constant on `metric.ball xβ Ο.R`. -/
lemma normed_convolution_eq_right {xβ : G}
(hg : β x β ball xβ Ο.R, g x = g xβ) : (Ο.normed ΞΌ β[lsmul β β, ΞΌ] g : G β E') xβ = g xβ :=
by { simp_rw [convolution_eq_right' _ Ο.support_normed_eq.subset hg, lsmul_apply],
exact integral_normed_smul Ο ΞΌ (g xβ) }
variables [is_add_left_invariant ΞΌ]
/-- If `Ο` is a normed bump function, approximate `(Ο β g) xβ` if `g` is near `g xβ` on a ball with
radius `Ο.R` around `xβ`. -/
lemma dist_normed_convolution_le {xβ : G} {Ξ΅ : β}
(hmg : ae_strongly_measurable g ΞΌ)
(hg : β x β ball xβ Ο.R, dist (g x) (g xβ) β€ Ξ΅) :
dist ((Ο.normed ΞΌ β[lsmul β β, ΞΌ] g : G β E') xβ) (g xβ) β€ Ξ΅ :=
dist_convolution_le (by simp_rw [β dist_self (g xβ), hg xβ (mem_ball_self Ο.R_pos)])
Ο.support_normed_eq.subset Ο.nonneg_normed Ο.integral_normed hmg hg
/-- `(Ο i β g i) (k i)` tends to `zβ` as `i` tends to some filter `l` if
* `Ο` is a sequence of normed bump functions such that `(Ο i).R` tends to `0` as `i` tends to `l`;
* `g i` is `mu`-a.e. strongly measurable as `i` tends to `l`;
* `g i x` tends to `zβ` as `(i, x)` tends to `l ΓαΆ π xβ`;
* `k i` tends to `xβ`. -/
lemma convolution_tendsto_right {ΞΉ} {Ο : ΞΉ β cont_diff_bump_of_inner (0 : G)}
{g : ΞΉ β G β E'} {k : ΞΉ β G} {xβ : G} {zβ : E'} {l : filter ΞΉ}
(hΟ : tendsto (Ξ» i, (Ο i).R) l (π 0))
(hig : βαΆ i in l, ae_strongly_measurable (g i) ΞΌ)
(hcg : tendsto (uncurry g) (l ΓαΆ π xβ) (π zβ))
(hk : tendsto k l (π xβ)) :
tendsto (Ξ» i, ((Ξ» x, (Ο i).normed ΞΌ x) β[lsmul β β, ΞΌ] g i : G β E') (k i)) l (π zβ) :=
convolution_tendsto_right (eventually_of_forall $ Ξ» i, (Ο i).nonneg_normed)
(eventually_of_forall $ Ξ» i, (Ο i).integral_normed)
(tendsto_support_normed_small_sets hΟ) hig hcg hk
/-- Special case of `cont_diff_bump_of_inner.convolution_tendsto_right` where `g` is continuous,
and the limit is taken only in the first function. -/
lemma convolution_tendsto_right_of_continuous {ΞΉ} {Ο : ΞΉ β cont_diff_bump_of_inner (0 : G)}
{l : filter ΞΉ} (hΟ : tendsto (Ξ» i, (Ο i).R) l (π 0))
(hg : continuous g) (xβ : G) :
tendsto (Ξ» i, ((Ξ» x, (Ο i).normed ΞΌ x) β[lsmul β β, ΞΌ] g : G β E') xβ) l (π (g xβ)) :=
convolution_tendsto_right hΟ (eventually_of_forall $ Ξ» _, hg.ae_strongly_measurable)
((hg.tendsto xβ).comp tendsto_snd) tendsto_const_nhds
end cont_diff_bump_of_inner
end measurability
end nontrivially_normed_field
open_locale convolution
section is_R_or_C
variables [is_R_or_C π]
variables [normed_space π E]
variables [normed_space π E']
variables [normed_space π E'']
variables [normed_space β F] [normed_space π F]
variables {n : ββ}
variables [complete_space F]
variables [measurable_space G] {ΞΌ Ξ½ : measure G}
variables (L : E βL[π] E' βL[π] F)
section assoc
variables [normed_add_comm_group F'] [normed_space β F'] [normed_space π F'] [complete_space F']
variables [normed_add_comm_group F''] [normed_space β F''] [normed_space π F''] [complete_space F'']
variables {k : G β E''}
variables (Lβ : F βL[π] E'' βL[π] F')
variables (Lβ : E βL[π] F'' βL[π] F')
variables (Lβ : E' βL[π] E'' βL[π] F'')
variables [add_group G]
variables [sigma_finite ΞΌ] [sigma_finite Ξ½] [is_add_right_invariant ΞΌ]
lemma integral_convolution
[has_measurable_addβ G] [has_measurable_neg G]
[normed_space β E] [normed_space β E']
[complete_space E] [complete_space E']
(hf : integrable f Ξ½) (hg : integrable g ΞΌ) :
β« x, (f β[L, Ξ½] g) x βΞΌ = L (β« x, f x βΞ½) (β« x, g x βΞΌ) :=
begin
refine (integral_integral_swap (by apply hf.convolution_integrand L hg)).trans _,
simp_rw [integral_comp_comm _ (hg.comp_sub_right _), integral_sub_right_eq_self],
exact (L.flip (β« x, g x βΞΌ)).integral_comp_comm hf
end
variables [has_measurable_addβ G] [is_add_right_invariant Ξ½] [has_measurable_neg G]
/-- Convolution is associative. This has a weak but inconvenient integrability condition.
See also `convolution_assoc`. -/
lemma convolution_assoc' (hL : β (x : E) (y : E') (z : E''), Lβ (L x y) z = Lβ x (Lβ y z))
{xβ : G}
(hfg : βα΅ y βΞΌ, convolution_exists_at f g y L Ξ½)
(hgk : βα΅ x βΞ½, convolution_exists_at g k x Lβ ΞΌ)
(hi : integrable (uncurry (Ξ» x y, (Lβ (f y)) ((Lβ (g (x - y))) (k (xβ - x))))) (ΞΌ.prod Ξ½)) :
((f β[L, Ξ½] g) β[Lβ, ΞΌ] k) xβ = (f β[Lβ, Ξ½] (g β[Lβ, ΞΌ] k)) xβ :=
calc ((f β[L, Ξ½] g) β[Lβ, ΞΌ] k) xβ
= β« t, Lβ (β« s, L (f s) (g (t - s)) βΞ½) (k (xβ - t)) βΞΌ : rfl
... = β« t, β« s, Lβ (L (f s) (g (t - s))) (k (xβ - t)) βΞ½ βΞΌ :
integral_congr_ae (hfg.mono $ Ξ» t ht, ((Lβ.flip (k (xβ - t))).integral_comp_comm ht).symm)
... = β« t, β« s, Lβ (f s) (Lβ (g (t - s)) (k (xβ - t))) βΞ½ βΞΌ : by simp_rw hL
... = β« s, β« t, Lβ (f s) (Lβ (g (t - s)) (k (xβ - t))) βΞΌ βΞ½ : by rw [integral_integral_swap hi]
... = β« s, β« u, Lβ (f s) (Lβ (g u) (k ((xβ - s) - u))) βΞΌ βΞ½ : begin
congr', ext t,
rw [eq_comm, β integral_sub_right_eq_self _ t],
{ simp_rw [sub_sub_sub_cancel_right] },
{ apply_instance },
end
... = β« s, Lβ (f s) (β« u, Lβ (g u) (k ((xβ - s) - u)) βΞΌ) βΞ½ : begin
refine integral_congr_ae _,
refine ((quasi_measure_preserving_sub_left_of_right_invariant Ξ½ xβ).ae hgk).mono (Ξ» t ht, _),
exact (Lβ (f t)).integral_comp_comm ht,
end
... = (f β[Lβ, Ξ½] (g β[Lβ, ΞΌ] k)) xβ : rfl
/-- Convolution is associative. This requires that
* all maps are a.e. strongly measurable w.r.t one of the measures
* `f β[L, Ξ½] g` exists almost everywhere
* `βgβ β[ΞΌ] βkβ` exists almost everywhere
* `βfβ β[Ξ½] (βgβ β[ΞΌ] βkβ)` exists at `xβ` -/
lemma convolution_assoc (hL : β (x : E) (y : E') (z : E''), Lβ (L x y) z = Lβ x (Lβ y z))
{xβ : G}
(hf : ae_strongly_measurable f Ξ½)
(hg : ae_strongly_measurable g ΞΌ)
(hk : ae_strongly_measurable k ΞΌ)
(hfg : βα΅ y βΞΌ, convolution_exists_at f g y L Ξ½)
(hgk : βα΅ x βΞ½, convolution_exists_at (Ξ» x, βg xβ) (Ξ» x, βk xβ) x (mul β β) ΞΌ)
(hfgk : convolution_exists_at (Ξ» x, βf xβ) ((Ξ» x, βg xβ) β[mul β β, ΞΌ] (Ξ» x, βk xβ))
xβ (mul β β) Ξ½) :
((f β[L, Ξ½] g) β[Lβ, ΞΌ] k) xβ = (f β[Lβ, Ξ½] (g β[Lβ, ΞΌ] k)) xβ :=
begin
refine convolution_assoc' L Lβ Lβ Lβ hL hfg (hgk.mono $ Ξ» x hx, hx.of_norm Lβ hg hk) _,
/- the following is similar to `integrable.convolution_integrand` -/
have h_meas : ae_strongly_measurable
(uncurry (Ξ» x y, Lβ (f y) (Lβ (g x) (k (xβ - y - x))))) (ΞΌ.prod Ξ½),
{ refine Lβ.ae_strongly_measurable_compβ hf.snd _,
refine Lβ.ae_strongly_measurable_compβ hg.fst _,
refine (hk.mono' _).comp_measurable ((measurable_const.sub measurable_snd).sub measurable_fst),
refine quasi_measure_preserving.absolutely_continuous _,
refine quasi_measure_preserving.prod_of_left
((measurable_const.sub measurable_snd).sub measurable_fst) (eventually_of_forall $ Ξ» y, _),
dsimp only,
exact quasi_measure_preserving_sub_left_of_right_invariant ΞΌ _ },
have h2_meas : ae_strongly_measurable (Ξ» y, β« x, βLβ (f y) (Lβ (g x) (k (xβ - y - x)))β βΞΌ) Ξ½ :=
h_meas.prod_swap.norm.integral_prod_right',
have h3 : map (Ξ» z : G Γ G, (z.1 - z.2, z.2)) (ΞΌ.prod Ξ½) = ΞΌ.prod Ξ½ :=
(measure_preserving_sub_prod ΞΌ Ξ½).map_eq,
suffices : integrable (uncurry (Ξ» x y, Lβ (f y) (Lβ (g x) (k (xβ - y - x))))) (ΞΌ.prod Ξ½),
{ rw [β h3] at this,
convert this.comp_measurable (measurable_sub.prod_mk measurable_snd),
ext β¨x, yβ©,
simp_rw [uncurry, function.comp_apply, sub_sub_sub_cancel_right] },
simp_rw [integrable_prod_iff' h_meas],
refine β¨((quasi_measure_preserving_sub_left_of_right_invariant Ξ½ xβ).ae hgk).mono
(Ξ» t ht, (Lβ (f t)).integrable_comp $ ht.of_norm Lβ hg hk), _β©,
refine (hfgk.const_mul (βLββ * βLββ)).mono' h2_meas
(((quasi_measure_preserving_sub_left_of_right_invariant Ξ½ xβ).ae hgk).mono $ Ξ» t ht, _),
{ simp_rw [convolution_def, mul_apply', mul_mul_mul_comm βLββ βLββ, β integral_mul_left],
rw [real.norm_of_nonneg],
{ refine integral_mono_of_nonneg (eventually_of_forall $ Ξ» t, norm_nonneg _)
((ht.const_mul _).const_mul _) (eventually_of_forall $ Ξ» s, _),
refine (Lβ.le_op_normβ _ _).trans _,
refine mul_le_mul_of_nonneg_left _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)),
rw [β mul_assoc],
apply Lβ.le_op_normβ },
exact integral_nonneg (Ξ» x, norm_nonneg _) }
end
end assoc
variables [normed_add_comm_group G] [borel_space G] [normed_space π G]
lemma convolution_precompR_apply {g : G β E'' βL[π] E'}
(hf : locally_integrable f ΞΌ) (hcg : has_compact_support g) (hg : continuous g)
(xβ : G) (x : E'') : (f β[L.precompR E'', ΞΌ] g) xβ x = (f β[L, ΞΌ] (Ξ» a, g a x)) xβ :=
begin
rcases hcg.eq_zero_or_finite_dimensional π hg with rfl|fin_dim,
{ simp only [convolution, pi.zero_apply, integral_const, smul_zero, zero_apply,
_root_.map_zero] },
resetI,
haveI : proper_space G, from finite_dimensional.proper_is_R_or_C π G,
have := hcg.convolution_exists_right (L.precompR E'' : _) hf hg xβ,
simp_rw [convolution_def, continuous_linear_map.integral_apply this],
refl,
end
variables [sigma_finite ΞΌ] [is_add_left_invariant ΞΌ]
/-- Compute the total derivative of `f β g` if `g` is `C^1` with compact support and `f` is locally
integrable. To write down the total derivative as a convolution, we use
`continuous_linear_map.precompR`. -/
lemma has_compact_support.has_fderiv_at_convolution_right
(hcg : has_compact_support g) (hf : locally_integrable f ΞΌ) (hg : cont_diff π 1 g) (xβ : G) :
has_fderiv_at (f β[L, ΞΌ] g) ((f β[L.precompR G, ΞΌ] fderiv π g) xβ) xβ :=
begin
rcases hcg.eq_zero_or_finite_dimensional π hg.continuous with rfl|fin_dim,
{ have : fderiv π (0 : G β E') = 0, from fderiv_const (0 : E'),
simp only [this, convolution_zero, pi.zero_apply],
exact has_fderiv_at_const (0 : F) xβ },
resetI,
haveI : proper_space G, from finite_dimensional.proper_is_R_or_C π G,
set L' := L.precompR G,
have h1 : βαΆ x in π xβ, ae_strongly_measurable (Ξ» t, L (f t) (g (x - t))) ΞΌ :=
eventually_of_forall
(hf.ae_strongly_measurable.convolution_integrand_snd L hg.continuous.ae_strongly_measurable),
have h2 : β x, ae_strongly_measurable (Ξ» t, L' (f t) (fderiv π g (x - t))) ΞΌ,
{ exact hf.ae_strongly_measurable.convolution_integrand_snd L'
(hg.continuous_fderiv le_rfl).ae_strongly_measurable },
have h3 : β x t, has_fderiv_at (Ξ» x, g (x - t)) (fderiv π g (x - t)) x,
{ intros x t,
simpa using (hg.differentiable le_rfl).differentiable_at.has_fderiv_at.comp x
((has_fderiv_at_id x).sub (has_fderiv_at_const t x)) },
let K' := - tsupport (fderiv π g) + closed_ball xβ 1,
have hK' : is_compact K' := (hcg.fderiv π).neg.add (is_compact_closed_ball xβ 1),
refine has_fderiv_at_integral_of_dominated_of_fderiv_le
zero_lt_one h1 _ (h2 xβ) _ _ _,
{ exact K'.indicator (Ξ» t, βL'β * βf tβ * (β¨ x, βfderiv π g xβ)) },
{ exact hcg.convolution_exists_right L hf hg.continuous xβ },
{ refine eventually_of_forall (Ξ» t x hx, _),
exact (hcg.fderiv π).convolution_integrand_bound_right L'
(hg.continuous_fderiv le_rfl) (ball_subset_closed_ball hx) },
{ rw [integrable_indicator_iff hK'.measurable_set],
exact ((hf hK').norm.const_mul _).mul_const _ },
{ exact eventually_of_forall (Ξ» t x hx, (L _).has_fderiv_at.comp x (h3 x t)) },
end
lemma has_compact_support.has_fderiv_at_convolution_left [is_neg_invariant ΞΌ]
(hcf : has_compact_support f) (hf : cont_diff π 1 f) (hg : locally_integrable g ΞΌ) (xβ : G) :
has_fderiv_at (f β[L, ΞΌ] g) ((fderiv π f β[L.precompL G, ΞΌ] g) xβ) xβ :=
begin
simp only [β convolution_flip] {single_pass := tt},
exact hcf.has_fderiv_at_convolution_right L.flip hg hf xβ,
end
lemma has_compact_support.cont_diff_convolution_right
(hcg : has_compact_support g) (hf : locally_integrable f ΞΌ) (hg : cont_diff π n g) :
cont_diff π n (f β[L, ΞΌ] g) :=
begin
rcases hcg.eq_zero_or_finite_dimensional π hg.continuous with rfl|fin_dim,
{ simp only [convolution_zero], exact cont_diff_zero_fun, },
resetI,
haveI : proper_space G, from finite_dimensional.proper_is_R_or_C π G,
induction n using enat.nat_induction with n ih ih generalizing g,
{ rw [cont_diff_zero] at hg β’,
exact hcg.continuous_convolution_right L hf hg },
{ have h : β x, has_fderiv_at (f β[L, ΞΌ] g) ((f β[L.precompR G, ΞΌ] fderiv π g) x) x :=
hcg.has_fderiv_at_convolution_right L hf hg.one_of_succ,
rw cont_diff_succ_iff_fderiv_apply,
split,
{ exact Ξ» xβ, β¨_, h xββ© },
{ simp_rw [fderiv_eq h, convolution_precompR_apply L hf (hcg.fderiv π)
(hg.one_of_succ.continuous_fderiv le_rfl)],
intro x,
refine ih _ _,
{ refine @has_compact_support.comp_left _ _ _ _ _ _ (Ξ» (G : _ βL[π] _), G x) _
(hcg.fderiv π) (continuous_linear_map.zero_apply x) },
{ revert x, rw [β cont_diff_clm_apply_iff],
exact (cont_diff_succ_iff_fderiv.mp hg).2 } } },
{ rw [cont_diff_top] at hg β’, exact Ξ» n, ih n hcg (hg n) }
end
lemma has_compact_support.cont_diff_convolution_left [is_neg_invariant ΞΌ]
(hcf : has_compact_support f) (hf : cont_diff π n f) (hg : locally_integrable g ΞΌ) :
cont_diff π n (f β[L, ΞΌ] g) :=
by { rw [β convolution_flip], exact hcf.cont_diff_convolution_right L.flip hg hf }
end is_R_or_C
section real
/-! The one-variable case -/
variables [is_R_or_C π]
variables [normed_space π E]
variables [normed_space π E']
variables [normed_space β F] [normed_space π F]
variables {fβ : π β E} {gβ : π β E'}
variables {n : ββ}
variables (L : E βL[π] E' βL[π] F)
variables [complete_space F]
variables {ΞΌ : measure π}
variables [is_add_left_invariant ΞΌ] [sigma_finite ΞΌ]
lemma has_compact_support.has_deriv_at_convolution_right
(hf : locally_integrable fβ ΞΌ) (hcg : has_compact_support gβ) (hg : cont_diff π 1 gβ)
(xβ : π) :
has_deriv_at (fβ β[L, ΞΌ] gβ) ((fβ β[L, ΞΌ] deriv gβ) xβ) xβ :=
begin
convert (hcg.has_fderiv_at_convolution_right L hf hg xβ).has_deriv_at,
rw [convolution_precompR_apply L hf (hcg.fderiv π) (hg.continuous_fderiv le_rfl)],
refl,
end
lemma has_compact_support.has_deriv_at_convolution_left [is_neg_invariant ΞΌ]
(hcf : has_compact_support fβ) (hf : cont_diff π 1 fβ)
(hg : locally_integrable gβ ΞΌ) (xβ : π) :
has_deriv_at (fβ β[L, ΞΌ] gβ) ((deriv fβ β[L, ΞΌ] gβ) xβ) xβ :=
begin
simp only [β convolution_flip] {single_pass := tt},
exact hcf.has_deriv_at_convolution_right L.flip hg hf xβ,
end
end real
|
d48aeeac48db6504781a304c9ce63343f1eec076 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/matrix/finite_dimensional.lean | 1930c3fab027cd497becdc1a3529d63a6e7de7ed | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 1,993 | lean | /-
Copyright (c) 2019 Johannes HΓΆlzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes HΓΆlzl, Patrick Massot, Casper Putz, Anne Baanen
-/
import data.matrix.basic
import linear_algebra.finite_dimensional
import linear_algebra.free_module.finite.matrix
import linear_algebra.matrix.to_lin
/-!
# The finite-dimensional space of matrices
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file shows that `m` by `n` matrices form a finite-dimensional space.
Note that this is proven more generally elsewhere over modules as `module.finite.matrix`; this file
exists only to provide an entry in the instance list for `finite_dimensional`.
## Main definitions
* `matrix.finite_dimensional`: matrices form a finite dimensional vector space over a field `K`
* `linear_map.finite_dimensional`
## Tags
matrix, finite dimensional, findim, finrank
-/
universes u v
namespace matrix
section finite_dimensional
variables {m n : Type*} {R : Type v} [field R]
instance [finite m] [finite n] : finite_dimensional R (matrix m n R) :=
module.finite.matrix
end finite_dimensional
end matrix
namespace linear_map
variables {K : Type*} [field K]
variables {V : Type*} [add_comm_group V] [module K V] [finite_dimensional K V]
variables {W : Type*} [add_comm_group W] [module K W] [finite_dimensional K W]
instance finite_dimensional : finite_dimensional K (V ββ[K] W) :=
module.finite.linear_map _ _
variables {A : Type*} [ring A] [algebra K A] [module A V] [is_scalar_tower K A V]
[module A W] [is_scalar_tower K A W]
/-- Linear maps over a `k`-algebra are finite dimensional (over `k`) if both the source and
target are, as they form a subspace of all `k`-linear maps. -/
instance finite_dimensional' : finite_dimensional K (V ββ[A] W) :=
finite_dimensional.of_injective (restrict_scalars_linear_map K A V W)
(restrict_scalars_injective _)
end linear_map
|
78d9d8960538e255befe9798d50411da3f2b14ef | 097294e9b80f0d9893ac160b9c7219aa135b51b9 | /instructor/types/prod/product_types.lean | a8399e741b66270df32a45b22971a3928a8cc51d | [] | no_license | AbigailCastro17/CS2102-Discrete-Math | cf296251be9418ce90206f5e66bde9163e21abf9 | d741e4d2d6a9b2e0c8380e51706218b8f608cee4 | refs/heads/main | 1,682,891,087,358 | 1,621,401,341,000 | 1,621,401,341,000 | 368,749,959 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,038 | lean | -- Product types, record types, structures, tuples
-- Polymorphic types and functions
namespace hidden
inductive prod_nat_nat : Type
| mk : β β β β prod_nat_nat
-- Polymorphic data type! Yay!
inductive prod_S_T (S T : Type) : Type
| mk: S β T β prod_S_T
def p1 := prod_nat_nat.mk 5 3
def p2 := prod_nat_nat.mk 4 0
-- Polymorphic
def p3 := prod_S_T.mk "String!" tt
def p4 := prod_S_T.mk tt 4
def p5 := prod_S_T.mk tt ff
-- inspector/getter
def fst_nat_nat : prod_nat_nat β β :=
Ξ» (p : prod_nat_nat),
match p with
| (prod_nat_nat.mk x _) := x
end
-- polymorphic
def fst_S_T (S T : Type) : (prod_S_T S T) β S :=
Ξ» (p : prod_S_T S T),
match p with
| (prod_S_T.mk x _) := x
end
def snd_nat_nat : prod_nat_nat β β :=
Ξ» (p : prod_nat_nat),
match p with
| (prod_nat_nat.mk _ y) := y
end
-- polymorphic
def snd_S_T (S T : Type) : (prod_S_T S T) β T :=
Ξ» (p : prod_S_T S T),
match p with
| (prod_S_T.mk _ y) := y
end
#reduce snd_S_T string bool p3
/-
Takes a pair, p, and a nat, n, and returns a new
pair, like p, but with n as its new first element.
-/
def set_fst_nat_nat : prod_nat_nat β β β prod_nat_nat :=
Ξ» (p : prod_nat_nat) (n : β),
prod_nat_nat.mk n (snd_nat_nat p)
/-
-- polymorphic
Takes an S-T pair, p, and an S object, s, and returns a
new S-T pair like p but with s as a new first value
-/
def set_fst_S_T (S T : Type) : (prod_S_T S T) β S β prod_S_T S T :=
Ξ» (p : prod_S_T S T) (s : S),
prod_S_T.mk s (snd_S_T S T p)
def set_snd_nat_nat : prod_nat_nat β β β prod_nat_nat :=
Ξ» p n,
prod_nat_nat.mk (fst_nat_nat p) n
def swap_nat_nat : prod_nat_nat β prod_nat_nat :=
Ξ» p,
match p with
| (prod_nat_nat.mk x y) := prod_nat_nat.mk y x
end
#eval fst_nat_nat p1
#reduce set_fst_nat_nat p1 9
#reduce set_snd_nat_nat p1 9
#reduce swap_nat_nat p1
-- distance
-- pairwise addition
end hidden |
0b438d9488e946a3bcc3be56fdd96425bde78a1d | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/fintype/big_operators.lean | c34174eba89f20cf0086fe28bbe740b86fa19df9 | [
"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 | 10,065 | 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 data.fintype.option
import data.fintype.powerset
import data.fintype.sigma
import data.fintype.sum
import data.fintype.vector
import algebra.big_operators.ring
import algebra.big_operators.option
/-!
Results about "big operations" over a `fintype`, and consequent
results about cardinalities of certain types.
## Implementation note
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This content had previously been in `data.fintype.basic`, but was moved here to avoid
requiring `algebra.big_operators` (and hence many other imports) as a
dependency of `fintype`.
However many of the results here really belong in `algebra.big_operators.basic`
and should be moved at some point.
-/
universes u v
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*}
open_locale big_operators
namespace fintype
@[to_additive]
lemma prod_bool [comm_monoid Ξ±] (f : bool β Ξ±) : β b, f b = f tt * f ff := by simp
lemma card_eq_sum_ones {Ξ±} [fintype Ξ±] : fintype.card Ξ± = β a : Ξ±, 1 :=
finset.card_eq_sum_ones _
section
open finset
variables {ΞΉ : Type*} [decidable_eq ΞΉ] [fintype ΞΉ]
@[to_additive]
lemma prod_extend_by_one [comm_monoid Ξ±] (s : finset ΞΉ) (f : ΞΉ β Ξ±) :
β i, (if i β s then f i else 1) = β i in s, f i :=
by rw [β prod_filter, filter_mem_eq_inter, univ_inter]
end
section
variables {M : Type*} [fintype Ξ±] [comm_monoid M]
@[to_additive]
lemma prod_eq_one (f : Ξ± β M) (h : β a, f a = 1) :
(β a, f a) = 1 :=
finset.prod_eq_one $ Ξ» a ha, h a
@[to_additive]
lemma prod_congr (f g : Ξ± β M) (h : β a, f a = g a) :
(β a, f a) = β a, g a :=
finset.prod_congr rfl $ Ξ» a ha, h a
@[to_additive]
lemma prod_eq_single {f : Ξ± β M} (a : Ξ±) (h : β x β a, f x = 1) :
(β x, f x) = f a :=
finset.prod_eq_single a (Ξ» x _ hx, h x hx) $ Ξ» ha, (ha (finset.mem_univ a)).elim
@[to_additive]
lemma prod_eq_mul {f : Ξ± β M} (a b : Ξ±) (hβ : a β b) (hβ : β x, x β a β§ x β b β f x = 1) :
(β x, f x) = (f a) * (f b) :=
begin
apply finset.prod_eq_mul a b hβ (Ξ» x _ hx, hβ x hx);
exact Ξ» hc, (hc (finset.mem_univ _)).elim
end
/-- If a product of a `finset` of a subsingleton type has a given
value, so do the terms in that product. -/
@[to_additive "If a sum of a `finset` of a subsingleton type has a given
value, so do the terms in that sum."]
lemma eq_of_subsingleton_of_prod_eq {ΞΉ : Type*} [subsingleton ΞΉ] {s : finset ΞΉ}
{f : ΞΉ β M} {b : M} (h : β i in s, f i = b) : β i β s, f i = b :=
finset.eq_of_card_le_one_of_prod_eq (finset.card_le_one_of_subsingleton s) h
end
end fintype
open finset
section
variables {M : Type*} [fintype Ξ±] [comm_monoid M]
@[simp, to_additive]
lemma fintype.prod_option (f : option Ξ± β M) : β i, f i = f none * β i, f (some i) :=
finset.prod_insert_none f univ
end
open finset
@[simp] theorem fintype.card_sigma {Ξ± : Type*} (Ξ² : Ξ± β Type*)
[fintype Ξ±] [β a, fintype (Ξ² a)] :
fintype.card (sigma Ξ²) = β a, fintype.card (Ξ² a) :=
card_sigma _ _
@[simp] lemma finset.card_pi [decidable_eq Ξ±] {Ξ΄ : Ξ± β Type*}
(s : finset Ξ±) (t : Ξ a, finset (Ξ΄ a)) :
(s.pi t).card = β a in s, card (t a) :=
multiset.card_pi _ _
@[simp] lemma fintype.card_pi_finset [decidable_eq Ξ±] [fintype Ξ±]
{Ξ΄ : Ξ± β Type*} (t : Ξ a, finset (Ξ΄ a)) :
(fintype.pi_finset t).card = β a, card (t a) :=
by simp [fintype.pi_finset, card_map]
@[simp] lemma fintype.card_pi {Ξ² : Ξ± β Type*} [decidable_eq Ξ±] [fintype Ξ±]
[f : Ξ a, fintype (Ξ² a)] : fintype.card (Ξ a, Ξ² a) = β a, fintype.card (Ξ² a) :=
fintype.card_pi_finset _
-- FIXME ouch, this should be in the main file.
@[simp] lemma fintype.card_fun [decidable_eq Ξ±] [fintype Ξ±] [fintype Ξ²] :
fintype.card (Ξ± β Ξ²) = fintype.card Ξ² ^ fintype.card Ξ± :=
by rw [fintype.card_pi, finset.prod_const]; refl
@[simp] lemma card_vector [fintype Ξ±] (n : β) :
fintype.card (vector Ξ± n) = fintype.card Ξ± ^ n :=
by rw fintype.of_equiv_card; simp
@[simp, to_additive]
lemma finset.prod_attach_univ [fintype Ξ±] [comm_monoid Ξ²] (f : {a : Ξ± // a β @univ Ξ± _} β Ξ²) :
β x in univ.attach, f x = β x, f β¨x, (mem_univ _)β© :=
fintype.prod_equiv (equiv.subtype_univ_equiv (Ξ» x, mem_univ _)) _ _ (Ξ» x, by simp)
/-- Taking a product over `univ.pi t` is the same as taking the product over `fintype.pi_finset t`.
`univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ
in the type of their element, `univ.pi t` is a `finset (Ξ a β univ, t a)` and
`fintype.pi_finset t` is a `finset (Ξ a, t a)`. -/
@[to_additive "Taking a sum over `univ.pi t` is the same as taking the sum over
`fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`,
but differ in the type of their element, `univ.pi t` is a `finset (Ξ a β univ, t a)` and
`fintype.pi_finset t` is a `finset (Ξ a, t a)`."]
lemma finset.prod_univ_pi [decidable_eq Ξ±] [fintype Ξ±] [comm_monoid Ξ²]
{Ξ΄ : Ξ± β Type*} {t : Ξ (a : Ξ±), finset (Ξ΄ a)}
(f : (Ξ (a : Ξ±), a β (univ : finset Ξ±) β Ξ΄ a) β Ξ²) :
β x in univ.pi t, f x = β x in fintype.pi_finset t, f (Ξ» a _, x a) :=
prod_bij (Ξ» x _ a, x a (mem_univ _))
(by simp)
(by simp)
(by simp [function.funext_iff] {contextual := tt})
(Ξ» x hx, β¨Ξ» a _, x a, by simp * at *β©)
/-- The product over `univ` of a sum can be written as a sum over the product of sets,
`fintype.pi_finset`. `finset.prod_sum` is an alternative statement when the product is not
over `univ` -/
lemma finset.prod_univ_sum [decidable_eq Ξ±] [fintype Ξ±] [comm_semiring Ξ²] {Ξ΄ : Ξ± β Type u_1}
[Ξ (a : Ξ±), decidable_eq (Ξ΄ a)] {t : Ξ (a : Ξ±), finset (Ξ΄ a)}
{f : Ξ (a : Ξ±), Ξ΄ a β Ξ²} :
β a, β b in t a, f a b = β p in fintype.pi_finset t, β x, f x (p x) :=
by simp only [finset.prod_attach_univ, prod_sum, finset.sum_univ_pi]
/-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a fintype of cardinality `n`
gives `(a + b)^n`. The "good" proof involves expanding along all coordinates using the fact that
`x^n` is multilinear, but multilinear maps are only available now over rings, so we give instead
a proof reducing to the usual binomial theorem to have a result over semirings. -/
lemma fintype.sum_pow_mul_eq_add_pow
(Ξ± : Type*) [fintype Ξ±] {R : Type*} [comm_semiring R] (a b : R) :
β s : finset Ξ±, a ^ s.card * b ^ (fintype.card Ξ± - s.card) =
(a + b) ^ (fintype.card Ξ±) :=
finset.sum_pow_mul_eq_add_pow _ _ _
@[to_additive]
lemma function.bijective.prod_comp [fintype Ξ±] [fintype Ξ²] [comm_monoid Ξ³] {f : Ξ± β Ξ²}
(hf : function.bijective f) (g : Ξ² β Ξ³) :
β i, g (f i) = β i, g i :=
fintype.prod_bijective f hf _ _ (Ξ» x, rfl)
@[to_additive]
lemma equiv.prod_comp [fintype Ξ±] [fintype Ξ²] [comm_monoid Ξ³] (e : Ξ± β Ξ²) (f : Ξ² β Ξ³) :
β i, f (e i) = β i, f i :=
e.bijective.prod_comp f
@[to_additive]
lemma equiv.prod_comp' [fintype Ξ±] [fintype Ξ²] [comm_monoid Ξ³] (e : Ξ± β Ξ²) (f : Ξ± β Ξ³) (g : Ξ² β Ξ³)
(h : β i, f i = g (e i)) : β i, f i = β i, g i :=
(show f = g β e, from funext h).symm βΈ e.prod_comp _
/-- It is equivalent to compute the product of a function over `fin n` or `finset.range n`. -/
@[to_additive "It is equivalent to sum a function over `fin n` or `finset.range n`."]
lemma fin.prod_univ_eq_prod_range [comm_monoid Ξ±] (f : β β Ξ±) (n : β) :
β i : fin n, f i = β i in range n, f i :=
calc (β i : fin n, f i) = β i : {x // x β range n}, f i :
(fin.equiv_subtype.trans (equiv.subtype_equiv_right (by simp))).prod_comp' _ _ (by simp)
... = β i in range n, f i : by rw [β attach_eq_univ, prod_attach]
@[to_additive]
lemma finset.prod_fin_eq_prod_range [comm_monoid Ξ²] {n : β} (c : fin n β Ξ²) :
β i, c i = β i in finset.range n, if h : i < n then c β¨i, hβ© else 1 :=
begin
rw [β fin.prod_univ_eq_prod_range, finset.prod_congr rfl],
rintros β¨i, hiβ© _,
simp only [fin.coe_eq_val, hi, dif_pos]
end
@[to_additive]
lemma finset.prod_to_finset_eq_subtype {M : Type*} [comm_monoid M] [fintype Ξ±]
(p : Ξ± β Prop) [decidable_pred p] (f : Ξ± β M) :
β a in {x | p x}.to_finset, f a = β a : subtype p, f a :=
by { rw β finset.prod_subtype, simp }
@[to_additive] lemma finset.prod_fiberwise [decidable_eq Ξ²] [fintype Ξ²] [comm_monoid Ξ³]
(s : finset Ξ±) (f : Ξ± β Ξ²) (g : Ξ± β Ξ³) :
β b : Ξ², β a in s.filter (Ξ» a, f a = b), g a = β a in s, g a :=
finset.prod_fiberwise_of_maps_to (Ξ» x _, mem_univ _) _
@[to_additive]
lemma fintype.prod_fiberwise [fintype Ξ±] [decidable_eq Ξ²] [fintype Ξ²] [comm_monoid Ξ³]
(f : Ξ± β Ξ²) (g : Ξ± β Ξ³) :
(β b : Ξ², β a : {a // f a = b}, g (a : Ξ±)) = β a, g a :=
begin
rw [β (equiv.sigma_fiber_equiv f).prod_comp, β univ_sigma_univ, prod_sigma],
refl
end
lemma fintype.prod_dite [fintype Ξ±] {p : Ξ± β Prop} [decidable_pred p]
[comm_monoid Ξ²] (f : Ξ (a : Ξ±) (ha : p a), Ξ²) (g : Ξ (a : Ξ±) (ha : Β¬p a), Ξ²) :
(β a, dite (p a) (f a) (g a)) = (β a : {a // p a}, f a a.2) * (β a : {a // Β¬p a}, g a a.2) :=
begin
simp only [prod_dite, attach_eq_univ],
congr' 1,
{ convert (equiv.subtype_equiv_right _).prod_comp (Ξ» x : {x // p x}, f x x.2),
simp },
{ convert (equiv.subtype_equiv_right _).prod_comp (Ξ» x : {x // Β¬p x}, g x x.2),
simp }
end
section
open finset
variables {Ξ±β : Type*} {Ξ±β : Type*} {M : Type*} [fintype Ξ±β] [fintype Ξ±β] [comm_monoid M]
@[to_additive]
lemma fintype.prod_sum_elim (f : Ξ±β β M) (g : Ξ±β β M) :
(β x, sum.elim f g x) = (β aβ, f aβ) * (β aβ, g aβ) :=
prod_disj_sum _ _ _
@[simp, to_additive]
lemma fintype.prod_sum_type (f : Ξ±β β Ξ±β β M) :
(β x, f x) = (β aβ, f (sum.inl aβ)) * (β aβ, f (sum.inr aβ)) :=
prod_disj_sum _ _ _
end
|
44b5b40f843dc2fb46bdf7913eb88545c51b5eec | 4fa161becb8ce7378a709f5992a594764699e268 | /src/linear_algebra/finsupp_vector_space.lean | e5135dec149a5f9c9b5fe43973c92be61feb06c7 | [
"Apache-2.0"
] | permissive | laughinggas/mathlib | e4aa4565ae34e46e834434284cb26bd9d67bc373 | 86dcd5cda7a5017c8b3c8876c89a510a19d49aad | refs/heads/master | 1,669,496,232,688 | 1,592,831,995,000 | 1,592,831,995,000 | 274,155,979 | 0 | 0 | Apache-2.0 | 1,592,835,190,000 | 1,592,835,189,000 | null | UTF-8 | Lean | false | false | 6,337 | lean | /-
Copyright (c) 2019 Johannes HΓΆlzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes HΓΆlzl
Linear structures on function with finite support `ΞΉ ββ Ξ²`.
-/
import data.mv_polynomial
import linear_algebra.dimension
noncomputable theory
local attribute [instance, priority 100] classical.prop_decidable
open set linear_map submodule
namespace finsupp
section module
variables {R : Type*} {M : Type*} {ΞΉ : Type*}
variables [ring R] [add_comm_group M] [module R M]
lemma linear_independent_single {Ο : ΞΉ β Type*}
{f : Ξ ΞΉ, Ο ΞΉ β M} (hf : βi, linear_independent R (f i)) :
linear_independent R (Ξ» ix : Ξ£ i, Ο i, single ix.1 (f ix.1 ix.2)) :=
begin
apply @linear_independent_Union_finite R _ _ _ _ ΞΉ Ο (Ξ» i x, single i (f i x)),
{ assume i,
have h_disjoint : disjoint (span R (range (f i))) (ker (lsingle i)),
{ rw ker_lsingle,
exact disjoint_bot_right },
apply linear_independent.image (hf i) h_disjoint },
{ intros i t ht hit,
refine (disjoint_lsingle_lsingle {i} t (disjoint_singleton_left.2 hit)).mono _ _,
{ rw span_le,
simp only [supr_singleton],
rw range_coe,
apply range_comp_subset_range },
{ refine supr_le_supr (Ξ» i, supr_le_supr _),
intros hi,
rw span_le,
rw range_coe,
apply range_comp_subset_range } }
end
end module
section vector_space
variables {K : Type*} {V : Type*} {ΞΉ : Type*}
variables [field K] [add_comm_group V] [vector_space K V]
open linear_map submodule
lemma is_basis_single {Ο : ΞΉ β Type*} (f : Ξ ΞΉ, Ο ΞΉ β V)
(hf : βi, is_basis K (f i)) :
is_basis K (Ξ» ix : Ξ£ i, Ο i, single ix.1 (f ix.1 ix.2)) :=
begin
split,
{ apply linear_independent_single,
exact Ξ» i, (hf i).1 },
{ rw [range_sigma_eq_Union_range, span_Union],
simp only [image_univ.symm, Ξ» i, image_comp (single i) (f i), span_single_image],
simp only [image_univ, (hf _).2, map_top, supr_lsingle_range] }
end
end vector_space
section dim
universes u v
variables {K : Type u} {V : Type v} {ΞΉ : Type v}
variables [field K] [add_comm_group V] [vector_space K V]
lemma dim_eq : vector_space.dim K (ΞΉ ββ V) = cardinal.mk ΞΉ * vector_space.dim K V :=
begin
rcases exists_is_basis K V with β¨bs, hbsβ©,
rw [β cardinal.lift_inj, cardinal.lift_mul, β hbs.mk_eq_dim,
β (is_basis_single _ (Ξ»a:ΞΉ, hbs)).mk_eq_dim, β cardinal.sum_mk,
β cardinal.lift_mul, cardinal.lift_inj],
{ simp only [cardinal.mk_image_eq (single_injective.{u u} _), cardinal.sum_const] }
end
end dim
end finsupp
section vector_space
/- We use `universe variables` instead of `universes` here because universes introduced by the
`universes` keyword do not get replaced by metavariables once a lemma has been proven. So if you
prove a lemma using universe `u`, you can only apply it to universe `u` in other lemmas of the
same section. -/
universe variables u v w
variables {K : Type u} {V Vβ Vβ : Type v} {V' : Type w}
variables [field K]
variables [add_comm_group V] [vector_space K V]
variables [add_comm_group Vβ] [vector_space K Vβ]
variables [add_comm_group Vβ] [vector_space K Vβ]
variables [add_comm_group V'] [vector_space K V']
open vector_space
lemma equiv_of_dim_eq_lift_dim
(h : cardinal.lift.{v w} (dim K V) = cardinal.lift.{w v} (dim K V')) :
nonempty (V ββ[K] V') :=
begin
haveI := classical.dec_eq V,
haveI := classical.dec_eq V',
rcases exists_is_basis K V with β¨m, hmβ©,
rcases exists_is_basis K V' with β¨m', hm'β©,
rw [βcardinal.lift_inj.1 hm.mk_eq_dim, βcardinal.lift_inj.1 hm'.mk_eq_dim] at h,
rcases quotient.exact h with β¨eβ©,
let e := (equiv.ulift.symm.trans e).trans equiv.ulift,
exact β¨((module_equiv_finsupp hm).trans
(finsupp.dom_lcongr e)).trans
(module_equiv_finsupp hm').symmβ©,
end
def equiv_of_dim_eq_dim (h : dim K Vβ = dim K Vβ) : Vβ ββ[K] Vβ :=
begin
classical,
exact classical.choice (equiv_of_dim_eq_lift_dim (cardinal.lift_inj.2 h))
end
def fin_dim_vectorspace_equiv (n : β)
(hn : (dim K V) = n) : V ββ[K] (fin n β K) :=
begin
have : cardinal.lift.{v u} (n : cardinal.{v}) = cardinal.lift.{u v} (n : cardinal.{u}),
by simp,
have hn := cardinal.lift_inj.{v u}.2 hn,
rw this at hn,
rw β@dim_fin_fun K _ n at hn,
exact classical.choice (equiv_of_dim_eq_lift_dim hn),
end
lemma eq_bot_iff_dim_eq_zero (p : submodule K V) (h : dim K p = 0) : p = β₯ :=
begin
have : dim K p = dim K (β₯ : submodule K V) := by rwa [dim_bot],
let e := equiv_of_dim_eq_dim this,
exact e.eq_bot_of_equiv _
end
lemma injective_of_surjective (f : Vβ ββ[K] Vβ)
(hVβ : dim K Vβ < cardinal.omega) (heq : dim K Vβ = dim K Vβ) (hf : f.range = β€) : f.ker = β₯ :=
have hk : dim K f.ker < cardinal.omega := lt_of_le_of_lt (dim_submodule_le _) hVβ,
begin
rcases cardinal.lt_omega.1 hVβ with β¨dβ, eqββ©,
rcases cardinal.lt_omega.1 hk with β¨dβ, eqββ©,
have : 0 = dβ,
{ have := dim_eq_of_surjective f (linear_map.range_eq_top.1 hf),
rw [heq, eqβ, eqβ, β nat.cast_add, cardinal.nat_cast_inj] at this,
exact nat.add_left_cancel this },
refine eq_bot_iff_dim_eq_zero _ _,
rw [eqβ, β this, nat.cast_zero]
end
end vector_space
section vector_space
universes u
open vector_space
variables {K V : Type u} [field K] [add_comm_group V] [vector_space K V]
lemma cardinal_mk_eq_cardinal_mk_field_pow_dim (h : dim K V < cardinal.omega) :
cardinal.mk V = cardinal.mk K ^ dim K V :=
begin
rcases exists_is_basis K V with β¨s, hsβ©,
have : nonempty (fintype s),
{ rwa [β cardinal.lt_omega_iff_fintype, cardinal.lift_inj.1 hs.mk_eq_dim] },
cases this with hsf, letI := hsf,
calc cardinal.mk V = cardinal.mk (s ββ K) : quotient.sound β¨(module_equiv_finsupp hs).to_equivβ©
... = cardinal.mk (s β K) : quotient.sound β¨finsupp.equiv_fun_on_fintypeβ©
... = _ : by rw [β cardinal.lift_inj.1 hs.mk_eq_dim, cardinal.power_def]
end
lemma cardinal_lt_omega_of_dim_lt_omega [fintype K] (h : dim K V < cardinal.omega) :
cardinal.mk V < cardinal.omega :=
begin
rw [cardinal_mk_eq_cardinal_mk_field_pow_dim h],
exact cardinal.power_lt_omega (cardinal.lt_omega_iff_fintype.2 β¨infer_instanceβ©) h
end
end vector_space
|
7ff780ffb2ce4befd8fa2d38c92d1d39574b7f67 | c09f5945267fd905e23a77be83d9a78580e04a4a | /src/analysis/asymptotics.lean | 1200c879809747073f02f7c8da2b36610634dc39 | [
"Apache-2.0"
] | permissive | OHIHIYA20/mathlib | 023a6df35355b5b6eb931c404f7dd7535dccfa89 | 1ec0a1f49db97d45e8666a3bf33217ff79ca1d87 | refs/heads/master | 1,587,964,529,965 | 1,551,819,319,000 | 1,551,819,319,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 26,185 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
We introduce these relations:
`is_O f g l` : "f is big O of g along l"
`is_o f g l` : "f is little o of g along l"
Here `l` is any filter on the domain of `f` and `g`, which are assumed to be the same. The codomains
of `f` and `g` do not need to be the same; all that is needed that there is a norm associated with
these types, and it is the norm that is compared asymptotically.
Often the ranges of `f` and `g` will be the real numbers, in which case the norm is the absolute
value. In general, we have
`is_O f g l β is_O (Ξ» x, β₯f xβ₯) (Ξ» x, β₯g xβ₯) l`,
and similarly for `is_o`. But our setup allows us to use the notions e.g. with functions
to the integers, rationals, complex numbers, or any normed vector space without mentioning the
norm explicitly.
If `f` and `g` are functions to a normed field like the reals or complex numbers and `g` is always
nonzero, we have
`is_o f g l β tendsto (Ξ» x, f x / (g x)) (nhds 0) l`.
In fact, the right-to-left direction holds without the hypothesis on `g`, and in the other direction
it suffices to assume that `f` is zero wherever `g` is. (This generalization is useful in defining
the FrΓ©chet derivative.)
-/
import analysis.normed_space.basic
open filter
namespace asymptotics
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ξ΄ : Type*}
section
variables [has_norm Ξ²] [has_norm Ξ³] [has_norm Ξ΄]
def is_O (f : Ξ± β Ξ²) (g : Ξ± β Ξ³) (l : filter Ξ±) : Prop :=
β c > 0, { x | β₯ f x β₯ β€ c * β₯ g x β₯ } β l.sets
def is_o (f : Ξ± β Ξ²) (g : Ξ± β Ξ³) (l : filter Ξ±) : Prop :=
β c > 0, { x | β₯ f x β₯ β€ c * β₯ g x β₯ } β l.sets
theorem is_O_refl (f : Ξ± β Ξ²) (l : filter Ξ±) : is_O f f l :=
β¨1, zero_lt_one, by { filter_upwards [univ_mem_sets], intros x _, simp }β©
theorem is_O.comp {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} (hfg : is_O f g l)
{Ξ΄ : Type*} (k : Ξ΄ β Ξ±) :
is_O (f β k) (g β k) (l.comap k) :=
let β¨c, cpos, hfgcβ© := hfg in
β¨c, cpos, mem_comap_sets.mpr β¨_, hfgc, set.subset.refl _β©β©
theorem is_o.comp {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} (hfg : is_o f g l)
{Ξ΄ : Type*} (k : Ξ΄ β Ξ±) :
is_o (f β k) (g β k) (l.comap k) :=
Ξ» c cpos, mem_comap_sets.mpr β¨_, hfg c cpos, set.subset.refl _β©
theorem is_O.mono {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {lβ lβ : filter Ξ±} (h : lβ β€ lβ)
(h' : is_O f g lβ) : is_O f g lβ :=
let β¨c, cpos, h'cβ© := h' in β¨c, cpos, h (h'c)β©
theorem is_o.mono {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {lβ lβ : filter Ξ±} (h : lβ β€ lβ)
(h' : is_o f g lβ) : is_o f g lβ :=
Ξ» c cpos, h (h' c cpos)
theorem is_o.to_is_O {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} (hgf : is_o f g l) : is_O f g l :=
β¨1, zero_lt_one, hgf 1 zero_lt_oneβ©
theorem is_O.trans {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {k : Ξ± β Ξ΄} {l : filter Ξ±}
(hβ : is_O f g l) (hβ : is_O g k l) :
is_O f k l :=
let β¨c, cpos, hcβ© := hβ,
β¨c', c'pos, hc'β© := hβ in
begin
use [c * c', mul_pos cpos c'pos],
filter_upwards [hc, hc'], dsimp,
intros x hβx hβx, rw mul_assoc,
exact le_trans hβx (mul_le_mul_of_nonneg_left hβx (le_of_lt cpos))
end
theorem is_o.trans_is_O {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {k : Ξ± β Ξ΄} {l : filter Ξ±}
(hβ : is_o f g l) (hβ : is_O g k l) :
is_o f k l :=
begin
intros c cpos,
rcases hβ with β¨c', c'pos, hc'β©,
have cc'pos := div_pos cpos c'pos,
filter_upwards [hβ (c / c') cc'pos, hc'], dsimp,
intros x hβx hβx,
refine le_trans hβx (le_trans (mul_le_mul_of_nonneg_left hβx (le_of_lt cc'pos)) _),
rw [βmul_assoc, div_mul_cancel _ (ne_of_gt c'pos)]
end
theorem is_O.trans_is_o {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {k : Ξ± β Ξ΄} {l : filter Ξ±}
(hβ : is_O f g l) (hβ : is_o g k l) :
is_o f k l :=
begin
intros c cpos,
rcases hβ with β¨c', c'pos, hc'β©,
have cc'pos := div_pos cpos c'pos,
filter_upwards [hc', hβ (c / c') cc'pos], dsimp,
intros x hβx hβx,
refine le_trans hβx (le_trans (mul_le_mul_of_nonneg_left hβx (le_of_lt c'pos)) _),
rw [βmul_assoc, mul_div_cancel' _ (ne_of_gt c'pos)]
end
theorem is_o.trans {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {k : Ξ± β Ξ΄} {l : filter Ξ±}
(hβ : is_o f g l) (hβ : is_o g k l) :
is_o f k l :=
hβ.to_is_O.trans_is_o hβ
theorem is_o_join {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {lβ lβ : filter Ξ±}
(hβ : is_o f g lβ) (hβ : is_o f g lβ) :
is_o f g (lβ β lβ) :=
begin
intros c cpos,
rw mem_sup_sets,
exact β¨hβ c cpos, hβ c cposβ©
end
theorem is_O_congr {fβ fβ : Ξ± β Ξ²} {gβ gβ : Ξ± β Ξ³} {l : filter Ξ±}
(hf : {x | fβ x = fβ x} β l.sets) (hg : {x | gβ x = gβ x} β l.sets) :
is_O fβ gβ l β is_O fβ gβ l :=
bex_congr $ Ξ» c _, filter.congr_sets $
by filter_upwards [hf, hg] Ξ» x eβ eβ,
by dsimp at eβ eβ β’; rw [eβ, eβ]
theorem is_o_congr {fβ fβ : Ξ± β Ξ²} {gβ gβ : Ξ± β Ξ³} {l : filter Ξ±}
(hf : {x | fβ x = fβ x} β l.sets) (hg : {x | gβ x = gβ x} β l.sets) :
is_o fβ gβ l β is_o fβ gβ l :=
ball_congr $ Ξ» c _, filter.congr_sets $
by filter_upwards [hf, hg] Ξ» x eβ eβ,
by dsimp at eβ eβ β’; rw [eβ, eβ]
theorem is_O.congr {fβ fβ : Ξ± β Ξ²} {gβ gβ : Ξ± β Ξ³} {l : filter Ξ±}
(hf : β x, fβ x = fβ x) (hg : β x, gβ x = gβ x) :
is_O fβ gβ l β is_O fβ gβ l :=
(is_O_congr (univ_mem_sets' hf) (univ_mem_sets' hg)).1
theorem is_o.congr {fβ fβ : Ξ± β Ξ²} {gβ gβ : Ξ± β Ξ³} {l : filter Ξ±}
(hf : β x, fβ x = fβ x) (hg : β x, gβ x = gβ x) :
is_o fβ gβ l β is_o fβ gβ l :=
(is_o_congr (univ_mem_sets' hf) (univ_mem_sets' hg)).1
theorem is_O_congr_left {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±}
(h : {x | fβ x = fβ x} β l.sets) :
is_O fβ g l β is_O fβ g l :=
is_O_congr h (univ_mem_sets' $ Ξ» _, rfl)
theorem is_o_congr_left {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±}
(h : {x | fβ x = fβ x} β l.sets) :
is_o fβ g l β is_o fβ g l :=
is_o_congr h (univ_mem_sets' $ Ξ» _, rfl)
theorem is_O.congr_left {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±}
(hf : β x, fβ x = fβ x) : is_O fβ g l β is_O fβ g l :=
is_O.congr hf (Ξ» _, rfl)
theorem is_o.congr_left {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±}
(hf : β x, fβ x = fβ x) : is_o fβ g l β is_o fβ g l :=
is_o.congr hf (Ξ» _, rfl)
theorem is_O_congr_right {f : Ξ± β Ξ²} {gβ gβ : Ξ± β Ξ³} {l : filter Ξ±}
(h : {x | gβ x = gβ x} β l.sets) :
is_O f gβ l β is_O f gβ l :=
is_O_congr (univ_mem_sets' $ Ξ» _, rfl) h
theorem is_o_congr_right {f : Ξ± β Ξ²} {gβ gβ : Ξ± β Ξ³} {l : filter Ξ±}
(h : {x | gβ x = gβ x} β l.sets) :
is_o f gβ l β is_o f gβ l :=
is_o_congr (univ_mem_sets' $ Ξ» _, rfl) h
theorem is_O.congr_right {f : Ξ± β Ξ²} {gβ gβ : Ξ± β Ξ³} {l : filter Ξ±}
(hg : β x, gβ x = gβ x) : is_O f gβ l β is_O f gβ l :=
is_O.congr (Ξ» _, rfl) hg
theorem is_o.congr_right {f : Ξ± β Ξ²} {gβ gβ : Ξ± β Ξ³} {l : filter Ξ±}
(hg : β x, gβ x = gβ x) : is_o f gβ l β is_o f gβ l :=
is_o.congr (Ξ» _, rfl) hg
end
section
variables [has_norm Ξ²] [normed_group Ξ³]
@[simp]
theorem is_O_norm_right {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_O f (Ξ» x, β₯g xβ₯) l β is_O f g l :=
by simp only [is_O, norm_norm]
@[simp]
theorem is_o_norm_right {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_o f (Ξ» x, β₯g xβ₯) l β is_o f g l :=
by simp only [is_o, norm_norm]
@[simp]
theorem is_O_neg_right {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_O f (Ξ» x, -(g x)) l β is_O f g l :=
by { rw βis_O_norm_right, simp only [norm_neg], rw is_O_norm_right }
@[simp]
theorem is_o_neg_right {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_o f (Ξ» x, -(g x)) l β is_o f g l :=
by { rw βis_o_norm_right, simp only [norm_neg], rw is_o_norm_right }
theorem is_O_iff {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_O f g l β β c, { x | β₯f xβ₯ β€ c * β₯g xβ₯ } β l.sets :=
suffices (β c, { x | β₯f xβ₯ β€ c * β₯g xβ₯ } β l.sets) β is_O f g l,
from β¨Ξ» β¨c, cpos, hcβ©, β¨c, hcβ©, thisβ©,
assume β¨c, hcβ©,
or.elim (lt_or_ge 0 c)
(assume : c > 0, β¨c, this, hcβ©)
(assume h'c : c β€ 0,
have {x : Ξ± | β₯f xβ₯ β€ 1 * β₯g xβ₯} β l.sets,
begin
filter_upwards [hc], intros x,
show β₯f xβ₯ β€ c * β₯g xβ₯ β β₯f xβ₯ β€ 1 * β₯g xβ₯,
{ intro hx, apply le_trans hx,
apply mul_le_mul_of_nonneg_right _ (norm_nonneg _),
show c β€ 1, from le_trans h'c zero_le_one }
end,
β¨1, zero_lt_one, thisβ©)
theorem is_O_join {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {lβ lβ : filter Ξ±}
(hβ : is_O f g lβ) (hβ : is_O f g lβ) :
is_O f g (lβ β lβ) :=
begin
rcases hβ with β¨cβ, cβpos, hcββ©,
rcases hβ with β¨cβ, cβpos, hcββ©,
have : 0 < max cβ cβ, by { rw lt_max_iff, left, exact cβpos },
use [max cβ cβ, this],
rw mem_sup_sets, split,
{ filter_upwards [hcβ], dsimp, intros x hx,
exact le_trans hx (mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _)) },
filter_upwards [hcβ], dsimp, intros x hx,
exact le_trans hx (mul_le_mul_of_nonneg_right (le_max_right _ _) (norm_nonneg _))
end
end
section
variables [normed_group Ξ²] [has_norm Ξ³]
@[simp] theorem is_O_norm_left {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_O (Ξ» x, β₯f xβ₯) g l β is_O f g l :=
by simp only [is_O, norm_norm]
@[simp] theorem is_o_norm_left {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_o (Ξ» x, β₯f xβ₯) g l β is_o f g l :=
by simp only [is_o, norm_norm]
@[simp] theorem is_O_neg_left {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_O (Ξ» x, -f x) g l β is_O f g l :=
by { rw βis_O_norm_left, simp only [norm_neg], rw is_O_norm_left }
@[simp] theorem is_o_neg_left {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_o (Ξ» x, -f x) g l β is_o f g l :=
by { rw βis_o_norm_left, simp only [norm_neg], rw is_o_norm_left }
theorem is_O.add {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} (hβ : is_O fβ g l) (hβ : is_O fβ g l) :
is_O (Ξ» x, fβ x + fβ x) g l :=
let β¨cβ, cβpos, hcββ© := hβ,
β¨cβ, cβpos, hcββ© := hβ in
begin
use [cβ + cβ, add_pos cβpos cβpos],
filter_upwards [hcβ, hcβ],
intros x hxβ hxβ,
show β₯fβ x + fβ xβ₯ β€ (cβ + cβ) * β₯g xβ₯,
apply le_trans (norm_triangle _ _),
rw add_mul,
exact add_le_add hxβ hxβ
end
theorem is_o.add {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} (hβ : is_o fβ g l) (hβ : is_o fβ g l) :
is_o (Ξ» x, fβ x + fβ x) g l :=
begin
intros c cpos,
filter_upwards [hβ (c / 2) (half_pos cpos), hβ (c / 2) (half_pos cpos)],
intros x hxβ hxβ, dsimp at hxβ hxβ,
apply le_trans (norm_triangle _ _),
apply le_trans (add_le_add hxβ hxβ),
rw [βmul_add, βtwo_mul, βmul_assoc, div_mul_cancel _ two_ne_zero]
end
theorem is_O.sub {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} (hβ : is_O fβ g l) (hβ : is_O fβ g l) :
is_O (Ξ» x, fβ x - fβ x) g l :=
hβ.add (is_O_neg_left.mpr hβ)
theorem is_o.sub {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} (hβ : is_o fβ g l) (hβ : is_o fβ g l) :
is_o (Ξ» x, fβ x - fβ x) g l :=
hβ.add (is_o_neg_left.mpr hβ)
theorem is_O_comm {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_O (Ξ» x, fβ x - fβ x) g l β is_O (Ξ» x, fβ x - fβ x) g l :=
by simpa using @is_O_neg_left _ _ _ _ _ (Ξ» x, fβ x - fβ x) g l
theorem is_O.symm {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_O (Ξ» x, fβ x - fβ x) g l β is_O (Ξ» x, fβ x - fβ x) g l :=
is_O_comm.1
theorem is_O.tri {fβ fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±}
(hβ : is_O (Ξ» x, fβ x - fβ x) g l)
(hβ : is_O (Ξ» x, fβ x - fβ x) g l) :
is_O (Ξ» x, fβ x - fβ x) g l :=
(hβ.add hβ).congr_left (by simp)
theorem is_O.congr_of_sub {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±}
(h : is_O (Ξ» x, fβ x - fβ x) g l) :
is_O fβ g l β is_O fβ g l :=
β¨Ξ» h', (h'.sub h).congr_left (Ξ» x, sub_sub_cancel _ _),
Ξ» h', (h.add h').congr_left (Ξ» x, sub_add_cancel _ _)β©
theorem is_o_comm {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_o (Ξ» x, fβ x - fβ x) g l β is_o (Ξ» x, fβ x - fβ x) g l :=
by simpa using @is_o_neg_left _ _ _ _ _ (Ξ» x, fβ x - fβ x) g l
theorem is_o.symm {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_o (Ξ» x, fβ x - fβ x) g l β is_o (Ξ» x, fβ x - fβ x) g l :=
is_o_comm.1
theorem is_o.tri {fβ fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±}
(hβ : is_o (Ξ» x, fβ x - fβ x) g l)
(hβ : is_o (Ξ» x, fβ x - fβ x) g l) :
is_o (Ξ» x, fβ x - fβ x) g l :=
(hβ.add hβ).congr_left (by simp)
theorem is_o.congr_of_sub {fβ fβ : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±}
(h : is_o (Ξ» x, fβ x - fβ x) g l) :
is_o fβ g l β is_o fβ g l :=
β¨Ξ» h', (h'.sub h).congr_left (Ξ» x, sub_sub_cancel _ _),
Ξ» h', (h.add h').congr_left (Ξ» x, sub_add_cancel _ _)β©
end
section
variables [normed_group Ξ²] [normed_group Ξ³]
theorem is_O_zero (g : Ξ± β Ξ³) (l : filter Ξ±) :
is_O (Ξ» x, (0 : Ξ²)) g l :=
β¨1, zero_lt_one, by { filter_upwards [univ_mem_sets], intros x _, simp }β©
theorem is_O_refl_left {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_O (Ξ» x, f x - f x) g l :=
by simpa using is_O_zero g l
theorem is_O_zero_right_iff {f : Ξ± β Ξ²} {l : filter Ξ±} :
is_O f (Ξ» x, (0 : Ξ³)) l β {x | f x = 0} β l.sets :=
begin
rw [is_O_iff], split,
{ rintros β¨c, hcβ©,
filter_upwards [hc], dsimp,
intro x, rw [norm_zero, mul_zero], intro hx,
rw βnorm_eq_zero,
exact le_antisymm hx (norm_nonneg _) },
intro h, use 0,
filter_upwards [h], dsimp,
intros x hx,
rw [hx, norm_zero, zero_mul]
end
theorem is_o_zero (g : Ξ± β Ξ³) (l : filter Ξ±) :
is_o (Ξ» x, (0 : Ξ²)) g l :=
Ξ» c cpos,
by { filter_upwards [univ_mem_sets], intros x _, simp,
exact mul_nonneg (le_of_lt cpos) (norm_nonneg _)}
theorem is_o_refl_left {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} :
is_o (Ξ» x, f x - f x) g l :=
by simpa using is_o_zero g l
theorem is_o_zero_right_iff {f : Ξ± β Ξ²} (l : filter Ξ±) :
is_o f (Ξ» x, (0 : Ξ³)) l β {x | f x = 0} β l.sets :=
begin
split,
{ intro h, exact is_O_zero_right_iff.mp h.to_is_O },
intros h c cpos,
filter_upwards [h], dsimp,
intros x hx,
rw [hx, norm_zero, norm_zero, mul_zero]
end
end
section
variables [has_norm Ξ²] [normed_field Ξ³]
theorem is_O_const_one (c : Ξ²) (l : filter Ξ±) :
is_O (Ξ» x : Ξ±, c) (Ξ» x, (1 : Ξ³)) l :=
begin
rw is_O_iff,
use β₯cβ₯, simp only [norm_one, mul_one],
convert univ_mem_sets, simp only [le_refl]
end
end
section
variables [normed_field Ξ²] [normed_group Ξ³]
theorem is_O_const_mul_left {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} (h : is_O f g l) (c : Ξ²) :
is_O (Ξ» x, c * f x) g l :=
begin
cases classical.em (c = 0) with h'' h'',
{ simp [h''], apply is_O_zero },
rcases h with β¨c', c'pos, h'β©,
have cne0 : β₯cβ₯ β 0, from mt (norm_eq_zero _).mp h'',
have cpos : β₯cβ₯ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0),
use [β₯cβ₯ * c', mul_pos cpos c'pos],
filter_upwards [h'], dsimp,
intros x hβ,
rw [normed_field.norm_mul, mul_assoc],
exact mul_le_mul_of_nonneg_left hβ (norm_nonneg _)
end
theorem is_O_const_mul_left_iff {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} {c : Ξ²} (hc : c β 0) :
is_O (Ξ» x, c * f x) g l β is_O f g l :=
begin
split,
{ intro h,
convert is_O_const_mul_left h cβ»ΒΉ, ext,
rw [βmul_assoc, inv_mul_cancel hc, one_mul] },
intro h, apply is_O_const_mul_left h
end
theorem is_o_const_mul_left {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±}
(h : is_o f g l) (c : Ξ²) :
is_o (Ξ» x, c * f x) g l :=
begin
cases classical.em (c = 0) with h'' h'',
{ simp [h''], apply is_o_zero },
have cne0 : β₯cβ₯ β 0, from mt (norm_eq_zero _).mp h'',
have cpos : β₯cβ₯ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0),
intros c' c'pos, dsimp,
filter_upwards [h (c' / β₯cβ₯) (div_pos c'pos cpos)], dsimp,
intros x hx, rw [normed_field.norm_mul],
apply le_trans (mul_le_mul_of_nonneg_left hx (le_of_lt cpos)),
rw [βmul_assoc, mul_div_cancel' _ cne0]
end
theorem is_o_const_mul_left_iff {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} {c : Ξ²} (hc : c β 0) :
is_o (Ξ» x, c * f x) g l β is_o f g l :=
begin
split,
{ intro h,
convert is_o_const_mul_left h cβ»ΒΉ, ext,
rw [βmul_assoc, inv_mul_cancel hc, one_mul] },
intro h',
apply is_o_const_mul_left h'
end
end
section
variables [normed_group Ξ²] [normed_field Ξ³]
theorem is_O_of_is_O_const_mul_right {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} {c : Ξ³}
(h : is_O f (Ξ» x, c * g x) l) :
is_O f g l :=
begin
cases classical.em (c = 0) with h' h',
{ simp [h', is_O_zero_right_iff] at h, rw is_O_congr_left h, apply is_O_zero },
have cne0 : β₯cβ₯ β 0, from mt (norm_eq_zero _).mp h',
have cpos : β₯cβ₯ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0),
rcases h with β¨c', c'pos, h''β©,
use [c' * β₯cβ₯, mul_pos c'pos cpos],
convert h'', ext x, dsimp,
rw [normed_field.norm_mul, mul_assoc]
end
theorem is_O_const_mul_right_iff {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} {c : Ξ³} (hc : c β 0) :
is_O f (Ξ» x, c * g x) l β is_O f g l :=
begin
split,
{ intro h, exact is_O_of_is_O_const_mul_right h },
intro h,
apply is_O_of_is_O_const_mul_right,
show is_O f (Ξ» (x : Ξ±), cβ»ΒΉ * (c * g x)) l,
convert h, ext, rw [βmul_assoc, inv_mul_cancel hc, one_mul]
end
theorem is_o_of_is_o_const_mul_right {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} {c : Ξ³}
(h : is_o f (Ξ» x, c * g x) l) :
is_o f g l :=
begin
cases classical.em (c = 0) with h' h',
{ simp [h', is_o_zero_right_iff] at h, rw is_o_congr_left h, apply is_o_zero },
have cne0 : β₯cβ₯ β 0, from mt (norm_eq_zero _).mp h',
have cpos : β₯cβ₯ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0),
intros c' c'pos,
convert h (c' / β₯cβ₯) (div_pos c'pos cpos), dsimp,
ext x, rw [normed_field.norm_mul, βmul_assoc, div_mul_cancel _ cne0]
end
theorem is_o_const_mul_right {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} {c : Ξ³} (hc : c β 0) :
is_o f (Ξ» x, c * g x) l β is_o f g l :=
begin
split,
{ intro h, exact is_o_of_is_o_const_mul_right h },
intro h,
apply is_o_of_is_o_const_mul_right,
show is_o f (Ξ» (x : Ξ±), cβ»ΒΉ * (c * g x)) l,
convert h, ext, rw [βmul_assoc, inv_mul_cancel hc, one_mul]
end
theorem is_o_one_iff {f : Ξ± β Ξ²} {l : filter Ξ±} :
is_o f (Ξ» x, (1 : Ξ³)) l β tendsto f l (nhds 0) :=
begin
rw [normed_space.tendsto_nhds_zero, is_o], split,
{ intros h e epos,
filter_upwards [h (e / 2) (half_pos epos)], simp,
intros x hx,
exact lt_of_le_of_lt hx (half_lt_self epos) },
intros h e epos,
filter_upwards [h e epos], simp,
intros x hx,
exact le_of_lt hx
end
end
section
variables [normed_group Ξ²] [normed_group Ξ³]
theorem is_O.trans_tendsto {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±}
(hβ : is_O f g l) (hβ : tendsto g l (nhds 0)) :
tendsto f l (nhds 0) :=
(@is_o_one_iff _ _ β _ _ _ _).1 $ hβ.trans_is_o $ is_o_one_iff.2 hβ
theorem is_o.trans_tendsto {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±}
(hβ : is_o f g l) : tendsto g l (nhds 0) β tendsto f l (nhds 0) :=
hβ.to_is_O.trans_tendsto
end
section
variables [normed_field Ξ²] [normed_field Ξ³]
theorem is_O_mul {fβ fβ : Ξ± β Ξ²} {gβ gβ : Ξ± β Ξ³} {l : filter Ξ±}
(hβ : is_O fβ gβ l) (hβ : is_O fβ gβ l) :
is_O (Ξ» x, fβ x * fβ x) (Ξ» x, gβ x * gβ x) l :=
begin
rcases hβ with β¨cβ, cβpos, hcββ©,
rcases hβ with β¨cβ, cβpos, hcββ©,
use [cβ * cβ, mul_pos cβpos cβpos],
filter_upwards [hcβ, hcβ], dsimp,
intros x hxβ hxβ,
rw [normed_field.norm_mul, normed_field.norm_mul, mul_assoc, mul_left_comm cβ, βmul_assoc],
exact mul_le_mul hxβ hxβ (norm_nonneg _) (mul_nonneg (le_of_lt cβpos) (norm_nonneg _))
end
theorem is_o_mul_left {fβ fβ : Ξ± β Ξ²} {gβ gβ : Ξ± β Ξ³} {l : filter Ξ±}
(hβ : is_O fβ gβ l) (hβ : is_o fβ gβ l):
is_o (Ξ» x, fβ x * fβ x) (Ξ» x, gβ x * gβ x) l :=
begin
intros c cpos,
rcases hβ with β¨cβ, cβpos, hcββ©,
filter_upwards [hcβ, hβ (c / cβ) (div_pos cpos cβpos)], dsimp,
intros x hxβ hxβ,
rw [normed_field.norm_mul, normed_field.norm_mul],
apply le_trans (mul_le_mul hxβ hxβ (norm_nonneg _) (mul_nonneg (le_of_lt cβpos) (norm_nonneg _))),
rw [mul_comm cβ, mul_assoc, mul_left_comm cβ, βmul_assoc _ cβ, div_mul_cancel _ (ne_of_gt cβpos)],
rw [mul_left_comm]
end
theorem is_o_mul_right {fβ fβ : Ξ± β Ξ²} {gβ gβ : Ξ± β Ξ³} {l : filter Ξ±}
(hβ : is_o fβ gβ l) (hβ : is_O fβ gβ l):
is_o (Ξ» x, fβ x * fβ x) (Ξ» x, gβ x * gβ x) l :=
by convert is_o_mul_left hβ hβ; simp only [mul_comm]
theorem is_o_mul {fβ fβ : Ξ± β Ξ²} {gβ gβ : Ξ± β Ξ³} {l : filter Ξ±}
(hβ : is_o fβ gβ l) (hβ : is_o fβ gβ l):
is_o (Ξ» x, fβ x * fβ x) (Ξ» x, gβ x * gβ x) l :=
is_o_mul_left hβ.to_is_O hβ
end
/-
Note: the theorems in the next two sections can also be used for the integers, since
scalar multiplication is multiplication.
-/
section
variables {K : Type*} [normed_field K] [normed_space K Ξ²] [normed_group Ξ³]
theorem is_O_const_smul_left {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} (h : is_O f g l) (c : K) :
is_O (Ξ» x, c β’ f x) g l :=
begin
rw [βis_O_norm_left], simp only [norm_smul],
apply is_O_const_mul_left,
rw [is_O_norm_left],
apply h
end
theorem is_O_const_smul_left_iff {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} {c : K} (hc : c β 0) :
is_O (Ξ» x, c β’ f x) g l β is_O f g l :=
begin
have cne0 : β₯cβ₯ β 0, from mt (norm_eq_zero _).mp hc,
rw [βis_O_norm_left], simp only [norm_smul],
rw [is_O_const_mul_left_iff cne0, is_O_norm_left]
end
theorem is_o_const_smul_left {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} (h : is_o f g l) (c : K) :
is_o (Ξ» x, c β’ f x) g l :=
begin
rw [βis_o_norm_left], simp only [norm_smul],
apply is_o_const_mul_left,
rw [is_o_norm_left],
apply h
end
theorem is_o_const_smul_left_iff {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} {c : K} (hc : c β 0) :
is_o (Ξ» x, c β’ f x) g l β is_o f g l :=
begin
have cne0 : β₯cβ₯ β 0, from mt (norm_eq_zero _).mp hc,
rw [βis_o_norm_left], simp only [norm_smul],
rw [is_o_const_mul_left_iff cne0, is_o_norm_left]
end
end
section
variables {K : Type*} [normed_group Ξ²] [normed_field K] [normed_space K Ξ³]
theorem is_O_const_smul_right {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} {c : K} (hc : c β 0) :
is_O f (Ξ» x, c β’ g x) l β is_O f g l :=
begin
have cne0 : β₯cβ₯ β 0, from mt (norm_eq_zero _).mp hc,
rw [βis_O_norm_right], simp only [norm_smul],
rw [is_O_const_mul_right_iff cne0, is_O_norm_right]
end
theorem is_o_const_smul_right {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} {c : K} (hc : c β 0) :
is_o f (Ξ» x, c β’ g x) l β is_o f g l :=
begin
have cne0 : β₯cβ₯ β 0, from mt (norm_eq_zero _).mp hc,
rw [βis_o_norm_right], simp only [norm_smul],
rw [is_o_const_mul_right cne0, is_o_norm_right]
end
end
section
variables {K : Type*} [normed_field K] [normed_space K Ξ²] [normed_space K Ξ³]
theorem is_O_smul {k : Ξ± β K} {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} (h : is_O f g l) :
is_O (Ξ» x, k x β’ f x) (Ξ» x, k x β’ g x) l :=
begin
rw [βis_O_norm_left, βis_O_norm_right], simp only [norm_smul],
apply is_O_mul (is_O_refl _ _),
rw [is_O_norm_left, is_O_norm_right],
exact h
end
theorem is_o_smul {k : Ξ± β K} {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {l : filter Ξ±} (h : is_o f g l) :
is_o (Ξ» x, k x β’ f x) (Ξ» x, k x β’ g x) l :=
begin
rw [βis_o_norm_left, βis_o_norm_right], simp only [norm_smul],
apply is_o_mul_left (is_O_refl _ _),
rw [is_o_norm_left, is_o_norm_right],
exact h
end
end
section
variables [normed_field Ξ²]
theorem tendsto_nhds_zero_of_is_o {f g : Ξ± β Ξ²} {l : filter Ξ±} (h : is_o f g l) :
tendsto (Ξ» x, f x / (g x)) l (nhds 0) :=
have eqβ : is_o (Ξ» x, f x / g x) (Ξ» x, g x / g x) l,
from is_o_mul_right h (is_O_refl _ _),
have eqβ : is_O (Ξ» x, g x / g x) (Ξ» x, (1 : Ξ²)) l,
begin
use [1, zero_lt_one],
filter_upwards [univ_mem_sets], simp,
intro x,
cases classical.em (β₯g xβ₯ = 0) with h' h'; simp [h'],
exact zero_le_one
end,
is_o_one_iff.mp (eqβ.trans_is_O eqβ)
private theorem is_o_of_tendsto {f g : Ξ± β Ξ²} {l : filter Ξ±}
(hgf : β x, g x = 0 β f x = 0) (h : tendsto (Ξ» x, f x / (g x)) l (nhds 0)) :
is_o f g l :=
have eqβ : is_o (Ξ» x, f x / (g x)) (Ξ» x, (1 : Ξ²)) l,
from is_o_one_iff.mpr h,
have eqβ : is_o (Ξ» x, f x / g x * g x) g l,
by convert is_o_mul_right eqβ (is_O_refl _ _); simp,
have eqβ : is_O f (Ξ» x, f x / g x * g x) l,
begin
use [1, zero_lt_one],
filter_upwards [univ_mem_sets], simp,
intro x,
cases classical.em (β₯g xβ₯ = 0) with h' h',
{ rw hgf _ ((norm_eq_zero _).mp h'), simp },
rw [normed_field.norm_mul, norm_div, div_mul_cancel _ h']
end,
eqβ.trans_is_o eqβ
theorem is_o_iff_tendsto [normed_field Ξ²] {f g : Ξ± β Ξ²} {l : filter Ξ±}
(hgf : β x, g x = 0 β f x = 0) :
is_o f g l β tendsto (Ξ» x, f x / (g x)) l (nhds 0) :=
iff.intro tendsto_nhds_zero_of_is_o (is_o_of_tendsto hgf)
end
end asymptotics
|
fab7e16d9c12e801e60a9b64d8b1266c18982672 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/order/iterate.lean | 9aae5877a14b24ed265cf635fdd00621d569cc2f | [
"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 | 6,384 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import logic.function.iterate
import data.nat.basic
/-!
# Inequalities on iterates
In this file we prove some inequalities comparing `f^[n] x` and `g^[n] x` where `f` and `g` are
two self-maps that commute with each other.
Current selection of inequalities is motivated by formalization of the rotation number of
a circle homeomorphism.
-/
variables {Ξ± : Type*}
namespace monotone
variables [preorder Ξ±] {f : Ξ± β Ξ±} {x y : β β Ξ±}
lemma seq_le_seq (hf : monotone f) (n : β) (hβ : x 0 β€ y 0)
(hx : β k < n, x (k + 1) β€ f (x k)) (hy : β k < n, f (y k) β€ y (k + 1)) :
x n β€ y n :=
begin
induction n with n ihn,
{ exact hβ },
{ refine (hx _ n.lt_succ_self).trans ((hf $ ihn _ _).trans (hy _ n.lt_succ_self)),
exact Ξ» k hk, hx _ (hk.trans n.lt_succ_self),
exact Ξ» k hk, hy _ (hk.trans n.lt_succ_self) }
end
lemma seq_pos_lt_seq_of_lt_of_le (hf : monotone f) {n : β} (hn : 0 < n) (hβ : x 0 β€ y 0)
(hx : β k < n, x (k + 1) < f (x k)) (hy : β k < n, f (y k) β€ y (k + 1)) :
x n < y n :=
begin
induction n with n ihn, { exact hn.false.elim },
suffices : x n β€ y n,
from (hx n n.lt_succ_self).trans_le ((hf this).trans $ hy n n.lt_succ_self),
cases n, { exact hβ },
refine (ihn n.zero_lt_succ (Ξ» k hk, hx _ _) (Ξ» k hk, hy _ _)).le;
exact hk.trans n.succ.lt_succ_self
end
lemma seq_pos_lt_seq_of_le_of_lt (hf : monotone f) {n : β} (hn : 0 < n) (hβ : x 0 β€ y 0)
(hx : β k < n, x (k + 1) β€ f (x k)) (hy : β k < n, f (y k) < y (k + 1)) :
x n < y n :=
hf.dual.seq_pos_lt_seq_of_lt_of_le hn hβ hy hx
lemma seq_lt_seq_of_lt_of_le (hf : monotone f) (n : β) (hβ : x 0 < y 0)
(hx : β k < n, x (k + 1) < f (x k)) (hy : β k < n, f (y k) β€ y (k + 1)) :
x n < y n :=
by { cases n, exacts [hβ, hf.seq_pos_lt_seq_of_lt_of_le n.zero_lt_succ hβ.le hx hy] }
lemma seq_lt_seq_of_le_of_lt (hf : monotone f) (n : β) (hβ : x 0 < y 0)
(hx : β k < n, x (k + 1) β€ f (x k)) (hy : β k < n, f (y k) < y (k + 1)) :
x n < y n :=
hf.dual.seq_lt_seq_of_lt_of_le n hβ hy hx
end monotone
namespace function
section preorder
variables [preorder Ξ±] {f : Ξ± β Ξ±}
lemma id_le_iterate_of_id_le (h : id β€ f) :
β n, id β€ (f^[n])
| 0 := by { rw function.iterate_zero, exact le_rfl }
| (n + 1) := Ξ» x,
begin
rw function.iterate_succ_apply',
exact (id_le_iterate_of_id_le n x).trans (h _),
end
lemma iterate_le_id_of_le_id (h : f β€ id) :
β n, (f^[n]) β€ id :=
@id_le_iterate_of_id_le (order_dual Ξ±) _ f h
lemma iterate_le_iterate_of_id_le (h : id β€ f) {m n : β} (hmn : m β€ n) :
f^[m] β€ (f^[n]) :=
begin
rw [βadd_sub_cancel_of_le hmn, add_comm, function.iterate_add],
exact Ξ» x, id_le_iterate_of_id_le h _ _,
end
lemma iterate_le_iterate_of_le_id (h : f β€ id) {m n : β} (hmn : m β€ n) :
f^[n] β€ (f^[m]) :=
@iterate_le_iterate_of_id_le (order_dual Ξ±) _ f h m n hmn
end preorder
namespace commute
section preorder
variables [preorder Ξ±] {f g : Ξ± β Ξ±}
lemma iterate_le_of_map_le (h : commute f g) (hf : monotone f) (hg : monotone g)
{x} (hx : f x β€ g x) (n : β) :
f^[n] x β€ (g^[n]) x :=
by refine hf.seq_le_seq n _ (Ξ» k hk, _) (Ξ» k hk, _);
simp [iterate_succ' f, h.iterate_right _ _, hg.iterate _ hx]
lemma iterate_pos_lt_of_map_lt (h : commute f g) (hf : monotone f) (hg : strict_mono g)
{x} (hx : f x < g x) {n} (hn : 0 < n) :
f^[n] x < (g^[n]) x :=
by refine hf.seq_pos_lt_seq_of_le_of_lt hn _ (Ξ» k hk, _) (Ξ» k hk, _);
simp [iterate_succ' f, h.iterate_right _ _, hg.iterate _ hx]
lemma iterate_pos_lt_of_map_lt' (h : commute f g) (hf : strict_mono f) (hg : monotone g)
{x} (hx : f x < g x) {n} (hn : 0 < n) :
f^[n] x < (g^[n]) x :=
@iterate_pos_lt_of_map_lt (order_dual Ξ±) _ g f h.symm hg.dual hf.dual x hx n hn
end preorder
variables [linear_order Ξ±] {f g : Ξ± β Ξ±}
lemma iterate_pos_lt_iff_map_lt (h : commute f g) (hf : monotone f)
(hg : strict_mono g) {x n} (hn : 0 < n) :
f^[n] x < (g^[n]) x β f x < g x :=
begin
rcases lt_trichotomy (f x) (g x) with H|H|H,
{ simp only [*, iterate_pos_lt_of_map_lt] },
{ simp only [*, h.iterate_eq_of_map_eq, lt_irrefl] },
{ simp only [lt_asymm H, lt_asymm (h.symm.iterate_pos_lt_of_map_lt' hg hf H hn)] }
end
lemma iterate_pos_lt_iff_map_lt' (h : commute f g) (hf : strict_mono f)
(hg : monotone g) {x n} (hn : 0 < n) :
f^[n] x < (g^[n]) x β f x < g x :=
@iterate_pos_lt_iff_map_lt (order_dual Ξ±) _ _ _ h.symm hg.dual hf.dual x n hn
lemma iterate_pos_le_iff_map_le (h : commute f g) (hf : monotone f)
(hg : strict_mono g) {x n} (hn : 0 < n) :
f^[n] x β€ (g^[n]) x β f x β€ g x :=
by simpa only [not_lt] using not_congr (h.symm.iterate_pos_lt_iff_map_lt' hg hf hn)
lemma iterate_pos_le_iff_map_le' (h : commute f g) (hf : strict_mono f)
(hg : monotone g) {x n} (hn : 0 < n) :
f^[n] x β€ (g^[n]) x β f x β€ g x :=
by simpa only [not_lt] using not_congr (h.symm.iterate_pos_lt_iff_map_lt hg hf hn)
lemma iterate_pos_eq_iff_map_eq (h : commute f g) (hf : monotone f)
(hg : strict_mono g) {x n} (hn : 0 < n) :
f^[n] x = (g^[n]) x β f x = g x :=
by simp only [le_antisymm_iff, h.iterate_pos_le_iff_map_le hf hg hn,
h.symm.iterate_pos_le_iff_map_le' hg hf hn]
end commute
end function
namespace monotone
open function
section
variables {Ξ² : Type*} [preorder Ξ²] {f : Ξ± β Ξ±} {g : Ξ² β Ξ²} {h : Ξ± β Ξ²}
lemma le_iterate_comp_of_le (hg : monotone g) (H : β x, h (f x) β€ g (h x)) (n : β) (x : Ξ±) :
h (f^[n] x) β€ (g^[n] (h x)) :=
by refine hg.seq_le_seq n _ (Ξ» k hk, _) (Ξ» k hk, _); simp [iterate_succ', H _]
lemma iterate_comp_le_of_le (hg : monotone g) (H : β x, g (h x) β€ h (f x)) (n : β) (x : Ξ±) :
g^[n] (h x) β€ h (f^[n] x) :=
hg.dual.le_iterate_comp_of_le H n x
end
variables [preorder Ξ±] {f g : Ξ± β Ξ±}
/-- If `f β€ g` and `f` is monotone, then `f^[n] β€ g^[n]`. -/
lemma iterate_le_of_le (hf : monotone f) (h : f β€ g) (n : β) :
f^[n] β€ (g^[n]) :=
hf.iterate_comp_le_of_le h n
/-- If `f β€ g` and `f` is monotone, then `f^[n] β€ g^[n]`. -/
lemma iterate_ge_of_ge (hg : monotone g) (h : f β€ g) (n : β) :
f^[n] β€ (g^[n]) :=
hg.dual.iterate_le_of_le h n
end monotone
|
81a181b73c0f84475255a434271d8601cf265d59 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/rewrite_search/frontend.lean | 910c7f57ffd0b2a75a418af49f2d40c4df695ea8 | [
"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,342 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Keeley Hoek, Scott Morrison
-/
import tactic.rewrite_search.explain
import tactic.rewrite_search.discovery
import tactic.rewrite_search.search
/-!
# `rewrite_search`: solving goals by searching for a series of rewrites.
`rewrite_search` is a tactic for solving equalities or iff statements by searching for a
sequence of rewrite tactic applications.
## Algorithm sketch
The fundamental data structure behind the search algorithm is a graph of expressions. Each
vertex represents one expression, and an edge in the graph represents a way to rewrite one
expression into another with a single application of a rewrite tactic. Thus, a path in the
graph represents a way to rewrite one expression into another with multiple applications of
a rewrite tactic.
The graph starts out with two vertices, one for the left hand side of the equality, and one
for the right hand side of the equality. The basic loop of the algorithm is to repeatedly add
edges to the graph by taking vertices in the graph and applying a possible rewrite to them.
Through this process, the graph is made up of two connected components; one component contains
expressions that are equivalent to the left hand side, and one component contains expressions
that are equivalent to the right hand side. The algorithm completes when we discover an
edge that connects the two components, creating a path of rewrites that connects the
left hand side and right hand side of the graph. For more detail, see Keeley's report at
https://hoek.io/res/2018.s2.lean.report.pdf, although note that the edit distance mechanism
described is currently not implemented, only plain breadth-first search.
This algorithm is generally superior to one that only expands nodes starting from a single
side, because it is replacing one tree of depth `2d` with two trees of depth `d`. This is
a quadratic speedup for regular trees; our trees aren't regular but it's still probably
a much better algorithm. We can only use this specific algorithm for rewrite-type tactics,
though, not general sequences of tactics, because it relies on the fact that any rewrite
can be reversed.
## File structure
* `discovery.lean` contains the logic for figuring out which rewrite rules to consider.
* `search.lean` contains the graph algorithms to find a successful sequence of tactics.
* `explain.lean` generates concise Lean code to run a tactic, from the autogenerated sequence
of tactics.
* `frontend.lean` contains the user-facing interface to the `rewrite_search` tactics.
* `types.lean` contains data structures shared across multiple of these components.
-/
namespace tactic.interactive
open lean.parser interactive interactive.types tactic.rewrite_search
/--
Parse a specification for a single rewrite rule.
The name of a lemma indicates using it as a rewrite. Prepending a "β" reverses the direction.
-/
private meta def rws_parser : lean.parser (pexpr Γ bool) :=
do flipped β optional $ tk "β",
pexp β lean.parser.pexpr 0,
return (pexp, flipped.is_some)
/--
Search for a chain of rewrites to prove an equation or iff statement.
Collects rewrite rules, runs a graph search to find a chain of rewrites to prove the
current target, and generates a string explanation for it.
Takes an optional list of rewrite rules specified in the same way as the `rw` tactic accepts.
-/
meta def rewrite_search (explain : parse $ optional (tk "?"))
(rs : parse $ optional (list_of rws_parser)) (cfg : config := {}) : tactic unit :=
do t β tactic.target,
if t.has_meta_var then
tactic.fail "rewrite_search is not suitable for goals containing metavariables"
else tactic.skip,
implicit_rules β collect_rules,
explicit_rules β (rs.get_or_else []).mmap (Ξ» β¨pe, dirβ©, do e β to_expr' pe, return (e, dir)),
let rules := implicit_rules ++ explicit_rules,
g β mk_graph cfg rules t,
(_, proof, steps) β g.find_proof,
tactic.exact proof,
if explain.is_some then explain_search_result cfg rules proof steps else skip
add_tactic_doc
{ name := "rewrite_search",
category := doc_category.tactic,
decl_names := [`tactic.interactive.rewrite_search],
tags := ["rewrite", "automation"] }
end tactic.interactive
|
e4b331943e6b5ed0ff13d6df8f81478bba307cac | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /test/linarith.lean | 5c340974ce2cb3376c04c8f23e6591eb549646cc | [
"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 | 10,534 | lean | import tactic.linarith
import algebra.field_power
example {Ξ± : Type} (_inst : Ξ (a : Prop), decidable a)
[linear_ordered_field Ξ±]
{a b c : Ξ±}
(ha : a < 0)
(hb : Β¬b = 0)
(hc' : c = 0)
(h : (1 - a) * (b * b) β€ 0)
(hc : 0 β€ 0)
(this : -(a * -b * -b + b * -b + 0) = (1 - a) * (b * b))
(h : (1 - a) * (b * b) β€ 0) :
0 < 1 - a :=
begin
linarith
end
example (e b c a v0 v1 : β) (h1 : v0 = 5*a) (h2 : v1 = 3*b) (h3 : v0 + v1 + c = 10) :
v0 + 5 + (v1 - 3) + (c - 2) = 10 :=
by linarith
example (u v r s t : β) (h : 0 < u*(t*v + t*r + s)) : 0 < (t*(r + v) + s)*3*u :=
by linarith
example (A B : β) (h : 0 < A * B) : 0 < 8*A*B :=
begin
linarith
end
example (A B : β) (h : 0 < A * B) : 0 < A*8*B :=
begin
linarith
end
example (A B : β) (h : 0 < A * B) : 0 < A*B/8 :=
begin
linarith
end
example (A B : β) (h : 0 < A * B) : 0 < A/8*B :=
begin
linarith
end
example (Ξ΅ : β) (h1 : Ξ΅ > 0) : Ξ΅ / 2 + Ξ΅ / 3 + Ξ΅ / 7 < Ξ΅ :=
by linarith
example (x y z : β) (h1 : 2*x < 3*y) (h2 : -4*x + z/2 < 0)
(h3 : 12*y - z < 0) : false :=
by linarith
example (Ξ΅ : β) (h1 : Ξ΅ > 0) : Ξ΅ / 2 < Ξ΅ :=
by linarith
example (Ξ΅ : β) (h1 : Ξ΅ > 0) : Ξ΅ / 3 + Ξ΅ / 3 + Ξ΅ / 3 = Ξ΅ :=
by linarith
example (a b c : β) (h2 : b + 2 > 3 + b) : false :=
by linarith {discharger := `[ring]}
example (a b c : β) (h2 : b + 2 > 3 + b) : false :=
by linarith
example (a b c : β) (x y : β€) (h1 : x β€ 3*y) (h2 : b + 2 > 3 + b) : false :=
by linarith {restrict_type := β}
example (g v V c h : β) (h1 : h = 0) (h2 : v = V) (h3 : V > 0) (h4 : g > 0)
(h5 : 0 β€ c) (h6 : c < 1) :
v β€ V :=
by linarith
constant nat.prime : β β Prop
example (x y z : β) (h1 : 2*x + ((-3)*y) < 0) (h2 : (-4)*x + 2*z < 0)
(h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false :=
by linarith
example (x y z : β) (h1 : 2*1*x + (3)*(y*(-1)) < 0) (h2 : (-2)*x*2 < -(z + z))
(h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false :=
by linarith
example (x y z : β€) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0)
(h3 : 12*y - 4* z < 0) : false :=
by linarith
example (x y z : β€) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5)
(h3 : 12*y - 4* z < 0) : false :=
by linarith
example (x y z : β€) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) :
Β¬ 12*y - 4* z < 0 :=
by linarith
example (w x y z : β€) (h1 : 4*x + (-3)*y + 6*w β€ 0) (h2 : (-1)*x < 0)
(h3 : y < 0) (h4 : w β₯ 0) (h5 : nat.prime x.nat_abs) : false :=
by linarith
example (a b c : β) (h1 : a > 0) (h2 : b > 5) (h3 : c < -10)
(h4 : a + b - c < 3) : false :=
by linarith
example (a b c : β) (h2 : b > 0) (h3 : Β¬ b β₯ 0) : false :=
by linarith
example (a b c : β) (h2 : (2 : β) > 3) : a + b - c β₯ 3 :=
by linarith {exfalso := ff}
example (x : β) (hx : x > 0) (h : x.num < 0) : false :=
by linarith [rat.num_pos_iff_pos.mpr hx, h]
example (x : β) (hx : x > 0) (h : x.num < 0) : false :=
by linarith only [rat.num_pos_iff_pos.mpr hx, h]
example (x y z : β) (hx : x β€ 3*y) (h2 : y β€ 2*z) (h3 : x β₯ 6*z) : x = 3*y :=
by linarith
example (x y z : β) (hx : x β€ 3*y) (h2 : y β€ 2*z) (h3 : x β₯ 6*z) : x = 3*y :=
by linarith
example (x y z : β) (hx : Β¬ x > 3*y) (h2 : Β¬ y > 2*z) (h3 : x β₯ 6*z) : x = 3*y :=
by linarith
example (h1 : (1 : β) < 1) : false :=
by linarith
example (a b c : β) (h2 : b > 0) (h3 : b < 0) : nat.prime 10 :=
by linarith
example (a b c : β) : a + b β₯ a :=
by linarith
example (a b c : β) : Β¬ a + b < a :=
by linarith
example (x y : β) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) (h' : (x + 4) * x β₯ 0)
(h'' : (6 + 3 * y) * y β₯ 0) : false :=
by linarith
example (x y : β)
(h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3 β§ (x + 4) * x β₯ 0 β§ (6 + 3 * y) * y β₯ 0) : false :=
by linarith
example (a b i : β) (h1 : Β¬ a < i) (h2 : b < i) (h3 : a β€ b) : false :=
by linarith
example (n : β) (h1 : n β€ 3) (h2 : n > 2) : n = 3 := by linarith
example (z : β) (hz : Β¬ z β₯ 2) (h2 : Β¬ z + 1 β€ 2) : false :=
by linarith
example (z : β) (hz : Β¬ z β₯ 2) : z + 1 β€ 2 :=
by linarith
example (a b c : β) (h1 : 1 / a < b) (h2 : b < c) : 1 / a < c :=
by linarith
example
(N : β) (n : β) (Hirrelevant : n > N)
(A : β) (l : β) (h : A - l β€ -(A - l)) (h_1 : Β¬A β€ -A) (h_2 : Β¬l β€ -l)
(h_3 : -(A - l) < 1) : A < l + 1 := by linarith
example (d : β) (q n : β) (h1 : ((q : β) - 1)*n β₯ 0) (h2 : d = 2/3*(((q : β) - 1)*n)) :
d β€ ((q : β) - 1)*n :=
by linarith
example (d : β) (q n : β) (h1 : ((q : β) - 1)*n β₯ 0) (h2 : d = 2/3*(((q : β) - 1)*n)) :
((q : β) - 1)*n - d = 1/3 * (((q : β) - 1)*n) :=
by linarith
example (a : β) (ha : 0 β€ a) : 0 * 0 β€ 2 * a :=
by linarith
example (x : β) : id x β₯ x :=
by success_if_fail {linarith}; linarith!
example (x y z : β) (hx : x < 5) (hx2 : x > 5) (hy : y < 5000000000) (hz : z > 34*y) : false :=
by linarith only [hx, hx2]
example (x y z : β) (hx : x < 5) (hy : y < 5000000000) (hz : z > 34*y) : x β€ 5 :=
by linarith only [hx]
example (x y : β) (h : x < y) : x β y := by linarith
example (x y : β) (h : x < y) : Β¬ x = y := by linarith
example (u v x y A B : β)
(a : 0 < A)
(a_1 : 0 <= 1 - A)
(a_2 : 0 <= B - 1)
(a_3 : 0 <= B - x)
(a_4 : 0 <= B - y)
(a_5 : 0 <= u)
(a_6 : 0 <= v)
(a_7 : 0 < A - u)
(a_8 : 0 < A - v) :
u * y + v * x + u * v < 3 * A * B :=
by nlinarith
example (u v x y A B : β) : (0 < A) β (A β€ 1) β (1 β€ B)
β (x β€ B) β ( y β€ B)
β (0 β€ u ) β (0 β€ v )
β (u < A) β ( v < A)
β (u * y + v * x + u * v < 3 * A * B) :=
begin
intros,
nlinarith
end
example (u v x y A B : β)
(a : 0 < A)
(a_1 : 0 <= 1 - A)
(a_2 : 0 <= B - 1)
(a_3 : 0 <= B - x)
(a_4 : 0 <= B - y)
(a_5 : 0 <= u)
(a_6 : 0 <= v)
(a_7 : 0 < A - u)
(a_8 : 0 < A - v) :
(0 < A * A)
-> (0 <= A * (1 - A))
-> (0 <= A * (B - 1))
-> (0 <= A * (B - x))
-> (0 <= A * (B - y))
-> (0 <= A * u)
-> (0 <= A * v)
-> (0 < A * (A - u))
-> (0 < A * (A - v))
-> (0 <= (1 - A) * A)
-> (0 <= (1 - A) * (1 - A))
-> (0 <= (1 - A) * (B - 1))
-> (0 <= (1 - A) * (B - x))
-> (0 <= (1 - A) * (B - y))
-> (0 <= (1 - A) * u)
-> (0 <= (1 - A) * v)
-> (0 <= (1 - A) * (A - u))
-> (0 <= (1 - A) * (A - v))
-> (0 <= (B - 1) * A)
-> (0 <= (B - 1) * (1 - A))
-> (0 <= (B - 1) * (B - 1))
-> (0 <= (B - 1) * (B - x))
-> (0 <= (B - 1) * (B - y))
-> (0 <= (B - 1) * u)
-> (0 <= (B - 1) * v)
-> (0 <= (B - 1) * (A - u))
-> (0 <= (B - 1) * (A - v))
-> (0 <= (B - x) * A)
-> (0 <= (B - x) * (1 - A))
-> (0 <= (B - x) * (B - 1))
-> (0 <= (B - x) * (B - x))
-> (0 <= (B - x) * (B - y))
-> (0 <= (B - x) * u)
-> (0 <= (B - x) * v)
-> (0 <= (B - x) * (A - u))
-> (0 <= (B - x) * (A - v))
-> (0 <= (B - y) * A)
-> (0 <= (B - y) * (1 - A))
-> (0 <= (B - y) * (B - 1))
-> (0 <= (B - y) * (B - x))
-> (0 <= (B - y) * (B - y))
-> (0 <= (B - y) * u)
-> (0 <= (B - y) * v)
-> (0 <= (B - y) * (A - u))
-> (0 <= (B - y) * (A - v))
-> (0 <= u * A)
-> (0 <= u * (1 - A))
-> (0 <= u * (B - 1))
-> (0 <= u * (B - x))
-> (0 <= u * (B - y))
-> (0 <= u * u)
-> (0 <= u * v)
-> (0 <= u * (A - u))
-> (0 <= u * (A - v))
-> (0 <= v * A)
-> (0 <= v * (1 - A))
-> (0 <= v * (B - 1))
-> (0 <= v * (B - x))
-> (0 <= v * (B - y))
-> (0 <= v * u)
-> (0 <= v * v)
-> (0 <= v * (A - u))
-> (0 <= v * (A - v))
-> (0 < (A - u) * A)
-> (0 <= (A - u) * (1 - A))
-> (0 <= (A - u) * (B - 1))
-> (0 <= (A - u) * (B - x))
-> (0 <= (A - u) * (B - y))
-> (0 <= (A - u) * u)
-> (0 <= (A - u) * v)
-> (0 < (A - u) * (A - u))
-> (0 < (A - u) * (A - v))
-> (0 < (A - v) * A)
-> (0 <= (A - v) * (1 - A))
-> (0 <= (A - v) * (B - 1))
-> (0 <= (A - v) * (B - x))
-> (0 <= (A - v) * (B - y))
-> (0 <= (A - v) * u)
-> (0 <= (A - v) * v)
-> (0 < (A - v) * (A - u))
-> (0 < (A - v) * (A - v))
->
u * y + v * x + u * v < 3 * A * B :=
begin
intros,
linarith
end
example (A B : β) : (0 < A) β (1 β€ B) β (0 < A / 8 * B) :=
begin
intros, nlinarith
end
example (x y : β) : 0 β€ x ^2 + y ^2 :=
by nlinarith
example (x y : β) : 0 β€ x*x + y*y :=
by nlinarith
example (x y : β) : x = 0 β y = 0 β x*x + y*y = 0 :=
by intros; nlinarith
lemma norm_eq_zero_iff {x y : β} : x * x + y * y = 0 β x = 0 β§ y = 0 :=
begin
split,
{ intro, split; nlinarith },
{ intro, nlinarith }
end
lemma norm_nonpos_right {x y : β} (h1 : x * x + y * y β€ 0) : y = 0 :=
by nlinarith
lemma norm_nonpos_left (x y : β) (h1 : x * x + y * y β€ 0) : x = 0 :=
by nlinarith
variables {E : Type*} [add_group E]
example (f : β€ β E) (h : 0 = f 0) : 1 β€ 2 := by nlinarith
example (a : E) (h : a = a) : 1 β€ 2 := by nlinarith
-- test that the apply bug doesn't affect linarith preprocessing
constant Ξ± : Type
variable [fact false] -- we work in an inconsistent context below
def leΞ± : Ξ± β Ξ± β Prop := Ξ» a b, β c : Ξ±, true
noncomputable instance : linear_ordered_field Ξ± :=
by refine_struct { le := leΞ± }; exact (fact.out false).elim
example (a : Ξ±) (ha : a < 2) : a β€ a :=
by linarith
example (p q r s t u v w : β) (h1 : p + u = q + t) (h2 : r + w = s + v) :
p * r + q * s + (t * w + u * v) = p * s + q * r + (t * v + u * w) :=
by nlinarith
-- Tests involving a norm, including that squares in a type where `sq_nonneg` does not apply
-- do not cause an exception
variables {R : Type*} [ring R] (abs : R β β)
lemma abs_nonneg' : β r, 0 β€ abs r := (fact.out false).elim
example (t : R) (a b : β) (h : a β€ b) : abs (t^2) * a β€ abs (t^2) * b :=
by nlinarith [abs_nonneg' abs (t^2)]
example (t : R) (a b : β) (h : a β€ b) : a β€ abs (t^2) + b :=
by linarith [abs_nonneg' abs (t^2)]
example (t : R) (a b : β) (h : a β€ b) : abs t * a β€ abs t * b :=
by nlinarith [abs_nonneg' abs t]
constant T : Type
attribute [instance]
constant T_zero : ordered_ring T
namespace T
lemma zero_lt_one : (0 : T) < 1 := (fact.out false).elim
lemma works {a b : β} (hab : a β€ b) (h : b < a) : false :=
begin
linarith,
end
end T
example (a b c : β) (h : a β b) (h3 : b β c) (h2 : a β₯ b) : b β c :=
by linarith {split_ne := tt}
example (a b c : β) (h : a β b) (h2 : a β₯ b) (h3 : b β c) : a > b :=
by linarith {split_ne := tt}
example (x y : β) (hβ : 0 β€ y) (hβ : y β€ x) : y * x β€ x * x := by nlinarith
example (x y : β) (hβ : 0 β€ y) (hβ : y β€ x) : y * x β€ x ^ 2 := by nlinarith
axiom foo {x : int} : 1 β€ x β 1 β€ x*x
lemma bar (x y: int)(h : 0 β€ y β§ 1 β€ x) : 1 β€ y + x*x := by linarith [foo h.2]
|
c9a8b1dd765fbcfb1b508320bdc6258a5fac9153 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /src/Lean/Parser.lean | ddb9e777c9e0ddd9b89af231e40af9bbf5979b7c | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 6,277 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Parser.Basic
import Lean.Parser.Level
import Lean.Parser.Term
import Lean.Parser.Tactic
import Lean.Parser.Command
import Lean.Parser.Module
import Lean.Parser.Syntax
import Lean.Parser.Do
namespace Lean
namespace Parser
builtin_initialize
registerAlias "ws" checkWsBefore
registerAlias "noWs" checkNoWsBefore
registerAlias "linebreak" checkLinebreakBefore
registerAlias "num" numLit
registerAlias "str" strLit
registerAlias "char" charLit
registerAlias "name" nameLit
registerAlias "ident" ident
registerAlias "colGt" checkColGt
registerAlias "colGe" checkColGe
registerAlias "lookahead" lookahead
registerAlias "atomic" atomic
registerAlias "many" many
registerAlias "many1" many1
registerAlias "notFollowedBy" (notFollowedBy Β· "element")
registerAlias "optional" optional
registerAlias "withPosition" withPosition
registerAlias "interpolatedStr" interpolatedStr
registerAlias "orelse" orelse
registerAlias "andthen" andthen
registerAlias "incQuotDepth" incQuotDepth
end Parser
namespace PrettyPrinter
namespace Parenthesizer
-- Close the mutual recursion loop; see corresponding `[extern]` in the parenthesizer.
@[export lean_mk_antiquot_parenthesizer]
def mkAntiquot.parenthesizer (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parenthesizer :=
Parser.mkAntiquot.parenthesizer name kind anonymous
-- The parenthesizer auto-generated these instances correctly, but tagged them with the wrong kind, since the actual kind
-- (e.g. `ident`) is not equal to the parser name `Lean.Parser.Term.ident`.
@[builtinParenthesizer ident] def ident.parenthesizer : Parenthesizer := Parser.Term.ident.parenthesizer
@[builtinParenthesizer numLit] def numLit.parenthesizer : Parenthesizer := Parser.Term.num.parenthesizer
@[builtinParenthesizer scientificLit] def scientificLit.parenthesizer : Parenthesizer := Parser.Term.scientific.parenthesizer
@[builtinParenthesizer charLit] def charLit.parenthesizer : Parenthesizer := Parser.Term.char.parenthesizer
@[builtinParenthesizer strLit] def strLit.parenthesizer : Parenthesizer := Parser.Term.str.parenthesizer
open Lean.Parser
@[export lean_pretty_printer_parenthesizer_interpret_parser_descr]
unsafe def interpretParserDescr : ParserDescr β CoreM Parenthesizer
| ParserDescr.const n => getConstAlias parenthesizerAliasesRef n
| ParserDescr.unary n d => return (β getUnaryAlias parenthesizerAliasesRef n) (β interpretParserDescr d)
| ParserDescr.binary n dβ dβ => return (β getBinaryAlias parenthesizerAliasesRef n) (β interpretParserDescr dβ) (β interpretParserDescr dβ)
| ParserDescr.node k prec d => return leadingNode.parenthesizer k prec (β interpretParserDescr d)
| ParserDescr.nodeWithAntiquot _ k d => return node.parenthesizer k (β interpretParserDescr d)
| ParserDescr.sepBy p sep psep trail => return sepBy.parenthesizer (β interpretParserDescr p) sep (β interpretParserDescr psep) trail
| ParserDescr.sepBy1 p sep psep trail => return sepBy1.parenthesizer (β interpretParserDescr p) sep (β interpretParserDescr psep) trail
| ParserDescr.trailingNode k prec lhsPrec d => return trailingNode.parenthesizer k prec lhsPrec (β interpretParserDescr d)
| ParserDescr.symbol tk => return symbol.parenthesizer tk
| ParserDescr.nonReservedSymbol tk includeIdent => return nonReservedSymbol.parenthesizer tk includeIdent
| ParserDescr.parser constName => combinatorParenthesizerAttribute.runDeclFor constName
| ParserDescr.cat catName prec => return categoryParser.parenthesizer catName prec
end Parenthesizer
namespace Formatter
@[export lean_mk_antiquot_formatter]
def mkAntiquot.formatter (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Formatter :=
Parser.mkAntiquot.formatter name kind anonymous
@[builtinFormatter ident] def ident.formatter : Formatter := Parser.Term.ident.formatter
@[builtinFormatter numLit] def numLit.formatter : Formatter := Parser.Term.num.formatter
@[builtinFormatter scientificLit] def scientificLit.formatter : Formatter := Parser.Term.scientific.formatter
@[builtinFormatter charLit] def charLit.formatter : Formatter := Parser.Term.char.formatter
@[builtinFormatter strLit] def strLit.formatter : Formatter := Parser.Term.str.formatter
open Lean.Parser
@[export lean_pretty_printer_formatter_interpret_parser_descr]
unsafe def interpretParserDescr : ParserDescr β CoreM Formatter
| ParserDescr.const n => getConstAlias formatterAliasesRef n
| ParserDescr.unary n d => return (β getUnaryAlias formatterAliasesRef n) (β interpretParserDescr d)
| ParserDescr.binary n dβ dβ => return (β getBinaryAlias formatterAliasesRef n) (β interpretParserDescr dβ) (β interpretParserDescr dβ)
| ParserDescr.node k prec d => return node.formatter k (β interpretParserDescr d)
| ParserDescr.nodeWithAntiquot _ k d => return node.formatter k (β interpretParserDescr d)
| ParserDescr.sepBy p sep psep trail => return sepBy.formatter (β interpretParserDescr p) sep (β interpretParserDescr psep) trail
| ParserDescr.sepBy1 p sep psep trail => return sepBy1.formatter (β interpretParserDescr p) sep (β interpretParserDescr psep) trail
| ParserDescr.trailingNode k prec lhsPrec d => return trailingNode.formatter k prec lhsPrec (β interpretParserDescr d)
| ParserDescr.symbol tk => return symbol.formatter tk
| ParserDescr.nonReservedSymbol tk includeIdent => return nonReservedSymbol.formatter tk
| ParserDescr.parser constName => combinatorFormatterAttribute.runDeclFor constName
| ParserDescr.cat catName prec => return categoryParser.formatter catName
end Formatter
end PrettyPrinter
end Lean
|
a959081013f53fa7488ef184445030fb70f0cd67 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/category_theory/single_obj.lean | 61c406f614b45fea132abb21be680c8c186ecc80 | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 5,351 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import category_theory.endomorphism
import category_theory.groupoid
import category_theory.category.Cat
import data.equiv.mul_add
import algebra.category.Mon.basic
/-!
# Single-object category
Single object category with a given monoid of endomorphisms. It is defined to facilitate transfering
some definitions and lemmas (e.g., conjugacy etc.) from category theory to monoids and groups.
## Main definitions
Given a type `Ξ±` with a monoid structure, `single_obj Ξ±` is `unit` type with `category` structure
such that `End (single_obj Ξ±).star` is the monoid `Ξ±`. This can be extended to a functor `Mon β₯€
Cat`.
If `Ξ±` is a group, then `single_obj Ξ±` is a groupoid.
An element `x : Ξ±` can be reinterpreted as an element of `End (single_obj.star Ξ±)` using
`single_obj.to_End`.
## Implementation notes
- `category_struct.comp` on `End (single_obj.star Ξ±)` is `flip (*)`, not `(*)`. This way
multiplication on `End` agrees with the multiplication on `Ξ±`.
- By default, Lean puts instances into `category_theory` namespace instead of
`category_theory.single_obj`, so we give all names explicitly.
-/
universes u v w
namespace category_theory
/-- Type tag on `unit` used to define single-object categories and groupoids. -/
def single_obj (Ξ± : Type u) : Type := unit
namespace single_obj
variables (Ξ± : Type u)
/-- One and `flip (*)` become `id` and `comp` for morphisms of the single object category. -/
instance category_struct [has_one Ξ±] [has_mul Ξ±] : category_struct (single_obj Ξ±) :=
{ hom := Ξ» _ _, Ξ±,
comp := Ξ» _ _ _ x y, y * x,
id := Ξ» _, 1 }
/-- Monoid laws become category laws for the single object category. -/
instance category [monoid Ξ±] : category (single_obj Ξ±) :=
{ comp_id' := Ξ» _ _, one_mul,
id_comp' := Ξ» _ _, mul_one,
assoc' := Ξ» _ _ _ _ x y z, (mul_assoc z y x).symm }
/-- Groupoid structure on `single_obj Ξ±` -/
instance groupoid [group Ξ±] : groupoid (single_obj Ξ±) :=
{ inv := Ξ» _ _ x, xβ»ΒΉ,
inv_comp' := Ξ» _ _, mul_right_inv,
comp_inv' := Ξ» _ _, mul_left_inv }
protected def star : single_obj Ξ± := unit.star
/-- The endomorphisms monoid of the only object in `single_obj Ξ±` is equivalent to the original
monoid Ξ±. -/
def to_End [monoid Ξ±] : Ξ± β* End (single_obj.star Ξ±) :=
{ map_mul' := Ξ» x y, rfl,
.. equiv.refl Ξ± }
lemma to_End_def [monoid Ξ±] (x : Ξ±) : to_End Ξ± x = x := rfl
/-- There is a 1-1 correspondence between monoid homomorphisms `Ξ± β Ξ²` and functors between the
corresponding single-object categories. It means that `single_obj` is a fully faithful
functor. -/
def map_hom (Ξ± : Type u) (Ξ² : Type v) [monoid Ξ±] [monoid Ξ²] :
(Ξ± β* Ξ²) β (single_obj Ξ±) β₯€ (single_obj Ξ²) :=
{ to_fun := Ξ» f,
{ obj := id,
map := Ξ» _ _, βf,
map_id' := Ξ» _, f.map_one,
map_comp' := Ξ» _ _ _ x y, f.map_mul y x },
inv_fun := Ξ» f,
{ to_fun := @functor.map _ _ _ _ f (single_obj.star Ξ±) (single_obj.star Ξ±),
map_one' := f.map_id _,
map_mul' := Ξ» x y, f.map_comp y x },
left_inv := Ξ» β¨f, hβ, hββ©, rfl,
right_inv := Ξ» f, by cases f; obviously }
lemma map_hom_id (Ξ± : Type u) [monoid Ξ±] : map_hom Ξ± Ξ± (monoid_hom.id Ξ±) = π _ := rfl
lemma map_hom_comp {Ξ± : Type u} {Ξ² : Type v} [monoid Ξ±] [monoid Ξ²] (f : Ξ± β* Ξ²)
{Ξ³ : Type w} [monoid Ξ³] (g : Ξ² β* Ξ³) :
map_hom Ξ± Ξ³ (g.comp f) = map_hom Ξ± Ξ² f β map_hom Ξ² Ξ³ g :=
rfl
end single_obj
end category_theory
open category_theory
namespace monoid_hom
/-- Reinterpret a monoid homomorphism `f : Ξ± β Ξ²` as a functor `(single_obj Ξ±) β₯€ (single_obj Ξ²)`.
See also `category_theory.single_obj.map_hom` for an equivalence between these types. -/
@[reducible] def to_functor {Ξ± : Type u} {Ξ² : Type v} [monoid Ξ±] [monoid Ξ²] (f : Ξ± β* Ξ²) :
(single_obj Ξ±) β₯€ (single_obj Ξ²) :=
single_obj.map_hom Ξ± Ξ² f
@[simp] lemma id_to_functor (Ξ± : Type u) [monoid Ξ±] : (id Ξ±).to_functor = π _ := rfl
@[simp] lemma comp_to_functor {Ξ± : Type u} {Ξ² : Type v} [monoid Ξ±] [monoid Ξ²] (f : Ξ± β* Ξ²)
{Ξ³ : Type w} [monoid Ξ³] (g : Ξ² β* Ξ³) :
(g.comp f).to_functor = f.to_functor β g.to_functor :=
rfl
end monoid_hom
namespace units
variables (Ξ± : Type u) [monoid Ξ±]
/--
The units in a monoid are (multiplicatively) equivalent to
the automorphisms of `star` when we think of the monoid as a single-object category. -/
def to_Aut : units Ξ± β* Aut (single_obj.star Ξ±) :=
(units.map_equiv (single_obj.to_End Ξ±)).trans $
Aut.units_End_equiv_Aut _
@[simp] lemma to_Aut_hom (x : units Ξ±) : (to_Aut Ξ± x).hom = single_obj.to_End Ξ± x := rfl
@[simp] lemma to_Aut_inv (x : units Ξ±) :
(to_Aut Ξ± x).inv = single_obj.to_End Ξ± (xβ»ΒΉ : units Ξ±) :=
rfl
end units
namespace Mon
open category_theory
/-- The fully faithful functor from `Mon` to `Cat`. -/
def to_Cat : Mon β₯€ Cat :=
{ obj := Ξ» x, Cat.of (single_obj x),
map := Ξ» x y f, single_obj.map_hom x y f }
instance to_Cat_full : full to_Cat :=
{ preimage := Ξ» x y, (single_obj.map_hom x y).inv_fun,
witness' := Ξ» x y, by apply equiv.right_inv }
instance to_Cat_faithful : faithful to_Cat :=
{ injectivity' := Ξ» x y, by apply equiv.injective }
end Mon
|
359beeeac19621c08201914d1bde26bf621756b7 | e38e95b38a38a99ecfa1255822e78e4b26f65bb0 | /src/certigrad/det.lean | 99d26515a15b6972dcf2de935bc566be630d5634 | [
"Apache-2.0"
] | permissive | ColaDrill/certigrad | fefb1be3670adccd3bed2f3faf57507f156fd501 | fe288251f623ac7152e5ce555f1cd9d3a20203c2 | refs/heads/master | 1,593,297,324,250 | 1,499,903,753,000 | 1,499,903,753,000 | 97,075,797 | 1 | 0 | null | 1,499,916,210,000 | 1,499,916,210,000 | null | UTF-8 | Lean | false | false | 4,261 | lean | /-
Copyright (c) 2017 Daniel Selsam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Daniel Selsam
Interface for deterministic operators.
-/
import .tgrads .util .tcont
namespace certigrad
open T list
namespace det
def function (ishapes : list S) (oshape : S) : Type := dvec T ishapes β T oshape
def precondition (shapes : list S) : Type := dvec T shapes β Prop
def pullback (ishapes : list S) (oshape : S) : Type := Ξ (xs : dvec T ishapes) (y gy : T oshape) (idx : β) (fshape : S), T fshape
noncomputable def is_odifferentiable {ishapes : list S} {oshape : S} (f : dvec T ishapes β T oshape) (f_pre : dvec T ishapes β Prop) : Prop :=
β (xs : dvec T ishapes), f_pre xs β
β (idx : β) (fshape : S), at_idx ishapes idx fshape β
β (k : T oshape β β), is_cdifferentiable k (f xs) β is_cdifferentiable (Ξ» ΞΈβ, k (f $ dvec.update_at ΞΈβ xs idx)) (dvec.get fshape xs idx)
noncomputable def pullback_correct {ishapes : list S} {oshape : S}
(f : dvec T ishapes β T oshape)
(f_pre : dvec T ishapes β Prop)
(f_pb : dvec T ishapes β T oshape β T oshape β β β Ξ fshape, T fshape) : Prop :=
β (xs : dvec T ishapes) (y : T oshape), y = f xs β
β (g_out : T oshape) {idx : β} {fshape : S}, at_idx ishapes idx fshape β
f_pre xs β
f_pb xs y g_out idx fshape
=
T.tmulT (T.D (Ξ» ΞΈβ, f (dvec.update_at ΞΈβ xs idx)) (dvec.get fshape xs idx)) g_out
noncomputable def is_ocontinuous {ishapes : list S} {oshape : S} (f : dvec T ishapes β T oshape) (f_pre : dvec T ishapes β Prop) : Prop :=
β (xs : dvec T ishapes) {idx : β} {ishape : S}, at_idx ishapes idx ishape β
f_pre xs β T.is_continuous (Ξ» ΞΈβ, f (dvec.update_at ΞΈβ xs idx)) (dvec.get ishape xs idx)
inductive op : Ξ (ishapes : list S) (oshape : S), Type
| mk : β {ishapes : list S} {oshape : S} (id : string)
(f :function ishapes oshape) (f_pre : precondition ishapes) (f_pb : pullback ishapes oshape),
is_odifferentiable f f_pre β pullback_correct f f_pre f_pb β is_ocontinuous f f_pre β
op ishapes oshape
-- Note: we keep this separate because we use it in a program transformation
-- (we want to be able to pattern match on it)
| mvn_iso_empirical_kl : Ξ (shape : S), op [shape, shape, shape] []
namespace op
def f : Ξ {ishapes : list S} {oshape : S}, op ishapes oshape β function ishapes oshape
| ._ ._ (@op.mk ishapes id oshape fn f_pre f_pb is_odiff pb_correct is_continuous) := fn
| ._ ._ (@op.mvn_iso_empirical_kl shape) := Ξ» xs, T.mvn_iso_empirical_kl xs^.head xs^.head2 xs^.head3
def pre : Ξ {ishapes : list S} {oshape : S}, op ishapes oshape β precondition ishapes
| ._ ._ (@op.mk id ishapes oshape fn f_pre f_pb is_odiff pb_correct is_continuous) := f_pre
| ._ ._ (@mvn_iso_empirical_kl shape) := Ξ» xs, false
def pb : Ξ {ishapes : list S} {oshape : S}, op ishapes oshape β pullback ishapes oshape
| ._ ._ (@op.mk id ishapes oshape fn f_pre f_pb is_odiff pb_correct is_continuous) := f_pb
| ._ ._ (@mvn_iso_empirical_kl shape) := Ξ» xs y gy idx fshape, T.error "mvn_iso_empirical_kl: gradients not implemented"
def is_odiff : Ξ {ishapes : list S} {oshape : S} (op : op ishapes oshape), is_odifferentiable op^.f op^.pre
| ._ ._ (@op.mk id ishapes oshape fn f_pre f_pb f_is_odiff f_pb_correct f_is_continuous) := f_is_odiff
| ._ ._ (@mvn_iso_empirical_kl shape) := Ξ» xs H_pre idx fshape H_fshape_at_idx k H_k, false.rec _ H_pre
def pb_correct : Ξ {ishapes : list S} {oshape : S} (op : op ishapes oshape), pullback_correct op^.f op^.pre op^.pb
| ._ ._ (@op.mk id ishapes oshape fn f_pre f_pb f_is_odiff f_pb_correct f_is_continuous) := f_pb_correct
| ._ ._ (@mvn_iso_empirical_kl shape) := Ξ» xs y _ g_out _ _ H_at_idx H_pre, false.rec _ H_pre
def is_ocont : Ξ {ishapes : list S} {oshape : S} (op : op ishapes oshape), is_ocontinuous op^.f op^.pre
| ._ ._ (@op.mk id ishapes oshape fn f_pre f_pb f_is_odiff f_pb_correct f_is_continuous) := f_is_continuous
| ._ ._ (@mvn_iso_empirical_kl shape) := Ξ» xs idx ishape H_ishape_at_idx H_pre, false.rec _ H_pre
end op
end det
end certigrad
|
be4427093ae56dc7de24735fe3fe47ace59cd40e | 1717bcbca047a0d25d687e7e9cd482fba00d058f | /src/topology/algebra/group.lean | a6ba84ff7053082a84e0ff58dfc4f991bb65850f | [
"Apache-2.0"
] | permissive | swapnilkapoor22/mathlib | 51ad5804e6a0635ed5c7611cee73e089ab271060 | 3e7efd4ecd5d379932a89212eebd362beb01309e | refs/heads/master | 1,676,467,741,465 | 1,610,301,556,000 | 1,610,301,556,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,342 | lean | /-
Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes HΓΆlzl, Mario Carneiro, Patrick Massot
-/
import order.filter.pointwise
import group_theory.quotient_group
import topology.algebra.monoid
import topology.homeomorph
/-!
# Theory of topological groups
This file defines the following typeclasses:
* `topological_group`, `topological_add_group`: multiplicative and additive topological groups,
i.e., groups with continuous `(*)` and `(β»ΒΉ)` / `(+)` and `(-)`;
* `has_continuous_sub G` means that `G` has a continuous subtraction operation.
There is an instance deducing `has_continuous_sub` from `topological_group` but we use a separate
typeclass because, e.g., `β` and `ββ₯0` have continuous subtraction but are not additive groups.
We also define `homeomorph` versions of several `equiv`s: `homeomorph.mul_left`,
`homeomorph.mul_right`, `homeomorph.inv`, and prove a few facts about neighbourhood filters in
groups.
## Tags
topological space, group, topological group
-/
open classical set filter topological_space function
open_locale classical topological_space filter
universes u v w x
variables {Ξ± : Type u} {Ξ² : Type v} {G : Type w} {H : Type x}
section continuous_mul_group
/-!
### Groups with continuous multiplication
In this section we prove a few statements about groups with continuous `(*)`.
-/
variables [topological_space G] [group G] [has_continuous_mul G]
/-- Multiplication from the left in a topological group as a homeomorphism. -/
@[to_additive "Addition from the left in a topological additive group as a homeomorphism."]
protected def homeomorph.mul_left (a : G) : G ββ G :=
{ continuous_to_fun := continuous_const.mul continuous_id,
continuous_inv_fun := continuous_const.mul continuous_id,
.. equiv.mul_left a }
@[to_additive]
lemma is_open_map_mul_left (a : G) : is_open_map (Ξ» x, a * x) :=
(homeomorph.mul_left a).is_open_map
@[to_additive]
lemma is_closed_map_mul_left (a : G) : is_closed_map (Ξ» x, a * x) :=
(homeomorph.mul_left a).is_closed_map
/-- Multiplication from the right in a topological group as a homeomorphism. -/
@[to_additive "Addition from the right in a topological additive group as a homeomorphism."]
protected def homeomorph.mul_right (a : G) :
G ββ G :=
{ continuous_to_fun := continuous_id.mul continuous_const,
continuous_inv_fun := continuous_id.mul continuous_const,
.. equiv.mul_right a }
@[to_additive]
lemma is_open_map_mul_right (a : G) : is_open_map (Ξ» x, x * a) :=
(homeomorph.mul_right a).is_open_map
@[to_additive]
lemma is_closed_map_mul_right (a : G) : is_closed_map (Ξ» x, x * a) :=
(homeomorph.mul_right a).is_closed_map
@[to_additive]
lemma is_open_map_div_right (a : G) : is_open_map (Ξ» x, x / a) :=
by simpa only [div_eq_mul_inv] using is_open_map_mul_right (aβ»ΒΉ)
@[to_additive]
lemma is_closed_map_div_right (a : G) : is_closed_map (Ξ» x, x / a) :=
by simpa only [div_eq_mul_inv] using is_closed_map_mul_right (aβ»ΒΉ)
end continuous_mul_group
section topological_group
/-!
### Topological groups
A topological group is a group in which the multiplication and inversion operations are
continuous. Topological additive groups are defined in the same way. Equivalently, we can require
that the division operation `Ξ» x y, x * yβ»ΒΉ` (resp., subtraction) is continuous.
-/
/-- A topological (additive) group is a group in which the addition and negation operations are
continuous. -/
class topological_add_group (G : Type u) [topological_space G] [add_group G]
extends has_continuous_add G : Prop :=
(continuous_neg : continuous (Ξ»a:G, -a))
/-- A topological group is a group in which the multiplication and inversion operations are
continuous. -/
@[to_additive]
class topological_group (G : Type*) [topological_space G] [group G]
extends has_continuous_mul G : Prop :=
(continuous_inv : continuous (has_inv.inv : G β G))
variables [topological_space G] [group G] [topological_group G]
export topological_group (continuous_inv)
export topological_add_group (continuous_neg)
@[to_additive]
lemma continuous_on_inv {s : set G} : continuous_on has_inv.inv s :=
continuous_inv.continuous_on
@[to_additive]
lemma continuous_within_at_inv {s : set G} {x : G} : continuous_within_at has_inv.inv s x :=
continuous_inv.continuous_within_at
@[to_additive]
lemma continuous_at_inv {x : G} : continuous_at has_inv.inv x :=
continuous_inv.continuous_at
@[to_additive]
lemma tendsto_inv (a : G) : tendsto has_inv.inv (π a) (π (aβ»ΒΉ)) :=
continuous_at_inv
/-- If a function converges to a value in a multiplicative topological group, then its inverse
converges to the inverse of this value. For the version in normed fields assuming additionally
that the limit is nonzero, use `tendsto.inv'`. -/
@[to_additive]
lemma filter.tendsto.inv {f : Ξ± β G} {l : filter Ξ±} {y : G} (h : tendsto f l (π y)) :
tendsto (Ξ» x, (f x)β»ΒΉ) l (π yβ»ΒΉ) :=
(continuous_inv.tendsto y).comp h
variables [topological_space Ξ±] {f : Ξ± β G} {s : set Ξ±} {x : Ξ±}
@[continuity, to_additive]
lemma continuous.inv (hf : continuous f) : continuous (Ξ»x, (f x)β»ΒΉ) :=
continuous_inv.comp hf
attribute [continuity] continuous.neg -- TODO
@[to_additive]
lemma continuous_on.inv (hf : continuous_on f s) : continuous_on (Ξ»x, (f x)β»ΒΉ) s :=
continuous_inv.comp_continuous_on hf
@[to_additive]
lemma continuous_within_at.inv (hf : continuous_within_at f s x) :
continuous_within_at (Ξ» x, (f x)β»ΒΉ) s x :=
hf.inv
@[instance, to_additive]
instance [topological_space H] [group H] [topological_group H] :
topological_group (G Γ H) :=
{ continuous_inv := continuous_inv.prod_map continuous_inv }
variable (G)
/-- Inversion in a topological group as a homeomorphism. -/
@[to_additive "Negation in a topological group as a homeomorphism."]
protected def homeomorph.inv : G ββ G :=
{ continuous_to_fun := continuous_inv,
continuous_inv_fun := continuous_inv,
.. equiv.inv G }
@[to_additive]
lemma nhds_one_symm : comap has_inv.inv (π (1 : G)) = π (1 : G) :=
((homeomorph.inv G).comap_nhds_eq _).trans (congr_arg nhds one_inv)
variable {G}
@[to_additive]
lemma inv_closure (s : set G) : (closure s)β»ΒΉ = closure sβ»ΒΉ :=
(homeomorph.inv G).preimage_closure s
@[to_additive exists_nhds_half_neg]
lemma exists_nhds_split_inv {s : set G} (hs : s β π (1 : G)) :
β V β π (1 : G), β (v β V) (w β V), v / w β s :=
have ((Ξ»p : G Γ G, p.1 * p.2β»ΒΉ) β»ΒΉ' s) β π ((1, 1) : G Γ G),
from continuous_at_fst.mul continuous_at_snd.inv (by simpa),
by simpa only [div_eq_mul_inv, nhds_prod_eq, mem_prod_self_iff, prod_subset_iff, mem_preimage]
using this
@[to_additive]
lemma nhds_translation_mul_inv (x : G) : comap (Ξ» y : G, y * xβ»ΒΉ) (π 1) = π x :=
((homeomorph.mul_right xβ»ΒΉ).comap_nhds_eq 1).trans $ show π (1 * xβ»ΒΉβ»ΒΉ) = π x, by simp
@[to_additive]
lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G}
(tg : @topological_group G t _) (tg' : @topological_group G t' _)
(h : @nhds G t 1 = @nhds G t' 1) : t = t' :=
eq_of_nhds_eq_nhds $ Ξ» x, by
rw [β @nhds_translation_mul_inv G t _ _ x , β @nhds_translation_mul_inv G t' _ _ x , β h]
@[to_additive]
lemma topological_group.of_nhds_aux {G : Type*} [group G] [topological_space G]
(hinv : tendsto (Ξ» (x : G), xβ»ΒΉ) (π 1) (π 1))
(hleft : β (xβ : G), π xβ = map (Ξ» (x : G), xβ * x) (π 1))
(hconj : β (xβ : G), map (Ξ» (x : G), xβ * x * xββ»ΒΉ) (π 1) β€ π 1) : continuous (Ξ» x : G, xβ»ΒΉ) :=
begin
rw continuous_iff_continuous_at,
rintros xβ,
have key : (Ξ» x, (xβ*x)β»ΒΉ) = (Ξ» x, xββ»ΒΉ*x) β (Ξ» x, xβ*x*xββ»ΒΉ) β (Ξ» x, xβ»ΒΉ),
by {ext ; simp[mul_assoc] },
calc map (Ξ» x, xβ»ΒΉ) (π xβ)
= map (Ξ» x, xβ»ΒΉ) (map (Ξ» x, xβ*x) $ π 1) : by rw hleft
... = map (Ξ» x, (xβ*x)β»ΒΉ) (π 1) : by rw filter.map_map
... = map (((Ξ» x, xββ»ΒΉ*x) β (Ξ» x, xβ*x*xββ»ΒΉ)) β (Ξ» x, xβ»ΒΉ)) (π 1) : by rw key
... = map ((Ξ» x, xββ»ΒΉ*x) β (Ξ» x, xβ*x*xββ»ΒΉ)) _ : by rw β filter.map_map
... β€ map ((Ξ» x, xββ»ΒΉ * x) β Ξ» x, xβ * x * xββ»ΒΉ) (π 1) : map_mono hinv
... = map (Ξ» x, xββ»ΒΉ * x) (map (Ξ» x, xβ * x * xββ»ΒΉ) (π 1)) : filter.map_map
... β€ map (Ξ» x, xββ»ΒΉ * x) (π 1) : map_mono (hconj xβ)
... = π xββ»ΒΉ : (hleft _).symm
end
@[to_additive]
lemma topological_group.of_nhds_one' {G : Type*} [group G] [topological_space G]
(hmul : tendsto (uncurry ((*) : G β G β G)) ((π 1) ΓαΆ π 1) (π 1))
(hinv : tendsto (Ξ» x : G, xβ»ΒΉ) (π 1) (π 1))
(hleft : β xβ : G, π xβ = map (Ξ» x, xβ*x) (π 1))
(hright : β xβ : G, π xβ = map (Ξ» x, x*xβ) (π 1)) : topological_group G :=
begin
refine { continuous_mul := (has_continuous_mul.of_nhds_one hmul hleft hright).continuous_mul,
continuous_inv := topological_group.of_nhds_aux hinv hleft _ },
intros xβ,
suffices : map (Ξ» (x : G), xβ * x * xββ»ΒΉ) (π 1) = π 1, by simp [this, le_refl],
rw [show (Ξ» x, xβ * x * xββ»ΒΉ) = (Ξ» x, xβ * x) β Ξ» x, x*xββ»ΒΉ, by {ext, simp [mul_assoc] },
β filter.map_map, β hright, hleft xββ»ΒΉ, filter.map_map],
convert map_id,
ext,
simp
end
@[to_additive]
lemma topological_group.of_nhds_one {G : Type*} [group G] [topological_space G]
(hmul : tendsto (uncurry ((*) : G β G β G)) ((π 1) ΓαΆ π 1) (π 1))
(hinv : tendsto (Ξ» x : G, xβ»ΒΉ) (π 1) (π 1))
(hleft : β xβ : G, π xβ = map (Ξ» x, xβ*x) (π 1))
(hconj : β xβ : G, tendsto (Ξ» x, xβ*x*xββ»ΒΉ) (π 1) (π 1)) : topological_group G :=
{ continuous_mul := begin
rw continuous_iff_continuous_at,
rintros β¨xβ, yββ©,
have key : (Ξ» (p : G Γ G), xβ * p.1 * (yβ * p.2)) =
((Ξ» x, xβ*yβ*x) β (uncurry (*)) β (prod.map (Ξ» x, yββ»ΒΉ*x*yβ) id)),
by { ext, simp [uncurry, prod.map, mul_assoc] },
specialize hconj yββ»ΒΉ, rw inv_inv at hconj,
calc map (Ξ» (p : G Γ G), p.1 * p.2) (π (xβ, yβ))
= map (Ξ» (p : G Γ G), p.1 * p.2) ((π xβ) ΓαΆ π yβ)
: by rw nhds_prod_eq
... = map (Ξ» (p : G Γ G), xβ * p.1 * (yβ * p.2)) ((π 1) ΓαΆ (π 1))
: by rw [hleft xβ, hleft yβ, prod_map_map_eq, filter.map_map]
... = map (((Ξ» x, xβ*yβ*x) β (uncurry (*))) β (prod.map (Ξ» x, yββ»ΒΉ*x*yβ) id))((π 1) ΓαΆ (π 1))
: by rw key
... = map ((Ξ» x, xβ*yβ*x) β (uncurry (*))) ((map (Ξ» x, yββ»ΒΉ*x*yβ) $ π 1) ΓαΆ (π 1))
: by rw [β filter.map_map, β prod_map_map_eq', map_id]
... β€ map ((Ξ» x, xβ*yβ*x) β (uncurry (*))) ((π 1) ΓαΆ (π 1))
: map_mono (filter.prod_mono hconj $ le_refl _)
... = map (Ξ» x, xβ*yβ*x) (map (uncurry (*)) ((π 1) ΓαΆ (π 1))) : by rw filter.map_map
... β€ map (Ξ» x, xβ*yβ*x) (π 1) : map_mono hmul
... = π (xβ*yβ) : (hleft _).symm
end,
continuous_inv := topological_group.of_nhds_aux hinv hleft hconj}
@[to_additive]
lemma topological_group.of_comm_of_nhds_one {G : Type*} [comm_group G] [topological_space G]
(hmul : tendsto (uncurry ((*) : G β G β G)) ((π 1) ΓαΆ π 1) (π 1))
(hinv : tendsto (Ξ» x : G, xβ»ΒΉ) (π 1) (π 1))
(hleft : β xβ : G, π xβ = map (Ξ» x, xβ*x) (π 1)) : topological_group G :=
topological_group.of_nhds_one hmul hinv hleft (by simpa using tendsto_id)
end topological_group
section quotient_topological_group
variables [topological_space G] [group G] [topological_group G] (N : subgroup G) (n : N.normal)
@[to_additive]
instance {G : Type*} [group G] [topological_space G] (N : subgroup G) :
topological_space (quotient_group.quotient N) :=
quotient.topological_space
open quotient_group
@[to_additive]
lemma quotient_group.is_open_map_coe : is_open_map (coe : G β quotient N) :=
begin
intros s s_op,
change is_open ((coe : G β quotient N) β»ΒΉ' (coe '' s)),
rw quotient_group.preimage_image_coe N s,
exact is_open_Union (Ξ» n, is_open_map_mul_right n s s_op)
end
@[to_additive]
instance topological_group_quotient [N.normal] : topological_group (quotient N) :=
{ continuous_mul := begin
have cont : continuous ((coe : G β quotient N) β (Ξ» (p : G Γ G), p.fst * p.snd)) :=
continuous_quot_mk.comp continuous_mul,
have quot : quotient_map (Ξ» p : G Γ G, ((p.1:quotient N), (p.2:quotient N))),
{ apply is_open_map.to_quotient_map,
{ exact (quotient_group.is_open_map_coe N).prod (quotient_group.is_open_map_coe N) },
{ exact continuous_quot_mk.prod_map continuous_quot_mk },
{ exact (surjective_quot_mk _).prod_map (surjective_quot_mk _) } },
exact (quotient_map.continuous_iff quot).2 cont,
end,
continuous_inv := begin
have : continuous ((coe : G β quotient N) β (Ξ» (a : G), aβ»ΒΉ)) :=
continuous_quot_mk.comp continuous_inv,
convert continuous_quotient_lift _ this,
end }
attribute [instance] topological_add_group_quotient
end quotient_topological_group
/-- A typeclass saying that `Ξ» p : G Γ G, p.1 - p.2` is a continuous function. This property
automatically holds for topological additive groups but it also holds, e.g., for `ββ₯0`. -/
class has_continuous_sub (G : Type*) [topological_space G] [has_sub G] : Prop :=
(continuous_sub : continuous (Ξ» p : G Γ G, p.1 - p.2))
@[priority 100] -- see Note [lower instance priority]
instance topological_add_group.to_has_continuous_sub [topological_space G] [add_group G]
[topological_add_group G] :
has_continuous_sub G :=
β¨by { simp only [sub_eq_add_neg], exact continuous_fst.add continuous_snd.neg }β©
export has_continuous_sub (continuous_sub)
section has_continuous_sub
variables [topological_space G] [has_sub G] [has_continuous_sub G]
lemma filter.tendsto.sub {f g : Ξ± β G} {l : filter Ξ±} {a b : G} (hf : tendsto f l (π a))
(hg : tendsto g l (π b)) :
tendsto (Ξ»x, f x - g x) l (π (a - b)) :=
(continuous_sub.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
variables [topological_space Ξ±] {f g : Ξ± β G} {s : set Ξ±} {x : Ξ±}
@[continuity] lemma continuous.sub (hf : continuous f) (hg : continuous g) :
continuous (Ξ» x, f x - g x) :=
continuous_sub.comp (hf.prod_mk hg : _)
lemma continuous_within_at.sub (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) :
continuous_within_at (Ξ» x, f x - g x) s x :=
hf.sub hg
lemma continuous_on.sub (hf : continuous_on f s) (hg : continuous_on g s) :
continuous_on (Ξ»x, f x - g x) s :=
Ξ» x hx, (hf x hx).sub (hg x hx)
end has_continuous_sub
lemma nhds_translation [topological_space G] [add_group G] [topological_add_group G] (x : G) :
comap (Ξ»y:G, y - x) (π 0) = π x :=
by simpa only [sub_eq_add_neg] using nhds_translation_add_neg x
/-- additive group with a neighbourhood around 0.
Only used to construct a topology and uniform space.
This is currently only available for commutative groups, but it can be extended to
non-commutative groups too.
-/
class add_group_with_zero_nhd (G : Type u) extends add_comm_group G :=
(Z [] : filter G)
(zero_Z : pure 0 β€ Z)
(sub_Z : tendsto (Ξ»p:GΓG, p.1 - p.2) (Z ΓαΆ Z) Z)
namespace add_group_with_zero_nhd
variables (G) [add_group_with_zero_nhd G]
local notation `Z` := add_group_with_zero_nhd.Z
@[priority 100] -- see Note [lower instance priority]
instance : topological_space G :=
topological_space.mk_of_nhds $ Ξ»a, map (Ξ»x, x + a) (Z G)
variables {G}
lemma neg_Z : tendsto (Ξ»a:G, - a) (Z G) (Z G) :=
have tendsto (Ξ»a, (0:G)) (Z G) (Z G),
by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt},
have tendsto (Ξ»a:G, 0 - a) (Z G) (Z G), from
sub_Z.comp (tendsto.prod_mk this tendsto_id),
by simpa
lemma add_Z : tendsto (Ξ»p:GΓG, p.1 + p.2) (Z G ΓαΆ Z G) (Z G) :=
suffices tendsto (Ξ»p:GΓG, p.1 - -p.2) (Z G ΓαΆ Z G) (Z G),
by simpa [sub_eq_add_neg],
sub_Z.comp (tendsto.prod_mk tendsto_fst (neg_Z.comp tendsto_snd))
lemma exists_Z_half {s : set G} (hs : s β Z G) : β V β Z G, β (v β V) (w β V), v + w β s :=
begin
have : ((Ξ»a:GΓG, a.1 + a.2) β»ΒΉ' s) β Z G ΓαΆ Z G := add_Z (by simpa using hs),
rcases mem_prod_self_iff.1 this with β¨V, H, H'β©,
exact β¨V, H, prod_subset_iff.1 H'β©
end
lemma nhds_eq (a : G) : π a = map (Ξ»x, x + a) (Z G) :=
topological_space.nhds_mk_of_nhds _ _
(assume a, calc pure a = map (Ξ»x, x + a) (pure 0) : by simp
... β€ _ : map_mono zero_Z)
(assume b s hs,
let β¨t, ht, eqtβ© := exists_Z_half hs in
have t0 : (0:G) β t, by simpa using zero_Z ht,
begin
refine β¨(Ξ»x:G, x + b) '' t, image_mem_map ht, _, _β©,
{ refine set.image_subset_iff.2 (assume b hbt, _),
simpa using eqt 0 t0 b hbt },
{ rintros _ β¨c, hb, rflβ©,
refine (Z G).sets_of_superset ht (assume x hxt, _),
simpa [add_assoc] using eqt _ hxt _ hb }
end)
lemma nhds_zero_eq_Z : π 0 = Z G := by simp [nhds_eq]; exact filter.map_id
@[priority 100] -- see Note [lower instance priority]
instance : has_continuous_add G :=
β¨ continuous_iff_continuous_at.2 $ assume β¨a, bβ©,
begin
rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq,
tendsto_map'_iff],
suffices : tendsto ((Ξ»x:G, (a + b) + x) β (Ξ»p:GΓG,p.1 + p.2)) (Z G ΓαΆ Z G)
(map (Ξ»x:G, (a + b) + x) (Z G)),
{ simpa [(β), add_comm, add_left_comm] },
exact tendsto_map.comp add_Z
end β©
@[priority 100] -- see Note [lower instance priority]
instance : topological_add_group G :=
β¨continuous_iff_continuous_at.2 $ assume a,
begin
rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff],
suffices : tendsto ((Ξ»x:G, x - a) β (Ξ»x:G, -x)) (Z G) (map (Ξ»x:G, x - a) (Z G)),
{ simpa [(β), add_comm, sub_eq_add_neg] using this },
exact tendsto_map.comp neg_Z
endβ©
end add_group_with_zero_nhd
section filter_mul
section
variables [topological_space G] [group G] [topological_group G]
@[to_additive]
lemma is_open.mul_left {s t : set G} : is_open t β is_open (s * t) := Ξ» ht,
begin
have : βa, is_open ((Ξ» (x : G), a * x) '' t) :=
assume a, is_open_map_mul_left a t ht,
rw β Union_mul_left_image,
exact is_open_Union (Ξ»a, is_open_Union $ Ξ»ha, this _),
end
@[to_additive]
lemma is_open.mul_right {s t : set G} : is_open s β is_open (s * t) := Ξ» hs,
begin
have : βa, is_open ((Ξ» (x : G), x * a) '' s),
assume a, apply is_open_map_mul_right, exact hs,
rw β Union_mul_right_image,
exact is_open_Union (Ξ»a, is_open_Union $ Ξ»ha, this _),
end
variables (G)
lemma topological_group.t1_space (h : @is_closed G _ {1}) : t1_space G :=
β¨assume x, by { convert is_closed_map_mul_right x _ h, simp }β©
lemma topological_group.regular_space [t1_space G] : regular_space G :=
β¨assume s a hs ha,
let f := Ξ» p : G Γ G, p.1 * (p.2)β»ΒΉ in
have hf : continuous f := continuous_fst.mul continuous_snd.inv,
-- a β -s implies f (a, 1) β -s, and so (a, 1) β fβ»ΒΉ' (-s);
-- and so can find tβ tβ open such that a β tβ Γ tβ β fβ»ΒΉ' (-s)
let β¨tβ, tβ, htβ, htβ, a_mem_tβ, one_mem_tβ, t_subsetβ© :=
is_open_prod_iff.1 ((is_open_compl_iff.2 hs).preimage hf) a (1:G) (by simpa [f]) in
begin
use [s * tβ, htβ.mul_left, Ξ» x hx, β¨x, 1, hx, one_mem_tβ, mul_one _β©],
apply inf_principal_eq_bot,
rw mem_nhds_sets_iff,
refine β¨tβ, _, htβ, a_mem_tββ©,
rintros x hx β¨y, z, hy, hz, yzβ©,
have : x * zβ»ΒΉ β sαΆ := (prod_subset_iff.1 t_subset) x hx z hz,
have : x * zβ»ΒΉ β s, rw β yz, simpa,
contradiction
endβ©
local attribute [instance] topological_group.regular_space
lemma topological_group.t2_space [t1_space G] : t2_space G := regular_space.t2_space G
end
section
/-! Some results about an open set containing the product of two sets in a topological group. -/
variables [topological_space G] [group G] [topological_group G]
/-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1`
such that `KV β U`. -/
@[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0`
such that `K + V β U`."]
lemma compact_open_separated_mul {K U : set G} (hK : is_compact K) (hU : is_open U) (hKU : K β U) :
β V : set G, is_open V β§ (1 : G) β V β§ K * V β U :=
begin
let W : G β set G := Ξ» x, (Ξ» y, x * y) β»ΒΉ' U,
have h1W : β x, is_open (W x) := Ξ» x, hU.preimage (continuous_mul_left x),
have h2W : β x β K, (1 : G) β W x := Ξ» x hx, by simp only [mem_preimage, mul_one, hKU hx],
choose V hV using Ξ» x : K, exists_open_nhds_one_mul_subset (mem_nhds_sets (h1W x) (h2W x.1 x.2)),
let X : K β set G := Ξ» x, (Ξ» y, (x : G)β»ΒΉ * y) β»ΒΉ' (V x),
cases hK.elim_finite_subcover X (Ξ» x, (hV x).1.preimage (continuous_mul_left xβ»ΒΉ)) _ with t ht, swap,
{ intros x hx, rw [mem_Union], use β¨x, hxβ©, rw [mem_preimage], convert (hV _).2.1,
simp only [mul_left_inv, subtype.coe_mk] },
refine β¨β x β t, V x, is_open_bInter (finite_mem_finset _) (Ξ» x hx, (hV x).1), _, _β©,
{ simp only [mem_Inter], intros x hx, exact (hV x).2.1 },
rintro _ β¨x, y, hx, hy, rflβ©, simp only [mem_Inter] at hy,
have := ht hx, simp only [mem_Union, mem_preimage] at this, rcases this with β¨z, h1z, h2zβ©,
have : (z : G)β»ΒΉ * x * y β W z := (hV z).2.2 (mul_mem_mul h2z (hy z h1z)),
rw [mem_preimage] at this, convert this using 1, simp only [mul_assoc, mul_inv_cancel_left]
end
/-- A compact set is covered by finitely many left multiplicative translates of a set
with non-empty interior. -/
@[to_additive "A compact set is covered by finitely many left additive translates of a set
with non-empty interior."]
lemma compact_covered_by_mul_left_translates {K V : set G} (hK : is_compact K)
(hV : (interior V).nonempty) : β t : finset G, K β β g β t, (Ξ» h, g * h) β»ΒΉ' V :=
begin
cases hV with gβ hgβ,
rcases is_compact.elim_finite_subcover hK (Ξ» x : G, interior $ (Ξ» h, x * h) β»ΒΉ' V) _ _ with β¨t, htβ©,
{ refine β¨t, subset.trans ht _β©,
apply Union_subset_Union, intro g, apply Union_subset_Union, intro hg, apply interior_subset },
{ intro g, apply is_open_interior },
{ intros g hg, rw [mem_Union], use gβ * gβ»ΒΉ,
apply preimage_interior_subset_interior_preimage, exact continuous_const.mul continuous_id,
rwa [mem_preimage, inv_mul_cancel_right] }
end
end
section
variables [topological_space G] [comm_group G] [topological_group G]
@[to_additive]
lemma nhds_mul (x y : G) : π (x * y) = π x * π y :=
filter_eq $ set.ext $ assume s,
begin
rw [β nhds_translation_mul_inv x, β nhds_translation_mul_inv y, β nhds_translation_mul_inv (x*y)],
split,
{ rintros β¨t, ht, tsβ©,
rcases exists_nhds_one_split ht with β¨V, V1, hβ©,
refine β¨(Ξ»a, a * xβ»ΒΉ) β»ΒΉ' V, (Ξ»a, a * yβ»ΒΉ) β»ΒΉ' V,
β¨V, V1, subset.refl _β©, β¨V, V1, subset.refl _β©, _β©,
rintros a β¨v, w, v_mem, w_mem, rflβ©,
apply ts,
simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * xβ»ΒΉ) v_mem (w * yβ»ΒΉ) w_mem },
{ rintros β¨a, c, β¨b, hb, baβ©, β¨d, hd, dcβ©, acβ©,
refine β¨b β© d, inter_mem_sets hb hd, assume v, _β©,
simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *,
rintros β¨vb, vdβ©,
refine ac β¨v * yβ»ΒΉ, y, _, _, _β©,
{ rw β mul_assoc _ _ _ at vb, exact ba _ vb },
{ apply dc y, rw mul_right_inv, exact mem_of_nhds hd },
{ simp only [inv_mul_cancel_right] } }
end
@[to_additive]
lemma nhds_is_mul_hom : is_mul_hom (Ξ»x:G, π x) := β¨Ξ»_ _, nhds_mul _ _β©
end
end filter_mul
instance additive.topological_add_group {G} [h : topological_space G]
[group G] [topological_group G] : @topological_add_group (additive G) h _ :=
{ continuous_neg := @continuous_inv G _ _ _ }
instance multiplicative.topological_group {G} [h : topological_space G]
[add_group G] [topological_add_group G] : @topological_group (multiplicative G) h _ :=
{ continuous_inv := @continuous_neg G _ _ _ }
|
03294a72d39ce440c54413d9f1a38a4b93d3ee5e | 42c01158c2730cc6ac3e058c1339c18cb90366e2 | /xenalib/M1Fstuff.lean | a030730d9b45d4b15645a0aa83e5caf6db196a44 | [] | no_license | ChrisHughes24/xena | c80d94355d0c2ae8deddda9d01e6d31bc21c30ae | 337a0d7c9f0e255e08d6d0a383e303c080c6ec0c | refs/heads/master | 1,631,059,898,392 | 1,511,200,551,000 | 1,511,200,551,000 | 111,468,589 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,966 | lean | import analysis.real init.classical tactic.norm_num
namespace M1F
theorem floor_real_exists : β (x : β), β (n : β€), βn β€ x β§ x < n+1 :=
begin
intro x,
have H : β (q : β), x < βq β§ βq < x + 1,
exact @exists_rat_btwn x (x+1) (by simp [zero_lt_one]),
cases H with q Hq,
cases classical.em (x < rat.floor q) with Hb Hs,
exact β¨rat.floor q - 1,
begin
split,
rw [int.cast_sub,int.cast_one],
apply sub_left_le_of_le_add _,
rw [add_comm],
suffices H7 : (βq:real) β€ x+1,
exact calc (β(rat.floor q):β) = (β((rat.floor q):β):β) : by simp
... β€ (βq:β) : rat.cast_le.mpr (rat.floor_le q)
... β€ x+1 : H7,
exact le_of_lt Hq.right,
rwa [int.cast_sub,int.cast_one,sub_add_cancel],
end
β©,
exact β¨rat.floor q,
begin
split,
have H : (x < β(rat.floor q)) β¨ (x β₯ β(rat.floor q)),
exact lt_or_ge x β(rat.floor q),
cases H with F T,
exact false.elim (Hs F),
exact T,
clear Hs,
have H1 : x < βq,
{ exact Hq.left },
clear Hq,
-- insanity starts here
suffices H2 : q < β((rat.floor q)+(1:β€)),
exact calc x < (q:β) : H1
... < ((((rat.floor q + 1):β€):β):β) : rat.cast_lt.2 H2
... = (((rat.floor q + 1):β€):β) : by simp
... = ((rat.floor q):β)+((1:β€):β) : int.cast_add _ _
... = β(rat.floor q) + 1 : by rw [int.cast_one],
clear H1,
exact rat.lt_succ_floor q,
endβ©
end
lemma rational_half_not_an_integer : Β¬ (β y : β€, 1/2 = (y:rat)) :=
begin
apply not_exists.2,
rw [one_div_eq_inv],
assume x:β€,
intro H,
have H6 : ((1:β€):β)=((2:β€):β)*x,
exact calc
((1:β€):β) = (1:β) : by simp
... = (2:β)* 2β»ΒΉ : eq.symm (mul_inv_cancel (by norm_num))
... = (2*x) : by rw[H],
clear H,
rw [βint.cast_mul,int.cast_inj] at H6,
have H : (1:β€) = 0,
exact calc (1:β€) = 1 % 2 : eq.symm (int.mod_eq_of_lt (by norm_num) (by norm_num))
... = (2*x) % 2 : eq.symm (by rw [βH6])
... = 0 : by simp,
revert H,
norm_num,
end
-- set_option pp.all true
lemma real_half_not_an_integer : Β¬ (β y : β€, ((1/2):β) = (y:β)) :=
begin
assume H_real : (β y : β€, ((1/2):β) = (y:β)),
cases H_real with a Ha,
suffices H2 : ((1:β€):β) = ((2:β€):β)*((a:β€):β),
rw [βint.cast_mul,int.cast_inj] at H2,
have H8 : (2*a) % 2 = 0,
simp [@int.add_mul_mod_self 0],
have H9 : (1:int) % 2 = 0,
apply @eq.subst β€ (Ξ» t, t%2 =0) _ _ (eq.symm H2) H8,
have H10 : (1:int) % 2 β 0,
exact dec_trivial,
contradiction,
have H20: (2:β) β 0, {norm_num},
have H1 : (βa:β) * 2 = 1,
exact mul_eq_of_eq_div (a:β) 1 H20 (eq.symm Ha),
have H2 : 1 = 2 * (βa:β),
rw [mul_comm] at H1,
exact eq.symm (H1),
have H3 : (1:β) = ((1:β€):β), by simp,
have H4 : (2:β) = ((2:β€):β), by simp,
rwa [βH3,βH4],
end
definition is_irrational (x : β) := Β¬ (β (q : β), (q:β) = x)
end M1F
|
eeddb5122ed74e0ba79c67e7dec546a88a1f39d8 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/limits/fubini.lean | b66f019afc4c22efbc34b3a2b83d80863b2b0956 | [
"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 | 11,271 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.limits.has_limits
import category_theory.products.basic
import category_theory.functor.currying
/-!
# A Fubini theorem for categorical limits
We prove that $lim_{J Γ K} G = lim_J (lim_K G(j, -))$ for a functor `G : J Γ K β₯€ C`,
when all the appropriate limits exist.
We begin working with a functor `F : J β₯€ K β₯€ C`. We'll write `G : J Γ K β₯€ C` for the associated
"uncurried" functor.
In the first part, given a coherent family `D` of limit cones over the functors `F.obj j`,
and a cone `c` over `G`, we construct a cone over the cone points of `D`.
We then show that if `c` is a limit cone, the constructed cone is also a limit cone.
In the second part, we state the Fubini theorem in the setting where limits are
provided by suitable `has_limit` classes.
We construct
`limit_uncurry_iso_limit_comp_lim F : limit (uncurry.obj F) β
limit (F β lim)`
and give simp lemmas characterising it.
For convenience, we also provide
`limit_iso_limit_curry_comp_lim G : limit G β
limit ((curry.obj G) β lim)`
in terms of the uncurried functor.
## Future work
The dual statement.
-/
universes v u
open category_theory
namespace category_theory.limits
variables {J K : Type v} [small_category J] [small_category K]
variables {C : Type u} [category.{v} C]
variables (F : J β₯€ K β₯€ C)
/--
A structure carrying a diagram of cones over the functors `F.obj j`.
-/
-- We could try introducing a "dependent functor type" to handle this?
structure diagram_of_cones :=
(obj : Ξ j : J, cone (F.obj j))
(map : Ξ {j j' : J} (f : j βΆ j'), (cones.postcompose (F.map f)).obj (obj j) βΆ obj j')
(id : β j : J, (map (π j)).hom = π _ . obviously)
(comp : β {jβ jβ jβ : J} (f : jβ βΆ jβ) (g : jβ βΆ jβ),
(map (f β« g)).hom = (map f).hom β« (map g).hom . obviously)
variables {F}
/--
Extract the functor `J β₯€ C` consisting of the cone points and the maps between them,
from a `diagram_of_cones`.
-/
@[simps]
def diagram_of_cones.cone_points (D : diagram_of_cones F) :
J β₯€ C :=
{ obj := Ξ» j, (D.obj j).X,
map := Ξ» j j' f, (D.map f).hom,
map_id' := Ξ» j, D.id j,
map_comp' := Ξ» jβ jβ jβ f g, D.comp f g, }
/--
Given a diagram `D` of limit cones over the `F.obj j`, and a cone over `uncurry.obj F`,
we can construct a cone over the diagram consisting of the cone points from `D`.
-/
@[simps]
def cone_of_cone_uncurry
{D : diagram_of_cones F} (Q : Ξ j, is_limit (D.obj j))
(c : cone (uncurry.obj F)) :
cone (D.cone_points) :=
{ X := c.X,
Ο :=
{ app := Ξ» j, (Q j).lift
{ X := c.X,
Ο :=
{ app := Ξ» k, c.Ο.app (j, k),
naturality' := Ξ» k k' f,
begin
dsimp, simp only [category.id_comp],
have := @nat_trans.naturality _ _ _ _ _ _ c.Ο (j, k) (j, k') (π j, f),
dsimp at this,
simp only [category.id_comp, category_theory.functor.map_id, nat_trans.id_app] at this,
exact this,
end } },
naturality' := Ξ» j j' f, (Q j').hom_ext
begin
dsimp,
intro k,
simp only [limits.cone_morphism.w, limits.cones.postcompose_obj_Ο, limits.is_limit.fac_assoc,
limits.is_limit.fac, nat_trans.comp_app, category.id_comp, category.assoc],
have := @nat_trans.naturality _ _ _ _ _ _ c.Ο (j, k) (j', k) (f, π k),
dsimp at this,
simp only [category.id_comp, category.comp_id,
category_theory.functor.map_id, nat_trans.id_app] at this,
exact this,
end, } }.
/--
`cone_of_cone_uncurry Q c` is a limit cone when `c` is a limit cone.`
-/
def cone_of_cone_uncurry_is_limit
{D : diagram_of_cones F} (Q : Ξ j, is_limit (D.obj j))
{c : cone (uncurry.obj F)} (P : is_limit c) :
is_limit (cone_of_cone_uncurry Q c) :=
{ lift := Ξ» s, P.lift
{ X := s.X,
Ο :=
{ app := Ξ» p, s.Ο.app p.1 β« (D.obj p.1).Ο.app p.2,
naturality' := Ξ» p p' f,
begin
dsimp, simp only [category.id_comp, category.assoc],
rcases p with β¨j, kβ©,
rcases p' with β¨j', k'β©,
rcases f with β¨fj, fkβ©,
dsimp,
slice_rhs 3 4 { rw βnat_trans.naturality, },
slice_rhs 2 3 { rw β(D.obj j).Ο.naturality, },
simp only [functor.const.obj_map, category.id_comp, category.assoc],
have w := (D.map fj).w k',
dsimp at w,
rw βw,
have n := s.Ο.naturality fj,
dsimp at n,
simp only [category.id_comp] at n,
rw n,
simp,
end, } },
fac' := Ξ» s j,
begin
apply (Q j).hom_ext,
intro k,
simp,
end,
uniq' := Ξ» s m w,
begin
refine P.uniq { X := s.X, Ο := _, } m _,
rintro β¨j, kβ©,
dsimp,
rw [βw j],
simp,
end, }
section
variables (F)
variables [has_limits_of_shape K C]
/--
Given a functor `F : J β₯€ K β₯€ C`, with all needed limits,
we can construct a diagram consisting of the limit cone over each functor `F.obj j`,
and the universal cone morphisms between these.
-/
@[simps]
noncomputable def diagram_of_cones.mk_of_has_limits : diagram_of_cones F :=
{ obj := Ξ» j, limit.cone (F.obj j),
map := Ξ» j j' f, { hom := lim.map (F.map f), }, }
-- Satisfying the inhabited linter.
noncomputable instance diagram_of_cones_inhabited : inhabited (diagram_of_cones F) :=
β¨diagram_of_cones.mk_of_has_limits Fβ©
@[simp]
lemma diagram_of_cones.mk_of_has_limits_cone_points :
(diagram_of_cones.mk_of_has_limits F).cone_points = (F β lim) :=
rfl
variables [has_limit (uncurry.obj F)]
variables [has_limit (F β lim)]
/--
The Fubini theorem for a functor `F : J β₯€ K β₯€ C`,
showing that the limit of `uncurry.obj F` can be computed as
the limit of the limits of the functors `F.obj j`.
-/
noncomputable def limit_uncurry_iso_limit_comp_lim : limit (uncurry.obj F) β
limit (F β lim) :=
begin
let c := limit.cone (uncurry.obj F),
let P : is_limit c := limit.is_limit _,
let G := diagram_of_cones.mk_of_has_limits F,
let Q : Ξ j, is_limit (G.obj j) := Ξ» j, limit.is_limit _,
have Q' := cone_of_cone_uncurry_is_limit Q P,
have Q'' := (limit.is_limit (F β lim)),
exact is_limit.cone_point_unique_up_to_iso Q' Q'',
end
@[simp, reassoc]
lemma limit_uncurry_iso_limit_comp_lim_hom_Ο_Ο {j} {k} :
(limit_uncurry_iso_limit_comp_lim F).hom β« limit.Ο _ j β« limit.Ο _ k = limit.Ο _ (j, k) :=
begin
dsimp [limit_uncurry_iso_limit_comp_lim, is_limit.cone_point_unique_up_to_iso,
is_limit.unique_up_to_iso],
simp,
end
@[simp, reassoc]
lemma limit_uncurry_iso_limit_comp_lim_inv_Ο {j} {k} :
(limit_uncurry_iso_limit_comp_lim F).inv β« limit.Ο _ (j, k) = limit.Ο _ j β« limit.Ο _ k :=
begin
rw [βcancel_epi (limit_uncurry_iso_limit_comp_lim F).hom],
simp,
end
end
section
variables (F) [has_limits_of_shape J C] [has_limits_of_shape K C]
-- With only moderate effort these could be derived if needed:
variables [has_limits_of_shape (J Γ K) C] [has_limits_of_shape (K Γ J) C]
/-- The limit of `F.flip β lim` is isomorphic to the limit of `F β lim`. -/
noncomputable
def limit_flip_comp_lim_iso_limit_comp_lim : limit (F.flip β lim) β
limit (F β lim) :=
(limit_uncurry_iso_limit_comp_lim _).symm βͺβ«
has_limit.iso_of_nat_iso (uncurry_obj_flip _) βͺβ«
(has_limit.iso_of_equivalence (prod.braiding _ _)
(nat_iso.of_components (Ξ» _, by refl) (by tidy))) βͺβ«
limit_uncurry_iso_limit_comp_lim _
@[simp, reassoc]
lemma limit_flip_comp_lim_iso_limit_comp_lim_hom_Ο_Ο (j) (k) :
(limit_flip_comp_lim_iso_limit_comp_lim F).hom β« limit.Ο _ j β« limit.Ο _ k =
limit.Ο _ k β« limit.Ο _ j :=
by { dsimp [limit_flip_comp_lim_iso_limit_comp_lim], simp, dsimp, simp, } -- See note [dsimp, simp]
@[simp, reassoc]
lemma limit_flip_comp_lim_iso_limit_comp_lim_inv_Ο_Ο (k) (j) :
(limit_flip_comp_lim_iso_limit_comp_lim F).inv β« limit.Ο _ k β« limit.Ο _ j =
limit.Ο _ j β« limit.Ο _ k :=
by { dsimp [limit_flip_comp_lim_iso_limit_comp_lim], simp, dsimp, simp, dsimp, simp, }
end
section
variables (G : J Γ K β₯€ C)
section
variables [has_limits_of_shape K C]
variables [has_limit G]
variables [has_limit ((curry.obj G) β lim)]
/--
The Fubini theorem for a functor `G : J Γ K β₯€ C`,
showing that the limit of `G` can be computed as
the limit of the limits of the functors `G.obj (j, _)`.
-/
noncomputable def limit_iso_limit_curry_comp_lim : limit G β
limit ((curry.obj G) β lim) :=
begin
have i : G β
uncurry.obj ((@curry J _ K _ C _).obj G) := currying.symm.unit_iso.app G,
haveI : limits.has_limit (uncurry.obj ((@curry J _ K _ C _).obj G)) :=
has_limit_of_iso i,
transitivity limit (uncurry.obj ((@curry J _ K _ C _).obj G)),
apply has_limit.iso_of_nat_iso i,
exact limit_uncurry_iso_limit_comp_lim ((@curry J _ K _ C _).obj G),
end
@[simp, reassoc]
lemma limit_iso_limit_curry_comp_lim_hom_Ο_Ο {j} {k} :
(limit_iso_limit_curry_comp_lim G).hom β« limit.Ο _ j β« limit.Ο _ k = limit.Ο _ (j, k) :=
by simp [limit_iso_limit_curry_comp_lim, is_limit.cone_point_unique_up_to_iso,
is_limit.unique_up_to_iso]
@[simp, reassoc]
lemma limit_iso_limit_curry_comp_lim_inv_Ο {j} {k} :
(limit_iso_limit_curry_comp_lim G).inv β« limit.Ο _ (j, k) = limit.Ο _ j β« limit.Ο _ k :=
begin
rw [βcancel_epi (limit_iso_limit_curry_comp_lim G).hom],
simp,
end
end
section
variables [has_limits C] -- Certainly one could weaken the hypotheses here.
open category_theory.prod
/--
A variant of the Fubini theorem for a functor `G : J Γ K β₯€ C`,
showing that $\lim_k \lim_j G(j,k) β
\lim_j \lim_k G(j,k)$.
-/
noncomputable
def limit_curry_swap_comp_lim_iso_limit_curry_comp_lim :
limit ((curry.obj (swap K J β G)) β lim) β
limit ((curry.obj G) β lim) :=
calc
limit ((curry.obj (swap K J β G)) β lim)
β
limit (swap K J β G) : (limit_iso_limit_curry_comp_lim _).symm
... β
limit G : has_limit.iso_of_equivalence (braiding K J) (iso.refl _)
... β
limit ((curry.obj G) β lim) : limit_iso_limit_curry_comp_lim _
@[simp]
lemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_hom_Ο_Ο {j} {k} :
(limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).hom β« limit.Ο _ j β« limit.Ο _ k =
limit.Ο _ k β« limit.Ο _ j :=
begin
dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim],
simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_hom_Ο,
iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_Ο_Ο, eq_to_iso_refl, category.assoc],
erw [nat_trans.id_app], -- Why can't `simp` do this`?
dsimp, simp,
end
@[simp]
lemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_inv_Ο_Ο {j} {k} :
(limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).inv β« limit.Ο _ k β« limit.Ο _ j =
limit.Ο _ j β« limit.Ο _ k :=
begin
dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim],
simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_inv_Ο,
iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_Ο_Ο, eq_to_iso_refl, category.assoc],
erw [nat_trans.id_app], -- Why can't `simp` do this`?
dsimp, simp,
end
end
end
end category_theory.limits
|
5deaf9254d151536d91037844b179d7ab2210c25 | 4b846d8dabdc64e7ea03552bad8f7fa74763fc67 | /library/init/data/set.lean | f4fd5279861b9f81a17309cc86db1619b7ba4e87 | [
"Apache-2.0"
] | permissive | pacchiano/lean | 9324b33f3ac3b5c5647285160f9f6ea8d0d767dc | fdadada3a970377a6df8afcd629a6f2eab6e84e8 | refs/heads/master | 1,611,357,380,399 | 1,489,870,101,000 | 1,489,870,101,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,642 | 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.logic init.category.functor
universes u v
def set (Ξ± : Type u) := Ξ± β Prop
def set_of {Ξ± : Type u} (p : Ξ± β Prop) : set Ξ± :=
p
namespace set
variables {Ξ± : Type u} {Ξ² : Type v}
protected def mem (a : Ξ±) (s : set Ξ±) :=
s a
instance : has_mem Ξ± (set Ξ±) :=
β¨set.memβ©
protected def subset (sβ sβ : set Ξ±) :=
β β¦aβ¦, a β sβ β a β sβ
instance : has_subset (set Ξ±) :=
β¨set.subsetβ©
protected def sep (p : Ξ± β Prop) (s : set Ξ±) : set Ξ± :=
{a | a β s β§ p a}
instance : has_sep Ξ± (set Ξ±) :=
β¨set.sepβ©
instance : has_emptyc (set Ξ±) :=
β¨Ξ» a, falseβ©
protected def insert (a : Ξ±) (s : set Ξ±) : set Ξ± :=
{b | b = a β¨ b β s}
instance : has_insert Ξ± (set Ξ±) :=
β¨set.insertβ©
protected def union (sβ sβ : set Ξ±) : set Ξ± :=
{a | a β sβ β¨ a β sβ}
instance : has_union (set Ξ±) :=
β¨set.unionβ©
protected def inter (sβ sβ : set Ξ±) : set Ξ± :=
{a | a β sβ β§ a β sβ}
instance : has_inter (set Ξ±) :=
β¨set.interβ©
def compl (s : set Ξ±) : set Ξ± :=
{a | a β s}
instance : has_neg (set Ξ±) :=
β¨complβ©
protected def diff (s t : set Ξ±) : set Ξ± :=
{a β s | a β t}
instance : has_sdiff (set Ξ±) :=
β¨set.diffβ©
def powerset (s : set Ξ±) : set (set Ξ±) :=
{t | t β s}
prefix `π«`:100 := powerset
def image (f : Ξ± β Ξ²) (s : set Ξ±) : set Ξ² :=
{b | β a, a β s β§ f a = b}
instance : functor set :=
{map := @set.image}
end set
|
946196c5f43dbdd2920814e0c92a9090cc4aaab1 | 9bb72db9297f7837f673785604fb89b3184e13f8 | /library/init/algebra/classes.lean | 367e02c693e579e2cc25a505ee98ad91b9dd4820 | [
"Apache-2.0"
] | permissive | dselsam/lean | ec83d7592199faa85687d884bbaaa570b62c1652 | 6b0bd5bc2e07e13880d332c89093fe3032bb2469 | refs/heads/master | 1,621,807,064,966 | 1,611,454,685,000 | 1,611,975,642,000 | 42,734,348 | 3 | 3 | null | 1,498,748,560,000 | 1,442,594,289,000 | C++ | UTF-8 | Lean | false | false | 13,161 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.logic init.data.ordering.basic
universes u v
@[algebra] class is_symm_op (Ξ± : Type u) (Ξ² : out_param (Type v)) (op : Ξ± β Ξ± β Ξ²) : Prop :=
(symm_op : β a b, op a b = op b a)
@[algebra] class is_commutative (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) : Prop :=
(comm : β a b, op a b = op b a)
instance is_symm_op_of_is_commutative (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) [is_commutative Ξ± op] : is_symm_op Ξ± Ξ± op :=
{symm_op := is_commutative.comm}
@[algebra] class is_associative (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) : Prop :=
(assoc : β a b c, op (op a b) c = op a (op b c))
@[algebra] class is_left_id (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) (o : out_param Ξ±) : Prop :=
(left_id : β a, op o a = a)
@[algebra] class is_right_id (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) (o : out_param Ξ±) : Prop :=
(right_id : β a, op a o = a)
@[algebra] class is_left_null (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) (o : out_param Ξ±) : Prop :=
(left_null : β a, op o a = o)
@[algebra] class is_right_null (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) (o : out_param Ξ±) : Prop :=
(right_null : β a, op a o = o)
@[algebra] class is_left_cancel (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) : Prop :=
(left_cancel : β a b c, op a b = op a c β b = c)
@[algebra] class is_right_cancel (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) : Prop :=
(right_cancel : β a b c, op a b = op c b β a = c)
@[algebra] class is_idempotent (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) : Prop :=
(idempotent : β a, op a a = a)
@[algebra] class is_left_distrib (Ξ± : Type u) (opβ : Ξ± β Ξ± β Ξ±) (opβ : out_param $ Ξ± β Ξ± β Ξ±) : Prop :=
(left_distrib : β a b c, opβ a (opβ b c) = opβ (opβ a b) (opβ a c))
@[algebra] class is_right_distrib (Ξ± : Type u) (opβ : Ξ± β Ξ± β Ξ±) (opβ : out_param $ Ξ± β Ξ± β Ξ±) : Prop :=
(right_distrib : β a b c, opβ (opβ a b) c = opβ (opβ a c) (opβ b c))
@[algebra] class is_left_inv (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) (inv : out_param $ Ξ± β Ξ±) (o : out_param Ξ±) : Prop :=
(left_inv : β a, op (inv a) a = o)
@[algebra] class is_right_inv (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) (inv : out_param $ Ξ± β Ξ±) (o : out_param Ξ±) : Prop :=
(right_inv : β a, op a (inv a) = o)
@[algebra] class is_cond_left_inv (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) (inv : out_param $ Ξ± β Ξ±) (o : out_param Ξ±) (p : out_param $ Ξ± β Prop) : Prop :=
(left_inv : β a, p a β op (inv a) a = o)
@[algebra] class is_cond_right_inv (Ξ± : Type u) (op : Ξ± β Ξ± β Ξ±) (inv : out_param $ Ξ± β Ξ±) (o : out_param Ξ±) (p : out_param $ Ξ± β Prop) : Prop :=
(right_inv : β a, p a β op a (inv a) = o)
@[algebra] class is_distinct (Ξ± : Type u) (a : Ξ±) (b : Ξ±) : Prop :=
(distinct : a β b)
/-
-- The following type class doesn't seem very useful, a regular simp lemma should work for this.
class is_inv (Ξ± : Type u) (Ξ² : Type v) (f : Ξ± β Ξ²) (g : out Ξ² β Ξ±) : Prop :=
(inv : β a, g (f a) = a)
-- The following one can also be handled using a regular simp lemma
class is_idempotent (Ξ± : Type u) (f : Ξ± β Ξ±) : Prop :=
(idempotent : β a, f (f a) = f a)
-/
/-- `is_irrefl X r` means the binary relation `r` on `X` is irreflexive (that is, `r x x` never
holds). -/
@[algebra] class is_irrefl (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) : Prop :=
(irrefl : β a, Β¬ r a a)
/-- `is_refl X r` means the binary relation `r` on `X` is reflexive. -/
@[algebra] class is_refl (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) : Prop :=
(refl : β a, r a a)
/-- `is_symm X r` means the binary relation `r` on `X` is symmetric. -/
@[algebra] class is_symm (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) : Prop :=
(symm : β a b, r a b β r b a)
/-- The opposite of a symmetric relation is symmetric. -/
instance is_symm_op_of_is_symm (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) [is_symm Ξ± r] : is_symm_op Ξ± Prop r :=
{symm_op := Ξ» a b, propext $ iff.intro (is_symm.symm a b) (is_symm.symm b a)}
/-- `is_asymm X r` means that the binary relation `r` on `X` is asymmetric, that is,
`r a b β Β¬ r b a`. -/
@[algebra] class is_asymm (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) : Prop :=
(asymm : β a b, r a b β Β¬ r b a)
/-- `is_antisymm X r` means the binary relation `r` on `X` is antisymmetric. -/
@[algebra] class is_antisymm (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) : Prop :=
(antisymm : β a b, r a b β r b a β a = b)
/-- `is_trans X r` means the binary relation `r` on `X` is transitive. -/
@[algebra] class is_trans (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) : Prop :=
(trans : β a b c, r a b β r b c β r a c)
/-- `is_total X r` means that the binary relation `r` on `X` is total, that is, that for any
`x y : X` we have `r x y` or `r y x`.-/
@[algebra] class is_total (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) : Prop :=
(total : β a b, r a b β¨ r b a)
/-- `is_preorder X r` means that the binary relation `r` on `X` is a pre-order, that is, reflexive
and transitive. -/
@[algebra] class is_preorder (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) extends is_refl Ξ± r, is_trans Ξ± r : Prop.
/-- `is_total_preorder X r` means that the binary relation `r` on `X` is total and a preorder. -/
@[algebra] class is_total_preorder (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) extends is_trans Ξ± r, is_total Ξ± r : Prop.
/-- Every total pre-order is a pre-order. -/
instance is_total_preorder_is_preorder (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) [s : is_total_preorder Ξ± r] : is_preorder Ξ± r :=
{trans := s.trans,
refl := Ξ» a, or.elim (@is_total.total _ r _ a a) id id}
@[algebra] class is_partial_order (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) extends is_preorder Ξ± r, is_antisymm Ξ± r : Prop.
@[algebra] class is_linear_order (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) extends is_partial_order Ξ± r, is_total Ξ± r : Prop.
@[algebra] class is_equiv (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) extends is_preorder Ξ± r, is_symm Ξ± r : Prop.
@[algebra] class is_per (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) extends is_symm Ξ± r, is_trans Ξ± r : Prop.
@[algebra] class is_strict_order (Ξ± : Type u) (r : Ξ± β Ξ± β Prop) extends is_irrefl Ξ± r, is_trans Ξ± r : Prop.
@[algebra] class is_incomp_trans (Ξ± : Type u) (lt : Ξ± β Ξ± β Prop) : Prop :=
(incomp_trans : β a b c, (Β¬ lt a b β§ Β¬ lt b a) β (Β¬ lt b c β§ Β¬ lt c b) β (Β¬ lt a c β§ Β¬ lt c a))
@[algebra] class is_strict_weak_order (Ξ± : Type u) (lt : Ξ± β Ξ± β Prop) extends is_strict_order Ξ± lt, is_incomp_trans Ξ± lt : Prop.
@[algebra] class is_trichotomous (Ξ± : Type u) (lt : Ξ± β Ξ± β Prop) : Prop :=
(trichotomous : β a b, lt a b β¨ a = b β¨ lt b a)
@[algebra] class is_strict_total_order (Ξ± : Type u) (lt : Ξ± β Ξ± β Prop)
extends is_trichotomous Ξ± lt, is_strict_weak_order Ξ± lt : Prop.
instance eq_is_equiv (Ξ± : Type u) : is_equiv Ξ± (=) :=
{symm := @eq.symm _, trans := @eq.trans _, refl := eq.refl}
section
variables {Ξ± : Type u} {r : Ξ± β Ξ± β Prop}
local infix `βΊ`:50 := r
lemma irrefl [is_irrefl Ξ± r] (a : Ξ±) : Β¬ a βΊ a :=
is_irrefl.irrefl a
lemma refl [is_refl Ξ± r] (a : Ξ±) : a βΊ a :=
is_refl.refl a
lemma trans [is_trans Ξ± r] {a b c : Ξ±} : a βΊ b β b βΊ c β a βΊ c :=
is_trans.trans _ _ _
lemma symm [is_symm Ξ± r] {a b : Ξ±} : a βΊ b β b βΊ a :=
is_symm.symm _ _
lemma antisymm [is_antisymm Ξ± r] {a b : Ξ±} : a βΊ b β b βΊ a β a = b :=
is_antisymm.antisymm _ _
lemma asymm [is_asymm Ξ± r] {a b : Ξ±} : a βΊ b β Β¬ b βΊ a :=
is_asymm.asymm _ _
lemma trichotomous [is_trichotomous Ξ± r] : β (a b : Ξ±), a βΊ b β¨ a = b β¨ b βΊ a :=
is_trichotomous.trichotomous
lemma incomp_trans [is_incomp_trans Ξ± r] {a b c : Ξ±} : (Β¬ a βΊ b β§ Β¬ b βΊ a) β (Β¬ b βΊ c β§ Β¬ c βΊ b) β (Β¬ a βΊ c β§ Β¬ c βΊ a) :=
is_incomp_trans.incomp_trans _ _ _
instance is_asymm_of_is_trans_of_is_irrefl [is_trans Ξ± r] [is_irrefl Ξ± r] : is_asymm Ξ± r :=
β¨Ξ» a b hβ hβ, absurd (trans hβ hβ) (irrefl a)β©
section explicit_relation_variants
variable (r)
@[elab_simple]
lemma irrefl_of [is_irrefl Ξ± r] (a : Ξ±) : Β¬ a βΊ a := irrefl a
@[elab_simple]
lemma refl_of [is_refl Ξ± r] (a : Ξ±) : a βΊ a := refl a
@[elab_simple]
lemma trans_of [is_trans Ξ± r] {a b c : Ξ±} : a βΊ b β b βΊ c β a βΊ c := trans
@[elab_simple]
lemma symm_of [is_symm Ξ± r] {a b : Ξ±} : a βΊ b β b βΊ a := symm
@[elab_simple]
lemma asymm_of [is_asymm Ξ± r] {a b : Ξ±} : a βΊ b β Β¬ b βΊ a := asymm
@[elab_simple]
lemma total_of [is_total Ξ± r] (a b : Ξ±) : a βΊ b β¨ b βΊ a :=
is_total.total _ _
@[elab_simple]
lemma trichotomous_of [is_trichotomous Ξ± r] : β (a b : Ξ±), a βΊ b β¨ a = b β¨ b βΊ a := trichotomous
@[elab_simple]
lemma incomp_trans_of [is_incomp_trans Ξ± r] {a b c : Ξ±} : (Β¬ a βΊ b β§ Β¬ b βΊ a) β (Β¬ b βΊ c β§ Β¬ c βΊ b) β (Β¬ a βΊ c β§ Β¬ c βΊ a) := incomp_trans
end explicit_relation_variants
end
namespace strict_weak_order
section
parameters {Ξ± : Type u} {r : Ξ± β Ξ± β Prop}
local infix `βΊ`:50 := r
def equiv (a b : Ξ±) : Prop :=
Β¬ a βΊ b β§ Β¬ b βΊ a
parameter [is_strict_weak_order Ξ± r]
local infix ` β `:50 := equiv
lemma erefl (a : Ξ±) : a β a :=
β¨irrefl a, irrefl aβ©
lemma esymm {a b : Ξ±} : a β b β b β a :=
Ξ» β¨hβ, hββ©, β¨hβ, hββ©
lemma etrans {a b c : Ξ±} : a β b β b β c β a β c :=
incomp_trans
lemma not_lt_of_equiv {a b : Ξ±} : a β b β Β¬ a βΊ b :=
Ξ» h, h.1
lemma not_lt_of_equiv' {a b : Ξ±} : a β b β Β¬ b βΊ a :=
Ξ» h, h.2
instance is_equiv : is_equiv Ξ± equiv :=
{refl := erefl, trans := @etrans, symm := @esymm}
end
/- Notation for the equivalence relation induced by lt -/
notation a ` β[`:50 lt `]` b:50 := @equiv _ lt a b
end strict_weak_order
lemma is_strict_weak_order_of_is_total_preorder {Ξ± : Type u} {le : Ξ± β Ξ± β Prop} {lt : Ξ± β Ξ± β Prop} [decidable_rel le] [s : is_total_preorder Ξ± le]
(h : β a b, lt a b β Β¬ le b a) : is_strict_weak_order Ξ± lt :=
{
trans :=
Ξ» a b c hab hbc,
have nba : Β¬ le b a, from iff.mp (h _ _) hab,
have ncb : Β¬ le c b, from iff.mp (h _ _) hbc,
have hab : le a b, from or.resolve_left (total_of le b a) nba,
have nca : Β¬ le c a, from Ξ» hca : le c a,
have hcb : le c b, from trans_of le hca hab,
absurd hcb ncb,
iff.mpr (h _ _) nca,
irrefl := Ξ» a hlt, absurd (refl_of le a) (iff.mp (h _ _) hlt),
incomp_trans := Ξ» a b c β¨nab, nbaβ© β¨nbc, ncbβ©,
have hba : le b a, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nab),
have hab : le a b, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nba),
have hcb : le c b, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nbc),
have hbc : le b c, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) ncb),
have hac : le a c, from trans_of le hab hbc,
have hca : le c a, from trans_of le hcb hba,
and.intro
(Ξ» n, absurd hca (iff.mp (h _ _) n))
(Ξ» n, absurd hac (iff.mp (h _ _) n))
}
lemma lt_of_lt_of_incomp {Ξ± : Type u} {lt : Ξ± β Ξ± β Prop} [is_strict_weak_order Ξ± lt] [decidable_rel lt]
: β {a b c}, lt a b β (Β¬ lt b c β§ Β¬ lt c b) β lt a c :=
Ξ» a b c hab β¨nbc, ncbβ©,
have nca : Β¬ lt c a, from Ξ» hca, absurd (trans_of lt hca hab) ncb,
decidable.by_contradiction $
Ξ» nac : Β¬ lt a c,
have Β¬ lt a b β§ Β¬ lt b a, from incomp_trans_of lt β¨nac, ncaβ© β¨ncb, nbcβ©,
absurd hab this.1
lemma lt_of_incomp_of_lt {Ξ± : Type u} {lt : Ξ± β Ξ± β Prop} [is_strict_weak_order Ξ± lt] [decidable_rel lt]
: β {a b c}, (Β¬ lt a b β§ Β¬ lt b a) β lt b c β lt a c :=
Ξ» a b c β¨nab, nbaβ© hbc,
have nca : Β¬ lt c a, from Ξ» hca, absurd (trans_of lt hbc hca) nba,
decidable.by_contradiction $
Ξ» nac : Β¬ lt a c,
have Β¬ lt b c β§ Β¬ lt c b, from incomp_trans_of lt β¨nba, nabβ© β¨nac, ncaβ©,
absurd hbc this.1
lemma eq_of_incomp {Ξ± : Type u} {lt : Ξ± β Ξ± β Prop} [is_trichotomous Ξ± lt] {a b} : (Β¬ lt a b β§ Β¬ lt b a) β a = b :=
Ξ» β¨nab, nbaβ©,
match trichotomous_of lt a b with
| or.inl hab := absurd hab nab
| or.inr (or.inl hab) := hab
| or.inr (or.inr hba) := absurd hba nba
end
lemma eq_of_eqv_lt {Ξ± : Type u} {lt : Ξ± β Ξ± β Prop} [is_trichotomous Ξ± lt] {a b} : a β[lt] b β a = b :=
eq_of_incomp
lemma incomp_iff_eq {Ξ± : Type u} {lt : Ξ± β Ξ± β Prop} [is_trichotomous Ξ± lt] [is_irrefl Ξ± lt] (a b) : (Β¬ lt a b β§ Β¬ lt b a) β a = b :=
iff.intro eq_of_incomp (Ξ» hab, eq.subst hab (and.intro (irrefl_of lt a) (irrefl_of lt a)))
lemma eqv_lt_iff_eq {Ξ± : Type u} {lt : Ξ± β Ξ± β Prop} [is_trichotomous Ξ± lt] [is_irrefl Ξ± lt] (a b) : a β[lt] b β a = b :=
incomp_iff_eq a b
lemma not_lt_of_lt {Ξ± : Type u} {lt : Ξ± β Ξ± β Prop} [is_strict_order Ξ± lt] {a b} : lt a b β Β¬ lt b a :=
Ξ» hβ hβ, absurd (trans_of lt hβ hβ) (irrefl_of lt _)
|
e765f5696f91aef67827abea6e95607e6e74789d | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/reflexive_elim_prop_bug.lean | e0343fa58c6c76bc8e88a146d5fa4737392281f7 | [
"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 | 555 | lean | namespace tst1
inductive Foo : Type
| node : (β β Foo) β Foo
| leaf : Foo
constant Bar : Type
constant P : Bar β Prop
constant Q : Bar β Type
axiom P_ax : β b, P b
lemma foo_error : β (foo : Foo) (b : Bar), P b
| (Foo.node f) := Ξ» b, foo_error (f 0) b
| Foo.leaf := Ξ» b, P_ax b
end tst1
namespace tst2
inductive Foo : Type
| node : (β β Foo) β Foo
constant Bar : Type
constant P : Bar β Prop
constant Q : Bar β Type
lemma foo_error : β (foo : Foo) (b : Bar), P b
| (Foo.node f) := Ξ» b, foo_error (f 0) b
end tst2
|
811089441244dfcdb04db17121a5445a42b95c34 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/order/monoid.lean | 4ea1b086f8a434d6aa243440509b6bea7666a12b | [
"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 | 40,858 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes HΓΆlzl
-/
import algebra.group.with_one
import algebra.group.type_tags
import algebra.group.prod
import algebra.order.monoid_lemmas
import order.bounded_order
import order.min_max
import order.hom.basic
/-!
# Ordered monoids
This file develops the basics of ordered monoids.
## Implementation details
Unfortunately, the number of `'` appended to lemmas in this file
may differ between the multiplicative and the additive version of a lemma.
The reason is that we did not want to change existing names in the library.
-/
set_option old_structure_cmd true
open function
universe u
variable {Ξ± : Type u}
/-- An ordered commutative monoid is a commutative monoid
with a partial order such that `a β€ b β c * a β€ c * b` (multiplication is monotone)
-/
@[protect_proj, ancestor comm_monoid partial_order]
class ordered_comm_monoid (Ξ± : Type*) extends comm_monoid Ξ±, partial_order Ξ± :=
(mul_le_mul_left : β a b : Ξ±, a β€ b β β c : Ξ±, c * a β€ c * b)
/-- An ordered (additive) commutative monoid is a commutative monoid
with a partial order such that `a β€ b β c + a β€ c + b` (addition is monotone)
-/
@[protect_proj, ancestor add_comm_monoid partial_order]
class ordered_add_comm_monoid (Ξ± : Type*) extends add_comm_monoid Ξ±, partial_order Ξ± :=
(add_le_add_left : β a b : Ξ±, a β€ b β β c : Ξ±, c + a β€ c + b)
attribute [to_additive] ordered_comm_monoid
section ordered_instances
@[to_additive]
instance ordered_comm_monoid.to_covariant_class_left (M : Type*) [ordered_comm_monoid M] :
covariant_class M M (*) (β€) :=
{ elim := Ξ» a b c bc, ordered_comm_monoid.mul_le_mul_left _ _ bc a }
/- This instance can be proven with `by apply_instance`. However, `with_bot β` does not
pick up a `covariant_class M M (function.swap (*)) (β€)` instance without it (see PR #7940). -/
@[to_additive]
instance ordered_comm_monoid.to_covariant_class_right (M : Type*) [ordered_comm_monoid M] :
covariant_class M M (swap (*)) (β€) :=
covariant_swap_mul_le_of_covariant_mul_le M
/- This is not an instance, to avoid creating a loop in the type-class system: in a
`left_cancel_semigroup` with a `partial_order`, assuming `covariant_class M M (*) (β€)`
implies `covariant_class M M (*) (<)` . -/
@[to_additive] lemma has_mul.to_covariant_class_left
(M : Type*) [has_mul M] [linear_order M] [covariant_class M M (*) (<)] :
covariant_class M M (*) (β€) :=
{ elim := Ξ» a b c bc, by
{ rcases eq_or_lt_of_le bc with rfl | bc,
{ exact rfl.le },
{ exact (mul_lt_mul_left' bc a).le } } }
/- This is not an instance, to avoid creating a loop in the type-class system: in a
`right_cancel_semigroup` with a `partial_order`, assuming `covariant_class M M (swap (*)) (<)`
implies `covariant_class M M (swap (*)) (β€)` . -/
@[to_additive] lemma has_mul.to_covariant_class_right
(M : Type*) [has_mul M] [linear_order M] [covariant_class M M (swap (*)) (<)] :
covariant_class M M (swap (*)) (β€) :=
{ elim := Ξ» a b c bc, by
{ rcases eq_or_lt_of_le bc with rfl | bc,
{ exact rfl.le },
{ exact (mul_lt_mul_right' bc a).le } } }
end ordered_instances
/-- An `ordered_comm_monoid` with one-sided 'division' in the sense that
if `a β€ b`, there is some `c` for which `a * c = b`. This is a weaker version
of the condition on canonical orderings defined by `canonically_ordered_monoid`. -/
class has_exists_mul_of_le (Ξ± : Type u) [ordered_comm_monoid Ξ±] : Prop :=
(exists_mul_of_le : β {a b : Ξ±}, a β€ b β β (c : Ξ±), b = a * c)
/-- An `ordered_add_comm_monoid` with one-sided 'subtraction' in the sense that
if `a β€ b`, then there is some `c` for which `a + c = b`. This is a weaker version
of the condition on canonical orderings defined by `canonically_ordered_add_monoid`. -/
class has_exists_add_of_le (Ξ± : Type u) [ordered_add_comm_monoid Ξ±] : Prop :=
(exists_add_of_le : β {a b : Ξ±}, a β€ b β β (c : Ξ±), b = a + c)
attribute [to_additive] has_exists_mul_of_le
export has_exists_mul_of_le (exists_mul_of_le)
export has_exists_add_of_le (exists_add_of_le)
/-- A linearly ordered additive commutative monoid. -/
@[protect_proj, ancestor linear_order ordered_add_comm_monoid]
class linear_ordered_add_comm_monoid (Ξ± : Type*)
extends linear_order Ξ±, ordered_add_comm_monoid Ξ±.
/-- A linearly ordered commutative monoid. -/
@[protect_proj, ancestor linear_order ordered_comm_monoid, to_additive]
class linear_ordered_comm_monoid (Ξ± : Type*)
extends linear_order Ξ±, ordered_comm_monoid Ξ±.
/-- A linearly ordered commutative monoid with a zero element. -/
class linear_ordered_comm_monoid_with_zero (Ξ± : Type*)
extends linear_ordered_comm_monoid Ξ±, comm_monoid_with_zero Ξ± :=
(zero_le_one : (0 : Ξ±) β€ 1)
/-- A linearly ordered commutative monoid with an additively absorbing `β€` element.
Instances should include number systems with an infinite element adjoined.` -/
@[protect_proj, ancestor linear_ordered_add_comm_monoid has_top]
class linear_ordered_add_comm_monoid_with_top (Ξ± : Type*)
extends linear_ordered_add_comm_monoid Ξ±, has_top Ξ± :=
(le_top : β x : Ξ±, x β€ β€)
(top_add' : β x : Ξ±, β€ + x = β€)
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_add_comm_monoid_with_top.to_order_top (Ξ± : Type u)
[h : linear_ordered_add_comm_monoid_with_top Ξ±] : order_top Ξ± :=
{ ..h }
section linear_ordered_add_comm_monoid_with_top
variables [linear_ordered_add_comm_monoid_with_top Ξ±] {a b : Ξ±}
@[simp]
lemma top_add (a : Ξ±) : β€ + a = β€ := linear_ordered_add_comm_monoid_with_top.top_add' a
@[simp]
lemma add_top (a : Ξ±) : a + β€ = β€ :=
trans (add_comm _ _) (top_add _)
end linear_ordered_add_comm_monoid_with_top
/-- Pullback an `ordered_comm_monoid` under an injective map.
See note [reducible non-instances]. -/
@[reducible, to_additive function.injective.ordered_add_comm_monoid
"Pullback an `ordered_add_comm_monoid` under an injective map."]
def function.injective.ordered_comm_monoid [ordered_comm_monoid Ξ±] {Ξ² : Type*}
[has_one Ξ²] [has_mul Ξ²]
(f : Ξ² β Ξ±) (hf : function.injective f) (one : f 1 = 1)
(mul : β x y, f (x * y) = f x * f y) :
ordered_comm_monoid Ξ² :=
{ mul_le_mul_left := Ξ» a b ab c, show f (c * a) β€ f (c * b), by
{ rw [mul, mul], apply mul_le_mul_left', exact ab },
..partial_order.lift f hf,
..hf.comm_monoid f one mul }
/-- Pullback a `linear_ordered_comm_monoid` under an injective map.
See note [reducible non-instances]. -/
@[reducible, to_additive function.injective.linear_ordered_add_comm_monoid
"Pullback an `ordered_add_comm_monoid` under an injective map."]
def function.injective.linear_ordered_comm_monoid [linear_ordered_comm_monoid Ξ±] {Ξ² : Type*}
[has_one Ξ²] [has_mul Ξ²]
(f : Ξ² β Ξ±) (hf : function.injective f) (one : f 1 = 1)
(mul : β x y, f (x * y) = f x * f y) :
linear_ordered_comm_monoid Ξ² :=
{ .. hf.ordered_comm_monoid f one mul,
.. linear_order.lift f hf }
lemma bit0_pos [ordered_add_comm_monoid Ξ±] {a : Ξ±} (h : 0 < a) : 0 < bit0 a :=
add_pos h h
namespace units
@[to_additive]
instance [monoid Ξ±] [preorder Ξ±] : preorder Ξ±Λ£ :=
preorder.lift (coe : Ξ±Λ£ β Ξ±)
@[simp, norm_cast, to_additive]
theorem coe_le_coe [monoid Ξ±] [preorder Ξ±] {a b : Ξ±Λ£} :
(a : Ξ±) β€ b β a β€ b := iff.rfl
@[simp, norm_cast, to_additive]
theorem coe_lt_coe [monoid Ξ±] [preorder Ξ±] {a b : Ξ±Λ£} :
(a : Ξ±) < b β a < b := iff.rfl
@[to_additive]
instance [monoid Ξ±] [partial_order Ξ±] : partial_order Ξ±Λ£ :=
partial_order.lift coe units.ext
@[to_additive]
instance [monoid Ξ±] [linear_order Ξ±] : linear_order Ξ±Λ£ :=
linear_order.lift coe units.ext
@[simp, norm_cast, to_additive]
theorem max_coe [monoid Ξ±] [linear_order Ξ±] {a b : Ξ±Λ£} :
(β(max a b) : Ξ±) = max a b :=
by by_cases b β€ a; simp [max_def, h]
@[simp, norm_cast, to_additive]
theorem min_coe [monoid Ξ±] [linear_order Ξ±] {a b : Ξ±Λ£} :
(β(min a b) : Ξ±) = min a b :=
by by_cases a β€ b; simp [min_def, h]
end units
namespace with_zero
local attribute [semireducible] with_zero
instance [preorder Ξ±] : preorder (with_zero Ξ±) := with_bot.preorder
instance [partial_order Ξ±] : partial_order (with_zero Ξ±) := with_bot.partial_order
instance [partial_order Ξ±] : order_bot (with_zero Ξ±) := with_bot.order_bot
lemma zero_le [partial_order Ξ±] (a : with_zero Ξ±) : 0 β€ a := order_bot.bot_le a
lemma zero_lt_coe [preorder Ξ±] (a : Ξ±) : (0 : with_zero Ξ±) < a := with_bot.bot_lt_coe a
@[simp, norm_cast] lemma coe_lt_coe [partial_order Ξ±] {a b : Ξ±} : (a : with_zero Ξ±) < b β a < b :=
with_bot.coe_lt_coe
@[simp, norm_cast] lemma coe_le_coe [partial_order Ξ±] {a b : Ξ±} : (a : with_zero Ξ±) β€ b β a β€ b :=
with_bot.coe_le_coe
instance [lattice Ξ±] : lattice (with_zero Ξ±) := with_bot.lattice
instance [linear_order Ξ±] : linear_order (with_zero Ξ±) := with_bot.linear_order
lemma mul_le_mul_left {Ξ± : Type u} [has_mul Ξ±] [preorder Ξ±]
[covariant_class Ξ± Ξ± (*) (β€)] :
β (a b : with_zero Ξ±),
a β€ b β β (c : with_zero Ξ±), c * a β€ c * b :=
begin
rintro (_ | a) (_ | b) h (_ | c);
try { exact Ξ» f hf, option.no_confusion hf },
{ exact false.elim (not_lt_of_le h (with_zero.zero_lt_coe a))},
{ simp_rw [some_eq_coe] at h β’,
norm_cast at h β’,
exact covariant_class.elim _ h }
end
lemma lt_of_mul_lt_mul_left {Ξ± : Type u} [has_mul Ξ±] [partial_order Ξ±]
[contravariant_class Ξ± Ξ± (*) (<)] :
β (a b c : with_zero Ξ±), a * b < a * c β b < c :=
begin
rintro (_ | a) (_ | b) (_ | c) h;
try { exact false.elim (lt_irrefl none h) },
{ exact with_zero.zero_lt_coe c },
{ exact false.elim (not_le_of_lt h (with_zero.zero_le _)) },
{ simp_rw [some_eq_coe] at h β’,
norm_cast at h β’,
apply lt_of_mul_lt_mul_left' h }
end
instance [ordered_comm_monoid Ξ±] : ordered_comm_monoid (with_zero Ξ±) :=
{ mul_le_mul_left := with_zero.mul_le_mul_left,
..with_zero.comm_monoid_with_zero,
..with_zero.partial_order }
/-
Note 1 : the below is not an instance because it requires `zero_le`. It seems
like a rather pathological definition because Ξ± already has a zero.
Note 2 : there is no multiplicative analogue because it does not seem necessary.
Mathematicians might be more likely to use the order-dual version, where all
elements are β€ 1 and then 1 is the top element.
-/
/--
If `0` is the least element in `Ξ±`, then `with_zero Ξ±` is an `ordered_add_comm_monoid`.
-/
def ordered_add_comm_monoid [ordered_add_comm_monoid Ξ±]
(zero_le : β a : Ξ±, 0 β€ a) : ordered_add_comm_monoid (with_zero Ξ±) :=
begin
suffices, refine
{ add_le_add_left := this,
..with_zero.partial_order,
..with_zero.add_comm_monoid, .. },
{ intros a b h c ca hβ,
cases b with b,
{ rw le_antisymm h bot_le at hβ,
exact β¨_, hβ, le_rflβ© },
cases a with a,
{ change c + 0 = some ca at hβ,
simp at hβ, simp [hβ],
exact β¨_, rfl, by simpa using add_le_add_left (zero_le b) _β© },
{ simp at h,
cases c with c; change some _ = _ at hβ;
simp [-add_comm] at hβ; subst ca; refine β¨_, rfl, _β©,
{ exact h },
{ exact add_le_add_left h _ } } }
end
end with_zero
namespace with_top
section has_one
variables [has_one Ξ±]
@[to_additive] instance : has_one (with_top Ξ±) := β¨(1 : Ξ±)β©
@[simp, norm_cast, to_additive] lemma coe_one : ((1 : Ξ±) : with_top Ξ±) = 1 := rfl
@[simp, norm_cast, to_additive] lemma coe_eq_one {a : Ξ±} : (a : with_top Ξ±) = 1 β a = 1 :=
coe_eq_coe
@[simp, norm_cast, to_additive] theorem one_eq_coe {a : Ξ±} : 1 = (a : with_top Ξ±) β a = 1 :=
trans eq_comm coe_eq_one
@[simp, to_additive] theorem top_ne_one : β€ β (1 : with_top Ξ±) .
@[simp, to_additive] theorem one_ne_top : (1 : with_top Ξ±) β β€ .
end has_one
instance [has_add Ξ±] : has_add (with_top Ξ±) :=
β¨Ξ» oβ oβ, oβ.bind (Ξ» a, oβ.map (Ξ» b, a + b))β©
@[norm_cast] lemma coe_add [has_add Ξ±] {a b : Ξ±} : ((a + b : Ξ±) : with_top Ξ±) = a + b := rfl
@[norm_cast] lemma coe_bit0 [has_add Ξ±] {a : Ξ±} : ((bit0 a : Ξ±) : with_top Ξ±) = bit0 a := rfl
@[norm_cast]
lemma coe_bit1 [has_add Ξ±] [has_one Ξ±] {a : Ξ±} : ((bit1 a : Ξ±) : with_top Ξ±) = bit1 a := rfl
@[simp] lemma add_top [has_add Ξ±] : β{a : with_top Ξ±}, a + β€ = β€
| none := rfl
| (some a) := rfl
@[simp] lemma top_add [has_add Ξ±] {a : with_top Ξ±} : β€ + a = β€ := rfl
lemma add_eq_top [has_add Ξ±] {a b : with_top Ξ±} : a + b = β€ β a = β€ β¨ b = β€ :=
by cases a; cases b; simp [none_eq_top, some_eq_coe, βwith_top.coe_add, βwith_zero.coe_add]
lemma add_lt_top [has_add Ξ±] [partial_order Ξ±] {a b : with_top Ξ±} : a + b < β€ β a < β€ β§ b < β€ :=
by simp [lt_top_iff_ne_top, add_eq_top, not_or_distrib]
lemma add_eq_coe [has_add Ξ±] : β {a b : with_top Ξ±} {c : Ξ±},
a + b = c β β (a' b' : Ξ±), βa' = a β§ βb' = b β§ a' + b' = c
| none b c := by simp [none_eq_top]
| (some a) none c := by simp [none_eq_top]
| (some a) (some b) c :=
by simp only [some_eq_coe, β coe_add, coe_eq_coe, exists_and_distrib_left, exists_eq_left]
@[simp] lemma add_coe_eq_top_iff [has_add Ξ±] {x : with_top Ξ±} {y : Ξ±} : x + y = β€ β x = β€ :=
by { induction x using with_top.rec_top_coe; simp [β coe_add, -with_zero.coe_add] }
@[simp] lemma coe_add_eq_top_iff [has_add Ξ±] {x : Ξ±} {y : with_top Ξ±} : βx + y = β€ β y = β€ :=
by { induction y using with_top.rec_top_coe; simp [β coe_add, -with_zero.coe_add] }
instance [add_semigroup Ξ±] : add_semigroup (with_top Ξ±) :=
{ add_assoc := begin
repeat { refine with_top.rec_top_coe _ _; try { intro }};
simp [βwith_top.coe_add, add_assoc]
end,
..with_top.has_add }
instance [add_comm_semigroup Ξ±] : add_comm_semigroup (with_top Ξ±) :=
{ add_comm :=
begin
repeat { refine with_top.rec_top_coe _ _; try { intro }};
simp [βwith_top.coe_add, add_comm]
end,
..with_top.add_semigroup }
instance [add_monoid Ξ±] : add_monoid (with_top Ξ±) :=
{ zero_add :=
begin
refine with_top.rec_top_coe _ _,
{ simpa },
{ intro,
rw [βwith_top.coe_zero, βwith_top.coe_add, zero_add] }
end,
add_zero :=
begin
refine with_top.rec_top_coe _ _,
{ simpa },
{ intro,
rw [βwith_top.coe_zero, βwith_top.coe_add, add_zero] }
end,
..with_top.has_zero,
..with_top.add_semigroup }
instance [add_comm_monoid Ξ±] : add_comm_monoid (with_top Ξ±) :=
{ ..with_top.add_monoid, ..with_top.add_comm_semigroup }
instance [ordered_add_comm_monoid Ξ±] : ordered_add_comm_monoid (with_top Ξ±) :=
{ add_le_add_left :=
begin
rintros a b h (_|c), { simp [none_eq_top] },
rcases b with (_|b), { simp [none_eq_top] },
rcases le_coe_iff.1 h with β¨a, rfl, hβ©,
simp only [some_eq_coe, β coe_add, coe_le_coe] at h β’,
exact add_le_add_left h c
end,
..with_top.partial_order, ..with_top.add_comm_monoid }
instance [linear_ordered_add_comm_monoid Ξ±] :
linear_ordered_add_comm_monoid_with_top (with_top Ξ±) :=
{ top_add' := Ξ» x, with_top.top_add,
..with_top.order_top,
..with_top.linear_order,
..with_top.ordered_add_comm_monoid,
..option.nontrivial }
/-- Coercion from `Ξ±` to `with_top Ξ±` as an `add_monoid_hom`. -/
def coe_add_hom [add_monoid Ξ±] : Ξ± β+ with_top Ξ± :=
β¨coe, rfl, Ξ» _ _, rflβ©
@[simp] lemma coe_coe_add_hom [add_monoid Ξ±] : β(coe_add_hom : Ξ± β+ with_top Ξ±) = coe := rfl
@[simp] lemma zero_lt_top [ordered_add_comm_monoid Ξ±] : (0 : with_top Ξ±) < β€ :=
coe_lt_top 0
@[simp, norm_cast] lemma zero_lt_coe [ordered_add_comm_monoid Ξ±] (a : Ξ±) :
(0 : with_top Ξ±) < a β 0 < a :=
coe_lt_coe
end with_top
namespace with_bot
instance [has_zero Ξ±] : has_zero (with_bot Ξ±) := with_top.has_zero
instance [has_one Ξ±] : has_one (with_bot Ξ±) := with_top.has_one
instance [add_semigroup Ξ±] : add_semigroup (with_bot Ξ±) := with_top.add_semigroup
instance [add_comm_semigroup Ξ±] : add_comm_semigroup (with_bot Ξ±) := with_top.add_comm_semigroup
instance [add_monoid Ξ±] : add_monoid (with_bot Ξ±) := with_top.add_monoid
instance [add_comm_monoid Ξ±] : add_comm_monoid (with_bot Ξ±) := with_top.add_comm_monoid
instance [ordered_add_comm_monoid Ξ±] : ordered_add_comm_monoid (with_bot Ξ±) :=
begin
suffices, refine
{ add_le_add_left := this,
..with_bot.partial_order,
..with_bot.add_comm_monoid, ..},
{ intros a b h c ca hβ,
cases c with c, {cases hβ},
cases a with a; cases hβ,
cases b with b, {cases le_antisymm h bot_le},
simp at h,
exact β¨_, rfl, add_le_add_left h _β©, }
end
instance [linear_ordered_add_comm_monoid Ξ±] : linear_ordered_add_comm_monoid (with_bot Ξ±) :=
{ ..with_bot.linear_order,
..with_bot.ordered_add_comm_monoid }
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
lemma coe_zero [has_zero Ξ±] : ((0 : Ξ±) : with_bot Ξ±) = 0 := rfl
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
lemma coe_one [has_one Ξ±] : ((1 : Ξ±) : with_bot Ξ±) = 1 := rfl
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
lemma coe_eq_zero {Ξ± : Type*}
[add_monoid Ξ±] {a : Ξ±} : (a : with_bot Ξ±) = 0 β a = 0 :=
by norm_cast
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
lemma coe_add [add_semigroup Ξ±] (a b : Ξ±) : ((a + b : Ξ±) : with_bot Ξ±) = a + b := by norm_cast
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
lemma coe_bit0 [add_semigroup Ξ±] {a : Ξ±} : ((bit0 a : Ξ±) : with_bot Ξ±) = bit0 a :=
by norm_cast
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
lemma coe_bit1 [add_semigroup Ξ±] [has_one Ξ±] {a : Ξ±} : ((bit1 a : Ξ±) : with_bot Ξ±) = bit1 a :=
by norm_cast
@[simp] lemma bot_add [add_semigroup Ξ±] (a : with_bot Ξ±) : β₯ + a = β₯ := rfl
@[simp] lemma add_bot [add_semigroup Ξ±] (a : with_bot Ξ±) : a + β₯ = β₯ := by cases a; refl
@[simp] lemma add_eq_bot [add_semigroup Ξ±] {m n : with_bot Ξ±} :
m + n = β₯ β m = β₯ β¨ n = β₯ :=
with_top.add_eq_top
end with_bot
/-- A canonically ordered additive monoid is an ordered commutative additive monoid
in which the ordering coincides with the subtractibility relation,
which is to say, `a β€ b` iff there exists `c` with `b = a + c`.
This is satisfied by the natural numbers, for example, but not
the integers or other nontrivial `ordered_add_comm_group`s. -/
@[protect_proj, ancestor ordered_add_comm_monoid has_bot]
class canonically_ordered_add_monoid (Ξ± : Type*) extends ordered_add_comm_monoid Ξ±, has_bot Ξ± :=
(bot_le : β x : Ξ±, β₯ β€ x)
(le_iff_exists_add : β a b : Ξ±, a β€ b β β c, b = a + c)
@[priority 100] -- see Note [lower instance priority]
instance canonically_ordered_add_monoid.to_order_bot (Ξ± : Type u)
[h : canonically_ordered_add_monoid Ξ±] : order_bot Ξ± :=
{ ..h }
/-- A canonically ordered monoid is an ordered commutative monoid
in which the ordering coincides with the divisibility relation,
which is to say, `a β€ b` iff there exists `c` with `b = a * c`.
Examples seem rare; it seems more likely that the `order_dual`
of a naturally-occurring lattice satisfies this than the lattice
itself (for example, dual of the lattice of ideals of a PID or
Dedekind domain satisfy this; collections of all things β€ 1 seem to
be more natural that collections of all things β₯ 1).
-/
@[protect_proj, ancestor ordered_comm_monoid has_bot, to_additive]
class canonically_ordered_monoid (Ξ± : Type*) extends ordered_comm_monoid Ξ±, has_bot Ξ± :=
(bot_le : β x : Ξ±, β₯ β€ x)
(le_iff_exists_mul : β a b : Ξ±, a β€ b β β c, b = a * c)
@[priority 100, to_additive] -- see Note [lower instance priority]
instance canonically_ordered_monoid.to_order_bot (Ξ± : Type u)
[h : canonically_ordered_monoid Ξ±] : order_bot Ξ± :=
{ ..h }
section canonically_ordered_monoid
variables [canonically_ordered_monoid Ξ±] {a b c d : Ξ±}
@[to_additive]
lemma le_iff_exists_mul : a β€ b β βc, b = a * c :=
canonically_ordered_monoid.le_iff_exists_mul a b
@[to_additive]
lemma self_le_mul_right (a b : Ξ±) : a β€ a * b :=
le_iff_exists_mul.mpr β¨b, rflβ©
@[to_additive]
lemma self_le_mul_left (a b : Ξ±) : a β€ b * a :=
by { rw [mul_comm], exact self_le_mul_right a b }
@[simp, to_additive zero_le] lemma one_le (a : Ξ±) : 1 β€ a :=
le_iff_exists_mul.mpr β¨a, (one_mul _).symmβ©
@[simp, to_additive] lemma bot_eq_one : (β₯ : Ξ±) = 1 :=
le_antisymm bot_le (one_le β₯)
@[simp, to_additive] lemma mul_eq_one_iff : a * b = 1 β a = 1 β§ b = 1 :=
mul_eq_one_iff' (one_le _) (one_le _)
@[simp, to_additive] lemma le_one_iff_eq_one : a β€ 1 β a = 1 :=
iff.intro
(assume h, le_antisymm h (one_le a))
(assume h, h βΈ le_refl a)
@[to_additive] lemma one_lt_iff_ne_one : 1 < a β a β 1 :=
iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (one_le _) hne.symm
@[to_additive] lemma exists_pos_mul_of_lt (h : a < b) : β c > 1, a * c = b :=
begin
obtain β¨c, hcβ© := le_iff_exists_mul.1 h.le,
refine β¨c, one_lt_iff_ne_one.2 _, hc.symmβ©,
rintro rfl,
simpa [hc, lt_irrefl] using h
end
@[to_additive] lemma le_mul_left (h : a β€ c) : a β€ b * c :=
calc a = 1 * a : by simp
... β€ b * c : mul_le_mul' (one_le _) h
@[to_additive] lemma le_mul_self : a β€ b * a :=
le_mul_left (le_refl a)
@[to_additive] lemma le_mul_right (h : a β€ b) : a β€ b * c :=
calc a = a * 1 : by simp
... β€ b * c : mul_le_mul' h (one_le _)
@[to_additive] lemma le_self_mul : a β€ a * c :=
le_mul_right (le_refl a)
@[to_additive]
lemma lt_iff_exists_mul [covariant_class Ξ± Ξ± (*) (<)] : a < b β β c > 1, b = a * c :=
begin
simp_rw [lt_iff_le_and_ne, and_comm, le_iff_exists_mul, β exists_and_distrib_left, exists_prop],
apply exists_congr, intro c,
rw [and.congr_left_iff, gt_iff_lt], rintro rfl,
split,
{ rw [one_lt_iff_ne_one], apply mt, rintro rfl, rw [mul_one] },
{ rw [β (self_le_mul_right a c).lt_iff_ne], apply lt_mul_of_one_lt_right' }
end
-- This instance looks absurd: a monoid already has a zero
/-- Adding a new zero to a canonically ordered additive monoid produces another one. -/
instance with_zero.canonically_ordered_add_monoid {Ξ± : Type u} [canonically_ordered_add_monoid Ξ±] :
canonically_ordered_add_monoid (with_zero Ξ±) :=
{ le_iff_exists_add := Ξ» a b, begin
apply with_zero.cases_on a,
{ exact iff_of_true bot_le β¨b, (zero_add b).symmβ© },
apply with_zero.cases_on b,
{ intro b',
refine iff_of_false (mt (le_antisymm bot_le) (by simp)) (not_exists.mpr (Ξ» c, _)),
apply with_zero.cases_on c;
simp [βwith_zero.coe_add] },
{ simp only [le_iff_exists_add, with_zero.coe_le_coe],
intros,
split; rintro β¨c, hβ©,
{ exact β¨c, congr_arg coe hβ© },
{ induction c using with_zero.cases_on,
{ refine β¨0, _β©,
simpa using h },
{ refine β¨c, _β©,
simpa [βwith_zero.coe_add] using h } } }
end,
.. with_zero.order_bot,
.. with_zero.ordered_add_comm_monoid zero_le }
instance with_top.canonically_ordered_add_monoid {Ξ± : Type u} [canonically_ordered_add_monoid Ξ±] :
canonically_ordered_add_monoid (with_top Ξ±) :=
{ le_iff_exists_add := assume a b,
match a, b with
| a, none := show a β€ β€ β βc, β€ = a + c, by simp; refine β¨β€, _β©; cases a; refl
| (some a), (some b) := show (a:with_top Ξ±) β€ βb β βc:with_top Ξ±, βb = βa + c,
begin
simp [canonically_ordered_add_monoid.le_iff_exists_add, -add_comm],
split,
{ rintro β¨c, rflβ©, refine β¨c, _β©, norm_cast },
{ exact assume h, match b, h with _, β¨some c, rflβ© := β¨_, rflβ© end }
end
| none, some b := show (β€ : with_top Ξ±) β€ b β βc:with_top Ξ±, βb = β€ + c, by simp
end,
.. with_top.order_bot,
.. with_top.ordered_add_comm_monoid }
@[priority 100, to_additive]
instance canonically_ordered_monoid.has_exists_mul_of_le (Ξ± : Type u)
[canonically_ordered_monoid Ξ±] : has_exists_mul_of_le Ξ± :=
{ exists_mul_of_le := Ξ» a b hab, le_iff_exists_mul.mp hab }
end canonically_ordered_monoid
lemma pos_of_gt {M : Type*} [canonically_ordered_add_monoid M] {n m : M} (h : n < m) : 0 < m :=
lt_of_le_of_lt (zero_le _) h
/-- A canonically linear-ordered additive monoid is a canonically ordered additive monoid
whose ordering is a linear order. -/
@[protect_proj, ancestor canonically_ordered_add_monoid linear_order]
class canonically_linear_ordered_add_monoid (Ξ± : Type*)
extends canonically_ordered_add_monoid Ξ±, linear_order Ξ±
/-- A canonically linear-ordered monoid is a canonically ordered monoid
whose ordering is a linear order. -/
@[protect_proj, ancestor canonically_ordered_monoid linear_order, to_additive]
class canonically_linear_ordered_monoid (Ξ± : Type*)
extends canonically_ordered_monoid Ξ±, linear_order Ξ±
section canonically_linear_ordered_monoid
variables [canonically_linear_ordered_monoid Ξ±]
@[priority 100, to_additive] -- see Note [lower instance priority]
instance canonically_linear_ordered_monoid.semilattice_sup : semilattice_sup Ξ± :=
{ ..linear_order.to_lattice }
instance with_top.canonically_linear_ordered_add_monoid
(Ξ± : Type*) [canonically_linear_ordered_add_monoid Ξ±] :
canonically_linear_ordered_add_monoid (with_top Ξ±) :=
{ .. (infer_instance : canonically_ordered_add_monoid (with_top Ξ±)),
.. (infer_instance : linear_order (with_top Ξ±)) }
@[to_additive]
lemma min_mul_distrib (a b c : Ξ±) : min a (b * c) = min a (min a b * min a c) :=
begin
cases le_total a b with hb hb,
{ simp [hb, le_mul_right] },
{ cases le_total a c with hc hc,
{ simp [hc, le_mul_left] },
{ simp [hb, hc] } }
end
@[to_additive]
lemma min_mul_distrib' (a b c : Ξ±) : min (a * b) c = min (min a c * min b c) c :=
by simpa [min_comm _ c] using min_mul_distrib c a b
@[simp, to_additive]
lemma one_min (a : Ξ±) : min 1 a = 1 :=
min_eq_left (one_le a)
@[simp, to_additive]
lemma min_one (a : Ξ±) : min a 1 = 1 :=
min_eq_right (one_le a)
end canonically_linear_ordered_monoid
/-- An ordered cancellative additive commutative monoid
is an additive commutative monoid with a partial order,
in which addition is cancellative and monotone. -/
@[protect_proj, ancestor add_cancel_comm_monoid partial_order]
class ordered_cancel_add_comm_monoid (Ξ± : Type u)
extends add_cancel_comm_monoid Ξ±, partial_order Ξ± :=
(add_le_add_left : β a b : Ξ±, a β€ b β β c : Ξ±, c + a β€ c + b)
(le_of_add_le_add_left : β a b c : Ξ±, a + b β€ a + c β b β€ c)
/-- An ordered cancellative commutative monoid
is a commutative monoid with a partial order,
in which multiplication is cancellative and monotone. -/
@[protect_proj, ancestor cancel_comm_monoid partial_order, to_additive]
class ordered_cancel_comm_monoid (Ξ± : Type u)
extends cancel_comm_monoid Ξ±, partial_order Ξ± :=
(mul_le_mul_left : β a b : Ξ±, a β€ b β β c : Ξ±, c * a β€ c * b)
(le_of_mul_le_mul_left : β a b c : Ξ±, a * b β€ a * c β b β€ c)
section ordered_cancel_comm_monoid
variables [ordered_cancel_comm_monoid Ξ±] {a b c d : Ξ±}
@[to_additive]
lemma ordered_cancel_comm_monoid.lt_of_mul_lt_mul_left : β a b c : Ξ±, a * b < a * c β b < c :=
Ξ» a b c h, lt_of_le_not_le
(ordered_cancel_comm_monoid.le_of_mul_le_mul_left a b c h.le) $
mt (Ξ» h, ordered_cancel_comm_monoid.mul_le_mul_left _ _ h _) (not_le_of_gt h)
@[to_additive]
instance ordered_cancel_comm_monoid.to_contravariant_class_left
(M : Type*) [ordered_cancel_comm_monoid M] :
contravariant_class M M (*) (<) :=
{ elim := Ξ» a b c, ordered_cancel_comm_monoid.lt_of_mul_lt_mul_left _ _ _ }
/- This instance can be proven with `by apply_instance`. However, by analogy with the
instance `ordered_cancel_comm_monoid.to_covariant_class_right` above, I imagine that without
this instance, some Type would not have a `contravariant_class M M (function.swap (*)) (<)`
instance. -/
@[to_additive]
instance ordered_cancel_comm_monoid.to_contravariant_class_right
(M : Type*) [ordered_cancel_comm_monoid M] :
contravariant_class M M (swap (*)) (<) :=
contravariant_swap_mul_lt_of_contravariant_mul_lt M
@[priority 100, to_additive] -- see Note [lower instance priority]
instance ordered_cancel_comm_monoid.to_ordered_comm_monoid : ordered_comm_monoid Ξ± :=
{ ..βΉordered_cancel_comm_monoid Ξ±βΊ }
/-- Pullback an `ordered_cancel_comm_monoid` under an injective map.
See note [reducible non-instances]. -/
@[reducible, to_additive function.injective.ordered_cancel_add_comm_monoid
"Pullback an `ordered_cancel_add_comm_monoid` under an injective map."]
def function.injective.ordered_cancel_comm_monoid {Ξ² : Type*}
[has_one Ξ²] [has_mul Ξ²]
(f : Ξ² β Ξ±) (hf : function.injective f) (one : f 1 = 1)
(mul : β x y, f (x * y) = f x * f y) :
ordered_cancel_comm_monoid Ξ² :=
{ le_of_mul_le_mul_left := Ξ» a b c (bc : f (a * b) β€ f (a * c)),
(mul_le_mul_iff_left (f a)).mp (by rwa [β mul, β mul]),
..hf.left_cancel_semigroup f mul,
..hf.ordered_comm_monoid f one mul }
end ordered_cancel_comm_monoid
/-! Some lemmas about types that have an ordering and a binary operation, with no
rules relating them. -/
@[to_additive]
lemma fn_min_mul_fn_max {Ξ²} [linear_order Ξ±] [comm_semigroup Ξ²] (f : Ξ± β Ξ²) (n m : Ξ±) :
f (min n m) * f (max n m) = f n * f m :=
by { cases le_total n m with h h; simp [h, mul_comm] }
@[to_additive]
lemma min_mul_max [linear_order Ξ±] [comm_semigroup Ξ±] (n m : Ξ±) :
min n m * max n m = n * m :=
fn_min_mul_fn_max id n m
/-- A linearly ordered cancellative additive commutative monoid
is an additive commutative monoid with a decidable linear order
in which addition is cancellative and monotone. -/
@[protect_proj, ancestor ordered_cancel_add_comm_monoid linear_ordered_add_comm_monoid]
class linear_ordered_cancel_add_comm_monoid (Ξ± : Type u)
extends ordered_cancel_add_comm_monoid Ξ±, linear_ordered_add_comm_monoid Ξ±
/-- A linearly ordered cancellative commutative monoid
is a commutative monoid with a linear order
in which multiplication is cancellative and monotone. -/
@[protect_proj, ancestor ordered_cancel_comm_monoid linear_ordered_comm_monoid, to_additive]
class linear_ordered_cancel_comm_monoid (Ξ± : Type u)
extends ordered_cancel_comm_monoid Ξ±, linear_ordered_comm_monoid Ξ±
section covariant_class_mul_le
variables [linear_order Ξ±]
section has_mul
variable [has_mul Ξ±]
section left
variable [covariant_class Ξ± Ξ± (*) (β€)]
@[to_additive] lemma min_mul_mul_left (a b c : Ξ±) : min (a * b) (a * c) = a * min b c :=
(monotone_id.const_mul' a).map_min.symm
@[to_additive]
lemma max_mul_mul_left (a b c : Ξ±) : max (a * b) (a * c) = a * max b c :=
(monotone_id.const_mul' a).map_max.symm
end left
section right
variable [covariant_class Ξ± Ξ± (function.swap (*)) (β€)]
@[to_additive]
lemma min_mul_mul_right (a b c : Ξ±) : min (a * c) (b * c) = min a b * c :=
(monotone_id.mul_const' c).map_min.symm
@[to_additive]
lemma max_mul_mul_right (a b c : Ξ±) : max (a * c) (b * c) = max a b * c :=
(monotone_id.mul_const' c).map_max.symm
end right
end has_mul
variable [monoid Ξ±]
@[to_additive]
lemma min_le_mul_of_one_le_right [covariant_class Ξ± Ξ± (*) (β€)] {a b : Ξ±} (hb : 1 β€ b) :
min a b β€ a * b :=
min_le_iff.2 $ or.inl $ le_mul_of_one_le_right' hb
@[to_additive]
lemma min_le_mul_of_one_le_left [covariant_class Ξ± Ξ± (function.swap (*)) (β€)] {a b : Ξ±}
(ha : 1 β€ a) : min a b β€ a * b :=
min_le_iff.2 $ or.inr $ le_mul_of_one_le_left' ha
@[to_additive]
lemma max_le_mul_of_one_le [covariant_class Ξ± Ξ± (*) (β€)]
[covariant_class Ξ± Ξ± (function.swap (*)) (β€)] {a b : Ξ±} (ha : 1 β€ a) (hb : 1 β€ b) :
max a b β€ a * b :=
max_le_iff.2 β¨le_mul_of_one_le_right' hb, le_mul_of_one_le_left' haβ©
end covariant_class_mul_le
section linear_ordered_cancel_comm_monoid
variables [linear_ordered_cancel_comm_monoid Ξ±]
/-- Pullback a `linear_ordered_cancel_comm_monoid` under an injective map.
See note [reducible non-instances]. -/
@[reducible, to_additive function.injective.linear_ordered_cancel_add_comm_monoid
"Pullback a `linear_ordered_cancel_add_comm_monoid` under an injective map."]
def function.injective.linear_ordered_cancel_comm_monoid {Ξ² : Type*}
[has_one Ξ²] [has_mul Ξ²]
(f : Ξ² β Ξ±) (hf : function.injective f) (one : f 1 = 1)
(mul : β x y, f (x * y) = f x * f y) :
linear_ordered_cancel_comm_monoid Ξ² :=
{ ..hf.linear_ordered_comm_monoid f one mul,
..hf.ordered_cancel_comm_monoid f one mul }
end linear_ordered_cancel_comm_monoid
namespace order_dual
@[to_additive] instance [h : has_mul Ξ±] : has_mul (order_dual Ξ±) := h
@[to_additive] instance [h : has_one Ξ±] : has_one (order_dual Ξ±) := h
@[to_additive] instance [h : monoid Ξ±] : monoid (order_dual Ξ±) := h
@[to_additive] instance [h : comm_monoid Ξ±] : comm_monoid (order_dual Ξ±) := h
@[to_additive] instance [h : cancel_comm_monoid Ξ±] : cancel_comm_monoid (order_dual Ξ±) := h
@[to_additive]
instance contravariant_class_mul_le [has_le Ξ±] [has_mul Ξ±] [c : contravariant_class Ξ± Ξ± (*) (β€)] :
contravariant_class (order_dual Ξ±) (order_dual Ξ±) (*) (β€) :=
β¨c.1.flipβ©
@[to_additive]
instance covariant_class_mul_le [has_le Ξ±] [has_mul Ξ±] [c : covariant_class Ξ± Ξ± (*) (β€)] :
covariant_class (order_dual Ξ±) (order_dual Ξ±) (*) (β€) :=
β¨c.1.flipβ©
@[to_additive] instance contravariant_class_swap_mul_le [has_le Ξ±] [has_mul Ξ±]
[c : contravariant_class Ξ± Ξ± (swap (*)) (β€)] :
contravariant_class (order_dual Ξ±) (order_dual Ξ±) (swap (*)) (β€) :=
β¨c.1.flipβ©
@[to_additive]
instance covariant_class_swap_mul_le [has_le Ξ±] [has_mul Ξ±]
[c : covariant_class Ξ± Ξ± (swap (*)) (β€)] :
covariant_class (order_dual Ξ±) (order_dual Ξ±) (swap (*)) (β€) :=
β¨c.1.flipβ©
@[to_additive]
instance contravariant_class_mul_lt [has_lt Ξ±] [has_mul Ξ±] [c : contravariant_class Ξ± Ξ± (*) (<)] :
contravariant_class (order_dual Ξ±) (order_dual Ξ±) (*) (<) :=
β¨c.1.flipβ©
@[to_additive]
instance covariant_class_mul_lt [has_lt Ξ±] [has_mul Ξ±] [c : covariant_class Ξ± Ξ± (*) (<)] :
covariant_class (order_dual Ξ±) (order_dual Ξ±) (*) (<) :=
β¨c.1.flipβ©
@[to_additive] instance contravariant_class_swap_mul_lt [has_lt Ξ±] [has_mul Ξ±]
[c : contravariant_class Ξ± Ξ± (swap (*)) (<)] :
contravariant_class (order_dual Ξ±) (order_dual Ξ±) (swap (*)) (<) :=
β¨c.1.flipβ©
@[to_additive]
instance covariant_class_swap_mul_lt [has_lt Ξ±] [has_mul Ξ±]
[c : covariant_class Ξ± Ξ± (swap (*)) (<)] :
covariant_class (order_dual Ξ±) (order_dual Ξ±) (swap (*)) (<) :=
β¨c.1.flipβ©
@[to_additive]
instance [ordered_comm_monoid Ξ±] : ordered_comm_monoid (order_dual Ξ±) :=
{ mul_le_mul_left := Ξ» a b h c, mul_le_mul_left' h c,
.. order_dual.partial_order Ξ±,
.. order_dual.comm_monoid }
@[to_additive ordered_cancel_add_comm_monoid.to_contravariant_class]
instance ordered_cancel_comm_monoid.to_contravariant_class [ordered_cancel_comm_monoid Ξ±] :
contravariant_class (order_dual Ξ±) (order_dual Ξ±) has_mul.mul has_le.le :=
{ elim := Ξ» a b c bc, (ordered_cancel_comm_monoid.le_of_mul_le_mul_left a c b (dual_le.mp bc)) }
@[to_additive]
instance [ordered_cancel_comm_monoid Ξ±] : ordered_cancel_comm_monoid (order_dual Ξ±) :=
{ le_of_mul_le_mul_left := Ξ» a b c : Ξ±, le_of_mul_le_mul_left',
.. order_dual.ordered_comm_monoid, .. order_dual.cancel_comm_monoid }
@[to_additive]
instance [linear_ordered_cancel_comm_monoid Ξ±] :
linear_ordered_cancel_comm_monoid (order_dual Ξ±) :=
{ .. order_dual.linear_order Ξ±,
.. order_dual.ordered_cancel_comm_monoid }
@[to_additive]
instance [linear_ordered_comm_monoid Ξ±] :
linear_ordered_comm_monoid (order_dual Ξ±) :=
{ .. order_dual.linear_order Ξ±,
.. order_dual.ordered_comm_monoid }
end order_dual
section linear_ordered_cancel_add_comm_monoid
variables [linear_ordered_cancel_add_comm_monoid Ξ±]
lemma lt_or_lt_of_add_lt_add {a b m n : Ξ±} (h : m + n < a + b) : m < a β¨ n < b :=
by { contrapose! h, exact add_le_add h.1 h.2 }
end linear_ordered_cancel_add_comm_monoid
section ordered_cancel_add_comm_monoid
variable [ordered_cancel_add_comm_monoid Ξ±]
namespace with_top
lemma add_lt_add_iff_left {a b c : with_top Ξ±} (ha : a β β€) : a + b < a + c β b < c :=
begin
lift a to Ξ± using ha,
cases b; cases c,
{ simp [none_eq_top] },
{ simp [some_eq_coe, none_eq_top, coe_lt_top] },
{ simp [some_eq_coe, none_eq_top, β coe_add, coe_lt_top] },
{ simp [some_eq_coe, β coe_add, coe_lt_coe] }
end
lemma add_lt_add_iff_right {a b c : with_top Ξ±} (ha : a β β€) : (c + a < b + a β c < b) :=
by simp only [β add_comm a, add_lt_add_iff_left ha]
instance contravariant_class_add_lt : contravariant_class (with_top Ξ±) (with_top Ξ±) (+) (<) :=
begin
refine β¨Ξ» a b c h, _β©,
cases a,
{ rw [none_eq_top, top_add, top_add] at h, exact (lt_irrefl β€ h).elim },
{ exact (add_lt_add_iff_left coe_ne_top).1 h }
end
end with_top
namespace with_bot
lemma add_lt_add_iff_left {a b c : with_bot Ξ±} (ha : a β β₯) : a + b < a + c β b < c :=
@with_top.add_lt_add_iff_left (order_dual Ξ±) _ a c b ha
lemma add_lt_add_iff_right {a b c : with_bot Ξ±} (ha : a β β₯) : b + a < c + a β b < c :=
@with_top.add_lt_add_iff_right (order_dual Ξ±) _ _ _ _ ha
instance contravariant_class_add_lt : contravariant_class (with_bot Ξ±) (with_bot Ξ±) (+) (<) :=
@order_dual.contravariant_class_add_lt (with_top $ order_dual Ξ±) _ _ _
end with_bot
end ordered_cancel_add_comm_monoid
namespace prod
variables {M N : Type*}
@[to_additive]
instance [ordered_cancel_comm_monoid M] [ordered_cancel_comm_monoid N] :
ordered_cancel_comm_monoid (M Γ N) :=
{ mul_le_mul_left := Ξ» a b h c, β¨mul_le_mul_left' h.1 _, mul_le_mul_left' h.2 _β©,
le_of_mul_le_mul_left := Ξ» a b c h, β¨le_of_mul_le_mul_left' h.1, le_of_mul_le_mul_left' h.2β©,
.. prod.cancel_comm_monoid, .. prod.partial_order M N }
end prod
section type_tags
instance : Ξ [preorder Ξ±], preorder (multiplicative Ξ±) := id
instance : Ξ [preorder Ξ±], preorder (additive Ξ±) := id
instance : Ξ [partial_order Ξ±], partial_order (multiplicative Ξ±) := id
instance : Ξ [partial_order Ξ±], partial_order (additive Ξ±) := id
instance : Ξ [linear_order Ξ±], linear_order (multiplicative Ξ±) := id
instance : Ξ [linear_order Ξ±], linear_order (additive Ξ±) := id
instance [ordered_add_comm_monoid Ξ±] : ordered_comm_monoid (multiplicative Ξ±) :=
{ mul_le_mul_left := @ordered_add_comm_monoid.add_le_add_left Ξ± _,
..multiplicative.partial_order,
..multiplicative.comm_monoid }
instance [ordered_comm_monoid Ξ±] : ordered_add_comm_monoid (additive Ξ±) :=
{ add_le_add_left := @ordered_comm_monoid.mul_le_mul_left Ξ± _,
..additive.partial_order,
..additive.add_comm_monoid }
instance [ordered_cancel_add_comm_monoid Ξ±] : ordered_cancel_comm_monoid (multiplicative Ξ±) :=
{ le_of_mul_le_mul_left := @ordered_cancel_add_comm_monoid.le_of_add_le_add_left Ξ± _,
..multiplicative.left_cancel_semigroup,
..multiplicative.ordered_comm_monoid }
instance [ordered_cancel_comm_monoid Ξ±] : ordered_cancel_add_comm_monoid (additive Ξ±) :=
{ le_of_add_le_add_left := @ordered_cancel_comm_monoid.le_of_mul_le_mul_left Ξ± _,
..additive.add_left_cancel_semigroup,
..additive.ordered_add_comm_monoid }
instance [linear_ordered_add_comm_monoid Ξ±] : linear_ordered_comm_monoid (multiplicative Ξ±) :=
{ ..multiplicative.linear_order,
..multiplicative.ordered_comm_monoid }
instance [linear_ordered_comm_monoid Ξ±] : linear_ordered_add_comm_monoid (additive Ξ±) :=
{ ..additive.linear_order,
..additive.ordered_add_comm_monoid }
end type_tags
/-- The order embedding sending `b` to `a * b`, for some fixed `a`.
See also `order_iso.mul_left` when working in an ordered group. -/
@[to_additive "The order embedding sending `b` to `a + b`, for some fixed `a`.
See also `order_iso.add_left` when working in an additive ordered group.", simps]
def order_embedding.mul_left
{Ξ± : Type*} [has_mul Ξ±] [linear_order Ξ±] [covariant_class Ξ± Ξ± (*) (<)] (m : Ξ±) : Ξ± βͺo Ξ± :=
order_embedding.of_strict_mono (Ξ» n, m * n) (Ξ» a b w, mul_lt_mul_left' w m)
/-- The order embedding sending `b` to `b * a`, for some fixed `a`.
See also `order_iso.mul_right` when working in an ordered group. -/
@[to_additive "The order embedding sending `b` to `b + a`, for some fixed `a`.
See also `order_iso.add_right` when working in an additive ordered group.", simps]
def order_embedding.mul_right
{Ξ± : Type*} [has_mul Ξ±] [linear_order Ξ±] [covariant_class Ξ± Ξ± (swap (*)) (<)] (m : Ξ±) :
Ξ± βͺo Ξ± :=
order_embedding.of_strict_mono (Ξ» n, n * m) (Ξ» a b w, mul_lt_mul_right' w m)
|
e56ae4217a91b7cd8db28a0aa7403ba79ad27fb4 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/interactive/complete_namespace.lean | a6f296ed5d8909a021de695e38638275b4a734e2 | [
"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 | 131 | lean | prelude
inductive foo.bar
open foo
--^ "command": "complete"
namespace foo
open bar
--^ "command": "complete"
end foo
|
ace12ee30b7821dcbd21e8153fe4503ecf3989fa | 8e6cad62ec62c6c348e5faaa3c3f2079012bdd69 | /src/topology/paracompact.lean | 86daa82552f6770ace4dbeac1dfcd71f01473c21 | [
"Apache-2.0"
] | permissive | benjamindavidson/mathlib | 8cc81c865aa8e7cf4462245f58d35ae9a56b150d | fad44b9f670670d87c8e25ff9cdf63af87ad731e | refs/heads/master | 1,679,545,578,362 | 1,615,343,014,000 | 1,615,343,014,000 | 312,926,983 | 0 | 0 | Apache-2.0 | 1,615,360,301,000 | 1,605,399,418,000 | Lean | UTF-8 | Lean | false | false | 15,276 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Yury Kudryashov
-/
import topology.subset_properties
import topology.separation
import data.option.basic
/-!
# Paracompact topological spaces
A topological space `X` is said to be paracompact if every open covering of `X` admits a locally
finite refinement.
The definition requires that each set of the new covering is a subset of one of the sets of the
initial covering. However, one can ensure that each open covering `s : ΞΉ β set X` admits a *precise*
locally finite refinement, i.e., an open covering `t : ΞΉ β set X` with the same index set such that
`β i, t i β s i`, see lemma `precise_refinement`. We also provide a convenience lemma
`precise_refinement_set` that deals with open coverings of a closed subset of `X` instead of the
whole space.
We also prove the following facts.
* Every compact space is paracompact, see instance `paracompact_of_compact`.
* A locally compact sigma compact Hausdorff space is paracompact, see instance
`paracompact_of_locally_compact_sigma_compact`. Moreover, we can choose a locally finite
refinement with sets in a given collection of filter bases of `π x, `x : X`, see
`refinement_of_locally_compact_sigma_compact_of_nhds_basis`. For example, in a proper metric space
every open covering `β i, s i` admits a refinement `β i, metric.ball (c i) (r i)`.
* Every paracompact Hausdorff space is normal. This statement is not an instance to avoid loops in
the instance graph.
* Every `emetric_space` is a paracompact space, see instance `emetric_space.paracompact_space` in
`topology/metric_space/emetric_space`.
## TODO
* Define partition of unity.
* Prove (some of) [Michael's theorems](https://ncatlab.org/nlab/show/Michael%27s+theorem).
## Tags
compact space, paracompact space, locally finite covering
-/
open set filter function
open_locale filter topological_space
universes u v
/-- A topological space is called paracompact, if every open covering of this space admits a locally
finite refinement. We use the same universe for all types in the definition to avoid creating a
class like `paracompact_space.{u v}`. Due to lemma `precise_refinement` below, every open covering
`s : Ξ± β set X` indexed on `Ξ± : Type v` has a *precise* locally finite refinement, i.e., a locally
finite refinement `t : Ξ± β set X` indexed on the same type such that each `β i, t i β s i`. -/
class paracompact_space (X : Type v) [topological_space X] : Prop :=
(locally_finite_refinement :
β (Ξ± : Type v) (s : Ξ± β set X) (ho : β a, is_open (s a)) (hc : (β a, s a) = univ),
β (Ξ² : Type v) (t : Ξ² β set X) (ho : β b, is_open (t b)) (hc : (β b, t b) = univ),
locally_finite t β§ β b, β a, t b β s a)
variables {ΞΉ : Type u} {X : Type v} [topological_space X]
/-- Any open cover of a paracompact space has a locally finite *precise* refinement, that is,
one indexed on the same type with each open set contained in the corresponding original one. -/
lemma precise_refinement [paracompact_space X] (u : ΞΉ β set X) (uo : β a, is_open (u a))
(uc : (β i, u i) = univ) :
β v : ΞΉ β set X, (β a, is_open (v a)) β§ (β i, v i) = univ β§ locally_finite v β§ (β a, v a β u a) :=
begin
-- Apply definition to `range u`, then turn existence quantifiers into functions using `choose`
have := paracompact_space.locally_finite_refinement (range u) coe
(set_coe.forall.2 $ forall_range_iff.2 uo) (by rwa [β sUnion_range, subtype.range_coe]),
simp only [set_coe.exists, subtype.coe_mk, exists_range_iff', Union_eq_univ_iff,
exists_prop] at this,
choose Ξ± t hto hXt htf ind hind, choose t_inv ht_inv using hXt, choose U hxU hU using htf,
-- Send each `i` to the union of `t a` over `a β ind β»ΒΉ' {i}`
refine β¨Ξ» i, β (a : Ξ±) (ha : ind a = i), t a, _, _, _, _β©,
{ exact Ξ» a, is_open_Union (Ξ» a, is_open_Union $ Ξ» ha, hto a) },
{ simp only [eq_univ_iff_forall, mem_Union],
exact Ξ» x, β¨ind (t_inv x), _, rfl, ht_inv _β© },
{ refine Ξ» x, β¨U x, hxU x, ((hU x).image ind).subset _β©,
simp only [subset_def, mem_Union, mem_set_of_eq, set.nonempty, mem_inter_eq],
rintro i β¨y, β¨a, rfl, hyaβ©, hyUβ©,
exact mem_image_of_mem _ β¨y, hya, hyUβ© },
{ simp only [subset_def, mem_Union],
rintro i x β¨a, rfl, hxaβ©,
exact hind _ hxa }
end
/-- In a paracompact space, every open covering of a closed set admits a locally finite refinement
indexed by the same type. -/
lemma precise_refinement_set [paracompact_space X] {s : set X} (hs : is_closed s)
(u : ΞΉ β set X) (uo : β i, is_open (u i)) (us : s β β i, u i) :
β v : ΞΉ β set X, (β i, is_open (v i)) β§ (s β β i, v i) β§ locally_finite v β§ (β i, v i β u i) :=
begin
rcases precise_refinement (Ξ» i, option.elim i sαΆ u)
(option.forall.2 β¨is_open_compl_iff.2 hs, uoβ©) _ with β¨v, vo, vc, vf, vuβ©,
refine β¨v β some, Ξ» i, vo _, _, vf.comp_injective (option.some_injective _), Ξ» i, vu _β©,
{ simp only [Union_option, β compl_subset_iff_union] at vc,
exact subset.trans (subset_compl_comm.1 $ vu option.none) vc },
{ simpa only [Union_option, option.elim, β compl_subset_iff_union, compl_compl] }
end
/-- A compact space is paracompact. -/
@[priority 100] -- See note [lower instance priority]
instance paracompact_of_compact [compact_space X] : paracompact_space X :=
begin
-- the proof is trivial: we choose a finite subcover using compactness, and use it
refine β¨Ξ» ΞΉ s ho hu, _β©,
rcases compact_univ.elim_finite_subcover _ ho hu.ge with β¨T, hTβ©,
have := hT, simp only [subset_def, mem_Union] at this,
choose i hiT hi using Ξ» x, this x (mem_univ x),
refine β¨(T : set ΞΉ), Ξ» t, s t, Ξ» t, ho _, _, locally_finite_of_fintype _, Ξ» t, β¨t, subset.rflβ©β©,
rwa [Union_subtype, finset.set_bUnion_coe, β univ_subset_iff],
end
/-- Let `X` be a locally compact sigma compact Hausdorff topological space, let `s` be a closed set
in `X`. Suppose that for each `x β s` the sets `B x : ΞΉ x β set X` with the predicate
`p x : ΞΉ x β Prop` form a basis of the filter `π x`. Then there exists a locally finite covering
`Ξ» i, B (c i) (r i)` of `s` such that all βcentersβ `c i` belong to `s` and each `r i` satisfies
`p (c i)`.
The notation is inspired by the case `B x r = metric.ball x r` but the theorem applies to
`nhds_basis_opens` as well. If the covering must be subordinate to some open covering of `s`, then
the user should use a basis obtained by `filter.has_basis.restrict_subset` or a similar lemma, see
the proof of `paracompact_of_locally_compact_sigma_compact` for an example.
The formalization is based on two [ncatlab](https://ncatlab.org/) proofs:
* [locally compact and sigma compact spaces are paracompact](https://ncatlab.org/nlab/show/locally+compact+and+sigma-compact+spaces+are+paracompact);
* [open cover of smooth manifold admits locally finite refinement by closed balls](https://ncatlab.org/nlab/show/partition+of+unity#ExistenceOnSmoothManifolds).
See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis` for a version of this lemma
dealing with a covering of the whole space.
In most cases (namely, if `B c r βͺ B c r'` is again a set of the form `B c r''`) it is possible
to choose `Ξ± = X`. This fact is not yet formalized in `mathlib`. -/
theorem refinement_of_locally_compact_sigma_compact_of_nhds_basis_set
[locally_compact_space X] [sigma_compact_space X] [t2_space X]
{ΞΉ : X β Type u} {p : Ξ x, ΞΉ x β Prop} {B : Ξ x, ΞΉ x β set X} {s : set X}
(hs : is_closed s) (hB : β x β s, (π x).has_basis (p x) (B x)) :
β (Ξ± : Type v) (c : Ξ± β X) (r : Ξ a, ΞΉ (c a)), (β a, c a β s β§ p (c a) (r a)) β§
(s β β a, B (c a) (r a)) β§ locally_finite (Ξ» a, B (c a) (r a)) :=
begin
classical,
-- For technical reasons we prepend two empty sets to the sequence `compact_exhaustion.choice X`
set K' : compact_exhaustion X := compact_exhaustion.choice X,
set K : compact_exhaustion X := K'.shiftr.shiftr,
set Kdiff := Ξ» n, K (n + 1) \ interior (K n),
-- Now we restate some properties of `compact_exhaustion` for `K`/`Kdiff`
have hKcov : β x, x β Kdiff (K'.find x + 1),
{ intro x,
simpa only [K'.find_shiftr]
using diff_subset_diff_right interior_subset (K'.shiftr.mem_diff_shiftr_find x) },
have Kdiffc : β n, is_compact (Kdiff n β© s),
from Ξ» n, (compact_diff (K.is_compact _) is_open_interior).inter_right hs,
-- Next we choose a finite covering `B (c n i) (r n i)` of each
-- `Kdiff (n + 1) β© s` such that `B (c n i) (r n i) β© s` is disjoint with `K n`
have : β n (x : Kdiff (n + 1) β© s), (K n)αΆ β π (x : X),
from Ξ» n x, mem_nhds_sets (K.is_closed n) (Ξ» hx', x.2.1.2 $ K.subset_interior_succ _ hx'),
haveI : β n (x : Kdiff n β© s), nonempty (ΞΉ x) := Ξ» n x, (hB x x.2.2).nonempty,
choose! r hrp hr using (Ξ» n (x : Kdiff (n + 1) β© s), (hB x x.2.2).mem_iff.1 (this n x)),
have hxr : β n x (hx : x β Kdiff (n + 1) β© s), B x (r n β¨x, hxβ©) β π x,
from Ξ» n x hx, (hB x hx.2).mem_of_mem (hrp _ β¨x, hxβ©),
choose T hT using Ξ» n, (Kdiffc (n + 1)).elim_nhds_subcover' _ (hxr n),
set T' : Ξ n, set β₯(Kdiff (n + 1) β© s) := Ξ» n, T n,
-- Finally, we take the union of all these coverings
refine β¨Ξ£ n, T' n, Ξ» a, a.2, Ξ» a, r a.1 a.2, _, _, _β©,
{ rintro β¨n, x, hxβ©, exact β¨x.2.2, hrp _ _β© },
{ refine (Ξ» x hx, mem_Union.2 _),
rcases mem_bUnion_iff.1 (hT _ β¨hKcov x, hxβ©) with β¨β¨c, hcβ©, hcT, hcxβ©,
exact β¨β¨_, β¨c, hcβ©, hcTβ©, hcxβ© },
{ intro x,
refine β¨interior (K (K'.find x + 3)),
mem_nhds_sets is_open_interior (K.subset_interior_succ _ (hKcov x).1), _β©,
have : (β k β€ K'.find x + 2, (range $ sigma.mk k) : set (Ξ£ n, T' n)).finite,
from (finite_le_nat _).bUnion (Ξ» k hk, finite_range _),
apply this.subset, rintro β¨k, c, hcβ©,
simp only [mem_Union, mem_set_of_eq, mem_image_eq, subtype.coe_mk],
rintro β¨x, hxB : x β B c (r k c), hxKβ©,
refine β¨k, _, β¨c, hcβ©, rflβ©,
have := (mem_compl_iff _ _).1 (hr k c hxB),
contrapose! this with hnk,
exact K.subset hnk (interior_subset hxK) },
end
/-- Let `X` be a locally compact sigma compact Hausdorff topological space. Suppose that for each
`x` the sets `B x : ΞΉ x β set X` with the predicate `p x : ΞΉ x β Prop` form a basis of the filter
`π x`. Then there exists a locally finite covering `Ξ» i, B (c i) (r i)` of `X` such that each `r i`
satisfies `p (c i)`
The notation is inspired by the case `B x r = metric.ball x r` but the theorem applies to
`nhds_basis_opens` as well. If the covering must be subordinate to some open covering of `s`, then
the user should use a basis obtained by `filter.has_basis.restrict_subset` or a similar lemma, see
the proof of `paracompact_of_locally_compact_sigma_compact` for an example.
The formalization is based on two [ncatlab](https://ncatlab.org/) proofs:
* [locally compact and sigma compact spaces are paracompact](https://ncatlab.org/nlab/show/locally+compact+and+sigma-compact+spaces+are+paracompact);
* [open cover of smooth manifold admits locally finite refinement by closed balls](https://ncatlab.org/nlab/show/partition+of+unity#ExistenceOnSmoothManifolds).
See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis_set` for a version of this lemma
dealing with a covering of a closed set.
In most cases (namely, if `B c r βͺ B c r'` is again a set of the form `B c r''`) it is possible
to choose `Ξ± = X`. This fact is not yet formalized in `mathlib`. -/
theorem refinement_of_locally_compact_sigma_compact_of_nhds_basis
[locally_compact_space X] [sigma_compact_space X] [t2_space X]
{ΞΉ : X β Type u} {p : Ξ x, ΞΉ x β Prop} {B : Ξ x, ΞΉ x β set X}
(hB : β x, (π x).has_basis (p x) (B x)) :
β (Ξ± : Type v) (c : Ξ± β X) (r : Ξ a, ΞΉ (c a)), (β a, p (c a) (r a)) β§
(β a, B (c a) (r a)) = univ β§ locally_finite (Ξ» a, B (c a) (r a)) :=
let β¨Ξ±, c, r, hp, hU, hfinβ© := refinement_of_locally_compact_sigma_compact_of_nhds_basis_set
is_closed_univ (Ξ» x _, hB x)
in β¨Ξ±, c, r, Ξ» a, (hp a).2, univ_subset_iff.1 hU, hfinβ©
/-- A locally compact sigma compact Hausdorff space is paracompact. See also
`refinement_of_locally_compact_sigma_compact_of_nhds_basis` for a more precise statement. -/
@[priority 100] -- See note [lower instance priority]
instance paracompact_of_locally_compact_sigma_compact [locally_compact_space X]
[sigma_compact_space X] [t2_space X] : paracompact_space X :=
begin
refine β¨Ξ» Ξ± s ho hc, _β©,
choose i hi using Union_eq_univ_iff.1 hc,
have : β x : X, (π x).has_basis (Ξ» t : set X, (x β t β§ is_open t) β§ t β s (i x)) id,
from Ξ» x : X, (nhds_basis_opens x).restrict_subset (mem_nhds_sets (ho (i x)) (hi x)),
rcases refinement_of_locally_compact_sigma_compact_of_nhds_basis this
with β¨Ξ², c, t, hto, htc, htfβ©,
exact β¨Ξ², t, Ξ» x, (hto x).1.2, htc, htf, Ξ» b, β¨i $ c b, (hto b).2β©β©
end
/- DieudonnΓ©βs theorem: a paracompact Hausdorff space is normal. Formalization is based on the proof
at [ncatlab](https://ncatlab.org/nlab/show/paracompact+Hausdorff+spaces+are+normal). -/
lemma normal_of_paracompact_t2 [t2_space X] [paracompact_space X] : normal_space X :=
begin
/- First we show how to go from points to a set on one side. -/
have : β (s t : set X), is_closed s β is_closed t β
(β x β s, β u v, is_open u β§ is_open v β§ x β u β§ t β v β§ disjoint u v) β
β u v, is_open u β§ is_open v β§ s β u β§ t β v β§ disjoint u v,
{ /- For each `x β s` we choose open disjoint `u x β x` and `v x β t`. The sets `u x` form an
open covering of `s`. We choose a locally finite refinement `u' : s β set X`, then `β i, u' i`
and `(closure (β i, u' i))αΆ` are disjoint open neighborhoods of `s` and `t`. -/
intros s t hs ht H, choose u v hu hv hxu htv huv using set_coe.forall'.1 H,
rcases precise_refinement_set hs u hu (Ξ» x hx, mem_Union.2 β¨β¨x, hxβ©, hxu _β©)
with β¨u', hu'o, hcov', hu'fin, hsubβ©,
refine β¨β i, u' i, (closure (β i, u' i))αΆ, is_open_Union hu'o, is_closed_closure, hcov', _,
disjoint_compl_right.mono le_rfl (compl_le_compl subset_closure)β©,
rw [hu'fin.closure_Union, compl_Union, subset_Inter_iff],
refine Ξ» i x hxt hxu, absurd (htv i hxt) (closure_minimal _ (is_closed_compl_iff.2 $ hv _) hxu),
exact Ξ» y hyu hyv, huv i β¨hsub _ hyu, hyvβ© },
/- Now we apply the lemma twice: first to `s` and `t`, then to `t` and each point of `s`. -/
refine β¨Ξ» s t hs ht hst, this s t hs ht (Ξ» x hx, _)β©,
rcases this t {x} ht is_closed_singleton (Ξ» y hyt, _) with β¨v, u, hv, hu, htv, hxu, huvβ©,
{ exact β¨u, v, hu, hv, singleton_subset_iff.1 hxu, htv, huv.symmβ© },
{ have : x β y, by { rintro rfl, exact hst β¨hx, hytβ© },
rcases t2_separation this with β¨v, u, hv, hu, hxv, hyu, hdβ©,
exact β¨u, v, hu, hv, hyu, singleton_subset_iff.2 hxv, disjoint.symm hd.leβ© }
end
|
0c5ffb0204effb34b24b3745942d7460a695c28c | 07c76fbd96ea1786cc6392fa834be62643cea420 | /hott/types/W.hlean | 46baa61bcb7277b1f785976795734632809c968b | [
"Apache-2.0"
] | permissive | fpvandoorn/lean2 | 5a430a153b570bf70dc8526d06f18fc000a60ad9 | 0889cf65b7b3cebfb8831b8731d89c2453dd1e9f | refs/heads/master | 1,592,036,508,364 | 1,545,093,958,000 | 1,545,093,958,000 | 75,436,854 | 0 | 0 | null | 1,480,718,780,000 | 1,480,718,780,000 | null | UTF-8 | Lean | false | false | 4,773 | hlean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Theorems about W-types (well-founded trees)
-/
import .sigma .pi
open eq equiv is_equiv sigma sigma.ops
inductive Wtype.{l k} {A : Type.{l}} (B : A β Type.{k}) : Type.{max l k} :=
sup : Ξ (a : A), (B a β Wtype.{l k} B) β Wtype.{l k} B
namespace Wtype
notation `W` binders `, ` r:(scoped B, Wtype B) := r
universe variables u v
variables {A A' : Type.{u}} {B B' : A β Type.{v}} {C : Ξ (a : A), B a β Type}
{a a' : A} {f : B a β W a, B a} {f' : B a' β W a, B a} {w w' : W(a : A), B a}
protected definition pr1 [unfold 3] (w : W(a : A), B a) : A :=
by cases w with a f; exact a
protected definition pr2 [unfold 3] (w : W(a : A), B a) : B (Wtype.pr1 w) β W(a : A), B a :=
by cases w with a f; exact f
namespace ops
postfix `.1`:(max+1) := Wtype.pr1
postfix `.2`:(max+1) := Wtype.pr2
notation `β¨` a `, ` f `β©`:0 := Wtype.sup a f --input β¨ β© as \< \>
end ops
open ops
protected definition eta [unfold 3] (w : W a, B a) : β¨w.1 , w.2β© = w :=
by cases w; exact idp
definition sup_eq_sup [unfold 8] (p : a = a') (q : f =[p] f') : β¨a, fβ© = β¨a', f'β© :=
by cases q; exact idp
definition Wtype_eq [unfold 3 4] (p : w.1 = w'.1) (q : w.2 =[p] w'.2) : w = w' :=
by cases w; cases w';exact (sup_eq_sup p q)
definition Wtype_eq_pr1 [unfold 5] (p : w = w') : w.1 = w'.1 :=
by cases p;exact idp
definition Wtype_eq_pr2 [unfold 5] (p : w = w') : w.2 =[Wtype_eq_pr1 p] w'.2 :=
by cases p;exact idpo
namespace ops
postfix `..1`:(max+1) := Wtype_eq_pr1
postfix `..2`:(max+1) := Wtype_eq_pr2
end ops open ops open sigma
definition sup_path_W (p : w.1 = w'.1) (q : w.2 =[p] w'.2)
: β¨(Wtype_eq p q)..1, (Wtype_eq p q)..2β© = β¨p, qβ© :=
by cases w; cases w'; cases q; exact idp
definition pr1_path_W (p : w.1 = w'.1) (q : w.2 =[p] w'.2) : (Wtype_eq p q)..1 = p :=
!sup_path_W..1
definition pr2_path_W (p : w.1 = w'.1) (q : w.2 =[p] w'.2)
: (Wtype_eq p q)..2 =[pr1_path_W p q] q :=
!sup_path_W..2
definition eta_path_W (p : w = w') : Wtype_eq (p..1) (p..2) = p :=
by cases p; cases w; exact idp
definition transport_pr1_path_W {B' : A β Type} (p : w.1 = w'.1) (q : w.2 =[p] w'.2)
: transport (Ξ»x, B' x.1) (Wtype_eq p q) = transport B' p :=
by cases w; cases w'; cases q; exact idp
definition path_W_uncurried (pq : Ξ£(p : w.1 = w'.1), w.2 =[p] w'.2) : w = w' :=
by cases pq with p q; exact (Wtype_eq p q)
definition sup_path_W_uncurried (pq : Ξ£(p : w.1 = w'.1), w.2 =[p] w'.2)
: β¨(path_W_uncurried pq)..1, (path_W_uncurried pq)..2β© = pq :=
by cases pq with p q; exact (sup_path_W p q)
definition pr1_path_W_uncurried (pq : Ξ£(p : w.1 = w'.1), w.2 =[p] w'.2)
: (path_W_uncurried pq)..1 = pq.1 :=
!sup_path_W_uncurried..1
definition pr2_path_W_uncurried (pq : Ξ£(p : w.1 = w'.1), w.2 =[p] w'.2)
: (path_W_uncurried pq)..2 =[pr1_path_W_uncurried pq] pq.2 :=
!sup_path_W_uncurried..2
definition eta_path_W_uncurried (p : w = w') : path_W_uncurried β¨p..1, p..2β© = p :=
!eta_path_W
definition transport_pr1_path_W_uncurried {B' : A β Type} (pq : Ξ£(p : w.1 = w'.1), w.2 =[p] w'.2)
: transport (Ξ»x, B' x.1) (@path_W_uncurried A B w w' pq) = transport B' pq.1 :=
by cases pq with p q; exact (transport_pr1_path_W p q)
definition isequiv_path_W /-[instance]-/ (w w' : W a, B a)
: is_equiv (path_W_uncurried : (Ξ£(p : w.1 = w'.1), w.2 =[p] w'.2) β w = w') :=
adjointify path_W_uncurried
(Ξ»p, β¨p..1, p..2β©)
eta_path_W_uncurried
sup_path_W_uncurried
definition equiv_path_W (w w' : W a, B a) : (Ξ£(p : w.1 = w'.1), w.2 =[p] w'.2) β (w = w') :=
equiv.mk path_W_uncurried !isequiv_path_W
definition double_induction_on {P : (W a, B a) β (W a, B a) β Type} (w w' : W a, B a)
(H : β (a a' : A) (f : B a β W a, B a) (f' : B a' β W a, B a),
(β (b : B a) (b' : B a'), P (f b) (f' b')) β P (sup a f) (sup a' f')) : P w w' :=
begin
revert w',
induction w with a f IH,
intro w',
cases w' with a' f',
apply H, intro b b',
apply IH
end
/- truncatedness -/
open is_trunc pi
definition is_trunc_W [instance] (n : trunc_index)
[HA : is_trunc (n.+1) A] : is_trunc (n.+1) (W a, B a) :=
begin
fapply is_trunc_succ_intro, intro w w',
eapply (double_induction_on w w'), intro a a' f f' IH,
fapply is_trunc_equiv_closed,
{ apply equiv_path_W},
{ apply is_trunc_sigma,
intro p, cases p,
apply is_trunc_equiv_closed_rev n !pathover_idp,
apply is_trunc_pi_eq, intro b, apply IH }
end
end Wtype
|
b5a8cdbfc5273cc0d6aa62ae7876b678e3d8c19d | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/smt_tests2.lean | 41bfe0763885966810275839e2197172977f95ee | [
"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,312 | lean | lemma ex1 (a b c : nat) (f : nat β nat β nat) : f 0 1 = 1 β (Ξ» x y : nat, x) = f β false :=
begin [smt]
intros
end
lemma ex2 (a b c : nat) (f : nat β nat β nat) : f 0 1 = 1 β f = (Ξ» x y, x) β false :=
begin [smt]
intros
end
lemma ex3 (a b c : nat) (f : nat β nat) : f = (Ξ» x, x) β f 0 = 1 β false :=
begin [smt]
intros
end
lemma ex4 (a b c : nat) (f : nat β nat) : (Ξ» x : nat, x) = f β f 0 = 1 β false :=
begin [smt]
intros
end
open list
universe variables u
lemma ex5 {Ξ± : Type u} (l : list Ξ±) (a : Ξ±) (f : Ξ± β Ξ± Γ Ξ±) :
f = (Ξ» x, (x, x)) β map f (a::l) = (a, a) :: map f l :=
begin [smt]
intros,
add_eqn_lemmas map,
ematch
end
lemma ex6 {Ξ± : Type u} (l : list Ξ±) (a : Ξ±) (f : Ξ± β Ξ± Γ Ξ±) :
map f (a::l) β (a, a) :: map f l β f = (Ξ» x, (x, x)) β false :=
begin [smt]
intros,
add_eqn_lemmas map,
ematch
end
lemma ex7 (a b c : nat) (f : nat β nat β nat) : f 0 1 = 1 β (Ξ» (x : nat) (y : char), x) == f β f = (Ξ» (x : nat) (y : nat), 2) β false :=
begin [smt]
intros
end
/-
The following kind of propagation is not supported yet.
We can add it if it is needed in practice.
example (a b c : nat) (f : nat β nat β nat) : (Ξ» x : nat, x) = f b β f b 0 = 1 β false :=
begin [smt]
close
end
-/
|
f2d9dc87d2e04b947d5474b0a2ed80b85e9466bf | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/fintype/list.lean | 1accc08def6a384c482e3a1206adba8d9dcd9c5b | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 1,903 | lean | /-
Copyright (c) 2021 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import data.fintype.basic
import data.finset.powerset
/-!
# Fintype instance for nodup lists
The subtype of `{l : list Ξ± // l.nodup}` over a `[fintype Ξ±]`
admits a `fintype` instance.
## Implementation details
To construct the `fintype` instance, a function lifting a `multiset Ξ±`
to the `finset (list Ξ±)` that can construct it is provided.
This function is applied to the `finset.powerset` of `finset.univ`.
In general, a `decidable_eq` instance is not necessary to define this function,
but a proof of `(list.permutations l).nodup` is required to avoid it,
which is a TODO.
-/
variables {Ξ± : Type*} [decidable_eq Ξ±]
open list
namespace multiset
/--
The `finset` of `l : list Ξ±` that, given `m : multiset Ξ±`, have the property `β¦lβ§ = m`.
-/
def lists : multiset Ξ± β finset (list Ξ±) :=
Ξ» s, quotient.lift_on s (Ξ» l, l.permutations.to_finset)
(Ξ» l l' (h : l ~ l'),
begin
ext sl,
simp only [mem_permutations, list.mem_to_finset],
exact β¨Ξ» hs, hs.trans h, Ξ» hs, hs.trans h.symmβ©
end)
@[simp] lemma lists_coe (l : list Ξ±) :
lists (l : multiset Ξ±) = l.permutations.to_finset := rfl
@[simp] lemma mem_lists_iff (s : multiset Ξ±) (l : list Ξ±) :
l β lists s β s = β¦lβ§ :=
begin
induction s using quotient.induction_on,
simpa using perm_comm
end
end multiset
instance fintype_nodup_list [fintype Ξ±] : fintype {l : list Ξ± // l.nodup} :=
fintype.subtype ((finset.univ : finset Ξ±).powerset.bUnion (Ξ» s, s.val.lists)) (Ξ» l,
begin
suffices : (β (a : finset Ξ±), a.val = βl) β l.nodup,
{ simpa },
split,
{ rintro β¨s, hsβ©,
simpa [βmultiset.coe_nodup, βhs] using s.nodup },
{ intro hl,
refine β¨β¨βl, hlβ©, _β©,
simp }
end)
|
8d4338d913cc6012fa133a6430e57b08649852db | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Data/Name.lean | f6d7d114e7077116faac36d2dd02b4a6935efd69 | [
"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 | 5,653 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.LeanInit
import Init.Data.UInt
import Init.Data.ToString
import Init.Data.Hashable
import Init.Data.HashSet
import Init.Data.RBMap
import Init.Data.RBTree
namespace Lean
instance stringToName : HasCoe String Name :=
β¨mkNameSimpleβ©
namespace Name
@[export lean_name_hash] def hashEx : Name β USize :=
Name.hash
def getPrefix : Name β Name
| anonymous => anonymous
| str p s _ => p
| num p s _ => p
def getRoot : Name β Name
| anonymous => anonymous
| n@(str anonymous _ _) => n
| n@(num anonymous _ _) => n
| str n _ _ => getRoot n
| num n _ _ => getRoot n
def getNumParts : Name β Nat
| anonymous => 0
| str p _ _ => getNumParts p + 1
| num p _ _ => getNumParts p + 1
def updatePrefix : Name β Name β Name
| anonymous, newP => anonymous
| str p s _, newP => mkNameStr newP s
| num p s _, newP => mkNameNum newP s
def components' : Name β List Name
| anonymous => []
| str n s _ => mkNameStr anonymous s :: components' n
| num n v _ => mkNameNum anonymous v :: components' n
def components (n : Name) : List Name :=
n.components'.reverse
def eqStr : Name β String β Bool
| str anonymous s _, s' => s == s'
| _, _ => false
def replacePrefix : Name β Name β Name β Name
| anonymous, anonymous, newP => newP
| anonymous, _, _ => anonymous
| n@(str p s _), queryP, newP => if n == queryP then newP else mkNameStr (p.replacePrefix queryP newP) s
| n@(num p s _), queryP, newP => if n == queryP then newP else mkNameNum (p.replacePrefix queryP newP) s
def isPrefixOf : Name β Name β Bool
| p, anonymous => p == anonymous
| p, n@(num p' _ _) => p == n || isPrefixOf p p'
| p, n@(str p' _ _) => p == n || isPrefixOf p p'
def isSuffixOf : Name β Name β Bool
| anonymous, _ => true
| str pβ sβ _, str pβ sβ _ => sβ == sβ && isSuffixOf pβ pβ
| num pβ nβ _, num pβ nβ _ => nβ == nβ && isSuffixOf pβ pβ
| _, _ => false
def lt : Name β Name β Bool
| anonymous, anonymous => false
| anonymous, _ => true
| num pβ iβ _, num pβ iβ _ => lt pβ pβ || (pβ == pβ && iβ < iβ)
| num _ _ _, str _ _ _ => true
| str pβ nβ _, str pβ nβ _ => lt pβ pβ || (pβ == pβ && nβ < nβ)
| _, _ => false
def quickLtAux : Name β Name β Bool
| anonymous, anonymous => false
| anonymous, _ => true
| num n v _, num n' v' _ => v < v' || (v = v' && n.quickLtAux n')
| num _ _ _, str _ _ _ => true
| str n s _, str n' s' _ => s < s' || (s = s' && n.quickLtAux n')
| _, _ => false
def quickLt (nβ nβ : Name) : Bool :=
if nβ.hash < nβ.hash then true
else if nβ.hash > nβ.hash then false
else quickLtAux nβ nβ
/- Alternative HasLt instance. -/
@[inline] protected def hasLtQuick : HasLess Name :=
β¨fun a b => Name.quickLt a b = trueβ©
@[inline] instance : DecidableRel (@HasLess.Less Name Name.hasLtQuick) :=
inferInstanceAs (DecidableRel (fun a b => Name.quickLt a b = true))
def appendAfter : Name β String β Name
| str p s _, suffix => mkNameStr p (s ++ suffix)
| n, suffix => mkNameStr n suffix
def appendIndexAfter : Name β Nat β Name
| str p s _, idx => mkNameStr p (s ++ "_" ++ toString idx)
| n, idx => mkNameStr n ("_" ++ toString idx)
def appendBefore : Name β String β Name
| anonymous, pre => mkNameStr anonymous pre
| str p s _, pre => mkNameStr p (pre ++ s)
| num p n _, pre => mkNameNum (mkNameStr p pre) n
/- The frontend does not allow user declarations to start with `_` in any of its parts.
We use name parts starting with `_` internally to create auxiliary names (e.g., `_private`). -/
def isInternal : Name β Bool
| str p s _ => s.get 0 == '_' || isInternal p
| num p _ _ => isInternal p
| _ => false
def isAtomic : Name β Bool
| anonymous => true
| str anonymous _ _ => true
| num anonymous _ _ => true
| _ => false
def isAnonymous : Name β Bool
| anonymous => true
| _ => false
end Name
def NameMap (Ξ± : Type) := RBMap Name Ξ± Name.quickLt
@[inline] def mkNameMap (Ξ± : Type) : NameMap Ξ± := mkRBMap Name Ξ± Name.quickLt
namespace NameMap
variable {Ξ± : Type}
instance (Ξ± : Type) : HasEmptyc (NameMap Ξ±) := β¨mkNameMap Ξ±β©
instance (Ξ± : Type) : Inhabited (NameMap Ξ±) := β¨{}β©
def insert (m : NameMap Ξ±) (n : Name) (a : Ξ±) := RBMap.insert m n a
def contains (m : NameMap Ξ±) (n : Name) : Bool := RBMap.contains m n
@[inline] def find? (m : NameMap Ξ±) (n : Name) : Option Ξ± := RBMap.find? m n
end NameMap
def NameSet := RBTree Name Name.quickLt
namespace NameSet
def empty : NameSet := mkRBTree Name Name.quickLt
instance : HasEmptyc NameSet := β¨emptyβ©
instance : Inhabited NameSet := β¨{}β©
def insert (s : NameSet) (n : Name) := RBTree.insert s n
def contains (s : NameSet) (n : Name) : Bool := RBMap.contains s n
end NameSet
def NameHashSet := HashSet Name
namespace NameHashSet
@[inline] def empty : NameHashSet := HashSet.empty
instance : HasEmptyc NameHashSet := β¨emptyβ©
instance : Inhabited NameHashSet := β¨{}β©
def insert (s : NameHashSet) (n : Name) := HashSet.insert s n
def contains (s : NameHashSet) (n : Name) : Bool := HashSet.contains s n
end NameHashSet
end Lean
open Lean
def String.toName (s : String) : Name :=
let ps := s.splitOn ".";
ps.foldl (fun n p => mkNameStr n p.trim) Name.anonymous
|
7a25eba000260c7b409e2f0d2b7923fe8c22ec12 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /library/hott/types/prod.lean | 65d8f62041b0eaaae6f1d0a2d3b3e72d1206a184 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 849 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Ported from Coq HoTT
Theorems about products
-/
import ..trunc data.prod
open path Equiv IsEquiv truncation prod
variables {A A' B B' C D : Type}
{a a' a'' : A} {b bβ bβ b' b'' : B} {u v w : A Γ B}
namespace prod
definition eta_prod (u : A Γ B) : (prβ u , prβ u) β u :=
destruct u (Ξ»u1 u2, idp)
/- Symmetry -/
definition isequiv_prod_symm [instance] (A B : Type) : IsEquiv (@flip A B) :=
adjointify flip
flip
(Ξ»u, destruct u (Ξ»b a, idp))
(Ξ»u, destruct u (Ξ»a b, idp))
definition equiv_prod_symm (A B : Type) : A Γ B β B Γ A :=
Equiv.mk flip _
check typeof idp : flip (flip (a,b)) β (a,b)
end prod
|
4db9b9d1dff25becd15a7c39adc72de586f74c65 | f3849be5d845a1cb97680f0bbbe03b85518312f0 | /tests/lean/char_lits.lean | 90d322b68417bd26fdb8d82963ee71b5e499b6c2 | [
"Apache-2.0"
] | permissive | bjoeris/lean | 0ed95125d762b17bfcb54dad1f9721f953f92eeb | 4e496b78d5e73545fa4f9a807155113d8e6b0561 | refs/heads/master | 1,611,251,218,281 | 1,495,337,658,000 | 1,495,337,658,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 209 | lean | import system.io
open io
#check 'a'
#eval 'a'
#eval '\n'
#eval '\\'
variable [io.interface]
#eval put_str (list.cons '\\' "aaa")
#eval put_str ['\n']
#eval put_str ['\n']
#eval put_str (list.cons '\'' "aaa")
|
908a75bea56b697838d57beab58066b6c877dd5c | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/algebra/subalgebra.lean | fc20aa2936735515b3e60799a21808610e1d319e | [
"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 | 43,654 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import algebra.algebra.operations
import data.set.Union_lift
import ring_theory.subring.pointwise
/-!
# Subalgebras over Commutative Semiring
In this file we define `subalgebra`s and the usual operations on them (`map`, `comap'`).
More lemmas about `adjoin` can be found in `ring_theory.adjoin`.
-/
universes u u' v w w'
open_locale tensor_product big_operators
set_option old_structure_cmd true
/-- A subalgebra is a sub(semi)ring that includes the range of `algebra_map`. -/
structure subalgebra (R : Type u) (A : Type v)
[comm_semiring R] [semiring A] [algebra R A] extends subsemiring A : Type v :=
(algebra_map_mem' : β r, algebra_map R A r β carrier)
(zero_mem' := (algebra_map R A).map_zero βΈ algebra_map_mem' 0)
(one_mem' := (algebra_map R A).map_one βΈ algebra_map_mem' 1)
/-- Reinterpret a `subalgebra` as a `subsemiring`. -/
add_decl_doc subalgebra.to_subsemiring
namespace subalgebra
variables {R' : Type u'} {R : Type u} {A : Type v} {B : Type w} {C : Type w'}
variables [comm_semiring R]
variables [semiring A] [algebra R A] [semiring B] [algebra R B] [semiring C] [algebra R C]
include R
instance : set_like (subalgebra R A) A :=
β¨subalgebra.carrier, Ξ» p q h, by cases p; cases q; congr'β©
@[simp]
lemma mem_carrier {s : subalgebra R A} {x : A} : x β s.carrier β x β s := iff.rfl
@[ext] theorem ext {S T : subalgebra R A} (h : β x : A, x β S β x β T) : S = T := set_like.ext h
@[simp] lemma mem_to_subsemiring {S : subalgebra R A} {x} : x β S.to_subsemiring β x β S := iff.rfl
@[simp] lemma coe_to_subsemiring (S : subalgebra R A) : (βS.to_subsemiring : set A) = S := rfl
theorem to_subsemiring_injective :
function.injective (to_subsemiring : subalgebra R A β subsemiring A) :=
Ξ» S T h, ext $ Ξ» x, by rw [β mem_to_subsemiring, β mem_to_subsemiring, h]
theorem to_subsemiring_inj {S U : subalgebra R A} : S.to_subsemiring = U.to_subsemiring β S = U :=
to_subsemiring_injective.eq_iff
/-- Copy of a subalgebra with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (S : subalgebra R A) (s : set A) (hs : s = βS) : subalgebra R A :=
{ carrier := s,
add_mem' := hs.symm βΈ S.add_mem',
mul_mem' := hs.symm βΈ S.mul_mem',
algebra_map_mem' := hs.symm βΈ S.algebra_map_mem' }
@[simp] lemma coe_copy (S : subalgebra R A) (s : set A) (hs : s = βS) :
(S.copy s hs : set A) = s := rfl
lemma copy_eq (S : subalgebra R A) (s : set A) (hs : s = βS) : S.copy s hs = S :=
set_like.coe_injective hs
variables (S : subalgebra R A)
theorem algebra_map_mem (r : R) : algebra_map R A r β S :=
S.algebra_map_mem' r
theorem srange_le : (algebra_map R A).srange β€ S.to_subsemiring :=
Ξ» x β¨r, hrβ©, hr βΈ S.algebra_map_mem r
theorem range_subset : set.range (algebra_map R A) β S :=
Ξ» x β¨r, hrβ©, hr βΈ S.algebra_map_mem r
theorem range_le : set.range (algebra_map R A) β€ S :=
S.range_subset
theorem one_mem : (1 : A) β S :=
S.to_subsemiring.one_mem
theorem mul_mem {x y : A} (hx : x β S) (hy : y β S) : x * y β S :=
S.to_subsemiring.mul_mem hx hy
theorem smul_mem {x : A} (hx : x β S) (r : R) : r β’ x β S :=
(algebra.smul_def r x).symm βΈ S.mul_mem (S.algebra_map_mem r) hx
theorem pow_mem {x : A} (hx : x β S) (n : β) : x ^ n β S :=
S.to_subsemiring.pow_mem hx n
theorem zero_mem : (0 : A) β S :=
S.to_subsemiring.zero_mem
theorem add_mem {x y : A} (hx : x β S) (hy : y β S) : x + y β S :=
S.to_subsemiring.add_mem hx hy
theorem neg_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x : A} (hx : x β S) : -x β S :=
neg_one_smul R x βΈ S.smul_mem hx _
theorem sub_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x y : A} (hx : x β S) (hy : y β S) : x - y β S :=
by simpa only [sub_eq_add_neg] using S.add_mem hx (S.neg_mem hy)
theorem nsmul_mem {x : A} (hx : x β S) (n : β) : n β’ x β S :=
S.to_subsemiring.nsmul_mem hx n
theorem zsmul_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x : A} (hx : x β S) : β (n : β€), n β’ x β S
| (n : β) := by { rw [coe_nat_zsmul], exact S.nsmul_mem hx n }
| -[1+ n] := by { rw [zsmul_neg_succ_of_nat], exact S.neg_mem (S.nsmul_mem hx _) }
theorem coe_nat_mem (n : β) : (n : A) β S :=
S.to_subsemiring.coe_nat_mem n
theorem coe_int_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) (n : β€) : (n : A) β S :=
int.cases_on n (Ξ» i, S.coe_nat_mem i) (Ξ» i, S.neg_mem $ S.coe_nat_mem $ i + 1)
theorem list_prod_mem {L : list A} (h : β x β L, x β S) : L.prod β S :=
S.to_subsemiring.list_prod_mem h
theorem list_sum_mem {L : list A} (h : β x β L, x β S) : L.sum β S :=
S.to_subsemiring.list_sum_mem h
theorem multiset_prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) {m : multiset A} (h : β x β m, x β S) : m.prod β S :=
S.to_subsemiring.multiset_prod_mem m h
theorem multiset_sum_mem {m : multiset A} (h : β x β m, x β S) : m.sum β S :=
S.to_subsemiring.multiset_sum_mem m h
theorem prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) {ΞΉ : Type w} {t : finset ΞΉ} {f : ΞΉ β A}
(h : β x β t, f x β S) : β x in t, f x β S :=
S.to_subsemiring.prod_mem h
theorem sum_mem {ΞΉ : Type w} {t : finset ΞΉ} {f : ΞΉ β A}
(h : β x β t, f x β S) : β x in t, f x β S :=
S.to_subsemiring.sum_mem h
/-- The projection from a subalgebra of `A` to an additive submonoid of `A`. -/
def to_add_submonoid {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
(S : subalgebra R A) : add_submonoid A :=
S.to_subsemiring.to_add_submonoid
/-- The projection from a subalgebra of `A` to a submonoid of `A`. -/
def to_submonoid {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
(S : subalgebra R A) : submonoid A :=
S.to_subsemiring.to_submonoid
/-- A subalgebra over a ring is also a `subring`. -/
def to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) :
subring A :=
{ neg_mem' := Ξ» _, S.neg_mem,
.. S.to_subsemiring }
@[simp] lemma mem_to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} {x} : x β S.to_subring β x β S := iff.rfl
@[simp] lemma coe_to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
(S : subalgebra R A) : (βS.to_subring : set A) = S := rfl
theorem to_subring_injective {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] :
function.injective (to_subring : subalgebra R A β subring A) :=
Ξ» S T h, ext $ Ξ» x, by rw [β mem_to_subring, β mem_to_subring, h]
theorem to_subring_inj {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S U : subalgebra R A} : S.to_subring = U.to_subring β S = U :=
to_subring_injective.eq_iff
instance : inhabited S := β¨(0 : S.to_subsemiring)β©
section
/-! `subalgebra`s inherit structure from their `subsemiring` / `semiring` coercions. -/
instance to_semiring {R A}
[comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) :
semiring S := S.to_subsemiring.to_semiring
instance to_comm_semiring {R A}
[comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) :
comm_semiring S := S.to_subsemiring.to_comm_semiring
instance to_ring {R A}
[comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) :
ring S := S.to_subring.to_ring
instance to_comm_ring {R A}
[comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) :
comm_ring S := S.to_subring.to_comm_ring
instance to_ordered_semiring {R A}
[comm_semiring R] [ordered_semiring A] [algebra R A] (S : subalgebra R A) :
ordered_semiring S := S.to_subsemiring.to_ordered_semiring
instance to_ordered_comm_semiring {R A}
[comm_semiring R] [ordered_comm_semiring A] [algebra R A] (S : subalgebra R A) :
ordered_comm_semiring S := S.to_subsemiring.to_ordered_comm_semiring
instance to_ordered_ring {R A}
[comm_ring R] [ordered_ring A] [algebra R A] (S : subalgebra R A) :
ordered_ring S := S.to_subring.to_ordered_ring
instance to_ordered_comm_ring {R A}
[comm_ring R] [ordered_comm_ring A] [algebra R A] (S : subalgebra R A) :
ordered_comm_ring S := S.to_subring.to_ordered_comm_ring
instance to_linear_ordered_semiring {R A}
[comm_semiring R] [linear_ordered_semiring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_semiring S := S.to_subsemiring.to_linear_ordered_semiring
/-! There is no `linear_ordered_comm_semiring`. -/
instance to_linear_ordered_ring {R A}
[comm_ring R] [linear_ordered_ring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_ring S := S.to_subring.to_linear_ordered_ring
instance to_linear_ordered_comm_ring {R A}
[comm_ring R] [linear_ordered_comm_ring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_comm_ring S := S.to_subring.to_linear_ordered_comm_ring
end
/-- Convert a `subalgebra` to `submodule` -/
def to_submodule : submodule R A :=
{ carrier := S,
zero_mem' := (0:S).2,
add_mem' := Ξ» x y hx hy, (β¨x, hxβ© + β¨y, hyβ© : S).2,
smul_mem' := Ξ» c x hx, (algebra.smul_def c x).symm βΈ
(β¨algebra_map R A c, S.range_le β¨c, rflβ©β© * β¨x, hxβ©:S).2 }
@[simp] lemma mem_to_submodule {x} : x β S.to_submodule β x β S := iff.rfl
@[simp] lemma coe_to_submodule (S : subalgebra R A) : (βS.to_submodule : set A) = S := rfl
theorem to_submodule_injective :
function.injective (to_submodule : subalgebra R A β submodule R A) :=
Ξ» S T h, ext $ Ξ» x, by rw [β mem_to_submodule, β mem_to_submodule, h]
theorem to_submodule_inj {S U : subalgebra R A} : S.to_submodule = U.to_submodule β S = U :=
to_submodule_injective.eq_iff
section
/-! `subalgebra`s inherit structure from their `submodule` coercions. -/
instance module' [semiring R'] [has_scalar R' R] [module R' A] [is_scalar_tower R' R A] :
module R' S :=
S.to_submodule.module'
instance : module R S := S.module'
instance [semiring R'] [has_scalar R' R] [module R' A] [is_scalar_tower R' R A] :
is_scalar_tower R' R S :=
S.to_submodule.is_scalar_tower
instance algebra' [comm_semiring R'] [has_scalar R' R] [algebra R' A]
[is_scalar_tower R' R A] : algebra R' S :=
{ commutes' := Ξ» c x, subtype.eq $ algebra.commutes _ _,
smul_def' := Ξ» c x, subtype.eq $ algebra.smul_def _ _,
.. (algebra_map R' A).cod_srestrict S.to_subsemiring $ Ξ» x, begin
rw [algebra.algebra_map_eq_smul_one, βsmul_one_smul R x (1 : A),
βalgebra.algebra_map_eq_smul_one],
exact algebra_map_mem S _,
end }
instance : algebra R S := S.algebra'
end
instance nontrivial [nontrivial A] : nontrivial S :=
S.to_subsemiring.nontrivial
instance no_zero_smul_divisors_bot [no_zero_smul_divisors R A] : no_zero_smul_divisors R S :=
β¨Ξ» c x h,
have c = 0 β¨ (x : A) = 0,
from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h),
this.imp_right (@subtype.ext_iff _ _ x 0).mprβ©
@[simp, norm_cast] lemma coe_add (x y : S) : (β(x + y) : A) = βx + βy := rfl
@[simp, norm_cast] lemma coe_mul (x y : S) : (β(x * y) : A) = βx * βy := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : S) : A) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : S) : A) = 1 := rfl
@[simp, norm_cast] lemma coe_neg {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} (x : S) : (β(-x) : A) = -βx := rfl
@[simp, norm_cast] lemma coe_sub {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} (x y : S) : (β(x - y) : A) = βx - βy := rfl
@[simp, norm_cast] lemma coe_smul [semiring R'] [has_scalar R' R] [module R' A]
[is_scalar_tower R' R A] (r : R') (x : S) : (β(r β’ x) : A) = r β’ βx := rfl
@[simp, norm_cast] lemma coe_algebra_map [comm_semiring R'] [has_scalar R' R] [algebra R' A]
[is_scalar_tower R' R A] (r : R') :
β(algebra_map R' S r) = algebra_map R' A r := rfl
@[simp, norm_cast] lemma coe_pow (x : S) (n : β) : (β(x^n) : A) = (βx)^n :=
begin
induction n with n ih,
{ simp, },
{ simp [pow_succ, ih], },
end
@[simp, norm_cast] lemma coe_eq_zero {x : S} : (x : A) = 0 β x = 0 :=
(subtype.ext_iff.symm : (x : A) = (0 : S) β x = 0)
@[simp, norm_cast] lemma coe_eq_one {x : S} : (x : A) = 1 β x = 1 :=
(subtype.ext_iff.symm : (x : A) = (1 : S) β x = 1)
-- todo: standardize on the names these morphisms
-- compare with submodule.subtype
/-- Embedding of a subalgebra into the algebra. -/
def val : S ββ[R] A :=
by refine_struct { to_fun := (coe : S β A) }; intros; refl
@[simp] lemma coe_val : (S.val : S β A) = coe := rfl
lemma val_apply (x : S) : S.val x = (x : A) := rfl
@[simp] lemma to_subsemiring_subtype : S.to_subsemiring.subtype = (S.val : S β+* A) :=
rfl
@[simp] lemma to_subring_subtype {R A : Type*} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) : S.to_subring.subtype = (S.val : S β+* A) :=
rfl
/-- As submodules, subalgebras are idempotent. -/
@[simp] theorem mul_self : S.to_submodule * S.to_submodule = S.to_submodule :=
begin
apply le_antisymm,
{ rw submodule.mul_le,
intros y hy z hz,
exact mul_mem S hy hz },
{ intros x hx1,
rw β mul_one x,
exact submodule.mul_mem_mul hx1 (one_mem S) }
end
/-- Linear equivalence between `S : submodule R A` and `S`. Though these types are equal,
we define it as a `linear_equiv` to avoid type equalities. -/
def to_submodule_equiv (S : subalgebra R A) : S.to_submodule ββ[R] S :=
linear_equiv.of_eq _ _ rfl
/-- Transport a subalgebra via an algebra homomorphism. -/
def map (S : subalgebra R A) (f : A ββ[R] B) : subalgebra R B :=
{ algebra_map_mem' := Ξ» r, f.commutes r βΈ set.mem_image_of_mem _ (S.algebra_map_mem r),
.. S.to_subsemiring.map (f : A β+* B) }
lemma map_mono {Sβ Sβ : subalgebra R A} {f : A ββ[R] B} :
Sβ β€ Sβ β Sβ.map f β€ Sβ.map f :=
set.image_subset f
lemma map_injective {Sβ Sβ : subalgebra R A} (f : A ββ[R] B)
(hf : function.injective f) (ih : Sβ.map f = Sβ.map f) : Sβ = Sβ :=
ext $ set.ext_iff.1 $ set.image_injective.2 hf $ set.ext $ set_like.ext_iff.mp ih
@[simp] lemma map_id (S : subalgebra R A) : S.map (alg_hom.id R A) = S :=
set_like.coe_injective $ set.image_id _
lemma map_map (S : subalgebra R A) (g : B ββ[R] C) (f : A ββ[R] B) :
(S.map f).map g = S.map (g.comp f) :=
set_like.coe_injective $ set.image_image _ _ _
lemma mem_map {S : subalgebra R A} {f : A ββ[R] B} {y : B} :
y β map S f β β x β S, f x = y :=
subsemiring.mem_map
lemma map_to_submodule {S : subalgebra R A} {f : A ββ[R] B} :
(S.map f).to_submodule = S.to_submodule.map f.to_linear_map :=
set_like.coe_injective rfl
lemma map_to_subsemiring {S : subalgebra R A} {f : A ββ[R] B} :
(S.map f).to_subsemiring = S.to_subsemiring.map f.to_ring_hom :=
set_like.coe_injective rfl
@[simp] lemma coe_map (S : subalgebra R A) (f : A ββ[R] B) :
(S.map f : set B) = f '' S :=
rfl
/-- Preimage of a subalgebra under an algebra homomorphism. -/
def comap' (S : subalgebra R B) (f : A ββ[R] B) : subalgebra R A :=
{ algebra_map_mem' := Ξ» r, show f (algebra_map R A r) β S,
from (f.commutes r).symm βΈ S.algebra_map_mem r,
.. S.to_subsemiring.comap (f : A β+* B) }
theorem map_le {S : subalgebra R A} {f : A ββ[R] B} {U : subalgebra R B} :
map S f β€ U β S β€ comap' U f :=
set.image_subset_iff
lemma gc_map_comap (f : A ββ[R] B) : galois_connection (Ξ» S, map S f) (Ξ» S, comap' S f) :=
Ξ» S U, map_le
@[simp] lemma mem_comap (S : subalgebra R B) (f : A ββ[R] B) (x : A) :
x β S.comap' f β f x β S :=
iff.rfl
@[simp, norm_cast] lemma coe_comap (S : subalgebra R B) (f : A ββ[R] B) :
(S.comap' f : set A) = f β»ΒΉ' (S : set B) :=
rfl
instance no_zero_divisors {R A : Type*} [comm_ring R] [semiring A] [no_zero_divisors A]
[algebra R A] (S : subalgebra R A) : no_zero_divisors S :=
S.to_subsemiring.no_zero_divisors
instance is_domain {R A : Type*} [comm_ring R] [ring A] [is_domain A] [algebra R A]
(S : subalgebra R A) : is_domain S :=
subring.is_domain S.to_subring
end subalgebra
namespace alg_hom
variables {R' : Type u'} {R : Type u} {A : Type v} {B : Type w} {C : Type w'}
variables [comm_semiring R]
variables [semiring A] [algebra R A] [semiring B] [algebra R B] [semiring C] [algebra R C]
variables (Ο : A ββ[R] B)
/-- Range of an `alg_hom` as a subalgebra. -/
protected def range (Ο : A ββ[R] B) : subalgebra R B :=
{ algebra_map_mem' := Ξ» r, β¨algebra_map R A r, Ο.commutes rβ©,
.. Ο.to_ring_hom.srange }
@[simp] lemma mem_range (Ο : A ββ[R] B) {y : B} :
y β Ο.range β β x, Ο x = y := ring_hom.mem_srange
theorem mem_range_self (Ο : A ββ[R] B) (x : A) : Ο x β Ο.range := Ο.mem_range.2 β¨x, rflβ©
@[simp] lemma coe_range (Ο : A ββ[R] B) : (Ο.range : set B) = set.range Ο :=
by { ext, rw [set_like.mem_coe, mem_range], refl }
theorem range_comp (f : A ββ[R] B) (g : B ββ[R] C) : (g.comp f).range = f.range.map g :=
set_like.coe_injective (set.range_comp g f)
theorem range_comp_le_range (f : A ββ[R] B) (g : B ββ[R] C) : (g.comp f).range β€ g.range :=
set_like.coe_mono (set.range_comp_subset_range f g)
/-- Restrict the codomain of an algebra homomorphism. -/
def cod_restrict (f : A ββ[R] B) (S : subalgebra R B) (hf : β x, f x β S) : A ββ[R] S :=
{ commutes' := Ξ» r, subtype.eq $ f.commutes r,
.. ring_hom.cod_srestrict (f : A β+* B) S.to_subsemiring hf }
@[simp] lemma val_comp_cod_restrict (f : A ββ[R] B) (S : subalgebra R B) (hf : β x, f x β S) :
S.val.comp (f.cod_restrict S hf) = f :=
alg_hom.ext $ Ξ» _, rfl
@[simp] lemma coe_cod_restrict (f : A ββ[R] B) (S : subalgebra R B) (hf : β x, f x β S) (x : A) :
β(f.cod_restrict S hf x) = f x := rfl
theorem injective_cod_restrict (f : A ββ[R] B) (S : subalgebra R B) (hf : β x, f x β S) :
function.injective (f.cod_restrict S hf) β function.injective f :=
β¨Ξ» H x y hxy, H $ subtype.eq hxy, Ξ» H x y hxy, H (congr_arg subtype.val hxy : _)β©
/-- Restrict the codomain of a alg_hom `f` to `f.range`.
This is the bundled version of `set.range_factorization`. -/
@[reducible] def range_restrict (f : A ββ[R] B) : A ββ[R] f.range :=
f.cod_restrict f.range f.mem_range_self
/-- The equalizer of two R-algebra homomorphisms -/
def equalizer (Ο Ο : A ββ[R] B) : subalgebra R A :=
{ carrier := {a | Ο a = Ο a},
add_mem' := Ξ» x y (hx : Ο x = Ο x) (hy : Ο y = Ο y),
by rw [set.mem_set_of_eq, Ο.map_add, Ο.map_add, hx, hy],
mul_mem' := Ξ» x y (hx : Ο x = Ο x) (hy : Ο y = Ο y),
by rw [set.mem_set_of_eq, Ο.map_mul, Ο.map_mul, hx, hy],
algebra_map_mem' := Ξ» x,
by rw [set.mem_set_of_eq, alg_hom.commutes, alg_hom.commutes] }
@[simp] lemma mem_equalizer (Ο Ο : A ββ[R] B) (x : A) :
x β Ο.equalizer Ο β Ο x = Ο x := iff.rfl
/-- The range of a morphism of algebras is a fintype, if the domain is a fintype.
Note that this instance can cause a diamond with `subtype.fintype` if `B` is also a fintype. -/
instance fintype_range [fintype A] [decidable_eq B] (Ο : A ββ[R] B) : fintype Ο.range :=
set.fintype_range Ο
end alg_hom
namespace alg_equiv
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
/-- Restrict an algebra homomorphism with a left inverse to an algebra isomorphism to its range.
This is a computable alternative to `alg_equiv.of_injective`. -/
def of_left_inverse
{g : B β A} {f : A ββ[R] B} (h : function.left_inverse g f) :
A ββ[R] f.range :=
{ to_fun := f.range_restrict,
inv_fun := g β f.range.val,
left_inv := h,
right_inv := Ξ» x, subtype.ext $
let β¨x', hx'β© := f.mem_range.mp x.prop in
show f (g x) = x, by rw [βhx', h x'],
..f.range_restrict }
@[simp] lemma of_left_inverse_apply
{g : B β A} {f : A ββ[R] B} (h : function.left_inverse g f) (x : A) :
β(of_left_inverse h x) = f x := rfl
@[simp] lemma of_left_inverse_symm_apply
{g : B β A} {f : A ββ[R] B} (h : function.left_inverse g f) (x : f.range) :
(of_left_inverse h).symm x = g x := rfl
/-- Restrict an injective algebra homomorphism to an algebra isomorphism -/
noncomputable def of_injective (f : A ββ[R] B) (hf : function.injective f) :
A ββ[R] f.range :=
of_left_inverse (classical.some_spec hf.has_left_inverse)
@[simp] lemma of_injective_apply (f : A ββ[R] B) (hf : function.injective f) (x : A) :
β(of_injective f hf x) = f x := rfl
/-- Restrict an algebra homomorphism between fields to an algebra isomorphism -/
noncomputable def of_injective_field {E F : Type*} [division_ring E] [semiring F]
[nontrivial F] [algebra R E] [algebra R F] (f : E ββ[R] F) : E ββ[R] f.range :=
of_injective f f.to_ring_hom.injective
/-- Given an equivalence `e : A ββ[R] B` of `R`-algebras and a subalgebra `S` of `A`,
`subalgebra_map` is the induced equivalence between `S` and `S.map e` -/
@[simps] def subalgebra_map (e : A ββ[R] B) (S : subalgebra R A) :
S ββ[R] (S.map e.to_alg_hom) :=
{ commutes' := Ξ» r, by { ext, simp },
..e.to_ring_equiv.subsemiring_map S.to_subsemiring }
end alg_equiv
namespace algebra
variables (R : Type u) {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
/-- The minimal subalgebra that includes `s`. -/
def adjoin (s : set A) : subalgebra R A :=
{ algebra_map_mem' := Ξ» r, subsemiring.subset_closure $ or.inl β¨r, rflβ©,
.. subsemiring.closure (set.range (algebra_map R A) βͺ s) }
variables {R}
protected lemma gc : galois_connection (adjoin R : set A β subalgebra R A) coe :=
Ξ» s S, β¨Ξ» H, le_trans (le_trans (set.subset_union_right _ _) subsemiring.subset_closure) H,
Ξ» H, show subsemiring.closure (set.range (algebra_map R A) βͺ s) β€ S.to_subsemiring,
from subsemiring.closure_le.2 $ set.union_subset S.range_subset Hβ©
/-- Galois insertion between `adjoin` and `coe`. -/
protected def gi : galois_insertion (adjoin R : set A β subalgebra R A) coe :=
{ choice := Ξ» s hs, (adjoin R s).copy s $ le_antisymm (algebra.gc.le_u_l s) hs,
gc := algebra.gc,
le_l_u := Ξ» S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_rfl,
choice_eq := Ξ» _ _, subalgebra.copy_eq _ _ _ }
instance : complete_lattice (subalgebra R A) :=
galois_insertion.lift_complete_lattice algebra.gi
@[simp]
lemma coe_top : (β(β€ : subalgebra R A) : set A) = set.univ := rfl
@[simp] lemma mem_top {x : A} : x β (β€ : subalgebra R A) :=
set.mem_univ x
@[simp] lemma top_to_submodule : (β€ : subalgebra R A).to_submodule = β€ := rfl
@[simp] lemma top_to_subsemiring : (β€ : subalgebra R A).to_subsemiring = β€ := rfl
@[simp] lemma top_to_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A] :
(β€ : subalgebra R A).to_subring = β€ := rfl
@[simp] lemma to_submodule_eq_top {S : subalgebra R A} : S.to_submodule = β€ β S = β€ :=
subalgebra.to_submodule_injective.eq_iff' top_to_submodule
@[simp] lemma to_subsemiring_eq_top {S : subalgebra R A} : S.to_subsemiring = β€ β S = β€ :=
subalgebra.to_subsemiring_injective.eq_iff' top_to_subsemiring
@[simp] lemma to_subring_eq_top {R A : Type*} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} : S.to_subring = β€ β S = β€ :=
subalgebra.to_subring_injective.eq_iff' top_to_subring
lemma mem_sup_left {S T : subalgebra R A} : β {x : A}, x β S β x β S β T :=
show S β€ S β T, from le_sup_left
lemma mem_sup_right {S T : subalgebra R A} : β {x : A}, x β T β x β S β T :=
show T β€ S β T, from le_sup_right
lemma mul_mem_sup {S T : subalgebra R A} {x y : A} (hx : x β S) (hy : y β T) :
x * y β S β T :=
(S β T).mul_mem (mem_sup_left hx) (mem_sup_right hy)
lemma map_sup (f : A ββ[R] B) (S T : subalgebra R A) : (S β T).map f = S.map f β T.map f :=
(subalgebra.gc_map_comap f).l_sup
@[simp, norm_cast]
lemma coe_inf (S T : subalgebra R A) : (β(S β T) : set A) = S β© T := rfl
@[simp]
lemma mem_inf {S T : subalgebra R A} {x : A} : x β S β T β x β S β§ x β T := iff.rfl
@[simp] lemma inf_to_submodule (S T : subalgebra R A) :
(S β T).to_submodule = S.to_submodule β T.to_submodule := rfl
@[simp] lemma inf_to_subsemiring (S T : subalgebra R A) :
(S β T).to_subsemiring = S.to_subsemiring β T.to_subsemiring := rfl
@[simp, norm_cast]
lemma coe_Inf (S : set (subalgebra R A)) : (β(Inf S) : set A) = β s β S, βs := Inf_image
lemma mem_Inf {S : set (subalgebra R A)} {x : A} : x β Inf S β β p β S, x β p :=
by simp only [β set_like.mem_coe, coe_Inf, set.mem_Interβ]
@[simp] lemma Inf_to_submodule (S : set (subalgebra R A)) :
(Inf S).to_submodule = Inf (subalgebra.to_submodule '' S) :=
set_like.coe_injective $ by simp
@[simp] lemma Inf_to_subsemiring (S : set (subalgebra R A)) :
(Inf S).to_subsemiring = Inf (subalgebra.to_subsemiring '' S) :=
set_like.coe_injective $ by simp
@[simp, norm_cast]
lemma coe_infi {ΞΉ : Sort*} {S : ΞΉ β subalgebra R A} : (β(β¨
i, S i) : set A) = β i, S i :=
by simp [infi]
lemma mem_infi {ΞΉ : Sort*} {S : ΞΉ β subalgebra R A} {x : A} : (x β β¨
i, S i) β β i, x β S i :=
by simp only [infi, mem_Inf, set.forall_range_iff]
@[simp] lemma infi_to_submodule {ΞΉ : Sort*} (S : ΞΉ β subalgebra R A) :
(β¨
i, S i).to_submodule = β¨
i, (S i).to_submodule :=
set_like.coe_injective $ by simp
instance : inhabited (subalgebra R A) := β¨β₯β©
theorem mem_bot {x : A} : x β (β₯ : subalgebra R A) β x β set.range (algebra_map R A) :=
suffices (of_id R A).range = (β₯ : subalgebra R A),
by { rw [β this, βset_like.mem_coe, alg_hom.coe_range], refl },
le_bot_iff.mp (Ξ» x hx, subalgebra.range_le _ ((of_id R A).coe_range βΈ hx))
theorem to_submodule_bot : (β₯ : subalgebra R A).to_submodule = R β 1 :=
by { ext x, simp [mem_bot, -set.singleton_one, submodule.mem_span_singleton, algebra.smul_def] }
@[simp] theorem coe_bot : ((β₯ : subalgebra R A) : set A) = set.range (algebra_map R A) :=
by simp [set.ext_iff, algebra.mem_bot]
theorem eq_top_iff {S : subalgebra R A} :
S = β€ β β x : A, x β S :=
β¨Ξ» h x, by rw h; exact mem_top, Ξ» h, by ext x; exact β¨Ξ» _, mem_top, Ξ» _, h xβ©β©
@[simp] theorem range_id : (alg_hom.id R A).range = β€ :=
set_like.coe_injective set.range_id
@[simp] theorem map_top (f : A ββ[R] B) : subalgebra.map (β€ : subalgebra R A) f = f.range :=
set_like.coe_injective set.image_univ
@[simp] theorem map_bot (f : A ββ[R] B) : subalgebra.map (β₯ : subalgebra R A) f = β₯ :=
set_like.coe_injective $
by simp only [β set.range_comp, (β), algebra.coe_bot, subalgebra.coe_map, f.commutes]
@[simp] theorem comap_top (f : A ββ[R] B) : subalgebra.comap' (β€ : subalgebra R B) f = β€ :=
eq_top_iff.2 $ Ξ» x, mem_top
/-- `alg_hom` to `β€ : subalgebra R A`. -/
def to_top : A ββ[R] (β€ : subalgebra R A) :=
(alg_hom.id R A).cod_restrict β€ (Ξ» _, mem_top)
theorem surjective_algebra_map_iff :
function.surjective (algebra_map R A) β (β€ : subalgebra R A) = β₯ :=
β¨Ξ» h, eq_bot_iff.2 $ Ξ» y _, let β¨x, hxβ© := h y in hx βΈ subalgebra.algebra_map_mem _ _,
Ξ» h y, algebra.mem_bot.1 $ eq_bot_iff.1 h (algebra.mem_top : y β _)β©
theorem bijective_algebra_map_iff {R A : Type*} [field R] [semiring A] [nontrivial A]
[algebra R A] :
function.bijective (algebra_map R A) β (β€ : subalgebra R A) = β₯ :=
β¨Ξ» h, surjective_algebra_map_iff.1 h.2,
Ξ» h, β¨(algebra_map R A).injective, surjective_algebra_map_iff.2 hβ©β©
/-- The bottom subalgebra is isomorphic to the base ring. -/
noncomputable def bot_equiv_of_injective (h : function.injective (algebra_map R A)) :
(β₯ : subalgebra R A) ββ[R] R :=
alg_equiv.symm $ alg_equiv.of_bijective (algebra.of_id R _)
β¨Ξ» x y hxy, h (congr_arg subtype.val hxy : _),
Ξ» β¨y, hyβ©, let β¨x, hxβ© := algebra.mem_bot.1 hy in β¨x, subtype.eq hxβ©β©
/-- The bottom subalgebra is isomorphic to the field. -/
@[simps symm_apply]
noncomputable def bot_equiv (F R : Type*) [field F] [semiring R] [nontrivial R] [algebra F R] :
(β₯ : subalgebra F R) ββ[F] F :=
bot_equiv_of_injective (ring_hom.injective _)
/-- The top subalgebra is isomorphic to the field. -/
@[simps] def top_equiv : (β€ : subalgebra R A) ββ[R] A :=
alg_equiv.of_alg_hom (subalgebra.val β€) to_top rfl $ alg_hom.ext $ Ξ» x, subtype.ext rfl
end algebra
namespace subalgebra
open algebra
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
variables (S : subalgebra R A)
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_subsingleton [subsingleton A] : subsingleton (subalgebra R A) :=
β¨Ξ» B C, ext (Ξ» x, by { simp only [subsingleton.elim x 0, zero_mem] })β©
/--
For performance reasons this is not an instance. If you need this instance, add
```
local attribute [instance] alg_hom.subsingleton subalgebra.subsingleton_of_subsingleton
```
in the section that needs it.
-/
-- TODO[gh-6025]: make this an instance once safe to do so
lemma _root_.alg_hom.subsingleton [subsingleton (subalgebra R A)] : subsingleton (A ββ[R] B) :=
β¨Ξ» f g, alg_hom.ext $ Ξ» a,
have a β (β₯ : subalgebra R A) := subsingleton.elim (β€ : subalgebra R A) β₯ βΈ mem_top,
let β¨x, hxβ© := set.mem_range.mp (mem_bot.mp this) in
hx βΈ (f.commutes _).trans (g.commutes _).symmβ©
-- TODO[gh-6025]: make this an instance once safe to do so
lemma _root_.alg_equiv.subsingleton_left [subsingleton (subalgebra R A)] :
subsingleton (A ββ[R] B) :=
begin
haveI : subsingleton (A ββ[R] B) := alg_hom.subsingleton,
exact β¨Ξ» f g, alg_equiv.ext
(Ξ» x, alg_hom.ext_iff.mp (subsingleton.elim f.to_alg_hom g.to_alg_hom) x)β©,
end
-- TODO[gh-6025]: make this an instance once safe to do so
lemma _root_.alg_equiv.subsingleton_right [subsingleton (subalgebra R B)] :
subsingleton (A ββ[R] B) :=
begin
haveI : subsingleton (B ββ[R] A) := alg_equiv.subsingleton_left,
exact β¨Ξ» f g, eq.trans (alg_equiv.symm_symm _).symm
(by rw [subsingleton.elim f.symm g.symm, alg_equiv.symm_symm])β©
end
lemma range_val : S.val.range = S :=
ext $ set.ext_iff.1 $ S.val.coe_range.trans subtype.range_val
instance : unique (subalgebra R R) :=
{ uniq :=
begin
intro S,
refine le_antisymm (Ξ» r hr, _) bot_le,
simp only [set.mem_range, mem_bot, id.map_eq_self, exists_apply_eq_apply, default],
end
.. algebra.subalgebra.inhabited }
/-- The map `S β T` when `S` is a subalgebra contained in the subalgebra `T`.
This is the subalgebra version of `submodule.of_le`, or `subring.inclusion` -/
def inclusion {S T : subalgebra R A} (h : S β€ T) : S ββ[R] T :=
{ to_fun := set.inclusion h,
map_one' := rfl,
map_add' := Ξ» _ _, rfl,
map_mul' := Ξ» _ _, rfl,
map_zero' := rfl,
commutes' := Ξ» _, rfl }
lemma inclusion_injective {S T : subalgebra R A} (h : S β€ T) :
function.injective (inclusion h) :=
Ξ» _ _, subtype.ext β subtype.mk.inj
@[simp] lemma inclusion_self {S : subalgebra R A}:
inclusion (le_refl S) = alg_hom.id R S :=
alg_hom.ext $ Ξ» x, subtype.ext rfl
@[simp] lemma inclusion_right {S T : subalgebra R A} (h : S β€ T) (x : T)
(m : (x : A) β S) : inclusion h β¨x, mβ© = x := subtype.ext rfl
@[simp] lemma inclusion_inclusion {S T U : subalgebra R A} (hst : S β€ T) (htu : T β€ U)
(x : S) : inclusion htu (inclusion hst x) = inclusion (le_trans hst htu) x :=
subtype.ext rfl
@[simp] lemma coe_inclusion {S T : subalgebra R A} (h : S β€ T) (s : S) :
(inclusion h s : A) = s := rfl
/-- Two subalgebras that are equal are also equivalent as algebras.
This is the `subalgebra` version of `linear_equiv.of_eq` and `equiv.set.of_eq`. -/
@[simps apply]
def equiv_of_eq (S T : subalgebra R A) (h : S = T) : S ββ[R] T :=
{ to_fun := Ξ» x, β¨x, h βΈ x.2β©,
inv_fun := Ξ» x, β¨x, h.symm βΈ x.2β©,
map_mul' := Ξ» _ _, rfl,
commutes' := Ξ» _, rfl,
.. linear_equiv.of_eq _ _ (congr_arg to_submodule h) }
@[simp] lemma equiv_of_eq_symm (S T : subalgebra R A) (h : S = T) :
(equiv_of_eq S T h).symm = equiv_of_eq T S h.symm :=
rfl
@[simp] lemma equiv_of_eq_rfl (S : subalgebra R A) :
equiv_of_eq S S rfl = alg_equiv.refl :=
by { ext, refl }
@[simp] lemma equiv_of_eq_trans (S T U : subalgebra R A) (hST : S = T) (hTU : T = U) :
(equiv_of_eq S T hST).trans (equiv_of_eq T U hTU) = equiv_of_eq S U (trans hST hTU) :=
rfl
section prod
variables (Sβ : subalgebra R B)
/-- The product of two subalgebras is a subalgebra. -/
def prod : subalgebra R (A Γ B) :=
{ carrier := (S : set A) ΓΛ’ (Sβ : set B),
algebra_map_mem' := Ξ» r, β¨algebra_map_mem _ _, algebra_map_mem _ _β©,
.. S.to_subsemiring.prod Sβ.to_subsemiring }
@[simp] lemma coe_prod :
(prod S Sβ : set (A Γ B)) = (S : set A) ΓΛ’ (Sβ : set B):= rfl
lemma prod_to_submodule :
(S.prod Sβ).to_submodule = S.to_submodule.prod Sβ.to_submodule := rfl
@[simp] lemma mem_prod {S : subalgebra R A} {Sβ : subalgebra R B} {x : A Γ B} :
x β prod S Sβ β x.1 β S β§ x.2 β Sβ := set.mem_prod
@[simp] lemma prod_top : (prod β€ β€ : subalgebra R (A Γ B)) = β€ :=
by ext; simp
lemma prod_mono {S T : subalgebra R A} {Sβ Tβ : subalgebra R B} :
S β€ T β Sβ β€ Tβ β prod S Sβ β€ prod T Tβ := set.prod_mono
@[simp] lemma prod_inf_prod {S T : subalgebra R A} {Sβ Tβ : subalgebra R B} :
S.prod Sβ β T.prod Tβ = (S β T).prod (Sβ β Tβ) :=
set_like.coe_injective set.prod_inter_prod
end prod
section supr_lift
variables {ΞΉ : Type*}
lemma coe_supr_of_directed [nonempty ΞΉ] {S : ΞΉ β subalgebra R A}
(dir : directed (β€) S) : β(supr S) = β i, (S i : set A) :=
let K : subalgebra R A :=
{ carrier := β i, (S i),
mul_mem' := Ξ» x y hx hy,
let β¨i, hiβ© := set.mem_Union.1 hx in
let β¨j, hjβ© := set.mem_Union.1 hy in
let β¨k, hik, hjkβ© := dir i j in
set.mem_Union.2 β¨k, subalgebra.mul_mem (S k) (hik hi) (hjk hj)β© ,
add_mem' := Ξ» x y hx hy,
let β¨i, hiβ© := set.mem_Union.1 hx in
let β¨j, hjβ© := set.mem_Union.1 hy in
let β¨k, hik, hjkβ© := dir i j in
set.mem_Union.2 β¨k, subalgebra.add_mem (S k) (hik hi) (hjk hj)β©,
algebra_map_mem' := Ξ» r, let i := @nonempty.some ΞΉ infer_instance in
set.mem_Union.2 β¨i, subalgebra.algebra_map_mem _ _β© } in
have supr S = K,
from le_antisymm (supr_le (Ξ» i, set.subset_Union (Ξ» i, β(S i)) i))
(set_like.coe_subset_coe.1
(set.Union_subset (Ξ» i, set_like.coe_subset_coe.2 (le_supr _ _)))),
this.symm βΈ rfl
/-- Define an algebra homomorphism on a directed supremum of subalgebras by defining
it on each subalgebra, and proving that it agrees on the intersection of subalgebras. -/
noncomputable def supr_lift [nonempty ΞΉ]
(K : ΞΉ β subalgebra R A)
(dir : directed (β€) K)
(f : Ξ i, K i ββ[R] B)
(hf : β (i j : ΞΉ) (h : K i β€ K j), f i = (f j).comp (inclusion h))
(T : subalgebra R A) (hT : T = supr K) :
β₯T ββ[R] B :=
by subst hT; exact
{ to_fun := set.Union_lift (Ξ» i, β(K i)) (Ξ» i x, f i x)
(Ξ» i j x hxi hxj,
let β¨k, hik, hjkβ© := dir i j in
begin
rw [hf i k hik, hf j k hjk],
refl
end) β(supr K)
(by rw coe_supr_of_directed dir; refl),
map_one' := set.Union_lift_const _ (Ξ» _, 1) (Ξ» _, rfl) _ (by simp),
map_zero' := set.Union_lift_const _ (Ξ» _, 0) (Ξ» _, rfl) _ (by simp),
map_mul' := set.Union_lift_binary (coe_supr_of_directed dir) dir _
(Ξ» _, (*)) (Ξ» _ _ _, rfl) _ (by simp),
map_add' := set.Union_lift_binary (coe_supr_of_directed dir) dir _
(Ξ» _, (+)) (Ξ» _ _ _, rfl) _ (by simp),
commutes' := Ξ» r, set.Union_lift_const _ (Ξ» _, algebra_map _ _ r)
(Ξ» _, rfl) _ (Ξ» i, by erw [alg_hom.commutes (f i)]) }
variables [nonempty ΞΉ] {K : ΞΉ β subalgebra R A} {dir : directed (β€) K}
{f : Ξ i, K i ββ[R] B}
{hf : β (i j : ΞΉ) (h : K i β€ K j), f i = (f j).comp (inclusion h)}
{T : subalgebra R A} {hT : T = supr K}
@[simp] lemma supr_lift_inclusion {i : ΞΉ} (x : K i) (h : K i β€ T) :
supr_lift K dir f hf T hT (inclusion h x) = f i x :=
by subst T; exact set.Union_lift_inclusion _ _
@[simp] lemma supr_lift_comp_inclusion {i : ΞΉ} (h : K i β€ T) :
(supr_lift K dir f hf T hT).comp (inclusion h) = f i :=
by ext; simp
@[simp] lemma supr_lift_mk {i : ΞΉ} (x : K i) (hx : (x : A) β T) :
supr_lift K dir f hf T hT β¨x, hxβ© = f i x :=
by subst hT; exact set.Union_lift_mk x hx
lemma supr_lift_of_mem {i : ΞΉ} (x : T) (hx : (x : A) β K i) :
supr_lift K dir f hf T hT x = f i β¨x, hxβ© :=
by subst hT; exact set.Union_lift_of_mem x hx
end supr_lift
/-! ## Actions by `subalgebra`s
These are just copies of the definitions about `subsemiring` starting from
`subring.mul_action`.
-/
section actions
variables {Ξ± Ξ² : Type*}
/-- The action by a subalgebra is the action by the underlying ring. -/
instance [mul_action A Ξ±] (S : subalgebra R A) : mul_action S Ξ± :=
S.to_subsemiring.mul_action
lemma smul_def [mul_action A Ξ±] {S : subalgebra R A} (g : S) (m : Ξ±) : g β’ m = (g : A) β’ m := rfl
instance smul_comm_class_left
[mul_action A Ξ²] [has_scalar Ξ± Ξ²] [smul_comm_class A Ξ± Ξ²] (S : subalgebra R A) :
smul_comm_class S Ξ± Ξ² :=
S.to_subsemiring.smul_comm_class_left
instance smul_comm_class_right
[has_scalar Ξ± Ξ²] [mul_action A Ξ²] [smul_comm_class Ξ± A Ξ²] (S : subalgebra R A) :
smul_comm_class Ξ± S Ξ² :=
S.to_subsemiring.smul_comm_class_right
/-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/
instance is_scalar_tower_left
[has_scalar Ξ± Ξ²] [mul_action A Ξ±] [mul_action A Ξ²] [is_scalar_tower A Ξ± Ξ²] (S : subalgebra R A) :
is_scalar_tower S Ξ± Ξ² :=
S.to_subsemiring.is_scalar_tower
instance [mul_action A Ξ±] [has_faithful_scalar A Ξ±] (S : subalgebra R A) :
has_faithful_scalar S Ξ± :=
S.to_subsemiring.has_faithful_scalar
/-- The action by a subalgebra is the action by the underlying algebra. -/
instance [add_monoid Ξ±] [distrib_mul_action A Ξ±] (S : subalgebra R A) : distrib_mul_action S Ξ± :=
S.to_subsemiring.distrib_mul_action
/-- The action by a subalgebra is the action by the underlying algebra. -/
instance module_left [add_comm_monoid Ξ±] [module A Ξ±] (S : subalgebra R A) : module S Ξ± :=
S.to_subsemiring.module
/-- The action by a subalgebra is the action by the underlying algebra. -/
instance to_algebra {R A : Type*} [comm_semiring R] [comm_semiring A] [semiring Ξ±]
[algebra R A] [algebra A Ξ±] (S : subalgebra R A) : algebra S Ξ± :=
algebra.of_subsemiring S.to_subsemiring
lemma algebra_map_eq {R A : Type*} [comm_semiring R] [comm_semiring A] [semiring Ξ±]
[algebra R A] [algebra A Ξ±] (S : subalgebra R A) :
algebra_map S Ξ± = (algebra_map A Ξ±).comp S.val := rfl
@[simp] lemma srange_algebra_map {R A : Type*} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) :
(algebra_map S A).srange = S.to_subsemiring :=
by rw [algebra_map_eq, algebra.id.map_eq_id, ring_hom.id_comp, β to_subsemiring_subtype,
subsemiring.srange_subtype]
@[simp] lemma range_algebra_map {R A : Type*} [comm_ring R] [comm_ring A]
[algebra R A] (S : subalgebra R A) :
(algebra_map S A).range = S.to_subring :=
by rw [algebra_map_eq, algebra.id.map_eq_id, ring_hom.id_comp, β to_subring_subtype,
subring.range_subtype]
instance no_zero_smul_divisors_top [no_zero_divisors A] (S : subalgebra R A) :
no_zero_smul_divisors S A :=
β¨Ξ» c x h,
have (c : A) = 0 β¨ x = 0,
from eq_zero_or_eq_zero_of_mul_eq_zero h,
this.imp_left (@subtype.ext_iff _ _ c 0).mprβ©
end actions
section pointwise
variables {R' : Type*} [semiring R'] [mul_semiring_action R' A] [smul_comm_class R' R A]
/-- The action on a subalgebra corresponding to applying the action to every element.
This is available as an instance in the `pointwise` locale. -/
protected def pointwise_mul_action : mul_action R' (subalgebra R A) :=
{ smul := Ξ» a S, S.map (mul_semiring_action.to_alg_hom _ _ a),
one_smul := Ξ» S,
(congr_arg (Ξ» f, S.map f) (alg_hom.ext $ by exact one_smul R')).trans S.map_id,
mul_smul := Ξ» aβ aβ S,
(congr_arg (Ξ» f, S.map f) (alg_hom.ext $ by exact mul_smul _ _)).trans (S.map_map _ _).symm }
localized "attribute [instance] subalgebra.pointwise_mul_action" in pointwise
open_locale pointwise
@[simp] lemma coe_pointwise_smul (m : R') (S : subalgebra R A) : β(m β’ S) = m β’ (S : set A) := rfl
@[simp] lemma pointwise_smul_to_subsemiring (m : R') (S : subalgebra R A) :
(m β’ S).to_subsemiring = m β’ S.to_subsemiring := rfl
@[simp] lemma pointwise_smul_to_submodule (m : R') (S : subalgebra R A) :
(m β’ S).to_submodule = m β’ S.to_submodule := rfl
@[simp] lemma pointwise_smul_to_subring {R' R A : Type*} [semiring R'] [comm_ring R] [ring A]
[mul_semiring_action R' A] [algebra R A] [smul_comm_class R' R A] (m : R') (S : subalgebra R A) :
(m β’ S).to_subring = m β’ S.to_subring := rfl
lemma smul_mem_pointwise_smul (m : R') (r : A) (S : subalgebra R A) : r β S β m β’ r β m β’ S :=
(set.smul_mem_smul_set : _ β _ β m β’ (S : set A))
end pointwise
section center
lemma _root_.set.algebra_map_mem_center (r : R) : algebra_map R A r β set.center A :=
by simp [algebra.commutes, set.mem_center_iff]
variables (R A)
/-- The center of an algebra is the set of elements which commute with every element. They form a
subalgebra. -/
def center : subalgebra R A :=
{ algebra_map_mem' := set.algebra_map_mem_center,
.. subsemiring.center A }
lemma coe_center : (center R A : set A) = set.center A := rfl
@[simp] lemma center_to_subsemiring :
(center R A).to_subsemiring = subsemiring.center A :=
rfl
@[simp] lemma center_to_subring (R A : Type*) [comm_ring R] [ring A] [algebra R A] :
(center R A).to_subring = subring.center A :=
rfl
@[simp] lemma center_eq_top (A : Type*) [comm_semiring A] [algebra R A] : center R A = β€ :=
set_like.coe_injective (set.center_eq_univ A)
variables {R A}
instance : comm_semiring (center R A) := subsemiring.center.comm_semiring
instance {A : Type*} [ring A] [algebra R A] : comm_ring (center R A) := subring.center.comm_ring
lemma mem_center_iff {a : A} : a β center R A β β (b : A), b*a = a*b := iff.rfl
end center
end subalgebra
section nat
variables {R : Type*} [semiring R]
/-- A subsemiring is a `β`-subalgebra. -/
def subalgebra_of_subsemiring (S : subsemiring R) : subalgebra β R :=
{ algebra_map_mem' := Ξ» i, S.coe_nat_mem i,
.. S }
@[simp] lemma mem_subalgebra_of_subsemiring {x : R} {S : subsemiring R} :
x β subalgebra_of_subsemiring S β x β S :=
iff.rfl
end nat
section int
variables {R : Type*} [ring R]
/-- A subring is a `β€`-subalgebra. -/
def subalgebra_of_subring (S : subring R) : subalgebra β€ R :=
{ algebra_map_mem' := Ξ» i, int.induction_on i S.zero_mem
(Ξ» i ih, S.add_mem ih S.one_mem)
(Ξ» i ih, show ((-i - 1 : β€) : R) β S, by { rw [int.cast_sub, int.cast_one],
exact S.sub_mem ih S.one_mem }),
.. S }
variables {S : Type*} [semiring S]
@[simp] lemma mem_subalgebra_of_subring {x : R} {S : subring R} :
x β subalgebra_of_subring S β x β S :=
iff.rfl
end int
|
de64374ec56769f41604681f8d7ce816b7558f5e | 367134ba5a65885e863bdc4507601606690974c1 | /src/meta/coinductive_predicates.lean | 4e6339b53fb949141285f3679f5eedbf7b5464b3 | [
"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 | 20,448 | lean | /-
Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes HΓΆlzl (CMU)
-/
import tactic.core
section
universe u
@[user_attribute]
meta def monotonicity : user_attribute := { name := `monotonicity, descr := "Monotonicity rules for predicates" }
lemma monotonicity.pi {Ξ± : Sort u} {p q : Ξ± β Prop} (h : βa, implies (p a) (q a)) :
implies (Ξ a, p a) (Ξ a, q a) :=
assume h' a, h a (h' a)
lemma monotonicity.imp {p p' q q' : Prop} (hβ : implies p' q') (hβ : implies q p) :
implies (p β p') (q β q') :=
assume h, hβ β h β hβ
@[monotonicity]
lemma monotonicity.const (p : Prop) : implies p p := id
@[monotonicity]
lemma monotonicity.true (p : Prop) : implies p true := assume _, trivial
@[monotonicity]
lemma monotonicity.false (p : Prop) : implies false p := false.elim
@[monotonicity]
lemma monotonicity.exists {Ξ± : Sort u} {p q : Ξ± β Prop} (h : βa, implies (p a) (q a)) :
implies (βa, p a) (βa, q a) :=
exists_imp_exists h
@[monotonicity]
lemma monotonicity.and {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') :
implies (p β§ q) (p' β§ q') :=
and.imp hp hq
@[monotonicity]
lemma monotonicity.or {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') :
implies (p β¨ q) (p' β¨ q') :=
or.imp hp hq
@[monotonicity]
lemma monotonicity.not {p q : Prop} (h : implies p q) :
implies (Β¬ q) (Β¬ p) :=
mt h
end
namespace tactic
open expr tactic
/- TODO: use backchaining -/
private meta def mono_aux (ns : list name) (hs : list expr) : tactic unit := do
intros,
(do
`(implies %%p %%q) β target,
(do is_def_eq p q, eapplyc `monotone.const) <|>
(do
(expr.pi pn pbi pd pb) β whnf p,
(expr.pi qn qbi qd qb) β whnf q,
sort u β infer_type pd,
(do is_def_eq pd qd,
let p' := expr.lam pn pbi pd pb,
let q' := expr.lam qn qbi qd qb,
eapply ((const `monotonicity.pi [u] : expr) pd p' q'),
skip) <|>
(do guard $ u = level.zero β§ is_arrow p β§ is_arrow q,
let p' := pb.lower_vars 0 1,
let q' := qb.lower_vars 0 1,
eapply ((const `monotonicity.imp []: expr) pd p' qd q'),
skip))) <|>
first (hs.map $ Ξ»h, apply_core h {md := transparency.none, new_goals := new_goals.non_dep_only} >> skip) <|>
first (ns.map $ Ξ»n, do c β mk_const n, apply_core c {md := transparency.none, new_goals := new_goals.non_dep_only}, skip),
all_goals' mono_aux
meta def mono (e : expr) (hs : list expr) : tactic unit := do
t β target,
t' β infer_type e,
ns β attribute.get_instances `monotonicity,
((), p) β solve_aux `(implies %%t' %%t) (mono_aux ns hs),
exact (p e)
end tactic
/-
The coinductive predicate `pred`:
coinductive {u} pred (A) : a β Prop
| r : βA b, pred A p
where
`u` is a list of universe parameters
`A` is a list of global parameters
`pred` is a list predicates to be defined
`a` are the indices for each `pred`
`r` is a list of introduction rules for each `pred`
`b` is a list of parameters for each rule in `r` and `pred`
`p` is are the instances of `a` using `A` and `b`
`pred` is compiled to the following defintions:
inductive {u} pred.functional (A) ([pred'] : a β Prop) : a β Prop
| r : βa [f], b[pred/pred'] β pred.functional a [f] p
lemma {u} pred.functional.mono (A) ([predβ] [predβ] : a β Prop) [(h : βb, predβ b β predβ b)] :
βp, pred.functional A predβ p β pred.functional A predβ p
def {u} pred_i (A) (a) : Prop :=
β[pred'], (Ξi, βa, pred_i a β pred_i.functional A [pred] a) β§ pred'_i a
lemma {u} pred_i.corec_functional (A) [Ξi, C_i : a_i β Prop] [Ξi, h : βa, C_i a β pred_i.functional A C_i a] :
βa, C_i a β pred_i A a
lemma {u} pred_i.destruct (A) (a) : pred A a β pred.functional A [pred A] a
lemma {u} pred_i.construct (A) : βa, pred_i.functional A [pred A] a β pred_i A a
lemma {u} pred_i.cases_on (A) (C : a β Prop) {a} (h : pred_i a) [Ξi, βa, b β C p] β C a
lemma {u} pred_i.corec_on (A) [(C : a β Prop)] (a) (h : C_i a)
[Ξi, h_i : βa, C_i a β [V j βb, a = p]] : pred_i A a
lemma {u} pred.r (A) (b) : pred_i A p
-/
namespace tactic
open level expr tactic
namespace add_coinductive_predicate
/- private -/ meta structure coind_rule : Type :=
(orig_nm : name)
(func_nm : name)
(type : expr)
(loc_type : expr)
(args : list expr)
(loc_args : list expr)
(concl : expr)
(insts : list expr)
/- private -/ meta structure coind_pred : Type :=
(u_names : list name)
(params : list expr)
(pd_name : name)
(type : expr)
(intros : list coind_rule)
(locals : list expr)
(fβ fβ : expr)
(u_f : level)
namespace coind_pred
meta def u_params (pd : coind_pred) : list level :=
pd.u_names.map param
meta def fβ_l (pd : coind_pred) : expr :=
pd.fβ.app_of_list pd.locals
meta def fβ_l (pd : coind_pred) : expr :=
pd.fβ.app_of_list pd.locals
meta def pred (pd : coind_pred) : expr :=
const pd.pd_name pd.u_params
meta def func (pd : coind_pred) : expr :=
const (pd.pd_name ++ "functional") pd.u_params
meta def func_g (pd : coind_pred) : expr :=
pd.func.app_of_list $ pd.params
meta def pred_g (pd : coind_pred) : expr :=
pd.pred.app_of_list $ pd.params
meta def impl_locals (pd : coind_pred) : list expr :=
pd.locals.map to_implicit_binder
meta def impl_params (pd : coind_pred) : list expr :=
pd.params.map to_implicit_binder
meta def le (pd : coind_pred) (fβ fβ : expr) : expr :=
(imp (fβ.app_of_list pd.locals) (fβ.app_of_list pd.locals)).pis pd.impl_locals
meta def corec_functional (pd : coind_pred) : expr :=
const (pd.pd_name ++ "corec_functional") pd.u_params
meta def mono (pd : coind_pred) : expr :=
const (pd.func.const_name ++ "mono") pd.u_params
meta def rec' (pd : coind_pred) : tactic expr :=
do let c := pd.func.const_name ++ "rec",
env β get_env,
decl β env.get c,
let num := decl.univ_params.length,
return (const c $ if num = pd.u_params.length then pd.u_params else level.zero :: pd.u_params)
-- ^^ `rec`'s universes are not always `u_params`, e.g. eq, wf, false
meta def construct (pd : coind_pred) : expr :=
const (pd.pd_name ++ "construct") pd.u_params
meta def destruct (pd : coind_pred) : expr :=
const (pd.pd_name ++ "destruct") pd.u_params
meta def add_theorem (pd : coind_pred) (n : name) (type : expr) (tac : tactic unit) : tactic expr :=
add_theorem_by n pd.u_names type tac
end coind_pred
end add_coinductive_predicate
open add_coinductive_predicate
/- compact_relation bs as_ps: Product a relation of the form:
R := Ξ» as, β bs, Ξ_i a_i = p_i[bs]
This relation is user visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and
hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`. -/
private meta def compact_relation :
list expr β list (expr Γ expr) β list expr Γ list (expr Γ expr)
| [] ps := ([], ps)
| (list.cons b bs) ps :=
match ps.span (Ξ»ap:expr Γ expr, Β¬ ap.2 =β b) with
| (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps)
| (psβ, list.cons (a, _) psβ) := let i := a.instantiate_local b.local_uniq_name in
compact_relation (bs.map i) ((psβ ++ psβ).map (Ξ»β¨a, pβ©, (a, i p)))
end
meta def add_coinductive_predicate
(u_names : list name) (params : list expr) (preds : list $ expr Γ list expr) : command := do
let params_names := params.map local_pp_name,
let u_params := u_names.map param,
pre_info β preds.mmap (Ξ»β¨c, isβ©, do
(ls, t) β open_pis c.local_type,
(is_def_eq t `(Prop) <|>
fail (format! "Type of {c.local_pp_name} is not Prop. Currently only " ++
"coinductive predicates are supported.")),
let n := if preds.length = 1 then "" else "_" ++ c.local_pp_name.last_string,
fβ β mk_local_def (mk_simple_name $ "C" ++ n) c.local_type,
fβ β mk_local_def (mk_simple_name $ "Cβ" ++ n) c.local_type,
return (ls, (fβ, fβ))),
let fs := pre_info.map prod.snd,
let fsβ := fs.map prod.fst,
let fsβ := fs.map prod.snd,
pds β (preds.zip pre_info).mmap (Ξ»β¨β¨c, isβ©, ls, fβ, fββ©, do
sort u_f β infer_type fβ >>= infer_type,
let pred_g := Ξ»c:expr, (const c.local_uniq_name u_params : expr).app_of_list params,
intros β is.mmap (Ξ»i, do
(args, t') β open_pis i.local_type,
(name.mk_string sub p) β return i.local_uniq_name,
let loc_args := args.map $ Ξ»e, (fsβ.zip preds).foldl (Ξ»(e:expr) β¨f, c, _β©,
e.replace_with (pred_g c) f) e,
let t' := t'.replace_with (pred_g c) fβ,
return { tactic.add_coinductive_predicate.coind_rule .
orig_nm := i.local_uniq_name,
func_nm := (p ++ "functional") ++ sub,
type := i.local_type,
loc_type := t'.pis loc_args,
concl := t',
loc_args := loc_args,
args := args,
insts := t'.get_app_args }),
return { tactic.add_coinductive_predicate.coind_pred .
pd_name := c.local_uniq_name, type := c.local_type, fβ := fβ, fβ := fβ, u_f := u_f,
intros := intros, locals := ls, params := params, u_names := u_names }),
/- Introduce all functionals -/
pds.mmap' (Ξ»pd:coind_pred, do
let func_fβ := pd.func_g.app_of_list $ fsβ,
let func_fβ := pd.func_g.app_of_list $ fsβ,
/- Define functional for `pd` as inductive predicate -/
func_intros β pd.intros.mmap (Ξ»r:coind_rule, do
let t := instantiate_local pd.fβ.local_uniq_name (pd.func_g.app_of_list fsβ) r.loc_type,
return (r.func_nm, r.orig_nm, t.pis $ params ++ fsβ)),
add_inductive pd.func.const_name u_names
(params.length + preds.length) (pd.type.pis $ params ++ fsβ) (func_intros.map $ Ξ»β¨t, _, rβ©, (t, r)),
/- Prove monotonicity rule -/
mono_params β pds.mmap (Ξ»pd, do
h β mk_local_def `h $ pd.le pd.fβ pd.fβ,
return [pd.fβ, pd.fβ, h]),
pd.add_theorem (pd.func.const_name ++ "mono")
((pd.le func_fβ func_fβ).pis $ params ++ mono_params.join)
(do
ps β intro_lst $ params.map expr.local_pp_name,
fs β pds.mmap (Ξ»pd, do
[fβ, fβ, h] β intro_lst [pd.fβ.local_pp_name, pd.fβ.local_pp_name, `h],
-- the type of h' reduces to h
let h' := local_const h.local_uniq_name h.local_pp_name h.local_binding_info $
(((const `implies [] : expr)
(fβ.app_of_list pd.locals) (fβ.app_of_list pd.locals)).pis pd.locals).instantiate_locals $
(ps.zip params).map $ Ξ»β¨lv, pβ©, (p.local_uniq_name, lv),
return (fβ, h')),
m β pd.rec',
eapply $ m.app_of_list ps, -- somehow `induction` / `cases` doesn't work?
func_intros.mmap' (Ξ»β¨n, pp_n, tβ©, solve1 $ do
bs β intros,
ms β apply_core ((const n u_params).app_of_list $ ps ++ fs.map prod.fst) {new_goals := new_goals.all},
params β (ms.zip bs).enum.mfilter (Ξ»β¨n, m, dβ©, bnot <$> is_assigned m.2),
params.mmap' (Ξ»β¨n, m, dβ©, mono d (fs.map prod.snd) <|>
fail format! "failed to prove montonoicity of {n+1}. parameter of intro-rule {pp_n}")))),
pds.mmap' (Ξ»pd, do
let func_f := Ξ»pd:coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.fβ,
/- define final predicate -/
pred_body β mk_exists_lst (pds.map coind_pred.fβ) $
mk_and_lst $ (pds.map $ Ξ»pd, pd.le pd.fβ (func_f pd)) ++ [pd.fβ.app_of_list pd.locals],
add_decl $ mk_definition pd.pd_name u_names (pd.type.pis $ params) $
pred_body.lambdas $ params ++ pd.locals,
/- prove `corec_functional` rule -/
hs β pds.mmap $ Ξ»pd:coind_pred, mk_local_def `hc $ pd.le pd.fβ (func_f pd),
pd.add_theorem (pd.pred.const_name ++ "corec_functional")
((pd.le pd.fβ pd.pred_g).pis $ params ++ fsβ ++ hs)
(do
intro_lst $ params.map local_pp_name,
fs β intro_lst $ fsβ.map local_pp_name,
hs β intro_lst $ hs.map local_pp_name,
ls β intro_lst $ pd.locals.map local_pp_name,
h β intro `h,
whnf_target,
fs.mmap' existsi,
hs.mmap' (Ξ»f, econstructor >> exact f),
exact h)),
let func_f := Ξ»pd : coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.pred_g,
/- prove `destruct` rules -/
pds.enum.mmap' (Ξ»β¨n, pdβ©, do
let destruct := pd.le pd.pred_g (func_f pd),
pd.add_theorem (pd.pred.const_name ++ "destruct") (destruct.pis params) (do
ps β intro_lst $ params.map local_pp_name,
ls β intro_lst $ pd.locals.map local_pp_name,
h β intro `h,
(fs, h, _) β elim_gen_prod pds.length h [] [],
(hs, h, _) β elim_gen_prod pds.length h [] [],
eapply $ pd.mono.app_of_list ps,
pds.mmap' (Ξ»pd:coind_pred, focus1 $ do
eapply $ pd.corec_functional,
focus $ hs.map exact),
some h' β return $ hs.nth n,
eapply h',
exact h)),
/- prove `construct` rules -/
pds.mmap' (Ξ»pd,
pd.add_theorem (pd.pred.const_name ++ "construct")
((pd.le (func_f pd) pd.pred_g).pis params) (do
ps β intro_lst $ params.map local_pp_name,
let func_pred_g := Ξ»pd:coind_pred,
pd.func.app_of_list $ ps ++ pds.map (Ξ»pd:coind_pred, pd.pred.app_of_list ps),
eapply $ pd.corec_functional.app_of_list $ ps ++ pds.map func_pred_g,
pds.mmap' (Ξ»pd:coind_pred, solve1 $ do
eapply $ pd.mono.app_of_list ps,
pds.mmap' (Ξ»pd, solve1 $ eapply (pd.destruct.app_of_list ps) >> skip)))),
/- prove `cases_on` rules -/
pds.mmap' (Ξ»pd, do
let C := pd.fβ.to_implicit_binder,
h β mk_local_def `h $ pd.pred_g.app_of_list pd.locals,
rules β pd.intros.mmap (Ξ»r:coind_rule, do
mk_local_def (mk_simple_name r.orig_nm.last_string) $ (C.app_of_list r.insts).pis r.args),
cases_on β pd.add_theorem (pd.pred.const_name ++ "cases_on")
((C.app_of_list pd.locals).pis $ params ++ [C] ++ pd.impl_locals ++ [h] ++ rules)
(do
ps β intro_lst $ params.map local_pp_name,
C β intro `C,
ls β intro_lst $ pd.locals.map local_pp_name,
h β intro `h,
rules β intro_lst $ rules.map local_pp_name,
func_rec β pd.rec',
eapply $ func_rec.app_of_list $ ps ++ pds.map (Ξ»pd, pd.pred.app_of_list ps) ++ [C] ++ rules,
eapply $ pd.destruct,
exact h),
set_basic_attribute `elab_as_eliminator cases_on.const_name),
/- prove `corec_on` rules -/
pds.mmap' (Ξ»pd, do
rules β pds.mmap (Ξ»pd, do
intros β pd.intros.mmap (Ξ»r, do
let (bs, eqs) := compact_relation r.loc_args $ pd.locals.zip r.insts,
eqs β eqs.mmap (Ξ»β¨l, iβ©, do
sort u β infer_type l.local_type,
return $ (const `eq [u] : expr) l.local_type i l),
match bs, eqs with
| [], [] := return ((0, 0), mk_true)
| _, [] := prod.mk (bs.length, 0) <$> mk_exists_lst bs.init bs.ilast.local_type
| _, _ := prod.mk (bs.length, eqs.length) <$> mk_exists_lst bs (mk_and_lst eqs)
end),
let shape := intros.map prod.fst,
let intros := intros.map prod.snd,
prod.mk shape <$>
mk_local_def (mk_simple_name $ "h_" ++ pd.pd_name.last_string)
(((pd.fβ.app_of_list pd.locals).imp (mk_or_lst intros)).pis pd.locals)),
let shape := rules.map prod.fst,
let rules := rules.map prod.snd,
h β mk_local_def `h $ pd.fβ.app_of_list pd.locals,
pd.add_theorem (pd.pred.const_name ++ "corec_on")
((pd.pred_g.app_of_list $ pd.locals).pis $ params ++ fsβ ++ pd.impl_locals ++ [h] ++ rules)
(do
ps β intro_lst $ params.map local_pp_name,
fs β intro_lst $ fsβ.map local_pp_name,
ls β intro_lst $ pd.locals.map local_pp_name,
h β intro `h,
rules β intro_lst $ rules.map local_pp_name,
eapply $ pd.corec_functional.app_of_list $ ps ++ fs,
(pds.zip $ rules.zip shape).mmap (Ξ»β¨pd, hr, sβ©, solve1 $ do
ls β intro_lst $ pd.locals.map local_pp_name,
h' β intro `h,
h' β note `h' none $ hr.app_of_list ls h',
match s.length with
| 0 := induction h' >> skip -- h' : false
| (n+1) := do
hs β elim_gen_sum n h',
(hs.zip $ pd.intros.zip s).mmap' (Ξ»β¨h, r, n_bs, n_eqsβ©, solve1 $ do
(as, h, _) β elim_gen_prod (n_bs - (if n_eqs = 0 then 1 else 0)) h [] [],
if n_eqs > 0 then do
(eqs, eq', _) β elim_gen_prod (n_eqs - 1) h [] [],
(eqs ++ [eq']).mmap' subst
else skip,
eapply ((const r.func_nm u_params).app_of_list $ ps ++ fs),
iterate assumption)
end),
exact h)),
/- prove constructors -/
pds.mmap' (Ξ»pd, pd.intros.mmap' (Ξ»r,
pd.add_theorem r.orig_nm (r.type.pis params) $ do
ps β intro_lst $ params.map local_pp_name,
bs β intros,
eapply $ pd.construct,
exact $ (const r.func_nm u_params).app_of_list $ ps ++ pds.map (Ξ»pd, pd.pred.app_of_list ps) ++ bs)),
pds.mmap' (Ξ»pd:coind_pred, set_basic_attribute `irreducible pd.pd_name),
try triv -- we setup a trivial goal for the tactic framework
open lean.parser
open interactive
@[user_command]
meta def coinductive_predicate (meta_info : decl_meta_info) (_ : parse $ tk "coinductive") : lean.parser unit := do
decl β inductive_decl.parse meta_info,
add_coinductive_predicate decl.u_names decl.params $ decl.decls.map $ Ξ» d, (d.sig, d.intros),
decl.decls.mmap' $ Ξ» d, do {
get_env >>= Ξ» env, set_env $ env.add_namespace d.name,
meta_info.attrs.apply d.name,
d.attrs.apply d.name,
some doc_string β pure meta_info.doc_string | skip,
add_doc_string d.name doc_string
}
/-- Prepares coinduction proofs. This tactic constructs the coinduction invariant from
the quantifiers in the current goal.
Current version: do not support mutual inductive rules -/
meta def coinduction (rule : expr) (ns : list name) : tactic unit := focus1 $
do
ctxts' β intros,
ctxts β ctxts'.mmap (Ξ»v,
local_const v.local_uniq_name v.local_pp_name v.local_binding_info <$> infer_type v),
mvars β apply_core rule {approx := ff, new_goals := new_goals.all},
-- analyse relation
g β list.head <$> get_goals,
(list.cons _ m_is) β return $ mvars.drop_while (Ξ»v, v.2 β g),
tgt β target,
(is, ty) β open_pis tgt,
-- construct coinduction predicate
(bs, eqs) β compact_relation ctxts <$>
((is.zip m_is).mmap (Ξ»β¨i, mβ©, prod.mk i <$> instantiate_mvars m.2)),
solve1 (do
eqs β mk_and_lst <$> eqs.mmap (Ξ»β¨i, mβ©,
mk_app `eq [m, i] >>= instantiate_mvars)
<|> do { x β mk_psigma (eqs.map prod.fst),
y β mk_psigma (eqs.map prod.snd),
t β infer_type x,
mk_mapp `eq [t,x,y] },
rel β mk_exists_lst bs eqs,
exact (rel.lambdas is)),
-- prove predicate
solve1 (do
target >>= instantiate_mvars >>= change, -- TODO: bug in existsi & constructor when mvars in hyptohesis
bs.mmap existsi,
iterate' (econstructor >> skip)),
-- clean up remaining coinduction steps
all_goals' (do
ctxts'.reverse.mmap clear,
target >>= instantiate_mvars >>= change, -- TODO: bug in subst when mvars in hyptohesis
is β intro_lst $ is.map expr.local_pp_name,
h β intro1,
(_, h, ns) β elim_gen_prod (bs.length - (if eqs.length = 0 then 1 else 0)) h [] ns,
(match eqs with
| [] := clear h
| (e::eqs) := do
(hs, h, ns) β elim_gen_prod eqs.length h [] ns,
(h::(hs.reverse) : list _).mfoldl (Ξ» (hs : list name) (h : expr),
do [(_,hs',Ο)] β cases_core h hs,
clear (h.instantiate_locals Ο),
pure $ hs.drop hs'.length) ns,
skip
end))
namespace interactive
open interactive interactive.types expr lean.parser
local postfix `?`:9001 := optional
local postfix *:9001 := many
meta def coinduction (corec_name : parse ident)
(ns : parse with_ident_list)
(revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do
rule β mk_const corec_name,
locals β mmap tactic.get_local $ revert.get_or_else [],
revert_lst locals,
tactic.coinduction rule ns,
skip
end interactive
end tactic
|
253069be38ca5f3b86b406adc2f0a36475868184 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/tactic/omega/find_scalars.lean | 854a0a7dedff3bdfc8216186e03b22baf39cb391 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 1,885 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
A tactic which performs FourierβMotzkin elimination to find
a contradictory linear combination of input constraints.
-/
import tactic.omega.term data.list.min_max
open list.func
namespace omega
meta def trisect (m : nat) :
list (list nat Γ term) β (list (list nat Γ term) Γ
list (list nat Γ term) Γ list (list nat Γ term))
| [] := ([],[],[])
| ((p,t)::pts) :=
let (neg,zero,pos) := trisect pts in
if get m t.snd < 0
then ((p,t)::neg,zero,pos)
else if get m t.snd = 0
then (neg,(p,t)::zero,pos)
else (neg,zero,(p,t)::pos)
meta def elim_var_aux (m : nat) :
((list nat Γ term) Γ (list nat Γ term)) β tactic (list nat Γ term)
| ((p1,t1), (p2,t2)) :=
let n := int.nat_abs (get m t1.snd) in
let o := int.nat_abs (get m t2.snd) in
let lcm := (nat.lcm n o) in
let n' := lcm / n in
let o' := lcm / o in
return (add (p1.map ((*) n')) (p2.map ((*) o')),
term.add (t1.mul n') (t2.mul o'))
meta def elim_var (m : nat) (neg pos : list (list nat Γ term)) :
tactic (list (list nat Γ term)) :=
let pairs := list.product neg pos in
monad.mapm (elim_var_aux m) pairs
meta def find_neg_const : list (list nat Γ term) β tactic (list nat)
| [] := tactic.failed
| ((Ο,β¨c,_β©)::l) := if c < 0 then return Ο else find_neg_const l
meta def find_scalars_core : nat β list (list nat Γ term) β tactic (list nat)
| 0 pts := find_neg_const pts
| (m+1) pts :=
let (neg,zero,pos) := trisect m pts in
do new β elim_var m neg pos,
find_scalars_core m (new ++ zero)
meta def find_scalars (ts : list term) : tactic (list nat) :=
find_scalars_core
(ts.map (Ξ» t : term, t.snd.length)).maximum
(ts.map_with_index (Ξ» m t, (list.func.set 1 [] m, t)))
end omega |
a8c2de9bc644ff61aa2b34dd5d623a9d236bce09 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/tactic/positivity.lean | b9c36aa5a13cb2890c451f9bab39d11ce43ba34f | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 15,684 | lean | /-
Copyright (c) 2022 Mario Carneiro, Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Heather Macbeth
-/
import tactic.norm_num
/-! # `positivity` tactic
The `positivity` tactic in this file solves goals of the form `0 β€ x` and `0 < x`. The tactic works
recursively according to the syntax of the expression `x`. For example, a goal of the form
`0 β€ 3 * a ^ 2 + b * c` can be solved either
* by a hypothesis such as `5 β€ 3 * a ^ 2 + b * c` which directly implies the nonegativity of
`3 * a ^ 2 + b * c`; or,
* by the application of the lemma `add_nonneg` and the success of the `positivity` tactic on the two
sub-expressions `3 * a ^ 2` and `b * c`.
For each supported operation, one must write a small tactic, tagged with the attribute
`@[positivity]`, which operates only on goals whose leading function application is that operation.
Typically, this small tactic will run the full `positivity` tactic on one or more of the function's
arguments (which is where the recursion comes in), and if successful will combine this with an
appropriate lemma to give positivity of the full expression.
This file contains the core `positivity` logic and the small tactics handling the basic operations:
`min`, `max`, `+`, `*`, `/`, `β»ΒΉ`, raising to natural powers, and taking absolute values. Further
extensions, e.g. to handle `real.sqrt` and norms, can be found in the files of the library which
introduce these operations.
## Main declarations
* `tactic.norm_num.positivity` tries to prove positivity of an expression by running `norm_num` on
it. This is one of the base cases of the recursion.
* `tactic.positivity.compare_hyp` tries to prove positivity of an expression by comparing with a
provided hypothesis. If the hypothesis is of the form `a β€ b` or similar, with `b` matching the
expression whose proof of positivity is desired, then it will check whether `a` can be proved
positive via `tactic.norm_num.positivity` and if so apply a transitivity lemma. This is the other
base case of the recursion.
* `tactic.positivity.attr` creates the `positivity` user attribute for tagging the extension
tactics handling specific operations, and specifies the behaviour for a single step of the
recursion
* `tactic.positivity.core` collects the list of tactics with the `@[positivity]` attribute and
calls the first recursion step as specified in `tactic.positivity.attr`. Its input is `e : expr`
and its output (if it succeeds) is a term of a custom inductive type
`tactic.positivity.strictness`, containing an `expr` which is a proof of the
strict-positivity/nonnegativity of `e` as well as an indication of whether what could be proved
was strict-positivity or nonnegativity
* `tactic.interactive.positivity` is the user-facing tactic. It parses the goal and, if it is of
one of the forms `0 β€ e`, `0 < e`, `e > 0`, `e β₯ 0`, it sends `e` to `tactic.positivity.core`.
## TODO
Implement extensions for other operations (raising to non-numeral powers, `exp`, `log`, coercions
from `β` and `ββ₯0`).
-/
namespace tactic
/-- Inductive type recording either `positive` and an expression (typically a proof of a fact
`0 < x`) or `nonnegative` and an expression (typically a proof of a fact `0 β€ x`). -/
@[derive [decidable_eq]]
meta inductive positivity.strictness : Type
| positive : expr β positivity.strictness
| nonnegative : expr β positivity.strictness
export positivity.strictness (positive nonnegative)
private lemma lt_of_lt_of_eq'' {Ξ±} [preorder Ξ±] {b b' a : Ξ±} : b = b' β a < b' β a < b :=
Ξ» h1 h2, lt_of_lt_of_eq h2 h1.symm
/-- First base case of the `positivity` tactic. We try `norm_num` to prove directly that an
expression `e` is positive or nonnegative. -/
meta def norm_num.positivity (e : expr) : tactic strictness := do
(e', p) β norm_num.derive e <|> refl_conv e,
e'' β e'.to_rat,
typ β infer_type e',
ic β mk_instance_cache typ,
if e'' > 0 then do
(ic, pβ) β norm_num.prove_pos ic e',
p β mk_app ``lt_of_lt_of_eq'' [p, pβ],
pure (positive p)
else if e'' = 0 then do
p' β mk_app ``ge_of_eq [p],
pure (nonnegative p')
else failed
namespace positivity
/-- Given two tactics whose result is `strictness`, report a `strictness`:
- if at least one gives `positive`, report `positive` and one of the expressions giving a proof of
positivity
- if neither gives `pos` but at least one gives `nonnegative`, report `nonnegative` and one of the
expressions giving a proof of nonnegativity
- if both fail, fail -/
meta def orelse' (tac1 tac2 : tactic strictness) : tactic strictness := do
res β try_core tac1,
match res with
| none := tac2
| some res@(nonnegative e) := tac2 <|> pure res
| some res@(positive _) := pure res
end
/-! ### Core logic of the `positivity` tactic -/
/-- Second base case of the `positivity` tactic. Prove an expression `e` is positive/nonnegative by
finding a hypothesis of the form `a < e` or `a β€ e` in which `a` can be proved positive/nonnegative
by `norm_num`. -/
meta def compare_hyp (e pβ : expr) : tactic strictness := do
p_typ β infer_type pβ,
(lo, hi, strictβ) β match p_typ with -- TODO also handle equality hypotheses
| `(%%lo β€ %%hi) := pure (lo, hi, ff)
| `(%%hi β₯ %%lo) := pure (lo, hi, ff)
| `(%%lo < %%hi) := pure (lo, hi, tt)
| `(%%hi > %%lo) := pure (lo, hi, tt)
| _ := failed
end,
is_def_eq e hi,
strictnessβ β norm_num.positivity lo,
match strictnessβ, strictβ with
| (positive pβ), tt := positive <$> mk_app ``lt_trans [pβ, pβ]
| (positive pβ), ff := positive <$> mk_app `lt_of_lt_of_le [pβ, pβ]
| (nonnegative pβ), tt := positive <$> mk_app `lt_of_le_of_lt [pβ, pβ]
| (nonnegative pβ), ff := nonnegative <$> mk_app `le_trans [pβ, pβ]
end
/-- Attribute allowing a user to tag a tactic as an extension for `tactic.positivity`. The main
(recursive) step of this tactic is to try successively all the extensions tagged with this attribute
on the expression at hand, and also to try the two "base case" tactics `tactic.norm_num.positivity`,
`tactic.positivity.compare_hyp` on the expression at hand. -/
@[user_attribute]
meta def attr : user_attribute (expr β tactic strictness) unit :=
{ name := `positivity,
descr := "extensions handling particular operations for the `positivity` tactic",
cache_cfg :=
{ mk_cache := Ξ» ns, do
{ t β ns.mfoldl
(Ξ» (t : expr β tactic strictness) n, do
t' β eval_expr (expr β tactic strictness) (expr.const n []),
pure (Ξ» e, orelse' (t' e) (t e)))
(Ξ» _, failed),
pure $ Ξ» e, orelse'
(t e) $ orelse' -- run all the extensions on `e`
(norm_num.positivity e) $ -- directly try `norm_num` on `e`
-- loop over hypotheses and try to compare with `e`
local_context >>= list.foldl (Ξ» tac h, orelse' tac (compare_hyp e h)) failed },
dependencies := [] } }
/-- Look for a proof of positivity/nonnegativity of an expression `e`; if found, return the proof
together with a `strictness` stating whether the proof found was for strict positivity
(`positive p`) or only for nonnegativity (`nonnegative p`). -/
meta def core (e : expr) : tactic strictness := do
f β attr.get_cache,
f e <|> fail "failed to prove positivity/nonnegativity"
end positivity
open positivity
namespace interactive
setup_tactic_parser
/-- Tactic solving goals of the form `0 β€ x` and `0 < x`. The tactic works recursively according to
the syntax of the expression `x`, if the atoms composing the expression all have numeric lower
bounds which can be proved positive/nonnegative by `norm_num`. This tactic either closes the goal
or fails.
Examples:
```
example {a : β€} (ha : 3 < a) : 0 β€ a ^ 3 + a := by positivity
example {a : β€} (ha : 1 < a) : 0 < |(3:β€) + a| := by positivity
example {b : β€} : 0 β€ max (-3) (b ^ 2) := by positivity
```
-/
meta def positivity : tactic unit := focus1 $ do
t β target,
(rel_desired, a) β match t with
| `(0 β€ %%eβ) := pure (ff, eβ)
| `(%%eβ β₯ 0) := pure (ff, eβ)
| `(0 < %%eβ) := pure (tt, eβ)
| `(%%eβ > 0) := pure (tt, eβ)
| _ := fail "not a positivity/nonnegativity goal"
end,
strictness_proved β tactic.positivity.core a,
match rel_desired, strictness_proved with
| tt, (positive p) := pure p
| tt, (nonnegative _) := fail ("failed to prove strict positivity, but it would be possible to "
++ "prove nonnegativity if desired")
| ff, (positive p) := mk_app ``le_of_lt [p]
| ff, (nonnegative p) := pure p
end >>= tactic.exact
add_tactic_doc
{ name := "positivity",
category := doc_category.tactic,
decl_names := [`tactic.interactive.positivity],
tags := ["arithmetic", "monotonicity", "finishing"] }
end interactive
variables {R : Type*}
/-! ### `positivity` extensions for particular arithmetic operations -/
private lemma le_min_of_lt_of_le [linear_order R] (a b c : R) (ha : a < b) (hb : a β€ c) :
a β€ min b c :=
le_min ha.le hb
private lemma le_min_of_le_of_lt [linear_order R] (a b c : R) (ha : a β€ b) (hb : a < c) :
a β€ min b c :=
le_min ha hb.le
/-- Extension for the `positivity` tactic: the `min` of two numbers is nonnegative if both are
nonnegative, and strictly positive if both are. -/
@[positivity]
meta def positivity_min : expr β tactic strictness
| `(min %%a %%b) := do
strictness_a β core a,
strictness_b β core b,
match strictness_a, strictness_b with
| (positive pa), (positive pb) := positive <$> mk_app ``lt_min [pa, pb]
| (positive pa), (nonnegative pb) := nonnegative <$> mk_app ``le_min_of_lt_of_le [pa, pb]
| (nonnegative pa), (positive pb) := nonnegative <$> mk_app ``le_min_of_le_of_lt [pa, pb]
| (nonnegative pa), (nonnegative pb) := nonnegative <$> mk_app ``le_min [pa, pb]
end
| _ := failed
/-- Extension for the `positivity` tactic: the `max` of two numbers is nonnegative if at least one
is nonnegative, and strictly positive if at least one is positive. -/
@[positivity]
meta def positivity_max : expr β tactic strictness
| `(max %%a %%b) := tactic.positivity.orelse' (do
strictness_a β core a,
match strictness_a with
| (positive pa) := positive <$> mk_mapp ``lt_max_of_lt_left [none, none, none, a, b, pa]
| (nonnegative pa) :=
nonnegative <$> mk_mapp ``le_max_of_le_left [none, none, none, a, b, pa]
end)
(do
strictness_b β core b,
match strictness_b with
| (positive pb) := positive <$> mk_mapp ``lt_max_of_lt_right [none, none, none, a, b, pb]
| (nonnegative pb) :=
nonnegative <$> mk_mapp ``le_max_of_le_right [none, none, none, a, b, pb]
end)
| _ := failed
/-- Extension for the `positivity` tactic: addition is nonnegative if both summands are nonnegative,
and strictly positive if at least one summand is. -/
@[positivity]
meta def positivity_add : expr β tactic strictness
| `(%%a + %%b) := do
strictness_a β core a,
strictness_b β core b,
match strictness_a, strictness_b with
| (positive pa), (positive pb) := positive <$> mk_app ``add_pos [pa, pb]
| (positive pa), (nonnegative pb) := positive <$> mk_app ``lt_add_of_pos_of_le [pa, pb]
| (nonnegative pa), (positive pb) := positive <$> mk_app ``lt_add_of_le_of_pos [pa, pb]
| (nonnegative pa), (nonnegative pb) := nonnegative <$> mk_app ``add_nonneg [pa, pb]
end
| _ := failed
private lemma mul_nonneg_of_pos_of_nonneg [linear_ordered_semiring R] (a b : R) (ha : 0 < a)
(hb : 0 β€ b) :
0 β€ a * b :=
mul_nonneg ha.le hb
private lemma mul_nonneg_of_nonneg_of_pos [linear_ordered_semiring R] (a b : R) (ha : 0 β€ a)
(hb : 0 < b) :
0 β€ a * b :=
mul_nonneg ha hb.le
/-- Extension for the `positivity` tactic: multiplication is nonnegative if both multiplicands are
nonnegative, and strictly positive if both multiplicands are. -/
@[positivity]
meta def positivity_mul : expr β tactic strictness
| `(%%a * %%b) := do
strictness_a β core a,
strictness_b β core b,
match strictness_a, strictness_b with
| (positive pa), (positive pb) := positive <$> mk_app ``mul_pos [pa, pb]
| (positive pa), (nonnegative pb) := nonnegative <$> mk_app ``mul_nonneg_of_pos_of_nonneg [pa, pb]
| (nonnegative pa), (positive pb) := nonnegative <$> mk_app ``mul_nonneg_of_nonneg_of_pos [pa, pb]
| (nonnegative pa), (nonnegative pb) := nonnegative <$> mk_app ``mul_nonneg [pa, pb]
end
| _ := failed
private lemma div_nonneg_of_pos_of_nonneg [linear_ordered_field R] {a b : R} (ha : 0 < a)
(hb : 0 β€ b) :
0 β€ a / b :=
div_nonneg ha.le hb
private lemma div_nonneg_of_nonneg_of_pos [linear_ordered_field R] {a b : R} (ha : 0 β€ a)
(hb : 0 < b) :
0 β€ a / b :=
div_nonneg ha hb.le
/-- Extension for the `positivity` tactic: division is nonnegative if both numerator and denominator
are nonnegative, and strictly positive if both numerator and denominator are. -/
@[positivity]
meta def positivity_div : expr β tactic strictness
| `(%%a / %%b) := do -- TODO handle eg `int.div_nonneg`
strictness_a β core a,
strictness_b β core b,
match strictness_a, strictness_b with
| (positive pa), (positive pb) := positive <$> mk_app ``div_pos [pa, pb]
| (positive pa), (nonnegative pb) := nonnegative <$> mk_app ``div_nonneg_of_pos_of_nonneg [pa, pb]
| (nonnegative pa), (positive pb) := nonnegative <$> mk_app ``div_nonneg_of_nonneg_of_pos [pa, pb]
| (nonnegative pa), (nonnegative pb) := nonnegative <$> mk_app ``div_nonneg [pa, pb]
end
| _ := failed
/-- Extension for the `positivity` tactic: an inverse of a positive number is positive, an inverse
of a nonnegative number is nonnegative. -/
@[positivity]
meta def positivity_inv : expr β tactic strictness
| `((%%a)β»ΒΉ) := do
strictness_a β core a,
match strictness_a with
| (positive pa) := positive <$> mk_app ``inv_pos_of_pos [pa]
| (nonnegative pa) := nonnegative <$> mk_app ``inv_nonneg_of_nonneg [pa]
end
| _ := failed
private lemma pow_zero_pos [ordered_semiring R] [nontrivial R] (a : R) : 0 < a ^ 0 :=
zero_lt_one.trans_le (pow_zero a).ge
/-- Extension for the `positivity` tactic: raising a number `a` to a natural number power `n` is
known to be positive if `n = 0` (since `a ^ 0 = 1`) or if `0 < a`, and is known to be nonnegative if
`n = 2` (squares are nonnegative) or if `0 β€ a`. -/
@[positivity]
meta def positivity_pow : expr β tactic strictness
| `(%%a ^ %%n) := do
n_typ β infer_type n,
match n_typ with
| `(β) := do
if n = `(0) then
positive <$> mk_app ``pow_zero_pos [a]
else tactic.positivity.orelse'
-- squares are nonnegative (TODO: similar for any `bit0` exponent?)
(nonnegative <$> mk_app ``sq_nonneg [a])
-- moreover `a ^ n` is positive if `a` is and nonnegative if `a` is
(do
strictness_a β core a,
match strictness_a with
| (positive pa) := positive <$> mk_app ``pow_pos [pa, n]
| (nonnegative pa) := nonnegative <$> mk_app ``pow_nonneg [pa, n]
end)
| _ := failed -- TODO handle integer powers, maybe even real powers
end
| _ := failed
/-- Extension for the `positivity` tactic: an absolute value is nonnegative, and is strictly
positive if its input is. -/
@[positivity]
meta def positivity_abs : expr β tactic strictness
| `(|%%a|) := do
(do -- if can prove `0 < a`, report positivity
positive pa β core a,
positive <$> mk_app ``abs_pos_of_pos [pa]) <|>
nonnegative <$> mk_app ``abs_nonneg [a] -- else report nonnegativity
| _ := failed
end tactic
|
af0b9b27f4d42737a5fd0f914007b16228e44dd6 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/playground/parser/parser.lean | 213c5137a30200ee8473a0b6cd6a22b67c6976c9 | [
"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 | 32,509 | lean | import init.lean.name init.lean.parser.trie init.lean.parser.identifier
import syntax filemap
open Lean
export Lean.Parser (Trie)
-- namespace Lean
namespace Parser
/-- 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)
def ofListAux {Ξ± : Type} : List (Name Γ Ξ±) β TokenMap Ξ± β TokenMap Ξ±
| [] m := m
| (β¨k,vβ©::xs) m := ofListAux xs (m.insert k v)
def ofList {Ξ± : Type} (es : List (Name Γ Ξ±)) : TokenMap Ξ± :=
ofListAux es RBMap.empty
end TokenMap
structure FrontendConfig :=
(filename : String)
(input : String)
(fileMap : FileMap)
structure TokenConfig :=
(val : String)
(lbp : Nat := 0)
namespace TokenConfig
def beq : TokenConfig β TokenConfig β Bool
| β¨valβ, lbpββ© β¨valβ, lbpββ© := valβ == valβ && lbpβ == lbpβ
instance : HasBeq TokenConfig :=
β¨beqβ©
end TokenConfig
structure TokenCacheEntry :=
(startPos stopPos : String.Pos)
(token : Syntax)
structure ParserCache :=
(tokenCache : Option TokenCacheEntry := none)
structure ParserConfig extends FrontendConfig :=
(tokens : Trie TokenConfig)
structure ParserData :=
(stxStack : Array Syntax) (pos : String.Pos) (cache : ParserCache) (errorMsg : Option String)
@[inline] def ParserData.hasError (d : ParserData) : Bool :=
d.errorMsg != none
@[inline] def ParserData.stackSize (d : ParserData) : Nat :=
d.stxStack.size
def ParserData.restore (d : ParserData) (iniStackSz : Nat) (iniPos : Nat) : ParserData :=
{ stxStack := d.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos, .. d}
def ParserData.setPos (d : ParserData) (pos : Nat) : ParserData :=
{ pos := pos, .. d }
def ParserData.setCache (d : ParserData) (cache : ParserCache) : ParserData :=
{ cache := cache, .. d }
def ParserData.pushSyntax (d : ParserData) (n : Syntax) : ParserData :=
{ stxStack := d.stxStack.push n, .. d }
def ParserData.shrinkStack (d : ParserData) (iniStackSz : Nat) : ParserData :=
{ stxStack := d.stxStack.shrink iniStackSz, .. d }
def ParserData.next (d : ParserData) (s : String) (pos : Nat) : ParserData :=
{ pos := s.next pos, .. d }
def ParserData.toErrorMsg (d : ParserData) (cfg : ParserConfig) : String :=
match d.errorMsg with
| none := ""
| some msg :=
let pos := cfg.fileMap.toPosition d.pos in
cfg.filename ++ ":" ++ toString pos.line ++ ":" ++ toString pos.column ++ " " ++ msg
def ParserFn := String β ParserData β ParserData
instance : Inhabited ParserFn :=
β¨Ξ» s, idβ©
structure ParserInfo :=
(updateTokens : Trie TokenConfig β Trie TokenConfig := Ξ» tks, tks)
(firstTokens : List TokenConfig := [])
@[inline] def andthenFn (p q : ParserFn) : ParserFn
| s d :=
let d := p s d in
if d.hasError then d else q s d
@[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo :=
{ updateTokens := q.updateTokens β p.updateTokens,
firstTokens := p.firstTokens }
def ParserData.mkNode (d : ParserData) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserData :=
match d 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 `d`
d
else
let newNode := Syntax.node k (stack.extract iniStackSz stack.size) [] in
let stack := stack.shrink iniStackSz in
let stack := stack.push newNode in
β¨stack, pos, cache, errβ©
@[inline] def nodeFn (k : SyntaxNodeKind) (p : ParserFn) : ParserFn
| s d :=
let iniSz := d.stackSize in
let d := p s d in
d.mkNode k iniSz
@[noinline] def nodeInfo (p : ParserInfo) : ParserInfo :=
{ updateTokens := p.updateTokens,
firstTokens := p.firstTokens }
@[inline] def orelseFn (p q : ParserFn) : ParserFn
| s d :=
let iniSz := d.stackSize in
let iniPos := d.pos in
let d := p s d in
if d.hasError && d.pos == iniPos then q s (d.restore iniSz iniPos) else d
@[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo :=
{ updateTokens := q.updateTokens β p.updateTokens,
firstTokens := p.firstTokens ++ q.firstTokens }
@[inline] def tryFn (p : ParserFn) : ParserFn
| s d :=
let iniSz := d.stackSize in
let iniPos := d.pos in
match p s d with
| β¨stack, _, cache, some msgβ© := β¨stack.shrink iniSz, iniPos, cache, some msgβ©
| other := other
@[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo :=
{ updateTokens := info.updateTokens,
firstTokens := [] }
@[inline] def optionalFn (p : ParserFn) : ParserFn :=
Ξ» s d,
let iniSz := d.stackSize in
let iniPos := d.pos in
let d := p s d in
let d := if d.hasError then d.restore iniSz iniPos else d in
d.mkNode nullKind iniSz
def ParserData.mkError (d : ParserData) (msg : String) : ParserData :=
match d with
| β¨stack, pos, cache, _β© := β¨stack, pos, cache, some msgβ©
def ParserData.mkEOIError (d : ParserData) : ParserData :=
d.mkError "end of input"
def ParserData.mkErrorAt (d : ParserData) (msg : String) (pos : String.Pos) : ParserData :=
match d with
| β¨stack, _, cache, _β© := β¨stack, pos, cache, some msgβ©
@[specialize] partial def manyAux (p : ParserFn) : String β ParserData β ParserData
| s d :=
let iniSz := d.stackSize in
let iniPos := d.pos in
let d := p s d in
if d.hasError then d.restore iniSz iniPos
else if iniPos == d.pos then d.mkError "invalid 'many' parser combinator application, parser did not consume anything"
else manyAux s d
@[inline] def manyFn (p : ParserFn) : ParserFn
| s d :=
let iniSz := d.stackSize in
let d := manyAux p s d in
d.mkNode nullKind iniSz
@[specialize] private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) : Bool β ParserFn
| pOpt s d :=
let sz := d.stackSize in
let pos := d.pos in
let d := p s d in
if d.hasError then
let d := d.restore sz pos in
if pOpt then
d.mkNode nullKind iniSz
else
-- append `Syntax.missing` to make clear that List is incomplete
let d := d.pushSyntax Syntax.missing in
d.mkNode nullKind iniSz
else
let sz := d.stackSize in
let pos := d.pos in
let d := sep s d in
if d.hasError then
let d := d.restore sz pos in
d.mkNode nullKind iniSz
else
sepByFnAux allowTrailingSep s d
@[specialize] def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn
| s d :=
let iniSz := d.stackSize in
sepByFnAux p sep allowTrailingSep iniSz true s d
@[specialize] def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn
| s d :=
let iniSz := d.stackSize in
sepByFnAux p sep allowTrailingSep iniSz false s d
@[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo :=
{ updateTokens := sep.updateTokens β p.updateTokens,
firstTokens := [] }
@[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo :=
{ updateTokens := sep.updateTokens β p.updateTokens,
firstTokens := p.firstTokens }
@[specialize] partial def satisfyFn (p : Char β Bool) (errorMsg : String := "unexpected character") : ParserFn
| s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
if p c then d.next s i
else d.mkError errorMsg
@[specialize] partial def takeUntilFn (p : Char β Bool) : ParserFn
| s d :=
let i := d.pos in
if s.atEnd i then d
else
let c := s.get i in
if p c then d
else takeUntilFn s (d.next s i)
@[specialize] def takeWhileFn (p : Char β Bool) : ParserFn :=
takeUntilFn (Ξ» c, !p c)
@[inline] def takeWhile1Fn (p : Char β Bool) (errorMsg : String) : ParserFn :=
andthenFn (satisfyFn p errorMsg) (takeWhileFn p)
partial def finishCommentBlock : Nat β ParserFn
| nesting s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
let i := s.next i in
if c == '-' then
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
if c == '/' then -- "-/" end of comment
if nesting == 1 then d.next s i
else finishCommentBlock (nesting-1) s (d.next s i)
else
finishCommentBlock nesting s (d.next s i)
else if c == '/' then
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
if c == '-' then finishCommentBlock (nesting+1) s (d.next s i)
else finishCommentBlock nesting s (d.setPos i)
else finishCommentBlock nesting s (d.setPos i)
/- Consume whitespace and comments -/
partial def whitespace : ParserFn
| s d :=
let i := d.pos in
if s.atEnd i then d
else
let c := s.get i in
if c.isWhitespace then whitespace s (d.next s i)
else if c == '-' then
let i := s.next i in
let c := s.get i in
if c == '-' then andthenFn (takeUntilFn (= '\n')) whitespace s (d.next s i)
else d
else if c == '/' then
let i := s.next i in
let c := s.get i in
if c == '-' then
let i := s.next i in
let c := s.get i in
if c == '-' then d -- "/--" doc comment is an actual token
else andthenFn (finishCommentBlock 1) whitespace s (d.next s i)
else d
else d
def mkEmptySubstringAt (s : String) (p : Nat) : Substring :=
{str := s, startPos := p, stopPos := p }
private def rawAux (startPos : Nat) (trailingWs : Bool) : ParserFn
| s d :=
let stopPos := d.pos in
let leading := mkEmptySubstringAt s startPos in
let val := s.extract startPos stopPos in
if trailingWs then
let d := whitespace s d in
let stopPos' := d.pos in
let trailing : Substring := { str := s, startPos := stopPos, stopPos := stopPos' } in
let atom := Syntax.atom (some { leading := leading, pos := startPos, trailing := trailing }) val in
d.pushSyntax atom
else
let trailing := mkEmptySubstringAt s stopPos in
let atom := Syntax.atom (some { leading := leading, pos := startPos, trailing := trailing }) val in
d.pushSyntax atom
/-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/
@[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn
| s d :=
let startPos := d.pos in
let d := p s d in
if d.hasError then d else rawAux startPos trailingWs s d
def hexDigitFn : ParserFn
| s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
let i := s.next i in
if c.isDigit || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') then d.setPos i
else d.mkError "invalid hexadecimal numeral, hexadecimal digit expected"
def quotedCharFn : ParserFn
| s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
if c == '\\' || c == '\"' || c == '\'' || c == '\n' || c == '\t' then
d.next s i
else if c == 'x' then
andthenFn hexDigitFn hexDigitFn s (d.next s i)
else if c == 'u' then
andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) s (d.next s i)
else
d.mkError "invalid escape sequence"
def mkStrLitKind : IO SyntaxNodeKind := nextKind `strLit
@[init mkStrLitKind] constant strLitKind : SyntaxNodeKind := default _
/-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/
def mkNodeToken (k : SyntaxNodeKind) (startPos : Nat) (s : String) (d : ParserData) : ParserData :=
let stopPos := d.pos in
let leading := mkEmptySubstringAt s startPos in
let val := s.extract startPos stopPos in
let d := whitespace s d in
let wsStopPos := d.pos in
let trailing := { Substring . str := s, startPos := stopPos, stopPos := wsStopPos } in
let atom := Syntax.atom (some { leading := leading, pos := startPos, trailing := trailing }) val in
let tk := Syntax.node k (Array.singleton atom) [] in
d.pushSyntax tk
partial def strLitFnAux (startPos : Nat) : ParserFn
| s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
let d := d.setPos (s.next i) in
if c == '\"' then
mkNodeToken strLitKind startPos s d
else if c == '\\' then andthenFn quotedCharFn strLitFnAux s d
else strLitFnAux s d
def mkNumberKind : IO SyntaxNodeKind := nextKind `number
@[init mkNumberKind] constant numberKind : SyntaxNodeKind := default _
def decimalNumberFn (startPos : Nat) : ParserFn
| s d :=
let d := takeWhileFn (Ξ» c, c.isDigit) s d in
let i := d.pos in
let c := s.get i in
let d :=
if c == '.' then
let i := s.next i in
let c := s.get i in
if c.isDigit then
takeWhileFn (Ξ» c, c.isDigit) s (d.setPos i)
else
d
else
d in
mkNodeToken numberKind startPos s d
def binNumberFn (startPos : Nat) : ParserFn
| s d :=
let d := takeWhile1Fn (Ξ» c, c == '0' || c == '1') "expected binary number" s d in
mkNodeToken numberKind startPos s d
def octalNumberFn (startPos : Nat) : ParserFn
| s d :=
let d := takeWhile1Fn (Ξ» c, '0' β€ c && c β€ '7') "expected octal number" s d in
mkNodeToken numberKind startPos s d
def hexNumberFn (startPos : Nat) : ParserFn
| s d :=
let d := takeWhile1Fn (Ξ» c, ('0' β€ c && c β€ '9') || ('a' β€ c && c β€ 'f') || ('A' β€ c && c β€ 'F')) "expected hexadecimal number" s d in
mkNodeToken numberKind startPos s d
def numberFnAux : ParserFn
| s d :=
let startPos := d.pos in
if s.atEnd startPos then d.mkEOIError
else
let c := s.get startPos in
if c == '0' then
let i := s.next startPos in
let c := s.get i in
if c == 'b' || c == 'B' then
binNumberFn startPos s (d.next s i)
else if c == 'o' || c == 'O' then
octalNumberFn startPos s (d.next s i)
else if c == 'x' || c == 'X' then
hexNumberFn startPos s (d.next s i)
else
decimalNumberFn startPos s (d.setPos i)
else if c.isDigit then
decimalNumberFn startPos s (d.next s startPos)
else
d.mkError "expected numeral"
def isIdCont : String β ParserData β Bool
| s d :=
let i := d.pos in
let c := s.get i in
if c == '.' then
let i := s.next i in
if s.atEnd i then
false
else
let c := s.get i in
isIdFirst c || isIdBeginEscape c
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 - idStopPos
def mkTokenAndFixPos (startPos : Nat) (tk : Option TokenConfig) (s : String) (d : ParserData) : ParserData :=
match tk with
| none := d.mkErrorAt "token expected" startPos
| some tk :=
let leading := mkEmptySubstringAt s startPos in
let val := tk.val in
let stopPos := startPos + val.bsize in
let d := d.setPos stopPos in
let d := whitespace s d in
let wsStopPos := d.pos in
let trailing := { Substring . str := s, startPos := stopPos, stopPos := wsStopPos } in
let atom := Syntax.atom (some { leading := leading, pos := startPos, trailing := trailing }) val in
d.pushSyntax atom
def mkIdResult (startPos : Nat) (tk : Option TokenConfig) (val : Name) (s : String) (d : ParserData) : ParserData :=
let stopPos := d.pos in
if isToken startPos stopPos tk then
mkTokenAndFixPos startPos tk s d
else
let rawVal : Substring := { str := s, startPos := startPos, stopPos := stopPos } in
let d := whitespace s d in
let trailingStopPos := d.pos in
let leading := mkEmptySubstringAt s startPos in
let trailing : Substring := { str := s, startPos := stopPos, stopPos := trailingStopPos } in
let info : SourceInfo := {leading := leading, trailing := trailing, pos := startPos} in
let atom := Syntax.ident (some info) rawVal val [] [] in
d.pushSyntax atom
partial def identFnAux (startPos : Nat) (tk : Option TokenConfig) : Name β ParserFn
| r s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
if isIdBeginEscape c then
let startPart := s.next i in
let d := takeUntilFn isIdEndEscape s (d.setPos startPart) in
let stopPart := d.pos in
let d := satisfyFn isIdEndEscape "end of escaped identifier expected" s d in
if d.hasError then d
else
let r := Name.mkString r (s.extract startPart stopPart) in
if isIdCont s d then
identFnAux r s d
else
mkIdResult startPos tk r s d
else if isIdFirst c then
let startPart := i in
let d := takeWhileFn isIdRest s (d.next s i) in
let stopPart := d.pos in
let r := Name.mkString r (s.extract startPart stopPart) in
if isIdCont s d then
identFnAux r s d
else
mkIdResult startPart tk r s d
else
mkTokenAndFixPos startPos tk s d
def ParserData.keepNewError (d : ParserData) (oldStackSize : Nat) : ParserData :=
match d with
| β¨stack, pos, cache, errβ© := β¨stack.shrink oldStackSize, pos, cache, errβ©
def ParserData.keepPrevError (d : ParserData) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option String) : ParserData :=
match d with
| β¨stack, _, cache, _β© := β¨stack.shrink oldStackSize, oldStopPos, cache, oldErrorβ©
def ParserData.mergeErrors (d : ParserData) (oldStackSize : Nat) (oldError : String) : ParserData :=
match d with
| β¨stack, pos, cache, some errβ© := β¨stack.shrink oldStackSize, pos, cache, some (err ++ "; " ++ oldError)β©
| other := other
def ParserData.mkLongestNodeAlt (d : ParserData) (startSize : Nat) : ParserData :=
match d 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 d
else
-- parser created more than one node, combine them into a single node
let node := Syntax.node nullKind (stack.extract startSize stack.size) [] in
let stack := stack.shrink startSize in
β¨stack.push node, pos, cache, noneβ©
def ParserData.keepLatest (d : ParserData) (startStackSize : Nat) : ParserData :=
match d with
| β¨stack, pos, cache, _β© :=
let node := stack.back in
let stack := stack.shrink startStackSize in
let stack := stack.push node in
β¨stack, pos, cache, noneβ©
def ParserData.replaceLongest (d : ParserData) (startStackSize : Nat) (prevStackSize : Nat) : ParserData :=
let d := d.mkLongestNodeAlt prevStackSize in
d.keepLatest startStackSize
def longestMatchStep (startSize : Nat) (startPos : String.Pos) (p : ParserFn) : ParserFn :=
Ξ» s d,
let prevErrorMsg := d.errorMsg in
let prevStopPos := d.pos in
let prevSize := d.stackSize in
let d := d.restore prevSize startPos in
let d := p s d in
match prevErrorMsg, d.errorMsg with
| none, none := -- both succeeded
if d.pos > prevStopPos then d.replaceLongest startSize prevSize -- replace
else if d.pos < prevStopPos then d.restore prevSize prevStopPos -- keep prev
else d.mkLongestNodeAlt prevSize -- keep both
| none, some _ := -- prev succeeded, current failed
d.restore prevSize prevStopPos
| some oldError, some _ := -- both failed
if d.pos > prevStopPos then d.keepNewError prevSize
else if d.pos < prevStopPos then d.keepPrevError prevSize prevStopPos prevErrorMsg
else d.mergeErrors prevSize oldError
| some _, none := -- prev failed, current succeeded
d.mkLongestNodeAlt startSize
def longestMatchMkResult (startSize : Nat) (d : ParserData) : ParserData :=
if !d.hasError && d.stackSize > startSize + 1 then d.mkNode choiceKind startSize else d
def longestMatchFnAux (startSize : Nat) (startPos : String.Pos) : List ParserFn β ParserFn
| [] := Ξ» _ d, longestMatchMkResult startSize d
| (p::ps) := Ξ» s d,
let d := longestMatchStep startSize startPos p s d in
longestMatchFnAux ps s d
def longestMatchFnβ (p : ParserFn) : ParserFn :=
Ξ» s d,
let startSize := d.stackSize in
let d := p s d in
if d.hasError then d else d.mkLongestNodeAlt startSize
def longestMatchFnβ (p q : ParserFn) : ParserFn :=
Ξ» s d,
let startSize := d.stackSize in
let startPos := d.pos in
let d := p s d in
let d := if d.hasError then d.shrinkStack startSize else d.mkLongestNodeAlt startSize in
let d := longestMatchStep startSize startPos q s d in
longestMatchMkResult startSize d
def longestMatchFn : List ParserFn β ParserFn
| [] := Ξ» _ d, d.mkError "longest match: empty list"
| [p] := longestMatchFnβ p
| (p::ps) := Ξ» s d,
let startSize := d.stackSize in
let startPos := d.pos in
let d := p s d in
if d.hasError then
let d := d.shrinkStack startSize in
longestMatchFnAux startSize startPos ps s d
else
let d := d.mkLongestNodeAlt startSize in
longestMatchFnAux startSize startPos ps s d
structure AbsParser (Ο : Type) :=
(info : ParserInfo := {})
(fn : Ο)
abbrev Parser := AbsParser ParserFn
class ParserFnLift (Ο : Type) :=
(lift {} : ParserFn β Ο)
(map : (ParserFn β ParserFn) β Ο β Ο)
(mapβ : (ParserFn β ParserFn β ParserFn) β Ο β Ο β Ο)
(mapList : (List ParserFn β ParserFn) β List Ο β Ο)
instance parserLiftInhabited {Ο : Type} [ParserFnLift Ο] : Inhabited Ο :=
β¨ParserFnLift.lift (default _)β©
instance idParserLift : ParserFnLift ParserFn :=
{ lift := Ξ» p, p,
map := Ξ» m p, m p,
mapβ := Ξ» m p1 p2, m p1 p2,
mapList := Ξ» m ps, m ps }
@[inline]
def liftParser {Ο : Type} [ParserFnLift Ο] (info : ParserInfo) (fn : ParserFn) : AbsParser Ο :=
{ info := info, fn := ParserFnLift.lift fn }
@[inline]
def mapParser {Ο : Type} [ParserFnLift Ο] (infoFn : ParserInfo β ParserInfo) (pFn : ParserFn β ParserFn) : AbsParser Ο β AbsParser Ο :=
Ξ» p, { info := infoFn p.info, fn := ParserFnLift.map pFn p.fn }
@[inline]
def mapParserβ {Ο : Type} [ParserFnLift Ο] (infoFn : ParserInfo β ParserInfo β ParserInfo) (pFn : ParserFn β ParserFn β ParserFn)
: AbsParser Ο β AbsParser Ο β AbsParser Ο :=
Ξ» p q, { info := infoFn p.info q.info, fn := ParserFnLift.mapβ pFn p.fn q.fn }
def EnvParserFn (Ξ± : Type) (Ο : Type) :=
Ξ± β Ο
def RecParserFn (Ξ± Ο : Type) :=
EnvParserFn (Ξ± β Ο) Ο
instance envParserLift (Ξ± Ο : Type) [ParserFnLift Ο] : ParserFnLift (EnvParserFn Ξ± Ο) :=
{ lift := Ξ» p a, ParserFnLift.lift p,
map := Ξ» m p a, ParserFnLift.map m (p a),
mapβ := Ξ» m p1 p2 a, ParserFnLift.mapβ m (p1 a) (p2 a),
mapList := Ξ» m ps a, ParserFnLift.mapList m (ps.map (Ξ» p, p a)) }
instance recParserLift (Ξ± Ο : Type) [ParserFnLift Ο] : ParserFnLift (RecParserFn Ξ± Ο) :=
inferInstanceAs (ParserFnLift (EnvParserFn (Ξ± β Ο) Ο))
namespace RecParserFn
variables {Ξ± Ο : Type}
@[inline] def recurse (a : Ξ±) : RecParserFn Ξ± Ο :=
Ξ» p, p a
@[inline] def run [ParserFnLift Ο] (x : RecParserFn Ξ± Ο) (rec : Ξ± β RecParserFn Ξ± Ο) : Ο :=
x (fix (Ξ» f a, rec a f))
end RecParserFn
@[inline] def andthen {Ο : Type} [ParserFnLift Ο] : AbsParser Ο β AbsParser Ο β AbsParser Ο :=
mapParserβ andthenInfo andthenFn
instance absParserAndthen {Ο : Type} [ParserFnLift Ο] : HasAndthen (AbsParser Ο) :=
β¨andthenβ©
@[inline] def node {Ο : Type} [ParserFnLift Ο] (k : SyntaxNodeKind) : AbsParser Ο β AbsParser Ο :=
mapParser nodeInfo (nodeFn k)
@[inline] def orelse {Ο : Type} [ParserFnLift Ο] : AbsParser Ο β AbsParser Ο β AbsParser Ο :=
mapParserβ orelseInfo orelseFn
instance absParserHasOrelse {Ο : Type} [ParserFnLift Ο] : HasOrelse (AbsParser Ο) :=
β¨orelseβ©
@[inline] def try {Ο : Type} [ParserFnLift Ο] : AbsParser Ο β AbsParser Ο :=
mapParser noFirstTokenInfo tryFn
@[inline] def many {Ο : Type} [ParserFnLift Ο] : AbsParser Ο β AbsParser Ο :=
mapParser noFirstTokenInfo manyFn
@[inline] def optional {Ο : Type} [ParserFnLift Ο] : AbsParser Ο β AbsParser Ο :=
mapParser noFirstTokenInfo optionalFn
@[inline] def many1 {Ο : Type} [ParserFnLift Ο] (p : AbsParser Ο) : AbsParser Ο :=
andthen p (many p)
@[inline] def sepBy {Ο : Type} [ParserFnLift Ο] (p sep : AbsParser Ο) (allowTrailingSep : Bool := false) : AbsParser Ο :=
mapParserβ sepByInfo (sepByFn allowTrailingSep) p sep
@[inline] def sepBy1 {Ο : Type} [ParserFnLift Ο] (p sep : AbsParser Ο) (allowTrailingSep : Bool := false) : AbsParser Ο :=
mapParserβ sepBy1Info (sepBy1Fn allowTrailingSep) p sep
def longestMatchInfo {Ο : Type} (ps : List (AbsParser Ο)) : ParserInfo :=
{ updateTokens := Ξ» trie, ps.foldl (Ξ» trie p, p.info.updateTokens trie) trie,
firstTokens := ps.foldl (Ξ» tks p, p.info.firstTokens ++ tks) [] }
def liftLongestMatchFn {Ο : Type} [ParserFnLift Ο] : List (AbsParser Ο) β Ο
| [] := ParserFnLift.lift (longestMatchFn [])
| [p] := ParserFnLift.map longestMatchFnβ p.fn
| [p, q] := ParserFnLift.mapβ longestMatchFnβ p.fn q.fn
| ps := ParserFnLift.mapList longestMatchFn (ps.map (Ξ» p, p.fn))
@[inline] def longestMatch {Ο : Type} [ParserFnLift Ο] (ps : List (AbsParser Ο)) : AbsParser Ο :=
{ info := longestMatchInfo ps,
fn := liftLongestMatchFn ps }
abbrev BasicParserFn : Type := EnvParserFn ParserConfig ParserFn
abbrev BasicParser : Type := AbsParser BasicParserFn
abbrev CmdParserFn (Ο : Type) : Type := EnvParserFn Ο (RecParserFn Unit ParserFn)
abbrev TermParserFn : Type := RecParserFn Nat (CmdParserFn ParserConfig)
abbrev TermParser : Type := AbsParser TermParserFn
abbrev TrailingTermParserFn : Type := EnvParserFn Syntax TermParserFn
abbrev TrailingTermParser : Type := AbsParser TrailingTermParserFn
structure TermParsingTables :=
(leadingTermParsers : TokenMap TermParserFn)
(trailingTermParsers : TokenMap TrailingTermParserFn)
-- local Term parsers (such as from `local notation`) hide previous parsers instead of overloading them
(localLeadingTermParsers : TokenMap TermParserFn := RBMap.empty)
(localTrailingTermParsers : TokenMap TrailingTermParserFn := RBMap.empty)
structure CommandParserConfig extends ParserConfig :=
(pTables : TermParsingTables)
abbrev CommandParserFn : Type := CmdParserFn CommandParserConfig
abbrev CommandParser : Type := AbsParser CommandParserFn
@[inline] def Term.parser (rbp : Nat := 0) : TermParser :=
{ fn := RecParserFn.recurse rbp }
@[inline] def Command.parser : CommandParser :=
{ fn := Ξ» _, RecParserFn.recurse () }
@[inline] def basicParser2TermParser (p : BasicParser) : TermParser :=
{ info := p.info, fn := Ξ» _ cfg _, p.fn cfg }
instance basic2term : HasCoe BasicParser TermParser :=
β¨basicParser2TermParserβ©
@[inline] def basicParser2CmdParser (p : BasicParser) : CommandParser :=
{ info := p.info, fn := Ξ» cfg _, p.fn cfg.toParserConfig }
instance basicmd : HasCoe BasicParser CommandParser :=
β¨basicParser2CmdParserβ©
private def tokenFnAux : BasicParserFn
| cfg s d :=
let i := d.pos in
let c := s.get i in
if c == '\"' then
strLitFnAux i s (d.next s i)
else if c.isDigit then
numberFnAux s d
else
let (_, tk) := cfg.tokens.matchPrefix s i in
identFnAux i tk Name.anonymous s d
private def updateCache (startPos : Nat) (d : ParserData) : ParserData :=
match d with
| β¨stack, pos, cache, noneβ© :=
if stack.size == 0 then d
else
let tk := stack.back in
β¨stack, pos, { tokenCache := some { startPos := startPos, stopPos := pos, token := tk } }, noneβ©
| other := other
def tokenFn : BasicParserFn
| cfg s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
match d.cache with
| { tokenCache := some tkc } :=
if tkc.startPos == i then
let d := d.pushSyntax tkc.token in
d.setPos tkc.stopPos
else
let d := tokenFnAux cfg s d in
updateCache i d
| _ :=
let d := tokenFnAux cfg s d in
updateCache i d
@[inline] def satisfySymbolFn (p : String β Bool) (errorMsg : String) : BasicParserFn
| cfg s d :=
let startPos := d.pos in
let d := tokenFn cfg s d in
if d.hasError then
d.mkErrorAt errorMsg startPos
else
match d.stxStack.back with
| Syntax.atom _ sym := if p sym then d else d.mkErrorAt errorMsg startPos
| _ := d.mkErrorAt errorMsg startPos
def symbolFnAux (sym : String) (errorMsg : String) : BasicParserFn :=
satisfySymbolFn (== sym) errorMsg
@[inline] def symbolFn (sym : String) : BasicParserFn :=
symbolFnAux sym ("expected '" ++ sym ++ "'")
def symbolInfo (sym : String) (lbp : Nat) : ParserInfo :=
{ updateTokens := Ξ» trie, trie.insert sym { val := sym, lbp := lbp },
firstTokens := [ { val := sym, lbp := lbp } ] }
@[inline] def symbol (sym : String) (lbp : Nat := 0) : BasicParser :=
{ info := symbolInfo sym lbp,
fn := symbolFn sym }
def unicodeSymbolFnAux (sym asciiSym : String) (errorMsg : String) : BasicParserFn :=
satisfySymbolFn (Ξ» s, s == sym || s == asciiSym) errorMsg
@[inline] def unicodeSymbolFn (sym asciiSym : String) : BasicParserFn :=
unicodeSymbolFnAux sym asciiSym ("expected '" ++ sym ++ "' or '" ++ asciiSym ++ "'")
def unicodeSymbolInfo (sym asciiSym : String) (lbp : Nat) : ParserInfo :=
{ updateTokens := Ξ» trie,
let trie := trie.insert sym { val := sym, lbp := lbp } in
trie.insert sym { val := asciiSym, lbp := lbp },
firstTokens := [ { val := sym, lbp := lbp },
{ val := asciiSym, lbp := lbp } ] }
@[inline] def unicodeSymbol (sym asciiSym : String) (lbp : Nat := 0) : BasicParser :=
{ info := unicodeSymbolInfo sym asciiSym lbp,
fn := unicodeSymbolFn sym asciiSym }
def numberFn : BasicParserFn
| cfg s d :=
let d := tokenFn cfg s d in
if d.hasError || !(d.stxStack.back.isOfKind numberKind) then
d.mkError "expected numeral"
else
d
@[inline] def number : BasicParser :=
{ fn := numberFn }
def strLitFn : BasicParserFn
| cfg s d :=
let d := tokenFn cfg s d in
if d.hasError || !(d.stxStack.back.isOfKind strLitKind) then
d.mkError "expected string literal"
else
d
@[inline] def strLit : BasicParser :=
{ fn := numberFn }
def identFn : BasicParserFn
| cfg s d :=
let d := tokenFn cfg s d in
if d.hasError || !(d.stxStack.back.isIdent) then
d.mkError "expected identifier"
else
d
@[inline] def ident : BasicParser :=
{ fn := identFn }
instance string2basic : HasCoe String BasicParser :=
β¨symbolβ©
def mkFrontendConfig (filename input : String) : FrontendConfig :=
{ filename := filename,
input := input,
fileMap := input.toFileMap }
def BasicParser.run (p : BasicParser) (input : String) (filename : String := "<input>") : Except String Syntax :=
let frontendCfg := mkFrontendConfig filename input in
let tokens := p.info.updateTokens {} in
let cfg : ParserConfig := { tokens := tokens, .. frontendCfg } in
let d : ParserData := { stxStack := Array.empty, pos := 0, cache := {}, errorMsg := none } in
let d := p.fn cfg input d in
if d.hasError then
Except.error (d.toErrorMsg cfg)
else
Except.ok d.stxStack.back
-- Helper function for testing (non-recursive) term parsers
def TermParser.test (p : TermParser) (input : String) (filename : String := "<input>") : Except String Syntax :=
let frontendCfg := mkFrontendConfig filename input in
let tokens := p.info.updateTokens {} in
let cfg : ParserConfig := { tokens := tokens, .. frontendCfg } in
let d : ParserData := { stxStack := Array.empty, pos := 0, cache := {}, errorMsg := none } in
let dummyCmdParser : Unit β ParserFn := Ξ» _ _ d, d.mkError "no command parser" in
let dummyTermParser : β β CmdParserFn ParserConfig := Ξ» _ _ _ _ d, d.mkError "no term parser" in
let d := p.fn dummyTermParser cfg dummyCmdParser input d in
if d.hasError then
Except.error (d.toErrorMsg cfg)
else
Except.ok d.stxStack.back
-- Stopped here
@[noinline] def termPrattParser (tbl : TermParsingTables) (rbp : Nat) : TermParserFn :=
Ξ» g, g 0 -- TODO(Leo)
@[specialize] def TermParserFn.run (p : TermParserFn) : CommandParserFn
| cfg r s d :=
let p := RecParserFn.run p (termPrattParser cfg.pTables) in
p cfg.toParserConfig r s d
def parseExpr (rbp : Nat) : CommandParserFn :=
TermParserFn.run (RecParserFn.recurse rbp)
end Parser
-- end Lean
|
0c76b7e0c6aaefc901eaf00dcf556b95edf748e0 | 4b846d8dabdc64e7ea03552bad8f7fa74763fc67 | /library/tools/super/demod.lean | 4d5f4125075f4320a2068792fff19dc583e97f4e | [
"Apache-2.0"
] | permissive | pacchiano/lean | 9324b33f3ac3b5c5647285160f9f6ea8d0d767dc | fdadada3a970377a6df8afcd629a6f2eab6e84e8 | refs/heads/master | 1,611,357,380,399 | 1,489,870,101,000 | 1,489,870,101,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,189 | lean | /-
Copyright (c) 2017 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .superposition
open tactic monad expr
namespace super
meta def is_demodulator (c : clause) : bool :=
match c^.get_lits with
| [clause.literal.right eqn] := eqn^.is_eq^.is_some
| _ := ff
end
variable gt : expr β expr β bool
meta def demod' (cs1 : list derived_clause) : clause β list derived_clause β tactic (list derived_clause Γ clause) | c2 used_demods :=
(first $ do
i β list.range c2^.num_lits,
pos β rwr_positions c2 i,
c1 β cs1,
(ltr, congr_ax) β [(tt, ``super.sup_ltr), (ff, ``super.sup_rtl)],
[do c2' β try_sup gt c1^.c c2 0 i pos ltr tt congr_ax,
demod' c2' (c1 :: used_demods)]
) <|> return (used_demods, c2)
meta def demod (cs1 : list derived_clause) (c2 : clause) : tactic (list derived_clause Γ clause) := do
c2qf β c2^.open_constn c2^.num_quants,
(used_demods, c2qf') β demod' gt cs1 c2qf.1 [],
if used_demods^.empty then return ([], c2) else
return (used_demods, c2qf'^.close_constn c2qf.2)
meta def demod_fwd_inf : inference :=
take given, do
active β get_active,
demods β return (do ac β active^.values, guard $ is_demodulator ac^.c, guard $ ac^.id β given^.id, [ac]),
if demods^.empty then skip else do
(used_demods, given') β demod gt demods given^.c,
if used_demods^.empty then skip else do
remove_redundant given^.id used_demods,
mk_derived given' given^.sc^.sched_now >>= add_inferred
meta def demod_back1 (given active : derived_clause) : prover unit := do
(used_demods, c') β demod gt [given] active^.c,
if used_demods^.empty then skip else do
remove_redundant active^.id used_demods,
mk_derived c' active^.sc^.sched_now >>= add_inferred
meta def demod_back_inf : inference :=
take given, if Β¬is_demodulator given^.c then skip else
do active β get_active, sequence' $ do
ac β active^.values,
guard $ ac^.id β given^.id,
[demod_back1 gt given ac]
@[super.inf]
meta def demod_inf : inf_decl := {
prio := 10,
inf := take given, do
gt β get_term_order,
demod_fwd_inf gt given,
demod_back_inf gt given,
skip
}
end super
|
c05015294dd7a0d2b5e1ad5e2337b055f06b8ee1 | 1fd908b06e3f9c1252cb2285ada1102623a67f72 | /hit/trunc.lean | b224852086337769cb192695bd3339ffd382b97c | [
"Apache-2.0"
] | permissive | avigad/hott3 | 609a002849182721e7c7ae536d9f1e2956d6d4d3 | f64750cd2de7a81e87d4828246d1369d59f16f43 | refs/heads/master | 1,629,027,243,322 | 1,510,946,717,000 | 1,510,946,717,000 | 103,570,461 | 0 | 0 | null | 1,505,415,620,000 | 1,505,415,620,000 | null | UTF-8 | Lean | false | false | 5,989 | lean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
n-truncation of types.
Ported from Coq HoTT
-/
/- The hit n-truncation is primitive, declared in init.hit. -/
import types.sigma types.pointed
universes u v w
hott_theory
namespace hott
open hott.is_trunc hott.eq hott.equiv hott.is_equiv function prod sum sigma
namespace trunc
@[hott, induction, priority 1500] protected def elim {n : βββ} {A : Type _} {P : Type _}
[Pt : is_trunc n P] (H : A β P) : trunc n A β P :=
trunc.rec H
@[hott] protected def elim_on {n : βββ} {A : Type _} {P : Type _} (aa : trunc n A)
[Pt : is_trunc n P] (H : A β P) : P :=
trunc.elim H aa
variables {X : Type _} {Y : Type _} {Z : Type _} {P : X β Type _} {m : βββ} (n : βββ) (A : Type _) (B : Type _)
@[hott] def untrunc_of_is_trunc [H : is_trunc m X] : trunc m X β X :=
trunc.rec id
variables (A n)
@[hott, instance] def is_equiv_tr [H : is_trunc n A] : is_equiv (@tr n A) :=
adjointify _
(untrunc_of_is_trunc)
(Ξ»aa, trunc.rec_on aa (Ξ»a, idp))
(Ξ»a, idp)
@[hott] def trunc_equiv [H : is_trunc n A] : trunc n A β A :=
(equiv.mk tr (is_equiv_tr n A))β»ΒΉα΅
@[hott] def is_trunc_of_is_equiv_tr [H : is_equiv (@tr n A)] : is_trunc n A :=
is_trunc_is_equiv_closed_rev n (@tr n A) (by infer)
/- Functoriality -/
@[hott] def trunc_functor (f : X β Y) : trunc n X β trunc n Y :=
Ξ»xx, trunc.rec_on xx (Ξ»x, tr (f x))
@[hott] def trunc_functor_compose (f : X β Y) (g : Y β Z)
: trunc_functor n (g β f) ~ trunc_functor n g β trunc_functor n f :=
Ξ»xx, trunc.rec_on xx (Ξ»x, idp)
@[hott] def trunc_functor_id : trunc_functor n (@id A) ~ id :=
Ξ»xx, trunc.rec_on xx (Ξ»x, idp)
@[hott] def trunc_functor_cast {X Y : Type _} (n : βββ) (p : X = Y) :
trunc_functor n (cast p) ~ cast (ap (trunc n) p) :=
begin
intro x, hinduction x using trunc.rec with x,
exact fn_tr_eq_tr_fn p (Ξ»y, tr) x β¬ tr_eq_cast_ap _ _
end
@[hott] def is_equiv_trunc_functor (f : X β Y) [H : is_equiv f]
: is_equiv (trunc_functor n f) :=
adjointify _
(trunc_functor n fβ»ΒΉαΆ )
(Ξ»yy, trunc.rec_on yy (Ξ»y, ap tr (right_inv _ _)))
(Ξ»xx, trunc.rec_on xx (Ξ»x, ap tr (left_inv _ _)))
@[hott] def trunc_homotopy {f g : X β Y} (p : f ~ g) : trunc_functor n f ~ trunc_functor n g :=
Ξ»xx, trunc.rec_on xx (Ξ»x, ap tr (p x))
section
@[hott] def trunc_equiv_trunc (f : X β Y) : trunc n X β trunc n Y :=
equiv.mk _ (is_equiv_trunc_functor n f)
end
section
@[hott] def trunc_prod_equiv : trunc n (X Γ Y) β trunc n X Γ trunc n Y :=
begin
fapply equiv.MK,
{ exact (Ξ»pp, trunc.rec_on pp (Ξ»p, (tr p.1, tr p.2))) },
{ intro p, induction p with xx yy,
hinduction xx with x, hinduction yy with y, exact tr (x,y) },
{ intro p, induction p with xx yy,
hinduction xx with x, hinduction yy with y, refl },
{ intro pp, hinduction pp with p, induction p, refl }
end
end
/- Propositional truncation -/
@[hott] def ttrunc (n : βββ) (X : Type _) : n-Type :=
trunctype.mk (trunc n X) (by infer)
@[hott, hsimp] def carrier_ttrunc (n : βββ) (X : Type _) : @coe_sort _ (hott.has_coe_to_sort n) (ttrunc n X) = trunc n X :=
by refl
@[hott, reducible] def merely (A : Type _) : Prop := ttrunc -1 A
notation `β₯`:max A `β₯`:0 := merely A
@[hott, reducible] def Exists (P : X β Type _) : Prop := β₯ sigma P β₯
@[hott, reducible] def or (A B : Type _) : Prop := β₯ A β B β₯
hott_theory_cmd "local notation `exists` binders `,` r:(scoped P, hott.trunc.Exists P) := r"
hott_theory_cmd "local notation `β` binders `,` r:(scoped P, Exists P) := r"
hott_theory_cmd "local notation A ` \\/ ` B := or A B"
hott_theory_cmd "local notation A β¨ B := or A B"
@[hott, reducible] def merely.intro (a : A) : β₯ A β₯ := tr a
@[hott, reducible] def exists.intro (x : X) (p : P x) : βx, P x := tr β¨x, pβ©
@[hott, reducible] def or.intro_left (x : X) : X β¨ Y := tr (inl x)
@[hott, reducible] def or.intro_right (y : Y) : X β¨ Y := tr (inr y)
@[hott, induction] def merely.rec {A : Type u} {P : β₯Aβ₯ β Type v} [Pt : Ξ (aa : β₯Aβ₯), is_prop (P aa)]
(H : Ξ (a : A), P (tr a)) (x : β₯Aβ₯) : P x :=
begin dsimp [merely] at x, hinduction x with a, exact H a end
@[hott, induction] def exists.elim {A : Type _} {p : A β Type _} {B : Type _} [is_prop B] (H : Exists p)
(H' : β (a : A), p a β B) : B :=
begin hinduction H with x, induction x with a x, exact H' a x end
@[hott] def is_contr_of_merely_prop [H : is_prop A] (aa : merely A) : is_contr A :=
is_contr_of_inhabited_prop (trunc.rec_on aa id)
@[hott] def trunc_sigma_equiv : trunc n (Ξ£ x, P x) β trunc n (Ξ£ x, trunc n (P x)) :=
begin
fapply equiv.MK; intro x,
{ hinduction x with p, exact tr β¨p.1, tr p.2β© },
{ hinduction x with p, induction p with a p, hinduction p with p, exact tr β¨a, pβ© },
{ hinduction x with p, induction p with a p, hinduction p with p, refl },
{ hinduction x with p, induction p with a p, refl }
end
@[hott] def trunc_sigma_equiv_of_is_trunc [H : is_trunc n X]
: trunc n (Ξ£ x, P x) β Ξ£ x, trunc n (P x) :=
calc
trunc n (Ξ£ x, P x) β trunc n (Ξ£ x, trunc n (P x)) : trunc_sigma_equiv _
... β Ξ£ x, trunc n (P x) : trunc_equiv _ _
/- the (non-dependent) universal property -/
@[hott] def trunc_arrow_equiv [H : is_trunc n B] :
(trunc n A β B) β (A β B) :=
begin
fapply equiv.MK,
{ intros g a, exact g (tr a) },
{ intros f x, hinduction x with a, exact f a },
{ intro f, apply eq_of_homotopy, intro a, refl },
{ intro g, apply eq_of_homotopy, intro x, hinduction x, refl },
end
end trunc
end hott |
06d004ae4bff420ab9be722fbb39b999703171f9 | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /src/Init/Prelude.lean | 438b61e9d2e902f63c3c9d3e759a82f047d74f5b | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 76,926 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
universe u v w
@[inline] def id {Ξ± : Sort u} (a : Ξ±) : Ξ± := a
abbrev Function.comp {Ξ± : Sort u} {Ξ² : Sort v} {Ξ΄ : Sort w} (f : Ξ² β Ξ΄) (g : Ξ± β Ξ²) : Ξ± β Ξ΄ :=
fun x => f (g x)
abbrev Function.const {Ξ± : Sort u} (Ξ² : Sort v) (a : Ξ±) : Ξ² β Ξ± :=
fun x => a
set_option checkBinderAnnotations false in
@[reducible] def inferInstance {Ξ± : Sort u} [i : Ξ±] : Ξ± := i
set_option checkBinderAnnotations false in
@[reducible] def inferInstanceAs (Ξ± : Sort u) [i : Ξ±] : Ξ± := i
set_option bootstrap.inductiveCheckResultingUniverse false in
inductive PUnit : Sort u where
| unit : PUnit
/-- An abbreviation for `PUnit.{0}`, its most common instantiation.
This Type should be preferred over `PUnit` where possible to avoid
unnecessary universe parameters. -/
abbrev Unit : Type := PUnit
@[matchPattern] abbrev Unit.unit : Unit := PUnit.unit
/-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/
unsafe axiom lcProof {Ξ± : Prop} : Ξ±
/-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/
unsafe axiom lcUnreachable {Ξ± : Sort u} : Ξ±
inductive True : Prop where
| intro : True
inductive False : Prop
inductive Empty : Type
set_option bootstrap.inductiveCheckResultingUniverse false in
inductive PEmpty : Sort u where
def Not (a : Prop) : Prop := a β False
@[macroInline] def False.elim {C : Sort u} (h : False) : C :=
False.rec (fun _ => C) h
@[macroInline] def absurd {a : Prop} {b : Sort v} (hβ : a) (hβ : Not a) : b :=
False.elim (hβ hβ)
inductive Eq {Ξ± : Sort u} (a : Ξ±) : Ξ± β Prop where
| refl {} : Eq a a
@[simp] abbrev Eq.ndrec.{u1, u2} {Ξ± : Sort u2} {a : Ξ±} {motive : Ξ± β Sort u1} (m : motive a) {b : Ξ±} (h : Eq a b) : motive b :=
Eq.rec (motive := fun Ξ± _ => motive Ξ±) m h
@[matchPattern] def rfl {Ξ± : Sort u} {a : Ξ±} : Eq a a := Eq.refl a
@[simp] theorem id_eq (a : Ξ±) : Eq (id a) a := rfl
theorem Eq.subst {Ξ± : Sort u} {motive : Ξ± β Prop} {a b : Ξ±} (hβ : Eq a b) (hβ : motive a) : motive b :=
Eq.ndrec hβ hβ
theorem Eq.symm {Ξ± : Sort u} {a b : Ξ±} (h : Eq a b) : Eq b a :=
h βΈ rfl
theorem Eq.trans {Ξ± : Sort u} {a b c : Ξ±} (hβ : Eq a b) (hβ : Eq b c) : Eq a c :=
hβ βΈ hβ
@[macroInline] def cast {Ξ± Ξ² : Sort u} (h : Eq Ξ± Ξ²) (a : Ξ±) : Ξ² :=
Eq.rec (motive := fun Ξ± _ => Ξ±) a h
theorem congrArg {Ξ± : Sort u} {Ξ² : Sort v} {aβ aβ : Ξ±} (f : Ξ± β Ξ²) (h : Eq aβ aβ) : Eq (f aβ) (f aβ) :=
h βΈ rfl
theorem congr {Ξ± : Sort u} {Ξ² : Sort v} {fβ fβ : Ξ± β Ξ²} {aβ aβ : Ξ±} (hβ : Eq fβ fβ) (hβ : Eq aβ aβ) : Eq (fβ aβ) (fβ aβ) :=
hβ βΈ hβ βΈ rfl
theorem congrFun {Ξ± : Sort u} {Ξ² : Ξ± β Sort v} {f g : (x : Ξ±) β Ξ² x} (h : Eq f g) (a : Ξ±) : Eq (f a) (g a) :=
h βΈ rfl
/-
Initialize the Quotient Module, which effectively adds the following definitions:
constant Quot {Ξ± : Sort u} (r : Ξ± β Ξ± β Prop) : Sort u
constant Quot.mk {Ξ± : Sort u} (r : Ξ± β Ξ± β Prop) (a : Ξ±) : Quot r
constant Quot.lift {Ξ± : Sort u} {r : Ξ± β Ξ± β Prop} {Ξ² : Sort v} (f : Ξ± β Ξ²) :
(β a b : Ξ±, r a b β Eq (f a) (f b)) β Quot r β Ξ²
constant Quot.ind {Ξ± : Sort u} {r : Ξ± β Ξ± β Prop} {Ξ² : Quot r β Prop} :
(β a : Ξ±, Ξ² (Quot.mk r a)) β β q : Quot r, Ξ² q
-/
init_quot
inductive HEq {Ξ± : Sort u} (a : Ξ±) : {Ξ² : Sort u} β Ξ² β Prop where
| refl {} : HEq a a
@[matchPattern] protected def HEq.rfl {Ξ± : Sort u} {a : Ξ±} : HEq a a :=
HEq.refl a
theorem eq_of_heq {Ξ± : Sort u} {a a' : Ξ±} (h : HEq a a') : Eq a a' :=
have : (Ξ± Ξ² : Sort u) β (a : Ξ±) β (b : Ξ²) β HEq a b β (h : Eq Ξ± Ξ²) β Eq (cast h a) b :=
fun Ξ± Ξ² a b hβ =>
HEq.rec (motive := fun {Ξ²} (b : Ξ²) (h : HEq a b) => (hβ : Eq Ξ± Ξ²) β Eq (cast hβ a) b)
(fun (hβ : Eq Ξ± Ξ±) => rfl)
hβ
this Ξ± Ξ± a a' h rfl
structure Prod (Ξ± : Type u) (Ξ² : Type v) where
fst : Ξ±
snd : Ξ²
attribute [unbox] Prod
/-- Similar to `Prod`, but `Ξ±` and `Ξ²` can be propositions.
We use this Type internally to automatically generate the brecOn recursor. -/
structure PProd (Ξ± : Sort u) (Ξ² : Sort v) where
fst : Ξ±
snd : Ξ²
/-- Similar to `Prod`, but `Ξ±` and `Ξ²` are in the same universe. -/
structure MProd (Ξ± Ξ² : Type u) where
fst : Ξ±
snd : Ξ²
structure And (a b : Prop) : Prop where
intro :: (left : a) (right : b)
inductive Or (a b : Prop) : Prop where
| inl (h : a) : Or a b
| inr (h : b) : Or a b
theorem Or.intro_left (b : Prop) (h : a) : Or a b :=
Or.inl h
theorem Or.intro_right (a : Prop) (h : b) : Or a b :=
Or.inr h
theorem Or.elim {c : Prop} (h : Or a b) (left : a β c) (right : b β c) : c :=
match h with
| Or.inl h => left h
| Or.inr h => right h
inductive Bool : Type where
| false : Bool
| true : Bool
export Bool (false true)
/- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/
structure Subtype {Ξ± : Sort u} (p : Ξ± β Prop) where
val : Ξ±
property : p val
/-- Gadget for optional parameter support. -/
@[reducible] def optParam (Ξ± : Sort u) (default : Ξ±) : Sort u := Ξ±
/-- Gadget for marking output parameters in type classes. -/
@[reducible] def outParam (Ξ± : Sort u) : Sort u := Ξ±
/-- Auxiliary Declaration used to implement the notation (a : Ξ±) -/
@[reducible] def typedExpr (Ξ± : Sort u) (a : Ξ±) : Ξ± := a
/-- Auxiliary Declaration used to implement the named patterns `x@p` -/
@[reducible] def namedPattern {Ξ± : Sort u} (x a : Ξ±) : Ξ± := a
/- Auxiliary axiom used to implement `sorry`. -/
@[extern "lean_sorry", neverExtract]
axiom sorryAx (Ξ± : Sort u) (synthetic := true) : Ξ±
theorem eq_false_of_ne_true : {b : Bool} β Not (Eq b true) β Eq b false
| true, h => False.elim (h rfl)
| false, h => rfl
theorem eq_true_of_ne_false : {b : Bool} β Not (Eq b false) β Eq b true
| true, h => rfl
| false, h => False.elim (h rfl)
theorem ne_false_of_eq_true : {b : Bool} β Eq b true β Not (Eq b false)
| true, _ => fun h => Bool.noConfusion h
| false, h => Bool.noConfusion h
theorem ne_true_of_eq_false : {b : Bool} β Eq b false β Not (Eq b true)
| true, h => Bool.noConfusion h
| false, _ => fun h => Bool.noConfusion h
class Inhabited (Ξ± : Sort u) where
mk {} :: (default : Ξ±)
constant arbitrary [Inhabited Ξ±] : Ξ± :=
Inhabited.default
instance : Inhabited (Sort u) where
default := PUnit
instance (Ξ± : Sort u) {Ξ² : Sort v} [Inhabited Ξ²] : Inhabited (Ξ± β Ξ²) where
default := fun _ => arbitrary
instance (Ξ± : Sort u) {Ξ² : Ξ± β Sort v} [(a : Ξ±) β Inhabited (Ξ² a)] : Inhabited ((a : Ξ±) β Ξ² a) where
default := fun _ => arbitrary
deriving instance Inhabited for Bool
/-- Universe lifting operation from Sort to Type -/
structure PLift (Ξ± : Sort u) : Type u where
up :: (down : Ξ±)
/- Bijection between Ξ± and PLift Ξ± -/
theorem PLift.up_down {Ξ± : Sort u} : β (b : PLift Ξ±), Eq (up (down b)) b
| up a => rfl
theorem PLift.down_up {Ξ± : Sort u} (a : Ξ±) : Eq (down (up a)) a :=
rfl
/- Pointed types -/
structure PointedType where
(type : Type u)
(val : type)
instance : Inhabited PointedType.{u} where
default := { type := PUnit.{u+1}, val := β¨β© }
/-- Universe lifting operation -/
structure ULift.{r, s} (Ξ± : Type s) : Type (max s r) where
up :: (down : Ξ±)
/- Bijection between Ξ± and ULift.{v} Ξ± -/
theorem ULift.up_down {Ξ± : Type u} : β (b : ULift.{v} Ξ±), Eq (up (down b)) b
| up a => rfl
theorem ULift.down_up {Ξ± : Type u} (a : Ξ±) : Eq (down (up.{v} a)) a :=
rfl
class inductive Decidable (p : Prop) where
| isFalse (h : Not p) : Decidable p
| isTrue (h : p) : Decidable p
@[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool :=
Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true)
export Decidable (isTrue isFalse decide)
abbrev DecidablePred {Ξ± : Sort u} (r : Ξ± β Prop) :=
(a : Ξ±) β Decidable (r a)
abbrev DecidableRel {Ξ± : Sort u} (r : Ξ± β Ξ± β Prop) :=
(a b : Ξ±) β Decidable (r a b)
abbrev DecidableEq (Ξ± : Sort u) :=
(a b : Ξ±) β Decidable (Eq a b)
def decEq {Ξ± : Sort u} [s : DecidableEq Ξ±] (a b : Ξ±) : Decidable (Eq a b) :=
s a b
theorem decide_eq_true : [s : Decidable p] β p β Eq (decide p) true
| isTrue _, _ => rfl
| isFalse hβ, hβ => absurd hβ hβ
theorem decide_eq_false : [s : Decidable p] β Not p β Eq (decide p) false
| isTrue hβ, hβ => absurd hβ hβ
| isFalse h, _ => rfl
theorem of_decide_eq_true [s : Decidable p] : Eq (decide p) true β p := fun h =>
match (generalizing := false) s with
| isTrue hβ => hβ
| isFalse hβ => absurd h (ne_true_of_eq_false (decide_eq_false hβ))
theorem of_decide_eq_false [s : Decidable p] : Eq (decide p) false β Not p := fun h =>
match (generalizing := false) s with
| isTrue hβ => absurd h (ne_false_of_eq_true (decide_eq_true hβ))
| isFalse hβ => hβ
@[inline] instance : DecidableEq Bool :=
fun a b => match a, b with
| false, false => isTrue rfl
| false, true => isFalse (fun h => Bool.noConfusion h)
| true, false => isFalse (fun h => Bool.noConfusion h)
| true, true => isTrue rfl
class BEq (Ξ± : Type u) where
beq : Ξ± β Ξ± β Bool
open BEq (beq)
instance [DecidableEq Ξ±] : BEq Ξ± where
beq a b := decide (Eq a b)
-- We use "dependent" if-then-else to be able to communicate the if-then-else condition
-- to the branches
@[macroInline] def dite {Ξ± : Sort u} (c : Prop) [h : Decidable c] (t : c β Ξ±) (e : Not c β Ξ±) : Ξ± :=
Decidable.casesOn (motive := fun _ => Ξ±) h e t
/- if-then-else -/
@[macroInline] def ite {Ξ± : Sort u} (c : Prop) [h : Decidable c] (t e : Ξ±) : Ξ± :=
Decidable.casesOn (motive := fun _ => Ξ±) h (fun _ => e) (fun _ => t)
@[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) :=
match dp with
| isTrue hp =>
match dq with
| isTrue hq => isTrue β¨hp, hqβ©
| isFalse hq => isFalse (fun h => hq (And.right h))
| isFalse hp =>
isFalse (fun h => hp (And.left h))
@[macroInline] instance [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) :=
match dp with
| isTrue hp => isTrue (Or.inl hp)
| isFalse hp =>
match dq with
| isTrue hq => isTrue (Or.inr hq)
| isFalse hq =>
isFalse fun h => match h with
| Or.inl h => hp h
| Or.inr h => hq h
instance [dp : Decidable p] : Decidable (Not p) :=
match dp with
| isTrue hp => isFalse (absurd hp)
| isFalse hp => isTrue hp
/- Boolean operators -/
@[macroInline] def cond {Ξ± : Type u} (c : Bool) (x y : Ξ±) : Ξ± :=
match c with
| true => x
| false => y
@[macroInline] def or (x y : Bool) : Bool :=
match x with
| true => true
| false => y
@[macroInline] def and (x y : Bool) : Bool :=
match x with
| false => false
| true => y
@[inline] def not : Bool β Bool
| true => false
| false => true
inductive Nat where
| zero : Nat
| succ (n : Nat) : Nat
instance : Inhabited Nat where
default := Nat.zero
/- For numeric literals notation -/
class OfNat (Ξ± : Type u) (n : Nat) where
ofNat : Ξ±
@[defaultInstance 100] /- low prio -/
instance (n : Nat) : OfNat Nat n where
ofNat := n
class LE (Ξ± : Type u) where le : Ξ± β Ξ± β Prop
class LT (Ξ± : Type u) where lt : Ξ± β Ξ± β Prop
@[reducible] def GE.ge {Ξ± : Type u} [LE Ξ±] (a b : Ξ±) : Prop := LE.le b a
@[reducible] def GT.gt {Ξ± : Type u} [LT Ξ±] (a b : Ξ±) : Prop := LT.lt b a
@[inline] def max [LT Ξ±] [DecidableRel (@LT.lt Ξ± _)] (a b : Ξ±) : Ξ± :=
ite (LT.lt b a) a b
@[inline] def min [LE Ξ±] [DecidableRel (@LE.le Ξ± _)] (a b : Ξ±) : Ξ± :=
ite (LE.le a b) a b
/-- Transitive chaining of proofs, used e.g. by `calc`. -/
class Trans (r : Ξ± β Ξ² β Prop) (s : Ξ² β Ξ³ β Prop) (t : outParam (Ξ± β Ξ³ β Prop)) where
trans : r a b β s b c β t a c
export Trans (trans)
instance (r : Ξ± β Ξ³ β Prop) : Trans Eq r r where
trans heq h' := heq βΈ h'
instance (r : Ξ± β Ξ² β Prop) : Trans r Eq r where
trans h' heq := heq βΈ h'
class HAdd (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hAdd : Ξ± β Ξ² β Ξ³
class HSub (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hSub : Ξ± β Ξ² β Ξ³
class HMul (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hMul : Ξ± β Ξ² β Ξ³
class HDiv (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hDiv : Ξ± β Ξ² β Ξ³
class HMod (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hMod : Ξ± β Ξ² β Ξ³
class HPow (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hPow : Ξ± β Ξ² β Ξ³
class HAppend (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hAppend : Ξ± β Ξ² β Ξ³
class HOrElse (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hOrElse : Ξ± β (Unit β Ξ²) β Ξ³
class HAndThen (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hAndThen : Ξ± β (Unit β Ξ²) β Ξ³
class HAnd (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hAnd : Ξ± β Ξ² β Ξ³
class HXor (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hXor : Ξ± β Ξ² β Ξ³
class HOr (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hOr : Ξ± β Ξ² β Ξ³
class HShiftLeft (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hShiftLeft : Ξ± β Ξ² β Ξ³
class HShiftRight (Ξ± : Type u) (Ξ² : Type v) (Ξ³ : outParam (Type w)) where
hShiftRight : Ξ± β Ξ² β Ξ³
class Add (Ξ± : Type u) where
add : Ξ± β Ξ± β Ξ±
class Sub (Ξ± : Type u) where
sub : Ξ± β Ξ± β Ξ±
class Mul (Ξ± : Type u) where
mul : Ξ± β Ξ± β Ξ±
class Neg (Ξ± : Type u) where
neg : Ξ± β Ξ±
class Div (Ξ± : Type u) where
div : Ξ± β Ξ± β Ξ±
class Mod (Ξ± : Type u) where
mod : Ξ± β Ξ± β Ξ±
class Pow (Ξ± : Type u) (Ξ² : Type v) where
pow : Ξ± β Ξ² β Ξ±
class Append (Ξ± : Type u) where
append : Ξ± β Ξ± β Ξ±
class OrElse (Ξ± : Type u) where
orElse : Ξ± β (Unit β Ξ±) β Ξ±
class AndThen (Ξ± : Type u) where
andThen : Ξ± β (Unit β Ξ±) β Ξ±
class AndOp (Ξ± : Type u) where
and : Ξ± β Ξ± β Ξ±
class Xor (Ξ± : Type u) where
xor : Ξ± β Ξ± β Ξ±
class OrOp (Ξ± : Type u) where
or : Ξ± β Ξ± β Ξ±
class Complement (Ξ± : Type u) where
complement : Ξ± β Ξ±
class ShiftLeft (Ξ± : Type u) where
shiftLeft : Ξ± β Ξ± β Ξ±
class ShiftRight (Ξ± : Type u) where
shiftRight : Ξ± β Ξ± β Ξ±
@[defaultInstance]
instance [Add Ξ±] : HAdd Ξ± Ξ± Ξ± where
hAdd a b := Add.add a b
@[defaultInstance]
instance [Sub Ξ±] : HSub Ξ± Ξ± Ξ± where
hSub a b := Sub.sub a b
@[defaultInstance]
instance [Mul Ξ±] : HMul Ξ± Ξ± Ξ± where
hMul a b := Mul.mul a b
@[defaultInstance]
instance [Div Ξ±] : HDiv Ξ± Ξ± Ξ± where
hDiv a b := Div.div a b
@[defaultInstance]
instance [Mod Ξ±] : HMod Ξ± Ξ± Ξ± where
hMod a b := Mod.mod a b
@[defaultInstance]
instance [Pow Ξ± Ξ²] : HPow Ξ± Ξ² Ξ± where
hPow a b := Pow.pow a b
@[defaultInstance]
instance [Append Ξ±] : HAppend Ξ± Ξ± Ξ± where
hAppend a b := Append.append a b
@[defaultInstance]
instance [OrElse Ξ±] : HOrElse Ξ± Ξ± Ξ± where
hOrElse a b := OrElse.orElse a b
@[defaultInstance]
instance [AndThen Ξ±] : HAndThen Ξ± Ξ± Ξ± where
hAndThen a b := AndThen.andThen a b
@[defaultInstance]
instance [AndOp Ξ±] : HAnd Ξ± Ξ± Ξ± where
hAnd a b := AndOp.and a b
@[defaultInstance]
instance [Xor Ξ±] : HXor Ξ± Ξ± Ξ± where
hXor a b := Xor.xor a b
@[defaultInstance]
instance [OrOp Ξ±] : HOr Ξ± Ξ± Ξ± where
hOr a b := OrOp.or a b
@[defaultInstance]
instance [ShiftLeft Ξ±] : HShiftLeft Ξ± Ξ± Ξ± where
hShiftLeft a b := ShiftLeft.shiftLeft a b
@[defaultInstance]
instance [ShiftRight Ξ±] : HShiftRight Ξ± Ξ± Ξ± where
hShiftRight a b := ShiftRight.shiftRight a b
open HAdd (hAdd)
open HMul (hMul)
open HPow (hPow)
open HAppend (hAppend)
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_add"]
protected def Nat.add : (@& Nat) β (@& Nat) β Nat
| a, Nat.zero => a
| a, Nat.succ b => Nat.succ (Nat.add a b)
instance : Add Nat where
add := Nat.add
/- We mark the following definitions as pattern to make sure they can be used in recursive equations,
and reduced by the equation Compiler. -/
attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_mul"]
protected def Nat.mul : (@& Nat) β (@& Nat) β Nat
| a, 0 => 0
| a, Nat.succ b => Nat.add (Nat.mul a b) a
instance : Mul Nat where
mul := Nat.mul
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_pow"]
protected def Nat.pow (m : @& Nat) : (@& Nat) β Nat
| 0 => 1
| succ n => Nat.mul (Nat.pow m n) m
instance : Pow Nat Nat where
pow := Nat.pow
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_dec_eq"]
def Nat.beq : (@& Nat) β (@& Nat) β Bool
| zero, zero => true
| zero, succ m => false
| succ n, zero => false
| succ n, succ m => beq n m
theorem Nat.eq_of_beq_eq_true : {n m : Nat} β Eq (beq n m) true β Eq n m
| zero, zero, h => rfl
| zero, succ m, h => Bool.noConfusion h
| succ n, zero, h => Bool.noConfusion h
| succ n, succ m, h =>
have : Eq (beq n m) true := h
have : Eq n m := eq_of_beq_eq_true this
this βΈ rfl
theorem Nat.ne_of_beq_eq_false : {n m : Nat} β Eq (beq n m) false β Not (Eq n m)
| zero, zero, hβ, hβ => Bool.noConfusion hβ
| zero, succ m, hβ, hβ => Nat.noConfusion hβ
| succ n, zero, hβ, hβ => Nat.noConfusion hβ
| succ n, succ m, hβ, hβ =>
have : Eq (beq n m) false := hβ
Nat.noConfusion hβ (fun hβ => absurd hβ (ne_of_beq_eq_false this))
@[extern "lean_nat_dec_eq"]
protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) :=
match h:beq n m with
| true => isTrue (eq_of_beq_eq_true h)
| false => isFalse (ne_of_beq_eq_false h)
@[inline] instance : DecidableEq Nat := Nat.decEq
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_dec_le"]
def Nat.ble : @& Nat β @& Nat β Bool
| zero, zero => true
| zero, succ m => true
| succ n, zero => false
| succ n, succ m => ble n m
protected inductive Nat.le (n : Nat) : Nat β Prop
| refl : Nat.le n n
| step {m} : Nat.le n m β Nat.le n (succ m)
instance : LE Nat where
le := Nat.le
protected def Nat.lt (n m : Nat) : Prop :=
Nat.le (succ n) m
instance : LT Nat where
lt := Nat.lt
theorem Nat.not_succ_le_zero : β (n : Nat), LE.le (succ n) 0 β False
| 0, h => nomatch h
| succ n, h => nomatch h
theorem Nat.not_lt_zero (n : Nat) : Not (LT.lt n 0) :=
not_succ_le_zero n
theorem Nat.zero_le : (n : Nat) β LE.le 0 n
| zero => Nat.le.refl
| succ n => Nat.le.step (zero_le n)
theorem Nat.succ_le_succ : LE.le n m β LE.le (succ n) (succ m)
| Nat.le.refl => Nat.le.refl
| Nat.le.step h => Nat.le.step (succ_le_succ h)
theorem Nat.zero_lt_succ (n : Nat) : LT.lt 0 (succ n) :=
succ_le_succ (zero_le n)
theorem Nat.le_step (h : LE.le n m) : LE.le n (succ m) :=
Nat.le.step h
protected theorem Nat.le_trans {n m k : Nat} : LE.le n m β LE.le m k β LE.le n k
| h, Nat.le.refl => h
| hβ, Nat.le.step hβ => Nat.le.step (Nat.le_trans hβ hβ)
protected theorem Nat.lt_trans {n m k : Nat} (hβ : LT.lt n m) : LT.lt m k β LT.lt n k :=
Nat.le_trans (le_step hβ)
theorem Nat.le_succ (n : Nat) : LE.le n (succ n) :=
Nat.le.step Nat.le.refl
theorem Nat.le_succ_of_le {n m : Nat} (h : LE.le n m) : LE.le n (succ m) :=
Nat.le_trans h (le_succ m)
protected theorem Nat.le_refl (n : Nat) : LE.le n n :=
Nat.le.refl
theorem Nat.succ_pos (n : Nat) : LT.lt 0 (succ n) :=
zero_lt_succ n
set_option bootstrap.genMatcherCode false in
@[extern c inline "lean_nat_sub(#1, lean_box(1))"]
def Nat.pred : (@& Nat) β Nat
| 0 => 0
| succ a => a
theorem Nat.pred_le_pred : {n m : Nat} β LE.le n m β LE.le (pred n) (pred m)
| _, _, Nat.le.refl => Nat.le.refl
| 0, succ m, Nat.le.step h => h
| succ n, succ m, Nat.le.step h => Nat.le_trans (le_succ _) h
theorem Nat.le_of_succ_le_succ {n m : Nat} : LE.le (succ n) (succ m) β LE.le n m :=
pred_le_pred
theorem Nat.le_of_lt_succ {m n : Nat} : LT.lt m (succ n) β LE.le m n :=
le_of_succ_le_succ
protected theorem Nat.eq_or_lt_of_le : {n m: Nat} β LE.le n m β Or (Eq n m) (LT.lt n m)
| zero, zero, h => Or.inl rfl
| zero, succ n, h => Or.inr (Nat.succ_le_succ (Nat.zero_le _))
| succ n, zero, h => absurd h (not_succ_le_zero _)
| succ n, succ m, h =>
have : LE.le n m := Nat.le_of_succ_le_succ h
match Nat.eq_or_lt_of_le this with
| Or.inl h => Or.inl (h βΈ rfl)
| Or.inr h => Or.inr (succ_le_succ h)
protected theorem Nat.lt_or_ge (n m : Nat) : Or (LT.lt n m) (GE.ge n m) :=
match m with
| zero => Or.inr (zero_le n)
| succ m =>
match Nat.lt_or_ge n m with
| Or.inl h => Or.inl (le_succ_of_le h)
| Or.inr h =>
match Nat.eq_or_lt_of_le h with
| Or.inl h1 => Or.inl (h1 βΈ Nat.le_refl _)
| Or.inr h1 => Or.inr h1
theorem Nat.not_succ_le_self : (n : Nat) β Not (LE.le (succ n) n)
| 0 => not_succ_le_zero _
| succ n => fun h => absurd (le_of_succ_le_succ h) (not_succ_le_self n)
protected theorem Nat.lt_irrefl (n : Nat) : Not (LT.lt n n) :=
Nat.not_succ_le_self n
protected theorem Nat.lt_of_le_of_lt {n m k : Nat} (hβ : LE.le n m) (hβ : LT.lt m k) : LT.lt n k :=
Nat.le_trans (Nat.succ_le_succ hβ) hβ
protected theorem Nat.le_antisymm {n m : Nat} (hβ : LE.le n m) (hβ : LE.le m n) : Eq n m :=
match hβ with
| Nat.le.refl => rfl
| Nat.le.step h => absurd (Nat.lt_of_le_of_lt h hβ) (Nat.lt_irrefl n)
protected theorem Nat.lt_of_le_of_ne {n m : Nat} (hβ : LE.le n m) (hβ : Not (Eq n m)) : LT.lt n m :=
match Nat.lt_or_ge n m with
| Or.inl hβ => hβ
| Or.inr hβ => absurd (Nat.le_antisymm hβ hβ) hβ
theorem Nat.le_of_ble_eq_true (h : Eq (Nat.ble n m) true) : LE.le n m :=
match n, m with
| 0, _ => Nat.zero_le _
| succ _, succ _ => Nat.succ_le_succ (le_of_ble_eq_true h)
theorem Nat.ble_self_eq_true : (n : Nat) β Eq (Nat.ble n n) true
| 0 => rfl
| succ n => ble_self_eq_true n
theorem Nat.ble_succ_eq_true : {n m : Nat} β Eq (Nat.ble n m) true β Eq (Nat.ble n (succ m)) true
| 0, _, _ => rfl
| succ n, succ m, h => ble_succ_eq_true (n := n) h
theorem Nat.ble_eq_true_of_le (h : LE.le n m) : Eq (Nat.ble n m) true :=
match h with
| Nat.le.refl => Nat.ble_self_eq_true n
| Nat.le.step h => Nat.ble_succ_eq_true (ble_eq_true_of_le h)
theorem Nat.not_le_of_not_ble_eq_true (h : Not (Eq (Nat.ble n m) true)) : Not (LE.le n m) :=
fun h' => absurd (Nat.ble_eq_true_of_le h') h
@[extern "lean_nat_dec_le"]
instance Nat.decLe (n m : @& Nat) : Decidable (LE.le n m) :=
dite (Eq (Nat.ble n m) true) (fun h => isTrue (Nat.le_of_ble_eq_true h)) (fun h => isFalse (Nat.not_le_of_not_ble_eq_true h))
@[extern "lean_nat_dec_lt"]
instance Nat.decLt (n m : @& Nat) : Decidable (LT.lt n m) :=
decLe (succ n) m
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_sub"]
protected def Nat.sub : (@& Nat) β (@& Nat) β Nat
| a, 0 => a
| a, succ b => pred (Nat.sub a b)
instance : Sub Nat where
sub := Nat.sub
@[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit β Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) :=
fun _ => β¨64, Or.inr rflβ© -- inhabitant
def System.Platform.numBits : Nat :=
(getNumBits ()).val
theorem System.Platform.numBits_eq : Or (Eq numBits 32) (Eq numBits 64) :=
(getNumBits ()).property
structure Fin (n : Nat) where
val : Nat
isLt : LT.lt val n
theorem Fin.eq_of_val_eq {n} : β {i j : Fin n}, Eq i.val j.val β Eq i j
| β¨v, hβ©, β¨_, _β©, rfl => rfl
theorem Fin.val_eq_of_eq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val :=
h βΈ rfl
theorem Fin.ne_of_val_ne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) :=
fun h' => absurd (val_eq_of_eq h') h
instance (n : Nat) : DecidableEq (Fin n) :=
fun i j =>
match decEq i.val j.val with
| isTrue h => isTrue (Fin.eq_of_val_eq h)
| isFalse h => isFalse (Fin.ne_of_val_ne h)
instance {n} : LT (Fin n) where
lt a b := LT.lt a.val b.val
instance {n} : LE (Fin n) where
le a b := LE.le a.val b.val
instance Fin.decLt {n} (a b : Fin n) : Decidable (LT.lt a b) := Nat.decLt ..
instance Fin.decLe {n} (a b : Fin n) : Decidable (LE.le a b) := Nat.decLe ..
def UInt8.size : Nat := 256
structure UInt8 where
val : Fin UInt8.size
attribute [extern "lean_uint8_of_nat_mk"] UInt8.mk
attribute [extern "lean_uint8_to_nat"] UInt8.val
@[extern "lean_uint8_of_nat"]
def UInt8.ofNatCore (n : @& Nat) (h : LT.lt n UInt8.size) : UInt8 := {
val := { val := n, isLt := h }
}
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) :=
match a, b with
| β¨nβ©, β¨mβ© =>
dite (Eq n m) (fun h => isTrue (h βΈ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt8 := UInt8.decEq
instance : Inhabited UInt8 where
default := UInt8.ofNatCore 0 (by decide)
def UInt16.size : Nat := 65536
structure UInt16 where
val : Fin UInt16.size
attribute [extern "lean_uint16_of_nat_mk"] UInt16.mk
attribute [extern "lean_uint16_to_nat"] UInt16.val
@[extern "lean_uint16_of_nat"]
def UInt16.ofNatCore (n : @& Nat) (h : LT.lt n UInt16.size) : UInt16 := {
val := { val := n, isLt := h }
}
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) :=
match a, b with
| β¨nβ©, β¨mβ© =>
dite (Eq n m) (fun h => isTrue (h βΈ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt16 := UInt16.decEq
instance : Inhabited UInt16 where
default := UInt16.ofNatCore 0 (by decide)
def UInt32.size : Nat := 4294967296
structure UInt32 where
val : Fin UInt32.size
attribute [extern "lean_uint32_of_nat_mk"] UInt32.mk
attribute [extern "lean_uint32_to_nat"] UInt32.val
@[extern "lean_uint32_of_nat"]
def UInt32.ofNatCore (n : @& Nat) (h : LT.lt n UInt32.size) : UInt32 := {
val := { val := n, isLt := h }
}
@[extern "lean_uint32_to_nat"]
def UInt32.toNat (n : UInt32) : Nat := n.val.val
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) :=
match a, b with
| β¨nβ©, β¨mβ© =>
dite (Eq n m) (fun h => isTrue (h βΈ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt32 := UInt32.decEq
instance : Inhabited UInt32 where
default := UInt32.ofNatCore 0 (by decide)
instance : LT UInt32 where
lt a b := LT.lt a.val b.val
instance : LE UInt32 where
le a b := LE.le a.val b.val
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 < #2"]
def UInt32.decLt (a b : UInt32) : Decidable (LT.lt a b) :=
match a, b with
| β¨nβ©, β¨mβ© => inferInstanceAs (Decidable (LT.lt n m))
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 <= #2"]
def UInt32.decLe (a b : UInt32) : Decidable (LE.le a b) :=
match a, b with
| β¨nβ©, β¨mβ© => inferInstanceAs (Decidable (LE.le n m))
instance (a b : UInt32) : Decidable (LT.lt a b) := UInt32.decLt a b
instance (a b : UInt32) : Decidable (LE.le a b) := UInt32.decLe a b
def UInt64.size : Nat := 18446744073709551616
structure UInt64 where
val : Fin UInt64.size
attribute [extern "lean_uint64_of_nat_mk"] UInt64.mk
attribute [extern "lean_uint64_to_nat"] UInt64.val
@[extern "lean_uint64_of_nat"]
def UInt64.ofNatCore (n : @& Nat) (h : LT.lt n UInt64.size) : UInt64 := {
val := { val := n, isLt := h }
}
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) :=
match a, b with
| β¨nβ©, β¨mβ© =>
dite (Eq n m) (fun h => isTrue (h βΈ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt64 := UInt64.decEq
instance : Inhabited UInt64 where
default := UInt64.ofNatCore 0 (by decide)
def USize.size : Nat := hPow 2 System.Platform.numBits
theorem usize_size_eq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) :=
show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from
match System.Platform.numBits, System.Platform.numBits_eq with
| _, Or.inl rfl => Or.inl (by decide)
| _, Or.inr rfl => Or.inr (by decide)
structure USize where
val : Fin USize.size
attribute [extern "lean_usize_of_nat_mk"] USize.mk
attribute [extern "lean_usize_to_nat"] USize.val
@[extern "lean_usize_of_nat"]
def USize.ofNatCore (n : @& Nat) (h : LT.lt n USize.size) : USize := {
val := { val := n, isLt := h }
}
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 == #2"]
def USize.decEq (a b : USize) : Decidable (Eq a b) :=
match a, b with
| β¨nβ©, β¨mβ© =>
dite (Eq n m) (fun h =>isTrue (h βΈ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq USize := USize.decEq
instance : Inhabited USize where
default := USize.ofNatCore 0 (match USize.size, usize_size_eq with
| _, Or.inl rfl => by decide
| _, Or.inr rfl => by decide)
@[extern "lean_usize_of_nat"]
def USize.ofNat32 (n : @& Nat) (h : LT.lt n 4294967296) : USize := {
val := {
val := n
isLt := match USize.size, usize_size_eq with
| _, Or.inl rfl => h
| _, Or.inr rfl => Nat.lt_trans h (by decide)
}
}
abbrev Nat.isValidChar (n : Nat) : Prop :=
Or (LT.lt n 0xd800) (And (LT.lt 0xdfff n) (LT.lt n 0x110000))
abbrev UInt32.isValidChar (n : UInt32) : Prop :=
n.toNat.isValidChar
/-- The `Char` Type represents an unicode scalar value.
See http://www.unicode.org/glossary/#unicode_scalar_value). -/
structure Char where
val : UInt32
valid : val.isValidChar
private theorem isValidChar_UInt32 {n : Nat} (h : n.isValidChar) : LT.lt n UInt32.size :=
match h with
| Or.inl h => Nat.lt_trans h (by decide)
| Or.inr β¨_, hβ© => Nat.lt_trans h (by decide)
@[extern "lean_uint32_of_nat"]
private def Char.ofNatAux (n : @& Nat) (h : n.isValidChar) : Char :=
{ val := β¨{ val := n, isLt := isValidChar_UInt32 h }β©, valid := h }
@[noinline, matchPattern]
def Char.ofNat (n : Nat) : Char :=
dite (n.isValidChar)
(fun h => Char.ofNatAux n h)
(fun _ => { val := β¨{ val := 0, isLt := by decide }β©, valid := Or.inl (by decide) })
theorem Char.eq_of_val_eq : β {c d : Char}, Eq c.val d.val β Eq c d
| β¨v, hβ©, β¨_, _β©, rfl => rfl
theorem Char.val_eq_of_eq : β {c d : Char}, Eq c d β Eq c.val d.val
| _, _, rfl => rfl
theorem Char.ne_of_val_ne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) :=
fun h' => absurd (val_eq_of_eq h') h
theorem Char.val_ne_of_ne {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) :=
fun h' => absurd (eq_of_val_eq h') h
instance : DecidableEq Char :=
fun c d =>
match decEq c.val d.val with
| isTrue h => isTrue (Char.eq_of_val_eq h)
| isFalse h => isFalse (Char.ne_of_val_ne h)
def Char.utf8Size (c : Char) : UInt32 :=
let v := c.val
ite (LE.le v (UInt32.ofNatCore 0x7F (by decide)))
(UInt32.ofNatCore 1 (by decide))
(ite (LE.le v (UInt32.ofNatCore 0x7FF (by decide)))
(UInt32.ofNatCore 2 (by decide))
(ite (LE.le v (UInt32.ofNatCore 0xFFFF (by decide)))
(UInt32.ofNatCore 3 (by decide))
(UInt32.ofNatCore 4 (by decide))))
inductive Option (Ξ± : Type u) where
| none : Option Ξ±
| some (val : Ξ±) : Option Ξ±
attribute [unbox] Option
export Option (none some)
instance {Ξ±} : Inhabited (Option Ξ±) where
default := none
@[macroInline] def Option.getD : Option Ξ± β Ξ± β Ξ±
| some x, _ => x
| none, e => e
inductive List (Ξ± : Type u) where
| nil : List Ξ±
| cons (head : Ξ±) (tail : List Ξ±) : List Ξ±
instance {Ξ±} : Inhabited (List Ξ±) where
default := List.nil
protected def List.hasDecEq {Ξ±: Type u} [DecidableEq Ξ±] : (a b : List Ξ±) β Decidable (Eq a b)
| nil, nil => isTrue rfl
| cons a as, nil => isFalse (fun h => List.noConfusion h)
| nil, cons b bs => isFalse (fun h => List.noConfusion h)
| cons a as, cons b bs =>
match decEq a b with
| isTrue hab =>
match List.hasDecEq as bs with
| isTrue habs => isTrue (hab βΈ habs βΈ rfl)
| isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs))
| isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab))
instance {Ξ± : Type u} [DecidableEq Ξ±] : DecidableEq (List Ξ±) := List.hasDecEq
@[specialize]
def List.foldl {Ξ± Ξ²} (f : Ξ± β Ξ² β Ξ±) : (init : Ξ±) β List Ξ² β Ξ±
| a, nil => a
| a, cons b l => foldl f (f a b) l
def List.set : List Ξ± β Nat β Ξ± β List Ξ±
| cons a as, 0, b => cons b as
| cons a as, Nat.succ n, b => cons a (set as n b)
| nil, _, _ => nil
def List.length : List Ξ± β Nat
| nil => 0
| cons a as => HAdd.hAdd (length as) 1
def List.lengthTRAux : List Ξ± β Nat β Nat
| nil, n => n
| cons a as, n => lengthTRAux as (Nat.succ n)
def List.lengthTR (as : List Ξ±) : Nat :=
lengthTRAux as 0
@[simp] theorem List.length_cons {Ξ±} (a : Ξ±) (as : List Ξ±) : Eq (cons a as).length as.length.succ :=
rfl
def List.concat {Ξ± : Type u} : List Ξ± β Ξ± β List Ξ±
| nil, b => cons b nil
| cons a as, b => cons a (concat as b)
def List.get {Ξ± : Type u} : (as : List Ξ±) β (i : Nat) β LT.lt i as.length β Ξ±
| nil, i, h => absurd h (Nat.not_lt_zero _)
| cons a as, 0, h => a
| cons a as, Nat.succ i, h =>
have : LT.lt i.succ as.length.succ := length_cons .. βΈ h
get as i (Nat.le_of_succ_le_succ this)
structure String where
data : List Char
attribute [extern "lean_string_mk"] String.mk
attribute [extern "lean_string_data"] String.data
@[extern "lean_string_dec_eq"]
def String.decEq (sβ sβ : @& String) : Decidable (Eq sβ sβ) :=
match sβ, sβ with
| β¨sββ©, β¨sββ© =>
dite (Eq sβ sβ) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq String := String.decEq
/-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded.
Codepoint positions (counting the Unicode codepoints rather than bytes)
are represented by plain `Nat`s instead.
Indexing a `String` by a byte position is constant-time, while codepoint
positions need to be translated internally to byte positions in linear-time. -/
abbrev String.Pos := Nat
structure Substring where
str : String
startPos : String.Pos
stopPos : String.Pos
@[inline] def Substring.bsize : Substring β Nat
| β¨_, b, eβ© => e.sub b
def String.csize (c : Char) : Nat :=
c.utf8Size.toNat
private def String.utf8ByteSizeAux : List Char β Nat β Nat
| List.nil, r => r
| List.cons c cs, r => utf8ByteSizeAux cs (hAdd r (csize c))
@[extern "lean_string_utf8_byte_size"]
def String.utf8ByteSize : (@& String) β Nat
| β¨sβ© => utf8ByteSizeAux s 0
@[inline] def String.bsize (s : String) : Nat :=
utf8ByteSize s
@[inline] def String.toSubstring (s : String) : Substring := {
str := s
startPos := 0
stopPos := s.bsize
}
@[extern c inline "#3"]
unsafe def unsafeCast {Ξ± : Type u} {Ξ² : Type v} (a : Ξ±) : Ξ² :=
cast lcProof (PUnit.{v})
@[neverExtract, extern "lean_panic_fn"]
constant panic {Ξ± : Type u} [Inhabited Ξ±] (msg : String) : Ξ±
/-
The Compiler has special support for arrays.
They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array
-/
structure Array (Ξ± : Type u) where
data : List Ξ±
attribute [extern "lean_array_data"] Array.data
attribute [extern "lean_array_mk"] Array.mk
/- The parameter `c` is the initial capacity -/
@[extern "lean_mk_empty_array_with_capacity"]
def Array.mkEmpty {Ξ± : Type u} (c : @& Nat) : Array Ξ± := {
data := List.nil
}
def Array.empty {Ξ± : Type u} : Array Ξ± :=
mkEmpty 0
@[reducible, extern "lean_array_get_size"]
def Array.size {Ξ± : Type u} (a : @& Array Ξ±) : Nat :=
a.data.length
@[extern "lean_array_fget"]
def Array.get {Ξ± : Type u} (a : @& Array Ξ±) (i : @& Fin a.size) : Ξ± :=
a.data.get i.val i.isLt
@[inline] def Array.getD (a : Array Ξ±) (i : Nat) (vβ : Ξ±) : Ξ± :=
dite (LT.lt i a.size) (fun h => a.get β¨i, hβ©) (fun _ => vβ)
/- "Comfortable" version of `fget`. It performs a bound check at runtime. -/
@[extern "lean_array_get"]
def Array.get! {Ξ± : Type u} [Inhabited Ξ±] (a : @& Array Ξ±) (i : @& Nat) : Ξ± :=
Array.getD a i arbitrary
def Array.getOp {Ξ± : Type u} [Inhabited Ξ±] (self : Array Ξ±) (idx : Nat) : Ξ± :=
self.get! idx
@[extern "lean_array_push"]
def Array.push {Ξ± : Type u} (a : Array Ξ±) (v : Ξ±) : Array Ξ± := {
data := List.concat a.data v
}
@[extern "lean_array_fset"]
def Array.set (a : Array Ξ±) (i : @& Fin a.size) (v : Ξ±) : Array Ξ± := {
data := a.data.set i.val v
}
@[inline] def Array.setD (a : Array Ξ±) (i : Nat) (v : Ξ±) : Array Ξ± :=
dite (LT.lt i a.size) (fun h => a.set β¨i, hβ© v) (fun _ => a)
@[extern "lean_array_set"]
def Array.set! (a : Array Ξ±) (i : @& Nat) (v : Ξ±) : Array Ξ± :=
Array.setD a i v
-- Slower `Array.append` used in quotations.
protected def Array.appendCore {Ξ± : Type u} (as : Array Ξ±) (bs : Array Ξ±) : Array Ξ± :=
let rec loop (i : Nat) (j : Nat) (as : Array Ξ±) : Array Ξ± :=
dite (LT.lt j bs.size)
(fun hlt =>
match i with
| 0 => as
| Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get β¨j, hltβ©)))
(fun _ => as)
loop bs.size 0 as
@[inlineIfReduce]
def List.toArrayAux : List Ξ± β Array Ξ± β Array Ξ±
| nil, r => r
| cons a as, r => toArrayAux as (r.push a)
@[inlineIfReduce]
def List.redLength : List Ξ± β Nat
| nil => 0
| cons _ as => as.redLength.succ
@[inline, matchPattern, export lean_list_to_array]
def List.toArray (as : List Ξ±) : Array Ξ± :=
as.toArrayAux (Array.mkEmpty as.redLength)
class Bind (m : Type u β Type v) where
bind : {Ξ± Ξ² : Type u} β m Ξ± β (Ξ± β m Ξ²) β m Ξ²
export Bind (bind)
class Pure (f : Type u β Type v) where
pure {Ξ± : Type u} : Ξ± β f Ξ±
export Pure (pure)
class Functor (f : Type u β Type v) : Type (max (u+1) v) where
map : {Ξ± Ξ² : Type u} β (Ξ± β Ξ²) β f Ξ± β f Ξ²
mapConst : {Ξ± Ξ² : Type u} β Ξ± β f Ξ² β f Ξ± := Function.comp map (Function.const _)
class Seq (f : Type u β Type v) : Type (max (u+1) v) where
seq : {Ξ± Ξ² : Type u} β f (Ξ± β Ξ²) β (Unit β f Ξ±) β f Ξ²
class SeqLeft (f : Type u β Type v) : Type (max (u+1) v) where
seqLeft : {Ξ± Ξ² : Type u} β f Ξ± β (Unit β f Ξ²) β f Ξ±
class SeqRight (f : Type u β Type v) : Type (max (u+1) v) where
seqRight : {Ξ± Ξ² : Type u} β f Ξ± β (Unit β f Ξ²) β f Ξ²
class Applicative (f : Type u β Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where
map := fun x y => Seq.seq (pure x) fun _ => y
seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b
seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b
class Monad (m : Type u β Type v) extends Applicative m, Bind m : Type (max (u+1) v) where
map f x := bind x (Function.comp pure f)
seq f x := bind f fun y => Functor.map y (x ())
seqLeft x y := bind x fun a => bind (y ()) (fun _ => pure a)
seqRight x y := bind x fun _ => y ()
instance {Ξ± : Type u} {m : Type u β Type v} [Monad m] : Inhabited (Ξ± β m Ξ±) where
default := pure
instance {Ξ± : Type u} {m : Type u β Type v} [Monad m] [Inhabited Ξ±] : Inhabited (m Ξ±) where
default := pure arbitrary
-- A fusion of Haskell's `sequence` and `map`
def Array.sequenceMap {Ξ± : Type u} {Ξ² : Type v} {m : Type v β Type w} [Monad m] (as : Array Ξ±) (f : Ξ± β m Ξ²) : m (Array Ξ²) :=
let rec loop (i : Nat) (j : Nat) (bs : Array Ξ²) : m (Array Ξ²) :=
dite (LT.lt j as.size)
(fun hlt =>
match i with
| 0 => pure bs
| Nat.succ i' => Bind.bind (f (as.get β¨j, hltβ©)) fun b => loop i' (hAdd j 1) (bs.push b))
(fun _ => bs)
loop as.size 0 Array.empty
/-- A Function for lifting a computation from an inner Monad to an outer Monad.
Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html),
but `n` does not have to be a monad transformer.
Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/
class MonadLift (m : Type u β Type v) (n : Type u β Type w) where
monadLift : {Ξ± : Type u} β m Ξ± β n Ξ±
/-- The reflexive-transitive closure of `MonadLift`.
`monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`.
Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/
class MonadLiftT (m : Type u β Type v) (n : Type u β Type w) where
monadLift : {Ξ± : Type u} β m Ξ± β n Ξ±
export MonadLiftT (monadLift)
abbrev liftM := @monadLift
instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where
monadLift x := MonadLift.monadLift (m := n) (monadLift x)
instance (m) : MonadLiftT m m where
monadLift x := x
/-- A functor in the category of monads. Can be used to lift monad-transforming functions.
Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html),
but not restricted to monad transformers.
Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/
class MonadFunctor (m : Type u β Type v) (n : Type u β Type w) where
monadMap {Ξ± : Type u} : ({Ξ² : Type u} β m Ξ² β m Ξ²) β n Ξ± β n Ξ±
/-- The reflexive-transitive closure of `MonadFunctor`.
`monadMap` is used to transitively lift Monad morphisms -/
class MonadFunctorT (m : Type u β Type v) (n : Type u β Type w) where
monadMap {Ξ± : Type u} : ({Ξ² : Type u} β m Ξ² β m Ξ²) β n Ξ± β n Ξ±
export MonadFunctorT (monadMap)
instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where
monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f)
instance monadFunctorRefl (m) : MonadFunctorT m m where
monadMap f := f
inductive Except (Ξ΅ : Type u) (Ξ± : Type v) where
| error : Ξ΅ β Except Ξ΅ Ξ±
| ok : Ξ± β Except Ξ΅ Ξ±
attribute [unbox] Except
instance {Ξ΅ : Type u} {Ξ± : Type v} [Inhabited Ξ΅] : Inhabited (Except Ξ΅ Ξ±) where
default := Except.error arbitrary
/-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/
class MonadExceptOf (Ξ΅ : Type u) (m : Type v β Type w) where
throw {Ξ± : Type v} : Ξ΅ β m Ξ±
tryCatch {Ξ± : Type v} : m Ξ± β (Ξ΅ β m Ξ±) β m Ξ±
abbrev throwThe (Ξ΅ : Type u) {m : Type v β Type w} [MonadExceptOf Ξ΅ m] {Ξ± : Type v} (e : Ξ΅) : m Ξ± :=
MonadExceptOf.throw e
abbrev tryCatchThe (Ξ΅ : Type u) {m : Type v β Type w} [MonadExceptOf Ξ΅ m] {Ξ± : Type v} (x : m Ξ±) (handle : Ξ΅ β m Ξ±) : m Ξ± :=
MonadExceptOf.tryCatch x handle
/-- Similar to `MonadExceptOf`, but `Ξ΅` is an outParam for convenience -/
class MonadExcept (Ξ΅ : outParam (Type u)) (m : Type v β Type w) where
throw {Ξ± : Type v} : Ξ΅ β m Ξ±
tryCatch {Ξ± : Type v} : m Ξ± β (Ξ΅ β m Ξ±) β m Ξ±
export MonadExcept (throw tryCatch)
instance (Ξ΅ : outParam (Type u)) (m : Type v β Type w) [MonadExceptOf Ξ΅ m] : MonadExcept Ξ΅ m where
throw := throwThe Ξ΅
tryCatch := tryCatchThe Ξ΅
namespace MonadExcept
variable {Ξ΅ : Type u} {m : Type v β Type w}
@[inline] protected def orElse [MonadExcept Ξ΅ m] {Ξ± : Type v} (tβ : m Ξ±) (tβ : Unit β m Ξ±) : m Ξ± :=
tryCatch tβ fun _ => tβ ()
instance [MonadExcept Ξ΅ m] {Ξ± : Type v} : OrElse (m Ξ±) where
orElse := MonadExcept.orElse
end MonadExcept
/-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/
def ReaderT (Ο : Type u) (m : Type u β Type v) (Ξ± : Type u) : Type (max u v) :=
Ο β m Ξ±
instance (Ο : Type u) (m : Type u β Type v) (Ξ± : Type u) [Inhabited (m Ξ±)] : Inhabited (ReaderT Ο m Ξ±) where
default := fun _ => arbitrary
@[inline] def ReaderT.run {Ο : Type u} {m : Type u β Type v} {Ξ± : Type u} (x : ReaderT Ο m Ξ±) (r : Ο) : m Ξ± :=
x r
namespace ReaderT
section
variable {Ο : Type u} {m : Type u β Type v} {Ξ± : Type u}
instance : MonadLift m (ReaderT Ο m) where
monadLift x := fun _ => x
instance (Ξ΅) [MonadExceptOf Ξ΅ m] : MonadExceptOf Ξ΅ (ReaderT Ο m) where
throw e := liftM (m := m) (throw e)
tryCatch := fun x c r => tryCatchThe Ξ΅ (x r) (fun e => (c e) r)
end
section
variable {Ο : Type u} {m : Type u β Type v} [Monad m] {Ξ± Ξ² : Type u}
@[inline] protected def read : ReaderT Ο m Ο :=
pure
@[inline] protected def pure (a : Ξ±) : ReaderT Ο m Ξ± :=
fun r => pure a
@[inline] protected def bind (x : ReaderT Ο m Ξ±) (f : Ξ± β ReaderT Ο m Ξ²) : ReaderT Ο m Ξ² :=
fun r => bind (x r) fun a => f a r
@[inline] protected def map (f : Ξ± β Ξ²) (x : ReaderT Ο m Ξ±) : ReaderT Ο m Ξ² :=
fun r => Functor.map f (x r)
instance : Monad (ReaderT Ο m) where
pure := ReaderT.pure
bind := ReaderT.bind
map := ReaderT.map
instance (Ο m) [Monad m] : MonadFunctor m (ReaderT Ο m) where
monadMap f x := fun ctx => f (x ctx)
@[inline] protected def adapt {Ο' : Type u} [Monad m] {Ξ± : Type u} (f : Ο' β Ο) : ReaderT Ο m Ξ± β ReaderT Ο' m Ξ± :=
fun x r => x (f r)
end
end ReaderT
/-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader).
It does not contain `local` because this Function cannot be lifted using `monadLift`.
Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function.
Note: This class can be seen as a simplification of the more "principled" definition
```
class MonadReader (Ο : outParam (Type u)) (n : Type u β Type u) where
lift {Ξ± : Type u} : ({m : Type u β Type u} β [Monad m] β ReaderT Ο m Ξ±) β n Ξ±
```
-/
class MonadReaderOf (Ο : Type u) (m : Type u β Type v) where
read : m Ο
@[inline] def readThe (Ο : Type u) {m : Type u β Type v} [MonadReaderOf Ο m] : m Ο :=
MonadReaderOf.read
/-- Similar to `MonadReaderOf`, but `Ο` is an outParam for convenience -/
class MonadReader (Ο : outParam (Type u)) (m : Type u β Type v) where
read : m Ο
export MonadReader (read)
instance (Ο : Type u) (m : Type u β Type v) [MonadReaderOf Ο m] : MonadReader Ο m where
read := readThe Ο
instance {Ο : Type u} {m : Type u β Type v} {n : Type u β Type w} [MonadLift m n] [MonadReaderOf Ο m] : MonadReaderOf Ο n where
read := liftM (m := m) read
instance {Ο : Type u} {m : Type u β Type v} [Monad m] : MonadReaderOf Ο (ReaderT Ο m) where
read := ReaderT.read
class MonadWithReaderOf (Ο : Type u) (m : Type u β Type v) where
withReader {Ξ± : Type u} : (Ο β Ο) β m Ξ± β m Ξ±
@[inline] def withTheReader (Ο : Type u) {m : Type u β Type v} [MonadWithReaderOf Ο m] {Ξ± : Type u} (f : Ο β Ο) (x : m Ξ±) : m Ξ± :=
MonadWithReaderOf.withReader f x
class MonadWithReader (Ο : outParam (Type u)) (m : Type u β Type v) where
withReader {Ξ± : Type u} : (Ο β Ο) β m Ξ± β m Ξ±
export MonadWithReader (withReader)
instance (Ο : Type u) (m : Type u β Type v) [MonadWithReaderOf Ο m] : MonadWithReader Ο m where
withReader := withTheReader Ο
instance {Ο : Type u} {m : Type u β Type v} {n : Type u β Type v} [MonadFunctor m n] [MonadWithReaderOf Ο m] : MonadWithReaderOf Ο n where
withReader f := monadMap (m := m) (withTheReader Ο f)
instance {Ο : Type u} {m : Type u β Type v} [Monad m] : MonadWithReaderOf Ο (ReaderT Ο m) where
withReader f x := fun ctx => x (f ctx)
/-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html).
In contrast to the Haskell implementation, we use overlapping instances to derive instances
automatically from `monadLift`. -/
class MonadStateOf (Ο : Type u) (m : Type u β Type v) where
/- Obtain the top-most State of a Monad stack. -/
get : m Ο
/- Set the top-most State of a Monad stack. -/
set : Ο β m PUnit
/- Map the top-most State of a Monad stack.
Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a`
because the latter does not use the State linearly (without sufficient inlining). -/
modifyGet {Ξ± : Type u} : (Ο β Prod Ξ± Ο) β m Ξ±
export MonadStateOf (set)
abbrev getThe (Ο : Type u) {m : Type u β Type v} [MonadStateOf Ο m] : m Ο :=
MonadStateOf.get
@[inline] abbrev modifyThe (Ο : Type u) {m : Type u β Type v} [MonadStateOf Ο m] (f : Ο β Ο) : m PUnit :=
MonadStateOf.modifyGet fun s => (PUnit.unit, f s)
@[inline] abbrev modifyGetThe {Ξ± : Type u} (Ο : Type u) {m : Type u β Type v} [MonadStateOf Ο m] (f : Ο β Prod Ξ± Ο) : m Ξ± :=
MonadStateOf.modifyGet f
/-- Similar to `MonadStateOf`, but `Ο` is an outParam for convenience -/
class MonadState (Ο : outParam (Type u)) (m : Type u β Type v) where
get : m Ο
set : Ο β m PUnit
modifyGet {Ξ± : Type u} : (Ο β Prod Ξ± Ο) β m Ξ±
export MonadState (get modifyGet)
instance (Ο : Type u) (m : Type u β Type v) [MonadStateOf Ο m] : MonadState Ο m where
set := MonadStateOf.set
get := getThe Ο
modifyGet f := MonadStateOf.modifyGet f
@[inline] def modify {Ο : Type u} {m : Type u β Type v} [MonadState Ο m] (f : Ο β Ο) : m PUnit :=
modifyGet fun s => (PUnit.unit, f s)
@[inline] def getModify {Ο : Type u} {m : Type u β Type v} [MonadState Ο m] [Monad m] (f : Ο β Ο) : m Ο :=
modifyGet fun s => (s, f s)
-- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer
-- will be picked first
instance {Ο : Type u} {m : Type u β Type v} {n : Type u β Type w} [MonadLift m n] [MonadStateOf Ο m] : MonadStateOf Ο n where
get := liftM (m := m) MonadStateOf.get
set s := liftM (m := m) (MonadStateOf.set s)
modifyGet f := monadLift (m := m) (MonadState.modifyGet f)
namespace EStateM
inductive Result (Ξ΅ Ο Ξ± : Type u) where
| ok : Ξ± β Ο β Result Ξ΅ Ο Ξ±
| error : Ξ΅ β Ο β Result Ξ΅ Ο Ξ±
variable {Ξ΅ Ο Ξ± : Type u}
instance [Inhabited Ξ΅] [Inhabited Ο] : Inhabited (Result Ξ΅ Ο Ξ±) where
default := Result.error arbitrary arbitrary
end EStateM
open EStateM (Result) in
def EStateM (Ξ΅ Ο Ξ± : Type u) := Ο β Result Ξ΅ Ο Ξ±
namespace EStateM
variable {Ξ΅ Ο Ξ± Ξ² : Type u}
instance [Inhabited Ξ΅] : Inhabited (EStateM Ξ΅ Ο Ξ±) where
default := fun s => Result.error arbitrary s
@[inline] protected def pure (a : Ξ±) : EStateM Ξ΅ Ο Ξ± := fun s =>
Result.ok a s
@[inline] protected def set (s : Ο) : EStateM Ξ΅ Ο PUnit := fun _ =>
Result.ok β¨β© s
@[inline] protected def get : EStateM Ξ΅ Ο Ο := fun s =>
Result.ok s s
@[inline] protected def modifyGet (f : Ο β Prod Ξ± Ο) : EStateM Ξ΅ Ο Ξ± := fun s =>
match f s with
| (a, s) => Result.ok a s
@[inline] protected def throw (e : Ξ΅) : EStateM Ξ΅ Ο Ξ± := fun s =>
Result.error e s
/-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/
class Backtrackable (Ξ΄ : outParam (Type u)) (Ο : Type u) where
save : Ο β Ξ΄
restore : Ο β Ξ΄ β Ο
@[inline] protected def tryCatch {Ξ΄} [Backtrackable Ξ΄ Ο] {Ξ±} (x : EStateM Ξ΅ Ο Ξ±) (handle : Ξ΅ β EStateM Ξ΅ Ο Ξ±) : EStateM Ξ΅ Ο Ξ± := fun s =>
let d := Backtrackable.save s
match x s with
| Result.error e s => handle e (Backtrackable.restore s d)
| ok => ok
@[inline] protected def orElse {Ξ΄} [Backtrackable Ξ΄ Ο] (xβ : EStateM Ξ΅ Ο Ξ±) (xβ : Unit β EStateM Ξ΅ Ο Ξ±) : EStateM Ξ΅ Ο Ξ± := fun s =>
let d := Backtrackable.save s;
match xβ s with
| Result.error _ s => xβ () (Backtrackable.restore s d)
| ok => ok
@[inline] def adaptExcept {Ξ΅' : Type u} (f : Ξ΅ β Ξ΅') (x : EStateM Ξ΅ Ο Ξ±) : EStateM Ξ΅' Ο Ξ± := fun s =>
match x s with
| Result.error e s => Result.error (f e) s
| Result.ok a s => Result.ok a s
@[inline] protected def bind (x : EStateM Ξ΅ Ο Ξ±) (f : Ξ± β EStateM Ξ΅ Ο Ξ²) : EStateM Ξ΅ Ο Ξ² := fun s =>
match x s with
| Result.ok a s => f a s
| Result.error e s => Result.error e s
@[inline] protected def map (f : Ξ± β Ξ²) (x : EStateM Ξ΅ Ο Ξ±) : EStateM Ξ΅ Ο Ξ² := fun s =>
match x s with
| Result.ok a s => Result.ok (f a) s
| Result.error e s => Result.error e s
@[inline] protected def seqRight (x : EStateM Ξ΅ Ο Ξ±) (y : Unit β EStateM Ξ΅ Ο Ξ²) : EStateM Ξ΅ Ο Ξ² := fun s =>
match x s with
| Result.ok _ s => y () s
| Result.error e s => Result.error e s
instance : Monad (EStateM Ξ΅ Ο) where
bind := EStateM.bind
pure := EStateM.pure
map := EStateM.map
seqRight := EStateM.seqRight
instance {Ξ΄} [Backtrackable Ξ΄ Ο] : OrElse (EStateM Ξ΅ Ο Ξ±) where
orElse := EStateM.orElse
instance : MonadStateOf Ο (EStateM Ξ΅ Ο) where
set := EStateM.set
get := EStateM.get
modifyGet := EStateM.modifyGet
instance {Ξ΄} [Backtrackable Ξ΄ Ο] : MonadExceptOf Ξ΅ (EStateM Ξ΅ Ο) where
throw := EStateM.throw
tryCatch := EStateM.tryCatch
@[inline] def run (x : EStateM Ξ΅ Ο Ξ±) (s : Ο) : Result Ξ΅ Ο Ξ± :=
x s
@[inline] def run' (x : EStateM Ξ΅ Ο Ξ±) (s : Ο) : Option Ξ± :=
match run x s with
| Result.ok v _ => some v
| Result.error .. => none
@[inline] def dummySave : Ο β PUnit := fun _ => β¨β©
@[inline] def dummyRestore : Ο β PUnit β Ο := fun s _ => s
/- Dummy default instance -/
instance nonBacktrackable : Backtrackable PUnit Ο where
save := dummySave
restore := dummyRestore
end EStateM
class Hashable (Ξ± : Sort u) where
hash : Ξ± β UInt64
export Hashable (hash)
@[extern c inline "(size_t)#1"]
constant UInt64.toUSize (u : UInt64) : USize
@[extern c inline "(uint64_t)#1"]
constant USize.toUInt64 (u : USize) : UInt64
@[extern "lean_uint64_mix_hash"]
constant mixHash (uβ uβ : UInt64) : UInt64
@[extern "lean_string_hash"]
protected constant String.hash (s : @& String) : UInt64
instance : Hashable String where
hash := String.hash
namespace Lean
/- Hierarchical names -/
inductive Name where
| anonymous : Name
| str : Name β String β UInt64 β Name
| num : Name β Nat β UInt64 β Name
instance : Inhabited Name where
default := Name.anonymous
protected def Name.hash : Name β UInt64
| Name.anonymous => UInt64.ofNatCore 1723 (by decide)
| Name.str p s h => h
| Name.num p v h => h
instance : Hashable Name where
hash := Name.hash
namespace Name
@[export lean_name_mk_string]
def mkStr (p : Name) (s : String) : Name :=
Name.str p s (mixHash (hash p) (hash s))
@[export lean_name_mk_numeral]
def mkNum (p : Name) (v : Nat) : Name :=
Name.num p v (mixHash (hash p) (dite (LT.lt v UInt64.size) (fun h => UInt64.ofNatCore v h) (fun _ => UInt64.ofNatCore 17 (by decide))))
def mkSimple (s : String) : Name :=
mkStr Name.anonymous s
@[extern "lean_name_eq"]
protected def beq : (@& Name) β (@& Name) β Bool
| anonymous, anonymous => true
| str pβ sβ _, str pβ sβ _ => and (BEq.beq sβ sβ) (Name.beq pβ pβ)
| num pβ nβ _, num pβ nβ _ => and (BEq.beq nβ nβ) (Name.beq pβ pβ)
| _, _ => false
instance : BEq Name where
beq := Name.beq
protected def append : Name β Name β Name
| n, anonymous => n
| n, str p s _ => Name.mkStr (Name.append n p) s
| n, num p d _ => Name.mkNum (Name.append n p) d
instance : Append Name where
append := Name.append
end Name
/- Syntax -/
/-- Source information of tokens. -/
inductive SourceInfo where
/-
Token from original input with whitespace and position information.
`leading` will be inferred after parsing by `Syntax.updateLeading`. During parsing,
it is not at all clear what the preceding token was, especially with backtracking. -/
| original (leading : Substring) (pos : String.Pos) (trailing : Substring) (endPos : String.Pos)
/-
Synthesized token (e.g. from a quotation) annotated with a span from the original source.
In the delaborator, we "misuse" this constructor to store synthetic positions identifying
subterms. -/
| synthetic (pos : String.Pos) (endPos : String.Pos)
/- Synthesized token without position information. -/
| protected none
instance : Inhabited SourceInfo := β¨SourceInfo.noneβ©
namespace SourceInfo
def getPos? (info : SourceInfo) (originalOnly := false) : Option String.Pos :=
match info, originalOnly with
| original (pos := pos) .., _ => some pos
| synthetic (pos := pos) .., false => some pos
| _, _ => none
end SourceInfo
abbrev SyntaxNodeKind := Name
/- Syntax AST -/
inductive Syntax where
| missing : Syntax
| node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax
| atom (info : SourceInfo) (val : String) : Syntax
| ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax
instance : Inhabited Syntax where
default := Syntax.missing
/- Builtin kinds -/
def choiceKind : SyntaxNodeKind := `choice
def nullKind : SyntaxNodeKind := `null
def groupKind : SyntaxNodeKind := `group
def identKind : SyntaxNodeKind := `ident
def strLitKind : SyntaxNodeKind := `strLit
def charLitKind : SyntaxNodeKind := `charLit
def numLitKind : SyntaxNodeKind := `numLit
def scientificLitKind : SyntaxNodeKind := `scientificLit
def nameLitKind : SyntaxNodeKind := `nameLit
def fieldIdxKind : SyntaxNodeKind := `fieldIdx
def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind
def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind
namespace Syntax
def getKind (stx : Syntax) : SyntaxNodeKind :=
match stx with
| Syntax.node k args => k
-- We use these "pseudo kinds" for antiquotation kinds.
-- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident)
-- is compiled to ``if stx.isOfKind `ident ...``
| Syntax.missing => `missing
| Syntax.atom _ v => Name.mkSimple v
| Syntax.ident .. => identKind
def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax :=
match stx with
| Syntax.node _ args => Syntax.node k args
| _ => stx
def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool :=
beq stx.getKind k
def getArg (stx : Syntax) (i : Nat) : Syntax :=
match stx with
| Syntax.node _ args => args.getD i Syntax.missing
| _ => Syntax.missing
-- Add `stx[i]` as sugar for `stx.getArg i`
@[inline] def getOp (self : Syntax) (idx : Nat) : Syntax :=
self.getArg idx
def getArgs (stx : Syntax) : Array Syntax :=
match stx with
| Syntax.node _ args => args
| _ => Array.empty
def getNumArgs (stx : Syntax) : Nat :=
match stx with
| Syntax.node _ args => args.size
| _ => 0
def isMissing : Syntax β Bool
| Syntax.missing => true
| _ => false
def isNodeOf (stx : Syntax) (k : SyntaxNodeKind) (n : Nat) : Bool :=
and (stx.isOfKind k) (beq stx.getNumArgs n)
def isIdent : Syntax β Bool
| ident _ _ _ _ => true
| _ => false
def getId : Syntax β Name
| ident _ _ val _ => val
| _ => Name.anonymous
def matchesNull (stx : Syntax) (n : Nat) : Bool :=
isNodeOf stx nullKind n
def matchesIdent (stx : Syntax) (id : Name) : Bool :=
and stx.isIdent (beq stx.getId id)
def setArgs (stx : Syntax) (args : Array Syntax) : Syntax :=
match stx with
| node k _ => node k args
| stx => stx
def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax :=
match stx with
| node k args => node k (args.setD i arg)
| stx => stx
/-- Retrieve the left-most leaf's info in the Syntax tree. -/
partial def getHeadInfo? : Syntax β Option SourceInfo
| atom info _ => some info
| ident info .. => some info
| node _ args =>
let rec loop (i : Nat) : Option SourceInfo :=
match decide (LT.lt i args.size) with
| true => match getHeadInfo? (args.get! i) with
| some info => some info
| none => loop (hAdd i 1)
| false => none
loop 0
| _ => none
/-- Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token. -/
partial def getHeadInfo (stx : Syntax) : SourceInfo :=
match stx.getHeadInfo? with
| some info => info
| none => SourceInfo.none
def getPos? (stx : Syntax) (originalOnly := false) : Option String.Pos :=
stx.getHeadInfo.getPos? originalOnly
partial def getTailPos? (stx : Syntax) (originalOnly := false) : Option String.Pos :=
match stx, originalOnly with
| atom (SourceInfo.original (endPos := pos) ..) .., _ => some pos
| atom (SourceInfo.synthetic (endPos := pos) ..) _, false => some pos
| ident (SourceInfo.original (endPos := pos) ..) .., _ => some pos
| ident (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos
| node _ args, _ =>
let rec loop (i : Nat) : Option String.Pos :=
match decide (LT.lt i args.size) with
| true => match getTailPos? (args.get! ((args.size.sub i).sub 1)) originalOnly with
| some info => some info
| none => loop (hAdd i 1)
| false => none
loop 0
| _, _ => none
/--
An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically
remove/insert the separators. -/
structure SepArray (sep : String) where
elemsAndSeps : Array Syntax
end Syntax
def SourceInfo.fromRef (ref : Syntax) : SourceInfo :=
match ref.getPos?, ref.getTailPos? with
| some pos, some tailPos => SourceInfo.synthetic pos tailPos
| _, _ => SourceInfo.none
def mkAtom (val : String) : Syntax :=
Syntax.atom SourceInfo.none val
def mkAtomFrom (src : Syntax) (val : String) : Syntax :=
Syntax.atom (SourceInfo.fromRef src) val
/- Parser descriptions -/
inductive ParserDescr where
| const (name : Name)
| unary (name : Name) (p : ParserDescr)
| binary (name : Name) (pβ pβ : ParserDescr)
| node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr)
| trailingNode (kind : SyntaxNodeKind) (prec lhsPrec : Nat) (p : ParserDescr)
| symbol (val : String)
| nonReservedSymbol (val : String) (includeIdent : Bool)
| cat (catName : Name) (rbp : Nat)
| parser (declName : Name)
| nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr)
| sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false)
| sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false)
instance : Inhabited ParserDescr where
default := ParserDescr.symbol ""
abbrev TrailingParserDescr := ParserDescr
/-
Runtime support for making quotation terms auto-hygienic, by mangling identifiers
introduced by them with a "macro scope" supplied by the context. Details to appear in a
paper soon.
-/
abbrev MacroScope := Nat
/-- Macro scope used internally. It is not available for our frontend. -/
def reservedMacroScope := 0
/-- First macro scope available for our frontend -/
def firstFrontendMacroScope := hAdd reservedMacroScope 1
class MonadRef (m : Type β Type) where
getRef : m Syntax
withRef {Ξ±} : Syntax β m Ξ± β m Ξ±
export MonadRef (getRef)
instance (m n : Type β Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where
getRef := liftM (getRef : m _)
withRef ref x := monadMap (m := m) (MonadRef.withRef ref) x
def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax :=
match ref.getPos? with
| some _ => ref
| _ => oldRef
@[inline] def withRef {m : Type β Type} [Monad m] [MonadRef m] {Ξ±} (ref : Syntax) (x : m Ξ±) : m Ξ± :=
bind getRef fun oldRef =>
let ref := replaceRef ref oldRef
MonadRef.withRef ref x
/-- A monad that supports syntax quotations. Syntax quotations (in term
position) are monadic values that when executed retrieve the current "macro
scope" from the monad and apply it to every identifier they introduce
(independent of whether this identifier turns out to be a reference to an
existing declaration, or an actually fresh binding during further
elaboration). We also apply the position of the result of `getRef` to each
introduced symbol, which results in better error positions than not applying
any position. -/
class MonadQuotation (m : Type β Type) extends MonadRef m where
-- Get the fresh scope of the current macro invocation
getCurrMacroScope : m MacroScope
getMainModule : m Name
/- Execute action in a new macro invocation context. This transformer should be
used at all places that morally qualify as the beginning of a "macro call",
e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it
can also be used internally inside a "macro" if identifiers introduced by
e.g. different recursive calls should be independent and not collide. While
returning an intermediate syntax tree that will recursively be expanded by
the elaborator can be used for the same effect, doing direct recursion inside
the macro guarded by this transformer is often easier because one is not
restricted to passing a single syntax tree. Modelling this helper as a
transformer and not just a monadic action ensures that the current macro
scope before the recursive call is restored after it, as expected. -/
withFreshMacroScope {Ξ± : Type} : m Ξ± β m Ξ±
export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope)
def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := do
SourceInfo.fromRef (β getRef)
instance {m n : Type β Type} [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where
getCurrMacroScope := liftM (m := m) getCurrMacroScope
getMainModule := liftM (m := m) getMainModule
withFreshMacroScope := monadMap (m := m) withFreshMacroScope
/-
We represent a name with macro scopes as
```
<actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes>
```
Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5]
```
foo.bla._@.Init.Data.List.Basic._hyg.2.5
```
We may have to combine scopes from different files/modules.
The main modules being processed is always the right most one.
This situation may happen when we execute a macro generated in
an imported file in the current file.
```
foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4
```
The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance.
-/
def Name.hasMacroScopes : Name β Bool
| str _ s _ => beq s "_hyg"
| num p _ _ => hasMacroScopes p
| _ => false
private def eraseMacroScopesAux : Name β Name
| Name.str p s _ => match beq s "_@" with
| true => p
| false => eraseMacroScopesAux p
| Name.num p _ _ => eraseMacroScopesAux p
| Name.anonymous => Name.anonymous
@[export lean_erase_macro_scopes]
def Name.eraseMacroScopes (n : Name) : Name :=
match n.hasMacroScopes with
| true => eraseMacroScopesAux n
| false => n
private def simpMacroScopesAux : Name β Name
| Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i
| n => eraseMacroScopesAux n
/- Helper function we use to create binder names that do not need to be unique. -/
@[export lean_simp_macro_scopes]
def Name.simpMacroScopes (n : Name) : Name :=
match n.hasMacroScopes with
| true => simpMacroScopesAux n
| false => n
structure MacroScopesView where
name : Name
imported : Name
mainModule : Name
scopes : List MacroScope
instance : Inhabited MacroScopesView where
default := β¨arbitrary, arbitrary, arbitrary, arbitraryβ©
def MacroScopesView.review (view : MacroScopesView) : Name :=
match view.scopes with
| List.nil => view.name
| List.cons _ _ =>
let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg")
view.scopes.foldl Name.mkNum base
private def assembleParts : List Name β Name β Name
| List.nil, acc => acc
| List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s)
| List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n)
| _, acc => panic "Error: unreachable @ assembleParts"
private def extractImported (scps : List MacroScope) (mainModule : Name) : Name β List Name β MacroScopesView
| n@(Name.str p str _), parts =>
match beq str "_@" with
| true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps }
| false => extractImported scps mainModule p (List.cons n parts)
| n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts)
| _, _ => panic "Error: unreachable @ extractImported"
private def extractMainModule (scps : List MacroScope) : Name β List Name β MacroScopesView
| n@(Name.str p str _), parts =>
match beq str "_@" with
| true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps }
| false => extractMainModule scps p (List.cons n parts)
| n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil
| _, _ => panic "Error: unreachable @ extractMainModule"
private def extractMacroScopesAux : Name β List MacroScope β MacroScopesView
| Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc)
| Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg"
| _, _ => panic "Error: unreachable @ extractMacroScopesAux"
/--
Revert all `addMacroScope` calls. `v = extractMacroScopes n β n = v.review`.
This operation is useful for analyzing/transforming the original identifiers, then adding back
the scopes (via `MacroScopesView.review`). -/
def extractMacroScopes (n : Name) : MacroScopesView :=
match n.hasMacroScopes with
| true => extractMacroScopesAux n List.nil
| false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous }
def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name :=
match n.hasMacroScopes with
| true =>
let view := extractMacroScopes n
match beq view.mainModule mainModule with
| true => Name.mkNum n scp
| false =>
{ view with
imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule)
mainModule := mainModule
scopes := List.cons scp List.nil
}.review
| false =>
Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp
@[inline] def MonadQuotation.addMacroScope {m : Type β Type} [MonadQuotation m] [Monad m] (n : Name) : m Name :=
bind getMainModule fun mainModule =>
bind getCurrMacroScope fun scp =>
pure (Lean.addMacroScope mainModule n scp)
def defaultMaxRecDepth := 512
def maxRecDepthErrorMessage : String :=
"maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)"
namespace Macro
/- References -/
private constant MethodsRefPointed : PointedType.{0}
private def MethodsRef : Type := MethodsRefPointed.type
structure Context where
methods : MethodsRef
mainModule : Name
currMacroScope : MacroScope
currRecDepth : Nat := 0
maxRecDepth : Nat := defaultMaxRecDepth
ref : Syntax
inductive Exception where
| error : Syntax β String β Exception
| unsupportedSyntax : Exception
structure State where
macroScope : MacroScope
traceMsgs : List (Prod Name String) := List.nil
deriving Inhabited
end Macro
abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception Macro.State)
abbrev Macro := Syntax β MacroM Syntax
namespace Macro
instance : MonadRef MacroM where
getRef := bind read fun ctx => pure ctx.ref
withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x
def addMacroScope (n : Name) : MacroM Name :=
bind read fun ctx =>
pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope)
def throwUnsupported {Ξ±} : MacroM Ξ± :=
throw Exception.unsupportedSyntax
def throwError {Ξ±} (msg : String) : MacroM Ξ± :=
bind getRef fun ref =>
throw (Exception.error ref msg)
def throwErrorAt {Ξ±} (ref : Syntax) (msg : String) : MacroM Ξ± :=
withRef ref (throwError msg)
@[inline] protected def withFreshMacroScope {Ξ±} (x : MacroM Ξ±) : MacroM Ξ± :=
bind (modifyGet (fun s => (s.macroScope, { s with macroScope := hAdd s.macroScope 1 }))) fun fresh =>
withReader (fun ctx => { ctx with currMacroScope := fresh }) x
@[inline] def withIncRecDepth {Ξ±} (ref : Syntax) (x : MacroM Ξ±) : MacroM Ξ± :=
bind read fun ctx =>
match beq ctx.currRecDepth ctx.maxRecDepth with
| true => throw (Exception.error ref maxRecDepthErrorMessage)
| false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x
instance : MonadQuotation MacroM where
getCurrMacroScope ctx := pure ctx.currMacroScope
getMainModule ctx := pure ctx.mainModule
withFreshMacroScope := Macro.withFreshMacroScope
structure Methods where
expandMacro? : Syntax β MacroM (Option Syntax)
getCurrNamespace : MacroM Name
hasDecl : Name β MacroM Bool
resolveNamespace? : Name β MacroM (Option Name)
resolveGlobalName : Name β MacroM (List (Prod Name (List String)))
deriving Inhabited
unsafe def mkMethodsImp (methods : Methods) : MethodsRef :=
unsafeCast methods
@[implementedBy mkMethodsImp]
constant mkMethods (methods : Methods) : MethodsRef := MethodsRefPointed.val
instance : Inhabited MethodsRef where
default := mkMethods arbitrary
unsafe def getMethodsImp : MacroM Methods :=
bind read fun ctx => pure (unsafeCast (ctx.methods))
@[implementedBy getMethodsImp] constant getMethods : MacroM Methods
/-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/
def expandMacro? (stx : Syntax) : MacroM (Option Syntax) := do
(β getMethods).expandMacro? stx
/-- Return `true` if the environment contains a declaration with name `declName` -/
def hasDecl (declName : Name) : MacroM Bool := do
(β getMethods).hasDecl declName
def getCurrNamespace : MacroM Name := do
(β getMethods).getCurrNamespace
def resolveNamespace? (n : Name) : MacroM (Option Name) := do
(β getMethods).resolveNamespace? n
def resolveGlobalName (n : Name) : MacroM (List (Prod Name (List String))) := do
(β getMethods).resolveGlobalName n
def trace (clsName : Name) (msg : String) : MacroM Unit := do
modify fun s => { s with traceMsgs := List.cons (Prod.mk clsName msg) s.traceMsgs }
end Macro
export Macro (expandMacro?)
namespace PrettyPrinter
abbrev UnexpandM := EStateM Unit Unit
/--
Function that tries to reverse macro expansions as a post-processing step of delaboration.
While less general than an arbitrary delaborator, it can be declared without importing `Lean`.
Used by the `[appUnexpander]` attribute. -/
-- a `kindUnexpander` could reasonably be added later
abbrev Unexpander := Syntax β UnexpandM Syntax
-- unexpanders should not need to introduce new names
instance : MonadQuotation UnexpandM where
getRef := pure Syntax.missing
withRef := fun _ => id
getCurrMacroScope := pure 0
getMainModule := pure `_fakeMod
withFreshMacroScope := id
end PrettyPrinter
end Lean
|
60f23368e7277a54717343b139ed5765d188474a | 2c41ae31b2b771ad5646ad880201393f5269a7f0 | /Lean/Qualities/Scalable.lean | cee88319cbebfb58a9becca584603656480da08f | [] | no_license | kevinsullivan/Boehm | 926f25bc6f1a8b6bd47d333d936fdfc278228312 | 55208395bff20d48a598b7fa33a4d55a2447a9cf | refs/heads/master | 1,586,127,134,302 | 1,488,252,326,000 | 1,488,252,326,000 | 32,836,930 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 659 | lean | -- Scalable
/-
[Scalable] is parameterized by an instance of type [SystemType], and it's a sub-attribute to [MissionEffective].
An instance of type [SystemType] is deemed [Scalable] if and only if all the requirements are satisfied.
-/
import SystemModel.System
inductive Scalable (sys_type: SystemType): Prop
| intro : (exists scalable: sys_type ^.Contexts -> sys_type ^.Phases -> sys_type ^.Stakeholders -> @SystemInstance sys_type -> Prop,
forall c: sys_type ^.Contexts, forall p: sys_type ^.Phases,
forall s: sys_type ^.Stakeholders, forall st: @SystemInstance sys_type, scalable c p s st) ->
Scalable
|
5ea249764160b1eb1ca5e3922af291c07f28397e | 07c76fbd96ea1786cc6392fa834be62643cea420 | /hott/types/equiv.hlean | bf04ad5526982682d154a14774f99659f05c83f6 | [
"Apache-2.0"
] | permissive | fpvandoorn/lean2 | 5a430a153b570bf70dc8526d06f18fc000a60ad9 | 0889cf65b7b3cebfb8831b8731d89c2453dd1e9f | refs/heads/master | 1,592,036,508,364 | 1,545,093,958,000 | 1,545,093,958,000 | 75,436,854 | 0 | 0 | null | 1,480,718,780,000 | 1,480,718,780,000 | null | UTF-8 | Lean | false | false | 12,611 | hlean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Ported from Coq HoTT
Theorems about the types equiv and is_equiv
-/
import .fiber .arrow arity ..prop_trunc cubical.square .pointed
open eq is_trunc sigma sigma.ops pi fiber function equiv
namespace is_equiv
variables {A B : Type} (f : A β B) [H : is_equiv f]
include H
/- is_equiv f is a mere proposition -/
definition is_contr_right_inverse : is_contr (Ξ£(g : B β A), f β g ~ id) :=
begin
fapply is_trunc_equiv_closed,
{apply sigma_equiv_sigma_right, intro g, apply eq_equiv_homotopy},
fapply is_trunc_equiv_closed,
{apply fiber.sigma_char},
fapply is_contr_fiber_of_is_equiv,
apply (to_is_equiv (arrow_equiv_arrow_right B (equiv.mk f H))),
end
definition is_contr_right_coherence (u : Ξ£(g : B β A), f β g ~ id)
: is_contr (Ξ£(Ξ· : u.1 β f ~ id), Ξ (a : A), u.2 (f a) = ap f (Ξ· a)) :=
begin
apply is_contr_equiv_closed_rev !sigma_pi_equiv_pi_sigma,
apply is_contr_equiv_closed,
{ apply pi_equiv_pi_right, intro a,
apply (fiber_eq_equiv (fiber.mk (u.1 (f a)) (u.2 (f a))) (fiber.mk a idp)) },
exact _
end
omit H
protected definition sigma_char : (is_equiv f) β
(Ξ£(g : B β A) (Ξ΅ : f β g ~ id) (Ξ· : g β f ~ id), Ξ (a : A), Ξ΅ (f a) = ap f (Ξ· a)) :=
equiv.MK (Ξ»H, β¨inv f, right_inv f, left_inv f, adj fβ©)
(Ξ»p, is_equiv.mk f p.1 p.2.1 p.2.2.1 p.2.2.2)
(Ξ»p, begin
induction p with p1 p2,
induction p2 with p21 p22,
induction p22 with p221 p222,
reflexivity
end)
(Ξ»H, by induction H; reflexivity)
protected definition sigma_char' : (is_equiv f) β
(Ξ£(u : Ξ£(g : B β A), f β g ~ id) (Ξ· : u.1 β f ~ id), Ξ (a : A), u.2 (f a) = ap f (Ξ· a)) :=
calc
(is_equiv f) β
(Ξ£(g : B β A) (Ξ΅ : f β g ~ id) (Ξ· : g β f ~ id), Ξ (a : A), Ξ΅ (f a) = ap f (Ξ· a))
: is_equiv.sigma_char
... β (Ξ£(u : Ξ£(g : B β A), f β g ~ id), Ξ£(Ξ· : u.1 β f ~ id), Ξ (a : A), u.2 (f a) = ap f (Ξ· a))
: sigma_assoc_equiv (Ξ»u, Ξ£(Ξ· : u.1 β f ~ id), Ξ (a : A), u.2 (f a) = ap f (Ξ· a))
local attribute is_contr_right_inverse [instance] [priority 1600]
local attribute is_contr_right_coherence [instance] [priority 1600]
theorem is_prop_is_equiv [instance] : is_prop (is_equiv f) :=
is_prop_of_imp_is_contr
(Ξ»(H : is_equiv f), is_contr_equiv_closed (equiv.symm !is_equiv.sigma_char') _)
definition inv_eq_inv {A B : Type} {f f' : A β B} {Hf : is_equiv f} {Hf' : is_equiv f'}
(p : f = f') : fβ»ΒΉ = f'β»ΒΉ :=
apd011 inv p !is_prop.elimo
/- contractible fibers -/
definition is_contr_fun_of_is_equiv [H : is_equiv f] : is_contr_fun f :=
is_contr_fiber_of_is_equiv f
definition is_prop_is_contr_fun (f : A β B) : is_prop (is_contr_fun f) := _
definition is_equiv_of_is_contr_fun [H : is_contr_fun f] : is_equiv f :=
adjointify _ (Ξ»b, point (center (fiber f b)))
(Ξ»b, point_eq (center (fiber f b)))
(Ξ»a, ap point (center_eq (fiber.mk a idp)))
definition is_equiv_of_imp_is_equiv (H : B β is_equiv f) : is_equiv f :=
@is_equiv_of_is_contr_fun _ _ f (Ξ»b, @is_contr_fiber_of_is_equiv _ _ _ (H b) _)
definition is_equiv_equiv_is_contr_fun : is_equiv f β is_contr_fun f :=
equiv_of_is_prop _ (Ξ»H, !is_equiv_of_is_contr_fun) _ _
theorem inv_commute'_fn {A : Type} {B C : A β Type} (f : Ξ {a}, B a β C a) [H : Ξ a, is_equiv (@f a)]
{g : A β A} (h : Ξ {a}, B a β B (g a)) (h' : Ξ {a}, C a β C (g a))
(p : Ξ β¦a : Aβ¦ (b : B a), f (h b) = h' (f b)) {a : A} (b : B a) :
inv_commute' @f @h @h' p (f b)
= (ap fβ»ΒΉ (p b))β»ΒΉ β¬ left_inv f (h b) β¬ (ap h (left_inv f b))β»ΒΉ :=
begin
rewrite [β[inv_commute',inj'],+ap_con,-adj_inv f,+con.assoc,inv_con_cancel_left,
adj f,+ap_inv,-+ap_compose,
eq_bot_of_square (natural_square_tr (Ξ»b, (left_inv f (h b))β»ΒΉ β¬ ap fβ»ΒΉ (p b)) (left_inv f b))β»ΒΉΚ°,
con_inv,inv_inv,+con.assoc],
do 3 apply whisker_left,
rewrite [con_inv_cancel_left,con.left_inv]
end
end is_equiv
/- Moving equivalences around in homotopies -/
namespace is_equiv
variables {A B C : Type} (f : A β B) [Hf : is_equiv f]
include Hf
section pre_compose
variables (Ξ± : A β C) (Ξ² : B β C)
-- homotopy_inv_of_homotopy_pre is in init.equiv
protected definition inv_homotopy_of_homotopy_pre.is_equiv
: is_equiv (inv_homotopy_of_homotopy_pre f Ξ± Ξ²) :=
adjointify _ (homotopy_of_inv_homotopy_pre f Ξ± Ξ²)
abstract begin
intro q, apply eq_of_homotopy, intro b,
unfold inv_homotopy_of_homotopy_pre,
unfold homotopy_of_inv_homotopy_pre,
apply inverse, apply eq_bot_of_square,
apply eq_hconcat (ap02 Ξ± (adj_inv f b)),
apply eq_hconcat (ap_compose Ξ± fβ»ΒΉ (right_inv f b))β»ΒΉ,
apply natural_square q (right_inv f b)
end end
abstract begin
intro p, apply eq_of_homotopy, intro a,
unfold inv_homotopy_of_homotopy_pre,
unfold homotopy_of_inv_homotopy_pre,
apply trans (con.assoc
(ap Ξ± (left_inv f a))β»ΒΉ
(p (fβ»ΒΉ (f a)))
(ap Ξ² (right_inv f (f a))))β»ΒΉ,
apply inverse, apply eq_bot_of_square,
refine hconcat_eq _ (ap02 Ξ² (adj f a))β»ΒΉ,
refine hconcat_eq _ (ap_compose Ξ² f (left_inv f a)),
apply natural_square p (left_inv f a)
end end
end pre_compose
section post_compose
variables (Ξ± : C β A) (Ξ² : C β B)
-- homotopy_inv_of_homotopy_post is in init.equiv
protected definition inv_homotopy_of_homotopy_post.is_equiv
: is_equiv (inv_homotopy_of_homotopy_post f Ξ± Ξ²) :=
adjointify _ (homotopy_of_inv_homotopy_post f Ξ± Ξ²)
abstract begin
intro q, apply eq_of_homotopy, intro c,
unfold inv_homotopy_of_homotopy_post,
unfold homotopy_of_inv_homotopy_post,
apply trans (whisker_right (left_inv f (Ξ± c))
(ap_con fβ»ΒΉ (right_inv f (Ξ² c))β»ΒΉ (ap f (q c))
β¬ whisker_right (ap fβ»ΒΉ (ap f (q c)))
(ap_inv fβ»ΒΉ (right_inv f (Ξ² c))))),
apply inverse, apply eq_bot_of_square,
apply eq_hconcat (adj_inv f (Ξ² c))β»ΒΉ,
apply eq_vconcat (ap_compose fβ»ΒΉ f (q c))β»ΒΉ,
refine vconcat_eq _ (ap_id (q c)),
apply natural_square_tr (left_inv f) (q c)
end end
abstract begin
intro p, apply eq_of_homotopy, intro c,
unfold inv_homotopy_of_homotopy_post,
unfold homotopy_of_inv_homotopy_post,
apply trans (whisker_left (right_inv f (Ξ² c))β»ΒΉ
(ap_con f (ap fβ»ΒΉ (p c)) (left_inv f (Ξ± c)))),
apply trans (con.assoc (right_inv f (Ξ² c))β»ΒΉ (ap f (ap fβ»ΒΉ (p c)))
(ap f (left_inv f (Ξ± c))))β»ΒΉ,
apply inverse, apply eq_bot_of_square,
refine hconcat_eq _ (adj f (Ξ± c)),
apply eq_vconcat (ap_compose f fβ»ΒΉ (p c))β»ΒΉ,
refine vconcat_eq _ (ap_id (p c)),
apply natural_square_tr (right_inv f) (p c)
end end
end post_compose
end is_equiv
namespace is_equiv
/- Theorem 4.7.7 -/
variables {A : Type} {P Q : A β Type}
variable (f : Ξ a, P a β Q a)
definition is_fiberwise_equiv [reducible] := Ξ a, is_equiv (f a)
definition is_equiv_total_of_is_fiberwise_equiv [H : is_fiberwise_equiv f] : is_equiv (total f) :=
is_equiv_sigma_functor id f
definition is_fiberwise_equiv_of_is_equiv_total [H : is_equiv (total f)]
: is_fiberwise_equiv f :=
begin
intro a,
apply is_equiv_of_is_contr_fun, intro q,
exact is_contr_equiv_closed (fiber_total_equiv f q) _
end
end is_equiv
namespace equiv
open is_equiv
variables {A B C : Type}
definition equiv_mk_eq {f f' : A β B} [H : is_equiv f] [H' : is_equiv f'] (p : f = f')
: equiv.mk f H = equiv.mk f' H' :=
apd011 equiv.mk p !is_prop.elimo
definition equiv_eq' {f f' : A β B} (p : to_fun f = to_fun f') : f = f' :=
by (cases f; cases f'; apply (equiv_mk_eq p))
definition equiv_eq {f f' : A β B} (p : to_fun f ~ to_fun f') : f = f' :=
by apply equiv_eq'; apply eq_of_homotopy p
definition ap_equiv_eq {X Y : Type} {e e' : X β Y} (p : e ~ e') (x : X) :
ap (Ξ»(e : X β Y), e x) (equiv_eq p) = p x :=
begin
cases e with e He, cases e' with e' He', esimp at *, esimp [equiv_eq],
refine homotopy.rec_on' p _, intro q, induction q, esimp [equiv_eq', equiv_mk_eq],
assert H : He = He', apply is_prop.elim, induction H, rewrite [is_prop_elimo_self]
end
definition trans_symm (f : A β B) (g : B β C) : (f β¬e g)β»ΒΉα΅ = gβ»ΒΉα΅ β¬e fβ»ΒΉα΅ :> (C β A) :=
equiv_eq' idp
definition symm_symm (f : A β B) : fβ»ΒΉα΅β»ΒΉα΅ = f :> (A β B) :=
equiv_eq' idp
protected definition equiv.sigma_char [constructor]
(A B : Type) : (A β B) β Ξ£(f : A β B), is_equiv f :=
begin
fapply equiv.MK,
{intro F, exact β¨to_fun F, to_is_equiv Fβ©},
{intro p, cases p with f H, exact (equiv.mk f H)},
{intro p, cases p, exact idp},
{intro F, cases F, exact idp},
end
definition equiv_eq_char (f f' : A β B) : (f = f') β (to_fun f = to_fun f') :=
calc
(f = f') β (!equiv.sigma_char f = !equiv.sigma_char f')
: eq_equiv_fn_eq !equiv.sigma_char
... β ((to_fun !equiv.sigma_char f).1 = (to_fun !equiv.sigma_char f').1 ) : equiv_subtype
... β (to_fun f = to_fun f') : equiv.rfl
definition is_equiv_ap_to_fun (f f' : A β B)
: is_equiv (ap to_fun : f = f' β to_fun f = to_fun f') :=
begin
fapply adjointify,
{intro p, cases f with f H, cases f' with f' H', cases p, apply ap (mk f'), apply is_prop.elim},
{intro p, cases f with f H, cases f' with f' H', cases p,
apply @concat _ _ (ap to_fun (ap (equiv.mk f') (is_prop.elim H H'))), {apply idp},
generalize is_prop.elim H H', intro q, cases q, apply idp},
{intro p, cases p, cases f with f H, apply ap (ap (equiv.mk f)), apply is_set.elim}
end
definition equiv_pathover {A : Type} {a a' : A} (p : a = a')
{B : A β Type} {C : A β Type} (f : B a β C a) (g : B a' β C a')
(r : to_fun f =[p] to_fun g) : f =[p] g :=
begin
fapply pathover_of_fn_pathover_fn,
{ intro a, apply equiv.sigma_char },
{ apply sigma_pathover _ _ _ r, apply is_prop.elimo }
end
definition equiv_pathover2 {A : Type} {a a' : A} (p : a = a')
{B : A β Type} {C : A β Type} (f : B a β C a) (g : B a' β C a')
(r : Ξ (b : B a) (b' : B a') (q : b =[p] b'), f b =[p] g b') : f =[p] g :=
begin
apply equiv_pathover, apply arrow_pathover, exact r
end
definition equiv_pathover_inv {A : Type} {a a' : A} (p : a = a')
{B : A β Type} {C : A β Type} (f : B a β C a) (g : B a' β C a')
(r : to_inv f =[p] to_inv g) : f =[p] g :=
begin
/- this proof is a bit weird, but it works -/
apply equiv_pathover,
change fβ»ΒΉαΆ β»ΒΉαΆ =[p] gβ»ΒΉαΆ β»ΒΉαΆ ,
apply apo (Ξ»(a: A) (h : C a β B a), hβ»ΒΉαΆ ),
apply equiv_pathover,
exact r
end
definition is_contr_equiv (A B : Type) [HA : is_contr A] [HB : is_contr B] : is_contr (A β B) :=
begin
refine is_contr_of_inhabited_prop _ _,
{ exact equiv_of_is_contr_of_is_contr _ _ },
{ apply is_prop.mk,
intro x y, cases x with fx Hx, cases y with fy Hy, generalize Hy,
apply (eq_of_homotopy (Ξ» a, !eq_of_is_contr)) βΈ (Ξ» Hy, !is_prop.elim βΈ rfl) }
end
definition is_trunc_succ_equiv (n : trunc_index) (A B : Type)
[HA : is_trunc n.+1 A] [HB : is_trunc n.+1 B] : is_trunc n.+1 (A β B) :=
@is_trunc_equiv_closed _ _ n.+1 (equiv.symm !equiv.sigma_char)
(@is_trunc_sigma _ _ _ _ (Ξ» f, is_trunc_succ_of_is_prop _ _ _))
definition is_trunc_equiv (n : trunc_index) (A B : Type)
[HA : is_trunc n A] [HB : is_trunc n B] : is_trunc n (A β B) :=
by cases n; apply !is_contr_equiv; apply !is_trunc_succ_equiv
definition inj'_idp {A B : Type} (f : A β B) [is_equiv f] (x : A)
: inj' f (idpath (f x)) = idpath x :=
!con.left_inv
definition inj'_con {A B : Type} (f : A β B) [is_equiv f] {x y z : A}
(p : f x = f y) (q : f y = f z)
: inj' f (p β¬ q) = inj' f p β¬ inj' f q :=
begin
unfold inj',
refine _ β¬ !con.assoc, apply whisker_right,
refine _ β¬ !con.assocβ»ΒΉ β¬ !con.assocβ»ΒΉ, apply whisker_left,
refine !ap_con β¬ _, apply whisker_left,
refine !con_inv_cancel_leftβ»ΒΉ
end
end equiv
|
1f0b61d412e3990a9d2e4ae73c75fbb541b33f96 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /12_Axioms.org.14.lean | 840903e59a53c32177cc5d988e09fba43b643a68 | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,280 | lean | import standard
import data.prod
open prod prod.ops quot
private definition eqv {A : Type} (pβ pβ : A Γ A) : Prop :=
(pβ.1 = pβ.1 β§ pβ.2 = pβ.2) β¨ (pβ.1 = pβ.2 β§ pβ.2 = pβ.1)
infix `~` := eqv
open eq or
local notation `β¨` Hβ `,` Hβ `β©` := and.intro Hβ Hβ
private theorem eqv.refl {A : Type} : β p : A Γ A, p ~ p :=
take p, inl β¨rfl, rflβ©
private theorem eqv.symm {A : Type} : β pβ pβ : A Γ A, pβ ~ pβ β pβ ~ pβ
| (aβ, aβ) (bβ, bβ) (inl β¨aβbβ, aβbββ©) := inl β¨symm aβbβ, symm aβbββ©
| (aβ, aβ) (bβ, bβ) (inr β¨aβbβ, aβbββ©) := inr β¨symm aβbβ, symm aβbββ©
private theorem eqv.trans {A : Type} : β pβ pβ pβ : A Γ A, pβ ~ pβ β pβ ~ pβ β pβ ~ pβ
| (aβ, aβ) (bβ, bβ) (cβ, cβ) (inl β¨aβbβ, aβbββ©) (inl β¨bβcβ, bβcββ©) :=
inl β¨trans aβbβ bβcβ, trans aβbβ bβcββ©
| (aβ, aβ) (bβ, bβ) (cβ, cβ) (inl β¨aβbβ, aβbββ©) (inr β¨bβcβ, bβcββ©) :=
inr β¨trans aβbβ bβcβ, trans aβbβ bβcββ©
| (aβ, aβ) (bβ, bβ) (cβ, cβ) (inr β¨aβbβ, aβbββ©) (inl β¨bβcβ, bβcββ©) :=
inr β¨trans aβbβ bβcβ, trans aβbβ bβcββ©
| (aβ, aβ) (bβ, bβ) (cβ, cβ) (inr β¨aβbβ, aβbββ©) (inr β¨bβcβ, bβcββ©) :=
inl β¨trans aβbβ bβcβ, trans aβbβ bβcββ©
private theorem is_equivalence (A : Type) : equivalence (@eqv A) :=
mk_equivalence (@eqv A) (@eqv.refl A) (@eqv.symm A) (@eqv.trans A)
definition uprod.setoid [instance] (A : Type) : setoid (A Γ A) :=
setoid.mk (@eqv A) (is_equivalence A)
definition uprod (A : Type) : Type :=
quot (uprod.setoid A)
namespace uprod
definition mk {A : Type} (aβ aβ : A) : uprod A :=
β¦(aβ, aβ)β§
notation `{` aβ `,` aβ `}` := mk aβ aβ
theorem mk_eq_mk {A : Type} (aβ aβ : A) : {aβ, aβ} = {aβ, aβ} :=
quot.sound (inr β¨rfl, rflβ©)
-- BEGIN
private definition mem_fn {A : Type} (a : A) : A Γ A β Prop
| (aβ, aβ) := a = aβ β¨ a = aβ
-- auxiliary lemma for proving mem_respects
private lemma mem_swap {A : Type} {a : A} : β {p : A Γ A}, mem_fn a p = mem_fn a (swap p)
| (aβ, aβ) := propext (iff.intro
(Ξ» l : a = aβ β¨ a = aβ, or.elim l (Ξ» hβ, inr hβ) (Ξ» hβ, inl hβ))
(Ξ» r : a = aβ β¨ a = aβ, or.elim r (Ξ» hβ, inr hβ) (Ξ» hβ, inl hβ)))
private lemma mem_respects {A : Type} : β {pβ pβ : A Γ A} (a : A), pβ ~ pβ β mem_fn a pβ = mem_fn a pβ
| (aβ, aβ) (bβ, bβ) a (inl β¨aβbβ, aβbββ©) :=
begin esimp at aβbβ, esimp at aβbβ, rewrite [aβbβ, aβbβ] end
| (aβ, aβ) (bβ, bβ) a (inr β¨aβbβ, aβbββ©) :=
begin esimp at aβbβ, esimp at aβbβ, rewrite [aβbβ, aβbβ], apply mem_swap end
definition mem {A : Type} (a : A) (u : uprod A) : Prop :=
quot.lift_on u (Ξ» p, mem_fn a p) (Ξ» pβ pβ e, mem_respects a e)
infix `β` := mem
theorem mem_mk_left {A : Type} (a b : A) : a β {a, b} :=
inl rfl
theorem mem_mk_right {A : Type} (a b : A) : b β {a, b} :=
inr rfl
theorem mem_or_mem_of_mem_mk {A : Type} {a b c : A} : c β {a, b} β c = a β¨ c = b :=
Ξ» h, h
-- END
end uprod
|
ae1b7952c94a755088b5570c35eaeb29b63be63f | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/tactic/pi_instances.lean | 5eefbb79cc75ea8a36bddc25bb61ad64999d985d | [
"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 | 1,812 | lean | /-
Copyright (c) 2018 Simon Hudon All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Simon Hudon
Automation for creating instances of mathematical structures for pi types
-/
import tactic.solve_by_elim order.basic
namespace tactic
open interactive interactive.types lean.parser expr
open functor has_seq list nat tactic.interactive
meta def derive_field : tactic unit :=
do b β target >>= is_prop,
field β get_current_field,
if b then do
field β get_current_field,
vs β introv [] <|> pure [],
hs β intros <|> pure [],
resetI,
x β get_unused_name,
try (() <$ ext1 [rcases_patt.one x] <|> () <$ intro x),
x' β try_core (get_local x),
applyc field,
hs.mmap (Ξ» h, try $
() <$ (to_expr ``(congr_fun %%h %%(x'.iget)) >>= apply) <|>
() <$ apply (h x'.iget) <|>
() <$ (to_expr ``(set.mem_image_of_mem _ %%h) >>= apply) <|>
() <$ (solve_by_elim) ),
return ()
else focus1 $ do
field β get_current_field,
e β mk_const field,
expl_arity β get_expl_arity e,
xs β (iota expl_arity).mmap $ Ξ» _, intro1,
x β intro1,
applyc field,
xs.mmap' (Ξ» h, try $ () <$ (apply (h x) <|> apply h) <|> refine ``(set.image ($ %%x) %%h)) <|> fail "args",
return ()
/--
`pi_instance` constructs an instance of `my_class (Ξ i : I, f i)`
where we know `Ξ i, my_class (f i)`. If an order relation is required,
it defaults to `pi.partial_order`. Any field of the instance that
`pi_instance` cannot construct is left untouched and generated as a new goal.
-/
meta def pi_instance : tactic unit :=
refine_struct ``( { ..pi.partial_order, .. } );
propagate_tags (try (derive_field ; done))
run_cmd add_interactive [`pi_instance]
end tactic
|
dd00021bf5a4680c165bcb189292ecaba9d72aa0 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/dep_bug.lean | a87316a5f77d63d6f66f91f5af94f42351865a16 | [
"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 | 301 | lean | open tactic
example (a b c : nat) (H : c = b) : a + c = a + b :=
by do
N β to_expr ``(nat),
define `v N,
trace_state,
trace "------------",
to_expr ```(a + b) >>= exact,
trace_state,
trace "------------",
get_local `H >>= subst,
trace_state,
to_expr ```(eq.refl v) >>= exact
|
a598e3bc187d0c37d5ff91859e8582ab8b22fd48 | 59a4b050600ed7b3d5826a8478db0a9bdc190252 | /src/category_theory/universal/uniqueness.lean | 55f007b807a75a3196cbe7f55d3c07d2c4fd0cee | [] | no_license | rwbarton/lean-category-theory | f720268d800b62a25d69842ca7b5d27822f00652 | 00df814d463406b7a13a56f5dcda67758ba1b419 | refs/heads/master | 1,585,366,296,767 | 1,536,151,349,000 | 1,536,151,349,000 | 147,652,096 | 0 | 0 | null | 1,536,226,960,000 | 1,536,226,960,000 | null | UTF-8 | Lean | false | false | 1,977 | lean | import category_theory.limits
universes u v
open category_theory
namespace category_theory.limits
variables {C : Type u} [π : category.{u v} C]
include π
section
@[extensionality] lemma homs_to_terminal_ext (X' : C) (X : C) [is_terminal.{u v} X] (f g : X' βΆ X) : f = g :=
begin
rw is_terminal.uniq X X' f,
rw is_terminal.uniq X X' g,
end
def terminals_iso (A B : C) [is_terminal.{u v} A] [is_terminal.{u v} B] : A β
B :=
{ hom := is_terminal.lift.{u v} B A,
inv := is_terminal.lift.{u v} A B }
end
section
def binary_products_iso {Y Z : C} (A B : span.{u v} Y Z) [is_binary_product A] [is_binary_product B] : A.X β
B.X :=
{ hom := is_binary_product.lift _ A,
inv := is_binary_product.lift _ B,
hom_inv_id' := sorry,
inv_hom_id' := sorry }
end
section
def equalizers_iso {Y Z : C} {f g : Y βΆ Z} (A B : fork.{u v} f g) (A_w : is_equalizer A) (B_w : is_equalizer B) : A.X β
B.X :=
{ hom := B_w.lift A,
inv := A_w.lift B,
hom_inv_id' := sorry,
inv_hom_id' := sorry }
end
section
def pullbacks_iso {Yβ Yβ Z : C} {rβ : Yβ βΆ Z} {rβ : Yβ βΆ Z} (A B : square.{u v} rβ rβ) (A_w : is_pullback A) (B_w : is_pullback B): A.X β
B.X :=
{ hom := B_w.lift A,
inv := A_w.lift B,
hom_inv_id' := sorry,
inv_hom_id' := sorry }
end
variables {J : Type v} [π₯ : small_category J]
include π₯
section
-- FIXME this is a horrible formulation
lemma homs_to_limit_ext {F : J β₯€ C} (c : cone.{u v} F) [is_limit c] {X : C} (f g : X βΆ c.X) (w : β j, f β« c.Ο j = g β« c.Ο j) : f = g :=
begin
let s : cone F := β¨ β¨ X β©, Ξ» j, f β« c.Ο j, by obviously β©,
have q := is_limit.uniq _ s f,
have p := is_limit.uniq _ s g,
rw [q, βp],
intros,
rw β w j,
intros,
refl
end
local attribute [back] homs_to_limit_ext
def limits_iso {F : J β₯€ C} (A B : cone.{u v} F) [is_limit A] [is_limit B] : A.X β
B.X :=
{ hom := is_limit.lift _ A,
inv := is_limit.lift _ B }
end
end category_theory.limits
|
a1308ee9df0acf6812eb888ada76198dfe7c66f6 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/analysis/normed_space/hahn_banach/extension.lean | 103c5f6d682639f055fdb64e05f86f853d8fdfa1 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 6,812 | lean | /-
Copyright (c) 2020 Yury Kudryashov All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Heather Macbeth
-/
import analysis.convex.cone
import analysis.normed_space.is_R_or_C
import analysis.normed_space.extend
/-!
# Extension Hahn-Banach theorem
In this file we prove the analytic Hahn-Banach theorem. For any continuous linear function on a
subspace, we can extend it to a function on the entire space without changing its norm.
We prove
* `real.exists_extension_norm_eq`: Hahn-Banach theorem for continuous linear functions on normed
spaces over `β`.
* `exists_extension_norm_eq`: Hahn-Banach theorem for continuous linear functions on normed spaces
over `β` or `β`.
In order to state and prove the corollaries uniformly, we prove the statements for a field `π`
satisfying `is_R_or_C π`.
In this setting, `exists_dual_vector` states that, for any nonzero `x`, there exists a continuous
linear form `g` of norm `1` with `g x = β₯xβ₯` (where the norm has to be interpreted as an element
of `π`).
-/
universes u v
namespace real
variables {E : Type*} [seminormed_add_comm_group E] [normed_space β E]
/-- Hahn-Banach theorem for continuous linear functions over `β`. -/
theorem exists_extension_norm_eq (p : subspace β E) (f : p βL[β] β) :
β g : E βL[β] β, (β x : p, g x = f x) β§ β₯gβ₯ = β₯fβ₯ :=
begin
rcases exists_extension_of_le_sublinear β¨p, fβ© (Ξ» x, β₯fβ₯ * β₯xβ₯)
(Ξ» c hc x, by simp only [norm_smul c x, real.norm_eq_abs, abs_of_pos hc, mul_left_comm])
(Ξ» x y, _) (Ξ» x, le_trans (le_abs_self _) (f.le_op_norm _))
with β¨g, g_eq, g_leβ©,
set g' := g.mk_continuous (β₯fβ₯)
(Ξ» x, abs_le.2 β¨neg_le.1 $ g.map_neg x βΈ norm_neg x βΈ g_le (-x), g_le xβ©),
{ refine β¨g', g_eq, _β©,
{ apply le_antisymm (g.mk_continuous_norm_le (norm_nonneg f) _),
refine f.op_norm_le_bound (norm_nonneg _) (Ξ» x, _),
dsimp at g_eq,
rw β g_eq,
apply g'.le_op_norm } },
{ simp only [β mul_add],
exact mul_le_mul_of_nonneg_left (norm_add_le x y) (norm_nonneg f) }
end
end real
section is_R_or_C
open is_R_or_C
variables {π : Type*} [is_R_or_C π] {F : Type*} [seminormed_add_comm_group F] [normed_space π F]
/-- Hahn-Banach theorem for continuous linear functions over `π` satisyfing `is_R_or_C π`. -/
theorem exists_extension_norm_eq (p : subspace π F) (f : p βL[π] π) :
β g : F βL[π] π, (β x : p, g x = f x) β§ β₯gβ₯ = β₯fβ₯ :=
begin
letI : module β F := restrict_scalars.module β π F,
letI : is_scalar_tower β π F := restrict_scalars.is_scalar_tower _ _ _,
letI : normed_space β F := normed_space.restrict_scalars _ π _,
-- Let `fr: p βL[β] β` be the real part of `f`.
let fr := re_clm.comp (f.restrict_scalars β),
have fr_apply : β x, fr x = re (f x), by { assume x, refl },
-- Use the real version to get a norm-preserving extension of `fr`, which
-- we'll call `g : F βL[β] β`.
rcases real.exists_extension_norm_eq (p.restrict_scalars β) fr with β¨g, β¨hextends, hnormeqβ©β©,
-- Now `g` can be extended to the `F βL[π] π` we need.
refine β¨g.extend_to_π, _β©,
-- It is an extension of `f`.
have h : β x : p, g.extend_to_π x = f x,
{ assume x,
rw [continuous_linear_map.extend_to_π_apply, βsubmodule.coe_smul, hextends, hextends],
have : (fr x : π) - I * β(fr (I β’ x)) = (re (f x) : π) - (I : π) * (re (f ((I : π) β’ x))),
by refl,
rw this,
apply ext,
{ simp only [add_zero, algebra.id.smul_eq_mul, I_re, of_real_im, add_monoid_hom.map_add,
zero_sub, I_im', zero_mul, of_real_re, eq_self_iff_true, sub_zero, mul_neg,
of_real_neg, mul_re, mul_zero, sub_neg_eq_add, continuous_linear_map.map_smul] },
{ simp only [algebra.id.smul_eq_mul, I_re, of_real_im, add_monoid_hom.map_add, zero_sub, I_im',
zero_mul, of_real_re, mul_neg, mul_im, zero_add, of_real_neg, mul_re,
sub_neg_eq_add, continuous_linear_map.map_smul] } },
-- And we derive the equality of the norms by bounding on both sides.
refine β¨h, le_antisymm _ _β©,
{ calc β₯g.extend_to_πβ₯
β€ β₯gβ₯ : g.extend_to_π.op_norm_le_bound g.op_norm_nonneg (norm_bound _)
... = β₯frβ₯ : hnormeq
... β€ β₯re_clmβ₯ * β₯fβ₯ : continuous_linear_map.op_norm_comp_le _ _
... = β₯fβ₯ : by rw [re_clm_norm, one_mul] },
{ exact f.op_norm_le_bound g.extend_to_π.op_norm_nonneg (Ξ» x, h x βΈ g.extend_to_π.le_op_norm x) }
end
end is_R_or_C
section dual_vector
variables (π : Type v) [is_R_or_C π]
variables {E : Type u} [normed_add_comm_group E] [normed_space π E]
open continuous_linear_equiv submodule
open_locale classical
lemma coord_norm' {x : E} (h : x β 0) : β₯(β₯xβ₯ : π) β’ coord π x hβ₯ = 1 :=
by rw [norm_smul, is_R_or_C.norm_coe_norm, coord_norm, mul_inv_cancel (mt norm_eq_zero.mp h)]
/-- Corollary of Hahn-Banach. Given a nonzero element `x` of a normed space, there exists an
element of the dual space, of norm `1`, whose value on `x` is `β₯xβ₯`. -/
theorem exists_dual_vector (x : E) (h : x β 0) : β g : E βL[π] π, β₯gβ₯ = 1 β§ g x = β₯xβ₯ :=
begin
let p : submodule π E := π β x,
let f := (β₯xβ₯ : π) β’ coord π x h,
obtain β¨g, hgβ© := exists_extension_norm_eq p f,
refine β¨g, _, _β©,
{ rw [hg.2, coord_norm'] },
{ calc g x = g (β¨x, mem_span_singleton_self xβ© : π β x) : by rw coe_mk
... = ((β₯xβ₯ : π) β’ coord π x h) (β¨x, mem_span_singleton_self xβ© : π β x) : by rw β hg.1
... = β₯xβ₯ : by simp }
end
/-- Variant of Hahn-Banach, eliminating the hypothesis that `x` be nonzero, and choosing
the dual element arbitrarily when `x = 0`. -/
theorem exists_dual_vector' [nontrivial E] (x : E) :
β g : E βL[π] π, β₯gβ₯ = 1 β§ g x = β₯xβ₯ :=
begin
by_cases hx : x = 0,
{ obtain β¨y, hyβ© := exists_ne (0 : E),
obtain β¨g, hgβ© : β g : E βL[π] π, β₯gβ₯ = 1 β§ g y = β₯yβ₯ := exists_dual_vector π y hy,
refine β¨g, hg.left, _β©,
simp [hx] },
{ exact exists_dual_vector π x hx }
end
/-- Variant of Hahn-Banach, eliminating the hypothesis that `x` be nonzero, but only ensuring that
the dual element has norm at most `1` (this can not be improved for the trivial
vector space). -/
theorem exists_dual_vector'' (x : E) :
β g : E βL[π] π, β₯gβ₯ β€ 1 β§ g x = β₯xβ₯ :=
begin
by_cases hx : x = 0,
{ refine β¨0, by simp, _β©,
symmetry,
simp [hx], },
{ rcases exists_dual_vector π x hx with β¨g, g_norm, g_eqβ©,
exact β¨g, g_norm.le, g_eqβ© }
end
end dual_vector
|
871c06b7183f0cc0c71c502c01a9e13534c44b8d | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/data/polynomial/field_division.lean | a927d2f8cbabc9580c98847c6759645a00288103 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 21,313 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes HΓΆlzl, Scott Morrison, Jens Wagemaker
-/
import data.polynomial.derivative
import data.polynomial.ring_division
import ring_theory.euclidean_domain
/-!
# Theory of univariate polynomials
This file starts looking like the ring theory of $ R[X] $
-/
noncomputable theory
open_locale classical big_operators polynomial
namespace polynomial
universes u v w y z
variables {R : Type u} {S : Type v} {k : Type y} {A : Type z} {a b : R} {n : β}
section is_domain
variables [comm_ring R] [is_domain R]
lemma roots_C_mul (p : R[X]) {a : R} (hzero : a β 0) : (C a * p).roots = p.roots :=
begin
by_cases hpzero : p = 0,
{ simp only [hpzero, mul_zero] },
rw multiset.ext,
intro b,
have prodzero : C a * p β 0,
{ simp only [hpzero, or_false, ne.def, mul_eq_zero, C_eq_zero, hzero, not_false_iff] },
rw [count_roots, count_roots, root_multiplicity_mul prodzero],
have mulzero : root_multiplicity b (C a) = 0,
{ simp only [hzero, root_multiplicity_eq_zero, eval_C, is_root.def, not_false_iff] },
simp only [mulzero, zero_add]
end
lemma derivative_root_multiplicity_of_root [char_zero R] {p : R[X]} {t : R} (hpt : p.is_root t) :
p.derivative.root_multiplicity t = p.root_multiplicity t - 1 :=
begin
rcases eq_or_ne p 0 with rfl | hp,
{ simp },
nth_rewrite 0 [βp.div_by_monic_mul_pow_root_multiplicity_eq t],
simp only [derivative_pow, derivative_mul, derivative_sub, derivative_X,
derivative_C, sub_zero, mul_one],
set n := p.root_multiplicity t - 1,
have hn : n + 1 = _ := tsub_add_cancel_of_le ((root_multiplicity_pos hp).mpr hpt),
rw βhn,
set q := p /β (X - C t) ^ (n + 1) with hq,
convert_to root_multiplicity t ((X - C t) ^ n * (derivative q * (X - C t) + q * β(n + 1))) = n,
{ congr,
rw [mul_add, mul_left_comm $ (X - C t) ^ n, βpow_succ'],
congr' 1,
rw [mul_left_comm $ (X - C t) ^ n, mul_comm $ (X - C t) ^ n] },
have h : (derivative q * (X - C t) + q * β(n + 1)).eval t β 0,
{ suffices : eval t q * β(n + 1) β 0,
{ simpa },
refine mul_ne_zero _ (nat.cast_ne_zero.mpr n.succ_ne_zero),
convert eval_div_by_monic_pow_root_multiplicity_ne_zero t hp,
exact hn βΈ hq },
rw [root_multiplicity_mul, root_multiplicity_X_sub_C_pow, root_multiplicity_eq_zero h, add_zero],
refine mul_ne_zero (pow_ne_zero n $ X_sub_C_ne_zero t) _,
contrapose! h,
rw [h, eval_zero]
end
lemma root_multiplicity_sub_one_le_derivative_root_multiplicity [char_zero R] (p : R[X]) (t : R) :
p.root_multiplicity t - 1 β€ p.derivative.root_multiplicity t :=
begin
by_cases p.is_root t,
{ exact (derivative_root_multiplicity_of_root h).symm.le },
{ rw [root_multiplicity_eq_zero h, zero_tsub],
exact zero_le _ }
end
section normalization_monoid
variables [normalization_monoid R]
instance : normalization_monoid R[X] :=
{ norm_unit := Ξ» p, β¨C β(norm_unit (p.leading_coeff)), C β(norm_unit (p.leading_coeff))β»ΒΉ,
by rw [β ring_hom.map_mul, units.mul_inv, C_1], by rw [β ring_hom.map_mul, units.inv_mul, C_1]β©,
norm_unit_zero := units.ext (by simp),
norm_unit_mul := Ξ» p q hp0 hq0, units.ext (begin
dsimp,
rw [ne.def, β leading_coeff_eq_zero] at *,
rw [leading_coeff_mul, norm_unit_mul hp0 hq0, units.coe_mul, C_mul],
end),
norm_unit_coe_units := Ξ» u,
units.ext begin
rw [β mul_one uβ»ΒΉ, units.coe_mul, units.eq_inv_mul_iff_mul_eq],
dsimp,
rcases polynomial.is_unit_iff.1 β¨u, rflβ© with β¨_, β¨w, rflβ©, h2β©,
rw [β h2, leading_coeff_C, norm_unit_coe_units, β C_mul, units.mul_inv, C_1],
end }
@[simp]
lemma coe_norm_unit {p : R[X]} :
(norm_unit p : R[X]) = C β(norm_unit p.leading_coeff) :=
by simp [norm_unit]
lemma leading_coeff_normalize (p : R[X]) :
leading_coeff (normalize p) = normalize (leading_coeff p) := by simp
lemma monic.normalize_eq_self {p : R[X]} (hp : p.monic) :
normalize p = p :=
by simp only [polynomial.coe_norm_unit, normalize_apply, hp.leading_coeff, norm_unit_one,
units.coe_one, polynomial.C.map_one, mul_one]
lemma roots_normalize {p : R[X]} : (normalize p).roots = p.roots :=
by rw [normalize_apply, mul_comm, coe_norm_unit,
roots_C_mul _ (norm_unit (leading_coeff p)).ne_zero]
end normalization_monoid
end is_domain
section division_ring
variables [division_ring R] {p q : R[X]}
lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p β 0) (hp : Β¬is_unit p) :
0 < degree p :=
lt_of_not_ge (Ξ» h, begin
rw [eq_C_of_degree_le_zero h] at hp0 hp,
exact hp (is_unit.map C
(is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))),
end)
lemma monic_mul_leading_coeff_inv (h : p β 0) :
monic (p * C (leading_coeff p)β»ΒΉ) :=
by rw [monic, leading_coeff_mul, leading_coeff_C,
mul_inv_cancel (show leading_coeff p β 0, from mt leading_coeff_eq_zero.1 h)]
lemma degree_mul_leading_coeff_inv (p : R[X]) (h : q β 0) :
degree (p * C (leading_coeff q)β»ΒΉ) = degree p :=
have hβ : (leading_coeff q)β»ΒΉ β 0 :=
inv_ne_zero (mt leading_coeff_eq_zero.1 h),
by rw [degree_mul, degree_C hβ, add_zero]
@[simp] lemma map_eq_zero [semiring S] [nontrivial S] (f : R β+* S) : p.map f = 0 β p = 0 :=
by simp only [polynomial.ext_iff, map_eq_zero, coeff_map, coeff_zero]
lemma map_ne_zero [semiring S] [nontrivial S] {f : R β+* S} (hp : p β 0) : p.map f β 0 :=
mt (map_eq_zero f).1 hp
end division_ring
section field
variables [field R] {p q : R[X]}
lemma is_unit_iff_degree_eq_zero : is_unit p β degree p = 0 :=
β¨degree_eq_zero_of_is_unit,
Ξ» h, have degree p β€ 0, by simp [*, le_refl],
have hc : coeff p 0 β 0, from Ξ» hc,
by rw [eq_C_of_degree_le_zero this, hc] at h;
simpa using h,
is_unit_iff_dvd_one.2 β¨C (coeff p 0)β»ΒΉ, begin
conv in p { rw eq_C_of_degree_le_zero this },
rw [β C_mul, _root_.mul_inv_cancel hc, C_1]
endβ©β©
theorem irreducible_of_monic {p : R[X]} (hp1 : p.monic) (hp2 : p β 1) :
irreducible p β (β f g : R[X], f.monic β g.monic β f * g = p β f = 1 β¨ g = 1) :=
β¨Ξ» hp3 f g hf hg hfg, or.cases_on (hp3.is_unit_or_is_unit hfg.symm)
(assume huf : is_unit f, or.inl $ eq_one_of_is_unit_of_monic hf huf)
(assume hug : is_unit g, or.inr $ eq_one_of_is_unit_of_monic hg hug),
Ξ» hp3, β¨mt (eq_one_of_is_unit_of_monic hp1) hp2, Ξ» f g hp,
have hf : f β 0, from Ξ» hf, by { rw [hp, hf, zero_mul] at hp1, exact not_monic_zero hp1 },
have hg : g β 0, from Ξ» hg, by { rw [hp, hg, mul_zero] at hp1, exact not_monic_zero hp1 },
or.imp (Ξ» hf, is_unit_of_mul_eq_one _ _ hf) (Ξ» hg, is_unit_of_mul_eq_one _ _ hg) $
hp3 (f * C f.leading_coeffβ»ΒΉ) (g * C g.leading_coeffβ»ΒΉ)
(monic_mul_leading_coeff_inv hf) (monic_mul_leading_coeff_inv hg) $
by rw [mul_assoc, mul_left_comm _ g, β mul_assoc, β C_mul, β mul_inv, β leading_coeff_mul,
β hp, monic.def.1 hp1, inv_one, C_1, mul_one]β©β©
/-- Division of polynomials. See `polynomial.div_by_monic` for more details.-/
def div (p q : R[X]) :=
C (leading_coeff q)β»ΒΉ * (p /β (q * C (leading_coeff q)β»ΒΉ))
/-- Remainder of polynomial division. See `polynomial.mod_by_monic` for more details. -/
def mod (p q : R[X]) :=
p %β (q * C (leading_coeff q)β»ΒΉ)
private lemma quotient_mul_add_remainder_eq_aux (p q : R[X]) :
q * div p q + mod p q = p :=
if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add]
else begin
conv {to_rhs, rw β mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)},
rw [div, mod, add_comm, mul_assoc]
end
private lemma remainder_lt_aux (p : R[X]) (hq : q β 0) :
degree (mod p q) < degree q :=
by rw β degree_mul_leading_coeff_inv q hq; exact
degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq)
instance : has_div R[X] := β¨divβ©
instance : has_mod R[X] := β¨modβ©
lemma div_def : p / q = C (leading_coeff q)β»ΒΉ * (p /β (q * C (leading_coeff q)β»ΒΉ)) := rfl
lemma mod_def : p % q = p %β (q * C (leading_coeff q)β»ΒΉ) := rfl
lemma mod_by_monic_eq_mod (p : R[X]) (hq : monic q) : p %β q = p % q :=
show p %β q = p %β (q * C (leading_coeff q)β»ΒΉ), by simp only [monic.def.1 hq, inv_one, mul_one, C_1]
lemma div_by_monic_eq_div (p : R[X]) (hq : monic q) : p /β q = p / q :=
show p /β q = C (leading_coeff q)β»ΒΉ * (p /β (q * C (leading_coeff q)β»ΒΉ)),
by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one]
lemma mod_X_sub_C_eq_C_eval (p : R[X]) (a : R) : p % (X - C a) = C (p.eval a) :=
mod_by_monic_eq_mod p (monic_X_sub_C a) βΈ mod_by_monic_X_sub_C_eq_C_eval _ _
lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p β is_root p a :=
div_by_monic_eq_div p (monic_X_sub_C a) βΈ mul_div_by_monic_eq_iff_is_root
instance : euclidean_domain R[X] :=
{ quotient := (/),
quotient_zero := by simp [div_def],
remainder := (%),
r := _,
r_well_founded := degree_lt_wf,
quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux,
remainder_lt := Ξ» p q hq, remainder_lt_aux _ hq,
mul_left_not_lt := Ξ» p q hq, not_lt_of_ge (degree_le_mul_left _ hq),
.. polynomial.comm_ring,
.. polynomial.nontrivial }
lemma mod_eq_self_iff (hq0 : q β 0) : p % q = p β degree p < degree q :=
β¨Ξ» h, h βΈ euclidean_domain.mod_lt _ hq0,
Ξ» h, have Β¬degree (q * C (leading_coeff q)β»ΒΉ) β€ degree p :=
not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0,
begin
rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)],
unfold div_mod_by_monic_aux,
simp only [this, false_and, if_false]
endβ©
lemma div_eq_zero_iff (hq0 : q β 0) : p / q = 0 β degree p < degree q :=
β¨Ξ» h, by have := euclidean_domain.div_add_mod p q;
rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this,
Ξ» h, have hlt : degree p < degree (q * C (leading_coeff q)β»ΒΉ),
by rwa degree_mul_leading_coeff_inv q hq0,
have hm : monic (q * C (leading_coeff q)β»ΒΉ) := monic_mul_leading_coeff_inv hq0,
by rw [div_def, (div_by_monic_eq_zero_iff hm).2 hlt, mul_zero]β©
lemma degree_add_div (hq0 : q β 0) (hpq : degree q β€ degree p) :
degree q + degree (p / q) = degree p :=
have degree (p % q) < degree (q * (p / q)) :=
calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0
... β€ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)),
by conv_rhs { rw [β euclidean_domain.div_add_mod p q,
degree_add_eq_left_of_degree_lt this, degree_mul] }
lemma degree_div_le (p q : R[X]) : degree (p / q) β€ degree p :=
if hq : q = 0 then by simp [hq]
else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq];
exact degree_div_by_monic_le _ _
lemma degree_div_lt (hp : p β 0) (hq : 0 < degree q) : degree (p / q) < degree p :=
have hq0 : q β 0, from Ξ» hq0, by simpa [hq0] using hq,
by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0];
exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp
(by rw degree_mul_leading_coeff_inv _ hq0; exact hq)
@[simp] lemma degree_map [division_ring k] (p : R[X]) (f : R β+* k) :
degree (p.map f) = degree p :=
p.degree_map_eq_of_injective f.injective
@[simp] lemma nat_degree_map [division_ring k] (f : R β+* k) :
nat_degree (p.map f) = nat_degree p :=
nat_degree_eq_of_degree_eq (degree_map _ f)
@[simp] lemma leading_coeff_map [division_ring k] (f : R β+* k) :
leading_coeff (p.map f) = f (leading_coeff p) :=
by simp only [β coeff_nat_degree, coeff_map f, nat_degree_map]
theorem monic_map_iff [division_ring k] {f : R β+* k} {p : R[X]} :
(p.map f).monic β p.monic :=
by rw [monic, leading_coeff_map, β f.map_one, function.injective.eq_iff f.injective, monic]
theorem is_unit_map [field k] (f : R β+* k) :
is_unit (p.map f) β is_unit p :=
by simp_rw [is_unit_iff_degree_eq_zero, degree_map]
lemma map_div [field k] (f : R β+* k) :
(p / q).map f = p.map f / q.map f :=
if hq0 : q = 0 then by simp [hq0]
else
by rw [div_def, div_def, polynomial.map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)];
simp [coeff_map f]
lemma map_mod [field k] (f : R β+* k) :
(p % q).map f = p.map f % q.map f :=
if hq0 : q = 0 then by simp [hq0]
else by rw [mod_def, mod_def, leading_coeff_map f, β map_invβ f, β map_C f,
β polynomial.map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)]
section
open euclidean_domain
theorem gcd_map [field k] (f : R β+* k) :
gcd (p.map f) (q.map f) = (gcd p q).map f :=
gcd.induction p q (Ξ» x, by simp_rw [polynomial.map_zero, euclidean_domain.gcd_zero_left]) $
Ξ» x y hx ih,
by rw [gcd_val, β map_mod, ih, β gcd_val]
end
lemma evalβ_gcd_eq_zero [comm_semiring k] {Ο : R β+* k} {f g : R[X]} {Ξ± : k}
(hf : f.evalβ Ο Ξ± = 0) (hg : g.evalβ Ο Ξ± = 0) : (euclidean_domain.gcd f g).evalβ Ο Ξ± = 0 :=
by rw [euclidean_domain.gcd_eq_gcd_ab f g, polynomial.evalβ_add, polynomial.evalβ_mul,
polynomial.evalβ_mul, hf, hg, zero_mul, zero_mul, zero_add]
lemma eval_gcd_eq_zero {f g : R[X]} {Ξ± : R} (hf : f.eval Ξ± = 0) (hg : g.eval Ξ± = 0) :
(euclidean_domain.gcd f g).eval Ξ± = 0 := evalβ_gcd_eq_zero hf hg
lemma root_left_of_root_gcd [comm_semiring k] {Ο : R β+* k} {f g : R[X]} {Ξ± : k}
(hΞ± : (euclidean_domain.gcd f g).evalβ Ο Ξ± = 0) : f.evalβ Ο Ξ± = 0 :=
by { cases euclidean_domain.gcd_dvd_left f g with p hp,
rw [hp, polynomial.evalβ_mul, hΞ±, zero_mul] }
lemma root_right_of_root_gcd [comm_semiring k] {Ο : R β+* k} {f g : R[X]} {Ξ± : k}
(hΞ± : (euclidean_domain.gcd f g).evalβ Ο Ξ± = 0) : g.evalβ Ο Ξ± = 0 :=
by { cases euclidean_domain.gcd_dvd_right f g with p hp,
rw [hp, polynomial.evalβ_mul, hΞ±, zero_mul] }
lemma root_gcd_iff_root_left_right [comm_semiring k] {Ο : R β+* k} {f g : R[X]} {Ξ± : k} :
(euclidean_domain.gcd f g).evalβ Ο Ξ± = 0 β (f.evalβ Ο Ξ± = 0) β§ (g.evalβ Ο Ξ± = 0) :=
β¨Ξ» h, β¨root_left_of_root_gcd h, root_right_of_root_gcd hβ©, Ξ» h, evalβ_gcd_eq_zero h.1 h.2β©
lemma is_root_gcd_iff_is_root_left_right {f g : R[X]} {Ξ± : R} :
(euclidean_domain.gcd f g).is_root Ξ± β f.is_root Ξ± β§ g.is_root Ξ± :=
root_gcd_iff_root_left_right
theorem is_coprime_map [field k] (f : R β+* k) :
is_coprime (p.map f) (q.map f) β is_coprime p q :=
by rw [β euclidean_domain.gcd_is_unit_iff, β euclidean_domain.gcd_is_unit_iff, gcd_map, is_unit_map]
lemma mem_roots_map [comm_ring k] [is_domain k] {f : R β+* k} {x : k} (hp : p β 0) :
x β (p.map f).roots β p.evalβ f x = 0 :=
begin
rw mem_roots (show p.map f β 0, by exact map_ne_zero hp),
dsimp only [is_root],
rw polynomial.eval_map,
end
lemma mem_root_set [comm_ring k] [is_domain k] [algebra R k] {x : k} (hp : p β 0) :
x β p.root_set k β aeval x p = 0 :=
iff.trans multiset.mem_to_finset (mem_roots_map hp)
lemma root_set_C_mul_X_pow [comm_ring S] [is_domain S] [algebra R S]
{n : β} (hn : n β 0) {a : R} (ha : a β 0) : (C a * X ^ n).root_set S = {0} :=
begin
ext x,
rw [set.mem_singleton_iff, mem_root_set, aeval_mul, aeval_C, aeval_X_pow, mul_eq_zero],
{ simp_rw [_root_.map_eq_zero, pow_eq_zero_iff (nat.pos_of_ne_zero hn), or_iff_right_iff_imp],
exact Ξ» ha', (ha ha').elim },
{ exact mul_ne_zero (mt C_eq_zero.mp ha) (pow_ne_zero n X_ne_zero) },
end
lemma root_set_monomial [comm_ring S] [is_domain S] [algebra R S]
{n : β} (hn : n β 0) {a : R} (ha : a β 0) : (monomial n a).root_set S = {0} :=
by rw [βC_mul_X_pow_eq_monomial, root_set_C_mul_X_pow hn ha]
lemma root_set_X_pow [comm_ring S] [is_domain S] [algebra R S]
{n : β} (hn : n β 0) : (X ^ n : R[X]).root_set S = {0} :=
by { rw [βone_mul (X ^ n : R[X]), βC_1, root_set_C_mul_X_pow hn], exact one_ne_zero }
lemma root_set_prod [comm_ring S] [is_domain S] [algebra R S]
{ΞΉ : Type*} (f : ΞΉ β R[X]) (s : finset ΞΉ) (h : s.prod f β 0) :
(s.prod f).root_set S = β (i β s), (f i).root_set S :=
begin
simp only [root_set, βfinset.mem_coe],
rw [polynomial.map_prod, roots_prod, finset.bind_to_finset, s.val_to_finset, finset.coe_bUnion],
rwa [βpolynomial.map_prod, ne, map_eq_zero],
end
lemma exists_root_of_degree_eq_one (h : degree p = 1) : β x, is_root p x :=
β¨-(p.coeff 0 / p.coeff 1),
have p.coeff 1 β 0,
by rw β nat_degree_eq_of_degree_eq_some h;
exact mt leading_coeff_eq_zero.1 (Ξ» h0, by simpa [h0] using h),
by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p β€ 1, by rw h; exact le_rfl)] };
simp [is_root, mul_div_cancel' _ this]β©
lemma coeff_inv_units (u : R[X]Λ£) (n : β) :
((βu : R[X]).coeff n)β»ΒΉ = ((βuβ»ΒΉ : R[X]).coeff n) :=
begin
rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units uβ»ΒΉ),
coeff_C, coeff_C, inv_eq_one_div],
split_ifs,
{ rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero,
coeff_zero_eq_eval_zero, β eval_mul, β units.coe_mul, inv_mul_self];
simp },
{ simp }
end
lemma monic_normalize (hp0 : p β 0) : monic (normalize p) :=
begin
rw [ne.def, β leading_coeff_eq_zero, β ne.def, β is_unit_iff_ne_zero] at hp0,
rw [monic, leading_coeff_normalize, normalize_eq_one],
apply hp0,
end
lemma leading_coeff_div (hpq : q.degree β€ p.degree) :
(p / q).leading_coeff = p.leading_coeff / q.leading_coeff :=
begin
by_cases hq : q = 0, { simp [hq] },
rw [div_def, leading_coeff_mul, leading_coeff_C,
leading_coeff_div_by_monic_of_monic (monic_mul_leading_coeff_inv hq) _,
mul_comm, div_eq_mul_inv],
rwa [degree_mul_leading_coeff_inv q hq]
end
lemma div_C_mul : p / (C a * q) = C aβ»ΒΉ * (p / q) :=
begin
by_cases ha : a = 0,
{ simp [ha] },
simp only [div_def, leading_coeff_mul, mul_inv,
leading_coeff_C, C.map_mul, mul_assoc],
congr' 3,
rw [mul_left_comm q, β mul_assoc, β C.map_mul, mul_inv_cancel ha,
C.map_one, one_mul]
end
lemma C_mul_dvd (ha : a β 0) : C a * p β£ q β p β£ q :=
β¨Ξ» h, dvd_trans (dvd_mul_left _ _) h, Ξ» β¨r, hrβ©, β¨C aβ»ΒΉ * r,
by rw [mul_assoc, mul_left_comm p, β mul_assoc, β C.map_mul, _root_.mul_inv_cancel ha,
C.map_one, one_mul, hr]β©β©
lemma dvd_C_mul (ha : a β 0) : p β£ polynomial.C a * q β p β£ q :=
β¨Ξ» β¨r, hrβ©, β¨C aβ»ΒΉ * r,
by rw [mul_left_comm p, β hr, β mul_assoc, β C.map_mul, _root_.inv_mul_cancel ha,
C.map_one, one_mul]β©,
Ξ» h, dvd_trans h (dvd_mul_left _ _)β©
lemma coe_norm_unit_of_ne_zero (hp : p β 0) : (norm_unit p : R[X]) = C p.leading_coeffβ»ΒΉ :=
have p.leading_coeff β 0 := mt leading_coeff_eq_zero.mp hp,
by simp [comm_group_with_zero.coe_norm_unit _ this]
lemma normalize_monic (h : monic p) : normalize p = p := by simp [h]
theorem map_dvd_map' [field k] (f : R β+* k) {x y : R[X]} : x.map f β£ y.map f β x β£ y :=
if H : x = 0 then by rw [H, polynomial.map_zero, zero_dvd_iff, zero_dvd_iff, map_eq_zero]
else by rw [β normalize_dvd_iff, β @normalize_dvd_iff R[X],
normalize_apply, normalize_apply,
coe_norm_unit_of_ne_zero H, coe_norm_unit_of_ne_zero (mt (map_eq_zero f).1 H),
leading_coeff_map, β map_invβ f, β map_C, β polynomial.map_mul,
map_dvd_map _ f.injective (monic_mul_leading_coeff_inv H)]
lemma degree_normalize : degree (normalize p) = degree p := by simp
lemma prime_of_degree_eq_one (hp1 : degree p = 1) : prime p :=
have prime (normalize p),
from monic.prime_of_degree_eq_one (hp1 βΈ degree_normalize)
(monic_normalize (Ξ» hp0, absurd hp1 (hp0.symm βΈ by simp; exact dec_trivial))),
(normalize_associated _).prime this
lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p :=
(prime_of_degree_eq_one hp1).irreducible
theorem not_irreducible_C (x : R) : Β¬irreducible (C x) :=
if H : x = 0 then by { rw [H, C_0], exact not_irreducible_zero }
else Ξ» hx, irreducible.not_unit hx $ is_unit_C.2 $ is_unit_iff_ne_zero.2 H
theorem degree_pos_of_irreducible (hp : irreducible p) : 0 < p.degree :=
lt_of_not_ge $ Ξ» hp0, have _ := eq_C_of_degree_le_zero hp0,
not_irreducible_C (p.coeff 0) $ this βΈ hp
/-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a β 0`,
then `f / (X - a)` is coprime with `X - a`.
Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/
lemma is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type*} [field K]
(f : K[X]) (a : K) (hf' : f.derivative.eval a β 0) :
is_coprime (X - C a : K[X]) (f /β (X - C a)) :=
begin
refine or.resolve_left (euclidean_domain.dvd_or_coprime (X - C a) (f /β (X - C a))
(irreducible_of_degree_eq_one (polynomial.degree_X_sub_C a))) _,
contrapose! hf' with h,
have key : (X - C a) * (f /β (X - C a)) = f - (f %β (X - C a)),
{ rw [eq_sub_iff_add_eq, β eq_sub_iff_add_eq', mod_by_monic_eq_sub_mul_div],
exact monic_X_sub_C a },
replace key := congr_arg derivative key,
simp only [derivative_X, derivative_mul, one_mul, sub_zero, derivative_sub,
mod_by_monic_X_sub_C_eq_C_eval, derivative_C] at key,
have : (X - C a) β£ derivative f := key βΈ (dvd_add h (dvd_mul_right _ _)),
rw [β dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval] at this,
rw [β C_inj, this, C_0],
end
end field
end polynomial
|
b7d1c9fc033d0d1f712fc6e9832e2f2122d173cb | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/set.lean | afbcc93f77cfe57d1b58e090b025f994ae67568f | [
"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 | 131 | lean | import logic
open bool nat
definition set {{T : Type}} := T β bool
infix `β` := Ξ»x A, A x = tt
check 1 β (Ξ» x : nat, tt)
|
2ab6c72ddf1dd7bf48ad0996ef79b99fa5800ec4 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/examples/deps/b/B.lean | 661392753c6d71c6732f118beb8aae9f1ede5f2f | [
"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 | 34 | lean | import Root
def b := s!"B{root}"
|
7a00fc2bc746fb7767dc4a34b02abf510f34eb3d | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/univ2.lean | 35793c93191f163d80ab2252112a71f495e62d84 | [
"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 | 231 | lean | import logic
axiom I : Type
definition F (X : Type) : Type := (X β Prop) β Prop
axiom unfoldd : I β F I
axiom foldd : F I β I
axiom iso1 : βx, foldd (unfoldd x) = x
theorem iso2 : βx, foldd (unfoldd x) = x
:= sorry
|
717ce375c6d15694a9a47303359aee63a6fbcd26 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/field_theory/finite/polynomial.lean | 3ba4e3e01b0fb13cc7486b41f02ac88c33b4e9a1 | [
"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 | 7,506 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import field_theory.finite.basic
import field_theory.mv_polynomial
import data.mv_polynomial.expand
import linear_algebra.basic
/-!
## Polynomials over finite fields
-/
namespace mv_polynomial
variables {Ο : Type*}
/-- A polynomial over the integers is divisible by `n : β`
if and only if it is zero over `zmod n`. -/
lemma C_dvd_iff_zmod (n : β) (Ο : mv_polynomial Ο β€) :
C (n:β€) β£ Ο β map (int.cast_ring_hom (zmod n)) Ο = 0 :=
C_dvd_iff_map_hom_eq_zero _ _ (char_p.int_cast_eq_zero_iff (zmod n) n) _
section frobenius
variables {p : β} [fact p.prime]
lemma frobenius_zmod (f : mv_polynomial Ο (zmod p)) :
frobenius _ p f = expand p f :=
begin
apply induction_on f,
{ intro a, rw [expand_C, frobenius_def, β C_pow, zmod.pow_card], },
{ simp only [alg_hom.map_add, ring_hom.map_add], intros _ _ hf hg, rw [hf, hg] },
{ simp only [expand_X, ring_hom.map_mul, alg_hom.map_mul],
intros _ _ hf, rw [hf, frobenius_def], },
end
lemma expand_zmod (f : mv_polynomial Ο (zmod p)) :
expand p f = f ^ p :=
(frobenius_zmod _).symm
end frobenius
end mv_polynomial
namespace mv_polynomial
noncomputable theory
open_locale big_operators classical
open set linear_map submodule
variables {K : Type*} {Ο : Type*}
variables [field K] [fintype K] [fintype Ο]
def indicator (a : Ο β K) : mv_polynomial Ο K :=
β n, (1 - (X n - C (a n))^(fintype.card K - 1))
lemma eval_indicator_apply_eq_one (a : Ο β K) :
eval a (indicator a) = 1 :=
have 0 < fintype.card K - 1,
begin
rw [β finite_field.card_units, fintype.card_pos_iff],
exact β¨1β©
end,
by simp only [indicator, (finset.univ.prod_hom (eval a)).symm, ring_hom.map_sub,
is_ring_hom.map_one (eval a), is_monoid_hom.map_pow (eval a), eval_X, eval_C,
sub_self, zero_pow this, sub_zero, finset.prod_const_one]
lemma eval_indicator_apply_eq_zero (a b : Ο β K) (h : a β b) :
eval a (indicator b) = 0 :=
have βi, a i β b i, by rwa [(β ), function.funext_iff, not_forall] at h,
begin
rcases this with β¨i, hiβ©,
simp only [indicator, (finset.univ.prod_hom (eval a)).symm, ring_hom.map_sub,
is_ring_hom.map_one (eval a), is_monoid_hom.map_pow (eval a), eval_X, eval_C,
sub_self, finset.prod_eq_zero_iff],
refine β¨i, finset.mem_univ _, _β©,
rw [finite_field.pow_card_sub_one_eq_one, sub_self],
rwa [(β ), sub_eq_zero],
end
lemma degrees_indicator (c : Ο β K) :
degrees (indicator c) β€ β s : Ο, (fintype.card K - 1) β’β {s} :=
begin
rw [indicator],
refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _),
refine le_trans (degrees_sub _ _) _,
rw [degrees_one, β bot_eq_zero, bot_sup_eq],
refine le_trans (degrees_pow _ _) (nsmul_le_nsmul_of_le_right _ _),
refine le_trans (degrees_sub _ _) _,
rw [degrees_C, β bot_eq_zero, sup_bot_eq],
exact degrees_X' _
end
lemma indicator_mem_restrict_degree (c : Ο β K) :
indicator c β restrict_degree Ο K (fintype.card K - 1) :=
begin
rw [mem_restrict_degree_iff_sup, indicator],
assume n,
refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _),
rw [β finset.univ.sum_hom (multiset.count n)],
simp only [is_add_monoid_hom.map_nsmul (multiset.count n), multiset.singleton_eq_singleton,
nsmul_eq_mul, nat.cast_id],
transitivity,
refine finset.sum_eq_single n _ _,
{ assume b hb ne, rw [multiset.count_cons_of_ne ne.symm, multiset.count_zero, mul_zero] },
{ assume h, exact (h $ finset.mem_univ _).elim },
{ rw [multiset.count_cons_self, multiset.count_zero, mul_one] }
end
section
variables (K Ο)
def evalβ : mv_polynomial Ο K ββ[K] (Ο β K) β K :=
β¨ Ξ»p e, eval e p,
assume p q, (by { ext x, rw ring_hom.map_add, refl, }),
assume a p, funext $ assume e, by rw [smul_eq_C_mul, ring_hom.map_mul, eval_C]; refl β©
end
lemma evalβ_apply (p : mv_polynomial Ο K) (e : Ο β K) : evalβ K Ο p e = eval e p :=
rfl
lemma map_restrict_dom_evalβ : (restrict_degree Ο K (fintype.card K - 1)).map (evalβ K Ο) = β€ :=
begin
refine top_unique (submodule.le_def'.2 $ assume e _, mem_map.2 _),
refine β¨β n : Ο β K, e n β’ indicator n, _, _β©,
{ exact sum_mem _ (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) },
{ ext n,
simp only [linear_map.map_sum, @finset.sum_apply (Ο β K) (Ξ»_, K) _ _ _ _ _,
pi.smul_apply, linear_map.map_smul],
simp only [evalβ_apply],
transitivity,
refine finset.sum_eq_single n _ _,
{ assume b _ h,
rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] },
{ assume h, exact (h $ finset.mem_univ n).elim },
{ rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } }
end
end mv_polynomial
namespace mv_polynomial
open_locale classical
open linear_map submodule
universe u
variables (Ο : Type u) (K : Type u) [fintype Ο] [field K] [fintype K]
@[derive [add_comm_group, vector_space K, inhabited]]
def R : Type u := restrict_degree Ο K (fintype.card K - 1)
noncomputable instance decidable_restrict_degree (m : β) :
decidable_pred (Ξ»n, n β {n : Ο ββ β | βi, n i β€ m }) :=
by simp only [set.mem_set_of_eq]; apply_instance
lemma dim_R : vector_space.dim K (R Ο K) = fintype.card (Ο β K) :=
calc vector_space.dim K (R Ο K) =
vector_space.dim K (β₯{s : Ο ββ β | β (n : Ο), s n β€ fintype.card K - 1} ββ K) :
linear_equiv.dim_eq
(finsupp.supported_equiv_finsupp {s : Ο ββ β | βn:Ο, s n β€ fintype.card K - 1 })
... = cardinal.mk {s : Ο ββ β | β (n : Ο), s n β€ fintype.card K - 1} :
by rw [finsupp.dim_eq, dim_of_field, mul_one]
... = cardinal.mk {s : Ο β β | β (n : Ο), s n < fintype.card K } :
begin
refine quotient.sound β¨equiv.subtype_equiv finsupp.equiv_fun_on_fintype $ assume f, _β©,
refine forall_congr (assume n, nat.le_sub_right_iff_add_le _),
exact fintype.card_pos_iff.2 β¨0β©
end
... = cardinal.mk (Ο β {n // n < fintype.card K}) :
quotient.sound β¨@equiv.subtype_pi_equiv_pi Ο (Ξ»_, β) (Ξ»s n, n < fintype.card K)β©
... = cardinal.mk (Ο β fin (fintype.card K)) :
quotient.sound β¨equiv.arrow_congr (equiv.refl Ο) (equiv.fin_equiv_subtype _).symmβ©
... = cardinal.mk (Ο β K) :
begin
refine (trunc.induction_on (fintype.equiv_fin K) $ assume (e : K β fin (fintype.card K)), _),
refine quotient.sound β¨equiv.arrow_congr (equiv.refl Ο) e.symmβ©
end
... = fintype.card (Ο β K) : cardinal.fintype_card _
def evalα΅’ : R Ο K ββ[K] (Ο β K) β K :=
((evalβ K Ο).comp (restrict_degree Ο K (fintype.card K - 1)).subtype)
lemma range_evalα΅’ : (evalα΅’ Ο K).range = β€ :=
begin
rw [evalα΅’, linear_map.range_comp, range_subtype],
exact map_restrict_dom_evalβ
end
lemma ker_evalβ : (evalα΅’ Ο K).ker = β₯ :=
begin
refine injective_of_surjective _ _ _ (range_evalα΅’ _ _),
{ rw [dim_R], exact cardinal.nat_lt_omega _ },
{ rw [dim_R, dim_fun, dim_of_field, mul_one] }
end
lemma eq_zero_of_eval_eq_zero (p : mv_polynomial Ο K)
(h : βv:Ο β K, eval v p = 0) (hp : p β restrict_degree Ο K (fintype.card K - 1)) :
p = 0 :=
let p' : R Ο K := β¨p, hpβ© in
have p' β (evalα΅’ Ο K).ker := by { rw [mem_ker], ext v, exact h v },
show p'.1 = (0 : R Ο K).1,
begin
rw [ker_evalβ, mem_bot] at this,
rw [this]
end
end mv_polynomial
|
7d19f65079aa7599242fa1a880d846dba4fef412 | ad3e8f15221a986da27c99f371922c0b3f5792b6 | /src/week04/solutions/e02_limits.lean | 9c0910874572bfdf712ac91de7727099f9a23920 | [] | no_license | VArtem/lean-itmo | a0e1424c8cc4c2de2ac85ab6fd4a12d80e9b85f1 | dc44cd06f9f5b984d051831b3aaa7364e64c2dc4 | refs/heads/main | 1,683,761,214,467 | 1,622,821,295,000 | 1,622,821,295,000 | 357,236,048 | 12 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,652 | lean | import data.real.basic
import tactic
/-
-- ΠΡΠΎΡ ΡΠ°ΠΉΠ» ΠΏΠ΅ΡΠ΅Π²Π΅Π΄Π΅Π½ ΠΈ Π°Π΄Π°ΠΏΡΠΈΡΠΎΠ²Π°Π½ ΠΈΠ· ΡΡΠ΅ΡΡΠ΅ΠΉ Π½Π΅Π΄Π΅Π»ΠΈ ΠΊΡΡΡΠ° Formalising Mathematics: https://github.com/ImperialCollegeLondon/formalising-mathematics/blob/master/src/week_3/Part_A_limits.lean
Π ΡΡΠΎΠΌ ΡΠ°ΠΉΠ»Π΅ ΠΌΡ ΡΠ°Π·ΠΎΠ²ΡΠ΅ΠΌ ΡΠ΅ΠΎΡΠΈΡ ΠΏΡΠ΅Π΄Π΅Π»ΠΎΠ² ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°ΡΠ΅Π»ΡΠ½ΠΎΡΡΠ΅ΠΉ Π²Π΅ΡΠ΅ΡΡΠ²Π΅Π½Π½ΡΡ
ΡΠΈΡΠ΅Π» ΡΠ΅ΡΠ΅Π· ΠΏΡΠΈΠ²ΡΡΠ½ΠΎΠ΅ ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΠ΅ ΠΏΡΠ΅Π΄Π΅Π»Π°. ΠΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°ΡΠ΅Π»ΡΠ½ΠΎΡΡΡ `aβ, aβ, ...` Π±ΡΠ΄Π΅ΠΌ ΠΌΠΎΠ΄Π΅Π»ΠΈΡΠΎΠ²Π°ΡΡ, ΠΊΠ°ΠΊ ΡΡΠ½ΠΊΡΠΈΡ `β β β`
ΠΠΏΡΠ΅Π΄Π΅Π»ΠΈΠΌ ΠΎΡΠ½ΠΎΡΠ΅Π½ΠΈΠ΅ `is_limit (a : β β β) (l : β)`, ΠΎΠ·Π½Π°ΡΠ°ΡΡΠ΅Π΅, ΡΡΠΎ `aβ β l`:
`β Ξ΅ > 0, β N, β n β₯ N, | a n - l | < Ξ΅`
Π’Π΅ΠΎΡΠ΅ΠΌΡ Π² ΡΡΠΎΠΌ ΡΠ°ΠΉΠ»Π΅:
* `variables (a b c : β β β) (c l m : β)`
* `is_limit_const : is_limit (Ξ» n, c) c`
* `is_limit_subsingleton (hl : is_limit a l) (hm : is_limit a m) : l = m`
* `is_limit_add (h1 : is_limit a l) (h2 : is_limit b m) : is_limit (a + b) (l + m)`
* `is_limit_mul (h1 : is_limit a l) (h2 : is_limit b m) : is_limit (a * b) (l * m)`
* `is_limit_le_of_le (hl : is_limit a l) (hm : is_limit b m) (hle : β n, a n β€ b n) : l β€ m`
* `sandwich (ha : is_limit a l) (hc : is_limit c l)`
`(hab : β n, a n β€ b n) (hbc : β n, b n β€ c n) : is_limit b l`
-/
variable asd : β
local notation `|` x `|` := abs x
definition is_limit (a : β β β) (l : β) : Prop :=
β Ξ΅ > 0, β N, β n β₯ N, | a n - l | < Ξ΅
/-
ΠΠ±ΡΠ°ΡΠΈΡΠ΅ Π²Π½ΠΈΠΌΠ°Π½ΠΈΠ΅, ΡΡΠΎ ΠΏΡΠ΅Π΄Π΅Π» ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°ΡΠ΅Π»ΡΠ½ΠΎΡΡΠΈ ΡΡΠΎ Π½Π΅ ΡΡΠ½ΠΊΡΠΈΡ `(β β β) β β`, Π° Π±ΠΈΠ½Π°ΡΠ½ΠΎΠ΅ ΠΎΡΠ½ΠΎΡΠ΅Π½ΠΈΠ΅ Π½Π°Π΄ (β β β) ΠΈ β, ΠΏΠΎΡΠΎΠΌΡ ΡΡΠΎ Ρ Π½Π΅ΠΊΠΎΡΠΎΡΡΡ
ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°ΡΠ΅Π»ΡΠ½ΠΎΡΡΠ΅ΠΉ Π½Π΅Ρ ΠΏΡΠ΅Π΄Π΅Π»ΠΎΠ², ΠΈ Π² ΡΠ΅ΠΎΡΠΈΠΈ, Π½Π΅ΠΊΠΎΡΠΎΡΡΠ΅ ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°ΡΠ΅Π»ΡΠ½ΠΎΡΡΠΈ ΠΌΠΎΠ³ΡΡ ΠΈΠΌΠ΅ΡΡ Π½Π΅ΡΠΊΠΎΠ»ΡΠΊΠΎ ΠΏΡΠ΅Π΄Π΅Π»Π°Ρ
(Π² ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½Π½ΡΡ
ΠΏΡΠΎΡΡΡΠ°Π½ΡΡΠ²Π°Ρ
).
-/
/-- ΠΡΠ΅Π΄Π΅Π» ΠΊΠΎΠ½ΡΡΠ°Π½ΡΠ½ΠΎΠΉ ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°ΡΠ΅Π»ΡΠ½ΠΎΡΡΠΈ - ΠΊΠΎΠ½ΡΡΠ°Π½ΡΠ° -/
lemma is_limit_const (c : β) : is_limit (Ξ» n, c) c :=
begin
-- `is_limit a l` ΠΏΠΎ ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΡ ΡΡΠΎ `β Ξ΅, Ξ΅ > 0 β ...`, ΠΏΠΎΡΡΠΎΠΌΡ ΡΡΠ°Π·Ρ Π½Π°ΡΠΈΠ½Π°Π΅ΠΌ Ρ `intros`.
intros Ξ΅ Ξ΅pos,
-- ΠΡΠΆΠ½ΠΎ ΠΏΡΠ΅Π΄ΡΡΠ²ΠΈΡΡ `N`, Π½Π°ΡΠΈΠ½Π°Ρ Ρ ΠΊΠΎΡΠΎΡΠΎΠ³ΠΎ Π²ΡΠΏΠΎΠ»Π½ΡΠ΅ΡΡΡ Π½Π΅ΡΠ°Π²Π΅Π½ΡΡΠ²ΠΎ, ΠΏΠΎΠ΄ΠΎΠΉΠ΄Π΅Ρ Π»ΡΠ±ΠΎΠ΅
use 37,
-- Π’Π΅ΠΏΠ΅ΡΡ Π±Π΅ΡΠ΅ΠΌ Π»ΡΠ±ΠΎΠ΅ `n β₯ N` ΠΈ Π΄ΠΎΠΊΠ°ΠΆΠ΅ΠΌ ΠΏΡΠΎ ΡΡΠΎ ΠΊΠΎΠ½ΠΊΡΠ΅ΡΠ½ΠΎΠ΅ `n` Π½Π΅ΡΠ°Π²Π΅Π½ΡΡΠ²ΠΎ
-- ΠΡΠΎΡΠΎΠΉ ΠΏΠ°ΡΠ°ΠΌΠ΅ΡΡ Π±Π΅ΡΠΏΠΎΠ»Π΅Π·Π΅Π½, ΠΏΠΎΡΡΠΎΠΌΡ ΠΌΠΎΠΆΠ½ΠΎ Π½Π°ΠΏΠΈΡΠ°ΡΡ `-`, ΡΠΎΠ³Π΄Π° Π² Π½Π°ΡΠ΅ΠΌ ΠΊΠΎΠ½ΡΠ΅ΠΊΡΡΠ΅ Π΅Π³ΠΎ Π½Π΅ Π±ΡΠ΄Π΅Ρ
rintro n -,
-- Π ΡΠ΅Π»ΠΈ Ρ Π½Π°Ρ Π΅ΡΡΡ `(Ξ» (n : β), c) n` - Π½Π΅ΡΠ΅Π΄ΡΡΠΈΡΠΎΠ²Π°Π½Π½Π°Ρ Π»ΡΠΌΠ±Π΄Π°
-- Π§ΡΠΎΠ±Ρ ΠΈΠ·Π±Π°Π²ΠΈΡΡΡΡ ΠΎΡ ΡΠ°ΠΊΠΈΡ
(ΠΈ ΠΏΠΎΠ΄ΠΎΠ±Π½ΡΡ
Π½Π΅ΡΠ΄ΠΎΠ±ΡΡΠ²), ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΠ΅ΠΌ `dsimp only`
dsimp only,
-- `simp` Π΄ΠΎΠ»ΠΆΠ΅Π½ Π·Π½Π°ΡΡ ΠΎ ΡΠΎΠΌ, ΡΡΠΎ `c - c = 0` ΠΈ `abs 0 = 0`
simp,
-- `a > b` ΠΏΠΎ ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΡ ΡΠ°Π²Π½ΠΎ `b < a` ΠΏΠΎΡΡΠΎΠΌΡ ΡΡΠ°Π±ΠΎΡΠ°Π΅Ρ `exact`
exact Ξ΅pos,
end
theorem is_limit_subsingleton {a : β β β} {l m : β} (hl : is_limit a l)
(hm : is_limit a m) : l = m :=
begin
-- ΠΠΎΠΊΠ°ΠΆΠ΅ΠΌ ΠΎΡ ΠΏΡΠΎΡΠΈΠ²Π½ΠΎΠ³ΠΎ: ΠΏΡΡΡΡ l β m
by_contra h,
-- ΠΠ΄Π΅Ρ ΠΌΠ°ΡΠ΅ΠΌΠ°ΡΠΈΡΠ΅ΡΠΊΠΎΠ³ΠΎ Π΄ΠΎΠΊΠ°Π·Π°ΡΠ΅Π»ΡΡΡΠ²Π°: Π²ΠΎΠ·ΡΠΌΠ΅ΠΌ `Ξ΅ = |l - m| / 2`
-- Π’ΠΎΠ³Π΄Π° ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°ΡΠ΅Π»ΡΠ½ΠΎΡΡΡ `a` Π±ΡΠ΄Π΅Ρ Π² ΠΏΡΠ΅Π΄Π΅Π»Π°Ρ
`Ξ΅` ΠΎΡ `l` ΠΈ Π² ΠΏΡΠ΅Π΄Π΅Π»Π°Ρ
`Ξ΅` ΠΎΡ `m`
-- ΠΠ· ΡΠ΅Π³ΠΎ ΠΌΡ ΠΏΠΎΠ»ΡΡΠΈΠΌ ΠΏΡΠΎΡΠΈΠ²ΠΎΡΠ΅ΡΠΈΠ΅
-- Π§ΡΠΎΠ±Ρ ΡΠΌΠ΅Π½ΡΡΠΈΡΡ ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΡΠ»ΡΡΠ°Π΅Π² ΡΠΎΠ³Π΄Π°, ΠΊΠΎΠ³Π΄Π° ΡΠ΅Π»Ρ ΠΈ Π²ΡΠ΅ Π»ΠΎΠΊΠ°Π»ΡΠ½ΡΠ΅ Π³ΠΈΠΏΠΎΡΠ΅Π·Ρ ΡΠΈΠΌΠΌΠ΅ΡΡΠΈΡΠ½Ρ,
-- ΠΡΠΏΠΎΠ»ΡΠ·ΡΠ΅ΠΌ ΡΠ°ΠΊΡΠΈΠΊΡ `wlog`: https://leanprover-community.github.io/mathlib_docs/tactic/wlog.html
wlog hlm : l < m,
-- Lean ΠΏΡΠΎΠ²Π΅ΡΠΈΡ ΡΠΈΠΌΠΌΠ΅ΡΡΠΈΡΠ½ΠΎΡΡΡ ΠΎΡΠ½ΠΎΡΠΈΡΠ΅Π»ΡΠ½ΠΎ `l` ΠΈ `m`
-- ΠΠΎ ΡΠ³Π΅Π½Π΅ΡΠΈΡΡΠ΅Ρ Π½ΠΎΠ²ΡΡ ΡΠ΅Π»Ρ `l < m` or `m < l`
{ have : l < m β¨ l = m β¨ m < l := lt_trichotomy l m,
-- ΠΡΡΠ°Π»Π°ΡΡ ΡΠΈΡΡΠΎ Π»ΠΎΠ³ΠΈΡΠ΅ΡΠΊΠ°Ρ ΡΠ΅Π»Ρ: Β¬ B, A β¨ B β¨ C β’ A β¨ C, `tauto` ΡΠΏΡΠ°Π²ΠΈΡΡΡ
tauto },
-- ΠΠΎΠ·ΡΠΌΠ΅ΠΌ `Ξ΅ = (m - l) / 2`, ΠΎΠ±ΠΎΠ·Π½Π°ΡΠΈΠΌ Π·Π° `hΞ΅` ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΠ΅ `e`
set Ξ΅ := (m - l)/2 with hΞ΅,
-- ΠΠΎΠΊΠ°ΠΆΠ΅ΠΌ, ΡΡΠΎ `Ξ΅ > 0`, ΡΠ°ΠΊΡΠΈΠΊΠ° `linarith` ΡΠΏΡΠ°Π²ΠΈΡΡΡ
have Ξ΅pos : Ξ΅ > 0 := by linarith,
-- ΠΠΎΠ΄ΡΡΠ°Π²ΠΈΠΌ ΡΡΠΎ `Ξ΅`, Π° ΡΠ°ΠΊΠΆΠ΅ Π΄ΠΎΠΊΠ°Π·Π°ΡΠ΅Π»ΡΡΡΠ²ΠΎ, ΡΡΠΎ `Ξ΅ > 0` Π² ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΠ΅ ΠΏΡΠ΅Π΄Π΅Π»Π° `hl` ΠΈ `hm`
specialize hl Ξ΅ Ξ΅pos,
specialize hm Ξ΅ Ξ΅pos,
-- Π’Π΅ΠΏΠ΅ΡΡ `hl` ΠΈ `hm` Π²ΡΠ³Π»ΡΠ΄ΡΡ, ΠΊΠ°ΠΊ β N, β n β₯ m, |a n - l| < Ξ΅, ΡΠ°Π·Π±Π΅ΡΠ΅ΠΌ ΠΈΡ
Π½Π° ΡΠ°ΡΡΠΈ
cases hl with L hL,
cases hm with M hM,
-- ΠΠΏΡΠ΅Π΄Π΅Π»ΠΈΠΌ `N = max L M`,
set N := max L M with hN,
have hLN : L β€ N := le_max_left L M,
have hMN : M β€ N := le_max_right L M,
-- ΠΠΎΠ΄ΡΡΠ°Π²ΠΈΠΌ `N` Π² Π»ΠΎΠΊΠ°Π»ΡΠ½ΡΠ΅ ΡΡΠ²Π΅ΡΠΆΠ΄Π΅Π½ΠΈΡ `hL` ΠΈ `hM`, Π²ΠΌΠ΅ΡΡΠ΅ Ρ Π΄ΠΎΠΊΠ°Π·Π°ΡΠ΅Π»ΡΡΡΠ²Π°ΠΌΠΈ, ΡΡΠΎ `N β₯ L` ΠΈ `N β₯ M`
specialize hL N hLN,
specialize hM N hMN,
-- Π£ Π½Π°Ρ Π΅ΡΡΡ ΡΡΠ²Π΅ΡΠΆΠ΄Π΅Π½ΠΈΡ `hL: |a N - l| < Ξ΅`, `hM: |a N - m| < Ξ΅` ΠΈ `hΞ΅: Ξ΅ = (m - l) / 2`
-- Π₯ΠΎΡΠ΅ΡΡΡ ΡΠ΅ΡΠΈΡΡ ΠΈΡ
Π°Π²ΡΠΎΠΌΠ°ΡΠΈΡΠ΅ΡΠΊΠΈ, ΡΠ°ΠΊΡΠΈΠΊΠ° `linarith` Π·Π°ΡΠΎΡΠ΅Π½Π° Π½Π° ΡΠΎ, ΡΡΠΎΠ±Ρ ΡΠ΅ΡΠ°ΡΡ Π»ΠΈΠ½Π΅ΠΉΠ½ΡΠ΅ Π½Π΅ΡΠ°Π²Π΅Π½ΡΡΠ²Π°
-- ΠΠΎ `linarith` Π½Π΅ Π·Π½Π°Π΅Ρ ΠΏΡΠΎ `abs`, ΠΏΠΎΡΡΠΎΠΌΡ Π½Π°Π΄ΠΎ ΠΏΠΎΠΌΠΎΡΡ
rw abs_lt at hL hM,
linarith,
end
/-
ΠΠΎΠΏΠΎΠ΄ΡΠΎΠ±Π½Π΅Π΅ ΠΏΡΠΎ ΡΠ°ΠΊΡΠΈΠΊΠΈ `linarith`, `ring` ΠΈ `convert`
### `ring`
Π’Π°ΠΊΡΠΈΠΊΠ° `ring` Π΄ΠΎΠΊΠ°Π·ΡΠ²Π°Π΅Ρ ΡΠ΅Π»ΠΈ Π² ΠΊΠΎΠΌΠΌΡΡΠ°ΡΠΈΠ²Π½ΡΡ
ΠΊΠΎΠ»ΡΡΠ°Ρ
(ΠΈΠ»ΠΈ Π΄Π°ΠΆΠ΅
Π² ΠΊΠΎΠΌΠΌΡΡΠ°ΡΠΈΠ²Π½ΡΡ
ΠΏΠΎΠ»ΡΠΊΠΎΠ»ΡΡΠ°Ρ
ΡΠΈΠΏΠ° β). ΠΠ°ΠΏΡΠΈΠΌΠ΅Ρ, Π΅ΡΠ»ΠΈ `(x y : β)`
ΠΈ ΡΠ΅Π»Ρ ΡΠ°Π²Π½Π° `(x+y)^3=x^3+3*x^2*y+3*x*y^2+y^3`, ΡΠΎ `ring` ΡΠΏΡΠ°Π²ΠΈΡΡΡ
Π·Π°ΠΊΡΡΡΡ ΡΡΡ ΡΠ΅Π»Ρ.
Π ΡΠ»Π΅Π΄ΡΡΡΠ΅ΠΌ Π΄ΠΎΠΊΠ°Π·Π°ΡΠ΅Π»ΡΡΡΠ²Π΅ `is_limit_add` ΠΏΠΎΠ»Π΅Π·Π½ΠΎ ΠΈΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΡ `ring`, ΡΡΠΎΠ±Ρ Π΄ΠΎΠΊΠ°Π·Π°ΡΡ
ΡΠ°Π²Π΅Π½ΡΡΠ²Π° Π²ΠΈΠ΄Π° `a n + b n - (l + m) = (a n - l) + (b n - m)` ΠΈ `Ξ΅/2 + Ξ΅/2 = Ξ΅`.
Π ΡΠΎΠΆΠ°Π»Π΅Π½ΠΈΡ, `ring` Π½Π΅ ΠΏΠΎΠ½ΠΈΠΌΠ°Π΅Ρ `Ξ»`-ΡΠ΅ΡΠΌΡ ΠΈ ΡΠ°Π±ΠΎΡΠ°Π΅Ρ Ρ ΡΠΎΡΠ½ΠΎΡΡΡΡ Π΄ΠΎ ΡΠΈΠ½ΡΠ°ΠΊΡΠΈΡΠ΅ΡΠΊΠΎΠ³ΠΎ ΡΠ°Π²Π΅Π½ΡΡΠ²Π°.
Π’Π°ΠΊΠΆΠ΅, `ring` ΡΠ°Π±ΠΎΡΠ°Π΅Ρ ΡΠΎΠ»ΡΠΊΠΎ Ρ ΡΠ΅Π»ΡΡ, Π½Π΅ ΡΠΌΠΎΡΡΡ Π½Π° Π»ΠΎΠΊΠ°Π»ΡΠ½ΡΠ΅ Π³ΠΈΠΏΠΎΡΠ΅Π·Ρ, ΠΏΠΎΡΡΠΎΠΌΡ Π² ΠΏΡΠΈΠΌΠ΅ΡΠ΅
```
a b c : β
ha : a = b + c
β’ 2 * a = b + b + c + c
```
ΠΡΠΎΡΡΠΎ `ring` Π½Π΅ ΡΡΠ°Π±ΠΎΡΠ°Π΅Ρ, ΡΠ½Π°ΡΠ°Π»Π° Π½ΡΠΆΠ½ΠΎ ΡΠ΄Π΅Π»Π°ΡΡ `rw ha`.
### `linarith`
`linarith` ΡΠ΅ΡΠ°Π΅Ρ Π»ΠΈΠ½Π΅ΠΉΠ½ΡΠ΅ ΡΡΠ°Π²Π½Π΅Π½ΠΈΡ, Π½Π°ΠΏΡΠΈΠΌΠ΅Ρ:
```
a b c : β
hab : a β€ b
hbc : b < c
β’ a β€ c + 1
```
`linarith` ΡΠΌΠΎΡΡΠΈΡ ΡΠΎΠ»ΡΠΊΠΎ Π½Π° Π³ΠΈΠΏΠΎΡΠ΅Π·Ρ, ΡΠ²Π»ΡΡΡΠΈΠ΅ΡΡ Π½Π΅ΡΠ°Π²Π΅Π½ΡΡΠ²Π°ΠΌΠΈ, ΠΈ Π½Π΅ ΡΠΌΠΎΠΆΠ΅Ρ ΡΠ΅ΡΠΈΡΡ ΡΠ»Π΅Π΄ΡΡΡΠΈΠΉ ΠΏΡΠΈΠΌΠ΅Ρ:
```
a b c : β
hab : a β€ b
hbc : a β€ b β b < c
β’ a β€ c + 1
```
ΠΡΠΎΠΌΠ΅ ΠΎΠ΄Π½ΠΎΠ³ΠΎ ΡΠ»ΡΡΠ°Ρ: Π΅ΡΠ»ΠΈ Π² Π³ΠΈΠΏΠΎΡΠ΅Π·Π΅ Π΅ΡΡΡ `β§`, ΡΠΎ `linarith` ΡΠΌΠΎΠΆΠ΅Ρ ΠΈΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΡ ΠΎΠ±Π° Π°ΡΠ³ΡΠΌΠ΅Π½ΡΠ°
```
a b c : β
h : a β€ b β§ b < c
β’ a β€ c + 1
```
ΠΠΎ Π½Π΅ ΡΠΌΠΎΠΆΠ΅Ρ Π΄ΠΎΠΊΠ°Π·Π°ΡΡ `β§` Π² ΡΠ΅Π»ΠΈ, Π½ΡΠΆΠ½ΠΎ ΡΠ΄Π΅Π»Π°ΡΡ `split`
```
a b c : β
h : a β€ b β§ b < c
β’ a β€ c + 1 β§ a β€ c + 1
```
### convert
Π’Π°ΠΊΡΠΈΠΊΠ° `convert` ΠΏΠΎΠ·Π²ΠΎΠ»ΡΠ΅Ρ Π·Π°ΠΌΠ΅Π½ΠΈΡΡ ΡΠ΅Π»Ρ Π½Π° ΡΠ»Π΅Π³ΠΊΠ° ΠΎΡΠ»ΠΈΡΠ°ΡΡΡΡΡΡ, ΠΈ ΠΎΡΡΠ°Π²Π»ΡΠ΅Ρ
ΡΠ΅Π»ΠΈ Π² ΠΌΠ΅ΡΡΠ°Ρ
ΠΎΡΠ»ΠΈΡΠΈΡ ΡΠ΅Π»Π΅ΠΉ. ΠΡΠ»ΠΈ ΡΠ΅Π»Ρ `β’ P` ΠΈ Π΅ΡΡΡ Π³ΠΈΠΏΠΎΡΠ΅Π·Π° `h : P'`, Π³Π΄Π΅ `P` ΠΈ `P'`
ΠΎΡΠ»ΠΈΡΠ°ΡΡΡΡ Π½Π΅ΡΠΈΠ»ΡΠ½ΠΎ, ΡΠΎ `convert h'` Π·Π°ΠΊΡΠΎΠ΅Ρ ΡΠ΅Π»Ρ ΠΈ ΡΠΎΠ·Π΄Π°Π΅Ρ Π½Π΅ΡΠΊΠΎΠ»ΡΠΊΠΎ ΡΠ΅Π»Π΅ΠΉ Π΄Π»Ρ Π²ΡΠ΅Ρ
ΠΌΠ΅ΡΡ, Π³Π΄Π΅ `P` ΠΈ `P` ΠΎΡΠ»ΠΈΡΠ°ΡΡΡΡ.
ΠΠ°ΠΏΡΠΈΠΌΠ΅Ρ:
-/
example (a b : β) (h : a * 2 = b + 1) : a + a = b - (-1) :=
begin
-- `rw h` Π½Π΅ ΡΡΠ°Π±ΠΎΡΠ°Π΅Ρ, ΠΏΠΎΡΠΎΠΌΡ ΡΡΠΎ `a * 2` Π½ΠΈΠ³Π΄Π΅ Π½Π΅ Π²ΡΡΡΠ΅ΡΠ°Π΅ΡΡΡ
convert h,
-- Π‘Π³Π΅Π½Π΅ΡΠΈΡΠΎΠ²Π°Π½ΠΎ Π΄Π²Π΅ ΡΠ΅Π»ΠΈ: `a + a = a * 2` ΠΈ `b - -1 = b + 1`
{ ring },
{ ring },
end
/-
ΠΠ½ΠΎΠ³Π΄Π° `convert` ΡΡ
ΠΎΠ΄ΠΈΡ ΡΠ»ΠΈΡΠΊΠΎΠΌ Π³Π»ΡΠ±ΠΎΠΊΠΎ, ΠΈ Π΅ΠΌΡ ΠΏΡΠΈΠ΄Π΅ΡΡΡ ΠΎΠ³ΡΠ°Π½ΠΈΡΠΈΡΡ Π³Π»ΡΠ±ΠΈΠ½Ρ ΡΡΠ°Π²Π½Π΅Π½ΠΈΡ.
ΠΠΎΠΏΡΠΎΠ±ΡΠΉΡΠ΅ ΡΠ°ΡΠΊΠΎΠΌΠΌΠ΅Π½ΡΠΈΡΠΎΠ²Π°ΡΡ `convert h` Π½ΠΈΠΆΠ΅, ΠΈ ΠΏΠΎΡΠΌΠΎΡΡΠΈΡΠ΅, ΠΊΠ°ΠΊΠΈΠ΅ ΡΠ΅Π»ΠΈ ΠΏΠΎΠ»ΡΡΠΈΠ»ΠΈΡΡ.
-/
example (a b : β) (h : a * 2 = b + 1) : a + a = 1 + b :=
begin
-- convert h,
convert h using 1, -- Π΅ΡΠ»ΠΈ Π·Π°ΠΌΠ΅Π½ΠΈΡΡ Π½Π° `using 2` ΠΈΠ»ΠΈ Π±ΠΎΠ»ΡΡΠ΅, Π±ΡΠ΄Π΅Ρ ΡΠΎΡ ΠΆΠ΅ ΡΡΡΠ΅ΠΊΡ
{ ring },
{ ring }
end
lemma is_limit_add_const {a : β β β} {l : β} (c : β) (ha : is_limit a l) :
is_limit (Ξ» i, a i + c) (l + c) :=
begin
rintro Ξ΅ Ξ΅pos,
obtain β¨N, hβ© := ha Ξ΅ Ξ΅pos,
use N,
dsimp only,
ring_nf,
exact h,
end
lemma is_limit_add_const_iff {a : β β β} {l : β} (c : β) :
is_limit a l β is_limit (Ξ» i, a i + c) (l + c) :=
begin
split, {
refine is_limit_add_const _,
}, {
intro h,
convert is_limit_add_const (-c) h,
all_goals {simp only [add_neg_cancel_right]},
}
end
lemma is_limit_iff_is_limit_sub_eq_zero (a : β β β) (l : β) :
is_limit a l β is_limit (Ξ» i, a i - l) 0 :=
begin
convert is_limit_add_const_iff (-l),
ring,
end
/-
ΠΠΎΠΊΠ°ΠΆΠ΅ΠΌ, ΡΡΠΎ Π΅ΡΠ»ΠΈ aβ β l ΠΈ bβ β m ΡΠΎ aβ + bβ β l + m.
ΠΠ°ΡΠ΅ΠΌΠ°ΡΠΈΡΠ΅ΡΠΊΠΎΠ΅ ΡΠ°ΡΡΡΠΆΠ΄Π΅Π½ΠΈΠ΅, Π²ΠΎΠ·ΡΠΌΠ΅ΠΌ Ξ΅/2,
ΠΡΠ±Π΅ΡΠ΅ΠΌ Π΄ΠΎΡΡΠ°ΡΠΎΡΠ½ΠΎ Π±ΠΎΠ»ΡΡΠΎΠ΅ L, ΡΡΠΎΠ±Ρ ΠΈΠ· n β₯ L ΡΠ»Π΅Π΄ΠΎΠ²Π°Π»ΠΎ |aβ - l| < Ξ΅/2
ΠΡΠ±Π΅ΡΠ΅ΠΌ Π΄ΠΎΡΡΠ°ΡΠΎΡΠ½ΠΎ Π±ΠΎΠ»ΡΡΠΎΠ΅ M, ΡΡΠΎΠ±Ρ ΠΈΠ· n β₯ M ΡΠ»Π΅Π΄ΠΎΠ²Π°Π»ΠΎ |bβ - m| < Ξ΅/2
Π’Π΅ΠΏΠ΅ΡΡ N = max L M ΡΡΠ°Π±ΠΎΡΠ°Π΅Ρ.
ΠΠΎΠ»Π΅Π·Π½ΡΠ΅ Π»Π΅ΠΌΠΌΡ:
`pi.add_apply a b : (a + b) n = a n + b n` ΠΈ Π΄ΡΡΠ³ΠΈΠ΅ Π½Π°ΡΠΈΠ½Π°ΡΡΠΈΠ΅ΡΡ Ρ `pi.`
`abs_add x y : |x + y| β€ |x| + |y|`
Π£Π΄Π°ΡΠΈ!
-/
theorem is_limit_add {a b : β β β} {l m : β}
(h1 : is_limit a l) (h2 : is_limit b m) :
is_limit (a + b) (l + m) :=
begin
rintro Ξ΅ Ξ΅pos,
obtain β¨Nβ, hββ© := h1 (Ξ΅/2) (by linarith),
obtain β¨Nβ, hββ© := h2 (Ξ΅/2) (by linarith),
use [max Nβ Nβ],
rintro n hn,
specialize hβ n (le_of_max_le_left hn),
specialize hβ n (le_of_max_le_right hn),
calc |(a + b) n - (l + m)| = |a n + b n - (l + m)| : by rw pi.add_apply
... = |(a n - l) + (b n - m)| : by ring_nf
... β€ |a n - l| + |b n - m| : abs_add _ _
... < Ξ΅ : by linarith
end
-- Π’Π°ΠΊΠΆΠ΅ Π΄ΠΎΠΊΠ°ΠΆΠ΅ΠΌ ΠΏΡΠΎ Π²Π·Π°ΠΈΠΌΠΎΠ΄Π΅ΠΉΡΡΠ²ΠΈΠ΅ ΠΏΡΠ΅Π΄Π΅Π»Π° ΠΈ ΡΠΌΠ½ΠΎΠΆΠ΅Π½ΠΈΡ
-- ΠΠΎΠ»Π΅Π·Π½ΡΠ΅ Π»Π΅ΠΌΠΌΡ
-- `abs_pos : 0 < |a| β a β 0`
-- `div_pos : 0 < a β 0 < b β 0 < a / b`
-- `abs_mul x y : |x * y| = |x| * |y|`
-- `lt_div_iff' : 0 < c β (a < b / c β c * a < b)`
-- ΠΡΠΈ ΠΈ ΠΏΠΎΡ
ΠΎΠΆΠΈΠ΅ ΠΏΠΎΠ»Π΅Π·Π½ΡΠ΅ Π»Π΅ΠΌΠΌΡ ΠΌΠΎΠΆΠ½ΠΎ Π½Π°ΠΉΡΠΈ Π»ΠΈΠ±ΠΎ "ΡΠ³Π°Π΄Π°Ρ" Π½Π°Π·Π²Π°Π½ΠΈΠ΅ Π»Π΅ΠΌΠΌΡ
-- Π ΠΊΠΎΠΌΠ±ΠΈΠ½Π°ΡΠΈΠΈ Ρ ctrl+ΠΏΡΠΎΠ±Π΅Π», ΠΈΠ»ΠΈ `library_search`
-- ΠΠΎΠΊΠ°ΠΆΠ΅ΠΌ, ΡΡΠΎ Ρ * aβ β c * l
-- Π‘ΠΊΠΎΡΠ΅Π΅ Π²ΡΠ΅Π³ΠΎ, c = 0 Π±ΡΠ΄Π΅Ρ ΠΎΡΠ΄Π΅Π»ΡΠ½ΡΠΌ ΡΠ»ΡΡΠ°Π΅ΠΌ, ΠΏΠΎΡΡΠΎΠΌΡ Π½Π°ΡΠ½ΠΈΡΠ΅ Ρ
-- `by_cases hc : c = 0`
lemma is_limit_mul_const_left {a : β β β} {l c : β} (h : is_limit a l) :
is_limit (Ξ» n, c * (a n)) (c * l) :=
begin
by_cases hc : c = 0,
{ subst hc, simp, exact is_limit_const 0,},
intros Ξ΅ Ξ΅pos,
have cpos : |c| > 0 := abs_pos.2 hc,
obtain β¨N, hβ© := h (Ξ΅ / |c|) (div_pos Ξ΅pos cpos),
use N,
intros n hn,
specialize h n hn,
dsimp only,
rwa [β mul_sub_left_distrib, abs_mul, β lt_div_iff' cpos],
end
lemma is_limit_linear (a : β β β) (b : β β β) (Ξ± Ξ² c d : β)
(ha : is_limit a Ξ±) (hb : is_limit b Ξ²) :
is_limit ( Ξ» n, c * (a n) + d * (b n) ) (c * Ξ± + d * Ξ²) :=
begin
apply is_limit_add (is_limit_mul_const_left ha) (is_limit_mul_const_left hb),
end
-- ΠΠ΅ΡΠ΅ΠΉΠ΄Π΅ΠΌ ΠΊ ΠΏΡΠ΅Π΄Π΅Π»Ρ ΠΏΡΠΎΠΈΠ·Π²Π΅Π΄Π΅Π½ΠΈΡ
-- ΠΠΌΠ΅ΡΡΠΎ ΠΈΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΡ `βΞ΅`, Π²ΡΠ±Π΅ΡΠΈΡΠ΅ `N` ΡΠ°ΠΊ, ΡΡΠΎΠ±Ρ `|a n| β€ Ξ΅`
-- ΠΈ `|b n| β€ 1`, ΠΊΠΎΠ³Π΄Π° `n β₯ N`; ΡΡΠΎΠ³ΠΎ Π΄ΠΎΡΡΠ°ΡΠΎΡΠ½ΠΎ.
lemma is_limit_mul_eq_zero_of_is_limit_eq_zero {a : β β β} {b : β β β}
(ha : is_limit a 0) (hb : is_limit b 0) : is_limit (a * b) 0 :=
begin
intros Ξ΅ Ξ΅pos,
obtain β¨Nβ, hββ© := ha Ξ΅ Ξ΅pos,
obtain β¨Nβ, hββ© := hb 1 zero_lt_one,
use [max Nβ Nβ],
intros n hn,
specialize hβ n (le_of_max_le_left hn),
specialize hβ n (le_of_max_le_right hn),
rw sub_zero at *,
rw [pi.mul_apply, abs_mul, β mul_one Ξ΅],
exact mul_lt_mul' (le_of_lt hβ) hβ (abs_nonneg _) Ξ΅pos,
-- Π’Π°ΠΊΠΆΠ΅ Π΅ΡΡΡ ΠΏΠΎΠ΄Ρ
Π°ΡΠ΅Π½Π½Π°Ρ ΡΠ°ΠΊΡΠΈΠΊΠ° `nlinarith`, ΠΊΠΎΡΠΎΡΠ°Ρ Π²ΠΌΠ΅ΡΡΠ΅ Ρ Π½Π΅ΠΊΠΎΡΠΎΡΡΠΌΠΈ ΡΡΠ²Π΅ΡΠΆΠ΄Π΅Π½ΠΈΡΠΌΠΈ
-- ΠΡΠΎ ΠΏΡΠΎΠΈΠ·Π²Π΅Π΄Π΅Π½ΠΈΡ ΡΠΈΡΠ΅Π» ΠΏΠΎΠΏΡΡΠ°Π΅ΡΡΡ Π΄ΠΎΠΊΠ°Π·Π°ΡΡ ΡΠ΅Π»Ρ
-- ΠΡΠ»ΠΈ Π΄ΠΎΠ±Π°Π²ΠΈΡΡ Π² ΠΊΠΎΠ½ΡΠ΅ΠΊΡΡ Π½Π΅ΠΎΡΡΠΈΡΠ°ΡΠ΅Π»ΡΠ½ΠΎΡΡΡ `abs`, ΡΠΎ ΡΠ»Π΅Π΄ΡΡΡΠΈΠ΅ ΡΡΡΠΎΠΊΠΈ ΡΠΎΠΆΠ΅ Π·Π°Π²Π΅ΡΡΠ°Ρ ΡΠ΅Π»Ρ
-- have nnegβ := abs_nonneg (a n),
-- have nnegβ := abs_nonneg (a n),
-- nlinarith,
end
-- ΠΡΠ»ΠΈ aβ β l ΠΈ bβ β m ΡΠΎ aβ * bβ β l * m.
-- Π Π΅ΠΊΠΎΠΌΠ΅Π½Π΄ΡΠ΅ΠΌΠΎΠ΅ Π΄ΠΎΠΊΠ°Π·Π°ΡΠ΅Π»ΡΡΡΠ²ΠΎ: Π½Π°ΡΠ½ΠΈΡΠ΅ Ρ
-- `suffices : is_limit (Ξ» i, (a i - l) * (b i - m) + (l * (b i - m)) + m * (a i - l)) 0,`
-- (Π²ΡΡΠ°ΠΆΠ΅Π½ΠΈΠ΅ Π²Π½ΡΡΡΠΈ ΡΠ°Π²Π½ΠΎ `a i * b i - l * m`)
-- ΡΠ°Π·Π»ΠΎΠΆΠΈΡΠ΅ Π½Π° ΡΡΠΌΠΌΡ ΡΡΠ΅Ρ
ΡΠ»Π°Π³Π°Π΅ΠΌΡΡ
, ΠΏΠΎΠΊΠ°Π·Π°Π², ΡΡΠΎ ΠΏΡΠ΅Π΄Π΅Π» ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ ΡΠ°Π²Π΅Π½ 0
theorem is_limit_mul (a : β β β) (b : β β β) (l m : β)
(h1 : is_limit a l) (h2 : is_limit b m) :
is_limit (a * b) (l * m) :=
begin
suffices : is_limit (Ξ» i, (a i - l) * (b i - m) + (l * (b i - m)) + m * (a i - l)) 0,
{ rw is_limit_iff_is_limit_sub_eq_zero,
convert this,
ext,
rw pi.mul_apply,
ring, },
convert @is_limit_add _ _ 0 0 _ _,
rw zero_add,
convert @is_limit_add _ _ 0 0 _ _,
rw zero_add,
{ apply is_limit_mul_eq_zero_of_is_limit_eq_zero,
rwa β is_limit_iff_is_limit_sub_eq_zero,
rwa β is_limit_iff_is_limit_sub_eq_zero,
},
{ simp_rw mul_sub_left_distrib,
rw [β is_limit_iff_is_limit_sub_eq_zero],
exact is_limit_mul_const_left h2,
},
{ simp_rw mul_sub_left_distrib,
rw [β is_limit_iff_is_limit_sub_eq_zero],
exact is_limit_mul_const_left h1,
},
end
-- ΠΡΠ»ΠΈ aβ β l ΠΈ bβ β m, Π° ΡΠ°ΠΊΠΆΠ΅ aβ β€ bβ Π΄Π»Ρ Π²ΡΠ΅Ρ
n, ΡΠΎ l β€ m
theorem is_limit_le_of_le (a : β β β) (b : β β β)
(l : β) (m : β) (hl : is_limit a l) (hm : is_limit b m)
(hle : β n, a n β€ b n) : l β€ m :=
begin
by_contra hml,
set Ξ΅ := (l - m) / 2 with Ξ΅_def,
have Ξ΅pos : Ξ΅ > 0 := by linarith,
obtain β¨Nβ, hββ© := hl Ξ΅ Ξ΅pos,
obtain β¨Nβ, hββ© := hm Ξ΅ Ξ΅pos,
specialize hle (max Nβ Nβ),
specialize hβ (max Nβ Nβ) (le_max_left Nβ Nβ),
specialize hβ (max Nβ Nβ) (le_max_right Nβ Nβ),
obtain β¨hββ, hβββ© := (abs_lt.1 hβ),
obtain β¨hββ, hβββ© := (abs_lt.1 hβ),
linarith,
end
-- ΠΠΎΠ»ΠΈΡΠ΅ΠΉΡΠΊΠΈΠ΅ ΡΡΠ½Π΄Π²ΠΈΡΠΈ
theorem sandwich (a b c : β β β)
(l : β) (ha : is_limit a l) (hc : is_limit c l)
(hab : β n, a n β€ b n) (hbc : β n, b n β€ c n) : is_limit b l :=
begin
intros Ξ΅ Ξ΅pos,
obtain β¨Nβ, hββ© := ha Ξ΅ Ξ΅pos,
obtain β¨Nβ, hββ© := hc Ξ΅ Ξ΅pos,
use [max Nβ Nβ],
intros n hn,
specialize hab n,
specialize hbc n,
specialize hβ n (le_of_max_le_left hn),
specialize hβ n (le_of_max_le_right hn),
rw abs_lt at hβ hβ β’,
cases hβ, cases hβ,
split;
linarith,
end
-- ΠΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΠ΅ ΠΎΠ³ΡΠ°Π½ΠΈΡΠ΅Π½Π½ΠΎΠΉ ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°ΡΠ΅Π»ΡΠ½ΠΎΡΡΠΈ
definition is_bounded (a : β β β) := β B, β n, |a n| β€ B
-- ΠΡΠΎΠΈΠ·Π²Π΅Π΄Π΅Π½ΠΈΠ΅ Π±Π΅ΡΠΊΠΎΠ½Π΅ΡΠ½ΠΎ ΠΌΠ°Π»ΠΎΠΉ Π½Π° ΠΎΠ³ΡΠ°Π½ΠΈΡΠ΅Π½Π½ΡΡ
lemma tendsto_bounded_mul_zero {a : β β β} {b : β β β}
(hA : is_bounded a) (hB : is_limit b 0)
: is_limit (a*b) 0 :=
begin
rcases hA with β¨B, hββ©,
have Bpos : 0 β€ B := le_trans (abs_nonneg _) (hβ 0),
rcases eq_or_lt_of_le Bpos with rfl | Bpos,
{ simp_rw abs_nonpos_iff at hβ,
convert is_limit_const 0,
ext,
simp only [hβ, zero_mul, pi.mul_apply],
},
intros Ξ΅ Ξ΅pos,
obtain β¨N, hββ© := hB (Ξ΅ / B) (div_pos Ξ΅pos Bpos),
use N,
intros n hn,
specialize hβ n,
specialize hβ n hn,
rw sub_zero at hβ β’,
rw [pi.mul_apply, abs_mul],
convert β mul_lt_mul' hβ hβ (abs_nonneg _) Bpos,
exact mul_div_cancel' _ (ne_of_gt Bpos),
end
-- ΠΠΎΠΆΠ½ΠΎ ΠΏΡΠΎΠ΄ΠΎΠ»ΠΆΠΈΡΡ ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΡΡ Π½ΠΎΠ²ΡΠ΅ ΠΏΠΎΠ½ΡΡΠΈΡ, ΠΈ ΡΠ°ΠΊ Π΄Π°Π»Π΅Π΅, ...
def is_cauchy (a : β β β) : Prop :=
β Ξ΅ > 0, β N, β m β₯ N, β n β₯ N, |a m - a n| < Ξ΅
|
b5baa879ec52d8770a1e433b76468b74a152f12c | fecda8e6b848337561d6467a1e30cf23176d6ad0 | /src/data/zmod/basic.lean | fe1696cb20581a7aee05a0e8fef7927eb82554b1 | [
"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 | 27,685 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Chris Hughes
-/
import data.int.modeq
import algebra.char_p
import data.nat.totient
import ring_theory.ideal.operations
/-!
# Integers mod `n`
Definition of the integers mod n, and the field structure on the integers mod p.
## Definitions
* `zmod n`, which is for integers modulo a nat `n : β`
* `val a` is defined as a natural number:
- for `a : zmod 0` it is the absolute value of `a`
- for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class
* `val_min_abs` returns the integer closest to zero in the equivalence class.
* A coercion `cast` is defined from `zmod n` into any ring.
This is a ring hom if the ring has characteristic dividing `n`
-/
namespace fin
/-!
## Ring structure on `fin n`
We define a commutative ring structure on `fin n`, but we do not register it as instance.
Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions
to register the ring structure on `zmod n` as type class instance.
-/
open nat nat.modeq int
/-- Negation on `fin n` -/
def has_neg (n : β) : has_neg (fin n) :=
β¨Ξ» a, β¨nat_mod (-(a.1 : β€)) n,
begin
have npos : 0 < n := lt_of_le_of_lt (nat.zero_le _) a.2,
have h : (n : β€) β 0 := int.coe_nat_ne_zero_iff_pos.2 npos,
have := int.mod_lt (-(a.1 : β€)) h,
rw [(abs_of_nonneg (int.coe_nat_nonneg n))] at this,
rwa [β int.coe_nat_lt, nat_mod, to_nat_of_nonneg (int.mod_nonneg _ h)]
endβ©β©
/-- Additive commutative semigroup structure on `fin (n+1)`. -/
def add_comm_semigroup (n : β) : add_comm_semigroup (fin (n+1)) :=
{ add_assoc := Ξ» β¨a, haβ© β¨b, hbβ© β¨c, hcβ©, fin.eq_of_veq
(show ((a + b) % (n+1) + c) β‘ (a + (b + c) % (n+1)) [MOD (n+1)],
from calc ((a + b) % (n+1) + c) β‘ a + b + c [MOD (n+1)] : modeq_add (nat.mod_mod _ _) rfl
... β‘ a + (b + c) [MOD (n+1)] : by rw add_assoc
... β‘ (a + (b + c) % (n+1)) [MOD (n+1)] : modeq_add rfl (nat.mod_mod _ _).symm),
add_comm := Ξ» β¨a, _β© β¨b, _β©,
fin.eq_of_veq (show (a + b) % (n+1) = (b + a) % (n+1), by rw add_comm),
..fin.has_add }
/-- Multiplicative commutative semigroup structure on `fin (n+1)`. -/
def comm_semigroup (n : β) : comm_semigroup (fin (n+1)) :=
{ mul_assoc := Ξ» β¨a, haβ© β¨b, hbβ© β¨c, hcβ©, fin.eq_of_veq
(calc ((a * b) % (n+1) * c) β‘ a * b * c [MOD (n+1)] : modeq_mul (nat.mod_mod _ _) rfl
... β‘ a * (b * c) [MOD (n+1)] : by rw mul_assoc
... β‘ a * (b * c % (n+1)) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _).symm),
mul_comm := Ξ» β¨a, _β© β¨b, _β©,
fin.eq_of_veq (show (a * b) % (n+1) = (b * a) % (n+1), by rw mul_comm),
..fin.has_mul }
local attribute [instance] fin.add_comm_semigroup fin.comm_semigroup
private lemma one_mul_aux (n : β) (a : fin (n+1)) : (1 : fin (n+1)) * a = a :=
begin
cases n with n,
{ exact subsingleton.elim _ _ },
{ have hβ : (a : β) % n.succ.succ = a := nat.mod_eq_of_lt a.2,
apply fin.ext,
simp only [coe_mul, coe_one, hβ, one_mul], }
end
private lemma left_distrib_aux (n : β) : β a b c : fin (n+1), a * (b + c) = a * b + a * c :=
Ξ» β¨a, haβ© β¨b, hbβ© β¨c, hcβ©, fin.eq_of_veq
(calc a * ((b + c) % (n+1)) β‘ a * (b + c) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _)
... β‘ a * b + a * c [MOD (n+1)] : by rw mul_add
... β‘ (a * b) % (n+1) + (a * c) % (n+1) [MOD (n+1)] :
modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm)
/-- Commutative ring structure on `fin (n+1)`. -/
def comm_ring (n : β) : comm_ring (fin (n+1)) :=
{ zero_add := Ξ» β¨a, haβ©, fin.eq_of_veq (show (0 + a) % (n+1) = a,
by rw zero_add; exact nat.mod_eq_of_lt ha),
add_zero := Ξ» β¨a, haβ©, fin.eq_of_veq (nat.mod_eq_of_lt ha),
add_left_neg :=
Ξ» β¨a, haβ©, fin.eq_of_veq (show (((-a : β€) % (n+1)).to_nat + a) % (n+1) = 0,
from int.coe_nat_inj
begin
have npos : 0 < n+1 := lt_of_le_of_lt (nat.zero_le _) ha,
have hn : ((n+1) : β€) β 0 := (ne_of_lt (int.coe_nat_lt.2 npos)).symm,
rw [int.coe_nat_mod, int.coe_nat_add, to_nat_of_nonneg (int.mod_nonneg _ hn), add_comm],
simp,
end),
one_mul := one_mul_aux n,
mul_one := Ξ» a, by rw mul_comm; exact one_mul_aux n a,
left_distrib := left_distrib_aux n,
right_distrib := Ξ» a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl,
..fin.has_zero,
..fin.has_one,
..fin.has_neg (n+1),
..fin.add_comm_semigroup n,
..fin.comm_semigroup n }
end fin
/-- The integers modulo `n : β`. -/
def zmod : β β Type
| 0 := β€
| (n+1) := fin (n+1)
namespace zmod
instance fintype : Ξ (n : β) [fact (0 < n)], fintype (zmod n)
| 0 _ := false.elim $ nat.not_lt_zero 0 βΉ0 < 0βΊ
| (n+1) _ := fin.fintype (n+1)
lemma card (n : β) [fact (0 < n)] : fintype.card (zmod n) = n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 βΉ0 < 0βΊ },
{ exact fintype.card_fin (n+1) }
end
instance decidable_eq : Ξ (n : β), decidable_eq (zmod n)
| 0 := int.decidable_eq
| (n+1) := fin.decidable_eq _
instance has_repr : Ξ (n : β), has_repr (zmod n)
| 0 := int.has_repr
| (n+1) := fin.has_repr _
instance comm_ring : Ξ (n : β), comm_ring (zmod n)
| 0 := int.comm_ring
| (n+1) := fin.comm_ring n
instance inhabited (n : β) : inhabited (zmod n) := β¨0β©
/-- `val a` is a natural number defined as:
- for `a : zmod 0` it is the absolute value of `a`
- for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class
See `zmod.val_min_abs` for a variant that takes values in the integers.
-/
def val : Ξ {n : β}, zmod n β β
| 0 := int.nat_abs
| (n+1) := (coe : fin (n + 1) β β)
lemma val_lt {n : β} [fact (0 < n)] (a : zmod n) : a.val < n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 βΉ0 < 0βΊ },
exact fin.is_lt a
end
@[simp] lemma val_zero : β {n}, (0 : zmod n).val = 0
| 0 := rfl
| (n+1) := rfl
lemma val_cast_nat {n : β} (a : β) : (a : zmod n).val = a % n :=
begin
casesI n,
{ rw [nat.mod_zero, int.nat_cast_eq_coe_nat],
exact int.nat_abs_of_nat a, },
rw β fin.of_nat_eq_coe,
refl
end
instance (n : β) : char_p (zmod n) n :=
{ cast_eq_zero_iff :=
begin
intro k,
cases n,
{ simp only [int.nat_cast_eq_coe_nat, zero_dvd_iff, int.coe_nat_eq_zero], },
rw [fin.eq_iff_veq],
show (k : zmod (n+1)).val = (0 : zmod (n+1)).val β _,
rw [val_cast_nat, val_zero, nat.dvd_iff_mod_eq_zero],
end }
@[simp] lemma cast_self (n : β) : (n : zmod n) = 0 :=
char_p.cast_eq_zero (zmod n) n
@[simp] lemma cast_self' (n : β) : (n + 1 : zmod (n + 1)) = 0 :=
by rw [β nat.cast_add_one, cast_self (n + 1)]
section universal_property
variables {n : β} {R : Type*}
section
variables [has_zero R] [has_one R] [has_add R] [has_neg R]
/-- Cast an integer modulo `n` to another semiring.
This function is a morphism if the characteristic of `R` divides `n`.
See `zmod.cast_hom` for a bundled version. -/
def cast : Ξ {n : β}, zmod n β R
| 0 := int.cast
| (n+1) := Ξ» i, i.val
-- see Note [coercion into rings]
@[priority 900] instance (n : β) : has_coe_t (zmod n) R := β¨castβ©
@[simp] lemma cast_zero : ((0 : zmod n) : R) = 0 :=
by { cases n; refl }
end
lemma nat_cast_surjective [fact (0 < n)] :
function.surjective (coe : β β zmod n) :=
begin
assume i,
casesI n,
{ exfalso, exact nat.not_lt_zero 0 βΉ0 < 0βΊ },
{ change fin (n + 1) at i,
refine β¨i, _β©,
rw [fin.ext_iff, fin.coe_coe_eq_self] }
end
lemma int_cast_surjective :
function.surjective (coe : β€ β zmod n) :=
begin
assume i,
cases n,
{ exact β¨i, int.cast_id iβ© },
{ rcases nat_cast_surjective i with β¨k, rflβ©,
refine β¨k, _β©, norm_cast }
end
lemma cast_val {n : β} [fact (0 < n)] (a : zmod n) :
(a.val : zmod n) = a :=
begin
rcases nat_cast_surjective a with β¨k, rflβ©,
symmetry,
rw [val_cast_nat, β sub_eq_zero, β nat.cast_sub, char_p.cast_eq_zero_iff (zmod n) n],
{ apply nat.dvd_sub_mod },
{ apply nat.mod_le }
end
@[simp, norm_cast]
lemma cast_id : β n (i : zmod n), βi = i
| 0 i := int.cast_id i
| (n+1) i := cast_val i
variables [ring R]
@[simp] lemma nat_cast_val [fact (0 < n)] (i : zmod n) :
(i.val : R) = i :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 βΉ0 < 0βΊ },
refl
end
section char_dvd
/-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/
variables {n} {m : β} [char_p R m]
@[simp] lemma cast_one (h : m β£ n) : ((1 : zmod n) : R) = 1 :=
begin
casesI n,
{ exact int.cast_one },
show ((1 % (n+1) : β) : R) = 1,
cases n, { rw [nat.dvd_one] at h, substI m, apply subsingleton.elim },
rw nat.mod_eq_of_lt,
{ exact nat.cast_one },
exact nat.lt_of_sub_eq_succ rfl
end
lemma cast_add (h : m β£ n) (a b : zmod n) : ((a + b : zmod n) : R) = a + b :=
begin
casesI n,
{ apply int.cast_add },
simp only [coe_coe],
symmetry,
erw [fin.coe_add, β nat.cast_add, β sub_eq_zero, β nat.cast_sub (nat.mod_le _ _),
@char_p.cast_eq_zero_iff R _ m],
exact dvd_trans h (nat.dvd_sub_mod _),
end
lemma cast_mul (h : m β£ n) (a b : zmod n) : ((a * b : zmod n) : R) = a * b :=
begin
casesI n,
{ apply int.cast_mul },
simp only [coe_coe],
symmetry,
erw [fin.coe_mul, β nat.cast_mul, β sub_eq_zero, β nat.cast_sub (nat.mod_le _ _),
@char_p.cast_eq_zero_iff R _ m],
exact dvd_trans h (nat.dvd_sub_mod _),
end
/-- The canonical ring homomorphism from `zmod n` to a ring of characteristic `n`. -/
def cast_hom (h : m β£ n) (R : Type*) [ring R] [char_p R m] : zmod n β+* R :=
{ to_fun := coe,
map_zero' := cast_zero,
map_one' := cast_one h,
map_add' := cast_add h,
map_mul' := cast_mul h }
@[simp] lemma cast_hom_apply {h : m β£ n} (i : zmod n) : cast_hom h R i = i := rfl
@[simp, norm_cast]
lemma cast_sub (h : m β£ n) (a b : zmod n) : ((a - b : zmod n) : R) = a - b :=
(cast_hom h R).map_sub a b
@[simp, norm_cast]
lemma cast_neg (h : m β£ n) (a : zmod n) : ((-a : zmod n) : R) = -a :=
(cast_hom h R).map_neg a
@[simp, norm_cast]
lemma cast_pow (h : m β£ n) (a : zmod n) (k : β) : ((a ^ k : zmod n) : R) = a ^ k :=
(cast_hom h R).map_pow a k
@[simp, norm_cast]
lemma cast_nat_cast (h : m β£ n) (k : β) : ((k : zmod n) : R) = k :=
(cast_hom h R).map_nat_cast k
@[simp, norm_cast]
lemma cast_int_cast (h : m β£ n) (k : β€) : ((k : zmod n) : R) = k :=
(cast_hom h R).map_int_cast k
end char_dvd
section char_eq
/-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/
variable [char_p R n]
@[simp] lemma cast_one' : ((1 : zmod n) : R) = 1 :=
cast_one (dvd_refl _)
@[simp] lemma cast_add' (a b : zmod n) : ((a + b : zmod n) : R) = a + b :=
cast_add (dvd_refl _) a b
@[simp] lemma cast_mul' (a b : zmod n) : ((a * b : zmod n) : R) = a * b :=
cast_mul (dvd_refl _) a b
@[simp] lemma cast_sub' (a b : zmod n) : ((a - b : zmod n) : R) = a - b :=
cast_sub (dvd_refl _) a b
@[simp] lemma cast_pow' (a : zmod n) (k : β) : ((a ^ k : zmod n) : R) = a ^ k :=
cast_pow (dvd_refl _) a k
@[simp, norm_cast]
lemma cast_nat_cast' (k : β) : ((k : zmod n) : R) = k :=
cast_nat_cast (dvd_refl _) k
@[simp, norm_cast]
lemma cast_int_cast' (k : β€) : ((k : zmod n) : R) = k :=
cast_int_cast (dvd_refl _) k
end char_eq
end universal_property
lemma int_coe_eq_int_coe_iff (a b : β€) (c : β) :
(a : zmod c) = (b : zmod c) β a β‘ b [ZMOD c] :=
char_p.int_coe_eq_int_coe_iff (zmod c) c a b
lemma nat_coe_eq_nat_coe_iff (a b c : β) :
(a : zmod c) = (b : zmod c) β a β‘ b [MOD c] :=
begin
convert zmod.int_coe_eq_int_coe_iff a b c,
simp [nat.modeq.modeq_iff_dvd, int.modeq.modeq_iff_dvd],
end
lemma int_coe_zmod_eq_zero_iff_dvd (a : β€) (b : β) : (a : zmod b) = 0 β (b : β€) β£ a :=
begin
change (a : zmod b) = ((0 : β€) : zmod b) β (b : β€) β£ a,
rw [zmod.int_coe_eq_int_coe_iff, int.modeq.modeq_zero_iff],
end
lemma nat_coe_zmod_eq_zero_iff_dvd (a b : β) : (a : zmod b) = 0 β b β£ a :=
begin
change (a : zmod b) = ((0 : β) : zmod b) β b β£ a,
rw [zmod.nat_coe_eq_nat_coe_iff, nat.modeq.modeq_zero_iff],
end
@[push_cast, simp]
lemma cast_mod_int (a : β€) (b : β) : ((a % b : β€) : zmod b) = (a : zmod b) :=
begin
rw zmod.int_coe_eq_int_coe_iff,
apply int.modeq.mod_modeq,
end
@[simp] lemma coe_to_nat (p : β) :
β {z : β€} (h : 0 β€ z), (z.to_nat : zmod p) = z
| (n : β) h := by simp only [int.cast_coe_nat, int.to_nat_coe_nat]
| -[1+n] h := false.elim h
lemma val_injective (n : β) [fact (0 < n)] :
function.injective (zmod.val : zmod n β β) :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 βΉ_βΊ },
assume a b h,
ext,
exact h
end
lemma val_one_eq_one_mod (n : β) : (1 : zmod n).val = 1 % n :=
by rw [β nat.cast_one, val_cast_nat]
lemma val_one (n : β) [fact (1 < n)] : (1 : zmod n).val = 1 :=
by { rw val_one_eq_one_mod, exact nat.mod_eq_of_lt βΉ1 < nβΊ }
lemma val_add {n : β} [fact (0 < n)] (a b : zmod n) : (a + b).val = (a.val + b.val) % n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 βΉ0 < 0βΊ },
{ apply fin.val_add }
end
lemma val_mul {n : β} (a b : zmod n) : (a * b).val = (a.val * b.val) % n :=
begin
cases n,
{ rw nat.mod_zero, apply int.nat_abs_mul },
{ apply fin.val_mul }
end
instance nontrivial (n : β) [fact (1 < n)] : nontrivial (zmod n) :=
β¨β¨0, 1, assume h, zero_ne_one $
calc 0 = (0 : zmod n).val : by rw val_zero
... = (1 : zmod n).val : congr_arg zmod.val h
... = 1 : val_one n β©β©
/-- The inversion on `zmod n`.
It is setup in such a way that `a * aβ»ΒΉ` is equal to `gcd a.val n`.
In particular, if `a` is coprime to `n`, and hence a unit, `a * aβ»ΒΉ = 1`. -/
def inv : Ξ (n : β), zmod n β zmod n
| 0 i := int.sign i
| (n+1) i := nat.gcd_a i.val (n+1)
instance (n : β) : has_inv (zmod n) := β¨inv nβ©
lemma inv_zero : β (n : β), (0 : zmod n)β»ΒΉ = 0
| 0 := int.sign_zero
| (n+1) := show (nat.gcd_a _ (n+1) : zmod (n+1)) = 0,
by { rw val_zero, unfold nat.gcd_a nat.xgcd nat.xgcd_aux, refl }
lemma mul_inv_eq_gcd {n : β} (a : zmod n) :
a * aβ»ΒΉ = nat.gcd a.val n :=
begin
cases n,
{ calc a * aβ»ΒΉ = a * int.sign a : rfl
... = a.nat_abs : by rw [int.mul_sign, int.nat_cast_eq_coe_nat]
... = a.val.gcd 0 : by rw nat.gcd_zero_right; refl },
{ set k := n.succ,
calc a * aβ»ΒΉ = a * aβ»ΒΉ + k * nat.gcd_b (val a) k : by rw [cast_self, zero_mul, add_zero]
... = β(βa.val * nat.gcd_a (val a) k + k * nat.gcd_b (val a) k) :
by { push_cast, rw cast_val, refl }
... = nat.gcd a.val k : (congr_arg coe (nat.gcd_eq_gcd_ab a.val k)).symm, }
end
@[simp] lemma cast_mod_nat (n : β) (a : β) : ((a % n : β) : zmod n) = a :=
by conv {to_rhs, rw β nat.mod_add_div a n}; simp
lemma eq_iff_modeq_nat (n : β) {a b : β} : (a : zmod n) = b β a β‘ b [MOD n] :=
begin
cases n,
{ simp only [nat.modeq, int.coe_nat_inj', nat.mod_zero, int.nat_cast_eq_coe_nat], },
{ rw [fin.ext_iff, nat.modeq, β val_cast_nat, β val_cast_nat], exact iff.rfl, }
end
lemma coe_mul_inv_eq_one {n : β} (x : β) (h : nat.coprime x n) :
(x * xβ»ΒΉ : zmod n) = 1 :=
begin
rw [nat.coprime, nat.gcd_comm, nat.gcd_rec] at h,
rw [mul_inv_eq_gcd, val_cast_nat, h, nat.cast_one],
end
/-- `unit_of_coprime` makes an element of `units (zmod n)` given
a natural number `x` and a proof that `x` is coprime to `n` -/
def unit_of_coprime {n : β} (x : β) (h : nat.coprime x n) : units (zmod n) :=
β¨x, xβ»ΒΉ, coe_mul_inv_eq_one x h, by rw [mul_comm, coe_mul_inv_eq_one x h]β©
@[simp] lemma cast_unit_of_coprime {n : β} (x : β) (h : nat.coprime x n) :
(unit_of_coprime x h : zmod n) = x := rfl
lemma val_coe_unit_coprime {n : β} (u : units (zmod n)) :
nat.coprime (u : zmod n).val n :=
begin
cases n,
{ rcases int.units_eq_one_or u with rfl|rfl; exact dec_trivial },
apply nat.modeq.coprime_of_mul_modeq_one ((uβ»ΒΉ : units (zmod (n+1))) : zmod (n+1)).val,
have := units.ext_iff.1 (mul_right_inv u),
rw [units.coe_one] at this,
rw [β eq_iff_modeq_nat, nat.cast_one, β this], clear this,
rw [β cast_val ((u * uβ»ΒΉ : units (zmod (n+1))) : zmod (n+1))],
rw [units.coe_mul, val_mul, cast_mod_nat],
end
@[simp] lemma inv_coe_unit {n : β} (u : units (zmod n)) :
(u : zmod n)β»ΒΉ = (uβ»ΒΉ : units (zmod n)) :=
begin
have := congr_arg (coe : β β zmod n) (val_coe_unit_coprime u),
rw [β mul_inv_eq_gcd, nat.cast_one] at this,
let u' : units (zmod n) := β¨u, (u : zmod n)β»ΒΉ, this, by rwa mul_commβ©,
have h : u = u', { apply units.ext, refl },
rw h,
refl
end
lemma mul_inv_of_unit {n : β} (a : zmod n) (h : is_unit a) :
a * aβ»ΒΉ = 1 :=
begin
rcases h with β¨u, rflβ©,
rw [inv_coe_unit, u.mul_inv],
end
lemma inv_mul_of_unit {n : β} (a : zmod n) (h : is_unit a) :
aβ»ΒΉ * a = 1 :=
by rw [mul_comm, mul_inv_of_unit a h]
/-- Equivalence between the units of `zmod n` and
the subtype of terms `x : zmod n` for which `x.val` is comprime to `n` -/
def units_equiv_coprime {n : β} [fact (0 < n)] :
units (zmod n) β {x : zmod n // nat.coprime x.val n} :=
{ to_fun := Ξ» x, β¨x, val_coe_unit_coprime xβ©,
inv_fun := Ξ» x, unit_of_coprime x.1.val x.2,
left_inv := Ξ» β¨_, _, _, _β©, units.ext (cast_val _),
right_inv := Ξ» β¨_, _β©, by simp }
section totient
open_locale nat
@[simp] lemma card_units_eq_totient (n : β) [fact (0 < n)] :
fintype.card (units (zmod n)) = Ο n :=
calc fintype.card (units (zmod n)) = fintype.card {x : zmod n // x.val.coprime n} :
fintype.card_congr zmod.units_equiv_coprime
... = Ο n :
begin
apply finset.card_congr (Ξ» (a : {x : zmod n // x.val.coprime n}) _, a.1.val),
{ intro a, simp [(a : zmod n).val_lt, a.prop.symm] {contextual := tt} },
{ intros _ _ _ _ h, rw subtype.ext_iff_val, apply val_injective, exact h, },
{ intros b hb,
rw [finset.mem_filter, finset.mem_range] at hb,
refine β¨β¨b, _β©, finset.mem_univ _, _β©,
{ let u := unit_of_coprime b hb.2.symm,
exact val_coe_unit_coprime u },
{ show zmod.val (b : zmod n) = b,
rw [val_cast_nat, nat.mod_eq_of_lt hb.1], } }
end
end totient
instance subsingleton_units : subsingleton (units (zmod 2)) :=
β¨Ξ» x y, begin
cases x with x xi,
cases y with y yi,
revert x y xi yi,
exact dec_trivial
endβ©
lemma le_div_two_iff_lt_neg (n : β) [hn : fact ((n : β) % 2 = 1)]
{x : zmod n} (hx0 : x β 0) : x.val β€ (n / 2 : β) β (n / 2 : β) < (-x).val :=
begin
haveI npos : fact (0 < n) := by
{ apply (nat.eq_zero_or_pos n).resolve_left,
unfreezingI { rintro rfl },
simpa [fact] using hn, },
have hn2 : (n : β) / 2 < n := nat.div_lt_of_lt_mul ((lt_mul_iff_one_lt_left npos).2 dec_trivial),
have hn2' : (n : β) - n / 2 = n / 2 + 1,
{ conv {to_lhs, congr, rw [β nat.succ_sub_one n, nat.succ_sub npos]},
rw [β nat.two_mul_odd_div_two hn, two_mul, β nat.succ_add, nat.add_sub_cancel], },
have hxn : (n : β) - x.val < n,
{ rw [nat.sub_lt_iff (le_of_lt x.val_lt) (le_refl _), nat.sub_self],
rw β zmod.cast_val x at hx0,
exact nat.pos_of_ne_zero (Ξ» h, by simpa [h] using hx0) },
by conv {to_rhs, rw [β nat.succ_le_iff, nat.succ_eq_add_one, β hn2', β zero_add (- x),
β zmod.cast_self, β sub_eq_add_neg, β zmod.cast_val x, β nat.cast_sub (le_of_lt x.val_lt),
zmod.val_cast_nat, nat.mod_eq_of_lt hxn, nat.sub_le_sub_left_iff (le_of_lt x.val_lt)] }
end
lemma ne_neg_self (n : β) [hn : fact ((n : β) % 2 = 1)] {a : zmod n} (ha : a β 0) : a β -a :=
Ξ» h, have a.val β€ n / 2 β (n : β) / 2 < (-a).val := le_div_two_iff_lt_neg n ha,
by rwa [β h, β not_lt, not_iff_self] at this
lemma neg_one_ne_one {n : β} [fact (2 < n)] :
(-1 : zmod n) β 1 :=
char_p.neg_one_ne_one (zmod n) n
@[simp] lemma neg_eq_self_mod_two : β (a : zmod 2), -a = a := dec_trivial
@[simp] lemma nat_abs_mod_two (a : β€) : (a.nat_abs : zmod 2) = a :=
begin
cases a,
{ simp only [int.nat_abs_of_nat, int.cast_coe_nat, int.of_nat_eq_coe] },
{ simp only [neg_eq_self_mod_two, nat.cast_succ, int.nat_abs, int.cast_neg_succ_of_nat] }
end
@[simp] lemma val_eq_zero : β {n : β} (a : zmod n), a.val = 0 β a = 0
| 0 a := int.nat_abs_eq_zero
| (n+1) a := by { rw fin.ext_iff, exact iff.rfl }
lemma val_cast_of_lt {n : β} {a : β} (h : a < n) : (a : zmod n).val = a :=
by rw [val_cast_nat, nat.mod_eq_of_lt h]
lemma neg_val' {n : β} [fact (0 < n)] (a : zmod n) : (-a).val = (n - a.val) % n :=
begin
have : ((-a).val + a.val) % n = (n - a.val + a.val) % n,
{ rw [βval_add, add_left_neg, nat.sub_add_cancel (le_of_lt a.val_lt), nat.mod_self, val_zero], },
calc (-a).val = val (-a) % n : by rw nat.mod_eq_of_lt ((-a).val_lt)
... = (n - val a) % n : nat.modeq.modeq_add_cancel_right rfl this
end
lemma neg_val {n : β} [fact (0 < n)] (a : zmod n) : (-a).val = if a = 0 then 0 else n - a.val :=
begin
rw neg_val',
by_cases h : a = 0, { rw [if_pos h, h, val_zero, nat.sub_zero, nat.mod_self] },
rw if_neg h,
apply nat.mod_eq_of_lt,
apply nat.sub_lt βΉ0 < nβΊ,
contrapose! h,
rwa [nat.le_zero_iff, val_eq_zero] at h,
end
/-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`,
The result will be in the interval `(-n/2, n/2]`. -/
def val_min_abs : Ξ {n : β}, zmod n β β€
| 0 x := x
| n@(_+1) x := if x.val β€ n / 2 then x.val else (x.val : β€) - n
@[simp] lemma val_min_abs_def_zero (x : zmod 0) : val_min_abs x = x := rfl
lemma val_min_abs_def_pos {n : β} [fact (0 < n)] (x : zmod n) :
val_min_abs x = if x.val β€ n / 2 then x.val else x.val - n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 βΉ0 < 0βΊ },
{ refl }
end
@[simp] lemma coe_val_min_abs : β {n : β} (x : zmod n), (x.val_min_abs : zmod n) = x
| 0 x := int.cast_id x
| k@(n+1) x :=
begin
rw val_min_abs_def_pos,
split_ifs,
{ rw [int.cast_coe_nat, cast_val] },
{ rw [int.cast_sub, int.cast_coe_nat, cast_val, int.cast_coe_nat, cast_self, sub_zero], }
end
lemma nat_abs_val_min_abs_le {n : β} [fact (0 < n)] (x : zmod n) : x.val_min_abs.nat_abs β€ n / 2 :=
begin
rw zmod.val_min_abs_def_pos,
split_ifs with h, { exact h },
have : (x.val - n : β€) β€ 0,
{ rw [sub_nonpos, int.coe_nat_le], exact le_of_lt x.val_lt, },
rw [β int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub],
conv_lhs { congr, rw [β nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul,
int.coe_nat_bit0, int.coe_nat_one] },
suffices : ((n % 2 : β) + (n / 2) : β€) β€ (val x),
{ rw β sub_nonneg at this β’, apply le_trans this (le_of_eq _), ring },
norm_cast,
calc (n : β) % 2 + n / 2 β€ 1 + n / 2 :
nat.add_le_add_right (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) _
... β€ x.val :
by { rw add_comm, exact nat.succ_le_of_lt (lt_of_not_ge h) }
end
@[simp] lemma val_min_abs_zero : β n, (0 : zmod n).val_min_abs = 0
| 0 := by simp only [val_min_abs_def_zero]
| (n+1) := by simp only [val_min_abs_def_pos, if_true, int.coe_nat_zero, zero_le, val_zero]
@[simp] lemma val_min_abs_eq_zero {n : β} (x : zmod n) :
x.val_min_abs = 0 β x = 0 :=
begin
cases n, { simp },
split,
{ simp only [val_min_abs_def_pos, int.coe_nat_succ],
split_ifs with h h; assume h0,
{ apply val_injective, rwa [int.coe_nat_eq_zero] at h0, },
{ apply absurd h0, rw sub_eq_zero, apply ne_of_lt, exact_mod_cast x.val_lt } },
{ rintro rfl, rw val_min_abs_zero }
end
lemma cast_nat_abs_val_min_abs {n : β} [fact (0 < n)] (a : zmod n) :
(a.val_min_abs.nat_abs : zmod n) = if a.val β€ (n : β) / 2 then a else -a :=
begin
have : (a.val : β€) - n β€ 0,
by { erw [sub_nonpos, int.coe_nat_le], exact le_of_lt a.val_lt, },
rw [zmod.val_min_abs_def_pos],
split_ifs,
{ rw [int.nat_abs_of_nat, cast_val] },
{ rw [β int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this, int.cast_neg, int.cast_sub],
rw [int.cast_coe_nat, int.cast_coe_nat, cast_self, sub_zero, cast_val], }
end
@[simp] lemma nat_abs_val_min_abs_neg {n : β} (a : zmod n) :
(-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs :=
begin
cases n, { simp only [int.nat_abs_neg, val_min_abs_def_zero], },
by_cases ha0 : a = 0, { rw [ha0, neg_zero] },
by_cases haa : -a = a, { rw [haa] },
suffices hpa : (n+1 : β) - a.val β€ (n+1) / 2 β (n+1 : β) / 2 < a.val,
{ rw [val_min_abs_def_pos, val_min_abs_def_pos],
rw β not_le at hpa,
simp only [if_neg ha0, neg_val, hpa, int.coe_nat_sub (le_of_lt a.val_lt)],
split_ifs,
all_goals { rw [β int.nat_abs_neg], congr' 1, ring } },
suffices : (((n+1 : β) % 2) + 2 * ((n + 1) / 2)) - a.val β€ (n+1) / 2 β (n+1 : β) / 2 < a.val,
by rwa [nat.mod_add_div] at this,
suffices : (n + 1) % 2 + (n + 1) / 2 β€ val a β (n + 1) / 2 < val a,
by rw [nat.sub_le_iff, two_mul, β add_assoc, nat.add_sub_cancel, this],
cases (n + 1 : β).mod_two_eq_zero_or_one with hn0 hn1,
{ split,
{ assume h,
apply lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h),
contrapose! haa,
rw [β zmod.cast_val a, β haa, neg_eq_iff_add_eq_zero, β nat.cast_add],
rw [char_p.cast_eq_zero_iff (zmod (n+1)) (n+1)],
rw [β two_mul, β zero_add (2 * _), β hn0, nat.mod_add_div] },
{ rw [hn0, zero_add], exact le_of_lt } },
{ rw [hn1, add_comm, nat.succ_le_iff] }
end
lemma val_eq_ite_val_min_abs {n : β} [fact (0 < n)] (a : zmod n) :
(a.val : β€) = a.val_min_abs + if a.val β€ n / 2 then 0 else n :=
by { rw [zmod.val_min_abs_def_pos], split_ifs; simp only [add_zero, sub_add_cancel] }
lemma prime_ne_zero (p q : β) [hp : fact p.prime] [hq : fact q.prime] (hpq : p β q) :
(q : zmod p) β 0 :=
by rwa [β nat.cast_zero, ne.def, eq_iff_modeq_nat, nat.modeq.modeq_zero_iff,
β hp.coprime_iff_not_dvd, nat.coprime_primes hp hq]
end zmod
namespace zmod
variables (p : β) [fact p.prime]
private lemma mul_inv_cancel_aux (a : zmod p) (h : a β 0) : a * aβ»ΒΉ = 1 :=
begin
obtain β¨k, rflβ© := nat_cast_surjective a,
apply coe_mul_inv_eq_one,
apply nat.coprime.symm,
rwa [nat.prime.coprime_iff_not_dvd βΉp.primeβΊ, β char_p.cast_eq_zero_iff (zmod p)]
end
/-- Field structure on `zmod p` if `p` is prime. -/
instance : field (zmod p) :=
{ mul_inv_cancel := mul_inv_cancel_aux p,
inv_zero := inv_zero p,
.. zmod.comm_ring p,
.. zmod.has_inv p,
.. zmod.nontrivial p }
end zmod
lemma ring_hom.ext_zmod {n : β} {R : Type*} [semiring R] (f g : (zmod n) β+* R) : f = g :=
begin
ext a,
obtain β¨k, rflβ© := zmod.int_cast_surjective a,
let Ο : β€ β+* R := f.comp (int.cast_ring_hom (zmod n)),
let Ο : β€ β+* R := g.comp (int.cast_ring_hom (zmod n)),
show Ο k = Ο k,
rw Ο.ext_int Ο,
end
instance zmod.subsingleton_ring_hom {n : β} {R : Type*} [semiring R] :
subsingleton ((zmod n) β+* R) :=
β¨ring_hom.ext_zmodβ©
lemma zmod.ring_hom_surjective {R : Type*} [comm_ring R] {n : β} (f : R β+* (zmod n)) :
function.surjective f :=
begin
intros k,
rcases zmod.int_cast_surjective k with β¨n, rflβ©,
refine β¨n, f.map_int_cast nβ©
end
lemma zmod.ring_hom_eq_of_ker_eq {R : Type*} [comm_ring R] {n : β} (f g : R β+* (zmod n))
(h : f.ker = g.ker) : f = g :=
by rw [β f.lift_of_surjective_comp (zmod.ring_hom_surjective f) g (le_of_eq h),
ring_hom.ext_zmod (f.lift_of_surjective _ _ _) (ring_hom.id _),
ring_hom.id_comp]
|
d288432675befc58d4758b7fbdd8d2b81e5686e0 | a7dd8b83f933e72c40845fd168dde330f050b1c9 | /src/data/rat.lean | 7670306ab38ecda2606df1abb3a6f7996c39b438 | [
"Apache-2.0"
] | permissive | NeilStrickland/mathlib | 10420e92ee5cb7aba1163c9a01dea2f04652ed67 | 3efbd6f6dff0fb9b0946849b43b39948560a1ffe | refs/heads/master | 1,589,043,046,346 | 1,558,938,706,000 | 1,558,938,706,000 | 181,285,984 | 0 | 0 | Apache-2.0 | 1,568,941,848,000 | 1,555,233,833,000 | Lean | UTF-8 | Lean | false | false | 45,245 | 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
Introduces the rational numbers as discrete, linear ordered field.
-/
import
data.nat.gcd data.pnat data.int.sqrt data.equiv.encodable
algebra.group algebra.ordered_group algebra.group_power
algebra.ordered_field
tactic.norm_cast
/- rational numbers -/
/-- `rat`, or `β`, is the type of rational numbers. It is defined
as the set of pairs β¨n, dβ© of integers such that `d` is positive and `n` and
`d` are coprime. This representation is preferred to the quotient
because without periodic reduction, the numerator and denominator can grow
exponentially (for example, adding 1/2 to itself repeatedly). -/
structure rat := mk' ::
(num : β€)
(denom : β)
(pos : denom > 0)
(cop : num.nat_abs.coprime denom)
notation `β` := rat
namespace rat
protected def repr : β β string
| β¨n, d, _, _β© := if d = 1 then _root_.repr n else
_root_.repr n ++ "/" ++ _root_.repr d
instance : has_repr β := β¨rat.reprβ©
instance : has_to_string β := β¨rat.reprβ©
meta instance : has_to_format β := β¨coe β rat.reprβ©
instance : encodable β := encodable.of_equiv (Ξ£ n : β€, {d : β // d > 0 β§ n.nat_abs.coprime d})
β¨Ξ» β¨a, b, c, dβ©, β¨a, b, c, dβ©, Ξ»β¨a, b, c, dβ©, β¨a, b, c, dβ©,
Ξ» β¨a, b, c, dβ©, rfl, Ξ»β¨a, b, c, dβ©, rflβ©
/-- Embed an integer as a rational number -/
def of_int (n : β€) : β :=
β¨n, 1, nat.one_pos, nat.coprime_one_right _β©
instance : has_zero β := β¨of_int 0β©
instance : has_one β := β¨of_int 1β©
instance : inhabited β := β¨0β©
/-- Form the quotient `n / d` where `n:β€` and `d:β+` (not necessarily coprime) -/
def mk_pnat (n : β€) : β+ β β | β¨d, dposβ© :=
let n' := n.nat_abs, g := n'.gcd d in
β¨n / g, d / g, begin
apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2,
simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _)
end, begin
have : int.nat_abs (n / βg) = n' / g,
{ cases int.nat_abs_eq n with e e; rw e, { refl },
rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl },
exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) },
rw this,
exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos)
endβ©
/-- Form the quotient `n / d` where `n:β€` and `d:β`. In the case `d = 0`, we
define `n / 0 = 0` by convention. -/
def mk_nat (n : β€) (d : β) : β :=
if d0 : d = 0 then 0 else mk_pnat n β¨d, nat.pos_of_ne_zero d0β©
/-- Form the quotient `n / d` where `n d : β€`. -/
def mk : β€ β β€ β β
| n (int.of_nat d) := mk_nat n d
| n -[1+ d] := mk_pnat (-n) d.succ_pnat
local infix ` /. `:70 := mk
theorem mk_pnat_eq (n d h) : mk_pnat n β¨d, hβ© = n /. d :=
by change n /. d with dite _ _ _; simp [ne_of_gt h]
theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl
@[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl
@[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 :=
by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl
@[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 :=
by by_cases n = 0; simp [*, mk_nat]
@[simp] theorem zero_mk (n) : 0 /. n = 0 :=
by cases n; simp [mk]
private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : β€) β£ a :=
int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b
@[simp] theorem mk_eq_zero {a b : β€} (b0 : b β 0) : a /. b = 0 β a = 0 :=
begin
constructor; intro h; [skip, {subst a, simp}],
have : β {a b}, mk_pnat a b = 0 β a = 0,
{ intros a b e, cases b with b h,
injection e with e,
apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e },
cases b with b; simp [mk, mk_nat] at h,
{ simp [mt (congr_arg int.of_nat) b0] at h,
exact this h },
{ apply neg_inj, simp [this h] }
end
theorem mk_eq : β {a b c d : β€} (hb : b β 0) (hd : d β 0),
a /. b = c /. d β a * d = c * b :=
suffices β a b c d hb hd, mk_pnat a β¨b, hbβ© = mk_pnat c β¨d, hdβ© β a * d = c * b,
begin
intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hb],
all_goals {
cases d with d d; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hd],
all_goals { rw this, try {refl} } },
{ change a * β(d.succ) = -c * βb β a * -(d.succ) = c * b,
constructor; intro h; apply neg_inj; simpa [left_distrib, neg_add_eq_iff_eq_add,
eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h },
{ change -a * βd = c * b.succ β a * d = c * -b.succ,
constructor; intro h; apply neg_inj; simpa [left_distrib, eq_comm] using h },
{ change -a * d.succ = -c * b.succ β a * -d.succ = c * -b.succ,
simp [left_distrib] }
end,
begin
intros, simp [mk_pnat], constructor; intro h,
{ cases h with ha hb,
have ha, {
have dv := @gcd_abs_dvd_left,
have := int.eq_mul_of_div_eq_right dv ha,
rw β int.mul_div_assoc _ dv at this,
exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm },
have hb, {
have dv := Ξ» {a b}, nat.gcd_dvd_right (int.nat_abs a) b,
have := nat.eq_mul_of_div_eq_right dv hb,
rw β nat.mul_div_assoc _ dv at this,
exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm },
have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : β€) β 0, {
refine int.coe_nat_ne_zero.2 (ne_of_gt _),
apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption },
apply eq_of_mul_eq_mul_right m0,
simpa [mul_comm, mul_left_comm] using
congr (congr_arg (*) ha.symm) (congr_arg coe hb) },
{ suffices : β a c, a * d = c * b β
a / a.gcd b = c / c.gcd d β§ b / a.gcd b = d / c.gcd d,
{ cases this a.nat_abs c.nat_abs
(by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with hβ hβ,
have hs := congr_arg int.sign h,
simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb),
int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs,
conv in a { rw β int.sign_mul_nat_abs a },
conv in c { rw β int.sign_mul_nat_abs c },
rw [int.mul_div_assoc, int.mul_div_assoc],
exact β¨congr (congr_arg (*) hs) (congr_arg coe hβ), hββ©,
all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } },
intros a c h,
suffices bd : b / a.gcd b = d / c.gcd d,
{ refine β¨_, bdβ©,
apply nat.eq_of_mul_eq_mul_left hb,
rw [β nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd,
β nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] },
suffices : β {a c : β} (b>0) (d>0),
a * d = c * b β b / a.gcd b β€ d / c.gcd d,
{ exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) },
intros a c b hb d hd h,
have gb0 := nat.gcd_pos_of_pos_right a hb,
have gd0 := nat.gcd_pos_of_pos_right c hd,
apply nat.le_of_dvd,
apply (nat.le_div_iff_mul_le _ _ gd0).2,
simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _),
apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left,
refine β¨c / c.gcd d, _β©,
rw [β nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
β nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)],
apply congr_arg (/ c.gcd d),
rw [mul_comm, β nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] }
end
@[simp] theorem div_mk_div_cancel_left {a b c : β€} (c0 : c β 0) :
(a * c) /. (b * c) = a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp },
apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc]
end
theorem num_denom : β a : β, a = a.num /. a.denom
| β¨n, d, h, (c:_=1)β© := show _ = mk_nat n d,
by simp [mk_nat, ne_of_gt h, mk_pnat, c]
theorem num_denom' (n d h c) : (β¨n, d, h, cβ© : β) = n /. d := num_denom _
@[elab_as_eliminator] theorem {u} num_denom_cases_on {C : β β Sort u}
: β (a : β) (H : β n d, d > 0 β (int.nat_abs n).coprime d β C (n /. d)), C a
| β¨n, d, h, cβ© H := by rw num_denom'; exact H n d h c
@[elab_as_eliminator] theorem {u} num_denom_cases_on' {C : β β Sort u}
(a : β) (H : β (n:β€) (d:β), d β 0 β C (n /. d)) : C a :=
num_denom_cases_on a $ Ξ» n d h c,
H n d $ ne_of_gt h
theorem num_dvd (a) {b : β€} (b0 : b β 0) : (a /. b).num β£ a :=
begin
cases e : a /. b with n d h c,
rw [rat.num_denom', rat.mk_eq b0
(ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $
c.dvd_of_dvd_mul_right _),
have := congr_arg int.nat_abs e,
simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this]
end
theorem denom_dvd (a b : β€) : ((a /. b).denom : β€) β£ b :=
begin
by_cases b0 : b = 0, {simp [b0]},
cases e : a /. b with n d h c,
rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _),
rw [β int.nat_abs_mul, β int.coe_nat_dvd, int.dvd_nat_abs, β e], simp
end
protected def add : β β β β β
| β¨nβ, dβ, hβ, cββ© β¨nβ, dβ, hβ, cββ© := mk_pnat (nβ * dβ + nβ * dβ) β¨dβ * dβ, mul_pos hβ hββ©
instance : has_add β := β¨rat.addβ©
theorem lift_binop_eq (f : β β β β β) (fβ : β€ β β€ β β€ β β€ β β€) (fβ : β€ β β€ β β€ β β€ β β€)
(fv : β {nβ dβ hβ cβ nβ dβ hβ cβ},
f β¨nβ, dβ, hβ, cββ© β¨nβ, dβ, hβ, cββ© = fβ nβ dβ nβ dβ /. fβ nβ dβ nβ dβ)
(f0 : β {nβ dβ nβ dβ} (dβ0 : dβ β 0) (dβ0 : dβ β 0), fβ nβ dβ nβ dβ β 0)
(a b c d : β€) (b0 : b β 0) (d0 : d β 0)
(H : β {nβ dβ nβ dβ} (hβ : a * dβ = nβ * b) (hβ : c * dβ = nβ * d),
fβ nβ dβ nβ dβ * fβ a b c d = fβ a b c d * fβ nβ dβ nβ dβ) :
f (a /. b) (c /. d) = fβ a b c d /. fβ a b c d :=
begin
generalize ha : a /. b = x, cases x with nβ dβ hβ cβ, rw num_denom' at ha,
generalize hc : c /. d = x, cases x with nβ dβ hβ cβ, rw num_denom' at hc,
rw fv,
have dβ0 := ne_of_gt (int.coe_nat_lt.2 hβ),
have dβ0 := ne_of_gt (int.coe_nat_lt.2 hβ),
exact (mk_eq (f0 dβ0 dβ0) (f0 b0 d0)).2 (H ((mk_eq b0 dβ0).1 ha) ((mk_eq d0 dβ0).1 hc))
end
@[simp] theorem add_def {a b c d : β€} (b0 : b β 0) (d0 : d β 0) :
a /. b + c /. d = (a * d + c * b) /. (b * d) :=
begin
apply lift_binop_eq rat.add; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero dβ0 dβ0 },
calc (nβ * dβ + nβ * dβ) * (b * d) =
(nβ * b) * dβ * d + (nβ * d) * (dβ * b) : by simp [mul_add, mul_comm, mul_left_comm]
... = (a * dβ) * dβ * d + (c * dβ) * (dβ * b) : by rw [hβ, hβ]
... = (a * d + c * b) * (dβ * dβ) : by simp [mul_add, mul_comm, mul_left_comm]
end
protected def neg : β β β
| β¨n, d, h, cβ© := β¨-n, d, h, by simp [c]β©
instance : has_neg β := β¨rat.negβ©
@[simp] theorem neg_def {a b : β€} : -(a /. b) = -a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with nβ dβ hβ cβ, rw num_denom' at ha,
show rat.mk' _ _ _ _ = _, rw num_denom',
have d0 := ne_of_gt (int.coe_nat_lt.2 hβ),
apply (mk_eq d0 b0).2, have hβ := (mk_eq b0 d0).1 ha,
simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg hβ]
end
protected def mul : β β β β β
| β¨nβ, dβ, hβ, cββ© β¨nβ, dβ, hβ, cββ© := mk_pnat (nβ * nβ) β¨dβ * dβ, mul_pos hβ hββ©
instance : has_mul β := β¨rat.mulβ©
@[simp] theorem mul_def {a b c d : β€} (b0 : b β 0) (d0 : d β 0) :
(a /. b) * (c /. d) = (a * c) /. (b * d) :=
begin
apply lift_binop_eq rat.mul; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero dβ0 dβ0 },
cc
end
protected def inv : β β β
| β¨(n+1:β), d, h, cβ© := β¨d, n+1, n.succ_pos, c.symmβ©
| β¨0, d, h, cβ© := 0
| β¨-[1+ n], d, h, cβ© := β¨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact cβ©
instance : has_inv β := β¨rat.invβ©
@[simp] theorem inv_def {a b : β€} : (a /. b)β»ΒΉ = b /. a :=
begin
by_cases a0 : a = 0, { subst a0, simp, refl },
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha,
refine eq.trans (_ : rat.inv β¨n, d, h, cβ© = d /. n) _,
{ cases n with n; [cases n with n, skip],
{ refl },
{ change int.of_nat n.succ with (n+1:β),
unfold rat.inv, rw num_denom' },
{ unfold rat.inv, rw num_denom', refl } },
have n0 : n β 0,
{ refine mt (Ξ» (n0 : n = 0), _) a0,
subst n0, simp at ha,
exact (mk_eq_zero b0).1 ha },
have d0 := ne_of_gt (int.coe_nat_lt.2 h),
have ha := (mk_eq b0 d0).1 ha,
apply (mk_eq n0 a0).2,
cc
end
variables (a b c : β)
protected theorem add_zero : a + 0 = a :=
num_denom_cases_on' a $ Ξ» n d h,
by rw [β zero_mk d]; simp [h, -zero_mk]
protected theorem zero_add : 0 + a = a :=
num_denom_cases_on' a $ Ξ» n d h,
by rw [β zero_mk d]; simp [h, -zero_mk]
protected theorem add_comm : a + b = b + a :=
num_denom_cases_on' a $ Ξ» nβ dβ hβ,
num_denom_cases_on' b $ Ξ» nβ dβ hβ,
by simp [hβ, hβ, mul_comm]
protected theorem add_assoc : a + b + c = a + (b + c) :=
num_denom_cases_on' a $ Ξ» nβ dβ hβ,
num_denom_cases_on' b $ Ξ» nβ dβ hβ,
num_denom_cases_on' c $ Ξ» nβ dβ hβ,
by simp [hβ, hβ, hβ, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm]
protected theorem add_left_neg : -a + a = 0 :=
num_denom_cases_on' a $ Ξ» n d h,
by simp [h]
protected theorem mul_one : a * 1 = a :=
num_denom_cases_on' a $ Ξ» n d h,
by change (1:β) with 1 /. 1; simp [h]
protected theorem one_mul : 1 * a = a :=
num_denom_cases_on' a $ Ξ» n d h,
by change (1:β) with 1 /. 1; simp [h]
protected theorem mul_comm : a * b = b * a :=
num_denom_cases_on' a $ Ξ» nβ dβ hβ,
num_denom_cases_on' b $ Ξ» nβ dβ hβ,
by simp [hβ, hβ, mul_comm]
protected theorem mul_assoc : a * b * c = a * (b * c) :=
num_denom_cases_on' a $ Ξ» nβ dβ hβ,
num_denom_cases_on' b $ Ξ» nβ dβ hβ,
num_denom_cases_on' c $ Ξ» nβ dβ hβ,
by simp [hβ, hβ, hβ, mul_ne_zero, mul_comm, mul_left_comm]
protected theorem add_mul : (a + b) * c = a * c + b * c :=
num_denom_cases_on' a $ Ξ» nβ dβ hβ,
num_denom_cases_on' b $ Ξ» nβ dβ hβ,
num_denom_cases_on' c $ Ξ» nβ dβ hβ,
by simp [hβ, hβ, hβ, mul_ne_zero];
refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 hβ)).symm.trans _;
simp [mul_add, mul_comm, mul_assoc, mul_left_comm]
protected theorem mul_add : a * (b + c) = a * b + a * c :=
by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a]
protected theorem zero_ne_one : 0 β (1:β) :=
mt (Ξ» (h : 0 = 1 /. 1), (mk_eq_zero one_ne_zero).1 h.symm) one_ne_zero
protected theorem mul_inv_cancel : a β 0 β a * aβ»ΒΉ = 1 :=
num_denom_cases_on' a $ Ξ» n d h a0,
have n0 : n β 0, from mt (by intro e; subst e; simp) a0,
by simp [h, n0, mul_comm]; exact
eq.trans (by simp) (@div_mk_div_cancel_left 1 1 _ n0)
protected theorem inv_mul_cancel (h : a β 0) : aβ»ΒΉ * a = 1 :=
eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h)
instance : decidable_eq β := by tactic.mk_dec_eq_instance
instance : discrete_field β :=
{ zero := 0,
add := rat.add,
neg := rat.neg,
one := 1,
mul := rat.mul,
inv := rat.inv,
zero_add := rat.zero_add,
add_zero := rat.add_zero,
add_comm := rat.add_comm,
add_assoc := rat.add_assoc,
add_left_neg := rat.add_left_neg,
mul_one := rat.mul_one,
one_mul := rat.one_mul,
mul_comm := rat.mul_comm,
mul_assoc := rat.mul_assoc,
left_distrib := rat.mul_add,
right_distrib := rat.add_mul,
zero_ne_one := rat.zero_ne_one,
mul_inv_cancel := rat.mul_inv_cancel,
inv_mul_cancel := rat.inv_mul_cancel,
has_decidable_eq := rat.decidable_eq,
inv_zero := rfl }
/- Extra instances to short-circuit type class resolution -/
instance : field β := by apply_instance
instance : division_ring β := by apply_instance
instance : integral_domain β := by apply_instance
-- TODO(Mario): this instance slows down data.real.basic
--instance : domain β := by apply_instance
instance : nonzero_comm_ring β := by apply_instance
instance : comm_ring β := by apply_instance
--instance : ring β := by apply_instance
instance : comm_semiring β := by apply_instance
instance : semiring β := by apply_instance
instance : add_comm_group β := by apply_instance
instance : add_group β := by apply_instance
instance : add_comm_monoid β := by apply_instance
instance : add_monoid β := by apply_instance
instance : add_left_cancel_semigroup β := by apply_instance
instance : add_right_cancel_semigroup β := by apply_instance
instance : add_comm_semigroup β := by apply_instance
instance : add_semigroup β := by apply_instance
instance : comm_monoid β := by apply_instance
instance : monoid β := by apply_instance
instance : comm_semigroup β := by apply_instance
instance : semigroup β := by apply_instance
theorem sub_def {a b c d : β€} (b0 : b β 0) (d0 : d β 0) :
a /. b - c /. d = (a * d - c * b) /. (b * d) :=
by simp [b0, d0]
protected def nonneg : β β Prop
| β¨n, d, h, cβ© := n β₯ 0
@[simp] theorem mk_nonneg (a : β€) {b : β€} (h : b > 0) : (a /. b).nonneg β a β₯ 0 :=
begin
generalize ha : a /. b = x, cases x with nβ dβ hβ cβ, rw num_denom' at ha,
simp [rat.nonneg],
have d0 := int.coe_nat_lt.2 hβ,
have := (mk_eq (ne_of_gt h) (ne_of_gt d0)).1 ha,
constructor; intro hβ,
{ apply nonneg_of_mul_nonneg_right _ d0,
rw this, exact mul_nonneg hβ (le_of_lt h) },
{ apply nonneg_of_mul_nonneg_right _ h,
rw β this, exact mul_nonneg hβ (int.coe_zero_le _) },
end
protected def nonneg_add {a b} : rat.nonneg a β rat.nonneg b β rat.nonneg (a + b) :=
num_denom_cases_on' a $ Ξ» nβ dβ hβ,
num_denom_cases_on' b $ Ξ» nβ dβ hβ,
begin
have dβ0 : (dβ:β€) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero hβ),
have dβ0 : (dβ:β€) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero hβ),
simp [dβ0, dβ0, hβ, hβ, mul_pos dβ0 dβ0],
intros nβ0 nβ0,
apply add_nonneg; apply mul_nonneg; {assumption <|> apply int.coe_zero_le}
end
protected def nonneg_mul {a b} : rat.nonneg a β rat.nonneg b β rat.nonneg (a * b) :=
num_denom_cases_on' a $ Ξ» nβ dβ hβ,
num_denom_cases_on' b $ Ξ» nβ dβ hβ,
begin
have dβ0 : (dβ:β€) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero hβ),
have dβ0 : (dβ:β€) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero hβ),
simp [dβ0, dβ0, hβ, hβ, mul_pos dβ0 dβ0],
exact mul_nonneg
end
protected def nonneg_antisymm {a} : rat.nonneg a β rat.nonneg (-a) β a = 0 :=
num_denom_cases_on' a $ Ξ» n d h,
begin
have d0 : (d:β€) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h),
simp [d0, h],
exact Ξ» hβ hβ, le_antisymm (nonpos_of_neg_nonneg hβ) hβ
end
protected def nonneg_total : rat.nonneg a β¨ rat.nonneg (-a) :=
by cases a with n; exact
or.imp_right neg_nonneg_of_nonpos (le_total 0 n)
instance decidable_nonneg : decidable (rat.nonneg a) :=
by cases a; unfold rat.nonneg; apply_instance
protected def le (a b : β) := rat.nonneg (b - a)
instance : has_le β := β¨rat.leβ©
instance decidable_le : decidable_rel ((β€) : β β β β Prop)
| a b := show decidable (rat.nonneg (b - a)), by apply_instance
protected theorem le_def {a b c d : β€} (b0 : b > 0) (d0 : d > 0) :
a /. b β€ c /. d β a * d β€ c * b :=
show rat.nonneg _ β _,
by simpa [ne_of_gt b0, ne_of_gt d0, mul_pos b0 d0, mul_comm]
using @sub_nonneg _ _ (b * c) (a * d)
protected theorem le_refl : a β€ a :=
show rat.nonneg (a - a), by rw sub_self; exact le_refl (0 : β€)
protected theorem le_total : a β€ b β¨ b β€ a :=
by have := rat.nonneg_total (b - a); rwa neg_sub at this
protected theorem le_antisymm {a b : β} (hab : a β€ b) (hba : b β€ a) : a = b :=
by have := eq_neg_of_add_eq_zero (rat.nonneg_antisymm hba $ by simpa);
rwa neg_neg at this
protected theorem le_trans {a b c : β} (hab : a β€ b) (hbc : b β€ c) : a β€ c :=
have rat.nonneg (b - a + (c - b)), from rat.nonneg_add hab hbc,
by simpa
instance : decidable_linear_order β :=
{ le := rat.le,
le_refl := rat.le_refl,
le_trans := @rat.le_trans,
le_antisymm := @rat.le_antisymm,
le_total := rat.le_total,
decidable_eq := by apply_instance,
decidable_le := assume a b, rat.decidable_nonneg (b - a) }
/- Extra instances to short-circuit type class resolution -/
instance : has_lt β := by apply_instance
instance : lattice.distrib_lattice β := by apply_instance
instance : lattice.lattice β := by apply_instance
instance : lattice.semilattice_inf β := by apply_instance
instance : lattice.semilattice_sup β := by apply_instance
instance : lattice.has_inf β := by apply_instance
instance : lattice.has_sup β := by apply_instance
instance : linear_order β := by apply_instance
instance : partial_order β := by apply_instance
instance : preorder β := by apply_instance
theorem nonneg_iff_zero_le {a} : rat.nonneg a β 0 β€ a :=
show rat.nonneg a β rat.nonneg (a - 0), by simp
theorem num_nonneg_iff_zero_le : β {a : β}, 0 β€ a.num β 0 β€ a
| β¨n, d, h, cβ© := @nonneg_iff_zero_le β¨n, d, h, cβ©
theorem mk_le {a b c d : β€} (hβ : b > 0) (hβ : d > 0) :
a /. b β€ c /. d β a * d β€ c * b :=
by conv in (_ β€ _) {
simp only [(β€), rat.le],
rw [sub_def (ne_of_gt hβ) (ne_of_gt hβ),
mk_nonneg _ (mul_pos hβ hβ), ge, sub_nonneg] }
protected theorem add_le_add_left {a b c : β} : c + a β€ c + b β a β€ b :=
by unfold has_le.le rat.le; rw add_sub_add_left_eq_sub
protected theorem mul_nonneg {a b : β} (ha : 0 β€ a) (hb : 0 β€ b) : 0 β€ a * b :=
by rw β nonneg_iff_zero_le at ha hb β’; exact rat.nonneg_mul ha hb
instance : discrete_linear_ordered_field β :=
{ zero_lt_one := dec_trivial,
add_le_add_left := assume a b ab c, rat.add_le_add_left.2 ab,
add_lt_add_left := assume a b ab c, lt_of_not_ge $ Ξ» ba,
not_le_of_lt ab $ rat.add_le_add_left.1 ba,
mul_nonneg := @rat.mul_nonneg,
mul_pos := assume a b ha hb, lt_of_le_of_ne
(rat.mul_nonneg (le_of_lt ha) (le_of_lt hb))
(mul_ne_zero (ne_of_lt ha).symm (ne_of_lt hb).symm).symm,
..rat.discrete_field, ..rat.decidable_linear_order }
/- Extra instances to short-circuit type class resolution -/
instance : linear_ordered_field β := by apply_instance
instance : decidable_linear_ordered_comm_ring β := by apply_instance
instance : linear_ordered_comm_ring β := by apply_instance
instance : linear_ordered_ring β := by apply_instance
instance : ordered_ring β := by apply_instance
instance : decidable_linear_ordered_semiring β := by apply_instance
instance : linear_ordered_semiring β := by apply_instance
instance : ordered_semiring β := by apply_instance
instance : decidable_linear_ordered_comm_group β := by apply_instance
instance : ordered_comm_group β := by apply_instance
instance : ordered_cancel_comm_monoid β := by apply_instance
instance : ordered_comm_monoid β := by apply_instance
attribute [irreducible] rat.le
theorem num_pos_iff_pos {a : β} : 0 < a.num β 0 < a :=
lt_iff_lt_of_le_iff_le $
by simpa [(by cases a; refl : (-a).num = -a.num)]
using @num_nonneg_iff_zero_le (-a)
theorem of_int_eq_mk (z : β€) : of_int z = z /. 1 := num_denom' _ _ _ _
theorem coe_int_eq_mk : β z : β€, βz = z /. 1
| (n : β) := show (n:β) = n /. 1,
by induction n with n IH n; simp [*, show (1:β) = 1 /. 1, from rfl]
| -[1+ n] := show (-(n + 1) : β) = -[1+ n] /. 1, begin
induction n with n IH, {refl},
show -(n + 1 + 1 : β) = -[1+ n.succ] /. 1,
rw [neg_add, IH],
simpa [show -1 = (-1) /. 1, from rfl]
end
theorem coe_int_eq_of_int (z : β€) : βz = of_int z :=
(coe_int_eq_mk z).trans (of_int_eq_mk z).symm
theorem mk_eq_div (n d : β€) : n /. d = (n / d : β) :=
begin
by_cases d0 : d = 0, {simp [d0, div_zero]},
rw [division_def, coe_int_eq_mk, coe_int_eq_mk, inv_def,
mul_def one_ne_zero d0, one_mul, mul_one]
end
/-- `floor q` is the largest integer `z` such that `z β€ q` -/
def floor : β β β€
| β¨n, d, h, cβ© := n / d
theorem le_floor {z : β€} : β {r : β}, z β€ floor r β (z : β) β€ r
| β¨n, d, h, cβ© := begin
simp [floor],
rw [num_denom'],
have h' := int.coe_nat_lt.2 h,
conv { to_rhs,
rw [coe_int_eq_mk, mk_le zero_lt_one h', mul_one] },
exact int.le_div_iff_mul_le h'
end
theorem floor_lt {r : β} {z : β€} : floor r < z β r < z :=
lt_iff_lt_of_le_iff_le le_floor
theorem floor_le (r : β) : (floor r : β) β€ r :=
le_floor.1 (le_refl _)
theorem lt_succ_floor (r : β) : r < (floor r).succ :=
floor_lt.1 $ int.lt_succ_self _
@[simp] theorem floor_coe (z : β€) : floor z = z :=
eq_of_forall_le_iff $ Ξ» a, by rw [le_floor, int.cast_le]
theorem floor_mono {a b : β} (h : a β€ b) : floor a β€ floor b :=
le_floor.2 (le_trans (floor_le _) h)
@[simp] theorem floor_add_int (r : β) (z : β€) : floor (r + z) = floor r + z :=
eq_of_forall_le_iff $ Ξ» a, by rw [le_floor,
β sub_le_iff_le_add, β sub_le_iff_le_add, le_floor, int.cast_sub]
theorem floor_sub_int (r : β) (z : β€) : floor (r - z) = floor r - z :=
eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _)
/-- `ceil q` is the smallest integer `z` such that `q β€ z` -/
def ceil (r : β) : β€ :=
-(floor (-r))
theorem ceil_le {z : β€} {r : β} : ceil r β€ z β r β€ z :=
by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff]
theorem le_ceil (r : β) : r β€ ceil r :=
ceil_le.1 (le_refl _)
@[simp] theorem ceil_coe (z : β€) : ceil z = z :=
by rw [ceil, β int.cast_neg, floor_coe, neg_neg]
theorem ceil_mono {a b : β} (h : a β€ b) : ceil a β€ ceil b :=
ceil_le.2 (le_trans h (le_ceil _))
@[simp] theorem ceil_add_int (r : β) (z : β€) : ceil (r + z) = ceil r + z :=
by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl
theorem ceil_sub_int (r : β) (z : β€) : ceil (r - z) = ceil r - z :=
eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _)
/- cast (injection into fields) -/
section cast
variables {Ξ± : Type*}
section
variables [division_ring Ξ±]
/-- Construct the canonical injection from `β` into an arbitrary
division ring. If the field has positive characteristic `p`,
we define `1 / p = 1 / 0 = 0` for consistency with our
division by zero convention. -/
protected def cast : β β Ξ±
| β¨n, d, h, cβ© := n / d
@[priority 0] instance cast_coe : has_coe β Ξ± := β¨rat.castβ©
@[simp] theorem cast_of_int (n : β€) : (of_int n : Ξ±) = n :=
show (n / (1:β) : Ξ±) = n, by rw [nat.cast_one, div_one]
@[simp, squash_cast] theorem cast_coe_int (n : β€) : ((n : β) : Ξ±) = n :=
by rw [coe_int_eq_of_int, cast_of_int]
@[simp, elim_cast] theorem coe_int_num (n : β€) : (n : β).num = n :=
by rw coe_int_eq_of_int; refl
@[simp, elim_cast] theorem coe_int_denom (n : β€) : (n : β).denom = 1 :=
by rw coe_int_eq_of_int; refl
@[simp, elim_cast] theorem coe_nat_num (n : β) : (n : β).num = n :=
by rw [β int.cast_coe_nat, coe_int_num]
@[simp, elim_cast] theorem coe_nat_denom (n : β) : (n : β).denom = 1 :=
by rw [β int.cast_coe_nat, coe_int_denom]
@[simp, squash_cast] theorem cast_coe_nat (n : β) : ((n : β) : Ξ±) = n := cast_coe_int n
@[simp, squash_cast] theorem cast_zero : ((0 : β) : Ξ±) = 0 :=
(cast_of_int _).trans int.cast_zero
@[simp, squash_cast] theorem cast_one : ((1 : β) : Ξ±) = 1 :=
(cast_of_int _).trans int.cast_one
theorem mul_cast_comm (a : Ξ±) :
β (n : β), (n.denom : Ξ±) β 0 β a * n = n * a
| β¨n, d, h, cβ© hβ := show a * (n * dβ»ΒΉ) = n * dβ»ΒΉ * a,
by rw [β mul_assoc, int.mul_cast_comm, mul_assoc, mul_assoc,
β show (d:Ξ±)β»ΒΉ * a = a * dβ»ΒΉ, from
division_ring.inv_comm_of_comm hβ (int.mul_cast_comm a d).symm]
@[move_cast] theorem cast_mk_of_ne_zero (a b : β€)
(b0 : (b:Ξ±) β 0) : (a /. b : Ξ±) = a / b :=
begin
have b0' : b β 0, { refine mt _ b0, simp {contextual := tt} },
cases e : a /. b with n d h c,
have d0 : (d:Ξ±) β 0,
{ intro d0,
have dd := denom_dvd a b,
cases (show (d:β€) β£ b, by rwa e at dd) with k ke,
have : (b:Ξ±) = (d:Ξ±) * (k:Ξ±), {rw [ke, int.cast_mul], refl},
rw [d0, zero_mul] at this, contradiction },
rw [num_denom'] at e,
have := congr_arg (coe : β€ β Ξ±) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e),
rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this,
symmetry, change (a * bβ»ΒΉ : Ξ±) = n / d,
rw [eq_div_iff_mul_eq _ _ d0, mul_assoc, nat.mul_cast_comm,
β mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one]
end
@[move_cast] theorem cast_add_of_ne_zero : β {m n : β},
(m.denom : Ξ±) β 0 β (n.denom : Ξ±) β 0 β ((m + n : β) : Ξ±) = m + n
| β¨nβ, dβ, hβ, cββ© β¨nβ, dβ, hβ, cββ© := Ξ» (dβ0 : (dβ:Ξ±) β 0) (dβ0 : (dβ:Ξ±) β 0), begin
have dβ0' : (dβ:β€) β 0 := int.coe_nat_ne_zero.2 (Ξ» e, by rw e at dβ0; exact dβ0 rfl),
have dβ0' : (dβ:β€) β 0 := int.coe_nat_ne_zero.2 (Ξ» e, by rw e at dβ0; exact dβ0 rfl),
rw [num_denom', num_denom', add_def dβ0' dβ0'],
suffices : (nβ * (dβ * (dββ»ΒΉ * dββ»ΒΉ)) +
nβ * (dβ * dββ»ΒΉ) * dββ»ΒΉ : Ξ±) = nβ * dββ»ΒΉ + nβ * dββ»ΒΉ,
{ rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero],
{ simpa [division_def, left_distrib, right_distrib, mul_inv_eq,
dβ0, dβ0, division_ring.mul_ne_zero dβ0 dβ0, mul_assoc] },
all_goals {simp [dβ0, dβ0, division_ring.mul_ne_zero dβ0 dβ0]} },
rw [β mul_assoc (dβ:Ξ±), mul_inv_cancel dβ0, one_mul,
β nat.mul_cast_comm], simp [dβ0, mul_assoc]
end
@[simp, move_cast] theorem cast_neg : β n, ((-n : β) : Ξ±) = -n
| β¨n, d, h, cβ© := show (β-n * dβ»ΒΉ : Ξ±) = -(n * dβ»ΒΉ),
by rw [int.cast_neg, neg_mul_eq_neg_mul]
@[move_cast] theorem cast_sub_of_ne_zero {m n : β}
(m0 : (m.denom : Ξ±) β 0) (n0 : (n.denom : Ξ±) β 0) : ((m - n : β) : Ξ±) = m - n :=
have ((-n).denom : Ξ±) β 0, by cases n; exact n0,
by simp [m0, this, cast_add_of_ne_zero]
@[move_cast] theorem cast_mul_of_ne_zero : β {m n : β},
(m.denom : Ξ±) β 0 β (n.denom : Ξ±) β 0 β ((m * n : β) : Ξ±) = m * n
| β¨nβ, dβ, hβ, cββ© β¨nβ, dβ, hβ, cββ© := Ξ» (dβ0 : (dβ:Ξ±) β 0) (dβ0 : (dβ:Ξ±) β 0), begin
have dβ0' : (dβ:β€) β 0 := int.coe_nat_ne_zero.2 (Ξ» e, by rw e at dβ0; exact dβ0 rfl),
have dβ0' : (dβ:β€) β 0 := int.coe_nat_ne_zero.2 (Ξ» e, by rw e at dβ0; exact dβ0 rfl),
rw [num_denom', num_denom', mul_def dβ0' dβ0'],
suffices : (nβ * ((nβ * dββ»ΒΉ) * dββ»ΒΉ) : Ξ±) = nβ * (dββ»ΒΉ * (nβ * dββ»ΒΉ)),
{ rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero],
{ simpa [division_def, mul_inv_eq, dβ0, dβ0, division_ring.mul_ne_zero dβ0 dβ0, mul_assoc] },
all_goals {simp [dβ0, dβ0, division_ring.mul_ne_zero dβ0 dβ0]} },
rw [division_ring.inv_comm_of_comm dβ0 (nat.mul_cast_comm _ _).symm]
end
@[move_cast] theorem cast_inv_of_ne_zero : β {n : β},
(n.num : Ξ±) β 0 β (n.denom : Ξ±) β 0 β ((nβ»ΒΉ : β) : Ξ±) = nβ»ΒΉ
| β¨n, d, h, cβ© := Ξ» (n0 : (n:Ξ±) β 0) (d0 : (d:Ξ±) β 0), begin
have n0' : (n:β€) β 0 := Ξ» e, by rw e at n0; exact n0 rfl,
have d0' : (d:β€) β 0 := int.coe_nat_ne_zero.2 (Ξ» e, by rw e at d0; exact d0 rfl),
rw [num_denom', inv_def],
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div];
simp [n0, d0]
end
@[move_cast] theorem cast_div_of_ne_zero {m n : β} (md : (m.denom : Ξ±) β 0)
(nn : (n.num : Ξ±) β 0) (nd : (n.denom : Ξ±) β 0) : ((m / n : β) : Ξ±) = m / n :=
have (nβ»ΒΉ.denom : β€) β£ n.num,
by conv in nβ»ΒΉ.denom { rw [num_denom n, inv_def] };
apply denom_dvd,
have (nβ»ΒΉ.denom : Ξ±) = 0 β (n.num : Ξ±) = 0, from
Ξ» h, let β¨k, eβ© := this in
by have := congr_arg (coe : β€ β Ξ±) e;
rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this,
by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def]
@[simp, elim_cast] theorem cast_inj [char_zero Ξ±] : β {m n : β}, (m : Ξ±) = n β m = n
| β¨nβ, dβ, hβ, cββ© β¨nβ, dβ, hβ, cββ© := begin
refine β¨Ξ» h, _, congr_arg _β©,
have dβ0 : dβ β 0 := ne_of_gt hβ,
have dβ0 : dβ β 0 := ne_of_gt hβ,
have dβa : (dβ:Ξ±) β 0 := nat.cast_ne_zero.2 dβ0,
have dβa : (dβ:Ξ±) β 0 := nat.cast_ne_zero.2 dβ0,
rw [num_denom', num_denom'] at h β’,
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [dβ0, dβ0] at h β’,
rwa [eq_div_iff_mul_eq _ _ dβa, division_def, mul_assoc,
division_ring.inv_comm_of_comm dβa (nat.mul_cast_comm _ _),
β mul_assoc, β division_def, eq_comm, eq_div_iff_mul_eq _ _ dβa, eq_comm,
β int.cast_coe_nat, β int.cast_mul, β int.cast_coe_nat, β int.cast_mul,
int.cast_inj, β mk_eq (int.coe_nat_ne_zero.2 dβ0) (int.coe_nat_ne_zero.2 dβ0)] at h
end
theorem cast_injective [char_zero Ξ±] : function.injective (coe : β β Ξ±)
| m n := cast_inj.1
@[simp] theorem cast_eq_zero [char_zero Ξ±] {n : β} : (n : Ξ±) = 0 β n = 0 :=
by rw [β cast_zero, cast_inj]
@[simp] theorem cast_ne_zero [char_zero Ξ±] {n : β} : (n : Ξ±) β 0 β n β 0 :=
not_congr cast_eq_zero
theorem eq_cast_of_ne_zero (f : β β Ξ±) (H1 : f 1 = 1)
(Hadd : β x y, f (x + y) = f x + f y)
(Hmul : β x y, f (x * y) = f x * f y) :
β n : β, (n.denom : Ξ±) β 0 β f n = n
| β¨n, d, h, cβ© := Ξ» (hβ : ((d:β€):Ξ±) β 0), show _ = (n / (d:β€) : Ξ±), begin
rw [num_denom', mk_eq_div, eq_div_iff_mul_eq _ _ hβ],
have : β n : β€, f n = n, { apply int.eq_cast; simp [H1, Hadd] },
rw [β this, β this, β Hmul, div_mul_cancel],
exact int.cast_ne_zero.2 (int.coe_nat_ne_zero.2 $ ne_of_gt h),
end
theorem eq_cast [char_zero Ξ±] (f : β β Ξ±) (H1 : f 1 = 1)
(Hadd : β x y, f (x + y) = f x + f y)
(Hmul : β x y, f (x * y) = f x * f y) (n : β) : f n = n :=
eq_cast_of_ne_zero _ H1 Hadd Hmul _ $
nat.cast_ne_zero.2 $ ne_of_gt n.pos
end
@[move_cast] theorem cast_mk [discrete_field Ξ±] [char_zero Ξ±] (a b : β€) : ((a /. b) : Ξ±) = a / b :=
if b0 : b = 0 then by simp [b0, div_zero]
else cast_mk_of_ne_zero a b (int.cast_ne_zero.2 b0)
@[simp, move_cast] theorem cast_add [division_ring Ξ±] [char_zero Ξ±] (m n) : ((m + n : β) : Ξ±) = m + n :=
cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp, move_cast] theorem cast_sub [division_ring Ξ±] [char_zero Ξ±] (m n) : ((m - n : β) : Ξ±) = m - n :=
cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp, move_cast] theorem cast_mul [division_ring Ξ±] [char_zero Ξ±] (m n) : ((m * n : β) : Ξ±) = m * n :=
cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp, move_cast] theorem cast_inv [discrete_field Ξ±] [char_zero Ξ±] (n) : ((nβ»ΒΉ : β) : Ξ±) = nβ»ΒΉ :=
if n0 : n.num = 0 then
by simp [show n = 0, by rw [num_denom n, n0]; simp, inv_zero] else
cast_inv_of_ne_zero (int.cast_ne_zero.2 n0) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp, move_cast] theorem cast_div [discrete_field Ξ±] [char_zero Ξ±] (m n) : ((m / n : β) : Ξ±) = m / n :=
by rw [division_def, cast_mul, cast_inv, division_def]
@[simp, move_cast] theorem cast_pow [discrete_field Ξ±] [char_zero Ξ±] (q) (k : β) : ((q ^ k : β) : Ξ±) = q ^ k :=
by induction k; simp only [*, cast_one, cast_mul, pow_zero, pow_succ]
@[simp, squash_cast, move_cast] theorem cast_bit0 [division_ring Ξ±] [char_zero Ξ±] (n : β) : ((bit0 n : β) : Ξ±) = bit0 n := cast_add _ _
@[simp, squash_cast, move_cast] theorem cast_bit1 [division_ring Ξ±] [char_zero Ξ±] (n : β) : ((bit1 n : β) : Ξ±) = bit1 n :=
by rw [bit1, cast_add, cast_one, cast_bit0]; refl
@[simp] theorem cast_nonneg [linear_ordered_field Ξ±] : β {n : β}, 0 β€ (n : Ξ±) β 0 β€ n
| β¨n, d, h, cβ© := show 0 β€ (n * dβ»ΒΉ : Ξ±) β 0 β€ (β¨n, d, h, cβ© : β),
by rw [num_denom', β nonneg_iff_zero_le, mk_nonneg _ (int.coe_nat_pos.2 h),
mul_nonneg_iff_right_nonneg_of_pos (@inv_pos Ξ± _ _ (nat.cast_pos.2 h)),
int.cast_nonneg]
@[simp, elim_cast] theorem cast_le [linear_ordered_field Ξ±] {m n : β} : (m : Ξ±) β€ n β m β€ n :=
by rw [β sub_nonneg, β cast_sub, cast_nonneg, sub_nonneg]
@[simp, elim_cast] theorem cast_lt [linear_ordered_field Ξ±] {m n : β} : (m : Ξ±) < n β m < n :=
by simpa [-cast_le] using not_congr (@cast_le Ξ± _ n m)
@[simp] theorem cast_nonpos [linear_ordered_field Ξ±] {n : β} : (n : Ξ±) β€ 0 β n β€ 0 :=
by rw [β cast_zero, cast_le]
@[simp] theorem cast_pos [linear_ordered_field Ξ±] {n : β} : (0 : Ξ±) < n β 0 < n :=
by rw [β cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [linear_ordered_field Ξ±] {n : β} : (n : Ξ±) < 0 β n < 0 :=
by rw [β cast_zero, cast_lt]
@[simp, squash_cast] theorem cast_id : β n : β, βn = n
| β¨n, d, h, cβ© := show (n / (d : β€) : β) = _, by rw [num_denom', mk_eq_div]
@[simp, move_cast] theorem cast_min [discrete_linear_ordered_field Ξ±] {a b : β} : (β(min a b) : Ξ±) = min a b :=
by by_cases a β€ b; simp [h, min]
@[simp, move_cast] theorem cast_max [discrete_linear_ordered_field Ξ±] {a b : β} : (β(max a b) : Ξ±) = max a b :=
by by_cases a β€ b; simp [h, max]
@[simp, move_cast] theorem cast_abs [discrete_linear_ordered_field Ξ±] {q : β} : ((abs q : β) : Ξ±) = abs q :=
by simp [abs]
end cast
/- nat ceiling -/
/-- `nat_ceil q` is the smallest nonnegative integer `n` with `q β€ n`.
It is the same as `ceil q` when `q β₯ 0`, otherwise it is `0`. -/
def nat_ceil (q : β) : β := int.to_nat (ceil q)
theorem nat_ceil_le {q : β} {n : β} : nat_ceil q β€ n β q β€ n :=
by rw [nat_ceil, int.to_nat_le, ceil_le]; refl
theorem lt_nat_ceil {q : β} {n : β} : n < nat_ceil q β (n : β) < q :=
not_iff_not.1 $ by rw [not_lt, not_lt, nat_ceil_le]
theorem le_nat_ceil (q : β) : q β€ nat_ceil q :=
nat_ceil_le.1 (le_refl _)
theorem nat_ceil_mono {qβ qβ : β} (h : qβ β€ qβ) : nat_ceil qβ β€ nat_ceil qβ :=
nat_ceil_le.2 (le_trans h (le_nat_ceil _))
@[simp] theorem nat_ceil_coe (n : β) : nat_ceil n = n :=
show (ceil (n:β€)).to_nat = n, by rw [ceil_coe]; refl
@[simp] theorem nat_ceil_zero : nat_ceil 0 = 0 := nat_ceil_coe 0
theorem nat_ceil_add_nat {q : β} (hq : 0 β€ q) (n : β) : nat_ceil (q + n) = nat_ceil q + n :=
show int.to_nat (ceil (q + (n:β€))) = int.to_nat (ceil q) + n,
by rw [ceil_add_int]; exact
match ceil q, int.eq_coe_of_zero_le (ceil_mono hq) with
| _, β¨m, rflβ© := rfl
end
theorem nat_ceil_lt_add_one {q : β} (hq : q β₯ 0) : β(nat_ceil q) < q + 1 :=
lt_nat_ceil.1 $ by rw [
show nat_ceil (q+1) = nat_ceil q+1, from nat_ceil_add_nat hq 1]; apply nat.lt_succ_self
@[simp] lemma denom_neg_eq_denom : β q : β, (-q).denom = q.denom
| β¨_, d, _, _β© := rfl
@[simp] lemma num_neg_eq_neg_num : β q : β, (-q).num = -(q.num)
| β¨n, _, _, _β© := rfl
@[simp] lemma num_zero : rat.num 0 = 0 := rfl
lemma zero_of_num_zero {q : β} (hq : q.num = 0) : q = 0 :=
have q = q.num /. q.denom, from num_denom _,
by simpa [hq]
lemma zero_iff_num_zero {q : β} : q = 0 β q.num = 0 :=
β¨Ξ» _, by simp *, zero_of_num_zeroβ©
lemma num_ne_zero_of_ne_zero {q : β} (h : q β 0) : q.num β 0 :=
assume : q.num = 0,
h $ zero_of_num_zero this
@[simp] lemma num_one : (1 : β).num = 1 := rfl
@[simp] lemma denom_one : (1 : β).denom = 1 := rfl
lemma denom_ne_zero (q : β) : q.denom β 0 :=
ne_of_gt q.pos
lemma mk_num_ne_zero_of_ne_zero {q : β} {n d : β€} (hq : q β 0) (hqnd : q = n /. d) : n β 0 :=
assume : n = 0,
hq $ by simpa [this] using hqnd
lemma mk_denom_ne_zero_of_ne_zero {q : β} {n d : β€} (hq : q β 0) (hqnd : q = n /. d) : d β 0 :=
assume : d = 0,
hq $ by simpa [this] using hqnd
lemma mk_ne_zero_of_ne_zero {n d : β€} (h : n β 0) (hd : d β 0) : n /. d β 0 :=
assume : n /. d = 0,
h $ (mk_eq_zero hd).1 this
lemma mul_num_denom (q r : β) : q * r = (q.num * r.num) /. β(q.denom * r.denom) :=
have hq' : (βq.denom : β€) β 0, by have := denom_ne_zero q; simpa,
have hr' : (βr.denom : β€) β 0, by have := denom_ne_zero r; simpa,
suffices (q.num /. βq.denom) * (r.num /. βr.denom) = (q.num * r.num) /. β(q.denom * r.denom),
by rwa [βnum_denom q, βnum_denom r] at this,
by simp [mul_def hq' hr']
lemma div_num_denom (q r : β) : q / r = (q.num * r.denom) /. (q.denom * r.num) :=
if hr : r.num = 0 then
have hr' : r = 0, from zero_of_num_zero hr,
by simp *
else calc q / r = q * rβ»ΒΉ : div_eq_mul_inv
... = (q.num /. q.denom) * (r.num /. r.denom)β»ΒΉ : by rw [βnum_denom q, βnum_denom r]
... = (q.num /. q.denom) * (r.denom /. r.num) : by rw inv_def
... = (q.num * r.denom) /. (q.denom * r.num) : mul_def (by simpa using denom_ne_zero q) hr
lemma num_denom_mk {q : β} {n d : β€} (hn : n β 0) (hd : d β 0) (qdf : q = n /. d) :
β c : β€, n = c * q.num β§ d = c * q.denom :=
have hq : q β 0, from
assume : q = 0,
hn $ (rat.mk_eq_zero hd).1 (by cc),
have q.num /. q.denom = n /. d, by rwa [βrat.num_denom q],
have q.num * d = n * β(q.denom), from (rat.mk_eq (by simp [rat.denom_ne_zero]) hd).1 this,
begin
existsi n / q.num,
have hqdn : q.num β£ n, begin rw qdf, apply rat.num_dvd, assumption end,
split,
{ rw int.div_mul_cancel hqdn },
{ apply int.eq_mul_div_of_mul_eq_mul_of_dvd_left,
{apply rat.num_ne_zero_of_ne_zero hq},
{simp [rat.denom_ne_zero]},
repeat {assumption} }
end
theorem mk_pnat_num (n : β€) (d : β+) :
(mk_pnat n d).num = n / nat.gcd n.nat_abs d :=
by cases d; refl
theorem mk_pnat_denom (n : β€) (d : β+) :
(mk_pnat n d).denom = d / nat.gcd n.nat_abs d :=
by cases d; refl
theorem mul_num (qβ qβ : β) : (qβ * qβ).num =
(qβ.num * qβ.num) / nat.gcd (qβ.num * qβ.num).nat_abs (qβ.denom * qβ.denom) :=
by cases qβ; cases qβ; refl
theorem mul_denom (qβ qβ : β) : (qβ * qβ).denom =
(qβ.denom * qβ.denom) / nat.gcd (qβ.num * qβ.num).nat_abs (qβ.denom * qβ.denom) :=
by cases qβ; cases qβ; refl
theorem mul_self_num (q : β) : (q * q).num = q.num * q.num :=
by rw [mul_num, int.nat_abs_mul, nat.coprime.gcd_eq_one, int.coe_nat_one, int.div_one];
exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop)
theorem mul_self_denom (q : β) : (q * q).denom = q.denom * q.denom :=
by rw [rat.mul_denom, int.nat_abs_mul, nat.coprime.gcd_eq_one, nat.div_one];
exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop)
theorem abs_def (q : β) : abs q = q.num.nat_abs /. q.denom :=
begin
have hz : (0:β) = 0 /. 1 := rfl,
cases le_total q 0 with hq hq,
{ rw [abs_of_nonpos hq],
rw [num_denom q, hz, rat.le_def (int.coe_nat_pos.2 q.pos) zero_lt_one,
mul_one, zero_mul] at hq,
rw [int.of_nat_nat_abs_of_nonpos hq, β neg_def, β num_denom q] },
{ rw [abs_of_nonneg hq],
rw [num_denom q, hz, rat.le_def zero_lt_one (int.coe_nat_pos.2 q.pos),
mul_one, zero_mul] at hq,
rw [int.nat_abs_of_nonneg hq, β num_denom q] }
end
lemma add_num_denom (q r : β) : q + r =
((q.num * r.denom + q.denom * r.num : β€)) /. (βq.denom * βr.denom : β€) :=
have hqd : (q.denom : β€) β 0, from int.coe_nat_ne_zero_iff_pos.2 q.3,
have hrd : (r.denom : β€) β 0, from int.coe_nat_ne_zero_iff_pos.2 r.3,
by conv { to_lhs, rw [rat.num_denom q, rat.num_denom r, rat.add_def hqd hrd] };
simp [mul_comm]
def sqrt (q : β) : β :=
rat.mk (int.sqrt q.num) (nat.sqrt q.denom)
theorem sqrt_eq (q : β) : rat.sqrt (q*q) = abs q :=
by rw [sqrt, mul_self_num, mul_self_denom,
int.sqrt_eq, nat.sqrt_eq, abs_def]
theorem exists_mul_self (x : β) :
(β q, q * q = x) β rat.sqrt x * rat.sqrt x = x :=
β¨Ξ» β¨n, hnβ©, by rw [β hn, sqrt_eq, abs_mul_abs_self],
Ξ» h, β¨rat.sqrt x, hβ©β©
theorem sqrt_nonneg (q : β) : 0 β€ rat.sqrt q :=
nonneg_iff_zero_le.1 $ (mk_nonneg _ $ int.coe_nat_pos.2 $
nat.pos_of_ne_zero $ Ξ» H, nat.pos_iff_ne_zero.1 q.pos $ nat.sqrt_eq_zero.1 H).2 trivial
end rat
|
8102114fcf890a1f55c8f81c1fc9b410ab1a4d15 | 1a61aba1b67cddccce19532a9596efe44be4285f | /hott/types/pi.hlean | 2d08232e0daaba8c92308ae23877ce34edff9eaf | [
"Apache-2.0"
] | permissive | eigengrau/lean | 07986a0f2548688c13ba36231f6cdbee82abf4c6 | f8a773be1112015e2d232661ce616d23f12874d0 | refs/heads/master | 1,610,939,198,566 | 1,441,352,386,000 | 1,441,352,494,000 | 41,903,576 | 0 | 0 | null | 1,441,352,210,000 | 1,441,352,210,000 | null | UTF-8 | Lean | false | false | 9,146 | hlean | /-
Copyright (c) 2014-15 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Partially ported from Coq HoTT
Theorems about pi-types (dependent function spaces)
-/
import types.sigma arity
open eq equiv is_equiv funext sigma
namespace pi
variables {A A' : Type} {B : A β Type} {B' : A' β Type} {C : Ξ a, B a β Type}
{D : Ξ a b, C a b β Type}
{a a' a'' : A} {b bβ bβ : B a} {b' : B a'} {b'' : B a''} {f g : Ξ a, B a}
/- Paths -/
/-
Paths [p : f β g] in a function type [Ξ x:X, P x] are equivalent to functions taking values
in path types, [H : Ξ x:X, f x β g x], or concisely, [H : f ~ g].
This equivalence, however, is just the combination of [apd10] and function extensionality
[funext], and as such, [eq_of_homotopy]
Now we show how these things compute.
-/
definition apd10_eq_of_homotopy (h : f ~ g) : apd10 (eq_of_homotopy h) ~ h :=
apd10 (right_inv apd10 h)
definition eq_of_homotopy_eta (p : f = g) : eq_of_homotopy (apd10 p) = p :=
left_inv apd10 p
definition eq_of_homotopy_idp (f : Ξ a, B a) : eq_of_homotopy (Ξ»x : A, refl (f x)) = refl f :=
!eq_of_homotopy_eta
/-
The identification of the path space of a dependent function space,
up to equivalence, is of course just funext.
-/
definition eq_equiv_homotopy (f g : Ξ x, B x) : (f = g) β (f ~ g) :=
equiv.mk apd10 _
definition pi_eq_equiv (f g : Ξ x, B x) : (f = g) β (f ~ g) := !eq_equiv_homotopy
definition is_equiv_eq_of_homotopy (f g : Ξ x, B x)
: is_equiv (eq_of_homotopy : f ~ g β f = g) :=
_
definition homotopy_equiv_eq (f g : Ξ x, B x) : (f ~ g) β (f = g) :=
equiv.mk eq_of_homotopy _
/- Transport -/
definition pi_transport (p : a = a') (f : Ξ (b : B a), C a b)
: (transport (Ξ»a, Ξ (b : B a), C a b) p f) ~ (Ξ»b, !tr_inv_tr βΈ (p βΈD (f (pβ»ΒΉ βΈ b)))) :=
by induction p; reflexivity
/- A special case of [transport_pi] where the type [B] does not depend on [A],
and so it is just a fixed type [B]. -/
definition pi_transport_constant {C : A β A' β Type} (p : a = a') (f : Ξ (b : A'), C a b) (b : A')
: (transport _ p f) b = p βΈ (f b) :=
by induction p; reflexivity
/- Pathovers -/
definition pi_pathover {f : Ξ b, C a b} {g : Ξ b', C a' b'} {p : a = a'}
(r : Ξ (b : B a) (b' : B a') (q : b =[p] b'), f b =[apo011 C p q] g b') : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply eq_of_pathover_idp, apply r
end
-- a version where C is uncurried, but where the conclusion of r is still a proper pathover
-- instead of a heterogenous equality
definition pi_pathover' {C : (Ξ£a, B a) β Type} {f : Ξ b, C β¨a, bβ©} {g : Ξ b', C β¨a', b'β©}
{p : a = a'} (r : Ξ (b : B a) (b' : B a') (q : b =[p] b'), f b =[dpair_eq_dpair p q] g b')
: f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply (@eq_of_pathover_idp _ C), exact (r b b (pathover.idpatho b)),
end
definition pi_pathover_left {f : Ξ b, C a b} {g : Ξ b', C a' b'} {p : a = a'}
(r : Ξ (b : B a), f b =[apo011 C p !pathover_tr] g (p βΈ b)) : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply eq_of_pathover_idp, apply r
end
definition pi_pathover_right {f : Ξ b, C a b} {g : Ξ b', C a' b'} {p : a = a'}
(r : Ξ (b' : B a'), f (pβ»ΒΉ βΈ b') =[apo011 C p !tr_pathover] g b') : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply eq_of_pathover_idp, apply r
end
definition pi_pathover_constant {C : A β A' β Type} {f : Ξ (b : A'), C a b}
{g : Ξ (b : A'), C a' b} {p : a = a'}
(r : Ξ (b : A'), f b =[p] g b) : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
exact eq_of_pathover_idp (r b),
end
/- Maps on paths -/
/- The action of maps given by lambda. -/
definition ap_lambdaD {C : A' β Type} (p : a = a') (f : Ξ a b, C b) :
ap (Ξ»a b, f a b) p = eq_of_homotopy (Ξ»b, ap (Ξ»a, f a b) p) :=
begin
apply (eq.rec_on p),
apply inverse,
apply eq_of_homotopy_idp
end
/- Dependent paths -/
/- with more implicit arguments the conclusion of the following theorem is
(Ξ (b : B a), transportD B C p b (f b) = g (transport B p b)) β
(transport (Ξ»a, Ξ (b : B a), C a b) p f = g) -/
definition heq_piD (p : a = a') (f : Ξ (b : B a), C a b)
(g : Ξ (b' : B a'), C a' b') : (Ξ (b : B a), p βΈD (f b) = g (p βΈ b)) β (p βΈ f = g) :=
eq.rec_on p (Ξ»g, !homotopy_equiv_eq) g
definition heq_pi {C : A β Type} (p : a = a') (f : Ξ (b : B a), C a)
(g : Ξ (b' : B a'), C a') : (Ξ (b : B a), p βΈ (f b) = g (p βΈ b)) β (p βΈ f = g) :=
eq.rec_on p (Ξ»g, !homotopy_equiv_eq) g
section
open sigma sigma.ops
/- more implicit arguments:
(Ξ (b : B a), transport C (sigma_eq p idp) (f b) = g (p βΈ b)) β
(Ξ (b : B a), transportD B (Ξ»(a : A) (b : B a), C β¨a, bβ©) p b (f b) = g (transport B p b)) -/
definition heq_pi_sigma {C : (Ξ£a, B a) β Type} (p : a = a')
(f : Ξ (b : B a), C β¨a, bβ©) (g : Ξ (b' : B a'), C β¨a', b'β©) :
(Ξ (b : B a), (sigma_eq p !pathover_tr) βΈ (f b) = g (p βΈ b)) β
(Ξ (b : B a), p βΈD (f b) = g (p βΈ b)) :=
eq.rec_on p (Ξ»g, !equiv.refl) g
end
/- Functorial action -/
variables (f0 : A' β A) (f1 : Ξ (a':A'), B (f0 a') β B' a')
/- The functoriality of [forall] is slightly subtle: it is contravariant in the domain type and covariant in the codomain, but the codomain is dependent on the domain. -/
definition pi_functor [unfold-full] : (Ξ (a:A), B a) β (Ξ (a':A'), B' a') := Ξ»g a', f1 a' (g (f0 a'))
definition ap_pi_functor {g g' : Ξ (a:A), B a} (h : g ~ g')
: ap (pi_functor f0 f1) (eq_of_homotopy h)
= eq_of_homotopy (Ξ»a':A', (ap (f1 a') (h (f0 a')))) :=
begin
apply (is_equiv_rect (@apd10 A B g g')), intro p, clear h,
cases p,
apply concat,
exact (ap (ap (pi_functor f0 f1)) (eq_of_homotopy_idp g)),
apply symm, apply eq_of_homotopy_idp
end
/- Equivalences -/
definition is_equiv_pi_functor [instance] [H0 : is_equiv f0]
[H1 : Ξ a', is_equiv (f1 a')] : is_equiv (pi_functor f0 f1) :=
begin
apply (adjointify (pi_functor f0 f1) (pi_functor f0β»ΒΉ
(Ξ»(a : A) (b' : B' (f0β»ΒΉ a)), transport B (right_inv f0 a) ((f1 (f0β»ΒΉ a))β»ΒΉ b')))),
begin
intro h, apply eq_of_homotopy, intro a', esimp,
rewrite [adj f0 a',-tr_compose,fn_tr_eq_tr_fn _ f1,right_inv (f1 _)],
apply apd
end,
begin
intro h, apply eq_of_homotopy, intro a, esimp,
rewrite [left_inv (f1 _)],
apply apd
end
end
definition pi_equiv_pi_of_is_equiv [H : is_equiv f0]
[H1 : Ξ a', is_equiv (f1 a')] : (Ξ a, B a) β (Ξ a', B' a') :=
equiv.mk (pi_functor f0 f1) _
definition pi_equiv_pi (f0 : A' β A) (f1 : Ξ a', (B (to_fun f0 a') β B' a'))
: (Ξ a, B a) β (Ξ a', B' a') :=
pi_equiv_pi_of_is_equiv (to_fun f0) (Ξ»a', to_fun (f1 a'))
definition pi_equiv_pi_id {P Q : A β Type} (g : Ξ a, P a β Q a) : (Ξ a, P a) β (Ξ a, Q a) :=
pi_equiv_pi equiv.refl g
/- Truncatedness: any dependent product of n-types is an n-type -/
open is_trunc
definition is_trunc_pi (B : A β Type) (n : trunc_index)
[H : βa, is_trunc n (B a)] : is_trunc n (Ξ a, B a) :=
begin
revert B H,
eapply (trunc_index.rec_on n),
{intro B H,
fapply is_contr.mk,
intro a, apply center,
intro f, apply eq_of_homotopy,
intro x, apply (center_eq (f x))},
{intro n IH B H,
fapply is_trunc_succ_intro, intro f g,
fapply is_trunc_equiv_closed,
apply equiv.symm, apply eq_equiv_homotopy,
apply IH,
intro a,
show is_trunc n (f a = g a), from
is_trunc_eq n (f a) (g a)}
end
local attribute is_trunc_pi [instance]
definition is_trunc_eq_pi [instance] [priority 500] (n : trunc_index) (f g : Ξ a, B a)
[H : βa, is_trunc n (f a = g a)] : is_trunc n (f = g) :=
begin
apply is_trunc_equiv_closed_rev,
apply eq_equiv_homotopy
end
definition is_trunc_not [instance] (n : trunc_index) (A : Type) : is_trunc (n.+1) Β¬A :=
by unfold not;exact _
definition is_hprop_pi_eq [instance] [priority 490] (a : A) : is_hprop (Ξ (a' : A), a = a') :=
is_hprop_of_imp_is_contr
( assume (f : Ξ a', a = a'),
assert H : is_contr A, from is_contr.mk a f,
_)
definition is_hprop_neg (A : Type) : is_hprop (Β¬A) := _
/- Symmetry of Ξ -/
definition is_equiv_flip [instance] {P : A β A' β Type}
: is_equiv (@function.flip A A' P) :=
begin
fapply is_equiv.mk,
exact (@function.flip _ _ (function.flip P)),
repeat (intro f; apply idp)
end
definition pi_comm_equiv {P : A β A' β Type} : (Ξ a b, P a b) β (Ξ b a, P a b) :=
equiv.mk (@function.flip _ _ P) _
end pi
attribute pi.is_trunc_pi [instance] [priority 1510]
|
ab2e83bc6ab13f800ce8d964e2fb6e41d0704b04 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/tactic/print_sorry.lean | f380ddec871fb0115235bff98cf94e6b8c0b02d0 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 4,856 | lean | /-
Copyright (c) 2022 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
import data.bool.basic
/-!
# Print sorry
Adds a command `#print_sorry_in nm` that prints all occurrences of `sorry` in declarations used in
`nm`, including all intermediate declarations.
Other searches through the environment can be done using `tactic.find_all_exprs`
-/
namespace tactic
/-- Auxilliary data type for `tactic.find_all_exprs` -/
meta structure find_all_expr_data :=
(matching_subexpr : bool) -- this declaration contains a subexpression on which the test passes
(test_passed : bool) -- the search has found a matching subexpression somewhere
-- name, contains subexpression directly, direct descendants
(descendants : list (name Γ bool Γ name_set))
(name_map : name_map bool) -- all data
(direct_descendants : name_set) -- direct descendants of a declaration
/-- Auxilliary declaration for `tactic.find_all_exprs`.
Traverse all declarations occurring in the declaration with the given name,
excluding declarations `n` such that `g n` is true (and all their descendants),
recording the structure of which declaration depends on which,
and whether `f e` is true on any subexpression `e` of the declaration. -/
meta def find_all_exprs_aux (env : environment) (f : expr β bool) (g : name β bool) : name β
find_all_expr_data β tactic find_all_expr_data
| n β¨bβ, bβ, l, ns, descβ© :=
match ns.find n with -- Skip declarations that we have already handled.
| some b := pure β¨bβ, b || bβ, l, ns, if b then desc.insert n else descβ©
| none := if g n then pure β¨bβ, bβ, l, ns.insert n ff, descβ© else do
d β env.get n,
let process (v : expr) : tactic find_all_expr_data :=
v.mfold β¨ff, ff, l, ns, mk_name_setβ© $ Ξ» e _ p,
if f e then pure β¨tt, tt, p.descendants, p.name_map, p.direct_descendantsβ© else
if e.is_constant then find_all_exprs_aux e.const_name p else pure p,
β¨b', b, l, ns, desc'β© β process d.value,
pure β¨bβ, bβ || b, if b then (n, b', desc')::l else l, ns.insert n b,
if b then desc.insert n else descβ©
end
/-- `tactic.find_all_exprs env test exclude nm` searches for all declarations (transitively)
occuring in `nm` that contain a subexpression `e` such that `test e` is true.
All declarations `n` such that `exclude n` is true (and all their descendants) are ignored. -/
meta def find_all_exprs (env : environment) (test : expr β bool) (exclude : name β bool)
(nm : name) : tactic $ list $ name Γ bool Γ name_set := do
β¨_, _, l, _, _β© β find_all_exprs_aux env test exclude nm β¨ff, ff, [], mk_name_map, mk_name_setβ©,
pure l
end tactic
open tactic
/-- Print all declarations that (transitively) occur in the value of declaration `nm` and depend on
`sorry`. If `ignore_mathlib` is set true, then all declarations in `mathlib` are
assumed to be `sorry`-free, which greatly reduces the search space. We could also exclude `core`,
but this doesn't speed up the search. -/
meta def print_sorry_in (nm : name) (ignore_mathlib := tt) : tactic unit := do
env β get_env,
dir β get_mathlib_dir,
data β find_all_exprs env (Ξ» e, e.is_sorry.is_some)
(if ignore_mathlib then env.is_prefix_of_file dir else Ξ» _, ff) nm,
let to_print : list format := data.map $ Ξ» β¨nm, contains_sorry, descβ©,
let s1 := if contains_sorry then " contains sorry" else "",
s2 := if contains_sorry && !desc.empty then " and" else "",
s3 := string.join $ (desc.to_list.map to_string).intersperse ", ",
s4 := if !desc.empty then format!" depends on {s3}" else "" in
format!"{nm}{s1}{s2}{s4}.",
trace $ format.join $ to_print.intersperse format.line
setup_tactic_parser
/-- The command
```
#print_sorry_in nm
```
prints all declarations that (transitively) occur in the value of declaration `nm` and depend on
`sorry`. This command assumes that no `sorry` occurs in mathlib. To find `sorry` in mathlib, use
``#eval print_sorry_in `nm ff`` instead.
Example:
```
def foo1 : false := sorry
def foo2 : false β§ false := β¨sorry, foo1β©
def foo3 : false := foo2.left
def foo4 : true := trivial
def foo5 : true β§ false := β¨foo4, foo3β©
#print_sorry_in foo5
```
prints
```
foo5 depends on foo3.
foo3 depends on foo2.
foo2 contains sorry and depends on foo1.
foo1 contains sorry.
```
-/
@[user_command]
meta def print_sorry_in_cmd (_ : parse $ tk "#print_sorry_in") : parser unit := do
nm β ident,
nm β resolve_name nm,
print_sorry_in nm.const_name
add_tactic_doc
{ name := "print_sorry_in",
category := doc_category.cmd,
decl_names := [`print_sorry_in_cmd],
tags := ["search", "environment", "debugging"] }
|
09a921ba2e2cc917eee6973bc190a6a5a8e798a1 | a4fc62ff52cb859cadb6cdfa156b33d12a5fcfb1 | /Mandlebrah.lean | c0702a74c24c93bf5b39f48bd7155c317a11c95d | [] | no_license | chughes87/Mandlebrah | f86b2406422922d7bb0d89a3d28775bd8862e074 | 559d300a9ef3d43832d3b47cffb014abe7649538 | refs/heads/master | 1,692,395,039,560 | 1,632,105,435,000 | 1,632,105,435,000 | 407,995,906 | 6 | 2 | null | 1,632,197,696,000 | 1,632,010,899,000 | Lean | UTF-8 | Lean | false | false | 3,785 | lean | import Mandlebrah.Complex
def step (c z : Complex) : Complex := z ^ 2 + c
def mandel (c : Complex) (bound : Float := 2.0) (maxSteps : Nat := 20) : Nat :=
let rec iterate : Complex β Nat β Nat β Nat := Ξ»
| _, 0, _ => 0
| z, maxSteps + 1, currStep =>
match (Complex.Abs z β₯ bound : Bool) with
| true => currStep
| false => iterate (step c z) maxSteps currStep.succ
iterate 0 maxSteps 0
def twoDeeRange (default: a) (x y: Nat) : Array (Array a) :=
Array.mkArray y <| Array.mkArray x default
def buildDimToComplex (xMax yMax : Nat) (cMin cMax : Complex) : Nat β Nat β Complex :=
let xScalar : Float := (cMax.real - cMin.real) / Float.ofNat xMax
let yScalar : Float := (cMax.i - cMin.i) / Float.ofNat yMax
fun (px py : Nat) => cMin + Complex.mk ((Float.ofNat px) * xScalar) ((Float.ofNat py) * yScalar)
section x
variable (size : Nat)
variable (hpx hpy: Nat)
variable (hcMin hcMax : Complex)
variable (hp: hpx < size β§ hpy < size β§ hpx >0 β§ hpy > 0 )
variable (hc: hcMin < hcMax)
variable (hsize: size > 0)
def ap: Nat β Nat β Complex :=
(buildDimToComplex size size hcMin hcMax)
#check ap
theorem BDimIdAtZero : hcMin = (buildDimToComplex size size hcMin hcMax 0 0 ) := by
apply Eq.symm
sorry
theorem existsAIncrement : β x : Float, β p : Nat, β q: Nat,
(buildDimToComplex size size hcMin hcMax p q) -
(buildDimToComplex size size hcMin hcMax (p+1) (q+1)) * x = 0 :=
sorry
theorem DimInBounds : hcMin < (buildDimToComplex size size hcMin hcMax hpy hpx) β§
hcMax > (buildDimToComplex size size hcMin hcMax hpy hpx) := by sorry
#check size < hpx
-- theorem dimToComplexBounded : hcomp := by
sorry
end x
def newScene (px py : Nat) (cMin cMax : Complex) (maxSteps : Nat) : Array (Array Nat) := do
let mut scene : Array (Array Complex) := twoDeeRange (Complex.mk 0 0) px py
let dimToComplex := buildDimToComplex px py cMin cMax
Array.mapIdx scene Ξ» idy dimx =>
Array.mapIdx dimx Ξ» idx elem =>
(dimToComplex idx idy) |> mandel
@[inline] def Float.max (x y : Float) : Float := if x β€ y then y else x
@[inline] def Float.min (x y : Float) : Float := if x β€ y then x else y
open Float in
def Float.clampToUInt8 (x : Float) : UInt8 :=
toUInt8 <| min 255 <| max 0 x
def IO.FS.Handle.writeColor (handle : IO.FS.Handle) (cMax : Nat) (c : Nat) : IO Unit := do
let r := Float.clampToUInt8 (Float.ofNat c / (Float.ofNat cMax) * 255)
let g := Float.clampToUInt8 (Float.ofNat c / (Float.ofNat cMax) * 255)
let b := Float.clampToUInt8 (Float.ofNat c / (Float.ofNat cMax) * 255)
handle.putStrLn s!"{r} {g} {b}"
def writeFile (filename : String) (maxSteps := 50) (width := 500) (height := 500) : IO Unit := do
IO.println "boop"
let pixels := newScene height width (Complex.mk (-1) (-1)) (Complex.mk 1 1) maxSteps
IO.FS.withFile filename IO.FS.Mode.write Ξ» handle => do
handle.putStrLn "P3"
handle.putStrLn s!"{width} {height} 255"
for i in [0:width] do
for j in [0:height] do
let pixel := pixels[i][j]
handle.writeColor maxSteps pixel
-- #eval newScene 10 10 (Complex.mk (-1) (-1)) (Complex.mk 1 1)
-- #eval Nat.succ 1
-- #eval x
-- #eval Complex.add (Complex.mk 1 1) (Complex.mk 1 2)
-- #eval Complex.mul (Complex.mk 1 1) (Complex.mk 1 2)
-- #eval Complex.mk 1 1 + Complex.mk 11 2
-- #eval x * y
-- #eval x ^ 2
-- #eval Complex.Abs y
-- #eval stepIn 1000000.0 1000000 y 0
-- #eval writeFile "out.ppm"
def main : List String β IO Unit
| [] => writeFile "out.ppm"
| (x::xs) => writeFile x |
e8c7c4f83bcd9e6a3a4e42d01bcee58117221e9d | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebraic_topology/simplicial_set.lean | 5d5aca42921e6fb533f6a1c85e75eed8f3145f13 | [
"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 | 5,169 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Scott Morrison, Adam Topaz
-/
import algebraic_topology.simplicial_object
import algebraic_topology.topological_simplex
import category_theory.limits.presheaf
import category_theory.limits.types
import category_theory.yoneda
import topology.category.Top.limits
/-!
A simplicial set is just a simplicial object in `Type`,
i.e. a `Type`-valued presheaf on the simplex category.
(One might be tempted to call these "simplicial types" when working in type-theoretic foundations,
but this would be unnecessarily confusing given the existing notion of a simplicial type in
homotopy type theory.)
We define the standard simplices `Ξ[n]` as simplicial sets,
and their boundaries `βΞ[n]` and horns `Ξ[n, i]`.
(The notations are available via `open_locale simplicial`.)
## Future work
There isn't yet a complete API for simplices, boundaries, and horns.
As an example, we should have a function that constructs
from a non-surjective order preserving function `fin n β fin n`
a morphism `Ξ[n] βΆ βΞ[n]`.
-/
universes v u
open category_theory
open_locale simplicial
/-- The category of simplicial sets.
This is the category of contravariant functors from
`simplex_category` to `Type u`. -/
@[derive [large_category, limits.has_limits, limits.has_colimits]]
def sSet : Type (u+1) := simplicial_object (Type u)
namespace sSet
/-- The `n`-th standard simplex `Ξ[n]` associated with a nonempty finite linear order `n`
is the Yoneda embedding of `n`. -/
def standard_simplex : simplex_category β₯€ sSet := yoneda
localized "notation `Ξ[`n`]` := sSet.standard_simplex.obj (simplex_category.mk n)" in simplicial
instance : inhabited sSet := β¨Ξ[0]β©
section
/-- The `m`-simplices of the `n`-th standard simplex are
the monotone maps from `fin (m+1)` to `fin (n+1)`. -/
def as_order_hom {n} {m} (Ξ± : Ξ[n].obj m) :
order_hom (fin (m.unop.len+1)) (fin (n+1)) := Ξ±.to_order_hom
end
/-- The boundary `βΞ[n]` of the `n`-th standard simplex consists of
all `m`-simplices of `standard_simplex n` that are not surjective
(when viewed as monotone function `m β n`). -/
def boundary (n : β) : sSet :=
{ obj := Ξ» m, {Ξ± : Ξ[n].obj m // Β¬ function.surjective (as_order_hom Ξ±)},
map := Ξ» mβ mβ f Ξ±, β¨f.unop β« (Ξ± : Ξ[n].obj mβ),
by { intro h, apply Ξ±.property, exact function.surjective.of_comp h }β© }
localized "notation `βΞ[`n`]` := sSet.boundary n" in simplicial
/-- The inclusion of the boundary of the `n`-th standard simplex into that standard simplex. -/
def boundary_inclusion (n : β) :
βΞ[n] βΆ Ξ[n] :=
{ app := Ξ» m (Ξ± : {Ξ± : Ξ[n].obj m // _}), Ξ± }
/-- `horn n i` (or `Ξ[n, i]`) is the `i`-th horn of the `n`-th standard simplex, where `i : n`.
It consists of all `m`-simplices `Ξ±` of `Ξ[n]`
for which the union of `{i}` and the range of `Ξ±` is not all of `n`
(when viewing `Ξ±` as monotone function `m β n`). -/
def horn (n : β) (i : fin (n+1)) : sSet :=
{ obj := Ξ» m,
{ Ξ± : Ξ[n].obj m // set.range (as_order_hom Ξ±) βͺ {i} β set.univ },
map := Ξ» mβ mβ f Ξ±, β¨f.unop β« (Ξ± : Ξ[n].obj mβ),
begin
intro h, apply Ξ±.property,
rw set.eq_univ_iff_forall at h β’, intro j,
apply or.imp _ id (h j),
intro hj,
exact set.range_comp_subset_range _ _ hj,
endβ© }
localized "notation `Ξ[`n`, `i`]` := sSet.horn (n : β) i" in simplicial
/-- The inclusion of the `i`-th horn of the `n`-th standard simplex into that standard simplex. -/
def horn_inclusion (n : β) (i : fin (n+1)) :
Ξ[n, i] βΆ Ξ[n] :=
{ app := Ξ» m (Ξ± : {Ξ± : Ξ[n].obj m // _}), Ξ± }
section examples
open_locale simplicial
/-- The simplicial circle. -/
noncomputable def S1 : sSet :=
limits.colimit $ limits.parallel_pair
((standard_simplex.map $ simplex_category.Ξ΄ 0) : Ξ[0] βΆ Ξ[1])
(standard_simplex.map $ simplex_category.Ξ΄ 1)
end examples
/-- Truncated simplicial sets. -/
@[derive [large_category, limits.has_limits, limits.has_colimits]]
def truncated (n : β) := simplicial_object.truncated (Type u) n
/-- The skeleton functor on simplicial sets. -/
def sk (n : β) : sSet β₯€ sSet.truncated n := simplicial_object.sk n
instance {n} : inhabited (sSet.truncated n) := β¨(sk n).obj $ Ξ[0]β©
end sSet
/-- The functor associating the singular simplicial set to a topological space. -/
noncomputable def Top.to_sSet : Top β₯€ sSet :=
colimit_adj.restricted_yoneda simplex_category.to_Top
/-- The geometric realization functor. -/
noncomputable def sSet.to_Top : sSet β₯€ Top :=
colimit_adj.extend_along_yoneda simplex_category.to_Top
/-- Geometric realization is left adjoint to the singular simplicial set construction. -/
noncomputable def sSet_Top_adj : sSet.to_Top β£ Top.to_sSet :=
colimit_adj.yoneda_adjunction _
/-- The geometric realization of the representable simplicial sets agree
with the usual topological simplices. -/
noncomputable def sSet.to_Top_simplex :
(yoneda : simplex_category β₯€ _) β sSet.to_Top β
simplex_category.to_Top :=
colimit_adj.is_extension_along_yoneda _
|
183178bb153b2f03f7cfb97a71663eb48bb1f7b7 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/module/torsion.lean | 9326615a9c7712ac45e4be6ab625728aa314212f | [
"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 | 27,501 | lean | /-
Copyright (c) 2022 Pierre-Alexandre Bazin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Pierre-Alexandre Bazin
-/
import algebra.direct_sum.module
import linear_algebra.isomorphisms
import group_theory.torsion
import ring_theory.coprime.ideal
import ring_theory.finiteness
/-!
# Torsion submodules
## Main definitions
* `torsion_of R M x` : the torsion ideal of `x`, containing all `a` such that `a β’ x = 0`.
* `submodule.torsion_by R M a` : the `a`-torsion submodule, containing all elements `x` of `M` such
that `a β’ x = 0`.
* `submodule.torsion_by_set R M s` : the submodule containing all elements `x` of `M` such that
`a β’ x = 0` for all `a` in `s`.
* `submodule.torsion' R M S` : the `S`-torsion submodule, containing all elements `x` of `M` such
that `a β’ x = 0` for some `a` in `S`.
* `submodule.torsion R M` : the torsion submoule, containing all elements `x` of `M` such that
`a β’ x = 0` for some non-zero-divisor `a` in `R`.
* `module.is_torsion_by R M a` : the property that defines a `a`-torsion module. Similarly,
`is_torsion_by_set`, `is_torsion'` and `is_torsion`.
* `module.is_torsion_by_set.module` : Creates a `R β§Έ I`-module from a `R`-module that
`is_torsion_by_set R _ I`.
## Main statements
* `quot_torsion_of_equiv_span_singleton` : isomorphism between the span of an element of `M` and
the quotient by its torsion ideal.
* `torsion' R M S` and `torsion R M` are submodules.
* `torsion_by_set_eq_torsion_by_span` : torsion by a set is torsion by the ideal generated by it.
* `submodule.torsion_by_is_torsion_by` : the `a`-torsion submodule is a `a`-torsion module.
Similar lemmas for `torsion'` and `torsion`.
* `submodule.torsion_by_is_internal` : a `β i, p i`-torsion module is the internal direct sum of its
`p i`-torsion submodules when the `p i` are pairwise coprime. A more general version with coprime
ideals is `submodule.torsion_by_set_is_internal`.
* `submodule.no_zero_smul_divisors_iff_torsion_bot` : a module over a domain has
`no_zero_smul_divisors` (that is, there is no non-zero `a`, `x` such that `a β’ x = 0`)
iff its torsion submodule is trivial.
* `submodule.quotient_torsion.torsion_eq_bot` : quotienting by the torsion submodule makes the
torsion submodule of the new module trivial. If `R` is a domain, we can derive an instance
`submodule.quotient_torsion.no_zero_smul_divisors : no_zero_smul_divisors R (M β§Έ torsion R M)`.
## Notation
* The notions are defined for a `comm_semiring R` and a `module R M`. Some additional hypotheses on
`R` and `M` are required by some lemmas.
* The letters `a`, `b`, ... are used for scalars (in `R`), while `x`, `y`, ... are used for vectors
(in `M`).
## Tags
Torsion, submodule, module, quotient
-/
namespace ideal
section torsion_of
variables (R M : Type*) [semiring R] [add_comm_monoid M] [module R M]
/--The torsion ideal of `x`, containing all `a` such that `a β’ x = 0`.-/
@[simps] def torsion_of (x : M) : ideal R := (linear_map.to_span_singleton R M x).ker
@[simp] lemma torsion_of_zero : torsion_of R M (0 : M) = β€ := by simp [torsion_of]
variables {R M}
@[simp] lemma mem_torsion_of_iff (x : M) (a : R) : a β torsion_of R M x β a β’ x = 0 := iff.rfl
variables (R)
@[simp] lemma torsion_of_eq_top_iff (m : M) : torsion_of R M m = β€ β m = 0 :=
begin
refine β¨Ξ» h, _, Ξ» h, by simp [h]β©,
rw [β one_smul R m, β mem_torsion_of_iff m (1 : R), h],
exact submodule.mem_top,
end
@[simp] lemma torsion_of_eq_bot_iff_of_no_zero_smul_divisors
[nontrivial R] [no_zero_smul_divisors R M] (m : M) :
torsion_of R M m = β₯ β m β 0 :=
begin
refine β¨Ξ» h contra, _, Ξ» h, (submodule.eq_bot_iff _).mpr $ Ξ» r hr, _β©,
{ rw [contra, torsion_of_zero] at h,
exact bot_ne_top.symm h, },
{ rw [mem_torsion_of_iff, smul_eq_zero] at hr,
tauto, },
end
/-- See also `complete_lattice.independent.linear_independent` which provides the same conclusion
but requires the stronger hypothesis `no_zero_smul_divisors R M`. -/
lemma complete_lattice.independent.linear_independent' {ΞΉ R M : Type*} {v : ΞΉ β M}
[ring R] [add_comm_group M] [module R M]
(hv : complete_lattice.independent $ Ξ» i, (R β v i))
(h_ne_zero : β i, ideal.torsion_of R M (v i) = β₯) :
linear_independent R v :=
begin
refine linear_independent_iff_not_smul_mem_span.mpr (Ξ» i r hi, _),
replace hv := complete_lattice.independent_def.mp hv i,
simp only [supr_subtype', β submodule.span_range_eq_supr, disjoint_iff] at hv,
have : r β’ v i β β₯,
{ rw [β hv, submodule.mem_inf],
refine β¨submodule.mem_span_singleton.mpr β¨r, rflβ©, _β©,
convert hi,
ext,
simp, },
rw [β submodule.mem_bot R, β h_ne_zero i],
simpa using this,
end
end torsion_of
section
variables (R M : Type*) [ring R] [add_comm_group M] [module R M]
/--The span of `x` in `M` is isomorphic to `R` quotiented by the torsion ideal of `x`.-/
noncomputable def quot_torsion_of_equiv_span_singleton (x : M) :
(R β§Έ torsion_of R M x) ββ[R] (R β x) :=
(linear_map.to_span_singleton R M x).quot_ker_equiv_range.trans $
linear_equiv.of_eq _ _ (linear_map.span_singleton_eq_range R M x).symm
variables {R M}
@[simp] lemma quot_torsion_of_equiv_span_singleton_apply_mk (x : M) (a : R) :
quot_torsion_of_equiv_span_singleton R M x (submodule.quotient.mk a) =
a β’ β¨x, submodule.mem_span_singleton_self xβ© := rfl
end
end ideal
open_locale non_zero_divisors
section defs
variables (R M : Type*) [comm_semiring R] [add_comm_monoid M] [module R M]
namespace submodule
/-- The `a`-torsion submodule for `a` in `R`, containing all elements `x` of `M` such that
`a β’ x = 0`. -/
@[simps] def torsion_by (a : R) : submodule R M := (distrib_mul_action.to_linear_map _ _ a).ker
/-- The submodule containing all elements `x` of `M` such that `a β’ x = 0` for all `a` in `s`. -/
@[simps] def torsion_by_set (s : set R) : submodule R M := Inf (torsion_by R M '' s)
/-- The `S`-torsion submodule, containing all elements `x` of `M` such that `a β’ x = 0` for some
`a` in `S`. -/
@[simps] def torsion' (S : Type*)
[comm_monoid S] [distrib_mul_action S M] [smul_comm_class S R M] :
submodule R M :=
{ carrier := { x | β a : S, a β’ x = 0 },
zero_mem' := β¨1, smul_zero _β©,
add_mem' := Ξ» x y β¨a, hxβ© β¨b, hyβ©,
β¨b * a,
by rw [smul_add, mul_smul, mul_comm, mul_smul, hx, hy, smul_zero, smul_zero, add_zero]β©,
smul_mem' := Ξ» a x β¨b, hβ©, β¨b, by rw [smul_comm, h, smul_zero]β© }
/-- The torsion submodule, containing all elements `x` of `M` such that `a β’ x = 0` for some
non-zero-divisor `a` in `R`. -/
@[reducible] def torsion := torsion' R M Rβ°
end submodule
namespace module
/-- A `a`-torsion module is a module where every element is `a`-torsion. -/
@[reducible] def is_torsion_by (a : R) := β β¦x : Mβ¦, a β’ x = 0
/-- A module where every element is `a`-torsion for all `a` in `s`. -/
@[reducible] def is_torsion_by_set (s : set R) := β β¦x : Mβ¦ β¦a : sβ¦, (a : R) β’ x = 0
/-- A `S`-torsion module is a module where every element is `a`-torsion for some `a` in `S`. -/
@[reducible] def is_torsion' (S : Type*) [has_smul S M] := β β¦x : Mβ¦, β a : S, a β’ x = 0
/-- A torsion module is a module where every element is `a`-torsion for some non-zero-divisor `a`.
-/
@[reducible] def is_torsion := β β¦x : Mβ¦, β a : Rβ°, a β’ x = 0
end module
end defs
variables {R M : Type*}
section
variables [comm_semiring R] [add_comm_monoid M] [module R M] (s : set R) (a : R)
namespace submodule
@[simp] lemma smul_torsion_by (x : torsion_by R M a) : a β’ x = 0 := subtype.ext x.prop
@[simp] lemma smul_coe_torsion_by (x : torsion_by R M a) : a β’ (x : M) = 0 := x.prop
@[simp] lemma mem_torsion_by_iff (x : M) : x β torsion_by R M a β a β’ x = 0 := iff.rfl
@[simp] lemma mem_torsion_by_set_iff (x : M) :
x β torsion_by_set R M s β β a : s, (a : R) β’ x = 0 :=
begin
refine β¨Ξ» h β¨a, haβ©, mem_Inf.mp h _ (set.mem_image_of_mem _ ha), Ξ» h, mem_Inf.mpr _β©,
rintro _ β¨a, ha, rflβ©, exact h β¨a, haβ©
end
@[simp] lemma torsion_by_singleton_eq : torsion_by_set R M {a} = torsion_by R M a :=
begin
ext x,
simp only [mem_torsion_by_set_iff, set_coe.forall, subtype.coe_mk, set.mem_singleton_iff,
forall_eq, mem_torsion_by_iff]
end
lemma torsion_by_set_le_torsion_by_set_of_subset {s t : set R} (st : s β t) :
torsion_by_set R M t β€ torsion_by_set R M s :=
Inf_le_Inf $ Ξ» _ β¨a, ha, hβ©, β¨a, st ha, hβ©
/-- Torsion by a set is torsion by the ideal generated by it. -/
lemma torsion_by_set_eq_torsion_by_span :
torsion_by_set R M s = torsion_by_set R M (ideal.span s) :=
begin
refine le_antisymm (Ξ» x hx, _) (torsion_by_set_le_torsion_by_set_of_subset subset_span),
rw mem_torsion_by_set_iff at hx β’,
suffices : ideal.span s β€ ideal.torsion_of R M x,
{ rintro β¨a, haβ©, exact this ha },
rw ideal.span_le, exact Ξ» a ha, hx β¨a, haβ©
end
lemma torsion_by_span_singleton_eq : torsion_by_set R M (R β a) = torsion_by R M a :=
((torsion_by_set_eq_torsion_by_span _).symm.trans $ torsion_by_singleton_eq _)
lemma torsion_by_le_torsion_by_of_dvd (a b : R) (dvd : a β£ b) :
torsion_by R M a β€ torsion_by R M b :=
begin
rw [β torsion_by_span_singleton_eq, β torsion_by_singleton_eq],
apply torsion_by_set_le_torsion_by_set_of_subset,
rintro c (rfl : c = b), exact ideal.mem_span_singleton.mpr dvd
end
@[simp] lemma torsion_by_one : torsion_by R M 1 = β₯ :=
eq_bot_iff.mpr (Ξ» _ h, by { rw [mem_torsion_by_iff, one_smul] at h, exact h })
@[simp] lemma torsion_by_univ : torsion_by_set R M set.univ = β₯ :=
by { rw [eq_bot_iff, β torsion_by_one, β torsion_by_singleton_eq],
exact torsion_by_set_le_torsion_by_set_of_subset (Ξ» _ _, trivial) }
end submodule
open submodule
namespace module
@[simp] lemma is_torsion_by_singleton_iff : is_torsion_by_set R M {a} β is_torsion_by R M a :=
begin
refine β¨Ξ» h x, @h _ β¨_, set.mem_singleton _β©, Ξ» h x, _β©,
rintro β¨b, rfl : b = aβ©, exact @h _
end
lemma is_torsion_by_set_iff_torsion_by_set_eq_top :
is_torsion_by_set R M s β submodule.torsion_by_set R M s = β€ :=
β¨Ξ» h, eq_top_iff.mpr (Ξ» _ _, (mem_torsion_by_set_iff _ _).mpr $ @h _),
Ξ» h x, by { rw [β mem_torsion_by_set_iff, h], trivial }β©
/-- A `a`-torsion module is a module whose `a`-torsion submodule is the full space. -/
lemma is_torsion_by_iff_torsion_by_eq_top : is_torsion_by R M a β torsion_by R M a = β€ :=
by rw [β torsion_by_singleton_eq, β is_torsion_by_singleton_iff,
is_torsion_by_set_iff_torsion_by_set_eq_top]
lemma is_torsion_by_set_iff_is_torsion_by_span :
is_torsion_by_set R M s β is_torsion_by_set R M (ideal.span s) :=
by rw [is_torsion_by_set_iff_torsion_by_set_eq_top, is_torsion_by_set_iff_torsion_by_set_eq_top,
torsion_by_set_eq_torsion_by_span]
lemma is_torsion_by_span_singleton_iff : is_torsion_by_set R M (R β a) β is_torsion_by R M a :=
((is_torsion_by_set_iff_is_torsion_by_span _).symm.trans $ is_torsion_by_singleton_iff _)
end module
namespace submodule
open module
lemma torsion_by_set_is_torsion_by_set : is_torsion_by_set R (torsion_by_set R M s) s :=
Ξ» β¨x, hxβ© a, subtype.ext $ (mem_torsion_by_set_iff _ _).mp hx a
/-- The `a`-torsion submodule is a `a`-torsion module. -/
lemma torsion_by_is_torsion_by : is_torsion_by R (torsion_by R M a) a := Ξ» _, smul_torsion_by _ _
@[simp] lemma torsion_by_torsion_by_eq_top : torsion_by R (torsion_by R M a) a = β€ :=
(is_torsion_by_iff_torsion_by_eq_top a).mp $ torsion_by_is_torsion_by a
@[simp] lemma torsion_by_set_torsion_by_set_eq_top :
torsion_by_set R (torsion_by_set R M s) s = β€ :=
(is_torsion_by_set_iff_torsion_by_set_eq_top s).mp $ torsion_by_set_is_torsion_by_set s
variables (R M)
lemma torsion_gc : @galois_connection (submodule R M) (ideal R)α΅α΅ _ _
annihilator (Ξ» I, torsion_by_set R M $ I.of_dual) :=
Ξ» A I, β¨Ξ» h x hx, (mem_torsion_by_set_iff _ _).mpr $ Ξ» β¨a, haβ©, mem_annihilator.mp (h ha) x hx,
Ξ» h a ha, mem_annihilator.mpr $ Ξ» x hx, (mem_torsion_by_set_iff _ _).mp (h hx) β¨a, haβ©β©
variables {R M}
section coprime
open_locale big_operators
variables {ΞΉ : Type*} {p : ΞΉ β ideal R} {S : finset ΞΉ}
variables (hp : (S : set ΞΉ).pairwise $ Ξ» i j, p i β p j = β€)
include hp
lemma supr_torsion_by_ideal_eq_torsion_by_infi :
(β¨ i β S, torsion_by_set R M $ p i) = torsion_by_set R M β(β¨
i β S, p i) :=
begin
cases S.eq_empty_or_nonempty with h h,
{ rw h, convert supr_emptyset, convert torsion_by_univ, convert top_coe, exact infi_emptyset },
apply le_antisymm,
{ apply supr_le _, intro i, apply supr_le _, intro is,
apply torsion_by_set_le_torsion_by_set_of_subset,
exact (infi_le (Ξ» i, β¨
(H : i β S), p i) i).trans (infi_le _ is), },
{ intros x hx,
rw mem_supr_finset_iff_exists_sum,
obtain β¨ΞΌ, hΞΌβ© := (mem_supr_finset_iff_exists_sum _ _).mp
((ideal.eq_top_iff_one _).mp $ (ideal.supr_infi_eq_top_iff_pairwise h _).mpr hp),
refine β¨Ξ» i, β¨(ΞΌ i : R) β’ x, _β©, _β©,
{ rw mem_torsion_by_set_iff at hx β’,
rintro β¨a, haβ©, rw smul_smul,
suffices : a * ΞΌ i β β¨
i β S, p i, from hx β¨_, thisβ©,
rw mem_infi, intro j, rw mem_infi, intro hj,
by_cases ij : j = i,
{ rw ij, exact ideal.mul_mem_right _ _ ha },
{ have := coe_mem (ΞΌ i), simp only [mem_infi] at this,
exact ideal.mul_mem_left _ _ (this j hj ij) } },
{ simp_rw coe_mk, rw [β finset.sum_smul, hΞΌ, one_smul] } }
end
lemma sup_indep_torsion_by_ideal : S.sup_indep (Ξ» i, torsion_by_set R M $ p i) :=
Ξ» T hT i hi hiT, begin
rw [disjoint_iff, finset.sup_eq_supr,
supr_torsion_by_ideal_eq_torsion_by_infi $ Ξ» i hi j hj ij, hp (hT hi) (hT hj) ij],
have := @galois_connection.u_inf _ _ (order_dual.to_dual _) (order_dual.to_dual _) _ _ _ _
(torsion_gc R M), dsimp at this β’,
rw [β this, ideal.sup_infi_eq_top, top_coe, torsion_by_univ],
intros j hj, apply hp hi (hT hj), rintro rfl, exact hiT hj
end
omit hp
variables {q : ΞΉ β R} (hq : (S : set ΞΉ).pairwise $ is_coprime on q)
include hq
lemma supr_torsion_by_eq_torsion_by_prod :
(β¨ i β S, torsion_by R M $ q i) = torsion_by R M (β i in S, q i) :=
begin
rw [β torsion_by_span_singleton_eq, ideal.submodule_span_eq,
β ideal.finset_inf_span_singleton _ _ hq, finset.inf_eq_infi,
β supr_torsion_by_ideal_eq_torsion_by_infi],
{ congr, ext : 1, congr, ext : 1, exact (torsion_by_span_singleton_eq _).symm },
{ exact Ξ» i hi j hj ij, (ideal.sup_eq_top_iff_is_coprime _ _).mpr (hq hi hj ij), }
end
lemma sup_indep_torsion_by : S.sup_indep (Ξ» i, torsion_by R M $ q i) :=
begin
convert sup_indep_torsion_by_ideal
(Ξ» i hi j hj ij, (ideal.sup_eq_top_iff_is_coprime (q i) _).mpr $ hq hi hj ij),
ext : 1, exact (torsion_by_span_singleton_eq _).symm,
end
end coprime
end submodule
end
section needs_group
variables [comm_ring R] [add_comm_group M] [module R M]
namespace submodule
open_locale big_operators
variables {ΞΉ : Type*} [decidable_eq ΞΉ] {S : finset ΞΉ}
/--If the `p i` are pairwise coprime, a `β¨
i, p i`-torsion module is the internal direct sum of
its `p i`-torsion submodules.-/
lemma torsion_by_set_is_internal {p : ΞΉ β ideal R}
(hp : (S : set ΞΉ).pairwise $ Ξ» i j, p i β p j = β€)
(hM : module.is_torsion_by_set R M (β¨
i β S, p i : ideal R)) :
direct_sum.is_internal (Ξ» i : S, torsion_by_set R M $ p i) :=
direct_sum.is_internal_submodule_of_independent_of_supr_eq_top
(complete_lattice.independent_iff_sup_indep.mpr $ sup_indep_torsion_by_ideal hp)
((supr_subtype'' βS $ Ξ» i, torsion_by_set R M $ p i).trans $
(supr_torsion_by_ideal_eq_torsion_by_infi hp).trans $
(module.is_torsion_by_set_iff_torsion_by_set_eq_top _).mp hM)
/--If the `q i` are pairwise coprime, a `β i, q i`-torsion module is the internal direct sum of
its `q i`-torsion submodules.-/
lemma torsion_by_is_internal {q : ΞΉ β R} (hq : (S : set ΞΉ).pairwise $ is_coprime on q)
(hM : module.is_torsion_by R M $ β i in S, q i) :
direct_sum.is_internal (Ξ» i : S, torsion_by R M $ q i) :=
begin
rw [β module.is_torsion_by_span_singleton_iff, ideal.submodule_span_eq,
β ideal.finset_inf_span_singleton _ _ hq, finset.inf_eq_infi] at hM,
convert torsion_by_set_is_internal
(Ξ» i hi j hj ij, (ideal.sup_eq_top_iff_is_coprime (q i) _).mpr $ hq hi hj ij) hM,
ext : 1, exact (torsion_by_span_singleton_eq _).symm,
end
end submodule
namespace module
variables {I : ideal R} (hM : is_torsion_by_set R M I)
include hM
/-- can't be an instance because hM can't be inferred -/
def is_torsion_by_set.has_smul : has_smul (R β§Έ I) M :=
{ smul := Ξ» b x, quotient.lift_on' b (β’ x) $ Ξ» bβ bβ h, begin
show bβ β’ x = bβ β’ x,
have : (-bβ + bβ) β’ x = 0 := @hM x β¨_, quotient_add_group.left_rel_apply.mp hβ©,
rw [add_smul, neg_smul, neg_add_eq_zero] at this,
exact this
end }
@[simp] lemma is_torsion_by_set.mk_smul (b : R) (x : M) :
by haveI := hM.has_smul; exact ideal.quotient.mk I b β’ x = b β’ x := rfl
/-- A `(R β§Έ I)`-module is a `R`-module which `is_torsion_by_set R M I`. -/
def is_torsion_by_set.module : module (R β§Έ I) M :=
@function.surjective.module_left _ _ _ _ _ _ _ hM.has_smul
_ ideal.quotient.mk_surjective (is_torsion_by_set.mk_smul hM)
instance is_torsion_by_set.is_scalar_tower {S : Type*} [has_smul S R] [has_smul S M]
[is_scalar_tower S R M] [is_scalar_tower S R R] :
@@is_scalar_tower S (R β§Έ I) M _ (is_torsion_by_set.module hM).to_has_smul _ :=
{ smul_assoc := Ξ» b d x, quotient.induction_on' d $ Ξ» c, (smul_assoc b c x : _) }
omit hM
instance : module (R β§Έ I) (M β§Έ I β’ (β€ : submodule R M)) :=
is_torsion_by_set.module (Ξ» x r, begin
induction x using quotient.induction_on,
refine (submodule.quotient.mk_eq_zero _).mpr (submodule.smul_mem_smul r.prop _),
trivial,
end)
end module
namespace submodule
instance (I : ideal R) : module (R β§Έ I) (torsion_by_set R M I) :=
module.is_torsion_by_set.module $ torsion_by_set_is_torsion_by_set I
@[simp] lemma torsion_by_set.mk_smul (I : ideal R) (b : R) (x : torsion_by_set R M I) :
ideal.quotient.mk I b β’ x = b β’ x := rfl
instance (I : ideal R) {S : Type*} [has_smul S R] [has_smul S M]
[is_scalar_tower S R M] [is_scalar_tower S R R] :
is_scalar_tower S (R β§Έ I) (torsion_by_set R M I) :=
infer_instance
/-- The `a`-torsion submodule as a `(R β§Έ Rβa)`-module. -/
instance (a : R) : module (R β§Έ R β a) (torsion_by R M a) :=
module.is_torsion_by_set.module $
(module.is_torsion_by_span_singleton_iff a).mpr $ torsion_by_is_torsion_by a
@[simp] lemma torsion_by.mk_smul (a b : R) (x : torsion_by R M a) :
ideal.quotient.mk (R β a) b β’ x = b β’ x := rfl
instance (a : R) {S : Type*} [has_smul S R] [has_smul S M]
[is_scalar_tower S R M] [is_scalar_tower S R R] :
is_scalar_tower S (R β§Έ R β a) (torsion_by R M a) :=
infer_instance
end submodule
end needs_group
namespace submodule
section torsion'
open module
variables [comm_semiring R] [add_comm_monoid M] [module R M]
variables (S : Type*) [comm_monoid S] [distrib_mul_action S M] [smul_comm_class S R M]
@[simp] lemma mem_torsion'_iff (x : M) : x β torsion' R M S β β a : S, a β’ x = 0 := iff.rfl
@[simp] lemma mem_torsion_iff (x : M) : x β torsion R M β β a : Rβ°, a β’ x = 0 := iff.rfl
@[simps] instance : has_smul S (torsion' R M S) :=
β¨Ξ» s x, β¨s β’ x, by { obtain β¨x, a, hβ© := x, use a, dsimp, rw [smul_comm, h, smul_zero] }β©β©
instance : distrib_mul_action S (torsion' R M S) := subtype.coe_injective.distrib_mul_action
((torsion' R M S).subtype).to_add_monoid_hom (Ξ» (c : S) x, rfl)
instance : smul_comm_class S R (torsion' R M S) := β¨Ξ» s a x, subtype.ext $ smul_comm _ _ _β©
/-- A `S`-torsion module is a module whose `S`-torsion submodule is the full space. -/
lemma is_torsion'_iff_torsion'_eq_top : is_torsion' M S β torsion' R M S = β€ :=
β¨Ξ» h, eq_top_iff.mpr (Ξ» _ _, @h _), Ξ» h x, by { rw [β @mem_torsion'_iff R, h], trivial }β©
/-- The `S`-torsion submodule is a `S`-torsion module. -/
lemma torsion'_is_torsion' : is_torsion' (torsion' R M S) S := Ξ» β¨x, β¨a, hβ©β©, β¨a, subtype.ext hβ©
@[simp] lemma torsion'_torsion'_eq_top : torsion' R (torsion' R M S) S = β€ :=
(is_torsion'_iff_torsion'_eq_top S).mp $ torsion'_is_torsion' S
/-- The torsion submodule of the torsion submodule (viewed as a module) is the full
torsion module. -/
@[simp] lemma torsion_torsion_eq_top : torsion R (torsion R M) = β€ := torsion'_torsion'_eq_top Rβ°
/-- The torsion submodule is always a torsion module. -/
lemma torsion_is_torsion : module.is_torsion R (torsion R M) := torsion'_is_torsion' Rβ°
end torsion'
section torsion
variables [comm_semiring R] [add_comm_monoid M] [module R M]
open_locale big_operators
lemma is_torsion_by_ideal_of_finite_of_is_torsion [module.finite R M] (hM : module.is_torsion R M) :
β I : ideal R, (I : set R) β© Rβ° β β
β§ module.is_torsion_by_set R M I :=
begin
cases (module.finite_def.mp infer_instance : (β€ : submodule R M).fg) with S h,
refine β¨β x in S, ideal.torsion_of R M x, _, _β©,
{ rw set.ne_empty_iff_nonempty,
refine β¨_, _, (β x in S, (@hM x).some : Rβ°).2β©,
rw [subtype.val_eq_coe, submonoid.coe_finset_prod],
apply ideal.prod_mem_prod,
exact Ξ» x _, (@hM x).some_spec },
{ rw [module.is_torsion_by_set_iff_torsion_by_set_eq_top, eq_top_iff, β h, span_le],
intros x hx, apply torsion_by_set_le_torsion_by_set_of_subset,
{ apply ideal.le_of_dvd, exact finset.dvd_prod_of_mem _ hx },
{ rw mem_torsion_by_set_iff, rintro β¨a, haβ©, exact ha } }
end
variables [no_zero_divisors R] [nontrivial R]
lemma coe_torsion_eq_annihilator_ne_bot :
(torsion R M : set M) = { x : M | (R β x).annihilator β β₯ } :=
begin
ext x, simp_rw [submodule.ne_bot_iff, mem_annihilator, mem_span_singleton],
exact β¨Ξ» β¨a, haxβ©, β¨a, Ξ» _ β¨b, hbβ©, by rw [β hb, smul_comm, β submonoid.smul_def, hax, smul_zero],
non_zero_divisors.coe_ne_zero _β©,
Ξ» β¨a, hax, haβ©, β¨β¨_, mem_non_zero_divisors_of_ne_zero haβ©, hax x β¨1, one_smul _ _β©β©β©
end
/-- A module over a domain has `no_zero_smul_divisors` iff its torsion submodule is trivial. -/
lemma no_zero_smul_divisors_iff_torsion_eq_bot :
no_zero_smul_divisors R M β torsion R M = β₯ :=
begin
split; intro h,
{ haveI : no_zero_smul_divisors R M := h,
rw eq_bot_iff, rintro x β¨a, haxβ©,
change (a : R) β’ x = 0 at hax,
cases eq_zero_or_eq_zero_of_smul_eq_zero hax with h0 h0,
{ exfalso, exact non_zero_divisors.coe_ne_zero a h0 }, { exact h0 } },
{ exact { eq_zero_or_eq_zero_of_smul_eq_zero := Ξ» a x hax, begin
by_cases ha : a = 0,
{ left, exact ha },
{ right, rw [β mem_bot _, β h],
exact β¨β¨a, mem_non_zero_divisors_of_ne_zero haβ©, haxβ© }
end } }
end
end torsion
namespace quotient_torsion
variables [comm_ring R] [add_comm_group M] [module R M]
/-- Quotienting by the torsion submodule gives a torsion-free module. -/
@[simp] lemma torsion_eq_bot : torsion R (M β§Έ torsion R M) = β₯ :=
eq_bot_iff.mpr $ Ξ» z, quotient.induction_on' z $ Ξ» x β¨a, haxβ©,
begin
rw [quotient.mk'_eq_mk, β quotient.mk_smul, quotient.mk_eq_zero] at hax,
rw [mem_bot, quotient.mk'_eq_mk, quotient.mk_eq_zero],
cases hax with b h,
exact β¨b * a, (mul_smul _ _ _).trans hβ©
end
instance no_zero_smul_divisors [is_domain R] : no_zero_smul_divisors R (M β§Έ torsion R M) :=
no_zero_smul_divisors_iff_torsion_eq_bot.mpr torsion_eq_bot
end quotient_torsion
section p_torsion
open module
section
variables [monoid R] [add_comm_monoid M] [distrib_mul_action R M]
lemma is_torsion'_powers_iff (p : R) :
is_torsion' M (submonoid.powers p) β β x : M, β n : β, p ^ n β’ x = 0 :=
β¨Ξ» h x, let β¨β¨a, β¨n, rflβ©β©, hxβ© := @h x in β¨n, hxβ©,
Ξ» h x, let β¨n, hnβ© := h x in β¨β¨_, β¨n, rflβ©β©, hnβ©β©
/--In a `p ^ β`-torsion module (that is, a module where all elements are cancelled by scalar
multiplication by some power of `p`), the smallest `n` such that `p ^ n β’ x = 0`.-/
def p_order {p : R} (hM : is_torsion' M $ submonoid.powers p) (x : M)
[Ξ n : β, decidable (p ^ n β’ x = 0)] :=
nat.find $ (is_torsion'_powers_iff p).mp hM x
@[simp] lemma pow_p_order_smul {p : R} (hM : is_torsion' M $ submonoid.powers p) (x : M)
[Ξ n : β, decidable (p ^ n β’ x = 0)] : p ^ p_order hM x β’ x = 0 :=
nat.find_spec $ (is_torsion'_powers_iff p).mp hM x
end
variables [comm_semiring R] [add_comm_monoid M] [module R M] [Ξ x : M, decidable (x = 0)]
lemma exists_is_torsion_by {p : R} (hM : is_torsion' M $ submonoid.powers p)
(d : β) (hd : d β 0) (s : fin d β M) (hs : span R (set.range s) = β€) :
β j : fin d, module.is_torsion_by R M (p ^ p_order hM (s j)) :=
begin
let oj := list.argmax (Ξ» i, p_order hM $ s i) (list.fin_range d),
have hoj : oj.is_some := (option.ne_none_iff_is_some.mp $
Ξ» eq_none, hd $ list.fin_range_eq_nil.mp $ list.argmax_eq_none.mp eq_none),
use option.get hoj,
rw [is_torsion_by_iff_torsion_by_eq_top, eq_top_iff, β hs, submodule.span_le,
set.range_subset_iff], intro i, change _ β’ _ = _,
have : p_order hM (s i) β€ p_order hM (s $ option.get hoj) :=
list.le_of_mem_argmax (list.mem_fin_range i) (option.get_mem hoj),
rw [β nat.sub_add_cancel this, pow_add, mul_smul, pow_p_order_smul, smul_zero]
end
end p_torsion
end submodule
namespace ideal.quotient
open submodule
lemma torsion_by_eq_span_singleton {R : Type*} [comm_ring R] (a b : R) (ha : a β Rβ°) :
torsion_by R (R β§Έ R β a * b) a = R β (mk _ b) :=
begin
ext x, rw [mem_torsion_by_iff, mem_span_singleton],
obtain β¨x, rflβ© := mk_surjective x, split; intro h,
{ rw [β mk_eq_mk, β quotient.mk_smul, quotient.mk_eq_zero, mem_span_singleton] at h,
obtain β¨c, hβ© := h, rw [smul_eq_mul, smul_eq_mul, mul_comm, mul_assoc,
mul_cancel_left_mem_non_zero_divisor ha, mul_comm] at h,
use c, rw [β h, β mk_eq_mk, β quotient.mk_smul, smul_eq_mul, mk_eq_mk] },
{ obtain β¨c, hβ© := h,
rw [β h, smul_comm, β mk_eq_mk, β quotient.mk_smul,
(quotient.mk_eq_zero _).mpr $ mem_span_singleton_self _, smul_zero] }
end
end ideal.quotient
namespace add_monoid
theorem is_torsion_iff_is_torsion_nat [add_comm_monoid M] :
add_monoid.is_torsion M β module.is_torsion β M :=
begin
refine β¨Ξ» h x, _, Ξ» h x, _β©,
{ obtain β¨n, h0, hnβ© := (is_of_fin_add_order_iff_nsmul_eq_zero x).mp (h x),
exact β¨β¨n, mem_non_zero_divisors_of_ne_zero $ ne_of_gt h0β©, hnβ© },
{ rw is_of_fin_add_order_iff_nsmul_eq_zero,
obtain β¨n, hnβ© := @h x,
refine β¨n, nat.pos_of_ne_zero (non_zero_divisors.coe_ne_zero _), hnβ© }
end
theorem is_torsion_iff_is_torsion_int [add_comm_group M] :
add_monoid.is_torsion M β module.is_torsion β€ M :=
begin
refine β¨Ξ» h x, _, Ξ» h x, _β©,
{ obtain β¨n, h0, hnβ© := (is_of_fin_add_order_iff_nsmul_eq_zero x).mp (h x),
exact β¨β¨n, mem_non_zero_divisors_of_ne_zero $ ne_of_gt $ int.coe_nat_pos.mpr h0β©,
(coe_nat_zsmul _ _).trans hnβ© },
{ rw is_of_fin_add_order_iff_nsmul_eq_zero,
obtain β¨n, hnβ© := @h x,
exact exists_nsmul_eq_zero_of_zsmul_eq_zero (non_zero_divisors.coe_ne_zero n) hn }
end
end add_monoid
|
b3a4fedadff9a3f4d5f4d0f9bae96247ea03bf13 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/topology/category/UniformSpace.lean | c36c99337f26bf7ff0f6bc4e71a5aaa9315b6b68 | [
"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 | 6,986 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Patrick Massot, Scott Morrison
-/
import category_theory.monad.limits
import topology.uniform_space.completion
import topology.category.Top.basic
/-!
# The category of uniform spaces
We construct the category of uniform spaces, show that the complete separated uniform spaces
form a reflective subcategory, and hence possess all limits that uniform spaces do.
TODO: show that uniform spaces actually have all limits!
-/
universes u
open category_theory
/-- A (bundled) uniform space. -/
def UniformSpace : Type (u+1) := bundled uniform_space
namespace UniformSpace
/-- The information required to build morphisms for `UniformSpace`. -/
instance : unbundled_hom @uniform_continuous :=
β¨@uniform_continuous_id, @uniform_continuous.compβ©
attribute [derive [has_coe_to_sort, large_category, concrete_category]] UniformSpace
instance (x : UniformSpace) : uniform_space x := x.str
/-- Construct a bundled `UniformSpace` from the underlying type and the typeclass. -/
def of (Ξ± : Type u) [uniform_space Ξ±] : UniformSpace := β¨Ξ±β©
instance : inhabited UniformSpace := β¨UniformSpace.of emptyβ©
@[simp] lemma coe_of (X : Type u) [uniform_space X] : (of X : Type u) = X := rfl
instance (X Y : UniformSpace) : has_coe_to_fun (X βΆ Y) :=
{ F := Ξ» _, X β Y, coe := category_theory.functor.map (forget UniformSpace) }
@[simp] lemma coe_comp {X Y Z : UniformSpace} (f : X βΆ Y) (g : Y βΆ Z) :
(f β« g : X β Z) = g β f := rfl
@[simp] lemma coe_id (X : UniformSpace) : (π X : X β X) = id := rfl
@[simp] lemma coe_mk {X Y : UniformSpace} (f : X β Y) (hf : uniform_continuous f) :
((β¨f, hfβ© : X βΆ Y) : X β Y) = f := rfl
lemma hom_ext {X Y : UniformSpace} {f g : X βΆ Y} : (f : X β Y) = g β f = g := subtype.eq
/-- The forgetful functor from uniform spaces to topological spaces. -/
instance has_forget_to_Top : has_forgetβ UniformSpace.{u} Top.{u} :=
{ forgetβ :=
{ obj := Ξ» X, Top.of X,
map := Ξ» X Y f, { to_fun := f,
continuous_to_fun := uniform_continuous.continuous f.property }, }, }
end UniformSpace
/-- A (bundled) complete separated uniform space. -/
structure CpltSepUniformSpace :=
(Ξ± : Type u)
[is_uniform_space : uniform_space Ξ±]
[is_complete_space : complete_space Ξ±]
[is_separated : separated_space Ξ±]
namespace CpltSepUniformSpace
instance : has_coe_to_sort CpltSepUniformSpace :=
{ S := Type u, coe := CpltSepUniformSpace.Ξ± }
attribute [instance] is_uniform_space is_complete_space is_separated
def to_UniformSpace (X : CpltSepUniformSpace) : UniformSpace :=
UniformSpace.of X
instance complete_space (X : CpltSepUniformSpace) : complete_space ((to_UniformSpace X).Ξ±) :=
CpltSepUniformSpace.is_complete_space X
instance separated_space (X : CpltSepUniformSpace) : separated_space ((to_UniformSpace X).Ξ±) :=
CpltSepUniformSpace.is_separated X
/-- Construct a bundled `UniformSpace` from the underlying type and the appropriate typeclasses. -/
def of (X : Type u) [uniform_space X] [complete_space X] [separated_space X] :
CpltSepUniformSpace := β¨Xβ©
@[simp] lemma coe_of (X : Type u) [uniform_space X] [complete_space X] [separated_space X] :
(of X : Type u) = X := rfl
instance : inhabited CpltSepUniformSpace :=
begin
haveI : separated_space empty := separated_iff_t2.mpr (by apply_instance),
exact β¨CpltSepUniformSpace.of emptyβ©
end
/-- The category instance on `CpltSepUniformSpace`. -/
instance category : large_category CpltSepUniformSpace :=
induced_category.category to_UniformSpace
/-- The concrete category instance on `CpltSepUniformSpace`. -/
instance concrete_category : concrete_category CpltSepUniformSpace :=
induced_category.concrete_category to_UniformSpace
instance has_forget_to_UniformSpace : has_forgetβ CpltSepUniformSpace UniformSpace :=
induced_category.has_forgetβ to_UniformSpace
end CpltSepUniformSpace
namespace UniformSpace
open uniform_space
open CpltSepUniformSpace
/-- The functor turning uniform spaces into complete separated uniform spaces. -/
noncomputable def completion_functor : UniformSpace β₯€ CpltSepUniformSpace :=
{ obj := Ξ» X, CpltSepUniformSpace.of (completion X),
map := Ξ» X Y f, β¨completion.map f.1, completion.uniform_continuous_mapβ©,
map_id' := Ξ» X, subtype.eq completion.map_id,
map_comp' := Ξ» X Y Z f g, subtype.eq (completion.map_comp g.property f.property).symm, }.
/-- The inclusion of a uniform space into its completion. -/
def completion_hom (X : UniformSpace) :
X βΆ (forgetβ CpltSepUniformSpace UniformSpace).obj (completion_functor.obj X) :=
{ val := (coe : X β completion X),
property := completion.uniform_continuous_coe X }
@[simp] lemma completion_hom_val (X : UniformSpace) (x) :
(completion_hom X) x = (x : completion X) := rfl
/-- The mate of a morphism from a `UniformSpace` to a `CpltSepUniformSpace`. -/
noncomputable def extension_hom {X : UniformSpace} {Y : CpltSepUniformSpace}
(f : X βΆ (forgetβ CpltSepUniformSpace UniformSpace).obj Y) :
completion_functor.obj X βΆ Y :=
{ val := completion.extension f,
property := completion.uniform_continuous_extension }
@[simp] lemma extension_hom_val {X : UniformSpace} {Y : CpltSepUniformSpace}
(f : X βΆ (forgetβ _ _).obj Y) (x) :
(extension_hom f) x = completion.extension f x := rfl.
@[simp] lemma extension_comp_coe {X : UniformSpace} {Y : CpltSepUniformSpace}
(f : to_UniformSpace (CpltSepUniformSpace.of (completion X)) βΆ to_UniformSpace Y) :
extension_hom (completion_hom X β« f) = f :=
by { apply subtype.eq, funext x, exact congr_fun (completion.extension_comp_coe f.property) x }
/-- The completion functor is left adjoint to the forgetful functor. -/
noncomputable def adj : completion_functor β£ forgetβ CpltSepUniformSpace UniformSpace :=
adjunction.mk_of_hom_equiv
{ hom_equiv := Ξ» X Y,
{ to_fun := Ξ» f, completion_hom X β« f,
inv_fun := Ξ» f, extension_hom f,
left_inv := Ξ» f, by { dsimp, erw extension_comp_coe },
right_inv := Ξ» f,
begin
apply subtype.eq, funext x, cases f,
exact @completion.extension_coe _ _ _ _ _ (CpltSepUniformSpace.separated_space _) f_property _
end },
hom_equiv_naturality_left_symm' := Ξ» X X' Y f g,
begin
apply hom_ext, funext x, dsimp,
erw [coe_comp, βcompletion.extension_map],
refl, exact g.property, exact f.property,
end }
noncomputable instance : is_right_adjoint (forgetβ CpltSepUniformSpace UniformSpace) :=
β¨completion_functor, adjβ©
noncomputable instance : reflective (forgetβ CpltSepUniformSpace UniformSpace) := {}
open category_theory.limits
-- TODO Once someone defines `has_limits UniformSpace`, turn this into an instance.
example [has_limits.{u} UniformSpace.{u}] : has_limits.{u} CpltSepUniformSpace.{u} :=
has_limits_of_reflective $ forgetβ CpltSepUniformSpace UniformSpace.{u}
end UniformSpace
|
5f082614c35d5b298edc2492b3253b2d638cb622 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/set_theory/lists.lean | 29619cc8e300acdae60cd5d1c5df3a8efb4aac18 | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 11,852 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
A computable model of hereditarily finite sets with atoms
(ZFA without infinity). This is useful for calculations in naive
set theory.
-/
import tactic.interactive data.list.basic data.sigma
variables {Ξ± : Type*}
@[derive decidable_eq]
inductive {u} lists' (Ξ± : Type u) : bool β Type u
| atom : Ξ± β lists' ff
| nil : lists' tt
| cons' {b} : lists' b β lists' tt β lists' tt
def lists (Ξ± : Type*) := Ξ£ b, lists' Ξ± b
namespace lists'
instance [inhabited Ξ±] : β b, inhabited (lists' Ξ± b)
| tt := β¨nilβ©
| ff := β¨atom (default _)β©
def cons : lists Ξ± β lists' Ξ± tt β lists' Ξ± tt
| β¨b, aβ© l := cons' a l
@[simp] def to_list : β {b}, lists' Ξ± b β list (lists Ξ±)
| _ (atom a) := []
| _ nil := []
| _ (cons' a l) := β¨_, aβ© :: l.to_list
@[simp] theorem to_list_cons (a : lists Ξ±) (l) :
to_list (cons a l) = a :: l.to_list :=
by cases a; simp [cons]
@[simp] def of_list : list (lists Ξ±) β lists' Ξ± tt
| [] := nil
| (a :: l) := cons a (of_list l)
@[simp] theorem to_of_list (l : list (lists Ξ±)) : to_list (of_list l) = l :=
by induction l; simp *
@[simp] theorem of_to_list : β (l : lists' Ξ± tt), of_list (to_list l) = l :=
suffices β b (h : tt = b) (l : lists' Ξ± b),
let l' : lists' Ξ± tt := by rw h; exact l in
of_list (to_list l') = l', from this _ rfl,
Ξ» b h l, begin
induction l, {cases h}, {exact rfl},
case lists'.cons' : b a l IHβ IHβ {
intro, change l' with cons' a l,
simpa [cons] using IHβ rfl }
end
end lists'
mutual inductive lists.equiv, lists'.subset
with lists.equiv : lists Ξ± β lists Ξ± β Prop
| refl (l) : lists.equiv l l
| antisymm {lβ lβ : lists' Ξ± tt} :
lists'.subset lβ lβ β lists'.subset lβ lβ β lists.equiv β¨_, lββ© β¨_, lββ©
with lists'.subset : lists' Ξ± tt β lists' Ξ± tt β Prop
| nil {l} : lists'.subset lists'.nil l
| cons {a a' l l'} : lists.equiv a a' β a' β lists'.to_list l' β
lists'.subset l l' β lists'.subset (lists'.cons a l) l'
local infix ~ := equiv
namespace lists'
instance : has_subset (lists' Ξ± tt) := β¨lists'.subsetβ©
instance {b} : has_mem (lists Ξ±) (lists' Ξ± b) :=
β¨Ξ» a l, β a' β l.to_list, a ~ a'β©
theorem mem_def {b a} {l : lists' Ξ± b} :
a β l β β a' β l.to_list, a ~ a' := iff.rfl
@[simp] theorem mem_cons {a y l} : a β @cons Ξ± y l β a ~ y β¨ a β l :=
by simp [mem_def, or_and_distrib_right, exists_or_distrib]
theorem cons_subset {a} {lβ lβ : lists' Ξ± tt} :
lists'.cons a lβ β lβ β a β lβ β§ lβ β lβ :=
begin
refine β¨Ξ» h, _, Ξ» β¨β¨a', m, eβ©, sβ©, subset.cons e m sβ©,
generalize_hyp h' : lists'.cons a lβ = lβ' at h,
cases h with l a' a'' l l' e m s, {cases a, cases h'},
cases a, cases a', cases h', exact β¨β¨_, m, eβ©, sβ©
end
theorem of_list_subset {lβ lβ : list (lists Ξ±)} (h : lβ β lβ) :
lists'.of_list lβ β lists'.of_list lβ :=
begin
induction lβ, {exact subset.nil},
refine subset.cons (equiv.refl _) _ (lβ_ih (list.subset_of_cons_subset h)),
simp at h, simp [h]
end
@[refl] theorem subset.refl {l : lists' Ξ± tt} : l β l :=
by rw β lists'.of_to_list l; exact
of_list_subset (list.subset.refl _)
theorem subset_nil {l : lists' Ξ± tt} :
l β lists'.nil β l = lists'.nil :=
begin
rw β of_to_list l,
induction to_list l; intro h, {refl},
rcases cons_subset.1 h with β¨β¨_, β¨β©, _β©, _β©
end
theorem mem_of_subset' {a} {lβ lβ : lists' Ξ± tt}
(s : lβ β lβ) (h : a β lβ.to_list) : a β lβ :=
begin
induction s with _ a a' l l' e m s IH, {cases h},
simp at h, rcases h with rfl|h,
exacts [β¨_, m, eβ©, IH h]
end
theorem subset_def {lβ lβ : lists' Ξ± tt} :
lβ β lβ β β a β lβ.to_list, a β lβ :=
β¨Ξ» H a, mem_of_subset' H, Ξ» H, begin
rw β of_to_list lβ,
revert H, induction to_list lβ; intro,
{ exact subset.nil },
{ simp at H, exact cons_subset.2 β¨H.1, ih H.2β© }
endβ©
end lists'
namespace lists
@[pattern] def atom (a : Ξ±) : lists Ξ± := β¨_, lists'.atom aβ©
@[pattern] def of' (l : lists' Ξ± tt) : lists Ξ± := β¨_, lβ©
@[simp] def to_list : lists Ξ± β list (lists Ξ±)
| β¨b, lβ© := l.to_list
def is_list (l : lists Ξ±) : Prop := l.1
def of_list (l : list (lists Ξ±)) : lists Ξ± := of' (lists'.of_list l)
theorem is_list_to_list (l : list (lists Ξ±)) : is_list (of_list l) :=
eq.refl _
theorem to_of_list (l : list (lists Ξ±)) : to_list (of_list l) = l :=
by simp [of_list, of']
theorem of_to_list : β {l : lists Ξ±}, is_list l β of_list (to_list l) = l
| β¨tt, lβ© _ := by simp [of_list, of']
instance : inhabited (lists Ξ±) :=
β¨of' lists'.nilβ©
instance [decidable_eq Ξ±] : decidable_eq (lists Ξ±) :=
by unfold lists; apply_instance
instance [has_sizeof Ξ±] : has_sizeof (lists Ξ±) :=
by unfold lists; apply_instance
def induction_mut (C : lists Ξ± β Sort*) (D : lists' Ξ± tt β Sort*)
(C0 : β a, C (atom a)) (C1 : β l, D l β C (of' l))
(D0 : D lists'.nil) (D1 : β a l, C a β D l β D (lists'.cons a l)) :
pprod (β l, C l) (β l, D l) :=
begin
suffices : β {b} (l : lists' Ξ± b),
pprod (C β¨_, lβ©) (match b, l with
| tt, l := D l
| ff, l := punit
end),
{ exact β¨Ξ» β¨b, lβ©, (this _).1, Ξ» l, (this l).2β© },
intros, induction l with a b a l IHβ IHβ,
{ exact β¨C0 _, β¨β©β© },
{ exact β¨C1 _ D0, D0β© },
{ suffices, {exact β¨C1 _ this, thisβ©},
exact D1 β¨_, _β© _ IHβ.1 IHβ.2 }
end
def mem (a : lists Ξ±) : lists Ξ± β Prop
| β¨ff, lβ© := false
| β¨tt, lβ© := a β l
instance : has_mem (lists Ξ±) (lists Ξ±) := β¨memβ©
theorem is_list_of_mem {a : lists Ξ±} : β {l : lists Ξ±}, a β l β is_list l
| β¨_, lists'.nilβ© _ := rfl
| β¨_, lists'.cons' _ _β© _ := rfl
theorem equiv.antisymm_iff {lβ lβ : lists' Ξ± tt} :
of' lβ ~ of' lβ β lβ β lβ β§ lβ β lβ :=
begin
refine β¨Ξ» h, _, Ξ» β¨hβ, hββ©, equiv.antisymm hβ hββ©,
cases h with _ _ _ hβ hβ,
{ simp [lists'.subset.refl] }, { exact β¨hβ, hββ© }
end
attribute [refl] equiv.refl
theorem equiv_atom {a} {l : lists Ξ±} : atom a ~ l β atom a = l :=
β¨Ξ» h, by cases h; refl, Ξ» h, h βΈ equiv.refl _β©
theorem equiv.symm {lβ lβ : lists Ξ±} (h : lβ ~ lβ) : lβ ~ lβ :=
by cases h with _ _ _ hβ hβ; [refl, exact equiv.antisymm hβ hβ]
theorem equiv.trans : β {lβ lβ lβ : lists Ξ±}, lβ ~ lβ β lβ ~ lβ β lβ ~ lβ :=
begin
let trans := Ξ» (lβ : lists Ξ±), β β¦lβ lββ¦, lβ ~ lβ β lβ ~ lβ β lβ ~ lβ,
suffices : pprod (β lβ, trans lβ)
(β (l : lists' Ξ± tt) (l' β l.to_list), trans l'), {exact this.1},
apply induction_mut,
{ intros a lβ lβ hβ hβ,
rwa β equiv_atom.1 hβ at hβ },
{ intros lβ IH lβ lβ hβ hβ,
cases hβ with _ _ lβ, {exact hβ},
cases hβ with _ _ lβ, {exact hβ},
cases equiv.antisymm_iff.1 hβ with hlβ hrβ,
cases equiv.antisymm_iff.1 hβ with hlβ hrβ,
apply equiv.antisymm_iff.2; split; apply lists'.subset_def.2,
{ intros aβ mβ,
rcases lists'.mem_of_subset' hlβ mβ with β¨aβ, mβ, eβββ©,
rcases lists'.mem_of_subset' hlβ mβ with β¨aβ, mβ, eβββ©,
exact β¨aβ, mβ, IH _ mβ eββ eβββ© },
{ intros aβ mβ,
rcases lists'.mem_of_subset' hrβ mβ with β¨aβ, mβ, eβββ©,
rcases lists'.mem_of_subset' hrβ mβ with β¨aβ, mβ, eβββ©,
exact β¨aβ, mβ, (IH _ mβ eββ.symm eββ.symm).symmβ© } },
{ rintro _ β¨β© },
{ intros a l IHβ IHβ, simpa [IHβ] using IHβ }
end
instance : setoid (lists Ξ±) :=
β¨(~), equiv.refl, @equiv.symm _, @equiv.trans _β©
section decidable
@[simp] def equiv.decidable_meas :
(psum (Ξ£' (lβ : lists Ξ±), lists Ξ±) $
psum (Ξ£' (lβ : lists' Ξ± tt), lists' Ξ± tt)
Ξ£' (a : lists Ξ±), lists' Ξ± tt) β β
| (psum.inl β¨lβ, lββ©) := sizeof lβ + sizeof lβ
| (psum.inr $ psum.inl β¨lβ, lββ©) := sizeof lβ + sizeof lβ
| (psum.inr $ psum.inr β¨lβ, lββ©) := sizeof lβ + sizeof lβ
open well_founded_tactics
theorem sizeof_pos {b} (l : lists' Ξ± b) : 0 < sizeof l :=
by cases l; unfold_sizeof; trivial_nat_lt
theorem lt_sizeof_cons' {b} (a : lists' Ξ± b) (l) :
sizeof (β¨b, aβ© : lists Ξ±) < sizeof (lists'.cons' a l) :=
by {unfold_sizeof, apply sizeof_pos}
@[instance] mutual def equiv.decidable, subset.decidable, mem.decidable [decidable_eq Ξ±]
with equiv.decidable : β lβ lβ : lists Ξ±, decidable (lβ ~ lβ)
| β¨ff, lββ© β¨ff, lββ© := decidable_of_iff' (lβ = lβ) $
by cases lβ; refine equiv_atom.trans (by simp [atom])
| β¨ff, lββ© β¨tt, lββ© := is_false $ by rintro β¨β©
| β¨tt, lββ© β¨ff, lββ© := is_false $ by rintro β¨β©
| β¨tt, lββ© β¨tt, lββ© := begin
haveI :=
have sizeof lβ + sizeof lβ <
sizeof (β¨tt, lββ© : lists Ξ±) + sizeof (β¨tt, lββ© : lists Ξ±),
by default_dec_tac,
subset.decidable lβ lβ,
haveI :=
have sizeof lβ + sizeof lβ <
sizeof (β¨tt, lββ© : lists Ξ±) + sizeof (β¨tt, lββ© : lists Ξ±),
by default_dec_tac,
subset.decidable lβ lβ,
exact decidable_of_iff' _ equiv.antisymm_iff,
end
with subset.decidable : β lβ lβ : lists' Ξ± tt, decidable (lβ β lβ)
| lists'.nil lβ := is_true subset.nil
| (@lists'.cons' _ b a lβ) lβ := begin
haveI :=
have sizeof (β¨b, aβ© : lists Ξ±) + sizeof lβ <
sizeof (lists'.cons' a lβ) + sizeof lβ,
from add_lt_add_right (lt_sizeof_cons' _ _) _,
mem.decidable β¨b, aβ© lβ,
haveI :=
have sizeof lβ + sizeof lβ <
sizeof (lists'.cons' a lβ) + sizeof lβ,
by default_dec_tac,
subset.decidable lβ lβ,
exact decidable_of_iff' _ (@lists'.cons_subset _ β¨_, _β© _ _)
end
with mem.decidable : β (a : lists Ξ±) (l : lists' Ξ± tt), decidable (a β l)
| a lists'.nil := is_false $ by rintro β¨_, β¨β©, _β©
| a (lists'.cons' b lβ) := begin
haveI :=
have sizeof a + sizeof (β¨_, bβ© : lists Ξ±) <
sizeof a + sizeof (lists'.cons' b lβ),
from add_lt_add_left (lt_sizeof_cons' _ _) _,
equiv.decidable a β¨_, bβ©,
haveI :=
have sizeof a + sizeof lβ <
sizeof a + sizeof (lists'.cons' b lβ),
by default_dec_tac,
mem.decidable a lβ,
refine decidable_of_iff' (a ~ β¨_, bβ© β¨ a β lβ) _,
rw β lists'.mem_cons, refl
end
using_well_founded {
rel_tac := Ξ» _ _, `[exact β¨_, measure_wf equiv.decidable_measβ©],
dec_tac := `[assumption] }
end decidable
end lists
namespace lists'
theorem mem_equiv_left {l : lists' Ξ± tt} :
β {a a'}, a ~ a' β (a β l β a' β l) :=
suffices β {a a'}, a ~ a' β a β l β a' β l,
from Ξ» a a' e, β¨this e, this e.symmβ©,
Ξ» aβ aβ eβ β¨aβ, mβ, eββ©, β¨_, mβ, eβ.symm.trans eββ©
theorem mem_of_subset {a} {lβ lβ : lists' Ξ± tt}
(s : lβ β lβ) : a β lβ β a β lβ | β¨a', m, eβ© :=
(mem_equiv_left e).2 (mem_of_subset' s m)
theorem subset.trans {lβ lβ lβ : lists' Ξ± tt}
(hβ : lβ β lβ) (hβ : lβ β lβ) : lβ β lβ :=
subset_def.2 $ Ξ» aβ mβ, mem_of_subset hβ $ mem_of_subset' hβ mβ
end lists'
def finsets (Ξ± : Type*) := quotient (@lists.setoid Ξ±)
namespace finsets
instance : has_emptyc (finsets Ξ±) := β¨β¦lists.of' lists'.nilβ§β©
instance : inhabited (finsets Ξ±) := β¨β
β©
instance [decidable_eq Ξ±] : decidable_eq (finsets Ξ±) :=
by unfold finsets; apply_instance
end finsets
|
55cdf431e108b105845278b6c595ae03d3d32d5b | 92b1c7f0343a6a5cd36bc0f623a7490da3f1e0f3 | /src/stump/algorithm_measurable.lean | a3dc9376f6418b2166c3e242e93642ff0c712158 | [
"Apache-2.0"
] | permissive | jtristan/stump-learnable | 717453eb590af16e60c7d3806cc9e66492fab091 | aa3c089f41602efa08d31ef6b41e549456186d57 | refs/heads/master | 1,625,630,634,360 | 1,607,552,106,000 | 1,607,552,106,000 | 218,629,406 | 15 | 2 | null | null | null | null | UTF-8 | Lean | false | false | 3,294 | lean | /-
Copyright Β© 2019, Oracle and/or its affiliates. All rights reserved.
-/
import .algorithm_definition
import .setup_measurable
open set
namespace stump
variables (ΞΌ: probability_measure β) (target: β) (n: β)
@[simp]
lemma label_sample_measurable: β n: β, measurable (label_sample target n) :=
begin
intro,
apply measurable_map,
apply label_measurable,
end
@[simp]
lemma max_continuous: β n, continuous (max n) :=
begin
intros,
induction n,
{
unfold max,
apply continuous_id,
},
{
unfold max,
simp,
apply continuous_if; intros,
{
unfold rlt at H, simp at H,
have FOO := @frontier_lt_subset_eq nnreal (vec nnreal (nat.succ n_n)) _ _ _ _ (Ξ» x, max n_n x.snd) (Ξ» x, x.fst) _ (continuous_fst),
{
simp at FOO,
have BAR := mem_of_mem_of_subset H FOO, clear FOO,
rw mem_set_of_eq at BAR,
exact eq.symm BAR,
},
{
apply continuous.comp,
assumption,
apply continuous_snd,
},
},
{
apply continuous.comp,
apply continuous_fst,
apply continuous_id,
},
{
apply continuous.comp,
assumption,
apply continuous.comp,
apply continuous_snd,
apply continuous_id,
},
},
end
@[simp]
lemma max_is_measurable: is_measurable {v: vec β (nat.succ n) | rlt (max n v.snd) (v.fst)} :=
begin
dunfold vec,
unfold rlt,
simp,
apply is_measurable_of_continuous_vec,
{
apply continuous.comp,
apply max_continuous,
apply continuous_snd,
},
{
apply continuous_fst,
},
end
@[simp]
lemma max_measurable: β n, measurable (max n) :=
begin
intro n,
induction n,
{
unfold max,
apply measurable_id,
},
{
unfold max,
apply measurable.if,
unfold_coes, apply max_is_measurable,
apply measurable_fst,
apply measurable_id,
apply measurable.comp,
apply n_ih,
apply measurable_snd,
apply measurable_id,
}
end
@[simp]
lemma choose_measurable: measurable (choose n) :=
begin
unfold choose,
apply measurable.comp,
apply max_measurable,
unfold filter,
apply measurable_map,
apply measurable.if,
unfold_coes,
{
have PROD: {a: β Γ bool | a.snd = tt} = set.prod {x: β | true} {b: bool | b = tt},
{
rw ext_iff, intros,
rw mem_prod_eq,
repeat {rw mem_set_of_eq},
finish,
},
rw PROD,
apply is_measurable_set_prod,
{
rw β univ_def,
exact is_measurable.univ,
},
fsplit,
},
apply measurable_fst,
apply measurable_id,
apply measurable_const,
end
@[simp]
lemma is_measurable_vec_1:
β Ξ΅, is_measurable {v: vec (β Γ bool) n | error ΞΌ target (choose n v) > Ξ΅} :=
begin
intros,
have PREIM: {v: vec (β Γ bool) n | error ΞΌ target (choose n v) > Ξ΅} = (choose n) β»ΒΉ' {h: β | error ΞΌ target h > Ξ΅},
simp,
rw PREIM,
apply measurable.preimage; try {simp},
end
@[simp]
lemma is_measurable_vec_2:
β Ξ΅, is_measurable {v: vec (β Γ bool) n | error ΞΌ target (choose n v) β€ Ξ΅} :=
begin
intros,
have PREIM: {v: vec (β Γ bool) n | error ΞΌ target (choose n v) β€ Ξ΅} = (choose n) β»ΒΉ' {h: β | error ΞΌ target h β€ Ξ΅},
simp,
rw PREIM,
apply measurable.preimage; try {simp},
end
end stump |
f9c7f7d6c8ac38bf25b77e324ca8c8530683d416 | 9a0b1b3a653ea926b03d1495fef64da1d14b3174 | /tidy/rewrite_search/core/hook.lean | 99e39d9d55b2545c1149c0afb1fd2ebe82c7406a | [
"Apache-2.0"
] | permissive | khoek/mathlib-tidy | 8623b27b4e04e7d598164e7eaf248610d58f768b | 866afa6ab597c47f1b72e8fe2b82b97fff5b980f | refs/heads/master | 1,585,598,975,772 | 1,538,659,544,000 | 1,538,659,544,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,609 | lean | import tidy.lib.tactic
import tidy.rewrite_all_wrappers
import .shared
namespace tidy.rewrite_search
meta def rewrite_progress := mllist tactic rewrite
meta def progress_init (rs : list (expr Γ bool)) (exp : expr) (cfg : rewrite_all_cfg) (s : side) : tactic rewrite_progress := do
l β all_rewrites_mllist rs exp cfg,
l.map $ Ξ» t, β¨t.1, t.2.1, how.rewrite t.2.2.1 s t.2.2.2β©
meta def progress_next : rewrite_progress β tactic (rewrite_progress Γ option rewrite)
| mllist.nil := return (mllist.nil, none)
| (mllist.cons a l) := do r β l, return (r, some a)
meta def try_simp_rewrite (exp : expr) : tactic (option rewrite) := do
(do (simp_exp, simp_prf) β tactic.simp_expr exp,
return $ some β¨simp_exp, pure simp_prf, how.simpβ©)
<|> return none
-- FIXME I don't know how to extract a proof of equality from `simp_lemmas.dsimplify`
-- meta def try_dsimp_rewrite (exp : expr) : tactic (option rewrite) := do
-- (do dsimp_exp β tactic.dsimp_expr exp,
-- return $ some β¨dsimp_exp, ???, how.defeqβ©)
-- <|> return none
meta def discover_more_rewrites (rs : list (expr Γ bool)) (exp : expr) (cfg : rewrite_all_cfg) (s : side) (prog : option rewrite_progress) : tactic (option rewrite_progress Γ list rewrite) := do
(prog, head) β match prog with
| some prog := pure (prog, [])
| none := do
prog β progress_init rs exp cfg s,
sl β try_simp_rewrite exp,
pure (prog, sl.to_list)
end,
(prog, rw) β progress_next prog,
return (some prog, head.append rw.to_list)
end tidy.rewrite_search
|
e6ce23588de7ed4c0691ca1f2b01b1cbfff56f1e | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebraic_topology/dold_kan/decomposition.lean | fa1471a071589de0a5aa6d99beb2e4e4ec6b0288 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 5,411 | lean | /-
Copyright (c) 2022 JoΓ«l Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: JoΓ«l Riou
-/
import algebraic_topology.dold_kan.p_infty
/-!
# Decomposition of the Q endomorphisms
In this file, we obtain a lemma `decomposition_Q` which expresses
explicitly the projection `(Q q).f (n+1) : X _[n+1] βΆ X _[n+1]`
(`X : simplicial_object C` with `C` a preadditive category) as
a sum of terms which are postcompositions with degeneracies.
(TODO @joelriou: when `C` is abelian, define the degenerate
subcomplex of the alternating face map complex of `X` and show
that it is a complement to the normalized Moore complex.)
Then, we introduce an ad hoc structure `morph_components X n Z` which
can be used in order to define morphisms `X _[n+1] βΆ Z` using the
decomposition provided by `decomposition_Q`. This shall play a critical
role in the proof that the functor
`Nβ : simplicial_object C β₯€ karoubi (chain_complex C β))`
reflects isomorphisms.
-/
open category_theory category_theory.category category_theory.preadditive opposite
open_locale big_operators simplicial
noncomputable theory
namespace algebraic_topology
namespace dold_kan
variables {C : Type*} [category C] [preadditive C] {X X' : simplicial_object C}
/-- In each positive degree, this lemma decomposes the idempotent endomorphism
`Q q` as a sum of morphisms which are postcompositions with suitable degeneracies.
As `Q q` is the complement projection to `P q`, this implies that in the case of
simplicial abelian groups, any $(n+1)$-simplex $x$ can be decomposed as
$x = x' + \sum (i=0}^{q-1} Ο_{n-i}(y_i)$ where $x'$ is in the image of `P q` and
the $y_i$ are in degree $n$. -/
lemma decomposition_Q (n q : β) :
((Q q).f (n+1) : X _[n+1] βΆ X _[n+1]) =
β (i : fin (n+1)) in finset.filter (Ξ» i : fin(n+1), (i:β)<q) finset.univ,
(P i).f (n+1) β« X.Ξ΄ (i.rev).succ β« X.Ο i.rev :=
begin
induction q with q hq,
{ simp only [Q_eq_zero, homological_complex.zero_f_apply, nat.not_lt_zero,
finset.filter_false, finset.sum_empty], },
{ by_cases hqn : q+1 β€ n+1, swap,
{ rw [Q_is_eventually_constant (show n+1β€q, by linarith), hq],
congr,
ext,
have hx := x.is_lt,
simp only [nat.succ_eq_add_one],
split; intro h; linarith, },
{ cases nat.le.dest (nat.succ_le_succ_iff.mp hqn) with a ha,
rw [Q_eq, homological_complex.sub_f_apply, homological_complex.comp_f, hq],
symmetry,
conv_rhs { rw [sub_eq_add_neg, add_comm], },
let q' : fin (n+1) := β¨q, nat.succ_le_iff.mp hqnβ©,
convert finset.sum_insert ( _ : q' β _),
{ ext i,
simp only [finset.mem_insert, finset.mem_filter, finset.mem_univ, true_and,
nat.lt_succ_iff_lt_or_eq, fin.ext_iff],
tauto, },
{ have hnaq' : n = a+q := by linarith,
simpa only [fin.coe_mk, (higher_faces_vanish.of_P q n).comp_HΟ_eq hnaq',
q'.rev_eq hnaq', neg_neg], },
{ simp only [finset.mem_filter, fin.coe_mk, lt_self_iff_false,
and_false, not_false_iff], }, }, },
end
variable (X)
/-- The structure `morph_components` is an ad hoc structure that is used in
the proof that `Nβ : simplicial_object C β₯€ karoubi (chain_complex C β))`
reflects isomorphisms. The fields are the data that are needed in order to
construct a morphism `X _[n+1] βΆ Z` (see `Ο`) using the decomposition of the
identity given by `decomposition_Q n (n+1)`. -/
@[ext, nolint has_nonempty_instance]
structure morph_components (n : β) (Z : C) :=
(a : X _[n+1] βΆ Z)
(b : fin (n+1) β (X _[n] βΆ Z))
namespace morph_components
variables {X} {n : β} {Z Z' : C} (f : morph_components X n Z) (g : X' βΆ X) (h : Z βΆ Z')
/-- The morphism `X _[n+1] βΆ Z ` associated to `f : morph_components X n Z`. -/
def Ο {Z : C} (f : morph_components X n Z) : X _[n+1] βΆ Z :=
P_infty.f (n+1) β« f.a + β (i : fin (n+1)), (P i).f (n+1) β« X.Ξ΄ i.rev.succ β« f.b i.rev
variables (X n)
/-- the canonical `morph_components` whose associated morphism is the identity
(see `F_id`) thanks to `decomposition_Q n (n+1)` -/
@[simps]
def id : morph_components X n (X _[n+1]) :=
{ a := P_infty.f (n+1),
b := Ξ» i, X.Ο i, }
@[simp] lemma id_Ο : (id X n).Ο = π _ :=
begin
simp only [β P_add_Q_f (n+1) (n+1), Ο],
congr' 1,
{ simp only [id, P_infty_f, P_f_idem], },
{ convert (decomposition_Q n (n+1)).symm,
ext i,
simpa only [finset.mem_univ, finset.mem_filter, true_and, true_iff] using fin.is_lt i, },
end
variables {X n}
/-- A `morph_components` can be postcomposed with a morphism. -/
@[simps]
def post_comp : morph_components X n Z' :=
{ a := f.a β« h,
b := Ξ» i, f.b i β« h }
@[simp] lemma post_comp_Ο : (f.post_comp h).Ο = f.Ο β« h :=
begin
unfold Ο post_comp,
simp only [add_comp, sum_comp, assoc],
end
/-- A `morph_components` can be precomposed with a morphism of simplicial objects. -/
@[simps]
def pre_comp : morph_components X' n Z :=
{ a := g.app (op [n+1]) β« f.a,
b := Ξ» i, g.app (op [n]) β« f.b i }
@[simp] lemma pre_comp_Ο : (f.pre_comp g).Ο = g.app (op [n+1]) β« f.Ο :=
begin
unfold Ο pre_comp,
simp only [P_infty_f, comp_add],
congr' 1,
{ simp only [P_f_naturality_assoc], },
{ simp only [comp_sum, P_f_naturality_assoc, simplicial_object.Ξ΄_naturality_assoc], }
end
end morph_components
end dold_kan
end algebraic_topology
|
0cd56160bfe3b71622edbd0ca9686c68d14cda88 | 217bb195841a8be2d1b4edd2084d6b69ccd62f50 | /tests/compiler/array_test.lean | 770b8a6b6ba1789f5a7027e4599b962cc2c09635 | [
"Apache-2.0"
] | permissive | frank-lesser/lean4 | 717f56c9bacd5bf3a67542d2f5cea721d4743a30 | 79e2abe33f73162f773ea731265e456dbfe822f9 | refs/heads/master | 1,589,741,267,933 | 1,556,424,200,000 | 1,556,424,281,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 767 | lean | def foo (a : Array Nat) : Array Nat :=
let a := a.push 0 in
let a := a.push 1 in
let a := a.push 2 in
let a := a.push 3 in
a
def main : IO UInt32 :=
do
let a : Array Nat := Array.empty,
IO.println (toString a),
IO.println (toString a.sz),
let a := foo a,
IO.println (toString a),
let a := a.hmap (+10),
IO.println (toString a),
IO.println (toString a.sz),
let a1 := a.pop,
let a2 := a.push 100,
IO.println (toString a1),
IO.println (toString a2),
let a2 := a.pop,
IO.println a2,
IO.println $ (([1, 2, 3, 4].toArray).hmap (+2)).map toString,
IO.println $ ([1, 2, 3, 4].toArray.extract 1 3),
IO.println $ ([1, 2, 3, 4].toArray.extract 0 100),
IO.println $ ([1, 2, 3, 4].toArray.extract 1 1),
IO.println $ ([1, 2, 3, 4].toArray.extract 2 4),
pure 0
|
d721fc66b45c70f77a8dcfd23a9061fbe89e0e38 | b11468ab3abb22a54747a1a0e6ffff1005799c4d | /lean/src/minif2f_import.lean | 79a2d61d128adabf4ac74548c5d56d92bb79ef88 | [
"Apache-2.0",
"MIT"
] | permissive | atkirtland/miniF2F | ddefddc11469053c1d93fe6ffbe7924d1c06f2f6 | 1c4b8bffebdf052260d11d47a5ff96dc7d1fb8db | refs/heads/main | 1,693,440,222,185 | 1,633,522,781,000 | 1,633,522,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,828 | lean | import algebra.algebra.basic
import algebra.big_operators.basic
import algebra.floor
import algebra.group_power.basic
import algebra.quadratic_discriminant
import algebra.ring.basic
import analysis.asymptotics.asymptotic_equivalent
import analysis.mean_inequalities
import analysis.normed_space.basic
import analysis.inner_product_space.basic
import analysis.inner_product_space.euclidean_dist
import analysis.normed_space.pi_Lp
import analysis.special_functions.exp_log
import analysis.special_functions.pow
import analysis.special_functions.trigonometric.basic
import combinatorics.simple_graph.basic
import data.complex.basic
import data.complex.exponential
import data.equiv.basic
import data.finset.basic
import data.int.basic
import data.int.gcd
import data.int.modeq
import data.list.palindrome
import data.multiset.basic
import data.nat.basic
import data.nat.choose.basic
import data.nat.digits
import data.nat.factorial.basic
import data.nat.modeq
import data.nat.parity
import data.nat.prime
import data.pnat.basic
import data.polynomial
import data.polynomial.basic
import data.polynomial.eval
import data.rat.basic
import data.real.basic
import data.real.ennreal
import data.real.irrational
import data.real.nnreal
import data.real.sqrt
import data.sym.sym2
import data.zmod.basic
import geometry.euclidean.basic
import geometry.euclidean.circumcenter
import geometry.euclidean.monge_point
import geometry.euclidean.sphere
import init.data.nat.gcd
import linear_algebra.affine_space.affine_map
import linear_algebra.affine_space.independent
import linear_algebra.affine_space.ordered
import linear_algebra.finite_dimensional
import measure_theory.integral.interval_integral
import number_theory.arithmetic_function
import order.bounds
import order.filter.basic
import topology.basic
import topology.instances.nnreal
|
124c1f12fabc179daedc9453605af72992fbf9d0 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/closed/monoidal.lean | 433aec0d14dce321188d99f604afc0fbbce6b0fa | [
"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 | 8,848 | lean | /-
Copyright (c) 2020 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.monoidal.functor
import category_theory.adjunction.limits
import category_theory.adjunction.mates
import category_theory.functor.inv_isos
/-!
# Closed monoidal categories
Define (right) closed objects and (right) closed monoidal categories.
## TODO
Some of the theorems proved about cartesian closed categories
should be generalised and moved to this file.
-/
universes v u uβ vβ
namespace category_theory
open category monoidal_category
/-- An object `X` is (right) closed if `(X β -)` is a left adjoint. -/
-- Note that this class carries a particular choice of right adjoint,
-- (which is only unique up to isomorphism),
-- not merely the existence of such, and
-- so definitional properties of instances may be important.
class closed {C : Type u} [category.{v} C] [monoidal_category.{v} C] (X : C) :=
(is_adj : is_left_adjoint (tensor_left X))
/-- A monoidal category `C` is (right) monoidal closed if every object is (right) closed. -/
class monoidal_closed (C : Type u) [category.{v} C] [monoidal_category.{v} C] :=
(closed' : Ξ (X : C), closed X)
attribute [instance, priority 100] monoidal_closed.closed'
variables {C : Type u} [category.{v} C] [monoidal_category.{v} C]
/--
If `X` and `Y` are closed then `X β Y` is.
This isn't an instance because it's not usually how we want to construct internal homs,
we'll usually prove all objects are closed uniformly.
-/
def tensor_closed {X Y : C}
(hX : closed X) (hY : closed Y) : closed (X β Y) :=
{ is_adj :=
begin
haveI := hX.is_adj,
haveI := hY.is_adj,
exact adjunction.left_adjoint_of_nat_iso (monoidal_category.tensor_left_tensor _ _).symm
end }
/--
The unit object is always closed.
This isn't an instance because most of the time we'll prove closedness for all objects at once,
rather than just for this one.
-/
def unit_closed : closed (π_ C) :=
{ is_adj :=
{ right := π C,
adj := adjunction.mk_of_hom_equiv
{ hom_equiv := Ξ» X _,
{ to_fun := Ξ» a, (left_unitor X).inv β« a,
inv_fun := Ξ» a, (left_unitor X).hom β« a,
left_inv := by tidy,
right_inv := by tidy },
hom_equiv_naturality_left_symm' := Ξ» X' X Y f g,
by { dsimp, rw left_unitor_naturality_assoc } } } }
variables (A B : C) {X X' Y Y' Z : C}
variables [closed A]
/--
This is the internal hom `A βΆ[C] -`.
-/
def ihom : C β₯€ C :=
(@closed.is_adj _ _ _ A _).right
namespace ihom
/-- The adjunction between `A β -` and `A βΉ -`. -/
def adjunction : tensor_left A β£ ihom A :=
closed.is_adj.adj
/-- The evaluation natural transformation. -/
def ev : ihom A β tensor_left A βΆ π C :=
(ihom.adjunction A).counit
/-- The coevaluation natural transformation. -/
def coev : π C βΆ tensor_left A β ihom A :=
(ihom.adjunction A).unit
@[simp] lemma ihom_adjunction_counit : (ihom.adjunction A).counit = ev A := rfl
@[simp] lemma ihom_adjunction_unit : (ihom.adjunction A).unit = coev A := rfl
@[simp, reassoc]
lemma ev_naturality {X Y : C} (f : X βΆ Y) :
((π A) β ((ihom A).map f)) β« (ev A).app Y = (ev A).app X β« f :=
(ev A).naturality f
@[simp, reassoc]
lemma coev_naturality {X Y : C} (f : X βΆ Y) :
f β« (coev A).app Y = (coev A).app X β« (ihom A).map ((π A) β f) :=
(coev A).naturality f
notation (name := ihom) A ` βΆ[`C`] ` B:10 := (@ihom C _ _ A _).obj B
@[simp, reassoc] lemma ev_coev :
((π A) β ((coev A).app B)) β« (ev A).app (A β B) = π (A β B) :=
adjunction.left_triangle_components (ihom.adjunction A)
@[simp, reassoc] lemma coev_ev :
(coev A).app (A βΆ[C] B) β« (ihom A).map ((ev A).app B) = π (A βΆ[C] B) :=
adjunction.right_triangle_components (ihom.adjunction A)
end ihom
open category_theory.limits
instance : preserves_colimits (tensor_left A) :=
(ihom.adjunction A).left_adjoint_preserves_colimits
variables {A}
-- Wrap these in a namespace so we don't clash with the core versions.
namespace monoidal_closed
/-- Currying in a monoidal closed category. -/
def curry : (A β Y βΆ X) β (Y βΆ (A βΆ[C] X)) :=
(ihom.adjunction A).hom_equiv _ _
/-- Uncurrying in a monoidal closed category. -/
def uncurry : (Y βΆ (A βΆ[C] X)) β (A β Y βΆ X) :=
((ihom.adjunction A).hom_equiv _ _).symm
@[simp] lemma hom_equiv_apply_eq (f : A β Y βΆ X) :
(ihom.adjunction A).hom_equiv _ _ f = curry f := rfl
@[simp] lemma hom_equiv_symm_apply_eq (f : Y βΆ (A βΆ[C] X)) :
((ihom.adjunction A).hom_equiv _ _).symm f = uncurry f := rfl
@[reassoc]
lemma curry_natural_left (f : X βΆ X') (g : A β X' βΆ Y) :
curry (((π _) β f) β« g) = f β« curry g :=
adjunction.hom_equiv_naturality_left _ _ _
@[reassoc]
lemma curry_natural_right (f : A β X βΆ Y) (g : Y βΆ Y') :
curry (f β« g) = curry f β« (ihom _).map g :=
adjunction.hom_equiv_naturality_right _ _ _
@[reassoc]
lemma uncurry_natural_right (f : X βΆ (A βΆ[C] Y)) (g : Y βΆ Y') :
uncurry (f β« (ihom _).map g) = uncurry f β« g :=
adjunction.hom_equiv_naturality_right_symm _ _ _
@[reassoc]
lemma uncurry_natural_left (f : X βΆ X') (g : X' βΆ (A βΆ[C] Y)) :
uncurry (f β« g) = ((π _) β f) β« uncurry g :=
adjunction.hom_equiv_naturality_left_symm _ _ _
@[simp]
lemma uncurry_curry (f : A β X βΆ Y) : uncurry (curry f) = f :=
(closed.is_adj.adj.hom_equiv _ _).left_inv f
@[simp]
lemma curry_uncurry (f : X βΆ (A βΆ[C] Y)) : curry (uncurry f) = f :=
(closed.is_adj.adj.hom_equiv _ _).right_inv f
lemma curry_eq_iff (f : A β Y βΆ X) (g : Y βΆ (A βΆ[C] X)) :
curry f = g β f = uncurry g :=
adjunction.hom_equiv_apply_eq _ f g
lemma eq_curry_iff (f : A β Y βΆ X) (g : Y βΆ (A βΆ[C] X)) :
g = curry f β uncurry g = f :=
adjunction.eq_hom_equiv_apply _ f g
-- I don't think these two should be simp.
lemma uncurry_eq (g : Y βΆ (A βΆ[C] X)) : uncurry g = ((π A) β g) β« (ihom.ev A).app X :=
adjunction.hom_equiv_counit _
lemma curry_eq (g : A β Y βΆ X) : curry g = (ihom.coev A).app Y β« (ihom A).map g :=
adjunction.hom_equiv_unit _
lemma curry_injective : function.injective (curry : (A β Y βΆ X) β (Y βΆ (A βΆ[C] X))) :=
(closed.is_adj.adj.hom_equiv _ _).injective
lemma uncurry_injective : function.injective (uncurry : (Y βΆ (A βΆ[C] X)) β (A β Y βΆ X)) :=
(closed.is_adj.adj.hom_equiv _ _).symm.injective
variables (A X)
lemma uncurry_id_eq_ev : uncurry (π (A βΆ[C] X)) = (ihom.ev A).app X :=
by rw [uncurry_eq, tensor_id, id_comp]
lemma curry_id_eq_coev : curry (π _) = (ihom.coev A).app X :=
by { rw [curry_eq, (ihom A).map_id (A β _)], apply comp_id }
section pre
variables {A B} [closed B]
/-- Pre-compose an internal hom with an external hom. -/
def pre (f : B βΆ A) : ihom A βΆ ihom B :=
transfer_nat_trans_self (ihom.adjunction _) (ihom.adjunction _) ((tensoring_left C).map f)
lemma id_tensor_pre_app_comp_ev (f : B βΆ A) (X : C) :
(π B β ((pre f).app X)) β« (ihom.ev B).app X =
(f β (π (A βΆ[C] X))) β« (ihom.ev A).app X :=
transfer_nat_trans_self_counit _ _ ((tensoring_left C).map f) X
lemma uncurry_pre (f : B βΆ A) (X : C) :
monoidal_closed.uncurry ((pre f).app X) = (f β π _) β« (ihom.ev A).app X :=
by rw [uncurry_eq, id_tensor_pre_app_comp_ev]
lemma coev_app_comp_pre_app (f : B βΆ A) :
(ihom.coev A).app X β« (pre f).app (A β X) =
(ihom.coev B).app X β« (ihom B).map (f β (π _)) :=
unit_transfer_nat_trans_self _ _ ((tensoring_left C).map f) X
@[simp]
lemma pre_id (A : C) [closed A] : pre (π A) = π _ :=
by { simp only [pre, functor.map_id], dsimp, simp, }
@[simp]
lemma pre_map {Aβ Aβ Aβ : C} [closed Aβ] [closed Aβ] [closed Aβ]
(f : Aβ βΆ Aβ) (g : Aβ βΆ Aβ) :
pre (f β« g) = pre g β« pre f :=
by rw [pre, pre, pre, transfer_nat_trans_self_comp, (tensoring_left C).map_comp]
end pre
/-- The internal hom functor given by the monoidal closed structure. -/
def internal_hom [monoidal_closed C] : Cα΅α΅ β₯€ C β₯€ C :=
{ obj := Ξ» X, ihom X.unop,
map := Ξ» X Y f, pre f.unop }
section of_equiv
variables {D : Type uβ} [category.{vβ} D] [monoidal_category.{vβ} D]
/-- Transport the property of being monoidal closed across a monoidal equivalence of categories -/
noncomputable
def of_equiv (F : monoidal_functor C D) [is_equivalence F.to_functor] [h : monoidal_closed D] :
monoidal_closed C :=
{ closed' := Ξ» X,
{ is_adj := begin
haveI q : closed (F.to_functor.obj X) := infer_instance,
haveI : is_left_adjoint (tensor_left (F.to_functor.obj X)) := q.is_adj,
have i := comp_inv_iso (monoidal_functor.comm_tensor_left F X),
exact adjunction.left_adjoint_of_nat_iso i,
end } }
end of_equiv
end monoidal_closed
end category_theory
|
bd62704ed7249b77147b2a23761f9fbc356d6fa6 | bab2ace2b909818f20ac125499a8dd88ce812721 | /src/2020/relations/partition_challenge.lean | 5617c34b379028d2ce0a69dfbc38aae5fd20180e | [] | no_license | LaplaceKorea/M40001_lean | 8a3cd411fb821a7665132c09e436f02f674cc666 | 116e9ed1fadf59dc2e78376fca92026859a03bf2 | refs/heads/master | 1,693,347,195,820 | 1,635,517,507,000 | 1,635,517,507,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,622 | lean | import tactic
/-!
# The partition challenge!
Prove that equivalence relations on Ξ± are the same as partitions of Ξ±.
Three sections:
1) partitions
2) equivalence classes
3) the challenge
## Overview
Say `Ξ±` is a type, and `R` is a binary relation on `Ξ±`.
The following things are already in Lean:
reflexive R := β (x : Ξ±), R x x
symmetric R := β β¦x y : Ξ±β¦, R x y β R y x
transitive R := β β¦x y z : Ξ±β¦, R x y β R y z β R x z
equivalence R := reflexive R β§ symmetric R β§ transitive R
In the file below, we will define partitions of `Ξ±` and "build some
interface" (i.e. prove some propositions). We will define
equivalence classes and do the same thing.
Finally, we will prove that there's a bijection between
equivalence relations on `Ξ±` and partitions of `Ξ±`.
-/
/-
# 1) Partitions
We define a partition, and prove some easy lemmas.
-/
/-
## Definition of a partition
Let `Ξ±` be a type. A *partition* on `Ξ±` is defined to be
the following data:
1) A set C of subsets of Ξ±, called "blocks".
2) A hypothesis (i.e. a proof!) that all the blocks are non-empty.
3) A hypothesis that every term of type Ξ± is in one of the blocks.
4) A hypothesis that two blocks with non-empty intersection are equal.
-/
/-- The structure of a partition on a Type Ξ±. -/
@[ext] structure partition (Ξ± : Type) :=
(C : set (set Ξ±))
(Hnonempty : β X β C, (X : set Ξ±).nonempty)
(Hcover : β a, β X β C, a β X)
(Hdisjoint : β X Y β C, (X β© Y : set Ξ±).nonempty β X = Y)
-- docstrings
/-- The set of blocks. -/
add_decl_doc partition.C
/-- Every element of a block is nonempty. -/
add_decl_doc partition.Hnonempty
/-- The blocks cover the type they partition -/
add_decl_doc partition.Hcover
/-- Two blocks which share an element are equal -/
add_decl_doc partition.Hdisjoint
/-
## Basic interface for partitions
-/
namespace partition
-- let Ξ± be a type, and fix a partition P on Ξ±. Let X and Y be subsets of Ξ±.
variables {Ξ± : Type} {P : partition Ξ±} {X Y : set Ξ±}
/-- If X and Y are blocks, and a is in X and Y, then X = Y. -/
theorem eq_of_mem (hX : X β P.C) (hY : Y β P.C) {a : Ξ±} (haX : a β X)
(haY : a β Y) : X = Y :=
-- Proof: follows immediately from the disjointness hypothesis.
P.Hdisjoint _ _ hX hY β¨a, haX, haYβ©
/-- If a is in two blocks X and Y, and if b is in X,
then b is in Y (as X=Y) -/
theorem mem_of_mem (hX : X β P.C) (hY : Y β P.C) {a b : Ξ±}
(haX : a β X) (haY : a β Y) (hbX : b β X) : b β Y :=
begin
sorry,
end
/-- Every term of type `Ξ±` is in one of the blocks for a partition `P`. -/
theorem mem_block (a : Ξ±) : β X : set Ξ±, X β P.C β§ a β X :=
begin
sorry,
end
end partition
/-
# 2) Equivalence classes.
We define equivalence classes and prove a few basic results about them.
-/
section equivalence_classes
/-!
## Definition of equivalence classes
-/
-- Notation and variables for the equivalence class section:
-- let Ξ± be a type, and let R be a binary relation on R.
variables {Ξ± : Type} (R : Ξ± β Ξ± β Prop)
/-- The equivalence class of `a` is the set of `b` related to `a`. -/
def cl (a : Ξ±) :=
{b : Ξ± | R b a}
/-!
## Basic lemmas about equivalence classes
-/
/-- Useful for rewriting -- `b` is in the equivalence class of `a` iff
`b` is related to `a`. True by definition. -/
theorem cl_def {a b : Ξ±} : b β cl R a β R b a := iff.rfl
-- Assume now that R is an equivalence relation.
variables {R} (hR : equivalence R)
include hR
/-- x is in cl(x) -/
lemma mem_cl_self (a : Ξ±) :
a β cl R a :=
begin
sorry,
end
lemma cl_sub_cl_of_mem_cl {a b : Ξ±} :
a β cl R b β
cl R a β cl R b :=
begin
sorry,
end
lemma cl_eq_cl_of_mem_cl {a b : Ξ±} :
a β cl R b β
cl R a = cl R b :=
begin
sorry
end
end equivalence_classes -- section
/-!
# 3) The challenge!
Let `Ξ±` be a type (i.e. a collection of stucff).
There is a bijection between equivalence relations on `Ξ±` and
partitions of `Ξ±`.
We prove this by writing down constructions in each direction
and proving that the constructions are two-sided inverses of one another.
-/
open partition
example (Ξ± : Type) : {R : Ξ± β Ξ± β Prop // equivalence R} β partition Ξ± :=
-- We define constructions (functions!) in both directions and prove that
-- one is a two-sided inverse of the other
{ -- Here is the first construction, from equivalence
-- relations to partitions.
-- Let R be an equivalence relation.
to_fun := Ξ» R, {
-- Let C be the set of equivalence classes for R.
C := { B : set Ξ± | β x : Ξ±, B = cl R.1 x},
-- I claim that C is a partition. We need to check the three
-- hypotheses for a partition (`Hnonempty`, `Hcover` and `Hdisjoint`),
-- so we need to supply three proofs.
Hnonempty := begin
cases R with R hR,
-- If X is an equivalence class then X is nonempty.
show β (X : set Ξ±), (β (a : Ξ±), X = cl R a) β X.nonempty,
sorry,
end,
Hcover := begin
cases R with R hR,
-- The equivalence classes cover Ξ±
show β (a : Ξ±), β (X : set Ξ±) (H : β (b : Ξ±), X = cl R b), a β X,
sorry,
end,
Hdisjoint := begin
cases R with R hR,
-- If two equivalence classes overlap, they are equal.
show β (X Y : set Ξ±), (β (a : Ξ±), X = cl R a) β
(β (b : Ξ±), Y = cl _ b) β (X β© Y).nonempty β X = Y,
sorry,
end },
-- Conversely, say P is an partition.
inv_fun := Ξ» P,
-- Let's define a binary relation `R` thus:
-- `R a b` iff *every* block containing `a` also contains `b`.
-- Because only one block contains a, this will work,
-- and it turns out to be a nice way of thinking about it.
β¨Ξ» a b, β X β P.C, a β X β b β X, begin
-- I claim this is an equivalence relation.
split,
{ -- It's reflexive
show β (a : Ξ±)
(X : set Ξ±), X β P.C β a β X β a β X,
sorry,
},
split,
{ -- it's symmetric
show β (a b : Ξ±),
(β (X : set Ξ±), X β P.C β a β X β b β X) β
β (X : set Ξ±), X β P.C β b β X β a β X,
sorry,
},
{ -- it's transitive
unfold transitive,
show β (a b c : Ξ±),
(β (X : set Ξ±), X β P.C β a β X β b β X) β
(β (X : set Ξ±), X β P.C β b β X β c β X) β
β (X : set Ξ±), X β P.C β a β X β c β X,
sorry,
}
endβ©,
-- If you start with the equivalence relation, and then make the partition
-- and a new equivalence relation, you get back to where you started.
left_inv := begin
rintro β¨R, hRβ©,
-- Tidying up the mess...
suffices : (Ξ» (a b : Ξ±), β (c : Ξ±), a β cl R c β b β cl R c) = R,
simpa,
-- ... you have to prove two binary relations are equal.
ext a b,
-- so you have to prove an if and only if.
show (β (c : Ξ±), a β cl R c β b β cl R c) β R a b,
sorry,
end,
-- Similarly, if you start with the partition, and then make the
-- equivalence relation, and then construct the corresponding partition
-- into equivalence classes, you have the same partition you started with.
right_inv := begin
-- Let P be a partition
intro P,
-- It suffices to prove that a subset X is in the original partition
-- if and only if it's in the one made from the equivalence relation.
ext X,
show (β (a : Ξ±), X = cl _ a) β X β P.C,
dsimp only,
sorry,
end }
/-
-- get these files with
leanproject get ImperialCollegeLondon/M40001_lean
-/ |
c3863d77c76cb1339050a6d20ce1f0caca9a3cb8 | 88fb7558b0636ec6b181f2a548ac11ad3919f8a5 | /tests/lean/eval_expr_error.lean | 85e30dc401ed59a237b29e62782f727dabbf1d64 | [
"Apache-2.0"
] | permissive | moritayasuaki/lean | 9f666c323cb6fa1f31ac597d777914aed41e3b7a | ae96ebf6ee953088c235ff7ae0e8c95066ba8001 | refs/heads/master | 1,611,135,440,814 | 1,493,852,869,000 | 1,493,852,869,000 | 90,269,903 | 0 | 0 | null | 1,493,906,291,000 | 1,493,906,291,000 | null | UTF-8 | Lean | false | false | 344 | lean | open tactic
meta def tst1 (A : Type) : tactic unit :=
do a β to_expr `(0),
v β eval_expr A a,
return ()
run_cmd do
a β to_expr `(nat.add),
v β eval_expr nat a,
trace v,
return ()
run_cmd do
a β to_expr `(Ξ» x : nat, x + 1),
v β (eval_expr nat a <|> trace "tactic failed" >> return 1),
trace v,
return ()
|
616929ec2b9acee13f045379e7fa6133496c2037 | 35960c5b117752aca7e3e7767c0b393e4dbd72a7 | /src/sch/core.lean | 9b0f89ece5cf58939717e88b9da9f057fd2832eb | [
"Apache-2.0"
] | permissive | spl/tts | 461dc76b83df8db47e4660d0941dc97e6d4fd7d1 | b65298fea68ce47c8ed3ba3dbce71c1a20dd3481 | refs/heads/master | 1,541,049,198,347 | 1,537,967,023,000 | 1,537,967,029,000 | 119,653,145 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,925 | lean | import typ
namespace tts ------------------------------------------------------------------
/-- Grammar of type schemes -/
@[derive decidable_eq]
structure sch (V : Type) : Type :=
(vars : list V)
(type : typ V)
(vars_nodup : vars.nodup)
attribute [pp_using_anonymous_constructor] sch
namespace sch ------------------------------------------------------------------
variables {V : Type} [_root_.decidable_eq V] -- Type of variable names
variables {vs : list V} -- List of variable names
variables {nd : vs.nodup} -- No duplicate variables names
variables {x : tagged V} -- Variables
variables {xs : list (tagged V)} -- List of variables
variables {t tx : typ V} -- Types
variables {ts txs : list (typ V)} -- Lists of types
theorem eq_of_veq : β {sβ sβ : sch V}, sβ.vars = sβ.vars β sβ.type = sβ.type β sβ = sβ
| β¨vsβ, tβ, ndββ© β¨vsβ, tβ, ndββ© ha ht := by congr; solve_by_elim
def arity (s : sch V) : β :=
s.vars.length
def of_typ (t : typ V) : sch V :=
β¨[], t, list.nodup_nilβ©
/-- Get the free variables of a scheme -/
def fv (s : sch V) : finset (tagged V) :=
typ.fv s.type
@[simp] theorem fv_mk : fv (mk vs t nd) = typ.fv t :=
rfl
/-- Open a type scheme with a list of types for bound variables -/
def open_typs (ts : list (typ V)) (s : sch V) : typ V :=
typ.open_typs ts s.type
@[simp] theorem open_typs_mk : open_typs ts (mk vs t nd) = typ.open_typs ts t :=
rfl
/-- Open a type scheme with a list of free variables for bound variables -/
def open_vars (xs : list (tagged V)) (s : sch V) : typ V :=
typ.open_vars xs s.type
@[simp] theorem open_vars_mk : open_vars xs (mk vs t nd) = typ.open_vars xs t :=
rfl
/-- Locally-closed type scheme -/
def lc (s : sch V) : Prop :=
typ.lc_body s.arity s.type
end /- namespace -/ sch --------------------------------------------------------
end /- namespace -/ tts --------------------------------------------------------
|
c7fc87e96617aa8f812534da507466c1fd205437 | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /src/Lean/Data/HashSet.lean | e11dae3273aa5a21c2cbee11a7c06d77de95ad16 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | Kha/lean4 | 1005785d2c8797ae266a303968848e5f6ce2fe87 | b99e11346948023cd6c29d248cd8f3e3fb3474cf | refs/heads/master | 1,693,355,498,027 | 1,669,080,461,000 | 1,669,113,138,000 | 184,748,176 | 0 | 0 | Apache-2.0 | 1,665,995,520,000 | 1,556,884,930,000 | Lean | UTF-8 | Lean | false | false | 6,963 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
namespace Lean
universe u v w
def HashSetBucket (Ξ± : Type u) :=
{ b : Array (List Ξ±) // b.size.isPowerOfTwo }
def HashSetBucket.update {Ξ± : Type u} (data : HashSetBucket Ξ±) (i : USize) (d : List Ξ±) (h : i.toNat < data.val.size) : HashSetBucket Ξ± :=
β¨ data.val.uset i d h,
by erw [Array.size_set]; apply data.property β©
structure HashSetImp (Ξ± : Type u) where
size : Nat
buckets : HashSetBucket Ξ±
def mkHashSetImp {Ξ± : Type u} (capacity := 8) : HashSetImp Ξ± :=
{ size := 0
buckets :=
β¨mkArray ((capacity * 4) / 3).nextPowerOfTwo [],
by simp; apply Nat.isPowerOfTwo_nextPowerOfTwoβ© }
namespace HashSetImp
variable {Ξ± : Type u}
/- Remark: we use a C implementation because this function is performance critical. -/
@[extern c inline "(size_t)(#2) & (lean_unbox(#1) - 1)"]
private def mkIdx {sz : Nat} (hash : UInt64) (h : sz.isPowerOfTwo) : { u : USize // u.toNat < sz } :=
-- TODO: avoid `if` in the reference implementation
let u := hash.toUSize &&& (sz.toUSize - 1)
if h' : u.toNat < sz then
β¨u, h'β©
else
β¨0, by simp [USize.toNat, OfNat.ofNat, USize.ofNat, Fin.ofNat']; rw [Nat.zero_mod]; apply Nat.pos_of_isPowerOfTwo hβ©
@[inline] def reinsertAux (hashFn : Ξ± β UInt64) (data : HashSetBucket Ξ±) (a : Ξ±) : HashSetBucket Ξ± :=
let β¨i, hβ© := mkIdx (hashFn a) data.property
data.update i (a :: data.val[i]) h
@[inline] def foldBucketsM {Ξ΄ : Type w} {m : Type w β Type w} [Monad m] (data : HashSetBucket Ξ±) (d : Ξ΄) (f : Ξ΄ β Ξ± β m Ξ΄) : m Ξ΄ :=
data.val.foldlM (init := d) fun d as => as.foldlM f d
@[inline] def foldBuckets {Ξ΄ : Type w} (data : HashSetBucket Ξ±) (d : Ξ΄) (f : Ξ΄ β Ξ± β Ξ΄) : Ξ΄ :=
Id.run $ foldBucketsM data d f
@[inline] def foldM {Ξ΄ : Type w} {m : Type w β Type w} [Monad m] (f : Ξ΄ β Ξ± β m Ξ΄) (d : Ξ΄) (h : HashSetImp Ξ±) : m Ξ΄ :=
foldBucketsM h.buckets d f
@[inline] def fold {Ξ΄ : Type w} (f : Ξ΄ β Ξ± β Ξ΄) (d : Ξ΄) (m : HashSetImp Ξ±) : Ξ΄ :=
foldBuckets m.buckets d f
@[inline] def forBucketsM {m : Type w β Type w} [Monad m] (data : HashSetBucket Ξ±) (f : Ξ± β m PUnit) : m PUnit :=
data.val.forM fun as => as.forM f
@[inline] def forM {m : Type w β Type w} [Monad m] (f : Ξ± β m PUnit) (h : HashSetImp Ξ±) : m PUnit :=
forBucketsM h.buckets f
def find? [BEq Ξ±] [Hashable Ξ±] (m : HashSetImp Ξ±) (a : Ξ±) : Option Ξ± :=
match m with
| β¨_, bucketsβ© =>
let β¨i, hβ© := mkIdx (hash a) buckets.property
buckets.val[i].find? (fun a' => a == a')
def contains [BEq Ξ±] [Hashable Ξ±] (m : HashSetImp Ξ±) (a : Ξ±) : Bool :=
match m with
| β¨_, bucketsβ© =>
let β¨i, hβ© := mkIdx (hash a) buckets.property
buckets.val[i].contains a
def moveEntries [Hashable Ξ±] (i : Nat) (source : Array (List Ξ±)) (target : HashSetBucket Ξ±) : HashSetBucket Ξ± :=
if h : i < source.size then
let idx : Fin source.size := β¨i, hβ©
let es : List Ξ± := source.get idx
-- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl
let source := source.set idx []
let target := es.foldl (reinsertAux hash) target
moveEntries (i+1) source target
else
target
termination_by _ i source _ => source.size - i
def expand [Hashable Ξ±] (size : Nat) (buckets : HashSetBucket Ξ±) : HashSetImp Ξ± :=
let bucketsNew : HashSetBucket Ξ± := β¨
mkArray (buckets.val.size * 2) [],
by simp; apply Nat.mul2_isPowerOfTwo_of_isPowerOfTwo buckets.property
β©
{ size := size,
buckets := moveEntries 0 buckets.val bucketsNew }
def insert [BEq Ξ±] [Hashable Ξ±] (m : HashSetImp Ξ±) (a : Ξ±) : HashSetImp Ξ± :=
match m with
| β¨size, bucketsβ© =>
let β¨i, hβ© := mkIdx (hash a) buckets.property
let bkt := buckets.val[i]
if bkt.contains a
then β¨size, buckets.update i (bkt.replace a a) hβ©
else
let size' := size + 1
let buckets' := buckets.update i (a :: bkt) h
if size' β€ buckets.val.size
then { size := size', buckets := buckets' }
else expand size' buckets'
def erase [BEq Ξ±] [Hashable Ξ±] (m : HashSetImp Ξ±) (a : Ξ±) : HashSetImp Ξ± :=
match m with
| β¨ size, buckets β© =>
let β¨i, hβ© := mkIdx (hash a) buckets.property
let bkt := buckets.val[i]
if bkt.contains a then β¨size - 1, buckets.update i (bkt.erase a) hβ©
else m
inductive WellFormed [BEq Ξ±] [Hashable Ξ±] : HashSetImp Ξ± β Prop where
| mkWff : β n, WellFormed (mkHashSetImp n)
| insertWff : β m a, WellFormed m β WellFormed (insert m a)
| eraseWff : β m a, WellFormed m β WellFormed (erase m a)
end HashSetImp
def HashSet (Ξ± : Type u) [BEq Ξ±] [Hashable Ξ±] :=
{ m : HashSetImp Ξ± // m.WellFormed }
open HashSetImp
def mkHashSet {Ξ± : Type u} [BEq Ξ±] [Hashable Ξ±] (capacity := 8) : HashSet Ξ± :=
β¨ mkHashSetImp capacity, WellFormed.mkWff capacity β©
namespace HashSet
@[inline] def empty [BEq Ξ±] [Hashable Ξ±] : HashSet Ξ± :=
mkHashSet
instance [BEq Ξ±] [Hashable Ξ±] : Inhabited (HashSet Ξ±) where
default := mkHashSet
instance [BEq Ξ±] [Hashable Ξ±] : EmptyCollection (HashSet Ξ±) := β¨mkHashSetβ©
variable {Ξ± : Type u} {_ : BEq Ξ±} {_ : Hashable Ξ±}
@[inline] def insert (m : HashSet Ξ±) (a : Ξ±) : HashSet Ξ± :=
match m with
| β¨ m, hw β© => β¨ m.insert a, WellFormed.insertWff m a hw β©
@[inline] def erase (m : HashSet Ξ±) (a : Ξ±) : HashSet Ξ± :=
match m with
| β¨ m, hw β© => β¨ m.erase a, WellFormed.eraseWff m a hw β©
@[inline] def find? (m : HashSet Ξ±) (a : Ξ±) : Option Ξ± :=
match m with
| β¨ m, _ β© => m.find? a
@[inline] def contains (m : HashSet Ξ±) (a : Ξ±) : Bool :=
match m with
| β¨ m, _ β© => m.contains a
@[inline] def foldM {Ξ΄ : Type w} {m : Type w β Type w} [Monad m] (f : Ξ΄ β Ξ± β m Ξ΄) (init : Ξ΄) (h : HashSet Ξ±) : m Ξ΄ :=
match h with
| β¨ h, _ β© => h.foldM f init
@[inline] def fold {Ξ΄ : Type w} (f : Ξ΄ β Ξ± β Ξ΄) (init : Ξ΄) (m : HashSet Ξ±) : Ξ΄ :=
match m with
| β¨ m, _ β© => m.fold f init
@[inline] def forM {m : Type w β Type w} [Monad m] (h : HashSet Ξ±) (f : Ξ± β m PUnit) : m PUnit :=
match h with
| β¨h, _β© => h.forM f
instance : ForM m (HashSet Ξ±) Ξ± where
forM := HashSet.forM
instance : ForIn m (HashSet Ξ±) Ξ± where
forIn := ForM.forIn
@[inline] def size (m : HashSet Ξ±) : Nat :=
match m with
| β¨ {size := sz, ..}, _ β© => sz
@[inline] def isEmpty (m : HashSet Ξ±) : Bool :=
m.size = 0
def toList (m : HashSet Ξ±) : List Ξ± :=
m.fold (init := []) fun r a => a::r
def toArray (m : HashSet Ξ±) : Array Ξ± :=
m.fold (init := #[]) fun r a => r.push a
def numBuckets (m : HashSet Ξ±) : Nat :=
m.val.buckets.val.size
|
f4c5fd1d3fd0c16e38c9dfb5b90acae3030a11ac | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/ring_theory/polynomial_algebra.lean | bc55dffa967ef868e1caff48675a43fa21d8fcc7 | [
"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 | 11,917 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import ring_theory.matrix_algebra
import data.polynomial.algebra_map
/-!
# Algebra isomorphism between matrices of polynomials and polynomials of matrices
Given `[comm_ring R] [ring A] [algebra R A]`
we show `polynomial A ββ[R] (A β[R] polynomial R)`.
Combining this with the isomorphism `matrix n n A ββ[R] (A β[R] matrix n n R)` proved earlier
in `ring_theory.matrix_algebra`, we obtain the algebra isomorphism
```
def mat_poly_equiv :
matrix n n (polynomial R) ββ[R] polynomial (matrix n n R)
```
which is characterized by
```
coeff (mat_poly_equiv m) k i j = coeff (m i j) k
```
We will use this algebra isomorphism to prove the Cayley-Hamilton theorem.
-/
universes u v w
open_locale tensor_product
open polynomial
open tensor_product
open algebra.tensor_product (alg_hom_of_linear_map_tensor_product include_left)
noncomputable theory
variables (R A : Type*)
variables [comm_semiring R]
variables [semiring A] [algebra R A]
namespace poly_equiv_tensor
/--
(Implementation detail).
The bare function underlying `A β[R] polynomial R ββ[R] polynomial A`, on pure tensors.
-/
def to_fun (a : A) (p : polynomial R) : polynomial A :=
p.sum (Ξ» n r, monomial n (a * algebra_map R A r))
/--
(Implementation detail).
The function underlying `A β[R] polynomial R ββ[R] polynomial A`,
as a linear map in the second factor.
-/
def to_fun_linear_right (a : A) : polynomial R ββ[R] polynomial A :=
{ to_fun := to_fun R A a,
map_smul' := Ξ» r p,
begin
dsimp [to_fun],
rw finsupp.sum_smul_index,
{ dsimp [finsupp.sum],
rw finset.smul_sum,
apply finset.sum_congr rfl,
intros k hk,
rw [monomial_eq_smul_X, monomial_eq_smul_X, algebra.smul_def, β C_mul', β C_mul',
β mul_assoc],
congr' 1,
rw [β algebra.commutes, β algebra.commutes],
simp only [ring_hom.map_mul, polynomial.algebra_map_apply, mul_assoc], },
{ intro i, simp only [ring_hom.map_zero, mul_zero, monomial_zero_right] },
end,
map_add' := Ξ» p q,
begin
simp only [to_fun],
rw finsupp.sum_add_index,
{ simp only [monomial_zero_right, forall_const, ring_hom.map_zero, mul_zero], },
{ intros i r s, simp only [ring_hom.map_add, mul_add, monomial_add], },
end, }
/--
(Implementation detail).
The function underlying `A β[R] polynomial R ββ[R] polynomial A`,
as a bilinear function of two arguments.
-/
def to_fun_bilinear : A ββ[R] polynomial R ββ[R] polynomial A :=
{ to_fun := to_fun_linear_right R A,
map_smul' := by {
intros, unfold to_fun_linear_right,
congr, simp only [linear_map.coe_mk],
unfold to_fun finsupp.sum monomial,
simp_rw [finset.smul_sum, finsupp.smul_single, β algebra.smul_mul_assoc],
refl },
map_add' := by {
intros, unfold to_fun_linear_right,
congr, simp only [linear_map.coe_mk],
unfold to_fun finsupp.sum monomial,
simp_rw [β finset.sum_add_distrib, β finsupp.single_add, β add_mul],
refl } }
/--
(Implementation detail).
The function underlying `A β[R] polynomial R ββ[R] polynomial A`,
as a linear map.
-/
def to_fun_linear : A β[R] polynomial R ββ[R] polynomial A :=
tensor_product.lift (to_fun_bilinear R A)
-- We apparently need to provide the decidable instance here
-- in order to successfully rewrite by this lemma.
lemma to_fun_linear_mul_tmul_mul_aux_1
(p : polynomial R) (k : β) (h : decidable (Β¬p.coeff k = 0)) (a : A) :
ite (Β¬coeff p k = 0) (a * (algebra_map R A) (coeff p k)) 0 = a * (algebra_map R A) (coeff p k) :=
by { classical, split_ifs; simp *, }
lemma to_fun_linear_mul_tmul_mul_aux_2 (k : β) (aβ aβ : A) (pβ pβ : polynomial R) :
aβ * aβ * (algebra_map R A) ((pβ * pβ).coeff k) =
(finset.nat.antidiagonal k).sum
(Ξ» x, aβ * (algebra_map R A) (coeff pβ x.1) * (aβ * (algebra_map R A) (coeff pβ x.2))) :=
begin
simp_rw [mul_assoc, algebra.commutes, βfinset.mul_sum, mul_assoc, βfinset.mul_sum],
congr,
simp_rw [algebra.commutes (coeff pβ _), coeff_mul, ring_hom.map_sum, ring_hom.map_mul],
end
lemma to_fun_linear_mul_tmul_mul (aβ aβ : A) (pβ pβ : polynomial R) :
(to_fun_linear R A) ((aβ * aβ) ββ[R] pβ * pβ) =
(to_fun_linear R A) (aβ ββ[R] pβ) * (to_fun_linear R A) (aβ ββ[R] pβ) :=
begin
dsimp [to_fun_linear],
simp only [lift.tmul],
dsimp [to_fun_bilinear, to_fun_linear_right, to_fun],
ext k,
-- TODO This is a bit annoying: the polynomial API is breaking down.
have apply_eq_coeff : β {p : β ββ R} {n : β}, p n = coeff p n := by { intros, refl },
simp_rw [coeff_sum, coeff_monomial, finsupp.sum, finset.sum_ite_eq', finsupp.mem_support_iff,
ne.def, coeff_mul, finset_sum_coeff, coeff_monomial,
finset.sum_ite_eq', finsupp.mem_support_iff, ne.def,
mul_ite, mul_zero, ite_mul, zero_mul, apply_eq_coeff],
simp_rw [ite_mul_zero_left (Β¬coeff pβ _ = 0) (aβ * (algebra_map R A) (coeff pβ _))],
simp_rw [ite_mul_zero_right (Β¬coeff pβ _ = 0) _ (_ * _)],
simp_rw [to_fun_linear_mul_tmul_mul_aux_1, to_fun_linear_mul_tmul_mul_aux_2],
end
lemma to_fun_linear_algebra_map_tmul_one (r : R) :
(to_fun_linear R A) ((algebra_map R A) r ββ[R] 1) = (algebra_map R (polynomial A)) r :=
begin
dsimp [to_fun_linear],
simp only [lift.tmul],
dsimp [to_fun_bilinear, to_fun_linear_right, to_fun],
rw [β C_1, βmonomial_zero_left, monomial, finsupp.sum_single_index],
{ simp, refl, },
{ simp, },
end
/--
(Implementation detail).
The algebra homomorphism `A β[R] polynomial R ββ[R] polynomial A`.
-/
def to_fun_alg_hom : A β[R] polynomial R ββ[R] polynomial A :=
alg_hom_of_linear_map_tensor_product
(to_fun_linear R A)
(to_fun_linear_mul_tmul_mul R A)
(to_fun_linear_algebra_map_tmul_one R A)
@[simp] lemma to_fun_alg_hom_apply_tmul (a : A) (p : polynomial R) :
to_fun_alg_hom R A (a ββ[R] p) = p.sum (Ξ» n r, monomial n (a * (algebra_map R A) r)) :=
by simp [to_fun_alg_hom, to_fun_linear, to_fun_bilinear, to_fun_linear_right, to_fun]
/--
(Implementation detail.)
The bare function `polynomial A β A β[R] polynomial R`.
(We don't need to show that it's an algebra map, thankfully --- just that it's an inverse.)
-/
def inv_fun (p : polynomial A) : A β[R] polynomial R :=
p.evalβ
(include_left : A ββ[R] A β[R] polynomial R)
((1 : A) ββ[R] (X : polynomial R))
@[simp]
lemma inv_fun_add {p q} : inv_fun R A (p + q) = inv_fun R A p + inv_fun R A q :=
by simp only [inv_fun, evalβ_add]
lemma left_inv (x : A β polynomial R) :
inv_fun R A ((to_fun_alg_hom R A) x) = x :=
begin
apply tensor_product.induction_on x,
{ simp [inv_fun], },
{ intros a p, dsimp only [inv_fun],
rw [to_fun_alg_hom_apply_tmul, evalβ_sum],
simp_rw [evalβ_monomial, alg_hom.coe_to_ring_hom, algebra.tensor_product.tmul_pow, one_pow,
algebra.tensor_product.include_left_apply, algebra.tensor_product.tmul_mul_tmul,
mul_one, one_mul, βalgebra.commutes, βalgebra.smul_def'', smul_tmul],
rw [finsupp.sum, βtmul_sum],
conv_rhs { rw [βsum_C_mul_X_eq p], },
simp only [algebra.smul_def''],
refl, },
{ intros p q hp hq,
simp only [alg_hom.map_add, inv_fun_add, hp, hq], },
end
lemma right_inv (x : polynomial A) :
(to_fun_alg_hom R A) (inv_fun R A x) = x :=
begin
apply polynomial.induction_on' x,
{ intros p q hp hq, simp only [inv_fun_add, alg_hom.map_add, hp, hq], },
{ intros n a,
rw [inv_fun, evalβ_monomial, alg_hom.coe_to_ring_hom, algebra.tensor_product.include_left_apply,
algebra.tensor_product.tmul_pow, one_pow, algebra.tensor_product.tmul_mul_tmul,
mul_one, one_mul, to_fun_alg_hom_apply_tmul, βmonomial_one_eq_X_pow],
dsimp [monomial],
rw [finsupp.sum_single_index]; simp, }
end
/--
(Implementation detail)
The equivalence, ignoring the algebra structure, `(A β[R] polynomial R) β polynomial A`.
-/
def equiv : (A β[R] polynomial R) β polynomial A :=
{ to_fun := to_fun_alg_hom R A,
inv_fun := inv_fun R A,
left_inv := left_inv R A,
right_inv := right_inv R A, }
end poly_equiv_tensor
open poly_equiv_tensor
/--
The `R`-algebra isomorphism `polynomial A ββ[R] (A β[R] polynomial R)`.
-/
def poly_equiv_tensor : polynomial A ββ[R] (A β[R] polynomial R) :=
alg_equiv.symm
{ ..(poly_equiv_tensor.to_fun_alg_hom R A), ..(poly_equiv_tensor.equiv R A) }
@[simp]
lemma poly_equiv_tensor_apply (p : polynomial A) :
poly_equiv_tensor R A p =
p.evalβ (include_left : A ββ[R] A β[R] polynomial R) ((1 : A) ββ[R] (X : polynomial R)) :=
rfl
@[simp]
lemma poly_equiv_tensor_symm_apply_tmul (a : A) (p : polynomial R) :
(poly_equiv_tensor R A).symm (a ββ p) = p.sum (Ξ» n r, monomial n (a * algebra_map R A r)) :=
begin
simp [poly_equiv_tensor, to_fun_alg_hom, alg_hom_of_linear_map_tensor_product, to_fun_linear],
refl,
end
open matrix
open_locale big_operators
variables {R}
variables {n : Type w} [fintype n] [decidable_eq n]
/--
The algebra isomorphism stating "matrices of polynomials are the same as polynomials of matrices".
(You probably shouldn't attempt to use this underlying definition ---
it's an algebra equivalence, and characterised extensionally by the lemma
`mat_poly_equiv_coeff_apply` below.)
-/
noncomputable def mat_poly_equiv :
matrix n n (polynomial R) ββ[R] polynomial (matrix n n R) :=
(((matrix_equiv_tensor R (polynomial R) n)).trans
(algebra.tensor_product.comm R _ _)).trans
(poly_equiv_tensor R (matrix n n R)).symm
open finset
lemma mat_poly_equiv_coeff_apply_aux_1 (i j : n) (k : β) (x : R) :
mat_poly_equiv (std_basis_matrix i j $ monomial k x) =
monomial k (std_basis_matrix i j x) :=
begin
simp only [mat_poly_equiv, alg_equiv.trans_apply,
matrix_equiv_tensor_apply_std_basis],
apply (poly_equiv_tensor R (matrix n n R)).injective,
simp only [alg_equiv.apply_symm_apply],
convert algebra.tensor_product.comm_tmul _ _ _ _ _,
simp only [poly_equiv_tensor_apply],
convert evalβ_monomial _ _,
simp only [algebra.tensor_product.tmul_mul_tmul, one_pow, one_mul, matrix.mul_one,
algebra.tensor_product.tmul_pow, algebra.tensor_product.include_left_apply, mul_eq_mul],
rw [monomial_eq_smul_X, β tensor_product.smul_tmul],
congr, ext, simp, dsimp, simp,
end
lemma mat_poly_equiv_coeff_apply_aux_2
(i j : n) (p : polynomial R) (k : β) :
coeff (mat_poly_equiv (std_basis_matrix i j p)) k =
std_basis_matrix i j (coeff p k) :=
begin
apply polynomial.induction_on' p,
{ intros p q hp hq, ext,
simp [hp, hq, coeff_add, add_val, std_basis_matrix_add], },
{ intros k x,
simp only [mat_poly_equiv_coeff_apply_aux_1, coeff_monomial],
split_ifs; { funext, simp, }, }
end
@[simp] lemma mat_poly_equiv_coeff_apply
(m : matrix n n (polynomial R)) (k : β) (i j : n) :
coeff (mat_poly_equiv m) k i j = coeff (m i j) k :=
begin
apply matrix.induction_on' m,
{ simp, },
{ intros p q hp hq, simp [hp, hq], },
{ intros i' j' x,
erw mat_poly_equiv_coeff_apply_aux_2,
dsimp [std_basis_matrix],
split_ifs,
{ rcases h with β¨rfl, rflβ©, simp [std_basis_matrix], },
{ simp [std_basis_matrix, h], }, },
end
@[simp] lemma mat_poly_equiv_symm_apply_coeff
(p : polynomial (matrix n n R)) (i j : n) (k : β) :
coeff (mat_poly_equiv.symm p i j) k = coeff p k i j :=
begin
have t : p = mat_poly_equiv
(mat_poly_equiv.symm p) := by simp,
conv_rhs { rw t, },
simp only [mat_poly_equiv_coeff_apply],
end
lemma mat_poly_equiv_smul_one (p : polynomial R) :
mat_poly_equiv (p β’ 1) = p.map (algebra_map R (matrix n n R)) :=
begin
ext m i j,
simp only [coeff_map, one_val, algebra_map_matrix_val, mul_boole,
smul_val, mat_poly_equiv_coeff_apply],
split_ifs; simp,
end
|
528b9d84ccc7795ec6c1ea0959e2af0c1d6b8f3e | 1b8f093752ba748c5ca0083afef2959aaa7dace5 | /src/category_theory/universal/cones.lean | 8499d5679a9b353689c7ea1993e494f0cfe517b9 | [] | 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,282 | 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.limits.shape
open category_theory
namespace category_theory.limits
universes u v
variables {J : Type v} [small_category J]
variables {C : Type u} [π : category.{u v} C]
include π
variable {F : J β₯€ C}
structure cone_morphism (A B : cone F) : Type v :=
(hom : A.X βΆ B.X)
(w' : Ξ j : J, hom β« (B.Ο j) = (A.Ο j) . obviously)
restate_axiom cone_morphism.w'
attribute [simp,search] cone_morphism.w
namespace cone_morphism
@[extensionality] lemma ext {A B : cone F} {f g : cone_morphism A B} (w : f.hom = g.hom) : f = g :=
begin
/- obviously' say: -/
induction f,
induction g,
dsimp at w,
induction w,
refl,
end
end cone_morphism
instance cones (F : J β₯€ C) : category.{(max u v) v} (cone F) :=
{ hom := Ξ» A B, cone_morphism A B,
comp := Ξ» _ _ _ f g, { hom := f.hom β« g.hom },
id := Ξ» B, { hom := π B.X } }
namespace cones
@[simp] lemma id.hom {F : J β₯€ C} (c : cone F) : (π c : cone_morphism c c).hom = π (c.X) := rfl
@[simp] lemma comp.hom {F : J β₯€ C} {c d e : cone F} (f : c βΆ d) (g : d βΆ e) : ((f β« g) : cone_morphism c e).hom = (f : cone_morphism c d).hom β« (g : cone_morphism d e).hom := rfl
section
variables {D : Type u} [π : category.{u v} D]
include π
def functoriality (F : J β₯€ C) (G : C β₯€ D) : (cone F) β₯€ (cone (F β G)) :=
{ obj := Ξ» A, { X := G A.X,
Ο := Ξ» j, G.map (A.Ο j),
w := begin /- `obviously'` says: -/ intros, simp, erw [βfunctor.map_comp, cone.w] end },
map' := Ξ» X Y f, { hom := G.map f.hom,
w' := begin /- `obviously'` says: -/ intros, dsimp, erw [βfunctor.map_comp, cone_morphism.w] end } }
end
end cones
structure cocone_morphism (A B : cocone F) :=
(hom : A.X βΆ B.X)
(w' : Ξ j : J, (A.ΞΉ j) β« hom = (B.ΞΉ j) . obviously)
restate_axiom cocone_morphism.w'
attribute [simp,search] cocone_morphism.w
namespace cocone_morphism
@[extensionality] lemma ext {A B : cocone F} {f g : cocone_morphism A B} (w : f.hom = g.hom) : f = g :=
begin
induction f,
induction g,
-- `obviously'` says:
dsimp at *,
induction w,
refl,
end
end cocone_morphism
instance cocones (F : J β₯€ C) : category.{(max u v) v} (cocone F) :=
{ hom := Ξ» A B, cocone_morphism A B,
comp := Ξ» _ _ _ f g, { hom := f.hom β« g.hom },
id := Ξ» B, { hom := π B.X } }
namespace cocones
@[simp] lemma id.hom {F : J β₯€ C} (c : cocone F) : (π c : cocone_morphism c c).hom = π (c.X) := rfl
@[simp] lemma comp.hom {F : J β₯€ C} {c d e : cocone F} (f : c βΆ d) (g : d βΆ e) : ((f β« g) : cocone_morphism c e).hom = (f : cocone_morphism c d).hom β« (g : cocone_morphism d e).hom := rfl
section
variables {D : Type u} [π : category.{u v} D]
include π
def functoriality (F : J β₯€ C) (G : C β₯€ D) : (cocone F) β₯€ (cocone (F β G)) :=
{ obj := Ξ» A, { X := G A.X,
ΞΉ := Ξ» j, G.map (A.ΞΉ j),
w := begin /- `obviously'` says: -/ intros, simp, erw [βfunctor.map_comp, cocone.w] end },
map' := Ξ» _ _ f, { hom := G.map f.hom,
w' := begin /- `obviously'` says: -/ intros, dsimp, erw [βfunctor.map_comp, cocone_morphism.w] end } }
end
end cocones
end category_theory.limits
namespace category_theory.functor
universes u v
variables {J : Type v} [small_category J]
variables {C : Type u} [category.{u v} C] {D : Type u} [category.{u v} D]
variables {F : J β₯€ C} {G : J β₯€ C}
open category_theory.limits
def map_cone (H : C β₯€ D) (c : cone F) : cone (F β H) := (cones.functoriality F H) c
def map_cocone (H : C β₯€ D) (c : cocone F) : cocone (F β H) := (cocones.functoriality F H) c
def map_cone_morphism (H : C β₯€ D) {c c' : cone F} (f : cone_morphism c c') : cone_morphism (H.map_cone c) (H.map_cone c') := (cones.functoriality F H).map f
def map_cocone_morphism (H : C β₯€ D) {c c' : cocone F} (f : cocone_morphism c c') : cocone_morphism (H.map_cocone c) (H.map_cocone c') := (cocones.functoriality F H).map f
end category_theory.functor |
6051f390a84f90f9b2d13b26409e9dce6d9b7772 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /tests/lean/run/binrel.lean | e7bceba7afb298f94ba4f1fe99eec4e0ff697025 | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 816 | lean | def ex1 (x y : Nat) (i j : Int) :=
binrel% Less x i
def ex2 (x y : Nat) (i j : Int) :=
binrel% Less i x
def ex3 (x y : Nat) (i j : Int) :=
binrel% Less (i + 1) x
def ex4 (x y : Nat) (i j : Int) :=
binrel% Less i (x + 1)
def ex5 (x y : Nat) (i j : Int) :=
binrel% Less i (x + y)
def ex6 (x y : Nat) (i j : Int) :=
binrel% Less (i + j) (x + 0)
def ex7 (x y : Nat) (i j : Int) :=
binrel% Less (i + j) (x + i)
def ex8 (x y : Nat) (i j : Int) :=
binrel% Less (i + 0) (x + i)
def ex9 (n : UInt32) :=
binrel% Less n 0xd800
def ex10 (x : Lean.Syntax) : Bool :=
x.getArgs.all (binrel% BEq.beq Β·.getKind `foo)
def ex11 (xs : Array (Nat Γ Nat)) :=
let f a b := binrel% Less a.1 b.1
f xs[1] xs[2]
def ex12 (i j : Int) :=
binrel% Eq (i, j) (0, 0)
def ex13 (i j : Int) :=
(i, j) = (0, 0)
|
d3493692baae9bbb46f72f11f64c7221d677969e | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/ll_infer_type_bug.lean | a71ae60d60540ac1d8d57e20d2310254a515a5d0 | [
"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 | 508 | lean |
partial def f : List Nat β Bool
| [] => false
| (a::as) => a > 0 && f as
#print f._cstage2
#exit
mutual def f1, f2, f3, f4, f5
with f1 : Nat β Bool
| 0 := f3 0
| x := f2 x
with f2 : Nat β Bool
| 0 := f4 0
| x := f3 x
with f3 : Nat β Bool
| 0 := f5 0
| x := f4 x
with f4 : Nat β Bool
| 0 := f5 0
| (x+1) := f4 x
with f5 : Nat β Bool
| 0 := true
| _ := false
#check f1._main._cstage2
#check f2._main._cstage2
#check f3._main._cstage2
#check f4._main._cstage2
#check f5._main._cstage2
|
2cc1304d91ee05266adcebe0f81b7b64944187d9 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/interactive/goal_info.lean | d0dc0a32b928c4e69e38e3915406c8a6830b550a | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 926 | lean | constant addc {a b : nat} : a + b = b + a
constant addassoc {a b c : nat} : (a + b) + c = a + (b + c)
constant zadd (a : nat) : 0 + a = a
open nat
example : β n m : β, n + m = m + n :=
begin
intros n m,
induction m with m' ih,
--^ "command": "info"
{ change n + 0 = 0 + n, simp [zadd] },
--^ "command": "info"
{ change succ (n + m') = succ m' + n,
rw [succ_add, ih]
--^ "command":"info"
}
end
example : β n m : β, n + m = m + n :=
begin
intros n m,
induction m with m' ih,
{ change n + 0 = 0 + n, simp [zadd] },
--^ "command": "info"
{ change succ (n + m') = succ m' + n,
rw [succ_add, ih]
}
end
example : β n m : β, n + m = m + n :=
begin
intros n m,
induction m with m' ih,
{ change n + 0 = 0 + n, simp [zadd] },
--^ "command": "info"
{ change succ (n + m') = succ m' + n,
rw [succ_add, ih]
}
end
|
64dd47489ddcc1e4a2c4ab9a3bb10ca7608ec5fc | 1e3a43e8ba59c6fe1c66775b6e833e721eaf1675 | /src/algebra/order_functions.lean | 705457594b56c84cea1b614da1267a2de01e9292 | [
"Apache-2.0"
] | permissive | Sterrs/mathlib | ea6910847b8dfd18500486de9ab0ee35704a3f52 | d9327e433804004aa1dc65091bbe0de1e5a08c5e | refs/heads/master | 1,650,769,884,257 | 1,587,808,694,000 | 1,587,808,694,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,209 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.ordered_group
universes u v
variables {Ξ± : Type u} {Ξ² : Type v}
attribute [simp] max_eq_left max_eq_right min_eq_left min_eq_right
/-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/
def strict_mono [has_lt Ξ±] [has_lt Ξ²] (f : Ξ± β Ξ²) : Prop :=
β β¦a bβ¦, a < b β f a < f b
namespace strict_mono
open ordering function
section
variables [linear_order Ξ±] [preorder Ξ²] {f : Ξ± β Ξ²}
lemma lt_iff_lt (H : strict_mono f) {a b} :
f a < f b β a < b :=
β¨Ξ» h, ((lt_trichotomy b a)
.resolve_left $ Ξ» h', lt_asymm h $ H h')
.resolve_left $ Ξ» e, ne_of_gt h $ congr_arg _ e, @H _ _β©
lemma injective (H : strict_mono f) : injective f
| a b e := ((lt_trichotomy a b)
.resolve_left $ Ξ» h, ne_of_lt (H h) e)
.resolve_right $ Ξ» h, ne_of_gt (H h) e
theorem compares (H : strict_mono f) {a b} :
β {o}, compares o (f a) (f b) β compares o a b
| lt := H.lt_iff_lt
| eq := β¨Ξ» h, H.injective h, congr_arg _β©
| gt := H.lt_iff_lt
lemma le_iff_le (H : strict_mono f) {a b} :
f a β€ f b β a β€ b :=
β¨Ξ» h, le_of_not_gt $ Ξ» h', not_le_of_lt (H h') h,
Ξ» h, (lt_or_eq_of_le h).elim (Ξ» h', le_of_lt (H h')) (Ξ» h', h' βΈ le_refl _)β©
end
protected lemma nat {Ξ²} [preorder Ξ²] {f : β β Ξ²} (h : βn, f n < f (n+1)) : strict_mono f :=
by { intros n m hnm, induction hnm with m' hnm' ih, apply h, exact lt.trans ih (h _) }
-- `preorder Ξ±` isn't strong enough: if the preorder on Ξ± is an equivalence relation,
-- then `strict_mono f` is vacuously true.
lemma monotone [partial_order Ξ±] [preorder Ξ²] {f : Ξ± β Ξ²} (H : strict_mono f) : monotone f :=
Ξ» a b h, (lt_or_eq_of_le h).rec (le_of_lt β (@H _ _)) (by rintro rfl; refl)
end strict_mono
section
open function
variables [partial_order Ξ±] [partial_order Ξ²] {f : Ξ± β Ξ²}
lemma strict_mono_of_monotone_of_injective (hβ : monotone f) (hβ : injective f) :
strict_mono f :=
Ξ» a b h,
begin
rw lt_iff_le_and_ne at β’ h,
exact β¨hβ h.1, Ξ» e, h.2 (hβ e)β©
end
end
section
variables [decidable_linear_order Ξ±] [decidable_linear_order Ξ²] {f : Ξ± β Ξ²} {a b c d : Ξ±}
-- translate from lattices to linear orders (sup β max, inf β min)
@[simp] lemma le_min_iff : c β€ min a b β c β€ a β§ c β€ b := le_inf_iff
@[simp] lemma max_le_iff : max a b β€ c β a β€ c β§ b β€ c := sup_le_iff
lemma max_le_max : a β€ c β b β€ d β max a b β€ max c d := sup_le_sup
lemma min_le_min : a β€ c β b β€ d β min a b β€ min c d := inf_le_inf
lemma le_max_left_of_le : a β€ b β a β€ max b c := le_sup_left_of_le
lemma le_max_right_of_le : a β€ c β a β€ max b c := le_sup_right_of_le
lemma min_le_left_of_le : a β€ c β min a b β€ c := inf_le_left_of_le
lemma min_le_right_of_le : b β€ c β min a b β€ c := inf_le_right_of_le
lemma max_min_distrib_left : max a (min b c) = min (max a b) (max a c) := sup_inf_left
lemma max_min_distrib_right : max (min a b) c = min (max a c) (max b c) := sup_inf_right
lemma min_max_distrib_left : min a (max b c) = max (min a b) (min a c) := inf_sup_left
lemma min_max_distrib_right : min (max a b) c = max (min a c) (min b c) := inf_sup_right
lemma min_le_max : min a b β€ max a b := le_trans (min_le_left a b) (le_max_left a b)
instance max_idem : is_idempotent Ξ± max := by apply_instance -- short-circuit type class inference
instance min_idem : is_idempotent Ξ± min := by apply_instance -- short-circuit type class inference
@[simp] lemma min_le_iff : min a b β€ c β a β€ c β¨ b β€ c :=
have a β€ b β (a β€ c β¨ b β€ c β a β€ c),
from assume h, or_iff_left_of_imp $ le_trans h,
have b β€ a β (a β€ c β¨ b β€ c β b β€ c),
from assume h, or_iff_right_of_imp $ le_trans h,
by cases le_total a b; simp *
@[simp] lemma le_max_iff : a β€ max b c β a β€ b β¨ a β€ c :=
have b β€ c β (a β€ b β¨ a β€ c β a β€ c),
from assume h, or_iff_right_of_imp $ assume h', le_trans h' h,
have c β€ b β (a β€ b β¨ a β€ c β a β€ b),
from assume h, or_iff_left_of_imp $ assume h', le_trans h' h,
by cases le_total b c; simp *
@[simp] lemma max_lt_iff : max a b < c β (a < c β§ b < c) :=
by rw [lt_iff_not_ge]; simp [(β₯), le_max_iff, not_or_distrib]
@[simp] lemma lt_min_iff : a < min b c β (a < b β§ a < c) :=
by rw [lt_iff_not_ge]; simp [(β₯), min_le_iff, not_or_distrib]
@[simp] lemma lt_max_iff : a < max b c β a < b β¨ a < c :=
by rw [lt_iff_not_ge]; simp [(β₯), max_le_iff, not_and_distrib]
@[simp] lemma min_lt_iff : min a b < c β a < c β¨ b < c :=
by rw [lt_iff_not_ge]; simp [(β₯), le_min_iff, not_and_distrib]
lemma max_lt_max (hβ : a < c) (hβ : b < d) : max a b < max c d :=
by apply max_lt; simp [lt_max_iff, hβ, hβ]
lemma min_lt_min (hβ : a < c) (hβ : b < d) : min a b < min c d :=
by apply lt_min; simp [min_lt_iff, hβ, hβ]
theorem min_right_comm (a b c : Ξ±) : min (min a b) c = min (min a c) b :=
right_comm min min_comm min_assoc a b c
theorem max.left_comm (a b c : Ξ±) : max a (max b c) = max b (max a c) :=
left_comm max max_comm max_assoc a b c
theorem max.right_comm (a b c : Ξ±) : max (max a b) c = max (max a c) b :=
right_comm max max_comm max_assoc a b c
lemma monotone.map_max (hf : monotone f) : f (max a b) = max (f a) (f b) :=
by cases le_total a b; simp [h, hf h]
lemma monotone.map_min (hf : monotone f) : f (min a b) = min (f a) (f b) :=
by cases le_total a b; simp [h, hf h]
theorem min_choice (a b : Ξ±) : min a b = a β¨ min a b = b :=
by by_cases h : a β€ b; simp [min, h]
theorem max_choice (a b : Ξ±) : max a b = a β¨ max a b = b :=
by by_cases h : a β€ b; simp [max, h]
lemma le_of_max_le_left {a b c : Ξ±} (h : max a b β€ c) : a β€ c :=
le_trans (le_max_left _ _) h
lemma le_of_max_le_right {a b c : Ξ±} (h : max a b β€ c) : b β€ c :=
le_trans (le_max_right _ _) h
end
lemma min_add {Ξ± : Type u} [decidable_linear_ordered_add_comm_group Ξ±] (a b c : Ξ±) :
min a b + c = min (a + c) (b + c) :=
if hle : a β€ b then
have a - c β€ b - c, from sub_le_sub hle (le_refl _),
by simp * at *
else
have b - c β€ a - c, from sub_le_sub (le_of_lt (lt_of_not_ge hle)) (le_refl _),
by simp * at *
lemma min_sub {Ξ± : Type u} [decidable_linear_ordered_add_comm_group Ξ±] (a b c : Ξ±) :
min a b - c = min (a - c) (b - c) :=
by simp [min_add, sub_eq_add_neg]
/- Some lemmas about types that have an ordering and a binary operation, with no
rules relating them. -/
lemma fn_min_add_fn_max [decidable_linear_order Ξ±] [add_comm_semigroup Ξ²] (f : Ξ± β Ξ²) (n m : Ξ±) :
f (min n m) + f (max n m) = f n + f m :=
by { cases le_total n m with h h; simp [h, add_comm] }
lemma min_add_max [decidable_linear_order Ξ±] [add_comm_semigroup Ξ±] (n m : Ξ±) :
min n m + max n m = n + m :=
fn_min_add_fn_max id n m
lemma fn_min_mul_fn_max [decidable_linear_order Ξ±] [comm_semigroup Ξ²] (f : Ξ± β Ξ²) (n m : Ξ±) :
f (min n m) * f (max n m) = f n * f m :=
by { cases le_total n m with h h; simp [h, mul_comm] }
lemma min_mul_max [decidable_linear_order Ξ±] [comm_semigroup Ξ±] (n m : Ξ±) :
min n m * max n m = n * m :=
fn_min_mul_fn_max id n m
section decidable_linear_ordered_add_comm_group
variables [decidable_linear_ordered_add_comm_group Ξ±] {a b c : Ξ±}
attribute [simp] abs_zero abs_neg
lemma abs_add (a b : Ξ±) : abs (a + b) β€ abs a + abs b := abs_add_le_abs_add_abs a b
theorem abs_le : abs a β€ b β - b β€ a β§ a β€ b :=
β¨assume h, β¨neg_le_of_neg_le $ le_trans (neg_le_abs_self _) h, le_trans (le_abs_self _) hβ©,
assume β¨hβ, hββ©, abs_le_of_le_of_neg_le hβ $ neg_le_of_neg_le hββ©
lemma abs_lt : abs a < b β - b < a β§ a < b :=
β¨assume h, β¨neg_lt_of_neg_lt $ lt_of_le_of_lt (neg_le_abs_self _) h, lt_of_le_of_lt (le_abs_self _) hβ©,
assume β¨hβ, hββ©, abs_lt_of_lt_of_neg_lt hβ $ neg_lt_of_neg_lt hββ©
lemma abs_sub_le_iff : abs (a - b) β€ c β a - b β€ c β§ b - a β€ c :=
by rw [abs_le, neg_le_sub_iff_le_add, @sub_le_iff_le_add' _ _ b, and_comm]
lemma abs_sub_lt_iff : abs (a - b) < c β a - b < c β§ b - a < c :=
by rw [abs_lt, neg_lt_sub_iff_lt_add, @sub_lt_iff_lt_add' _ _ b, and_comm]
lemma sub_abs_le_abs_sub (a b : Ξ±) : abs a - abs b β€ abs (a - b) := abs_sub_abs_le_abs_sub a b
lemma abs_abs_sub_le_abs_sub (a b : Ξ±) : abs (abs a - abs b) β€ abs (a - b) :=
abs_sub_le_iff.2 β¨sub_abs_le_abs_sub _ _, by rw abs_sub; apply sub_abs_le_abs_subβ©
lemma abs_eq (hb : 0 β€ b) : abs a = b β a = b β¨ a = -b :=
iff.intro
begin
cases le_total a 0 with a_nonpos a_nonneg,
{ rw [abs_of_nonpos a_nonpos, neg_eq_iff_neg_eq, eq_comm], exact or.inr },
{ rw [abs_of_nonneg a_nonneg, eq_comm], exact or.inl }
end
(by intro h; cases h; subst h; try { rw abs_neg }; exact abs_of_nonneg hb)
@[simp] lemma abs_eq_zero : abs a = 0 β a = 0 :=
β¨eq_zero_of_abs_eq_zero, Ξ» e, e.symm βΈ abs_zeroβ©
lemma abs_pos_iff {a : Ξ±} : 0 < abs a β a β 0 :=
β¨Ξ» h, mt abs_eq_zero.2 (ne_of_gt h), abs_pos_of_ne_zeroβ©
@[simp] lemma abs_nonpos_iff {a : Ξ±} : abs a β€ 0 β a = 0 :=
by rw [β not_lt, abs_pos_iff, not_not]
lemma abs_le_max_abs_abs (hab : a β€ b) (hbc : b β€ c) : abs b β€ max (abs a) (abs c) :=
abs_le_of_le_of_neg_le
(by simp [le_max_iff, le_trans hbc (le_abs_self c)])
(by simp [le_max_iff, le_trans (neg_le_neg hab) (neg_le_abs_self a)])
theorem abs_le_abs {Ξ± : Type*} [decidable_linear_ordered_add_comm_group Ξ±] {a b : Ξ±}
(hβ : a β€ b) (hβ : -a β€ b) :
abs a β€ abs b :=
calc abs a
β€ b : by { apply abs_le_of_le_of_neg_le; assumption }
... β€ abs b : le_abs_self _
lemma min_le_add_of_nonneg_right {a b : Ξ±} (hb : b β₯ 0) : min a b β€ a + b :=
calc
min a b β€ a : by apply min_le_left
... β€ a + b : le_add_of_nonneg_right hb
lemma min_le_add_of_nonneg_left {a b : Ξ±} (ha : a β₯ 0) : min a b β€ a + b :=
calc
min a b β€ b : by apply min_le_right
... β€ a + b : le_add_of_nonneg_left ha
lemma max_le_add_of_nonneg {a b : Ξ±} (ha : a β₯ 0) (hb : b β₯ 0) : max a b β€ a + b :=
max_le_iff.2 (by split; simpa)
lemma max_zero_sub_eq_self (a : Ξ±) : max a 0 - max (-a) 0 = a :=
begin
rcases le_total a 0,
{ rw [max_eq_right h, max_eq_left, zero_sub, neg_neg], { rwa [le_neg, neg_zero] } },
{ rw [max_eq_left, max_eq_right, sub_zero], { rwa [neg_le, neg_zero] }, exact h }
end
lemma abs_max_sub_max_le_abs (a b c : Ξ±) : abs (max a c - max b c) β€ abs (a - b) :=
begin
simp only [max],
split_ifs,
{ rw [sub_self, abs_zero], exact abs_nonneg _ },
{ calc abs (c - b) = - (c - b) : abs_of_neg (sub_neg_of_lt (lt_of_not_ge h_1))
... = b - c : neg_sub _ _
... β€ b - a : by { rw sub_le_sub_iff_left, exact h }
... = - (a - b) : by rw neg_sub
... β€ abs (a - b) : neg_le_abs_self _ },
{ calc abs (a - c) = a - c : abs_of_pos (sub_pos_of_lt (lt_of_not_ge h))
... β€ a - b : by { rw sub_le_sub_iff_left, exact h_1 }
... β€ abs (a - b) : le_abs_self _ },
{ refl }
end
lemma max_sub_min_eq_abs' (a b : Ξ±) : max a b - min a b = abs (a - b) :=
begin
cases le_total a b with ab ba,
{ rw [max_eq_right ab, min_eq_left ab, abs_of_nonpos, neg_sub], rwa sub_nonpos },
{ rw [max_eq_left ba, min_eq_right ba, abs_of_nonneg], exact sub_nonneg_of_le ba }
end
lemma max_sub_min_eq_abs (a b : Ξ±) : max a b - min a b = abs (b - a) :=
by { rw [abs_sub], exact max_sub_min_eq_abs' _ _ }
end decidable_linear_ordered_add_comm_group
section decidable_linear_ordered_semiring
variables [decidable_linear_ordered_semiring Ξ±] {a b c d : Ξ±}
lemma monotone_mul_left_of_nonneg (ha : 0 β€ a) : monotone (Ξ» x, a*x) :=
assume b c b_le_c, mul_le_mul_of_nonneg_left b_le_c ha
lemma monotone_mul_right_of_nonneg (ha : 0 β€ a) : monotone (Ξ» x, x*a) :=
assume b c b_le_c, mul_le_mul_of_nonneg_right b_le_c ha
lemma mul_max_of_nonneg (b c : Ξ±) (ha : 0 β€ a) : a * max b c = max (a * b) (a * c) :=
(monotone_mul_left_of_nonneg ha).map_max
lemma mul_min_of_nonneg (b c : Ξ±) (ha : 0 β€ a) : a * min b c = min (a * b) (a * c) :=
(monotone_mul_left_of_nonneg ha).map_min
lemma max_mul_of_nonneg (a b : Ξ±) (hc : 0 β€ c) : max a b * c = max (a * c) (b * c) :=
(monotone_mul_right_of_nonneg hc).map_max
lemma min_mul_of_nonneg (a b : Ξ±) (hc : 0 β€ c) : min a b * c = min (a * c) (b * c) :=
(monotone_mul_right_of_nonneg hc).map_min
end decidable_linear_ordered_semiring
section decidable_linear_ordered_comm_ring
variables [decidable_linear_ordered_comm_ring Ξ±] {a b c d : Ξ±}
@[simp] lemma abs_one : abs (1 : Ξ±) = 1 := abs_of_pos zero_lt_one
lemma max_mul_mul_le_max_mul_max (b c : Ξ±) (ha : 0 β€ a) (hd: 0 β€ d) :
max (a * b) (d * c) β€ max a c * max d b :=
have ba : b * a β€ max d b * max c a,
from mul_le_mul (le_max_right d b) (le_max_right c a) ha (le_trans hd (le_max_left d b)),
have cd : c * d β€ max a c * max b d,
from mul_le_mul (le_max_right a c) (le_max_right b d) hd (le_trans ha (le_max_left a c)),
max_le
(by simpa [mul_comm, max_comm] using ba)
(by simpa [mul_comm, max_comm] using cd)
end decidable_linear_ordered_comm_ring
|
0b4a49f3ff8a69b002d868845fdbe53cd5ffa0c4 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /src/Lean/Elab/Term.lean | bd0e737ac248089adc3d180ee8768c9f3e7dae8c | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 60,403 | 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.ResolveName
import Lean.Util.Sorry
import Lean.Structure
import Lean.Meta.ExprDefEq
import Lean.Meta.AppBuilder
import Lean.Meta.SynthInstance
import Lean.Meta.CollectMVars
import Lean.Meta.Tactic.Util
import Lean.Hygiene
import Lean.Util.RecDepth
import Lean.Elab.Log
import Lean.Elab.Level
import Lean.Elab.Attributes
import Lean.Elab.AutoBound
import Lean.Elab.InfoTree
namespace Lean.Elab.Term
/-
Set isDefEq configuration for the elaborator.
Note that we enable all approximations but `quasiPatternApprox`
In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration.
The example:
```
def ex : StateT Ξ΄ (StateT Ο Id) Ο :=
monadLift (get : StateT Ο Id Ο)
```
demonstrates why it produces counterintuitive behavior.
We have the `Monad-lift` application:
```
@monadLift ?m ?n ?c ?Ξ± (get : StateT Ο id Ο) : ?n ?Ξ±
```
It produces the following unification problem when we process the expected type:
```
?n ?Ξ± =?= StateT Ξ΄ (StateT Ο id) Ο
==> (approximate using first-order unification)
?n := StateT Ξ΄ (StateT Ο id)
?Ξ± := Ο
```
Then, we need to solve:
```
?m ?Ξ± =?= StateT Ο id Ο
==> instantiate metavars
?m Ο =?= StateT Ο id Ο
==> (approximate since it is a quasi-pattern unification constraint)
?m := fun Ο => StateT Ο id Ο
```
Note that the constraint is not a Milner pattern because Ο is in
the local context of `?m`. We are ignoring the other possible solutions:
```
?m := fun Ο' => StateT Ο id Ο
?m := fun Ο' => StateT Ο' id Ο
?m := fun Ο' => StateT Ο id Ο'
```
We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions).
If we had use first-order unification, then we would have produced
the right answer: `?m := StateT Ο id`
Haskell would work on this example since it always uses
first-order unification.
-/
def setElabConfig (cfg : Meta.Config) : Meta.Config :=
{ cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false }
structure Context where
fileName : String
fileMap : FileMap
declName? : Option Name := none
macroStack : MacroStack := []
currMacroScope : MacroScope := firstFrontendMacroScope
/- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`.
The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in
the list of pending synthetic metavariables, and returns `?m`. -/
mayPostpone : Bool := true
/- When `errToSorry` is set to true, the method `elabTerm` catches
exceptions and converts them into synthetic `sorry`s.
The implementation of choice nodes and overloaded symbols rely on the fact
that when `errToSorry` is set to false for an elaboration function `F`, then
`errToSorry` remains `false` for all elaboration functions invoked by `F`.
That is, it is safe to transition `errToSorry` from `true` to `false`, but
we must not set `errToSorry` to `true` when it is currently set to `false`. -/
errToSorry : Bool := true
/- When `autoBoundImplicit` is set to true, instead of producing
an "unknown identifier" error for unbound variables, we generate an
internal exception. This exception is caught at `elabBinders` and
`elabTypeWithUnboldImplicit`. Both methods add implicit declarations
for the unbound variable and try again. -/
autoBoundImplicit : Bool := false
autoBoundImplicits : Std.PArray Expr := {}
/-- We use synthetic metavariables as placeholders for pending elaboration steps. -/
inductive SyntheticMVarKind where
-- typeclass instance search
| typeClass
/- Similar to typeClass, but error messages are different.
if `f?` is `some f`, we produce an application type mismatch error message.
Otherwise, if `header?` is `some header`, we generate the error `(header ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)`
Otherwise, we generate the error `("type mismatch" ++ e ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` -/
| coe (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr)
-- tactic block execution
| tactic (declName? : Option Name) (tacticCode : Syntax)
-- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`)
| postponed (macroStack : MacroStack) (declName? : Option Name)
structure SyntheticMVarDecl where
mvarId : MVarId
stx : Syntax
kind : SyntheticMVarKind
inductive MVarErrorKind where
| implicitArg (ctx : Expr)
| hole
| custom (msgData : MessageData)
structure MVarErrorInfo where
mvarId : MVarId
ref : Syntax
kind : MVarErrorKind
structure LetRecToLift where
ref : Syntax
fvarId : FVarId
attrs : Array Attribute
shortDeclName : Name
declName : Name
lctx : LocalContext
localInstances : LocalInstances
type : Expr
val : Expr
mvarId : MVarId
structure State where
levelNames : List Name := []
syntheticMVars : List SyntheticMVarDecl := []
mvarErrorInfos : List MVarErrorInfo := []
messages : MessageLog := {}
letRecsToLift : List LetRecToLift := []
infoState : InfoState := {}
deriving Inhabited
abbrev TermElabM := ReaderT Context $ StateRefT State MetaM
abbrev TermElab := Syntax β Option Expr β TermElabM Expr
open Meta
instance {Ξ±} : Inhabited (TermElabM Ξ±) where
default := throw arbitrary
structure SavedState where
core : Core.State
meta : Meta.State
Β«elabΒ» : State
deriving Inhabited
def saveAllState : TermElabM SavedState := do
pure { core := (β getThe Core.State), meta := (β getThe Meta.State), Β«elabΒ» := (β get) }
def SavedState.restore (s : SavedState) : TermElabM Unit := do
let traceState β getTraceState -- We never backtrack trace message
set s.core
set s.meta
set s.elab
setTraceState traceState
abbrev TermElabResult := EStateM.Result Exception SavedState Expr
instance : Inhabited TermElabResult where
default := EStateM.Result.ok arbitrary arbitrary
def setMessageLog (messages : MessageLog) : TermElabM Unit :=
modify fun s => { s with messages := messages }
def resetMessageLog : TermElabM Unit :=
setMessageLog {}
def getMessageLog : TermElabM MessageLog :=
return (β get).messages
/--
Execute `x`, save resulting expression and new state.
If `x` fails, then it also stores exception and new state.
Remark: we do not capture `Exception.postpone`. -/
@[inline] def observing (x : TermElabM Expr) : TermElabM TermElabResult := do
let s β saveAllState
try
let e β x
let sNew β saveAllState
s.restore
pure (EStateM.Result.ok e sNew)
catch
| ex@(Exception.error _ _) =>
let sNew β saveAllState
s.restore
pure (EStateM.Result.error ex sNew)
| ex@(Exception.internal id _) =>
if id == postponeExceptionId then s.restore
throw ex
/--
Apply the result/exception and state captured with `observing`.
We use this method to implement overloaded notation and symbols. -/
def applyResult (result : TermElabResult) : TermElabM Expr :=
match result with
| EStateM.Result.ok e r => do r.restore; pure e
| EStateM.Result.error ex r => do r.restore; throw ex
@[inline] protected def liftMetaM {Ξ±} (x : MetaM Ξ±) : TermElabM Ξ± :=
liftM x
@[inline] def liftCoreM {Ξ±} (x : CoreM Ξ±) : TermElabM Ξ± :=
Term.liftMetaM $ liftM x
instance : MonadLiftT MetaM TermElabM where
monadLift := Term.liftMetaM
def getLevelNames : TermElabM (List Name) :=
return (β get).levelNames
def getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do
match (β getLCtx).find? fvar.fvarId! with
| some d => pure d
| none => unreachable!
instance : AddErrorMessageContext TermElabM where
add ref msg := do
let ctx β read
let ref := getBetterRef ref ctx.macroStack
let msg β addMessageContext msg
let msg β addMacroStack msg ctx.macroStack
pure (ref, msg)
instance : MonadLog TermElabM where
getRef := getRef
getFileMap := return (β read).fileMap
getFileName := return (β read).fileName
logMessage msg := do
let ctx β readThe Core.Context
let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data };
modify fun s => { s with messages := s.messages.add msg }
protected def getCurrMacroScope : TermElabM MacroScope := do pure (β read).currMacroScope
protected def getMainModule : TermElabM Name := do pure (β getEnv).mainModule
@[inline] protected def withFreshMacroScope {Ξ±} (x : TermElabM Ξ±) : TermElabM Ξ± := do
let fresh β modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }))
withReader (fun ctx => { ctx with currMacroScope := fresh }) x
instance : MonadQuotation TermElabM where
getCurrMacroScope := Term.getCurrMacroScope
getMainModule := Term.getMainModule
withFreshMacroScope := Term.withFreshMacroScope
instance : MonadInfoTree TermElabM where
getInfoState := return (β get).infoState
modifyInfoState f := modify fun s => { s with infoState := f s.infoState }
unsafe def mkTermElabAttributeUnsafe : IO (KeyedDeclsAttribute TermElab) :=
mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term"
@[implementedBy mkTermElabAttributeUnsafe]
constant mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab)
builtin_initialize termElabAttribute : KeyedDeclsAttribute TermElab β mkTermElabAttribute
/--
Auxiliary datatatype for presenting a Lean lvalue modifier.
We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`.
Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list
`[LVal.fieldName "foo", LVal.getOp i, LVal.fieldIdx 1]`.
Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/
inductive LVal where
| fieldIdx (ref : Syntax) (i : Nat)
| fieldName (ref : Syntax) (name : String)
| getOp (ref : Syntax) (idx : Syntax)
def LVal.getRef : LVal β Syntax
| LVal.fieldIdx ref _ => ref
| LVal.fieldName ref _ => ref
| LVal.getOp ref _ => ref
instance : ToString LVal where
toString
| LVal.fieldIdx _ i => toString i
| LVal.fieldName _ n => n
| LVal.getOp _ idx => "[" ++ toString idx ++ "]"
def getDeclName? : TermElabM (Option Name) := return (β read).declName?
def getLetRecsToLift : TermElabM (List LetRecToLift) := return (β get).letRecsToLift
def isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := return (β getMCtx).isExprAssigned mvarId
def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (β getMCtx).getDecl mvarId
def assignLevelMVar (mvarId : MVarId) (val : Level) : TermElabM Unit := modifyThe Meta.State fun s => { s with mctx := s.mctx.assignLevel mvarId val }
def withDeclName {Ξ±} (name : Name) (x : TermElabM Ξ±) : TermElabM Ξ± :=
withReader (fun ctx => { ctx with declName? := name }) x
def setLevelNames (levelNames : List Name) : TermElabM Unit :=
modify fun s => { s with levelNames := levelNames }
def withLevelNames {Ξ±} (levelNames : List Name) (x : TermElabM Ξ±) : TermElabM Ξ± := do
let levelNamesSaved β getLevelNames
setLevelNames levelNames
try x finally setLevelNames levelNamesSaved
def withoutErrToSorry {Ξ±} (x : TermElabM Ξ±) : TermElabM Ξ± :=
withReader (fun ctx => { ctx with errToSorry := false }) x
/-- Execute `x` with `autoBoundImplicit = (options.get `autoBoundImplicitLocal) && flag` -/
def withAutoBoundImplicitLocal {Ξ±} (x : TermElabM Ξ±) (flag := true) : TermElabM Ξ± := do
let flag := getAutoBoundImplicitLocalOption (β getOptions) && flag
withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) x
/-- For testing `TermElabM` methods. The #eval command will sign the error. -/
def throwErrorIfErrors : TermElabM Unit := do
if (β get).messages.hasErrors then
throwError "Error(s)"
@[inline] def traceAtCmdPos (cls : Name) (msg : Unit β MessageData) : TermElabM Unit :=
withRef Syntax.missing $ trace cls msg
def ppGoal (mvarId : MVarId) : TermElabM Format := liftMetaM $ Meta.ppGoal mvarId
@[inline] def savingMCtx {Ξ±} (x : TermElabM Ξ±) : TermElabM Ξ± := do
let mctx β getMCtx
try x finally setMCtx mctx
open Level (LevelElabM)
def liftLevelM {Ξ±} (x : LevelElabM Ξ±) : TermElabM Ξ± := do
let ctx β read
let ref β getRef
let mctx β getMCtx
let ngen β getNGen
let lvlCtx : Level.Context := { ref := ref, autoBoundImplicit := ctx.autoBoundImplicit }
match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (β getLevelNames) } with
| EStateM.Result.ok a newS => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a
| EStateM.Result.error ex _ => throw ex
def elabLevel (stx : Syntax) : TermElabM Level :=
liftLevelM $ Level.elabLevel stx
/- Elaborate `x` with `stx` on the macro stack -/
@[inline] def withMacroExpansion {Ξ±} (beforeStx afterStx : Syntax) (x : TermElabM Ξ±) : TermElabM Ξ± :=
withMacroExpansionInfo beforeStx afterStx do
withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x
/-
Add the given metavariable to the list of pending synthetic metavariables.
The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/
def registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do
modify fun s => { s with syntheticMVars := { mvarId := mvarId, stx := stx, kind := kind } :: s.syntheticMVars }
def registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do
registerSyntheticMVar (β getRef) mvarId kind
def registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := do
modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.hole } :: s.mvarErrorInfos }
def registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do
modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.implicitArg app } :: s.mvarErrorInfos }
def registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do
modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.custom msgData } :: s.mvarErrorInfos }
def registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit :=
match e.getAppFn with
| Expr.mvar mvarId _ => registerMVarErrorCustomInfo mvarId ref msgData
| _ => pure ()
/-
Auxiliary method for reporting errors of the form "... contains metavariables ...".
This kind of error is thrown, for example, at `Match.lean` where elaboration
cannot continue if there are metavariables in patterns.
We only want to log it if we haven't logged any error so far. -/
def throwMVarError {Ξ±} (m : MessageData) : TermElabM Ξ± := do
if (β get).messages.hasErrors then
throwAbortTerm
else
throwError! m
def MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) : TermElabM Unit := do
match mvarErrorInfo.kind with
| MVarErrorKind.implicitArg app => do
let app β instantiateMVars app
let msg : MessageData := m!"don't know how to synthesize implicit argument{indentExpr app.setAppPPExplicit}"
let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId
logErrorAt mvarErrorInfo.ref msg
| MVarErrorKind.hole => do
let msg : MessageData := "don't know how to synthesize placeholder"
let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId
logErrorAt mvarErrorInfo.ref msg
| MVarErrorKind.custom msgData =>
logErrorAt mvarErrorInfo.ref msgData
/--
Try to log errors for the unassigned metavariables `pendingMVarIds`.
Return `true` if there were "unfilled holes", and we should "abort" declaration.
TODO: try to fill "all" holes using synthetic "sorry's"
Remark: We only log the "unfilled holes" as new errors if no error has been logged so far. -/
def logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) : TermElabM Bool := do
let s β get
let hasOtherErrors := s.messages.hasErrors
let mut hasNewErrors := false
let mut alreadyVisited : NameSet := {}
for mvarErrorInfo in s.mvarErrorInfos do
let mvarId := mvarErrorInfo.mvarId
unless alreadyVisited.contains mvarId do
alreadyVisited := alreadyVisited.insert mvarId
let foundError β withMVarContext mvarId do
/- The metavariable `mvarErrorInfo.mvarId` may have been assigned or
delayed assigned to another metavariable that is unassigned. -/
let mvarDeps β getMVars (mkMVar mvarId)
if mvarDeps.any pendingMVarIds.contains then do
unless hasOtherErrors do
mvarErrorInfo.logError
pure true
else
pure false
if foundError then
hasNewErrors := true
return hasNewErrors
/-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/
def ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do
let pendingMVarIds β getMVarsAtDecl decl
if (β logUnassignedUsingErrorInfos pendingMVarIds) then
throwAbortCommand
/-
Execute `x` without allowing it to postpone elaboration tasks.
That is, `tryPostpone` is a noop. -/
@[inline] def withoutPostponing {Ξ±} (x : TermElabM Ξ±) : TermElabM Ξ± :=
withReader (fun ctx => { ctx with mayPostpone := false }) x
/-- Creates syntax for `(` <ident> `:` <type> `)` -/
def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax :=
mkNode `Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"]
/--
Convert unassigned universe level metavariables into parameters.
The new parameter names are of the form `u_i` where `i >= nextParamIdx`.
The method returns the updated expression and new `nextParamIdx`.
Remark: we make sure the generated parameter names do not clash with the universes at `ctx.levelNames`. -/
def levelMVarToParam (e : Expr) (nextParamIdx : Nat := 1) : TermElabM (Expr Γ Nat) := do
let mctx β getMCtx
let levelNames β getLevelNames
let r := mctx.levelMVarToParam (fun n => levelNames.elem n) e `u nextParamIdx
setMCtx r.mctx
pure (r.expr, r.nextParamIdx)
/-- Variant of `levelMVarToParam` where `nextParamIdx` is stored in a state monad. -/
def levelMVarToParam' (e : Expr) : StateRefT Nat TermElabM Expr := do
let nextParamIdx β get
let (e, nextParamIdx) β levelMVarToParam e nextParamIdx
set nextParamIdx
pure e
/--
Auxiliary method for creating fresh binder names.
Do not confuse with the method for creating fresh free/meta variable ids. -/
def mkFreshBinderName : TermElabM Name :=
withFreshMacroScope $ MonadQuotation.addMacroScope `x
/--
Auxiliary method for creating a `Syntax.ident` containing
a fresh name. This method is intended for creating fresh binder names.
It is just a thin layer on top of `mkFreshUserName`. -/
def mkFreshIdent (ref : Syntax) : TermElabM Syntax :=
return mkIdentFrom ref (β mkFreshBinderName)
private def liftAttrM {Ξ±} (x : AttrM Ξ±) : TermElabM Ξ± := do
liftCoreM x
private def applyAttributesCore
(declName : Name) (attrs : Array Attribute)
(applicationTime? : Option AttributeApplicationTime) : TermElabM Unit :=
for attr in attrs do
let env β getEnv
match getAttributeImpl env attr.name with
| Except.error errMsg => throwError errMsg
| Except.ok attrImpl =>
match applicationTime? with
| none => liftAttrM <| attrImpl.add declName attr.stx attr.kind
| some applicationTime =>
if applicationTime == attrImpl.applicationTime then
liftAttrM <| attrImpl.add declName attr.stx attr.kind
/-- Apply given attributes **at** a given application time -/
def applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit :=
applyAttributesCore declName attrs applicationTime
def applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit :=
applyAttributesCore declName attrs none
def mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do
let header : MessageData := match header? with
| some header => m!"{header} "
| none => m!"type mismatch{indentExpr e}\n"
m!"{header}{β mkHasTypeButIsExpectedMsg eType expectedType}"
def throwTypeMismatchError {Ξ±} (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr)
(f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM Ξ± := do
/-
We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was
always of the form:
```
failed to synthesize instance
CoeT <eType> <e> <expectedType>
```
We should revisit this decision in the future and decide whether it may contain useful information
or not. -/
let extraMsg := Format.nil
/-
let extraMsg : MessageData := match extraMsg? with
| none => Format.nil
| some extraMsg => Format.line ++ extraMsg;
-/
match f? with
| none => throwError <| (β mkTypeMismatchError header? e eType expectedType) ++ extraMsg
| some f => Meta.throwAppTypeMismatch f e extraMsg
@[inline] def withoutMacroStackAtErr {Ξ±} (x : TermElabM Ξ±) : TermElabM Ξ± :=
withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := setMacroStackOption ctx.options false }) x
/- Try to synthesize metavariable using type class resolution.
This method assumes the local context and local instances of `instMVar` coincide
with the current local context and local instances.
Return `true` if the instance was synthesized successfully, and `false` if
the instance contains unassigned metavariables that are blocking the type class
resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/
def synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do
let instMVarDecl β getMVarDecl instMVar
let type := instMVarDecl.type
let type β instantiateMVars type
let result β trySynthInstance type maxResultSize?
match result with
| LOption.some val =>
if (β isExprMVarAssigned instMVar) then
let oldVal β instantiateMVars (mkMVar instMVar)
unless (β isDefEq oldVal val) do
throwError! "synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\ninferred{indentExpr oldVal}"
else
assignExprMVar instMVar val
pure true
| LOption.undef => pure false -- we will try later
| LOption.none => throwError! "failed to synthesize instance{indentExpr type}"
def maxCoeSizeDefault := 16
builtin_initialize
registerOption `maxCoeSize { defValue := maxCoeSizeDefault, group := "", descr := "maximum number of instances used to construct an automatic coercion" }
private def getCoeMaxSize (opts : Options) : Nat :=
opts.getNat `maxCoeSize maxCoeSizeDefault
def synthesizeCoeInstMVarCore (instMVar : MVarId) : TermElabM Bool := do
synthesizeInstMVarCore instMVar (getCoeMaxSize (β getOptions))
/-
The coercion from `Ξ±` to `Thunk Ξ±` cannot be implemented using an instance because it would
eagerly evaluate `e` -/
def tryCoeThunk? (expectedType : Expr) (eType : Expr) (e : Expr) : TermElabM (Option Expr) := do
match expectedType with
| Expr.app (Expr.const `Thunk u _) arg _ =>
if (β isDefEq eType arg) then
pure (some (mkApp2 (mkConst `Thunk.mk u) arg (mkSimpleThunk e)))
else
pure none
| _ =>
pure none
/--
Try to apply coercion to make sure `e` has type `expectedType`.
Relevant definitions:
```
class CoeT (Ξ± : Sort u) (a : Ξ±) (Ξ² : Sort v)
abbrev coe {Ξ± : Sort u} {Ξ² : Sort v} (a : Ξ±) [CoeT Ξ± a Ξ²] : Ξ²
``` -/
private def tryCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do
if (β isDefEq expectedType eType) then
pure e
else match (β tryCoeThunk? expectedType eType e) with
| some r => pure r
| none =>
let u β getLevel eType
let v β getLevel expectedType
let coeTInstType := mkAppN (mkConst `CoeT [u, v]) #[eType, e, expectedType]
let mvar β mkFreshExprMVar coeTInstType MetavarKind.synthetic
let eNew := mkAppN (mkConst `coe [u, v]) #[eType, expectedType, e, mvar]
let mvarId := mvar.mvarId!
try
withoutMacroStackAtErr do
unless (β synthesizeCoeInstMVarCore mvarId) do
registerSyntheticMVarWithCurrRef mvarId (SyntheticMVarKind.coe errorMsgHeader? expectedType eType e f?)
pure eNew
catch
| Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg
| _ => throwTypeMismatchError errorMsgHeader? expectedType eType e f?
private def isTypeApp? (type : Expr) : TermElabM (Option (Expr Γ Expr)) := do
let type β withReducible $ whnf type
match type with
| Expr.app m Ξ± _ => pure (some ((β instantiateMVars m), (β instantiateMVars Ξ±)))
| _ => pure none
/-
private def isMonad? (type : Expr) : TermElabM (Option IsMonadResult) := do
let type β withReducible $ whnf type
match type with
| Expr.app m Ξ± _ =>
try
let monadType β mkAppM `Monad #[m]
let result β trySynthInstance monadType
match result with
| LOption.some inst => pure (some { m := m, Ξ± := Ξ±, inst := inst })
| _ => pure none
catch _ => pure none
| _ => pure none
-/
private def isMonad? (m : Expr) : TermElabM (Option Expr) :=
try
let monadType β mkAppM `Monad #[m]
let result β trySynthInstance monadType
match result with
| LOption.some inst => pure inst
| _ => pure none
catch _ =>
pure none
def synthesizeInst (type : Expr) : TermElabM Expr := do
let type β instantiateMVars type
match (β trySynthInstance type) with
| LOption.some val => pure val
| LOption.undef => throwError! "failed to synthesize instance{indentExpr type}"
| LOption.none => throwError! "failed to synthesize instance{indentExpr type}"
def isMonadApp (type : Expr) : TermElabM Bool := do
let some (m, _) β isTypeApp? type | pure false
return (β isMonad? m) |>.isSome
/--
Try to coerce `a : Ξ±` into `m Ξ²` by first coercing `a : Ξ±` into β΅Ξ²`, and then using `pure`.
The method is only applied if `Ξ±` is not monadic (e.g., `Nat β IO Unit`), and the head symbol
of the resulting type is not a metavariable (e.g., `?m Unit` or `Bool β ?m Nat`).
The main limitation of the approach above is polymorphic code. As usual, coercions and polymorphism
do not interact well. In the example above, the lift is successfully applied to `true`, `false` and `!y`
since none of them is polymorphic
```
def f (x : Bool) : IO Bool := do
let y β if x == 0 then IO.println "hello"; true else false;
!y
```
On the other hand, the following fails since `+` is polymorphic
```
def f (x : Bool) : IO Nat := do
IO.prinln x
x + x -- Error: failed to synthesize `Add (IO Nat)`
```
-/
private def tryPureCoe? (errorMsgHeader? : Option String) (m Ξ² Ξ± a : Expr) : TermElabM (Option Expr) := do
let doIt : TermElabM (Option Expr) := do
try
let aNew β tryCoe errorMsgHeader? Ξ² Ξ± a none
let aNew β mkPure m aNew
pure (some aNew)
catch _ =>
pure none
forallTelescope Ξ± fun _ Ξ± => do
if (β isMonadApp Ξ±) then
pure none
else if !Ξ±.getAppFn.isMVar then
doIt
else
pure none
/-
Try coercions and monad lifts to make sure `e` has type `expectedType`.
If `expectedType` is of the form `n Ξ²`, we try monad lifts and other extensions.
Otherwise, we just use the basic `tryCoe`.
Extensions for monads.
Given an expected type of the form `n Ξ²`, if `eType` is of the form `Ξ±`, but not `m Ξ±`
1 - Try to coerce β΅Ξ±` into β΅Ξ²`, and use `pure` to lift it to `n Ξ±`.
It only works if `n` implements `Pure`
If `eType` is of the form `m Ξ±`. We use the following approaches.
1- Try to unify `n` and `m`. If it succeeds, then we use
```
coeM {m : Type u β Type v} {Ξ± Ξ² : Type u} [β a, CoeT Ξ± a Ξ²] [Monad m] (x : m Ξ±) : m Ξ²
```
`n` must be a `Monad` to use this one.
2- If there is monad lift from `m` to `n` and we can unify `Ξ±` and `Ξ²`, we use
```
liftM : β {m : Type u_1 β Type u_2} {n : Type u_1 β Type u_3} [self : MonadLiftT m n] {Ξ± : Type u_1}, m Ξ± β n Ξ±
```
Note that `n` may not be a `Monad` in this case. This happens quite a bit in code such as
```
def g (x : Nat) : IO Nat := do
IO.println x
pure x
def f {m} [MonadLiftT IO m] : m Nat :=
g 10
```
3- If there is a monad lif from `m` to `n` and a coercion from `Ξ±` to `Ξ²`, we use
```
liftCoeM {m : Type u β Type v} {n : Type u β Type w} {Ξ± Ξ² : Type u} [MonadLiftT m n] [β a, CoeT Ξ± a Ξ²] [Monad n] (x : m Ξ±) : n Ξ²
```
Note that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `Ξ±` to `Ξ²` for all values in `Ξ±`.
This is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and
we only have a coercion from decidable propositions. Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)`
using the instance `pureCoeDepProp`.
Note that, approach 2 is more powerful than `tryCoe`.
Recall that type class resolution never assigns metavariables created by other modules.
Now, consider the following scenario
```lean
def g (x : Nat) : IO Nat := ...
deg h (x : Nat) : StateT Nat IO Nat := do
v β g x;
IO.Println v;
...
```
Let's assume there is no other occurrence of `v` in `h`.
Thus, we have that the expected of `g x` is `StateT Nat IO ?Ξ±`,
and the given type is `IO Nat`. So, even if we add a coercion.
```
instance {Ξ± m n} [MonadLiftT m n] {Ξ±} : Coe (m Ξ±) (n Ξ±) := ...
```
It is not applicable because TC would have to assign `?Ξ± := Nat`.
On the other hand, TC can easily solve `[MonadLiftT IO (StateT Nat IO)]`
since this goal does not contain any metavariables. And then, we
convert `g x` into `liftM $ g x`.
-/
private def tryLiftAndCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do
let expectedType β instantiateMVars expectedType
let eType β instantiateMVars eType
let throwMismatch {Ξ±} : TermElabM Ξ± := throwTypeMismatchError errorMsgHeader? expectedType eType e f?
let tryCoeSimple : TermElabM Expr :=
tryCoe errorMsgHeader? expectedType eType e f?
let some (n, Ξ²) β isTypeApp? expectedType | tryCoeSimple
let tryPureCoeAndSimple : TermElabM Expr := do
match (β tryPureCoe? errorMsgHeader? n Ξ² eType e) with
| some eNew => pure eNew
| none => tryCoeSimple
let some (m, Ξ±) β isTypeApp? eType | tryPureCoeAndSimple
if (β isDefEq m n) then
let some monadInst β isMonad? n | tryCoeSimple
try mkAppOptM `coeM #[m, Ξ±, Ξ², none, monadInst, e] catch _ => throwMismatch
else
try
-- Construct lift from `m` to `n`
let monadLiftType β mkAppM `MonadLiftT #[m, n]
let monadLiftVal β synthesizeInst monadLiftType
let u_1 β getDecLevel Ξ±
let u_2 β getDecLevel eType
let u_3 β getDecLevel expectedType
let eNew := mkAppN (Lean.mkConst `liftM [u_1, u_2, u_3]) #[m, n, monadLiftVal, Ξ±, e]
let eNewType β inferType eNew
if (β isDefEq expectedType eNewType) then
pure eNew -- approach 2 worked
else
let some monadInst β isMonad? n | tryCoeSimple
let u β getLevel Ξ±
let v β getLevel Ξ²
let coeTInstType := Lean.mkForall `a BinderInfo.default Ξ± $ mkAppN (mkConst `CoeT [u, v]) #[Ξ±, mkBVar 0, Ξ²]
let coeTInstVal β synthesizeInst coeTInstType
let eNew := mkAppN (Lean.mkConst `liftCoeM [u_1, u_2, u_3]) #[m, n, Ξ±, Ξ², monadLiftVal, coeTInstVal, monadInst, e]
let eNewType β inferType eNew
unless (β isDefEq expectedType eNewType) do throwMismatch
pure eNew -- approach 3 worked
catch _ =>
/-
If `m` is not a monad, then we try to use `tryPureCoe?` and then `tryCoe?`.
Otherwise, we just try `tryCoe?`.
-/
match (β isMonad? m) with
| none => tryPureCoeAndSimple
| some _ => tryCoeSimple
/--
If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal.
If they are not, then try coercions.
Argument `f?` is used only for generating error messages. -/
def ensureHasTypeAux (expectedType? : Option Expr) (eType : Expr) (e : Expr)
(f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do
match expectedType? with
| none => pure e
| some expectedType =>
if (β isDefEq eType expectedType) then
pure e
else
tryLiftAndCoe errorMsgHeader? expectedType eType e f?
/--
If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal.
If they are not, then try coercions. -/
def ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) : TermElabM Expr :=
match expectedType? with
| none => pure e
| _ => do
let eType β inferType e
ensureHasTypeAux expectedType? eType e none errorMsgHeader?
private def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do
let expectedType β match expectedType? with
| none => mkFreshTypeMVar
| some expectedType => pure expectedType
let syntheticSorry β mkSyntheticSorry expectedType
logException ex
pure syntheticSorry
/-- If `mayPostpone == true`, throw `Expection.postpone`. -/
def tryPostpone : TermElabM Unit := do
if (β read).mayPostpone then
throwPostpone
/-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/
def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do
if e.getAppFn.isMVar then
let e β instantiateMVars e
if e.getAppFn.isMVar then
tryPostpone
def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit :=
match e? with
| some e => tryPostponeIfMVar e
| none => tryPostpone
def tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do
tryPostponeIfNoneOrMVar expectedType?
let some expectedType β pure expectedType? |
throwError! "{msg}, expected type must be known"
let expectedType β instantiateMVars expectedType
if expectedType.hasExprMVar then
tryPostpone
throwError! "{msg}, expected type contains metavariables{indentExpr expectedType}"
pure expectedType
private def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
trace[Elab.postpone]! "{stx} : {expectedType?}"
let mvar β mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque
let ctx β read
registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed ctx.macroStack ctx.declName?)
pure mvar
/-
Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or
an error is found. -/
private def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool)
: List TermElab β TermElabM Expr
| [] => do throwError! "unexpected syntax{indentD stx}"
| (elabFn::elabFns) => do
try
elabFn stx expectedType?
catch ex => match ex with
| Exception.error _ _ =>
if (β read).errToSorry then
exceptionToSorry ex expectedType?
else
throw ex
| Exception.internal id _ =>
if (β read).errToSorry && id == abortTermExceptionId then
exceptionToSorry ex expectedType?
else if id == unsupportedSyntaxExceptionId then
s.restore
elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns
else if catchExPostpone && id == postponeExceptionId then
/- If `elab` threw `Exception.postpone`, we reset any state modifications.
For example, we want to make sure pending synthetic metavariables created by `elab` before
it threw `Exception.postpone` are discarded.
Note that we are also discarding the messages created by `elab`.
For example, consider the expression.
`((f.x a1).x a2).x a3`
Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`.
Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone`
because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and
finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would
keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is
wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch
and new metavariables are created for the nested functions. -/
s.restore
postponeElabTerm stx expectedType?
else
throw ex
private def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do
let s β saveAllState
let table := termElabAttribute.ext.getState (β getEnv) |>.table
let k := stx.getKind
match table.find? k with
| some elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns
| none => throwError! "elaboration function for '{k}' has not been implemented"
instance : MonadMacroAdapter TermElabM where
getCurrMacroScope := getCurrMacroScope
getNextMacroScope := return (β getThe Core.State).nextMacroScope
setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next }
private def isExplicit (stx : Syntax) : Bool :=
match stx with
| `(@$f) => true
| _ => false
private def isExplicitApp (stx : Syntax) : Bool :=
stx.getKind == `Lean.Parser.Term.app && isExplicit stx[0]
/--
Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation.
Example: `fun {Ξ±} (a : Ξ±) => a` -/
private def isLambdaWithImplicit (stx : Syntax) : Bool :=
match stx with
| `(fun $binders* => $body) => binders.any fun b => b.isOfKind `Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder
| _ => false
private partial def dropTermParens : Syntax β Syntax | stx =>
match stx with
| `(($stx)) => dropTermParens stx
| _ => stx
/-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/
def blockImplicitLambda (stx : Syntax) : Bool :=
let stx := dropTermParens stx
isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx
/--
Return normalized expected type if it is of the form `{a : Ξ±} β Ξ²` or `[a : Ξ±] β Ξ²` and
`blockImplicitLambda stx` is not true, else return `none`. -/
private def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) :=
if blockImplicitLambda stx then
pure none
else match expectedType? with
| some expectedType => do
let expectedType β whnfForall expectedType
match expectedType with
| Expr.forallE _ _ _ c => if c.binderInfo.isExplicit then pure none else pure $ some expectedType
| _ => pure none
| _ => pure none
private def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (fvars : Array Expr) : TermElabM Expr := do
let body β elabUsingElabFns stx expectedType catchExPostpone
let body β ensureHasType expectedType body
let r β mkLambdaFVars fvars body
trace[Elab.implicitForall]! r
pure r
private partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) : Expr β Array Expr β TermElabM Expr
| type@(Expr.forallE n d b c), fvars =>
if c.binderInfo.isExplicit then
elabImplicitLambdaAux stx catchExPostpone type fvars
else withFreshMacroScope do
let n β MonadQuotation.addMacroScope n
withLocalDecl n c.binderInfo d fun fvar => do
let type β whnfForall (b.instantiate1 fvar)
elabImplicitLambda stx catchExPostpone type (fvars.push fvar)
| type, fvars =>
elabImplicitLambdaAux stx catchExPostpone type fvars
/- Main loop for `elabTerm` -/
private partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax β TermElabM Expr
| stx => withFreshMacroScope $ withIncRecDepth do
trace[Elab.step]! "expected type: {expectedType?}, term\n{stx}"
withNestedTraces do
let env β getEnv
let stxNew? β catchInternalId unsupportedSyntaxExceptionId
(do let newStx β adaptMacro (getMacros env) stx; pure (some newStx))
(fun _ => pure none)
match stxNew? with
| some stxNew => withMacroExpansion stx stxNew $ elabTermAux expectedType? catchExPostpone implicitLambda stxNew
| _ =>
let implicit? β if implicitLambda then useImplicitLambda? stx expectedType? else pure none
match implicit? with
| some expectedType => elabImplicitLambda stx catchExPostpone expectedType #[]
| none => elabUsingElabFns stx expectedType? catchExPostpone
def addTermInfo (stx : Syntax) (e : Expr) : TermElabM Unit := do
if (β getInfoState).enabled then
pushInfoTree <| InfoTree.node (children := {}) <| Info.ofTermInfo { lctx := (β getLCtx), expr := e, stx := stx }
def mkTermInfo (stx : Syntax) (e : Expr) : TermElabM (Sum Info MVarId) := do
let isHole? : TermElabM (Option MVarId) := do
match e with
| Expr.mvar mvarId _ =>
let isHole := (β get).syntheticMVars.any fun d => match d.kind with
| SyntheticMVarKind.tactic .. => true
| SyntheticMVarKind.postponed .. => true
| _ => false
if isHole then pure mvarId else pure none
| _ => pure none
match (β isHole?) with
| none => return Sum.inl <| Info.ofTermInfo { lctx := (β getLCtx), expr := e, stx := stx }
| some mvarId => return Sum.inr mvarId
/--
Main function for elaborating terms.
It extracts the elaboration methods from the environment using the node kind.
Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods.
It creates a fresh macro scope for executing the elaboration method.
All unlogged trace messages produced by the elaboration method are logged using
the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`,
the error is logged and a synthetic sorry expression is returned.
If the elaboration throws `Exception.postpone` and `catchExPostpone == true`,
a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered,
and returned.
The option `catchExPostpone == false` is used to implement `resumeElabTerm`
to prevent the creation of another synthetic metavariable when resuming the elaboration. -/
def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) : TermElabM Expr :=
withInfoContext' (withRef stx <| elabTermAux expectedType? catchExPostpone true stx) (mkTermInfo stx)
def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do
let e β elabTerm stx expectedType? catchExPostpone
withRef stx $ ensureHasType expectedType? e errorMsgHeader?
def elabTermWithoutImplicitLambdas (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) : TermElabM Expr := do
elabTermAux expectedType? catchExPostpone false stx
/-- Adapt a syntax transformation to a regular, term-producing elaborator. -/
def adaptExpander (exp : Syntax β TermElabM Syntax) : TermElab := fun stx expectedType? => do
let stx' β exp stx
withMacroExpansion stx stx' $ elabTerm stx' expectedType?
def mkInstMVar (type : Expr) : TermElabM Expr := do
let mvar β mkFreshExprMVar type MetavarKind.synthetic
let mvarId := mvar.mvarId!
unless (β synthesizeInstMVarCore mvarId) do
registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass
pure mvar
/-
Relevant definitions:
```
class CoeSort (Ξ± : Sort u) (Ξ² : outParam (Sort v))
abbrev coeSort {Ξ± : Sort u} {Ξ² : Sort v} (a : Ξ±) [CoeSort Ξ± Ξ²] : Ξ²
``` -/
private def tryCoeSort (Ξ± : Expr) (a : Expr) : TermElabM Expr := do
let Ξ² β mkFreshTypeMVar
let u β getLevel Ξ±
let v β getLevel Ξ²
let coeSortInstType := mkAppN (Lean.mkConst `CoeSort [u, v]) #[Ξ±, Ξ²]
let mvar β mkFreshExprMVar coeSortInstType MetavarKind.synthetic
let mvarId := mvar.mvarId!
try
withoutMacroStackAtErr do
if (β synthesizeCoeInstMVarCore mvarId) then
pure $ mkAppN (Lean.mkConst `coeSort [u, v]) #[Ξ±, Ξ², a, mvar]
else
throwError "type expected"
catch
| Exception.error _ msg => throwError! "type expected\n{msg}"
| _ => throwError! "type expected"
/--
Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort`
or is unifiable with `Expr.sort`, or can be coerced into one. -/
def ensureType (e : Expr) : TermElabM Expr := do
if (β isType e) then
pure e
else
let eType β inferType e
let u β mkFreshLevelMVar
if (β isDefEq eType (mkSort u)) then
pure e
else
tryCoeSort eType e
/-- Elaborate `stx` and ensure result is a type. -/
def elabType (stx : Syntax) : TermElabM Expr := do
let u β mkFreshLevelMVar
let type β elabTerm stx (mkSort u)
withRef stx $ ensureType type
/--
Elaborate `stx` creating new implicit variables for unbound ones when `autoBoundImplicit == true`, and then
execute the continuation `k` in the potentially extended local context.
The auto bound implicit locals are stored in the context variable `autoBoundImplicits`
-/
partial def elabTypeWithAutoBoundImplicit {Ξ±} (stx : Syntax) (k : Expr β TermElabM Ξ±) : TermElabM Ξ± := do
if (β read).autoBoundImplicit then
let rec loop : TermElabM Ξ± := do
try
k (β elabType stx)
catch
| ex => match isAutoBoundImplicitLocalException? ex with
| some n =>
withLocalDecl n BinderInfo.implicit (β mkFreshTypeMVar) fun x =>
withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } )
loop
| none => throw ex
loop
else
k (β elabType stx)
/--
Return `autoBoundImplicits ++ xs.
This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs` -/
def addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do
let autoBoundImplicits := (β read).autoBoundImplicits
for auto in autoBoundImplicits do
let localDecl β getLocalDecl auto.fvarId!
for x in xs do
if (β getMCtx).localDeclDependsOn localDecl x.fvarId! then
throwError! "invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'"
return autoBoundImplicits.toArray ++ xs
def mkAuxName (suffix : Name) : TermElabM Name := do
match (β read).declName? with
| none => throwError "auxiliary declaration cannot be created when declaration name is not available"
| some declName => Lean.mkAuxName (declName ++ suffix) 1
builtin_initialize registerTraceClass `Elab.letrec
/- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it
is delayed assigned to one. -/
def isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do
trace[Elab.letrec]! "mvarId: {mkMVar mvarId} letrecMVars: {(β get).letRecsToLift.map (mkMVar $ Β·.mvarId)}"
let mvarId := (β getMCtx).getDelayedRoot mvarId
trace[Elab.letrec]! "mvarId root: {mkMVar mvarId}"
return (β get).letRecsToLift.any (Β·.mvarId == mvarId)
/- =======================================
Builtin elaboration functions
======================================= -/
@[builtinTermElab Β«propΒ»] def elabProp : TermElab := fun _ _ =>
return mkSort levelZero
private def elabOptLevel (stx : Syntax) : TermElabM Level :=
if stx.isNone then
pure levelZero
else
elabLevel stx[0]
@[builtinTermElab Β«sortΒ»] def elabSort : TermElab := fun stx _ =>
return mkSort (β elabOptLevel stx[1])
@[builtinTermElab Β«typeΒ»] def elabTypeStx : TermElab := fun stx _ =>
return mkSort (mkLevelSucc (β elabOptLevel stx[1]))
@[builtinTermElab Β«holeΒ»] def elabHole : TermElab := fun stx expectedType? => do
let mvar β mkFreshExprMVar expectedType?
registerMVarErrorHoleInfo mvar.mvarId! stx
pure mvar
@[builtinTermElab Β«syntheticHoleΒ»] def elabSyntheticHole : TermElab := fun stx expectedType? => do
let arg := stx[1]
let userName := if arg.isIdent then arg.getId else Name.anonymous
let mkNewHole : Unit β TermElabM Expr := fun _ => do
let mvar β mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque userName
registerMVarErrorHoleInfo mvar.mvarId! stx
pure mvar
if userName.isAnonymous then
mkNewHole ()
else
let mctx β getMCtx
match mctx.findUserName? userName with
| none => mkNewHole ()
| some mvarId =>
let mvar := mkMVar mvarId
let mvarDecl β getMVarDecl mvarId
let lctx β getLCtx
if mvarDecl.lctx.isSubPrefixOf lctx then
pure mvar
else match mctx.getExprAssignment? mvarId with
| some val =>
let val β instantiateMVars val
if mctx.isWellFormed lctx val then
pure val
else
withLCtx mvarDecl.lctx mvarDecl.localInstances do
throwError! "synthetic hole has already been defined and assigned to value incompatible with the current context{indentExpr val}"
| none =>
if mctx.isDelayedAssigned mvarId then
-- We can try to improve this case if needed.
throwError "synthetic hole has already beend defined and delayed assigned with an incompatible local context"
else if lctx.isSubPrefixOf mvarDecl.lctx then
let mvarNew β mkNewHole ()
modifyMCtx fun mctx => mctx.assignExpr mvarId mvarNew
pure mvarNew
else
throwError "synthetic hole has already been defined with an incompatible local context"
private def mkTacticMVar (type : Expr) (tacticCode : Syntax) : TermElabM Expr := do
let mvar β mkFreshExprMVar type MetavarKind.syntheticOpaque
let mvarId := mvar.mvarId!
let ref β getRef
let declName? β getDeclName?
registerSyntheticMVar ref mvarId $ SyntheticMVarKind.tactic declName? tacticCode
pure mvar
@[builtinTermElab byTactic] def elabByTactic : TermElab := fun stx expectedType? =>
match expectedType? with
| some expectedType => mkTacticMVar expectedType stx
| none => throwError ("invalid 'by' tactic, expected type has not been provided")
def resolveLocalName (n : Name) : TermElabM (Option (Expr Γ List String)) := do
let lctx β getLCtx
let view := extractMacroScopes n
let rec loop (n : Name) (projs : List String) :=
match lctx.findFromUserName? { view with name := n }.review with
| some decl => some (decl.toExpr, projs)
| none => match n with
| Name.str pre s _ => loop pre (s::projs)
| _ => none
pure $ loop view.name []
/- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/
def isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) :=
match stx with
| Syntax.ident _ _ val _ => do
let r? β resolveLocalName val
match r? with
| some (fvar, []) => pure (some fvar)
| _ => pure none
| _ => pure none
def mkFreshLevelMVars (num : Nat) : MetaM (List Level) :=
num.foldM (init := []) fun _ us =>
return (β mkFreshLevelMVar)::us
/--
Create an `Expr.const` using the given name and explicit levels.
Remark: fresh universe metavariables are created if the constant has more universe
parameters than `explicitLevels`. -/
def mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do
let cinfo β getConstInfo constName
if explicitLevels.length > cinfo.lparams.length then
throwError "too many explicit universe levels"
else
let numMissingLevels := cinfo.lparams.length - explicitLevels.length
let us β mkFreshLevelMVars numMissingLevels
pure $ Lean.mkConst constName (explicitLevels ++ us)
private def mkConsts (candidates : List (Name Γ List String)) (explicitLevels : List Level) : TermElabM (List (Expr Γ List String)) := do
candidates.foldlM (init := []) fun result (constName, projs) => do
-- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail.
let const β mkConst constName explicitLevels
pure $ (const, projs) :: result
def resolveName (n : Name) (preresolved : List (Name Γ List String)) (explicitLevels : List Level) : TermElabM (List (Expr Γ List String)) := do
match (β resolveLocalName n) with
| some (e, projs) =>
unless explicitLevels.isEmpty do
throwError! "invalid use of explicit universe parameters, '{e}' is a local"
pure [(e, projs)]
| none =>
let process (candidates : List (Name Γ List String)) : TermElabM (List (Expr Γ List String)) := do
if candidates.isEmpty then
if (β read).autoBoundImplicit && isValidAutoBoundImplicitName n then
throwAutoBoundImplicitLocal n
else
throwError! "unknown identifier '{Lean.mkConst n}'"
mkConsts candidates explicitLevels
if preresolved.isEmpty then
process (β resolveGlobalName n)
else
process preresolved
def resolveId? (stx : Syntax) (kind := "term") : TermElabM (Option Expr) :=
match stx with
| Syntax.ident _ _ val preresolved => do
let rs β try resolveName val preresolved [] catch _ => pure []
let rs := rs.filter fun β¨f, projsβ© => projs.isEmpty
let fs := rs.map fun (f, _) => f
match fs with
| [] => pure none
| [f] => pure (some f)
| _ => throwError! "ambiguous {kind}, use fully qualified name, possible interpretations {fs}"
| _ => throwError "identifier expected"
@[builtinTermElab cdot] def elabBadCDot : TermElab := fun stx _ =>
throwError "invalid occurrence of `Β·` notation, it must be surrounded by parentheses (e.g. `(Β· + 1)`)"
@[builtinTermElab strLit] def elabStrLit : TermElab := fun stx _ => do
match stx.isStrLit? with
| some val => pure $ mkStrLit val
| none => throwIllFormedSyntax
private def mkFreshTypeMVarFor (expectedType? : Option Expr) : TermElabM Expr := do
let typeMVar β mkFreshTypeMVar MetavarKind.synthetic
match expectedType? with
| some expectedType => discard <| isDefEq expectedType typeMVar
| _ => pure ()
return typeMVar
@[builtinTermElab numLit] def elabNumLit : TermElab := fun stx expectedType? => do
let val β match stx.isNatLit? with
| some val => pure val
| none => throwIllFormedSyntax
let typeMVar β mkFreshTypeMVarFor expectedType?
let u β getDecLevel typeMVar
let mvar β mkInstMVar (mkApp2 (Lean.mkConst `OfNat [u]) typeMVar (mkNatLit val))
return mkApp3 (Lean.mkConst `OfNat.ofNat [u]) typeMVar (mkNatLit val) mvar
@[builtinTermElab rawNatLit] def elabRawNatLit : TermElab := fun stx expectedType? => do
match stx[1].isNatLit? with
| some val => return mkNatLit val
| none => throwIllFormedSyntax
@[builtinTermElab scientificLit]
def elabScientificLit : TermElab := fun stx expectedType? => do
match stx.isScientificLit? with
| none => throwIllFormedSyntax
| some (m, sign, e) =>
let typeMVar β mkFreshTypeMVarFor expectedType?
let u β getDecLevel typeMVar
let mvar β mkInstMVar (mkApp (Lean.mkConst `OfScientific [u]) typeMVar)
return mkApp5 (Lean.mkConst `OfScientific.ofScientific [u]) typeMVar mvar (mkNatLit m) (toExpr sign) (mkNatLit e)
@[builtinTermElab charLit] def elabCharLit : TermElab := fun stx _ => do
match stx.isCharLit? with
| some val => return mkApp (Lean.mkConst `Char.ofNat) (mkNatLit val.toNat)
| none => throwIllFormedSyntax
@[builtinTermElab quotedName] def elabQuotedName : TermElab := fun stx _ =>
match stx[0].isNameLit? with
| some val => pure $ toExpr val
| none => throwIllFormedSyntax
@[builtinTermElab doubleQuotedName] def elabDoubleQuotedName : TermElab := fun stx _ => do
match stx[1].isNameLit? with
| some val => toExpr (β resolveGlobalConstNoOverload val)
| none => throwIllFormedSyntax
@[builtinTermElab typeOf] def elabTypeOf : TermElab := fun stx _ => do
inferType (β elabTerm stx[1] none)
@[builtinTermElab ensureTypeOf] def elabEnsureTypeOf : TermElab := fun stx expectedType? =>
match stx[2].isStrLit? with
| none => throwIllFormedSyntax
| some msg => do
let refTerm β elabTerm stx[1] none
let refTermType β inferType refTerm
elabTermEnsuringType stx[3] refTermType true msg
@[builtinTermElab ensureExpectedType] def elabEnsureExpectedType : TermElab := fun stx expectedType? =>
match stx[1].isStrLit? with
| none => throwIllFormedSyntax
| some msg => elabTermEnsuringType stx[2] expectedType? true msg
private def mkSomeContext : Context := {
fileName := "<TermElabM>"
fileMap := arbitrary
}
@[inline] def TermElabM.run {Ξ±} (x : TermElabM Ξ±) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM (Ξ± Γ State) :=
withConfig setElabConfig (x ctx |>.run s)
@[inline] def TermElabM.run' {Ξ±} (x : TermElabM Ξ±) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM Ξ± :=
(Β·.1) <$> x.run ctx s
@[inline] def TermElabM.toIO {Ξ±} (x : TermElabM Ξ±)
(ctxCore : Core.Context) (sCore : Core.State)
(ctxMeta : Meta.Context) (sMeta : Meta.State)
(ctx : Context) (s : State) : IO (Ξ± Γ Core.State Γ Meta.State Γ State) := do
let ((a, s), sCore, sMeta) β (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta
pure (a, sCore, sMeta, s)
instance {Ξ±} [MetaEval Ξ±] : MetaEval (TermElabM Ξ±) where
eval env opts x _ :=
let x : TermElabM Ξ± := do
try x finally
let s β get
s.messages.forM fun msg => do IO.println (β msg.toString)
MetaEval.eval env opts (hideUnit := true) $ x.run' mkSomeContext
unsafe def evalExpr (Ξ±) (typeName : Name) (value : Expr) : TermElabM Ξ± :=
withoutModifyingEnv do
let name β mkFreshUserName `_tmp
let type β inferType value
let type β whnfD type
unless type.isConstOf typeName do
throwError! "unexpected type at evalExpr{indentExpr type}"
let decl := Declaration.defnDecl {
name := name, lparams := [], type := type,
value := value, hints := ReducibilityHints.opaque,
safety := DefinitionSafety.unsafe
}
ensureNoUnassignedMVars decl
addAndCompile decl
evalConst Ξ± name
end Term
builtin_initialize
registerTraceClass `Elab.postpone
registerTraceClass `Elab.coe
registerTraceClass `Elab.debug
export Term (TermElabM)
end Lean.Elab
|
dd3cd68f26abc9453b62dacb4a0eb067795ec6ca | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/category/Group/equivalence_Group_AddGroup.lean | 00d5f4ec4861710b5d352eca35c7070706c8110f | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 2,675 | lean | /-
Copyright (c) 2022 Jujian Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jujian Zhang
-/
import algebra.category.Group.basic
import algebra.hom.equiv.type_tags
/-!
# Equivalence between `Group` and `AddGroup`
This file contains two equivalences:
* `Group_AddGroup_equivalence` : the equivalence between `Group` and `AddGroup` by sending
`X : Group` to `additive X` and `Y : AddGroup` to `multiplicative Y`.
* `CommGroup_AddCommGroup_equivalence` : the equivalence between `CommGroup` and `AddCommGroup` by
sending `X : CommGroup` to `additive X` and `Y : AddCommGroup` to `multiplicative Y`.
-/
open category_theory
namespace Group
/--
The functor `Group β₯€ AddGroup` by sending `X β¦ additive X` and `f β¦ f`.
-/
@[simps] def to_AddGroup : Group β₯€ AddGroup :=
{ obj := Ξ» X, AddGroup.of (additive X),
map := Ξ» X Y, monoid_hom.to_additive }
end Group
namespace CommGroup
/--
The functor `CommGroup β₯€ AddCommGroup` by sending `X β¦ additive X` and `f β¦ f`.
-/
@[simps] def to_AddCommGroup : CommGroup β₯€ AddCommGroup :=
{ obj := Ξ» X, AddCommGroup.of (additive X),
map := Ξ» X Y, monoid_hom.to_additive }
end CommGroup
namespace AddGroup
/--
The functor `AddGroup β₯€ Group` by sending `X β¦ multiplicative Y` and `f β¦ f`.
-/
@[simps] def to_Group : AddGroup β₯€ Group :=
{ obj := Ξ» X, Group.of (multiplicative X),
map := Ξ» X Y, add_monoid_hom.to_multiplicative }
end AddGroup
namespace AddCommGroup
/--
The functor `AddCommGroup β₯€ CommGroup` by sending `X β¦ multiplicative Y` and `f β¦ f`.
-/
@[simps] def to_CommGroup : AddCommGroup β₯€ CommGroup :=
{ obj := Ξ» X, CommGroup.of (multiplicative X),
map := Ξ» X Y, add_monoid_hom.to_multiplicative }
end AddCommGroup
/--
The equivalence of categories between `Group` and `AddGroup`
-/
@[simps] def Group_AddGroup_equivalence : Group β AddGroup :=
equivalence.mk Group.to_AddGroup AddGroup.to_Group
(nat_iso.of_components
(Ξ» X, mul_equiv.to_Group_iso (mul_equiv.multiplicative_additive X))
(Ξ» X Y f, rfl))
(nat_iso.of_components
(Ξ» X, add_equiv.to_AddGroup_iso (add_equiv.additive_multiplicative X))
(Ξ» X Y f, rfl))
/--
The equivalence of categories between `CommGroup` and `AddCommGroup`.
-/
@[simps] def CommGroup_AddCommGroup_equivalence : CommGroup β AddCommGroup :=
equivalence.mk CommGroup.to_AddCommGroup AddCommGroup.to_CommGroup
(nat_iso.of_components
(Ξ» X, mul_equiv.to_CommGroup_iso (mul_equiv.multiplicative_additive X))
(Ξ» X Y f, rfl))
(nat_iso.of_components
(Ξ» X, add_equiv.to_AddCommGroup_iso (add_equiv.additive_multiplicative X))
(Ξ» X Y f, rfl))
|
42dc7e0ea46a061fbde445eaa179019c8f2d5ac1 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/combinatorics/simple_graph/trails.lean | 607ac8ab2d38a7a319b9eee6adc567f275850590 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 5,928 | lean | /-
Copyright (c) 2022 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import combinatorics.simple_graph.connectivity
import data.nat.parity
/-!
# Trails and Eulerian trails
This module contains additional theory about trails, including Eulerian trails (also known
as Eulerian circuits).
## Main definitions
* `simple_graph.walk.is_eulerian` is the predicate that a trail is an Eulerian trail.
* `simple_graph.walk.is_trail.even_countp_edges_iff` gives a condition on the number of edges
in a trail that can be incident to a given vertex.
* `simple_graph.walk.is_eulerian.even_degree_iff` gives a condition on the degrees of vertices
when there exists an Eulerian trail.
* `simple_graph.walk.is_eulerian.card_odd_degree` gives the possible numbers of odd-degree
vertices when there exists an Eulerian trail.
## Todo
* Prove that there exists an Eulerian trail when the conclusion to
`simple_graph.walk.is_eulerian.card_odd_degree` holds.
## Tags
Eulerian trails
-/
namespace simple_graph
variables {V : Type*} {G : simple_graph V}
namespace walk
/-- The edges of a trail as a finset, since each edge in a trail appears exactly once. -/
@[reducible] def is_trail.edges_finset {u v : V} {p : G.walk u v}
(h : p.is_trail) : finset (sym2 V) :=
β¨p.edges, h.edges_nodupβ©
variables [decidable_eq V]
lemma is_trail.even_countp_edges_iff {u v : V} {p : G.walk u v} (ht : p.is_trail) (x : V) :
even (p.edges.countp (Ξ» e, x β e)) β (u β v β x β u β§ x β v) :=
begin
induction p with u u v w huv p ih,
{ simp, },
{ rw [cons_is_trail_iff] at ht,
specialize ih ht.1,
simp only [list.countp_cons, ne.def, edges_cons, sym2.mem_iff],
split_ifs with h,
{ obtain (rfl | rfl) := h,
{ rw [nat.even_add_one, ih],
simp only [huv.ne, imp_false, ne.def, not_false_iff, true_and, not_forall, not_not,
exists_prop, eq_self_iff_true, not_true, false_and, and_iff_right_iff_imp],
rintro rfl rfl,
exact G.loopless _ huv, },
{ rw [nat.even_add_one, ih, β not_iff_not],
simp only [huv.ne.symm, ne.def, eq_self_iff_true, not_true, false_and, not_forall,
not_false_iff, exists_prop, and_true, not_not, true_and, iff_and_self],
rintro rfl,
exact huv.ne, } },
{ rw not_or_distrib at h,
simp only [h.1, h.2, not_false_iff, true_and, add_zero, ne.def] at ih β’,
rw ih,
split;
{ rintro h' h'' rfl,
simp only [imp_false, eq_self_iff_true, not_true, not_not] at h',
cases h',
simpa using h } } },
end
/-- An *Eulerian trail* (also known as an "Eulerian path") is a walk
`p` that visits every edge exactly once. The lemma `simple_graph.walk.is_eulerian.is_trail` shows
that these are trails.
Combine with `p.is_circuit` to get an Eulerian circuit (also known as an "Eulerian cycle"). -/
def is_eulerian {u v : V} (p : G.walk u v) : Prop :=
β e, e β G.edge_set β p.edges.count e = 1
lemma is_eulerian.is_trail {u v : V} {p : G.walk u v}
(h : p.is_eulerian) : p.is_trail :=
begin
rw [is_trail_def, list.nodup_iff_count_le_one],
intro e,
by_cases he : e β p.edges,
{ exact (h e (edges_subset_edge_set _ he)).le },
{ simp [he] },
end
lemma is_eulerian.mem_edges_iff {u v : V} {p : G.walk u v} (h : p.is_eulerian) {e : sym2 V} :
e β p.edges β e β G.edge_set :=
β¨Ξ» h, p.edges_subset_edge_set h, Ξ» he, by simpa using (h e he).geβ©
/-- The edge set of an Eulerian graph is finite. -/
def is_eulerian.fintype_edge_set {u v : V} {p : G.walk u v}
(h : p.is_eulerian) : fintype G.edge_set :=
fintype.of_finset h.is_trail.edges_finset $ Ξ» e,
by simp only [finset.mem_mk, multiset.mem_coe, h.mem_edges_iff]
lemma is_trail.is_eulerian_of_forall_mem {u v : V} {p : G.walk u v}
(h : p.is_trail) (hc : β e, e β G.edge_set β e β p.edges) :
p.is_eulerian :=
Ξ» e he, list.count_eq_one_of_mem h.edges_nodup (hc e he)
lemma is_eulerian_iff {u v : V} (p : G.walk u v) :
p.is_eulerian β p.is_trail β§ β e, e β G.edge_set β e β p.edges :=
begin
split,
{ intro h,
exact β¨h.is_trail, Ξ» _, h.mem_edges_iff.mprβ©, },
{ rintro β¨h, hlβ©,
exact h.is_eulerian_of_forall_mem hl, },
end
lemma is_eulerian.edges_finset_eq [fintype G.edge_set]
{u v : V} {p : G.walk u v} (h : p.is_eulerian) :
h.is_trail.edges_finset = G.edge_finset :=
by { ext e, simp [h.mem_edges_iff] }
lemma is_eulerian.even_degree_iff {x u v : V} {p : G.walk u v} (ht : p.is_eulerian)
[fintype V] [decidable_rel G.adj] :
even (G.degree x) β (u β v β x β u β§ x β v) :=
begin
convert ht.is_trail.even_countp_edges_iff x,
rw [β multiset.coe_countp, multiset.countp_eq_card_filter, β card_incidence_finset_eq_degree],
change multiset.card _ = _,
congr' 1,
convert_to _ = (ht.is_trail.edges_finset.filter (has_mem.mem x)).val,
rw [ht.edges_finset_eq, G.incidence_finset_eq_filter x],
end
lemma is_eulerian.card_filter_odd_degree [fintype V] [decidable_rel G.adj]
{u v : V} {p : G.walk u v} (ht : p.is_eulerian)
{s} (h : s = (finset.univ : finset V).filter (Ξ» v, odd (G.degree v))) :
s.card = 0 β¨ s.card = 2 :=
begin
subst s,
simp only [nat.odd_iff_not_even, finset.card_eq_zero],
simp only [ht.even_degree_iff, ne.def, not_forall, not_and, not_not, exists_prop],
obtain (rfl | hn) := eq_or_ne u v,
{ left,
simp, },
{ right,
convert_to _ = ({u, v} : finset V).card,
{ simp [hn], },
{ congr',
ext x,
simp [hn, imp_iff_not_or], } },
end
lemma is_eulerian.card_odd_degree [fintype V] [decidable_rel G.adj]
{u v : V} {p : G.walk u v} (ht : p.is_eulerian) :
fintype.card {v : V | odd (G.degree v)} = 0 β¨ fintype.card {v : V | odd (G.degree v)} = 2 :=
begin
rw β set.to_finset_card,
apply is_eulerian.card_filter_odd_degree ht,
ext v,
simp,
end
end walk
end simple_graph
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.