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