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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
982f614a190d3ec0bb8a1f1a7e3ece69820a3094 | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/data/polynomial/basic.lean | 74facaeb919f815d702fc81764eacac67a661aa7 | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,920 | 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 algebra.monoid_algebra
/-!
# Theory of univariate polynomials
This file defines `polynomial R`, the type of univariate polynomials over the semiring `R`, builds
a semiring structure on it, and gives basic definitions that are expanded in other files in this
directory.
## Main definitions
* `monomial n a` is the polynomial `a X^n`. Note that `monomial n` is defined as an `R`-linear map.
* `C a` is the constant polynomial `a`. Note that `C` is defined as a ring homomorphism.
* `X` is the polynomial `X`, i.e., `monomial 1 1`.
* `p.sum f` is `β n in p.support, f n (p.coeff n)`, i.e., one sums the values of functions applied
to coefficients of the polynomial `p`.
* `p.erase n` is the polynomial `p` in which one removes the `c X^n` term.
There are often two natural variants of lemmas involving sums, depending on whether one acts on the
polynomials, or on the function. The naming convention is that one adds `index` when acting on
the polynomials. For instance,
* `sum_add_index` states that `(p + q).sum f = p.sum f + q.sum f`;
* `sum_add` states that `p.sum (Ξ» n x, f n x + g n x) = p.sum f + p.sum g`.
## Implementation
Polynomials are defined using `add_monoid_algebra R β`, where `R` is a commutative semiring, but
through a structure to make them irreducible from the point of view of the kernel. Most operations
are irreducible since Lean can not compute anyway with `add_monoid_algebra`. There are two
exceptions that we make semireducible:
* The zero polynomial, so that its coefficients are definitionally equal to `0`.
* The scalar action, to permit typeclass search to unfold it to resolve potential instance
diamonds.
The raw implementation of the equivalence between `polynomial R` and `add_monoid_algebra R β` is
done through `of_finsupp` and `to_finsupp` (or, equivalently, `rcases p` when `p` is a polynomial
gives an element `q` of `add_monoid_algebra R β`, and conversely `β¨qβ©` gives back `p`). The
equivalence is also registered as a ring equiv in `polynomial.to_finsupp_iso`. These should
in general not be used once the basic API for polynomials is constructed.
-/
noncomputable theory
/-- `polynomial R` is the type of univariate polynomials over `R`.
Polynomials should be seen as (semi-)rings with the additional constructor `X`.
The embedding from `R` is called `C`. -/
structure polynomial (R : Type*) [semiring R] := of_finsupp ::
(to_finsupp : add_monoid_algebra R β)
open finsupp add_monoid_algebra
open_locale big_operators
namespace polynomial
universes u
variables {R : Type u} {a b : R} {m n : β}
section semiring
variables [semiring R] {p q : polynomial R}
lemma forall_iff_forall_finsupp (P : polynomial R β Prop) :
(β p, P p) β β (q : add_monoid_algebra R β), P β¨qβ© :=
β¨Ξ» h q, h β¨qβ©, Ξ» h β¨pβ©, h pβ©
lemma exists_iff_exists_finsupp (P : polynomial R β Prop) :
(β p, P p) β β (q : add_monoid_algebra R β), P β¨qβ© :=
β¨Ξ» β¨β¨pβ©, hpβ©, β¨p, hpβ©, Ξ» β¨q, hqβ©, β¨β¨qβ©, hqβ© β©
/-- The function version of `monomial`. Use `monomial` instead of this one. -/
@[irreducible] def monomial_fun (n : β) (a : R) : polynomial R := β¨finsupp.single n aβ©
@[irreducible] private def add : polynomial R β polynomial R β polynomial R
| β¨aβ© β¨bβ© := β¨a + bβ©
@[irreducible] private def neg {R : Type u} [ring R] : polynomial R β polynomial R
| β¨aβ© := β¨-aβ©
@[irreducible] private def mul : polynomial R β polynomial R β polynomial R
| β¨aβ© β¨bβ© := β¨a * bβ©
instance : has_zero (polynomial R) := β¨β¨0β©β©
instance : has_one (polynomial R) := β¨monomial_fun 0 (1 : R)β©
instance : has_add (polynomial R) := β¨addβ©
instance {R : Type u} [ring R] : has_neg (polynomial R) := β¨negβ©
instance : has_mul (polynomial R) := β¨mulβ©
instance {S : Type*} [monoid S] [distrib_mul_action S R] : has_scalar S (polynomial R) :=
β¨Ξ» r p, β¨r β’ p.to_finsuppβ©β©
lemma zero_to_finsupp : (β¨0β© : polynomial R) = 0 :=
rfl
lemma one_to_finsupp : (β¨1β© : polynomial R) = 1 :=
begin
change (β¨1β© : polynomial R) = monomial_fun 0 (1 : R),
rw [monomial_fun],
refl
end
lemma add_to_finsupp {a b} : (β¨aβ© + β¨bβ© : polynomial R) = β¨a + bβ© := show add _ _ = _, by rw add
lemma neg_to_finsupp {R : Type u} [ring R] {a} : (-β¨aβ© : polynomial R) = β¨-aβ© :=
show neg _ = _, by rw neg
lemma mul_to_finsupp {a b} : (β¨aβ© * β¨bβ© : polynomial R) = β¨a * bβ© := show mul _ _ = _, by rw mul
lemma smul_to_finsupp {S : Type*} [monoid S] [distrib_mul_action S R] {a : S} {b} :
(a β’ β¨bβ© : polynomial R) = β¨a β’ bβ© := rfl
lemma _root_.is_smul_regular.polynomial {S : Type*} [monoid S] [distrib_mul_action S R] {a : S}
(ha : is_smul_regular R a) : is_smul_regular (polynomial R) a
| β¨xβ© β¨yβ© h := congr_arg _ $ ha.finsupp (polynomial.of_finsupp.inj h)
instance : inhabited (polynomial R) := β¨0β©
instance : semiring (polynomial R) :=
by refine_struct
{ zero := (0 : polynomial R),
one := 1,
mul := (*),
add := (+),
nsmul := (β’),
npow := npow_rec,
npow_zero' := Ξ» x, rfl,
npow_succ' := Ξ» n x, rfl };
{ repeat { rintro β¨_β©, };
simp [β zero_to_finsupp, β one_to_finsupp, add_to_finsupp, mul_to_finsupp, mul_assoc, mul_add,
add_mul, smul_to_finsupp, nat.succ_eq_one_add]; abel }
instance {S} [monoid S] [distrib_mul_action S R] : distrib_mul_action S (polynomial R) :=
{ smul := (β’),
one_smul := by { rintros β¨β©, simp [smul_to_finsupp] },
mul_smul := by { rintros _ _ β¨β©, simp [smul_to_finsupp, mul_smul], },
smul_add := by { rintros _ β¨β© β¨β©, simp [smul_to_finsupp, add_to_finsupp] },
smul_zero := by { rintros _, simp [β zero_to_finsupp, smul_to_finsupp] } }
instance {S} [monoid S] [distrib_mul_action S R] [has_faithful_scalar S R] :
has_faithful_scalar S (polynomial R) :=
{ eq_of_smul_eq_smul := Ξ» sβ sβ h, eq_of_smul_eq_smul $ Ξ» a : β ββ R, congr_arg to_finsupp (h β¨aβ©) }
instance {S} [semiring S] [module S R] : module S (polynomial R) :=
{ smul := (β’),
add_smul := by { rintros _ _ β¨β©, simp [smul_to_finsupp, add_to_finsupp, add_smul] },
zero_smul := by { rintros β¨β©, simp [smul_to_finsupp, β zero_to_finsupp] },
..polynomial.distrib_mul_action }
instance {Sβ Sβ} [monoid Sβ] [monoid Sβ] [distrib_mul_action Sβ R] [distrib_mul_action Sβ R]
[smul_comm_class Sβ Sβ R] : smul_comm_class Sβ Sβ (polynomial R) :=
β¨by { rintros _ _ β¨β©, simp [smul_to_finsupp, smul_comm] }β©
instance {Sβ Sβ} [has_scalar Sβ Sβ] [monoid Sβ] [monoid Sβ] [distrib_mul_action Sβ R]
[distrib_mul_action Sβ R] [is_scalar_tower Sβ Sβ R] : is_scalar_tower Sβ Sβ (polynomial R) :=
β¨by { rintros _ _ β¨β©, simp [smul_to_finsupp] }β©
instance [subsingleton R] : unique (polynomial R) :=
{ uniq := by { rintros β¨xβ©, change (β¨xβ© : polynomial R) = 0, rw [β zero_to_finsupp], simp },
.. polynomial.inhabited }
variable (R)
/-- Ring isomorphism between `polynomial R` and `add_monoid_algebra R β`. This is just an
implementation detail, but it can be useful to transfer results from `finsupp` to polynomials. -/
@[simps]
def to_finsupp_iso : polynomial R β+* add_monoid_algebra R β :=
{ to_fun := Ξ» p, p.to_finsupp,
inv_fun := Ξ» p, β¨pβ©,
left_inv := Ξ» β¨pβ©, rfl,
right_inv := Ξ» p, rfl,
map_mul' := by { rintros β¨β© β¨β©, simp [mul_to_finsupp] },
map_add' := by { rintros β¨β© β¨β©, simp [add_to_finsupp] } }
variable {R}
lemma sum_to_finsupp {ΞΉ : Type*} (s : finset ΞΉ) (f : ΞΉ β add_monoid_algebra R β) :
β i in s, (β¨f iβ© : polynomial R) = β¨β i in s, f iβ© :=
((to_finsupp_iso R).symm.to_add_monoid_hom.map_sum f s).symm
/--
The set of all `n` such that `X^n` has a non-zero coefficient.
-/
def support : polynomial R β finset β
| β¨pβ© := p.support
@[simp] lemma support_zero : (0 : polynomial R).support = β
:=
rfl
@[simp] lemma support_eq_empty : p.support = β
β p = 0 :=
by { rcases p, simp [support, β zero_to_finsupp] }
lemma card_support_eq_zero : p.support.card = 0 β p = 0 :=
by simp
/-- `monomial s a` is the monomial `a * X^s` -/
def monomial (n : β) : R ββ[R] polynomial R :=
{ to_fun := monomial_fun n,
map_add' := by simp [monomial_fun, add_to_finsupp],
map_smul' := by simp [monomial_fun, smul_to_finsupp] }
@[simp]
lemma monomial_zero_right (n : β) :
monomial n (0 : R) = 0 :=
by simp [monomial, monomial_fun]
-- This is not a `simp` lemma as `monomial_zero_left` is more general.
lemma monomial_zero_one : monomial 0 (1 : R) = 1 := rfl
lemma monomial_add (n : β) (r s : R) :
monomial n (r + s) = monomial n r + monomial n s :=
by simp [monomial, monomial_fun]
lemma monomial_mul_monomial (n m : β) (r s : R) :
monomial n r * monomial m s = monomial (n + m) (r * s) :=
by simp only [monomial, monomial_fun, linear_map.coe_mk, mul_to_finsupp,
add_monoid_algebra.single_mul_single]
@[simp]
lemma monomial_pow (n : β) (r : R) (k : β) :
(monomial n r)^k = monomial (n*k) (r^k) :=
begin
induction k with k ih,
{ simp [pow_zero, monomial_zero_one], },
{ simp [pow_succ, ih, monomial_mul_monomial, nat.succ_eq_add_one, mul_add, add_comm] },
end
lemma smul_monomial {S} [monoid S] [distrib_mul_action S R] (a : S) (n : β) (b : R) :
a β’ monomial n b = monomial n (a β’ b) :=
by simp [monomial, monomial_fun, smul_to_finsupp]
@[simp] lemma to_finsupp_iso_monomial : (to_finsupp_iso R) (monomial n a) = single n a :=
by simp [to_finsupp_iso, monomial, monomial_fun]
@[simp] lemma to_finsupp_iso_symm_single : (to_finsupp_iso R).symm (single n a) = monomial n a :=
by simp [to_finsupp_iso, monomial, monomial_fun]
lemma support_add : (p + q).support β p.support βͺ q.support :=
begin
rcases p, rcases q,
simp only [add_to_finsupp, support],
exact support_add
end
/--
`C a` is the constant polynomial `a`.
`C` is provided as a ring homomorphism.
-/
def C : R β+* polynomial R :=
{ map_one' := by simp [monomial_zero_one],
map_mul' := by simp [monomial_mul_monomial],
map_zero' := by simp,
.. monomial 0 }
@[simp] lemma monomial_zero_left (a : R) : monomial 0 a = C a := rfl
lemma C_0 : C (0 : R) = 0 := by simp
lemma C_1 : C (1 : R) = 1 := rfl
lemma C_mul : C (a * b) = C a * C b := C.map_mul a b
lemma C_add : C (a + b) = C a + C b := C.map_add a b
@[simp] lemma smul_C {S} [monoid S] [distrib_mul_action S R] (s : S) (r : R) :
s β’ C r = C (s β’ r) :=
smul_monomial _ _ r
@[simp] lemma C_bit0 : C (bit0 a) = bit0 (C a) := C_add
@[simp] lemma C_bit1 : C (bit1 a) = bit1 (C a) := by simp [bit1, C_bit0]
lemma C_pow : C (a ^ n) = C a ^ n := C.map_pow a n
@[simp]
lemma C_eq_nat_cast (n : β) : C (n : R) = (n : polynomial R) :=
C.map_nat_cast n
@[simp] lemma C_mul_monomial : C a * monomial n b = monomial n (a * b) :=
by simp only [βmonomial_zero_left, monomial_mul_monomial, zero_add]
@[simp] lemma monomial_mul_C : monomial n a * C b = monomial n (a * b) :=
by simp only [βmonomial_zero_left, monomial_mul_monomial, add_zero]
/-- `X` is the polynomial variable (aka indeterminate). -/
def X : polynomial R := monomial 1 1
lemma monomial_one_one_eq_X : monomial 1 (1 : R) = X := rfl
lemma monomial_one_right_eq_X_pow (n : β) : monomial n (1 : R) = X^n :=
begin
induction n with n ih,
{ simp [monomial_zero_one], },
{ rw [pow_succ, βih, βmonomial_one_one_eq_X, monomial_mul_monomial, add_comm, one_mul], }
end
/-- `X` commutes with everything, even when the coefficients are noncommutative. -/
lemma X_mul : X * p = p * X :=
begin
rcases p,
simp only [X, monomial, monomial_fun, mul_to_finsupp, linear_map.coe_mk],
ext,
simp [add_monoid_algebra.mul_apply, sum_single_index, add_comm],
end
lemma X_pow_mul {n : β} : X^n * p = p * X^n :=
begin
induction n with n ih,
{ simp, },
{ conv_lhs { rw pow_succ', },
rw [mul_assoc, X_mul, βmul_assoc, ih, mul_assoc, βpow_succ'], }
end
lemma X_pow_mul_assoc {n : β} : (p * X^n) * q = (p * q) * X^n :=
by rw [mul_assoc, X_pow_mul, βmul_assoc]
lemma commute_X (p : polynomial R) : commute X p := X_mul
@[simp]
lemma monomial_mul_X (n : β) (r : R) : monomial n r * X = monomial (n+1) r :=
by erw [monomial_mul_monomial, mul_one]
@[simp]
lemma monomial_mul_X_pow (n : β) (r : R) (k : β) : monomial n r * X^k = monomial (n+k) r :=
begin
induction k with k ih,
{ simp, },
{ simp [ih, pow_succ', βmul_assoc, add_assoc], },
end
@[simp]
lemma X_mul_monomial (n : β) (r : R) : X * monomial n r = monomial (n+1) r :=
by rw [X_mul, monomial_mul_X]
@[simp]
lemma X_pow_mul_monomial (k n : β) (r : R) : X^k * monomial n r = monomial (n+k) r :=
by rw [X_pow_mul, monomial_mul_X_pow]
/-- `coeff p n` (often denoted `p.coeff n`) is the coefficient of `X^n` in `p`. -/
def coeff : polynomial R β β β R
| β¨pβ© n := p n
lemma coeff_monomial : coeff (monomial n a) m = if n = m then a else 0 :=
by { simp only [monomial, monomial_fun, coeff, linear_map.coe_mk], rw finsupp.single_apply }
@[simp] lemma coeff_zero (n : β) : coeff (0 : polynomial R) n = 0 := rfl
@[simp] lemma coeff_one_zero : coeff (1 : polynomial R) 0 = 1 :=
by { rw [β monomial_zero_one, coeff_monomial], simp }
@[simp] lemma coeff_X_one : coeff (X : polynomial R) 1 = 1 := coeff_monomial
@[simp] lemma coeff_X_zero : coeff (X : polynomial R) 0 = 0 := coeff_monomial
@[simp] lemma coeff_monomial_succ : coeff (monomial (n+1) a) 0 = 0 :=
by simp [coeff_monomial]
lemma coeff_X : coeff (X : polynomial R) n = if 1 = n then 1 else 0 := coeff_monomial
lemma coeff_X_of_ne_one {n : β} (hn : n β 1) : coeff (X : polynomial R) n = 0 :=
by rw [coeff_X, if_neg hn.symm]
@[simp] lemma mem_support_iff : n β p.support β p.coeff n β 0 :=
by { rcases p, simp [support, coeff] }
lemma not_mem_support_iff : n β p.support β p.coeff n = 0 :=
by simp
lemma coeff_C : coeff (C a) n = ite (n = 0) a 0 :=
by { convert coeff_monomial using 2, simp [eq_comm], }
@[simp] lemma coeff_C_zero : coeff (C a) 0 = a := coeff_monomial
lemma coeff_C_ne_zero (h : n β 0) : (C a).coeff n = 0 :=
by rw [coeff_C, if_neg h]
theorem nontrivial.of_polynomial_ne (h : p β q) : nontrivial R :=
β¨β¨0, 1, Ξ» h01 : 0 = 1, h $
by rw [β mul_one p, β mul_one q, β C_1, β h01, C_0, mul_zero, mul_zero] β©β©
lemma monomial_eq_C_mul_X : β{n}, monomial n a = C a * X^n
| 0 := (mul_one _).symm
| (n+1) :=
calc monomial (n + 1) a = monomial n a * X : by { rw [X, monomial_mul_monomial, mul_one], }
... = (C a * X^n) * X : by rw [monomial_eq_C_mul_X]
... = C a * X^(n+1) : by simp only [pow_add, mul_assoc, pow_one]
@[simp] lemma C_inj : C a = C b β a = b :=
β¨Ξ» h, coeff_C_zero.symm.trans (h.symm βΈ coeff_C_zero), congr_arg Cβ©
@[simp] lemma C_eq_zero : C a = 0 β a = 0 :=
calc C a = 0 β C a = C 0 : by rw C_0
... β a = 0 : C_inj
theorem ext_iff {p q : polynomial R} : p = q β β n, coeff p n = coeff q n :=
by { rcases p, rcases q, simp [coeff, finsupp.ext_iff] }
@[ext] lemma ext {p q : polynomial R} : (β n, coeff p n = coeff q n) β p = q :=
ext_iff.2
lemma add_hom_ext {M : Type*} [add_monoid M] {f g : polynomial R β+ M}
(h : β n a, f (monomial n a) = g (monomial n a)) :
f = g :=
begin
set f' : add_monoid_algebra R β β+ M := f.comp (to_finsupp_iso R).symm with hf',
set g' : add_monoid_algebra R β β+ M := g.comp (to_finsupp_iso R).symm with hg',
have : β n a, f' (single n a) = g' (single n a) := Ξ» n, by simp [hf', hg', h n],
have A : f' = g' := finsupp.add_hom_ext this,
have B : f = f'.comp (to_finsupp_iso R), by { rw [hf', add_monoid_hom.comp_assoc], ext x,
simp only [ring_equiv.symm_apply_apply, add_monoid_hom.coe_comp, function.comp_app,
ring_hom.coe_add_monoid_hom, ring_equiv.coe_to_ring_hom, coe_coe]},
have C : g = g'.comp (to_finsupp_iso R), by { rw [hg', add_monoid_hom.comp_assoc], ext x,
simp only [ring_equiv.symm_apply_apply, add_monoid_hom.coe_comp, function.comp_app,
ring_hom.coe_add_monoid_hom, ring_equiv.coe_to_ring_hom, coe_coe]},
rw [B, C, A],
end
@[ext] lemma add_hom_ext' {M : Type*} [add_monoid M] {f g : polynomial R β+ M}
(h : β n, f.comp (monomial n).to_add_monoid_hom = g.comp (monomial n).to_add_monoid_hom) :
f = g :=
add_hom_ext (Ξ» n, add_monoid_hom.congr_fun (h n))
@[ext] lemma lhom_ext' {M : Type*} [add_comm_monoid M] [module R M] {f g : polynomial R ββ[R] M}
(h : β n, f.comp (monomial n) = g.comp (monomial n)) :
f = g :=
linear_map.to_add_monoid_hom_injective $ add_hom_ext $ Ξ» n, linear_map.congr_fun (h n)
-- this has the same content as the subsingleton
lemma eq_zero_of_eq_zero (h : (0 : R) = (1 : R)) (p : polynomial R) : p = 0 :=
by rw [βone_smul R p, βh, zero_smul]
lemma support_monomial (n) (a : R) (H : a β 0) : (monomial n a).support = singleton n :=
by simp [monomial, monomial_fun, support, finsupp.support_single_ne_zero H]
lemma support_monomial' (n) (a : R) : (monomial n a).support β singleton n :=
by simp [monomial, monomial_fun, support, finsupp.support_single_subset]
lemma X_pow_eq_monomial (n) : X ^ n = monomial n (1:R) :=
begin
induction n with n hn,
{ rw [pow_zero, monomial_zero_one] },
{ rw [pow_succ', hn, X, monomial_mul_monomial, one_mul] },
end
lemma monomial_eq_smul_X {n} : monomial n (a : R) = a β’ X^n :=
calc monomial n a = monomial n (a * 1) : by simp
... = a β’ monomial n 1 : by simp [monomial, monomial_fun, smul_to_finsupp]
... = a β’ X^n : by rw X_pow_eq_monomial
lemma support_X_pow (H : Β¬ (1:R) = 0) (n : β) : (X^n : polynomial R).support = singleton n :=
begin
convert support_monomial n 1 H,
exact X_pow_eq_monomial n,
end
lemma support_X_empty (H : (1:R)=0) : (X : polynomial R).support = β
:=
begin
rw [X, H, monomial_zero_right, support_zero],
end
lemma support_X (H : Β¬ (1 : R) = 0) : (X : polynomial R).support = singleton 1 :=
begin
rw [β pow_one X, support_X_pow H 1],
end
lemma monomial_left_inj {R : Type*} [semiring R] {a : R} (ha : a β 0) {i j : β} :
(monomial i a) = (monomial j a) β i = j :=
by simp [monomial, monomial_fun, finsupp.single_left_inj ha]
lemma nat_cast_mul {R : Type*} [semiring R] (n : β) (p : polynomial R) :
(n : polynomial R) * p = n β’ p :=
(nsmul_eq_mul _ _).symm
/-- Summing the values of a function applied to the coefficients of a polynomial -/
def sum {S : Type*} [add_comm_monoid S] (p : polynomial R) (f : β β R β S) : S :=
β n in p.support, f n (p.coeff n)
lemma sum_def {S : Type*} [add_comm_monoid S] (p : polynomial R) (f : β β R β S) :
p.sum f = β n in p.support, f n (p.coeff n) := rfl
lemma sum_eq_of_subset {S : Type*} [add_comm_monoid S] (p : polynomial R)
(f : β β R β S) (hf : β i, f i 0 = 0) (s : finset β) (hs : p.support β s) :
p.sum f = β n in s, f n (p.coeff n) :=
begin
apply finset.sum_subset hs (Ξ» n hn h'n, _),
rw not_mem_support_iff at h'n,
simp [h'n, hf]
end
/-- Expressing the product of two polynomials as a double sum. -/
lemma mul_eq_sum_sum :
p * q = β i in p.support, q.sum (Ξ» j a, (monomial (i + j)) (p.coeff i * a)) :=
begin
rcases p, rcases q,
simp [mul_to_finsupp, support, monomial, sum, monomial_fun, coeff, sum_to_finsupp],
refl
end
@[simp] lemma sum_zero_index {S : Type*} [add_comm_monoid S] (f : β β R β S) :
(0 : polynomial R).sum f = 0 :=
by simp [sum]
@[simp] lemma sum_monomial_index {S : Type*} [add_comm_monoid S]
(n : β) (a : R) (f : β β R β S) (hf : f n 0 = 0) :
(monomial n a : polynomial R).sum f = f n a :=
begin
by_cases h : a = 0,
{ simp [h, hf] },
{ simp [sum, support_monomial, h, coeff_monomial] }
end
@[simp] lemma sum_C_index {a} {Ξ²} [add_comm_monoid Ξ²] {f : β β R β Ξ²} (h : f 0 0 = 0) :
(C a).sum f = f 0 a :=
sum_monomial_index 0 a f h
-- the assumption `hf` is only necessary when the ring is trivial
@[simp] lemma sum_X_index {S : Type*} [add_comm_monoid S] {f : β β R β S} (hf : f 1 0 = 0) :
(X : polynomial R).sum f = f 1 1 :=
sum_monomial_index 1 1 f hf
lemma sum_add_index {S : Type*} [add_comm_monoid S] (p q : polynomial R)
(f : β β R β S) (hf : β i, f i 0 = 0) (h_add : βa bβ bβ, f a (bβ + bβ) = f a bβ + f a bβ) :
(p + q).sum f = p.sum f + q.sum f :=
begin
rcases p, rcases q,
simp only [add_to_finsupp, sum, support, coeff, pi.add_apply, coe_add],
exact finsupp.sum_add_index hf h_add,
end
lemma sum_add' {S : Type*} [add_comm_monoid S] (p : polynomial R) (f g : β β R β S) :
p.sum (f + g) = p.sum f + p.sum g :=
by simp [sum_def, finset.sum_add_distrib]
lemma sum_add {S : Type*} [add_comm_monoid S] (p : polynomial R) (f g : β β R β S) :
p.sum (Ξ» n x, f n x + g n x) = p.sum f + p.sum g :=
sum_add' _ _ _
lemma sum_smul_index {S : Type*} [add_comm_monoid S] (p : polynomial R) (b : R)
(f : β β R β S) (hf : β i, f i 0 = 0) : (b β’ p).sum f = p.sum (Ξ» n a, f n (b * a)) :=
begin
rcases p,
simp [smul_to_finsupp, sum, support, coeff],
exact finsupp.sum_smul_index hf,
end
/-- `erase p n` is the polynomial `p` in which the `X^n` term has been erased. -/
@[irreducible] definition erase (n : β) : polynomial R β polynomial R
| β¨pβ© := β¨p.erase nβ©
@[simp] lemma support_erase (p : polynomial R) (n : β) :
support (p.erase n) = (support p).erase n :=
by { rcases p, simp only [support, erase, support_erase], congr }
lemma monomial_add_erase (p : polynomial R) (n : β) : monomial n (coeff p n) + p.erase n = p :=
begin
rcases p,
simp [add_to_finsupp, monomial, monomial_fun, coeff, erase],
exact finsupp.single_add_erase _ _
end
lemma coeff_erase (p : polynomial R) (n i : β) :
(p.erase n).coeff i = if i = n then 0 else p.coeff i :=
begin
rcases p,
simp only [erase, coeff],
convert rfl
end
@[simp] lemma erase_zero (n : β) : (0 : polynomial R).erase n = 0 :=
by simp [β zero_to_finsupp, erase]
@[simp] lemma erase_monomial {n : β} {a : R} : erase n (monomial n a) = 0 :=
by simp [monomial, monomial_fun, erase, β zero_to_finsupp]
@[simp] lemma erase_same (p : polynomial R) (n : β) : coeff (p.erase n) n = 0 :=
by simp [coeff_erase]
@[simp] lemma erase_ne (p : polynomial R) (n i : β) (h : i β n) :
coeff (p.erase n) i = coeff p i :=
by simp [coeff_erase, h]
end semiring
section comm_semiring
variables [comm_semiring R]
instance : comm_semiring (polynomial R) :=
{ mul_comm := by { rintros β¨β© β¨β©, simp [mul_to_finsupp, mul_comm] }, .. polynomial.semiring }
end comm_semiring
section ring
variables [ring R]
instance : ring (polynomial R) :=
{ neg := has_neg.neg,
add_left_neg := by { rintros β¨β©, simp [neg_to_finsupp, add_to_finsupp, β zero_to_finsupp] },
gsmul := (β’),
gsmul_zero' := by { rintro β¨β©, simp [smul_to_finsupp, β zero_to_finsupp] },
gsmul_succ' := by { rintros n β¨β©, simp [smul_to_finsupp, add_to_finsupp, add_smul, add_comm] },
gsmul_neg' := by { rintros n β¨β©,
simp only [smul_to_finsupp, neg_to_finsupp], simp [add_smul, add_mul] },
.. polynomial.semiring }
@[simp] lemma coeff_neg (p : polynomial R) (n : β) : coeff (-p) n = -coeff p n :=
by { rcases p, simp [coeff, neg_to_finsupp] }
@[simp]
lemma coeff_sub (p q : polynomial R) (n : β) : coeff (p - q) n = coeff p n - coeff q n :=
by { rcases p, rcases q, simp [coeff, sub_eq_add_neg, add_to_finsupp, neg_to_finsupp] }
@[simp] lemma monomial_neg (n : β) (a : R) : monomial n (-a) = -(monomial n a) :=
by rw [eq_neg_iff_add_eq_zero, βmonomial_add, neg_add_self, monomial_zero_right]
@[simp] lemma support_neg {p : polynomial R} : (-p).support = p.support :=
by { rcases p, simp [support, neg_to_finsupp] }
end ring
instance [comm_ring R] : comm_ring (polynomial R) :=
{ .. polynomial.comm_semiring, .. polynomial.ring }
section nonzero_semiring
variables [semiring R] [nontrivial R]
instance : nontrivial (polynomial R) :=
begin
have h : nontrivial (add_monoid_algebra R β) := by apply_instance,
rcases h.exists_pair_ne with β¨x, y, hxyβ©,
refine β¨β¨β¨xβ©, β¨yβ©, _β©β©,
simp [hxy],
end
lemma X_ne_zero : (X : polynomial R) β 0 :=
mt (congr_arg (Ξ» p, coeff p 1)) (by simp)
end nonzero_semiring
section repr
variables [semiring R]
open_locale classical
instance [has_repr R] : has_repr (polynomial R) :=
β¨Ξ» p, if p = 0 then "0"
else (p.support.sort (β€)).foldr
(Ξ» n a, a ++ (if a = "" then "" else " + ") ++
if n = 0
then "C (" ++ repr (coeff p n) ++ ")"
else if n = 1
then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X"
else if (coeff p n) = 1 then "X ^ " ++ repr n
else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""β©
end repr
end polynomial
|
e6e2e3df85a28b4ff9106734c7003f99be2547be | aa5a655c05e5359a70646b7154e7cac59f0b4132 | /stage0/src/Lean/Data/Lsp/Extra.lean | ec240c916b85231481f64daa1f1494c1d58672cc | [
"Apache-2.0"
] | permissive | lambdaxymox/lean4 | ae943c960a42247e06eff25c35338268d07454cb | 278d47c77270664ef29715faab467feac8a0f446 | refs/heads/master | 1,677,891,867,340 | 1,612,500,005,000 | 1,612,500,005,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,110 | lean | /-
Copyright (c) 2020 Marc Huisinga. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Marc Huisinga
-/
import Lean.Data.Json
import Lean.Data.JsonRpc
import Lean.Data.Lsp.Basic
/-!
This file contains Lean-specific extensions to LSP.
The following additional packets are supported:
- "textDocument/waitForDiagnostics": Yields a response when all the diagnostics for a version of the document
greater or equal to the specified one have been emitted. If the request specifies a version above the most
recently processed one, the server will delay the response until it does receive the specified version.
Exists for synchronization purposes, e.g. during testing or when external tools might want to use our LSP server.
-/
namespace Lean.Lsp
open Json
structure WaitForDiagnosticsParams where
uri : DocumentUri
version : Nat
deriving ToJson, FromJson
structure WaitForDiagnostics
instance : FromJson WaitForDiagnostics :=
β¨fun j => WaitForDiagnostics.mkβ©
instance : ToJson WaitForDiagnostics :=
β¨fun o => mkObj []β©
end Lean.Lsp
|
c1f124614ec7330f198cc7cbef85dcb8d14d67bd | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2020/relations/equiv_partition2.lean | 9d4237d8036d39542e5a2f94813efacfbe716695 | [] | no_license | ImperialCollegeLondon/M40001_lean | 3a6a09298da395ab51bc220a535035d45bbe919b | 62a76fa92654c855af2b2fc2bef8e60acd16ccec | refs/heads/master | 1,666,750,403,259 | 1,665,771,117,000 | 1,665,771,117,000 | 209,141,835 | 115 | 12 | null | 1,640,270,596,000 | 1,568,749,174,000 | Lean | UTF-8 | Lean | false | false | 3,767 | lean | import tactic
/-
data.equiv.basic is the import which gives you the type `equiv X Y`, the type o
f
bijections from X to Y.
Here's the definition of equiv from that file.
structure equiv (Ξ± : Sort*) (Ξ² : Sort*) :=
(to_fun : Ξ± β Ξ²)
(inv_fun : Ξ² β Ξ±)
(left_inv : left_inverse inv_fun to_fun)
(right_inv : right_inverse inv_fun to_fun)
To make a term of type `equiv Ξ± Ξ²` you have to supply a function Ξ± β Ξ²,
a function Ξ² β Ξ±, and proofs that both composites are the identity function.
Let's see how to create the bijection β€ β β€ sending x to -x.
-/
-- let's prove that x β¦ -x can be extended to
example : equiv β€ β€ :=
{ to_fun := Ξ» x, -x, -- this is data
inv_fun := Ξ» x, -x, -- this is data
left_inv := begin -- this is a proof
change β (x : β€), - -x = x, -- that's the question
exact neg_neg, -- note: I guessed what this function was called.
-- If it had been called "lemma 12" I would not have been able to guess
end,
right_inv := neg_neg -- another proof, this time in term mode
}
/-
Q1 Define the type of partitions of a type.
A partition of X is a set of subsets of X with the property that each subset
is non-empty and each element of X is in precisely one of the subsets.
NB : this is one of the harder questions here.
-/
structure partition (X : Type*) :=
(β± : set (set X))
(disjoint : β A B β β±, A β B β A β© B = β
)
(cover : β x : X, β A β β±, x β A)
(nonempty : β A β β±, A β β
)
/-
Equivalence relations are in core Lean -- we don't need any imports.
Here's an example: I'll prove that the "always true" relation on a set is
an equivalence relation.
-/
def always_true (X : Type*) : X β X β Prop := Ξ» a b, true
-- and now here's the proof that it's an equivalence relation.
theorem always_true_refl (X) : reflexive (always_true X) :=
begin
intro x,
trivial
end
theorem always_true_symm (X) : symmetric (always_true X) :=
begin
intros a b H,
trivial
end
theorem always_true_trans (X) : transitive (always_true X) :=
begin
intros a b c Hab Hbc,
trivial
end
-- note pointy brackets to make a term of type "A β§ B β§ C"
theorem always_true_equiv (X): equivalence (always_true X) :=
β¨always_true_refl X, always_true_symm X, always_true_trans Xβ©
-- autocomplete made that proof really easy to type. It's really
-- lucky that I didn't call these lemmas lemma 12, lemma 13 and lemma 14.
-- if X is a type, then `setoid X` is is the type of equivalence relations on X.
-- I'll now make a term of type `setoid X` corresponding to that equivalence
-- relation above.
-- note squiggly brackets and commas at the end of each definition
-- to make a structure
def always_true_setoid (X : Type*) : setoid X :=
{ r := always_true X,
iseqv := always_true_equiv X }
/-
Q2 : If X is a type then `setoid X` is the type of equivalence relations on X,
and `partitions X` is the type of partitions of X. These two concepts are in
some sort of "canonical" bijection with each other (interesting exercise: make
this statement mathematically meaningful -- I know we all say it, but what
does it *mean*?).
Let's prove that these sets biject with each other by defining
a term of type equiv (setoid X) (partitions X)
-/
variable {X : Type*}
def F (S : setoid X) : partition X := sorry
/-
Q3 : now define a map the other way
-/
def G (P : partition X) : setoid X := sorry
/-
Q4 : now finally prove that the composite of maps in both directions
is the identity
-/
theorem FG_eq_id (P : partition X) : F (G P) = P := sorry
theorem GF_eq_id (S : setoid X) : G (F S) = S := sorry
/-
Q5 : now finally construct the term we seek.
-/
def partitions_biject_with_equivalence_relations :
equiv (setoid X) (partition X) := sorry
|
2a88a15efe1054ac863bfe111a12fb6b96609829 | 54d7e71c3616d331b2ec3845d31deb08f3ff1dea | /library/init/meta/environment.lean | a3eb3701b5f1ea1bc68e72fe1c86c18d3a447cd3 | [
"Apache-2.0"
] | permissive | pachugupta/lean | 6f3305c4292288311cc4ab4550060b17d49ffb1d | 0d02136a09ac4cf27b5c88361750e38e1f485a1a | refs/heads/master | 1,611,110,653,606 | 1,493,130,117,000 | 1,493,167,649,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,531 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.declaration init.meta.exceptional init.data.option.basic
meta constant environment : Type
namespace environment
/--
Information for a projection declaration
- `cname` is the name of the constructor associated with the projection.
- `nparams` is the number of constructor parameters
- `idx` is the parameter being projected by this projection
- `is_class` is tt iff this is a class projection.
-/
structure projection_info :=
(cname : name)
(nparams : nat)
(idx : nat)
(is_class : bool)
/- Create a standard environment using the given trust level -/
meta constant mk_std : nat β environment
/- Return the trust level of the given environment -/
meta constant trust_lvl : environment β nat
/- Add a new declaration to the environment -/
meta constant add : environment β declaration β exceptional environment
/- Retrieve a declaration from the environment -/
meta constant get : environment β name β exceptional declaration
meta def contains (env : environment) (d : name) : bool :=
match env.get d with
| exceptional.success _ := tt
| exceptional.exception ._ _ := ff
end
/- Return tt iff the given name is a namespace -/
meta constant is_namespace : environment β name β bool
/- Add a new inductive datatype to the environment
name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/
meta constant add_inductive : environment β name β list name β nat β expr β list (name Γ expr) β bool β
exceptional environment
/- Return tt iff the given name is an inductive datatype -/
meta constant is_inductive : environment β name β bool
/- Return tt iff the given name is a constructor -/
meta constant is_constructor : environment β name β bool
/- Return tt iff the given name is a recursor -/
meta constant is_recursor : environment β name β bool
/- Return tt iff the given name is a recursive inductive datatype -/
meta constant is_recursive : environment β name β bool
/- Return the name of the inductive datatype of the given constructor. -/
meta constant inductive_type_of : environment β name β option name
/- Return the constructors of the inductive datatype with the given name -/
meta constant constructors_of : environment β name β list name
/- Return the recursor of the given inductive datatype -/
meta constant recursor_of : environment β name β option name
/- Return the number of parameters of the inductive datatype -/
meta constant inductive_num_params : environment β name β nat
/- Return the number of indices of the inductive datatype -/
meta constant inductive_num_indices : environment β name β nat
/- Return tt iff the inductive datatype recursor supports dependent elimination -/
meta constant inductive_dep_elim : environment β name β bool
/- Return tt iff the given name is a generalized inductive datatype -/
meta constant is_ginductive : environment β name β bool
meta constant is_projection : environment β name β option projection_info
/- Fold over declarations in the environment -/
meta constant fold {Ξ± :Type} : environment β Ξ± β (declaration β Ξ± β Ξ±) β Ξ±
/- (relation_info env n) returns some value if n is marked as a relation in the given environment.
the tuple contains: total number of arguments of the relation, lhs position and rhs position. -/
meta constant relation_info : environment β name β option (nat Γ nat Γ nat)
/- (refl_for env R) returns the name of the reflexivity theorem for the relation R -/
meta constant refl_for : environment β name β option name
/- (symm_for env R) returns the name of the symmetry theorem for the relation R -/
meta constant symm_for : environment β name β option name
/- (trans_for env R) returns the name of the transitivity theorem for the relation R -/
meta constant trans_for : environment β name β option name
/- (decl_olean env d) returns the name of the .olean file where d was defined.
The result is none if d was not defined in an imported file. -/
meta constant decl_olean : environment β name β option string
/- (decl_pos env d) returns the source location of d if available. -/
meta constant decl_pos : environment β name β option pos
open expr
meta constant unfold_untrusted_macros : environment β expr β expr
meta def is_constructor_app (env : environment) (e : expr) : bool :=
is_constant (get_app_fn e) && is_constructor env (const_name (get_app_fn e))
meta def is_refl_app (env : environment) (e : expr) : option (name Γ expr Γ expr) :=
match (refl_for env (const_name (get_app_fn e))) with
| (some n) :=
if get_app_num_args e β₯ 2
then some (n, app_arg (app_fn e), app_arg e)
else none
| none := none
end
/-- Return true if 'n' has been declared in the current file -/
meta def in_current_file (env : environment) (n : name) : bool :=
(env.decl_olean n).is_none && env.contains n
meta def is_definition (env : environment) (n : name) : bool :=
match env.get n with
| exceptional.success (declaration.defn _ _ _ _ _ _) := tt
| _ := ff
end
end environment
meta instance : has_to_string environment :=
β¨Ξ» e, "[environment]"β©
meta instance : inhabited environment :=
β¨environment.mk_std 0β©
|
28920cf4def0c63b3fda6a3e2aadbd385c95e080 | e1440579fb0723caf9edf1ed07aee74bbf4f5ce7 | /lean-experiments/stumps-learnable/src/stump/stump_pac_theorem.lean | c774908d844a7f7f44a05920358acc982cc6ee16 | [
"Apache-2.0"
] | permissive | palmskog/coq-proba | 1ecc5b7f399894ea14d6094a31a063280a122099 | f73e2780871e2a3dd83b7ce9d3aed19f499f07e5 | refs/heads/master | 1,599,620,504,720 | 1,572,960,008,000 | 1,572,960,008,000 | 221,326,479 | 0 | 0 | Apache-2.0 | 1,573,598,769,000 | 1,573,598,768,000 | null | UTF-8 | Lean | false | false | 3,187 | lean | /-
Copyright Β© 2019, Oracle and/or its affiliates. All rights reserved.
-/
import .setup_definition .setup_measurable
import .algorithm_definition .algorithm_measurable
import .sample_complexity
import .stump_pac_lemmas
import .to_epsilon
open set nat
local attribute [instance] classical.prop_decidable
namespace stump
variables (ΞΌ: probability_measure β) (target: β) (n: β)
noncomputable
def denot: probability_measure β :=
let Ξ· := vec.prob_measure n ΞΌ in
let Ξ½ := map (label_sample target n) Ξ· in
let Ξ³ := map (choose n) Ξ½ in
Ξ³
lemma pullback:
β P: nnreal β Prop,
is_measurable {h: β | P(@error ΞΌ target h)} β
is_measurable {S: vec (β Γ bool) n | P(error ΞΌ target (choose n S))} β
(denot ΞΌ target n) {h: β | P(@error ΞΌ target h)} = (vec.prob_measure n ΞΌ) {S: vec β n | P(error ΞΌ target (choose n (label_sample target n S)))} :=
begin
intros,
dunfold denot,
rw map_apply,
rw map_apply,
repeat {simp},
repeat {assumption},
end
theorem choose_PAC:
β Ξ΅: nnreal, β Ξ΄: nnreal, β n: β,
Ξ΅ > 0 β Ξ΅ < 1 β Ξ΄ > 0 β Ξ΄ < 1 β (n: β) > (complexity Ξ΅ Ξ΄) β
(denot ΞΌ target n) {h: β | @error ΞΌ target h β€ Ξ΅} β₯ 1 - Ξ΄ :=
begin
introv eps_0 eps_1 delta_0 delta_1 n_gt,
by_cases((ΞΌ (Ioc 0 target)) > Ξ΅),
{
rw β probability_measure.neq_prob_set,
rw pullback ΞΌ target n (Ξ» x, x > Ξ΅) _ _; try {simp},
transitivity ((1 - Ξ΅)^(n+1)),
{
have EPS := extend_to_epsilon_1 ΞΌ target Ξ΅ eps_0 h, cases EPS with ΞΈ ΞΈ_prop, cases ΞΈ_prop,
have TZ: ΞΈ > 0,
{
by_contradiction h_contra,
simp at h_contra, rw h_contra at *,
have CONTRA: Β¬ (ΞΌ (Ioc 0 target) β€ Ξ΅), simp, assumption,
contradiction,
},
transitivity ((vec.prob_measure n ΞΌ) {S: vec β n | β (i: dfin (nat.succ n)), β p = label target (kth_projn S i), (if p.snd then p.fst else 0) < ΞΈ}),
{
apply probability_measure.prob_mono,
refine all_missed _ _ _ _ _ ΞΈ_prop_right,
},
{
have INDEP := @prob_independence β _ n _ (Ξ» x, β p = label target x, (if p.snd then p.fst else 0) < ΞΈ) ΞΌ (is_meas_one target ΞΈ TZ) (is_meas_forall target ΞΈ TZ),
rw INDEP, clear INDEP,
simp,
apply pow_preserves_order (n+1),
refine miss_prob _ _ _ _ TZ ΞΈ_prop_left,
},
},
{
apply complexity_enough Ξ΅ Ξ΄ n; assumption,
},
exact le_of_lt delta_1,
simp,
},
{
simp at h,
rw pullback ΞΌ target n (Ξ» x, x β€ Ξ΅) _ _; try {simp},
have DC: (vec.prob_measure n ΞΌ) {S: vec β n | error ΞΌ target (choose n (label_sample target n S)) β€ Ξ΅} = 1,
{
have AS := always_succeed ΞΌ target Ξ΅ eps_0 n h,
refine probability_measure.prob_trivial _ _ AS,
},
rw DC; try {assumption},
apply super_dumb, assumption,
},
end
end stump |
0c51da24113a117bfb1de0d4d89e01257a3f7cf5 | 36938939954e91f23dec66a02728db08a7acfcf9 | /lean/deps/typed_smt2/src/galois/smt2/basic.lean | e36cb53e439587e54d218675fab0c30e7ac874c4 | [
"Apache-2.0"
] | permissive | pnwamk/reopt-vcg | f8b56dd0279392a5e1c6aee721be8138e6b558d3 | c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d | refs/heads/master | 1,631,145,017,772 | 1,593,549,019,000 | 1,593,549,143,000 | 254,191,418 | 0 | 0 | null | 1,586,377,077,000 | 1,586,377,077,000 | null | UTF-8 | Lean | false | false | 12,550 | lean | /-
This declares sorts, terms, and semantics for generating SMTLIB
expressions and reasoning about their interpretation.
-/
import galois.category.except
import galois.data.bitvec
import galois.data.bool
import galois.data.buffer
import galois.data.list
import galois.data.option
import galois.logic
import galois.sexpr
import .atom
universes u v
/- A list whose element types are constructed from applying a function to another list. -/
inductive indexed_list {Ξ±:Type u} (f:Ξ± β Sort v) : list Ξ± β Sort (max (u+1) v)
| nil {} : indexed_list []
| cons {h:Ξ±} {r:list Ξ±} : f h β indexed_list r β indexed_list (h::r)
namespace indexed_list
section
parameter {Ξ±:Type u}
parameter {f:Ξ± β Sort v}
/- Return the nth_le element in the list. -/
def nth_le : Ξ {l:list Ξ±}, indexed_list f l β Ξ (i:β) (i_lt:i < l.length), f (l.nth_le i i_lt)
| ._ nil n h := absurd h (nat.not_lt_zero n)
| ._ (cons a l) 0 h := a
| ._ (cons a l) (n+1) h := nth_le l n (nat.le_of_succ_le_succ h)
end
end indexed_list
------------------------------------------------------------------------
-- SMT theory
namespace smt2
------------------------------------------------------------------------
-- ident_arg
/-
A identifier arg represents either a number or a
symbol (possibly with arguments provided).
-/
inductive ident_arg : Type
| nat {} : β β ident_arg
| sort {} : symbol β list ident_arg β ident_arg
namespace ident_arg
------------------------------------------------------------------------
-- is_child
/- is_child c x holds if one ident_arg appears as an argument to another. -/
inductive is_child : ident_arg β ident_arg β Prop
| mem : Ξ {x : ident_arg} {nm : symbol} {args : list ident_arg}
(is_mem : x β args),
is_child x (ident_arg.sort nm args)
/- Prove is_child relationship is well-founded. -/
def is_child.wf : well_founded is_child :=
begin
apply well_founded.intro,
intro z,
apply well_founded.fix (sizeof_measure_wf ident_arg) _ z,
intros y rec,
dsimp [sizeof_measure, measure, inv_image] at rec,
apply acc.intro,
intros x x_lt_y,
cases y with n nm args,
{ cases x_lt_y, },
{ cases x_lt_y with a b c x_in_args,
apply rec,
simp [sizeof, has_sizeof.sizeof, ident_arg.sizeof, nat.succ_add ],
transitivity, exact (list.mem_sizeof x_in_args),
apply nat.lt_of_le_of_lt (nat.le_add_left _ nm.sizeof),
exact (nat.succ_le_succ (nat.le_refl _)),
},
end
------------------------------------------------------------------------
-- fixpoint function based on is_child.
section
parameter {C : ident_arg β Sort _}
parameter (nat_eval : Ξ (n:β), C (nat n))
parameter (sort_eval : Ξ (nm:symbol) (args:list ident_arg),
(Ξ (y : ident_arg), y β args β C y)
β C (sort nm args))
def fix.f
: Ξ (x : ident_arg), (Ξ (y : ident_arg), ident_arg.is_child y x β C y) -> C x
| (nat n) _ := nat_eval n
| (sort nm args) ind := sort_eval nm args (Ξ»y h, ind y (is_child.mem h))
@[elab_with_expected_type]
def fix : Ξ (x : ident_arg), C x := well_founded.fix is_child.wf fix.f
end
------------------------------------------------------------------------
--
/-- Convert a ident_arg to an s-expression. -/
protected
def to_sexpr : ident_arg β sexpr atom :=
let num (n:β) := sexpr.atom (atom.numeral n) in
let app (nm : symbol) (args : list ident_arg) rec :=
sexpr.parens
(sexpr.atom (atom.symbol nm) :: args.map_with_mem rec) in
fix num app
def decidable_eq.nat (m:β) : Ξ (y:ident_arg), decidable (nat m = y)
| (nat n) :=
if p : m = n then
is_true (congr_arg nat p)
else
is_false (Ξ»h, p (ident_arg.nat.inj h))
| (sort nm args) := is_false (by contradiction)
def decidable_eq.app (nm : symbol) (args : list ident_arg)
(rec : Ξ (y:ident_arg), y β args β Ξ z, decidable (y = z))
: Ξ (y:ident_arg), decidable (sort nm args = y)
| (nat n) := is_false (by contradiction)
| (sort ynm yargs) :=
if pnm : nm = ynm then
let p (xe) (xmem) (ye) (ymem : ye β yargs)
: decidable (xe = ye) := rec xe xmem ye in
match list.has_dec_eq_with_mem args yargs p with
| is_true pr := is_true (eq.subst pnm (eq.subst pr rfl))
| is_false npr := is_false (Ξ»h, npr (ident_arg.sort.inj h).right)
end
else
is_false (Ξ»h, pnm (ident_arg.sort.inj h).left)
protected
def has_dec_eq : decidable_eq ident_arg :=
fix decidable_eq.nat decidable_eq.app
instance : decidable_eq ident_arg := ident_arg.has_dec_eq
instance : has_coe β ident_arg := β¨ident_arg.natβ©
end ident_arg
------------------------------------------------------------------------
-- sort
/--
Sorts in SMTLIB.
-/
inductive sort : Type
| Bool : sort
| BitVec (w:β) : sort
namespace sort
protected def to_sexpr : sort β sexpr atom
| Bool := symbol.of_string "Bool"
| (BitVec w) := sexpr.parens [reserved_word.of_string "_", symbol.of_string "BitVec", atom.numeral w]
instance sort_is_sexpr : has_coe sort (sexpr atom) := β¨sort.to_sexprβ©
instance : decidable_eq sort := by tactic.mk_dec_eq_instance
def domain : sort β Type
| Bool := bool
| (BitVec w) := bitvec w
def default : Ξ (s:sort), s.domain
| sort.Bool := tt
| (BitVec w) := (0 : bitvec w)
end sort
export sort(Bool)
export sort(BitVec)
------------------------------------------------------------------------
-- rank
/- The input sorts and output associated with a user-defined symbol. -/
structure rank : Type :=
(inputs : list sort)
(return : sort)
namespace rank
/- Returns the type of values in the domain. -/
def domain (r:rank) : Type := r.inputs.foldr (Ξ»a r, a.domain β r) r.return.domain
end rank
namespace sort
/- Returns the rank with no arguments and the given sort. -/
protected def to_rank (s:sort) : rank := β¨[],sβ©
instance sort_is_rank : has_coe sort rank := β¨sort.to_rankβ©
end sort
------------------------------------------------------------------------
-- interpretation
/-- This represents a mapping from constants to the associated sybol. -/
structure interpretation : Type :=
(var_map : rbmap symbol (sigma rank.domain))
namespace interpretation
protected
def lookup_var (i:interpretation) (nm:symbol) (s:sort) : option s.domain :=
match i.var_map.find nm with
| (some β¨β¨[],tβ©,dβ©) :=
if h : t = s then
some (cast (congr_arg sort.domain h) d)
else
none
| _ := none
end
protected
def bind (i:interpretation) (nm:symbol) (r:rank) (d:r.domain) : interpretation
:= { i with var_map := i.var_map.insert nm β¨r, dβ© }
protected def empty : interpretation := { var_map := mk_rbmap _ _ _ }
instance : has_emptyc interpretation := β¨interpretation.emptyβ©
end interpretation
------------------------------------------------------------------------
-- term
/- Defines a term in our logic. -/
structure term (s:sort) : Type :=
(to_sexpr : sexpr atom)
(interp : interpretation β s.domain)
namespace term
instance (s:sort) : has_coe (term s) (sexpr atom) := β¨term.to_sexprβ©
end term
/- Return the rank associated with a function with the given arguments and return type. -/
def arg_rank (args: list (symbol Γ sort)) (r:sort) : rank := β¨args.map prod.snd, rβ©
/- Return the function defined by the given arguments and term. -/
def function_def
: Ξ (i:interpretation) (args:list (symbol Γ sort)) {r:sort} (rhs : term r), (arg_rank args r).domain
| i [] r rhs := rhs.interp i
| i (β¨nm,sβ©::l) r rhs := Ξ»(x:s.domain), function_def (i.bind nm s.to_rank x) l rhs
def var (nm:symbol) (s:sort) : term s :=
{ to_sexpr := nm
, interp := Ξ»ctx,
match ctx.lookup_var nm s with
| (some v) := v
| none := s.default
end
}
------------------------------------------------------------------------
-- Apply predicates
/- Apply function to elements in list with a left associative operation. -/
def apply_left_assoc (m:interpretation) {s:sort}
(f : s.domain β s.domain β s.domain)
(x:term s) (l:list (term s)) : s.domain :=
list.foldl (Ξ»a (b:term s), f a (b.interp m)) (x.interp m) l
/- Apply function to elements in list with a right associative operation. -/
def apply_right_assoc (m:interpretation) {s:sort} (f : s.domain β s.domain β s.domain)
(l:list (term s)) (x:term s) : s.domain :=
list.foldr (Ξ»(a:term s) b, f (a.interp m) b) (x.interp m) l
/- Apply predicate to each two pair of elements in list and return conjunction. -/
def apply_chainable {Ξ±} (p : Ξ± β Ξ± β bool) : Ξ± β list Ξ± β bool
| x [] := tt
| x (h::r) := p x h && apply_chainable h r
/- Apply predicate to all elements in list, and return conjunction. -/
def all_band {Ξ±} (p : Ξ± β bool) : list Ξ± β bool
| [] := tt
| (h::r) := p h && all_band r
/- Apply predicate to each two pair of elements in list and return conjunction. -/
def apply_pairwise {Ξ±} (p : Ξ± β Ξ± β bool) : list Ξ± β bool
| [] := tt
| (h::r) := all_band (p h) r && apply_pairwise r
------------------------------------------------------------------------
-- Core theory
/-- True predicate. -/
protected
def true : term Bool :=
{ to_sexpr := symbol.of_string "true"
, interp := Ξ»m, tt
}
/-- False predicate. -/
protected
def false : term Bool :=
{ to_sexpr := symbol.of_string "false"
, interp := Ξ»m, ff
}
/-- False predicate. -/
protected
def not (x : term Bool) : term Bool :=
{ to_sexpr := sexpr.parens [sexpr.of_string "false", x]
, interp := Ξ»m, bnot (x.interp m)
}
protected
def implies (c : list (term Bool)) (p : term Bool) : term Bool :=
{ to_sexpr := sexpr.parens (sexpr.of_string "=>" :: (c.map term.to_sexpr ++ [p]))
, interp := Ξ»m, apply_right_assoc m bimplies c p
}
/-- Check if all terms in the arguments are true. -/
protected
def all (l:list (term Bool)) : term Bool :=
{ to_sexpr :=
match l with
| [] := symbol.of_string "true"
| [h] := h
| l := sexpr.parens (symbol.of_string "and" :: l.map term.to_sexpr)
end
, interp := Ξ»m, ball (l.map (Ξ»b, term.interp b m))
}
/-- Check if any terms in the arguments are true. -/
protected
def any (l:list (term Bool)) : term Bool :=
{ to_sexpr :=
match l with
| [] := symbol.of_string "false"
| [h] := h
| l := sexpr.parens (symbol.of_string "or" :: l.map term.to_sexpr)
end
, interp := Ξ»m, bany (l.map (Ξ»b, term.interp b m))
}
/-- Check if an odd number of Booleans in the list are true. -/
protected
def xor_list (l:list (term Bool)) : term Bool :=
{ to_sexpr :=
match l with
| [] := symbol.of_string "false"
| [h] := h
| l := sexpr.parens (symbol.of_string "xor" :: l.map term.to_sexpr)
end
, interp := Ξ»m, list.foldl bxor ff (l.map (Ξ»b, term.interp b m))
}
/-- Return true if all terms in list are equal. -/
def all_equal {s:sort} [h : decidable_eq s.domain] : list (term s) β term Bool
| [] := smt2.true
| [x] := smt2.true
| (x::l) :=
{ to_sexpr := sexpr.parens (symbol.of_string "=" :: x :: l.map term.to_sexpr)
, interp := Ξ»m,
apply_chainable (Ξ»(x y : s.domain), decidable.to_bool (x = y))
(x.interp m)
(l.map (Ξ»b, b.interp m))
}
/-- Assert all terms in list are pairwise distinct. -/
protected
def distinct {s:sort} [h : decidable_eq s.domain] : list (term s) β term Bool
| [] := smt2.true
| [x] := smt2.true
| l := { to_sexpr := sexpr.parens (symbol.of_string "=" :: l.map term.to_sexpr)
, interp := Ξ»m,
apply_pairwise (Ξ»(x y : s.domain), decidable.to_bool (x β y))
(l.map (Ξ»b, b.interp m))
}
/-- Return one term or another depending on Boolean predicate. -/
protected
def ite {s:sort} (c : term Bool) (x y : term s) : term s :=
{ to_sexpr := sexpr.parens [symbol.of_string "ite", c, x, y]
, interp := Ξ»m, cond (c.interp m) (x.interp m) (y.interp m)
}
def binding := symbol Γ sigma term
namespace binding
protected
def to_sexpr : binding β sexpr atom
| (nm, β¨s, tβ©) := sexpr.parens [nm, t]
instance : has_coe binding (sexpr atom) := β¨binding.to_sexprβ©
end binding
/- Extend the model with a list of bindings. -/
def extend_model (scope:interpretation) : interpretation β list binding β interpretation
| i [] := i
| i ((nm, β¨s, tβ©)::r) := extend_model (i.bind nm (s.to_rank) (t.interp scope)) r
/- Generate a term that with let bindings. -/
protected
def term_let {s:sort} : list binding β term s β term s
| [] t := t
| l t :=
{ to_sexpr := sexpr.parens [sexpr.of_string "let", sexpr.parens (l.map binding.to_sexpr), t]
, interp := Ξ»m, t.interp (extend_model m m l)
}
end smt2
|
09884b99073e39d0a75a01ffd75e0c971c1c94c9 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/def11.lean | ef5dd486b351c6c5b99f138ed09ca9e8a453c0ea | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,259 | lean |
inductive Formula
| eqf : Nat β Nat β Formula
| andf : Formula β Formula β Formula
| impf : Formula β Formula β Formula
| notf : Formula β Formula
| orf : Formula β Formula β Formula
| allf : (Nat β Formula) β Formula
namespace Formula
def implies (a b : Prop) : Prop := a β b
def denote : Formula β Prop
| eqf n1 n2 => n1 = n2
| andf f1 f2 => denote f1 β§ denote f2
| impf f1 f2 => implies (denote f1) (denote f2)
| orf f1 f2 => denote f1 β¨ denote f2
| notf f => Β¬ denote f
| allf f => (n : Nat) β denote (f n)
theorem denote_eqf (n1 n2 : Nat) : denote (eqf n1 n2) = (n1 = n2) :=
rfl
theorem denote_andf (f1 f2 : Formula) : denote (andf f1 f2) = (denote f1 β§ denote f2) :=
rfl
theorem denote_impf (f1 f2 : Formula) : denote (impf f1 f2) = (denote f1 β denote f2) :=
rfl
theorem denote_orf (f1 f2 : Formula) : denote (orf f1 f2) = (denote f1 β¨ denote f2) :=
rfl
theorem denote_notf (f : Formula) : denote (notf f) = Β¬ denote f :=
rfl
theorem denote_allf (f : Nat β Formula) : denote (allf f) = (β n, denote (f n)) :=
rfl
theorem ex : denote (allf (fun nβ => allf (fun nβ => impf (eqf nβ nβ) (eqf nβ nβ)))) = (β (nβ nβ : Nat), nβ = nβ β nβ = nβ) :=
rfl
end Formula
|
ec787304fc785aa1ad05c4a98aefa9fc9f7427e3 | d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6 | /Papyrus.lean | 58f9a9d101e9d644d8e9539104c692051b46f36f | [
"Apache-2.0"
] | permissive | xubaiw/lean4-papyrus | c3fbbf8ba162eb5f210155ae4e20feb2d32c8182 | 02e82973a5badda26fc0f9fd15b3d37e2eb309e0 | refs/heads/master | 1,691,425,756,824 | 1,632,122,825,000 | 1,632,123,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 203 | lean | import Papyrus.Init
import Papyrus.Context
import Papyrus.MemoryBufferRef
import Papyrus.ExecutionEngineRef
import Papyrus.GenericValueRef
import Papyrus.IR
import Papyrus.Builders
import Papyrus.Script
|
b3a70dd1df1cf5304b29d0e9a347b815cb50b5e8 | 6f1049e897f569e5c47237de40321e62f0181948 | /src/solutions/01_equality_rewriting.lean | a209de463ac0cc88f678f982a127f77f84273be7 | [
"Apache-2.0"
] | permissive | anrddh/tutorials | f654a0807b9523608544836d9a81939f8e1dceb8 | 3ba43804e7b632201c494cdaa8da5406f1a255f9 | refs/heads/master | 1,655,542,921,827 | 1,588,846,595,000 | 1,588,846,595,000 | 262,330,134 | 0 | 0 | null | 1,588,944,346,000 | 1,588,944,345,000 | null | UTF-8 | Lean | false | false | 5,592 | lean | import data.real.basic
/-
One of the earliest kind of proofs one encounters while learning mathematics is proving by
a calculation. It may not sound like a proof, but this is actually using lemmas expressing
properties of operations on numbers. It also uses the fundamental property of equality: if two
mathematical objects A and B are equal then, in any statement involving A, one can replace A
by B. This operation is called rewriting, and the Lean "tactic" for this is `rw`.
In the following exercises, we will use the following two lemmas:
mul_assoc a b c : a * b * c = a * (b * c)
mul_comm a b : a*b = b*a
Hence the command
rw mul_assoc a b c,
will replace a*b*c by a*(b*c) in the current goal.
In order to replace backward, we use
rw β mul_assoc a b c,
replacing a*(b*c) by a*b*c in the current goal.
Of course we don't want to constantly invoke those lemmas, and we will eventually introduce
more powerful solutions.
-/
example (a b c : β) : (a * b) * c = b * (a * c) :=
begin
rw mul_comm a b,
rw mul_assoc b a c,
end
-- 0001
example (a b c : β) : (c * b) * a = b * (a * c) :=
begin
-- sorry
rw mul_comm c b,
rw mul_assoc b c a,
rw mul_comm c a,
-- sorry
end
-- 0002
example (a b c : β) : a * (b * c) = b * (a * c) :=
begin
-- sorry
rw β mul_assoc a b c,
rw mul_comm a b,
rw mul_assoc b a c,
-- sorry
end
/-
Now let's return to the preceding example to experiment with what happens
if we don't give arguments to mul_assoc or mul_comm.
For instance, you can start the next proof with
rw β mul_assoc,
Try to figure out what happens.
-/
-- 0003
example (a b c : β) : a * (b * c) = b * (a * c) :=
begin
-- sorry
rw β mul_assoc,
-- "rw mul_comm," ne fait pas ce qu'on veut.
rw mul_comm a b,
rw mul_assoc,
-- sorry
end
/-
We can also perform rewriting in an assumption of the local context, using for instance
rw mul_comm a b at hyp,
in order to replace a*b by b*a in assumption hyp.
The next example will use a third lemma:
two_mul a : 2*a = a + a
Also we use the exact tactic, which allows to provide a direct proof term.
-/
example (a b c d : β) (hyp : c = d*a + b) (hyp' : b = a*d) : c = 2*a*d :=
begin
rw hyp' at hyp,
rw mul_comm d a at hyp,
rw β two_mul (a*d) at hyp,
rw β mul_assoc 2 a d at hyp,
exact hyp, -- Our assumption hyp is now exactly what we have to prove
end
/-
And the next one can use:
sub_self x : x - x = 0
-/
-- 0004
example (a b c d : β) (hyp : c = b*a - d) (hyp' : d = a*b) : c = 0 :=
begin
-- sorry
rw hyp' at hyp,
rw mul_comm b a at hyp,
rw sub_self (a*b) at hyp,
exact hyp,
-- sorry
end
/-
What is written in the two preceding example is very far away from what we would write on
paper. Let's now see how to get a more natural layout.
Inside each pair of curly braces below, the goal is to prove equality with the preceding line.
-/
example (a b c d : β) (hyp : c = d*a + b) (hyp' : b = a*d) : c = 2*a*d :=
begin
calc c = d*a + b : by { rw hyp }
... = d*a + a*d : by { rw hyp' }
... = a*d + a*d : by { rw mul_comm d a }
... = 2*(a*d) : by { rw two_mul }
... = 2*a*d : by { rw mul_assoc },
end
/-
Let's note there is no comma at the end of each line of calculation. calc is really one
command, and the comma comes only after it's fully done.
From a practical point of view, when writing such a proof, it is convenient to:
* pause the tactic state view update in VScode by clicking the Pause icon button
in the top right corner of the Lean Goal buffer
* write the full calculation, ending each line with ": by {}"
* resume tactic state update by clicking the Play icon button and fill in proofs between
curly braces.
Let's return to the other example using this method.
-/
-- 0005
example (a b c d : β) (hyp : c = b*a - d) (hyp' : d = a*b) : c = 0 :=
begin
-- sorry
calc c = b*a - d : by { rw hyp }
... = b*a - a*b : by { rw hyp' }
... = a*b - a*b : by { rw mul_comm a b }
... = 0 : by { rw sub_self (a*b) },
-- sorry
end
/-
The preceding proofs have exhauted our supply of "mul_comm" patience. Now it's time
to get the computer to work harder. The ring tactic will prove any goal that follow by
applying only the axioms of commutative (semi-)rings, in particuler commutativity and
associativity of addition and multiplication, as well as distributivity.
We also note that curly braces are not necessary when we write a single tactic proof, so
let's get rid of them.
-/
example (a b c d : β) (hyp : c = d*a + b) (hyp' : b = a*d) : c = 2*a*d :=
begin
calc c = d*a + b : by rw hyp
... = d*a + a*d : by rw hyp'
... = 2*a*d : by ring,
end
/-
Of course we can use ring outside of calc. Let's do the next one in one line.
-/
-- 0006
example (a b c : β) : a * (b * c) = b * (a * c) :=
begin
-- sorry
ring,
-- sorry
end
/-
This is too much fun. Let's do it again.
-/
-- 0007
example (a b : β) : (a + b) + a = 2*a + b :=
begin
-- sorry
ring,
-- sorry
end
/-
Maybe this is cheating. Let's try to do the next computation without ring.
We could use:
pow_two x : x^2 = x*x
mul_sub a b c : a*(b-c) = a*b - a*c
add_mul a b c : (a+b)*c = a*c + b*c
add_sub a b c : a + (b - c) = (a + b) - c
sub_sub a b c : a - b - c = a - (b + c)
add_zero a : a + 0 = a
-/
-- 0008
example (a b : β) : (a + b)*(a - b) = a^2 - b^2 :=
begin
-- sorry
rw pow_two a,
rw pow_two b,
rw mul_sub (a+b) a b,
rw add_mul a b a,
rw add_mul a b b,
rw mul_comm b a,
rw β sub_sub,
rw β add_sub,
rw sub_self,
rw add_zero,
-- sorry
end
/- Let's stick to ring in the end. -/ |
413ff7e53fe729c2f1abb218e7cdf52b1606728c | 36938939954e91f23dec66a02728db08a7acfcf9 | /lean4/deps/galois_stdlib/src/Galois/Init/Json.lean | fb2014cdbc62c2b27ce365e3f9bfd4944a7e9448 | [] | no_license | pnwamk/reopt-vcg | f8b56dd0279392a5e1c6aee721be8138e6b558d3 | c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d | refs/heads/master | 1,631,145,017,772 | 1,593,549,019,000 | 1,593,549,143,000 | 254,191,418 | 0 | 0 | null | 1,586,377,077,000 | 1,586,377,077,000 | null | UTF-8 | Lean | false | false | 4,614 | lean |
import Init.Lean.Data.Json
import Init.Data.RBMap
universes u
-- Missing stuff
namespace Lean.Json
open Lean (Json HasFromJson HasToJson)
open Lean.Json
instance rbmapToJson : HasToJson (RBMap String Json Lean.strLt) :=
-- N.B., we manually have to extract the RBNode from the RBMap and have no
-- static guarantee they also used Lean.strLt =\ See
-- https://github.com/leanprover/lean4/blob/f3976fc53a883ac7606fc59357d43f4b51016ca7
-- /src/Init/Lean/Data/Json/Basic.lean#L96
-- Check back later to see if this is fixed (in reality we'll probably just break
-- at the usage of `Lean.Json.obj` when we update Lean4 and it has been changed to
-- just use the RBMap itself).
β¨Ξ» rbm => Lean.Json.obj $ rbm.valβ©
section
variables (Ξ± : Type u) [HasFromJson Ξ±]
-- Extract the value for the specified key of a Json object while expecting it to be of a certain
-- type (which has a HasFromJson instance).
private def parseObjValAsDescrAux (descr : String) (js:Json) (key : String) (dflt : Option Ξ±) : Except String Ξ± :=
match js.getObjVal? key with
| Option.some js' => match fromJson? js' with
| Option.some a => Except.ok a
| Option.none =>
Except.error $ "Excepted key `"++key++"` to have a "++ descr ++" value but got `"++js'.pretty++"`."
| Option.none => match js with
| obj _ => match dflt with
| Option.some a => Except.ok a
| Option.none =>
Except.error $ "Expected a Json object with key `"++key++"` but got `"++js.pretty++"`."
| _ => Except.error $ "Expected a Json object but got `"++js.pretty++"`."
def parseObjValAsDescr (descr : String) (js:Json) (key : String) : Except String Ξ± :=
@parseObjValAsDescrAux _ _ descr js key none
def parseObjValAsDescrD (descr : String) (js:Json) (key : String) (dflt : Ξ±) : Except String Ξ± :=
@parseObjValAsDescrAux _ _ descr js key (some dflt)
end
def parseObjValAsBool := parseObjValAsDescr Bool "Bool"
def parseObjValAsBoolD := parseObjValAsDescrD Bool "Bool"
def parseObjValAsString := parseObjValAsDescr String "String"
def parseObjValAsStringD := parseObjValAsDescrD String "String"
def parseObjValAsNat := parseObjValAsDescr Nat "Nat"
def parseObjValAsNatD := parseObjValAsDescrD Nat "Nat"
def parseObjValAsInt := parseObjValAsDescr Int "Int"
def parseObjValAsIntD := parseObjValAsDescrD Int "Int"
def parseObjValAsArr := parseObjValAsDescr (Array Json) "Array"
def parseObjValAsArrD := parseObjValAsDescrD (Array Json) "Array"
def parseObjValAsArrOf (Ξ± : Type u) [HasFromJson Ξ±] (dscr : String) := parseObjValAsDescr (Array Ξ±) ("(Array "++dscr++")")
def parseObjValAsArrOfD (Ξ± : Type u) [HasFromJson Ξ±] (dscr : String) := parseObjValAsDescrD (Array Ξ±) ("(Array "++dscr++")")
private def parseObjValAsArrWithAux
{Ξ± : Type u}
(parser : Json β Except String Ξ±)
(js:Json)
(key : String)
(dflt : Option (Array Ξ±))
: Except String (Array Ξ±) :=
match js.getObjVal? key with
| Option.none => match dflt with
| Option.some as => pure as
| Option.none => Except.error $ "Expected a Json object with key `"++key++"`."
| Option.some rawJson => match rawJson.getArr? with
| Option.some xs => do
vals β Array.mapM parser xs;
pure vals
| Option.none =>
Except.error $ "Expected a Json object's `"++key
++"` field to contain an array, but got `"
++rawJson.pretty++"`."
-- Parse a Json object field as an array and use the given parser for the sub-elements.
def parseObjValAsArrWith {Ξ± : Type u} (parser : Json β Except String Ξ±) (js:Json) (key : String) : Except String (Array Ξ±) :=
parseObjValAsArrWithAux parser js key none
def parseObjValAsArrWithD {Ξ± : Type u} (parser : Json β Except String Ξ±) (js:Json) (key : String) (dflt : Array Ξ±) : Except String (Array Ξ±) :=
parseObjValAsArrWithAux parser js key (some dflt)
-- Equality of Json terms modulo object mapping details. It
-- gets a little gross since the RBNode interface is a little
-- messier than the RBMap interface =\
--
-- FIXME clean up when Lean.Json is updated to use RBMap instead of
-- RBNode.
partial def isEqv : Json β Json β Bool
| null, null => true
| bool b1, bool b2 => true
| num n1, num n2 => n1 = n2
| str s1, str s2 => s1 = s2
| arr a1, arr a2 => Array.isEqv a1 a2 isEqv
| obj kvs1, obj kvs2 =>
match kvs1.min, kvs2.min with
| Option.none, Option.none => true
| Option.some β¨k1,v1β©, Option.some β¨k2,v2β© =>
if k1 = k2 && isEqv v1 v2 then
let o1 := obj $ RBNode.erase Lean.strLt k1 kvs1;
let o2 := obj $ RBNode.erase Lean.strLt k2 kvs2;
isEqv o1 o2
else
false
| _,_ => false
| _, _ => false
end Lean.Json
|
4799efccc553aa3099a2fdf7b39870c698f9063a | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/Lake/Config/LeanExeConfig.lean | 5026f7b712782537530b9737577da7baf519c8c2 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,838 | lean | /-
Copyright (c) 2022 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone
-/
import Lake.Build.Facets
import Lake.Config.LeanConfig
namespace Lake
open Lean System
/-- A Lean executable's declarative configuration. -/
structure LeanExeConfig extends LeanConfig where
/-- The name of the target. -/
name : Name
/--
The subdirectory of the package's source directory containing the executable's
Lean source file. Defaults simply to said `srcDir`.
(This will be passed to `lean` as the `-R` option.)
-/
srcDir : FilePath := "."
/--
The root module of the binary executable.
Should include a `main` definition that will serve
as the entry point of the program.
The root is built by recursively building its
local imports (i.e., fellow modules of the workspace).
Defaults to the name of the target.
-/
root : Name := name
/--
The name of the binary executable.
Defaults to the target name with any `.` replaced with a `-`.
-/
exeName : String := name.toStringWithSep "-" (escape := false)
/-- An `Array` of target names to build before the executable's modules. -/
extraDepTargets : Array Name := #[]
/--
An `Array` of module facets to build and combine into the executable.
Defaults to ``#[Module.oFacet]`` (i.e., the object file compiled from
the Lean source).
-/
nativeFacets : Array (ModuleFacet (BuildJob FilePath)) := #[Module.oFacet]
/--
Whether to expose symbols within the executable to the Lean interpreter.
This allows the executable to interpret Lean files (e.g., via
`Lean.Elab.runFrontend`).
Implementation-wise, this passes `-rdynamic` to the linker when building
on non-Windows systems.
Defaults to `false`.
-/
supportInterpreter : Bool := false
deriving Inhabited
|
45de14f816458b475c55004194ebe5e183539ae7 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/star/basic.lean | a1f239829754ae7b34be479c58352c4d99b7226b | [
"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 | 17,295 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import tactic.apply_fun
import algebra.field.opposite
import algebra.field_power
import algebra.ring.aut
import group_theory.group_action.units
import group_theory.group_action.opposite
import algebra.ring.comp_typeclasses
/-!
# Star monoids, rings, and modules
We introduce the basic algebraic notions of star monoids, star rings, and star modules.
A star algebra is simply a star ring that is also a star module.
These are implemented as "mixin" typeclasses, so to summon a star ring (for example)
one needs to write `(R : Type) [ring R] [star_ring R]`.
This avoids difficulties with diamond inheritance.
We also define the class `star_ordered_ring R`, which says that the order on `R` respects the
star operation, i.e. an element `r` is nonnegative iff there exists an `s` such that
`r = star s * s`.
For now we simply do not introduce notations,
as different users are expected to feel strongly about the relative merits of
`r^*`, `rβ `, `rα`, and so on.
Our star rings are actually star semirings, but of course we can prove
`star_neg : star (-r) = - star r` when the underlying semiring is a ring.
## TODO
* In a Banach star algebra without a well-defined square root, the natural ordering is given by the
positive cone which is the closure of the sums of elements `star r * r`. A weaker version of
`star_ordered_ring` could be defined for this case. Note that the current definition has the
advantage of not requiring a topology.
-/
universes u v
open mul_opposite
/--
Notation typeclass (with no default notation!) for an algebraic structure with a star operation.
-/
class has_star (R : Type u) :=
(star : R β R)
variables {R : Type u}
export has_star (star)
/--
A star operation (e.g. complex conjugate).
-/
add_decl_doc star
/--
Typeclass for a star operation with is involutive.
-/
class has_involutive_star (R : Type u) extends has_star R :=
(star_involutive : function.involutive star)
export has_involutive_star (star_involutive)
@[simp] lemma star_star [has_involutive_star R] (r : R) : star (star r) = r :=
star_involutive _
lemma star_injective [has_involutive_star R] : function.injective (star : R β R) :=
star_involutive.injective
/-- `star` as an equivalence when it is involutive. -/
protected def equiv.star [has_involutive_star R] : equiv.perm R :=
star_involutive.to_perm _
lemma eq_star_of_eq_star [has_involutive_star R] {r s : R} (h : r = star s) : s = star r :=
by simp [h]
lemma eq_star_iff_eq_star [has_involutive_star R] {r s : R} : r = star s β s = star r :=
β¨eq_star_of_eq_star, eq_star_of_eq_starβ©
lemma star_eq_iff_star_eq [has_involutive_star R] {r s : R} : star r = s β star s = r :=
eq_comm.trans $ eq_star_iff_eq_star.trans eq_comm
/--
Typeclass for a trivial star operation. This is mostly meant for `β`.
-/
class has_trivial_star (R : Type u) [has_star R] : Prop :=
(star_trivial : β (r : R), star r = r)
export has_trivial_star (star_trivial)
attribute [simp] star_trivial
/--
A `*`-semigroup is a semigroup `R` with an involutive operations `star`
so `star (r * s) = star s * star r`.
-/
class star_semigroup (R : Type u) [semigroup R] extends has_involutive_star R :=
(star_mul : β r s : R, star (r * s) = star s * star r)
export star_semigroup (star_mul)
attribute [simp] star_mul
/-- In a commutative ring, make `simp` prefer leaving the order unchanged. -/
@[simp] lemma star_mul' [comm_semigroup R] [star_semigroup R] (x y : R) :
star (x * y) = star x * star y :=
(star_mul x y).trans (mul_comm _ _)
/-- `star` as an `mul_equiv` from `R` to `Rα΅α΅α΅` -/
@[simps apply]
def star_mul_equiv [semigroup R] [star_semigroup R] : R β* Rα΅α΅α΅ :=
{ to_fun := Ξ» x, mul_opposite.op (star x),
map_mul' := Ξ» x y, (star_mul x y).symm βΈ (mul_opposite.op_mul _ _),
..(has_involutive_star.star_involutive.to_perm star).trans op_equiv}
/-- `star` as a `mul_aut` for commutative `R`. -/
@[simps apply]
def star_mul_aut [comm_semigroup R] [star_semigroup R] : mul_aut R :=
{ to_fun := star,
map_mul' := star_mul',
..(has_involutive_star.star_involutive.to_perm star) }
variables (R)
@[simp] lemma star_one [monoid R] [star_semigroup R] : star (1 : R) = 1 :=
op_injective $ (star_mul_equiv : R β* Rα΅α΅α΅).map_one.trans (op_one _).symm
variables {R}
@[simp] lemma star_pow [monoid R] [star_semigroup R] (x : R) (n : β) : star (x ^ n) = star x ^ n :=
op_injective $
((star_mul_equiv : R β* Rα΅α΅α΅).to_monoid_hom.map_pow x n).trans (op_pow (star x) n).symm
@[simp] lemma star_inv [group R] [star_semigroup R] (x : R) : star (xβ»ΒΉ) = (star x)β»ΒΉ :=
op_injective $
((star_mul_equiv : R β* Rα΅α΅α΅).to_monoid_hom.map_inv x).trans (op_inv (star x)).symm
@[simp] lemma star_zpow [group R] [star_semigroup R] (x : R) (z : β€) : star (x ^ z) = star x ^ z :=
op_injective $
((star_mul_equiv : R β* Rα΅α΅α΅).to_monoid_hom.map_zpow x z).trans (op_zpow (star x) z).symm
/-- When multiplication is commutative, `star` preserves division. -/
@[simp] lemma star_div [comm_group R] [star_semigroup R] (x y : R) :
star (x / y) = star x / star y :=
(star_mul_aut : R β* R).to_monoid_hom.map_div _ _
section
open_locale big_operators
@[simp] lemma star_prod [comm_monoid R] [star_semigroup R] {Ξ± : Type*}
(s : finset Ξ±) (f : Ξ± β R):
star (β x in s, f x) = β x in s, star (f x) :=
(star_mul_aut : R β* R).map_prod _ _
end
/--
Any commutative monoid admits the trivial `*`-structure.
See note [reducible non-instances].
-/
@[reducible]
def star_semigroup_of_comm {R : Type*} [comm_monoid R] : star_semigroup R :=
{ star := id,
star_involutive := Ξ» x, rfl,
star_mul := mul_comm }
section
local attribute [instance] star_semigroup_of_comm
/-- Note that since `star_semigroup_of_comm` is reducible, `simp` can already prove this. --/
lemma star_id_of_comm {R : Type*} [comm_semiring R] {x : R} : star x = x := rfl
end
/--
A `*`-additive monoid `R` is an additive monoid with an involutive `star` operation which
preserves addition.
-/
class star_add_monoid (R : Type u) [add_monoid R] extends has_involutive_star R :=
(star_add : β r s : R, star (r + s) = star r + star s)
export star_add_monoid (star_add)
attribute [simp] star_add
/-- `star` as an `add_equiv` -/
@[simps apply]
def star_add_equiv [add_monoid R] [star_add_monoid R] : R β+ R :=
{ to_fun := star,
map_add' := star_add,
..(has_involutive_star.star_involutive.to_perm star)}
variables (R)
@[simp] lemma star_zero [add_monoid R] [star_add_monoid R] : star (0 : R) = 0 :=
(star_add_equiv : R β+ R).map_zero
variables {R}
@[simp]
lemma star_eq_zero [add_monoid R] [star_add_monoid R] {x : R} : star x = 0 β x = 0 :=
star_add_equiv.map_eq_zero_iff
lemma star_ne_zero [add_monoid R] [star_add_monoid R] {x : R} : star x β 0 β x β 0 :=
star_eq_zero.not
@[simp] lemma star_neg [add_group R] [star_add_monoid R] (r : R) : star (-r) = - star r :=
(star_add_equiv : R β+ R).map_neg _
@[simp] lemma star_sub [add_group R] [star_add_monoid R] (r s : R) :
star (r - s) = star r - star s :=
(star_add_equiv : R β+ R).map_sub _ _
@[simp] lemma star_nsmul [add_monoid R] [star_add_monoid R] (x : R) (n : β) :
star (n β’ x) = n β’ star x :=
(star_add_equiv : R β+ R).to_add_monoid_hom.map_nsmul _ _
@[simp] lemma star_zsmul [add_group R] [star_add_monoid R] (x : R) (n : β€) :
star (n β’ x) = n β’ star x :=
(star_add_equiv : R β+ R).to_add_monoid_hom.map_zsmul _ _
section
open_locale big_operators
@[simp] lemma star_sum [add_comm_monoid R] [star_add_monoid R] {Ξ± : Type*}
(s : finset Ξ±) (f : Ξ± β R):
star (β x in s, f x) = β x in s, star (f x) :=
(star_add_equiv : R β+ R).map_sum _ _
end
/--
A `*`-ring `R` is a (semi)ring with an involutive `star` operation which is additive
which makes `R` with its multiplicative structure into a `*`-semigroup
(i.e. `star (r * s) = star s * star r`).
-/
class star_ring (R : Type u) [non_unital_semiring R] extends star_semigroup R :=
(star_add : β r s : R, star (r + s) = star r + star s)
@[priority 100]
instance star_ring.to_star_add_monoid [non_unital_semiring R] [star_ring R] : star_add_monoid R :=
{ star_add := star_ring.star_add }
/-- `star` as an `ring_equiv` from `R` to `Rα΅α΅α΅` -/
@[simps apply]
def star_ring_equiv [non_unital_semiring R] [star_ring R] : R β+* Rα΅α΅α΅ :=
{ to_fun := Ξ» x, mul_opposite.op (star x),
..star_add_equiv.trans (mul_opposite.op_add_equiv : R β+ Rα΅α΅α΅),
..star_mul_equiv }
@[simp, norm_cast] lemma star_nat_cast [semiring R] [star_ring R] (n : β) :
star (n : R) = n :=
(congr_arg unop (map_nat_cast (star_ring_equiv : R β+* Rα΅α΅α΅) n)).trans (unop_nat_cast _)
@[simp, norm_cast] lemma star_int_cast [ring R] [star_ring R] (z : β€) :
star (z : R) = z :=
(congr_arg unop ((star_ring_equiv : R β+* Rα΅α΅α΅).to_ring_hom.map_int_cast z)).trans (unop_int_cast _)
@[simp, norm_cast] lemma star_rat_cast [division_ring R] [char_zero R] [star_ring R] (r : β) :
star (r : R) = r :=
(congr_arg unop $ map_rat_cast (star_ring_equiv : R β+* Rα΅α΅α΅) r).trans (unop_rat_cast _)
/-- `star` as a ring automorphism, for commutative `R`. -/
@[simps apply]
def star_ring_aut [comm_semiring R] [star_ring R] : ring_aut R :=
{ to_fun := star,
..star_add_equiv,
..star_mul_aut }
variables (R)
/-- `star` as a ring endomorphism, for commutative `R`. This is used to denote complex
conjugation, and is available under the notation `conj` in the locale `complex_conjugate`.
Note that this is the preferred form (over `star_ring_aut`, available under the same hypotheses)
because the notation `E βββ[R] F` for an `R`-conjugate-linear map (short for
`E βββ[star_ring_end R] F`) does not pretty-print if there is a coercion involved, as would be the
case for `(βstar_ring_aut : R β* R)`. -/
def star_ring_end [comm_semiring R] [star_ring R] : R β+* R := @star_ring_aut R _ _
variables {R}
localized "notation `conj` := star_ring_end _" in complex_conjugate
/-- This is not a simp lemma, since we usually want simp to keep `star_ring_end` bundled.
For example, for complex conjugation, we don't want simp to turn `conj x`
into the bare function `star x` automatically since most lemmas are about `conj x`. -/
lemma star_ring_end_apply [comm_semiring R] [star_ring R] {x : R} :
star_ring_end R x = star x := rfl
@[simp] lemma star_ring_end_self_apply [comm_semiring R] [star_ring R] (x : R) :
star_ring_end R (star_ring_end R x) = x := star_star x
-- A more convenient name for complex conjugation
alias star_ring_end_self_apply β complex.conj_conj
alias star_ring_end_self_apply β is_R_or_C.conj_conj
@[simp] lemma star_inv' [division_ring R] [star_ring R] (x : R) : star (xβ»ΒΉ) = (star x)β»ΒΉ :=
op_injective $
((star_ring_equiv : R β+* Rα΅α΅α΅).to_ring_hom.map_inv x).trans (op_inv (star x)).symm
@[simp] lemma star_zpowβ [division_ring R] [star_ring R] (x : R) (z : β€) :
star (x ^ z) = star x ^ z :=
op_injective $
((star_ring_equiv : R β+* Rα΅α΅α΅).to_ring_hom.map_zpow x z).trans (op_zpow (star x) z).symm
/-- When multiplication is commutative, `star` preserves division. -/
@[simp] lemma star_div' [field R] [star_ring R] (x y : R) : star (x / y) = star x / star y :=
(star_ring_end R).map_div _ _
@[simp] lemma star_bit0 [add_monoid R] [star_add_monoid R] (r : R) :
star (bit0 r) = bit0 (star r) :=
by simp [bit0]
@[simp] lemma star_bit1 [semiring R] [star_ring R] (r : R) : star (bit1 r) = bit1 (star r) :=
by simp [bit1]
/--
Any commutative semiring admits the trivial `*`-structure.
See note [reducible non-instances].
-/
@[reducible]
def star_ring_of_comm {R : Type*} [comm_semiring R] : star_ring R :=
{ star := id,
star_add := Ξ» x y, rfl,
..star_semigroup_of_comm }
/--
An ordered `*`-ring is a ring which is both an `ordered_add_comm_group` and a `*`-ring,
and `0 β€ r β β s, r = star s * s`.
-/
class star_ordered_ring (R : Type u) [non_unital_semiring R] [partial_order R]
extends star_ring R :=
(add_le_add_left : β a b : R, a β€ b β β c : R, c + a β€ c + b)
(nonneg_iff : β r : R, 0 β€ r β β s, r = star s * s)
namespace star_ordered_ring
variables [ring R] [partial_order R] [star_ordered_ring R]
@[priority 100] -- see note [lower instance priority]
instance : ordered_add_comm_group R :=
{ ..show ring R, by apply_instance,
..show partial_order R, by apply_instance,
..show star_ordered_ring R, by apply_instance }
end star_ordered_ring
lemma star_mul_self_nonneg
[non_unital_semiring R] [partial_order R] [star_ordered_ring R] {r : R} : 0 β€ star r * r :=
(star_ordered_ring.nonneg_iff _).mpr β¨r, rflβ©
lemma star_mul_self_nonneg'
[non_unital_semiring R] [partial_order R] [star_ordered_ring R] {r : R} : 0 β€ r * star r :=
by { nth_rewrite_rhs 0 [βstar_star r], exact star_mul_self_nonneg }
/--
A star module `A` over a star ring `R` is a module which is a star add monoid,
and the two star structures are compatible in the sense
`star (r β’ a) = star r β’ star a`.
Note that it is up to the user of this typeclass to enforce
`[semiring R] [star_ring R] [add_comm_monoid A] [star_add_monoid A] [module R A]`, and that
the statement only requires `[has_star R] [has_star A] [has_smul R A]`.
If used as `[comm_ring R] [star_ring R] [semiring A] [star_ring A] [algebra R A]`, this represents a
star algebra.
-/
class star_module (R : Type u) (A : Type v) [has_star R] [has_star A] [has_smul R A] : Prop :=
(star_smul : β (r : R) (a : A), star (r β’ a) = star r β’ star a)
export star_module (star_smul)
attribute [simp] star_smul
/-- A commutative star monoid is a star module over itself via `monoid.to_mul_action`. -/
instance star_semigroup.to_star_module [comm_monoid R] [star_semigroup R] : star_module R R :=
β¨star_mul'β©
namespace ring_hom_inv_pair
/-- Instance needed to define star-linear maps over a commutative star ring
(ex: conjugate-linear maps when R = β). -/
instance [comm_semiring R] [star_ring R] :
ring_hom_inv_pair (star_ring_end R) (star_ring_end R) :=
β¨ring_hom.ext star_star, ring_hom.ext star_starβ©
end ring_hom_inv_pair
/-! ### Instances -/
namespace units
variables [monoid R] [star_semigroup R]
instance : star_semigroup RΛ£ :=
{ star := Ξ» u,
{ val := star u,
inv := star βuβ»ΒΉ,
val_inv := (star_mul _ _).symm.trans $ (congr_arg star u.inv_val).trans $ star_one _,
inv_val := (star_mul _ _).symm.trans $ (congr_arg star u.val_inv).trans $ star_one _ },
star_involutive := Ξ» u, units.ext (star_involutive _),
star_mul := Ξ» u v, units.ext (star_mul _ _) }
@[simp] lemma coe_star (u : RΛ£) : β(star u) = (star βu : R) := rfl
@[simp] lemma coe_star_inv (u : RΛ£) : β(star u)β»ΒΉ = (star βuβ»ΒΉ : R) := rfl
instance {A : Type*} [has_star A] [has_smul R A] [star_module R A] : star_module RΛ£ A :=
β¨Ξ» u a, (star_smul βu a : _)β©
end units
lemma is_unit.star [monoid R] [star_semigroup R] {a : R} : is_unit a β is_unit (star a)
| β¨u, huβ© := β¨star u, hu βΈ rflβ©
@[simp] lemma is_unit_star [monoid R] [star_semigroup R] {a : R} : is_unit (star a) β is_unit a :=
β¨Ξ» h, star_star a βΈ h.star, is_unit.starβ©
lemma ring.inverse_star [semiring R] [star_ring R] (a : R) :
ring.inverse (star a) = star (ring.inverse a) :=
begin
by_cases ha : is_unit a,
{ obtain β¨u, rflβ© := ha,
rw [ring.inverse_unit, βunits.coe_star, ring.inverse_unit, βunits.coe_star_inv], },
rw [ring.inverse_non_unit _ ha, ring.inverse_non_unit _ (mt is_unit_star.mp ha), star_zero],
end
instance invertible.star {R : Type*} [monoid R] [star_semigroup R] (r : R) [invertible r] :
invertible (star r) :=
{ inv_of := star (β
r),
inv_of_mul_self := by rw [βstar_mul, mul_inv_of_self, star_one],
mul_inv_of_self := by rw [βstar_mul, inv_of_mul_self, star_one] }
lemma star_inv_of {R : Type*} [monoid R] [star_semigroup R] (r : R)
[invertible r] [invertible (star r)] :
star (β
r) = β
(star r) :=
by { letI := invertible.star r, convert (rfl : star (β
r) = _) }
namespace mul_opposite
/-- The opposite type carries the same star operation. -/
instance [has_star R] : has_star (Rα΅α΅α΅) :=
{ star := Ξ» r, op (star (r.unop)) }
@[simp] lemma unop_star [has_star R] (r : Rα΅α΅α΅) : unop (star r) = star (unop r) := rfl
@[simp] lemma op_star [has_star R] (r : R) : op (star r) = star (op r) := rfl
instance [has_involutive_star R] : has_involutive_star (Rα΅α΅α΅) :=
{ star_involutive := Ξ» r, unop_injective (star_star r.unop) }
instance [monoid R] [star_semigroup R] : star_semigroup (Rα΅α΅α΅) :=
{ star_mul := Ξ» x y, unop_injective (star_mul y.unop x.unop) }
instance [add_monoid R] [star_add_monoid R] : star_add_monoid (Rα΅α΅α΅) :=
{ star_add := Ξ» x y, unop_injective (star_add x.unop y.unop) }
instance [semiring R] [star_ring R] : star_ring (Rα΅α΅α΅) :=
{ .. mul_opposite.star_add_monoid }
end mul_opposite
/-- A commutative star monoid is a star module over its opposite via
`monoid.to_opposite_mul_action`. -/
instance star_semigroup.to_opposite_star_module [comm_monoid R] [star_semigroup R] :
star_module Rα΅α΅α΅ R :=
β¨Ξ» r s, star_mul' s r.unopβ©
|
f84abfbea54f1dd1e5302416cf7c633b9c46f951 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/measure_theory/integral/mean_inequalities.lean | 614e0060f3520273c874789a9c5d415df7a91d86 | [
"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 | 19,534 | lean | /-
Copyright (c) 2020 RΓ©my Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: RΓ©my Degenne
-/
import measure_theory.integral.lebesgue
import analysis.mean_inequalities
import analysis.mean_inequalities_pow
import measure_theory.function.special_functions.basic
/-!
# Mean value inequalities for integrals
In this file we prove several inequalities on integrals, notably the HΓΆlder inequality and
the Minkowski inequality. The versions for finite sums are in `analysis.mean_inequalities`.
## Main results
HΓΆlder's inequality for the Lebesgue integral of `ββ₯0β` and `ββ₯0` functions: we prove
`β« (f * g) βΞΌ β€ (β« f^p βΞΌ) ^ (1/p) * (β« g^q βΞΌ) ^ (1/q)` for `p`, `q` conjugate real exponents
and `Ξ±β(e)nnreal` functions in two cases,
* `ennreal.lintegral_mul_le_Lp_mul_Lq` : ββ₯0β functions,
* `nnreal.lintegral_mul_le_Lp_mul_Lq` : ββ₯0 functions.
Minkowski's inequality for the Lebesgue integral of measurable functions with `ββ₯0β` values:
we prove `(β« (f + g)^p βΞΌ) ^ (1/p) β€ (β« f^p βΞΌ) ^ (1/p) + (β« g^p βΞΌ) ^ (1/p)` for `1 β€ p`.
-/
section lintegral
/-!
### HΓΆlder's inequality for the Lebesgue integral of ββ₯0β and nnreal functions
We prove `β« (f * g) βΞΌ β€ (β« f^p βΞΌ) ^ (1/p) * (β« g^q βΞΌ) ^ (1/q)` for `p`, `q`
conjugate real exponents and `Ξ±β(e)nnreal` functions in several cases, the first two being useful
only to prove the more general results:
* `ennreal.lintegral_mul_le_one_of_lintegral_rpow_eq_one` : ββ₯0β functions for which the
integrals on the right are equal to 1,
* `ennreal.lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top` : ββ₯0β functions for which the
integrals on the right are neither β€ nor 0,
* `ennreal.lintegral_mul_le_Lp_mul_Lq` : ββ₯0β functions,
* `nnreal.lintegral_mul_le_Lp_mul_Lq` : nnreal functions.
-/
noncomputable theory
open_locale classical big_operators nnreal ennreal
open measure_theory
variables {Ξ± : Type*} [measurable_space Ξ±] {ΞΌ : measure Ξ±}
namespace ennreal
lemma lintegral_mul_le_one_of_lintegral_rpow_eq_one {p q : β} (hpq : p.is_conjugate_exponent q)
{f g : Ξ± β ββ₯0β} (hf : ae_measurable f ΞΌ) (hf_norm : β«β» a, (f a)^p βΞΌ = 1)
(hg_norm : β«β» a, (g a)^q βΞΌ = 1) :
β«β» a, (f * g) a βΞΌ β€ 1 :=
begin
calc β«β» (a : Ξ±), ((f * g) a) βΞΌ
β€ β«β» (a : Ξ±), ((f a)^p / ennreal.of_real p + (g a)^q / ennreal.of_real q) βΞΌ :
lintegral_mono (Ξ» a, young_inequality (f a) (g a) hpq)
... = 1 :
begin
simp only [div_eq_mul_inv],
rw lintegral_add_left',
{ rw [lintegral_mul_const'' _ (hf.pow_const p), lintegral_mul_const', hf_norm, hg_norm,
β div_eq_mul_inv, β div_eq_mul_inv, hpq.inv_add_inv_conj_ennreal],
simp [hpq.symm.pos], },
{ exact (hf.pow_const _).mul_const _, },
end
end
/-- Function multiplied by the inverse of its p-seminorm `(β«β» f^p βΞΌ) ^ 1/p`-/
def fun_mul_inv_snorm (f : Ξ± β ββ₯0β) (p : β) (ΞΌ : measure Ξ±) : Ξ± β ββ₯0β :=
Ξ» a, (f a) * ((β«β» c, (f c) ^ p βΞΌ) ^ (1 / p))β»ΒΉ
lemma fun_eq_fun_mul_inv_snorm_mul_snorm {p : β} (f : Ξ± β ββ₯0β)
(hf_nonzero : β«β» a, (f a) ^ p βΞΌ β 0) (hf_top : β«β» a, (f a) ^ p βΞΌ β β€) {a : Ξ±} :
f a = (fun_mul_inv_snorm f p ΞΌ a) * (β«β» c, (f c)^p βΞΌ)^(1/p) :=
by simp [fun_mul_inv_snorm, mul_assoc, inv_mul_cancel, hf_nonzero, hf_top]
lemma fun_mul_inv_snorm_rpow {p : β} (hp0 : 0 < p) {f : Ξ± β ββ₯0β} {a : Ξ±} :
(fun_mul_inv_snorm f p ΞΌ a) ^ p = (f a)^p * (β«β» c, (f c) ^ p βΞΌ)β»ΒΉ :=
begin
rw [fun_mul_inv_snorm, mul_rpow_of_nonneg _ _ (le_of_lt hp0)],
suffices h_inv_rpow : ((β«β» (c : Ξ±), f c ^ p βΞΌ) ^ (1 / p))β»ΒΉ ^ p = (β«β» (c : Ξ±), f c ^ p βΞΌ)β»ΒΉ,
by rw h_inv_rpow,
rw [inv_rpow, β rpow_mul, one_div_mul_cancel hp0.ne', rpow_one]
end
lemma lintegral_rpow_fun_mul_inv_snorm_eq_one {p : β} (hp0_lt : 0 < p) {f : Ξ± β ββ₯0β}
(hf_nonzero : β«β» a, (f a)^p βΞΌ β 0) (hf_top : β«β» a, (f a)^p βΞΌ β β€) :
β«β» c, (fun_mul_inv_snorm f p ΞΌ c)^p βΞΌ = 1 :=
begin
simp_rw fun_mul_inv_snorm_rpow hp0_lt,
rw [lintegral_mul_const', mul_inv_cancel hf_nonzero hf_top],
rwa inv_ne_top
end
/-- HΓΆlder's inequality in case of finite non-zero integrals -/
lemma lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top {p q : β} (hpq : p.is_conjugate_exponent q)
{f g : Ξ± β ββ₯0β} (hf : ae_measurable f ΞΌ)
(hf_nontop : β«β» a, (f a)^p βΞΌ β β€) (hg_nontop : β«β» a, (g a)^q βΞΌ β β€)
(hf_nonzero : β«β» a, (f a)^p βΞΌ β 0) (hg_nonzero : β«β» a, (g a)^q βΞΌ β 0) :
β«β» a, (f * g) a βΞΌ β€ (β«β» a, (f a)^p βΞΌ)^(1/p) * (β«β» a, (g a)^q βΞΌ)^(1/q) :=
begin
let npf := (β«β» (c : Ξ±), (f c) ^ p βΞΌ) ^ (1/p),
let nqg := (β«β» (c : Ξ±), (g c) ^ q βΞΌ) ^ (1/q),
calc β«β» (a : Ξ±), (f * g) a βΞΌ
= β«β» (a : Ξ±), ((fun_mul_inv_snorm f p ΞΌ * fun_mul_inv_snorm g q ΞΌ) a)
* (npf * nqg) βΞΌ :
begin
refine lintegral_congr (Ξ» a, _),
rw [pi.mul_apply, fun_eq_fun_mul_inv_snorm_mul_snorm f hf_nonzero hf_nontop,
fun_eq_fun_mul_inv_snorm_mul_snorm g hg_nonzero hg_nontop, pi.mul_apply],
ring,
end
... β€ npf * nqg :
begin
rw lintegral_mul_const' (npf * nqg) _ (by simp [hf_nontop, hg_nontop, hf_nonzero, hg_nonzero]),
nth_rewrite 1 βone_mul (npf * nqg),
refine mul_le_mul _ (le_refl (npf * nqg)),
have hf1 := lintegral_rpow_fun_mul_inv_snorm_eq_one hpq.pos hf_nonzero hf_nontop,
have hg1 := lintegral_rpow_fun_mul_inv_snorm_eq_one hpq.symm.pos hg_nonzero hg_nontop,
exact lintegral_mul_le_one_of_lintegral_rpow_eq_one hpq (hf.mul_const _) hf1 hg1,
end
end
lemma ae_eq_zero_of_lintegral_rpow_eq_zero {p : β} (hp0 : 0 β€ p) {f : Ξ± β ββ₯0β}
(hf : ae_measurable f ΞΌ) (hf_zero : β«β» a, (f a)^p βΞΌ = 0) :
f =α΅[ΞΌ] 0 :=
begin
rw lintegral_eq_zero_iff' (hf.pow_const p) at hf_zero,
refine filter.eventually.mp hf_zero (filter.eventually_of_forall (Ξ» x, _)),
dsimp only,
rw [pi.zero_apply, β not_imp_not],
exact Ξ» hx, (rpow_pos_of_nonneg (pos_iff_ne_zero.2 hx) hp0).ne'
end
lemma lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero {p : β} (hp0 : 0 β€ p)
{f g : Ξ± β ββ₯0β} (hf : ae_measurable f ΞΌ) (hf_zero : β«β» a, (f a)^p βΞΌ = 0) :
β«β» a, (f * g) a βΞΌ = 0 :=
begin
rw β@lintegral_zero_fun Ξ± _ ΞΌ,
refine lintegral_congr_ae _,
suffices h_mul_zero : f * g =α΅[ΞΌ] 0 * g , by rwa zero_mul at h_mul_zero,
have hf_eq_zero : f =α΅[ΞΌ] 0, from ae_eq_zero_of_lintegral_rpow_eq_zero hp0 hf hf_zero,
exact hf_eq_zero.mul (ae_eq_refl g),
end
lemma lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top {p q : β} (hp0_lt : 0 < p) (hq0 : 0 β€ q)
{f g : Ξ± β ββ₯0β} (hf_top : β«β» a, (f a)^p βΞΌ = β€) (hg_nonzero : β«β» a, (g a)^q βΞΌ β 0) :
β«β» a, (f * g) a βΞΌ β€ (β«β» a, (f a)^p βΞΌ) ^ (1/p) * (β«β» a, (g a)^q βΞΌ) ^ (1/q) :=
begin
refine le_trans le_top (le_of_eq _),
have hp0_inv_lt : 0 < 1/p, by simp [hp0_lt],
rw [hf_top, ennreal.top_rpow_of_pos hp0_inv_lt],
simp [hq0, hg_nonzero],
end
/-- HΓΆlder's inequality for functions `Ξ± β ββ₯0β`. The integral of the product of two functions
is bounded by the product of their `βp` and `βq` seminorms when `p` and `q` are conjugate
exponents. -/
theorem lintegral_mul_le_Lp_mul_Lq (ΞΌ : measure Ξ±) {p q : β} (hpq : p.is_conjugate_exponent q)
{f g : Ξ± β ββ₯0β} (hf : ae_measurable f ΞΌ) (hg : ae_measurable g ΞΌ) :
β«β» a, (f * g) a βΞΌ β€ (β«β» a, (f a)^p βΞΌ) ^ (1/p) * (β«β» a, (g a)^q βΞΌ) ^ (1/q) :=
begin
by_cases hf_zero : β«β» a, (f a) ^ p βΞΌ = 0,
{ refine eq.trans_le _ (zero_le _),
exact lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero hpq.nonneg hf hf_zero, },
by_cases hg_zero : β«β» a, (g a) ^ q βΞΌ = 0,
{ refine eq.trans_le _ (zero_le _),
rw mul_comm,
exact lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero hpq.symm.nonneg hg hg_zero, },
by_cases hf_top : β«β» a, (f a) ^ p βΞΌ = β€,
{ exact lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top hpq.pos hpq.symm.nonneg hf_top hg_zero, },
by_cases hg_top : β«β» a, (g a) ^ q βΞΌ = β€,
{ rw [mul_comm, mul_comm ((β«β» (a : Ξ±), (f a) ^ p βΞΌ) ^ (1 / p))],
exact lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top hpq.symm.pos hpq.nonneg hg_top hf_zero, },
-- non-β€ non-zero case
exact ennreal.lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top hpq hf hf_top hg_top hf_zero hg_zero
end
lemma lintegral_rpow_add_lt_top_of_lintegral_rpow_lt_top {p : β}
{f g : Ξ± β ββ₯0β} (hf : ae_measurable f ΞΌ) (hf_top : β«β» a, (f a) ^ p βΞΌ < β€)
(hg_top : β«β» a, (g a) ^ p βΞΌ < β€) (hp1 : 1 β€ p) :
β«β» a, ((f + g) a) ^ p βΞΌ < β€ :=
begin
have hp0_lt : 0 < p, from lt_of_lt_of_le zero_lt_one hp1,
have hp0 : 0 β€ p, from le_of_lt hp0_lt,
calc β«β» (a : Ξ±), (f a + g a) ^ p βΞΌ
β€ β«β» a, ((2:ββ₯0β)^(p-1) * (f a) ^ p + (2:ββ₯0β)^(p-1) * (g a) ^ p) β ΞΌ :
begin
refine lintegral_mono (Ξ» a, _),
dsimp only,
have h_zero_lt_half_rpow : (0 : ββ₯0β) < (1 / 2) ^ p,
{ rw [βennreal.zero_rpow_of_pos hp0_lt],
exact ennreal.rpow_lt_rpow (by simp [zero_lt_one]) hp0_lt, },
have h_rw : (1 / 2) ^ p * (2:ββ₯0β) ^ (p - 1) = 1 / 2,
{ rw [sub_eq_add_neg, ennreal.rpow_add _ _ ennreal.two_ne_zero ennreal.coe_ne_top,
βmul_assoc, βennreal.mul_rpow_of_nonneg _ _ hp0, one_div,
ennreal.inv_mul_cancel ennreal.two_ne_zero ennreal.coe_ne_top, ennreal.one_rpow,
one_mul, ennreal.rpow_neg_one], },
rw βennreal.mul_le_mul_left (ne_of_lt h_zero_lt_half_rpow).symm _,
{ rw [mul_add, β mul_assoc, β mul_assoc, h_rw, βennreal.mul_rpow_of_nonneg _ _ hp0, mul_add],
refine ennreal.rpow_arith_mean_le_arith_mean2_rpow (1/2 : ββ₯0β) (1/2 : ββ₯0β)
(f a) (g a) _ hp1,
rw [ennreal.div_add_div_same, one_add_one_eq_two,
ennreal.div_self ennreal.two_ne_zero ennreal.coe_ne_top], },
{ rw β lt_top_iff_ne_top,
refine ennreal.rpow_lt_top_of_nonneg hp0 _,
rw [one_div, ennreal.inv_ne_top],
exact ennreal.two_ne_zero, },
end
... < β€ :
begin
have h_two : (2 : ββ₯0β) ^ (p - 1) β β€,
from ennreal.rpow_ne_top_of_nonneg (by simp [hp1]) ennreal.coe_ne_top,
rw [lintegral_add_left', lintegral_const_mul'' _ (hf.pow_const p),
lintegral_const_mul' _ _ h_two, ennreal.add_lt_top],
{ exact β¨ennreal.mul_lt_top h_two hf_top.ne, ennreal.mul_lt_top h_two hg_top.neβ© },
{ exact (hf.pow_const p).const_mul _ }
end
end
lemma lintegral_Lp_mul_le_Lq_mul_Lr {Ξ±} [measurable_space Ξ±] {p q r : β} (hp0_lt : 0 < p)
(hpq : p < q) (hpqr : 1/p = 1/q + 1/r) (ΞΌ : measure Ξ±) {f g : Ξ± β ββ₯0β}
(hf : ae_measurable f ΞΌ) (hg : ae_measurable g ΞΌ) :
(β«β» a, ((f * g) a)^p βΞΌ) ^ (1/p) β€ (β«β» a, (f a)^q βΞΌ) ^ (1/q) * (β«β» a, (g a)^r βΞΌ) ^ (1/r) :=
begin
have hp0_ne : p β 0, from (ne_of_lt hp0_lt).symm,
have hp0 : 0 β€ p, from le_of_lt hp0_lt,
have hq0_lt : 0 < q, from lt_of_le_of_lt hp0 hpq,
have hq0_ne : q β 0, from (ne_of_lt hq0_lt).symm,
have h_one_div_r : 1/r = 1/p - 1/q, by simp [hpqr],
have hr0_ne : r β 0,
{ have hr_inv_pos : 0 < 1/r,
by rwa [h_one_div_r, sub_pos, one_div_lt_one_div hq0_lt hp0_lt],
rw [one_div, _root_.inv_pos] at hr_inv_pos,
exact (ne_of_lt hr_inv_pos).symm, },
let p2 := q/p,
let q2 := p2.conjugate_exponent,
have hp2q2 : p2.is_conjugate_exponent q2,
from real.is_conjugate_exponent_conjugate_exponent (by simp [lt_div_iff, hpq, hp0_lt]),
calc (β«β» (a : Ξ±), ((f * g) a) ^ p βΞΌ) ^ (1 / p)
= (β«β» (a : Ξ±), (f a)^p * (g a)^p βΞΌ) ^ (1 / p) :
by simp_rw [pi.mul_apply, ennreal.mul_rpow_of_nonneg _ _ hp0]
... β€ ((β«β» a, (f a)^(p * p2) β ΞΌ)^(1/p2) * (β«β» a, (g a)^(p * q2) β ΞΌ)^(1/q2)) ^ (1/p) :
begin
refine ennreal.rpow_le_rpow _ (by simp [hp0]),
simp_rw ennreal.rpow_mul,
exact ennreal.lintegral_mul_le_Lp_mul_Lq ΞΌ hp2q2 (hf.pow_const _) (hg.pow_const _)
end
... = (β«β» (a : Ξ±), (f a) ^ q βΞΌ) ^ (1 / q) * (β«β» (a : Ξ±), (g a) ^ r βΞΌ) ^ (1 / r) :
begin
rw [@ennreal.mul_rpow_of_nonneg _ _ (1/p) (by simp [hp0]), βennreal.rpow_mul,
βennreal.rpow_mul],
have hpp2 : p * p2 = q,
{ symmetry, rw [mul_comm, βdiv_eq_iff hp0_ne], },
have hpq2 : p * q2 = r,
{ rw [β inv_inv r, β one_div, β one_div, h_one_div_r],
field_simp [q2, real.conjugate_exponent, p2, hp0_ne, hq0_ne] },
simp_rw [div_mul_div_comm, mul_one, mul_comm p2, mul_comm q2, hpp2, hpq2],
end
end
lemma lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow {p q : β}
(hpq : p.is_conjugate_exponent q) {f g : Ξ± β ββ₯0β}
(hf : ae_measurable f ΞΌ) (hg : ae_measurable g ΞΌ) (hf_top : β«β» a, (f a) ^ p βΞΌ β β€) :
β«β» a, (f a) * (g a) ^ (p - 1) βΞΌ β€ (β«β» a, (f a)^p βΞΌ) ^ (1/p) * (β«β» a, (g a)^p βΞΌ) ^ (1/q) :=
begin
refine le_trans (ennreal.lintegral_mul_le_Lp_mul_Lq ΞΌ hpq hf (hg.pow_const _)) _,
by_cases hf_zero_rpow : (β«β» (a : Ξ±), (f a) ^ p βΞΌ) ^ (1 / p) = 0,
{ rw [hf_zero_rpow, zero_mul],
exact zero_le _, },
have hf_top_rpow : (β«β» (a : Ξ±), (f a) ^ p βΞΌ) ^ (1 / p) β β€,
{ by_contra h,
refine hf_top _,
have hp_not_neg : Β¬ p < 0, by simp [hpq.nonneg],
simpa [hpq.pos, hp_not_neg] using h, },
refine (ennreal.mul_le_mul_left hf_zero_rpow hf_top_rpow).mpr (le_of_eq _),
congr,
ext1 a,
rw [βennreal.rpow_mul, hpq.sub_one_mul_conj],
end
lemma lintegral_rpow_add_le_add_snorm_mul_lintegral_rpow_add {p q : β}
(hpq : p.is_conjugate_exponent q) {f g : Ξ± β ββ₯0β} (hf : ae_measurable f ΞΌ)
(hf_top : β«β» a, (f a) ^ p βΞΌ β β€) (hg : ae_measurable g ΞΌ) (hg_top : β«β» a, (g a) ^ p βΞΌ β β€) :
β«β» a, ((f + g) a)^p β ΞΌ
β€ ((β«β» a, (f a)^p βΞΌ) ^ (1/p) + (β«β» a, (g a)^p βΞΌ) ^ (1/p))
* (β«β» a, (f a + g a)^p βΞΌ) ^ (1/q) :=
begin
calc β«β» a, ((f+g) a) ^ p βΞΌ β€ β«β» a, ((f + g) a) * ((f + g) a) ^ (p - 1) βΞΌ :
begin
refine lintegral_mono (Ξ» a, _),
dsimp only,
by_cases h_zero : (f + g) a = 0,
{ rw [h_zero, ennreal.zero_rpow_of_pos hpq.pos],
exact zero_le _, },
by_cases h_top : (f + g) a = β€,
{ rw [h_top, ennreal.top_rpow_of_pos hpq.sub_one_pos, ennreal.top_mul_top],
exact le_top, },
refine le_of_eq _,
nth_rewrite 1 βennreal.rpow_one ((f + g) a),
rw [βennreal.rpow_add _ _ h_zero h_top, add_sub_cancel'_right],
end
... = β«β» (a : Ξ±), f a * (f + g) a ^ (p - 1) βΞΌ + β«β» (a : Ξ±), g a * (f + g) a ^ (p - 1) βΞΌ :
begin
have h_add_m : ae_measurable (Ξ» (a : Ξ±), ((f + g) a) ^ (p-1)) ΞΌ,
from (hf.add hg).pow_const _,
have h_add_apply : β«β» (a : Ξ±), (f + g) a * (f + g) a ^ (p - 1) βΞΌ
= β«β» (a : Ξ±), (f a + g a) * (f + g) a ^ (p - 1) βΞΌ,
from rfl,
simp_rw [h_add_apply, add_mul],
rw lintegral_add_left' (hf.mul h_add_m),
end
... β€ ((β«β» a, (f a)^p βΞΌ) ^ (1/p) + (β«β» a, (g a)^p βΞΌ) ^ (1/p))
* (β«β» a, (f a + g a)^p βΞΌ) ^ (1/q) :
begin
rw add_mul,
exact add_le_add
(lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow hpq hf (hf.add hg) hf_top)
(lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow hpq hg (hf.add hg) hg_top),
end
end
private lemma lintegral_Lp_add_le_aux {p q : β}
(hpq : p.is_conjugate_exponent q) {f g : Ξ± β ββ₯0β} (hf : ae_measurable f ΞΌ)
(hf_top : β«β» a, (f a) ^ p βΞΌ β β€) (hg : ae_measurable g ΞΌ) (hg_top : β«β» a, (g a) ^ p βΞΌ β β€)
(h_add_zero : β«β» a, ((f+g) a) ^ p β ΞΌ β 0) (h_add_top : β«β» a, ((f+g) a) ^ p β ΞΌ β β€) :
(β«β» a, ((f + g) a)^p β ΞΌ) ^ (1/p) β€ (β«β» a, (f a)^p βΞΌ) ^ (1/p) + (β«β» a, (g a)^p βΞΌ) ^ (1/p) :=
begin
have hp_not_nonpos : Β¬ p β€ 0, by simp [hpq.pos],
have htop_rpow : (β«β» a, ((f+g) a) ^ p βΞΌ)^(1/p) β β€,
{ by_contra h,
exact h_add_top (@ennreal.rpow_eq_top_of_nonneg _ (1/p) (by simp [hpq.nonneg]) h), },
have h0_rpow : (β«β» a, ((f+g) a) ^ p β ΞΌ) ^ (1/p) β 0,
by simp [h_add_zero, h_add_top, hpq.nonneg, hp_not_nonpos, -pi.add_apply],
suffices h : 1 β€ (β«β» (a : Ξ±), ((f+g) a)^p βΞΌ) ^ -(1/p)
* ((β«β» (a : Ξ±), (f a)^p βΞΌ) ^ (1/p) + (β«β» (a : Ξ±), (g a)^p βΞΌ) ^ (1/p)),
by rwa [βmul_le_mul_left h0_rpow htop_rpow, βmul_assoc, βrpow_add _ _ h_add_zero h_add_top,
βsub_eq_add_neg, _root_.sub_self, rpow_zero, one_mul, mul_one] at h,
have h : β«β» (a : Ξ±), ((f+g) a)^p βΞΌ
β€ ((β«β» (a : Ξ±), (f a)^p βΞΌ) ^ (1/p) + (β«β» (a : Ξ±), (g a)^p βΞΌ) ^ (1/p))
* (β«β» (a : Ξ±), ((f+g) a)^p βΞΌ) ^ (1/q),
from lintegral_rpow_add_le_add_snorm_mul_lintegral_rpow_add hpq hf hf_top hg hg_top,
have h_one_div_q : 1/q = 1 - 1/p, by { nth_rewrite 1 βhpq.inv_add_inv_conj, ring, },
simp_rw [h_one_div_q, sub_eq_add_neg 1 (1/p), ennreal.rpow_add _ _ h_add_zero h_add_top,
rpow_one] at h,
nth_rewrite 1 mul_comm at h,
nth_rewrite 0 βone_mul (β«β» (a : Ξ±), ((f+g) a) ^ p βΞΌ) at h,
rwa [βmul_assoc, ennreal.mul_le_mul_right h_add_zero h_add_top, mul_comm] at h,
end
/-- Minkowski's inequality for functions `Ξ± β ββ₯0β`: the `βp` seminorm of the sum of two
functions is bounded by the sum of their `βp` seminorms. -/
theorem lintegral_Lp_add_le {p : β} {f g : Ξ± β ββ₯0β}
(hf : ae_measurable f ΞΌ) (hg : ae_measurable g ΞΌ) (hp1 : 1 β€ p) :
(β«β» a, ((f + g) a)^p β ΞΌ) ^ (1/p) β€ (β«β» a, (f a)^p βΞΌ) ^ (1/p) + (β«β» a, (g a)^p βΞΌ) ^ (1/p) :=
begin
have hp_pos : 0 < p, from lt_of_lt_of_le zero_lt_one hp1,
by_cases hf_top : β«β» a, (f a) ^ p βΞΌ = β€,
{ simp [hf_top, hp_pos], },
by_cases hg_top : β«β» a, (g a) ^ p βΞΌ = β€,
{ simp [hg_top, hp_pos], },
by_cases h1 : p = 1,
{ refine le_of_eq _,
simp_rw [h1, one_div_one, ennreal.rpow_one],
exact lintegral_add_left' hf _, },
have hp1_lt : 1 < p, by { refine lt_of_le_of_ne hp1 _, symmetry, exact h1, },
have hpq := real.is_conjugate_exponent_conjugate_exponent hp1_lt,
by_cases h0 : β«β» a, ((f+g) a) ^ p β ΞΌ = 0,
{ rw [h0, @ennreal.zero_rpow_of_pos (1/p) (by simp [lt_of_lt_of_le zero_lt_one hp1])],
exact zero_le _, },
have htop : β«β» a, ((f+g) a) ^ p β ΞΌ β β€,
{ rw β ne.def at hf_top hg_top,
rw β lt_top_iff_ne_top at hf_top hg_top β’,
exact lintegral_rpow_add_lt_top_of_lintegral_rpow_lt_top hf hf_top hg_top hp1, },
exact lintegral_Lp_add_le_aux hpq hf hf_top hg hg_top h0 htop,
end
end ennreal
/-- HΓΆlder's inequality for functions `Ξ± β ββ₯0`. The integral of the product of two functions
is bounded by the product of their `βp` and `βq` seminorms when `p` and `q` are conjugate
exponents. -/
theorem nnreal.lintegral_mul_le_Lp_mul_Lq {p q : β} (hpq : p.is_conjugate_exponent q)
{f g : Ξ± β ββ₯0} (hf : ae_measurable f ΞΌ) (hg : ae_measurable g ΞΌ) :
β«β» a, (f * g) a βΞΌ β€ (β«β» a, (f a)^p βΞΌ)^(1/p) * (β«β» a, (g a)^q βΞΌ)^(1/q) :=
begin
simp_rw [pi.mul_apply, ennreal.coe_mul],
exact ennreal.lintegral_mul_le_Lp_mul_Lq ΞΌ hpq hf.coe_nnreal_ennreal hg.coe_nnreal_ennreal,
end
end lintegral
|
9e8b9ce151e3a6f62f3bdfb17f502222529d2182 | f3849be5d845a1cb97680f0bbbe03b85518312f0 | /old_library/init/sigma_lex.lean | 5aa6ae184974711ca845767a98e7950f3ba31fdf | [
"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 | 5,781 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.sigma init.meta init.combinator
universe variables u v
namespace sigma
section
variables {A : Type u} {B : A β Type v}
variable (Ra : A β A β Prop)
variable (Rb : β a, B a β B a β Prop)
-- Lexicographical order based on Ra and Rb
inductive lex : sigma B β sigma B β Prop
| left : β {aβ : A} (bβ : B aβ) {aβ : A} (bβ : B aβ), Ra aβ aβ β lex (sigma.mk aβ bβ) (sigma.mk aβ bβ)
| right : β (a : A) {bβ bβ : B a}, Rb a bβ bβ β lex (sigma.mk a bβ) (sigma.mk a bβ)
end
section
open well_founded tactic
parameters {A : Type u} {B : A β Type v}
parameters {Ra : A β A β Prop} {Rb : Ξ a : A, B a β B a β Prop}
local infix `βΊ`:50 := lex Ra Rb
definition lex_accessible {a} (aca : acc Ra a) (acb : β a, well_founded (Rb a))
: β (b : B a), acc (lex Ra Rb) (sigma.mk a b) :=
acc.rec_on aca
(Ξ» xa aca (iHa : β y, Ra y xa β β b : B y, acc (lex Ra Rb) (sigma.mk y b)),
Ξ» b : B xa, acc.rec_on (well_founded.apply (acb xa) b)
(Ξ» xb acb
(iHb : β (y : B xa), Rb xa y xb β acc (lex Ra Rb) (sigma.mk xa y)),
acc.intro (sigma.mk xa xb) (Ξ» p (lt : p βΊ (sigma.mk xa xb)),
have aux : xa = xa β xb == xb β acc (lex Ra Rb) p, from
@sigma.lex.rec_on A B Ra Rb (Ξ» pβ pβ, pβ.1 = xa β pβ.2 == xb β acc (lex Ra Rb) pβ)
p (sigma.mk xa xb) lt
(Ξ» (aβ : A) (bβ : B aβ) (aβ : A) (bβ : B aβ) (H : Ra aβ aβ) (eqβ : aβ = xa) (eqβ : bβ == xb),
by do
get_local `eqβ >>= subst,
to_expr `(iHa aβ H bβ) >>= exact)
(Ξ» (a : A) (bβ bβ : B a) (H : Rb a bβ bβ) (eqβ : a = xa) (eqβ : bβ == xb),
by do
get_local `eqβ >>= subst,
to_expr `(eq_of_heq eqβ) >>= note `new_eqβ,
get_local `new_eqβ >>= subst,
to_expr `(iHb bβ H) >>= exact),
aux rfl (heq.refl xb))))
-- The lexicographical order of well founded relations is well-founded
definition lex_wf (Ha : well_founded Ra) (Hb : β x, well_founded (Rb x)) : well_founded (lex Ra Rb) :=
well_founded.intro (Ξ» p, destruct p (Ξ» a b, lex_accessible (well_founded.apply Ha a) Hb b))
end
section
parameters {A : Type u} {B : Type v}
definition lex_ndep (Ra : A β A β Prop) (Rb : B β B β Prop) :=
lex Ra (Ξ» a : A, Rb)
definition lex_ndep_wf {Ra : A β A β Prop} {Rb : B β B β Prop} (Ha : well_founded Ra) (Hb : well_founded Rb)
: well_founded (lex_ndep Ra Rb) :=
well_founded.intro (Ξ» p, destruct p (Ξ» a b, lex_accessible (well_founded.apply Ha a) (Ξ» x, Hb) b))
end
section
variables {A : Type u} {B : Type v}
variable (Ra : A β A β Prop)
variable (Rb : B β B β Prop)
-- Reverse lexicographical order based on Ra and Rb
inductive rev_lex : @sigma A (Ξ» a, B) β @sigma A (Ξ» a, B) β Prop
| left : β {aβ aβ : A} (b : B), Ra aβ aβ β rev_lex (sigma.mk aβ b) (sigma.mk aβ b)
| right : β (aβ : A) {bβ : B} (aβ : A) {bβ : B}, Rb bβ bβ β rev_lex (sigma.mk aβ bβ) (sigma.mk aβ bβ)
end
section
open well_founded tactic
parameters {A : Type u} {B : Type v}
parameters {Ra : A β A β Prop} {Rb : B β B β Prop}
local infix `βΊ`:50 := rev_lex Ra Rb
definition rev_lex_accessible {b} (acb : acc Rb b) (aca : β a, acc Ra a): β a, acc (rev_lex Ra Rb) (sigma.mk a b) :=
acc.rec_on acb
(Ξ» xb acb (iHb : β y, Rb y xb β β a, acc (rev_lex Ra Rb) (sigma.mk a y)),
Ξ» a, acc.rec_on (aca a)
(Ξ» xa aca (iHa : β y, Ra y xa β acc (rev_lex Ra Rb) (mk y xb)),
acc.intro (sigma.mk xa xb) (Ξ» p (lt : p βΊ (sigma.mk xa xb)),
have aux : xa = xa β xb = xb β acc (rev_lex Ra Rb) p, from
@rev_lex.rec_on A B Ra Rb (Ξ» pβ pβ, fst pβ = xa β snd pβ = xb β acc (rev_lex Ra Rb) pβ)
p (sigma.mk xa xb) lt
(Ξ» aβ aβ b (H : Ra aβ aβ) (eqβ : aβ = xa) (eqβ : b = xb),
show acc (rev_lex Ra Rb) (sigma.mk aβ b), from
have Raβ : Ra aβ xa, from eq.rec_on eqβ H,
have aux : acc (rev_lex Ra Rb) (sigma.mk aβ xb), from iHa aβ Raβ,
eq.rec_on (eq.symm eqβ) aux)
(Ξ» aβ bβ aβ bβ (H : Rb bβ bβ) (eqβ : aβ = xa) (eqβ : bβ = xb),
show acc (rev_lex Ra Rb) (mk aβ bβ), from
have Rbβ : Rb bβ xb, from eq.rec_on eqβ H,
iHb bβ Rbβ aβ),
aux rfl rfl)))
definition rev_lex_wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (rev_lex Ra Rb) :=
well_founded.intro (Ξ» p, destruct p (Ξ» a b, rev_lex_accessible (apply Hb b) (well_founded.apply Ha) a))
end
section
definition skip_left (A : Type u) {B : Type v} (Rb : B β B β Prop) : @sigma A (Ξ» a, B) β @sigma A (Ξ» a, B) β Prop :=
rev_lex empty_relation Rb
definition skip_left_wf (A : Type u) {B : Type v} {Rb : B β B β Prop} (Hb : well_founded Rb) : well_founded (skip_left A Rb) :=
rev_lex_wf empty_wf Hb
definition mk_skip_left {A : Type u} {B : Type v} {bβ bβ : B} {Rb : B β B β Prop}
(aβ aβ : A) (H : Rb bβ bβ) : skip_left A Rb (sigma.mk aβ bβ) (sigma.mk aβ bβ) :=
rev_lex.right _ _ _ H
end
end sigma
|
67fdffc91418d3822772a79813ea024d73fa9ce0 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/group_theory/monoid_localization.lean | 84691a14276907381f34cc3bb936fa9ec882c7cd | [
"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 | 40,817 | lean | /-
Copyright (c) 2019 Amelia Livingston. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Amelia Livingston
-/
import group_theory.congruence
import algebra.associated
import algebra.punit_instances
/-!
# Localizations of commutative monoids
Localizing a commutative ring at one of its submonoids does not rely on the ring's addition, so
we can generalize localizations to commutative monoids.
We characterize the localization of a commutative monoid `M` at a submonoid `S` up to
isomorphism; that is, a commutative monoid `N` is the localization of `M` at `S` iff we can find a
monoid homomorphism `f : M β* N` satisfying 3 properties:
1. For all `y β S`, `f y` is a unit;
2. For all `z : N`, there exists `(x, y) : M Γ S` such that `z * f y = f x`;
3. For all `x, y : M`, `f x = f y` iff there exists `c β S` such that `x * c = y * c`.
We also define the quotient of `M Γ S` by the unique congruence relation (equivalence relation
preserving a binary operation) `r` such that for any other congruence relation `s` on `M Γ S`
satisfying '`β y β S`, `(1, 1) βΌ (y, y)` under `s`', we have that `(xβ, yβ) βΌ (xβ, yβ)` by `s`
whenever `(xβ, yβ) βΌ (xβ, yβ)` by `r`. We show this relation is equivalent to the standard
localization relation.
This defines the localization as a quotient type, but the majority of subsequent lemmas in the file
are given in terms of localizations up to isomorphism, using maps which satisfy the characteristic
predicate.
Given such a localization map `f : M β* N`, we can define the surjection
`monoid_localization.mk` sending `(x, y) : M Γ S` to `f x * (f y)β»ΒΉ`, and
`monoid_localization.lift`, the homomorphism from `N` induced by a homomorphism from `M` which maps
elements of `S` to invertible elements of the codomain. Similarly, given commutative monoids
`P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism
`g : M β* P` such that `g(S) β T` induces a homomorphism of localizations,
`monoid_localization.map`, from `N` to `Q`.
## Implementation notes
In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one
structure with an isomorphic one; one way around this is to isolate a predicate characterizing
a structure up to isomorphism, and reason about things that satisfy the predicate.
The infimum form of the localization congruence relation is chosen as 'canonical' here, since it
shortens some proofs.
## Tags
localization, monoid localization, quotient monoid, congruence relation, characteristic predicate,
commutative monoid
-/
namespace add_submonoid
variables {M : Type*} [add_comm_monoid M] (S : add_submonoid M) (N : Type*) [add_comm_monoid N]
/-- The type of add_monoid homomorphisms satisfying the characteristic predicate: if `f : M β+ N`
satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/
@[nolint has_inhabited_instance] structure localization_map :=
(to_fun : M β+ N)
(map_add_units : β y : S, is_add_unit (to_fun y))
(surj : β z : N, β x : M Γ S, z + to_fun x.2 = to_fun x.1)
(eq_iff_exists : β x y, to_fun x = to_fun y β β c : S, x + c = y + c)
end add_submonoid
variables {M : Type*} [comm_monoid M] (S : submonoid M) (N : Type*) [comm_monoid N]
{P : Type*} [comm_monoid P]
namespace submonoid
/-- The type of monoid homomorphisms satisfying the characteristic predicate: if `f : M β* N`
satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/
@[nolint has_inhabited_instance] structure localization_map :=
(to_fun : M β* N)
(map_units : β y : S, is_unit (to_fun y))
(surj : β z : N, β x : M Γ S, z * to_fun x.2 = to_fun x.1)
(eq_iff_exists : β x y, to_fun x = to_fun y β β c : S, x * c = y * c)
attribute [to_additive add_submonoid.localization_map] submonoid.localization_map
namespace localization
/-- The congruence relation on `M Γ S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose
quotient is the localization of `M` at `S`, defined as the unique congruence relation on
`M Γ S` such that for any other congruence relation `s` on `M Γ S` where for all `y β S`,
`(1, 1) βΌ (y, y)` under `s`, we have that `(xβ, yβ) βΌ (xβ, yβ)` by `r` implies
`(xβ, yβ) βΌ (xβ, yβ)` by `s`. -/
@[to_additive "The congruence relation on `M Γ S`, `M` an `add_comm_monoid` and `S` an `add_submonoid` of `M`, whose quotient is the localization of `M` at `S`, defined as the unique congruence relation on `M Γ S` such that for any other congruence relation `s` on `M Γ S` where for all `y β S`, `(0, 0) βΌ (y, y)` under `s`, we have that `(xβ, yβ) βΌ (xβ, yβ)` by `r` implies `(xβ, yβ) βΌ (xβ, yβ)` by `s`."]
def r (S : submonoid M) : con (M Γ S) :=
Inf {c | β y : S, c 1 (y, y)}
/-- An alternate form of the congruence relation on `M Γ S`, `M` a `comm_monoid` and `S` a
submonoid of `M`, whose quotient is the localization of `M` at `S`. Its equivalence to `r` can
be useful for proofs. -/
@[to_additive "An alternate form of the congruence relation on `M Γ S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`. Its equivalence to `r` can be useful for proofs."]
def r' : con (M Γ S) :=
begin
refine { r := Ξ» a b : M Γ S, β c : S, a.1 * b.2 * c = b.1 * a.2 * c,
iseqv := β¨Ξ» a, β¨1, rflβ©, Ξ» a b β¨c, hcβ©, β¨c, hc.symmβ©, _β©,
.. },
{ rintros a b c β¨tβ, htββ© β¨tβ, htββ©,
use b.2 * tβ * tβ,
simp only [submonoid.coe_mul],
calc a.1 * c.2 * (b.2 * tβ * tβ) = a.1 * b.2 * tβ * c.2 * tβ : by ac_refl
... = b.1 * c.2 * tβ * a.2 * tβ : by { rw htβ, ac_refl }
... = c.1 * a.2 * (b.2 * tβ * tβ) : by { rw htβ, ac_refl } },
{ rintros a b c d β¨tβ, htββ© β¨tβ, htββ©,
use tβ * tβ,
calc (a.1 * c.1) * (b.2 * d.2) * (tβ * tβ) = (a.1 * b.2 * tβ) * (c.1 * d.2 * tβ) :
by ac_refl
... = (b.1 * d.1) * (a.2 * c.2) * (tβ * tβ) : by { rw [htβ, htβ], ac_refl } }
end
/-- The congruence relation used to localize a `comm_monoid` at a submonoid can be expressed
equivalently as an infimum (see `localization.r`) or explicitly
(see `localization.r'`). -/
@[to_additive "The additive congruence relation used to localize an `add_comm_monoid` at a submonoid can be expressed equivalently as an infimum (see `localization.r`) or explicitly (see `localization.r'`)."]
theorem r_eq_r' : r S = r' S :=
le_antisymm (Inf_le $ Ξ» _, β¨1, by simpβ©) $
le_Inf $ Ξ» b H β¨p, qβ© y β¨t, htβ©,
begin
rw [β mul_one (p, q), β mul_one y],
refine b.trans (b.mul (b.refl _) (H (y.2 * t))) _,
convert b.symm (b.mul (b.refl y) (H (q * t))); simp only [],
rw [prod.mk_mul_mk, submonoid.coe_mul, β mul_assoc, ht, mul_left_comm, mul_assoc],
refl
end
variables {S}
@[to_additive]
lemma r_iff_exists {x y : M Γ S} : r S x y β β c : S, x.1 * y.2 * c = y.1 * x.2 * c :=
by rw r_eq_r' S; refl
end localization
/-- The localization of a `comm_monoid` at one of its submonoids (as a quotient type). -/
@[to_additive "The localization of an `add_comm_monoid` at one of its submonoids (as a quotient type)."]
def localization := (localization.r S).quotient
@[to_additive] instance localization.inhabited :
inhabited (localization S) :=
con.quotient.inhabited
namespace localization_map
variables {S N}
@[to_additive, ext] lemma ext {f g : localization_map S N} (h : β x, f.1 x = g.1 x) : f = g :=
by cases f; cases g; simp only []; exact monoid_hom.ext h
attribute [ext] add_submonoid.localization_map.ext
@[to_additive] lemma ext_iff {f g : localization_map S N} : f = g β β x, f.1 x = g.1 x :=
β¨Ξ» h x, h βΈ rfl, extβ©
@[to_additive] lemma to_fun_inj {f g : localization_map S N} (h : f.1 = g.1) : f = g :=
ext $ monoid_hom.ext_iff.1 h
variables (S)
/-- Given a map `f : M β* N`, a section function sending `z : N` to some
`(x, y) : M Γ S` such that `f x * (f y)β»ΒΉ = z` if there always exists such an element. -/
@[to_additive "Given a map `f : M β+ N`, a section function sending `z : N` to some `(x, y) : M Γ S` such that `f x - f y = z` if there always exists such an element."]
noncomputable def sec (f : M β* N) :=
@classical.epsilon (N β M Γ S) β¨Ξ» z, 1β© (Ξ» g, β z, z * f (g z).2 = f (g z).1)
variables {S}
@[to_additive] lemma sec_spec {f : M β* N}
(h : β z : N, β x : M Γ S, z * f x.2 = f x.1) (z : N) :
z * f (sec S f z).2 = f (sec S f z).1 :=
@classical.epsilon_spec (N β M Γ S) (Ξ» g, β z, z * f (g z).2 = f (g z).1)
β¨Ξ» y, classical.some $ h y, Ξ» y, classical.some_spec $ h yβ© z
@[to_additive] lemma sec_spec' {f : M β* N}
(h : β z : N, β x : M Γ S, z * f x.2 = f x.1) (z : N) :
f (sec S f z).1 = f (sec S f z).2 * z :=
by rw [mul_comm, sec_spec h]
/-- Given a monoid hom `f : M β* N` and submonoid `S β M` such that `f(S) β units N`, for all
`w : M, z : N` and `y β S`, we have `w * (f y)β»ΒΉ = z β w = f y * z`. -/
@[to_additive "Given an add_monoid hom `f : M β+ N` and submonoid `S β M` such that `f(S) β add_units N`, for all `w : M, z : N` and `y β S`, we have `w - f y = z β w = f y + z`."]
lemma mul_inv_left {f : M β* N} (h : β y : S, is_unit (f y))
(y : S) (w z) : w * β(is_unit.lift_right (f.restrict S) h y)β»ΒΉ = z β w = f y * z :=
by rw mul_comm; convert units.inv_mul_eq_iff_eq_mul _;
exact (is_unit.coe_lift_right (f.restrict S) h _).symm
/-- Given a monoid hom `f : M β* N` and submonoid `S β M` such that `f(S) β units N`, for all
`w : M, z : N` and `y β S`, we have `z = w * (f y)β»ΒΉ β z * f y = w`. -/
@[to_additive "Given an add_monoid hom `f : M β+ N` and submonoid `S β M` such that `f(S) β add_units N`, for all `w : M, z : N` and `y β S`, we have `z = w - f y β z + f y = w`."]
lemma mul_inv_right {f : M β* N} (h : β y : S, is_unit (f y))
(y : S) (w z) : z = w * β(is_unit.lift_right (f.restrict S) h y)β»ΒΉ β z * f y = w :=
by rw [eq_comm, mul_inv_left h, mul_comm, eq_comm]
/-- Given a monoid hom `f : M β* N` and submonoid `S β M` such that
`f(S) β units N`, for all `xβ xβ : M` and `yβ, yβ β S`, we have
`f xβ * (f yβ)β»ΒΉ = f xβ * (f yβ)β»ΒΉ β f (xβ * yβ) = f (xβ * yβ)`. -/
@[to_additive "Given an add_monoid hom `f : M β+ N` and submonoid `S β M` such that `f(S) β add_units N`, for all `xβ xβ : M` and `yβ, yβ β S`, we have `f xβ - f yβ = f xβ - f yβ β f (xβ + yβ) = f (xβ + yβ)`."]
lemma mul_inv {f : M β* N} (h : β y : S, is_unit (f y)) {xβ xβ} {yβ yβ : S} :
f xβ * β(is_unit.lift_right (f.restrict S) h yβ)β»ΒΉ =
f xβ * β(is_unit.lift_right (f.restrict S) h yβ)β»ΒΉ β f (xβ * yβ) = f (xβ * yβ) :=
by rw [mul_inv_right h, mul_assoc, mul_comm _ (f yβ), βmul_assoc, mul_inv_left h, mul_comm xβ,
f.map_mul, f.map_mul]
/-- Given a monoid hom `f : M β* N` and submonoid `S β M` such that `f(S) β units N`, for all
`y, z β S`, we have `(f y)β»ΒΉ = (f z)β»ΒΉ β f y = f z`. -/
@[to_additive "Given an add_monoid hom `f : M β+ N` and submonoid `S β M` such that `f(S) β add_units N`, for all `y, z β S`, we have `- (f y) = - (f z) β f y = f z`."]
lemma inv_inj {f : M β* N} (hf : β y : S, is_unit (f y)) {y z}
(h : (is_unit.lift_right (f.restrict S) hf y)β»ΒΉ = (is_unit.lift_right (f.restrict S) hf z)β»ΒΉ) :
f y = f z :=
by rw [βmul_one (f y), eq_comm, βmul_inv_left hf y (f z) 1, h];
convert units.inv_mul _; exact (is_unit.coe_lift_right (f.restrict S) hf _).symm
/-- Given a monoid hom `f : M β* N` and submonoid `S β M` such that `f(S) β units N`, for all
`y β S`, `(f y)β»ΒΉ` is unique. -/
@[to_additive "Given an add_monoid hom `f : M β+ N` and submonoid `S β M` such that `f(S) β add_units N`, for all `y β S`, `- (f y)` is unique."]
lemma inv_unique {f : M β* N} (h : β y : S, is_unit (f y)) {y : S}
{z} (H : f y * z = 1) : β(is_unit.lift_right (f.restrict S) h y)β»ΒΉ = z :=
by rw [βone_mul β(_)β»ΒΉ, mul_inv_left, βH]
variables (f : localization_map S N)
/-- Given a localization map `f : M β* N`, the surjection sending `(x, y) : M Γ S` to
`f x * (f y)β»ΒΉ`. -/
@[to_additive "Given a localization map `f : M β+ N`, the surjection sending `(x, y) : M Γ S` to `f x - f y`."]
noncomputable def mk' (f : localization_map S N) (x : M) (y : S) : N :=
f.1 x * β(is_unit.lift_right (f.1.restrict S) f.2 y)β»ΒΉ
@[to_additive] lemma mk'_mul (xβ xβ : M) (yβ yβ : S) :
f.mk' (xβ * xβ) (yβ * yβ) = f.mk' xβ yβ * f.mk' xβ yβ :=
(mul_inv_left f.2 _ _ _).2 $ show _ = _ * (_ * _ * (_ * _)), by
rw [βmul_assoc, βmul_assoc, mul_inv_right f.2, mul_assoc, mul_assoc, mul_comm _ (f.1 xβ),
βmul_assoc, βmul_assoc, mul_inv_right f.2, submonoid.coe_mul, f.1.map_mul, f.1.map_mul];
ac_refl
@[to_additive] lemma mk'_one (x) : f.mk' x (1 : S) = f.1 x :=
by rw [mk', monoid_hom.map_one]; exact mul_one (f.1 x)
/-- Given a localization map `f : M β* N` for a submonoid `S β M`, for all `z : N` we have that if
`x : M, y β S` are such that `z * f y = f x`, then `f x * (f y)β»ΒΉ = z`. -/
@[simp, to_additive "Given a localization map `f : M β+ N` for a submonoid `S β M`, for all `z : N` we have that if `x : M, y β S` are such that `z + f y = f x`, then `f x - f y = z`."]
lemma mk'_sec (z : N) : f.mk' (sec S f.1 z).1 (sec S f.1 z).2 = z :=
show _ * _ = _, by rw [βsec_spec f.3, mul_inv_left, mul_comm]
@[to_additive] lemma mk'_surjective (z : N) : β x (y : S), f.mk' x y = z :=
β¨(sec S f.1 z).1, (sec S f.1 z).2, f.mk'_sec zβ©
@[to_additive] lemma mk'_spec (x) (y : S) :
f.mk' x y * f.1 y = f.1 x :=
show _ * _ * _ = _, by rw [mul_assoc, mul_comm _ (f.1 y), βmul_assoc, mul_inv_left, mul_comm]
@[to_additive] lemma mk'_spec' (x) (y : S) :
f.1 y * f.mk' x y = f.1 x :=
by rw [mul_comm, mk'_spec]
@[to_additive] theorem eq_mk'_iff_mul_eq {x} {y : S} {z} :
z = f.mk' x y β z * f.1 y = f.1 x :=
β¨Ξ» H, by rw [H, mk'_spec], Ξ» H, by erw [mul_inv_right, H]; reflβ©
@[to_additive] theorem mk'_eq_iff_eq_mul {x} {y : S} {z} :
f.mk' x y = z β f.1 x = z * f.1 y :=
by rw [eq_comm, eq_mk'_iff_mul_eq, eq_comm]
@[to_additive] lemma mk'_eq_iff_eq {xβ xβ} {yβ yβ : S} :
f.mk' xβ yβ = f.mk' xβ yβ β f.1 (xβ * yβ) = f.1 (xβ * yβ) :=
β¨Ξ» H, by rw [f.1.map_mul, f.mk'_eq_iff_eq_mul.1 H, mul_assoc,
mul_comm (f.1 _), βmul_assoc, mk'_spec, f.1.map_mul],
Ξ» H, by rw [mk'_eq_iff_eq_mul, mk', mul_assoc, mul_comm _ (f.1 yβ), βmul_assoc,
βf.1.map_mul, βH, f.1.map_mul, mul_inv_right f.2]β©
@[to_additive] protected lemma eq {aβ bβ} {aβ bβ : S} :
f.mk' aβ aβ = f.mk' bβ bβ β β c : S, aβ * bβ * c = bβ * aβ * c :=
f.mk'_eq_iff_eq.trans $ f.4 _ _
@[to_additive] protected lemma eq' {aβ bβ} {aβ bβ : S} :
f.mk' aβ aβ = f.mk' bβ bβ β localization.r S (aβ, aβ) (bβ, bβ) :=
by rw [f.eq, localization.r_iff_exists]
@[to_additive] lemma eq_iff_eq (g : localization_map S P) {x y} :
f.1 x = f.1 y β g.1 x = g.1 y :=
(f.4 _ _).trans (g.4 _ _).symm
@[to_additive] lemma mk'_eq_iff_mk'_eq (g : localization_map S P) {xβ xβ}
{yβ yβ : S} : f.mk' xβ yβ = f.mk' xβ yβ β g.mk' xβ yβ = g.mk' xβ yβ :=
f.eq'.trans g.eq'.symm
/-- Given a localization map `f : M β* N` for a submonoid `S β M`, for all `xβ : M` and `yβ β S`,
if `xβ : M, yβ β S` are such that `f xβ * (f yβ)β»ΒΉ * f yβ = f xβ`, then there exists `c β S`
such that `xβ * yβ * c = xβ * yβ * c`. -/
@[to_additive "Given a localization map `f : M β+ N` for a submonoid `S β M`, for all `xβ : M` and `yβ β S`, if `xβ : M, yβ β S` are such that `(f xβ - f yβ) + f yβ = f xβ`, then there exists `c β S` such that `xβ + yβ + c = xβ + yβ + c`."]
lemma exists_of_sec_mk' (x) (y : S) :
β c : S, x * (sec S f.1 $ f.mk' x y).2 * c = (sec S f.1 $ f.mk' x y).1 * y * c :=
(f.4 _ _).1 $ f.mk'_eq_iff_eq.1 $ (mk'_sec _ _).symm
@[to_additive] lemma mk'_eq_of_eq {aβ bβ : M} {aβ bβ : S} (H : bβ * aβ = aβ * bβ) :
f.mk' aβ aβ = f.mk' bβ bβ :=
f.mk'_eq_iff_eq.2 $ H βΈ rfl
@[simp, to_additive] lemma mk'_self (y : S) :
f.mk' (y : M) y = 1 :=
show _ * _ = _, by rw [mul_inv_left, mul_one]
@[simp, to_additive] lemma mk'_self' (x) (H : x β S) :
f.mk' x β¨x, Hβ© = 1 :=
by convert mk'_self _ _; refl
@[to_additive] lemma mul_mk'_eq_mk'_of_mul (xβ xβ) (y : S) :
f.1 xβ * f.mk' xβ y = f.mk' (xβ * xβ) y :=
by rw [βmk'_one, βmk'_mul, one_mul]
@[to_additive] lemma mk'_mul_eq_mk'_of_mul (xβ xβ) (y : S) :
f.mk' xβ y * f.1 xβ = f.mk' (xβ * xβ) y :=
by rw [mul_comm, mul_mk'_eq_mk'_of_mul]
@[to_additive] lemma mul_mk'_one_eq_mk' (x) (y : S) :
f.1 x * f.mk' 1 y = f.mk' x y :=
by rw [mul_mk'_eq_mk'_of_mul, mul_one]
@[to_additive] lemma mk'_mul_cancel_right (x : M) (y : S) :
f.mk' (x * y) y = f.1 x :=
by rw [βmul_mk'_one_eq_mk', f.1.map_mul, mul_assoc, mul_mk'_one_eq_mk', mk'_self, mul_one]
@[to_additive] lemma mk'_mul_cancel_left (x) (y : S) :
f.mk' ((y : M) * x) y = f.1 x :=
by rw [mul_comm, mk'_mul_cancel_right]
@[to_additive] lemma is_unit_comp (j : N β* P) (y : S) :
is_unit (j.comp f.1 y) :=
β¨units.map j $ is_unit.lift_right (f.1.restrict S) f.2 y,
show j _ = j _, from congr_arg j $ (is_unit.coe_lift_right (f.1.restrict S) f.2 _).symmβ©
variables {g : M β* P}
/-- Given a localization map `f : M β* N` for a submonoid `S β M` and a map of `comm_monoid`s
`g : M β* P` such that `g(S) β units P`, `f x = f y β g x = g y` for all `x y : M`. -/
@[to_additive "Given a localization map `f : M β+ N` for a submonoid `S β M` and a map of `add_comm_monoid`s `g : M β+ P` such that `g(S) β add_units P`, `f x = f y β g x = g y` for all `x y : M`."]
lemma eq_of_eq (hg : β y : S, is_unit (g y)) {x y} (h : f.1 x = f.1 y) :
g x = g y :=
begin
obtain β¨c, hcβ© := (f.4 _ _).1 h,
rw [βmul_one (g x), βis_unit.mul_lift_right_inv (g.restrict S) hg c],
show _ * (g c * _) = _,
rw [βmul_assoc, βg.map_mul, hc, mul_inv_left hg, g.map_mul, mul_comm],
end
/-- Given `comm_monoid`s `M, P`, localization maps `f : M β* N, k : P β* Q` for submonoids
`S, T` respectively, and `g : M β* P` such that `g(S) β T`, `f x = f y` implies
`k (g x) = k (g y)`. -/
@[to_additive "Given `add_comm_monoid`s `M, P`, localization maps `f : M β+ N, k : P β+ Q` for submonoids `S, T` respectively, and `g : M β+ P` such that `g(S) β T`, `f x = f y` implies `k (g x) = k (g y)`."]
lemma comp_eq_of_eq {T : submonoid P} {Q : Type*} [comm_monoid Q]
(hg : β y : S, g y β T) (k : localization_map T Q)
{x y} (h : f.1 x = f.1 y) : k.1 (g x) = k.1 (g y) :=
f.eq_of_eq (Ξ» y : S, show is_unit (k.1.comp g y), from k.2 β¨g y, hg yβ©) h
variables (hg : β y : S, is_unit (g y))
/-- Given a localization map `f : M β* N` for a submonoid `S β M` and a map of `comm_monoid`s
`g : M β* P` such that `g y` is invertible for all `y : S`, the homomorphism induced from
`N` to `P` sending `z : N` to `g x * (g y)β»ΒΉ`, where `(x, y) : M Γ S` are such that
`z = f x * (f y)β»ΒΉ`. -/
@[to_additive "Given a localization map `f : M β+ N` for a submonoid `S β M` and a map of `add_comm_monoid`s `g : M β+ P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` sending `z : N` to `g x - g y`, where `(x, y) : M Γ S` are such that `z = f x - f y`."]
noncomputable def lift : N β* P :=
{ to_fun := Ξ» z, g (sec S f.1 z).1 * β(is_unit.lift_right (g.restrict S) hg (sec S f.1 z).2)β»ΒΉ,
map_one' := by rw [mul_inv_left, mul_one]; exact f.eq_of_eq hg (by rw [βsec_spec f.3, one_mul]),
map_mul' := Ξ» x y, by rw [mul_inv_left hg, βmul_assoc, βmul_assoc, mul_inv_right hg,
mul_comm _ (g (sec S f.1 y).1), βmul_assoc, βmul_assoc, mul_inv_right hg];
repeat { rw βg.map_mul };
exact f.eq_of_eq hg (by repeat { rw f.1.map_mul <|> rw sec_spec' f.3 }; ac_refl) }
variables {S g}
/-- Given a localization map `f : M β* N` for a submonoid `S β M` and a map of `comm_monoid`s
`g : M β* P` such that `g y` is invertible for all `y : S`, the homomorphism induced from
`N` to `P` maps `f x * (f y)β»ΒΉ` to `g x * (g y)β»ΒΉ` for all `x : M, y β S`. -/
@[to_additive "Given a localization map `f : M β+ N` for a submonoid `S β M` and a map of `add_comm_monoid`s `g : M β+ P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` maps `f x - f y` to `g x - g y` for all `x : M, y β S`."]
lemma lift_mk' (x y) :
f.lift hg (f.mk' x y) = g x * β(is_unit.lift_right (g.restrict S) hg y)β»ΒΉ :=
(mul_inv hg).2 $ f.eq_of_eq hg $ by
rw [f.1.map_mul, f.1.map_mul, sec_spec' f.3, mul_assoc, f.mk'_spec, mul_comm]
/-- Given a localization map `f : M β* N` for a submonoid `S β M`, if a `comm_monoid` map
`g : M β* P` induces a map `f.lift hg : N β* P` then for all `z : N, v : P`, we have
`f.lift hg z = v β g x = g y * v`, where `x : M, y β S` are such that `z * f y = f x`. -/
@[to_additive "Given a localization map `f : M β+ N` for a submonoid `S β M`, if an `add_comm_monoid` map `g : M β+ P` induces a map `f.lift hg : N β+ P` then for all `z : N, v : P`, we have `f.lift hg z = v β g x = g y + v`, where `x : M, y β S` are such that `z + f y = f x`."]
lemma lift_spec (z v) :
f.lift hg z = v β g (sec S f.1 z).1 = g (sec S f.1 z).2 * v :=
mul_inv_left hg _ _ v
/-- Given a localization map `f : M β* N` for a submonoid `S β M`, if a `comm_monoid` map
`g : M β* P` induces a map `f.lift hg : N β* P` then for all `z : N, v w : P`, we have
`f.lift hg z * w = v β g x * w = g y * v`, where `x : M, y β S` are such that
`z * f y = f x`. -/
@[to_additive "Given a localization map `f : M β+ N` for a submonoid `S β M`, if an `add_comm_monoid` map `g : M β+ P` induces a map `f.lift hg : N β+ P` then for all `z : N, v w : P`, we have `f.lift hg z + w = v β g x + w = g y + v`, where `x : M, y β S` are such that `z + f y = f x`."]
lemma lift_spec_mul (z w v) :
f.lift hg z * w = v β g (sec S f.1 z).1 * w = g (sec S f.1 z).2 * v :=
begin
rw mul_comm,
show _ * (_ * _) = _ β _,
rw [βmul_assoc, mul_inv_left hg, mul_comm],
end
@[to_additive] lemma lift_mk'_spec (x v) (y : S) :
f.lift hg (f.mk' x y) = v β g x = g y * v :=
by rw f.lift_mk' hg; exact mul_inv_left hg _ _ _
/-- Given a localization map `f : M β* N` for a submonoid `S β M`, if a `comm_monoid` map
`g : M β* P` induces a map `f.lift hg : N β* P` then for all `z : N`, we have
`f.lift hg z * g y = g x`, where `x : M, y β S` are such that `z * f y = f x`. -/
@[to_additive "Given a localization map `f : M β+ N` for a submonoid `S β M`, if an `add_comm_monoid` map `g : M β+ P` induces a map `f.lift hg : N β+ P` then for all `z : N`, we have `f.lift hg z + g y = g x`, where `x : M, y β S` are such that `z + f y = f x`."]
lemma lift_mul_right (z) :
f.lift hg z * g (sec S f.1 z).2 = g (sec S f.1 z).1 :=
show _ * _ * _ = _, by erw [mul_assoc, is_unit.lift_right_inv_mul, mul_one]
/-- Given a localization map `f : M β* N` for a submonoid `S β M`, if a `comm_monoid` map
`g : M β* P` induces a map `f.lift hg : N β* P` then for all `z : N`, we have
`g y * f.lift hg z = g x`, where `x : M, y β S` are such that `z * f y = f x`. -/
@[to_additive "Given a localization map `f : M β+ N` for a submonoid `S β M`, if an `add_comm_monoid` map `g : M β+ P` induces a map `f.lift hg : N β+ P` then for all `z : N`, we have `g y + f.lift hg z = g x`, where `x : M, y β S` are such that `z + f y = f x`."]
lemma lift_mul_left (z) :
g (sec S f.1 z).2 * f.lift hg z = g (sec S f.1 z).1 :=
by rw [mul_comm, lift_mul_right]
@[simp, to_additive] lemma lift_eq (x : M) :
f.lift hg (f.1 x) = g x :=
by rw [lift_spec, βg.map_mul]; exact f.eq_of_eq hg (by rw [sec_spec' f.3, f.1.map_mul])
@[to_additive] lemma lift_eq_iff {x y : M Γ S} :
f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) β g (x.1 * y.2) = g (y.1 * x.2) :=
by rw [lift_mk', lift_mk', mul_inv hg]
@[simp, to_additive] lemma lift_comp : (f.lift hg).comp f.1 = g :=
by ext; exact f.lift_eq hg _
@[simp, to_additive] lemma lift_of_comp (j : N β* P) :
f.lift (f.is_unit_comp j) = j :=
begin
ext,
rw lift_spec,
show j _ = j _ * _,
erw [βj.map_mul, sec_spec' f.3],
end
@[to_additive] lemma epic_of_localization_map {j k : N β* P}
(h : β a, j.comp f.1 a = k.comp f.1 a) : j = k :=
begin
rw [βf.lift_of_comp j, βf.lift_of_comp k],
congr' 1,
ext,
exact h x,
end
@[to_additive] lemma lift_unique {j : N β* P}
(hj : β x, j (f.1 x) = g x) : f.lift hg = j :=
begin
ext,
rw [lift_spec, βhj, βhj, βj.map_mul],
apply congr_arg,
rw βsec_spec' f.3,
end
@[simp, to_additive] lemma lift_id (x) : f.lift f.2 x = x :=
monoid_hom.ext_iff.1 (f.lift_of_comp $ monoid_hom.id N) x
/-- Given two localization maps `f : M β* N, k : M β* P` for a submonoid `S β M`,
the hom from `P` to `N` induced by `f` is left inverse to the hom from `N` to `P`
induced by `k`. -/
@[simp, to_additive] lemma lift_left_inverse {k : localization_map S P} (z : N) :
k.lift f.2 (f.lift k.2 z) = z :=
begin
rw lift_spec,
cases f.3 z with x hx,
conv_rhs {congr, skip, rw f.eq_mk'_iff_mul_eq.2 hx},
rw [mk', βmul_assoc, mul_inv_right f.2, βf.1.map_mul, βf.1.map_mul],
apply k.eq_of_eq f.2,
rw [k.1.map_mul, k.1.map_mul, βsec_spec k.3, mul_assoc, lift_spec_mul],
repeat { rw βk.1.map_mul },
apply f.eq_of_eq k.2,
repeat { rw f.1.map_mul },
rw [sec_spec' f.3, βhx],
ac_refl,
end
@[to_additive] lemma lift_surjective_iff :
function.surjective (f.lift hg) β β v : P, β x : M Γ S, v * g x.2 = g x.1 :=
begin
split,
{ intros H v,
obtain β¨z, hzβ© := H v,
obtain β¨x, hxβ© := f.3 z,
use x,
rw [βhz, f.eq_mk'_iff_mul_eq.2 hx, lift_mk', mul_assoc, mul_comm _ (g βx.2)],
erw [is_unit.mul_lift_right_inv (g.restrict S) hg, mul_one] },
{ intros H v,
obtain β¨x, hxβ© := H v,
use f.mk' x.1 x.2,
rw [lift_mk', mul_inv_left hg, mul_comm, βhx] }
end
@[to_additive] lemma lift_injective_iff :
function.injective (f.lift hg) β β x y, f.1 x = f.1 y β g x = g y :=
begin
split,
{ intros H x y,
split,
{ exact f.eq_of_eq hg },
{ intro h,
rw [βf.lift_eq hg, βf.lift_eq hg] at h,
exact H h }},
{ intros H z w h,
obtain β¨x, hxβ© := f.3 z,
obtain β¨y, hyβ© := f.3 w,
rw [βf.mk'_sec z, βf.mk'_sec w],
exact (mul_inv f.2).2 ((H _ _).2 $ (mul_inv hg).1 h) }
end
variables {T : submonoid P} (hy : β y : S, g y β T) {Q : Type*} [comm_monoid Q]
(k : localization_map T Q)
/-- Given a `comm_monoid` homomorphism `g : M β* P` where for submonoids `S β M, T β P` we have
`g(S) β T`, the induced monoid homomorphism from the localization of `M` at `S` to the
localization of `P` at `T`: if `f : M β* N` and `k : P β* Q` are localization maps for `S` and
`T` respectively, we send `z : N` to `k (g x) * (k (g y))β»ΒΉ`, where `(x, y) : M Γ S` are such
that `z = f x * (f y)β»ΒΉ`. -/
@[to_additive "Given a `add_comm_monoid` homomorphism `g : M β+ P` where for submonoids `S β M, T β P` we have `g(S) β T`, the induced add_monoid homomorphism from the localization of `M` at `S` to the localization of `P` at `T`: if `f : M β+ N` and `k : P β+ Q` are localization maps for `S` and `T` respectively, we send `z : N` to `k (g x) - k (g y)`, where `(x, y) : M Γ S` are such that `z = f x - f y`."]
noncomputable def map : N β* Q :=
@lift _ _ _ _ _ _ _ f (k.1.comp g) $ Ξ» y, k.2 β¨g y, hy yβ©
variables {k}
@[to_additive] lemma map_eq (x) :
f.map hy k (f.1 x) = k.1 (g x) := f.lift_eq (Ξ» y, k.2 β¨g y, hy yβ©) x
@[simp, to_additive] lemma map_comp :
(f.map hy k).comp f.1 = k.1.comp g := f.lift_comp $ Ξ» y, k.2 β¨g y, hy yβ©
@[to_additive] lemma map_mk' (x) (y : S) :
f.map hy k (f.mk' x y) = k.mk' (g x) β¨g y, hy yβ© :=
begin
rw [map, lift_mk', mul_inv_left],
{ show k.1 (g x) = k.1 (g y) * _,
rw mul_mk'_eq_mk'_of_mul,
exact (k.mk'_mul_cancel_left (g x) β¨(g y), hy yβ©).symm },
end
/-- Given localization maps `f : M β* N, k : P β* Q` for submonoids `S, T` respectively, if a
`comm_monoid` homomorphism `g : M β* P` induces a `f.map hy k : N β* Q`, then for all `z : N`,
`u : Q`, we have `f.map hy k z = u β k (g x) = k (g y) * u` where `x : M, y β S` are such that
`z * f y = f x`. -/
@[to_additive "Given localization maps `f : M β+ N, k : P β+ Q` for submonoids `S, T` respectively, if an `add_comm_monoid` homomorphism `g : M β+ P` induces a `f.map hy k : N β+ Q`, then for all `z : N`, `u : Q`, we have `f.map hy k z = u β k (g x) = k (g y) + u` where `x : M, y β S` are such that `z + f y = f x`."]
lemma map_spec (z u) :
f.map hy k z = u β k.1 (g (sec S f.1 z).1) = k.1 (g (sec S f.1 z).2) * u :=
f.lift_spec (Ξ» y, k.2 β¨g y, hy yβ©) _ _
/-- Given localization maps `f : M β* N, k : P β* Q` for submonoids `S, T` respectively, if a
`comm_monoid` homomorphism `g : M β* P` induces a `f.map hy k : N β* Q`, then for all `z : N`,
we have `f.map hy k z * k (g y) = k (g x)` where `x : M, y β S` are such that
`z * f y = f x`. -/
@[to_additive "Given localization maps `f : M β+ N, k : P β+ Q` for submonoids `S, T` respectively, if an `add_comm_monoid` homomorphism `g : M β+ P` induces a `f.map hy k : N β+ Q`, then for all `z : N`, we have `f.map hy k z + k (g y) = k (g x)` where `x : M, y β S` are such that `z + f y = f x`."]
lemma map_mul_right (z) :
f.map hy k z * (k.1 (g (sec S f.1 z).2)) = k.1 (g (sec S f.1 z).1) :=
f.lift_mul_right (Ξ» y, k.2 β¨g y, hy yβ©) _
/-- Given localization maps `f : M β* N, k : P β* Q` for submonoids `S, T` respectively, if a
`comm_monoid` homomorphism `g : M β* P` induces a `f.map hy k : N β* Q`, then for all `z : N`,
we have `k (g y) * f.map hy k z = k (g x)` where `x : M, y β S` are such that
`z * f y = f x`. -/
@[to_additive "Given localization maps `f : M β+ N, k : P β+ Q` for submonoids `S, T` respectively, if an `add_comm_monoid` homomorphism `g : M β+ P` induces a `f.map hy k : N β+ Q`, then for all `z : N`, we have `k (g y) + f.map hy k z = k (g x)` where `x : M, y β S` are such that `z + f y = f x`."]
lemma map_mul_left (z) :
k.1 (g (sec S f.1 z).2) * f.map hy k z = k.1 (g (sec S f.1 z).1) :=
by rw [mul_comm, f.map_mul_right]
@[simp, to_additive] lemma map_id (z : N) :
f.map (Ξ» y, show monoid_hom.id M y β S, from y.2) f z = z :=
f.lift_id z
/-- If `comm_monoid` homs `g : M β* P, l : P β* A` induce maps of localizations, the composition
of the induced maps equals the map of localizations induced by `l β g`. -/
@[to_additive "If `add_comm_monoid` homs `g : M β+ P, l : P β+ A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l β g`."]
lemma map_comp_map {A : Type*} [comm_monoid A] {U : submonoid A} {R} [comm_monoid R]
(j : localization_map U R) {l : P β* A} (hl : β w : T, l w β U) :
(k.map hl j).comp (f.map hy k) = f.map (Ξ» x, show l.comp g x β U, from hl β¨g x, hy xβ©) j :=
begin
ext z,
show j.1 _ * _ = j.1 (l _) * _,
{ rw [mul_inv_left, βmul_assoc, mul_inv_right],
show j.1 _ * j.1 (l (g _)) = j.1 (l _) * _,
rw [βj.1.map_mul, βj.1.map_mul, βl.map_mul, βl.map_mul],
exact k.comp_eq_of_eq hl j
(by rw [k.1.map_mul, k.1.map_mul, sec_spec' k.3, mul_assoc, map_mul_right]) },
end
/-- If `comm_monoid` homs `g : M β* P, l : P β* A` induce maps of localizations, the composition
of the induced maps equals the map of localizations induced by `l β g`. -/
@[to_additive "If `add_comm_monoid` homs `g : M β+ P, l : P β+ A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l β g`."]
lemma map_map {A : Type*} [comm_monoid A] {U : submonoid A} {R} [comm_monoid R]
(j : localization_map U R) {l : P β* A} (hl : β w : T, l w β U) (x) :
k.map hl j (f.map hy k x) = f.map (Ξ» x, show l.comp g x β U, from hl β¨g x, hy xβ©) j x :=
by rw βf.map_comp_map hy j hl; refl
variables {g}
/-- If `f : M β* N` and `k : M β* R` are localization maps for a submonoid `S`, we get an
isomorphism of `N` and `R`. -/
@[to_additive "If `f : M β+ N` and `k : M β+ R` are localization maps for a submonoid `S`, we get an isomorphism of `N` and `R`."]
noncomputable def mul_equiv_of_localizations
(k : localization_map S P) : N β* P :=
β¨f.lift k.2, k.lift f.2, f.lift_left_inverse, k.lift_left_inverse, monoid_hom.map_mul _β©
@[to_additive, simp] lemma mul_equiv_of_localizations_apply
{k : localization_map S P} {x} : f.mul_equiv_of_localizations k x = f.lift k.2 x := rfl
@[to_additive, simp] lemma mul_equiv_of_localizations_symm_apply
{k : localization_map S P} {x} : (f.mul_equiv_of_localizations k).symm x = k.lift f.2 x := rfl
/-- If `f : M β* N` is a localization map for a submonoid `S` and `k : N β* P` is an isomorphism
of `comm_monoid`s, `k β f` is a localization map for `M` at `S`. -/
@[to_additive "If `f : M β+ N` is a localization map for a submonoid `S` and `k : N β+ P` is an isomorphism of `add_comm_monoid`s, `k β f` is a localization map for `M` at `S`."]
def to_mul_equiv (k : N β* P) :
localization_map S P :=
{ to_fun := k.to_monoid_hom.comp f.1,
map_units := Ξ» y, is_unit_comp f k.to_monoid_hom y,
surj := Ξ» v, let β¨z, hzβ© := k.to_equiv.surjective v in
let β¨x, hxβ© := f.3 z in β¨x, show v * k _ = k _, by rw [βhx, k.map_mul, βhz]; reflβ©,
eq_iff_exists := Ξ» x y, (k.to_equiv.apply_eq_iff_eq _ _).trans $ f.4 _ _ }
@[to_additive, simp] lemma to_mul_equiv_apply {k : N β* P} (x) :
(f.to_mul_equiv k).1 x = k (f.1 x) := rfl
@[to_additive, simp] lemma to_mul_equiv_eq {k : N β* P} :
(f.to_mul_equiv k).1 = k.to_monoid_hom.comp f.1 := rfl
@[to_additive] lemma symm_to_mul_equiv_apply {k : N β* P} (x) :
k.symm ((f.to_mul_equiv k).1 x) = f.1 x := k.symm_apply_apply (f.1 x)
@[to_additive] lemma comp_mul_equiv_symm_map_apply {k : P β* N} (x) :
k ((f.to_mul_equiv k.symm).1 x) = f.1 x := k.apply_symm_apply (f.1 x)
@[to_additive] lemma to_mul_equiv_eq_iff_eq {k : N β* P} {x y} :
(f.to_mul_equiv k).1 x = y β f.1 x = k.symm y :=
k.to_equiv.eq_symm_apply.symm
@[to_additive] lemma mul_equiv_of_to_mul_equiv (k : localization_map S P) :
f.to_mul_equiv (f.mul_equiv_of_localizations k) = k :=
to_fun_inj $ f.lift_comp k.2
@[to_additive] lemma mul_equiv_of_to_mul_equiv_apply {k : localization_map S P} {x} :
(f.to_mul_equiv (f.mul_equiv_of_localizations k)).1 x = k.1 x :=
ext_iff.1 (f.mul_equiv_of_to_mul_equiv k) x
@[to_additive] lemma to_mul_equiv_of_mul_equiv (k : N β* P) :
f.mul_equiv_of_localizations (f.to_mul_equiv k) = k :=
mul_equiv.ext $ monoid_hom.ext_iff.1 $ f.lift_of_comp k.to_monoid_hom
@[to_additive] lemma to_mul_equiv_of_mul_equiv_apply {k : N β* P} (x) :
f.mul_equiv_of_localizations (f.to_mul_equiv k) x = k x :=
by rw to_mul_equiv_of_mul_equiv
@[simp, to_additive] lemma to_mul_equiv_id :
f.to_mul_equiv (mul_equiv.refl N) = f :=
by ext; refl
@[to_additive] lemma to_mul_equiv_comp {k : N β* P} {j : P β* Q} :
(f.to_mul_equiv (k.trans j)).1 = j.to_monoid_hom.comp (f.to_mul_equiv k).1 :=
by ext; refl
/-- Given `comm_monoid`s `M, P` and submonoids `S β M, T β P`, if `f : M β* N` is a localization
map for `S` and `k : P β* M` is an isomorphism of `comm_monoid`s such that `k(T) = S`, `f β k`
is a localization map for `T`. -/
@[to_additive "Given `comm_monoid`s `M, P` and submonoids `S β M, T β P`, if `f : M β* N` is a localization map for `S` and `k : P β* M` is an isomorphism of `comm_monoid`s such that `k(T) = S`, `f β k` is a localization map for `T`."]
def of_mul_equiv {k : P β* M} (H : T.map k.to_monoid_hom = S) :
localization_map T N :=
let H' : S.comap k.to_monoid_hom = T :=
H βΈ (submonoid.ext' $ T.1.preimage_image_eq k.to_equiv.injective) in
{ to_fun := f.1.comp k.to_monoid_hom,
map_units := Ξ» y, let β¨z, hzβ© := f.2 β¨k y, H βΈ set.mem_image_of_mem k y.2β© in β¨z, hzβ©,
surj := Ξ» z, let β¨x, hxβ© := f.3 z in let β¨v, hvβ© := k.to_equiv.surjective x.1 in
let β¨w, hwβ© := k.to_equiv.surjective x.2 in β¨(v, β¨w, H' βΈ show k w β S, from hw.symm βΈ x.2.2β©),
show z * f.1 (k.to_equiv w) = f.1 (k.to_equiv v), by erw [hv, hw, hx]; reflβ©,
eq_iff_exists := Ξ» x y, show f.1 _ = f.1 _ β _, by erw f.4;
exact β¨Ξ» β¨c, hcβ©, let β¨d, hdβ© := k.to_equiv.surjective c in
β¨β¨d, H' βΈ show k d β S, from hd.symm βΈ c.2β©, by erw [βhd, βk.map_mul, βk.map_mul] at hc;
exact k.to_equiv.injective hcβ©, Ξ» β¨c, hcβ©, β¨β¨k c, H βΈ set.mem_image_of_mem k c.2β©,
by erw βk.map_mul; rw [hc, k.map_mul]; reflβ©β© }
@[to_additive, simp] lemma of_mul_equiv_apply {k : P β* M} (H : T.map k.to_monoid_hom = S) (x) :
(f.of_mul_equiv H).1 x = f.1 (k x) := rfl
@[to_additive, simp] lemma of_mul_equiv_eq {k : P β* M} (H : T.map k.to_monoid_hom = S) :
(f.of_mul_equiv H).1 = f.1.comp k.to_monoid_hom := rfl
@[to_additive] lemma symm_of_mul_equiv_apply {k : P β* M}
(H : T.map k.to_monoid_hom = S) (x) :
(f.of_mul_equiv H).1 (k.symm x) = f.1 x := congr_arg f.1 $ k.apply_symm_apply x
@[to_additive, simp] lemma comp_mul_equiv_symm_comap_apply {k : M β* P}
(H : T.map k.symm.to_monoid_hom = S) (x) :
(f.of_mul_equiv H).1 (k x) = f.1 x := congr_arg f.1 $ k.symm_apply_apply x
/-- A special case of `f β id = f`, `f` a localization map. -/
@[simp, to_additive "A special case of `f β id = f`, `f` a localization map."]
lemma of_mul_equiv_id :
f.of_mul_equiv (show S.map (mul_equiv.refl M).to_monoid_hom = S, from
submonoid.ext $ Ξ» x, β¨Ξ» β¨y, hy, hβ©, h βΈ hy, Ξ» h, β¨x, h, rflβ©β©) = f :=
by ext; refl
/-- Given localization maps `f : M β* N, k : P β* U` for submonoids `S, T` respectively, an
isomorphism `j : M β* P` such that `j(S) = T` induces an isomorphism of localizations
`N β* U`. -/
@[to_additive "Given localization maps `f : M β+ N, k : P β+ U` for submonoids `S, T` respectively, an isomorphism `j : M β+ P` such that `j(S) = T` induces an isomorphism of localizations `N β+ U`."]
noncomputable def mul_equiv_of_mul_equiv
(k : localization_map T Q) {j : M β* P} (H : S.map j.to_monoid_hom = T) :
N β* Q :=
f.mul_equiv_of_localizations $ k.of_mul_equiv H
@[to_additive, simp] lemma mul_equiv_of_mul_equiv_eq_map_apply
{k : localization_map T Q} {j : M β* P} (H : S.map j.to_monoid_hom = T) (x) :
f.mul_equiv_of_mul_equiv k H x =
f.map (Ξ» y : S, show j.to_monoid_hom y β T, from H βΈ set.mem_image_of_mem j y.2) k x := rfl
@[to_additive, simp] lemma mul_equiv_of_mul_equiv_eq_map
{k : localization_map T Q} {j : M β* P} (H : S.map j.to_monoid_hom = T) :
(f.mul_equiv_of_mul_equiv k H).to_monoid_hom =
f.map (Ξ» y : S, show j.to_monoid_hom y β T, from H βΈ set.mem_image_of_mem j y.2) k := rfl
@[to_additive, simp] lemma mul_equiv_of_mul_equiv_eq {k : localization_map T Q}
{j : M β* P} (H : S.map j.to_monoid_hom = T) (x) :
f.mul_equiv_of_mul_equiv k H (f.1 x) = k.1 (j x) :=
f.map_eq (Ξ» y : S, H βΈ set.mem_image_of_mem j y.2) _
@[to_additive] lemma mul_equiv_of_mul_equiv_mk' {k : localization_map T Q}
{j : M β* P} (H : S.map j.to_monoid_hom = T) (x y) :
f.mul_equiv_of_mul_equiv k H (f.mk' x y) = k.mk' (j x) β¨j y, H βΈ set.mem_image_of_mem j y.2β© :=
f.map_mk' (Ξ» y : S, H βΈ set.mem_image_of_mem j y.2) _ _
@[to_additive, simp] lemma to_mul_equiv_of_mul_equiv_of_mul_equiv_apply
{k : localization_map T Q} {j : M β* P} (H : S.map j.to_monoid_hom = T) (x) :
(f.to_mul_equiv (f.mul_equiv_of_mul_equiv k H)).1 x = k.1 (j x) :=
ext_iff.1 (f.mul_equiv_of_to_mul_equiv (k.of_mul_equiv H)) x
@[to_additive, simp] lemma to_mul_equiv_of_mul_equiv_of_mul_equiv
{k : localization_map T Q} {j : M β* P} (H : S.map j.to_monoid_hom = T) :
(f.to_mul_equiv (f.mul_equiv_of_mul_equiv k H)).1 = k.1.comp j.to_monoid_hom :=
monoid_hom.ext $ f.to_mul_equiv_of_mul_equiv_of_mul_equiv_apply H
end localization_map
end submonoid |
ec6966cc37630b008bcc45e98bfb23d85f0f7bce | 94e33a31faa76775069b071adea97e86e218a8ee | /src/tactic/core.lean | d827f4063edc3e5e39791f97238844d9ef1e3fe9 | [
"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 | 99,434 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek
-/
import control.basic
import data.dlist.basic
import meta.expr
import system.io
import tactic.binder_matching
import tactic.interactive_expr
import tactic.lean_core_docs
import tactic.project_dir
universe u
attribute [derive [has_reflect, decidable_eq]] tactic.transparency
-- Rather than import data.prod.lex here, we can get away with defining the order by hand.
instance : has_lt pos :=
{ lt := Ξ» x y, x.line < y.line β¨ x.line = y.line β§ x.column < y.column }
namespace tactic
/-- Reflexivity conversion: given `e` returns `(e, β’ e = e)` -/
meta def refl_conv (e : expr) : tactic (expr Γ expr) :=
do p β mk_eq_refl e, return (e, p)
/-- Turns a conversion tactic into one that always succeeds, where failure is interpreted as a
proof by reflexivity. -/
meta def or_refl_conv (tac : expr β tactic (expr Γ expr))
(e : expr) : tactic (expr Γ expr) := tac e <|> refl_conv e
/-- Transitivity conversion: given two conversions (which take an
expression `e` and returns `(e', β’ e = e')`), produces another
conversion that combines them with transitivity, treating failures
as reflexivity conversions. -/
meta def trans_conv (tβ tβ : expr β tactic (expr Γ expr)) (e : expr) :
tactic (expr Γ expr) :=
(do (eβ, pβ) β tβ e,
(do (eβ, pβ) β tβ eβ,
p β mk_eq_trans pβ pβ, return (eβ, p)) <|>
return (eβ, pβ)) <|> tβ e
end tactic
open tactic
namespace expr
/-- Given an expr `Ξ±` representing a type with numeral structure,
`of_nat Ξ± n` creates the `Ξ±`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (Ξ± : expr) : β β tactic expr :=
nat.binary_rec
(tactic.mk_mapp ``has_zero.zero [some Ξ±, none])
(Ξ» b n tac, if n = 0 then mk_mapp ``has_one.one [some Ξ±, none] else
do e β tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])
/-- Given an expr `Ξ±` representing a type with numeral structure,
`of_int Ξ± n` creates the `Ξ±`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (Ξ± : expr) : β€ β tactic expr
| (n : β) := expr.of_nat Ξ± n
| -[1+ n] := do
e β expr.of_nat Ξ± (n+1),
tactic.mk_app ``has_neg.neg [e]
/-- Convert a list of expressions to an expression denoting the list of those expressions. -/
meta def of_list (Ξ± : expr) : list expr β tactic expr
| [] := tactic.mk_app ``list.nil [Ξ±]
| (x :: xs) := do
exs β of_list xs,
tactic.mk_app ``list.cons [Ξ±, x, exs]
/-- Generates an expression of the form `β(args), inner`. `args` is assumed to be a list of local
constants. When possible, `p β§ q` is used instead of `β(_ : p), q`. -/
meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=
args.mfoldr (Ξ»arg i:expr, do
t β infer_type arg,
sort l β infer_type t,
return $ if arg.occurs i β¨ l β level.zero
then (const `Exists [l] : expr) t (i.lambdas [arg])
else (const `and [] : expr) t i)
inner
/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/
meta def traverse {m : Type β Type u} [applicative m]
{elab elab' : bool} (f : expr elab β m (expr elab')) :
expr elab β m (expr elab')
| (var v) := pure $ var v
| (sort l) := pure $ sort l
| (const n ls) := pure $ const n ls
| (mvar n n' e) := mvar n n' <$> f e
| (local_const n n' bi e) := local_const n n' bi <$> f e
| (app eβ eβ) := app <$> f eβ <*> f eβ
| (lam n bi eβ eβ) := lam n bi <$> f eβ <*> f eβ
| (pi n bi eβ eβ) := pi n bi <$> f eβ <*> f eβ
| (elet n eβ eβ eβ) := elet n <$> f eβ <*> f eβ <*> f eβ
| (macro mac es) := macro mac <$> list.traverse f es
/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,
with initial value `a`. -/
meta def mfoldl {Ξ± : Type} {m} [monad m] (f : Ξ± β expr β m Ξ±) : Ξ± β expr β m Ξ±
| x e := prod.snd <$> (state_t.run (e.traverse $ Ξ» e',
(get >>= monad_lift β flip f e' >>= put) $> e') x : m _)
/-- `kreplace e old new` replaces all occurrences of the expression `old` in `e`
with `new`. The occurrences of `old` in `e` are determined using keyed matching
with transparency `md`; see `kabstract` for details. If `unify` is true,
we may assign metavariables in `e` as we match subterms of `e` against `old`. -/
meta def kreplace (e old new : expr) (md := semireducible) (unify := tt)
: tactic expr := do
e β kabstract e old md unify,
pure $ e.instantiate_var new
end expr
namespace name
/--
`pre.contains_sorry_aux nm` checks whether `sorry` occurs in the value of the declaration `nm`
or (recusively) in any declarations occurring in the value of `nm` with namespace `pre`.
Auxiliary function for `name.contains_sorry`. -/
meta def contains_sorry_aux (pre : name) : name β tactic bool | nm := do
env β get_env,
decl β get_decl nm,
ff β return decl.value.contains_sorry | return tt,
(decl.value.list_names_with_prefix pre).mfold ff $
Ξ» n b, if b then return tt else n.contains_sorry_aux
/-- `nm.contains_sorry` checks whether `sorry` occurs in the value of the declaration `nm` or
in any declarations `nm._proof_i` (or to be more precise: any declaration in namespace `nm`).
See also `expr.contains_sorry`. -/
meta def contains_sorry (nm : name) : tactic bool := nm.contains_sorry_aux nm
end name
namespace interaction_monad
open result
variables {Ο : Type} {Ξ± : Type u}
/-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.read` in core.
meta def get_state : interaction_monad Ο Ο :=
Ξ» state, success state state
/-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.write` in core.
meta def set_state (state : Ο) : interaction_monad Ο unit :=
Ξ» _, success () state
/--
`run_with_state state tac` applies `tac` to the given state `state` and returns the result,
subsequently restoring the original state.
If `tac` fails, then `run_with_state` does too.
-/
meta def run_with_state (state : Ο) (tac : interaction_monad Ο Ξ±) : interaction_monad Ο Ξ± :=
Ξ» s, match tac state with
| success val _ := success val s
| exception fn pos _ := exception fn pos s
end
end interaction_monad
namespace format
/-- `join' [a,b,c]` produces the format object `abc`.
It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/
meta def join' (xs : list format) : format :=
xs.foldl compose nil
/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,
where `.` represents `format.join`. -/
meta def intercalate (x : format) : list format β format :=
join' β list.intersperse x
/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`
the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`
each line break is decided independently -/
meta def soft_break : format :=
group line
/-- Format a list as a comma separated list, without any brackets. -/
meta def comma_separated {Ξ± : Type*} [has_to_format Ξ±] : list Ξ± β format
| [] := nil
| xs := group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt)
end format
section format
open format
/-- format a `list` by separating elements with `soft_break` instead of `line` -/
meta def list.to_line_wrap_format {Ξ± : Type u} [has_to_format Ξ±] (l : list Ξ±) : format :=
bracket "[" "]" (comma_separated l)
end format
namespace tactic
open function
export interaction_monad (get_state set_state run_with_state)
/-- Private work function for `add_local_consts_as_local_hyps`: given
`mappings : list (expr Γ expr)` corresponding to pairs `(var, hyp)` of variables and the local
hypothesis created as a result and `(var :: rest) : list expr` of more local variables we
examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the
back of the queue and recurse. If it does not, then we perform replacements inside the type of
`var` using the `mappings`, create a new associate local hypothesis, add this to the list of
mappings, and recurse. We are done once all local hypotheses have been processed.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
private meta def add_local_consts_as_local_hyps_aux
: list (expr Γ expr) β list expr β tactic (list (expr Γ expr))
| mappings [] := return mappings
| mappings (var :: rest) := do
/- Determine if `var` contains any local variables in the lift `rest`. -/
let is_dependent := var.local_type.fold ff $ Ξ» e n b,
if b then b else e β rest,
/- If so, then skip it---add it to the end of the variable queue. -/
if is_dependent then
add_local_consts_as_local_hyps_aux mappings (rest ++ [var])
else do
/- Otherwise, replace all of the local constants referenced by the type of `var` with the
respective new corresponding local hypotheses as recorded in the list `mappings`. -/
let new_type := var.local_type.replace_subexprs mappings,
/- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/
hyp β assertv var.local_pp_name new_type (var.local_const_set_type new_type),
/- Process the next variable in the queue, with the mapping list updated to include the local
hypothesis which we just created. -/
add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest
/-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the
tactic state. This is harder than it sounds, since the list of local constants which we have
been passed can have dependencies between their types.
For example, suppose we have two local constants `n : β` and `h : n = 3`. Then we cannot blindly
add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as
a new local hypothesis, not the old local constant `n` with the same name. Of course, these
dependencies can be nested arbitrarily deep.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr Γ expr)) :=
/- The `list.reverse` below is a performance optimisation since the list of available variables
reported by the system is often mostly the reverse of the order in which they are dependent. -/
add_local_consts_as_local_hyps_aux [] vars.reverse.dedup
private meta def get_expl_pi_arity_aux : expr β tactic nat
| (expr.pi n bi d b) :=
do m β mk_fresh_name,
let l := expr.local_const m n bi d,
new_b β whnf (expr.instantiate_var b l),
r β get_expl_pi_arity_aux new_b,
if bi = binder_info.default then
return (r + 1)
else
return r
| e := return 0
/-- Compute the arity of explicit arguments of `type`. -/
meta def get_expl_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_expl_pi_arity_aux
/-- Compute the arity of explicit arguments of `fn`'s type. -/
meta def get_expl_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_expl_pi_arity
private meta def get_app_fn_args_whnf_aux (md : transparency)
(unfold_ginductive : bool) : list expr β expr β tactic (expr Γ list expr) :=
Ξ» args e, do
e β whnf e md unfold_ginductive,
match e with
| (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t
| _ := pure (e, args)
end
/--
For `e = f xβ ... xβ`, `get_app_fn_args_whnf e` returns `(f, [xβ, ..., xβ])`. `e`
is normalised as necessary; for example:
```
get_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)])
```
The returned expression is in whnf, but the arguments are generally not.
-/
meta def get_app_fn_args_whnf (e : expr) (md := semireducible)
(unfold_ginductive := tt) : tactic (expr Γ list expr) :=
get_app_fn_args_whnf_aux md unfold_ginductive [] e
/--
`get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is
normalised as necessary (with transparency `md`). `unfold_ginductive` controls
whether constructors of generalised inductive types are unfolded. The returned
expression is in whnf.
-/
meta def get_app_fn_whnf : expr β opt_param _ semireducible β opt_param _ tt β tactic expr
| e md unfold_ginductive := do
e β whnf e md unfold_ginductive,
match e with
| (expr.app f _) := get_app_fn_whnf f md unfold_ginductive
| _ := pure e
end
/--
`get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C xβ ... xβ`,
where `C` is a constant, after normalisation with transparency `md`. If so, the
name of `C` is returned. Otherwise the tactic fails. `unfold_ginductive`
controls whether constructors of generalised inductive types are unfolded.
-/
meta def get_app_fn_const_whnf (e : expr) (md := semireducible)
(unfold_ginductive := tt) : tactic name := do
f β get_app_fn_whnf e md unfold_ginductive,
match f with
| (expr.const n _) := pure n
| _ := fail format!
"expected a constant (possibly applied to some arguments), but got:\n{e}"
end
/--
`get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e`
is normalised as necessary (with transparency `md`). `unfold_ginductive`
controls whether constructors of generalised inductive types are unfolded. The
returned expressions are not necessarily in whnf.
-/
meta def get_app_args_whnf (e : expr) (md := semireducible)
(unfold_ginductive := tt) : tactic (list expr) :=
prod.snd <$> get_app_fn_args_whnf e md unfold_ginductive
/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with pi binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``pis [a, b] `(f a b)`` will return the expression
`Ξ (a : Ta) (b : Tb), f a b`. -/
meta def pis : list expr β expr β tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t β infer_type e,
f' β pis es f,
pure $ expr.pi pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with lambda binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``lambdas [a, b] `(f a b)`` will return the expression
`Ξ» (a : Ta) (b : Tb), f a b`. -/
meta def lambdas : list expr β expr β tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t β infer_type e,
f' β lambdas es f,
pure $ expr.lam pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- Given an expression `f` (likely a binary operation) and a further expression `x`, calling
`list_binary_operands f x` breaks `x` apart into successions of applications of `f` until this can
no longer be done and returns a list of the leaves of the process.
This matches `f` up to semireducible unification. In particular, it will match applications of the
same polymorphic function with different type-class arguments.
E.g., if `i1` and `i2` are both instances of `has_add T` and
`e := has_add.add T i1 x (has_add.add T i2 y z)`, then ``list_binary_operands `((+) : T β T β T) e``
returns `[x, y, z]`.
For example:
```lean
#eval list_binary_operands `(@has_add.add β _) `(3 + (4 * 5 + 6) + 7 / 3) >>= tactic.trace
-- [3, 4 * 5, 6, 7 / 3]
#eval list_binary_operands `(@list.append β) `([1, 2] ++ [3, 4] ++ (1 :: [])) >>= tactic.trace
-- [[1, 2], [3, 4], [1]]
```
-/
meta def list_binary_operands (f : expr) : expr β tactic (list expr)
| x@(expr.app (expr.app g a) b) := do
some _ β try_core (unify f g) | pure [x],
as β list_binary_operands a,
bs β list_binary_operands b,
pure (as ++ bs)
| a := pure [a]
-- TODO: move to `declaration` namespace in `meta/expr.lean`
/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named
`ls`, type `t`, and body `e`. -/
meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=
declaration.thm n ls t (task.pure e)
/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this
to the environment as a theorem with name `n` and universe parameters `ls`. -/
meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) :
tactic expr :=
do ((), body) β solve_aux type tac,
body β instantiate_mvars body,
add_decl $ mk_theorem n ls type body,
return $ expr.const n $ ls.map level.param
/-- `eval_expr' Ξ± e` attempts to evaluate the expression `e` in the type `Ξ±`.
This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare
situations the latter will fail but the former will succeed. -/
meta def eval_expr' (Ξ± : Type*) [_inst_1 : reflected _ Ξ±] (e : expr) : tactic Ξ± :=
mk_app ``id [e] >>= eval_expr Ξ±
/-- `mk_fresh_name` returns identifiers starting with underscores,
which are not legal when emitted by tactic programs. `mk_user_fresh_name`
turns the useful source of random names provided by `mk_fresh_name` into
names which are usable by tactic programs.
The returned name has four components which are all strings. -/
meta def mk_user_fresh_name : tactic name :=
do nm β mk_fresh_name,
return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__
/-- `has_attribute' attr_name decl_name` checks
whether `decl_name` exists and has attribute `attr_name`. -/
meta def has_attribute' (attr_name decl_name : name) : tactic bool :=
succeeds (has_attribute attr_name decl_name)
/-- Checks whether the name is a simp lemma -/
meta def is_simp_lemma : name β tactic bool :=
has_attribute' `simp
/-- Checks whether the name is an instance. -/
meta def is_instance : name β tactic bool :=
has_attribute' `instance
/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.
Covers all declarations from the current file. -/
meta def local_decls : tactic (name_map declaration) :=
do e β tactic.get_env,
let xs := e.fold native.mk_rb_map
(Ξ» d s, if environment.in_current_file e d.to_name
then s.insert d.to_name d else s),
pure xs
/-- `get_decls_from` returns a dictionary mapping names to their
corresponding declarations. Covers all declarations the files listed
in `fs`, with the current file listed as `none`.
The path of the file names is expected to be relative to
the root of the project (i.e. the location of `leanpkg.toml` when it
is present); e.g. `"src/tactic/core.lean"`
Possible issue: `get_decls_from` uses `get_cwd`, the current working
directory, which may not always point at the root of the project.
It would work better if it searched for the root directory or,
better yet, if Lean exposed its path information.
-/
meta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) :=
do root β unsafe_run_io $ io.env.get_cwd,
let fs := fs.map (option.map $ Ξ» path, root ++ "/" ++ path),
err β unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot β io.fs.file_exists,
guard (err = []) <|> fail format!"File not found: {err}",
e β tactic.get_env,
let xs := e.fold native.mk_rb_map
(Ξ» d s,
let source := e.decl_olean d.to_name in
if source β fs β§ (source = none β e.in_current_file d.to_name)
then s.insert d.to_name d else s),
pure xs
/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/
meta def get_unused_decl_name_aux (e : environment) (nm : name) : β β tactic name | n :=
let nm' := nm.append_suffix ("_" ++ to_string n) in
if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm'
/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it
returns that, otherwise it tries `nm_2`, `nm_3`, ... -/
meta def get_unused_decl_name (nm : name) : tactic name :=
get_env >>= Ξ» e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm
/--
Returns a pair `(e, t)`, where `e β mk_const d.to_name`, and `t = d.type`
but with universe params updated to match the fresh universe metavariables in `e`.
This should have the same effect as just
```lean
do e β mk_const d.to_name,
t β infer_type e,
return (e, t)
```
but is hopefully faster.
-/
meta def decl_mk_const (d : declaration) : tactic (expr Γ expr) :=
do subst β d.univ_params.mmap $ Ξ» u, prod.mk u <$> mk_meta_univ,
let e : expr := expr.const d.to_name (prod.snd <$> subst),
return (e, d.type.instantiate_univ_params subst)
/--
Replace every universe metavariable in an expression with a universe parameter.
(This is useful when making new declarations.)
-/
meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr :=
do
e.list_univ_meta_vars.enum.mmap (Ξ» n, do
let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)),
unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))),
instantiate_mvars e
/-- `mk_local n` creates a dummy local variable with name `n`.
The type of this local constant is a constant with name `n`, so it is very unlikely to be
a meaningful expression. -/
meta def mk_local (n : name) : expr :=
expr.local_const n n binder_info.default (expr.const n [])
/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,
`y : ty x` and `z : tz x y`, creates an expression of sigma type:
`β¨x,y,zβ© : Ξ£' (x : tx) (y : ty x), tz x y`.
-/
meta def mk_psigma : list expr β tactic expr
| [] := mk_const ``punit
| [x@(expr.local_const _ _ _ _)] := pure x
| (x@(expr.local_const _ _ _ _) :: xs) :=
do y β mk_psigma xs,
Ξ± β infer_type x,
Ξ² β infer_type y,
t β lambdas [x] Ξ² >>= instantiate_mvars,
r β mk_mapp ``psigma.mk [Ξ±,t],
pure $ r x y
| _ := fail "mk_psigma expects a list of local constants"
/--
Update the type of a local constant or metavariable. For local constants and
metavariables obtained via, for example, `tactic.get_local`, the type stored in
the expression is not necessarily the same as the type returned by `infer_type`.
This tactic, given a local constant or metavariable, updates the stored type to
match the output of `infer_type`. If the input is not a local constant or
metavariable, `update_type` does nothing.
-/
meta def update_type : expr β tactic expr
| e@(expr.local_const ppname uname binfo _) :=
expr.local_const ppname uname binfo <$> infer_type e
| e@(expr.mvar ppname uname _) :=
expr.mvar ppname uname <$> infer_type e
| e := pure e
/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`
times and uses `ns` to name the resulting variables. Returns a triple: list of new variables,
remaining term and unused variable names.
-/
meta def elim_gen_prod : nat β expr β list expr β list name β tactic (list expr Γ expr Γ list name)
| 0 e hs ns := return (hs.reverse, e, ns)
| (n + 1) e hs ns := do
t β infer_type e,
if t.is_app_of `eq then return (hs.reverse, e, ns)
else do
[(_, [h, h'], _)] β cases_core e (ns.take 1),
elim_gen_prod n h' (h :: hs) (ns.drop 1)
private meta def elim_gen_sum_aux : nat β expr β list expr β tactic (list expr Γ expr)
| 0 e hs := return (hs, e)
| (n + 1) e hs := do
[(_, [h], _), (_, [h'], _)] β induction e [],
swap,
elim_gen_sum_aux n h' (h::hs)
/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose
type is a (nested) sum `β`. Returns the list of local constants representing the components of `e`.
-/
meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do
(hs, h') β elim_gen_sum_aux n e [],
gs β get_goals,
set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),
return $ hs.reverse ++ [h']
/-- Given `elab_def`, a tactic to solve the current goal,
`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it
to close the goal. If `trusted` is false, it will be a meta definition. -/
meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=
do cxt β list.map expr.to_implicit_local_const <$> local_context,
t β target,
(eqns,d) β solve_aux t elab_def,
d β instantiate_mvars d,
t' β pis cxt t,
d' β lambdas cxt d,
let univ := t'.collect_univ_params,
add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,
applyc n
/-- Attempts to close the goal with `dec_trivial`. -/
meta def exact_dec_trivial : tactic unit := `[exact dec_trivial]
/-- Runs a tactic for a result, reverting the state after completion. -/
meta def retrieve {Ξ±} (tac : tactic Ξ±) : tactic Ξ± :=
Ξ» s, result.cases_on (tac s)
(Ξ» a s', result.success a s)
result.exception
/-- Runs a tactic for a result, reverting the state after completion or error. -/
meta def retrieve' {Ξ±} (tac : tactic Ξ±) : tactic Ξ± :=
Ξ» s, result.cases_on (tac s)
(Ξ» a s', result.success a s)
(Ξ» msg pos s', result.exception msg pos s)
/-- Repeat a tactic at least once, calling it recursively on all subgoals,
until it fails. This tactic fails if the first invocation fails. -/
meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t
/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and
at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/
meta def iterate_range : β β β β tactic unit β tactic unit
| 0 0 t := skip
| 0 (n+1) t := try (t >> iterate_range 0 n t)
| (m+1) n t := t >> iterate_range m (n-1) t
/--
Given a tactic `tac` that takes an expression
and returns a new expression and a proof of equality,
use that tactic to change the type of the hypotheses listed in `hs`,
as well as the goal if `tgt = tt`.
Returns `tt` if any types were successfully changed.
-/
meta def replace_at (tac : expr β tactic (expr Γ expr)) (hs : list expr) (tgt : bool) :
tactic bool :=
do to_remove β hs.mfilter $ Ξ» h, do
{ h_type β infer_type h,
succeeds $ do
(new_h_type, pr) β tac h_type,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact },
goal_simplified β succeeds $ do
{ guard tgt,
(new_t, pr) β target >>= tac,
replace_target new_t pr },
to_remove.mmap' (Ξ» h, try (clear h)),
return (Β¬ to_remove.empty β¨ goal_simplified)
/-- `revert_after e` reverts all local constants after local constant `e`. -/
meta def revert_after (e : expr) : tactic β := do
l β local_context,
[pos] β return $ l.indexes_of e | pp e >>= Ξ» s, fail format!"No such local constant {s}",
let l := l.drop pos.succ, -- all local hypotheses after `e`
revert_lst l
/-- `revert_target_deps` reverts all local constants on which the target depends (recursively).
Returns the number of local constants that have been reverted. -/
meta def revert_target_deps : tactic β :=
do tgt β target,
ctx β local_context,
l β ctx.mfilter (kdepends_on tgt),
n β revert_lst l,
if l = [] then return n
else do m β revert_target_deps, return (m + n)
/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant
with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.
`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the
goal, in which case it just calls `assert`.
In contrast to `generalize` it already introduces the generalized variable. -/
meta def generalize' (e : expr) (n : name) : tactic expr :=
(generalize e n >> intro n) <|> note n none e
/--
`intron_no_renames n` calls `intro` `n` times, using the pretty-printing name
provided by the binder to name the new local constant.
Unlike `intron`, it does not rename introduced constants if the names shadow existing constants.
-/
meta def intron_no_renames : β β tactic unit
| 0 := pure ()
| (n+1) := do
expr.pi pp_n _ _ _ β target,
intro pp_n,
intron_no_renames n
/-- `get_univ_level t` returns the universe level of a type `t` -/
meta def get_univ_level (t : expr) (md := semireducible) (unfold_ginductive := tt) :
tactic level :=
do expr.sort u β infer_type t >>= Ξ» s, whnf s md unfold_ginductive |
fail "get_univ_level: argument is not a type",
return u
/-!
### Various tactics related to local definitions (local constants of the form `x : Ξ± := t`)
We call `t` the value of `x`.
-/
/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined
locally using a `let` expression. Otherwise it fails. -/
meta def local_def_value (e : expr) : tactic expr :=
pp e >>= Ξ» s, -- running `pp` here, because we cannot access it in the `type_context` monad.
tactic.unsafe.type_context.run $ do
lctx <- tactic.unsafe.type_context.get_local_context,
some ldecl <- return $ lctx.get_local_decl e.local_uniq_name |
tactic.unsafe.type_context.fail format!"No such hypothesis {s}.",
some let_val <- return ldecl.value |
tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.",
return let_val
/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form
`e : Ξ± := t`) and otherwise fails. -/
meta def is_local_def (e : expr) : tactic unit := do
ctx β unsafe.type_context.get_local_context.run,
(some decl) β pure $ ctx.get_local_decl e.local_uniq_name |
fail format!"is_local_def: {e} is not a local constant",
when decl.value.is_none $ fail
format!"is_local_def: {e} is not a local definition"
/-- Returns the local definitions from the context. A local definition is a
local constant of the form `e : Ξ± := t`. The local definitions are returned in
the order in which they appear in the context. -/
meta def local_defs : tactic (list expr) := do
ctx β unsafe.type_context.get_local_context.run,
ctx' β local_context,
ctx'.mfilter $ Ξ» h, do
(some decl) β pure $ ctx.get_local_decl h.local_uniq_name |
fail format!"local_defs: local {h} not found in the local context",
pure decl.value.is_some
/-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs`
(using membership to `vs` instead of a predicate) and breaks `xs` when matches are found.
whereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes
them in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition
running up to the first match. -/
private def partition_local_deps_aux {Ξ±} [decidable_eq Ξ±] (vs : list Ξ±) :
list Ξ± β list Ξ± β list (list Ξ±)
| [] acc := [acc.reverse]
| (l :: ls) acc :=
if l β vs then acc.reverse :: partition_local_deps_aux ls [l]
else partition_local_deps_aux ls (l :: acc)
/-- `partition_local_deps vs`, with `vs` a list of local constants,
reorders `vs` in the order they appear in the local context together
with the variables that follow them. If local context is `[a,b,c,d,e,f]`,
and that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`.
The head of each list is one of the variables given as a parameter. -/
meta def partition_local_deps (vs : list expr) : tactic (list (list expr)) :=
do ls β local_context,
pure (partition_local_deps_aux vs ls []).tail.reverse
/-- `clear_value [eβ, eβ, eβ, ...]` clears the body of the local definitions `eβ`, `eβ`, `eβ`, ...
changing them into regular hypotheses. A hypothesis `e : Ξ± := t` is changed to `e : Ξ±`. The order of
locals `eβ`, `eβ`, `eβ` does not matter as a permutation will be chosen so as to preserve type
correctness. This tactic is called `clearbody` in Coq. -/
meta def clear_value (vs : list expr) : tactic unit := do
ls β partition_local_deps vs,
ls.mmap' $ Ξ» vs, do
{ revert_lst vs,
(expr.elet v t d b) β target |
fail format!"Cannot clear the body of {vs.head}. It is not a local definition.",
let e := expr.pi v binder_info.default t b,
type_check e <|>
fail format!"Cannot clear the body of {vs.head}. The resulting goal is not type correct.",
g β mk_meta_var e,
h β note `h none g,
tactic.exact $ h d,
gs β get_goals,
set_goals $ g :: gs },
ls.reverse.mmap' $ Ξ» vs, intro_lst $ vs.map expr.local_pp_name
/--
`context_has_local_def` is true iff there is at least one local definition in
the context.
-/
meta def context_has_local_def : tactic bool := do
ctx β local_context,
ctx.many (succeeds β local_def_value)
/--
`context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the
context up to and including `h` is a local definition.
-/
meta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do
ff β succeeds (local_def_value h) | pure tt,
ctx β local_context,
let ctx := ctx.take_while (β h),
ctx.many (succeeds β local_def_value)
/--
If the expression `h` is a local variable with type `x = t` or `t = x`, where `x` is a local
constant, `tactic.subst' h` substitutes `x` by `t` everywhere in the main goal and then clears `h`.
If `h` is another local variable, then we find a local constant with type `h = t` or `t = h` and
substitute `t` for `h`.
This is like `tactic.subst`, but fails with a nicer error message if the substituted variable is a
local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib.
-/
meta def subst' (h : expr) : tactic unit := do
e β do { -- we first find the variable being substituted away
t β infer_type h,
let (f, args) := t.get_app_fn_args,
if (f.const_name = `eq β¨ f.const_name = `heq) then do
{ let lhs := args.inth 1,
let rhs := args.ilast,
if rhs.is_local_constant then return rhs else
if lhs.is_local_constant then return lhs else fail
"subst tactic failed, hypothesis '{h.local_pp_name}' is not of the form (x = t) or (t = x)." }
else return h },
success_if_fail (is_local_def e) <|>
fail format!("Cannot substitute variable {e.local_pp_name}, " ++
"it is a local definition. If you really want to do this, use `clear_value` first."),
subst h
/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,
`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting
expression and a proof of equality. -/
meta def simp_bottom_up' (post : expr β tactic (expr Γ expr)) (e : expr) (cfg : simp_config := {}) :
tactic (expr Γ expr) :=
prod.snd <$> simplify_bottom_up () (Ξ» _, (<$>) (prod.mk ()) β post) e cfg
/-- Caches unary type classes on a type `Ξ± : Type.{univ}`. -/
meta structure instance_cache :=
(Ξ± : expr)
(univ : level)
(inst : name_map expr)
/-- Creates an `instance_cache` for the type `Ξ±`. -/
meta def mk_instance_cache (Ξ± : expr) : tactic instance_cache :=
do u β mk_meta_univ,
infer_type Ξ± >>= unify (expr.sort (level.succ u)),
u β get_univ_assignment u,
return β¨Ξ±, u, mk_name_mapβ©
namespace instance_cache
/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of
`n c.Ξ±` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance
via type class resolution, and updates the cache. -/
meta def get (c : instance_cache) (n : name) : tactic (instance_cache Γ expr) :=
match c.inst.find n with
| some i := return (c, i)
| none := do e β mk_app n [c.Ξ±] >>= mk_instance,
return (β¨c.Ξ±, c.univ, c.inst.insert n eβ©, e)
end
open expr
/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,
`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/
meta def append_typeclasses : expr β instance_cache β list expr β
tactic (instance_cache Γ list expr)
| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=
do (c, p) β c.get n, return (c, p :: l)
| _ c l := return (c, l)
/-- Creates the application `n c.Ξ± p l`, where `p` is a type class instance found in the cache `c`.
-/
meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache Γ expr) :=
do d β get_decl n,
(c, l) β append_typeclasses d.type.binding_body c l,
return (c, (expr.const n [c.univ]).mk_app (c.Ξ± :: l))
/-- `c.of_nat n` creates the `c.Ξ±`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (c : instance_cache) (n : β) : tactic (instance_cache Γ expr) :=
if n = 0 then c.mk_app ``has_zero.zero [] else do
(c, ai) β c.get ``has_add,
(c, oi) β c.get ``has_one,
(c, one) β c.mk_app ``has_one.one [],
return (c, n.binary_rec one $ Ξ» b n e,
if n = 0 then one else
cond b
((expr.const ``bit1 [c.univ]).mk_app [c.Ξ±, oi, ai, e])
((expr.const ``bit0 [c.univ]).mk_app [c.Ξ±, ai, e]))
/-- `c.of_int n` creates the `c.Ξ±`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (c : instance_cache) : β€ β tactic (instance_cache Γ expr)
| (n : β) := c.of_nat n
| -[1+ n] := do
(c, e) β c.of_nat (n+1),
c.mk_app ``has_neg.neg [e]
end instance_cache
/-- A variation on `assert` where a (possibly incomplete)
proof of the assertion is provided as a parameter.
``(h,gs) β local_proof `h p tac`` creates a local `h : p` and
use `tac` to (partially) construct a proof for it. `gs` is the
list of remaining goals in the proof of `h`.
The benefits over assert are:
- unlike with ``h β assert `h p, tac`` , `h` cannot be used by `tac`;
- when `tac` does not complete the proof of `h`, returning the list
of goals allows one to write a tactic using `h` and with the confidence
that a proof will not boil over to goals left over from the proof of `h`,
unlike what would be the case when using `tactic.swap`.
-/
meta def local_proof (h : name) (p : expr) (tacβ : tactic unit) :
tactic (expr Γ list expr) :=
focus1 $
do h' β assert h p,
[gβ,gβ] β get_goals,
set_goals [gβ], tacβ,
gs β get_goals,
set_goals [gβ],
return (h', gs)
/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/
meta def var_names : expr β list name
| (expr.pi n _ _ b) := n :: var_names b
| _ := []
/-- When `struct_n` is the name of a structure type,
`subobject_names struct_n` returns two lists of names `(instances, fields)`.
The names in `instances` are the projections from `struct_n` to the structures that it extends
(assuming it was defined with `old_structure_cmd false`).
The names in `fields` are the standard fields of `struct_n`. -/
meta def subobject_names (struct_n : name) : tactic (list name Γ list name) :=
do env β get_env,
c β match env.constructors_of struct_n with
| [c] := pure c
| [] :=
if env.is_inductive struct_n
then fail format!"{struct_n} does not have constructors"
else fail format!"{struct_n} is not an inductive type"
| _ := fail "too many constructors"
end,
vs β var_names <$> (mk_const c >>= infer_type),
fields β env.structure_fields struct_n,
return $ fields.partition (Ξ» fn, β("_" ++ fn.to_string) β vs)
private meta def expanded_field_list' : name β tactic (dlist $ name Γ name) | struct_n :=
do (so,fs) β subobject_names struct_n,
ts β so.mmap (Ξ» n, do
(_, e) β mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis,
expanded_field_list' $ e.get_app_fn.const_name),
return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)
open functor function
/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure
named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name
of the projection is `prefix.name`.
`struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/
meta def expanded_field_list (struct_n : name) : tactic (list $ name Γ name) :=
dlist.to_list <$> expanded_field_list' struct_n
/--
Return a list of all type classes which can be instantiated
for the given expression.
-/
meta def get_classes (e : expr) : tactic (list name) :=
attribute.get_instances `class >>= list.mfilter (Ξ» n,
succeeds $ mk_app n [e] >>= mk_instance)
/--
Finds an instance of an implication `cond β tgt`.
Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention
`e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used,
since it has been "proven" by a metavariable.
-/
meta def mk_conditional_instance (cond tgt : expr) : tactic (expr Γ expr) := do
f β mk_meta_var cond,
e β assertv `c cond f, swap,
reset_instance_cache,
inst β mk_instance tgt,
return (e, inst)
open nat
/-- Create a list of `n` fresh metavariables. -/
meta def mk_mvar_list : β β tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n
/-- Returns the only goal, or fails if there isn't just one goal. -/
meta def get_goal : tactic expr :=
do gs β get_goals,
match gs with
| [a] := return a
| [] := fail "there are no goals"
| _ := fail "there are too many goals"
end
/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,
or until it fails. Always succeeds. -/
meta def iterate_at_most_on_all_goals : nat β tactic unit β tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip
/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first
goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on
current goal. -/
meta def iterate_at_most_on_subgoals : nat β tactic unit β tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)
/-- This makes sure that the execution of the tactic does not change the tactic state.
This can be helpful while using rewrite, apply, or expr munging.
Remember to instantiate your metavariables before you're done! -/
meta def lock_tactic_state {Ξ±} (t : tactic Ξ±) : tactic Ξ±
| s := match t s with
| result.success a s' := result.success a s
| result.exception msg pos s' := result.exception msg pos s
end
/--
`apply_list l`, for `l : list (tactic expr)`,
tries to apply the lemmas generated by the tactics in `l` on the first goal, and
fail if none succeeds.
-/
meta def apply_list_expr (opt : apply_cfg) : list (tactic expr) β tactic unit
| [] := fail "no matching rule"
| (h::t) := (do e β h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t
/--
Given the name of a user attribute, produces a list of `tactic expr`s, each of which is the
application of `i_to_expr_for_apply` to a declaration with that attribute.
-/
meta def resolve_attribute_expr_list (attr_name : name) : tactic (list (tactic expr)) := do
l β attribute.get_instances attr_name,
list.map i_to_expr_for_apply <$> list.reverse <$> l.mmap resolve_name
/--`apply_rules args attrs n`: apply the lists of rules `args` (given as pexprs) and `attrs` (given
as names of attributes) and `the tactic assumption` on the first goal and the resulting subgoals,
iteratively, at most `n` times.
Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies
a lemma from the list until it can't.
-/
meta def apply_rules (args : list pexpr) (attrs : list name) (n : nat) (opt : apply_cfg) :
tactic unit := do
attr_exprs β lock_tactic_state $ attrs.mfoldl
(Ξ» l n, list.append l <$> resolve_attribute_expr_list n) [],
let args_exprs := args.map i_to_expr_for_apply ++ attr_exprs,
-- `args_exprs` is a list of `tactic expr`, rather than just `expr`, because these expressions will
-- be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck.
iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt args_exprs)
/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local
context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.
Fails if there is nothing named `h` in the local context. -/
meta def replace (h : name) (p : pexpr) : tactic unit :=
do h' β get_local h,
p β to_expr p,
note h none p,
clear h'
/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``
or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an
`iff`, returns an expression with the `iff` converted to either the forwards or backwards
implication, as requested. -/
meta def mk_iff_mp_app (iffmp : name) : expr β (nat β expr) β option expr
| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (Ξ» n, f (n+1) (expr.var n))
| `(%%a β %%b) f := some $ @expr.const tt iffmp [] a b (f 0)
| _ f := none
/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Ξ ..., A β B`, returns an expression whose type is `Ξ ..., A β B`. -/
meta def iff_mp_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mp ty (Ξ»_, e)
/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Ξ ..., A β B`, returns an expression whose type is `Ξ ..., B β A`. -/
meta def iff_mpr_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mpr ty (Ξ»_, e)
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the forward implication. -/
meta def iff_mp (e : expr) : tactic expr :=
do t β infer_type e,
iff_mp_core e t <|> fail "Target theorem must have the form `Ξ x y z, a β b`"
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the reverse implication. -/
meta def iff_mpr (e : expr) : tactic expr :=
do t β infer_type e,
iff_mpr_core e t <|> fail "Target theorem must have the form `Ξ x y z, a β b`"
/--
Attempts to apply `e`, and if that fails, if `e` is an `iff`,
try applying both directions separately.
-/
meta def apply_iff (e : expr) : tactic (list (name Γ expr)) :=
let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in
ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)
/--
Configuration options for `apply_any`:
* `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again.
* `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again.
* `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`.
-/
meta structure apply_any_opt extends apply_cfg :=
(use_symmetry : bool := tt)
(use_exfalso : bool := tt)
/--
This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s,
and evaluates these as thunks before trying to apply them.
We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`.
-/
meta def apply_any_thunk
(lemmas : list (tactic expr))
(opt : apply_any_opt := {})
(tac : tactic unit := skip)
(on_success : expr β tactic unit := (Ξ» _, skip))
(on_failure : tactic unit := skip) : tactic unit :=
do
let modes := [skip]
++ (if opt.use_symmetry then [symmetry] else [])
++ (if opt.use_exfalso then [exfalso] else []),
modes.any_of (Ξ» m, do m,
lemmas.any_of (Ξ» H, H >>= (Ξ» e, do apply e opt.to_apply_cfg, on_success e, tac))) <|>
(on_failure >> fail "apply_any tactic failed; no lemma could be applied")
/--
`apply_any lemmas` tries to apply one of the list `lemmas` to the current goal.
`apply_any lemmas opt` allows control over how lemmas are applied.
`opt` has fields:
* `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.)
* `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.)
* `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`).
`apply_any lemmas tac` calls the tactic `tac` after a successful application.
Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange
recursive invocations of `apply_any`.
-/
meta def apply_any
(lemmas : list expr)
(opt : apply_any_opt := {})
(tac : tactic unit := skip) : tactic unit :=
apply_any_thunk (lemmas.map pure) opt tac
/-- Try to apply a hypothesis from the local context to the goal. -/
meta def apply_assumption : tactic unit :=
local_context >>= apply_any
/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails
if this is not a definitional equality.
`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`
by reverting `h`, changing the goal, and reintroducing hypotheses. -/
meta def change_core (e : expr) : option expr β tactic unit
| none := tactic.change e
| (some h) :=
do num_reverted : β β revert h,
expr.pi n bi d b β target,
tactic.change $ expr.pi n bi e b,
intron num_reverted
/--
`change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,
assuming `olde` and `newe` are defeq when elaborated.
-/
meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit :=
do h β get_local hyp,
tp β infer_type h,
olde β to_expr olde, newe β to_expr newe,
let repl_tp := tp.replace (Ξ» a n, if a = olde then some newe else none),
when (repl_tp β tp) $ change_core repl_tp (some h)
/-- Returns a list of all metavariables in the current partial proof. This can differ from
the list of goals, since the goals can be manually edited. -/
meta def metavariables : tactic (list expr) :=
expr.list_meta_vars <$> result
/--
`sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`,
and fail otherwise.
-/
meta def sorry_if_contains_sorry : tactic unit :=
do
g β target,
guard g.contains_sorry <|> fail "goal does not contain `sorry`",
tactic.admit
/-- Fail if the target contains a metavariable. -/
meta def no_mvars_in_target : tactic unit :=
expr.has_meta_var <$> target >>= guardb β bnot
/-- Succeeds only if the current goal is a proposition. -/
meta def propositional_goal : tactic unit :=
do g :: _ β get_goals,
is_proof g >>= guardb
/-- Succeeds only if we can construct an instance showing the
current goal is a subsingleton type. -/
meta def subsingleton_goal : tactic unit :=
do g :: _ β get_goals,
ty β infer_type g >>= instantiate_mvars,
to_expr ``(subsingleton %%ty) >>= mk_instance >> skip
/--
Succeeds only if the current goal is "terminal",
in the sense that no other goals depend on it
(except possibly through shared metavariables; see `independent_goal`).
-/
meta def terminal_goal : tactic unit :=
propositional_goal <|> subsingleton_goal <|>
do gβ :: _ β get_goals,
mvars β (Ξ» L, list.erase L gβ) <$> metavariables,
mvars.mmap' $ Ξ» g, do
t β infer_type g >>= instantiate_mvars,
d β kdepends_on t gβ,
monad.whenb d $
pp t >>= Ξ» s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.")
/--
Succeeds only if the current goal is "independent", in the sense
that no other goals depend on it, even through shared meta-variables.
-/
meta def independent_goal : tactic unit :=
no_mvars_in_target >> terminal_goal
/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,
it only unfolds reducible definitions, so it sometimes fails faster. -/
meta def triv' : tactic unit := do c β mk_const `trivial, exact c reducible
variable {Ξ± : Type}
/-- Apply a tactic as many times as possible, collecting the results in a list.
Fail if the tactic does not succeed at least once. -/
meta def iterate1 (t : tactic Ξ±) : tactic (list Ξ±) :=
do r β decorate_ex "iterate1 failed: tactic did not succeed" t,
L β iterate t,
return (r :: L)
/-- Introduces one or more variables and returns the new local constants.
Fails if `intro` cannot be applied. -/
meta def intros1 : tactic (list expr) :=
iterate1 intro1
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders {Ξ± : Type} (t : tactic Ξ±) : tactic Ξ± :=
do
v β intros,
r β t,
revert_lst v,
return r
namespace interactive
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders (i : itactic) : itactic := tactic.under_binders i
end interactive
/-- `successes` invokes each tactic in turn, returning the list of successful results. -/
meta def successes (tactics : list (tactic Ξ±)) : tactic (list Ξ±) :=
list.filter_map id <$> monad.sequence (tactics.map (Ξ» t, try_core t))
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results,
and reverting to the original `tactic_state`.
-/
-- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`.
meta def try_all {Ξ± : Type} (tactics : list (tactic Ξ±)) : tactic (list Ξ±) :=
Ξ» s, result.success
(tactics.map $
Ξ» t : tactic Ξ±,
match t s with
| result.success a s' := [a]
| _ := []
end).join s
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results sorted by
the value produced by a subsequent execution of the `sort_by` tactic,
and reverting to the original `tactic_state`.
-/
meta def try_all_sorted {Ξ± : Type} (tactics : list (tactic Ξ±)) (sort_by : tactic β := num_goals) :
tactic (list (Ξ± Γ β)) :=
Ξ» s, result.success
((tactics.map $
Ξ» t : tactic Ξ±,
match (do a β t, n β sort_by, return (a, n)) s with
| result.success a s' := [a]
| _ := []
end).join.qsort (Ξ» p q : Ξ± Γ β, p.2 < q.2)) s
/-- Return target after instantiating metavars and whnf. -/
private meta def target' : tactic expr :=
target >>= instantiate_mvars >>= whnf
/--
Just like `split`, `fsplit` applies the constructor when the type of the target is
an inductive data type with one constructor.
However it does not reorder goals or invoke `auto_param` tactics.
-/
-- FIXME check if we can remove `auto_param := ff`
meta def fsplit : tactic unit :=
do [c] β target' >>= get_constructors_for |
fail "fsplit tactic failed, target is not an inductive datatype with only one constructor",
mk_const c >>= Ξ» e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip
run_cmd add_interactive [`fsplit]
add_tactic_doc
{ name := "fsplit",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fsplit],
tags := ["logic", "goal management"] }
/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`
succeeds, clears the old hypothesis. -/
meta def injections_and_clear : tactic unit :=
do l β local_context,
results β successes $ l.map $ Ξ» e, injection e >> clear e,
when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis")
run_cmd add_interactive [`injections_and_clear]
add_tactic_doc
{ name := "injections_and_clear",
category := doc_category.tactic,
decl_names := [`tactic.interactive.injections_and_clear],
tags := ["context management"] }
/-- Calls `cases` on every local hypothesis, succeeding if
it succeeds on at least one hypothesis. -/
meta def case_bash : tactic unit :=
do l β local_context,
r β successes (l.reverse.map (Ξ» h, cases h >> skip)),
when (r.empty) failed
/--
`note_anon t v`, given a proof `v : t`,
adds `h : t` to the current context, where the name `h` is fresh.
`note_anon none v` will infer the type `t` from `v`.
-/
-- While `note` provides a default value for `t`, it doesn't seem this could ever be used.
meta def note_anon (t : option expr) (v : expr) : tactic expr :=
do h β get_unused_name `h none,
note h t v
/-- `find_local t` returns a local constant with type t, or fails if none exists. -/
meta def find_local (t : pexpr) : tactic expr :=
do t' β to_expr t,
(prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|>
fail format!"No hypothesis found of the form: {t'}"
/-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values
of the previous local constants. `l` is a list of local constants and their values. -/
meta def dependent_pose_core (l : list (expr Γ expr)) : tactic unit := do
let lc := l.map prod.fst,
let lm := l.map (Ξ»β¨l, vβ©, (l.local_uniq_name, v)),
old::other_goals β get_goals,
t β infer_type old,
new_goal β mk_meta_var (t.pis lc),
set_goals (old :: new_goal :: other_goals),
exact ((new_goal.mk_app lc).instantiate_locals lm),
return ()
/--
Instantiates metavariables that appear in the current goal.
-/
meta def instantiate_mvars_in_target : tactic unit :=
target >>= instantiate_mvars >>= change
/--
Instantiates metavariables in all goals.
-/
meta def instantiate_mvars_in_goals : tactic unit :=
all_goals' $ instantiate_mvars_in_target
/-- Protect the declaration `n` -/
meta def mk_protected (n : name) : tactic unit :=
do env β get_env, set_env (env.mk_protected n)
end tactic
namespace lean.parser
open tactic interaction_monad
/-- A version of `lean.parser.many` that requires at least `n` items -/
meta def repeat_at_least {Ξ± : Type} (p : lean.parser Ξ±) : β β lean.parser (list Ξ±)
| 0 := many p
| (n + 1) := list.cons <$> p <*> repeat_at_least n
/-- A version of `lean.parser.sep_by` that allows trailing delimiters, but requires at least one
item. Like `lean.parser.sep_by`, as a result of the `lean.parser` monad not being pure, this is only
well-behaved if `p` and `s` are backtrackable; which in practice means they must not consume the
input when they do not have a match. -/
meta def sep_by_trailing {Ξ± : Type} (s : lean.parser unit) (p : lean.parser Ξ±) :
lean.parser (list Ξ±) :=
do
fst β p,
some () β optional s | pure [fst],
some rest β optional sep_by_trailing | pure [fst],
pure (fst :: rest)
/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the
current line. -/
meta def emit_command_here (str : string) : lean.parser string :=
do (_, left) β with_input command_like str,
return left
/-- Inner recursion for `emit_code_here`. -/
meta def emit_code_here_aux : string β β β lean.parser unit
| str slen := do
left β emit_command_here str,
let llen := left.length,
when (llen < slen β§ llen β 0) (emit_code_here_aux left llen)
/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in
source code. -/
meta def emit_code_here (s : string) : lean.parser unit := emit_code_here_aux s s.length
/-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the
top level, giving access to operations like `emit_code_here`. -/
@[user_command]
meta def run_parser_cmd (_ : interactive.parse $ tk "run_parser") : lean.parser unit :=
do e β lean.parser.pexpr 0,
p β eval_pexpr (lean.parser unit) e,
p
add_tactic_doc
{ name := "run_parser",
category := doc_category.cmd,
decl_names := [``run_parser_cmd],
tags := ["parsing"] }
/-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`).
This function deserves a C++ implementation in core lean, and will fail if it is not called from
the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/
meta def get_current_namespace : lean.parser name :=
do env β get_env,
n β tactic.mk_user_fresh_name,
emit_code_here $ sformat!"def {n} := ()",
nfull β tactic.resolve_constant n,
set_env env,
return $ nfull.get_nth_prefix n.components.length
/-- `get_variables` returns a list of existing variable names, along with their types and binder
info. -/
meta def get_variables : lean.parser (list (name Γ binder_info Γ expr)) :=
list.map expr.get_local_const_kind <$> list_available_include_vars
/-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been
"included" by an `include v` statement and are not (yet) `omit`ed. -/
meta def get_included_variables : lean.parser (list (name Γ binder_info Γ expr)) :=
do ns β list_include_var_names,
list.filter (Ξ» v, v.1 β ns) <$> get_variables
/-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local
variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the
local context---precisely those variables which would be ambiently accessible if we were in a
tactic-mode block where the goals had types `es.mmap to_expr`, for example.
Returns a new `ts : tactic_state` with these local variables added, and
`mappings : list (expr Γ expr)`, for which pairs `(var, hyp)` correspond to an existing variable
`var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/
meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr)
: lean.parser (tactic_state Γ list (expr Γ expr)) :=
do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the
declared variables to a fake `tactic_state`, and perform the resolution. At the end,
`to_expr e` has done the work of determining which variables were actually referenced, which
we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for
`pexpr`s). -/
vars β list_available_include_vars,
fake_es β lean.parser.of_tactic $ lock_tactic_state $ do
{ /- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard
them on this first pass. (We return the mappings generated by our second invocation of this
function below.) -/
add_local_consts_as_local_hyps vars,
es.mmap to_expr },
/- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were
referenced in `e` when it was resolved to `fake_e`.
It is important that we include variables of the kind a) because we want `simp` to have access
to declared local instances, and it is important that we only restrict to variables of kind a)
and b) together since we do not to recognise a hypothesis which is posited as a `variable`
in the environment but not referenced in the `pexpr` we were passed.
One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want
simp to use arbitrary hypotheses which were declared as `variables` in the local environment
but not referenced in the expression to simplify (as one would be expect generally in tactic
mode). -/
included_vars β list_include_var_names,
let referenced_vars := list.join $ fake_es.map $ Ξ» e, e.list_local_consts.map expr.local_pp_name,
/- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the
`pexpr` list which we were passed.) -/
let directly_included_vars := vars.filter $ Ξ» var,
(var.local_pp_name β included_vars) β¨ (var.local_pp_name β referenced_vars),
/- Inflate the list `directly_included_vars` to include those variables which are "implicitly
included" by virtue of reference to one or multiple others. For example, given
`variables (n : β) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass
instance `prime n` should be included, but `ih : even n` should not. -/
let all_implicitly_included_vars :=
expr.all_implicitly_included_variables vars directly_included_vars,
/- Capture a tactic state where both of these kinds of variables have been added as local
hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/
lean.parser.of_tactic $ do
{ mappings β add_local_consts_as_local_hyps all_implicitly_included_vars,
ts β get_state,
return (ts, mappings) }
end lean.parser
namespace tactic
variables {Ξ± : Type}
/--
Hole command used to fill in a structure's field when specifying an instance.
In the following:
```lean
instance : monad id :=
{! !}
```
invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under
construction.") produces:
```lean
instance : monad id :=
{ map := _,
map_const := _,
pure := _,
seq := _,
seq_left := _,
seq_right := _,
bind := _ }
```
-/
@[hole_command] meta def instance_stub : hole_command :=
{ name := "Instance Stub",
descr := "Generate a skeleton for the structure under construction.",
action := Ξ» _,
do tgt β target >>= whnf,
let cl := tgt.get_app_fn.const_name,
env β get_env,
fs β expanded_field_list cl,
let fs := fs.map prod.snd,
let fs := format.intercalate (",\n " : format) $ fs.map (Ξ» fn, format!"{fn} := _"),
let out := format.to_string format!"{{ {fs} }}",
return [(out,"")] }
add_tactic_doc
{ name := "instance_stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.instance_stub],
tags := ["instances"] }
/-- Like `resolve_name` except when the list of goals is
empty. In that situation `resolve_name` fails whereas
`resolve_name'` simply proceeds on a dummy goal -/
meta def resolve_name' (n : name) : tactic pexpr :=
do [] β get_goals | resolve_name n,
g β mk_mvar,
set_goals [g],
resolve_name n <* set_goals []
private meta def strip_prefix' (n : name) : list string β name β tactic name
| s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous
| s (name.mk_string a p) :=
do let n' := s.foldl (flip name.mk_string) name.anonymous,
do { n'' β tactic.resolve_constant n',
if n'' = n
then pure n'
else strip_prefix' (a :: s) p }
<|> strip_prefix' (a :: s) p
| s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n
/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/
meta def strip_prefix : name β tactic name
| n@(name.mk_string a a_1) :=
if (`_private).is_prefix_of n
then let n' := n.update_prefix name.anonymous in
n' <$ resolve_name' n' <|> pure n
else strip_prefix' n [a] a_1
| n := pure n
/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/
meta def mk_patterns (t : expr) : tactic (list format) :=
do let cl := t.get_app_fn.const_name,
env β get_env,
let fs := env.constructors_of cl,
fs.mmap $ Ξ» f,
do { (vs,_) β mk_const f >>= infer_type >>= open_pis,
let vs := vs.filter (Ξ» v, v.is_default_local),
vs β vs.mmap (Ξ» v,
do v' β get_unused_name v.local_pp_name,
pose v' none `(()),
pure v' ),
vs.mmap' $ Ξ» v, get_local v >>= clear,
let args := list.intersperse (" " : format) $ vs.map to_fmt,
f β strip_prefix f,
if args.empty
then pure $ format!"| {f} := _\n"
else pure format!"| ({f} {format.join args}) := _\n" }
/--
Hole command used to generate a `match` expression.
In the following:
```lean
meta def foo (e : expr) : tactic unit :=
{! e !}
```
invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression")
produces:
```lean
meta def foo (e : expr) : tactic unit :=
match e with
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
end
```
-/
@[hole_command] meta def match_stub : hole_command :=
{ name := "Match Stub",
descr := "Generate a list of equations for a `match` expression.",
action := Ξ» es,
do [e] β pure es | fail "expecting one expression",
e β to_expr e,
t β infer_type e >>= whnf,
fs β mk_patterns t,
e β pp e,
let out := format.to_string format!"match {e} with\n{format.join fs}end\n",
return [(out,"")] }
add_tactic_doc
{ name := "Match Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.match_stub],
tags := ["pattern matching"] }
/--
Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition")
in the following:
```lean
meta def foo : {! expr β tactic unit !} -- `:=` is omitted
```
produces:
```lean
meta def foo : expr β tactic unit
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
A similar result can be obtained by invoking "Equations Stub" on the following:
```lean
meta def foo : expr β tactic unit := -- do not forget to write `:=`!!
{! !}
```
```lean
meta def foo : expr β tactic unit := -- don't forget to erase `:=`!!
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
-/
@[hole_command] meta def eqn_stub : hole_command :=
{ name := "Equations Stub",
descr := "Generate a list of equations for a recursive definition.",
action := Ξ» es,
do t β match es with
| [t] := to_expr t
| [] := target
| _ := fail "expecting one type"
end,
e β whnf t,
(v :: _,_) β open_pis e | fail "expecting a Pi-type",
t' β infer_type v,
fs β mk_patterns t',
t β pp t,
let out :=
if es.empty then
format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}"
else format.to_string format!"{t}\n{format.join fs}",
return [(out,"")] }
add_tactic_doc
{ name := "Equations Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.eqn_stub],
tags := ["pattern matching"] }
/--
This command lists the constructors that can be used to satisfy the expected type.
Invoking "List Constructors" ("Show the list of constructors of the expected type")
in the following hole:
```lean
def foo : β€ β β :=
{! !}
```
produces:
```lean
def foo : β€ β β :=
{! sum.inl, sum.inr !}
```
and will display:
```lean
sum.inl : β€ β β€ β β
sum.inr : β β β€ β β
```
-/
@[hole_command] meta def list_constructors_hole : hole_command :=
{ name := "List Constructors",
descr := "Show the list of constructors of the expected type.",
action := Ξ» es,
do t β target >>= whnf,
(_,t) β open_pis t,
let cl := t.get_app_fn.const_name,
let args := t.get_app_args,
env β get_env,
let cs := env.constructors_of cl,
ts β cs.mmap $ Ξ» c,
do { e β mk_const c,
t β infer_type (e.mk_app args) >>= pp,
c β strip_prefix c,
pure format!"\n{c} : {t}\n" },
fs β format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure β to_fmt),
let out := format.to_string format!"{{! {fs} !}}",
trace (format.join ts).to_string,
return [(out,"")] }
add_tactic_doc
{ name := "List Constructors",
category := doc_category.hole_cmd,
decl_names := [`tactic.list_constructors_hole],
tags := ["goal information"] }
/-- Makes the declaration `classical.prop_decidable` available to type class inference.
This asserts that all propositions are decidable, but does not have computational content.
The `aggressive` argument controls whether the instance is added globally, where it has low
priority, or in the local context, where it has very high priority. -/
meta def classical (aggressive : bool := ff) : tactic unit :=
if aggressive then do
h β get_unused_name `_inst,
mk_const `classical.prop_decidable >>= note h none,
reset_instance_cache
else do
-- Turn on the `prop_decidable` instance. `9` is what we use in the `classical` locale
tactic.set_basic_attribute `instance `classical.prop_decidable ff (some 9)
open expr
/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,
returns the expression `f β g β h`. -/
meta def mk_comp (v : expr) : expr β tactic expr
| (app f e) :=
if e = v then pure f
else do
guard (Β¬ v.occurs f) <|> fail "bad guard",
e' β mk_comp e >>= instantiate_mvars,
f β instantiate_mvars f,
mk_mapp ``function.comp [none,none,none,f,e']
| e :=
do guard (e = v),
t β infer_type e,
mk_mapp ``id [t]
/-- Given two expressions `eβ` and `eβ`, return the expression `` `(%%eβ β %%eβ)``. -/
meta def mk_iff (eβ : expr) (eβ : expr) : expr := `(%%eβ β %%eβ)
/--
From a lemma of the shape `β x, f (g x) = h x`
derive an auxiliary lemma of the form `f β g = h`
for reasoning about higher-order functions.
-/
meta def mk_higher_order_type : expr β tactic expr
| (pi n bi d b@(pi _ _ _ _)) :=
do v β mk_local_def n d,
let b' := (b.instantiate_var v),
(pi n bi d β flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'
| (pi n bi d b) :=
do v β mk_local_def n d,
let b' := (b.instantiate_var v),
(l,r) β match_eq b' <|> fail format!"not an equality {b'}",
l' β mk_comp v l,
r' β mk_comp v r,
mk_app ``eq [l',r']
| e := failed
open lean.parser interactive.types
/-- A user attribute that applies to lemmas of the shape `β x, f (g x) = h x`.
It derives an auxiliary lemma of the form `f β g = h` for reasoning about higher-order functions.
-/
@[user_attribute]
meta def higher_order_attr : user_attribute unit (option name) :=
{ name := `higher_order,
parser := optional ident,
descr :=
"From a lemma of the shape `β x, f (g x) = h x` derive an auxiliary lemma of the
form `f β g = h` for reasoning about higher-order functions.",
after_set := some $ Ξ» lmm _ _,
do env β get_env,
decl β env.get lmm,
let num := decl.univ_params.length,
let lvls := (list.iota num).map (`l).append_after,
let l : expr := expr.const lmm $ lvls.map level.param,
t β infer_type l >>= instantiate_mvars,
t' β mk_higher_order_type t,
(_,pr) β solve_aux t' $ do
{ intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },
pr β instantiate_mvars pr,
lmm' β higher_order_attr.get_param lmm,
lmm' β (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime,
add_decl $ declaration.thm lmm' lvls t' (pure pr),
copy_attribute `simp lmm lmm',
copy_attribute `functor_norm lmm lmm' }
add_tactic_doc
{ name := "higher_order",
category := doc_category.attr,
decl_names := [`tactic.higher_order_attr],
tags := ["lemma derivation"] }
attribute [higher_order map_comp_pure] map_pure
/--
Copies a definition into the `tactic.interactive` namespace to make it usable
in proof scripts. It allows one to write
```lean
@[interactive]
meta def my_tactic := ...
```
instead of
```lean
meta def my_tactic := ...
run_cmd add_interactive [``my_tactic]
```
-/
@[user_attribute]
meta def interactive_attr : user_attribute :=
{ name := `interactive,
descr :=
"Put a definition in the `tactic.interactive` namespace to make it usable
in proof scripts.",
after_set := some $ Ξ» tac _ _, add_interactive [tac] }
add_tactic_doc
{ name := "interactive",
category := doc_category.attr,
decl_names := [``tactic.interactive_attr],
tags := ["environment"] }
/--
Use `refine` to partially discharge the goal,
or call `fconstructor` and try again.
-/
private meta def use_aux (h : pexpr) : tactic unit :=
(focus1 (refine h >> done)) <|> (fconstructor >> use_aux)
/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations
at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to
the expected type.
```lean
example : β x : β€, x = x :=
by tactic.use ``(42)
```
See the doc string for `tactic.interactive.use` for more information.
-/
protected meta def use (l : list pexpr) : tactic unit :=
focus1 $ seq' (l.mmap' $ Ξ» h, use_aux h <|> fail format!"failed to instantiate goal with {h}")
instantiate_mvars_in_target
/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the
local context. -/
meta def clear_aux_decl_aux : list expr β tactic unit
| [] := skip
| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l
/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/
meta def clear_aux_decl : tactic unit :=
local_context >>= clear_aux_decl_aux
/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)
finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/
meta def apply_at_aux (arg t : expr) : list expr β expr β expr β tactic (expr Γ list expr)
| vs e (pi n bi d b) :=
do { v β mk_meta_var d,
apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|>
(e arg, vs) <$ unify d t
| vs e _ := failed
/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/
meta def apply_at (e h : expr) : tactic unit :=
do ht β infer_type h,
et β infer_type e,
(h', gs') β apply_at_aux h ht [] e et,
note h.local_pp_name none h',
clear h,
gs' β gs'.mfilter is_assigned,
(g :: gs) β get_goals,
set_goals (g :: gs' ++ gs)
/-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/
meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit :=
do tgt β infer_type h,
env β get_env,
let r := get_app_fn tgt,
match env.symm_for (const_name r) with
| (some symm) := do s β mk_const symm,
apply_at s h
| none := fail
"symmetry tactic failed, target is not a relation application with the expected property."
end
/-- `setup_tactic_parser` is a user command that opens the namespaces used in writing
interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.
It does *not* use the `namespace` command, so it will typically be used after
`namespace tactic.interactive`.
-/
@[user_command]
meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") :
lean.parser unit :=
emit_code_here "
open _root_.lean
open _root_.lean.parser
open _root_.interactive _root_.interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many .
"
/-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if
`tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/
meta def finally {Ξ²} (tac : tactic Ξ±) (finalizer : tactic Ξ²) : tactic Ξ± :=
Ξ» s, match tac s with
| (result.success r s') := (finalizer >> pure r) s'
| (result.exception msg p s') := (finalizer >> result.exception msg p) s'
end
/--
`on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed.
-/
meta def on_exception {Ξ²} (handler : tactic Ξ²) (tac : tactic Ξ±) : tactic Ξ± | s :=
match tac s with
| result.exception msg p s' := (handler *> result.exception msg p) s'
| ok := ok
end
/-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/
meta def decorate_error (add_msg : string) (tac : tactic Ξ±) : tactic Ξ± | s :=
match tac s with
| result.exception msg p s :=
let msg (_ : unit) : format := match msg with
| some msg := add_msg ++ format.line ++ msg ()
| none := add_msg
end in
result.exception msg p s
| ok := ok
end
/-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails,
returns the error message. -/
meta def retrieve_or_report_error {Ξ± : Type u} (t : tactic Ξ±) : tactic (Ξ± β string) :=
Ξ» s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/
meta def try_or_report_error {Ξ± : Type u} (t : tactic Ξ±) : tactic (Ξ± β string) :=
Ξ» s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s'
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`.
-/
meta def succeeds_or_fails_with_msg {Ξ± : Type} (t : tactic Ξ±) (p : string β bool) : tactic unit :=
do x β retrieve_or_report_error t,
match x with
| (sum.inl _) := skip
| (sum.inr msg) := if p msg then skip else fail msg
end
add_tactic_doc
{ name := "setup_tactic_parser",
category := doc_category.cmd,
decl_names := [`tactic.setup_tactic_parser_cmd],
tags := ["parsing", "notation"] }
/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message
of `t`. -/
meta def trace_error (msg : string) (t : tactic Ξ±) : tactic Ξ±
| s := match t s with
| (result.success r s') := result.success r s'
| (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception
(some msg') p) s'
| (result.exception none p s') := result.exception none p s'
end
/--
``trace_if_enabled `n msg`` traces the message `msg`
only if tracing is enabled for the name `n`.
Create new names registered for tracing with `declare_trace n`.
Then use `set_option trace.n true/false` to enable or disable tracing for `n`.
-/
meta def trace_if_enabled
(n : name) {Ξ± : Type u} [has_to_tactic_format Ξ±] (msg : Ξ±) : tactic unit :=
when_tracing n (trace msg)
/--
``trace_state_if_enabled `n msg`` prints the tactic state,
preceded by the optional string `msg`,
only if tracing is enabled for the name `n`.
-/
meta def trace_state_if_enabled
(n : name) (msg : string := "") : tactic unit :=
when_tracing n ((if msg = "" then skip else trace msg) >> trace_state)
/--
This combinator is for testing purposes. It succeeds if `t` fails with message `msg`,
and fails otherwise.
-/
meta def success_if_fail_with_msg {Ξ± : Type u} (t : tactic Ξ±) (msg : string) : tactic unit :=
Ξ» s, match t s with
| (interaction_monad.result.exception msg' _ s') :=
let expected_msg := (msg'.iget ()).to_string in
if msg = expected_msg then result.success () s
else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s
| (interaction_monad.result.success a s) :=
mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s
end
/--
Construct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`.
-/
meta def tactic_statement (g : expr) : tactic string :=
do g β instantiate_mvars g,
g β head_beta g,
r β pp (replace_mvars g),
if g.has_meta_var
then return (sformat!"Try this: refine {r}")
else return (sformat!"Try this: exact {r}")
/-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the
initial goals and returns the goals `tac` ended on. -/
meta def with_local_goals {Ξ±} (gs : list expr) (tac : tactic Ξ±) : tactic (Ξ± Γ list expr) :=
do gs' β get_goals,
set_goals gs,
finally (prod.mk <$> tac <*> get_goals) (set_goals gs')
/-- like `with_local_goals` but discards the resulting goals -/
meta def with_local_goals' {Ξ±} (gs : list expr) (tac : tactic Ξ±) : tactic Ξ± :=
prod.fst <$> with_local_goals gs tac
/-- Representation of a proof goal that lends itself to comparison. The
following goal:
```lean
lβ : T,
lβ : T
β’ β v : T, foo
```
is represented as
```
(2, β lβ lβ v : T, foo)
```
The number 2 indicates that first the two bound variables of the
`β` are actually local constant. Comparing two such goals with `=`
rather than `=β` or `is_def_eq` tells us that proof script should
not see the difference between the two.
-/
meta def packaged_goal := β Γ expr
/-- proof state made of multiple `goal` meant for comparing
the result of running different tactics -/
meta def proof_state := list packaged_goal
meta instance goal.inhabited : inhabited packaged_goal := β¨(0,var 0)β©
meta instance proof_state.inhabited : inhabited proof_state :=
(infer_instance : inhabited (list packaged_goal))
/-- create a `packaged_goal` corresponding to the current goal -/
meta def get_packaged_goal : tactic packaged_goal := do
ls β local_context,
tgt β target >>= instantiate_mvars,
tgt β pis ls tgt,
pure (ls.length, tgt)
/-- `goal_of_mvar g`, with `g` a meta variable, creates a
`packaged_goal` corresponding to `g` interpretted as a proof goal -/
meta def goal_of_mvar (g : expr) : tactic packaged_goal :=
with_local_goals' [g] get_packaged_goal
/-- `get_proof_state` lists the user visible goal for each goal
of the current state and for each goal, abstracts all of the
meta variables of the other gaols.
This produces a list of goals in the form of `β Γ expr` where
the `expr` encodes the following proof state:
```lean
2 goals
lβ : tβ,
lβ : tβ,
lβ : tβ
β’ tgtβ
β’ tgtβ
```
as
```lean
[ (3, β (mv : tgtβ) (mv : tgtβ) (lβ : tβ) (lβ : tβ) (lβ : tβ), tgtβ),
(0, β (mv : tgtβ) (mv : tgtβ), tgtβ) ]
```
with 2 goals, the first 2 bound variables encode the meta variable
of all the goals, the next 3 (in the first goal) and 0 (in the second goal)
are the local constants.
This representation allows us to compare goals and proof states while
ignoring information like the unique name of local constants and
the equality or difference of meta variables that encode the same goal.
-/
meta def get_proof_state : tactic proof_state :=
do gs β get_goals,
gs.mmap $ Ξ» g, do
β¨n,gβ© β goal_of_mvar g,
g β gs.mfoldl (Ξ» g v, do
g β kabstract g v reducible ff,
pure $ pi `goal binder_info.default `(true) g ) g,
pure (n,g)
/--
Run `tac` in a disposable proof state and return the state.
See `proof_state`, `goal` and `get_proof_state`.
-/
meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) :=
try_core $ retrieve $ tac >> get_proof_state
open lean _root_.interactive
/-- A type alias for `tactic format`, standing for "pretty print format". -/
meta def pformat := tactic format
/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/
meta def pformat.mk (fmt : format) : pformat := pure fmt
/-- an alias for `pp`. -/
meta def to_pfmt {Ξ±} [has_to_tactic_format Ξ±] (x : Ξ±) : pformat :=
pp x
meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat :=
β¨ id β©
meta instance : has_append pformat :=
β¨ Ξ» x y, (++) <$> x <*> y β©
meta instance tactic.has_to_tactic_format [has_to_tactic_format Ξ±] :
has_to_tactic_format (tactic Ξ±) :=
β¨ Ξ» x, x >>= to_pfmt β©
private meta def parse_pformat : string β list char β parser pexpr
| acc [] := pure ``(to_pfmt %%(reflect acc))
| acc ('\n'::s) :=
do f β parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f)
| acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s
| acc ('{'::s) :=
do (e, s) β with_input (lean.parser.pexpr 0) s.as_string,
'}'::s β return s.to_list | fail "'}' expected",
f β parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f)
| acc (c::s) := parse_pformat (acc.str c) s
/-- See `format!` in `init/meta/interactive_base.lean`.
The main differences are that `pp` is called instead of `to_fmt` and that we can use
arguments of type `tactic Ξ±` in the quotations.
Now, consider the following:
```lean
e β to_expr ``(3 + 7),
trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add
-- (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`
trace pformat!"{e}" -- outputs `3 + 7`
```
The difference is significant. And now, the following is expressible:
```lean
e β to_expr ``(3 + 7),
trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : β`
```
See also: `trace!` and `fail!`
-/
@[user_notation]
meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr :=
do e β parse_pformat "" s.to_list,
return ``(%%e : pformat)
/--
The combination of `pformat` and `fail`.
-/
@[user_notation]
meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr :=
do e β pformat_macro () s,
pure ``((%%e : pformat) >>= fail)
/--
The combination of `pformat` and `trace`.
-/
@[user_notation]
meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr :=
do e β pformat_macro () s,
pure ``((%%e : pformat) >>= trace)
/-- A hackish way to get the `src` directory of any project.
Requires as argument any declaration name `n` in that project, and `k`, the number of characters
in the path of the file where `n` is declared not part of the `src` directory.
Example: For `mathlib_dir_locator` this is the length of `tactic/project_dir.lean`, so `23`.
Note: does not work in the file where `n` is declared. -/
meta def get_project_dir (n : name) (k : β) : tactic string :=
do e β get_env,
s β e.decl_olean n <|>
fail!"Did not find declaration {n}. This command does not work in the file where {n} is declared.",
return $ s.popn_back k
/-- A hackish way to get the `src` directory of mathlib. -/
meta def get_mathlib_dir : tactic string :=
get_project_dir `mathlib_dir_locator 23
/-- Checks whether a declaration with the given name is declared in mathlib.
If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,
since it is expensive to execute `get_mathlib_dir` many times. -/
meta def is_in_mathlib (n : name) : tactic bool :=
do ml β get_mathlib_dir, e β get_env, return $ e.is_prefix_of_file ml n
/--
Runs a tactic by name.
If it is a `tactic string`, return whatever string it returns.
If it is a `tactic unit`, return the name.
(This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.)
-/
meta def name_to_tactic (n : name) : tactic string :=
do d β get_decl n,
e β mk_const n,
let t := d.type,
if (t =β `(tactic unit)) then
(eval_expr (tactic unit) e) >>= (Ξ» t, t >> (name.to_string <$> strip_prefix n))
else if (t =β `(tactic string)) then
(eval_expr (tactic string) e) >>= (Ξ» t, t)
else fail!
"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`"
/-- auxiliary function for `apply_under_n_pis` -/
private meta def apply_under_n_pis_aux (func arg : pexpr) : β β β β expr β pexpr
| n 0 _ :=
let vars := ((list.range n).reverse.map (@expr.var ff)),
bd := vars.foldl expr.app arg.mk_explicit in
func bd
| n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp)
(apply_under_n_pis_aux (n+1) k bd)
| n (k+1) t := apply_under_n_pis_aux n 0 t
/--
Assumes `pi_expr` is of the form `Ξ x1 ... xn xn+1..., _`.
Creates a pexpr of the form `Ξ x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : β) : pexpr :=
apply_under_n_pis_aux func arg 0 n pi_expr
/--
Assumes `pi_expr` is of the form `Ξ x1 ... xn, _`.
Creates a pexpr of the form `Ξ x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr :=
apply_under_n_pis func arg pi_expr pi_expr.pi_arity
/--
If `func` is a `pexpr` representing a function that takes an argument `a`,
`get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`.
When `tgt` is a `pi` expr, `func` is elaborated in a context
with the domain of `tgt`.
Examples:
* ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function
argument.
* ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument
of type `Ξ± β Ξ±`.
* ```get_pexpr_arg_arity_with_tgt ``(module R) `(Ξ (R : Type), comm_ring R β true)``` returns 0
-/
meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic β :=
lock_tactic_state $ do
mv β mk_mvar,
solve_aux tgt $ intros >> to_expr ``(%%func %%mv),
expr.pi_arity <$> (infer_type mv >>= instantiate_mvars)
/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.
`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a
declaration named `m` can be found. -/
meta def find_private_decl (n : name) (fr : option name) : tactic name :=
do env β get_env,
fn β option_t.run (do
fr β option_t.mk (return fr),
d β monad_lift $ get_decl fr,
option_t.mk (return $ env.decl_olean d.to_name) ),
let p : string β bool :=
match fn with
| (some fn) := Ξ» x, fn = x
| none := Ξ» _, tt
end,
let xs := env.decl_filter_map (Ξ» d,
do fn β env.decl_olean d.to_name,
guard ((`_private).is_prefix_of d.to_name β§ p fn β§
d.to_name.update_prefix name.anonymous = n),
pure d.to_name),
match xs with
| [n] := pure n
| [] := fail "no such private found"
| _ := fail "many matches found"
end
open lean.parser interactive
/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`
and creates a local notation to refer to it.
`import_private foo` looks for `foo` in all imported files.
When possible, make `foo` non-private rather than using this feature.
-/
@[user_command]
meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit :=
do n β ident,
fr β optional (tk "from" *> ident),
n β find_private_decl n fr,
c β resolve_constant n,
d β get_decl n,
let c := @expr.const tt c d.univ_levels,
new_n β new_aux_decl_name,
add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted,
let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}",
emit_command_here $ new_not,
skip .
add_tactic_doc
{ name := "import_private",
category := doc_category.cmd,
decl_names := [`tactic.import_private_cmd],
tags := ["renaming"] }
/--
The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`.
Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.
`mk_simp_attribute simp_name none` will use a default description.
Appending the command with `with attr1 attr2 ...` will include all declarations tagged with
`attr1`, `attr2`, ... in the new simp set.
This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string
to the attribute that is defined. If you need to create a simp set in a file where this command is
not available, you should use
```lean
run_cmd mk_simp_attr `simp_name
run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here"
```
-/
@[user_command]
meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit :=
do n β ident,
d β parser.pexpr,
d β to_expr ``(%%d : option string),
descr β eval_expr (option string) d,
with_list β (tk "with" *> many ident) <|> return [],
mk_simp_attr n with_list,
add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n
add_tactic_doc
{ name := "mk_simp_attribute",
category := doc_category.cmd,
decl_names := [`tactic.mk_simp_attribute_cmd],
tags := ["simplification"] }
/--
Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns
the name of the declaration that defines this attribute.
Fails if there is no user attribute with this name.
Example: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/
meta def get_user_attribute_name (attr_name : name) : tactic name := do
ns β attribute.get_instances `user_attribute,
ns.mfirst (Ξ» nm, do
d β get_decl nm,
e β mk_app `user_attribute.name [d.value],
attr_nm β eval_expr name e,
guard $ attr_nm = attr_name,
return nm) <|> fail!"'{attr_name}' is not a user attribute."
/-- A tactic to set either a basic attribute or a user attribute.
If the user attribute has a parameter, the default value will be used.
This tactic raises an error if there is no `inhabited` instance for the parameter type. -/
meta def set_attribute (attr_name : name) (c_name : name) (persistent := tt)
(prio : option nat := none) : tactic unit := do
get_decl c_name <|> fail!"unknown declaration {c_name}",
s β try_or_report_error (set_basic_attribute attr_name c_name persistent prio),
sum.inr msg β return s | skip,
if msg =
(format!"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute").to_string
then do
user_attr_nm β get_user_attribute_name attr_name,
user_attr_const β mk_const user_attr_nm,
tac β eval_pexpr (tactic unit)
``(user_attribute.set %%user_attr_const %%`(c_name) default %%`(persistent)) <|>
fail! ("Cannot set attribute @[{attr_name}].\n" ++
"The corresponding user attribute {user_attr_nm} " ++
"has a parameter without a default value.\n" ++
"Solution: provide an `inhabited` instance."),
tac
else fail msg
end tactic
/--
`find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`),
and returns the value associated with this key if it exists.
Otherwise, it fails.
-/
meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr Γ v)) (e : expr) :
tactic (expr Γ v) :=
m.mfind $ Ξ» β¨e', valβ©, tactic.is_def_eq e e' red
|
18c4afc36a4e02c6070cb7696206489d63419b42 | 4a092885406df4e441e9bb9065d9405dacb94cd8 | /src/for_mathlib/pointwise.lean | 1cab4bc2b5f5b8211b3e2a406aa917024e9e7df6 | [
"Apache-2.0"
] | permissive | semorrison/lean-perfectoid-spaces | 78c1572cedbfae9c3e460d8aaf91de38616904d8 | bb4311dff45791170bcb1b6a983e2591bee88a19 | refs/heads/master | 1,588,841,765,494 | 1,554,805,620,000 | 1,554,805,620,000 | 180,353,546 | 0 | 1 | null | 1,554,809,880,000 | 1,554,809,880,000 | null | UTF-8 | Lean | false | false | 1,634 | lean | import algebra.pointwise
import group_theory.group_action
namespace set
local attribute [instance] set.pointwise_mul_semiring
local attribute [instance] set.singleton.is_monoid_hom
variables {Ξ± : Type*} [monoid Ξ±]
instance : mul_action Ξ± (set Ξ±) :=
{ smul := Ξ» a s, ({a} : set Ξ±) * s,
one_smul := one_mul,
mul_smul := Ξ» _ _ _, show {_} * _ = _,
by { erw is_monoid_hom.map_mul (singleton : Ξ± β set Ξ±), apply mul_assoc } }
lemma mem_smul_set {a : Ξ±} {s : set Ξ±} {x : Ξ±} :
x β a β’ s β β y β s, x = a * y :=
by { erw mem_pointwise_mul, simp }
lemma smul_set_eq_image {a : Ξ±} {s : set Ξ±} :
a β’ s = (Ξ» b, a * b) '' s :=
set.ext $ Ξ» x,
begin
simp only [mem_smul_set, exists_prop, mem_image],
apply exists_congr,
intro y,
apply and_congr iff.rfl,
split; exact eq.symm
end
lemma mul_le_mul {sβ sβ tβ tβ : set Ξ±} (hs : sβ β sβ) (ht : tβ β tβ) :
sβ * tβ β sβ * tβ :=
by { rintros _ β¨a, ha, b, hb, rflβ©, exact β¨a, hs ha, b, ht hb, rflβ© }
local attribute [instance] pointwise_mul pointwise_add
instance pointwise_mul_fintype [has_mul Ξ±] [decidable_eq Ξ±] (s t : set Ξ±) [hs : fintype s] [ht : fintype t] :
fintype (s * t : set Ξ±) := by {rw pointwise_mul_eq_image, apply set.fintype_image}
instance pointwise_add_fintype [has_add Ξ±] [decidable_eq Ξ±] (s t : set Ξ±) [hs : fintype s] [ht : fintype t] :
fintype (s + t : set Ξ±) := by {rw pointwise_add_eq_image, apply set.fintype_image}
-- attribute [to_additive set.pointwise_add_fintype] or something should go here but KMB forgot the
-- syntax for when it wasn't auto generated
end set
|
5c4f0677403358e178049eba01a39f9283e77ae4 | 6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf | /src/game/world3/level6.lean | 7596bc73fee66d14272f3e160739ff3fa0dc5979 | [
"Apache-2.0"
] | permissive | arolihas/natural_number_game | 4f0c93feefec93b8824b2b96adff8b702b8b43ce | 8e4f7b4b42888a3b77429f90cce16292bd288138 | refs/heads/master | 1,621,872,426,808 | 1,586,270,467,000 | 1,586,270,467,000 | 253,648,466 | 0 | 0 | null | 1,586,219,694,000 | 1,586,219,694,000 | null | UTF-8 | Lean | false | false | 1,050 | lean | import game.world3.level5 -- hide
import mynat.mul -- hide
namespace mynat -- hide
/-
# Multiplication World
## Level 6: `succ_mul`
We now begin our journey to `mul_comm`, the proof that `a * b = b * a`.
We'll get there in level 8. Until we're there, it is frustrating
but true that we cannot assume commutativity. We have `mul_succ`
but we're going to need `succ_mul` (guess what it says -- maybe you
are getting the hang of Lean's naming conventions).
Remember also that we have tools like
* `add_right_comm a b c : a + b + c = a + c + b`
These things are the tools we need to slowly build up the results
which we will need to do mathematics "normally".
We also now have access to Lean's `simp` tactic,
which will solve any goal which just needs a bunch
of rewrites of `add_assoc` and `add_comm`. Use if
you're getting lazy!
-/
/- Lemma
For all natural numbers $a$ and $b$, we have
$$ \operatorname{succ}(a) \times b = ab + b. $$
-/
lemma succ_mul (a b : mynat) : succ a * b = a * b + b :=
begin [nat_num_game]
end
end mynat -- hide
|
93715fb26ca6a4aed24f55eeb8e73b124b2ff77d | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /src/builtin/Int.lean | fe533c68ef5bc24e09022a5d0e8f173d4635fe93 | [
"Apache-2.0"
] | permissive | codyroux/lean0.1 | 1ce92751d664aacff0529e139083304a7bbc8a71 | 0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef | refs/heads/master | 1,610,830,535,062 | 1,402,150,480,000 | 1,402,150,480,000 | 19,588,851 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,334 | lean | import Nat
variable Int : Type
alias β€ : Int
builtin nat_to_int : Nat β Int
coercion nat_to_int
namespace Int
builtin numeral
builtin add : Int β Int β Int
infixl 65 + : add
builtin mul : Int β Int β Int
infixl 70 * : mul
builtin div : Int β Int β Int
infixl 70 div : div
builtin le : Int β Int β Bool
infix 50 <= : le
infix 50 β€ : le
definition ge (a b : Int) : Bool := b β€ a
infix 50 >= : ge
infix 50 β₯ : ge
definition lt (a b : Int) : Bool := Β¬ (a β₯ b)
infix 50 < : lt
definition gt (a b : Int) : Bool := Β¬ (a β€ b)
infix 50 > : gt
definition sub (a b : Int) : Int := a + -1 * b
infixl 65 - : sub
definition neg (a : Int) : Int := -1 * a
notation 75 - _ : neg
definition mod (a b : Int) : Int := a - b * (a div b)
infixl 70 mod : mod
definition divides (a b : Int) : Bool := (b mod a) = 0
infix 50 | : divides
definition abs (a : Int) : Int := if (0 β€ a) then a else (- a)
notation 55 | _ | : abs
set_opaque sub true
set_opaque neg true
set_opaque mod true
set_opaque divides true
set_opaque abs true
set_opaque ge true
set_opaque lt true
set_opaque gt true
end
namespace Nat
definition sub (a b : Nat) : Int := nat_to_int a - nat_to_int b
infixl 65 - : sub
definition neg (a : Nat) : Int := - (nat_to_int a)
notation 75 - _ : neg
set_opaque sub true
set_opaque neg true
end |
10348b545cd2cd12ab001f0126d6280415639921 | dcdf6d611bf037b80e9af2e690367d5f5adc3676 | /formalization.lean | 2e4058054ba1b29653af18fd2976713786d2afb2 | [] | no_license | ValentinBesnard/emi-verifying-and-monitoring-uml-models | fe40083194e35f218c616c0ba2a43bb5d7ecca60 | 911fbf731910daa7c9fd34432815e24e353cce1b | refs/heads/main | 1,672,976,455,748 | 1,604,757,635,000 | 1,604,757,635,000 | 309,122,953 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,000 | lean |
namespace emi
variables
{C : Type} -- configurations
{A : Type} -- actions
{L : Type} -- atomic propositions
-- STR structure
structure STR :=
(initial : set C)
(actions : C β set A)
(execute : C β A β set C)
-- Type to know if some actions are available or if there is a deadlock
universe u
inductive completed (Ξ± : Type u)
| deadlock {} : completed
| some : Ξ± β completed
-- Operator used to complete a STR by adding implicit transitions
def add_implicit_transitions
(str : @STR C A)
[β c, decidable (str.actions c = β
)]
: @STR C (completed A) :=
{
initial := str.initial,
actions := Ξ» c, if str.actions c = β
then
(singleton completed.deadlock)
else
{ oa | β a β str.actions c, oa = completed.some a },
execute := Ξ» c oa, match oa with
| completed.deadlock := singleton c
| completed.some a := { oc | β t β str.execute c a, oc = t }
end
}
-- Synchronous composition operator
def synchronous_composition (Cβ Cβ Aβ Aβ Lβ : Type)
(lhs : @STR Cβ Aβ)
(evalβ : Lβ β Cβ β Aβ β Cβ β bool)
(rhs : @STR Cβ Aβ)
(evalβ : Cβ β Aβ β Lβ)
: @STR (Cβ Γ Cβ) (Aβ Γ Aβ) :=
{
initial := { c | β (cβ β lhs.initial) (cβ β rhs.initial), c = (cβ, cβ) },
actions := Ξ» c, { a |
match c with
| (cβ, cβ) := β (aβ β lhs.actions cβ) (aβ β rhs.actions cβ)
(tβ β lhs.execute cβ aβ) (tβ β rhs.execute cβ aβ),
match tβ, tβ : β tβ tβ, Prop with
| tβ, tβ := evalβ (evalβ cβ aβ) cβ aβ tβ = tt β a = (aβ, aβ)
end
end
},
execute := Ξ» c a, { t |
match c, a with
| (cβ, cβ), (aβ, aβ) := β (tβ β lhs.execute cβ aβ)
(tβ β rhs.execute cβ aβ), t = (tβ, tβ)
end
}
}
end emi
|
5e511c93db91616e0bd44c420499cbc542efa3ac | fbf512ee44de430e3d3c5869751ad95325c938d7 | /list.lean | 5a0c2080180f52a4dd5231d3d94ff62601dedc33 | [] | no_license | skbaek/clausify | 4858c9005fb86a5e410bfcaa77524f82d955f655 | d09b071bdcce7577c3fffacd0893b776285b1590 | refs/heads/master | 1,588,360,590,818 | 1,553,553,880,000 | 1,553,553,880,000 | 177,644,542 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,103 | lean | import data.list.basic
variables {Ξ± Ξ² : Type}
namespace list
lemma map_eq_map_of_forall_mem_eq {f g : Ξ± β Ξ²} :
β {as}, (β a β as, f a = g a) β map f as = map g as
| [] h1 := rfl
| (a::as) h1 :=
begin
simp only [map], constructor,
apply h1 _ (or.inl rfl),
apply map_eq_map_of_forall_mem_eq,
apply forall_mem_of_forall_mem_cons h1
end
def gen_union [decidable_eq Ξ±] : list (list Ξ±) β list Ξ±
| [] := []
| [l] := l
| (l1::l2::ls) := l1 βͺ (gen_union (l2::ls))
notation `β` := gen_union
def max [has_zero Ξ±] [decidable_linear_order Ξ±] : list Ξ± β Ξ±
| [] := 0
| (a::as) := _root_.max a as.max
end list
#exit
lemma map_eq_map_of_funeq_over (P : Ξ± β Prop) {f g : Ξ± β Ξ²} :
β as, (β a, P a β f a = g a) β (β a β as, P a) β map f as = map g as
| [] h1 h2 := rfl
| (a::as) h1 h2 :=
begin
simp, constructor, apply h1 _ (h2 a (or.inl rfl)),
apply map_eq_map_of_funeq_over, apply h1,
apply forall_mem_of_forall_mem_cons h2
end
def to_string_sep_core {Ξ± : Type}
(f : Ξ± β string) (s : string) : list Ξ± β string
| [] := ""
| [a] := f a
| (a::as) := f a ++ s ++ to_string_sep_core as
def to_string_sep {Ξ± : Type} (s : string)
[has_to_string Ξ±] : list Ξ± β string :=
to_string_sep_core has_to_string.to_string s
def head_nonempty {Ξ± : Type} : Ξ (l : list Ξ±), l β [] β Ξ±
| [] h := by {exfalso, exact (h rfl)}
| (a::as) h := a
-- def pull_core : nat β list Ξ± β option (Ξ± Γ list Ξ±)
-- | _ [] := none
-- | 0 (a::as) := some β¨a,asβ©
-- | (n+1) (a::as) :=
-- match pull_core n as with
-- | none := none
-- | (some β¨a',as'β©) := (some β¨a',a::as'β©)
-- end
--
-- def pull (n as) : list Ξ± :=
-- match pull_core n as with
-- | none := as
-- | (some β¨a,as'β©) := (a::as')
-- end
def pull : nat β list Ξ± β list Ξ±
| _ [] := []
| 0 as := as
| (n+1) (a::as) :=
match pull n as with
| [] := a::as
| (a'::as') := a'::(a::as')
end
lemma pull_perm : β n (as : list Ξ±), pull n as ~ as
| 0 [] := perm.refl _
| 0 (a::as) := perm.refl _
| (n+1) [] := perm.refl _
| (n+1) (a::as) :=
begin
simp [pull], have ih := pull_perm n as,
cases (pull n as) with a' as', apply perm.refl,
apply (perm.trans (perm.swap _ _ _) (perm.skip _ ih))
end
lemma mem_pull_iff {n a} {as : list Ξ±} :
a β pull n as β a β as :=
mem_of_perm (pull_perm _ _)
lemma pull_nil : β n, pull n (nil : list Ξ±) = nil
| 0 := rfl
| (n+1) := rfl
def map_mems : Ξ (as : list Ξ±) (h : Ξ a β as, Ξ²), list Ξ²
| [] _ := []
| (a::as) h :=
(h a (or.inl rfl))::(map_mems as (Ξ» a' h', h a' (or.inr h')))
lemma map_mems_length_eq : β (as : list Ξ±) (h : Ξ a β as, Ξ²),
(map_mems as h).length = as.length
| [] _ := rfl
| (a::as) h :=
by { simp [map_mems], rw [map_mems_length_eq] }
def cond_map {C : Ξ± β Type} (f : Ξ a, C a β Ξ²) : Ξ (as : list Ξ±), (Ξ a β as, C a) β list Ξ²
| [] _ := []
| (a::as) h :=
(f a (h _ (or.inl rfl)))::(cond_map as (Ξ» a' h', h _ (or.inr h')))
lemma cond_map_length_eq {C : Ξ± β Type} (f : Ξ a, C a β Ξ²) :
Ξ (as : list Ξ±) (h : Ξ a β as, C a), (cond_map f as h).length = as.length
| [] _ := rfl
| (a::as) h :=
by { simp [cond_map], rw [cond_map_length_eq] }
theorem forall_mem_nil' (C : Ξ± β Type) : β x β @nil Ξ±, C x :=
Ξ» _ h, by cases h
lemma nth_append_ge :
β {as1 : list Ξ±} {m}, as1.length = m β β (as2 n), nth (as1 ++ as2) (m + n) = nth as2 n
| [] (m+1) h _ _ := by {cases h}
| [] 0 h as2 n := by {rw [nil_append, zero_add]}
| (a1::as1) 0 h _ _:= by {cases h}
| (a1::as1) (m+1) h as2 n:=
begin
rw [add_comm (m+1) n, (add_assoc n m 1).symm, (nat.succ_eq_add_one (n+m)).symm],
simp at *, rw (add_comm 1 _) at h,
apply (nth_append_ge (eq_of_add_eq_add_right h)),
end
lemma nth_append_lt :
β {as1 : list Ξ±} {n}, n < as1.length β β as2, nth (as1 ++ as2) n = nth as1 n
| [] _ h _ := by {cases h}
| (a1::as1) 0 _ _ := eq.refl _
| (a1::as1) (n+1) h as2 :=
begin
apply @nth_append_lt as1 n _ as2, simp at h,
rw add_comm 1 _ at h, apply nat.lt_of_succ_lt_succ,
repeat {rw nat.succ_eq_add_one}, assumption
end
lemma map_eq_map_of_funeq {f g : Ξ± β Ξ²} (h : β a, f a = g a) :
β as, map f as = map g as
| [] := rfl
| (a::as) := by {simp, constructor, apply h, apply map_eq_map_of_funeq}
def pad_update_nth [inhabited Ξ±] : list Ξ± β β β Ξ± β list Ξ±
| (x::xs) 0 a := a :: xs
| (x::xs) (i+1) a := x :: pad_update_nth xs i a
| [] 0 a := [a]
| [] (i+1) a := (default Ξ±) :: pad_update_nth [] i a
-- lemma nth_pad_update_nth [inhabited Ξ±] (as : list Ξ±) (k a) :
-- nth (pad_update_nth as k a) k = some a := sorry
lemma map_comp {f : Ξ² β Ξ³} {g : Ξ± β Ξ²} {as} :
map (f β g) as = map f (map g as) := by simp
end list
|
6af0c9f260562c75b4202df9b67484aff302e3fd | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/logic/equiv/option.lean | 9c5fe8dc68bde4ebeb9f646366c5b94205ba2f5a | [
"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 | 7,725 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import control.equiv_functor
import data.option.basic
import data.subtype
import logic.equiv.defs
/-!
# Equivalences for `option Ξ±`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define
* `equiv.option_congr`: the `option Ξ± β option Ξ²` constructed from `e : Ξ± β Ξ²` by sending `none` to
`none`, and applying a `e` elsewhere.
* `equiv.remove_none`: the `Ξ± β Ξ²` constructed from `option Ξ± β option Ξ²` by removing `none` from
both sides.
-/
namespace equiv
open option
variables {Ξ± Ξ² Ξ³ : Type*}
section option_congr
/-- A universe-polymorphic version of `equiv_functor.map_equiv option e`. -/
@[simps apply]
def option_congr (e : Ξ± β Ξ²) : option Ξ± β option Ξ² :=
{ to_fun := option.map e,
inv_fun := option.map e.symm,
left_inv := Ξ» x, (option.map_map _ _ _).trans $
e.symm_comp_self.symm βΈ congr_fun option.map_id x,
right_inv := Ξ» x, (option.map_map _ _ _).trans $
e.self_comp_symm.symm βΈ congr_fun option.map_id x }
@[simp] lemma option_congr_refl : option_congr (equiv.refl Ξ±) = equiv.refl _ :=
ext $ congr_fun option.map_id
@[simp] lemma option_congr_symm (e : Ξ± β Ξ²) : (option_congr e).symm = option_congr e.symm := rfl
@[simp] lemma option_congr_trans (eβ : Ξ± β Ξ²) (eβ : Ξ² β Ξ³) :
(option_congr eβ).trans (option_congr eβ) = option_congr (eβ.trans eβ) :=
ext $ option.map_map _ _
/-- When `Ξ±` and `Ξ²` are in the same universe, this is the same as the result of
`equiv_functor.map_equiv`. -/
lemma option_congr_eq_equiv_function_map_equiv {Ξ± Ξ² : Type*} (e : Ξ± β Ξ²) :
option_congr e = equiv_functor.map_equiv option e := rfl
end option_congr
section remove_none
variables (e : option Ξ± β option Ξ²)
private def remove_none_aux (x : Ξ±) : Ξ² :=
if h : (e (some x)).is_some
then option.get h
else option.get $ show (e none).is_some, from
begin
rw βoption.ne_none_iff_is_some,
intro hn,
rw [option.not_is_some_iff_eq_none, βhn] at h,
simpa only using e.injective h,
end
private lemma remove_none_aux_some {x : Ξ±} (h : β x', e (some x) = some x') :
some (remove_none_aux e x) = e (some x) :=
by simp [remove_none_aux, option.is_some_iff_exists.mpr h]
private lemma remove_none_aux_none {x : Ξ±} (h : e (some x) = none) :
some (remove_none_aux e x) = e none :=
by simp [remove_none_aux, option.not_is_some_iff_eq_none.mpr h]
private lemma remove_none_aux_inv (x : Ξ±) : remove_none_aux e.symm (remove_none_aux e x) = x :=
option.some_injective _ begin
cases h1 : e.symm (some (remove_none_aux e x)); cases h2 : (e (some x)),
{ rw remove_none_aux_none _ h1,
exact (e.eq_symm_apply.mpr h2).symm },
{ rw remove_none_aux_some _ β¨_, h2β© at h1,
simpa using h1, },
{ rw remove_none_aux_none _ h2 at h1,
simpa using h1, },
{ rw remove_none_aux_some _ β¨_, h1β©,
rw remove_none_aux_some _ β¨_, h2β©,
simp },
end
/-- Given an equivalence between two `option` types, eliminate `none` from that equivalence by
mapping `e.symm none` to `e none`. -/
def remove_none : Ξ± β Ξ² :=
{ to_fun := remove_none_aux e,
inv_fun := remove_none_aux e.symm,
left_inv := remove_none_aux_inv e,
right_inv := remove_none_aux_inv e.symm, }
@[simp]
lemma remove_none_symm : (remove_none e).symm = remove_none e.symm := rfl
lemma remove_none_some {x : Ξ±} (h : β x', e (some x) = some x') :
some (remove_none e x) = e (some x) := remove_none_aux_some e h
lemma remove_none_none {x : Ξ±} (h : e (some x) = none) :
some (remove_none e x) = e none := remove_none_aux_none e h
@[simp] lemma option_symm_apply_none_iff : e.symm none = none β e none = none :=
β¨Ξ» h, by simpa using (congr_arg e h).symm, Ξ» h, by simpa using (congr_arg e.symm h).symmβ©
lemma some_remove_none_iff {x : Ξ±} :
some (remove_none e x) = e none β e.symm none = some x :=
begin
cases h : e (some x) with a,
{ rw remove_none_none _ h,
simpa using (congr_arg e.symm h).symm },
{ rw remove_none_some _ β¨a, hβ©,
have := (congr_arg e.symm h),
rw [symm_apply_apply] at this,
simp only [false_iff, apply_eq_iff_eq],
simp [this] }
end
@[simp]
lemma remove_none_option_congr (e : Ξ± β Ξ²) : remove_none e.option_congr = e :=
equiv.ext $ Ξ» x, option.some_injective _ $ remove_none_some _ β¨e x, by simp [equiv_functor.map]β©
end remove_none
lemma option_congr_injective : function.injective (option_congr : Ξ± β Ξ² β option Ξ± β option Ξ²) :=
function.left_inverse.injective remove_none_option_congr
/-- Equivalences between `option Ξ±` and `Ξ²` that send `none` to `x` are equivalent to
equivalences between `Ξ±` and `{y : Ξ² // y β x}`. -/
def option_subtype [decidable_eq Ξ²] (x : Ξ²) :
{e : option Ξ± β Ξ² // e none = x} β (Ξ± β {y : Ξ² // y β x}) :=
{ to_fun := Ξ» e,
{ to_fun := Ξ» a, β¨e a, ((equiv_like.injective _).ne_iff' e.property).2 (some_ne_none _)β©,
inv_fun := Ξ» b, get (ne_none_iff_is_some.1 (((equiv_like.injective _).ne_iff'
(((apply_eq_iff_eq_symm_apply _).1 e.property).symm)).2 b.property)),
left_inv := Ξ» a, begin
rw [βsome_inj, some_get, βcoe_def],
exact symm_apply_apply (e : option Ξ± β Ξ²) a
end,
right_inv := Ξ» b, begin
ext,
simp,
exact apply_symm_apply _ _
end },
inv_fun := Ξ» e,
β¨{ to_fun := Ξ» a, cases_on' a x (coe β e),
inv_fun := Ξ» b, if h : b = x then none else e.symm β¨b, hβ©,
left_inv := Ξ» a, begin
cases a, { simp },
simp only [cases_on'_some, function.comp_app, subtype.coe_eta, symm_apply_apply,
dite_eq_ite],
exact if_neg (e a).property
end,
right_inv := Ξ» b, begin
by_cases h : b = x;
simp [h]
end},
rflβ©,
left_inv := Ξ» e, begin
ext a,
cases a,
{ simpa using e.property.symm },
{ simpa }
end,
right_inv := Ξ» e, begin
ext a,
refl
end }
@[simp] lemma option_subtype_apply_apply [decidable_eq Ξ²] (x : Ξ²)
(e : {e : option Ξ± β Ξ² // e none = x}) (a : Ξ±) (h) :
option_subtype x e a = β¨(e : option Ξ± β Ξ²) a, hβ© :=
rfl
@[simp] lemma coe_option_subtype_apply_apply [decidable_eq Ξ²] (x : Ξ²)
(e : {e : option Ξ± β Ξ² // e none = x}) (a : Ξ±) :
β(option_subtype x e a) = (e : option Ξ± β Ξ²) a :=
rfl
@[simp] lemma option_subtype_apply_symm_apply [decidable_eq Ξ²] (x : Ξ²)
(e : {e : option Ξ± β Ξ² // e none = x}) (b : {y : Ξ² // y β x}) :
β((option_subtype x e).symm b) = (e : option Ξ± β Ξ²).symm b :=
begin
dsimp only [option_subtype],
simp
end
@[simp] lemma option_subtype_symm_apply_apply_coe [decidable_eq Ξ²] (x : Ξ²)
(e : Ξ± β {y : Ξ² // y β x}) (a : Ξ±) : (option_subtype x).symm e a = e a :=
rfl
@[simp] lemma option_subtype_symm_apply_apply_some [decidable_eq Ξ²] (x : Ξ²)
(e : Ξ± β {y : Ξ² // y β x}) (a : Ξ±) : (option_subtype x).symm e (some a) = e a :=
rfl
@[simp] lemma option_subtype_symm_apply_apply_none [decidable_eq Ξ²] (x : Ξ²)
(e : Ξ± β {y : Ξ² // y β x}) : (option_subtype x).symm e none = x :=
rfl
@[simp] lemma option_subtype_symm_apply_symm_apply [decidable_eq Ξ²] (x : Ξ²)
(e : Ξ± β {y : Ξ² // y β x}) (b : {y : Ξ² // y β x}) :
((option_subtype x).symm e : option Ξ± β Ξ²).symm b = e.symm b :=
begin
simp only [option_subtype, coe_fn_symm_mk, subtype.coe_mk, subtype.coe_eta, dite_eq_ite,
ite_eq_right_iff],
exact Ξ» h, false.elim (b.property h),
end
end equiv
|
52b922dbd9492733de65133210dc0adcd41aca97 | 853df553b1d6ca524e3f0a79aedd32dde5d27ec3 | /src/geometry/manifold/real_instances.lean | 2bd9766b31863225cf990abd1fe155115764b833 | [
"Apache-2.0"
] | permissive | DanielFabian/mathlib | efc3a50b5dde303c59eeb6353ef4c35a345d7112 | f520d07eba0c852e96fe26da71d85bf6d40fcc2a | refs/heads/master | 1,668,739,922,971 | 1,595,201,756,000 | 1,595,201,756,000 | 279,469,476 | 0 | 0 | null | 1,594,696,604,000 | 1,594,696,604,000 | null | UTF-8 | Lean | false | false | 15,598 | lean | /-
Copyright (c) 2019 SΓ©bastien GouΓ«zel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: SΓ©bastien GouΓ«zel
-/
import geometry.manifold.smooth_manifold_with_corners
import linear_algebra.finite_dimensional
import analysis.normed_space.real_inner_product
/-!
# Constructing examples of manifolds over β
We introduce the necessary bits to be able to define manifolds modelled over `β^n`, boundaryless
or with boundary or with corners. As a concrete example, we construct explicitly the manifold with
boundary structure on the real interval `[x, y]`.
More specifically, we introduce
* `model_with_corners β (euclidean_space (fin n)) (euclidean_half_space n)` for the model space used
to define `n`-dimensional real manifolds with boundary
* `model_with_corners β (euclidean_space (fin n)) (euclidean_quadrant n)` for the model space used
to define `n`-dimensional real manifolds with corners
## Notations
In the locale `manifold`, we introduce the notations
* `π‘ n` for the identity model with corners on `euclidean_space (fin n)`
* `π‘β n` for `model_with_corners β (euclidean_space (fin n)) (euclidean_half_space n)`.
For instance, if a manifold `M` is boundaryless, smooth and modelled on `euclidean_space (fin m)`,
and `N` is smooth with boundary modelled on `euclidean_half_space n`, and `f : M β N` is a smooth
map, then the derivative of `f` can be written simply as `mfderiv (π‘ m) (π‘β n) f` (as to why the
model with corners can not be implicit, see the discussion in `smooth_manifold_with_corners.lean`).
## Implementation notes
The manifold structure on the interval `[x, y] = Icc x y` requires the assumption `x < y` as a
typeclass. We provide it as `[fact (x < y)]`.
-/
noncomputable theory
open set
/--
The half-space in `β^n`, used to model manifolds with boundary. We only define it when
`1 β€ n`, as the definition only makes sense in this case.
-/
def euclidean_half_space (n : β) [has_zero (fin n)] : Type :=
{x : euclidean_space (fin n) // 0 β€ x 0}
/--
The quadrant in `β^n`, used to model manifolds with corners, made of all vectors with nonnegative
coordinates.
-/
def euclidean_quadrant (n : β) : Type := {x : euclidean_space (fin n) // βi:fin n, 0 β€ x i}
section
/- Register class instances for euclidean half-space and quadrant, that can not be noticed
without the following reducibility attribute (which is only set in this section). -/
local attribute [reducible] euclidean_half_space euclidean_quadrant
variable {n : β}
instance [has_zero (fin n)] : topological_space (euclidean_half_space n) := by apply_instance
instance : topological_space (euclidean_quadrant n) := by apply_instance
instance [has_zero (fin n)] : inhabited (euclidean_half_space n) := β¨β¨0, le_refl _β©β©
instance : inhabited (euclidean_quadrant n) := β¨β¨0, Ξ» i, le_refl _β©β©
lemma range_half_space (n : β) [has_zero (fin n)] :
range (Ξ»x : euclidean_half_space n, x.val) = {y | 0 β€ y 0} :=
by simp
lemma range_quadrant (n : β) :
range (Ξ»x : euclidean_quadrant n, x.val) = {y | βi:fin n, 0 β€ y i} :=
by simp
end
/--
Definition of the model with corners `(euclidean_space (fin n), euclidean_half_space n)`, used as a
model for manifolds with boundary. In the locale `manifold`, use the shortcut `π‘β n`.
-/
def model_with_corners_euclidean_half_space (n : β) [has_zero (fin n)] :
model_with_corners β (euclidean_space (fin n)) (euclidean_half_space n) :=
{ to_fun := Ξ»x, x.val,
inv_fun := Ξ»x, β¨Ξ»i, if h : i = 0 then max (x i) 0 else x i, by simp [le_refl]β©,
source := univ,
target := range (Ξ»x : euclidean_half_space n, x.val),
map_source' := Ξ»x hx, by simpa only [subtype.range_val] using x.property,
map_target' := Ξ»x hx, mem_univ _,
left_inv' := Ξ»β¨xval, xpropβ© hx, begin
rw subtype.mk_eq_mk,
ext1 i,
by_cases hi : i = 0,
{ rw hi, simp only [xprop, dif_pos, max_eq_left] },
{ simp only [hi, dif_neg, not_false_iff] }
end,
right_inv' := Ξ»x hx, begin
simp only [mem_set_of_eq, subtype.range_val_subtype] at hx,
ext1 i,
by_cases hi : i = 0,
{ rw hi, simp only [hx, dif_pos, max_eq_left] } ,
{ simp only [hi, dif_neg, not_false_iff] }
end,
source_eq := rfl,
unique_diff' := begin
/- To check that the half-space has the unique differentiability property, we use the criterion
`unique_diff_on_convex`: it suffices to check that it is convex and with nonempty interior. -/
rw range_half_space,
apply unique_diff_on_convex,
show convex {y : euclidean_space (fin n) | 0 β€ y 0},
{ assume x y hx hy a b ha hb hab,
simpa only [add_zero] using add_le_add (mul_nonneg ha hx) (mul_nonneg hb hy) },
show (interior {y : euclidean_space (fin n) | 0 β€ y 0}).nonempty,
{ use (Ξ»i, 1),
rw mem_interior,
refine β¨(pi (univ : set (fin n)) (Ξ»i, (Ioi 0 : set β))), _,
is_open_set_pi finite_univ (Ξ»a ha, is_open_Ioi), _β©,
{ assume x hx,
simp only [pi, forall_prop_of_true, mem_univ, mem_Ioi] at hx,
exact le_of_lt (hx 0) },
{ simp only [pi, forall_prop_of_true, mem_univ, mem_Ioi],
assume i,
exact zero_lt_one } }
end,
continuous_to_fun := continuous_subtype_val,
continuous_inv_fun := begin
apply continuous_subtype_mk,
apply continuous_pi,
assume i,
by_cases h : i = 0,
{ rw h,
simp only [dif_pos],
have : continuous (Ξ»x:β, max x 0) := continuous_id.max continuous_const,
exact this.comp (continuous_apply 0) },
{ simp only [h, dif_neg, not_false_iff],
exact continuous_apply i }
end }
/--
Definition of the model with corners `(euclidean_space (fin n), euclidean_quadrant n)`, used as a
model for manifolds with corners -/
def model_with_corners_euclidean_quadrant (n : β) :
model_with_corners β (euclidean_space (fin n)) (euclidean_quadrant n) :=
{ to_fun := Ξ»x, x.val,
inv_fun := Ξ»x, β¨Ξ»i, max (x i) 0, Ξ»i, by simp only [le_refl, or_true, le_max_iff]β©,
source := univ,
target := range (Ξ»x : euclidean_quadrant n, x.val),
map_source' := Ξ»x hx, by simpa only [subtype.range_val] using x.property,
map_target' := Ξ»x hx, mem_univ _,
left_inv' := Ξ»β¨xval, xpropβ© hx, begin
rw subtype.mk_eq_mk,
ext1 i,
simp only [xprop i, max_eq_left]
end,
right_inv' := Ξ»x hx, begin
rw range_quadrant at hx,
ext1 i,
simp only [hx i, max_eq_left]
end,
source_eq := rfl,
unique_diff' := begin
/- To check that the quadrant has the unique differentiability property, we use the criterion
`unique_diff_on_convex`: it suffices to check that it is convex and with nonempty interior. -/
rw range_quadrant,
apply unique_diff_on_convex,
show convex {y : euclidean_space (fin n) | β (i : fin n), 0 β€ y i},
{ assume x y hx hy a b ha hb hab i,
simpa only [add_zero] using add_le_add (mul_nonneg ha (hx i)) (mul_nonneg hb (hy i)) },
show (interior {y : euclidean_space (fin n) | β (i : fin n), 0 β€ y i}).nonempty,
{ use (Ξ»i, 1),
rw mem_interior,
refine β¨(pi (univ : set (fin n)) (Ξ»i, (Ioi 0 : set β))), _,
is_open_set_pi finite_univ (Ξ»a ha, is_open_Ioi), _β©,
{ assume x hx i,
simp only [pi, forall_prop_of_true, mem_univ, mem_Ioi] at hx,
exact le_of_lt (hx i) },
{ simp only [pi, forall_prop_of_true, mem_univ, mem_Ioi],
assume i,
exact zero_lt_one } }
end,
continuous_to_fun := continuous_subtype_val,
continuous_inv_fun := begin
apply continuous_subtype_mk,
apply continuous_pi,
assume i,
have : continuous (Ξ»x:β, max x 0) := continuous.max continuous_id continuous_const,
exact this.comp (continuous_apply i)
end }
localized "notation `π‘ `n := model_with_corners_self β (euclidean_space (fin n))" in manifold
localized "notation `π‘β `n := model_with_corners_euclidean_half_space n" in manifold
/--
The left chart for the topological space `[x, y]`, defined on `[x,y)` and sending `x` to `0` in
`euclidean_half_space 1`.
-/
def Icc_left_chart (x y : β) [fact (x < y)] :
local_homeomorph (Icc x y) (euclidean_half_space 1) :=
{ source := {z : Icc x y | z.val < y},
target := {z : euclidean_half_space 1 | z.val 0 < y - x},
to_fun := Ξ»(z : Icc x y), β¨Ξ»i, z.val - x, sub_nonneg.mpr z.property.1β©,
inv_fun := Ξ»z, β¨min (z.val 0 + x) y, by simp [le_refl, z.prop, le_of_lt βΉx < yβΊ]β©,
map_source' := by simp only [imp_self, sub_lt_sub_iff_right, mem_set_of_eq, forall_true_iff],
map_target' :=
by { simp only [min_lt_iff, mem_set_of_eq], assume z hz, left,
dsimp [-subtype.val_eq_coe] at hz, linarith },
left_inv' := begin
rintros β¨z, hzβ© h'z,
simp only [mem_set_of_eq, mem_Icc] at hz h'z,
simp only [hz, min_eq_left, sub_add_cancel]
end,
right_inv' := begin
rintros β¨z, hzβ© h'z,
rw subtype.mk_eq_mk,
funext,
dsimp at hz h'z,
have A : x + z 0 β€ y, by linarith,
rw subsingleton.elim i 0,
simp only [A, add_comm, add_sub_cancel', min_eq_left],
end,
open_source := begin
have : is_open {z : β | z < y} := is_open_Iio,
exact continuous_subtype_val _ this
end,
open_target := begin
have : is_open {z : β | z < y - x} := is_open_Iio,
have : is_open {z : euclidean_space (fin 1) | z 0 < y - x} :=
@continuous_apply (fin 1) (Ξ» _, β) _ 0 _ this,
exact continuous_subtype_val _ this
end,
continuous_to_fun := begin
apply continuous.continuous_on,
apply continuous_subtype_mk,
have : continuous (Ξ» (z : β) (i : fin 1), z - x) :=
continuous.sub (continuous_pi $ Ξ»i, continuous_id) continuous_const,
exact this.comp continuous_subtype_val,
end,
continuous_inv_fun := begin
apply continuous.continuous_on,
apply continuous_subtype_mk,
have A : continuous (Ξ» z : β, min (z + x) y) :=
(continuous_id.add continuous_const).min continuous_const,
have B : continuous (Ξ»z : euclidean_space (fin 1), z 0) := continuous_apply 0,
exact (A.comp B).comp continuous_subtype_val
end }
/--
The right chart for the topological space `[x, y]`, defined on `(x,y]` and sending `y` to `0` in
`euclidean_half_space 1`.
-/
def Icc_right_chart (x y : β) [fact (x < y)] :
local_homeomorph (Icc x y) (euclidean_half_space 1) :=
{ source := {z : Icc x y | x < z.val},
target := {z : euclidean_half_space 1 | z.val 0 < y - x},
to_fun := Ξ»(z : Icc x y), β¨Ξ»i, y - z.val, sub_nonneg.mpr z.property.2β©,
inv_fun := Ξ»z,
β¨max (y - z.val 0) x, by simp [le_refl, z.prop, le_of_lt βΉx < yβΊ, sub_eq_add_neg]β©,
map_source' := by simp only [imp_self, mem_set_of_eq, sub_lt_sub_iff_left, forall_true_iff],
map_target' :=
by { simp only [lt_max_iff, mem_set_of_eq], assume z hz, left,
dsimp [-subtype.val_eq_coe] at hz, linarith },
left_inv' := begin
rintros β¨z, hzβ© h'z,
simp only [mem_set_of_eq, mem_Icc] at hz h'z,
simp only [hz, sub_eq_add_neg, max_eq_left, add_add_neg_cancel'_right, neg_add_rev, neg_neg]
end,
right_inv' := begin
rintros β¨z, hzβ© h'z,
rw subtype.mk_eq_mk,
funext,
dsimp at hz h'z,
have A : x β€ y - z 0, by linarith,
rw subsingleton.elim i 0,
simp only [A, sub_sub_cancel, max_eq_left],
end,
open_source := begin
have : is_open {z : β | x < z} := is_open_Ioi,
exact continuous_subtype_val _ this
end,
open_target := begin
have : is_open {z : β | z < y - x} := is_open_Iio,
have : is_open {z : euclidean_space (fin 1) | z 0 < y - x} :=
@continuous_apply (fin 1) (Ξ» _, β) _ 0 _ this,
exact continuous_subtype_val _ this
end,
continuous_to_fun := begin
apply continuous.continuous_on,
apply continuous_subtype_mk,
have : continuous (Ξ» (z : β) (i : fin 1), y - z) :=
continuous_const.sub (continuous_pi (Ξ»i, continuous_id)),
exact this.comp continuous_subtype_val,
end,
continuous_inv_fun := begin
apply continuous.continuous_on,
apply continuous_subtype_mk,
have A : continuous (Ξ» z : β, max (y - z) x) :=
(continuous_const.sub continuous_id).max continuous_const,
have B : continuous (Ξ»z : euclidean_space (fin 1), z 0) := continuous_apply 0,
exact (A.comp B).comp continuous_subtype_val
end }
/--
Charted space structure on `[x, y]`, using only two charts tkaing values in `euclidean_half_space 1`.
-/
instance Icc_manifold (x y : β) [fact (x < y)] : charted_space (euclidean_half_space 1) (Icc x y) :=
{ atlas := {Icc_left_chart x y, Icc_right_chart x y},
chart_at := Ξ»z, if z.val < y then Icc_left_chart x y else Icc_right_chart x y,
mem_chart_source := Ξ»z, begin
by_cases h' : z.val < y,
{ simp only [h', if_true],
exact h' },
{ simp only [h', if_false],
apply lt_of_lt_of_le βΉx < yβΊ,
simpa only [not_lt] using h'}
end,
chart_mem_atlas := Ξ»z, by { by_cases h' : z.val < y; simp [h'] } }
/--
The manifold structure on `[x, y]` is smooth.
-/
instance Icc_smooth_manifold (x y : β) [fact (x < y)] :
smooth_manifold_with_corners (π‘β 1) (Icc x y) :=
begin
have M : times_cont_diff_on β β€ (Ξ»z : euclidean_space (fin 1), - z + (Ξ»i, y - x)) univ,
{ rw times_cont_diff_on_univ,
exact times_cont_diff_id.neg.add times_cont_diff_const },
haveI : has_groupoid (Icc x y) (times_cont_diff_groupoid β€ (π‘β 1)) :=
begin
apply has_groupoid_of_pregroupoid,
assume e e' he he',
simp only [atlas, mem_singleton_iff, mem_insert_iff] at he he',
/- We need to check that any composition of two charts gives a `C^β` function. Each chart can be
either the left chart or the right chart, leaving 4 possibilities that we handle successively.
-/
rcases he with rfl | rfl; rcases he' with rfl | rfl,
{ -- `e = left chart`, `e' = left chart`
refine ((mem_groupoid_of_pregroupoid _ _).mpr _).1,
exact symm_trans_mem_times_cont_diff_groupoid _ _ _ },
{ -- `e = left chart`, `e' = right chart`
apply M.congr_mono _ (subset_univ _),
assume z hz,
simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, dif_pos,
lt_add_iff_pos_left, max_lt_iff, lt_min_iff, sub_pos, lt_max_iff, subtype.range_val]
with mfld_simps at hz,
have A : 0 β€ z 0 := hz.2,
have B : z 0 + x β€ y, by { have := hz.1.1.1, linarith },
ext i,
rw subsingleton.elim i 0,
simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, A, B,
pi_Lp.add_apply, dif_pos, min_eq_left, max_eq_left, pi_Lp.neg_apply] with mfld_simps,
ring },
{ -- `e = right chart`, `e' = left chart`
apply M.congr_mono _ (subset_univ _),
assume z hz,
simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, dif_pos,
max_lt_iff, sub_pos, subtype.range_val] with mfld_simps at hz,
have A : 0 β€ z 0 := hz.2,
have B : x β€ y - z 0, by { have := hz.1.1.1, dsimp at this, linarith },
ext i,
rw subsingleton.elim i 0,
simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, A, B,
pi_Lp.add_apply, dif_pos, max_eq_left, pi_Lp.neg_apply] with mfld_simps,
ring },
{ -- `e = right chart`, `e' = right chart`
refine ((mem_groupoid_of_pregroupoid _ _).mpr _).1,
exact symm_trans_mem_times_cont_diff_groupoid _ _ _ }
end,
constructor
end
|
6848c8fc942ed0bc7cfae9bb6b33e290e098f027 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/lazy_list/basic.lean | 2ffe03b984210931f9789ee0e6638b922b970034 | [
"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 | 7,707 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import control.traversable.equiv
import control.traversable.instances
import data.lazy_list
/-!
## Definitions on lazy lists
This file contains various definitions and proofs on lazy lists.
TODO: move the `lazy_list.lean` file from core to mathlib.
-/
universes u
namespace thunk
/-- Creates a thunk with a (non-lazy) constant value. -/
def mk {Ξ±} (x : Ξ±) : thunk Ξ± := Ξ» _, x
instance {Ξ± : Type u} [decidable_eq Ξ±] : decidable_eq (thunk Ξ±) | a b :=
have a = b β a () = b (), from β¨by cc, by intro; ext x; cases x; assumptionβ©,
by rw this; apply_instance
end thunk
namespace lazy_list
open function
/-- Isomorphism between strict and lazy lists. -/
def list_equiv_lazy_list (Ξ± : Type*) : list Ξ± β lazy_list Ξ± :=
{ to_fun := lazy_list.of_list,
inv_fun := lazy_list.to_list,
right_inv := by { intro, induction x, refl, simp! [*],
ext, cases x, refl },
left_inv := by { intro, induction x, refl, simp! [*] } }
instance {Ξ± : Type u} [decidable_eq Ξ±] : decidable_eq (lazy_list Ξ±)
| nil nil := is_true rfl
| (cons x xs) (cons y ys) :=
if h : x = y then
match decidable_eq (xs ()) (ys ()) with
| is_false h2 := is_false (by intro; cc)
| is_true h2 :=
have xs = ys, by ext u; cases u; assumption,
is_true (by cc)
end
else
is_false (by intro; cc)
| nil (cons _ _) := is_false (by cc)
| (cons _ _) nil := is_false (by cc)
/-- Traversal of lazy lists using an applicative effect. -/
protected def traverse {m : Type u β Type u} [applicative m] {Ξ± Ξ² : Type u}
(f : Ξ± β m Ξ²) : lazy_list Ξ± β m (lazy_list Ξ²)
| lazy_list.nil := pure lazy_list.nil
| (lazy_list.cons x xs) := lazy_list.cons <$> f x <*> (thunk.mk <$> traverse (xs ()))
instance : traversable lazy_list :=
{ map := @lazy_list.traverse id _,
traverse := @lazy_list.traverse }
instance : is_lawful_traversable lazy_list :=
begin
apply equiv.is_lawful_traversable' list_equiv_lazy_list;
intros ; resetI; ext,
{ induction x, refl,
simp! [equiv.map,functor.map] at *,
simp [*], refl, },
{ induction x, refl,
simp! [equiv.map,functor.map_const] at *,
simp [*], refl, },
{ induction x,
{ simp! [traversable.traverse,equiv.traverse] with functor_norm, refl },
simp! [equiv.map,functor.map_const,traversable.traverse] at *, rw x_ih,
dsimp [list_equiv_lazy_list,equiv.traverse,to_list,traversable.traverse,list.traverse],
simp! with functor_norm, refl },
end
/-- `init xs`, if `xs` non-empty, drops the last element of the list.
Otherwise, return the empty list. -/
def init {Ξ±} : lazy_list Ξ± β lazy_list Ξ±
| lazy_list.nil := lazy_list.nil
| (lazy_list.cons x xs) :=
let xs' := xs () in
match xs' with
| lazy_list.nil := lazy_list.nil
| (lazy_list.cons _ _) := lazy_list.cons x (init xs')
end
/-- Return the first object contained in the list that satisfies
predicate `p` -/
def find {Ξ±} (p : Ξ± β Prop) [decidable_pred p] : lazy_list Ξ± β option Ξ±
| nil := none
| (cons h t) := if p h then some h else find (t ())
/-- `interleave xs ys` creates a list where elements of `xs` and `ys` alternate. -/
def interleave {Ξ±} : lazy_list Ξ± β lazy_list Ξ± β lazy_list Ξ±
| lazy_list.nil xs := xs
| a@(lazy_list.cons x xs) lazy_list.nil := a
| (lazy_list.cons x xs) (lazy_list.cons y ys) :=
lazy_list.cons x (lazy_list.cons y (interleave (xs ()) (ys ())))
/-- `interleave_all (xs::ys::zs::xss)` creates a list where elements of `xs`, `ys`
and `zs` and the rest alternate. Every other element of the resulting list is taken from
`xs`, every fourth is taken from `ys`, every eighth is taken from `zs` and so on. -/
def interleave_all {Ξ±} : list (lazy_list Ξ±) β lazy_list Ξ±
| [] := lazy_list.nil
| (x :: xs) := interleave x (interleave_all xs)
/-- Monadic bind operation for `lazy_list`. -/
protected def bind {Ξ± Ξ²} : lazy_list Ξ± β (Ξ± β lazy_list Ξ²) β lazy_list Ξ²
| lazy_list.nil _ := lazy_list.nil
| (lazy_list.cons x xs) f := lazy_list.append (f x) (bind (xs ()) f)
/-- Reverse the order of a `lazy_list`.
It is done by converting to a `list` first because reversal involves evaluating all
the list and if the list is all evaluated, `list` is a better representation for
it than a series of thunks. -/
def reverse {Ξ±} (xs : lazy_list Ξ±) : lazy_list Ξ± :=
of_list xs.to_list.reverse
instance : monad lazy_list :=
{ pure := @lazy_list.singleton,
bind := @lazy_list.bind }
lemma append_nil {Ξ±} (xs : lazy_list Ξ±) : xs.append lazy_list.nil = xs :=
begin
induction xs, refl,
simp [lazy_list.append, xs_ih],
ext, congr,
end
lemma append_assoc {Ξ±} (xs ys zs : lazy_list Ξ±) :
(xs.append ys).append zs = xs.append (ys.append zs) :=
by induction xs; simp [append, *]
lemma append_bind {Ξ± Ξ²} (xs : lazy_list Ξ±) (ys : thunk (lazy_list Ξ±)) (f : Ξ± β lazy_list Ξ²) :
(@lazy_list.append _ xs ys).bind f = (xs.bind f).append ((ys ()).bind f) :=
by induction xs; simp [lazy_list.bind, append, *, append_assoc, append, lazy_list.bind]
instance : is_lawful_monad lazy_list :=
{ pure_bind := by { intros, apply append_nil },
bind_assoc := by { intros, dsimp [(>>=)], induction x; simp [lazy_list.bind, append_bind, *], },
id_map :=
begin
intros,
simp [(<$>)],
induction x; simp [lazy_list.bind, *, singleton, append],
ext β¨ β©, refl,
end }
/-- Try applying function `f` to every element of a `lazy_list` and
return the result of the first attempt that succeeds. -/
def mfirst {m} [alternative m] {Ξ± Ξ²} (f : Ξ± β m Ξ²) : lazy_list Ξ± β m Ξ²
| nil := failure
| (cons x xs) :=
f x <|> mfirst (xs ())
/-- Membership in lazy lists -/
protected def mem {Ξ±} (x : Ξ±) : lazy_list Ξ± β Prop
| lazy_list.nil := false
| (lazy_list.cons y ys) := x = y β¨ mem (ys ())
instance {Ξ±} : has_mem Ξ± (lazy_list Ξ±) :=
β¨ lazy_list.mem β©
instance mem.decidable {Ξ±} [decidable_eq Ξ±] (x : Ξ±) : Ξ xs : lazy_list Ξ±, decidable (x β xs)
| lazy_list.nil := decidable.false
| (lazy_list.cons y ys) :=
if h : x = y
then decidable.is_true (or.inl h)
else decidable_of_decidable_of_iff (mem.decidable (ys ())) (by simp [*, (β), lazy_list.mem])
@[simp]
lemma mem_nil {Ξ±} (x : Ξ±) : x β @lazy_list.nil Ξ± β false := iff.rfl
@[simp]
lemma mem_cons {Ξ±} (x y : Ξ±) (ys : thunk (lazy_list Ξ±)) :
x β @lazy_list.cons Ξ± y ys β x = y β¨ x β ys () := iff.rfl
theorem forall_mem_cons {Ξ±} {p : Ξ± β Prop} {a : Ξ±} {l : thunk (lazy_list Ξ±)} :
(β x β @lazy_list.cons _ a l, p x) β p a β§ β x β l (), p x :=
by simp only [has_mem.mem, lazy_list.mem, or_imp_distrib, forall_and_distrib, forall_eq]
/-! ### map for partial functions -/
/-- Partial map. If `f : Ξ a, p a β Ξ²` is a partial function defined on
`a : Ξ±` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`
but is defined only when all members of `l` satisfy `p`, using the proof
to apply `f`. -/
@[simp] def pmap {Ξ± Ξ²} {p : Ξ± β Prop} (f : Ξ a, p a β Ξ²) :
Ξ l : lazy_list Ξ±, (β a β l, p a) β lazy_list Ξ²
| lazy_list.nil H := lazy_list.nil
| (lazy_list.cons x xs) H := lazy_list.cons (f x (forall_mem_cons.1 H).1)
(pmap (xs ()) (forall_mem_cons.1 H).2)
/-- "Attach" the proof that the elements of `l` are in `l` to produce a new `lazy_list`
with the same elements but in the type `{x // x β l}`. -/
def attach {Ξ±} (l : lazy_list Ξ±) : lazy_list {x // x β l} := pmap subtype.mk l (Ξ» a, id)
instance {Ξ±} [has_repr Ξ±] : has_repr (lazy_list Ξ±) :=
β¨ Ξ» xs, repr xs.to_list β©
end lazy_list
|
bf78d679579f539e6f04be66bbad9023cd36f8dc | 38bf3fd2bb651ab70511408fcf70e2029e2ba310 | /src/data/nat/prime.lean | 5be31685ac3c85ea4dc91df964caa0a58db048a6 | [
"Apache-2.0"
] | permissive | JaredCorduan/mathlib | 130392594844f15dad65a9308c242551bae6cd2e | d5de80376088954d592a59326c14404f538050a1 | refs/heads/master | 1,595,862,206,333 | 1,570,816,457,000 | 1,570,816,457,000 | 209,134,499 | 0 | 0 | Apache-2.0 | 1,568,746,811,000 | 1,568,746,811,000 | null | UTF-8 | Lean | false | false | 18,235 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
Prime numbers.
-/
import data.nat.sqrt data.nat.gcd data.list.basic data.list.perm tactic.wlog
open bool subtype
namespace nat
open decidable
/-- `prime p` means that `p` is a prime number, that is, a natural number
at least 2 whose only divisors are `p` and `1`. -/
def prime (p : β) := 2 β€ p β§ β m β£ p, m = 1 β¨ m = p
theorem prime.two_le {p : β} : prime p β 2 β€ p := and.left
theorem prime.one_lt {p : β} : prime p β 1 < p := prime.two_le
lemma prime.ne_one {p : β} (hp : p.prime) : p β 1 :=
ne.symm $ (ne_of_lt hp.one_lt)
theorem prime_def_lt {p : β} : prime p β 2 β€ p β§ β m < p, m β£ p β m = 1 :=
and_congr_right $ Ξ» p2, forall_congr $ Ξ» m,
β¨Ξ» h l d, (h d).resolve_right (ne_of_lt l),
Ξ» h d, (decidable.lt_or_eq_of_le $
le_of_dvd (le_of_succ_le p2) d).imp_left (Ξ» l, h l d)β©
theorem prime_def_lt' {p : β} : prime p β 2 β€ p β§ β m, 2 β€ m β m < p β Β¬ m β£ p :=
prime_def_lt.trans $ and_congr_right $ Ξ» p2, forall_congr $ Ξ» m,
β¨Ξ» h m2 l d, not_lt_of_ge m2 ((h l d).symm βΈ dec_trivial),
Ξ» h l d, begin
rcases m with _|_|m,
{ rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial },
{ refl },
{ exact (h dec_trivial l).elim d }
endβ©
theorem prime_def_le_sqrt {p : β} : prime p β 2 β€ p β§
β m, 2 β€ m β m β€ sqrt p β Β¬ m β£ p :=
prime_def_lt'.trans $ and_congr_right $ Ξ» p2,
β¨Ξ» a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2,
Ξ» a, have β {m k}, m β€ k β 1 < m β p β m * k, from
Ξ» m k mk m1 e, a m m1
(le_sqrt.2 (e.symm βΈ mul_le_mul_left m mk)) β¨k, eβ©,
Ξ» m m2 l β¨k, eβ©, begin
cases (le_total m k) with mk km,
{ exact this mk m2 e },
{ rw [mul_comm] at e,
refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e,
rwa [one_mul, β e] }
endβ©
/--
This instance is slower than the instance `decidable_prime` defined below,
but has the advantage that it works in the kernel.
If you need to prove that a particular number is prime, in any case
you should not use `dec_trivial`, but rather `by norm_num`, which is
much faster.
-/
def decidable_prime_1 (p : β) : decidable (prime p) :=
decidable_of_iff' _ prime_def_lt'
local attribute [instance] decidable_prime_1
lemma prime.ne_zero {n : β} (h : prime n) : n β 0 :=
assume hn : n = 0,
have h2 : Β¬ prime 0, from dec_trivial,
h2 (hn βΈ h)
theorem prime.pos {p : β} (pp : prime p) : 0 < p :=
lt_of_succ_lt pp.one_lt
theorem not_prime_zero : Β¬ prime 0 := dec_trivial
theorem not_prime_one : Β¬ prime 1 := dec_trivial
theorem prime_two : prime 2 := dec_trivial
theorem prime_three : prime 3 := dec_trivial
theorem prime.pred_pos {p : β} (pp : prime p) : 0 < pred p :=
lt_pred_iff.2 pp.one_lt
theorem succ_pred_prime {p : β} (pp : prime p) : succ (pred p) = p :=
succ_pred_eq_of_pos pp.pos
theorem dvd_prime {p m : β} (pp : prime p) : m β£ p β m = 1 β¨ m = p :=
β¨Ξ» d, pp.2 m d, Ξ» h, h.elim (Ξ» e, e.symm βΈ one_dvd _) (Ξ» e, e.symm βΈ dvd_refl _)β©
theorem dvd_prime_two_le {p m : β} (pp : prime p) (H : 2 β€ m) : m β£ p β m = p :=
(dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H
theorem prime.not_dvd_one {p : β} (pp : prime p) : Β¬ p β£ 1
| d := (not_le_of_gt pp.one_lt) $ le_of_dvd dec_trivial d
theorem not_prime_mul {a b : β} (a1 : 1 < a) (b1 : 1 < b) : Β¬ prime (a * b) :=
Ξ» h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $
by simpa using (dvd_prime_two_le h a1).1 (dvd_mul_right _ _)
section min_fac
private lemma min_fac_lemma (n k : β) (h : Β¬ n < k * k) :
sqrt n - k < sqrt n + 2 - k :=
(nat.sub_lt_sub_right_iff $ le_sqrt.2 $ le_of_not_gt h).2 $
nat.lt_add_of_pos_right dec_trivial
def min_fac_aux (n : β) : β β β | k :=
if h : n < k * k then n else
if k β£ n then k else
have _, from min_fac_lemma n k h,
min_fac_aux (k + 2)
using_well_founded {rel_tac :=
Ξ» _ _, `[exact β¨_, measure_wf (Ξ» k, sqrt n + 2 - k)β©]}
/-- Returns the smallest prime factor of `n β 1`. -/
def min_fac : β β β
| 0 := 2
| 1 := 1
| (n+2) := if 2 β£ n then 2 else min_fac_aux (n + 2) 3
@[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl
@[simp] theorem min_fac_one : min_fac 1 = 1 := rfl
theorem min_fac_eq : β n, min_fac n = if 2 β£ n then 2 else min_fac_aux n 3
| 0 := rfl
| 1 := by simp [show 2β 1, from dec_trivial]; rw min_fac_aux; refl
| (n+2) :=
have 2 β£ n + 2 β 2 β£ n, from
(nat.dvd_add_iff_left (by refl)).symm,
by simp [min_fac, this]; congr
private def min_fac_prop (n k : β) :=
2 β€ k β§ k β£ n β§ β m, 2 β€ m β m β£ n β k β€ m
theorem min_fac_aux_has_prop {n : β} (n2 : 2 β€ n) (nd2 : Β¬ 2 β£ n) :
β k i, k = 2*i+3 β (β m, 2 β€ m β m β£ n β k β€ m) β min_fac_prop n (min_fac_aux n k)
| k := Ξ» i e a, begin
rw min_fac_aux,
by_cases h : n < k*k; simp [h],
{ have pp : prime n :=
prime_def_le_sqrt.2 β¨n2, Ξ» m m2 l d,
not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)β©,
from β¨n2, dvd_refl _, Ξ» m m2 d, le_of_eq
((dvd_prime_two_le pp m2).1 d).symmβ© },
have k2 : 2 β€ k, { subst e, exact dec_trivial },
by_cases dk : k β£ n; simp [dk],
{ exact β¨k2, dk, aβ© },
{ refine have _, from min_fac_lemma n k h,
min_fac_aux_has_prop (k+2) (i+1)
(by simp [e, left_distrib]) (Ξ» m m2 d, _),
cases nat.eq_or_lt_of_le (a m m2 d) with me ml,
{ subst me, contradiction },
apply (nat.eq_or_lt_of_le ml).resolve_left, intro me,
rw [β me, e] at d, change 2 * (i + 2) β£ n at d,
have := dvd_of_mul_right_dvd d, contradiction }
end
using_well_founded {rel_tac :=
Ξ» _ _, `[exact β¨_, measure_wf (Ξ» k, sqrt n + 2 - k)β©]}
theorem min_fac_has_prop {n : β} (n1 : n β 1) :
min_fac_prop n (min_fac n) :=
begin
by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]},
have n2 : 2 β€ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial },
simp [min_fac_eq],
by_cases d2 : 2 β£ n; simp [d2],
{ exact β¨le_refl _, d2, Ξ» k k2 d, k2β© },
{ refine min_fac_aux_has_prop n2 d2 3 0 rfl
(Ξ» m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)),
exact Ξ» e, e.symm βΈ d }
end
theorem min_fac_dvd (n : β) : min_fac n β£ n :=
by by_cases n1 : n = 1;
[exact n1.symm βΈ dec_trivial, exact (min_fac_has_prop n1).2.1]
theorem min_fac_prime {n : β} (n1 : n β 1) : prime (min_fac n) :=
let β¨f2, fd, aβ© := min_fac_has_prop n1 in
prime_def_lt'.2 β¨f2, Ξ» m m2 l d, not_le_of_gt l (a m m2 (dvd_trans d fd))β©
theorem min_fac_le_of_dvd {n : β} : β {m : β}, 2 β€ m β m β£ n β min_fac n β€ m :=
by by_cases n1 : n = 1;
[exact Ξ» m m2 d, n1.symm βΈ le_trans dec_trivial m2,
exact (min_fac_has_prop n1).2.2]
theorem min_fac_pos (n : β) : 0 < min_fac n :=
by by_cases n1 : n = 1;
[exact n1.symm βΈ dec_trivial, exact (min_fac_prime n1).pos]
theorem min_fac_le {n : β} (H : 0 < n) : min_fac n β€ n :=
le_of_dvd H (min_fac_dvd n)
theorem prime_def_min_fac {p : β} : prime p β 2 β€ p β§ min_fac p = p :=
β¨Ξ» pp, β¨pp.two_le,
let β¨f2, fd, aβ© := min_fac_has_prop $ ne_of_gt pp.one_lt in
((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)β©,
Ξ» β¨p2, eβ©, e βΈ min_fac_prime (ne_of_gt p2)β©
/--
This instance is faster in the virtual machine than `decidable_prime_1`,
but slower in the kernel.
If you need to prove that a particular number is prime, in any case
you should not use `dec_trivial`, but rather `by norm_num`, which is
much faster.
-/
instance decidable_prime (p : β) : decidable (prime p) :=
decidable_of_iff' _ prime_def_min_fac
theorem not_prime_iff_min_fac_lt {n : β} (n2 : 2 β€ n) : Β¬ prime n β min_fac n < n :=
(not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $
(lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm
end min_fac
theorem exists_dvd_of_not_prime {n : β} (n2 : 2 β€ n) (np : Β¬ prime n) :
β m, m β£ n β§ m β 1 β§ m β n :=
β¨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).one_lt,
ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 npβ©
theorem exists_dvd_of_not_prime2 {n : β} (n2 : 2 β€ n) (np : Β¬ prime n) :
β m, m β£ n β§ 2 β€ m β§ m < n :=
β¨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).two_le,
(not_prime_iff_min_fac_lt n2).1 npβ©
theorem exists_prime_and_dvd {n : β} (n2 : 2 β€ n) : β p, prime p β§ p β£ n :=
β¨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _β©
theorem exists_infinite_primes (n : β) : β p, n β€ p β§ prime p :=
let p := min_fac (fact n + 1) in
have f1 : fact n + 1 β 1, from ne_of_gt $ succ_lt_succ $ fact_pos _,
have pp : prime p, from min_fac_prime f1,
have np : n β€ p, from le_of_not_ge $ Ξ» h,
have hβ : p β£ fact n, from dvd_fact (min_fac_pos _) h,
have hβ : p β£ 1, from (nat.dvd_add_iff_right hβ).2 (min_fac_dvd _),
pp.not_dvd_one hβ,
β¨p, np, ppβ©
lemma prime.eq_two_or_odd {p : β} (hp : prime p) : p = 2 β¨ p % 2 = 1 :=
(nat.mod_two_eq_zero_or_one p).elim
(Ξ» h, or.inl ((hp.2 2 (dvd_of_mod_eq_zero h)).resolve_left dec_trivial).symm)
or.inr
theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 :=
div_lt_self dec_trivial (min_fac_prime dec_trivial).one_lt
/-- `factors n` is the prime factorization of `n`, listed in increasing order. -/
def factors : β β list β
| 0 := []
| 1 := []
| n@(k+2) :=
let m := min_fac n in have n / m < n := factors_lemma,
m :: factors (n / m)
lemma mem_factors : β {n p}, p β factors n β prime p
| 0 := Ξ» p, false.elim
| 1 := Ξ» p, false.elim
| n@(k+2) := Ξ» p h,
let m := min_fac n in have n / m < n := factors_lemma,
have hβ : p = m β¨ p β (factors (n / m)) :=
(list.mem_cons_iff _ _ _).1 h,
or.cases_on hβ (Ξ» hβ, hβ.symm βΈ min_fac_prime dec_trivial)
mem_factors
lemma prod_factors : β {n}, 0 < n β list.prod (factors n) = n
| 0 := (lt_irrefl _).elim
| 1 := Ξ» h, rfl
| n@(k+2) := Ξ» h,
let m := min_fac n in have n / m < n := factors_lemma,
show list.prod (m :: factors (n / m)) = n, from
have hβ : 0 < n / m :=
nat.pos_of_ne_zero $ Ξ» h,
have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h,
by rw zero_mul at this; exact (show k + 2 β 0, from dec_trivial) this,
by rw [list.prod_cons, prod_factors hβ, nat.mul_div_cancel' (min_fac_dvd _)]
theorem prime.coprime_iff_not_dvd {p n : β} (pp : prime p) : coprime p n β Β¬ p β£ n :=
β¨Ξ» co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]),
Ξ» nd, coprime_of_dvd $ Ξ» m m2 mp, ((dvd_prime_two_le pp m2).1 mp).symm βΈ ndβ©
theorem prime.dvd_iff_not_coprime {p n : β} (pp : prime p) : p β£ n β Β¬ coprime p n :=
iff_not_comm.2 pp.coprime_iff_not_dvd
theorem prime.dvd_mul {p m n : β} (pp : prime p) : p β£ m * n β p β£ m β¨ p β£ n :=
β¨Ξ» H, or_iff_not_imp_left.2 $ Ξ» h,
(pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H,
or.rec (Ξ» h, dvd_mul_of_dvd_left h _) (Ξ» h, dvd_mul_of_dvd_right h _)β©
theorem prime.not_dvd_mul {p m n : β} (pp : prime p)
(Hm : Β¬ p β£ m) (Hn : Β¬ p β£ n) : Β¬ p β£ m * n :=
mt pp.dvd_mul.1 $ by simp [Hm, Hn]
theorem prime.dvd_of_dvd_pow {p m n : β} (pp : prime p) (h : p β£ m^n) : p β£ m :=
by induction n with n IH;
[exact pp.not_dvd_one.elim h,
exact (pp.dvd_mul.1 h).elim IH id]
lemma prime.mul_eq_prime_pow_two_iff {x y p : β} (hp : p.prime) (hx : x β 1) (hy : y β 1) :
x * y = p ^ 2 β x = p β§ y = p :=
β¨Ξ» h, have pdvdxy : p β£ x * y, by rw h; simp [nat.pow_two],
begin
wlog := hp.dvd_mul.1 pdvdxy using x y,
cases case with a ha,
have hap : a β£ p, from β¨y, by rwa [ha, nat.pow_two,
mul_assoc, nat.mul_left_inj hp.pos, eq_comm] at hβ©,
exact ((nat.dvd_prime hp).1 hap).elim
(Ξ» _, by clear_aux_decl; simp [*, nat.pow_two, nat.mul_left_inj hp.pos] at *
{contextual := tt})
(Ξ» _, by clear_aux_decl; simp [*, nat.pow_two, mul_comm, mul_assoc,
nat.mul_left_inj hp.pos, nat.mul_right_eq_self_iff hp.pos] at *
{contextual := tt})
end,
Ξ» β¨hβ, hββ©, hβ.symm βΈ hβ.symm βΈ (nat.pow_two _).symmβ©
lemma prime.dvd_fact : β {n p : β} (hp : prime p), p β£ n.fact β p β€ n
| 0 p hp := iff_of_false hp.not_dvd_one (not_le_of_lt hp.pos)
| (n+1) p hp := begin
rw [fact_succ, hp.dvd_mul, prime.dvd_fact hp],
exact β¨Ξ» h, h.elim (le_of_dvd (succ_pos _)) le_succ_of_le,
Ξ» h, (_root_.lt_or_eq_of_le h).elim (or.inr β le_of_lt_succ)
(Ξ» h, or.inl $ by rw h)β©
end
theorem prime.coprime_pow_of_not_dvd {p m a : β} (pp : prime p) (h : Β¬ p β£ a) : coprime a (p^m) :=
(pp.coprime_iff_not_dvd.2 h).symm.pow_right _
theorem coprime_primes {p q : β} (pp : prime p) (pq : prime q) : coprime p q β p β q :=
pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_two_le pq pp.two_le
theorem coprime_pow_primes {p q : β} (n m : β) (pp : prime p) (pq : prime q) (h : p β q) :
coprime (p^n) (q^m) :=
((coprime_primes pp pq).2 h).pow _ _
theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : β) : coprime p i β¨ p β£ i :=
by rw [pp.dvd_iff_not_coprime]; apply em
theorem dvd_prime_pow {p : β} (pp : prime p) {m i : β} : i β£ (p^m) β β k β€ m, i = p^k :=
begin
induction m with m IH generalizing i, {simp [pow_succ, le_zero_iff] at *},
by_cases p β£ i,
{ cases h with a e, subst e,
rw [pow_succ, mul_comm (p^m) p, nat.mul_dvd_mul_iff_left pp.pos, IH],
split; intro h; rcases h with β¨k, h, eβ©,
{ exact β¨succ k, succ_le_succ h, by rw [mul_comm, e]; reflβ© },
cases k with k,
{ apply pp.not_dvd_one.elim,
simp at e, rw β e, apply dvd_mul_right },
{ refine β¨k, le_of_succ_le_succ h, _β©,
rwa [mul_comm, pow_succ, nat.mul_right_inj pp.pos] at e } },
{ split; intro d,
{ rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d,
exact β¨0, zero_le _, rflβ© },
{ rcases d with β¨k, l, eβ©,
rw e, exact pow_dvd_pow _ l } }
end
section
open list
lemma mem_list_primes_of_dvd_prod {p : β} (hp : prime p) :
β {l : list β}, (β p β l, prime p) β p β£ prod l β p β l
| [] := Ξ» hβ hβ, absurd hβ (prime.not_dvd_one hp)
| (q :: l) := Ξ» hβ hβ,
have hβ : p β£ q * prod l := @prod_cons _ _ l q βΈ hβ,
have hq : prime q := hβ q (mem_cons_self _ _),
or.cases_on ((prime.dvd_mul hp).1 hβ)
(Ξ» h, by rw [prime.dvd_iff_not_coprime hp, coprime_primes hp hq, ne.def, not_not] at h;
exact h βΈ mem_cons_self _ _)
(Ξ» h, have hl : β p β l, prime p := Ξ» p hlp, hβ p ((mem_cons_iff _ _ _).2 (or.inr hlp)),
(mem_cons_iff _ _ _).2 (or.inr (mem_list_primes_of_dvd_prod hl h)))
lemma mem_factors_iff_dvd {n p : β} (hn : 0 < n) (hp : prime p) : p β factors n β p β£ n :=
β¨Ξ» h, prod_factors hn βΈ list.dvd_prod h,
Ξ» h, mem_list_primes_of_dvd_prod hp (@mem_factors n) ((prod_factors hn).symm βΈ h)β©
lemma perm_of_prod_eq_prod : β {lβ lβ : list β}, prod lβ = prod lβ β
(β p β lβ, prime p) β (β p β lβ, prime p) β lβ ~ lβ
| [] [] _ _ _ := perm.nil
| [] (a :: l) hβ hβ hβ :=
have ha : a β£ 1 := @prod_nil β _ βΈ hβ.symm βΈ (@prod_cons _ _ l a).symm βΈ dvd_mul_right _ _,
absurd ha (prime.not_dvd_one (hβ a (mem_cons_self _ _)))
| (a :: l) [] hβ hβ hβ :=
have ha : a β£ 1 := @prod_nil β _ βΈ hβ βΈ (@prod_cons _ _ l a).symm βΈ dvd_mul_right _ _,
absurd ha (prime.not_dvd_one (hβ a (mem_cons_self _ _)))
| (a :: lβ) (b :: lβ) h hlβ hlβ :=
have hlβ' : β p β lβ, prime p := Ξ» p hp, hlβ p (mem_cons_of_mem _ hp),
have hlβ' : β p β (b :: lβ).erase a, prime p := Ξ» p hp, hlβ p (mem_of_mem_erase hp),
have ha : a β (b :: lβ) := mem_list_primes_of_dvd_prod (hlβ a (mem_cons_self _ _)) hlβ
(h βΈ by rw prod_cons; exact dvd_mul_right _ _),
have hb : b :: lβ ~ a :: (b :: lβ).erase a := perm_erase ha,
have hl : prod lβ = prod ((b :: lβ).erase a) :=
(nat.mul_left_inj (prime.pos (hlβ a (mem_cons_self _ _)))).1 $
by rwa [β prod_cons, β prod_cons, β prod_eq_of_perm hb],
perm.trans (perm.skip _ (perm_of_prod_eq_prod hl hlβ' hlβ')) hb.symm
lemma factors_unique {n : β} {l : list β} (hβ : prod l = n) (hβ : β p β l, prime p) : l ~ factors n :=
have hn : 0 < n := nat.pos_of_ne_zero $ Ξ» h, begin
rw h at *, clear h,
induction l with a l hi,
{ exact absurd hβ dec_trivial },
{ rw prod_cons at hβ,
exact nat.mul_ne_zero (ne_of_lt (prime.pos (hβ a (mem_cons_self _ _)))).symm
(hi (Ξ» p hp, hβ p (mem_cons_of_mem _ hp))) hβ }
end,
perm_of_prod_eq_prod (by rwa prod_factors hn) hβ (@mem_factors _)
end
lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : β} (p_prime : prime p) {m n k l : β}
(hpm : p ^ k β£ m) (hpn : p ^ l β£ n) (hpmn : p ^ (k+l+1) β£ m*n) :
p ^ (k+1) β£ m β¨ p ^ (l+1) β£ n :=
have hpd : p^(k+l) * p β£ m*n, from hpmn,
have hpd2 : p β£ (m*n) / p ^ (k+l), from dvd_div_of_mul_dvd hpd,
have hpd3 : p β£ (m*n) / (p^k * p^l), by simpa [nat.pow_add] using hpd2,
have hpd4 : p β£ (m / p^k) * (n / p^l), by simpa [nat.div_mul_div hpm hpn] using hpd3,
have hpd5 : p β£ (m / p^k) β¨ p β£ (n / p^l), from (prime.dvd_mul p_prime).1 hpd4,
show p^k*p β£ m β¨ p^l*p β£ n, from
hpd5.elim
(assume : p β£ m / p ^ k, or.inl $ mul_dvd_of_dvd_div hpm this)
(assume : p β£ n / p ^ l, or.inr $ mul_dvd_of_dvd_div hpn this)
/-- The type of prime numbers -/
def primes := {p : β // p.prime}
namespace primes
instance : has_repr nat.primes := β¨Ξ» p, repr p.valβ©
instance coe_nat : has_coe nat.primes β := β¨subtype.valβ©
theorem coe_nat_inj (p q : nat.primes) : (p : β) = (q : β) β p = q :=
Ξ» h, subtype.eq h
end primes
end nat
|
a40f2544fc96dcf693b748f386a7bb82f8808e87 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/ring_theory/class_group.lean | fb8c62f2999b47fa5819843fbecc0c4fc1314601 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 10,054 | lean | /-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import group_theory.quotient_group
import ring_theory.dedekind_domain.ideal
/-!
# The ideal class group
This file defines the ideal class group `class_group R K` of fractional ideals of `R`
inside `A`'s field of fractions `K`.
## Main definitions
- `to_principal_ideal` sends an invertible `x : K` to an invertible fractional ideal
- `class_group` is the quotient of invertible fractional ideals modulo `to_principal_ideal.range`
- `class_group.mk0` sends a nonzero integral ideal in a Dedekind domain to its class
## Main results
- `class_group.mk0_eq_mk0_iff` shows the equivalence with the "classical" definition,
where `I ~ J` iff `x I = y J` for `x y β (0 : R)`
-/
variables {R K L : Type*} [comm_ring R]
variables [field K] [field L] [decidable_eq L]
variables [algebra R K] [is_fraction_ring R K]
variables [algebra K L] [finite_dimensional K L]
variables [algebra R L] [is_scalar_tower R K L]
open_locale non_zero_divisors
open is_localization is_fraction_ring fractional_ideal units
section
variables (R K)
/-- `to_principal_ideal R K x` sends `x β 0 : K` to the fractional `R`-ideal generated by `x` -/
@[irreducible]
def to_principal_ideal : KΛ£ β* (fractional_ideal Rβ° K)Λ£ :=
{ to_fun := Ξ» x,
β¨span_singleton _ x,
span_singleton _ xβ»ΒΉ,
by simp only [span_singleton_one, units.mul_inv', span_singleton_mul_span_singleton],
by simp only [span_singleton_one, units.inv_mul', span_singleton_mul_span_singleton]β©,
map_mul' := Ξ» x y, ext
(by simp only [units.coe_mk, units.coe_mul, span_singleton_mul_span_singleton]),
map_one' := ext (by simp only [span_singleton_one, units.coe_mk, units.coe_one]) }
local attribute [semireducible] to_principal_ideal
variables {R K}
@[simp] lemma coe_to_principal_ideal (x : KΛ£) :
(to_principal_ideal R K x : fractional_ideal Rβ° K) = span_singleton _ x :=
rfl
@[simp] lemma to_principal_ideal_eq_iff {I : (fractional_ideal Rβ° K)Λ£} {x : KΛ£} :
to_principal_ideal R K x = I β span_singleton Rβ° (x : K) = I :=
units.ext_iff
end
instance principal_ideals.normal : (to_principal_ideal R K).range.normal :=
subgroup.normal_of_comm _
section
variables (R K)
/-- The ideal class group of `R` in a field of fractions `K`
is the group of invertible fractional ideals modulo the principal ideals. -/
@[derive(comm_group)]
def class_group := (fractional_ideal Rβ° K)Λ£ β§Έ (to_principal_ideal R K).range
instance : inhabited (class_group R K) := β¨1β©
variables {R} [is_domain R]
/-- Send a nonzero integral ideal to an invertible fractional ideal. -/
@[simps]
noncomputable def fractional_ideal.mk0 [is_dedekind_domain R] :
(ideal R)β° β* (fractional_ideal Rβ° K)Λ£ :=
{ to_fun := Ξ» I, units.mk0 I ((fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl Rβ°)).mpr
(mem_non_zero_divisors_iff_ne_zero.mp I.2)),
map_one' := by simp,
map_mul' := Ξ» x y, by simp }
/-- Send a nonzero ideal to the corresponding class in the class group. -/
@[simps]
noncomputable def class_group.mk0 [is_dedekind_domain R] :
(ideal R)β° β* class_group R K :=
(quotient_group.mk' _).comp (fractional_ideal.mk0 K)
variables {K}
lemma class_group.mk0_eq_mk0_iff_exists_fraction_ring [is_dedekind_domain R] {I J : (ideal R)β°} :
class_group.mk0 K I = class_group.mk0 K J β
β (x β (0 : K)), span_singleton Rβ° x * I = J :=
begin
simp only [class_group.mk0, monoid_hom.comp_apply, quotient_group.mk'_eq_mk'],
split,
{ rintros β¨_, β¨x, rflβ©, hxβ©,
refine β¨x, x.ne_zero, _β©,
simpa only [mul_comm, coe_mk0, monoid_hom.to_fun_eq_coe, coe_to_principal_ideal, units.coe_mul]
using congr_arg (coe : _ β fractional_ideal Rβ° K) hx },
{ rintros β¨x, hx, eq_Jβ©,
refine β¨_, β¨units.mk0 x hx, rflβ©, units.ext _β©,
simpa only [fractional_ideal.mk0_apply, units.coe_mk0, mul_comm, coe_to_principal_ideal,
coe_coe, units.coe_mul] using eq_J }
end
lemma class_group.mk0_eq_mk0_iff [is_dedekind_domain R] {I J : (ideal R)β°} :
class_group.mk0 K I = class_group.mk0 K J β
β (x y : R) (hx : x β 0) (hy : y β 0), ideal.span {x} * (I : ideal R) = ideal.span {y} * J :=
begin
refine class_group.mk0_eq_mk0_iff_exists_fraction_ring.trans β¨_, _β©,
{ rintros β¨z, hz, hβ©,
obtain β¨x, β¨y, hyβ©, rflβ© := is_localization.mk'_surjective Rβ° z,
refine β¨x, y, _, mem_non_zero_divisors_iff_ne_zero.mp hy, _β©,
{ rintro hx, apply hz,
rw [hx, is_fraction_ring.mk'_eq_div, (algebra_map R K).map_zero, zero_div] },
{ exact (fractional_ideal.mk'_mul_coe_ideal_eq_coe_ideal K hy).mp h } },
{ rintros β¨x, y, hx, hy, hβ©,
have hy' : y β Rβ° := mem_non_zero_divisors_iff_ne_zero.mpr hy,
refine β¨is_localization.mk' K x β¨y, hy'β©, _, _β©,
{ contrapose! hx,
rwa [is_localization.mk'_eq_iff_eq_mul, zero_mul, β (algebra_map R K).map_zero,
(is_fraction_ring.injective R K).eq_iff] at hx },
{ exact (fractional_ideal.mk'_mul_coe_ideal_eq_coe_ideal K hy').mpr h } },
end
lemma class_group.mk0_surjective [is_dedekind_domain R] :
function.surjective (class_group.mk0 K : (ideal R)β° β class_group R K) :=
begin
rintros β¨Iβ©,
obtain β¨a, a_ne_zero', haβ© := I.1.2,
have a_ne_zero := mem_non_zero_divisors_iff_ne_zero.mp a_ne_zero',
have fa_ne_zero : (algebra_map R K) a β 0 :=
is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors a_ne_zero',
refine β¨β¨{ carrier := { x | (algebra_map R K a)β»ΒΉ * algebra_map R K x β I.1 }, .. }, _β©, _β©,
{ simp only [ring_hom.map_add, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add],
exact Ξ» _ _ ha hb, submodule.add_mem I ha hb },
{ simp only [ring_hom.map_zero, set.mem_set_of_eq, mul_zero, ring_hom.map_mul],
exact submodule.zero_mem I },
{ intros c _ hb,
simp only [smul_eq_mul, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add,
mul_left_comm ((algebra_map R K) a)β»ΒΉ],
rw β algebra.smul_def c,
exact submodule.smul_mem I c hb },
{ rw [mem_non_zero_divisors_iff_ne_zero, submodule.zero_eq_bot, submodule.ne_bot_iff],
obtain β¨x, x_ne, x_memβ© := exists_ne_zero_mem_is_integer I.ne_zero,
refine β¨a * x, _, mul_ne_zero a_ne_zero x_neβ©,
change ((algebra_map R K) a)β»ΒΉ * (algebra_map R K) (a * x) β I.1,
rwa [ring_hom.map_mul, β mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] },
{ symmetry,
apply quotient.sound,
change setoid.r _ _,
rw quotient_group.left_rel_apply,
refine β¨units.mk0 (algebra_map R K a) fa_ne_zero, _β©,
apply @mul_left_cancel _ _ I,
rw [β mul_assoc, mul_right_inv, one_mul, eq_comm, mul_comm I],
apply units.ext,
simp only [monoid_hom.coe_mk, subtype.coe_mk, ring_hom.map_mul, coe_coe,
units.coe_mul, coe_to_principal_ideal, coe_mk0,
fractional_ideal.eq_span_singleton_mul],
split,
{ intros zJ' hzJ',
obtain β¨zJ, hzJ : (algebra_map R K a)β»ΒΉ * algebra_map R K zJ β βI, rflβ© :=
(mem_coe_ideal Rβ°).mp hzJ',
refine β¨_, hzJ, _β©,
rw [β mul_assoc, mul_inv_cancel fa_ne_zero, one_mul] },
{ intros zI' hzI',
obtain β¨y, hyβ© := ha zI' hzI',
rw [β algebra.smul_def, fractional_ideal.mk0_apply, coe_mk0, coe_coe, mem_coe_ideal],
refine β¨y, _, hyβ©,
show (algebra_map R K a)β»ΒΉ * algebra_map R K y β (I : fractional_ideal Rβ° K),
rwa [hy, algebra.smul_def, β mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] } }
end
end
lemma class_group.mk_eq_one_iff
{I : (fractional_ideal Rβ° K)Λ£} :
quotient_group.mk' (to_principal_ideal R K).range I = 1 β
(I : submodule R K).is_principal :=
begin
rw [β (quotient_group.mk' _).map_one, eq_comm, quotient_group.mk'_eq_mk'],
simp only [exists_prop, one_mul, exists_eq_right, to_principal_ideal_eq_iff,
monoid_hom.mem_range, coe_coe],
refine β¨Ξ» β¨x, hxβ©, β¨β¨x, by rw [β hx, coe_span_singleton]β©β©, _β©,
unfreezingI { intros hI },
obtain β¨x, hxβ© := @submodule.is_principal.principal _ _ _ _ _ _ hI,
have hx' : (I : fractional_ideal Rβ° K) = span_singleton Rβ° x,
{ apply subtype.coe_injective, rw [hx, coe_span_singleton] },
refine β¨units.mk0 x _, _β©,
{ intro x_eq, apply units.ne_zero I, simp [hx', x_eq] },
simp [hx']
end
variables [is_domain R]
lemma class_group.mk0_eq_one_iff [is_dedekind_domain R]
{I : ideal R} (hI : I β (ideal R)β°) :
class_group.mk0 K β¨I, hIβ© = 1 β I.is_principal :=
class_group.mk_eq_one_iff.trans (coe_submodule_is_principal R K)
/-- The class group of principal ideal domain is finite (in fact a singleton).
TODO: generalize to Dedekind domains -/
instance [is_principal_ideal_ring R] :
fintype (class_group R K) :=
{ elems := {1},
complete :=
begin
rintros β¨Iβ©,
rw [finset.mem_singleton],
exact class_group.mk_eq_one_iff.mpr (I : fractional_ideal Rβ° K).is_principal
end }
/-- The class number of a principal ideal domain is `1`. -/
lemma card_class_group_eq_one [is_principal_ideal_ring R] :
fintype.card (class_group R K) = 1 :=
begin
rw fintype.card_eq_one_iff,
use 1,
rintros β¨Iβ©,
exact class_group.mk_eq_one_iff.mpr (I : fractional_ideal Rβ° K).is_principal
end
/-- The class number is `1` iff the ring of integers is a principal ideal domain. -/
lemma card_class_group_eq_one_iff [is_dedekind_domain R] [fintype (class_group R K)] :
fintype.card (class_group R K) = 1 β is_principal_ideal_ring R :=
begin
split, swap, { introsI, convert card_class_group_eq_one, assumption, assumption, },
rw fintype.card_eq_one_iff,
rintros β¨I, hIβ©,
have eq_one : β J : class_group R K, J = 1 := Ξ» J, trans (hI J) (hI 1).symm,
refine β¨Ξ» I, _β©,
by_cases hI : I = β₯,
{ rw hI, exact bot_is_principal },
exact (class_group.mk0_eq_one_iff (mem_non_zero_divisors_iff_ne_zero.mpr hI)).mp (eq_one _),
end
|
1a8029b97032616e46f27704a0023e76fd39e8d5 | a721fe7446524f18ba361625fc01033d9c8b7a78 | /src/principia/mygroup/basic.lean | ea181c65044e2c83c6a46de68cd182e2dc7ebbde | [] | 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 | 1,699 | lean | namespace hidden
class mygroup (Ξ± : Type)
extends has_mul Ξ±, has_inv Ξ± :=
(e : Ξ±)
(mul_assoc (a b c : Ξ±) : a * b * c = a * (b * c))
(mul_id (a : Ξ±) : a * e = a)
(mul_inv (a : Ξ±) : a * aβ»ΒΉ = e)
namespace mygroup
variables {Ξ± : Type} [mygroup Ξ±]
variables {a b c : Ξ±}
-- This sucks
theorem mul_by_right : a = b β a * c = b * c :=
begin
assume h,
congr,
assumption,
end
theorem mul_cancel_right (c : Ξ±) : a * c = b * c β a = b :=
begin
assume h,
have := congr_arg (Ξ» d, d * cβ»ΒΉ) h,
dsimp only [] at this,
repeat { rwa [mul_assoc, mul_inv, mul_id] at this },
end
theorem mul_right (c : Ξ±) : a = b β a * c = b * c :=
β¨mul_by_right, mul_cancel_right cβ©
theorem mul_by_left : a = b β c * a = c * b :=
begin
assume h,
congr,
assumption,
end
theorem inv_mul : aβ»ΒΉ * a = e :=
begin
-- This is actually a really hard theorem
rw [βmul_inv aβ»ΒΉ, βmul_id (aβ»ΒΉ * a), βmul_inv aβ»ΒΉ, βmul_assoc],
apply mul_by_right,
rw [mul_assoc, mul_inv, mul_id],
end
theorem id_mul (a : Ξ±) : e * a = a :=
by rw [βmul_inv a, mul_assoc, inv_mul, mul_id]
theorem mul_cancel_left : c * a = c * b β a = b :=
begin
assume h,
have := congr_arg (Ξ» d, cβ»ΒΉ * d) h,
dsimp only [] at this,
repeat { rwa [βmul_assoc, inv_mul, id_mul] at this },
end
theorem mul_left (c : Ξ±) : a = b β c * a = c * b :=
β¨mul_by_left, mul_cancel_leftβ©
theorem id_unique : a * b = a β b = e :=
begin
split; assume h,
rwa [mul_left a, mul_id],
subst h,
from mul_id a,
end
theorem inv_unique : a * b = e β b = aβ»ΒΉ :=
begin
split; assume h,
rwa [mul_left a, mul_inv],
subst h,
from mul_inv a,
end
end mygroup
end hidden
|
cf247463e5d8442d188468d449a0b46d88c8dd73 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /library/standard/data/option.lean | 026131234bc10074417de1c5e10ff9057b58f9a3 | [
"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 | 1,985 | lean | ------------------------------------------------------------------------------------------------------
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Author: Leonardo de Moura
----------------------------------------------------------------------------------------------------
import logic.connectives.basic logic.connectives.eq logic.classes.inhabited logic.classes.decidable
using eq_proofs decidable
namespace option
inductive option (A : Type) : Type :=
| none {} : option A
| some : A β option A
theorem induction_on {A : Type} {p : option A β Prop} (o : option A) (H1 : p none) (H2 : βa, p (some a)) : p o :=
option_rec H1 H2 o
definition rec_on {A : Type} {C : option A β Type} (o : option A) (H1 : C none) (H2 : βa, C (some a)) : C o :=
option_rec H1 H2 o
definition is_none {A : Type} (o : option A) : Prop :=
option_rec true (Ξ» a, false) o
theorem is_none_none {A : Type} : is_none (@none A) :=
trivial
theorem not_is_none_some {A : Type} (a : A) : Β¬ is_none (some a) :=
not_false_trivial
theorem none_ne_some {A : Type} (a : A) : none β some a :=
assume H : none = some a, absurd
(H βΈ is_none_none)
(not_is_none_some a)
theorem some_inj {A : Type} {aβ aβ : A} (H : some aβ = some aβ) : aβ = aβ :=
congr2 (option_rec aβ (Ξ» a, a)) H
theorem inhabited_option [instance] (A : Type) : inhabited (option A) :=
inhabited_intro none
theorem decidable_eq [instance] {A : Type} {H : βaβ aβ : A, decidable (aβ = aβ)} (oβ oβ : option A) : decidable (oβ = oβ) :=
rec_on oβ
(rec_on oβ (inl (refl _)) (take aβ, (inr (none_ne_some aβ))))
(take aβ : A, rec_on oβ
(inr (ne_symm (none_ne_some aβ)))
(take aβ : A, decidable.rec_on (H aβ aβ)
(assume Heq : aβ = aβ, inl (Heq βΈ refl _))
(assume Hne : aβ β aβ, inr (assume Hn : some aβ = some aβ, absurd (some_inj Hn) Hne))))
end |
938f0df027ee11bddd89bc0c974da1a6c5d9d5f7 | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /tests/lean/interactive/codeaction.lean | 60df5adb33e5c5dcdfc71dfad34b193c2eae1d29 | [
"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",
"Apache-2.0",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | gebner/lean4 | d51c4922640a52a6f7426536ea669ef18a1d9af5 | 8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f | refs/heads/master | 1,685,732,780,391 | 1,672,962,627,000 | 1,673,459,398,000 | 373,307,283 | 0 | 0 | Apache-2.0 | 1,691,316,730,000 | 1,622,669,271,000 | Lean | UTF-8 | Lean | false | false | 833 | lean | import Lean
open Lean Server Lsp
@[codeActionProvider]
def helloProvider : CodeActionProvider := fun params _snap => do
let td := params.textDocument
let edit : TextEdit := {
range := params.range,
newText := "hello!!!"
}
let ca : CodeAction := {
title := "hello world",
kind? := "quickfix",
edit? := WorkspaceEdit.ofTextEdit td.uri edit
}
let longRunner : CodeAction := {
title := "a long-running action",
kind? := "refactor",
}
let lazyResult : IO CodeAction := do
let v? β IO.getEnv "PWD"
let v := v?.getD "none"
return { longRunner with
edit? := WorkspaceEdit.ofTextEdit td.uri { range := params.range, newText := v}
}
return #[ca, {eager := longRunner, lazy? := lazyResult}]
theorem asdf : (x : Nat) β x = x := by
intro x
--^ codeAction
rfl
|
5743e7aad3f2ae0defc489e3a44a751a86581a97 | 36c7a18fd72e5b57229bd8ba36493daf536a19ce | /library/algebra/ring_power.lean | 16ae88cfe4dee2a53acd7c6adba3266155897d7b | [
"Apache-2.0"
] | permissive | YHVHvx/lean | 732bf0fb7a298cd7fe0f15d82f8e248c11db49e9 | 038369533e0136dd395dc252084d3c1853accbf2 | refs/heads/master | 1,610,701,080,210 | 1,449,128,595,000 | 1,449,128,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,909 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
Properties of the power operation in an ordered ring or field.
(Right now, this file is just a stub. More soon.)
-/
import .group_power .ordered_field
open nat
namespace algebra
variable {A : Type}
section semiring
variable [s : semiring A]
include s
definition semiring_has_pow_nat [reducible] [instance] : has_pow_nat A :=
monoid_has_pow_nat
theorem zero_pow {m : β} (mpos : m > 0) : 0^m = (0 : A) :=
have hβ : β m : nat, (0 : A)^(succ m) = (0 : A),
begin
intro m, induction m,
rewrite pow_one,
apply zero_mul
end,
obtain m' (hβ : m = succ m'), from exists_eq_succ_of_pos mpos,
show 0^m = 0, by rewrite hβ; apply hβ
end semiring
section integral_domain
variable [s : integral_domain A]
include s
definition integral_domain_has_pow_nat [reducible] [instance] : has_pow_nat A :=
monoid_has_pow_nat
theorem eq_zero_of_pow_eq_zero {a : A} {m : β} (H : a^m = 0) : a = 0 :=
or.elim (eq_zero_or_pos m)
(suppose m = 0,
by rewrite [`m = 0` at H, pow_zero at H]; apply absurd H (ne.symm zero_ne_one))
(suppose m > 0,
have hβ : β m, a^succ m = 0 β a = 0,
begin
intro m,
induction m with m ih,
{rewrite pow_one; intros; assumption},
rewrite pow_succ,
intro H,
cases eq_zero_or_eq_zero_of_mul_eq_zero H with hβ hβ,
assumption,
exact ih hβ
end,
obtain m' (hβ : m = succ m'), from exists_eq_succ_of_pos `m > 0`,
show a = 0, by rewrite hβ at H; apply hβ m' H)
theorem pow_ne_zero_of_ne_zero {a : A} {m : β} (H : a β 0) : a^m β 0 :=
assume H', H (eq_zero_of_pow_eq_zero H')
end integral_domain
section division_ring
variable [s : division_ring A]
include s
theorem division_ring.pow_ne_zero_of_ne_zero {a : A} {m : β} (H : a β 0) : a^m β 0 :=
or.elim (eq_zero_or_pos m)
(suppose m = 0,
by rewrite [`m = 0`, pow_zero]; exact (ne.symm zero_ne_one))
(suppose m > 0,
have hβ : β m, a^succ m β 0,
begin
intro m,
induction m with m ih,
{rewrite pow_one; assumption},
rewrite pow_succ,
apply division_ring.mul_ne_zero H ih
end,
obtain m' (hβ : m = succ m'), from exists_eq_succ_of_pos `m > 0`,
show a^m β 0, by rewrite hβ; apply hβ m')
end division_ring
section linear_ordered_semiring
variable [s : linear_ordered_semiring A]
include s
theorem pow_pos_of_pos {x : A} (i : β) (H : x > 0) : x^i > 0 :=
begin
induction i with [j, ih],
{show (1 : A) > 0, from zero_lt_one},
{show x^(succ j) > 0, from mul_pos H ih}
end
theorem pow_nonneg_of_nonneg {x : A} (i : β) (H : x β₯ 0) : x^i β₯ 0 :=
begin
induction i with j ih,
{show (1 : A) β₯ 0, from le_of_lt zero_lt_one},
{show x^(succ j) β₯ 0, from mul_nonneg H ih}
end
theorem pow_le_pow_of_le {x y : A} (i : β) (Hβ : 0 β€ x) (Hβ : x β€ y) : x^i β€ y^i :=
begin
induction i with i ih,
{rewrite *pow_zero, apply le.refl},
rewrite *pow_succ,
have H : 0 β€ x^i, from pow_nonneg_of_nonneg i Hβ,
apply mul_le_mul Hβ ih H (le.trans Hβ Hβ)
end
theorem pow_ge_one {x : A} (i : β) (xge1 : x β₯ 1) : x^i β₯ 1 :=
assert H : x^i β₯ 1^i, from pow_le_pow_of_le i (le_of_lt zero_lt_one) xge1,
by rewrite one_pow at H; exact H
theorem pow_gt_one {x : A} {i : β} (xgt1 : x > 1) (ipos : i > 0) : x^i > 1 :=
assert xpos : x > 0, from lt.trans zero_lt_one xgt1,
begin
induction i with [i, ih],
{exfalso, exact !lt.irrefl ipos},
have xige1 : x^i β₯ 1, from pow_ge_one _ (le_of_lt xgt1),
rewrite [pow_succ, -mul_one 1],
apply mul_lt_mul xgt1 xige1 zero_lt_one,
apply le_of_lt xpos
end
end linear_ordered_semiring
section decidable_linear_ordered_comm_ring
variable [s : decidable_linear_ordered_comm_ring A]
include s
definition decidable_linear_ordered_comm_ring_has_pow_nat [reducible] [instance] : has_pow_nat A :=
monoid_has_pow_nat
theorem abs_pow (a : A) (n : β) : abs (a^n) = abs a^n :=
begin
induction n with n ih,
rewrite [*pow_zero, (abs_of_nonneg zero_le_one : abs (1 : A) = 1)],
rewrite [*pow_succ, abs_mul, ih]
end
end decidable_linear_ordered_comm_ring
section field
variable [s : field A]
include s
theorem field.div_pow (a : A) {b : A} {n : β} (bnz : b β 0) : (a / b)^n = a^n / b^n :=
begin
induction n with n ih,
rewrite [*pow_zero, div_one],
have bnnz : b^n β 0, from division_ring.pow_ne_zero_of_ne_zero bnz,
rewrite [*pow_succ, ih, !field.div_mul_div bnz bnnz]
end
end field
section discrete_field
variable [s : discrete_field A]
include s
theorem div_pow (a : A) {b : A} {n : β} : (a / b)^n = a^n / b^n :=
begin
induction n with n ih,
rewrite [*pow_zero, div_one],
rewrite [*pow_succ, ih, div_mul_div]
end
end discrete_field
end algebra
|
28922d002ecaf60236e7cefa9e9736c7aaba8921 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/simplifier_custom_relations.lean | 0224bb4c023c3586ce846fe7a5ee9a52f09238b7 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 1,010 | lean | open tactic
universe l
constants (A : Type.{l}) (rel : A β A β Prop)
(rel.refl : β a, rel a a)
(rel.symm : β a b, rel a b β rel b a)
(rel.trans : β a b c, rel a b β rel b c β rel a c)
attribute rel.refl [refl]
attribute rel.symm [symm]
attribute rel.trans [trans]
constants (x y z : A) (f g h : A β A)
(Hβ : rel (f x) (g y))
(Hβ : rel (h (g y)) z)
(Hf : β (a b : A), rel a b β rel (f a) (f b))
(Hg : β (a b : A), rel a b β rel (g a) (g b))
(Hh : β (a b : A), rel a b β rel (h a) (h b))
attribute Hβ Hβ [simp]
attribute Hf Hg Hh [congr]
print [simp] simp
print [congr] congr
meta_definition relsimp_core (e : expr) : tactic (expr Γ expr) :=
do simp_lemmas β mk_simp_lemmas,
e_type β infer_type e >>= whnf,
simplify_core failed `rel simp_lemmas e
example : rel (h (f x)) z :=
by do eβ β to_expr `(h (f x)),
(eβ', pf) β relsimp_core eβ,
exact pf
|
fa775a72c33602462fd8b49d7dab8a740cda3910 | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch2/ex1003.lean | 98935d1661368a5118557d0e01210cbfc30768fb | [] | no_license | Ailrun/Theorem_Proving_in_Lean | ae6a23f3c54d62d401314d6a771e8ff8b4132db2 | 2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68 | refs/heads/master | 1,609,838,270,467 | 1,586,846,743,000 | 1,586,846,743,000 | 240,967,761 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 194 | lean | universe u
constant vec : Type u β β β Type u
constant vec_add : Ξ {n : β}, vec β n β vec β n β vec β n
constant vec_reverse : Ξ {Ξ± : Type} {n : β}, vec Ξ± n -> vec Ξ± n
|
e3f0853f9654301beb1585e0d4a86c6cfd62d43c | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/set_theory/ordinal_notation.lean | 55c6fcbaf417d1952bf986ec604912e40c697b70 | [
"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 | 35,942 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import set_theory.ordinal_arithmetic
/-!
# Ordinal notation
Constructive ordinal arithmetic for ordinals below `Ξ΅β`.
We define a type `onote`, with constructors `0 : onote` and `onote.oadd e n a` representing
`Ο ^ e * n + a`.
We say that `o` is in Cantor normal form - `onote.NF o` - if either `o = 0` or
`o = Ο ^ e * n + a` with `a < Ο ^ e` and `a` in Cantor normal form.
The type `nonote` is the type of ordinals below `Ξ΅β` in Cantor normal form.
Various operations (addition, subtraction, multiplication, power function)
are defined on `onote` and `nonote`.
-/
open ordinal
open_locale ordinal -- get notation for `Ο`
/-- Recursive definition of an ordinal notation. `zero` denotes the
ordinal 0, and `oadd e n a` is intended to refer to `Ο^e * n + a`.
For this to be valid Cantor normal form, we must have the exponents
decrease to the right, but we can't state this condition until we've
defined `repr`, so it is a separate definition `NF`. -/
@[derive decidable_eq]
inductive onote : Type
| zero : onote
| oadd : onote β β+ β onote β onote
namespace onote
/-- Notation for 0 -/
instance : has_zero onote := β¨zeroβ©
@[simp] theorem zero_def : zero = 0 := rfl
instance : inhabited onote := β¨0β©
/-- Notation for 1 -/
instance : has_one onote := β¨oadd 0 1 0β©
/-- Notation for Ο -/
def omega : onote := oadd 1 1 0
/-- The ordinal denoted by a notation -/
@[simp] noncomputable def repr : onote β ordinal.{0}
| 0 := 0
| (oadd e n a) := Ο ^ repr e * n + repr a
/-- Auxiliary definition to print an ordinal notation -/
def to_string_aux1 (e : onote) (n : β) (s : string) : string :=
if e = 0 then _root_.to_string n else
(if e = 1 then "Ο" else "Ο^(" ++ s ++ ")") ++
if n = 1 then "" else "*" ++ _root_.to_string n
/-- Print an ordinal notation -/
def to_string : onote β string
| zero := "0"
| (oadd e n 0) := to_string_aux1 e n (to_string e)
| (oadd e n a) := to_string_aux1 e n (to_string e) ++ " + " ++ to_string a
/-- Print an ordinal notation -/
def repr' : onote β string
| zero := "0"
| (oadd e n a) := "(oadd " ++ repr' e ++ " " ++ _root_.to_string (n:β) ++ " " ++ repr' a ++ ")"
instance : has_to_string onote := β¨to_stringβ©
instance : has_repr onote := β¨repr'β©
instance : preorder onote :=
{ le := Ξ» x y, repr x β€ repr y,
lt := Ξ» x y, repr x < repr y,
le_refl := Ξ» a, @le_refl ordinal _ _,
le_trans := Ξ» a b c, @le_trans ordinal _ _ _ _,
lt_iff_le_not_le := Ξ» a b, @lt_iff_le_not_le ordinal _ _ _ }
theorem lt_def {x y : onote} : x < y β repr x < repr y := iff.rfl
theorem le_def {x y : onote} : x β€ y β repr x β€ repr y := iff.rfl
/-- Convert a `nat` into an ordinal -/
@[simp] def of_nat : β β onote
| 0 := 0
| (nat.succ n) := oadd 0 n.succ_pnat 0
@[simp] theorem of_nat_one : of_nat 1 = 1 := rfl
@[simp] theorem repr_of_nat (n : β) : repr (of_nat n) = n :=
by cases n; simp
@[simp] theorem repr_one : repr 1 = 1 :=
by simpa using repr_of_nat 1
theorem omega_le_oadd (e n a) : Ο ^ repr e β€ repr (oadd e n a) :=
begin
unfold repr,
refine le_trans _ (le_add_right _ _),
simpa using (mul_le_mul_iff_left $ power_pos (repr e) omega_pos).2 (nat_cast_le.2 n.2)
end
theorem oadd_pos (e n a) : 0 < oadd e n a :=
@lt_of_lt_of_le _ _ _ _ _ (power_pos _ omega_pos)
(omega_le_oadd _ _ _)
/-- Compare ordinal notations -/
def cmp : onote β onote β ordering
| 0 0 := ordering.eq
| _ 0 := ordering.gt
| 0 _ := ordering.lt
| oβ@(oadd eβ nβ aβ) oβ@(oadd eβ nβ aβ) :=
(cmp eβ eβ).or_else $ (_root_.cmp (nβ:β) nβ).or_else (cmp aβ aβ)
theorem eq_of_cmp_eq : β {oβ oβ}, cmp oβ oβ = ordering.eq β oβ = oβ
| 0 0 h := rfl
| (oadd e n a) 0 h := by injection h
| 0 (oadd e n a) h := by injection h
| oβ@(oadd eβ nβ aβ) oβ@(oadd eβ nβ aβ) h := begin
revert h, simp [cmp],
cases hβ : cmp eβ eβ; intro h; try {cases h},
have := eq_of_cmp_eq hβ, subst eβ,
revert h, cases hβ : _root_.cmp (nβ:β) nβ; intro h; try {cases h},
have := eq_of_cmp_eq h, subst aβ,
rw [_root_.cmp, cmp_using_eq_eq] at hβ,
have := subtype.eq (eq_of_incomp hβ), subst nβ, simp
end
theorem zero_lt_one : (0 : onote) < 1 :=
by rw [lt_def, repr, repr_one]; exact zero_lt_one
/-- `NF_below o b` says that `o` is a normal form ordinal notation
satisfying `repr o < Ο ^ b`. -/
inductive NF_below : onote β ordinal.{0} β Prop
| zero {b} : NF_below 0 b
| oadd' {e n a eb b} : NF_below e eb β
NF_below a (repr e) β repr e < b β NF_below (oadd e n a) b
/-- A normal form ordinal notation has the form
Ο ^ aβ * nβ + Ο ^ aβ * nβ + ... Ο ^ aβ * nβ
where `aβ > aβ > ... > aβ` and all the `aα΅’` are
also in normal form.
We will essentially only be interested in normal form
ordinal notations, but to avoid complicating the algorithms
we define everything over general ordinal notations and
only prove correctness with normal form as an invariant. -/
class NF (o : onote) : Prop := (out : Exists (NF_below o))
attribute [pp_nodot] NF
instance NF.zero : NF 0 := β¨β¨0, NF_below.zeroβ©β©
theorem NF_below.oadd {e n a b} : NF e β
NF_below a (repr e) β repr e < b β NF_below (oadd e n a) b
| β¨β¨eb, hβ©β© := NF_below.oadd' h
theorem NF_below.fst {e n a b} (h : NF_below (oadd e n a) b) : NF e :=
by cases h with _ _ _ _ eb _ hβ hβ hβ; exact β¨β¨_, hββ©β©
theorem NF.fst {e n a} : NF (oadd e n a) β NF e
| β¨β¨b, hβ©β© := h.fst
theorem NF_below.snd {e n a b} (h : NF_below (oadd e n a) b) : NF_below a (repr e) :=
by cases h with _ _ _ _ eb _ hβ hβ hβ; exact hβ
theorem NF.snd' {e n a} : NF (oadd e n a) β NF_below a (repr e)
| β¨β¨b, hβ©β© := h.snd
theorem NF.snd {e n a} (h : NF (oadd e n a)) : NF a :=
β¨β¨_, h.snd'β©β©
theorem NF.oadd {e a} (hβ : NF e) (n)
(hβ : NF_below a (repr e)) : NF (oadd e n a) :=
β¨β¨_, NF_below.oadd hβ hβ (ordinal.lt_succ_self _)β©β©
instance NF.oadd_zero (e n) [h : NF e] : NF (oadd e n 0) :=
h.oadd _ NF_below.zero
theorem NF_below.lt {e n a b} (h : NF_below (oadd e n a) b) : repr e < b :=
by cases h with _ _ _ _ eb _ hβ hβ hβ; exact hβ
theorem NF_below_zero : β {o}, NF_below o 0 β o = 0
| 0 := β¨Ξ» _, rfl, Ξ» _, NF_below.zeroβ©
| (oadd e n a) := β¨Ξ» h, (not_le_of_lt h.lt).elim (ordinal.zero_le _),
Ξ» e, e.symm βΈ NF_below.zeroβ©
theorem NF.zero_of_zero {e n a} (h : NF (oadd e n a)) (e0 : e = 0) : a = 0 :=
by simpa [e0, NF_below_zero] using h.snd'
theorem NF_below.repr_lt {o b} (h : NF_below o b) : repr o < Ο ^ b :=
begin
induction h with _ e n a eb b hβ hβ hβ _ IH,
{ exact power_pos _ omega_pos },
{ rw repr,
refine lt_of_lt_of_le ((ordinal.add_lt_add_iff_left _).2 IH) _,
rw β mul_succ,
refine le_trans (mul_le_mul_left _ $ ordinal.succ_le.2 $ nat_lt_omega _) _,
rw β power_succ,
exact power_le_power_right omega_pos (ordinal.succ_le.2 hβ) }
end
theorem NF_below.mono {o bβ bβ} (bb : bβ β€ bβ) (h : NF_below o bβ) : NF_below o bβ :=
begin
induction h with _ e n a eb b hβ hβ hβ _ IH; constructor,
exacts [hβ, hβ, lt_of_lt_of_le hβ bb]
end
theorem NF.below_of_lt {e n a b} (H : repr e < b) : NF (oadd e n a) β NF_below (oadd e n a) b
| β¨β¨b', hβ©β© := by cases h with _ _ _ _ eb _ hβ hβ hβ;
exact NF_below.oadd' hβ hβ H
theorem NF.below_of_lt' : β {o b}, repr o < Ο ^ b β NF o β NF_below o b
| 0 b H _ := NF_below.zero
| (oadd e n a) b H h := h.below_of_lt $ (power_lt_power_iff_right one_lt_omega).1 $
(lt_of_le_of_lt (omega_le_oadd _ _ _) H)
theorem NF_below_of_nat : β n, NF_below (of_nat n) 1
| 0 := NF_below.zero
| (nat.succ n) := NF_below.oadd NF.zero NF_below.zero ordinal.zero_lt_one
instance NF_of_nat (n) : NF (of_nat n) := β¨β¨_, NF_below_of_nat nβ©β©
instance NF_one : NF 1 := by rw β of_nat_one; apply_instance
theorem oadd_lt_oadd_1 {eβ nβ oβ eβ nβ oβ} (hβ : NF (oadd eβ nβ oβ)) (h : eβ < eβ) :
oadd eβ nβ oβ < oadd eβ nβ oβ :=
@lt_of_lt_of_le _ _ _ _ _ ((hβ.below_of_lt h).repr_lt) (omega_le_oadd _ _ _)
theorem oadd_lt_oadd_2 {e oβ oβ : onote} {nβ nβ : β+}
(hβ : NF (oadd e nβ oβ)) (h : (nβ:β) < nβ) : oadd e nβ oβ < oadd e nβ oβ :=
begin
simp [lt_def],
refine lt_of_lt_of_le ((ordinal.add_lt_add_iff_left _).2 hβ.snd'.repr_lt)
(le_trans _ (le_add_right _ _)),
rwa [β mul_succ, mul_le_mul_iff_left (power_pos _ omega_pos),
ordinal.succ_le, nat_cast_lt]
end
theorem oadd_lt_oadd_3 {e n aβ aβ} (h : aβ < aβ) :
oadd e n aβ < oadd e n aβ :=
begin
rw lt_def, unfold repr,
exact (ordinal.add_lt_add_iff_left _).2 h
end
theorem cmp_compares : β (a b : onote) [NF a] [NF b], (cmp a b).compares a b
| 0 0 hβ hβ := rfl
| (oadd e n a) 0 hβ hβ := oadd_pos _ _ _
| 0 (oadd e n a) hβ hβ := oadd_pos _ _ _
| oβ@(oadd eβ nβ aβ) oβ@(oadd eβ nβ aβ) hβ hβ := begin
rw cmp,
have IHe := @cmp_compares _ _ hβ.fst hβ.fst,
cases cmp eβ eβ,
case ordering.lt { exact oadd_lt_oadd_1 hβ IHe },
case ordering.gt { exact oadd_lt_oadd_1 hβ IHe },
change eβ = eβ at IHe, subst IHe,
unfold _root_.cmp, cases nh : cmp_using (<) (nβ:β) nβ,
case ordering.lt {
rw cmp_using_eq_lt at nh, exact oadd_lt_oadd_2 hβ nh },
case ordering.gt {
rw cmp_using_eq_gt at nh, exact oadd_lt_oadd_2 hβ nh },
rw cmp_using_eq_eq at nh,
have := subtype.eq (eq_of_incomp nh), subst nβ,
have IHa := @cmp_compares _ _ hβ.snd hβ.snd,
cases cmp aβ aβ,
case ordering.lt { exact oadd_lt_oadd_3 IHa },
case ordering.gt { exact oadd_lt_oadd_3 IHa },
change aβ = aβ at IHa, subst IHa, exact rfl
end
theorem repr_inj {a b} [NF a] [NF b] : repr a = repr b β a = b :=
β¨match cmp a b, cmp_compares a b with
| ordering.lt, (h : repr a < repr b), e := (ne_of_lt h e).elim
| ordering.gt, (h : repr a > repr b), e := (ne_of_gt h e).elim
| ordering.eq, h, e := h
end, congr_arg _β©
theorem NF.of_dvd_omega_power {b e n a} (h : NF (oadd e n a)) (d : Ο ^ b β£ repr (oadd e n a)) :
b β€ repr e β§ Ο ^ b β£ repr a :=
begin
have := mt repr_inj.1 (Ξ» h, by injection h : oadd e n a β 0),
have L := le_of_not_lt (Ξ» l, not_le_of_lt (h.below_of_lt l).repr_lt (le_of_dvd this d)),
simp at d,
exact β¨L, (dvd_add_iff $ dvd_mul_of_dvd_left (power_dvd_power _ L) _).1 dβ©
end
theorem NF.of_dvd_omega {e n a} (h : NF (oadd e n a)) :
Ο β£ repr (oadd e n a) β repr e β 0 β§ Ο β£ repr a :=
by rw [β power_one Ο, β one_le_iff_ne_zero]; exact h.of_dvd_omega_power
/-- `top_below b o` asserts that the largest exponent in `o`, if
it exists, is less than `b`. This is an auxiliary definition
for decidability of `NF`. -/
def top_below (b) : onote β Prop
| 0 := true
| (oadd e n a) := cmp e b = ordering.lt
instance decidable_top_below : decidable_rel top_below :=
by intros b o; cases o; delta top_below; apply_instance
theorem NF_below_iff_top_below {b} [NF b] : β {o},
NF_below o (repr b) β NF o β§ top_below b o
| 0 := β¨Ξ» h, β¨β¨β¨_, hβ©β©, trivialβ©, Ξ» _, NF_below.zeroβ©
| (oadd e n a) :=
β¨Ξ» h, β¨β¨β¨_, hβ©β©, (@cmp_compares _ b h.fst _).eq_lt.2 h.ltβ©,
Ξ» β¨hβ, hββ©, hβ.below_of_lt $ (@cmp_compares _ b hβ.fst _).eq_lt.1 hββ©
instance decidable_NF : decidable_pred NF
| 0 := is_true NF.zero
| (oadd e n a) := begin
have := decidable_NF e,
have := decidable_NF a, resetI,
apply decidable_of_iff (NF e β§ NF a β§ top_below e a),
abstract {
rw β and_congr_right (Ξ» h, @NF_below_iff_top_below _ h _),
exact β¨Ξ» β¨hβ, hββ©, NF.oadd hβ n hβ, Ξ» h, β¨h.fst, h.snd'β©β© },
end
/-- Addition of ordinal notations (correct only for normal input) -/
def add : onote β onote β onote
| 0 o := o
| (oadd e n a) o := match add a o with
| 0 := oadd e n 0
| o'@(oadd e' n' a') := match cmp e e' with
| ordering.lt := o'
| ordering.eq := oadd e (n + n') a'
| ordering.gt := oadd e n o'
end
end
instance : has_add onote := β¨addβ©
@[simp] theorem zero_add (o : onote) : 0 + o = o := rfl
theorem oadd_add (e n a o) : oadd e n a + o = add._match_1 e n (a + o) := rfl
/-- Subtraction of ordinal notations (correct only for normal input) -/
def sub : onote β onote β onote
| 0 o := 0
| o 0 := o
| oβ@(oadd eβ nβ aβ) (oadd eβ nβ aβ) := match cmp eβ eβ with
| ordering.lt := 0
| ordering.gt := oβ
| ordering.eq := match (nβ:β) - nβ with
| 0 := if nβ = nβ then sub aβ aβ else 0
| (nat.succ k) := oadd eβ k.succ_pnat aβ
end
end
instance : has_sub onote := β¨subβ©
theorem add_NF_below {b} : β {oβ oβ}, NF_below oβ b β NF_below oβ b β NF_below (oβ + oβ) b
| 0 o hβ hβ := hβ
| (oadd e n a) o hβ hβ := begin
have h' := add_NF_below (hβ.snd.mono $ le_of_lt hβ.lt) hβ,
simp [oadd_add], cases a + o with e' n' a',
{ exact NF_below.oadd hβ.fst NF_below.zero hβ.lt },
simp [add], have := @cmp_compares _ _ hβ.fst h'.fst,
cases cmp e e'; simp [add],
{ exact h' },
{ simp at this, subst e',
exact NF_below.oadd h'.fst h'.snd h'.lt },
{ exact NF_below.oadd hβ.fst (NF.below_of_lt this β¨β¨_, h'β©β©) hβ.lt }
end
instance add_NF (oβ oβ) : β [NF oβ] [NF oβ], NF (oβ + oβ)
| β¨β¨bβ, hββ©β© β¨β¨bβ, hββ©β© := β¨(bβ.le_total bβ).elim
(Ξ» h, β¨bβ, add_NF_below (hβ.mono h) hββ©)
(Ξ» h, β¨bβ, add_NF_below hβ (hβ.mono h)β©)β©
@[simp] theorem repr_add : β oβ oβ [NF oβ] [NF oβ], repr (oβ + oβ) = repr oβ + repr oβ
| 0 o hβ hβ := by simp
| (oadd e n a) o hβ hβ := begin
haveI := hβ.snd, have h' := repr_add a o,
conv at h' in (_+o) {simp [(+)]},
have nf := onote.add_NF a o,
conv at nf in (_+o) {simp [(+)]},
conv in (_+o) {simp [(+), add]},
cases add a o with e' n' a'; simp [add, h'.symm, add_assoc],
have := hβ.fst, haveI := nf.fst, have ee := cmp_compares e e',
cases cmp e e'; simp [add],
{ rw [β add_assoc, @add_absorp _ (repr e') (Ο ^ repr e' * (n':β))],
{ have := (hβ.below_of_lt ee).repr_lt, unfold repr at this,
exact lt_of_le_of_lt (le_add_right _ _) this },
{ simpa using (mul_le_mul_iff_left $
power_pos (repr e') omega_pos).2 (nat_cast_le.2 n'.pos) } },
{ change e = e' at ee, substI e',
rw [β add_assoc, β ordinal.mul_add, β nat.cast_add] }
end
theorem sub_NF_below : β {oβ oβ b}, NF_below oβ b β NF oβ β NF_below (oβ - oβ) b
| 0 o b hβ hβ := by cases o; exact NF_below.zero
| (oadd e n a) 0 b hβ hβ := hβ
| (oadd eβ nβ aβ) (oadd eβ nβ aβ) b hβ hβ := begin
have h' := sub_NF_below hβ.snd hβ.snd,
simp [has_sub.sub, sub] at h' β’,
have := @cmp_compares _ _ hβ.fst hβ.fst,
cases cmp eβ eβ; simp [sub],
{ apply NF_below.zero },
{ simp at this, subst eβ,
cases mn : (nβ:β) - nβ; simp [sub],
{ by_cases en : nβ = nβ; simp [en],
{ exact h'.mono (le_of_lt hβ.lt) },
{ exact NF_below.zero } },
{ exact NF_below.oadd hβ.fst hβ.snd hβ.lt } },
{ exact hβ }
end
instance sub_NF (oβ oβ) : β [NF oβ] [NF oβ], NF (oβ - oβ)
| β¨β¨bβ, hββ©β© hβ := β¨β¨bβ, sub_NF_below hβ hββ©β©
@[simp] theorem repr_sub : β oβ oβ [NF oβ] [NF oβ], repr (oβ - oβ) = repr oβ - repr oβ
| 0 o hβ hβ := by cases o; exact (ordinal.zero_sub _).symm
| (oadd e n a) 0 hβ hβ := (ordinal.sub_zero _).symm
| (oadd eβ nβ aβ) (oadd eβ nβ aβ) hβ hβ := begin
haveI := hβ.snd, haveI := hβ.snd, have h' := repr_sub aβ aβ,
conv at h' in (aβ-aβ) {simp [has_sub.sub]},
have nf := onote.sub_NF aβ aβ,
conv at nf in (aβ-aβ) {simp [has_sub.sub]},
conv in (_-oadd _ _ _) {simp [has_sub.sub, sub]},
have ee := @cmp_compares _ _ hβ.fst hβ.fst,
cases cmp eβ eβ,
{ rw [sub_eq_zero_iff_le.2], {refl},
exact le_of_lt (oadd_lt_oadd_1 hβ ee) },
{ change eβ = eβ at ee, substI eβ, unfold sub._match_1,
cases mn : (nβ:β) - nβ; dsimp only [sub._match_2],
{ by_cases en : nβ = nβ,
{ simp [en], rwa [add_sub_add_cancel] },
{ simp [en, -repr],
exact (sub_eq_zero_iff_le.2 $ le_of_lt $ oadd_lt_oadd_2 hβ $
lt_of_le_of_ne (nat.sub_eq_zero_iff_le.1 mn) (mt pnat.eq en)).symm } },
{ simp [nat.succ_pnat, -nat.cast_succ],
rw [(nat.sub_eq_iff_eq_add $ le_of_lt $ nat.lt_of_sub_eq_succ mn).1 mn,
add_comm, nat.cast_add, ordinal.mul_add, add_assoc, add_sub_add_cancel],
refine (ordinal.sub_eq_of_add_eq $ add_absorp hβ.snd'.repr_lt $
le_trans _ (le_add_right _ _)).symm,
simpa using mul_le_mul_left _ (nat_cast_le.2 $ nat.succ_pos _) } },
{ exact (ordinal.sub_eq_of_add_eq $ add_absorp (hβ.below_of_lt ee).repr_lt $
omega_le_oadd _ _ _).symm }
end
/-- Multiplication of ordinal notations (correct only for normal input) -/
def mul : onote β onote β onote
| 0 _ := 0
| _ 0 := 0
| oβ@(oadd eβ nβ aβ) (oadd eβ nβ aβ) :=
if eβ = 0 then oadd eβ (nβ * nβ) aβ else
oadd (eβ + eβ) nβ (mul oβ aβ)
instance : has_mul onote := β¨mulβ©
@[simp] theorem zero_mul (o : onote) : 0 * o = 0 := by cases o; refl
@[simp] theorem mul_zero (o : onote) : o * 0 = 0 := by cases o; refl
theorem oadd_mul (eβ nβ aβ eβ nβ aβ) : oadd eβ nβ aβ * oadd eβ nβ aβ =
if eβ = 0 then oadd eβ (nβ * nβ) aβ else
oadd (eβ + eβ) nβ (oadd eβ nβ aβ * aβ) := rfl
theorem oadd_mul_NF_below {eβ nβ aβ bβ} (hβ : NF_below (oadd eβ nβ aβ) bβ) :
β {oβ bβ}, NF_below oβ bβ β NF_below (oadd eβ nβ aβ * oβ) (repr eβ + bβ)
| 0 bβ hβ := NF_below.zero
| (oadd eβ nβ aβ) bβ hβ := begin
have IH := oadd_mul_NF_below hβ.snd,
by_cases e0 : eβ = 0; simp [e0, oadd_mul],
{ apply NF_below.oadd hβ.fst hβ.snd,
simpa using (add_lt_add_iff_left (repr eβ)).2
(lt_of_le_of_lt (ordinal.zero_le _) hβ.lt) },
{ haveI := hβ.fst, haveI := hβ.fst,
apply NF_below.oadd, apply_instance,
{ rwa repr_add },
{ rw [repr_add, ordinal.add_lt_add_iff_left], exact hβ.lt } }
end
instance mul_NF : β oβ oβ [NF oβ] [NF oβ], NF (oβ * oβ)
| 0 o hβ hβ := by cases o; exact NF.zero
| (oadd e n a) o β¨β¨bβ, hbββ©β© β¨β¨bβ, hbββ©β© :=
β¨β¨_, oadd_mul_NF_below hbβ hbββ©β©
@[simp] theorem repr_mul : β oβ oβ [NF oβ] [NF oβ], repr (oβ * oβ) = repr oβ * repr oβ
| 0 o hβ hβ := by cases o; exact (ordinal.zero_mul _).symm
| (oadd eβ nβ aβ) 0 hβ hβ := (ordinal.mul_zero _).symm
| (oadd eβ nβ aβ) (oadd eβ nβ aβ) hβ hβ := begin
have IH : repr (mul _ _) = _ := @repr_mul _ _ hβ hβ.snd,
conv {to_lhs, simp [(*)]},
have ao : repr aβ + Ο ^ repr eβ * (nβ:β) = Ο ^ repr eβ * (nβ:β),
{ apply add_absorp hβ.snd'.repr_lt,
simpa using (mul_le_mul_iff_left $ power_pos _ omega_pos).2
(nat_cast_le.2 nβ.2) },
by_cases e0 : eβ = 0; simp [e0, mul],
{ cases nat.exists_eq_succ_of_ne_zero nβ.ne_zero with x xe,
simp [hβ.zero_of_zero e0, xe, -nat.cast_succ],
rw [β nat_cast_succ x, add_mul_succ _ ao, mul_assoc] },
{ haveI := hβ.fst, haveI := hβ.fst,
simp [IH, repr_add, power_add, ordinal.mul_add],
rw β mul_assoc, congr' 2,
have := mt repr_inj.1 e0,
rw [add_mul_limit ao (power_is_limit_left omega_is_limit this),
mul_assoc, mul_omega_dvd (nat_cast_pos.2 nβ.pos) (nat_lt_omega _)],
simpa using power_dvd_power Ο (one_le_iff_ne_zero.2 this) },
end
/-- Calculate division and remainder of `o` mod Ο.
`split' o = (a, n)` means `o = Ο * a + n`. -/
def split' : onote β onote Γ β
| 0 := (0, 0)
| (oadd e n a) := if e = 0 then (0, n) else
let (a', m) := split' a in (oadd (e - 1) n a', m)
/-- Calculate division and remainder of `o` mod Ο.
`split o = (a, n)` means `o = a + n`, where `Ο β£ a`. -/
def split : onote β onote Γ β
| 0 := (0, 0)
| (oadd e n a) := if e = 0 then (0, n) else
let (a', m) := split a in (oadd e n a', m)
/-- `scale x o` is the ordinal notation for `Ο ^ x * o`. -/
def scale (x : onote) : onote β onote
| 0 := 0
| (oadd e n a) := oadd (x + e) n (scale a)
/-- `mul_nat o n` is the ordinal notation for `o * n`. -/
def mul_nat : onote β β β onote
| 0 m := 0
| _ 0 := 0
| (oadd e n a) (m+1) := oadd e (n * m.succ_pnat) a
/-- Auxiliary definition to compute the ordinal notation for the ordinal
exponentiation in `power` -/
def power_aux (e a0 a : onote) : β β β β onote
| _ 0 := 0
| 0 (m+1) := oadd e m.succ_pnat 0
| (k+1) m := scale (e + mul_nat a0 k) a + power_aux k m
/-- `power oβ oβ` calculates the ordinal notation for
the ordinal exponential `oβ ^ oβ`. -/
def power (oβ oβ : onote) : onote :=
match split oβ with
| (0, 0) := if oβ = 0 then 1 else 0
| (0, 1) := 1
| (0, m+1) := let (b', k) := split' oβ in
oadd b' (@has_pow.pow β+ _ _ m.succ_pnat k) 0
| (a@(oadd a0 _ _), m) := match split oβ with
| (b, 0) := oadd (a0 * b) 1 0
| (b, k+1) := let eb := a0*b in
scale (eb + mul_nat a0 k) a + power_aux eb a0 (mul_nat a m) k m
end
end
instance : has_pow onote onote := β¨powerβ©
theorem power_def (oβ oβ : onote) : oβ ^ oβ = power._match_1 oβ (split oβ) := rfl
theorem split_eq_scale_split' : β {o o' m} [NF o], split' o = (o', m) β split o = (scale 1 o', m)
| 0 o' m h p := by injection p; substs o' m; refl
| (oadd e n a) o' m h p := begin
by_cases e0 : e = 0; simp [e0, split, split'] at p β’,
{ rcases p with β¨rfl, rflβ©, exact β¨rfl, rflβ© },
{ revert p, cases h' : split' a with a' m',
haveI := h.fst, haveI := h.snd,
simp [split_eq_scale_split' h', split, split'],
have : 1 + (e - 1) = e,
{ refine repr_inj.1 _, simp,
have := mt repr_inj.1 e0,
exact add_sub_cancel_of_le (one_le_iff_ne_zero.2 this) },
intros, substs o' m, simp [scale, this] }
end
theorem NF_repr_split' : β {o o' m} [NF o], split' o = (o', m) β NF o' β§ repr o = Ο * repr o' + m
| 0 o' m h p := by injection p; substs o' m; simp [NF.zero]
| (oadd e n a) o' m h p := begin
by_cases e0 : e = 0; simp [e0, split, split'] at p β’,
{ rcases p with β¨rfl, rflβ©,
simp [h.zero_of_zero e0, NF.zero] },
{ revert p, cases h' : split' a with a' m',
haveI := h.fst, haveI := h.snd,
cases NF_repr_split' h' with IHβ IHβ,
simp [IHβ, split'],
intros, substs o' m,
have : Ο ^ repr e = Ο ^ (1 : ordinal.{0}) * Ο ^ (repr e - 1),
{ have := mt repr_inj.1 e0,
rw [β power_add, add_sub_cancel_of_le (one_le_iff_ne_zero.2 this)] },
refine β¨NF.oadd (by apply_instance) _ _, _β©,
{ simp at this β’,
refine IHβ.below_of_lt' ((mul_lt_mul_iff_left omega_pos).1 $
lt_of_le_of_lt (le_add_right _ m') _),
rw [β this, β IHβ], exact h.snd'.repr_lt },
{ rw this, simp [ordinal.mul_add, mul_assoc, add_assoc] } }
end
theorem scale_eq_mul (x) [NF x] : β o [NF o], scale x o = oadd x 1 0 * o
| 0 h := rfl
| (oadd e n a) h := begin
simp [(*)], simp [mul, scale],
haveI := h.snd,
by_cases e0 : e = 0,
{ rw scale_eq_mul, simp [e0, h.zero_of_zero, show x + 0 = x, from repr_inj.1 (by simp)] },
{ simp [e0, scale_eq_mul, (*)] }
end
instance NF_scale (x) [NF x] (o) [NF o] : NF (scale x o) :=
by rw scale_eq_mul; apply_instance
@[simp] theorem repr_scale (x) [NF x] (o) [NF o] : repr (scale x o) = Ο ^ repr x * repr o :=
by simp [scale_eq_mul]
theorem NF_repr_split {o o' m} [NF o] (h : split o = (o', m)) : NF o' β§ repr o = repr o' + m :=
begin
cases e : split' o with a n,
cases NF_repr_split' e with sβ sβ, resetI,
rw split_eq_scale_split' e at h,
injection h, substs o' n,
simp [repr_scale, sβ.symm],
apply_instance
end
theorem split_dvd {o o' m} [NF o] (h : split o = (o', m)) : Ο β£ repr o' :=
begin
cases e : split' o with a n,
rw split_eq_scale_split' e at h,
injection h, subst o',
cases NF_repr_split' e, resetI, simp
end
theorem split_add_lt {o e n a m} [NF o] (h : split o = (oadd e n a, m)) : repr a + m < Ο ^ repr e :=
begin
cases NF_repr_split h with hβ hβ,
cases hβ.of_dvd_omega (split_dvd h) with e0 d,
have := hβ.fst, have := hβ.snd,
refine add_lt_omega_power hβ.snd'.repr_lt (lt_of_lt_of_le (nat_lt_omega _) _),
simpa using power_le_power_right omega_pos (one_le_iff_ne_zero.2 e0),
end
@[simp] theorem mul_nat_eq_mul (n o) : mul_nat o n = o * of_nat n :=
by cases o; cases n; refl
instance NF_mul_nat (o) [NF o] (n) : NF (mul_nat o n) :=
by simp; apply_instance
instance NF_power_aux (e a0 a) [NF e] [NF a0] [NF a] : β k m, NF (power_aux e a0 a k m)
| k 0 := by cases k; exact NF.zero
| 0 (m+1) := NF.oadd_zero _ _
| (k+1) (m+1) := by haveI := NF_power_aux k;
simp [power_aux, nat.succ_ne_zero]; apply_instance
instance NF_power (oβ oβ) [NF oβ] [NF oβ] : NF (oβ ^ oβ) :=
begin
cases eβ : split oβ with a m,
have na := (NF_repr_split eβ).1,
cases eβ : split' oβ with b' k,
haveI := (NF_repr_split' eβ).1,
casesI a with a0 n a',
{ cases m with m,
{ by_cases oβ = 0; simp [pow, power, *]; apply_instance },
{ by_cases m = 0,
{ simp only [pow, power, *, zero_def], apply_instance },
{ simp [pow, power, *, - npow_eq_pow], apply_instance } } },
{ simp [pow, power, eβ, eβ, split_eq_scale_split' eβ],
have := na.fst,
cases k with k; simp [succ_eq_add_one, power]; resetI; apply_instance }
end
theorem scale_power_aux (e a0 a : onote) [NF e] [NF a0] [NF a] :
β k m, repr (power_aux e a0 a k m) = Ο ^ repr e * repr (power_aux 0 a0 a k m)
| 0 m := by cases m; simp [power_aux]
| (k+1) m := by by_cases m = 0; simp [h, power_aux,
ordinal.mul_add, power_add, mul_assoc, scale_power_aux]
theorem repr_power_auxβ {e a} [Ne : NF e] [Na : NF a] {a' : ordinal}
(e0 : repr e β 0) (h : a' < Ο ^ repr e) (aa : repr a = a') (n : β+) :
(Ο ^ repr e * (n:β) + a') ^ Ο = (Ο ^ repr e) ^ Ο :=
begin
subst aa,
have No := Ne.oadd n (Na.below_of_lt' h),
have := omega_le_oadd e n a, unfold repr at this,
refine le_antisymm _ (power_le_power_left _ this),
apply (power_le_of_limit
(ne_of_gt $ lt_of_lt_of_le (power_pos _ omega_pos) this) omega_is_limit).2,
intros b l,
have := (No.below_of_lt (lt_succ_self _)).repr_lt, unfold repr at this,
apply le_trans (power_le_power_left b $ le_of_lt this),
rw [β power_mul, β power_mul],
apply power_le_power_right omega_pos,
cases le_or_lt Ο (repr e) with h h,
{ apply le_trans (mul_le_mul_left _ $ le_of_lt $ lt_succ_self _),
rw [succ, add_mul_succ _ (one_add_of_omega_le h), β succ,
succ_le, mul_lt_mul_iff_left (ordinal.pos_iff_ne_zero.2 e0)],
exact omega_is_limit.2 _ l },
{ refine le_trans (le_of_lt $ mul_lt_omega (omega_is_limit.2 _ h) l) _,
simpa using mul_le_mul_right Ο (one_le_iff_ne_zero.2 e0) }
end
section
local infixr ^ := @pow ordinal.{0} ordinal ordinal.has_pow
theorem repr_power_auxβ {a0 a'} [N0 : NF a0] [Na' : NF a'] (m : β)
(d : Ο β£ repr a')
(e0 : repr a0 β 0) (h : repr a' + m < Ο ^ repr a0) (n : β+) (k : β) :
let R := repr (power_aux 0 a0 (oadd a0 n a' * of_nat m) k m) in
(k β 0 β R < (Ο ^ repr a0) ^ succ k) β§
(Ο ^ repr a0) ^ k * (Ο ^ repr a0 * (n:β) + repr a') + R =
(Ο ^ repr a0 * (n:β) + repr a' + m) ^ succ k :=
begin
intro,
haveI No : NF (oadd a0 n a') :=
N0.oadd n (Na'.below_of_lt' $ lt_of_le_of_lt (le_add_right _ _) h),
induction k with k IH, {cases m; simp [power_aux, R]},
rename R R', let R := repr (power_aux 0 a0 (oadd a0 n a' * of_nat m) k m),
let Ο0 := Ο ^ repr a0, let Ξ±' := Ο0 * n + repr a',
change (k β 0 β R < Ο0 ^ succ k) β§ Ο0 ^ k * Ξ±' + R = (Ξ±' + m) ^ succ k at IH,
have RR : R' = Ο0 ^ k * (Ξ±' * m) + R,
{ by_cases m = 0; simp [h, R', power_aux, R, power_mul],
{ cases k; simp [power_aux] }, { refl } },
have Ξ±0 : 0 < Ξ±', {simpa [Ξ±', lt_def, repr] using oadd_pos a0 n a'},
have Ο00 : 0 < Ο0 ^ k := power_pos _ (power_pos _ omega_pos),
have Rl : R < Ο ^ (repr a0 * succ βk),
{ by_cases k0 : k = 0,
{ simp [k0],
refine lt_of_lt_of_le _ (power_le_power_right omega_pos (one_le_iff_ne_zero.2 e0)),
cases m with m; simp [k0, R, power_aux, omega_pos],
rw [β nat.cast_succ], apply nat_lt_omega },
{ rw power_mul, exact IH.1 k0 } },
refine β¨Ξ»_, _, _β©,
{ rw [RR, β power_mul _ _ (succ k.succ)],
have e0 := ordinal.pos_iff_ne_zero.2 e0,
have rr0 := lt_of_lt_of_le e0 (le_add_left _ _),
apply add_lt_omega_power,
{ simp [power_mul, Ο0, power_add, mul_assoc],
rw [mul_lt_mul_iff_left Ο00, β ordinal.power_add],
have := (No.below_of_lt _).repr_lt, unfold repr at this,
refine mul_lt_omega_power rr0 this (nat_lt_omega _),
simpa using (add_lt_add_iff_left (repr a0)).2 e0 },
{ refine lt_of_lt_of_le Rl (power_le_power_right omega_pos $
mul_le_mul_left _ $ succ_le_succ.2 $ nat_cast_le.2 $ le_of_lt k.lt_succ_self) } },
refine calc
Ο0 ^ k.succ * Ξ±' + R'
= Ο0 ^ succ k * Ξ±' + (Ο0 ^ k * Ξ±' * m + R) : by rw [nat_cast_succ, RR, β mul_assoc]
... = (Ο0 ^ k * Ξ±' + R) * Ξ±' + (Ο0 ^ k * Ξ±' + R) * m : _
... = (Ξ±' + m) ^ succ k.succ : by rw [β ordinal.mul_add, β nat_cast_succ, power_succ, IH.2],
congr' 1,
{ have Ξ±d : Ο β£ Ξ±' := dvd_add (dvd_mul_of_dvd_left
(by simpa using power_dvd_power Ο (one_le_iff_ne_zero.2 e0)) _) d,
rw [ordinal.mul_add (Ο0 ^ k), add_assoc, β mul_assoc, β power_succ,
add_mul_limit _ (is_limit_iff_omega_dvd.2 β¨ne_of_gt Ξ±0, Ξ±dβ©), mul_assoc,
@mul_omega_dvd n (nat_cast_pos.2 n.pos) (nat_lt_omega _) _ Ξ±d],
apply @add_absorp _ (repr a0 * succ k),
{ refine add_lt_omega_power _ Rl,
rw [power_mul, power_succ, mul_lt_mul_iff_left Ο00],
exact No.snd'.repr_lt },
{ have := mul_le_mul_left (Ο0 ^ succ k) (one_le_iff_pos.2 $ nat_cast_pos.2 n.pos),
rw power_mul, simpa [-power_succ] } },
{ cases m,
{ have : R = 0, {cases k; simp [R, power_aux]}, simp [this] },
{ rw [β nat_cast_succ, add_mul_succ],
apply add_absorp Rl,
rw [power_mul, power_succ],
apply ordinal.mul_le_mul_left,
simpa [Ξ±', repr] using omega_le_oadd a0 n a' } }
end
end
theorem repr_power (oβ oβ) [NF oβ] [NF oβ] : repr (oβ ^ oβ) = repr oβ ^ repr oβ :=
begin
cases eβ : split oβ with a m,
cases NF_repr_split eβ with Nβ rβ,
cases a with a0 n a',
{ cases m with m,
{ by_cases oβ = 0; simp [power_def, power, eβ, h, rβ],
have := mt repr_inj.1 h, rw zero_power this },
{ cases eβ : split' oβ with b' k,
cases NF_repr_split' eβ with _ rβ,
by_cases m = 0; simp [power_def, power, eβ, h, rβ, eβ, rβ, -nat.cast_succ],
rw [power_add, power_mul, power_omega _ (nat_lt_omega _)],
simpa using nat_cast_lt.2 (nat.succ_lt_succ $ pos_iff_ne_zero.2 h) } },
{ haveI := Nβ.fst, haveI := Nβ.snd,
cases Nβ.of_dvd_omega (split_dvd eβ) with a00 ad,
have al := split_add_lt eβ,
have aa : repr (a' + of_nat m) = repr a' + m, {simp},
cases eβ : split' oβ with b' k,
cases NF_repr_split' eβ with _ rβ,
simp [power_def, power, eβ, rβ, split_eq_scale_split' eβ],
cases k with k; resetI,
{ simp [power, rβ, power_mul, repr_power_auxβ a00 al aa, add_assoc] },
{ simp [succ_eq_add_one, power, rβ, power_add, power_mul, mul_assoc, add_assoc],
rw [repr_power_auxβ a00 al aa, scale_power_aux], simp [power_mul],
rw [β ordinal.mul_add, β add_assoc (Ο ^ repr a0 * (n:β))], congr' 1,
rw [β power_succ],
exact (repr_power_auxβ _ ad a00 al _ _).2 } }
end
end onote
/-- The type of normal ordinal notations. (It would have been
nicer to define this right in the inductive type, but `NF o`
requires `repr` which requires `onote`, so all these things
would have to be defined at once, which messes up the VM
representation.) -/
def nonote := {o : onote // o.NF}
instance : decidable_eq nonote := by unfold nonote; apply_instance
namespace nonote
open onote
instance NF (o : nonote) : NF o.1 := o.2
/-- Construct a `nonote` from an ordinal notation
(and infer normality) -/
def mk (o : onote) [h : NF o] : nonote := β¨o, hβ©
/-- The ordinal represented by an ordinal notation.
(This function is noncomputable because ordinal
arithmetic is noncomputable. In computational applications
`nonote` can be used exclusively without reference
to `ordinal`, but this function allows for correctness
results to be stated.) -/
noncomputable def repr (o : nonote) : ordinal := o.1.repr
instance : has_to_string nonote := β¨Ξ» x, x.1.to_stringβ©
instance : has_repr nonote := β¨Ξ» x, x.1.repr'β©
instance : preorder nonote :=
{ le := Ξ» x y, repr x β€ repr y,
lt := Ξ» x y, repr x < repr y,
le_refl := Ξ» a, @le_refl ordinal _ _,
le_trans := Ξ» a b c, @le_trans ordinal _ _ _ _,
lt_iff_le_not_le := Ξ» a b, @lt_iff_le_not_le ordinal _ _ _ }
instance : has_zero nonote := β¨β¨0, NF.zeroβ©β©
instance : inhabited nonote := β¨0β©
/-- Convert a natural number to an ordinal notation -/
def of_nat (n : β) : nonote := β¨of_nat n, β¨β¨_, NF_below_of_nat _β©β©β©
/-- Compare ordinal notations -/
def cmp (a b : nonote) : ordering :=
cmp a.1 b.1
theorem cmp_compares : β a b : nonote, (cmp a b).compares a b
| β¨a, haβ© β¨b, hbβ© := begin
resetI,
dsimp [cmp], have := onote.cmp_compares a b,
cases onote.cmp a b; try {exact this},
exact subtype.mk_eq_mk.2 this
end
instance : linear_order nonote := linear_order_of_compares cmp cmp_compares
/-- Asserts that `repr a < Ο ^ repr b`. Used in `nonote.rec_on` -/
def below (a b : nonote) : Prop := NF_below a.1 (repr b)
/-- The `oadd` pseudo-constructor for `nonote` -/
def oadd (e : nonote) (n : β+) (a : nonote) (h : below a e) : nonote := β¨_, NF.oadd e.2 n hβ©
/-- This is a recursor-like theorem for `nonote` suggesting an
inductive definition, which can't actually be defined this
way due to conflicting dependencies. -/
@[elab_as_eliminator] def rec_on {C : nonote β Sort*} (o : nonote)
(H0 : C 0)
(H1 : β e n a h, C e β C a β C (oadd e n a h)) : C o :=
begin
cases o with o h, induction o with e n a IHe IHa,
{ exact H0 },
{ exact H1 β¨e, h.fstβ© n β¨a, h.sndβ© h.snd' (IHe _) (IHa _) }
end
/-- Addition of ordinal notations -/
instance : has_add nonote := β¨Ξ» x y, mk (x.1 + y.1)β©
theorem repr_add (a b) : repr (a + b) = repr a + repr b :=
onote.repr_add a.1 b.1
/-- Subtraction of ordinal notations -/
instance : has_sub nonote := β¨Ξ» x y, mk (x.1 - y.1)β©
theorem repr_sub (a b) : repr (a - b) = repr a - repr b :=
onote.repr_sub a.1 b.1
/-- Multiplication of ordinal notations -/
instance : has_mul nonote := β¨Ξ» x y, mk (x.1 * y.1)β©
theorem repr_mul (a b) : repr (a * b) = repr a * repr b :=
onote.repr_mul a.1 b.1
/-- Exponentiation of ordinal notations -/
def power (x y : nonote) := mk (x.1.power y.1)
theorem repr_power (a b) : repr (power a b) = (repr a).power (repr b) :=
onote.repr_power a.1 b.1
end nonote
|
7a30cd1307f685cb6223b1de63ade51ea1fd432a | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/polynomial/basic.lean | f9abb04851f25388d9a381b6c3cc353b359f5574 | [
"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 | 48,803 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.char_p.basic
import data.mv_polynomial.comm_ring
import data.mv_polynomial.equiv
import ring_theory.polynomial.content
import ring_theory.unique_factorization_domain
/-!
# Ring-theoretic supplement of data.polynomial.
## Main results
* `mv_polynomial.is_domain`:
If a ring is an integral domain, then so is its polynomial ring over finitely many variables.
* `polynomial.is_noetherian_ring`:
Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring.
* `polynomial.wf_dvd_monoid`:
If an integral domain is a `wf_dvd_monoid`, then so is its polynomial ring.
* `polynomial.unique_factorization_monoid`, `mv_polynomial.unique_factorization_monoid`:
If an integral domain is a `unique_factorization_monoid`, then so is its polynomial ring (of any
number of variables).
-/
noncomputable theory
open_locale classical big_operators polynomial
universes u v w
variables {R : Type u} {S : Type*}
namespace polynomial
section semiring
variables [semiring R]
instance (p : β) [h : char_p R p] : char_p R[X] p :=
let β¨hβ© := h in β¨Ξ» n, by rw [β map_nat_cast C, β C_0, C_inj, h]β©
variables (R)
/-- The `R`-submodule of `R[X]` consisting of polynomials of degree β€ `n`. -/
def degree_le (n : with_bot β) : submodule R R[X] :=
β¨
k : β, β¨
h : βk > n, (lcoeff R k).ker
/-- The `R`-submodule of `R[X]` consisting of polynomials of degree < `n`. -/
def degree_lt (n : β) : submodule R R[X] :=
β¨
k : β, β¨
h : k β₯ n, (lcoeff R k).ker
variable {R}
theorem mem_degree_le {n : with_bot β} {f : R[X]} :
f β degree_le R n β degree f β€ n :=
by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl
@[mono] theorem degree_le_mono {m n : with_bot β} (H : m β€ n) :
degree_le R m β€ degree_le R n :=
Ξ» f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H)
theorem degree_le_eq_span_X_pow {n : β} :
degree_le R n = submodule.span R β((finset.range (n+1)).image (Ξ» n, (X : R[X])^n)) :=
begin
apply le_antisymm,
{ intros p hp, replace hp := mem_degree_le.1 hp,
rw [β polynomial.sum_monomial_eq p, polynomial.sum],
refine submodule.sum_mem _ (Ξ» k hk, _),
show monomial _ _ β _,
have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk),
rw [monomial_eq_C_mul_X, C_mul'],
refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $
finset.mem_image.2 β¨_, finset.mem_range.2 (nat.lt_succ_of_le this), rflβ©) },
rw [submodule.span_le, finset.coe_image, set.image_subset_iff],
intros k hk, apply mem_degree_le.2,
exact (degree_X_pow_le _).trans
(with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk)
end
theorem mem_degree_lt {n : β} {f : R[X]} :
f β degree_lt R n β degree f < n :=
by { simp_rw [degree_lt, submodule.mem_infi, linear_map.mem_ker, degree,
finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe,
with_bot.coe_lt_coe, lt_iff_not_le, ne, not_imp_not], refl }
@[mono] theorem degree_lt_mono {m n : β} (H : m β€ n) :
degree_lt R m β€ degree_lt R n :=
Ξ» f hf, mem_degree_lt.2 (lt_of_lt_of_le (mem_degree_lt.1 hf) $ with_bot.coe_le_coe.2 H)
theorem degree_lt_eq_span_X_pow {n : β} :
degree_lt R n = submodule.span R β((finset.range n).image (Ξ» n, X^n) : finset R[X]) :=
begin
apply le_antisymm,
{ intros p hp, replace hp := mem_degree_lt.1 hp,
rw [β polynomial.sum_monomial_eq p, polynomial.sum],
refine submodule.sum_mem _ (Ξ» k hk, _),
show monomial _ _ β _,
have := with_bot.coe_lt_coe.1 ((finset.sup_lt_iff $ with_bot.bot_lt_coe n).1 hp k hk),
rw [monomial_eq_C_mul_X, C_mul'],
refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $
finset.mem_image.2 β¨_, finset.mem_range.2 this, rflβ©) },
rw [submodule.span_le, finset.coe_image, set.image_subset_iff],
intros k hk, apply mem_degree_lt.2,
exact lt_of_le_of_lt (degree_X_pow_le _) (with_bot.coe_lt_coe.2 $ finset.mem_range.1 hk)
end
/-- The first `n` coefficients on `degree_lt n` form a linear equivalence with `fin n β R`. -/
def degree_lt_equiv (R) [semiring R] (n : β) : degree_lt R n ββ[R] (fin n β R) :=
{ to_fun := Ξ» p n, (βp : R[X]).coeff n,
inv_fun := Ξ» f, β¨β i : fin n, monomial i (f i),
(degree_lt R n).sum_mem (Ξ» i _, mem_degree_lt.mpr (lt_of_le_of_lt
(degree_monomial_le i (f i)) (with_bot.coe_lt_coe.mpr i.is_lt)))β©,
map_add' := Ξ» p q, by { ext, rw [submodule.coe_add, coeff_add], refl },
map_smul' := Ξ» x p, by { ext, rw [submodule.coe_smul, coeff_smul], refl },
left_inv :=
begin
rintro β¨p, hpβ©, ext1,
simp only [submodule.coe_mk],
by_cases hp0 : p = 0,
{ subst hp0, simp only [coeff_zero, linear_map.map_zero, finset.sum_const_zero] },
rw [mem_degree_lt, degree_eq_nat_degree hp0, with_bot.coe_lt_coe] at hp,
conv_rhs { rw [p.as_sum_range' n hp, β fin.sum_univ_eq_sum_range] },
end,
right_inv :=
begin
intro f, ext i,
simp only [finset_sum_coeff, submodule.coe_mk],
rw [finset.sum_eq_single i, coeff_monomial, if_pos rfl],
{ rintro j - hji, rw [coeff_monomial, if_neg], rwa [β subtype.ext_iff] },
{ intro h, exact (h (finset.mem_univ _)).elim }
end }
/-- The finset of nonzero coefficients of a polynomial. -/
def frange (p : R[X]) : finset R :=
finset.image (Ξ» n, p.coeff n) p.support
lemma frange_zero : frange (0 : R[X]) = β
:=
rfl
lemma mem_frange_iff {p : R[X]} {c : R} :
c β p.frange β β n β p.support, c = p.coeff n :=
by simp [frange, eq_comm]
lemma frange_one : frange (1 : R[X]) β {1} :=
begin
simp [frange, finset.image_subset_iff],
simp only [β C_1, coeff_C],
assume n hn,
simp only [exists_prop, ite_eq_right_iff, not_forall] at hn,
simp [hn],
end
lemma coeff_mem_frange (p : R[X]) (n : β) (h : p.coeff n β 0) :
p.coeff n β p.frange :=
begin
simp only [frange, exists_prop, mem_support_iff, finset.mem_image, ne.def],
exact β¨n, h, rflβ©,
end
lemma geom_sum_X_comp_X_add_one_eq_sum (n : β) :
(geom_sum (X : R[X]) n).comp (X + 1) =
(finset.range n).sum (Ξ» (i : β), (n.choose (i + 1) : R[X]) * X ^ i) :=
begin
ext i,
transitivity (n.choose (i + 1) : R), swap,
{ simp only [finset_sum_coeff, β C_eq_nat_cast, coeff_C_mul_X_pow],
rw [finset.sum_eq_single i, if_pos rfl],
{ simp only [@eq_comm _ i, if_false, eq_self_iff_true, implies_true_iff] {contextual := tt}, },
{ simp only [nat.lt_add_one_iff, nat.choose_eq_zero_of_lt, nat.cast_zero, finset.mem_range,
not_lt, eq_self_iff_true, if_true, implies_true_iff] {contextual := tt}, } },
induction n with n ih generalizing i,
{ simp only [geom_sum_zero, zero_comp, coeff_zero, nat.choose_zero_succ, nat.cast_zero], },
simp only [geom_sum_succ', ih, add_comp, X_pow_comp, coeff_add, nat.choose_succ_succ,
nat.cast_add, coeff_X_add_one_pow],
end
lemma monic.geom_sum {P : R[X]}
(hP : P.monic) (hdeg : 0 < P.nat_degree) {n : β} (hn : n β 0) : (geom_sum P n).monic :=
begin
nontriviality R,
cases n, { exact (hn rfl).elim },
rw [geom_sum_succ', geom_sum_def],
refine (hP.pow _).add_of_left _,
refine lt_of_le_of_lt (degree_sum_le _ _) _,
rw [finset.sup_lt_iff],
{ simp only [finset.mem_range, degree_eq_nat_degree (hP.pow _).ne_zero,
with_bot.coe_lt_coe, hP.nat_degree_pow],
intro k, exact nsmul_lt_nsmul hdeg },
{ rw [bot_lt_iff_ne_bot, ne.def, degree_eq_bot],
exact (hP.pow _).ne_zero }
end
lemma monic.geom_sum' {P : R[X]}
(hP : P.monic) (hdeg : 0 < P.degree) {n : β} (hn : n β 0) : (geom_sum P n).monic :=
hP.geom_sum (nat_degree_pos_iff_degree_pos.2 hdeg) hn
lemma monic_geom_sum_X {n : β} (hn : n β 0) :
(geom_sum (X : R[X]) n).monic :=
begin
nontriviality R,
apply monic_X.geom_sum _ hn,
simpa only [nat_degree_X] using zero_lt_one
end
end semiring
section ring
variables [ring R]
/-- Given a polynomial, return the polynomial whose coefficients are in
the ring closure of the original coefficients. -/
def restriction (p : R[X]) : polynomial (subring.closure (βp.frange : set R)) :=
β i in p.support, monomial i (β¨p.coeff i,
if H : p.coeff i = 0 then H.symm βΈ (subring.closure _).zero_mem
else subring.subset_closure (p.coeff_mem_frange _ H)β© : (subring.closure (βp.frange : set R)))
@[simp] theorem coeff_restriction {p : R[X]} {n : β} :
β(coeff (restriction p) n) = coeff p n :=
begin
simp only [restriction, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq',
ne.def, ite_not],
split_ifs,
{ rw h, refl },
{ refl }
end
@[simp] theorem coeff_restriction' {p : R[X]} {n : β} :
(coeff (restriction p) n).1 = coeff p n :=
coeff_restriction
@[simp] lemma support_restriction (p : R[X]) :
support (restriction p) = support p :=
begin
ext i,
simp only [mem_support_iff, not_iff_not, ne.def],
conv_rhs { rw [β coeff_restriction] },
exact β¨Ξ» H, by { rw H, refl }, Ξ» H, subtype.coe_injective Hβ©
end
@[simp] theorem map_restriction {R : Type u} [comm_ring R]
(p : R[X]) : p.restriction.map (algebra_map _ _) = p :=
ext $ Ξ» n, by rw [coeff_map, algebra.algebra_map_of_subring_apply, coeff_restriction]
@[simp] theorem degree_restriction {p : R[X]} : (restriction p).degree = p.degree :=
by simp [degree]
@[simp] theorem nat_degree_restriction {p : R[X]} :
(restriction p).nat_degree = p.nat_degree :=
by simp [nat_degree]
@[simp] theorem monic_restriction {p : R[X]} : monic (restriction p) β monic p :=
begin
simp only [monic, leading_coeff, nat_degree_restriction],
rw [β@coeff_restriction _ _ p],
exact β¨Ξ» H, by { rw H, refl }, Ξ» H, subtype.coe_injective Hβ©
end
@[simp] theorem restriction_zero : restriction (0 : R[X]) = 0 :=
by simp only [restriction, finset.sum_empty, support_zero]
@[simp] theorem restriction_one : restriction (1 : R[X]) = 1 :=
ext $ Ξ» i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl
variables [semiring S] {f : R β+* S} {x : S}
theorem evalβ_restriction {p : R[X]} :
evalβ f x p =
evalβ (f.comp (subring.subtype (subring.closure (p.frange : set R)))) x p.restriction :=
begin
simp only [evalβ_eq_sum, sum, support_restriction, β@coeff_restriction _ _ p],
refl,
end
section to_subring
variables (p : R[X]) (T : subring R)
/-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`,
return the corresponding polynomial whose coefficients are in `T`. -/
def to_subring (hp : (βp.frange : set R) β T) : T[X] :=
β i in p.support, monomial i (β¨p.coeff i,
if H : p.coeff i = 0 then H.symm βΈ T.zero_mem
else hp (p.coeff_mem_frange _ H)β© : T)
variables (hp : (βp.frange : set R) β T)
include hp
@[simp] theorem coeff_to_subring {n : β} : β(coeff (to_subring p T hp) n) = coeff p n :=
begin
simp only [to_subring, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq',
ne.def, ite_not],
split_ifs,
{ rw h, refl },
{ refl }
end
@[simp] theorem coeff_to_subring' {n : β} : (coeff (to_subring p T hp) n).1 = coeff p n :=
coeff_to_subring _ _ hp
@[simp] lemma support_to_subring :
support (to_subring p T hp) = support p :=
begin
ext i,
simp only [mem_support_iff, not_iff_not, ne.def],
conv_rhs { rw [β coeff_to_subring p T hp] },
exact β¨Ξ» H, by { rw H, refl }, Ξ» H, subtype.coe_injective Hβ©
end
@[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree :=
by simp [degree]
@[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree :=
by simp [nat_degree]
@[simp] theorem monic_to_subring : monic (to_subring p T hp) β monic p :=
begin
simp_rw [monic, leading_coeff, nat_degree_to_subring, β coeff_to_subring p T hp],
exact β¨Ξ» H, by { rw H, refl }, Ξ» H, subtype.coe_injective Hβ©
end
omit hp
@[simp] theorem to_subring_zero : to_subring (0 : R[X]) T (by simp [frange_zero]) = 0 :=
by { ext i, simp }
@[simp] theorem to_subring_one : to_subring (1 : R[X]) T
(set.subset.trans frange_one $finset.singleton_subset_set_iff.2 T.one_mem) = 1 :=
ext $ Ξ» i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl
@[simp] theorem map_to_subring : (p.to_subring T hp).map (subring.subtype T) = p :=
by { ext n, simp [coeff_map] }
end to_subring
variables (T : subring R)
/-- Given a polynomial whose coefficients are in some subring, return
the corresponding polynomial whose coefficients are in the ambient ring. -/
def of_subring (p : T[X]) : R[X] :=
β i in p.support, monomial i (p.coeff i : R)
lemma coeff_of_subring (p : T[X]) (n : β) :
coeff (of_subring T p) n = (coeff p n : T) :=
begin
simp only [of_subring, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq',
ite_eq_right_iff, ne.def, ite_not, not_not, ite_eq_left_iff],
assume h,
rw h,
refl
end
@[simp] theorem frange_of_subring {p : T[X]} :
(β(p.of_subring T).frange : set R) β T :=
begin
assume i hi,
simp only [frange, set.mem_image, mem_support_iff, ne.def, finset.mem_coe, finset.coe_image]
at hi,
rcases hi with β¨n, hn, h'nβ©,
rw [β h'n, coeff_of_subring],
exact subtype.mem (coeff p n : T)
end
end ring
section comm_ring
variables [comm_ring R]
section mod_by_monic
variables {q : R[X]}
lemma mem_ker_mod_by_monic (hq : q.monic) {p : R[X]} :
p β (mod_by_monic_hom q).ker β q β£ p :=
linear_map.mem_ker.trans (dvd_iff_mod_by_monic_eq_zero hq)
@[simp] lemma ker_mod_by_monic_hom (hq : q.monic) :
(polynomial.mod_by_monic_hom q).ker = (ideal.span {q}).restrict_scalars R :=
submodule.ext (Ξ» f, (mem_ker_mod_by_monic hq).trans ideal.mem_span_singleton.symm)
end mod_by_monic
end comm_ring
end polynomial
namespace ideal
open polynomial
section semiring
variables [semiring R]
/-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/
def of_polynomial (I : ideal R[X]) : submodule R R[X] :=
{ carrier := I.carrier,
zero_mem' := I.zero_mem,
add_mem' := Ξ» _ _, I.add_mem,
smul_mem' := Ξ» c x H, by { rw [β C_mul'], exact I.mul_mem_left _ H } }
variables {I : ideal R[X]}
theorem mem_of_polynomial (x) : x β I.of_polynomial β x β I := iff.rfl
variables (I)
/-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I`
consisting of polynomials of degree β€ `n`. -/
def degree_le (n : with_bot β) : submodule R R[X] :=
degree_le R n β I.of_polynomial
/-- Given an ideal `I` of `R[X]`, make the ideal in `R` of
leading coefficients of polynomials in `I` with degree β€ `n`. -/
def leading_coeff_nth (n : β) : ideal R :=
(I.degree_le n).map $ lcoeff R n
/-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the
leading coefficients in `I`. -/
def leading_coeff : ideal R :=
β¨ n : β, I.leading_coeff_nth n
end semiring
section comm_semiring
variables [comm_semiring R] [semiring S]
/-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself -/
lemma polynomial_mem_ideal_of_coeff_mem_ideal (I : ideal R[X]) (p : R[X])
(hp : β (n : β), (p.coeff n) β I.comap C) : p β I :=
sum_C_mul_X_eq p βΈ submodule.sum_mem I (Ξ» n hn, I.mul_mem_right _ (hp n))
/-- The push-forward of an ideal `I` of `R` to `polynomial R` via inclusion
is exactly the set of polynomials whose coefficients are in `I` -/
theorem mem_map_C_iff {I : ideal R} {f : R[X]} :
f β (ideal.map C I : ideal R[X]) β β n : β, f.coeff n β I :=
begin
split,
{ intros hf,
apply submodule.span_induction hf,
{ intros f hf n,
cases (set.mem_image _ _ _).mp hf with x hx,
rw [β hx.right, coeff_C],
by_cases (n = 0),
{ simpa [h] using hx.left },
{ simp [h] } },
{ simp },
{ exact Ξ» f g hf hg n, by simp [I.add_mem (hf n) (hg n)] },
{ refine Ξ» f g hg n, _,
rw [smul_eq_mul, coeff_mul],
exact I.sum_mem (Ξ» c hc, I.mul_mem_left (f.coeff c.fst) (hg c.snd)) } },
{ intros hf,
rw β sum_monomial_eq f,
refine (I.map C : ideal R[X]).sum_mem (Ξ» n hn, _),
simp [monomial_eq_C_mul_X],
rw mul_comm,
exact (I.map C : ideal R[X]).mul_mem_left _ (mem_map_of_mem _ (hf n)) }
end
lemma _root_.polynomial.ker_map_ring_hom (f : R β+* S) :
(polynomial.map_ring_hom f).ker = f.ker.map C :=
begin
ext,
rw [mem_map_C_iff, ring_hom.mem_ker, polynomial.ext_iff],
simp_rw [coe_map_ring_hom, coeff_map, coeff_zero, ring_hom.mem_ker],
end
variable (I : ideal R[X])
theorem mem_leading_coeff_nth (n : β) (x) :
x β I.leading_coeff_nth n β β p β I, degree p β€ n β§ p.leading_coeff = x :=
begin
simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf,
mem_degree_le],
split,
{ rintro β¨p, β¨hpdeg, hpIβ©, rflβ©,
cases lt_or_eq_of_le hpdeg with hpdeg hpdeg,
{ refine β¨0, I.zero_mem, bot_le, _β©,
rw [leading_coeff_zero, eq_comm],
exact coeff_eq_zero_of_degree_lt hpdeg },
{ refine β¨p, hpI, le_of_eq hpdeg, _β©,
rw [polynomial.leading_coeff, nat_degree, hpdeg], refl } },
{ rintro β¨p, hpI, hpdeg, rflβ©,
have : nat_degree p + (n - nat_degree p) = n,
{ exact add_tsub_cancel_of_le (nat_degree_le_of_degree_le hpdeg) },
refine β¨p * X ^ (n - nat_degree p), β¨_, I.mul_mem_right _ hpIβ©, _β©,
{ apply le_trans (degree_mul_le _ _) _,
apply le_trans (add_le_add (degree_le_nat_degree) (degree_X_pow_le _)) _,
rw [β with_bot.coe_add, this],
exact le_rfl },
{ rw [polynomial.leading_coeff, β coeff_mul_X_pow p (n - nat_degree p), this] } }
end
theorem mem_leading_coeff_nth_zero (x) :
x β I.leading_coeff_nth 0 β C x β I :=
(mem_leading_coeff_nth _ _ _).trans
β¨Ξ» β¨p, hpI, hpdeg, hpxβ©, by rwa [β hpx, polynomial.leading_coeff,
nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg),
β eq_C_of_degree_le_zero hpdeg],
Ξ» hx, β¨C x, hx, degree_C_le, leading_coeff_C xβ©β©
theorem leading_coeff_nth_mono {m n : β} (H : m β€ n) :
I.leading_coeff_nth m β€ I.leading_coeff_nth n :=
begin
intros r hr,
simp only [set_like.mem_coe, mem_leading_coeff_nth] at hr β’,
rcases hr with β¨p, hpI, hpdeg, rflβ©,
refine β¨p * X ^ (n - m), I.mul_mem_right _ hpI, _, leading_coeff_mul_X_powβ©,
refine le_trans (degree_mul_le _ _) _,
refine le_trans (add_le_add hpdeg (degree_X_pow_le _)) _,
rw [β with_bot.coe_add, add_tsub_cancel_of_le H],
exact le_rfl
end
theorem mem_leading_coeff (x) :
x β I.leading_coeff β β p β I, polynomial.leading_coeff p = x :=
begin
rw [leading_coeff, submodule.mem_supr_of_directed],
simp only [mem_leading_coeff_nth],
{ split, { rintro β¨i, p, hpI, hpdeg, rflβ©, exact β¨p, hpI, rflβ© },
rintro β¨p, hpI, rflβ©, exact β¨nat_degree p, p, hpI, degree_le_nat_degree, rflβ© },
intros i j, exact β¨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _),
I.leading_coeff_nth_mono (nat.le_add_left _ _)β©
end
end comm_semiring
section ring
variables [ring R]
/-- `polynomial R` is never a field for any ring `R`. -/
lemma polynomial_not_is_field : Β¬ is_field R[X] :=
begin
nontriviality R,
intro hR,
obtain β¨p, hpβ© := hR.mul_inv_cancel X_ne_zero,
have hp0 : p β 0,
{ rintro rfl,
rw [mul_zero] at hp,
exact zero_ne_one hp },
have := degree_lt_degree_mul_X hp0,
rw [βX_mul, congr_arg degree hp, degree_one, nat.with_bot.lt_zero_iff, degree_eq_bot] at this,
exact hp0 this,
end
/-- The only constant in a maximal ideal over a field is `0`. -/
lemma eq_zero_of_constant_mem_of_maximal (hR : is_field R)
(I : ideal R[X]) [hI : I.is_maximal] (x : R) (hx : C x β I) : x = 0 :=
begin
refine classical.by_contradiction (Ξ» hx0, hI.ne_top ((eq_top_iff_one I).2 _)),
obtain β¨y, hyβ© := hR.mul_inv_cancel hx0,
convert I.mul_mem_left (C y) hx,
rw [β C.map_mul, hR.mul_comm y x, hy, ring_hom.map_one],
end
end ring
section comm_ring
variables [comm_ring R]
lemma quotient_map_C_eq_zero {I : ideal R} :
β a β I, ((quotient.mk (map C I : ideal R[X])).comp C) a = 0 :=
begin
intros a ha,
rw [ring_hom.comp_apply, quotient.eq_zero_iff_mem],
exact mem_map_of_mem _ ha,
end
lemma evalβ_C_mk_eq_zero {I : ideal R} :
β f β (map C I : ideal R[X]), evalβ_ring_hom (C.comp (quotient.mk I)) X f = 0 :=
begin
intros a ha,
rw β sum_monomial_eq a,
dsimp,
rw evalβ_sum,
refine finset.sum_eq_zero (Ξ» n hn, _),
dsimp,
rw evalβ_monomial (C.comp (quotient.mk I)) X,
refine mul_eq_zero_of_left (polynomial.ext (Ξ» m, _)) (X ^ n),
erw coeff_C,
by_cases h : m = 0,
{ simpa [h] using quotient.eq_zero_iff_mem.2 ((mem_map_C_iff.1 ha) n) },
{ simp [h] }
end
/-- If `I` is an ideal of `R`, then the ring polynomials over the quotient ring `I.quotient` is
isomorphic to the quotient of `polynomial R` by the ideal `map C I`,
where `map C I` contains exactly the polynomials whose coefficients all lie in `I` -/
def polynomial_quotient_equiv_quotient_polynomial (I : ideal R) :
polynomial (R β§Έ I) β+* R[X] β§Έ (map C I : ideal R[X]) :=
{ to_fun := evalβ_ring_hom
(quotient.lift I ((quotient.mk (map C I : ideal R[X])).comp C) quotient_map_C_eq_zero)
((quotient.mk (map C I : ideal R[X]) X)),
inv_fun := quotient.lift (map C I : ideal R[X])
(evalβ_ring_hom (C.comp (quotient.mk I)) X) evalβ_C_mk_eq_zero,
map_mul' := Ξ» f g, by simp only [coe_evalβ_ring_hom, evalβ_mul],
map_add' := Ξ» f g, by simp only [evalβ_add, coe_evalβ_ring_hom],
left_inv := begin
intro f,
apply polynomial.induction_on' f,
{ intros p q hp hq,
simp only [coe_evalβ_ring_hom] at hp,
simp only [coe_evalβ_ring_hom] at hq,
simp only [coe_evalβ_ring_hom, hp, hq, ring_hom.map_add] },
{ rintros n β¨xβ©,
simp only [monomial_eq_smul_X, C_mul', quotient.lift_mk, submodule.quotient.quot_mk_eq_mk,
quotient.mk_eq_mk, evalβ_X_pow, evalβ_smul, coe_evalβ_ring_hom, ring_hom.map_pow,
evalβ_C, ring_hom.coe_comp, ring_hom.map_mul, evalβ_X] }
end,
right_inv := begin
rintro β¨fβ©,
apply polynomial.induction_on' f,
{ simp_intros p q hp hq,
rw [hp, hq] },
{ intros n a,
simp only [monomial_eq_smul_X, β C_mul' a (X ^ n), quotient.lift_mk,
submodule.quotient.quot_mk_eq_mk, quotient.mk_eq_mk, evalβ_X_pow,
evalβ_smul, coe_evalβ_ring_hom, ring_hom.map_pow, evalβ_C, ring_hom.coe_comp,
ring_hom.map_mul, evalβ_X] },
end, }
@[simp]
lemma polynomial_quotient_equiv_quotient_polynomial_symm_mk (I : ideal R) (f : R[X]) :
I.polynomial_quotient_equiv_quotient_polynomial.symm (quotient.mk _ f) = f.map (quotient.mk I) :=
by rw [polynomial_quotient_equiv_quotient_polynomial, ring_equiv.symm_mk, ring_equiv.coe_mk,
ideal.quotient.lift_mk, coe_evalβ_ring_hom, evalβ_eq_eval_map, βpolynomial.map_map,
βevalβ_eq_eval_map, polynomial.evalβ_C_X]
@[simp]
lemma polynomial_quotient_equiv_quotient_polynomial_map_mk (I : ideal R) (f : R[X]) :
I.polynomial_quotient_equiv_quotient_polynomial (f.map I^.quotient.mk) = quotient.mk _ f :=
begin
apply (polynomial_quotient_equiv_quotient_polynomial I).symm.injective,
rw [ring_equiv.symm_apply_apply, polynomial_quotient_equiv_quotient_polynomial_symm_mk],
end
/-- If `P` is a prime ideal of `R`, then `R[x]/(P)` is an integral domain. -/
lemma is_domain_map_C_quotient {P : ideal R} (H : is_prime P) :
is_domain (R[X] β§Έ (map C P : ideal R[X])) :=
ring_equiv.is_domain (polynomial (R β§Έ P))
(polynomial_quotient_equiv_quotient_polynomial P).symm
/-- If `P` is a prime ideal of `R`, then `P.R[x]` is a prime ideal of `R[x]`. -/
lemma is_prime_map_C_of_is_prime {P : ideal R} (H : is_prime P) :
is_prime (map C P : ideal R[X]) :=
(quotient.is_domain_iff_prime (map C P : ideal R[X])).mp
(is_domain_map_C_quotient H)
/-- Given any ring `R` and an ideal `I` of `polynomial R`, we get a map `R β R[x] β R[x]/I`.
If we let `R` be the image of `R` in `R[x]/I` then we also have a map `R[x] β R'[x]`.
In particular we can map `I` across this map, to get `I'` and a new map `R' β R'[x] β R'[x]/I`.
This theorem shows `I'` will not contain any non-zero constant polynomials
-/
lemma eq_zero_of_polynomial_mem_map_range (I : ideal R[X])
(x : ((quotient.mk I).comp C).range)
(hx : C x β (I.map (polynomial.map_ring_hom ((quotient.mk I).comp C).range_restrict))) :
x = 0 :=
begin
let i := ((quotient.mk I).comp C).range_restrict,
have hi' : (polynomial.map_ring_hom i).ker β€ I,
{ refine Ξ» f hf, polynomial_mem_ideal_of_coeff_mem_ideal I f (Ξ» n, _),
rw [mem_comap, β quotient.eq_zero_iff_mem, β ring_hom.comp_apply],
rw [ring_hom.mem_ker, coe_map_ring_hom] at hf,
replace hf := congr_arg (Ξ» (f : polynomial _), f.coeff n) hf,
simp only [coeff_map, coeff_zero] at hf,
rwa [subtype.ext_iff, ring_hom.coe_range_restrict] at hf },
obtain β¨x, hx'β© := x,
obtain β¨y, rflβ© := (ring_hom.mem_range).1 hx',
refine subtype.eq _,
simp only [ring_hom.comp_apply, quotient.eq_zero_iff_mem, add_submonoid_class.coe_zero,
subtype.val_eq_coe],
suffices : C (i y) β (I.map (polynomial.map_ring_hom i)),
{ obtain β¨f, hfβ© := mem_image_of_mem_map_of_surjective (polynomial.map_ring_hom i)
(polynomial.map_surjective _ (((quotient.mk I).comp C).range_restrict_surjective)) this,
refine sub_add_cancel (C y) f βΈ I.add_mem (hi' _ : (C y - f) β I) hf.1,
rw [ring_hom.mem_ker, ring_hom.map_sub, hf.2, sub_eq_zero, coe_map_ring_hom, map_C] },
exact hx,
end
theorem is_fg_degree_le [is_noetherian_ring R] (I : ideal R[X]) (n : β) :
submodule.fg (I.degree_le n) :=
is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _
β¨_, degree_le_eq_span_X_pow.symmβ©) _
end comm_ring
end ideal
variables {Ο : Type v} {M : Type w}
variables [comm_ring R] [comm_ring S] [add_comm_group M] [module R M]
section prime
variables (Ο) {r : R}
namespace polynomial
lemma prime_C_iff : prime (C r) β prime r :=
β¨ comap_prime C (eval_ring_hom (0 : R)) (Ξ» r, eval_C),
Ξ» hr, by { have := hr.1,
rw β ideal.span_singleton_prime at hr β’,
{ convert ideal.is_prime_map_C_of_is_prime hr using 1,
rw [ideal.map_span, set.image_singleton] },
exacts [Ξ» h, this (C_eq_zero.1 h), this] } β©
end polynomial
namespace mv_polynomial
private lemma prime_C_iff_of_fintype [fintype Ο] : prime (C r : mv_polynomial Ο R) β prime r :=
begin
rw (rename_equiv R (fintype.equiv_fin Ο)).to_mul_equiv.prime_iff,
convert_to prime (C r) β _, { congr, apply rename_C },
{ symmetry, induction fintype.card Ο with d hd,
{ exact (is_empty_alg_equiv R (fin 0)).to_mul_equiv.symm.prime_iff },
{ rw [hd, β polynomial.prime_C_iff],
convert (fin_succ_equiv R d).to_mul_equiv.symm.prime_iff,
rw β fin_succ_equiv_comp_C_eq_C, refl } },
end
lemma prime_C_iff : prime (C r : mv_polynomial Ο R) β prime r :=
β¨ comap_prime C constant_coeff constant_coeff_C,
Ξ» hr, β¨ Ξ» h, hr.1 $ by { rw [β C_inj, h], simp },
Ξ» h, hr.2.1 $ by { rw β constant_coeff_C r, exact h.map _ },
Ξ» a b hd, begin
obtain β¨s,a',b',rfl,rflβ© := exists_finset_renameβ a b,
rw β algebra_map_eq at hd, have : algebra_map R _ r β£ a' * b',
{ convert (kill_compl subtype.coe_injective).to_ring_hom.map_dvd hd, simpa, simp },
rw β rename_C (coe : s β Ο), let f := (rename (coe : s β Ο)).to_ring_hom,
exact (((prime_C_iff_of_fintype s).2 hr).2.2 a' b' this).imp f.map_dvd f.map_dvd,
end β© β©
variable {Ο}
lemma prime_rename_iff (s : set Ο) {p : mv_polynomial s R} :
prime (rename (coe : s β Ο) p) β prime p :=
begin
classical, symmetry, let eqv := (sum_alg_equiv R _ _).symm.trans
(rename_equiv R $ (equiv.sum_comm β₯sαΆ s).trans $ equiv.set.sum_compl s),
rw [β prime_C_iff β₯sαΆ, eqv.to_mul_equiv.prime_iff], convert iff.rfl,
suffices : (rename coe).to_ring_hom = eqv.to_alg_hom.to_ring_hom.comp C,
{ apply ring_hom.congr_fun this },
{ apply ring_hom_ext,
{ intro, dsimp [eqv], erw [iter_to_sum_C_C, rename_C, rename_C] },
{ intro, dsimp [eqv], erw [iter_to_sum_C_X, rename_X, rename_X], refl } },
end
end mv_polynomial
end prime
namespace polynomial
@[priority 100]
instance {R : Type*} [comm_ring R] [is_domain R] [wf_dvd_monoid R] :
wf_dvd_monoid R[X] :=
{ well_founded_dvd_not_unit := begin
classical,
refine rel_hom_class.well_founded (β¨Ξ» (p : R[X]),
((if p = 0 then β€ else βp.degree : with_top (with_bot β)), p.leading_coeff), _β© :
dvd_not_unit βr prod.lex (<) dvd_not_unit)
(prod.lex_wf (with_top.well_founded_lt $ with_bot.well_founded_lt nat.lt_wf)
βΉwf_dvd_monoid RβΊ.well_founded_dvd_not_unit),
rintros a b β¨ane0, β¨c, β¨not_unit_c, rflβ©β©β©,
rw [polynomial.degree_mul, if_neg ane0],
split_ifs with hac,
{ rw [hac, polynomial.leading_coeff_zero],
apply prod.lex.left,
exact lt_of_le_of_ne le_top with_top.coe_ne_top },
have cne0 : c β 0 := right_ne_zero_of_mul hac,
simp only [cne0, ane0, polynomial.leading_coeff_mul],
by_cases hdeg : c.degree = 0,
{ simp only [hdeg, add_zero],
refine prod.lex.right _ β¨_, β¨c.leading_coeff, (Ξ» unit_c, not_unit_c _), rflβ©β©,
{ rwa [ne, polynomial.leading_coeff_eq_zero] },
rw [polynomial.is_unit_iff, polynomial.eq_C_of_degree_eq_zero hdeg],
use [c.leading_coeff, unit_c],
rw [polynomial.leading_coeff, polynomial.nat_degree_eq_of_degree_eq_some hdeg] },
{ apply prod.lex.left,
rw polynomial.degree_eq_nat_degree cne0 at *,
rw [with_top.coe_lt_coe, polynomial.degree_eq_nat_degree ane0,
β with_bot.coe_add, with_bot.coe_lt_coe],
exact lt_add_of_pos_right _ (nat.pos_of_ne_zero (Ξ» h, hdeg (h.symm βΈ with_bot.coe_zero))) },
end }
end polynomial
/-- Hilbert basis theorem: a polynomial ring over a noetherian ring is a noetherian ring. -/
protected theorem polynomial.is_noetherian_ring [is_noetherian_ring R] :
is_noetherian_ring R[X] :=
is_noetherian_ring_iff.2 β¨assume I : ideal R[X],
let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance))
(set.range I.leading_coeff_nth) β¨_, β¨0, rflβ©β© in
have hm : M β set.range I.leading_coeff_nth := well_founded.min_mem _ _ _,
let β¨N, HNβ© := hm, β¨s, hsβ© := I.is_fg_degree_le N in
have hm2 : β k, I.leading_coeff_nth k β€ M := Ξ» k, or.cases_on (le_or_lt k N)
(Ξ» h, HN βΈ I.leading_coeff_nth_mono h)
(Ξ» h x hx, classical.by_contradiction $ Ξ» hxm,
have Β¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min
(well_founded_submodule_gt _ _) _ _ _; exact β¨k, rflβ©,
this β¨HN βΈ I.leading_coeff_nth_mono (le_of_lt h), Ξ» H, hxm (H hx)β©),
have hs2 : β {x}, x β I.degree_le N β x β ideal.span (βs : set R[X]),
from hs βΈ Ξ» x hx, submodule.span_induction hx (Ξ» _ hx, ideal.subset_span hx) (ideal.zero_mem _)
(Ξ» _ _, ideal.add_mem _) (Ξ» c f hf, f.C_mul' c βΈ ideal.mul_mem_left _ _ hf),
β¨s, le_antisymm
(ideal.span_le.2 $ Ξ» x hx, have x β I.degree_le N, from hs βΈ submodule.subset_span hx, this.2) $
begin
have : submodule.span R[X] βs = ideal.span βs, by refl,
rw this,
intros p hp, generalize hn : p.nat_degree = k,
induction k using nat.strong_induction_on with k ih generalizing p,
cases le_or_lt k N,
{ subst k, refine hs2 β¨polynomial.mem_degree_le.2
(le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hpβ© },
{ have hp0 : p β 0,
{ rintro rfl, cases hn, exact nat.not_lt_zero _ h },
have : (0 : R) β 1,
{ intro h, apply hp0, ext i, refine (mul_one _).symm.trans _,
rw [β h, mul_zero], refl },
haveI : nontrivial R := β¨β¨0, 1, thisβ©β©,
have : p.leading_coeff β I.leading_coeff_nth N,
{ rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2
β¨_, hp, hn βΈ polynomial.degree_le_nat_degree, rflβ©) },
rw I.mem_leading_coeff_nth at this,
rcases this with β¨q, hq, hdq, hlqpβ©,
have hq0 : q β 0,
{ intro H, rw [β polynomial.leading_coeff_eq_zero] at H,
rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H },
have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree,
{ rw [polynomial.degree_mul', polynomial.degree_X_pow],
rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0],
rw [β with_bot.coe_add, add_tsub_cancel_of_le, hn],
{ refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) },
rw [polynomial.leading_coeff_X_pow, mul_one],
exact mt polynomial.leading_coeff_eq_zero.1 hq0 },
have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff,
{ rw [β hlqp, polynomial.leading_coeff_mul_X_pow] },
have := polynomial.degree_sub_lt h1 hp0 h2,
rw [polynomial.degree_eq_nat_degree hp0] at this,
rw β sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)),
refine (ideal.span βs).add_mem _ ((ideal.span βs).mul_mem_right _ _),
{ by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0,
{ rw hpq, exact ideal.zero_mem _ },
refine ih _ _ (I.sub_mem hp (I.mul_mem_right _ hq)) rfl,
rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this },
exact hs2 β¨polynomial.mem_degree_le.2 hdq, hqβ© }
endβ©β©
attribute [instance] polynomial.is_noetherian_ring
namespace polynomial
theorem exists_irreducible_of_degree_pos
{R : Type u} [comm_ring R] [is_domain R] [wf_dvd_monoid R]
{f : R[X]} (hf : 0 < f.degree) : β g, irreducible g β§ g β£ f :=
wf_dvd_monoid.exists_irreducible_factor
(Ξ» huf, ne_of_gt hf $ degree_eq_zero_of_is_unit huf)
(Ξ» hf0, not_lt_of_lt hf $ hf0.symm βΈ (@degree_zero R _).symm βΈ with_bot.bot_lt_coe _)
theorem exists_irreducible_of_nat_degree_pos
{R : Type u} [comm_ring R] [is_domain R] [wf_dvd_monoid R]
{f : R[X]} (hf : 0 < f.nat_degree) : β g, irreducible g β§ g β£ f :=
exists_irreducible_of_degree_pos $ by { contrapose! hf, exact nat_degree_le_of_degree_le hf }
theorem exists_irreducible_of_nat_degree_ne_zero
{R : Type u} [comm_ring R] [is_domain R] [wf_dvd_monoid R]
{f : R[X]} (hf : f.nat_degree β 0) : β g, irreducible g β§ g β£ f :=
exists_irreducible_of_nat_degree_pos $ nat.pos_of_ne_zero hf
lemma linear_independent_powers_iff_aeval
(f : M ββ[R] M) (v : M) :
linear_independent R (Ξ» n : β, (f ^ n) v)
β β (p : R[X]), aeval f p v = 0 β p = 0 :=
begin
rw linear_independent_iff,
simp only [finsupp.total_apply, aeval_endomorphism, forall_iff_forall_finsupp, sum, support,
coeff, of_finsupp_eq_zero],
exact iff.rfl,
end
lemma disjoint_ker_aeval_of_coprime
(f : M ββ[R] M) {p q : R[X]} (hpq : is_coprime p q) :
disjoint (aeval f p).ker (aeval f q).ker :=
begin
intros v hv,
rcases hpq with β¨p', q', hpq'β©,
simpa [linear_map.mem_ker.1 (submodule.mem_inf.1 hv).1,
linear_map.mem_ker.1 (submodule.mem_inf.1 hv).2]
using congr_arg (Ξ» p : R[X], aeval f p v) hpq'.symm,
end
lemma sup_aeval_range_eq_top_of_coprime
(f : M ββ[R] M) {p q : R[X]} (hpq : is_coprime p q) :
(aeval f p).range β (aeval f q).range = β€ :=
begin
rw eq_top_iff,
intros v hv,
rw submodule.mem_sup,
rcases hpq with β¨p', q', hpq'β©,
use aeval f (p * p') v,
use linear_map.mem_range.2 β¨aeval f p' v, by simp only [linear_map.mul_apply, aeval_mul]β©,
use aeval f (q * q') v,
use linear_map.mem_range.2 β¨aeval f q' v, by simp only [linear_map.mul_apply, aeval_mul]β©,
simpa only [mul_comm p p', mul_comm q q', aeval_one, aeval_add]
using congr_arg (Ξ» p : R[X], aeval f p v) hpq'
end
lemma sup_ker_aeval_le_ker_aeval_mul {f : M ββ[R] M} {p q : R[X]} :
(aeval f p).ker β (aeval f q).ker β€ (aeval f (p * q)).ker :=
begin
intros v hv,
rcases submodule.mem_sup.1 hv with β¨x, hx, y, hy, hxyβ©,
have h_eval_x : aeval f (p * q) x = 0,
{ rw [mul_comm, aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hx, linear_map.map_zero] },
have h_eval_y : aeval f (p * q) y = 0,
{ rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hy, linear_map.map_zero] },
rw [linear_map.mem_ker, βhxy, linear_map.map_add, h_eval_x, h_eval_y, add_zero],
end
lemma sup_ker_aeval_eq_ker_aeval_mul_of_coprime
(f : M ββ[R] M) {p q : R[X]} (hpq : is_coprime p q) :
(aeval f p).ker β (aeval f q).ker = (aeval f (p * q)).ker :=
begin
apply le_antisymm sup_ker_aeval_le_ker_aeval_mul,
intros v hv,
rw submodule.mem_sup,
rcases hpq with β¨p', q', hpq'β©,
have h_evalβ_qpp' := calc
aeval f (q * (p * p')) v = aeval f (p' * (p * q)) v :
by rw [mul_comm, mul_assoc, mul_comm, mul_assoc, mul_comm q p]
... = 0 :
by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero],
have h_evalβ_pqq' := calc
aeval f (p * (q * q')) v = aeval f (q' * (p * q)) v :
by rw [βmul_assoc, mul_comm]
... = 0 :
by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero],
rw aeval_mul at h_evalβ_qpp' h_evalβ_pqq',
refine β¨aeval f (q * q') v, linear_map.mem_ker.1 h_evalβ_pqq',
aeval f (p * p') v, linear_map.mem_ker.1 h_evalβ_qpp', _β©,
rw [add_comm, mul_comm p p', mul_comm q q'],
simpa using congr_arg (Ξ» p : R[X], aeval f p v) hpq'
end
end polynomial
namespace mv_polynomial
lemma is_noetherian_ring_fin_0 [is_noetherian_ring R] :
is_noetherian_ring (mv_polynomial (fin 0) R) :=
is_noetherian_ring_of_ring_equiv R
((mv_polynomial.is_empty_ring_equiv R pempty).symm.trans
(rename_equiv R fin_zero_equiv'.symm).to_ring_equiv)
theorem is_noetherian_ring_fin [is_noetherian_ring R] :
β {n : β}, is_noetherian_ring (mv_polynomial (fin n) R)
| 0 := is_noetherian_ring_fin_0
| (n+1) :=
@is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ _ _
(mv_polynomial.fin_succ_equiv _ n).to_ring_equiv.symm
(@polynomial.is_noetherian_ring (mv_polynomial (fin n) R) _ (is_noetherian_ring_fin))
/-- The multivariate polynomial ring in finitely many variables over a noetherian ring
is itself a noetherian ring. -/
instance is_noetherian_ring [fintype Ο] [is_noetherian_ring R] :
is_noetherian_ring (mv_polynomial Ο R) :=
@is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card Ο)) R) _ _ _
(rename_equiv R (fintype.equiv_fin Ο).symm).to_ring_equiv is_noetherian_ring_fin
lemma is_domain_fin_zero (R : Type u) [comm_ring R] [is_domain R] :
is_domain (mv_polynomial (fin 0) R) :=
ring_equiv.is_domain R
((rename_equiv R fin_zero_equiv').to_ring_equiv.trans
(mv_polynomial.is_empty_ring_equiv R pempty))
/-- Auxiliary lemma:
Multivariate polynomials over an integral domain
with variables indexed by `fin n` form an integral domain.
This fact is proven inductively,
and then used to prove the general case without any finiteness hypotheses.
See `mv_polynomial.is_domain` for the general case. -/
lemma is_domain_fin (R : Type u) [comm_ring R] [is_domain R] :
β (n : β), is_domain (mv_polynomial (fin n) R)
| 0 := is_domain_fin_zero R
| (n+1) :=
begin
haveI := is_domain_fin n,
exact ring_equiv.is_domain
(polynomial (mv_polynomial (fin n) R))
(mv_polynomial.fin_succ_equiv _ n).to_ring_equiv
end
/-- Auxiliary definition:
Multivariate polynomials in finitely many variables over an integral domain form an integral domain.
This fact is proven by transport of structure from the `mv_polynomial.is_domain_fin`,
and then used to prove the general case without finiteness hypotheses.
See `mv_polynomial.is_domain` for the general case. -/
lemma is_domain_fintype (R : Type u) (Ο : Type v) [comm_ring R] [fintype Ο]
[is_domain R] : is_domain (mv_polynomial Ο R) :=
@ring_equiv.is_domain _ (mv_polynomial (fin $ fintype.card Ο) R) _ _
(mv_polynomial.is_domain_fin _ _)
(rename_equiv R (fintype.equiv_fin Ο)).to_ring_equiv
protected theorem eq_zero_or_eq_zero_of_mul_eq_zero
{R : Type u} [comm_ring R] [is_domain R] {Ο : Type v}
(p q : mv_polynomial Ο R) (h : p * q = 0) : p = 0 β¨ q = 0 :=
begin
obtain β¨s, p, rflβ© := exists_finset_rename p,
obtain β¨t, q, rflβ© := exists_finset_rename q,
have :
rename (subtype.map id (finset.subset_union_left s t) : {x // x β s} β {x // x β s βͺ t}) p *
rename (subtype.map id (finset.subset_union_right s t) : {x // x β t} β {x // x β s βͺ t}) q = 0,
{ apply rename_injective _ subtype.val_injective, simpa using h },
letI := mv_polynomial.is_domain_fintype R {x // x β (s βͺ t)},
rw mul_eq_zero at this,
cases this; [left, right],
all_goals { simpa using congr_arg (rename subtype.val) this }
end
/-- The multivariate polynomial ring over an integral domain is an integral domain. -/
instance {R : Type u} {Ο : Type v} [comm_ring R] [is_domain R] :
is_domain (mv_polynomial Ο R) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := mv_polynomial.eq_zero_or_eq_zero_of_mul_eq_zero,
exists_pair_ne := β¨0, 1, Ξ» H,
begin
have : evalβ (ring_hom.id _) (Ξ» s, (0:R)) (0 : mv_polynomial Ο R) =
evalβ (ring_hom.id _) (Ξ» s, (0:R)) (1 : mv_polynomial Ο R),
{ congr, exact H },
simpa,
endβ©,
.. (by apply_instance : comm_ring (mv_polynomial Ο R)) }
lemma map_mv_polynomial_eq_evalβ {S : Type*} [comm_ring S] [fintype Ο]
(Ο : mv_polynomial Ο R β+* S) (p : mv_polynomial Ο R) :
Ο p = mv_polynomial.evalβ (Ο.comp mv_polynomial.C) (Ξ» s, Ο (mv_polynomial.X s)) p :=
begin
refine trans (congr_arg Ο (mv_polynomial.as_sum p)) _,
rw [mv_polynomial.evalβ_eq', Ο.map_sum],
congr,
ext,
simp only [monomial_eq, Ο.map_pow, Ο.map_prod, Ο.comp_apply, Ο.map_mul, finsupp.prod_pow],
end
lemma quotient_map_C_eq_zero {I : ideal R} {i : R} (hi : i β I) :
(ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial Ο R))).comp C i = 0 :=
begin
simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient.eq_zero_iff_mem],
exact ideal.mem_map_of_mem _ hi
end
/-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself,
multivariate version. -/
lemma mem_ideal_of_coeff_mem_ideal (I : ideal (mv_polynomial Ο R)) (p : mv_polynomial Ο R)
(hcoe : β (m : Ο ββ β), p.coeff m β I.comap C) : p β I :=
begin
rw as_sum p,
suffices : β m β p.support, monomial m (mv_polynomial.coeff m p) β I,
{ exact submodule.sum_mem I this },
intros m hm,
rw [β mul_one (coeff m p), β C_mul_monomial],
suffices : C (coeff m p) β I,
{ exact I.mul_mem_right (monomial m 1) this },
simpa [ideal.mem_comap] using hcoe m
end
/-- The push-forward of an ideal `I` of `R` to `mv_polynomial Ο R` via inclusion
is exactly the set of polynomials whose coefficients are in `I` -/
theorem mem_map_C_iff {I : ideal R} {f : mv_polynomial Ο R} :
f β (ideal.map C I : ideal (mv_polynomial Ο R)) β β (m : Ο ββ β), f.coeff m β I :=
begin
split,
{ intros hf,
apply submodule.span_induction hf,
{ intros f hf n,
cases (set.mem_image _ _ _).mp hf with x hx,
rw [β hx.right, coeff_C],
by_cases (n = 0),
{ simpa [h] using hx.left },
{ simp [ne.symm h] } },
{ simp },
{ exact Ξ» f g hf hg n, by simp [I.add_mem (hf n) (hg n)] },
{ refine Ξ» f g hg n, _,
rw [smul_eq_mul, coeff_mul],
exact I.sum_mem (Ξ» c hc, I.mul_mem_left (f.coeff c.fst) (hg c.snd)) } },
{ intros hf,
rw as_sum f,
suffices : β m β f.support, monomial m (coeff m f) β
(ideal.map C I : ideal (mv_polynomial Ο R)),
{ exact submodule.sum_mem _ this },
intros m hm,
rw [β mul_one (coeff m f), β C_mul_monomial],
suffices : C (coeff m f) β (ideal.map C I : ideal (mv_polynomial Ο R)),
{ exact ideal.mul_mem_right _ _ this },
apply ideal.mem_map_of_mem _,
exact hf m }
end
lemma ker_map (f : R β+* S) : (map f : mv_polynomial Ο R β+* mv_polynomial Ο S).ker = f.ker.map C :=
begin
ext,
rw [mv_polynomial.mem_map_C_iff, ring_hom.mem_ker, mv_polynomial.ext_iff],
simp_rw [coeff_map, coeff_zero, ring_hom.mem_ker],
end
lemma evalβ_C_mk_eq_zero {I : ideal R} {a : mv_polynomial Ο R}
(ha : a β (ideal.map C I : ideal (mv_polynomial Ο R))) :
evalβ_hom (C.comp (ideal.quotient.mk I)) X a = 0 :=
begin
rw as_sum a,
rw [coe_evalβ_hom, evalβ_sum],
refine finset.sum_eq_zero (Ξ» n hn, _),
simp only [evalβ_monomial, function.comp_app, ring_hom.coe_comp],
refine mul_eq_zero_of_left _ _,
suffices : coeff n a β I,
{ rw [β @ideal.mk_ker R _ I, ring_hom.mem_ker] at this,
simp only [this, C_0] },
exact mem_map_C_iff.1 ha n
end
/-- If `I` is an ideal of `R`, then the ring `mv_polynomial Ο I.quotient` is isomorphic as an
`R`-algebra to the quotient of `mv_polynomial Ο R` by the ideal generated by `I`. -/
def quotient_equiv_quotient_mv_polynomial (I : ideal R) :
mv_polynomial Ο (R β§Έ I) ββ[R]
mv_polynomial Ο R β§Έ (ideal.map C I : ideal (mv_polynomial Ο R)) :=
{ to_fun := evalβ_hom (ideal.quotient.lift I ((ideal.quotient.mk (ideal.map C I : ideal
(mv_polynomial Ο R))).comp C) (Ξ» i hi, quotient_map_C_eq_zero hi))
(Ξ» i, ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial Ο R)) (X i)),
inv_fun := ideal.quotient.lift (ideal.map C I : ideal (mv_polynomial Ο R))
(evalβ_hom (C.comp (ideal.quotient.mk I)) X) (Ξ» a ha, evalβ_C_mk_eq_zero ha),
map_mul' := ring_hom.map_mul _,
map_add' := ring_hom.map_add _,
left_inv := begin
intro f,
apply induction_on f,
{ rintro β¨rβ©,
rw [coe_evalβ_hom, evalβ_C],
simp only [evalβ_hom_eq_bindβ, submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk,
ideal.quotient.mk_eq_mk, bindβ_C_right, ring_hom.coe_comp] },
{ simp_intros p q hp hq only [ring_hom.map_add, mv_polynomial.coe_evalβ_hom, coe_evalβ_hom,
mv_polynomial.evalβ_add, mv_polynomial.evalβ_hom_eq_bindβ, evalβ_hom_eq_bindβ],
rw [hp, hq] },
{ simp_intros p i hp only [evalβ_hom_eq_bindβ, coe_evalβ_hom],
simp only [hp, evalβ_hom_eq_bindβ, coe_evalβ_hom, ideal.quotient.lift_mk, bindβ_X_right,
evalβ_mul, ring_hom.map_mul, evalβ_X] }
end,
right_inv := begin
rintro β¨fβ©,
apply induction_on f,
{ intros r,
simp only [submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk,
ring_hom.coe_comp, evalβ_hom_C] },
{ simp_intros p q hp hq only [evalβ_hom_eq_bindβ, submodule.quotient.quot_mk_eq_mk, evalβ_add,
ring_hom.map_add, coe_evalβ_hom, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk],
rw [hp, hq] },
{ simp_intros p i hp only [evalβ_hom_eq_bindβ, submodule.quotient.quot_mk_eq_mk, coe_evalβ_hom,
ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, bindβ_X_right, evalβ_mul, ring_hom.map_mul,
evalβ_X],
simp only [hp] }
end,
commutes' := Ξ» r, evalβ_hom_C _ _ (ideal.quotient.mk I r) }
end mv_polynomial
section unique_factorization_domain
variables {D : Type u} [comm_ring D] [is_domain D] [unique_factorization_monoid D] (Ο)
open unique_factorization_monoid
namespace polynomial
@[priority 100]
instance unique_factorization_monoid : unique_factorization_monoid (polynomial D) :=
begin
haveI := arbitrary (normalization_monoid D),
haveI := to_normalized_gcd_monoid D,
exact ufm_of_gcd_of_wf_dvd_monoid
end
end polynomial
namespace mv_polynomial
private lemma unique_factorization_monoid_of_fintype [fintype Ο] :
unique_factorization_monoid (mv_polynomial Ο D) :=
(rename_equiv D (fintype.equiv_fin Ο)).to_mul_equiv.symm.unique_factorization_monoid $
begin
induction fintype.card Ο with d hd,
{ apply (is_empty_alg_equiv D (fin 0)).to_mul_equiv.symm.unique_factorization_monoid,
apply_instance },
{ apply (fin_succ_equiv D d).to_mul_equiv.symm.unique_factorization_monoid,
exactI polynomial.unique_factorization_monoid },
end
@[priority 100]
instance : unique_factorization_monoid (mv_polynomial Ο D) :=
begin
rw iff_exists_prime_factors,
intros a ha, obtain β¨s,a',rflβ© := exists_finset_rename a,
obtain β¨w,h,u,hwβ© := iff_exists_prime_factors.1
(unique_factorization_monoid_of_fintype s) a' (Ξ» h, ha $ by simp [h]),
exact β¨ w.map (rename coe),
Ξ» b hb, let β¨b',hb',heβ© := multiset.mem_map.1 hb in he βΈ (prime_rename_iff βs).2 (h b' hb'),
units.map (@rename s Ο D _ coe).to_ring_hom.to_monoid_hom u,
by erw [multiset.prod_hom, β map_mul, hw] β©,
end
end mv_polynomial
end unique_factorization_domain
|
9a8508ff41a43d4b7368b1c2fd9d8c9c27291605 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/int/gcd.lean | fd2612cb1d56a6bde4b2bb6792ea8d2623edcea2 | [
"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 | 26,588 | lean | /-
Copyright (c) 2018 Guy Leroy. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sangwoo Jo (aka Jason), Guy Leroy, Johannes HΓΆlzl, Mario Carneiro
-/
import data.nat.prime
import data.int.order
/-!
# Extended GCD and divisibility over β€
## Main definitions
* Given `x y : β`, `xgcd x y` computes the pair of integers `(a, b)` such that
`gcd x y = x * a + y * b`. `gcd_a x y` and `gcd_b x y` are defined to be `a` and `b`,
respectively.
## Main statements
* `gcd_eq_gcd_ab`: BΓ©zout's lemma, given `x y : β`, `gcd x y = x * gcd_a x y + y * gcd_b x y`.
## Tags
BΓ©zout's lemma, Bezout's lemma
-/
/-! ### Extended Euclidean algorithm -/
namespace nat
/-- Helper function for the extended GCD algorithm (`nat.xgcd`). -/
def xgcd_aux : β β β€ β β€ β β β β€ β β€ β β Γ β€ Γ β€
| 0 s t r' s' t' := (r', s', t')
| r@(succ _) s t r' s' t' :=
have r' % r < r, from mod_lt _ $ succ_pos _,
let q := r' / r in xgcd_aux (r' % r) (s' - q * s) (t' - q * t) r s t
@[simp] theorem xgcd_zero_left {s t r' s' t'} : xgcd_aux 0 s t r' s' t' = (r', s', t') :=
by simp [xgcd_aux]
theorem xgcd_aux_rec {r s t r' s' t'} (h : 0 < r) :
xgcd_aux r s t r' s' t' = xgcd_aux (r' % r) (s' - (r' / r) * s) (t' - (r' / r) * t) r s t :=
by cases r; [exact absurd h (lt_irrefl _), {simp only [xgcd_aux], refl}]
/-- Use the extended GCD algorithm to generate the `a` and `b` values
satisfying `gcd x y = x * a + y * b`. -/
def xgcd (x y : β) : β€ Γ β€ := (xgcd_aux x 1 0 y 0 1).2
/-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/
def gcd_a (x y : β) : β€ := (xgcd x y).1
/-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/
def gcd_b (x y : β) : β€ := (xgcd x y).2
@[simp] theorem gcd_a_zero_left {s : β} : gcd_a 0 s = 0 :=
by { unfold gcd_a, rw [xgcd, xgcd_zero_left] }
@[simp] theorem gcd_b_zero_left {s : β} : gcd_b 0 s = 1 :=
by { unfold gcd_b, rw [xgcd, xgcd_zero_left] }
@[simp] theorem gcd_a_zero_right {s : β} (h : s β 0) : gcd_a s 0 = 1 :=
begin
unfold gcd_a xgcd,
induction s,
{ exact absurd rfl h, },
{ simp [xgcd_aux], }
end
@[simp] theorem gcd_b_zero_right {s : β} (h : s β 0) : gcd_b s 0 = 0 :=
begin
unfold gcd_b xgcd,
induction s,
{ exact absurd rfl h, },
{ simp [xgcd_aux], }
end
@[simp] theorem xgcd_aux_fst (x y) : β s t s' t',
(xgcd_aux x s t y s' t').1 = gcd x y :=
gcd.induction x y (by simp) (Ξ» x y h IH s t s' t', by simp [xgcd_aux_rec, h, IH]; rw β gcd_rec)
theorem xgcd_aux_val (x y) : xgcd_aux x 1 0 y 0 1 = (gcd x y, xgcd x y) :=
by rw [xgcd, β xgcd_aux_fst x y 1 0 0 1]; cases xgcd_aux x 1 0 y 0 1; refl
theorem xgcd_val (x y) : xgcd x y = (gcd_a x y, gcd_b x y) :=
by unfold gcd_a gcd_b; cases xgcd x y; refl
section
parameters (x y : β)
private def P : β Γ β€ Γ β€ β Prop
| (r, s, t) := (r : β€) = x * s + y * t
theorem xgcd_aux_P {r r'} : β {s t s' t'}, P (r, s, t) β P (r', s', t') β
P (xgcd_aux r s t r' s' t') :=
gcd.induction r r' (by simp) $ Ξ» a b h IH s t s' t' p p', begin
rw [xgcd_aux_rec h], refine IH _ p, dsimp [P] at *,
rw [int.mod_def], generalize : (b / a : β€) = k,
rw [p, p'],
simp [mul_add, mul_comm, mul_left_comm, add_comm, add_left_comm, sub_eq_neg_add, mul_assoc]
end
/-- **BΓ©zout's lemma**: given `x y : β`, `gcd x y = x * a + y * b`, where `a = gcd_a x y` and
`b = gcd_b x y` are computed by the extended Euclidean algorithm.
-/
theorem gcd_eq_gcd_ab : (gcd x y : β€) = x * gcd_a x y + y * gcd_b x y :=
by have := @xgcd_aux_P x y x y 1 0 0 1 (by simp [P]) (by simp [P]);
rwa [xgcd_aux_val, xgcd_val] at this
end
lemma exists_mul_mod_eq_gcd {k n : β} (hk : gcd n k < k) :
β m, n * m % k = gcd n k :=
begin
have hk' := int.coe_nat_ne_zero.mpr (ne_of_gt (lt_of_le_of_lt (zero_le (gcd n k)) hk)),
have key := congr_arg (Ξ» m, int.nat_mod m k) (gcd_eq_gcd_ab n k),
simp_rw int.nat_mod at key,
rw [int.add_mul_mod_self_left, βint.coe_nat_mod, int.to_nat_coe_nat, mod_eq_of_lt hk] at key,
refine β¨(n.gcd_a k % k).to_nat, eq.trans (int.coe_nat_inj _) key.symmβ©,
rw [int.coe_nat_mod, int.coe_nat_mul, int.to_nat_of_nonneg (int.mod_nonneg _ hk'),
int.to_nat_of_nonneg (int.mod_nonneg _ hk'), int.mul_mod, int.mod_mod, βint.mul_mod],
end
lemma exists_mul_mod_eq_one_of_coprime {k n : β} (hkn : coprime n k) (hk : 1 < k) :
β m, n * m % k = 1 :=
Exists.cases_on (exists_mul_mod_eq_gcd (lt_of_le_of_lt (le_of_eq hkn) hk))
(Ξ» m hm, β¨m, hm.trans hknβ©)
end nat
/-! ### Divisibility over β€ -/
namespace int
protected lemma coe_nat_gcd (m n : β) : int.gcd βm βn = nat.gcd m n := rfl
/-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/
def gcd_a : β€ β β€ β β€
| (of_nat m) n := m.gcd_a n.nat_abs
| -[1+ m] n := -m.succ.gcd_a n.nat_abs
/-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/
def gcd_b : β€ β β€ β β€
| m (of_nat n) := m.nat_abs.gcd_b n
| m -[1+ n] := -m.nat_abs.gcd_b n.succ
/-- **BΓ©zout's lemma** -/
theorem gcd_eq_gcd_ab : β x y : β€, (gcd x y : β€) = x * gcd_a x y + y * gcd_b x y
| (m : β) (n : β) := nat.gcd_eq_gcd_ab _ _
| (m : β) -[1+ n] := show (_ : β€) = _ + -(n+1) * -_, by rw neg_mul_neg; apply nat.gcd_eq_gcd_ab
| -[1+ m] (n : β) := show (_ : β€) = -(m+1) * -_ + _ , by rw neg_mul_neg; apply nat.gcd_eq_gcd_ab
| -[1+ m] -[1+ n] := show (_ : β€) = -(m+1) * -_ + -(n+1) * -_,
by { rw [neg_mul_neg, neg_mul_neg], apply nat.gcd_eq_gcd_ab }
theorem nat_abs_div (a b : β€) (H : b β£ a) : nat_abs (a / b) = (nat_abs a) / (nat_abs b) :=
begin
cases (nat.eq_zero_or_pos (nat_abs b)),
{rw eq_zero_of_nat_abs_eq_zero h, simp [int.div_zero]},
calc
nat_abs (a / b) = nat_abs (a / b) * 1 : by rw mul_one
... = nat_abs (a / b) * (nat_abs b / nat_abs b) : by rw nat.div_self h
... = nat_abs (a / b) * nat_abs b / nat_abs b : by rw (nat.mul_div_assoc _ dvd_rfl)
... = nat_abs (a / b * b) / nat_abs b : by rw (nat_abs_mul (a / b) b)
... = nat_abs a / nat_abs b : by rw int.div_mul_cancel H,
end
lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : β} (p_prime : nat.prime p) {m n : β€} {k l : β}
(hpm : β(p ^ k) β£ m)
(hpn : β(p ^ l) β£ n) (hpmn : β(p ^ (k+l+1)) β£ m*n) : β(p ^ (k+1)) β£ m β¨ β(p ^ (l+1)) β£ n :=
have hpm' : p ^ k β£ m.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpm,
have hpn' : p ^ l β£ n.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpn,
have hpmn' : (p ^ (k+l+1)) β£ m.nat_abs*n.nat_abs,
by rw βint.nat_abs_mul; apply (int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpmn),
let hsd := nat.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul p_prime hpm' hpn' hpmn' in
hsd.elim
(Ξ» hsd1, or.inl begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd1 end)
(Ξ» hsd2, or.inr begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd2 end)
theorem dvd_of_mul_dvd_mul_left {i j k : β€} (k_non_zero : k β 0) (H : k * i β£ k * j) : i β£ j :=
dvd.elim H (Ξ»l H1, by rw mul_assoc at H1; exact β¨_, mul_left_cancelβ k_non_zero H1β©)
theorem dvd_of_mul_dvd_mul_right {i j k : β€} (k_non_zero : k β 0) (H : i * k β£ j * k) : i β£ j :=
by rw [mul_comm i k, mul_comm j k] at H; exact dvd_of_mul_dvd_mul_left k_non_zero H
lemma prime.dvd_nat_abs_of_coe_dvd_sq {p : β} (hp : p.prime) (k : β€) (h : βp β£ k ^ 2) :
p β£ k.nat_abs :=
begin
apply @nat.prime.dvd_of_dvd_pow _ _ 2 hp,
rwa [sq, β nat_abs_mul, β coe_nat_dvd_left, β sq]
end
/-- β€ specific version of least common multiple. -/
def lcm (i j : β€) : β := nat.lcm (nat_abs i) (nat_abs j)
theorem lcm_def (i j : β€) : lcm i j = nat.lcm (nat_abs i) (nat_abs j) := rfl
protected lemma coe_nat_lcm (m n : β) : int.lcm βm βn = nat.lcm m n := rfl
theorem gcd_dvd_left (i j : β€) : (gcd i j : β€) β£ i :=
dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_left _ _
theorem gcd_dvd_right (i j : β€) : (gcd i j : β€) β£ j :=
dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_right _ _
theorem dvd_gcd {i j k : β€} (h1 : k β£ i) (h2 : k β£ j) : k β£ gcd i j :=
nat_abs_dvd.1 $ coe_nat_dvd.2 $ nat.dvd_gcd (nat_abs_dvd_iff_dvd.2 h1) (nat_abs_dvd_iff_dvd.2 h2)
theorem gcd_mul_lcm (i j : β€) : gcd i j * lcm i j = nat_abs (i * j) :=
by rw [int.gcd, int.lcm, nat.gcd_mul_lcm, nat_abs_mul]
theorem gcd_comm (i j : β€) : gcd i j = gcd j i := nat.gcd_comm _ _
theorem gcd_assoc (i j k : β€) : gcd (gcd i j) k = gcd i (gcd j k) := nat.gcd_assoc _ _ _
@[simp] theorem gcd_self (i : β€) : gcd i i = nat_abs i := by simp [gcd]
@[simp] theorem gcd_zero_left (i : β€) : gcd 0 i = nat_abs i := by simp [gcd]
@[simp] theorem gcd_zero_right (i : β€) : gcd i 0 = nat_abs i := by simp [gcd]
@[simp] theorem gcd_one_left (i : β€) : gcd 1 i = 1 := nat.gcd_one_left _
@[simp] theorem gcd_one_right (i : β€) : gcd i 1 = 1 := nat.gcd_one_right _
theorem gcd_mul_left (i j k : β€) : gcd (i * j) (i * k) = nat_abs i * gcd j k :=
by { rw [int.gcd, int.gcd, nat_abs_mul, nat_abs_mul], apply nat.gcd_mul_left }
theorem gcd_mul_right (i j k : β€) : gcd (i * j) (k * j) = gcd i k * nat_abs j :=
by { rw [int.gcd, int.gcd, nat_abs_mul, nat_abs_mul], apply nat.gcd_mul_right }
theorem gcd_pos_of_non_zero_left {i : β€} (j : β€) (i_non_zero : i β 0) : 0 < gcd i j :=
nat.gcd_pos_of_pos_left (nat_abs j) (nat_abs_pos_of_ne_zero i_non_zero)
theorem gcd_pos_of_non_zero_right (i : β€) {j : β€} (j_non_zero : j β 0) : 0 < gcd i j :=
nat.gcd_pos_of_pos_right (nat_abs i) (nat_abs_pos_of_ne_zero j_non_zero)
theorem gcd_eq_zero_iff {i j : β€} : gcd i j = 0 β i = 0 β§ j = 0 :=
begin
rw int.gcd,
split,
{ intro h,
exact β¨nat_abs_eq_zero.mp (nat.eq_zero_of_gcd_eq_zero_left h),
nat_abs_eq_zero.mp (nat.eq_zero_of_gcd_eq_zero_right h)β© },
{ intro h, rw [nat_abs_eq_zero.mpr h.left, nat_abs_eq_zero.mpr h.right],
apply nat.gcd_zero_left }
end
theorem gcd_pos_iff {i j : β€} : 0 < gcd i j β i β 0 β¨ j β 0 :=
pos_iff_ne_zero.trans $ gcd_eq_zero_iff.not.trans not_and_distrib
theorem gcd_div {i j k : β€} (H1 : k β£ i) (H2 : k β£ j) :
gcd (i / k) (j / k) = gcd i j / nat_abs k :=
by rw [gcd, nat_abs_div i k H1, nat_abs_div j k H2];
exact nat.gcd_div (nat_abs_dvd_iff_dvd.mpr H1) (nat_abs_dvd_iff_dvd.mpr H2)
theorem gcd_div_gcd_div_gcd {i j : β€} (H : 0 < gcd i j) :
gcd (i / gcd i j) (j / gcd i j) = 1 :=
begin
rw [gcd_div (gcd_dvd_left i j) (gcd_dvd_right i j)],
rw [nat_abs_of_nat, nat.div_self H]
end
theorem gcd_dvd_gcd_of_dvd_left {i k : β€} (j : β€) (H : i β£ k) : gcd i j β£ gcd k j :=
int.coe_nat_dvd.1 $ dvd_gcd ((gcd_dvd_left i j).trans H) (gcd_dvd_right i j)
theorem gcd_dvd_gcd_of_dvd_right {i k : β€} (j : β€) (H : i β£ k) : gcd j i β£ gcd j k :=
int.coe_nat_dvd.1 $ dvd_gcd (gcd_dvd_left j i) ((gcd_dvd_right j i).trans H)
theorem gcd_dvd_gcd_mul_left (i j k : β€) : gcd i j β£ gcd (k * i) j :=
gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _)
theorem gcd_dvd_gcd_mul_right (i j k : β€) : gcd i j β£ gcd (i * k) j :=
gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _)
theorem gcd_dvd_gcd_mul_left_right (i j k : β€) : gcd i j β£ gcd i (k * j) :=
gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _)
theorem gcd_dvd_gcd_mul_right_right (i j k : β€) : gcd i j β£ gcd i (j * k) :=
gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _)
theorem gcd_eq_left {i j : β€} (H : i β£ j) : gcd i j = nat_abs i :=
nat.dvd_antisymm (by unfold gcd; exact nat.gcd_dvd_left _ _)
(by unfold gcd; exact nat.dvd_gcd dvd_rfl (nat_abs_dvd_iff_dvd.mpr H))
theorem gcd_eq_right {i j : β€} (H : j β£ i) : gcd i j = nat_abs j :=
by rw [gcd_comm, gcd_eq_left H]
theorem ne_zero_of_gcd {x y : β€}
(hc : gcd x y β 0) : x β 0 β¨ y β 0 :=
begin
contrapose! hc,
rw [hc.left, hc.right, gcd_zero_right, nat_abs_zero]
end
theorem exists_gcd_one {m n : β€} (H : 0 < gcd m n) :
β (m' n' : β€), gcd m' n' = 1 β§ m = m' * gcd m n β§ n = n' * gcd m n :=
β¨_, _, gcd_div_gcd_div_gcd H,
(int.div_mul_cancel (gcd_dvd_left m n)).symm,
(int.div_mul_cancel (gcd_dvd_right m n)).symmβ©
theorem exists_gcd_one' {m n : β€} (H : 0 < gcd m n) :
β (g : β) (m' n' : β€), 0 < g β§ gcd m' n' = 1 β§ m = m' * g β§ n = n' * g :=
let β¨m', n', hβ© := exists_gcd_one H in β¨_, m', n', H, hβ©
theorem pow_dvd_pow_iff {m n : β€} {k : β} (k0 : 0 < k) : m ^ k β£ n ^ k β m β£ n :=
begin
refine β¨Ξ» h, _, Ξ» h, pow_dvd_pow_of_dvd h _β©,
apply int.nat_abs_dvd_iff_dvd.mp,
apply (nat.pow_dvd_pow_iff k0).mp,
rw [β int.nat_abs_pow, β int.nat_abs_pow],
exact int.nat_abs_dvd_iff_dvd.mpr h
end
lemma gcd_dvd_iff {a b : β€} {n : β} : gcd a b β£ n β β x y : β€, βn = a * x + b * y :=
begin
split,
{ intro h,
rw [β nat.mul_div_cancel' h, int.coe_nat_mul, gcd_eq_gcd_ab, add_mul, mul_assoc, mul_assoc],
refine β¨_, _, rflβ©, },
{ rintro β¨x, y, hβ©,
rw [βint.coe_nat_dvd, h],
exact dvd_add (dvd_mul_of_dvd_left (gcd_dvd_left a b) _)
(dvd_mul_of_dvd_left (gcd_dvd_right a b) y) }
end
lemma gcd_greatest {a b d : β€} (hd_pos : 0 β€ d) (hda : d β£ a) (hdb : d β£ b)
(hd : β e : β€, e β£ a β e β£ b β e β£ d) : d = gcd a b :=
dvd_antisymm hd_pos
(coe_zero_le (gcd a b)) (dvd_gcd hda hdb) (hd _ (gcd_dvd_left a b) (gcd_dvd_right a b))
/-- Euclid's lemma: if `a β£ b * c` and `gcd a c = 1` then `a β£ b`.
Compare with `is_coprime.dvd_of_dvd_mul_left` and
`unique_factorization_monoid.dvd_of_dvd_mul_left_of_no_prime_factors` -/
lemma dvd_of_dvd_mul_left_of_gcd_one {a b c : β€} (habc : a β£ b * c) (hab : gcd a c = 1) : a β£ b :=
begin
have := gcd_eq_gcd_ab a c,
simp only [hab, int.coe_nat_zero, int.coe_nat_succ, zero_add] at this,
have : b * a * gcd_a a c + b * c * gcd_b a c = b, { simp [mul_assoc, βmul_add, βthis] },
rw βthis,
exact dvd_add (dvd_mul_of_dvd_left (dvd_mul_left a b) _) (dvd_mul_of_dvd_left habc _),
end
/-- Euclid's lemma: if `a β£ b * c` and `gcd a b = 1` then `a β£ c`.
Compare with `is_coprime.dvd_of_dvd_mul_right` and
`unique_factorization_monoid.dvd_of_dvd_mul_right_of_no_prime_factors` -/
lemma dvd_of_dvd_mul_right_of_gcd_one {a b c : β€} (habc : a β£ b * c) (hab : gcd a b = 1) : a β£ c :=
by { rw mul_comm at habc, exact dvd_of_dvd_mul_left_of_gcd_one habc hab }
/-- For nonzero integers `a` and `b`, `gcd a b` is the smallest positive natural number that can be
written in the form `a * x + b * y` for some pair of integers `x` and `y` -/
theorem gcd_least_linear {a b : β€} (ha : a β 0) :
is_least { n : β | 0 < n β§ β x y : β€, βn = a * x + b * y } (a.gcd b) :=
begin
simp_rw βgcd_dvd_iff,
split,
{ simpa [and_true, dvd_refl, set.mem_set_of_eq] using gcd_pos_of_non_zero_left b ha },
{ simp only [lower_bounds, and_imp, set.mem_set_of_eq],
exact Ξ» n hn_pos hn, nat.le_of_dvd hn_pos hn },
end
/-! ### lcm -/
theorem lcm_comm (i j : β€) : lcm i j = lcm j i :=
by { rw [int.lcm, int.lcm], exact nat.lcm_comm _ _ }
theorem lcm_assoc (i j k : β€) : lcm (lcm i j) k = lcm i (lcm j k) :=
by { rw [int.lcm, int.lcm, int.lcm, int.lcm, nat_abs_of_nat, nat_abs_of_nat], apply nat.lcm_assoc }
@[simp] theorem lcm_zero_left (i : β€) : lcm 0 i = 0 :=
by { rw [int.lcm], apply nat.lcm_zero_left }
@[simp] theorem lcm_zero_right (i : β€) : lcm i 0 = 0 :=
by { rw [int.lcm], apply nat.lcm_zero_right }
@[simp] theorem lcm_one_left (i : β€) : lcm 1 i = nat_abs i :=
by { rw int.lcm, apply nat.lcm_one_left }
@[simp] theorem lcm_one_right (i : β€) : lcm i 1 = nat_abs i :=
by { rw int.lcm, apply nat.lcm_one_right }
@[simp] theorem lcm_self (i : β€) : lcm i i = nat_abs i :=
by { rw int.lcm, apply nat.lcm_self }
theorem dvd_lcm_left (i j : β€) : i β£ lcm i j :=
by { rw int.lcm, apply coe_nat_dvd_right.mpr, apply nat.dvd_lcm_left }
theorem dvd_lcm_right (i j : β€) : j β£ lcm i j :=
by { rw int.lcm, apply coe_nat_dvd_right.mpr, apply nat.dvd_lcm_right }
theorem lcm_dvd {i j k : β€} : i β£ k β j β£ k β (lcm i j : β€) β£ k :=
begin
rw int.lcm,
intros hi hj,
exact coe_nat_dvd_left.mpr
(nat.lcm_dvd (nat_abs_dvd_iff_dvd.mpr hi) (nat_abs_dvd_iff_dvd.mpr hj))
end
end int
lemma pow_gcd_eq_one {M : Type*} [monoid M] (x : M) {m n : β} (hm : x ^ m = 1) (hn : x ^ n = 1) :
x ^ m.gcd n = 1 :=
begin
cases m, { simp only [hn, nat.gcd_zero_left] },
obtain β¨x, rflβ© : is_unit x,
{ apply is_unit_of_pow_eq_one _ _ hm m.succ_pos },
simp only [β units.coe_pow] at *,
rw [β units.coe_one, β zpow_coe_nat, β units.ext_iff] at *,
simp only [nat.gcd_eq_gcd_ab, zpow_add, zpow_mul, hm, hn, one_zpow, one_mul]
end
lemma gcd_nsmul_eq_zero {M : Type*} [add_monoid M] (x : M) {m n : β} (hm : m β’ x = 0)
(hn : n β’ x = 0) : (m.gcd n) β’ x = 0 :=
begin
apply multiplicative.of_add.injective,
rw [of_add_nsmul, of_add_zero, pow_gcd_eq_one];
rwa [βof_add_nsmul, βof_add_zero, equiv.apply_eq_iff_eq]
end
attribute [to_additive gcd_nsmul_eq_zero] pow_gcd_eq_one
/-! ### GCD prover -/
open norm_num
namespace tactic
namespace norm_num
lemma int_gcd_helper' {d : β} {x y a b : β€} (hβ : (d:β€) β£ x) (hβ : (d:β€) β£ y)
(hβ : x * a + y * b = d) : int.gcd x y = d :=
begin
refine nat.dvd_antisymm _ (int.coe_nat_dvd.1 (int.dvd_gcd hβ hβ)),
rw [β int.coe_nat_dvd, β hβ],
apply dvd_add,
{ exact (int.gcd_dvd_left _ _).mul_right _ },
{ exact (int.gcd_dvd_right _ _).mul_right _ }
end
lemma nat_gcd_helper_dvd_left (x y a : β) (h : x * a = y) : nat.gcd x y = x :=
nat.gcd_eq_left β¨a, h.symmβ©
lemma nat_gcd_helper_dvd_right (x y a : β) (h : y * a = x) : nat.gcd x y = y :=
nat.gcd_eq_right β¨a, h.symmβ©
lemma nat_gcd_helper_2 (d x y a b u v tx ty : β) (hu : d * u = x) (hv : d * v = y)
(hx : x * a = tx) (hy : y * b = ty) (h : ty + d = tx) : nat.gcd x y = d :=
begin
rw β int.coe_nat_gcd, apply @int_gcd_helper' _ _ _ a (-b)
(int.coe_nat_dvd.2 β¨_, hu.symmβ©) (int.coe_nat_dvd.2 β¨_, hv.symmβ©),
rw [mul_neg, β sub_eq_add_neg, sub_eq_iff_eq_add'],
norm_cast, rw [hx, hy, h]
end
lemma nat_gcd_helper_1 (d x y a b u v tx ty : β) (hu : d * u = x) (hv : d * v = y)
(hx : x * a = tx) (hy : y * b = ty) (h : tx + d = ty) : nat.gcd x y = d :=
(nat.gcd_comm _ _).trans $ nat_gcd_helper_2 _ _ _ _ _ _ _ _ _ hv hu hy hx h
lemma nat_lcm_helper (x y d m n : β) (hd : nat.gcd x y = d) (d0 : 0 < d)
(xy : x * y = n) (dm : d * m = n) : nat.lcm x y = m :=
(nat.mul_right_inj d0).1 $ by rw [dm, β xy, β hd, nat.gcd_mul_lcm]
lemma nat_coprime_helper_zero_left (x : β) (h : 1 < x) : Β¬ nat.coprime 0 x :=
mt (nat.coprime_zero_left _).1 $ ne_of_gt h
lemma nat_coprime_helper_zero_right (x : β) (h : 1 < x) : Β¬ nat.coprime x 0 :=
mt (nat.coprime_zero_right _).1 $ ne_of_gt h
lemma nat_coprime_helper_1 (x y a b tx ty : β)
(hx : x * a = tx) (hy : y * b = ty) (h : tx + 1 = ty) : nat.coprime x y :=
nat_gcd_helper_1 _ _ _ _ _ _ _ _ _ (one_mul _) (one_mul _) hx hy h
lemma nat_coprime_helper_2 (x y a b tx ty : β)
(hx : x * a = tx) (hy : y * b = ty) (h : ty + 1 = tx) : nat.coprime x y :=
nat_gcd_helper_2 _ _ _ _ _ _ _ _ _ (one_mul _) (one_mul _) hx hy h
lemma nat_not_coprime_helper (d x y u v : β) (hu : d * u = x) (hv : d * v = y)
(h : 1 < d) : Β¬ nat.coprime x y :=
nat.not_coprime_of_dvd_of_dvd h β¨_, hu.symmβ© β¨_, hv.symmβ©
lemma int_gcd_helper (x y : β€) (nx ny d : β) (hx : (nx:β€) = x) (hy : (ny:β€) = y)
(h : nat.gcd nx ny = d) : int.gcd x y = d :=
by rwa [β hx, β hy, int.coe_nat_gcd]
lemma int_gcd_helper_neg_left (x y : β€) (d : β) (h : int.gcd x y = d) : int.gcd (-x) y = d :=
by rw int.gcd at h β’; rwa int.nat_abs_neg
lemma int_gcd_helper_neg_right (x y : β€) (d : β) (h : int.gcd x y = d) : int.gcd x (-y) = d :=
by rw int.gcd at h β’; rwa int.nat_abs_neg
lemma int_lcm_helper (x y : β€) (nx ny d : β) (hx : (nx:β€) = x) (hy : (ny:β€) = y)
(h : nat.lcm nx ny = d) : int.lcm x y = d :=
by rwa [β hx, β hy, int.coe_nat_lcm]
lemma int_lcm_helper_neg_left (x y : β€) (d : β) (h : int.lcm x y = d) : int.lcm (-x) y = d :=
by rw int.lcm at h β’; rwa int.nat_abs_neg
lemma int_lcm_helper_neg_right (x y : β€) (d : β) (h : int.lcm x y = d) : int.lcm x (-y) = d :=
by rw int.lcm at h β’; rwa int.nat_abs_neg
/-- Evaluates the `nat.gcd` function. -/
meta def prove_gcd_nat (c : instance_cache) (ex ey : expr) :
tactic (instance_cache Γ expr Γ expr) := do
x β ex.to_nat,
y β ey.to_nat,
match x, y with
| 0, _ := pure (c, ey, `(nat.gcd_zero_left).mk_app [ey])
| _, 0 := pure (c, ex, `(nat.gcd_zero_right).mk_app [ex])
| 1, _ := pure (c, `(1:β), `(nat.gcd_one_left).mk_app [ey])
| _, 1 := pure (c, `(1:β), `(nat.gcd_one_right).mk_app [ex])
| _, _ := do
let (d, a, b) := nat.xgcd_aux x 1 0 y 0 1,
if d = x then do
(c, ea) β c.of_nat (y / x),
(c, _, p) β prove_mul_nat c ex ea,
pure (c, ex, `(nat_gcd_helper_dvd_left).mk_app [ex, ey, ea, p])
else if d = y then do
(c, ea) β c.of_nat (x / y),
(c, _, p) β prove_mul_nat c ey ea,
pure (c, ey, `(nat_gcd_helper_dvd_right).mk_app [ex, ey, ea, p])
else do
(c, ed) β c.of_nat d,
(c, ea) β c.of_nat a.nat_abs,
(c, eb) β c.of_nat b.nat_abs,
(c, eu) β c.of_nat (x / d),
(c, ev) β c.of_nat (y / d),
(c, _, pu) β prove_mul_nat c ed eu,
(c, _, pv) β prove_mul_nat c ed ev,
(c, etx, px) β prove_mul_nat c ex ea,
(c, ety, py) β prove_mul_nat c ey eb,
(c, p) β if a β₯ 0 then prove_add_nat c ety ed etx else prove_add_nat c etx ed ety,
let pf : expr := if a β₯ 0 then `(nat_gcd_helper_2) else `(nat_gcd_helper_1),
pure (c, ed, pf.mk_app [ed, ex, ey, ea, eb, eu, ev, etx, ety, pu, pv, px, py, p])
end
/-- Evaluates the `nat.lcm` function. -/
meta def prove_lcm_nat (c : instance_cache) (ex ey : expr) :
tactic (instance_cache Γ expr Γ expr) := do
x β ex.to_nat,
y β ey.to_nat,
match x, y with
| 0, _ := pure (c, `(0:β), `(nat.lcm_zero_left).mk_app [ey])
| _, 0 := pure (c, `(0:β), `(nat.lcm_zero_right).mk_app [ex])
| 1, _ := pure (c, ey, `(nat.lcm_one_left).mk_app [ey])
| _, 1 := pure (c, ex, `(nat.lcm_one_right).mk_app [ex])
| _, _ := do
(c, ed, pd) β prove_gcd_nat c ex ey,
(c, p0) β prove_pos c ed,
(c, en, xy) β prove_mul_nat c ex ey,
d β ed.to_nat,
(c, em) β c.of_nat ((x * y) / d),
(c, _, dm) β prove_mul_nat c ed em,
pure (c, em, `(nat_lcm_helper).mk_app [ex, ey, ed, em, en, pd, p0, xy, dm])
end
/-- Evaluates the `int.gcd` function. -/
meta def prove_gcd_int (zc nc : instance_cache) : expr β expr β
tactic (instance_cache Γ instance_cache Γ expr Γ expr)
| x y := match match_neg x with
| some x := do
(zc, nc, d, p) β prove_gcd_int x y,
pure (zc, nc, d, `(int_gcd_helper_neg_left).mk_app [x, y, d, p])
| none := match match_neg y with
| some y := do
(zc, nc, d, p) β prove_gcd_int x y,
pure (zc, nc, d, `(int_gcd_helper_neg_right).mk_app [x, y, d, p])
| none := do
(zc, nc, nx, px) β prove_nat_uncast zc nc x,
(zc, nc, ny, py) β prove_nat_uncast zc nc y,
(nc, d, p) β prove_gcd_nat nc nx ny,
pure (zc, nc, d, `(int_gcd_helper).mk_app [x, y, nx, ny, d, px, py, p])
end
end
/-- Evaluates the `int.lcm` function. -/
meta def prove_lcm_int (zc nc : instance_cache) : expr β expr β
tactic (instance_cache Γ instance_cache Γ expr Γ expr)
| x y := match match_neg x with
| some x := do
(zc, nc, d, p) β prove_lcm_int x y,
pure (zc, nc, d, `(int_lcm_helper_neg_left).mk_app [x, y, d, p])
| none := match match_neg y with
| some y := do
(zc, nc, d, p) β prove_lcm_int x y,
pure (zc, nc, d, `(int_lcm_helper_neg_right).mk_app [x, y, d, p])
| none := do
(zc, nc, nx, px) β prove_nat_uncast zc nc x,
(zc, nc, ny, py) β prove_nat_uncast zc nc y,
(nc, d, p) β prove_lcm_nat nc nx ny,
pure (zc, nc, d, `(int_lcm_helper).mk_app [x, y, nx, ny, d, px, py, p])
end
end
/-- Evaluates the `nat.coprime` function. -/
meta def prove_coprime_nat (c : instance_cache) (ex ey : expr) :
tactic (instance_cache Γ (expr β expr)) := do
x β ex.to_nat,
y β ey.to_nat,
match x, y with
| 1, _ := pure (c, sum.inl $ `(nat.coprime_one_left).mk_app [ey])
| _, 1 := pure (c, sum.inl $ `(nat.coprime_one_right).mk_app [ex])
| 0, 0 := pure (c, sum.inr `(nat.not_coprime_zero_zero))
| 0, _ := do
c β mk_instance_cache `(β),
(c, p) β prove_lt_nat c `(1) ey,
pure (c, sum.inr $ `(nat_coprime_helper_zero_left).mk_app [ey, p])
| _, 0 := do
c β mk_instance_cache `(β),
(c, p) β prove_lt_nat c `(1) ex,
pure (c, sum.inr $ `(nat_coprime_helper_zero_right).mk_app [ex, p])
| _, _ := do
c β mk_instance_cache `(β),
let (d, a, b) := nat.xgcd_aux x 1 0 y 0 1,
if d = 1 then do
(c, ea) β c.of_nat a.nat_abs,
(c, eb) β c.of_nat b.nat_abs,
(c, etx, px) β prove_mul_nat c ex ea,
(c, ety, py) β prove_mul_nat c ey eb,
(c, p) β if a β₯ 0 then prove_add_nat c ety `(1) etx else prove_add_nat c etx `(1) ety,
let pf : expr := if a β₯ 0 then `(nat_coprime_helper_2) else `(nat_coprime_helper_1),
pure (c, sum.inl $ pf.mk_app [ex, ey, ea, eb, etx, ety, px, py, p])
else do
(c, ed) β c.of_nat d,
(c, eu) β c.of_nat (x / d),
(c, ev) β c.of_nat (y / d),
(c, _, pu) β prove_mul_nat c ed eu,
(c, _, pv) β prove_mul_nat c ed ev,
(c, p) β prove_lt_nat c `(1) ed,
pure (c, sum.inr $ `(nat_not_coprime_helper).mk_app [ed, ex, ey, eu, ev, pu, pv, p])
end
/-- Evaluates the `gcd`, `lcm`, and `coprime` functions. -/
@[norm_num] meta def eval_gcd : expr β tactic (expr Γ expr)
| `(nat.gcd %%ex %%ey) := do
c β mk_instance_cache `(β),
prod.snd <$> prove_gcd_nat c ex ey
| `(nat.lcm %%ex %%ey) := do
c β mk_instance_cache `(β),
prod.snd <$> prove_lcm_nat c ex ey
| `(nat.coprime %%ex %%ey) := do
c β mk_instance_cache `(β),
prove_coprime_nat c ex ey >>= sum.elim true_intro false_intro β prod.snd
| `(int.gcd %%ex %%ey) := do
zc β mk_instance_cache `(β€),
nc β mk_instance_cache `(β),
(prod.snd β prod.snd) <$> prove_gcd_int zc nc ex ey
| `(int.lcm %%ex %%ey) := do
zc β mk_instance_cache `(β€),
nc β mk_instance_cache `(β),
(prod.snd β prod.snd) <$> prove_lcm_int zc nc ex ey
| _ := failed
end norm_num
end tactic
|
a7ac3a979319ef12dedd290a97442b7b07fce317 | 54deab7025df5d2df4573383df7e1e5497b7a2c2 | /tactic/finish.lean | 50e7bde5143674fade621e72b7d84f988c69dce2 | [
"Apache-2.0"
] | permissive | HGldJ1966/mathlib | f8daac93a5b4ae805cfb0ecebac21a9ce9469009 | c5c5b504b918a6c5e91e372ee29ed754b0513e85 | refs/heads/master | 1,611,340,395,683 | 1,503,040,489,000 | 1,503,040,489,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,492 | lean | /-
Copyright (c) 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
These tactics do straightforward things: they call the simplifier, split conjunctive assumptions,
eliminate existential quantifiers on the left, and look for contradictions. They rely on ematching
and congruence closure to try to finish off a goal at the end.
The procedures *do* split on disjunctions and recreate the smt state for each terminal call, so
they are only meant to be used on small, straightforward problems.
We provide the following tactics:
finish -- solves the goal or fails
clarify -- makes as much progress as possible while not leaving more than one goal
safe -- splits freely, finishes off whatever subgoals it can, and leaves the rest
All accept an optional list of simplifier rules, typically definitions that should be expanded.
(The equations and identities should not refer to the local context.)
The variants ifinish, iclarify, and isafe restrict to intuitionistic logic. They do not work
well with the current heuristic instantiation method used by ematch, so they should be revisited
when the API changes.
-/
import logic.basic
declare_trace auto.done
declare_trace auto.finish
-- TODO(Jeremy): move these
namespace tactic
/- call (assert n t) with a fresh name n. -/
meta def assert_fresh (t : expr) : tactic expr :=
do n β get_unused_name `h none,
assert n t
/- call (assertv n t v) with a fresh name n. -/
meta def assertv_fresh (t : expr) (v : expr) : tactic expr :=
do h β get_unused_name `h none,
assertv h t v
-- returns the number of hypotheses reverted
meta def revert_all : tactic β :=
do ctx β local_context,
revert_lst ctx
namespace interactive
meta def revert_all := tactic.revert_all
end interactive
end tactic
open tactic expr
namespace auto
/- Utilities -/
meta def whnf_reducible (e : expr) : tactic expr := whnf e reducible
-- stolen from interactive.lean
meta def add_simps : simp_lemmas β list name β tactic simp_lemmas
| s [] := return s
| s (n::ns) := do s' β s.add_simp n, add_simps s' ns
/-
Configuration information for the auto tactics.
-/
structure auto_config : Type :=
(use_simp := tt) -- call the simplifier
(classical := tt) -- use classical logic
(max_ematch_rounds := 20) -- for the "done" tactic
/-
Preprocess goal.
We want to move everything to the left of the sequent arrow. For intuitionistic logic,
we replace the goal p with β f, (p β f) β f and introduce.
-/
theorem by_contradiction_trick (p : Prop) (h : β f : Prop, (p β f) β f) : p :=
h p id
meta def preprocess_goal (cfg : auto_config) : tactic unit :=
do repeat (intro1 >> skip),
tgt β target >>= whnf_reducible,
if (Β¬ (is_false tgt)) then
if cfg.classical then
(mk_mapp ``classical.by_contradiction [some tgt]) >>= apply >> intro1 >> skip
else
(mk_mapp ``decidable.by_contradiction [some tgt, none] >>= apply >> intro1 >> skip) <|>
applyc ``by_contradiction_trick >> intro1 >> intro1 >> skip
else
skip
/-
Normalize hypotheses. Bring conjunctions to the outside (for splitting),
bring universal quantifiers to the outside (for ematching). The classical normalizer
eliminates a β b in favor of Β¬ a β¨ b.
For efficiency, we push negations inwards from the top down. (For example, consider
simplifying Β¬ Β¬ (p β¨ q).)
-/
section
universe u
variable {Ξ± : Type u}
variables (p q : Prop)
variable (s : Ξ± β Prop)
local attribute [instance] classical.prop_decidable
theorem not_not_eq : (Β¬ Β¬ p) = p := propext not_not_iff
theorem not_and_eq : (Β¬ (p β§ q)) = (Β¬ p β¨ Β¬ q) := propext not_and_iff
theorem not_or_eq : (Β¬ (p β¨ q)) = (Β¬ p β§ Β¬ q) := propext not_or_iff
theorem not_forall_eq : (Β¬ β x, s x) = (β x, Β¬ s x) := propext not_forall_iff
theorem not_exists_eq : (Β¬ β x, s x) = (β x, Β¬ s x) := propext not_exists_iff
theorem not_implies_eq : (Β¬ (p β q)) = (p β§ Β¬ q) := propext not_implies_iff
theorem classical.implies_iff_not_or : (p β q) β (Β¬ p β¨ q) := implies_iff_not_or
end
def common_normalize_lemma_names : list name :=
[``bexists_def, ``forall_and_distrib, ``exists_implies_distrib]
def classical_normalize_lemma_names : list name :=
common_normalize_lemma_names ++ [``classical.implies_iff_not_or]
-- optionally returns an equivalent expression and proof of equivalence
private meta def transform_negation_step (cfg : auto_config) (e : expr) :
tactic (option (expr Γ expr)) :=
do e β whnf_reducible e,
match e with
| `(Β¬ %%ne) :=
(do ne β whnf_reducible ne,
match ne with
| `(Β¬ %%a) := do pr β mk_app ``not_not_eq [a],
return (some (a, pr))
| `(%%a β§ %%b) := do pr β mk_app ``not_and_eq [a, b],
return (some (`(Β¬ %%a β¨ Β¬ %%b), pr))
| `(%%a β¨ %%b) := do pr β mk_app ``not_or_eq [a, b],
return (some (`(Β¬ %%a β§ Β¬ %%b), pr))
| `(Exists %%p) := do pr β mk_app ``not_exists_eq [p],
`(%%_ = %%e') β infer_type pr,
return (some (e', pr))
| (pi n bi d p) := if Β¬ cfg.classical then return none
else if p.has_var then do
pr β mk_app ``not_forall_eq [lam n bi d (expr.abstract_local p n)],
`(%%_ = %%e') β infer_type pr,
return (some (e', pr))
else do
pr β mk_app ``not_implies_eq [d, p],
`(%%_ = %%e') β infer_type pr,
return (some (e', pr))
| _ := return none
end)
| _ := return none
end
-- given an expr 'e', returns a new expression and a proof of equality
private meta def transform_negation (cfg : auto_config) : expr β tactic (option (expr Γ expr)) :=
Ξ» e, do
opr β transform_negation_step cfg e,
match opr with
| (some (e', pr)) := do
opr' β transform_negation e',
match opr' with
| none := return (some (e', pr))
| (some (e'', pr')) := do pr'' β mk_eq_trans pr pr',
return (some (e'', pr''))
end
| none := return none
end
meta def normalize_negations (cfg : auto_config) (h : expr) : tactic unit :=
do t β infer_type h,
(_, e, pr) β simplify_top_down ()
(Ξ» _, Ξ» e, do
oepr β transform_negation cfg e,
match oepr with
| (some (e', pr)) := return ((), e', pr)
| none := do pr β mk_eq_refl e, return ((), e, pr)
end)
t,
replace_hyp h e pr,
skip
meta def normalize_hyp (cfg : auto_config) (simps : simp_lemmas) (h : expr) : tactic unit :=
(do h β simp_hyp simps [] h, try (normalize_negations cfg h)) <|>
try (normalize_negations cfg h)
meta def normalize_hyps (cfg : auto_config) : tactic unit :=
do simps β if cfg.classical then
add_simps simp_lemmas.mk classical_normalize_lemma_names
else
add_simps simp_lemmas.mk common_normalize_lemma_names,
local_context >>= monad.mapm' (normalize_hyp cfg simps)
/-
Eliminate existential quantifiers.
-/
-- eliminate an existential quantifier if there is one
meta def eelim : tactic unit :=
do ctx β local_context,
first $ ctx.map $ Ξ» h,
do t β infer_type h >>= whnf_reducible,
guard (is_app_of t ``Exists),
tgt β target,
to_expr ``(@exists.elim _ _ %%tgt %%h) >>= apply,
intros,
clear h
-- eliminate all existential quantifiers, fails if there aren't any
meta def eelims : tactic unit := eelim >> repeat eelim
/-
Substitute if there is a hypothesis x = t or t = x.
-/
-- carries out a subst if there is one, fails otherwise
meta def do_subst : tactic unit :=
do ctx β local_context,
first $ ctx.map $ Ξ» h,
do t β infer_type h >>= whnf_reducible,
match t with
| `(%%a = %%b) := subst h
| _ := failed
end
meta def do_substs : tactic unit := do_subst >> repeat do_subst
/-
Split all conjunctions.
-/
-- Assumes pr is a proof of t. Adds the consequences of t to the context
-- and returns tt if anything nontrivial has been added.
meta def add_conjuncts : expr β expr β tactic bool :=
Ξ» pr t,
let assert_consequences := Ξ» e t, mcond (add_conjuncts e t) skip (assertv_fresh t e >> skip) in
do t' β whnf_reducible t,
match t' with
| `(%%a β§ %%b) :=
do eβ β mk_app ``and.left [pr],
assert_consequences eβ a,
eβ β mk_app ``and.right [pr],
assert_consequences eβ b,
return tt
| `(true) :=
do return tt
| _ := return ff
end
-- return tt if any progress is made
meta def split_hyp (h : expr) : tactic bool :=
do t β infer_type h,
mcond (add_conjuncts h t) (clear h >> return tt) (return ff)
-- return tt if any progress is made
meta def split_hyps_aux : list expr β tactic bool
| [] := return ff
| (h :: hs) := do bβ β split_hyp h,
bβ β split_hyps_aux hs,
return (bβ || bβ)
-- fail if no progress is made
meta def split_hyps : tactic unit := local_context >>= split_hyps_aux >>= guardb
/-
Eagerly apply all the preprocessing rules.
-/
meta def preprocess_hyps (cfg : auto_config) : tactic unit :=
do repeat (intro1 >> skip),
preprocess_goal cfg,
normalize_hyps cfg,
repeat (do_substs <|> split_hyps <|> eelim /-<|> self_simplify_hyps-/)
/-
The terminal tactic, used to try to finish off goals:
- Call the contradiction tactic.
- Open an SMT state, and use ematching and congruence closure, with all the universal
statements in the context.
TODO(Jeremy): allow users to specify attribute for ematching lemmas?
-/
meta def mk_hinst_lemmas : list expr β smt_tactic hinst_lemmas
| [] := -- return hinst_lemmas.mk
do get_hinst_lemmas_for_attr `ematch
| (h :: hs) := do his β mk_hinst_lemmas hs,
t β infer_type h,
match t with
| (pi _ _ _ _) :=
do t' β infer_type t,
if t' = `(Prop) then
(do new_lemma β hinst_lemma.mk h,
return (hinst_lemmas.add his new_lemma)) <|> return his
else return his
| _ := return his
end
meta def done (cfg : auto_config := {}) : tactic unit :=
do when_tracing `auto.done (trace "entering done" >> trace_state),
contradiction <|>
(solve1 $
(do revert_all,
using_smt
(do smt_tactic.intros,
ctx β local_context,
hs β mk_hinst_lemmas ctx,
smt_tactic.repeat_at_most cfg.max_ematch_rounds
(smt_tactic.ematch_using hs >> smt_tactic.try smt_tactic.close))))
/-
Tactics that perform case splits.
-/
inductive case_option
| force -- fail unless all goals are solved
| at_most_one -- leave at most one goal
| accept -- leave as many goals as necessary
private meta def case_cont (s : case_option) (cont : case_option β tactic unit) : tactic unit :=
do match s with
| case_option.force := cont case_option.force >> cont case_option.force
| case_option.at_most_one :=
-- if the first one succeeds, commit to it, and try the second
(mcond (cont case_option.force >> return tt) (cont case_option.at_most_one) skip) <|>
-- otherwise, try the second
(swap >> cont case_option.force >> cont case_option.at_most_one)
| case_option.accept := focus [cont case_option.accept, cont case_option.accept]
end
-- three possible outcomes:
-- finds something to case, the continuations succeed ==> returns tt
-- finds something to case, the continutations fail ==> fails
-- doesn't find anything to case ==> returns ff
meta def case_hyp (h : expr) (s : case_option) (cont : case_option β tactic unit) : tactic bool :=
do t β infer_type h,
match t with
| `(%%a β¨ %%b) := cases h >> case_cont s cont >> return tt
| _ := return ff
end
meta def case_some_hyp_aux (s : case_option) (cont : case_option β tactic unit) :
list expr β tactic bool
| [] := return ff
| (h::hs) := mcond (case_hyp h s cont) (return tt) (case_some_hyp_aux hs)
meta def case_some_hyp (s : case_option) (cont : case_option β tactic unit) : tactic bool :=
local_context >>= case_some_hyp_aux s cont
/-
The main tactics.
-/
meta def safe_core (s : simp_lemmas Γ list name) (cfg : auto_config) : case_option β tactic unit :=
Ξ» co, focus1 $
do when_tracing `auto.finish (trace "entering safe_core" >> trace_state),
if cfg.use_simp then do
when_tracing `auto.finish (trace "simplifying hypotheses"),
simp_all s.1 s.2 { fail_if_unchanged := ff },
when_tracing `auto.finish (trace "result:" >> trace_state)
else skip,
tactic.done <|>
do when_tracing `auto.finish (trace "preprocessing hypotheses"),
preprocess_hyps cfg,
when_tracing `auto.finish (trace "result:" >> trace_state),
done cfg <|>
(mcond (case_some_hyp co safe_core)
skip
(match co with
| case_option.force := done cfg
| case_option.at_most_one := try (done cfg)
| case_option.accept := try (done cfg)
end))
meta def clarify (s : simp_lemmas Γ list name) (cfg : auto_config := {}) : tactic unit :=
safe_core s cfg case_option.at_most_one
meta def safe (s : simp_lemmas Γ list name) (cfg : auto_config := {}) : tactic unit :=
safe_core s cfg case_option.accept
meta def finish (s : simp_lemmas Γ list name) (cfg : auto_config := {}) : tactic unit :=
safe_core s cfg case_option.force
meta def iclarify (s : simp_lemmas Γ list name) (cfg : auto_config := {}) : tactic unit :=
clarify s {cfg with classical := false}
meta def isafe (s : simp_lemmas Γ list name) (cfg : auto_config := {}) : tactic unit :=
safe s {cfg with classical := false}
meta def ifinish (s : simp_lemmas Γ list name) (cfg : auto_config := {}) : tactic unit :=
finish s {cfg with classical := false}
end auto
/- interactive versions -/
open auto
namespace tactic
namespace interactive
open lean lean.parser interactive interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many
meta def clarify (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit :=
do s β mk_simp_set ff [] hs,
auto.clarify s cfg
meta def safe (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit :=
do s β mk_simp_set ff [] hs,
auto.safe s cfg
meta def finish (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit :=
do s β mk_simp_set ff [] hs,
auto.finish s cfg
meta def iclarify (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit :=
do s β mk_simp_set ff [] hs,
auto.iclarify s cfg
meta def isafe (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit :=
do s β mk_simp_set ff [] hs,
auto.isafe s cfg
meta def ifinish (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit :=
do s β mk_simp_set ff [] hs,
auto.ifinish s cfg
end interactive
end tactic
|
1db5eef1afceb1373cc28e68cd1f9157b2906ee0 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/deprecated/ring.lean | 6fc10e0209fa7da7c6bcfa0fc33e3df9c37395fb | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 4,653 | lean | /-
Copyright (c) 2020 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import deprecated.group
/-!
# Unbundled semiring and ring homomorphisms (deprecated)
This file defines typeclasses for unbundled semiring and ring homomorphisms. Though these classes are
deprecated, they are still widely used in mathlib, and probably will not go away before Lean 4
because Lean 3 often fails to coerce a bundled homomorphism to a function.
## main definitions
is_semiring_hom (deprecated), is_ring_hom (deprecated)
## Tags
is_semiring_hom, is_ring_hom
-/
universes u v w
variable {Ξ± : Type u}
/-- Predicate for semiring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/
class is_semiring_hom {Ξ± : Type u} {Ξ² : Type v} [semiring Ξ±] [semiring Ξ²] (f : Ξ± β Ξ²) : Prop :=
(map_zero [] : f 0 = 0)
(map_one [] : f 1 = 1)
(map_add [] : β {x y}, f (x + y) = f x + f y)
(map_mul [] : β {x y}, f (x * y) = f x * f y)
namespace is_semiring_hom
variables {Ξ² : Type v} [semiring Ξ±] [semiring Ξ²]
variables (f : Ξ± β Ξ²) [is_semiring_hom f] {x y : Ξ±}
/-- The identity map is a semiring homomorphism. -/
instance id : is_semiring_hom (@id Ξ±) := by refine {..}; intros; refl
/-- The composition of two semiring homomorphisms is a semiring homomorphism. -/
-- see Note [no instance on morphisms]
lemma comp {Ξ³} [semiring Ξ³] (g : Ξ² β Ξ³) [is_semiring_hom g] :
is_semiring_hom (g β f) :=
{ map_zero := by simp [map_zero f]; exact map_zero g,
map_one := by simp [map_one f]; exact map_one g,
map_add := Ξ» x y, by simp [map_add f]; rw map_add g; refl,
map_mul := Ξ» x y, by simp [map_mul f]; rw map_mul g; refl }
/-- A semiring homomorphism is an additive monoid homomorphism. -/
@[priority 100] -- see Note [lower instance priority]
instance : is_add_monoid_hom f :=
{ ..βΉis_semiring_hom fβΊ }
/-- A semiring homomorphism is a monoid homomorphism. -/
@[priority 100] -- see Note [lower instance priority]
instance : is_monoid_hom f :=
{ ..βΉis_semiring_hom fβΊ }
end is_semiring_hom
/-- Predicate for ring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/
class is_ring_hom {Ξ± : Type u} {Ξ² : Type v} [ring Ξ±] [ring Ξ²] (f : Ξ± β Ξ²) : Prop :=
(map_one [] : f 1 = 1)
(map_mul [] : β {x y}, f (x * y) = f x * f y)
(map_add [] : β {x y}, f (x + y) = f x + f y)
namespace is_ring_hom
variables {Ξ² : Type v} [ring Ξ±] [ring Ξ²]
/-- A map of rings that is a semiring homomorphism is also a ring homomorphism. -/
lemma of_semiring (f : Ξ± β Ξ²) [H : is_semiring_hom f] : is_ring_hom f := {..H}
variables (f : Ξ± β Ξ²) [is_ring_hom f] {x y : Ξ±}
/-- Ring homomorphisms map zero to zero. -/
lemma map_zero : f 0 = 0 :=
calc f 0 = f (0 + 0) - f 0 : by rw [map_add f]; simp
... = 0 : by simp
/-- Ring homomorphisms preserve additive inverses. -/
lemma map_neg : f (-x) = -f x :=
calc f (-x) = f (-x + x) - f x : by rw [map_add f]; simp
... = -f x : by simp [map_zero f]
/-- Ring homomorphisms preserve subtraction. -/
lemma map_sub : f (x - y) = f x - f y :=
by simp [sub_eq_add_neg, map_add f, map_neg f]
/-- The identity map is a ring homomorphism. -/
instance id : is_ring_hom (@id Ξ±) := by refine {..}; intros; refl
/-- The composition of two ring homomorphisms is a ring homomorphism. -/
-- see Note [no instance on morphisms]
lemma comp {Ξ³} [ring Ξ³] (g : Ξ² β Ξ³) [is_ring_hom g] :
is_ring_hom (g β f) :=
{ map_add := Ξ» x y, by simp [map_add f]; rw map_add g; refl,
map_mul := Ξ» x y, by simp [map_mul f]; rw map_mul g; refl,
map_one := by simp [map_one f]; exact map_one g }
/-- A ring homomorphism is also a semiring homomorphism. -/
@[priority 100] -- see Note [lower instance priority]
instance : is_semiring_hom f :=
{ map_zero := map_zero f, ..βΉis_ring_hom fβΊ }
@[priority 100] -- see Note [lower instance priority]
instance : is_add_group_hom f := { }
end is_ring_hom
variables {Ξ² : Type v} {Ξ³ : Type w} [rΞ± : semiring Ξ±] [rΞ² : semiring Ξ²]
namespace ring_hom
section
include rΞ± rΞ²
/-- Interpret `f : Ξ± β Ξ²` with `is_semiring_hom f` as a ring homomorphism. -/
def of (f : Ξ± β Ξ²) [is_semiring_hom f] : Ξ± β+* Ξ² :=
{ to_fun := f,
.. monoid_hom.of f,
.. add_monoid_hom.of f }
@[simp] lemma coe_of (f : Ξ± β Ξ²) [is_semiring_hom f] : β(of f) = f := rfl
instance (f : Ξ± β+* Ξ²) : is_semiring_hom f :=
{ map_zero := f.map_zero,
map_one := f.map_one,
map_add := f.map_add,
map_mul := f.map_mul }
end
instance {Ξ± Ξ³} [ring Ξ±] [ring Ξ³] (g : Ξ± β+* Ξ³) : is_ring_hom g :=
is_ring_hom.of_semiring g
end ring_hom
|
90be6abc429d84fc4e086ef32ef3f97526bb6b72 | a338c3e75cecad4fb8d091bfe505f7399febfd2b | /src/analysis/normed_space/multilinear.lean | 4e58cfacb0fca170c92cc31d3985c5dd89bc48c4 | [
"Apache-2.0"
] | permissive | bacaimano/mathlib | 88eb7911a9054874fba2a2b74ccd0627c90188af | f2edc5a3529d95699b43514d6feb7eb11608723f | refs/heads/master | 1,686,410,075,833 | 1,625,497,070,000 | 1,625,497,070,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 73,468 | lean | /-
Copyright (c) 2020 SΓ©bastien GouΓ«zel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: SΓ©bastien GouΓ«zel
-/
import analysis.normed_space.operator_norm
import topology.algebra.multilinear
/-!
# Operator norm on the space of continuous multilinear maps
When `f` is a continuous multilinear map in finitely many variables, we define its norm `β₯fβ₯` as the
smallest number such that `β₯f mβ₯ β€ β₯fβ₯ * β i, β₯m iβ₯` for all `m`.
We show that it is indeed a norm, and prove its basic properties.
## Main results
Let `f` be a multilinear map in finitely many variables.
* `exists_bound_of_continuous` asserts that, if `f` is continuous, then there exists `C > 0`
with `β₯f mβ₯ β€ C * β i, β₯m iβ₯` for all `m`.
* `continuous_of_bound`, conversely, asserts that this bound implies continuity.
* `mk_continuous` constructs the associated continuous multilinear map.
Let `f` be a continuous multilinear map in finitely many variables.
* `β₯fβ₯` is its norm, i.e., the smallest number such that `β₯f mβ₯ β€ β₯fβ₯ * β i, β₯m iβ₯` for
all `m`.
* `le_op_norm f m` asserts the fundamental inequality `β₯f mβ₯ β€ β₯fβ₯ * β i, β₯m iβ₯`.
* `norm_image_sub_le f mβ mβ` gives a control of the difference `f mβ - f mβ` in terms of
`β₯fβ₯` and `β₯mβ - mββ₯`.
We also register isomorphisms corresponding to currying or uncurrying variables, transforming a
continuous multilinear function `f` in `n+1` variables into a continuous linear function taking
values in continuous multilinear functions in `n` variables, and also into a continuous multilinear
function in `n` variables taking values in continuous linear functions. These operations are called
`f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and
`f.uncurry_right`). They induce continuous linear equivalences between spaces of
continuous multilinear functions in `n+1` variables and spaces of continuous linear functions into
continuous multilinear functions in `n` variables (resp. continuous multilinear functions in `n`
variables taking values in continuous linear functions), called respectively
`continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`.
## Implementation notes
We mostly follow the API (and the proofs) of `operator_norm.lean`, with the additional complexity
that we should deal with multilinear maps in several variables. The currying/uncurrying
constructions are based on those in `multilinear.lean`.
From the mathematical point of view, all the results follow from the results on operator norm in
one variable, by applying them to one variable after the other through currying. However, this
is only well defined when there is an order on the variables (for instance on `fin n`) although
the final result is independent of the order. While everything could be done following this
approach, it turns out that direct proofs are easier and more efficient.
-/
noncomputable theory
open_locale classical big_operators nnreal
open finset metric
local attribute [instance, priority 1001]
add_comm_group.to_add_comm_monoid normed_group.to_add_comm_group normed_space.to_module
-- hack to speed up simp when dealing with complicated types
local attribute [-instance] unique.subsingleton pi.subsingleton
/-!
### Type variables
We use the following type variables in this file:
* `π` : a `nondiscrete_normed_field`;
* `ΞΉ`, `ΞΉ'` : finite index types with decidable equality;
* `E`, `Eβ` : families of normed vector spaces over `π` indexed by `i : ΞΉ`;
* `E'` : a family of normed vector spaces over `π` indexed by `i' : ΞΉ'`;
* `Ei` : a family of normed vector spaces over `π` indexed by `i : fin (nat.succ n)`;
* `G`, `G'` : normed vector spaces over `π`.
-/
universes u v v' wE wEβ wE' wEi wG wG'
variables {π : Type u} {ΞΉ : Type v} {ΞΉ' : Type v'} {n : β}
{E : ΞΉ β Type wE} {Eβ : ΞΉ β Type wEβ} {E' : ΞΉ' β Type wE'} {Ei : fin n.succ β Type wEi}
{G : Type wG} {G' : Type wG'}
[decidable_eq ΞΉ] [fintype ΞΉ] [decidable_eq ΞΉ'] [fintype ΞΉ'] [nondiscrete_normed_field π]
[Ξ i, normed_group (E i)] [Ξ i, normed_space π (E i)]
[Ξ i, normed_group (Eβ i)] [Ξ i, normed_space π (Eβ i)]
[Ξ i, normed_group (E' i)] [Ξ i, normed_space π (E' i)]
[Ξ i, normed_group (Ei i)] [Ξ i, normed_space π (Ei i)]
[normed_group G] [normed_space π G] [normed_group G'] [normed_space π G']
/-!
### Continuity properties of multilinear maps
We relate continuity of multilinear maps to the inequality `β₯f mβ₯ β€ C * β i, β₯m iβ₯`, in
both directions. Along the way, we prove useful bounds on the difference `β₯f mβ - f mββ₯`.
-/
namespace multilinear_map
variable (f : multilinear_map π E G)
/-- If a multilinear map in finitely many variables on normed spaces satisfies the inequality
`β₯f mβ₯ β€ C * β i, β₯m iβ₯` on a shell `Ξ΅ i / β₯c iβ₯ < β₯m iβ₯ < Ξ΅ i` for some positive numbers `Ξ΅ i`
and elements `c i : π`, `1 < β₯c iβ₯`, then it satisfies this inequality for all `m`. -/
lemma bound_of_shell {Ξ΅ : ΞΉ β β} {C : β} (hΞ΅ : β i, 0 < Ξ΅ i) {c : ΞΉ β π} (hc : β i, 1 < β₯c iβ₯)
(hf : β m : Ξ i, E i, (β i, Ξ΅ i / β₯c iβ₯ β€ β₯m iβ₯) β (β i, β₯m iβ₯ < Ξ΅ i) β β₯f mβ₯ β€ C * β i, β₯m iβ₯)
(m : Ξ i, E i) : β₯f mβ₯ β€ C * β i, β₯m iβ₯ :=
begin
rcases em (β i, m i = 0) with β¨i, hiβ©|hm; [skip, push_neg at hm],
{ simp [f.map_coord_zero i hi, prod_eq_zero (mem_univ i), hi] },
choose Ξ΄ hΞ΄0 hΞ΄m_lt hle_Ξ΄m hΞ΄inv using Ξ» i, rescale_to_shell (hc i) (hΞ΅ i) (hm i),
have hΞ΄0 : 0 < β i, β₯Ξ΄ iβ₯, from prod_pos (Ξ» i _, norm_pos_iff.2 (hΞ΄0 i)),
simpa [map_smul_univ, norm_smul, prod_mul_distrib, mul_left_comm C, mul_le_mul_left hΞ΄0]
using hf (Ξ» i, Ξ΄ i β’ m i) hle_Ξ΄m hΞ΄m_lt,
end
/-- If a multilinear map in finitely many variables on normed spaces is continuous, then it
satisfies the inequality `β₯f mβ₯ β€ C * β i, β₯m iβ₯`, for some `C` which can be chosen to be
positive. -/
theorem exists_bound_of_continuous (hf : continuous f) :
β (C : β), 0 < C β§ (β m, β₯f mβ₯ β€ C * β i, β₯m iβ₯) :=
begin
by_cases hΞΉ : nonempty ΞΉ, swap,
{ refine β¨β₯f 0β₯ + 1, add_pos_of_nonneg_of_pos (norm_nonneg _) zero_lt_one, Ξ» m, _β©,
obtain rfl : m = 0, from funext (Ξ» i, (hΞΉ β¨iβ©).elim),
simp [univ_eq_empty.2 hΞΉ, zero_le_one] },
resetI,
obtain β¨Ξ΅ : β, Ξ΅0 : 0 < Ξ΅, hΞ΅ : β m : Ξ i, E i, β₯m - 0β₯ < Ξ΅ β β₯f m - f 0β₯ < 1β© :=
normed_group.tendsto_nhds_nhds.1 (hf.tendsto 0) 1 zero_lt_one,
simp only [sub_zero, f.map_zero] at hΞ΅,
rcases normed_field.exists_one_lt_norm π with β¨c, hcβ©,
have : 0 < (β₯cβ₯ / Ξ΅) ^ fintype.card ΞΉ, from pow_pos (div_pos (zero_lt_one.trans hc) Ξ΅0) _,
refine β¨_, this, _β©,
refine f.bound_of_shell (Ξ» _, Ξ΅0) (Ξ» _, hc) (Ξ» m hcm hm, _),
refine (hΞ΅ m ((pi_norm_lt_iff Ξ΅0).2 hm)).le.trans _,
rw [β div_le_iff' this, one_div, β inv_pow', inv_div, fintype.card, β prod_const],
exact prod_le_prod (Ξ» _ _, div_nonneg Ξ΅0.le (norm_nonneg _)) (Ξ» i _, hcm i)
end
/-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f mβ - f mβ`
using the multilinearity. Here, we give a precise but hard to use version. See
`norm_image_sub_le_of_bound` for a less precise but more usable version. The bound reads
`β₯f m - f m'β₯ β€
C * β₯m 1 - m' 1β₯ * max β₯m 2β₯ β₯m' 2β₯ * max β₯m 3β₯ β₯m' 3β₯ * ... * max β₯m nβ₯ β₯m' nβ₯ + ...`,
where the other terms in the sum are the same products where `1` is replaced by any `i`. -/
lemma norm_image_sub_le_of_bound' {C : β} (hC : 0 β€ C)
(H : β m, β₯f mβ₯ β€ C * β i, β₯m iβ₯) (mβ mβ : Ξ i, E i) :
β₯f mβ - f mββ₯ β€
C * β i, β j, if j = i then β₯mβ i - mβ iβ₯ else max β₯mβ jβ₯ β₯mβ jβ₯ :=
begin
have A : β(s : finset ΞΉ), β₯f mβ - f (s.piecewise mβ mβ)β₯
β€ C * β i in s, β j, if j = i then β₯mβ i - mβ iβ₯ else max β₯mβ jβ₯ β₯mβ jβ₯,
{ refine finset.induction (by simp) _,
assume i s his Hrec,
have I : β₯f (s.piecewise mβ mβ) - f ((insert i s).piecewise mβ mβ)β₯
β€ C * β j, if j = i then β₯mβ i - mβ iβ₯ else max β₯mβ jβ₯ β₯mβ jβ₯,
{ have A : ((insert i s).piecewise mβ mβ)
= function.update (s.piecewise mβ mβ) i (mβ i) := s.piecewise_insert _ _ _,
have B : s.piecewise mβ mβ = function.update (s.piecewise mβ mβ) i (mβ i),
{ ext j,
by_cases h : j = i,
{ rw h, simp [his] },
{ simp [h] } },
rw [B, A, β f.map_sub],
apply le_trans (H _) (mul_le_mul_of_nonneg_left _ hC),
refine prod_le_prod (Ξ»j hj, norm_nonneg _) (Ξ»j hj, _),
by_cases h : j = i,
{ rw h, simp },
{ by_cases h' : j β s;
simp [h', h, le_refl] } },
calc β₯f mβ - f ((insert i s).piecewise mβ mβ)β₯ β€
β₯f mβ - f (s.piecewise mβ mβ)β₯ + β₯f (s.piecewise mβ mβ) - f ((insert i s).piecewise mβ mβ)β₯ :
by { rw [β dist_eq_norm, β dist_eq_norm, β dist_eq_norm], exact dist_triangle _ _ _ }
... β€ (C * β i in s, β j, if j = i then β₯mβ i - mβ iβ₯ else max β₯mβ jβ₯ β₯mβ jβ₯)
+ C * β j, if j = i then β₯mβ i - mβ iβ₯ else max β₯mβ jβ₯ β₯mβ jβ₯ :
add_le_add Hrec I
... = C * β i in insert i s, β j, if j = i then β₯mβ i - mβ iβ₯ else max β₯mβ jβ₯ β₯mβ jβ₯ :
by simp [his, add_comm, left_distrib] },
convert A univ,
simp
end
/-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f mβ - f mβ`
using the multilinearity. Here, we give a usable but not very precise version. See
`norm_image_sub_le_of_bound'` for a more precise but less usable version. The bound is
`β₯f m - f m'β₯ β€ C * card ΞΉ * β₯m - m'β₯ * (max β₯mβ₯ β₯m'β₯) ^ (card ΞΉ - 1)`. -/
lemma norm_image_sub_le_of_bound {C : β} (hC : 0 β€ C)
(H : β m, β₯f mβ₯ β€ C * β i, β₯m iβ₯) (mβ mβ : Ξ i, E i) :
β₯f mβ - f mββ₯ β€ C * (fintype.card ΞΉ) * (max β₯mββ₯ β₯mββ₯) ^ (fintype.card ΞΉ - 1) * β₯mβ - mββ₯ :=
begin
have A : β (i : ΞΉ), β j, (if j = i then β₯mβ i - mβ iβ₯ else max β₯mβ jβ₯ β₯mβ jβ₯)
β€ β₯mβ - mββ₯ * (max β₯mββ₯ β₯mββ₯) ^ (fintype.card ΞΉ - 1),
{ assume i,
calc β j, (if j = i then β₯mβ i - mβ iβ₯ else max β₯mβ jβ₯ β₯mβ jβ₯)
β€ β j : ΞΉ, function.update (Ξ» j, max β₯mββ₯ β₯mββ₯) i (β₯mβ - mββ₯) j :
begin
apply prod_le_prod,
{ assume j hj, by_cases h : j = i; simp [h, norm_nonneg] },
{ assume j hj,
by_cases h : j = i,
{ rw h, simp, exact norm_le_pi_norm (mβ - mβ) i },
{ simp [h, max_le_max, norm_le_pi_norm] } }
end
... = β₯mβ - mββ₯ * (max β₯mββ₯ β₯mββ₯) ^ (fintype.card ΞΉ - 1) :
by { rw prod_update_of_mem (finset.mem_univ _), simp [card_univ_diff] } },
calc
β₯f mβ - f mββ₯
β€ C * β i, β j, if j = i then β₯mβ i - mβ iβ₯ else max β₯mβ jβ₯ β₯mβ jβ₯ :
f.norm_image_sub_le_of_bound' hC H mβ mβ
... β€ C * β i, β₯mβ - mββ₯ * (max β₯mββ₯ β₯mββ₯) ^ (fintype.card ΞΉ - 1) :
mul_le_mul_of_nonneg_left (sum_le_sum (Ξ»i hi, A i)) hC
... = C * (fintype.card ΞΉ) * (max β₯mββ₯ β₯mββ₯) ^ (fintype.card ΞΉ - 1) * β₯mβ - mββ₯ :
by { rw [sum_const, card_univ, nsmul_eq_mul], ring }
end
/-- If a multilinear map satisfies an inequality `β₯f mβ₯ β€ C * β i, β₯m iβ₯`, then it is
continuous. -/
theorem continuous_of_bound (C : β) (H : β m, β₯f mβ₯ β€ C * β i, β₯m iβ₯) :
continuous f :=
begin
let D := max C 1,
have D_pos : 0 β€ D := le_trans zero_le_one (le_max_right _ _),
replace H : β m, β₯f mβ₯ β€ D * β i, β₯m iβ₯,
{ assume m,
apply le_trans (H m) (mul_le_mul_of_nonneg_right (le_max_left _ _) _),
exact prod_nonneg (Ξ»(i : ΞΉ) hi, norm_nonneg (m i)) },
refine continuous_iff_continuous_at.2 (Ξ»m, _),
refine continuous_at_of_locally_lipschitz zero_lt_one
(D * (fintype.card ΞΉ) * (β₯mβ₯ + 1) ^ (fintype.card ΞΉ - 1)) (Ξ»m' h', _),
rw [dist_eq_norm, dist_eq_norm],
have : 0 β€ (max β₯m'β₯ β₯mβ₯), by simp,
have : (max β₯m'β₯ β₯mβ₯) β€ β₯mβ₯ + 1,
by simp [zero_le_one, norm_le_of_mem_closed_ball (le_of_lt h'), -add_comm],
calc
β₯f m' - f mβ₯
β€ D * (fintype.card ΞΉ) * (max β₯m'β₯ β₯mβ₯) ^ (fintype.card ΞΉ - 1) * β₯m' - mβ₯ :
f.norm_image_sub_le_of_bound D_pos H m' m
... β€ D * (fintype.card ΞΉ) * (β₯mβ₯ + 1) ^ (fintype.card ΞΉ - 1) * β₯m' - mβ₯ :
by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul_of_nonneg_left, mul_nonneg,
norm_nonneg, nat.cast_nonneg, pow_le_pow_of_le_left]
end
/-- Constructing a continuous multilinear map from a multilinear map satisfying a boundedness
condition. -/
def mk_continuous (C : β) (H : β m, β₯f mβ₯ β€ C * β i, β₯m iβ₯) :
continuous_multilinear_map π E G :=
{ cont := f.continuous_of_bound C H, ..f }
@[simp] lemma coe_mk_continuous (C : β) (H : β m, β₯f mβ₯ β€ C * β i, β₯m iβ₯) :
β(f.mk_continuous C H) = f :=
rfl
/-- Given a multilinear map in `n` variables, if one restricts it to `k` variables putting `z` on
the other coordinates, then the resulting restricted function satisfies an inequality
`β₯f.restr vβ₯ β€ C * β₯zβ₯^(n-k) * Ξ β₯v iβ₯` if the original function satisfies `β₯f vβ₯ β€ C * Ξ β₯v iβ₯`. -/
lemma restr_norm_le {k n : β} (f : (multilinear_map π (Ξ» i : fin n, G) G' : _))
(s : finset (fin n)) (hk : s.card = k) (z : G) {C : β}
(H : β m, β₯f mβ₯ β€ C * β i, β₯m iβ₯) (v : fin k β G) :
β₯f.restr s hk z vβ₯ β€ C * β₯zβ₯ ^ (n - k) * β i, β₯v iβ₯ :=
begin
rw [mul_right_comm, mul_assoc],
convert H _ using 2,
simp only [apply_dite norm, fintype.prod_dite, prod_const (β₯zβ₯), finset.card_univ,
fintype.card_of_subtype sαΆ (Ξ» x, mem_compl), card_compl, fintype.card_fin, hk, mk_coe,
β (s.order_iso_of_fin hk).symm.bijective.prod_comp (Ξ» x, β₯v xβ₯)],
refl
end
end multilinear_map
/-!
### Continuous multilinear maps
We define the norm `β₯fβ₯` of a continuous multilinear map `f` in finitely many variables as the
smallest number such that `β₯f mβ₯ β€ β₯fβ₯ * β i, β₯m iβ₯` for all `m`. We show that this
defines a normed space structure on `continuous_multilinear_map π E G`.
-/
namespace continuous_multilinear_map
variables (c : π) (f g : continuous_multilinear_map π E G) (m : Ξ i, E i)
theorem bound : β (C : β), 0 < C β§ (β m, β₯f mβ₯ β€ C * β i, β₯m iβ₯) :=
f.to_multilinear_map.exists_bound_of_continuous f.2
open real
/-- The operator norm of a continuous multilinear map is the inf of all its bounds. -/
def op_norm := Inf {c | 0 β€ (c : β) β§ β m, β₯f mβ₯ β€ c * β i, β₯m iβ₯}
instance has_op_norm : has_norm (continuous_multilinear_map π E G) := β¨op_normβ©
lemma norm_def : β₯fβ₯ = Inf {c | 0 β€ (c : β) β§ β m, β₯f mβ₯ β€ c * β i, β₯m iβ₯} := rfl
-- So that invocations of `real.Inf_le` make sense: we show that the set of
-- bounds is nonempty and bounded below.
lemma bounds_nonempty {f : continuous_multilinear_map π E G} :
β c, c β {c | 0 β€ c β§ β m, β₯f mβ₯ β€ c * β i, β₯m iβ₯} :=
let β¨M, hMp, hMbβ© := f.bound in β¨M, le_of_lt hMp, hMbβ©
lemma bounds_bdd_below {f : continuous_multilinear_map π E G} :
bdd_below {c | 0 β€ c β§ β m, β₯f mβ₯ β€ c * β i, β₯m iβ₯} :=
β¨0, Ξ» _ β¨hn, _β©, hnβ©
lemma op_norm_nonneg : 0 β€ β₯fβ₯ :=
lb_le_Inf _ bounds_nonempty (Ξ» _ β¨hx, _β©, hx)
/-- The fundamental property of the operator norm of a continuous multilinear map:
`β₯f mβ₯` is bounded by `β₯fβ₯` times the product of the `β₯m iβ₯`. -/
theorem le_op_norm : β₯f mβ₯ β€ β₯fβ₯ * β i, β₯m iβ₯ :=
begin
have A : 0 β€ β i, β₯m iβ₯ := prod_nonneg (Ξ»j hj, norm_nonneg _),
cases A.eq_or_lt with h hlt,
{ rcases prod_eq_zero_iff.1 h.symm with β¨i, _, hiβ©,
rw norm_eq_zero at hi,
have : f m = 0 := f.map_coord_zero i hi,
rw [this, norm_zero],
exact mul_nonneg (op_norm_nonneg f) A },
{ rw [β div_le_iff hlt],
apply (le_Inf _ bounds_nonempty bounds_bdd_below).2,
rintro c β¨_, hcβ©, rw [div_le_iff hlt], apply hc }
end
theorem le_of_op_norm_le {C : β} (h : β₯fβ₯ β€ C) : β₯f mβ₯ β€ C * β i, β₯m iβ₯ :=
(f.le_op_norm m).trans $ mul_le_mul_of_nonneg_right h (prod_nonneg $ Ξ» i _, norm_nonneg (m i))
lemma ratio_le_op_norm : β₯f mβ₯ / β i, β₯m iβ₯ β€ β₯fβ₯ :=
div_le_of_nonneg_of_le_mul (prod_nonneg $ Ξ» i _, norm_nonneg _) (op_norm_nonneg _) (f.le_op_norm m)
/-- The image of the unit ball under a continuous multilinear map is bounded. -/
lemma unit_le_op_norm (h : β₯mβ₯ β€ 1) : β₯f mβ₯ β€ β₯fβ₯ :=
calc
β₯f mβ₯ β€ β₯fβ₯ * β i, β₯m iβ₯ : f.le_op_norm m
... β€ β₯fβ₯ * β i : ΞΉ, 1 :
mul_le_mul_of_nonneg_left (prod_le_prod (Ξ»i hi, norm_nonneg _)
(Ξ»i hi, le_trans (norm_le_pi_norm _ _) h)) (op_norm_nonneg f)
... = β₯fβ₯ : by simp
/-- If one controls the norm of every `f x`, then one controls the norm of `f`. -/
lemma op_norm_le_bound {M : β} (hMp: 0 β€ M) (hM : β m, β₯f mβ₯ β€ M * β i, β₯m iβ₯) :
β₯fβ₯ β€ M :=
Inf_le _ bounds_bdd_below β¨hMp, hMβ©
/-- The operator norm satisfies the triangle inequality. -/
theorem op_norm_add_le : β₯f + gβ₯ β€ β₯fβ₯ + β₯gβ₯ :=
Inf_le _ bounds_bdd_below
β¨add_nonneg (op_norm_nonneg _) (op_norm_nonneg _), Ξ» x, by { rw add_mul,
exact norm_add_le_of_le (le_op_norm _ _) (le_op_norm _ _) }β©
/-- A continuous linear map is zero iff its norm vanishes. -/
theorem op_norm_zero_iff : β₯fβ₯ = 0 β f = 0 :=
begin
split,
{ assume h,
ext m,
simpa [h] using f.le_op_norm m },
{ rintro rfl,
apply le_antisymm (op_norm_le_bound 0 le_rfl (Ξ»m, _)) (op_norm_nonneg _),
simp }
end
variables {π' : Type*} [nondiscrete_normed_field π'] [normed_algebra π' π]
[normed_space π' G] [is_scalar_tower π' π G]
lemma op_norm_smul_le (c : π') : β₯c β’ fβ₯ β€ β₯cβ₯ * β₯fβ₯ :=
(c β’ f).op_norm_le_bound
(mul_nonneg (norm_nonneg _) (op_norm_nonneg _))
begin
intro m,
erw [norm_smul, mul_assoc],
exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _)
end
lemma op_norm_neg : β₯-fβ₯ = β₯fβ₯ := by { rw norm_def, apply congr_arg, ext, simp }
/-- Continuous multilinear maps themselves form a normed space with respect to
the operator norm. -/
instance to_normed_group : normed_group (continuous_multilinear_map π E G) :=
normed_group.of_core _ β¨op_norm_zero_iff, op_norm_add_le, op_norm_negβ©
instance to_normed_space : normed_space π' (continuous_multilinear_map π E G) :=
β¨Ξ» c f, f.op_norm_smul_le cβ©
theorem le_op_norm_mul_prod_of_le {b : ΞΉ β β} (hm : β i, β₯m iβ₯ β€ b i) : β₯f mβ₯ β€ β₯fβ₯ * β i, b i :=
(f.le_op_norm m).trans $ mul_le_mul_of_nonneg_left
(prod_le_prod (Ξ» _ _, norm_nonneg _) (Ξ» i _, hm i)) (norm_nonneg f)
theorem le_op_norm_mul_pow_card_of_le {b : β} (hm : β i, β₯m iβ₯ β€ b) :
β₯f mβ₯ β€ β₯fβ₯ * b ^ fintype.card ΞΉ :=
by simpa only [prod_const] using f.le_op_norm_mul_prod_of_le m hm
theorem le_op_norm_mul_pow_of_le {Ei : fin n β Type*} [Ξ i, normed_group (Ei i)]
[Ξ i, normed_space π (Ei i)] (f : continuous_multilinear_map π Ei G) (m : Ξ i, Ei i)
{b : β} (hm : β₯mβ₯ β€ b) :
β₯f mβ₯ β€ β₯fβ₯ * b ^ n :=
by simpa only [fintype.card_fin]
using f.le_op_norm_mul_pow_card_of_le m (Ξ» i, (norm_le_pi_norm m i).trans hm)
/-- The fundamental property of the operator norm of a continuous multilinear map:
`β₯f mβ₯` is bounded by `β₯fβ₯` times the product of the `β₯m iβ₯`, `nnnorm` version. -/
theorem le_op_nnnorm : nnnorm (f m) β€ nnnorm f * β i, nnnorm (m i) :=
nnreal.coe_le_coe.1 $ by { push_cast, exact f.le_op_norm m }
theorem le_of_op_nnnorm_le {C : ββ₯0} (h : nnnorm f β€ C) : nnnorm (f m) β€ C * β i, nnnorm (m i) :=
(f.le_op_nnnorm m).trans $ mul_le_mul' h le_rfl
lemma op_norm_prod (f : continuous_multilinear_map π E G) (g : continuous_multilinear_map π E G') :
β₯f.prod gβ₯ = max (β₯fβ₯) (β₯gβ₯) :=
le_antisymm
(op_norm_le_bound _ (norm_nonneg (f, g)) (Ξ» m,
have H : 0 β€ β i, β₯m iβ₯, from prod_nonneg $ Ξ» _ _, norm_nonneg _,
by simpa only [prod_apply, prod.norm_def, max_mul_of_nonneg, H]
using max_le_max (f.le_op_norm m) (g.le_op_norm m))) $
max_le
(f.op_norm_le_bound (norm_nonneg _) $ Ξ» m, (le_max_left _ _).trans ((f.prod g).le_op_norm _))
(g.op_norm_le_bound (norm_nonneg _) $ Ξ» m, (le_max_right _ _).trans ((f.prod g).le_op_norm _))
lemma norm_pi {ΞΉ' : Type v'} [fintype ΞΉ'] {E' : ΞΉ' β Type wE'} [Ξ i', normed_group (E' i')]
[Ξ i', normed_space π (E' i')] (f : Ξ i', continuous_multilinear_map π E (E' i')) :
β₯pi fβ₯ = β₯fβ₯ :=
begin
apply le_antisymm,
{ refine (op_norm_le_bound _ (norm_nonneg f) (Ξ» m, _)),
dsimp,
rw pi_norm_le_iff,
exacts [Ξ» i, (f i).le_of_op_norm_le m (norm_le_pi_norm f i),
mul_nonneg (norm_nonneg f) (prod_nonneg $ Ξ» _ _, norm_nonneg _)] },
{ refine (pi_norm_le_iff (norm_nonneg _)).2 (Ξ» i, _),
refine (op_norm_le_bound _ (norm_nonneg _) (Ξ» m, _)),
refine le_trans _ ((pi f).le_op_norm m),
convert norm_le_pi_norm (Ξ» j, f j m) i }
end
section
variables (π E E' G G')
/-- `continuous_multilinear_map.prod` as a `linear_isometry_equiv`. -/
def prodL :
(continuous_multilinear_map π E G) Γ (continuous_multilinear_map π E G') ββα΅’[π]
continuous_multilinear_map π E (G Γ G') :=
{ to_fun := Ξ» f, f.1.prod f.2,
inv_fun := Ξ» f, ((continuous_linear_map.fst π G G').comp_continuous_multilinear_map f,
(continuous_linear_map.snd π G G').comp_continuous_multilinear_map f),
map_add' := Ξ» f g, rfl,
map_smul' := Ξ» c f, rfl,
left_inv := Ξ» f, by ext; refl,
right_inv := Ξ» f, by ext; refl,
norm_map' := Ξ» f, op_norm_prod f.1 f.2 }
/-- `continuous_multilinear_map.pi` as a `linear_isometry_equiv`. -/
def piβα΅’ {ΞΉ' : Type v'} [fintype ΞΉ'] {E' : ΞΉ' β Type wE'} [Ξ i', normed_group (E' i')]
[Ξ i', normed_space π (E' i')] :
@linear_isometry_equiv π (Ξ i', continuous_multilinear_map π E (E' i'))
(continuous_multilinear_map π E (Ξ i, E' i)) _ _ _
(@pi.module ΞΉ' _ π _ _ (Ξ» i', infer_instance)) _ :=
{ to_linear_equiv :=
-- note: `pi_linear_equiv` does not unify correctly here, presumably due to issues with dependent
-- typeclass arguments.
{ map_add' := Ξ» f g, rfl,
map_smul' := Ξ» c f, rfl,
.. pi_equiv, },
norm_map' := norm_pi }
end
section restrict_scalars
variables [Ξ i, normed_space π' (E i)] [β i, is_scalar_tower π' π (E i)]
@[simp] lemma norm_restrict_scalars : β₯f.restrict_scalars π'β₯ = β₯fβ₯ :=
by simp only [norm_def, coe_restrict_scalars]
variable (π')
/-- `continuous_multilinear_map.restrict_scalars` as a `continuous_multilinear_map`. -/
def restrict_scalars_linear :
continuous_multilinear_map π E G βL[π'] continuous_multilinear_map π' E G :=
linear_map.mk_continuous
{ to_fun := restrict_scalars π',
map_add' := Ξ» mβ mβ, rfl,
map_smul' := Ξ» c m, rfl } 1 $ Ξ» f, by simp
variable {π'}
lemma continuous_restrict_scalars :
continuous (restrict_scalars π' : continuous_multilinear_map π E G β
continuous_multilinear_map π' E G) :=
(restrict_scalars_linear π').continuous
end restrict_scalars
/-- The difference `f mβ - f mβ` is controlled in terms of `β₯fβ₯` and `β₯mβ - mββ₯`, precise version.
For a less precise but more usable version, see `norm_image_sub_le`. The bound reads
`β₯f m - f m'β₯ β€
β₯fβ₯ * β₯m 1 - m' 1β₯ * max β₯m 2β₯ β₯m' 2β₯ * max β₯m 3β₯ β₯m' 3β₯ * ... * max β₯m nβ₯ β₯m' nβ₯ + ...`,
where the other terms in the sum are the same products where `1` is replaced by any `i`.-/
lemma norm_image_sub_le' (mβ mβ : Ξ i, E i) :
β₯f mβ - f mββ₯ β€
β₯fβ₯ * β i, β j, if j = i then β₯mβ i - mβ iβ₯ else max β₯mβ jβ₯ β₯mβ jβ₯ :=
f.to_multilinear_map.norm_image_sub_le_of_bound' (norm_nonneg _) f.le_op_norm _ _
/-- The difference `f mβ - f mβ` is controlled in terms of `β₯fβ₯` and `β₯mβ - mββ₯`, less precise
version. For a more precise but less usable version, see `norm_image_sub_le'`.
The bound is `β₯f m - f m'β₯ β€ β₯fβ₯ * card ΞΉ * β₯m - m'β₯ * (max β₯mβ₯ β₯m'β₯) ^ (card ΞΉ - 1)`.-/
lemma norm_image_sub_le (mβ mβ : Ξ i, E i) :
β₯f mβ - f mββ₯ β€ β₯fβ₯ * (fintype.card ΞΉ) * (max β₯mββ₯ β₯mββ₯) ^ (fintype.card ΞΉ - 1) * β₯mβ - mββ₯ :=
f.to_multilinear_map.norm_image_sub_le_of_bound (norm_nonneg _) f.le_op_norm _ _
/-- Applying a multilinear map to a vector is continuous in both coordinates. -/
lemma continuous_eval :
continuous (Ξ» p : continuous_multilinear_map π E G Γ Ξ i, E i, p.1 p.2) :=
begin
apply continuous_iff_continuous_at.2 (Ξ»p, _),
apply continuous_at_of_locally_lipschitz zero_lt_one
((β₯pβ₯ + 1) * (fintype.card ΞΉ) * (β₯pβ₯ + 1) ^ (fintype.card ΞΉ - 1) + β i, β₯p.2 iβ₯)
(Ξ»q hq, _),
have : 0 β€ (max β₯q.2β₯ β₯p.2β₯), by simp,
have : 0 β€ β₯pβ₯ + 1, by simp [le_trans zero_le_one],
have A : β₯qβ₯ β€ β₯pβ₯ + 1 := norm_le_of_mem_closed_ball (le_of_lt hq),
have : (max β₯q.2β₯ β₯p.2β₯) β€ β₯pβ₯ + 1 :=
le_trans (max_le_max (norm_snd_le q) (norm_snd_le p)) (by simp [A, -add_comm, zero_le_one]),
have : β (i : ΞΉ), i β univ β 0 β€ β₯p.2 iβ₯ := Ξ» i hi, norm_nonneg _,
calc dist (q.1 q.2) (p.1 p.2)
β€ dist (q.1 q.2) (q.1 p.2) + dist (q.1 p.2) (p.1 p.2) : dist_triangle _ _ _
... = β₯q.1 q.2 - q.1 p.2β₯ + β₯q.1 p.2 - p.1 p.2β₯ : by rw [dist_eq_norm, dist_eq_norm]
... β€ β₯q.1β₯ * (fintype.card ΞΉ) * (max β₯q.2β₯ β₯p.2β₯) ^ (fintype.card ΞΉ - 1) * β₯q.2 - p.2β₯
+ β₯q.1 - p.1β₯ * β i, β₯p.2 iβ₯ :
add_le_add (norm_image_sub_le _ _ _) ((q.1 - p.1).le_op_norm p.2)
... β€ (β₯pβ₯ + 1) * (fintype.card ΞΉ) * (β₯pβ₯ + 1) ^ (fintype.card ΞΉ - 1) * β₯q - pβ₯
+ β₯q - pβ₯ * β i, β₯p.2 iβ₯ :
by apply_rules [add_le_add, mul_le_mul, le_refl, le_trans (norm_fst_le q) A, nat.cast_nonneg,
mul_nonneg, pow_le_pow_of_le_left, pow_nonneg, norm_snd_le (q - p), norm_nonneg,
norm_fst_le (q - p), prod_nonneg]
... = ((β₯pβ₯ + 1) * (fintype.card ΞΉ) * (β₯pβ₯ + 1) ^ (fintype.card ΞΉ - 1)
+ (β i, β₯p.2 iβ₯)) * dist q p : by { rw dist_eq_norm, ring }
end
lemma continuous_eval_left (m : Ξ i, E i) :
continuous (Ξ» p : continuous_multilinear_map π E G, p m) :=
continuous_eval.comp (continuous_id.prod_mk continuous_const)
lemma has_sum_eval
{Ξ± : Type*} {p : Ξ± β continuous_multilinear_map π E G} {q : continuous_multilinear_map π E G}
(h : has_sum p q) (m : Ξ i, E i) : has_sum (Ξ» a, p a m) (q m) :=
begin
dsimp [has_sum] at h β’,
convert ((continuous_eval_left m).tendsto _).comp h,
ext s,
simp
end
lemma tsum_eval {Ξ± : Type*} {p : Ξ± β continuous_multilinear_map π E G} (hp : summable p)
(m : Ξ i, E i) : (β' a, p a) m = β' a, p a m :=
(has_sum_eval hp.has_sum m).tsum_eq.symm
open_locale topological_space
open filter
/-- If the target space is complete, the space of continuous multilinear maps with its norm is also
complete. The proof is essentially the same as for the space of continuous linear maps (modulo the
addition of `finset.prod` where needed. The duplication could be avoided by deducing the linear
case from the multilinear case via a currying isomorphism. However, this would mess up imports,
and it is more satisfactory to have the simplest case as a standalone proof. -/
instance [complete_space G] : complete_space (continuous_multilinear_map π E G) :=
begin
have nonneg : β (v : Ξ i, E i), 0 β€ β i, β₯v iβ₯ :=
Ξ» v, finset.prod_nonneg (Ξ» i hi, norm_nonneg _),
-- We show that every Cauchy sequence converges.
refine metric.complete_of_cauchy_seq_tendsto (Ξ» f hf, _),
-- We now expand out the definition of a Cauchy sequence,
rcases cauchy_seq_iff_le_tendsto_0.1 hf with β¨b, b0, b_bound, b_limβ©,
-- and establish that the evaluation at any point `v : Ξ i, E i` is Cauchy.
have cau : β v, cauchy_seq (Ξ» n, f n v),
{ assume v,
apply cauchy_seq_iff_le_tendsto_0.2 β¨Ξ» n, b n * β i, β₯v iβ₯, Ξ» n, _, _, _β©,
{ exact mul_nonneg (b0 n) (nonneg v) },
{ assume n m N hn hm,
rw dist_eq_norm,
apply le_trans ((f n - f m).le_op_norm v) _,
exact mul_le_mul_of_nonneg_right (b_bound n m N hn hm) (nonneg v) },
{ simpa using b_lim.mul tendsto_const_nhds } },
-- We assemble the limits points of those Cauchy sequences
-- (which exist as `G` is complete)
-- into a function which we call `F`.
choose F hF using Ξ»v, cauchy_seq_tendsto_of_complete (cau v),
-- Next, we show that this `F` is multilinear,
let Fmult : multilinear_map π E G :=
{ to_fun := F,
map_add' := Ξ» v i x y, begin
have A := hF (function.update v i (x + y)),
have B := (hF (function.update v i x)).add (hF (function.update v i y)),
simp at A B,
exact tendsto_nhds_unique A B
end,
map_smul' := Ξ» v i c x, begin
have A := hF (function.update v i (c β’ x)),
have B := filter.tendsto.smul (@tendsto_const_nhds _ β _ c _) (hF (function.update v i x)),
simp at A B,
exact tendsto_nhds_unique A B
end },
-- and that `F` has norm at most `(b 0 + β₯f 0β₯)`.
have Fnorm : β v, β₯F vβ₯ β€ (b 0 + β₯f 0β₯) * β i, β₯v iβ₯,
{ assume v,
have A : β n, β₯f n vβ₯ β€ (b 0 + β₯f 0β₯) * β i, β₯v iβ₯,
{ assume n,
apply le_trans ((f n).le_op_norm _) _,
apply mul_le_mul_of_nonneg_right _ (nonneg v),
calc β₯f nβ₯ = β₯(f n - f 0) + f 0β₯ : by { congr' 1, abel }
... β€ β₯f n - f 0β₯ + β₯f 0β₯ : norm_add_le _ _
... β€ b 0 + β₯f 0β₯ : begin
apply add_le_add_right,
simpa [dist_eq_norm] using b_bound n 0 0 (zero_le _) (zero_le _)
end },
exact le_of_tendsto (hF v).norm (eventually_of_forall A) },
-- Thus `F` is continuous, and we propose that as the limit point of our original Cauchy sequence.
let Fcont := Fmult.mk_continuous _ Fnorm,
use Fcont,
-- Our last task is to establish convergence to `F` in norm.
have : β n, β₯f n - Fcontβ₯ β€ b n,
{ assume n,
apply op_norm_le_bound _ (b0 n) (Ξ» v, _),
have A : βαΆ m in at_top, β₯(f n - f m) vβ₯ β€ b n * β i, β₯v iβ₯,
{ refine eventually_at_top.2 β¨n, Ξ» m hm, _β©,
apply le_trans ((f n - f m).le_op_norm _) _,
exact mul_le_mul_of_nonneg_right (b_bound n m n (le_refl _) hm) (nonneg v) },
have B : tendsto (Ξ» m, β₯(f n - f m) vβ₯) at_top (π (β₯(f n - Fcont) vβ₯)) :=
tendsto.norm (tendsto_const_nhds.sub (hF v)),
exact le_of_tendsto B A },
erw tendsto_iff_norm_tendsto_zero,
exact squeeze_zero (Ξ» n, norm_nonneg _) this b_lim,
end
end continuous_multilinear_map
/-- If a continuous multilinear map is constructed from a multilinear map via the constructor
`mk_continuous`, then its norm is bounded by the bound given to the constructor if it is
nonnegative. -/
lemma multilinear_map.mk_continuous_norm_le (f : multilinear_map π E G) {C : β} (hC : 0 β€ C)
(H : β m, β₯f mβ₯ β€ C * β i, β₯m iβ₯) : β₯f.mk_continuous C Hβ₯ β€ C :=
continuous_multilinear_map.op_norm_le_bound _ hC (Ξ»m, H m)
/-- If a continuous multilinear map is constructed from a multilinear map via the constructor
`mk_continuous`, then its norm is bounded by the bound given to the constructor if it is
nonnegative. -/
lemma multilinear_map.mk_continuous_norm_le' (f : multilinear_map π E G) {C : β}
(H : β m, β₯f mβ₯ β€ C * β i, β₯m iβ₯) : β₯f.mk_continuous C Hβ₯ β€ max C 0 :=
continuous_multilinear_map.op_norm_le_bound _ (le_max_right _ _) $
Ξ» m, (H m).trans $ mul_le_mul_of_nonneg_right (le_max_left _ _)
(prod_nonneg $ Ξ» _ _, norm_nonneg _)
namespace continuous_multilinear_map
/-- Given a continuous multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset
`s` of `k` of these variables, one gets a new continuous multilinear map on `fin k` by varying
these variables, and fixing the other ones equal to a given value `z`. It is denoted by
`f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit
identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/
def restr {k n : β} (f : (G [Γn]βL[π] G' : _))
(s : finset (fin n)) (hk : s.card = k) (z : G) : G [Γk]βL[π] G' :=
(f.to_multilinear_map.restr s hk z).mk_continuous
(β₯fβ₯ * β₯zβ₯^(n-k)) $ Ξ» v, multilinear_map.restr_norm_le _ _ _ _ f.le_op_norm _
lemma norm_restr {k n : β} (f : G [Γn]βL[π] G') (s : finset (fin n)) (hk : s.card = k) (z : G) :
β₯f.restr s hk zβ₯ β€ β₯fβ₯ * β₯zβ₯ ^ (n - k) :=
begin
apply multilinear_map.mk_continuous_norm_le,
exact mul_nonneg (norm_nonneg _) (pow_nonneg (norm_nonneg _) _)
end
section
variables (π ΞΉ) (A : Type*) [normed_comm_ring A] [normed_algebra π A]
/-- The continuous multilinear map on `A^ΞΉ`, where `A` is a normed commutative algebra
over `π`, associating to `m` the product of all the `m i`.
See also `continuous_multilinear_map.mk_pi_algebra_fin`. -/
protected def mk_pi_algebra : continuous_multilinear_map π (Ξ» i : ΞΉ, A) A :=
@multilinear_map.mk_continuous π ΞΉ (Ξ» i : ΞΉ, A) A _ _ _ _ _ _ _
(multilinear_map.mk_pi_algebra π ΞΉ A) (if nonempty ΞΉ then 1 else β₯(1 : A)β₯) $
begin
intro m,
by_cases hΞΉ : nonempty ΞΉ,
{ resetI, simp [hΞΉ, norm_prod_le' univ univ_nonempty] },
{ simp [eq_empty_of_not_nonempty hΞΉ univ, hΞΉ] }
end
variables {A π ΞΉ}
@[simp] lemma mk_pi_algebra_apply (m : ΞΉ β A) :
continuous_multilinear_map.mk_pi_algebra π ΞΉ A m = β i, m i :=
rfl
lemma norm_mk_pi_algebra_le [nonempty ΞΉ] :
β₯continuous_multilinear_map.mk_pi_algebra π ΞΉ Aβ₯ β€ 1 :=
calc β₯continuous_multilinear_map.mk_pi_algebra π ΞΉ Aβ₯ β€ if nonempty ΞΉ then 1 else β₯(1 : A)β₯ :
multilinear_map.mk_continuous_norm_le _ (by split_ifs; simp [zero_le_one]) _
... = _ : if_pos βΉ_βΊ
lemma norm_mk_pi_algebra_of_empty (h : Β¬nonempty ΞΉ) :
β₯continuous_multilinear_map.mk_pi_algebra π ΞΉ Aβ₯ = β₯(1 : A)β₯ :=
begin
apply le_antisymm,
calc β₯continuous_multilinear_map.mk_pi_algebra π ΞΉ Aβ₯ β€ if nonempty ΞΉ then 1 else β₯(1 : A)β₯ :
multilinear_map.mk_continuous_norm_le _ (by split_ifs; simp [zero_le_one]) _
... = β₯(1 : A)β₯ : if_neg βΉ_βΊ,
convert ratio_le_op_norm _ (Ξ» _, 1); [skip, apply_instance],
simp [eq_empty_of_not_nonempty h univ]
end
@[simp] lemma norm_mk_pi_algebra [norm_one_class A] :
β₯continuous_multilinear_map.mk_pi_algebra π ΞΉ Aβ₯ = 1 :=
begin
by_cases hΞΉ : nonempty ΞΉ,
{ resetI,
refine le_antisymm norm_mk_pi_algebra_le _,
convert ratio_le_op_norm _ (Ξ» _, 1); [skip, apply_instance],
simp },
{ simp [norm_mk_pi_algebra_of_empty hΞΉ] }
end
end
section
variables (π n) (A : Type*) [normed_ring A] [normed_algebra π A]
/-- The continuous multilinear map on `A^n`, where `A` is a normed algebra over `π`, associating to
`m` the product of all the `m i`.
See also: `multilinear_map.mk_pi_algebra`. -/
protected def mk_pi_algebra_fin : continuous_multilinear_map π (Ξ» i : fin n, A) A :=
@multilinear_map.mk_continuous π (fin n) (Ξ» i : fin n, A) A _ _ _ _ _ _ _
(multilinear_map.mk_pi_algebra_fin π n A) (nat.cases_on n β₯(1 : A)β₯ (Ξ» _, 1)) $
begin
intro m,
cases n,
{ simp },
{ have : @list.of_fn A n.succ m β [] := by simp,
simpa [β fin.prod_of_fn] using list.norm_prod_le' this }
end
variables {A π n}
@[simp] lemma mk_pi_algebra_fin_apply (m : fin n β A) :
continuous_multilinear_map.mk_pi_algebra_fin π n A m = (list.of_fn m).prod :=
rfl
lemma norm_mk_pi_algebra_fin_succ_le :
β₯continuous_multilinear_map.mk_pi_algebra_fin π n.succ Aβ₯ β€ 1 :=
multilinear_map.mk_continuous_norm_le _ zero_le_one _
lemma norm_mk_pi_algebra_fin_le_of_pos (hn : 0 < n) :
β₯continuous_multilinear_map.mk_pi_algebra_fin π n Aβ₯ β€ 1 :=
by cases n; [exact hn.false.elim, exact norm_mk_pi_algebra_fin_succ_le]
lemma norm_mk_pi_algebra_fin_zero :
β₯continuous_multilinear_map.mk_pi_algebra_fin π 0 Aβ₯ = β₯(1 : A)β₯ :=
begin
refine le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _) _,
convert ratio_le_op_norm _ (Ξ» _, 1); [simp, apply_instance]
end
@[simp] lemma norm_mk_pi_algebra_fin [norm_one_class A] :
β₯continuous_multilinear_map.mk_pi_algebra_fin π n Aβ₯ = 1 :=
begin
cases n,
{ simp [norm_mk_pi_algebra_fin_zero] },
{ refine le_antisymm norm_mk_pi_algebra_fin_succ_le _,
convert ratio_le_op_norm _ (Ξ» _, 1); [skip, apply_instance],
simp }
end
end
variables (π ΞΉ)
/-- The canonical continuous multilinear map on `π^ΞΉ`, associating to `m` the product of all the
`m i` (multiplied by a fixed reference element `z` in the target module) -/
protected def mk_pi_field (z : G) : continuous_multilinear_map π (Ξ»(i : ΞΉ), π) G :=
@multilinear_map.mk_continuous π ΞΉ (Ξ»(i : ΞΉ), π) G _ _ _ _ _ _ _
(multilinear_map.mk_pi_ring π ΞΉ z) (β₯zβ₯)
(Ξ» m, by simp only [multilinear_map.mk_pi_ring_apply, norm_smul, normed_field.norm_prod,
mul_comm])
variables {π ΞΉ}
@[simp] lemma mk_pi_field_apply (z : G) (m : ΞΉ β π) :
(continuous_multilinear_map.mk_pi_field π ΞΉ z : (ΞΉ β π) β G) m = (β i, m i) β’ z := rfl
lemma mk_pi_field_apply_one_eq_self (f : continuous_multilinear_map π (Ξ»(i : ΞΉ), π) G) :
continuous_multilinear_map.mk_pi_field π ΞΉ (f (Ξ»i, 1)) = f :=
to_multilinear_map_inj f.to_multilinear_map.mk_pi_ring_apply_one_eq_self
variables (π ΞΉ G)
/-- Continuous multilinear maps on `π^n` with values in `G` are in bijection with `G`, as such a
continuous multilinear map is completely determined by its value on the constant vector made of
ones. We register this bijection as a linear equivalence in
`continuous_multilinear_map.pi_field_equiv_aux`. The continuous linear equivalence is
`continuous_multilinear_map.pi_field_equiv`. -/
protected def pi_field_equiv_aux : G ββ[π] (continuous_multilinear_map π (Ξ»(i : ΞΉ), π) G) :=
{ to_fun := Ξ» z, continuous_multilinear_map.mk_pi_field π ΞΉ z,
inv_fun := Ξ» f, f (Ξ»i, 1),
map_add' := Ξ» z z', by { ext m, simp [smul_add] },
map_smul' := Ξ» c z, by { ext m, simp [smul_smul, mul_comm] },
left_inv := Ξ» z, by simp,
right_inv := Ξ» f, f.mk_pi_field_apply_one_eq_self }
/-- Continuous multilinear maps on `π^n` with values in `G` are in bijection with `G`, as such a
continuous multilinear map is completely determined by its value on the constant vector made of
ones. We register this bijection as a continuous linear equivalence in
`continuous_multilinear_map.pi_field_equiv`. -/
protected def pi_field_equiv : G βL[π] (continuous_multilinear_map π (Ξ»(i : ΞΉ), π) G) :=
{ continuous_to_fun := begin
refine (continuous_multilinear_map.pi_field_equiv_aux π ΞΉ G).to_linear_map.continuous_of_bound
(1 : β) (Ξ»z, _),
rw one_mul,
change β₯continuous_multilinear_map.mk_pi_field π ΞΉ zβ₯ β€ β₯zβ₯,
exact multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _
end,
continuous_inv_fun := begin
refine
(continuous_multilinear_map.pi_field_equiv_aux π ΞΉ G).symm.to_linear_map.continuous_of_bound
(1 : β) (Ξ»f, _),
rw one_mul,
change β₯f (Ξ»i, 1)β₯ β€ β₯fβ₯,
apply @continuous_multilinear_map.unit_le_op_norm π ΞΉ (Ξ» (i : ΞΉ), π) G _ _ _ _ _ _ _ f,
simp [pi_norm_le_iff zero_le_one, le_refl]
end,
.. continuous_multilinear_map.pi_field_equiv_aux π ΞΉ G }
end continuous_multilinear_map
namespace continuous_linear_map
lemma norm_comp_continuous_multilinear_map_le (g : G βL[π] G')
(f : continuous_multilinear_map π E G) :
β₯g.comp_continuous_multilinear_map fβ₯ β€ β₯gβ₯ * β₯fβ₯ :=
continuous_multilinear_map.op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) $ Ξ» m,
calc β₯g (f m)β₯ β€ β₯gβ₯ * (β₯fβ₯ * β i, β₯m iβ₯) : g.le_op_norm_of_le $ f.le_op_norm _
... = _ : (mul_assoc _ _ _).symm
/-- `continuous_linear_map.comp_continuous_multilinear_map` as a bundled continuous bilinear map. -/
def comp_continuous_multilinear_mapL :
(G βL[π] G') βL[π] continuous_multilinear_map π E G βL[π] continuous_multilinear_map π E G' :=
linear_map.mk_continuousβ
(linear_map.mkβ π comp_continuous_multilinear_map (Ξ» fβ fβ g, rfl) (Ξ» c f g, rfl)
(Ξ» f gβ gβ, by { ext1, apply f.map_add }) (Ξ» c f g, by { ext1, simp }))
1 $ Ξ» f g, by { rw one_mul, exact f.norm_comp_continuous_multilinear_map_le g }
/-- Flip arguments in `f : G βL[π] continuous_multilinear_map π E G'` to get
`continuous_multilinear_map π E (G βL[π] G')` -/
def flip_multilinear (f : G βL[π] continuous_multilinear_map π E G') :
continuous_multilinear_map π E (G βL[π] G') :=
multilinear_map.mk_continuous
{ to_fun := Ξ» m, linear_map.mk_continuous
{ to_fun := Ξ» x, f x m,
map_add' := Ξ» x y, by simp only [map_add, continuous_multilinear_map.add_apply],
map_smul' := Ξ» c x, by simp only [continuous_multilinear_map.smul_apply, map_smul]}
(β₯fβ₯ * β i, β₯m iβ₯) $ Ξ» x,
by { rw mul_right_comm, exact (f x).le_of_op_norm_le _ (f.le_op_norm x) },
map_add' := Ξ» m i x y,
by { ext1, simp only [add_apply, continuous_multilinear_map.map_add, linear_map.coe_mk,
linear_map.mk_continuous_apply]},
map_smul' := Ξ» m i c x,
by { ext1, simp only [coe_smul', continuous_multilinear_map.map_smul, linear_map.coe_mk,
linear_map.mk_continuous_apply, pi.smul_apply]} }
β₯fβ₯ $ Ξ» m,
linear_map.mk_continuous_norm_le _
(mul_nonneg (norm_nonneg f) (prod_nonneg $ Ξ» i hi, norm_nonneg (m i))) _
end continuous_linear_map
open continuous_multilinear_map
namespace multilinear_map
/-- Given a map `f : G ββ[π] multilinear_map π E G'` and an estimate
`H : β x m, β₯f x mβ₯ β€ C * β₯xβ₯ * β i, β₯m iβ₯`, construct a continuous linear
map from `G` to `continuous_multilinear_map π E G'`.
In order to lift, e.g., a map `f : (multilinear_map π E G) ββ[π] multilinear_map π E' G'`
to a map `(continuous_multilinear_map π E G) βL[π] continuous_multilinear_map π E' G'`,
one can apply this construction to `f.comp continuous_multilinear_map.to_multilinear_map_linear`
which is a linear map from `continuous_multilinear_map π E G` to `multilinear_map π E' G'`. -/
def mk_continuous_linear (f : G ββ[π] multilinear_map π E G') (C : β)
(H : β x m, β₯f x mβ₯ β€ C * β₯xβ₯ * β i, β₯m iβ₯) :
G βL[π] continuous_multilinear_map π E G' :=
linear_map.mk_continuous
{ to_fun := Ξ» x, (f x).mk_continuous (C * β₯xβ₯) $ H x,
map_add' := Ξ» x y, by { ext1, simp },
map_smul' := Ξ» c x, by { ext1, simp } }
(max C 0) $ Ξ» x, ((f x).mk_continuous_norm_le' _).trans_eq $
by rw [max_mul_of_nonneg _ _ (norm_nonneg x), zero_mul]
lemma mk_continuous_linear_norm_le' (f : G ββ[π] multilinear_map π E G') (C : β)
(H : β x m, β₯f x mβ₯ β€ C * β₯xβ₯ * β i, β₯m iβ₯) :
β₯mk_continuous_linear f C Hβ₯ β€ max C 0 :=
begin
dunfold mk_continuous_linear,
exact linear_map.mk_continuous_norm_le _ (le_max_right _ _) _
end
lemma mk_continuous_linear_norm_le (f : G ββ[π] multilinear_map π E G') {C : β} (hC : 0 β€ C)
(H : β x m, β₯f x mβ₯ β€ C * β₯xβ₯ * β i, β₯m iβ₯) :
β₯mk_continuous_linear f C Hβ₯ β€ C :=
(mk_continuous_linear_norm_le' f C H).trans_eq (max_eq_left hC)
/-- Given a map `f : multilinear_map π E (multilinear_map π E' G)` and an estimate
`H : β m m', β₯f m m'β₯ β€ C * β i, β₯m iβ₯ * β i, β₯m' iβ₯`, upgrade all `multilinear_map`s in the type to
`continuous_multilinear_map`s. -/
def mk_continuous_multilinear (f : multilinear_map π E (multilinear_map π E' G)) (C : β)
(H : β mβ mβ, β₯f mβ mββ₯ β€ C * (β i, β₯mβ iβ₯) * β i, β₯mβ iβ₯) :
continuous_multilinear_map π E (continuous_multilinear_map π E' G) :=
mk_continuous
{ to_fun := Ξ» m, mk_continuous (f m) (C * β i, β₯m iβ₯) $ H m,
map_add' := Ξ» m i x y, by { ext1, simp },
map_smul' := Ξ» m i c x, by { ext1, simp } }
(max C 0) $ Ξ» m, ((f m).mk_continuous_norm_le' _).trans_eq $
by { rw [max_mul_of_nonneg, zero_mul], exact prod_nonneg (Ξ» _ _, norm_nonneg _) }
@[simp] lemma mk_continuous_multilinear_apply (f : multilinear_map π E (multilinear_map π E' G))
{C : β} (H : β mβ mβ, β₯f mβ mββ₯ β€ C * (β i, β₯mβ iβ₯) * β i, β₯mβ iβ₯) (m : Ξ i, E i) :
β(mk_continuous_multilinear f C H m) = f m :=
rfl
lemma mk_continuous_multilinear_norm_le' (f : multilinear_map π E (multilinear_map π E' G)) (C : β)
(H : β mβ mβ, β₯f mβ mββ₯ β€ C * (β i, β₯mβ iβ₯) * β i, β₯mβ iβ₯) :
β₯mk_continuous_multilinear f C Hβ₯ β€ max C 0 :=
begin
dunfold mk_continuous_multilinear,
exact mk_continuous_norm_le _ (le_max_right _ _) _
end
lemma mk_continuous_multilinear_norm_le (f : multilinear_map π E (multilinear_map π E' G)) {C : β}
(hC : 0 β€ C) (H : β mβ mβ, β₯f mβ mββ₯ β€ C * (β i, β₯mβ iβ₯) * β i, β₯mβ iβ₯) :
β₯mk_continuous_multilinear f C Hβ₯ β€ C :=
(mk_continuous_multilinear_norm_le' f C H).trans_eq (max_eq_left hC)
end multilinear_map
namespace continuous_multilinear_map
lemma norm_comp_continuous_linear_le (g : continuous_multilinear_map π Eβ G)
(f : Ξ i, E i βL[π] Eβ i) :
β₯g.comp_continuous_linear_map fβ₯ β€ β₯gβ₯ * β i, β₯f iβ₯ :=
op_norm_le_bound _ (mul_nonneg (norm_nonneg _) $ prod_nonneg $ Ξ» i hi, norm_nonneg _) $ Ξ» m,
calc β₯g (Ξ» i, f i (m i))β₯ β€ β₯gβ₯ * β i, β₯f i (m i)β₯ : g.le_op_norm _
... β€ β₯gβ₯ * β i, (β₯f iβ₯ * β₯m iβ₯) :
mul_le_mul_of_nonneg_left
(prod_le_prod (Ξ» _ _, norm_nonneg _) (Ξ» i hi, (f i).le_op_norm (m i))) (norm_nonneg g)
... = (β₯gβ₯ * β i, β₯f iβ₯) * β i, β₯m iβ₯ : by rw [prod_mul_distrib, mul_assoc]
/-- `continuous_multilinear_map.comp_continuous_linear_map` as a bundled continuous linear map.
This implementation fixes `f : Ξ i, E i βL[π] Eβ i`.
TODO: Actually, the map is multilinear in `f` but an attempt to formalize this failed because of
issues with class instances. -/
def comp_continuous_linear_mapL (f : Ξ i, E i βL[π] Eβ i) :
continuous_multilinear_map π Eβ G βL[π] continuous_multilinear_map π E G :=
linear_map.mk_continuous
{ to_fun := Ξ» g, g.comp_continuous_linear_map f,
map_add' := Ξ» gβ gβ, rfl,
map_smul' := Ξ» c g, rfl }
(β i, β₯f iβ₯) $ Ξ» g, (norm_comp_continuous_linear_le _ _).trans_eq (mul_comm _ _)
@[simp] lemma comp_continuous_linear_mapL_apply (g : continuous_multilinear_map π Eβ G)
(f : Ξ i, E i βL[π] Eβ i) :
comp_continuous_linear_mapL f g = g.comp_continuous_linear_map f :=
rfl
lemma norm_comp_continuous_linear_mapL_le (f : Ξ i, E i βL[π] Eβ i) :
β₯@comp_continuous_linear_mapL π ΞΉ E Eβ G _ _ _ _ _ _ _ _ _ fβ₯ β€ (β i, β₯f iβ₯) :=
linear_map.mk_continuous_norm_le _ (prod_nonneg $ Ξ» i _, norm_nonneg _) _
end continuous_multilinear_map
section currying
/-!
### Currying
We associate to a continuous multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two
curried functions, named `f.curry_left` (which is a continuous linear map on `E 0` taking values
in continuous multilinear maps in `n` variables) and `f.curry_right` (which is a continuous
multilinear map in `n` variables taking values in continuous linear maps on `E (last n)`).
The inverse operations are called `uncurry_left` and `uncurry_right`.
We also register continuous linear equiv versions of these correspondences, in
`continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`.
-/
open fin function
lemma continuous_linear_map.norm_map_tail_le
(f : Ei 0 βL[π] (continuous_multilinear_map π (Ξ»(i : fin n), Ei i.succ) G)) (m : Ξ i, Ei i) :
β₯f (m 0) (tail m)β₯ β€ β₯fβ₯ * β i, β₯m iβ₯ :=
calc
β₯f (m 0) (tail m)β₯ β€ β₯f (m 0)β₯ * β i, β₯(tail m) iβ₯ : (f (m 0)).le_op_norm _
... β€ (β₯fβ₯ * β₯m 0β₯) * β i, β₯(tail m) iβ₯ :
mul_le_mul_of_nonneg_right (f.le_op_norm _) (prod_nonneg (Ξ»i hi, norm_nonneg _))
... = β₯fβ₯ * (β₯m 0β₯ * β i, β₯(tail m) iβ₯) : by ring
... = β₯fβ₯ * β i, β₯m iβ₯ : by { rw prod_univ_succ, refl }
lemma continuous_multilinear_map.norm_map_init_le
(f : continuous_multilinear_map π (Ξ»(i : fin n), Ei i.cast_succ) (Ei (last n) βL[π] G))
(m : Ξ i, Ei i) :
β₯f (init m) (m (last n))β₯ β€ β₯fβ₯ * β i, β₯m iβ₯ :=
calc
β₯f (init m) (m (last n))β₯ β€ β₯f (init m)β₯ * β₯m (last n)β₯ : (f (init m)).le_op_norm _
... β€ (β₯fβ₯ * (β i, β₯(init m) iβ₯)) * β₯m (last n)β₯ :
mul_le_mul_of_nonneg_right (f.le_op_norm _) (norm_nonneg _)
... = β₯fβ₯ * ((β i, β₯(init m) iβ₯) * β₯m (last n)β₯) : mul_assoc _ _ _
... = β₯fβ₯ * β i, β₯m iβ₯ : by { rw prod_univ_cast_succ, refl }
lemma continuous_multilinear_map.norm_map_cons_le
(f : continuous_multilinear_map π Ei G) (x : Ei 0) (m : Ξ (i : fin n), Ei i.succ) :
β₯f (cons x m)β₯ β€ β₯fβ₯ * β₯xβ₯ * β i, β₯m iβ₯ :=
calc
β₯f (cons x m)β₯ β€ β₯fβ₯ * β i, β₯cons x m iβ₯ : f.le_op_norm _
... = (β₯fβ₯ * β₯xβ₯) * β i, β₯m iβ₯ : by { rw prod_univ_succ, simp [mul_assoc] }
lemma continuous_multilinear_map.norm_map_snoc_le
(f : continuous_multilinear_map π Ei G) (m : Ξ (i : fin n), Ei i.cast_succ) (x : Ei (last n)) :
β₯f (snoc m x)β₯ β€ β₯fβ₯ * (β i, β₯m iβ₯) * β₯xβ₯ :=
calc
β₯f (snoc m x)β₯ β€ β₯fβ₯ * β i, β₯snoc m x iβ₯ : f.le_op_norm _
... = β₯fβ₯ * (β i, β₯m iβ₯) * β₯xβ₯ : by { rw prod_univ_cast_succ, simp [mul_assoc] }
/-! #### Left currying -/
/-- Given a continuous linear map `f` from `E 0` to continuous multilinear maps on `n` variables,
construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating
the variables, given by `m β¦ f (m 0) (tail m)`-/
def continuous_linear_map.uncurry_left
(f : Ei 0 βL[π] (continuous_multilinear_map π (Ξ»(i : fin n), Ei i.succ) G)) :
continuous_multilinear_map π Ei G :=
(@linear_map.uncurry_left π n Ei G _ _ _ _ _
(continuous_multilinear_map.to_multilinear_map_linear.comp f.to_linear_map)).mk_continuous
(β₯fβ₯) (Ξ»m, continuous_linear_map.norm_map_tail_le f m)
@[simp] lemma continuous_linear_map.uncurry_left_apply
(f : Ei 0 βL[π] (continuous_multilinear_map π (Ξ»(i : fin n), Ei i.succ) G)) (m : Ξ i, Ei i) :
f.uncurry_left m = f (m 0) (tail m) := rfl
/-- Given a continuous multilinear map `f` in `n+1` variables, split the first variable to obtain
a continuous linear map into continuous multilinear maps in `n` variables, given by
`x β¦ (m β¦ f (cons x m))`. -/
def continuous_multilinear_map.curry_left
(f : continuous_multilinear_map π Ei G) :
Ei 0 βL[π] (continuous_multilinear_map π (Ξ»(i : fin n), Ei i.succ) G) :=
linear_map.mk_continuous
{ -- define a linear map into `n` continuous multilinear maps from an `n+1` continuous multilinear
-- map
to_fun := Ξ»x, (f.to_multilinear_map.curry_left x).mk_continuous
(β₯fβ₯ * β₯xβ₯) (f.norm_map_cons_le x),
map_add' := Ξ»x y, by { ext m, exact f.cons_add m x y },
map_smul' := Ξ»c x, by { ext m, exact f.cons_smul m c x } }
-- then register its continuity thanks to its boundedness properties.
(β₯fβ₯) (Ξ»x, multilinear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _)
@[simp] lemma continuous_multilinear_map.curry_left_apply
(f : continuous_multilinear_map π Ei G) (x : Ei 0) (m : Ξ (i : fin n), Ei i.succ) :
f.curry_left x m = f (cons x m) := rfl
@[simp] lemma continuous_linear_map.curry_uncurry_left
(f : Ei 0 βL[π] (continuous_multilinear_map π (Ξ»(i : fin n), Ei i.succ) G)) :
f.uncurry_left.curry_left = f :=
begin
ext m x,
simp only [tail_cons, continuous_linear_map.uncurry_left_apply,
continuous_multilinear_map.curry_left_apply],
rw cons_zero
end
@[simp] lemma continuous_multilinear_map.uncurry_curry_left
(f : continuous_multilinear_map π Ei G) : f.curry_left.uncurry_left = f :=
continuous_multilinear_map.to_multilinear_map_inj $ f.to_multilinear_map.uncurry_curry_left
variables (π Ei G)
/-- The space of continuous multilinear maps on `Ξ (i : fin (n+1)), E i` is canonically isomorphic to
the space of continuous linear maps from `E 0` to the space of continuous multilinear maps on
`Ξ (i : fin n), E i.succ `, by separating the first variable. We register this isomorphism in
`continuous_multilinear_curry_left_equiv π E Eβ`. The algebraic version (without topology) is given
in `multilinear_curry_left_equiv π E Eβ`.
The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these
unless you need the full framework of linear isometric equivs. -/
def continuous_multilinear_curry_left_equiv :
(Ei 0 βL[π] (continuous_multilinear_map π (Ξ»(i : fin n), Ei i.succ) G)) ββα΅’[π]
(continuous_multilinear_map π Ei G) :=
linear_isometry_equiv.of_bounds
{ to_fun := continuous_linear_map.uncurry_left,
map_add' := Ξ»fβ fβ, by { ext m, refl },
map_smul' := Ξ»c f, by { ext m, refl },
inv_fun := continuous_multilinear_map.curry_left,
left_inv := continuous_linear_map.curry_uncurry_left,
right_inv := continuous_multilinear_map.uncurry_curry_left }
(Ξ» f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _)
(Ξ» f, linear_map.mk_continuous_norm_le _ (norm_nonneg f) _)
variables {π Ei G}
@[simp] lemma continuous_multilinear_curry_left_equiv_apply
(f : Ei 0 βL[π] (continuous_multilinear_map π (Ξ» i : fin n, Ei i.succ) G)) (v : Ξ i, Ei i) :
continuous_multilinear_curry_left_equiv π Ei G f v = f (v 0) (tail v) := rfl
@[simp] lemma continuous_multilinear_curry_left_equiv_symm_apply
(f : continuous_multilinear_map π Ei G) (x : Ei 0) (v : Ξ i : fin n, Ei i.succ) :
(continuous_multilinear_curry_left_equiv π Ei G).symm f x v = f (cons x v) := rfl
@[simp] lemma continuous_multilinear_map.curry_left_norm
(f : continuous_multilinear_map π Ei G) : β₯f.curry_leftβ₯ = β₯fβ₯ :=
(continuous_multilinear_curry_left_equiv π Ei G).symm.norm_map f
@[simp] lemma continuous_linear_map.uncurry_left_norm
(f : Ei 0 βL[π] (continuous_multilinear_map π (Ξ»(i : fin n), Ei i.succ) G)) :
β₯f.uncurry_leftβ₯ = β₯fβ₯ :=
(continuous_multilinear_curry_left_equiv π Ei G).norm_map f
/-! #### Right currying -/
/-- Given a continuous linear map `f` from continuous multilinear maps on `n` variables to
continuous linear maps on `E 0`, construct the corresponding continuous multilinear map on `n+1`
variables obtained by concatenating the variables, given by `m β¦ f (init m) (m (last n))`. -/
def continuous_multilinear_map.uncurry_right
(f : continuous_multilinear_map π (Ξ» i : fin n, Ei i.cast_succ) (Ei (last n) βL[π] G)) :
continuous_multilinear_map π Ei G :=
let f' : multilinear_map π (Ξ»(i : fin n), Ei i.cast_succ) (Ei (last n) ββ[π] G) :=
{ to_fun := Ξ» m, (f m).to_linear_map,
map_add' := Ξ» m i x y, by simp,
map_smul' := Ξ» m i c x, by simp } in
(@multilinear_map.uncurry_right π n Ei G _ _ _ _ _ f').mk_continuous
(β₯fβ₯) (Ξ»m, f.norm_map_init_le m)
@[simp] lemma continuous_multilinear_map.uncurry_right_apply
(f : continuous_multilinear_map π (Ξ»(i : fin n), Ei i.cast_succ) (Ei (last n) βL[π] G))
(m : Ξ i, Ei i) :
f.uncurry_right m = f (init m) (m (last n)) := rfl
/-- Given a continuous multilinear map `f` in `n+1` variables, split the last variable to obtain
a continuous multilinear map in `n` variables into continuous linear maps, given by
`m β¦ (x β¦ f (snoc m x))`. -/
def continuous_multilinear_map.curry_right
(f : continuous_multilinear_map π Ei G) :
continuous_multilinear_map π (Ξ» i : fin n, Ei i.cast_succ) (Ei (last n) βL[π] G) :=
let f' : multilinear_map π (Ξ»(i : fin n), Ei i.cast_succ) (Ei (last n) βL[π] G) :=
{ to_fun := Ξ»m, (f.to_multilinear_map.curry_right m).mk_continuous
(β₯fβ₯ * β i, β₯m iβ₯) $ Ξ»x, f.norm_map_snoc_le m x,
map_add' := Ξ» m i x y, by { simp, refl },
map_smul' := Ξ» m i c x, by { simp, refl } } in
f'.mk_continuous (β₯fβ₯) (Ξ»m, linear_map.mk_continuous_norm_le _
(mul_nonneg (norm_nonneg _) (prod_nonneg (Ξ»j hj, norm_nonneg _))) _)
@[simp] lemma continuous_multilinear_map.curry_right_apply
(f : continuous_multilinear_map π Ei G) (m : Ξ i : fin n, Ei i.cast_succ) (x : Ei (last n)) :
f.curry_right m x = f (snoc m x) := rfl
@[simp] lemma continuous_multilinear_map.curry_uncurry_right
(f : continuous_multilinear_map π (Ξ» i : fin n, Ei i.cast_succ) (Ei (last n) βL[π] G)) :
f.uncurry_right.curry_right = f :=
begin
ext m x,
simp only [snoc_last, continuous_multilinear_map.curry_right_apply,
continuous_multilinear_map.uncurry_right_apply],
rw init_snoc
end
@[simp] lemma continuous_multilinear_map.uncurry_curry_right
(f : continuous_multilinear_map π Ei G) : f.curry_right.uncurry_right = f :=
by { ext m, simp }
variables (π Ei G)
/--
The space of continuous multilinear maps on `Ξ (i : fin (n+1)), Ei i` is canonically isomorphic to
the space of continuous multilinear maps on `Ξ (i : fin n), Ei i.cast_succ` with values in the space
of continuous linear maps on `Ei (last n)`, by separating the last variable. We register this
isomorphism as a continuous linear equiv in `continuous_multilinear_curry_right_equiv π Ei G`.
The algebraic version (without topology) is given in `multilinear_curry_right_equiv π Ei G`.
The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these
unless you need the full framework of linear isometric equivs.
-/
def continuous_multilinear_curry_right_equiv :
(continuous_multilinear_map π (Ξ»(i : fin n), Ei i.cast_succ) (Ei (last n) βL[π] G)) ββα΅’[π]
(continuous_multilinear_map π Ei G) :=
linear_isometry_equiv.of_bounds
{ to_fun := continuous_multilinear_map.uncurry_right,
map_add' := Ξ»fβ fβ, by { ext m, refl },
map_smul' := Ξ»c f, by { ext m, refl },
inv_fun := continuous_multilinear_map.curry_right,
left_inv := continuous_multilinear_map.curry_uncurry_right,
right_inv := continuous_multilinear_map.uncurry_curry_right }
(Ξ» f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _)
(Ξ» f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _)
variables (n G')
/-- The space of continuous multilinear maps on `Ξ (i : fin (n+1)), G` is canonically isomorphic to
the space of continuous multilinear maps on `Ξ (i : fin n), G` with values in the space
of continuous linear maps on `G`, by separating the last variable. We register this
isomorphism as a continuous linear equiv in `continuous_multilinear_curry_right_equiv' π n G G'`.
For a version allowing dependent types, see `continuous_multilinear_curry_right_equiv`. When there
are no dependent types, use the primed version as it helps Lean a lot for unification.
The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these
unless you need the full framework of linear isometric equivs. -/
def continuous_multilinear_curry_right_equiv' :
(G [Γn]βL[π] (G βL[π] G')) ββα΅’[π] (G [Γn.succ]βL[π] G') :=
continuous_multilinear_curry_right_equiv π (Ξ» (i : fin n.succ), G) G'
variables {n π G Ei G'}
@[simp] lemma continuous_multilinear_curry_right_equiv_apply
(f : (continuous_multilinear_map π (Ξ»(i : fin n), Ei i.cast_succ) (Ei (last n) βL[π] G)))
(v : Ξ i, Ei i) :
(continuous_multilinear_curry_right_equiv π Ei G) f v = f (init v) (v (last n)) := rfl
@[simp] lemma continuous_multilinear_curry_right_equiv_symm_apply
(f : continuous_multilinear_map π Ei G)
(v : Ξ (i : fin n), Ei i.cast_succ) (x : Ei (last n)) :
(continuous_multilinear_curry_right_equiv π Ei G).symm f v x = f (snoc v x) := rfl
@[simp] lemma continuous_multilinear_curry_right_equiv_apply'
(f : G [Γn]βL[π] (G βL[π] G')) (v : Ξ (i : fin n.succ), G) :
continuous_multilinear_curry_right_equiv' π n G G' f v = f (init v) (v (last n)) := rfl
@[simp] lemma continuous_multilinear_curry_right_equiv_symm_apply'
(f : G [Γn.succ]βL[π] G') (v : Ξ (i : fin n), G) (x : G) :
(continuous_multilinear_curry_right_equiv' π n G G').symm f v x = f (snoc v x) := rfl
@[simp] lemma continuous_multilinear_map.curry_right_norm
(f : continuous_multilinear_map π Ei G) : β₯f.curry_rightβ₯ = β₯fβ₯ :=
(continuous_multilinear_curry_right_equiv π Ei G).symm.norm_map f
@[simp] lemma continuous_multilinear_map.uncurry_right_norm
(f : continuous_multilinear_map π (Ξ» i : fin n, Ei i.cast_succ) (Ei (last n) βL[π] G)) :
β₯f.uncurry_rightβ₯ = β₯fβ₯ :=
(continuous_multilinear_curry_right_equiv π Ei G).norm_map f
/-!
#### Currying with `0` variables
The space of multilinear maps with `0` variables is trivial: such a multilinear map is just an
arbitrary constant (note that multilinear maps in `0` variables need not map `0` to `0`!).
Therefore, the space of continuous multilinear maps on `(fin 0) β G` with values in `Eβ` is
isomorphic (and even isometric) to `Eβ`. As this is the zeroth step in the construction of iterated
derivatives, we register this isomorphism. -/
section
local attribute [instance] unique.subsingleton
variables {π G G'}
/-- Associating to a continuous multilinear map in `0` variables the unique value it takes. -/
def continuous_multilinear_map.uncurry0
(f : continuous_multilinear_map π (Ξ» (i : fin 0), G) G') : G' := f 0
variables (π G)
/-- Associating to an element `x` of a vector space `Eβ` the continuous multilinear map in `0`
variables taking the (unique) value `x` -/
def continuous_multilinear_map.curry0 (x : G') : G [Γ0]βL[π] G' :=
{ to_fun := Ξ»m, x,
map_add' := Ξ» m i, fin.elim0 i,
map_smul' := Ξ» m i, fin.elim0 i,
cont := continuous_const }
variable {G}
@[simp] lemma continuous_multilinear_map.curry0_apply (x : G') (m : (fin 0) β G) :
continuous_multilinear_map.curry0 π G x m = x := rfl
variable {π}
@[simp] lemma continuous_multilinear_map.uncurry0_apply (f : G [Γ0]βL[π] G') :
f.uncurry0 = f 0 := rfl
@[simp] lemma continuous_multilinear_map.apply_zero_curry0 (f : G [Γ0]βL[π] G') {x : fin 0 β G} :
continuous_multilinear_map.curry0 π G (f x) = f :=
by { ext m, simp [(subsingleton.elim _ _ : x = m)] }
lemma continuous_multilinear_map.uncurry0_curry0 (f : G [Γ0]βL[π] G') :
continuous_multilinear_map.curry0 π G (f.uncurry0) = f :=
by simp
variables (π G)
@[simp] lemma continuous_multilinear_map.curry0_uncurry0 (x : G') :
(continuous_multilinear_map.curry0 π G x).uncurry0 = x := rfl
@[simp] lemma continuous_multilinear_map.curry0_norm (x : G') :
β₯continuous_multilinear_map.curry0 π G xβ₯ = β₯xβ₯ :=
begin
apply le_antisymm,
{ exact continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (Ξ»m, by simp) },
{ simpa using (continuous_multilinear_map.curry0 π G x).le_op_norm 0 }
end
variables {π G}
@[simp] lemma continuous_multilinear_map.fin0_apply_norm (f : G [Γ0]βL[π] G') {x : fin 0 β G} :
β₯f xβ₯ = β₯fβ₯ :=
begin
have : x = 0 := subsingleton.elim _ _, subst this,
refine le_antisymm (by simpa using f.le_op_norm 0) _,
have : β₯continuous_multilinear_map.curry0 π G (f.uncurry0)β₯ β€ β₯f.uncurry0β₯ :=
continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (Ξ»m,
by simp [-continuous_multilinear_map.apply_zero_curry0]),
simpa
end
lemma continuous_multilinear_map.uncurry0_norm (f : G [Γ0]βL[π] G') : β₯f.uncurry0β₯ = β₯fβ₯ :=
by simp
variables (π G G')
/-- The continuous linear isomorphism between elements of a normed space, and continuous multilinear
maps in `0` variables with values in this normed space.
The direct and inverse maps are `uncurry0` and `curry0`. Use these unless you need the full
framework of linear isometric equivs. -/
def continuous_multilinear_curry_fin0 : (G [Γ0]βL[π] G') ββα΅’[π] G' :=
{ to_fun := Ξ»f, continuous_multilinear_map.uncurry0 f,
inv_fun := Ξ»f, continuous_multilinear_map.curry0 π G f,
map_add' := Ξ»f g, rfl,
map_smul' := Ξ»c f, rfl,
left_inv := continuous_multilinear_map.uncurry0_curry0,
right_inv := continuous_multilinear_map.curry0_uncurry0 π G,
norm_map' := continuous_multilinear_map.uncurry0_norm }
variables {π G G'}
@[simp] lemma continuous_multilinear_curry_fin0_apply (f : G [Γ0]βL[π] G') :
continuous_multilinear_curry_fin0 π G G' f = f 0 := rfl
@[simp] lemma continuous_multilinear_curry_fin0_symm_apply (x : G') (v : (fin 0) β G) :
(continuous_multilinear_curry_fin0 π G G').symm x v = x := rfl
end
/-! #### With 1 variable -/
variables (π G G')
/-- Continuous multilinear maps from `G^1` to `G'` are isomorphic with continuous linear maps from
`G` to `G'`. -/
def continuous_multilinear_curry_fin1 : (G [Γ1]βL[π] G') ββα΅’[π] (G βL[π] G') :=
(continuous_multilinear_curry_right_equiv π (Ξ» (i : fin 1), G) G').symm.trans
(continuous_multilinear_curry_fin0 π G (G βL[π] G'))
variables {π G G'}
@[simp] lemma continuous_multilinear_curry_fin1_apply (f : G [Γ1]βL[π] G') (x : G) :
continuous_multilinear_curry_fin1 π G G' f x = f (fin.snoc 0 x) := rfl
@[simp] lemma continuous_multilinear_curry_fin1_symm_apply
(f : G βL[π] G') (v : (fin 1) β G) :
(continuous_multilinear_curry_fin1 π G G').symm f v = f (v 0) := rfl
namespace continuous_multilinear_map
variables (π G G')
/-- An equivalence of the index set defines a linear isometric equivalence between the spaces
of multilinear maps. -/
def dom_dom_congr (Ο : ΞΉ β ΞΉ') :
continuous_multilinear_map π (Ξ» _ : ΞΉ, G) G' ββα΅’[π]
continuous_multilinear_map π (Ξ» _ : ΞΉ', G) G' :=
linear_isometry_equiv.of_bounds
{ to_fun := Ξ» f, (multilinear_map.dom_dom_congr Ο f.to_multilinear_map).mk_continuous β₯fβ₯ $
Ξ» m, (f.le_op_norm (Ξ» i, m (Ο i))).trans_eq $ by rw [β Ο.prod_comp],
inv_fun := Ξ» f, (multilinear_map.dom_dom_congr Ο.symm f.to_multilinear_map).mk_continuous β₯fβ₯ $
Ξ» m, (f.le_op_norm (Ξ» i, m (Ο.symm i))).trans_eq $ by rw [β Ο.symm.prod_comp],
left_inv := Ξ» f, ext $ Ξ» m, congr_arg f $ by simp only [Ο.symm_apply_apply],
right_inv := Ξ» f, ext $ Ξ» m, congr_arg f $ by simp only [Ο.apply_symm_apply],
map_add' := Ξ» f g, rfl,
map_smul' := Ξ» c f, rfl }
(Ξ» f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _)
(Ξ» f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _)
variables {π G G'}
section
variable [decidable_eq (ΞΉ β ΞΉ')]
/-- A continuous multilinear map with variables indexed by `ΞΉ β ΞΉ'` defines a continuous multilinear
map with variables indexed by `ΞΉ` taking values in the space of continuous multilinear maps with
variables indexed by `ΞΉ'`. -/
def curry_sum (f : continuous_multilinear_map π (Ξ» x : ΞΉ β ΞΉ', G) G') :
continuous_multilinear_map π (Ξ» x : ΞΉ, G) (continuous_multilinear_map π (Ξ» x : ΞΉ', G) G') :=
multilinear_map.mk_continuous_multilinear (multilinear_map.curry_sum f.to_multilinear_map) (β₯fβ₯) $
Ξ» m m', by simpa [fintype.prod_sum_type, mul_assoc] using f.le_op_norm (sum.elim m m')
@[simp] lemma curry_sum_apply (f : continuous_multilinear_map π (Ξ» x : ΞΉ β ΞΉ', G) G')
(m : ΞΉ β G) (m' : ΞΉ' β G) :
f.curry_sum m m' = f (sum.elim m m') :=
rfl
/-- A continuous multilinear map with variables indexed by `ΞΉ` taking values in the space of
continuous multilinear maps with variables indexed by `ΞΉ'` defines a continuous multilinear map with
variables indexed by `ΞΉ β ΞΉ'`. -/
def uncurry_sum
(f : continuous_multilinear_map π (Ξ» x : ΞΉ, G) (continuous_multilinear_map π (Ξ» x : ΞΉ', G) G')) :
continuous_multilinear_map π (Ξ» x : ΞΉ β ΞΉ', G) G' :=
multilinear_map.mk_continuous
(to_multilinear_map_linear.comp_multilinear_map f.to_multilinear_map).uncurry_sum (β₯fβ₯) $ Ξ» m,
by simpa [fintype.prod_sum_type, mul_assoc]
using (f (m β sum.inl)).le_of_op_norm_le (m β sum.inr) (f.le_op_norm _)
@[simp] lemma uncurry_sum_apply
(f : continuous_multilinear_map π (Ξ» x : ΞΉ, G) (continuous_multilinear_map π (Ξ» x : ΞΉ', G) G'))
(m : ΞΉ β ΞΉ' β G) :
f.uncurry_sum m = f (m β sum.inl) (m β sum.inr) :=
rfl
variables (π ΞΉ ΞΉ' G G')
/-- Linear isometric equivalence between the space of continuous multilinear maps with variables
indexed by `ΞΉ β ΞΉ'` and the space of continuous multilinear maps with variables indexed by `ΞΉ`
taking values in the space of continuous multilinear maps with variables indexed by `ΞΉ'`.
The forward and inverse functions are `continuous_multilinear_map.curry_sum`
and `continuous_multilinear_map.uncurry_sum`. Use this definition only if you need
some properties of `linear_isometry_equiv`. -/
def curry_sum_equiv : continuous_multilinear_map π (Ξ» x : ΞΉ β ΞΉ', G) G' ββα΅’[π]
continuous_multilinear_map π (Ξ» x : ΞΉ, G) (continuous_multilinear_map π (Ξ» x : ΞΉ', G) G') :=
linear_isometry_equiv.of_bounds
{ to_fun := curry_sum,
inv_fun := uncurry_sum,
map_add' := Ξ» f g, by { ext, refl },
map_smul' := Ξ» c f, by { ext, refl },
left_inv := Ξ» f, by { ext m, exact congr_arg f (sum.elim_comp_inl_inr m) },
right_inv := Ξ» f, by { ext mβ mβ, change f _ _ = f _ _,
rw [sum.elim_comp_inl, sum.elim_comp_inr] } }
(Ξ» f, multilinear_map.mk_continuous_multilinear_norm_le _ (norm_nonneg f) _)
(Ξ» f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _)
end
section
variables (π G G') {k l : β} {s : finset (fin n)} [decidable_pred (s : set (fin n))]
/-- If `s : finset (fin n)` is a finite set of cardinality `k` and its complement has cardinality
`l`, then the space of continuous multilinear maps `G [Γn]βL[π] G'` of `n` variables is isomorphic
to the space of continuous multilinear maps `G [Γk]βL[π] G [Γl]βL[π] G'` of `k` variables taking
values in the space of continuous multilinear maps of `l` variables. -/
def curry_fin_finset {k l n : β} {s : finset (fin n)} [decidable_pred (s : set (fin n))]
(hk : s.card = k) (hl : sαΆ.card = l) :
(G [Γn]βL[π] G') ββα΅’[π] (G [Γk]βL[π] G [Γl]βL[π] G') :=
(dom_dom_congr π G G' (fin_sum_equiv_of_finset hk hl).symm).trans
(curry_sum_equiv π (fin k) (fin l) G G')
variables {π G G'}
@[simp] lemma curry_fin_finset_apply (hk : s.card = k) (hl : sαΆ.card = l)
(f : G [Γn]βL[π] G') (mk : fin k β G) (ml : fin l β G) :
curry_fin_finset π G G' hk hl f mk ml =
f (Ξ» i, sum.elim mk ml ((fin_sum_equiv_of_finset hk hl).symm i)) :=
rfl
@[simp] lemma curry_fin_finset_symm_apply (hk : s.card = k) (hl : sαΆ.card = l)
(f : G [Γk]βL[π] G [Γl]βL[π] G') (m : fin n β G) :
(curry_fin_finset π G G' hk hl).symm f m =
f (Ξ» i, m $ fin_sum_equiv_of_finset hk hl (sum.inl i))
(Ξ» i, m $ fin_sum_equiv_of_finset hk hl (sum.inr i)) :=
rfl
@[simp] lemma curry_fin_finset_symm_apply_piecewise_const (hk : s.card = k) (hl : sαΆ.card = l)
(f : G [Γk]βL[π] G [Γl]βL[π] G') (x y : G) :
(curry_fin_finset π G G' hk hl).symm f (s.piecewise (Ξ» _, x) (Ξ» _, y)) = f (Ξ» _, x) (Ξ» _, y) :=
multilinear_map.curry_fin_finset_symm_apply_piecewise_const hk hl _ x y
@[simp] lemma curry_fin_finset_symm_apply_const (hk : s.card = k) (hl : sαΆ.card = l)
(f : G [Γk]βL[π] G [Γl]βL[π] G') (x : G) :
(curry_fin_finset π G G' hk hl).symm f (Ξ» _, x) = f (Ξ» _, x) (Ξ» _, x) :=
rfl
@[simp] lemma curry_fin_finset_apply_const (hk : s.card = k) (hl : sαΆ.card = l)
(f : G [Γn]βL[π] G') (x y : G) :
curry_fin_finset π G G' hk hl f (Ξ» _, x) (Ξ» _, y) = f (s.piecewise (Ξ» _, x) (Ξ» _, y)) :=
begin
refine (curry_fin_finset_symm_apply_piecewise_const hk hl _ _ _).symm.trans _, -- `rw` fails
rw linear_isometry_equiv.symm_apply_apply
end
end
end continuous_multilinear_map
end currying
|
5ac01876a73e9ae8a6f8beb5bd108021dc923ba0 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/order/filter/indicator_function.lean | 88d5dd450026c9f9832a8f596ac1c2a4cdeb73ab | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 3,252 | lean | /-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Yury Kudryashov
-/
import algebra.indicator_function
import order.filter.at_top_bot
/-!
# Indicator function and filters
Properties of indicator functions involving `=αΆ ` and `β€αΆ `.
## Tags
indicator, characteristic, filter
-/
variables {Ξ± Ξ² M E : Type*}
open set filter classical
open_locale filter classical
section has_zero
variables [has_zero M] {s t : set Ξ±} {f g : Ξ± β M} {a : Ξ±} {l : filter Ξ±}
lemma indicator_eventually_eq (hf : f =αΆ [l β π s] g) (hs : s =αΆ [l] t) :
indicator s f =αΆ [l] indicator t g :=
(eventually_inf_principal.1 hf).mp $ hs.mem_iff.mono $ Ξ» x hst hfg,
by_cases (Ξ» hxs : x β s, by simp only [*, hst.1 hxs, indicator_of_mem])
(Ξ» hxs, by simp only [indicator_of_not_mem hxs, indicator_of_not_mem (mt hst.2 hxs)])
end has_zero
section add_monoid
variables [add_monoid M] {s t : set Ξ±} {f g : Ξ± β M} {a : Ξ±} {l : filter Ξ±}
lemma indicator_union_eventually_eq (h : βαΆ a in l, a β s β© t) :
indicator (s βͺ t) f =αΆ [l] indicator s f + indicator t f :=
h.mono $ Ξ» a ha, indicator_union_of_not_mem_inter ha _
end add_monoid
section order
variables [has_zero Ξ²] [preorder Ξ²] {s t : set Ξ±} {f g : Ξ± β Ξ²} {a : Ξ±} {l : filter Ξ±}
lemma indicator_eventually_le_indicator (h : f β€αΆ [l β π s] g) :
indicator s f β€αΆ [l] indicator s g :=
(eventually_inf_principal.1 h).mono $ assume a h,
indicator_rel_indicator (le_refl _) h
end order
lemma tendsto_indicator_of_monotone {ΞΉ} [preorder ΞΉ] [has_zero Ξ²]
(s : ΞΉ β set Ξ±) (hs : monotone s) (f : Ξ± β Ξ²) (a : Ξ±) :
tendsto (Ξ»i, indicator (s i) f a) at_top (pure $ indicator (β i, s i) f a) :=
begin
by_cases h : βi, a β s i,
{ rcases h with β¨i, hiβ©,
refine tendsto_pure.2 ((eventually_ge_at_top i).mono $ assume n hn, _),
rw [indicator_of_mem (hs hn hi) _, indicator_of_mem ((subset_Union _ _) hi) _] },
{ rw [not_exists] at h,
simp only [indicator_of_not_mem (h _)],
convert tendsto_const_pure,
apply indicator_of_not_mem, simpa only [not_exists, mem_Union] }
end
lemma tendsto_indicator_of_antimono {ΞΉ} [preorder ΞΉ] [has_zero Ξ²]
(s : ΞΉ β set Ξ±) (hs : ββ¦i jβ¦, i β€ j β s j β s i) (f : Ξ± β Ξ²) (a : Ξ±) :
tendsto (Ξ»i, indicator (s i) f a) at_top (pure $ indicator (β i, s i) f a) :=
begin
by_cases h : βi, a β s i,
{ rcases h with β¨i, hiβ©,
refine tendsto_pure.2 ((eventually_ge_at_top i).mono $ assume n hn, _),
rw [indicator_of_not_mem _ _, indicator_of_not_mem _ _],
{ simp only [mem_Inter, not_forall], exact β¨i, hiβ© },
{ assume h, have := hs hn h, contradiction } },
{ push_neg at h,
simp only [indicator_of_mem, h, (mem_Inter.2 h), tendsto_const_pure] }
end
lemma tendsto_indicator_bUnion_finset {ΞΉ} [has_zero Ξ²] (s : ΞΉ β set Ξ±) (f : Ξ± β Ξ²) (a : Ξ±) :
tendsto (Ξ» (n : finset ΞΉ), indicator (βiβn, s i) f a) at_top (pure $ indicator (Union s) f a) :=
begin
rw Union_eq_Union_finset s,
refine tendsto_indicator_of_monotone (Ξ» n : finset ΞΉ, β i β n, s i) _ f a,
exact Ξ» tβ tβ, bUnion_subset_bUnion_left
end
|
1c3a2a60a4538ff9c57000ebc2e58485bdb12cbd | 2bafba05c98c1107866b39609d15e849a4ca2bb8 | /src/week_4/solutions/Part_C_topology.lean | ea6250d08cb1b9c4b67bd8bc2a947722bbdc8d7a | [
"Apache-2.0"
] | permissive | ImperialCollegeLondon/formalising-mathematics | b54c83c94b5c315024ff09997fcd6b303892a749 | 7cf1d51c27e2038d2804561d63c74711924044a1 | refs/heads/master | 1,651,267,046,302 | 1,638,888,459,000 | 1,638,888,459,000 | 331,592,375 | 284 | 24 | Apache-2.0 | 1,669,593,705,000 | 1,611,224,849,000 | Lean | UTF-8 | Lean | false | false | 9,788 | lean | import topology.subset_properties -- compactness of subsets of top spaces
/-!
# Topology, the traditional way
Let's do some topology! In this file we prove that
* the continuous image of a compact space is compact;
* A closed subset of a compact space is compact.
## Details
In fact we do a little more than this (but it's basically equivalent).
We do not work with compact topological spaces, we work with compact
subsets of topological spaces. What we will actually prove is this:
* If `f : X β Y` is a continuous map, and `S : set X` is a compact subset
(with the subspace topology), then `f '' S` (the image of `S` under `f`) is
compact (with the subspace topology).
* If `X` is a topological space, if `S` is a compact subset and if `C` is
a closed subset, then `S β© C` is a compact subset.
The original results are just the special case where `S` is `univ : set X`.
-/
-- Let X and Y be topological spaces, and let `f : X β Y` be a map.
variables (X Y : Type) [topological_space X] [topological_space Y] (f : X β Y)
-- I don't want to be typing `set.this` and `set.that` so let's open
-- the `set` namespace once and for all.
open set
/-!
## Compact subspaces
`is_compact` is a predicate on `set X`, if `X` is a topological space.
In other words, `is_compact X` doesn't make sense, but if `S : set X`
then `is_compact S` does. The actual definition in mathlib involves
filters! But it is a theorem in mathlib that `is_compact S` is true if and only
if every collection of open subsets of `X` whose union contains `S`
has a finite subcollection whose union contains `S`. Unfortunately,
mathlib's version of this, `compact_iff_finite_subcover`, uses a slightly
wacky notion of finite subcover involving `finset X`, the type of finite
subsets of `X` (a completely different type to the type `set X`!).
We prove an easier-to-use version involving `finite Z`, the predicate
saying that `Z : set ΞΉ` is finite. You can ignore this proof.
-/
lemma compact_iff_finite_subcover'
{Ξ± : Type} [topological_space Ξ±] {S : set Ξ±} :
is_compact S β (β {ΞΉ : Type} (U : ΞΉ β (set Ξ±)), (β i, is_open (U i)) β
S β (β i, U i) β (β (t : set ΞΉ), t.finite β§ S β (β i β t, U i))) :=
begin
rw compact_iff_finite_subcover,
split,
{ intros hs ΞΉ U hU hsU,
cases hs U hU hsU with F hF,
use [(βF : set ΞΉ), finset.finite_to_set F],
exact hF },
{ intros hs ΞΉ U hU hsU,
rcases hs U hU hsU with β¨F, hFfin, hFβ©,
use hFfin.to_finset,
convert hF,
ext,
simp }
end
/-!
## Continuous image of compact is compact
I would start with `rw compact_iff_finite_subcover' at hS β’,`
The proof that I recommend formalising is this. Say `S` is a compact
subset of `X`, and `f : X β Y` is continuous. We want to prove that
every cover of `f '' S` by open subsets of `Y` has a finite subcover.
So let's cover `f '' S` with opens `U i : set Y`, for `i : ΞΉ` and `ΞΉ` an index type.
Pull these opens back to `V i : set X` and observe that they cover `S`.
Choose a finite subcover corresponding to some `F : set ΞΉ` such that `F` is finite
(Lean writes this `h : F.finite`) and then check that the corresponding cover
of `f '' S` by the `U i` with `i β F` is a finite subcover.
Good luck! Please ask questions (or DM me on discord if you don't want to
ask publically). Also feel free to DM me if you manage to do it!
Useful theorems:
`continuous.is_open_preimage` -- preimage of an open set under a
continuous map is open.
`is_open_compl_iff` -- complement `SαΆ` of `S` is open iff `S` is closed.
## Some useful tactics:
### `specialize`
`specialize` can be used with `_`. If you have a hypothesis
`hS : β {ΞΉ : Type} (U : ΞΉ β set X), (β (i : ΞΉ), is_open (U i)) β ...`
and `U : ΞΉ β set X`, then
`specialize hS U` will change `hS` to
`hS : (β (i : ΞΉ), is_open (U i)) β ...`
But what if you now want to prove `β i, is_open (U i)` so you can feed it
into `hS` as an input? You can put
`specialize hS _`
and then that goal will pop out. Unfortunately it pops out _under_ the
current goal! You can swap two goals with the `swap` tactic though :-)
### `change`
If your goal is `β’ P` and `P` is definitionally equal to `Q`, then you
can write `change Q` and the goal will change to `Q`. Sometimes useful
because rewriting works up to syntactic equality, which is stronger
than definitional equality.
### `rwa`
`rwa h` just means `rw h, assumption`
### `contradiction`
If you have `h1 : P` and `h2 : Β¬ P` as hypotheses, then you can prove any goal with
the `contradiction` tactic, which just does `exfalso, apply h2, exact h1`.
### `set`
Note : The `set` tactic is totally unrelated to the `set X` type of subsets of `X`!
The `set` tactic can be used to define things. For example
`set T := f '' S with hT_def,` will define `T` to be `f '' S`
and will also define `hT_def : T = f '' S`.
-/
#check is_open_compl_iff
lemma image_compact_of_compact (hf : continuous f) (S : set X) (hS : is_compact S) :
is_compact (f '' S) :=
begin
-- proof I recommend:
-- (1) cover f''s with opens. Want finite subcover
-- (2) pull back
-- (3) finite subcover
-- (4) push forward
-- start by changing `is_compact` to something we can work with.
rw compact_iff_finite_subcover' at hS β’,
-- Define `T` to be `f '' S` -- why not?
set T := f '' S with hT_def,
-- Now `T = f '' S` and `hT_def` tells us that.
-- Note that `set T := ...` is about the *tactic* `set`.
-- OK let's go.
-- Say we have a cover of `f '' S` by opens `U i` for `i : ΞΉ`.
intro ΞΉ,
intro U,
intro hU,
intro hcoverU,
-- Define `V i` to be the pullback of `U i`.
set V : ΞΉ β set X := Ξ» i, f β»ΒΉ' (U i) with hV_def,
-- Let's check that the V's are open and cover `S`.
specialize hS V _, swap,
-- first let's check they're open.
{ intro i,
rw hV_def, dsimp only,
apply continuous.is_open_preimage hf _ (hU i) },
specialize hS _, swap,
-- Now let's check they cover `S`.
{ intros x hx,
have hfx : f x β T,
{ rw hT_def,
rw mem_image,
use x,
use hx },
specialize hcoverU hfx,
rw mem_Union at hcoverU β’,
-- and now we could take everything apart and then re-assemble,
-- but `x β fβ»ΒΉ' U` and `f x β U` are equal by definition!
exact hcoverU -- abuse of definitional equality!
},
-- Now let's take a finite subset `F : set ΞΉ` such that the `V i` for `i β F`
-- cover S.
rcases hS with β¨F, hFfinite, hFβ©,
-- I claim that this `F` gives us the finite subcover.
use F,
-- It's certainly finite.
use hFfinite,
-- Let's check it covers. Say `y : Y` is in `T`.
rintros y β¨x, hxs, rflβ©,
-- then `y = f x` for some `x : X`, and `x β S`.
rw subset_def at hF, -- this is definition so this line can be deleted.
-- then x is in the union of the `V i` for `i β F`.
specialize hF x hxs,
-- so it's in one of the `V i`
rw mem_bUnion_iff at hF β’,
-- and now we could take everything apart and then re-assemble,
-- but `x β fβ»ΒΉ' U` and `f x β U` are equal by definition!
exact hF,
end
/-
## Closed subset of a compact is compact.
This is a little trickier because given `U : ΞΉ β set X` we need
to produce `V : option ΞΉ β set X` at some point in the below
proof. We can make it using `option.rec`.
If `S` is compact and `C` is closed then we want to prove `S β© C` is compact.
Start with `rw compact_iff_finite_subcover' at hS β’,`.
Then given a cover `U : ΞΉ β set X`, define
`V : option ΞΉ β set X` like this:
`let V : option ΞΉ β set X := Ξ» x, option.rec CαΆ U x,`
For finiteness, if you have `F : set (option ΞΉ)` and `hF : F.finite`,
and you want `(some β»ΒΉ' F).finite`, then you can apply
`set.finite.preimage` and use `option.some_inj` to deal with the
injectivity.
-/
lemma closed_of_compact (S : set X) (hS : is_compact S)
(C : set X) (hC : is_closed C) : is_compact (S β© C) :=
begin
rw compact_iff_finite_subcover' at hS β’,
-- take a cover of S β© C by a family U of opens indexed by ΞΉ
intros ΞΉ U hUopen hSCcover,
-- Now let's define a family V of opens by V = U plus
-- one extra set, CαΆ. This family is indexed by `option ΞΉ`.
let V : option ΞΉ β set X := Ξ» x, option.rec CαΆ U x,
-- I claim that V is an open cover of the compact set S.
specialize hS V _, swap,
{ -- First let's check that V i is always open
intros i,
-- two cases
cases i with i,
{ -- CαΆ is open
change is_open CαΆ,
rwa is_open_compl_iff },
{ -- U i are open
change is_open (U i),
apply hUopen } },
specialize hS _, swap,
{ -- Now I claim they cover S
intro x,
intro hxS,
-- if x β S then it's either in C
by_cases hxC : x β C,
{ -- so it's hit by some U i
rw subset_def at hSCcover,
specialize hSCcover x β¨hxS, hxCβ©,
rw mem_Union at β’ hSCcover,
cases hSCcover with i hi,
use (some i),
exact hi },
{ -- or it's not
rw mem_Union,
-- in which case it's in CαΆ
use none } },
-- So the V's have a finite subcover.
rcases hS with β¨F, hFfinite, hFcoverβ©,
-- I claim that those V's which are U's are a finite subcover of S β© C
use (some : ΞΉ β option ΞΉ) β»ΒΉ' F,
split,
{ -- This cover is finite
apply finite.preimage _ hFfinite,
intros i hi j hj,
exact option.some_inj.mp },
-- and if x β S β© C,
rintros x β¨hxS, hxCβ©,
rw subset_def at hFcover,
specialize hFcover x hxS,
-- then it's in S
rw mem_bUnion_iff at hFcover β’,
-- so it's covered by the V's
rcases hFcover with β¨i, hiF, hxiβ©,
-- and it's not in CαΆ
cases i with i,
{ contradiction },
-- so it's in one of the U's.
{ use [i, hiF, hxi] },
end
|
f9faa184a048107263f634e18ab0c4ec545ade8a | cbb817439c51008d66b37ce6b1964fea61434d35 | /theorem-proving-in-lean/src/chap_10.lean | 769f05151e7763d4cd6195bdf812f5b9b4d9388e | [] | no_license | tomhoule/theorem-proving-in-lean-exercises | a07f99d4f6b41ce003e8a0274c7bc46359fa62b2 | 60ccc71b8a6df6924e7cc90aab713b804f78da9f | refs/heads/master | 1,663,582,321,828 | 1,590,352,467,000 | 1,590,352,476,000 | 257,107,936 | 3 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 519 | lean | variables a b c d e : Prop
variable p : Prop β Prop
theorem thmβ (h : a β b) (hβ : p a) : p b :=
propext h βΈ hβ
theorem thm2_propext_equivalence : ((a β b) β p a β p b) β ((a β b) β a = b) :=
begin
apply iff.intro,
{ intros hthm2 hequiv,
exact propext hequiv }, -- is there another way?
intros hpropext hequiv hpa,
have : a = b, from hpropext hequiv,
exact eq.rec hpa this
end
#print axioms thmβ
#print axioms thm2_propext_equivalence
#check @equivalence
|
52800b04fbc8893bdf52b2c5acedc3e88ec32dca | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/topology/opens.lean | 508e4d766810a8de34e8bd671c3b470656d8de5b | [
"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 | 8,256 | lean | /-
Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes HΓΆlzl, Mario Carneiro, Floris van Doorn
-/
import topology.bases
import topology.homeomorph
/-!
# Open sets
## Summary
We define the subtype of open sets in a topological space.
## Main Definitions
- `opens Ξ±` is the type of open subsets of a topological space `Ξ±`.
- `open_nhds_of x` is the type of open subsets of a topological space `Ξ±` containing `x : Ξ±`.
-
-/
open filter set
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*}
[topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³]
namespace topological_space
variable (Ξ±)
/-- The type of open subsets of a topological space. -/
def opens := {s : set Ξ± // is_open s}
variable {Ξ±}
namespace opens
instance : has_coe (opens Ξ±) (set Ξ±) := { coe := subtype.val }
lemma val_eq_coe (U : opens Ξ±) : U.1 = βU := rfl
/-- the coercion `opens Ξ± β set Ξ±` applied to a pair is the same as taking the first component -/
lemma coe_mk {Ξ± : Type*} [topological_space Ξ±] {U : set Ξ±} {hU : is_open U} :
β(β¨U, hUβ© : opens Ξ±) = U := rfl
instance : has_subset (opens Ξ±) :=
{ subset := Ξ» U V, (U : set Ξ±) β V }
instance : has_mem Ξ± (opens Ξ±) :=
{ mem := Ξ» a U, a β (U : set Ξ±) }
@[simp] lemma subset_coe {U V : opens Ξ±} : ((U : set Ξ±) β (V : set Ξ±)) = (U β V) := rfl
@[simp] lemma mem_coe {x : Ξ±} {U : opens Ξ±} : (x β (U : set Ξ±)) = (x β U) := rfl
@[ext] lemma ext {U V : opens Ξ±} (h : (U : set Ξ±) = V) : U = V := subtype.ext_iff.mpr h
@[ext] lemma ext_iff {U V : opens Ξ±} : (U : set Ξ±) = V β U = V :=
β¨opens.ext, congr_arg coeβ©
instance : partial_order (opens Ξ±) := subtype.partial_order _
/-- The interior of a set, as an element of `opens`. -/
def interior (s : set Ξ±) : opens Ξ± := β¨interior s, is_open_interiorβ©
lemma gc : galois_connection (coe : opens Ξ± β set Ξ±) interior :=
Ξ» U s, β¨Ξ» h, interior_maximal h U.property, Ξ» h, le_trans h interior_subsetβ©
/-- The galois insertion between sets and opens, but ordered by reverse inclusion. -/
def gi : @galois_insertion (order_dual (set Ξ±)) (order_dual (opens Ξ±)) _ _ interior subtype.val :=
{ choice := Ξ» s hs, β¨s, interior_eq_iff_open.mp $ le_antisymm interior_subset hsβ©,
gc := gc.dual,
le_l_u := Ξ» _, interior_subset,
choice_eq := Ξ» s hs, le_antisymm interior_subset hs }
@[simp] lemma gi_choice_val {s : order_dual (set Ξ±)} {hs} : (gi.choice s hs).val = s := rfl
instance : complete_lattice (opens Ξ±) :=
complete_lattice.copy
(@order_dual.complete_lattice _ (galois_insertion.lift_complete_lattice (@gi Ξ± _)))
/- le -/ (Ξ» U V, U β V) rfl
/- top -/ β¨set.univ, is_open_univβ© (subtype.ext_iff_val.mpr interior_univ.symm)
/- bot -/ β¨β
, is_open_emptyβ© rfl
/- sup -/ (Ξ» U V, β¨βU βͺ βV, is_open.union U.2 V.2β©) rfl
/- inf -/ (Ξ» U V, β¨βU β© βV, is_open.inter U.2 V.2β©)
begin
funext,
apply subtype.ext_iff_val.mpr,
exact (is_open.inter U.2 V.2).interior_eq.symm,
end
/- Sup -/ (Ξ» Us, β¨ββ (coe '' Us), is_open_sUnion $ Ξ» U hU,
by { rcases hU with β¨β¨V, hVβ©, h, h'β©, dsimp at h', subst h', exact hV}β©)
begin
funext,
apply subtype.ext_iff_val.mpr,
simp [Sup_range],
refl,
end
/- Inf -/ _ rfl
lemma le_def {U V : opens Ξ±} : U β€ V β (U : set Ξ±) β€ (V : set Ξ±) :=
by refl
@[simp] lemma mk_inf_mk {U V : set Ξ±} {hU : is_open U} {hV : is_open V} :
(β¨U, hUβ© β β¨V, hVβ© : opens Ξ±) = β¨U β V, is_open.inter hU hVβ© := rfl
@[simp,norm_cast] lemma coe_inf {U V : opens Ξ±} :
((U β V : opens Ξ±) : set Ξ±) = (U : set Ξ±) β (V : set Ξ±) := rfl
instance : has_inter (opens Ξ±) := β¨Ξ» U V, U β Vβ©
instance : has_union (opens Ξ±) := β¨Ξ» U V, U β Vβ©
instance : has_emptyc (opens Ξ±) := β¨β₯β©
instance : inhabited (opens Ξ±) := β¨β
β©
@[simp] lemma inter_eq (U V : opens Ξ±) : U β© V = U β V := rfl
@[simp] lemma union_eq (U V : opens Ξ±) : U βͺ V = U β V := rfl
@[simp] lemma empty_eq : (β
: opens Ξ±) = β₯ := rfl
@[simp] lemma Sup_s {Us : set (opens Ξ±)} : β(Sup Us) = ββ ((coe : _ β set Ξ±) '' Us) :=
by { rw [(@gc Ξ± _).l_Sup, set.sUnion_image], refl }
lemma supr_def {ΞΉ} (s : ΞΉ β opens Ξ±) : (β¨ i, s i) = β¨β i, s i, is_open_Union $ Ξ» i, (s i).2β© :=
by { ext, simp only [supr, opens.Sup_s, sUnion_image, bUnion_range], refl }
@[simp] lemma supr_mk {ΞΉ} (s : ΞΉ β set Ξ±) (h : Ξ i, is_open (s i)) :
(β¨ i, β¨s i, h iβ© : opens Ξ±) = β¨β i, s i, is_open_Union hβ© :=
by { rw supr_def, simp }
@[simp] lemma supr_s {ΞΉ} (s : ΞΉ β opens Ξ±) : ((β¨ i, s i : opens Ξ±) : set Ξ±) = β i, s i :=
by simp [supr_def]
@[simp] theorem mem_supr {ΞΉ} {x : Ξ±} {s : ΞΉ β opens Ξ±} : x β supr s β β i, x β s i :=
by { rw [βmem_coe], simp, }
@[simp] lemma mem_Sup {Us : set (opens Ξ±)} {x : Ξ±} : x β Sup Us β β u β Us, x β u :=
by simp_rw [Sup_eq_supr, mem_supr]
lemma open_embedding_of_le {U V : opens Ξ±} (i : U β€ V) :
open_embedding (set.inclusion i) :=
{ inj := set.inclusion_injective i,
induced := (@induced_compose _ _ _ _ (set.inclusion i) coe).symm,
open_range :=
begin
rw set.range_inclusion i,
exact U.property.preimage continuous_subtype_val
end, }
def is_basis (B : set (opens Ξ±)) : Prop := is_topological_basis ((coe : _ β set Ξ±) '' B)
lemma is_basis_iff_nbhd {B : set (opens Ξ±)} :
is_basis B β β {U : opens Ξ±} {x}, x β U β β U' β B, x β U' β§ U' β U :=
begin
split; intro h,
{ rintros β¨sU, hUβ© x hx,
rcases h.mem_nhds_iff.mp (is_open.mem_nhds hU hx)
with β¨sV, β¨β¨V, Hβ, Hββ©, hsVβ©β©,
refine β¨V, Hβ, _β©,
cases V, dsimp at Hβ, subst Hβ, exact hsV },
{ refine is_topological_basis_of_open_of_nhds _ _,
{ rintros sU β¨U, β¨Hβ, Hββ©β©, subst Hβ, exact U.property },
{ intros x sU hx hsU,
rcases @h (β¨sU, hsUβ© : opens Ξ±) x hx with β¨V, hV, Hβ©,
exact β¨V, β¨V, hV, rflβ©, Hβ© } }
end
lemma is_basis_iff_cover {B : set (opens Ξ±)} :
is_basis B β β U : opens Ξ±, β Us β B, U = Sup Us :=
begin
split,
{ intros hB U,
refine β¨{V : opens Ξ± | V β B β§ V β U}, Ξ» U hU, hU.left, _β©,
apply ext,
rw [Sup_s, hB.open_eq_sUnion' U.prop],
simp_rw [sUnion_image, sUnion_eq_bUnion, Union, supr_and, supr_image],
refl },
{ intro h,
rw is_basis_iff_nbhd,
intros U x hx,
rcases h U with β¨Us, hUs, rflβ©,
rcases mem_Sup.1 hx with β¨U, Us, xUβ©,
exact β¨U, hUs Us, xU, le_Sup Usβ© }
end
/-- The preimage of an open set, as an open set. -/
def comap {f : Ξ± β Ξ²} (hf : continuous f) (V : opens Ξ²) : opens Ξ± :=
β¨f β»ΒΉ' V.1, V.2.preimage hfβ©
@[simp] lemma comap_id (U : opens Ξ±) : U.comap continuous_id = U := by { ext, refl }
lemma comap_mono {f : Ξ± β Ξ²} (hf : continuous f) {V W : opens Ξ²} (hVW : V β W) :
V.comap hf β W.comap hf :=
Ξ» _ h, hVW h
@[simp] lemma coe_comap {f : Ξ± β Ξ²} (hf : continuous f) (U : opens Ξ²) :
β(U.comap hf) = f β»ΒΉ' U := rfl
@[simp] lemma comap_val {f : Ξ± β Ξ²} (hf : continuous f) (U : opens Ξ²) :
(U.comap hf).1 = f β»ΒΉ' U := rfl
protected lemma comap_comp {g : Ξ² β Ξ³} {f : Ξ± β Ξ²} (hg : continuous g) (hf : continuous f)
(U : opens Ξ³) : U.comap (hg.comp hf) = (U.comap hg).comap hf :=
by { ext1, simp only [coe_comap, preimage_preimage] }
/-- A homeomorphism induces an equivalence on open sets, by taking comaps. -/
@[simp] protected def equiv (f : Ξ± ββ Ξ²) : opens Ξ± β opens Ξ² :=
{ to_fun := opens.comap f.symm.continuous,
inv_fun := opens.comap f.continuous,
left_inv := by { intro U, ext1,
simp only [coe_comap, β preimage_comp, f.symm_comp_self, preimage_id] },
right_inv := by { intro U, ext1,
simp only [coe_comap, β preimage_comp, f.self_comp_symm, preimage_id] } }
end opens
/-- The open neighborhoods of a point. See also `opens` or `nhds`. -/
def open_nhds_of (x : Ξ±) : Type* := { s : set Ξ± // is_open s β§ x β s }
instance open_nhds_of.inhabited {Ξ± : Type*} [topological_space Ξ±] (x : Ξ±) :
inhabited (open_nhds_of x) := β¨β¨set.univ, is_open_univ, set.mem_univ _β©β©
end topological_space
|
c1a5539225ac472e07bfc9dcf00835f50d7f43e8 | 737dc4b96c97368cb66b925eeea3ab633ec3d702 | /src/Std/Data/HashSet.lean | 5d6e4617135d1361ca6dd0895f1fd84ef828cac9 | [
"Apache-2.0"
] | permissive | Bioye97/lean4 | 1ace34638efd9913dc5991443777b01a08983289 | bc3900cbb9adda83eed7e6affeaade7cfd07716d | refs/heads/master | 1,690,589,820,211 | 1,631,051,000,000 | 1,631,067,598,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,198 | 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 Std
universe u v w
def HashSetBucket (Ξ± : Type u) :=
{ b : Array (List Ξ±) // b.size > 0 }
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]; exact data.property β©
structure HashSetImp (Ξ± : Type u) where
size : Nat
buckets : HashSetBucket Ξ±
def mkHashSetImp {Ξ± : Type u} (nbuckets := 8) : HashSetImp Ξ± :=
let n := if nbuckets = 0 then 8 else nbuckets
{ size := 0,
buckets :=
β¨ mkArray n [],
by rw [Array.size_mkArray]; cases nbuckets; decide; apply Nat.zero_lt_succ β© }
namespace HashSetImp
variable {Ξ± : Type u}
def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } :=
β¨u % n, USize.modn_lt _ hβ©
@[inline] def reinsertAux (hashFn : Ξ± β UInt64) (data : HashSetBucket Ξ±) (a : Ξ±) : HashSetBucket Ξ± :=
let β¨i, hβ© := mkIdx data.property (hashFn a |>.toUSize)
data.update i (a :: data.val.uget i h) 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
def find? [BEq Ξ±] [Hashable Ξ±] (m : HashSetImp Ξ±) (a : Ξ±) : Option Ξ± :=
match m with
| β¨_, bucketsβ© =>
let β¨i, hβ© := mkIdx buckets.property (hash a |>.toUSize)
(buckets.val.uget i h).find? (fun a' => a == a')
def contains [BEq Ξ±] [Hashable Ξ±] (m : HashSetImp Ξ±) (a : Ξ±) : Bool :=
match m with
| β¨_, bucketsβ© =>
let β¨i, hβ© := mkIdx buckets.property (hash a |>.toUSize)
(buckets.val.uget i h).contains a
-- TODO: remove `partial` by using well-founded recursion
partial 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
def expand [Hashable Ξ±] (size : Nat) (buckets : HashSetBucket Ξ±) : HashSetImp Ξ± :=
let nbuckets := buckets.val.size * 2
have : nbuckets > 0 := Nat.mul_pos buckets.property (by decide)
let new_buckets : HashSetBucket Ξ± := β¨mkArray nbuckets [], by rw [Array.size_mkArray]; assumptionβ©
{ size := size,
buckets := moveEntries 0 buckets.val new_buckets }
def insert [BEq Ξ±] [Hashable Ξ±] (m : HashSetImp Ξ±) (a : Ξ±) : HashSetImp Ξ± :=
match m with
| β¨size, bucketsβ© =>
let β¨i, hβ© := mkIdx buckets.property (hash a |>.toUSize)
let bkt := buckets.val.uget i h
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 buckets.property (hash a |>.toUSize)
let bkt := buckets.val.uget i h
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 Ξ±] (nbuckets := 8) : HashSet Ξ± :=
β¨ mkHashSetImp nbuckets, WellFormed.mkWff nbuckets β©
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 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
end HashSet
end Std
|
dd4e2d76680a82f9db32608a0a434521e7889ebd | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/finset/prod.lean | d7f4856138c56cb7c0ea243a3284b4d50c58345e | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,198 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes HΓΆlzl, Mario Carneiro, Oliver Nash
-/
import data.finset.basic
/-!
# Finsets in product types
This file defines finset constructions on the product type `Ξ± Γ Ξ²`. Beware not to confuse with the
`finset.prod` operation which computes the multiplicative product.
## Main declarations
* `finset.product`: Turns `s : finset Ξ±`, `t : finset Ξ²` into their product in `finset (Ξ± Γ Ξ²)`.
* `finset.diag`: For `s : finset Ξ±`, `s.diag` is the `finset (Ξ± Γ Ξ±)` of pairs `(a, a)` with
`a β s`.
* `finset.off_diag`: For `s : finset Ξ±`, `s.off_diag` is the `finset (Ξ± Γ Ξ±)` of pairs `(a, b)` with
`a, b β s` and `a β b`.
-/
open multiset
variables {Ξ± Ξ² Ξ³ : Type*}
namespace finset
/-! ### prod -/
section prod
variables {s s' : finset Ξ±} {t t' : finset Ξ²}
/-- `product s t` is the set of pairs `(a, b)` such that `a β s` and `b β t`. -/
protected def product (s : finset Ξ±) (t : finset Ξ²) : finset (Ξ± Γ Ξ²) := β¨_, nodup_product s.2 t.2β©
@[simp] lemma product_val : (s.product t).1 = s.1.product t.1 := rfl
@[simp] lemma mem_product {p : Ξ± Γ Ξ²} : p β s.product t β p.1 β s β§ p.2 β t := mem_product
lemma subset_product [decidable_eq Ξ±] [decidable_eq Ξ²] {s : finset (Ξ± Γ Ξ²)} :
s β (s.image prod.fst).product (s.image prod.snd) :=
Ξ» p hp, mem_product.2 β¨mem_image_of_mem _ hp, mem_image_of_mem _ hpβ©
lemma product_subset_product (hs : s β s') (ht : t β t') : s.product t β s'.product t' :=
Ξ» β¨x,yβ© h, mem_product.2 β¨hs (mem_product.1 h).1, ht (mem_product.1 h).2β©
lemma product_subset_product_left (hs : s β s') : s.product t β s'.product t :=
product_subset_product hs (subset.refl _)
lemma product_subset_product_right (ht : t β t') : s.product t β s.product t' :=
product_subset_product (subset.refl _) ht
lemma product_eq_bUnion [decidable_eq Ξ±] [decidable_eq Ξ²] (s : finset Ξ±) (t : finset Ξ²) :
s.product t = s.bUnion (Ξ»a, t.image $ Ξ»b, (a, b)) :=
ext $ Ξ» β¨x, yβ©, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff,
and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left]
@[simp] lemma product_bUnion [decidable_eq Ξ³] (s : finset Ξ±) (t : finset Ξ²) (f : Ξ± Γ Ξ² β finset Ξ³) :
(s.product t).bUnion f = s.bUnion (Ξ» a, t.bUnion (Ξ» b, f (a, b))) :=
by { classical, simp_rw [product_eq_bUnion, bUnion_bUnion, image_bUnion] }
@[simp] lemma card_product (s : finset Ξ±) (t : finset Ξ²) : card (s.product t) = card s * card t :=
multiset.card_product _ _
lemma filter_product (p : Ξ± β Prop) (q : Ξ² β Prop) [decidable_pred p] [decidable_pred q] :
(s.product t).filter (Ξ» (x : Ξ± Γ Ξ²), p x.1 β§ q x.2) = (s.filter p).product (t.filter q) :=
by { ext β¨a, bβ©, simp only [mem_filter, mem_product], finish }
lemma filter_product_card (s : finset Ξ±) (t : finset Ξ²)
(p : Ξ± β Prop) (q : Ξ² β Prop) [decidable_pred p] [decidable_pred q] :
((s.product t).filter (Ξ» (x : Ξ± Γ Ξ²), p x.1 β q x.2)).card =
(s.filter p).card * (t.filter q).card + (s.filter (not β p)).card * (t.filter (not β q)).card :=
begin
classical,
rw [β card_product, β card_product, β filter_product, β filter_product, β card_union_eq],
{ apply congr_arg, ext β¨a, bβ©, simp only [filter_union_right, mem_filter, mem_product],
split; intros; finish },
{ rw disjoint_iff, change _ β© _ = β
, ext β¨a, bβ©, rw mem_inter, finish }
end
lemma empty_product (t : finset Ξ²) : (β
: finset Ξ±).product t = β
:= rfl
lemma product_empty (s : finset Ξ±) : s.product (β
: finset Ξ²) = β
:=
eq_empty_of_forall_not_mem (Ξ» x h, (finset.mem_product.1 h).2)
lemma nonempty.product (hs : s.nonempty) (ht : t.nonempty) : (s.product t).nonempty :=
let β¨x, hxβ© := hs, β¨y, hyβ© := ht in β¨(x, y), mem_product.2 β¨hx, hyβ©β©
lemma nonempty.fst (h : (s.product t).nonempty) : s.nonempty :=
let β¨xy, hxyβ© := h in β¨xy.1, (mem_product.1 hxy).1β©
lemma nonempty.snd (h : (s.product t).nonempty) : t.nonempty :=
let β¨xy, hxyβ© := h in β¨xy.2, (mem_product.1 hxy).2β©
@[simp] lemma nonempty_product : (s.product t).nonempty β s.nonempty β§ t.nonempty :=
β¨Ξ» h, β¨h.fst, h.sndβ©, Ξ» h, h.1.product h.2β©
@[simp] lemma union_product [decidable_eq Ξ±] [decidable_eq Ξ²] :
(s βͺ s').product t = s.product t βͺ s'.product t :=
by { ext β¨x, yβ©, simp only [or_and_distrib_right, mem_union, mem_product] }
@[simp] lemma product_union [decidable_eq Ξ±] [decidable_eq Ξ²] :
s.product (t βͺ t') = s.product t βͺ s.product t' :=
by { ext β¨x, yβ©, simp only [and_or_distrib_left, mem_union, mem_product] }
end prod
section diag
variables (s : finset Ξ±) [decidable_eq Ξ±]
/-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for
`a β s`. -/
def diag := (s.product s).filter (Ξ» (a : Ξ± Γ Ξ±), a.fst = a.snd)
/-- Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a β b`
for `a, b β s`. -/
def off_diag := (s.product s).filter (Ξ» (a : Ξ± Γ Ξ±), a.fst β a.snd)
@[simp] lemma mem_diag (x : Ξ± Γ Ξ±) : x β s.diag β x.1 β s β§ x.1 = x.2 :=
by { simp only [diag, mem_filter, mem_product], split; intros; finish }
@[simp] lemma mem_off_diag (x : Ξ± Γ Ξ±) : x β s.off_diag β x.1 β s β§ x.2 β s β§ x.1 β x.2 :=
by { simp only [off_diag, mem_filter, mem_product], split; intros; finish }
@[simp] lemma diag_card : (diag s).card = s.card :=
begin
suffices : diag s = s.image (Ξ» a, (a, a)), { rw this, apply card_image_of_inj_on, finish },
ext β¨aβ, aββ©, rw mem_diag, split; intros; finish,
end
@[simp] lemma off_diag_card : (off_diag s).card = s.card * s.card - s.card :=
begin
suffices : (diag s).card + (off_diag s).card = s.card * s.card,
{ nth_rewrite 2 β s.diag_card, finish },
rw β card_product,
apply filter_card_add_filter_neg_card_eq_card,
end
@[simp] lemma diag_empty : (β
: finset Ξ±).diag = β
:= rfl
@[simp] lemma off_diag_empty : (β
: finset Ξ±).off_diag = β
:= rfl
end diag
end finset
|
e24aad437bee774d8fedb7affffe03f26d61ac4a | 97f752b44fd85ec3f635078a2dd125ddae7a82b6 | /library/data/list/sorted.lean | fafaae626f5089cd88ea5e9cd9d66f20bfb745dd | [
"Apache-2.0"
] | permissive | tectronics/lean | ab977ba6be0fcd46047ddbb3c8e16e7c26710701 | f38af35e0616f89c6e9d7e3eb1d48e47ee666efe | refs/heads/master | 1,532,358,526,384 | 1,456,276,623,000 | 1,456,276,623,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,766 | 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
-/
import data.list.comb data.list.perm
namespace list
variable {A : Type}
variable (R : A β A β Prop)
inductive locally_sorted : list A β Prop :=
| base0 : locally_sorted []
| base : β a, locally_sorted [a]
| step : β {a b l}, R a b β locally_sorted (b::l) β locally_sorted (a::b::l)
inductive hd_rel (a : A) : list A β Prop :=
| base : hd_rel a []
| step : β {b} (l), R a b β hd_rel a (b::l)
inductive sorted : list A β Prop :=
| base : sorted []
| step : β {a : A} {l : list A}, hd_rel R a l β sorted l β sorted (a::l)
variable {R}
lemma hd_rel_inv : β {a b l}, hd_rel R a (b::l) β R a b :=
begin intros a b l h, cases h, assumption end
lemma sorted_inv : β {a l}, sorted R (a::l) β hd_rel R a l β§ sorted R l :=
begin intros a l h, cases h, split, repeat assumption end
lemma sorted.rect_on {P : list A β Type} : β {l}, sorted R l β P [] β (β a l, sorted R l β P l β hd_rel R a l β P (a::l)) β P l
| [] s hβ hβ := hβ
| (a::l) s hβ hβ :=
have hd_rel R a l, from and.left (sorted_inv s),
have sorted R l, from and.right (sorted_inv s),
have P l, from sorted.rect_on this hβ hβ,
hβ a l `sorted R l` `P l` `hd_rel R a l`
lemma sorted_singleton (a : A) : sorted R [a] :=
sorted.step !hd_rel.base !sorted.base
lemma sorted_of_locally_sorted : β {l}, locally_sorted R l β sorted R l
| [] h := !sorted.base
| [a] h := !sorted_singleton
| (a::b::l) (locally_sorted.step hβ hβ) :=
have sorted R (b::l), from sorted_of_locally_sorted hβ,
sorted.step (hd_rel.step _ hβ) this
lemma locally_sorted_of_sorted : β {l}, sorted R l β locally_sorted R l
| [] h := !locally_sorted.base0
| [a] h := !locally_sorted.base
| (a::b::l) (sorted.step (hd_rel.step _ hβ) hβ) :=
have locally_sorted R (b::l), from locally_sorted_of_sorted hβ,
locally_sorted.step hβ this
lemma locally_sorted_eq_sorted : @locally_sorted = @sorted :=
funext (Ξ» A, funext (Ξ» R, funext (Ξ» l, propext (iff.intro sorted_of_locally_sorted locally_sorted_of_sorted))))
variable (R)
inductive strongly_sorted : list A β Prop :=
| base : strongly_sorted []
| step : β {a l}, all l (R a) β strongly_sorted l β strongly_sorted (a::l)
variable {R}
lemma sorted_of_strongly_sorted : β {l}, strongly_sorted R l β sorted R l
| [] h := !sorted.base
| [a] h := !sorted_singleton
| (a::b::l) (strongly_sorted.step hβ hβ) :=
have hd_rel R a (b::l), from hd_rel.step _ (of_all_cons hβ),
have sorted R (b::l), from sorted_of_strongly_sorted hβ,
sorted.step `hd_rel R a (b::l)` `sorted R (b::l)`
lemma sorted_extends (trans : transitive R) : β {a l}, sorted R (a::l) β all l (R a)
| a [] h := !all_nil
| a (b::l) h :=
have hd_rel R a (b::l), from and.left (sorted_inv h),
have R a b, from hd_rel_inv this,
have all l (R b), from sorted_extends (and.right (sorted_inv h)),
all_of_forall (take x, suppose x β b::l,
or.elim (eq_or_mem_of_mem_cons this)
(suppose x = b, by+ subst x; assumption)
(suppose x β l,
have R b x, from of_mem_of_all this `all l (R b)`,
trans `R a b` `R b x`))
theorem strongly_sorted_of_sorted_of_transitive (trans : transitive R) : β {l}, sorted R l β strongly_sorted R l
| [] h := !strongly_sorted.base
| (a::l) h :=
have sorted R l, from and.right (sorted_inv h),
have strongly_sorted R l, from strongly_sorted_of_sorted_of_transitive this,
have all l (R a), from sorted_extends trans h,
strongly_sorted.step `all l (R a)` `strongly_sorted R l`
open perm
lemma eq_of_sorted_of_perm (tr : transitive R) (anti : anti_symmetric R) : β {lβ lβ : list A}, lβ ~ lβ β sorted R lβ β sorted R lβ β lβ = lβ
| [] [] hβ hβ hβ := rfl
| (aβ::lβ) [] hβ hβ hβ := absurd (perm.symm hβ) !not_perm_nil_cons
| [] (aβ::lβ) hβ hβ hβ := absurd hβ !not_perm_nil_cons
| (a::lβ) lβ hβ hβ hβ :=
have aux : β {t}, lβ = a::t β a::lβ = lβ, from
take t, suppose lβ = a::t,
have lβ ~ t, by rewrite [this at hβ]; apply perm_cons_inv hβ,
have sorted R lβ, from and.right (sorted_inv hβ),
have sorted R t, by rewrite [`lβ = a::t` at hβ]; exact and.right (sorted_inv hβ),
assert lβ = t, from eq_of_sorted_of_perm `lβ ~ t` `sorted R lβ` `sorted R t`,
show a :: lβ = lβ, by rewrite [`lβ = a::t`, this],
have a β lβ, from mem_perm hβ !mem_cons,
obtain s t (eβ : lβ = s ++ (a::t)), from mem_split this,
begin
cases s with b s,
{ have lβ = a::t, by exact eβ,
exact aux this },
{ have eβ : lβ = b::(s++(a::t)), by exact eβ,
have b β lβ, by rewrite eβ; apply mem_cons,
have hallβ : all (s++(a::t)) (R b), begin rewrite [eβ at hβ], apply sorted_extends tr hβ end,
have a β s++(a::t), from mem_append_right _ !mem_cons,
have R b a, from of_mem_of_all this hallβ,
have b β a::lβ, from mem_perm (perm.symm hβ) `b β lβ`,
have hallβ : all lβ (R a), from sorted_extends tr hβ,
apply or.elim (eq_or_mem_of_mem_cons `b β a::lβ`),
suppose b = a, by rewrite this at eβ; exact aux eβ,
suppose b β lβ,
have R a b, from of_mem_of_all this hallβ,
assert b = a, from anti `R b a` `R a b`,
by rewrite this at eβ; exact aux eβ }
end
end list
|
081ca5d67626bb2270cda1595e709978de966297 | ff5230333a701471f46c57e8c115a073ebaaa448 | /tests/lean/type_context.lean | c2cc9c56dbbb3a5d3b2f7270d21e0e635e19c470 | [
"Apache-2.0"
] | permissive | stanford-cs242/lean | f81721d2b5d00bc175f2e58c57b710d465e6c858 | 7bd861261f4a37326dcf8d7a17f1f1f330e4548c | refs/heads/master | 1,600,957,431,849 | 1,576,465,093,000 | 1,576,465,093,000 | 225,779,423 | 0 | 3 | Apache-2.0 | 1,575,433,936,000 | 1,575,433,935,000 | null | UTF-8 | Lean | false | false | 8,639 | lean | open tactic local_context tactic.unsafe tactic.unsafe.type_context
run_cmd do
n β type_context.run (pure "hello type_context"),
trace n
run_cmd do
n β type_context.run (do x β pure "hello", pure x),
trace n
run_cmd do
n β type_context.run $ (Ξ» x, x) <$> pure "hello",
trace n
run_cmd do -- should fail
f : β β type_context.run (type_context.fail $ "I failed"),
trace f
run_cmd do
m β tactic.mk_meta_var `(nat),
e β pure $ `([4,3,2]),
b β type_context.run (type_context.unify m e),
trace b, -- should be ff because the types are not equal
type_context.run (is_assigned m) >>= trace -- should be ff
run_cmd do
m β tactic.mk_meta_var `(nat),
r : nat β type_context.run (do unify m `(4), type_context.failure) <|> pure 5,
m β instantiate_mvars m,
trace m -- should be "?m_1"
/- What happens when you assign an mvar to itself?
It shouldn't stop you but it shouldn't stack-overflow either. -/
run_cmd do -- should fail with a 'deep recursion'
type β tactic.to_expr ```(nat),
m β tactic.mk_meta_var type,
a β type_context.run (type_context.assign m m *> type_context.get_assignment m),
trace $ to_bool $ a = m, -- should be tt
instantiate_mvars m
run_cmd do -- should fail with a 'deep recursion'
type β tactic.to_expr ```(nat),
m β tactic.mk_meta_var type,
mβ β to_expr ```(%%m + %%m),
type_context.run (type_context.assign m mβ),
instantiate_mvars m
/- What happens when you assign a pair of mvars to each other? -/
run_cmd do -- should fail with a 'deep recursion'
type β tactic.to_expr ```(nat),
mβ β tactic.mk_meta_var type,
mβ β tactic.mk_meta_var type,
type_context.run (type_context.assign mβ mβ),
type_context.run (type_context.assign mβ mβ),
trace mβ,
trace mβ
run_cmd do
x : pexpr β resolve_name `eq_mul_inv_of_mul_eq,
x β to_expr x,
y β infer_type x,
(t,us,es) β type_context.run $ type_context.to_tmp_mvars y,
trace t,
trace us,
trace es,
tactic.apply `(trivial), set_goals []
/- Some examples of rewriting tactics using type_context. -/
meta def my_infer : expr β tactic expr
| e := type_context.run $ type_context.infer e
run_cmd my_infer `(4 : nat) >>= tactic.trace
meta def my_intro_core : expr β type_context (expr Γ expr) | goal := do
target β infer goal,
match target with
|(expr.pi n bi y b) := do
lctx β get_context goal,
some (h,lctx) β pure $ local_context.mk_local n y bi lctx,
b β pure $ expr.instantiate_var b h,
goal' β mk_mvar name.anonymous b (some lctx),
assign goal $ expr.lam n bi y $ expr.mk_delayed_abstraction goal' [expr.local_uniq_name h],
pure (h, goal')
|_ := type_context.failure
end
open tactic
meta def my_intro : name β tactic expr | n := do
goal :: rest β get_goals,
(h, goal') β type_context.run $ my_intro_core goal,
set_goals $ goal' :: rest,
pure h
lemma my_intro_test : β (x : β), x = x := begin
my_intro `hello,
refl
end
#print my_intro_test
open native
meta instance level.has_lt : has_lt level := β¨Ξ» x y, level.lt x yβ©
meta instance level.dec_lt : decidable_rel (level.has_lt.lt) := by apply_instance
meta def my_mk_pattern (ls : list level) (es : list expr) (target : expr)
(ous : list level) (os : list expr) : tactic pattern
:= type_context.run $ do
(t, extra_ls, extra_es) β type_context.to_tmp_mvars target,
level2meta : list (name Γ level) β ls.mfoldl (Ξ» acc l, do
match l with
| level.param n :=
pure $ (prod.mk n $ type_context.level.mk_tmp_mvar $ acc.length + extra_ls.length) :: acc
| _ := type_context.failure end
) [],
let convert_level := Ξ» l, level.instantiate l level2meta,
expr2meta : rb_map expr expr β es.mfoldl (Ξ» acc e, do
e_type β infer e,
e_type β pure $ expr.replace e_type (Ξ» x _, rb_map.find acc x),
e_type β pure $ expr.instantiate_univ_params e_type level2meta,
i β pure $ rb_map.size acc + extra_es.length,
m β pure $ type_context.mk_tmp_mvar i e_type,
pure $ rb_map.insert acc e m
) $ rb_map.mk _ _,
let convert_expr := Ξ» x, expr.instantiate_univ_params (expr.replace x (Ξ» x _, rb_map.find expr2meta x)) level2meta,
uoutput β pure $ ous.map convert_level,
output β pure $ os.map convert_expr,
t β pure $ convert_expr target,
pure $ tactic.pattern.mk t uoutput output (extra_ls.length + level2meta.length) (extra_es.length + expr2meta.size)
/-- Reimplementation of tactic.match_pattern -/
meta def my_match_pattern_core : tactic.pattern β expr β type_context (list level Γ list expr)
| β¨target, uoutput, moutput, nuvars, nmvarsβ© e :=
-- open a temporary metavariable scope.
tmp_mode nuvars nmvars (do
-- match target with e.
result β type_context.unify target e,
if (Β¬ result) then type_context.fail "failed to unify" else do
-- fail when a tmp is not assigned
list.mmap (level.tmp_get_assignment) $ list.range nuvars,
list.mmap (tmp_get_assignment) $ list.range nmvars,
-- instantiate the temporary metavariables.
uo β list.mmap level.instantiate_mvars $ uoutput,
mo β list.mmap instantiate_mvars $ moutput,
pure (uo, mo)
)
meta def my_match_pattern : pattern β expr β tactic (list level Γ list expr)
|p e := do type_context.run $ my_match_pattern_core p e
/- Make a pattern for testing. -/
meta def my_pat := do
T β to_expr ```(Type),
Ξ± β pure $ expr.local_const `Ξ± `Ξ± binder_info.implicit T,
h β pure $ expr.local_const `h `h binder_info.default Ξ±,
LT β to_expr ```(list %%Ξ±),
t β pure $ expr.local_const `t `t binder_info.default LT,
target β to_expr ```(@list.cons %%Ξ± %%h %%t),
my_mk_pattern [] [Ξ±,h,t] target [] [h,t]
run_cmd do
p β my_pat,
trace $ p.target
run_cmd do -- ([], [3, [4, 5]])
p β my_pat,
res β my_match_pattern p `([3,4,5]),
tactic.trace res
run_cmd do -- should fail since doesn't match the pattern.
p β my_pat,
e β to_expr ```(list.empty),
res β my_match_pattern p `([] : list β),
tactic.trace res
run_cmd do
type_context.run (do
lc0 β type_context.get_local_context,
type_context.push_local `hi `(nat),
type_context.push_local `there `(nat),
lc1 β type_context.get_local_context,
type_context.pop_local,
lc2 β type_context.get_local_context,
type_context.trace lc0,
type_context.trace lc1,
type_context.trace lc2,
pure ()
)
run_cmd do
type_context.run (do
hi β mk_mvar `hi `(nat),
some hello β type_context.try (do
type_context.is_declared hi >>= guardb,
type_context.is_assigned hi >>= (guardb β bnot),
type_context.assign hi `(4),
type_context.is_assigned hi >>= guardb,
hello β mk_mvar `hello `(nat),
type_context.is_declared hello >>= guardb,
pure hello
),
type_context.is_declared hi >>= guardb,
type_context.is_declared hello >>= guardb,
pure ()
)
run_cmd do
type_context.run (do
hi β mk_mvar `hi `(nat),
none : option unit β type_context.try (do
type_context.assign hi `(4),
push_local `H `(nat),
failure
),
type_context.is_declared hi >>= guardb,
type_context.is_assigned hi >>= (guardb β bnot),
-- [note] the local variable stack should escape the try block.
type_context.get_local_context >>= (Ξ» l, guardb $ not $ list.empty $ local_context.to_list $ l),
pure ()
)
-- tactic.get_fun_info and unsafe.type_context.get_fun_info should do the same thing.
run_cmd do
f β tactic.resolve_name `has_bind.and_then >>= pure β pexpr.mk_explicit >>= to_expr,
fi β tactic.get_fun_info f,
fi β to_string <$> tactic.pp fi,
fiβ β type_context.run (unsafe.type_context.get_fun_info f),
fiβ β to_string <$> tactic.pp fiβ,
guard (fi = fiβ)
open tactic.unsafe.type_context
-- in_tmp_mode should work
run_cmd do
type_context.run (do
in_tmp_mode >>= guardb β bnot,
type_context.tmp_mode 0 3 (do
in_tmp_mode >>= guardb,
tmp_mode 0 2 (do
in_tmp_mode >>= guardb
),
in_tmp_mode >>= guardb
),
in_tmp_mode >>= guardb β bnot
) |
dc5ea5763292bf766bab62631470448178b9c438 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/order/absolute_value.lean | ab4188ad4df843db2bc22e6196b94d3613478688 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 11,462 | lean | /-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Anne Baanen
-/
import algebra.group_with_zero.units.lemmas
import algebra.order.field.defs
import algebra.order.hom.basic
import algebra.ring.regular
/-!
# Absolute values
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines a bundled type of absolute values `absolute_value R S`.
## Main definitions
* `absolute_value R S` is the type of absolute values on `R` mapping to `S`.
* `absolute_value.abs` is the "standard" absolute value on `S`, mapping negative `x` to `-x`.
* `absolute_value.to_monoid_with_zero_hom`: absolute values mapping to a
linear ordered field preserve `0`, `*` and `1`
* `is_absolute_value`: a type class stating that `f : Ξ² β Ξ±` satisfies the axioms of an abs val
-/
/-- `absolute_value R S` is the type of absolute values on `R` mapping to `S`:
the maps that preserve `*`, are nonnegative, positive definite and satisfy the triangle equality. -/
structure absolute_value (R S : Type*) [semiring R] [ordered_semiring S]
extends R ββ* S :=
(nonneg' : β x, 0 β€ to_fun x)
(eq_zero' : β x, to_fun x = 0 β x = 0)
(add_le' : β x y, to_fun (x + y) β€ to_fun x + to_fun y)
namespace absolute_value
attribute [nolint doc_blame] absolute_value.to_mul_hom
section ordered_semiring
section semiring
variables {R S : Type*} [semiring R] [ordered_semiring S] (abv : absolute_value R S)
instance zero_hom_class : zero_hom_class (absolute_value R S) R S :=
{ coe := Ξ» f, f.to_fun,
coe_injective' := Ξ» f g h, by { obtain β¨β¨_, _β©, _β© := f, obtain β¨β¨_, _β©, _β© := g, congr' },
map_zero := Ξ» f, (f.eq_zero' _).2 rfl }
instance mul_hom_class : mul_hom_class (absolute_value R S) R S :=
{ map_mul := Ξ» f, f.map_mul'
..absolute_value.zero_hom_class }
instance nonneg_hom_class : nonneg_hom_class (absolute_value R S) R S :=
{ map_nonneg := Ξ» f, f.nonneg',
..absolute_value.zero_hom_class }
instance subadditive_hom_class : subadditive_hom_class (absolute_value R S) R S :=
{ map_add_le_add := Ξ» f, f.add_le',
..absolute_value.zero_hom_class }
@[simp] lemma coe_mk (f : R ββ* S) {hβ hβ hβ} : ((absolute_value.mk f hβ hβ hβ) : R β S) = f := rfl
@[ext] lemma ext β¦f g : absolute_value R Sβ¦ : (β x, f x = g x) β f = g := fun_like.ext _ _
/-- See Note [custom simps projection]. -/
def simps.apply (f : absolute_value R S) : R β S := f
initialize_simps_projections absolute_value (to_mul_hom_to_fun β apply)
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (absolute_value R S) (Ξ» f, R β S) := fun_like.has_coe_to_fun
@[simp] lemma coe_to_mul_hom : βabv.to_mul_hom = abv := rfl
protected theorem nonneg (x : R) : 0 β€ abv x := abv.nonneg' x
@[simp] protected theorem eq_zero {x : R} : abv x = 0 β x = 0 := abv.eq_zero' x
protected theorem add_le (x y : R) : abv (x + y) β€ abv x + abv y := abv.add_le' x y
@[simp] protected theorem map_mul (x y : R) : abv (x * y) = abv x * abv y := abv.map_mul' x y
protected theorem ne_zero_iff {x : R} : abv x β 0 β x β 0 := abv.eq_zero.not
protected theorem pos {x : R} (hx : x β 0) : 0 < abv x :=
lt_of_le_of_ne (abv.nonneg x) (ne.symm $ mt abv.eq_zero.mp hx)
@[simp] protected theorem pos_iff {x : R} : 0 < abv x β x β 0 :=
β¨Ξ» hβ, mt abv.eq_zero.mpr hβ.ne', abv.posβ©
protected theorem ne_zero {x : R} (hx : x β 0) : abv x β 0 := (abv.pos hx).ne'
theorem map_one_of_is_regular (h : is_left_regular (abv 1)) : abv 1 = 1 :=
h $ by simp [βabv.map_mul]
@[simp] protected theorem map_zero : abv 0 = 0 := abv.eq_zero.2 rfl
end semiring
section ring
variables {R S : Type*} [ring R] [ordered_semiring S] (abv : absolute_value R S)
protected lemma sub_le (a b c : R) : abv (a - c) β€ abv (a - b) + abv (b - c) :=
by simpa [sub_eq_add_neg, add_assoc] using abv.add_le (a - b) (b - c)
@[simp] lemma map_sub_eq_zero_iff (a b : R) : abv (a - b) = 0 β a = b :=
abv.eq_zero.trans sub_eq_zero
end ring
end ordered_semiring
section ordered_ring
section semiring
section is_domain
-- all of these are true for `no_zero_divisors S`; but it doesn't work smoothly with the
-- `is_domain`/`cancel_monoid_with_zero` API
variables {R S : Type*} [semiring R] [ordered_ring S] (abv : absolute_value R S)
variables [is_domain S] [nontrivial R]
@[simp] protected theorem map_one : abv 1 = 1 :=
abv.map_one_of_is_regular ((is_regular_of_ne_zero $ abv.ne_zero one_ne_zero).left)
instance : monoid_with_zero_hom_class (absolute_value R S) R S :=
{ map_zero := Ξ» f, f.map_zero,
map_one := Ξ» f, f.map_one,
..absolute_value.mul_hom_class }
/-- Absolute values from a nontrivial `R` to a linear ordered ring preserve `*`, `0` and `1`. -/
def to_monoid_with_zero_hom : R β*β S := abv
@[simp] lemma coe_to_monoid_with_zero_hom : βabv.to_monoid_with_zero_hom = abv := rfl
/-- Absolute values from a nontrivial `R` to a linear ordered ring preserve `*` and `1`. -/
def to_monoid_hom : R β* S := abv
@[simp] lemma coe_to_monoid_hom : βabv.to_monoid_hom = abv := rfl
@[simp] protected lemma map_pow (a : R) (n : β) : abv (a ^ n) = abv a ^ n :=
abv.to_monoid_hom.map_pow a n
end is_domain
end semiring
section ring
variables {R S : Type*} [ring R] [ordered_ring S] (abv : absolute_value R S)
protected lemma le_sub (a b : R) : abv a - abv b β€ abv (a - b) :=
sub_le_iff_le_add.2 $ by simpa using abv.add_le (a - b) b
end ring
end ordered_ring
section ordered_comm_ring
variables {R S : Type*} [ring R] [ordered_comm_ring S] (abv : absolute_value R S)
variables [no_zero_divisors S]
@[simp] protected theorem map_neg (a : R) : abv (-a) = abv a :=
begin
by_cases ha : a = 0, { simp [ha] },
refine (mul_self_eq_mul_self_iff.mp
(by rw [β abv.map_mul, neg_mul_neg, abv.map_mul])).resolve_right _,
exact ((neg_lt_zero.mpr (abv.pos ha)).trans (abv.pos (neg_ne_zero.mpr ha))).ne'
end
protected theorem map_sub (a b : R) : abv (a - b) = abv (b - a) :=
by rw [β neg_sub, abv.map_neg]
end ordered_comm_ring
instance {R S : Type*} [ring R] [ordered_comm_ring S] [nontrivial R] [is_domain S] :
mul_ring_norm_class (absolute_value R S) R S :=
{ map_neg_eq_map := Ξ» f, f.map_neg,
eq_zero_of_map_eq_zero := Ξ» f a, f.eq_zero.1,
..absolute_value.subadditive_hom_class, ..absolute_value.monoid_with_zero_hom_class }
section linear_ordered_ring
variables {R S : Type*} [semiring R] [linear_ordered_ring S] (abv : absolute_value R S)
/-- `absolute_value.abs` is `abs` as a bundled `absolute_value`. -/
@[simps]
protected def abs : absolute_value S S :=
{ to_fun := abs,
nonneg' := abs_nonneg,
eq_zero' := Ξ» _, abs_eq_zero,
add_le' := abs_add,
map_mul' := abs_mul }
instance : inhabited (absolute_value S S) := β¨absolute_value.absβ©
end linear_ordered_ring
section linear_ordered_comm_ring
variables {R S : Type*} [ring R] [linear_ordered_comm_ring S] (abv : absolute_value R S)
lemma abs_abv_sub_le_abv_sub (a b : R) :
abs (abv a - abv b) β€ abv (a - b) :=
abs_sub_le_iff.2 β¨abv.le_sub _ _, by rw abv.map_sub; apply abv.le_subβ©
end linear_ordered_comm_ring
end absolute_value
/-- A function `f` is an absolute value if it is nonnegative, zero only at 0, additive, and
multiplicative.
See also the type `absolute_value` which represents a bundled version of absolute values.
-/
class is_absolute_value {S} [ordered_semiring S]
{R} [semiring R] (f : R β S) : Prop :=
(abv_nonneg [] : β x, 0 β€ f x)
(abv_eq_zero [] : β {x}, f x = 0 β x = 0)
(abv_add [] : β x y, f (x + y) β€ f x + f y)
(abv_mul [] : β x y, f (x * y) = f x * f y)
namespace is_absolute_value
section ordered_semiring
variables {S : Type*} [ordered_semiring S]
variables {R : Type*} [semiring R] (abv : R β S) [is_absolute_value abv]
/-- A bundled absolute value is an absolute value. -/
instance _root_.absolute_value.is_absolute_value
(abv : absolute_value R S) : is_absolute_value abv :=
{ abv_nonneg := abv.nonneg,
abv_eq_zero := Ξ» _, abv.eq_zero,
abv_add := abv.add_le,
abv_mul := abv.map_mul }
/-- Convert an unbundled `is_absolute_value` to a bundled `absolute_value`. -/
@[simps]
def to_absolute_value : absolute_value R S :=
{ to_fun := abv,
add_le' := abv_add abv,
eq_zero' := Ξ» _, abv_eq_zero abv,
nonneg' := abv_nonneg abv,
map_mul' := abv_mul abv }
theorem abv_zero : abv 0 = 0 := (to_absolute_value abv).map_zero
theorem abv_pos {a : R} : 0 < abv a β a β 0 := (to_absolute_value abv).pos_iff
end ordered_semiring
section linear_ordered_ring
variables {S : Type*} [linear_ordered_ring S]
instance abs_is_absolute_value : is_absolute_value (abs : S β S) :=
absolute_value.abs.is_absolute_value
end linear_ordered_ring
section ordered_ring
variables {S : Type*} [ordered_ring S]
section semiring
variables {R : Type*} [semiring R] (abv : R β S) [is_absolute_value abv]
variables [is_domain S]
theorem abv_one [nontrivial R] : abv 1 = 1 := (to_absolute_value abv).map_one
/-- `abv` as a `monoid_with_zero_hom`. -/
def abv_hom [nontrivial R] : R β*β S := (to_absolute_value abv).to_monoid_with_zero_hom
lemma abv_pow [nontrivial R] (abv : R β S) [is_absolute_value abv]
(a : R) (n : β) : abv (a ^ n) = abv a ^ n :=
(to_absolute_value abv).map_pow a n
end semiring
section ring
variables {R : Type*} [ring R] (abv : R β S) [is_absolute_value abv]
lemma abv_sub_le (a b c : R) : abv (a - c) β€ abv (a - b) + abv (b - c) :=
by simpa [sub_eq_add_neg, add_assoc] using abv_add abv (a - b) (b - c)
lemma sub_abv_le_abv_sub (a b : R) : abv a - abv b β€ abv (a - b) :=
(to_absolute_value abv).le_sub a b
end ring
end ordered_ring
section ordered_comm_ring
variables {S : Type*} [ordered_comm_ring S]
section ring
variables {R : Type*} [ring R] (abv : R β S) [is_absolute_value abv]
variables [no_zero_divisors S]
theorem abv_neg (a : R) : abv (-a) = abv a :=
(to_absolute_value abv).map_neg a
theorem abv_sub (a b : R) : abv (a - b) = abv (b - a) :=
(to_absolute_value abv).map_sub a b
end ring
end ordered_comm_ring
section linear_ordered_comm_ring
variables {S : Type*} [linear_ordered_comm_ring S]
section ring
variables {R : Type*} [ring R] (abv : R β S) [is_absolute_value abv]
lemma abs_abv_sub_le_abv_sub (a b : R) :
abs (abv a - abv b) β€ abv (a - b) :=
(to_absolute_value abv).abs_abv_sub_le_abv_sub a b
end ring
end linear_ordered_comm_ring
section linear_ordered_field
variables {S : Type*} [linear_ordered_semifield S]
section semiring
variables {R : Type*} [semiring R] [nontrivial R] (abv : R β S) [is_absolute_value abv]
lemma abv_one' : abv 1 = 1 :=
(to_absolute_value abv).map_one_of_is_regular
$ (is_regular_of_ne_zero $ (to_absolute_value abv).ne_zero one_ne_zero).left
/-- An absolute value as a monoid with zero homomorphism, assuming the target is a semifield. -/
def abv_hom' : R β*β S := β¨abv, abv_zero abv, abv_one' abv, abv_mul abvβ©
end semiring
section division_semiring
variables {R : Type*} [division_semiring R] (abv : R β S) [is_absolute_value abv]
theorem abv_inv (a : R) : abv aβ»ΒΉ = (abv a)β»ΒΉ := map_invβ (abv_hom' abv) a
theorem abv_div (a b : R) : abv (a / b) = abv a / abv b := map_divβ (abv_hom' abv) a b
end division_semiring
end linear_ordered_field
end is_absolute_value
|
78d298563d29c7baad014b94c7d2b3c23bf2e3ef | 9d2e3d5a2e2342a283affd97eead310c3b528a24 | /src/solutions/thursday/afternoon/category_theory/exercise4.lean | a9b78f0dbdb81f74013f8ef36a770869580a70f9 | [] | permissive | Vtec234/lftcm2020 | ad2610ab614beefe44acc5622bb4a7fff9a5ea46 | bbbd4c8162f8c2ef602300ab8fdeca231886375d | refs/heads/master | 1,668,808,098,623 | 1,594,989,081,000 | 1,594,990,079,000 | 280,423,039 | 0 | 0 | MIT | 1,594,990,209,000 | 1,594,990,209,000 | null | UTF-8 | Lean | false | false | 1,410 | lean | import algebra.category.CommRing
import category_theory.yoneda
open category_theory
open opposite
open polynomial
noncomputable theory
/-!
We show that the forgetful functor `CommRing β₯€ Type` is (co)representable.
There are a sequence of hints available in
`hints/thursday/afternoon/category_theory/hintX.lean`, for `X = 1,2,3,4`.
-/
-- Because we'll be working with `polynomial β€`, which is in `Type 0`,
-- we just restrict to that universe for this exercise.
notation `CommRing` := CommRing.{0}
/-!
One bonus hint before we start, showing you how to obtain the
ring homomorphism from `β€` into any commutative ring.
-/
example (R : CommRing) : β€ β+* R :=
by library_search
/-!
Also useful may be the functions
-/
#print polynomial.evalβ
#print polynomial.evalβ_ring_hom
/-!
The actual exercise!
-/
def CommRing_forget_representable : Ξ£ (R : CommRing), (forget CommRing) β
coyoneda.obj (op R) :=
-- sorry
β¨CommRing.of (polynomial β€),
{ hom :=
{ app := Ξ» R r, polynomial.evalβ_ring_hom (algebra_map β€ R) r, },
inv :=
{ app := Ξ» R f, by { dsimp at f, exact f X, }, }, }β©
-- sorry
/-!
There are some further hints in
`src/hints/thursday/afternoon/category_theory/exercise4/`
-/
/-
If you get an error message
```
synthesized type class instance is not definitionally equal to expression inferred by typing rules
```
while solving this exercise, see hint4.lean.
-/
|
9897cb4a35ad651ada630a1cd31c4b0757162c9b | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/group_theory/group_action/units.lean | c7d3df43e723d7674a921356cd6663ecc5f8a17b | [
"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 | 5,472 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import group_theory.group_action.defs
/-! # Group actions on and by `MΛ£`
This file provides the action of a unit on a type `Ξ±`, `has_scalar MΛ£ Ξ±`, in the presence of
`has_scalar M Ξ±`, with the obvious definition stated in `units.smul_def`. This definition preserves
`mul_action` and `distrib_mul_action` structures too.
Additionally, a `mul_action G M` for some group `G` satisfying some additional properties admits a
`mul_action G MΛ£` structure, again with the obvious definition stated in `units.coe_smul`.
These instances use a primed name.
The results are repeated for `add_units` and `has_vadd` where relevant.
-/
variables {G H M N : Type*} {Ξ± : Type*}
namespace units
/-! ### Action of the units of `M` on a type `Ξ±` -/
@[to_additive]
instance [monoid M] [has_scalar M Ξ±] : has_scalar MΛ£ Ξ± :=
{ smul := Ξ» m a, (m : M) β’ a }
@[to_additive]
lemma smul_def [monoid M] [has_scalar M Ξ±] (m : MΛ£) (a : Ξ±) :
m β’ a = (m : M) β’ a := rfl
lemma _root_.is_unit.inv_smul [monoid Ξ±] {a : Ξ±} (h : is_unit a) :
(h.unit)β»ΒΉ β’ a = 1 :=
h.coe_inv_mul
@[to_additive]
instance [monoid M] [has_scalar M Ξ±] [has_faithful_scalar M Ξ±] : has_faithful_scalar MΛ£ Ξ± :=
{ eq_of_smul_eq_smul := Ξ» uβ uβ h, units.ext $ eq_of_smul_eq_smul h, }
@[to_additive]
instance [monoid M] [mul_action M Ξ±] : mul_action MΛ£ Ξ± :=
{ one_smul := (one_smul M : _),
mul_smul := Ξ» m n, mul_smul (m : M) n, }
instance [monoid M] [add_monoid Ξ±] [distrib_mul_action M Ξ±] : distrib_mul_action MΛ£ Ξ± :=
{ smul_add := Ξ» m, smul_add (m : M),
smul_zero := Ξ» m, smul_zero m, }
instance [monoid M] [monoid Ξ±] [mul_distrib_mul_action M Ξ±] : mul_distrib_mul_action MΛ£ Ξ± :=
{ smul_mul := Ξ» m, smul_mul' (m : M),
smul_one := Ξ» m, smul_one m, }
instance smul_comm_class_left [monoid M] [has_scalar M Ξ±] [has_scalar N Ξ±]
[smul_comm_class M N Ξ±] : smul_comm_class MΛ£ N Ξ± :=
{ smul_comm := Ξ» m n, (smul_comm (m : M) n : _)}
instance smul_comm_class_right [monoid N] [has_scalar M Ξ±] [has_scalar N Ξ±]
[smul_comm_class M N Ξ±] : smul_comm_class M NΛ£ Ξ± :=
{ smul_comm := Ξ» m n, (smul_comm m (n : N) : _)}
instance [monoid M] [has_scalar M N] [has_scalar M Ξ±] [has_scalar N Ξ±] [is_scalar_tower M N Ξ±] :
is_scalar_tower MΛ£ N Ξ± :=
{ smul_assoc := Ξ» m n, (smul_assoc (m : M) n : _)}
/-! ### Action of a group `G` on units of `M` -/
/-- If an action `G` associates and commutes with multiplication on `M`, then it lifts to an
action on `MΛ£`. Notably, this provides `mul_action MΛ£ NΛ£` under suitable
conditions.
-/
instance mul_action' [group G] [monoid M] [mul_action G M] [smul_comm_class G M M]
[is_scalar_tower G M M] : mul_action G MΛ£ :=
{ smul := Ξ» g m, β¨g β’ (m : M), gβ»ΒΉ β’ β(mβ»ΒΉ),
by rw [smul_mul_smul, units.mul_inv, mul_right_inv, one_smul],
by rw [smul_mul_smul, units.inv_mul, mul_left_inv, one_smul]β©,
one_smul := Ξ» m, units.ext $ one_smul _ _,
mul_smul := Ξ» gβ gβ m, units.ext $ mul_smul _ _ _ }
@[simp] lemma coe_smul [group G] [monoid M] [mul_action G M] [smul_comm_class G M M]
[is_scalar_tower G M M] (g : G) (m : MΛ£) : β(g β’ m) = g β’ (m : M) := rfl
/-- Note that this lemma exists more generally as the global `smul_inv` -/
@[simp] lemma smul_inv [group G] [monoid M] [mul_action G M] [smul_comm_class G M M]
[is_scalar_tower G M M] (g : G) (m : MΛ£) : (g β’ m)β»ΒΉ = gβ»ΒΉ β’ mβ»ΒΉ := ext rfl
/-- Transfer `smul_comm_class G H M` to `smul_comm_class G H MΛ£` -/
instance smul_comm_class' [group G] [group H] [monoid M]
[mul_action G M] [smul_comm_class G M M]
[mul_action H M] [smul_comm_class H M M]
[is_scalar_tower G M M] [is_scalar_tower H M M]
[smul_comm_class G H M] : smul_comm_class G H MΛ£ :=
{ smul_comm := Ξ» g h m, units.ext $ smul_comm g h (m : M) }
/-- Transfer `is_scalar_tower G H M` to `is_scalar_tower G H MΛ£` -/
instance is_scalar_tower' [has_scalar G H] [group G] [group H] [monoid M]
[mul_action G M] [smul_comm_class G M M]
[mul_action H M] [smul_comm_class H M M]
[is_scalar_tower G M M] [is_scalar_tower H M M]
[is_scalar_tower G H M] : is_scalar_tower G H MΛ£ :=
{ smul_assoc := Ξ» g h m, units.ext $ smul_assoc g h (m : M) }
/-- Transfer `is_scalar_tower G M Ξ±` to `is_scalar_tower G MΛ£ Ξ±` -/
instance is_scalar_tower'_left [group G] [monoid M] [mul_action G M] [has_scalar M Ξ±]
[has_scalar G Ξ±] [smul_comm_class G M M] [is_scalar_tower G M M]
[is_scalar_tower G M Ξ±] :
is_scalar_tower G MΛ£ Ξ± :=
{ smul_assoc := Ξ» g m, (smul_assoc g (m : M) : _)}
-- Just to prove this transfers a particularly useful instance.
example [monoid M] [monoid N] [mul_action M N] [smul_comm_class M N N]
[is_scalar_tower M N N] : mul_action MΛ£ NΛ£ := units.mul_action'
/-- A stronger form of `units.mul_action'`. -/
instance mul_distrib_mul_action' [group G] [monoid M] [mul_distrib_mul_action G M]
[smul_comm_class G M M] [is_scalar_tower G M M] : mul_distrib_mul_action G MΛ£ :=
{ smul := (β’),
smul_one := Ξ» m, units.ext $ smul_one _,
smul_mul := Ξ» g mβ mβ, units.ext $ smul_mul' _ _ _,
.. units.mul_action' }
end units
lemma is_unit.smul [group G] [monoid M] [mul_action G M]
[smul_comm_class G M M] [is_scalar_tower G M M] {m : M} (g : G) (h : is_unit m) :
is_unit (g β’ m) :=
let β¨u, huβ© := h in hu βΈ β¨g β’ u, units.coe_smul _ _β©
|
ccf54f6495acf0b15ef163cb10692acf7086078d | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebraic_geometry/is_open_comap_C.lean | ec56600d25c4d324cf561b9a94055b6deb244b9e | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 3,036 | lean | /-
Copyright (c) 2021 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import algebraic_geometry.prime_spectrum
import ring_theory.polynomial.basic
/-!
The morphism `Spec R[x] --> Spec R` induced by the natural inclusion `R --> R[x]` is an open map.
The main result is the first part of the statement of Lemma 00FB in the Stacks Project.
https://stacks.math.columbia.edu/tag/00FB
-/
open ideal polynomial prime_spectrum set
namespace algebraic_geometry
namespace polynomial
variables {R : Type*} [comm_ring R] {f : polynomial R}
/-- Given a polynomial `f β R[x]`, `image_of_Df` is the subset of `Spec R` where at least one
of the coefficients of `f` does not vanish. Lemma `image_of_Df_eq_comap_C_compl_zero_locus`
proves that `image_of_Df` is the image of `(zero_locus {f})αΆ` under the morphism
`comap C : Spec R[x] β Spec R`. -/
def image_of_Df (f) : set (prime_spectrum R) :=
{p : prime_spectrum R | β i : β , (coeff f i) β p.as_ideal}
lemma is_open_image_of_Df : is_open (image_of_Df f) :=
begin
rw [image_of_Df, set_of_exists (Ξ» i (x : prime_spectrum R), coeff f i β x.val)],
exact is_open_Union (Ξ» i, is_open_basic_open),
end
/-- If a point of `Spec R[x]` is not contained in the vanishing set of `f`, then its image in
`Spec R` is contained in the open set where at least one of the coefficients of `f` is non-zero.
This lemma is a reformulation of `exists_coeff_not_mem_C_inverse`. -/
lemma comap_C_mem_image_of_Df {I : prime_spectrum (polynomial R)}
(H : I β (zero_locus {f} : set (prime_spectrum (polynomial R)))αΆ ) :
comap (polynomial.C : R β+* polynomial R) I β image_of_Df f :=
exists_coeff_not_mem_C_inverse (mem_compl_zero_locus_iff_not_mem.mp H)
/-- The open set `image_of_Df f` coincides with the image of `basic_open f` under the
morphism `CβΊ : Spec R[x] β Spec R`. -/
lemma image_of_Df_eq_comap_C_compl_zero_locus :
image_of_Df f = comap C '' (zero_locus {f})αΆ :=
begin
refine ext (Ξ» x, β¨Ξ» hx, β¨β¨map C x.val, (is_prime_map_C_of_is_prime x.property)β©, β¨_, _β©β©, _β©),
{ rw [mem_compl_eq, mem_zero_locus, singleton_subset_iff],
cases hx with i hi,
exact Ξ» a, hi (mem_map_C_iff.mp a i) },
{ refine subtype.ext (ext (Ξ» x, β¨Ξ» h, _, Ξ» h, subset_span (mem_image_of_mem C.1 h)β©)),
rw β @coeff_C_zero R x _,
exact mem_map_C_iff.mp h 0 },
{ rintro β¨xli, complement, rflβ©,
exact comap_C_mem_image_of_Df complement }
end
/-- The morphism `CβΊ : Spec R[x] β Spec R` is open.
Stacks Project "Lemma 00FB", first part.
https://stacks.math.columbia.edu/tag/00FB
-/
theorem is_open_map_comap_C :
is_open_map (comap (C : R β+* polynomial R)) :=
begin
rintros U β¨s, zβ©,
rw [β compl_compl U, β z, β Union_of_singleton_coe s, zero_locus_Union, compl_Inter, image_Union],
simp_rw [β image_of_Df_eq_comap_C_compl_zero_locus],
exact is_open_Union (Ξ» f, is_open_image_of_Df),
end
end polynomial
end algebraic_geometry
|
3f352431d56ef4eb6a11555fd43c5c457927df76 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/order/pointwise.lean | c40bd3a2299070d90b25d5b6d57f406a3816d823 | [
"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 | 7,355 | lean | /-
Copyright (c) 2021 Alex J. Best. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alex J. Best, YaΓ«l Dillies
-/
import algebra.bounds
import data.set.pointwise.smul
/-!
# Pointwise operations on ordered algebraic objects
This file contains lemmas about the effect of pointwise operations on sets with an order structure.
## TODO
`Sup (s β’ t) = Sup s β’ Sup t` and `Inf (s β’ t) = Inf s β’ Inf t` hold as well but
`covariant_class` is currently not polymorphic enough to state it.
-/
open function set
open_locale pointwise
variables {Ξ± : Type*}
section conditionally_complete_lattice
variables [conditionally_complete_lattice Ξ±]
section has_one
variables [has_one Ξ±]
@[simp, to_additive] lemma cSup_one : Sup (1 : set Ξ±) = 1 := cSup_singleton _
@[simp, to_additive] lemma cInf_one : Inf (1 : set Ξ±) = 1 := cInf_singleton _
end has_one
section group
variables [group Ξ±] [covariant_class Ξ± Ξ± (*) (β€)] [covariant_class Ξ± Ξ± (swap (*)) (β€)] {s t : set Ξ±}
@[to_additive] lemma cSup_inv (hsβ : s.nonempty) (hsβ : bdd_below s) : Sup sβ»ΒΉ = (Inf s)β»ΒΉ :=
by { rw βimage_inv, exact ((order_iso.inv Ξ±).map_cInf' hsβ hsβ).symm }
@[to_additive] lemma cInf_inv (hsβ : s.nonempty) (hsβ : bdd_above s) : Inf sβ»ΒΉ = (Sup s)β»ΒΉ :=
by { rw βimage_inv, exact ((order_iso.inv Ξ±).map_cSup' hsβ hsβ).symm }
@[to_additive] lemma cSup_mul (hsβ : s.nonempty) (hsβ : bdd_above s) (htβ : t.nonempty)
(htβ : bdd_above t) :
Sup (s * t) = Sup s * Sup t :=
cSup_image2_eq_cSup_cSup (Ξ» _, (order_iso.mul_right _).to_galois_connection)
(Ξ» _, (order_iso.mul_left _).to_galois_connection) hsβ hsβ htβ htβ
@[to_additive] lemma cInf_mul (hsβ : s.nonempty) (hsβ : bdd_below s) (htβ : t.nonempty)
(htβ : bdd_below t) :
Inf (s * t) = Inf s * Inf t :=
cInf_image2_eq_cInf_cInf (Ξ» _, (order_iso.mul_right _).symm.to_galois_connection)
(Ξ» _, (order_iso.mul_left _).symm.to_galois_connection) hsβ hsβ htβ htβ
@[to_additive] lemma cSup_div (hsβ : s.nonempty) (hsβ : bdd_above s) (htβ : t.nonempty)
(htβ : bdd_below t) :
Sup (s / t) = Sup s / Inf t :=
by rw [div_eq_mul_inv, cSup_mul hsβ hsβ htβ.inv htβ.inv, cSup_inv htβ htβ, div_eq_mul_inv]
@[to_additive] lemma cInf_div (hsβ : s.nonempty) (hsβ : bdd_below s) (htβ : t.nonempty)
(htβ : bdd_above t) :
Inf (s / t) = Inf s / Sup t :=
by rw [div_eq_mul_inv, cInf_mul hsβ hsβ htβ.inv htβ.inv, cInf_inv htβ htβ, div_eq_mul_inv]
end group
end conditionally_complete_lattice
section complete_lattice
variables [complete_lattice Ξ±]
section has_one
variables [has_one Ξ±]
@[simp, to_additive] lemma Sup_one : Sup (1 : set Ξ±) = 1 := Sup_singleton
@[simp, to_additive] lemma Inf_one : Inf (1 : set Ξ±) = 1 := Inf_singleton
end has_one
section group
variables [group Ξ±] [covariant_class Ξ± Ξ± (*) (β€)] [covariant_class Ξ± Ξ± (swap (*)) (β€)] (s t : set Ξ±)
@[to_additive] lemma Sup_inv (s : set Ξ±) : Sup sβ»ΒΉ = (Inf s)β»ΒΉ :=
by { rw [βimage_inv, Sup_image], exact ((order_iso.inv Ξ±).map_Inf _).symm }
@[to_additive] lemma Inf_inv (s : set Ξ±) : Inf sβ»ΒΉ = (Sup s)β»ΒΉ :=
by { rw [βimage_inv, Inf_image], exact ((order_iso.inv Ξ±).map_Sup _).symm }
@[to_additive] lemma Sup_mul : Sup (s * t) = Sup s * Sup t :=
Sup_image2_eq_Sup_Sup (Ξ» _, (order_iso.mul_right _).to_galois_connection) $
Ξ» _, (order_iso.mul_left _).to_galois_connection
@[to_additive] lemma Inf_mul : Inf (s * t) = Inf s * Inf t :=
Inf_image2_eq_Inf_Inf (Ξ» _, (order_iso.mul_right _).symm.to_galois_connection) $
Ξ» _, (order_iso.mul_left _).symm.to_galois_connection
@[to_additive] lemma Sup_div : Sup (s / t) = Sup s / Inf t :=
by simp_rw [div_eq_mul_inv, Sup_mul, Sup_inv]
@[to_additive] lemma Inf_div : Inf (s / t) = Inf s / Sup t :=
by simp_rw [div_eq_mul_inv, Inf_mul, Inf_inv]
end group
end complete_lattice
namespace linear_ordered_field
variables {K : Type*} [linear_ordered_field K] {a b r : K} (hr : 0 < r)
open set
include hr
lemma smul_Ioo : r β’ Ioo a b = Ioo (r β’ a) (r β’ b) :=
begin
ext x,
simp only [mem_smul_set, smul_eq_mul, mem_Ioo],
split,
{ rintro β¨a, β¨a_h_left_left, a_h_left_rightβ©, rflβ©, split,
exact (mul_lt_mul_left hr).mpr a_h_left_left,
exact (mul_lt_mul_left hr).mpr a_h_left_right, },
{ rintro β¨a_left, a_rightβ©,
use x / r,
refine β¨β¨(lt_div_iff' hr).mpr a_left, (div_lt_iff' hr).mpr a_rightβ©, _β©,
rw mul_div_cancel' _ (ne_of_gt hr), }
end
lemma smul_Icc : r β’ Icc a b = Icc (r β’ a) (r β’ b) :=
begin
ext x,
simp only [mem_smul_set, smul_eq_mul, mem_Icc],
split,
{ rintro β¨a, β¨a_h_left_left, a_h_left_rightβ©, rflβ©, split,
exact (mul_le_mul_left hr).mpr a_h_left_left,
exact (mul_le_mul_left hr).mpr a_h_left_right, },
{ rintro β¨a_left, a_rightβ©,
use x / r,
refine β¨β¨(le_div_iff' hr).mpr a_left, (div_le_iff' hr).mpr a_rightβ©, _β©,
rw mul_div_cancel' _ (ne_of_gt hr), }
end
lemma smul_Ico : r β’ Ico a b = Ico (r β’ a) (r β’ b) :=
begin
ext x,
simp only [mem_smul_set, smul_eq_mul, mem_Ico],
split,
{ rintro β¨a, β¨a_h_left_left, a_h_left_rightβ©, rflβ©, split,
exact (mul_le_mul_left hr).mpr a_h_left_left,
exact (mul_lt_mul_left hr).mpr a_h_left_right, },
{ rintro β¨a_left, a_rightβ©,
use x / r,
refine β¨β¨(le_div_iff' hr).mpr a_left, (div_lt_iff' hr).mpr a_rightβ©, _β©,
rw mul_div_cancel' _ (ne_of_gt hr), }
end
lemma smul_Ioc : r β’ Ioc a b = Ioc (r β’ a) (r β’ b) :=
begin
ext x,
simp only [mem_smul_set, smul_eq_mul, mem_Ioc],
split,
{ rintro β¨a, β¨a_h_left_left, a_h_left_rightβ©, rflβ©, split,
exact (mul_lt_mul_left hr).mpr a_h_left_left,
exact (mul_le_mul_left hr).mpr a_h_left_right, },
{ rintro β¨a_left, a_rightβ©,
use x / r,
refine β¨β¨(lt_div_iff' hr).mpr a_left, (div_le_iff' hr).mpr a_rightβ©, _β©,
rw mul_div_cancel' _ (ne_of_gt hr), }
end
lemma smul_Ioi : r β’ Ioi a = Ioi (r β’ a) :=
begin
ext x,
simp only [mem_smul_set, smul_eq_mul, mem_Ioi],
split,
{ rintro β¨a_w, a_h_left, rflβ©,
exact (mul_lt_mul_left hr).mpr a_h_left, },
{ rintro h,
use x / r,
split,
exact (lt_div_iff' hr).mpr h,
exact mul_div_cancel' _ (ne_of_gt hr), }
end
lemma smul_Iio : r β’ Iio a = Iio (r β’ a) :=
begin
ext x,
simp only [mem_smul_set, smul_eq_mul, mem_Iio],
split,
{ rintro β¨a_w, a_h_left, rflβ©,
exact (mul_lt_mul_left hr).mpr a_h_left, },
{ rintro h,
use x / r,
split,
exact (div_lt_iff' hr).mpr h,
exact mul_div_cancel' _ (ne_of_gt hr), }
end
lemma smul_Ici : r β’ Ici a = Ici (r β’ a) :=
begin
ext x,
simp only [mem_smul_set, smul_eq_mul, mem_Ioi],
split,
{ rintro β¨a_w, a_h_left, rflβ©,
exact (mul_le_mul_left hr).mpr a_h_left, },
{ rintro h,
use x / r,
split,
exact (le_div_iff' hr).mpr h,
exact mul_div_cancel' _ (ne_of_gt hr), }
end
lemma smul_Iic : r β’ Iic a = Iic (r β’ a) :=
begin
ext x,
simp only [mem_smul_set, smul_eq_mul, mem_Iio],
split,
{ rintro β¨a_w, a_h_left, rflβ©,
exact (mul_le_mul_left hr).mpr a_h_left, },
{ rintro h,
use x / r,
split,
exact (div_le_iff' hr).mpr h,
exact mul_div_cancel' _ (ne_of_gt hr), }
end
end linear_ordered_field
|
5b928038c66fc3716a996b5aacde4d8dc8ec51ef | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/topology/constructions.lean | 7bb032076578b24a6e5d4dab6e282b8775c77d41 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 34,464 | 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 topology.maps
/-!
# Constructions of new topological spaces from old ones
This file constructs products, sums, subtypes and quotients of topological spaces
and sets up their basic theory, such as criteria for maps into or out of these
constructions to be continuous; descriptions of the open sets, neighborhood filters,
and generators of these constructions; and their behavior with respect to embeddings
and other specific classes of maps.
## Implementation note
The constructed topologies are defined using induced and coinduced topologies
along with the complete lattice structure on topologies. Their universal properties
(for example, a map `X β Y Γ Z` is continuous if and only if both projections
`X β Y`, `X β Z` are) follow easily using order-theoretic descriptions of
continuity. With more work we can also extract descriptions of the open sets,
neighborhood filters and so on.
## Tags
product, sum, disjoint union, subspace, quotient space
-/
noncomputable theory
open topological_space set filter
open_locale classical topological_space filter
universes u v w x
variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} {Ξ΄ : Type x}
section constructions
instance {p : Ξ± β Prop} [t : topological_space Ξ±] : topological_space (subtype p) :=
induced coe t
instance {r : Ξ± β Ξ± β Prop} [t : topological_space Ξ±] : topological_space (quot r) :=
coinduced (quot.mk r) t
instance {s : setoid Ξ±} [t : topological_space Ξ±] : topological_space (quotient s) :=
coinduced quotient.mk t
instance [tβ : topological_space Ξ±] [tβ : topological_space Ξ²] : topological_space (Ξ± Γ Ξ²) :=
induced prod.fst tβ β induced prod.snd tβ
instance [tβ : topological_space Ξ±] [tβ : topological_space Ξ²] : topological_space (Ξ± β Ξ²) :=
coinduced sum.inl tβ β coinduced sum.inr tβ
instance {Ξ² : Ξ± β Type v} [tβ : Ξ a, topological_space (Ξ² a)] : topological_space (sigma Ξ²) :=
β¨a, coinduced (sigma.mk a) (tβ a)
instance Pi.topological_space {Ξ² : Ξ± β Type v} [tβ : Ξ a, topological_space (Ξ² a)] :
topological_space (Ξ a, Ξ² a) :=
β¨
a, induced (Ξ»f, f a) (tβ a)
instance ulift.topological_space [t : topological_space Ξ±] : topological_space (ulift.{v u} Ξ±) :=
t.induced ulift.down
/-- The image of a dense set under `quotient.mk` is a dense set. -/
lemma dense.quotient [setoid Ξ±] [topological_space Ξ±] {s : set Ξ±} (H : dense s) :
dense (quotient.mk '' s) :=
(surjective_quotient_mk Ξ±).dense_range.dense_image continuous_coinduced_rng H
/-- The composition of `quotient.mk` and a function with dense range has dense range. -/
lemma dense_range.quotient [setoid Ξ±] [topological_space Ξ±] {f : Ξ² β Ξ±} (hf : dense_range f) :
dense_range (quotient.mk β f) :=
(surjective_quotient_mk Ξ±).dense_range.comp hf continuous_coinduced_rng
instance {p : Ξ± β Prop} [topological_space Ξ±] [discrete_topology Ξ±] :
discrete_topology (subtype p) :=
β¨bot_unique $ assume s hs,
β¨coe '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.coe_injective)β©β©
instance sum.discrete_topology [topological_space Ξ±] [topological_space Ξ²]
[hΞ± : discrete_topology Ξ±] [hΞ² : discrete_topology Ξ²] : discrete_topology (Ξ± β Ξ²) :=
β¨by unfold sum.topological_space; simp [hΞ±.eq_bot, hΞ².eq_bot]β©
instance sigma.discrete_topology {Ξ² : Ξ± β Type v} [Ξ a, topological_space (Ξ² a)]
[h : Ξ a, discrete_topology (Ξ² a)] : discrete_topology (sigma Ξ²) :=
β¨by { unfold sigma.topological_space, simp [Ξ» a, (h a).eq_bot] }β©
section topΞ±
variable [topological_space Ξ±]
/-
The π filter and the subspace topology.
-/
theorem mem_nhds_subtype (s : set Ξ±) (a : {x // x β s}) (t : set {x // x β s}) :
t β π a β β u β π (a : Ξ±), coe β»ΒΉ' u β t :=
mem_nhds_induced coe a t
theorem nhds_subtype (s : set Ξ±) (a : {x // x β s}) :
π a = comap coe (π (a : Ξ±)) :=
nhds_induced coe a
end topΞ±
end constructions
section prod
variables [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³] [topological_space Ξ΄]
@[continuity] lemma continuous_fst : continuous (@prod.fst Ξ± Ξ²) :=
continuous_inf_dom_left continuous_induced_dom
lemma continuous_at_fst {p : Ξ± Γ Ξ²} : continuous_at prod.fst p :=
continuous_fst.continuous_at
@[continuity] lemma continuous_snd : continuous (@prod.snd Ξ± Ξ²) :=
continuous_inf_dom_right continuous_induced_dom
lemma continuous_at_snd {p : Ξ± Γ Ξ²} : continuous_at prod.snd p :=
continuous_snd.continuous_at
@[continuity] lemma continuous.prod_mk {f : Ξ³ β Ξ±} {g : Ξ³ β Ξ²}
(hf : continuous f) (hg : continuous g) : continuous (Ξ»x, (f x, g x)) :=
continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg)
lemma continuous.prod_map {f : Ξ³ β Ξ±} {g : Ξ΄ β Ξ²} (hf : continuous f) (hg : continuous g) :
continuous (Ξ» x : Ξ³ Γ Ξ΄, (f x.1, g x.2)) :=
(hf.comp continuous_fst).prod_mk (hg.comp continuous_snd)
lemma filter.eventually.prod_inl_nhds {p : Ξ± β Prop} {a : Ξ±} (h : βαΆ x in π a, p x) (b : Ξ²) :
βαΆ x in π (a, b), p (x : Ξ± Γ Ξ²).1 :=
continuous_at_fst h
lemma filter.eventually.prod_inr_nhds {p : Ξ² β Prop} {b : Ξ²} (h : βαΆ x in π b, p x) (a : Ξ±) :
βαΆ x in π (a, b), p (x : Ξ± Γ Ξ²).2 :=
continuous_at_snd h
lemma filter.eventually.prod_mk_nhds {pa : Ξ± β Prop} {a} (ha : βαΆ x in π a, pa x)
{pb : Ξ² β Prop} {b} (hb : βαΆ y in π b, pb y) :
βαΆ p in π (a, b), pa (p : Ξ± Γ Ξ²).1 β§ pb p.2 :=
(ha.prod_inl_nhds b).and (hb.prod_inr_nhds a)
lemma continuous_swap : continuous (prod.swap : Ξ± Γ Ξ² β Ξ² Γ Ξ±) :=
continuous.prod_mk continuous_snd continuous_fst
lemma is_open.prod {s : set Ξ±} {t : set Ξ²} (hs : is_open s) (ht : is_open t) :
is_open (set.prod s t) :=
is_open_inter (continuous_fst s hs) (continuous_snd t ht)
lemma nhds_prod_eq {a : Ξ±} {b : Ξ²} : π (a, b) = π a ΓαΆ π b :=
by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced]
lemma mem_nhds_prod_iff {a : Ξ±} {b : Ξ²} {s : set (Ξ± Γ Ξ²)} :
s β π (a, b) β β (u β π a) (v β π b), set.prod u v β s :=
by rw [nhds_prod_eq, mem_prod_iff]
lemma filter.has_basis.prod_nhds {ΞΉa ΞΉb : Type*} {pa : ΞΉa β Prop} {pb : ΞΉb β Prop}
{sa : ΞΉa β set Ξ±} {sb : ΞΉb β set Ξ²} {a : Ξ±} {b : Ξ²} (ha : (π a).has_basis pa sa)
(hb : (π b).has_basis pb sb) :
(π (a, b)).has_basis (Ξ» i : ΞΉa Γ ΞΉb, pa i.1 β§ pb i.2) (Ξ» i, (sa i.1).prod (sb i.2)) :=
by { rw nhds_prod_eq, exact ha.prod hb }
instance [discrete_topology Ξ±] [discrete_topology Ξ²] : discrete_topology (Ξ± Γ Ξ²) :=
β¨eq_of_nhds_eq_nhds $ assume β¨a, bβ©,
by rw [nhds_prod_eq, nhds_discrete Ξ±, nhds_discrete Ξ², nhds_bot, filter.prod_pure_pure]β©
lemma prod_mem_nhds_sets {s : set Ξ±} {t : set Ξ²} {a : Ξ±} {b : Ξ²}
(ha : s β π a) (hb : t β π b) : set.prod s t β π (a, b) :=
by rw [nhds_prod_eq]; exact prod_mem_prod ha hb
lemma nhds_swap (a : Ξ±) (b : Ξ²) : π (a, b) = (π (b, a)).map prod.swap :=
by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl
lemma filter.tendsto.prod_mk_nhds {Ξ³} {a : Ξ±} {b : Ξ²} {f : filter Ξ³} {ma : Ξ³ β Ξ±} {mb : Ξ³ β Ξ²}
(ha : tendsto ma f (π a)) (hb : tendsto mb f (π b)) :
tendsto (Ξ»c, (ma c, mb c)) f (π (a, b)) :=
by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb
lemma filter.eventually.curry_nhds {p : Ξ± Γ Ξ² β Prop} {x : Ξ±} {y : Ξ²} (h : βαΆ x in π (x, y), p x) :
βαΆ x' in π x, βαΆ y' in π y, p (x', y') :=
by { rw [nhds_prod_eq] at h, exact h.curry }
lemma continuous_at.prod {f : Ξ± β Ξ²} {g : Ξ± β Ξ³} {x : Ξ±}
(hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (Ξ»x, (f x, g x)) x :=
hf.prod_mk_nhds hg
lemma continuous_at.prod_map {f : Ξ± β Ξ³} {g : Ξ² β Ξ΄} {p : Ξ± Γ Ξ²}
(hf : continuous_at f p.fst) (hg : continuous_at g p.snd) :
continuous_at (Ξ» p : Ξ± Γ Ξ², (f p.1, g p.2)) p :=
(hf.comp continuous_fst.continuous_at).prod (hg.comp continuous_snd.continuous_at)
lemma continuous_at.prod_map' {f : Ξ± β Ξ³} {g : Ξ² β Ξ΄} {x : Ξ±} {y : Ξ²}
(hf : continuous_at f x) (hg : continuous_at g y) :
continuous_at (Ξ» p : Ξ± Γ Ξ², (f p.1, g p.2)) (x, y) :=
have hf : continuous_at f (x, y).fst, from hf,
have hg : continuous_at g (x, y).snd, from hg,
hf.prod_map hg
lemma prod_generate_from_generate_from_eq {Ξ± : Type*} {Ξ² : Type*} {s : set (set Ξ±)} {t : set (set Ξ²)}
(hs : ββ s = univ) (ht : ββ t = univ) :
@prod.topological_space Ξ± Ξ² (generate_from s) (generate_from t) =
generate_from {g | βuβs, βvβt, g = set.prod u v} :=
let G := generate_from {g | βuβs, βvβt, g = set.prod u v} in
le_antisymm
(le_generate_from $ assume g β¨u, hu, v, hv, g_eqβ©, g_eq.symm βΈ
@is_open.prod _ _ (generate_from s) (generate_from t) _ _
(generate_open.basic _ hu) (generate_open.basic _ hv))
(le_inf
(coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu,
have (βvβt, set.prod u v) = prod.fst β»ΒΉ' u,
from calc (βvβt, set.prod u v) = set.prod u univ :
set.ext $ assume β¨a, bβ©, by rw β ht; simp [and.left_comm] {contextual:=tt}
... = prod.fst β»ΒΉ' u : by simp [set.prod, preimage],
show G.is_open (prod.fst β»ΒΉ' u),
from this βΈ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv,
generate_open.basic _ β¨_, hu, _, hv, rflβ©)
(coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv,
have (βuβs, set.prod u v) = prod.snd β»ΒΉ' v,
from calc (βuβs, set.prod u v) = set.prod univ v:
set.ext $ assume β¨a, bβ©, by rw [βhs]; by_cases b β v; simp [h] {contextual:=tt}
... = prod.snd β»ΒΉ' v : by simp [set.prod, preimage],
show G.is_open (prod.snd β»ΒΉ' v),
from this βΈ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu,
generate_open.basic _ β¨_, hu, _, hv, rflβ©))
lemma prod_eq_generate_from :
prod.topological_space =
generate_from {g | β(s:set Ξ±) (t:set Ξ²), is_open s β§ is_open t β§ g = set.prod s t} :=
le_antisymm
(le_generate_from $ assume g β¨s, t, hs, ht, g_eqβ©, g_eq.symm βΈ hs.prod ht)
(le_inf
(ball_image_of_ball $ Ξ»t ht, generate_open.basic _ β¨t, univ, by simpa [set.prod_eq] using htβ©)
(ball_image_of_ball $ Ξ»t ht, generate_open.basic _ β¨univ, t, by simpa [set.prod_eq] using htβ©))
lemma is_open_prod_iff {s : set (Ξ±ΓΞ²)} : is_open s β
(βa b, (a, b) β s β βu v, is_open u β§ is_open v β§ a β u β§ b β v β§ set.prod u v β s) :=
begin
rw [is_open_iff_nhds],
simp_rw [le_principal_iff, prod.forall,
((nhds_basis_opens _).prod_nhds (nhds_basis_opens _)).mem_iff, prod.exists, exists_prop],
simp only [and_assoc, and.left_comm]
end
/-- Given a neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood
that is a subset of `s`. -/
lemma exists_nhds_square {s : set (Ξ± Γ Ξ±)} {x : Ξ±} (hx : s β π (x, x)) :
βU, is_open U β§ x β U β§ set.prod U U β s :=
by simpa [nhds_prod_eq, (nhds_basis_opens x).prod_self.mem_iff, and.assoc, and.left_comm] using hx
/-- The first projection in a product of topological spaces sends open sets to open sets. -/
lemma is_open_map_fst : is_open_map (@prod.fst Ξ± Ξ²) :=
begin
rw is_open_map_iff_nhds_le,
rintro β¨x, yβ© s hs,
rcases mem_nhds_prod_iff.1 hs with β¨tx, htx, ty, hty, htβ©,
simp only [subset_def, prod.forall, mem_prod] at ht,
exact mem_sets_of_superset htx (Ξ» x hx, ht x y β¨hx, mem_of_nhds htyβ©)
end
/-- The second projection in a product of topological spaces sends open sets to open sets. -/
lemma is_open_map_snd : is_open_map (@prod.snd Ξ± Ξ²) :=
begin
/- This lemma could be proved by composing the fact that the first projection is open, and
exchanging coordinates is a homeomorphism, hence open. As the `prod_comm` homeomorphism is defined
later, we rather go for the direct proof, copy-pasting the proof for the first projection. -/
rw is_open_map_iff_nhds_le,
rintro β¨x, yβ© s hs,
rcases mem_nhds_prod_iff.1 hs with β¨tx, htx, ty, hty, htβ©,
simp only [subset_def, prod.forall, mem_prod] at ht,
exact mem_sets_of_superset hty (Ξ» y hy, ht x y β¨mem_of_nhds htx, hyβ©)
end
/-- A product set is open in a product space if and only if each factor is open, or one of them is
empty -/
lemma is_open_prod_iff' {s : set Ξ±} {t : set Ξ²} :
is_open (set.prod s t) β (is_open s β§ is_open t) β¨ (s = β
) β¨ (t = β
) :=
begin
cases (set.prod s t).eq_empty_or_nonempty with h h,
{ simp [h, prod_eq_empty_iff.1 h] },
{ have st : s.nonempty β§ t.nonempty, from prod_nonempty_iff.1 h,
split,
{ assume H : is_open (set.prod s t),
refine or.inl β¨_, _β©,
show is_open s,
{ rw β fst_image_prod s st.2,
exact is_open_map_fst _ H },
show is_open t,
{ rw β snd_image_prod st.1 t,
exact is_open_map_snd _ H } },
{ assume H,
simp only [st.1.ne_empty, st.2.ne_empty, not_false_iff, or_false] at H,
exact H.1.prod H.2 } }
end
lemma closure_prod_eq {s : set Ξ±} {t : set Ξ²} :
closure (set.prod s t) = set.prod (closure s) (closure t) :=
set.ext $ assume β¨a, bβ©,
have (π a ΓαΆ π b) β π (set.prod s t) = (π a β π s) ΓαΆ (π b β π t),
by rw [βprod_inf_prod, prod_principal_principal],
by simp [closure_eq_cluster_pts, cluster_pt, nhds_prod_eq, this]; exact prod_ne_bot
lemma mem_closure2 {s : set Ξ±} {t : set Ξ²} {u : set Ξ³} {f : Ξ± β Ξ² β Ξ³} {a : Ξ±} {b : Ξ²}
(hf : continuous (Ξ»p:Ξ±ΓΞ², f p.1 p.2)) (ha : a β closure s) (hb : b β closure t)
(hu : βa b, a β s β b β t β f a b β u) :
f a b β closure u :=
have (a, b) β closure (set.prod s t), by rw [closure_prod_eq]; from β¨ha, hbβ©,
show (Ξ»p:Ξ±ΓΞ², f p.1 p.2) (a, b) β closure u, from
mem_closure hf this $ assume β¨a, bβ© β¨ha, hbβ©, hu a b ha hb
lemma is_closed.prod {sβ : set Ξ±} {sβ : set Ξ²} (hβ : is_closed sβ) (hβ : is_closed sβ) :
is_closed (set.prod sβ sβ) :=
closure_eq_iff_is_closed.mp $ by simp only [hβ.closure_eq, hβ.closure_eq, closure_prod_eq]
/-- The product of two dense sets is a dense set. -/
lemma dense.prod {s : set Ξ±} {t : set Ξ²} (hs : dense s) (ht : dense t) :
dense (s.prod t) :=
Ξ» x, by { rw closure_prod_eq, exact β¨hs x.1, ht x.2β© }
/-- If `f` and `g` are maps with dense range, then `prod.map f g` has dense range. -/
lemma dense_range.prod_map {ΞΉ : Type*} {ΞΊ : Type*} {f : ΞΉ β Ξ²} {g : ΞΊ β Ξ³}
(hf : dense_range f) (hg : dense_range g) : dense_range (prod.map f g) :=
by simpa only [dense_range, prod_range_range_eq] using hf.prod hg
lemma inducing.prod_mk {f : Ξ± β Ξ²} {g : Ξ³ β Ξ΄} (hf : inducing f) (hg : inducing g) :
inducing (Ξ»x:Ξ±ΓΞ³, (f x.1, g x.2)) :=
β¨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced,
induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]β©
lemma embedding.prod_mk {f : Ξ± β Ξ²} {g : Ξ³ β Ξ΄} (hf : embedding f) (hg : embedding g) :
embedding (Ξ»x:Ξ±ΓΞ³, (f x.1, g x.2)) :=
{ inj := assume β¨xβ, xββ© β¨yβ, yββ©, by simp; exact assume hβ hβ, β¨hf.inj hβ, hg.inj hββ©,
..hf.to_inducing.prod_mk hg.to_inducing }
protected lemma is_open_map.prod {f : Ξ± β Ξ²} {g : Ξ³ β Ξ΄} (hf : is_open_map f) (hg : is_open_map g) :
is_open_map (Ξ» p : Ξ± Γ Ξ³, (f p.1, g p.2)) :=
begin
rw [is_open_map_iff_nhds_le],
rintros β¨a, bβ©,
rw [nhds_prod_eq, nhds_prod_eq, β filter.prod_map_map_eq],
exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b)
end
protected lemma open_embedding.prod {f : Ξ± β Ξ²} {g : Ξ³ β Ξ΄}
(hf : open_embedding f) (hg : open_embedding g) : open_embedding (Ξ»x:Ξ±ΓΞ³, (f x.1, g x.2)) :=
open_embedding_of_embedding_open (hf.1.prod_mk hg.1)
(hf.is_open_map.prod hg.is_open_map)
lemma embedding_graph {f : Ξ± β Ξ²} (hf : continuous f) : embedding (Ξ»x, (x, f x)) :=
embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id
end prod
section sum
open sum
variables [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³]
@[continuity] lemma continuous_inl : continuous (@inl Ξ± Ξ²) :=
continuous_sup_rng_left continuous_coinduced_rng
@[continuity] lemma continuous_inr : continuous (@inr Ξ± Ξ²) :=
continuous_sup_rng_right continuous_coinduced_rng
@[continuity] lemma continuous_sum_rec {f : Ξ± β Ξ³} {g : Ξ² β Ξ³}
(hf : continuous f) (hg : continuous g) : @continuous (Ξ± β Ξ²) Ξ³ _ _ (@sum.rec Ξ± Ξ² (Ξ»_, Ξ³) f g) :=
continuous_sup_dom hf hg
lemma is_open_sum_iff {s : set (Ξ± β Ξ²)} :
is_open s β is_open (inl β»ΒΉ' s) β§ is_open (inr β»ΒΉ' s) :=
iff.rfl
lemma is_open_map_sum {f : Ξ± β Ξ² β Ξ³}
(hβ : is_open_map (Ξ» a, f (inl a))) (hβ : is_open_map (Ξ» b, f (inr b))) :
is_open_map f :=
begin
intros u hu,
rw is_open_sum_iff at hu,
cases hu with huβ huβ,
have : u = inl '' (inl β»ΒΉ' u) βͺ inr '' (inr β»ΒΉ' u),
{ ext (_|_); simp },
rw [this, set.image_union, set.image_image, set.image_image],
exact is_open_union (hβ _ huβ) (hβ _ huβ)
end
lemma embedding_inl : embedding (@inl Ξ± Ξ²) :=
{ induced := begin
unfold sum.topological_space,
apply le_antisymm,
{ rw β coinduced_le_iff_le_induced, exact le_sup_left },
{ intros u hu, existsi (inl '' u),
change
(is_open (inl β»ΒΉ' (@inl Ξ± Ξ² '' u)) β§
is_open (inr β»ΒΉ' (@inl Ξ± Ξ² '' u))) β§
inl β»ΒΉ' (inl '' u) = u,
have : inl β»ΒΉ' (@inl Ξ± Ξ² '' u) = u :=
preimage_image_eq u (Ξ» _ _, inl.inj_iff.mp), rw this,
have : inr β»ΒΉ' (@inl Ξ± Ξ² '' u) = β
:=
eq_empty_iff_forall_not_mem.mpr (assume a β¨b, _, hβ©, inl_ne_inr h), rw this,
exact β¨β¨hu, is_open_emptyβ©, rflβ© }
end,
inj := Ξ» _ _, inl.inj_iff.mp }
lemma embedding_inr : embedding (@inr Ξ± Ξ²) :=
{ induced := begin
unfold sum.topological_space,
apply le_antisymm,
{ rw β coinduced_le_iff_le_induced, exact le_sup_right },
{ intros u hu, existsi (inr '' u),
change
(is_open (inl β»ΒΉ' (@inr Ξ± Ξ² '' u)) β§
is_open (inr β»ΒΉ' (@inr Ξ± Ξ² '' u))) β§
inr β»ΒΉ' (inr '' u) = u,
have : inl β»ΒΉ' (@inr Ξ± Ξ² '' u) = β
:=
eq_empty_iff_forall_not_mem.mpr (assume b β¨a, _, hβ©, inr_ne_inl h), rw this,
have : inr β»ΒΉ' (@inr Ξ± Ξ² '' u) = u :=
preimage_image_eq u (Ξ» _ _, inr.inj_iff.mp), rw this,
exact β¨β¨is_open_empty, huβ©, rflβ© }
end,
inj := Ξ» _ _, inr.inj_iff.mp }
lemma open_embedding_inl : open_embedding (inl : Ξ± β Ξ± β Ξ²) :=
{ open_range := begin
rw is_open_sum_iff,
convert and.intro is_open_univ is_open_empty;
{ ext, simp }
end,
.. embedding_inl }
lemma open_embedding_inr : open_embedding (inr : Ξ² β Ξ± β Ξ²) :=
{ open_range := begin
rw is_open_sum_iff,
convert and.intro is_open_empty is_open_univ;
{ ext, simp }
end,
.. embedding_inr }
end sum
section subtype
variables [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³] {p : Ξ± β Prop}
lemma embedding_subtype_coe : embedding (coe : subtype p β Ξ±) :=
β¨β¨rflβ©, subtype.coe_injectiveβ©
@[continuity] lemma continuous_subtype_val : continuous (@subtype.val Ξ± p) :=
continuous_induced_dom
lemma continuous_subtype_coe : continuous (coe : subtype p β Ξ±) :=
continuous_subtype_val
lemma is_open.open_embedding_subtype_coe {s : set Ξ±} (hs : is_open s) :
open_embedding (coe : s β Ξ±) :=
{ induced := rfl,
inj := subtype.coe_injective,
open_range := (subtype.range_coe : range coe = s).symm βΈ hs }
lemma is_open.is_open_map_subtype_coe {s : set Ξ±} (hs : is_open s) :
is_open_map (coe : s β Ξ±) :=
hs.open_embedding_subtype_coe.is_open_map
lemma is_open_map.restrict {f : Ξ± β Ξ²} (hf : is_open_map f) {s : set Ξ±} (hs : is_open s) :
is_open_map (s.restrict f) :=
hf.comp hs.is_open_map_subtype_coe
lemma is_closed.closed_embedding_subtype_coe {s : set Ξ±} (hs : is_closed s) :
closed_embedding (coe : {x // x β s} β Ξ±) :=
{ induced := rfl,
inj := subtype.coe_injective,
closed_range := (subtype.range_coe : range coe = s).symm βΈ hs }
@[continuity] lemma continuous_subtype_mk {f : Ξ² β Ξ±}
(hp : βx, p (f x)) (h : continuous f) : continuous (Ξ»x, (β¨f x, hp xβ© : subtype p)) :=
continuous_induced_rng h
lemma continuous_inclusion {s t : set Ξ±} (h : s β t) : continuous (inclusion h) :=
continuous_subtype_mk _ continuous_subtype_coe
lemma continuous_at_subtype_coe {p : Ξ± β Prop} {a : subtype p} :
continuous_at (coe : subtype p β Ξ±) a :=
continuous_iff_continuous_at.mp continuous_subtype_coe _
lemma map_nhds_subtype_coe_eq {a : Ξ±} (ha : p a) (h : {a | p a} β π a) :
map (coe : subtype p β Ξ±) (π β¨a, haβ©) = π a :=
map_nhds_induced_eq $ by simpa only [subtype.coe_mk, subtype.range_coe] using h
lemma nhds_subtype_eq_comap {a : Ξ±} {h : p a} :
π (β¨a, hβ© : subtype p) = comap coe (π a) :=
nhds_induced _ _
lemma tendsto_subtype_rng {Ξ² : Type*} {p : Ξ± β Prop} {b : filter Ξ²} {f : Ξ² β subtype p} :
β{a:subtype p}, tendsto f b (π a) β tendsto (Ξ»x, (f x : Ξ±)) b (π (a : Ξ±))
| β¨a, haβ© := by rw [nhds_subtype_eq_comap, tendsto_comap_iff, subtype.coe_mk]
lemma continuous_subtype_nhds_cover {ΞΉ : Sort*} {f : Ξ± β Ξ²} {c : ΞΉ β Ξ± β Prop}
(c_cover : βx:Ξ±, βi, {x | c i x} β π x)
(f_cont : βi, continuous (Ξ»(x : subtype (c i)), f x)) :
continuous f :=
continuous_iff_continuous_at.mpr $ assume x,
let β¨i, (c_sets : {x | c i x} β π x)β© := c_cover x in
let x' : subtype (c i) := β¨x, mem_of_nhds c_setsβ© in
calc map f (π x) = map f (map coe (π x')) :
congr_arg (map f) (map_nhds_subtype_coe_eq _ $ c_sets).symm
... = map (Ξ»x:subtype (c i), f x) (π x') : rfl
... β€ π (f x) : continuous_iff_continuous_at.mp (f_cont i) x'
lemma continuous_subtype_is_closed_cover {ΞΉ : Sort*} {f : Ξ± β Ξ²} (c : ΞΉ β Ξ± β Prop)
(h_lf : locally_finite (Ξ»i, {x | c i x}))
(h_is_closed : βi, is_closed {x | c i x})
(h_cover : βx, βi, c i x)
(f_cont : βi, continuous (Ξ»(x : subtype (c i)), f x)) :
continuous f :=
continuous_iff_is_closed.mpr $
assume s hs,
have βi, is_closed ((coe : {x | c i x} β Ξ±) '' (f β coe β»ΒΉ' s)),
from assume i,
embedding_is_closed embedding_subtype_coe
(by simp [subtype.range_coe]; exact h_is_closed i)
(continuous_iff_is_closed.mp (f_cont i) _ hs),
have is_closed (βi, (coe : {x | c i x} β Ξ±) '' (f β coe β»ΒΉ' s)),
from is_closed_Union_of_locally_finite
(locally_finite_subset h_lf $ assume i x β¨β¨x', hx'β©, _, heqβ©, heq βΈ hx')
this,
have f β»ΒΉ' s = (βi, (coe : {x | c i x} β Ξ±) '' (f β coe β»ΒΉ' s)),
begin
apply set.ext,
have : β (x : Ξ±), f x β s β β (i : ΞΉ), c i x β§ f x β s :=
Ξ» x, β¨Ξ» hx, let β¨i, hiβ© := h_cover x in β¨i, hi, hxβ©,
Ξ» β¨i, hi, hxβ©, hxβ©,
simpa [and.comm, @and.left_comm (c _ _), β exists_and_distrib_right],
end,
by rwa [this]
lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}:
x β closure s β (x : Ξ±) β closure ((coe : _ β Ξ±) '' s) :=
closure_induced $ assume x y, subtype.eq
end subtype
section quotient
variables [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³]
variables {r : Ξ± β Ξ± β Prop} {s : setoid Ξ±}
lemma quotient_map_quot_mk : quotient_map (@quot.mk Ξ± r) :=
β¨quot.exists_rep, rflβ©
@[continuity] lemma continuous_quot_mk : continuous (@quot.mk Ξ± r) :=
continuous_coinduced_rng
@[continuity] lemma continuous_quot_lift {f : Ξ± β Ξ²} (hr : β a b, r a b β f a = f b)
(h : continuous f) : continuous (quot.lift f hr : quot r β Ξ²) :=
continuous_coinduced_dom h
lemma quotient_map_quotient_mk : quotient_map (@quotient.mk Ξ± s) :=
quotient_map_quot_mk
lemma continuous_quotient_mk : continuous (@quotient.mk Ξ± s) :=
continuous_coinduced_rng
lemma continuous_quotient_lift {f : Ξ± β Ξ²} (hs : β a b, a β b β f a = f b)
(h : continuous f) : continuous (quotient.lift f hs : quotient s β Ξ²) :=
continuous_coinduced_dom h
end quotient
section pi
variables {ΞΉ : Type*} {Ο : ΞΉ β Type*}
@[continuity]
lemma continuous_pi [topological_space Ξ±] [βi, topological_space (Ο i)] {f : Ξ± β Ξ i:ΞΉ, Ο i}
(h : βi, continuous (Ξ»a, f a i)) : continuous f :=
continuous_infi_rng $ assume i, continuous_induced_rng $ h i
@[continuity]
lemma continuous_apply [βi, topological_space (Ο i)] (i : ΞΉ) :
continuous (Ξ»p:Ξ i, Ο i, p i) :=
continuous_infi_dom continuous_induced_dom
/-- Embedding a factor into a product space (by fixing arbitrarily all the other coordinates) is
continuous. -/
@[continuity]
lemma continuous_update [decidable_eq ΞΉ] [βi, topological_space (Ο i)] {i : ΞΉ} {f : Ξ i:ΞΉ, Ο i} :
continuous (Ξ» x : Ο i, function.update f i x) :=
begin
refine continuous_pi (Ξ»j, _),
by_cases h : j = i,
{ rw h,
simpa using continuous_id },
{ simpa [h] using continuous_const }
end
lemma nhds_pi [t : βi, topological_space (Ο i)] {a : Ξ i, Ο i} :
π a = (β¨
i, comap (Ξ»x, x i) (π (a i))) :=
calc π a = (β¨
i, @nhds _ (@topological_space.induced _ _ (Ξ»x:Ξ i, Ο i, x i) (t i)) a) : nhds_infi
... = (β¨
i, comap (Ξ»x, x i) (π (a i))) : by simp [nhds_induced]
lemma tendsto_pi [t : βi, topological_space (Ο i)] {f : Ξ± β Ξ i, Ο i} {g : Ξ i, Ο i} {u : filter Ξ±} :
tendsto f u (π g) β β x, tendsto (Ξ» i, f i x) u (π (g x)) :=
by simp [nhds_pi, filter.tendsto_comap_iff]
lemma is_open_set_pi [βa, topological_space (Ο a)] {i : set ΞΉ} {s : Ξ a, set (Ο a)}
(hi : finite i) (hs : βaβi, is_open (s a)) : is_open (pi i s) :=
by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, continuous_apply a _ $ hs a ha)
lemma pi_eq_generate_from [βa, topological_space (Ο a)] :
Pi.topological_space =
generate_from {g | β(s:Ξ a, set (Ο a)) (i : finset ΞΉ), (βaβi, is_open (s a)) β§ g = pi βi s} :=
le_antisymm
(le_generate_from $ assume g β¨s, i, hi, eqβ©, eq.symm βΈ is_open_set_pi (finset.finite_to_set _) hi)
(le_infi $ assume a s β¨t, ht, s_eqβ©, generate_open.basic _ $
β¨function.update (Ξ»a, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]β©)
lemma pi_generate_from_eq {g : Ξ a, set (set (Ο a))} :
@Pi.topological_space ΞΉ Ο (Ξ»a, generate_from (g a)) =
generate_from {t | β(s:Ξ a, set (Ο a)) (i : finset ΞΉ), (βaβi, s a β g a) β§ t = pi βi s} :=
let G := {t | β(s:Ξ a, set (Ο a)) (i : finset ΞΉ), (βaβi, s a β g a) β§ t = pi βi s} in
begin
rw [pi_eq_generate_from],
refine le_antisymm (generate_from_mono _) (le_generate_from _),
exact assume s β¨t, i, ht, eqβ©, β¨t, i, assume a ha, generate_open.basic _ (ht a ha), eqβ©,
{ rintros s β¨t, i, hi, rflβ©,
rw [pi_def],
apply is_open_bInter (finset.finite_to_set _),
assume a ha, show ((generate_from G).coinduced (Ξ»f:Ξ a, Ο a, f a)).is_open (t a),
refine le_generate_from _ _ (hi a ha),
exact assume s hs, generate_open.basic _ β¨function.update (Ξ»a, univ) a s, {a}, by simp [hs]β© }
end
lemma pi_generate_from_eq_fintype {g : Ξ a, set (set (Ο a))} [fintype ΞΉ] (hg : βa, ββ g a = univ) :
@Pi.topological_space ΞΉ Ο (Ξ»a, generate_from (g a)) =
generate_from {t | β(s:Ξ a, set (Ο a)), (βa, s a β g a) β§ t = pi univ s} :=
let G := {t | β(s:Ξ a, set (Ο a)), (βa, s a β g a) β§ t = pi univ s} in
begin
rw [pi_generate_from_eq],
refine le_antisymm (generate_from_mono _) (le_generate_from _),
exact assume s β¨t, ht, eqβ©, β¨t, finset.univ, by simp [ht, eq]β©,
{ rintros s β¨t, i, ht, rflβ©,
apply is_open_iff_forall_mem_open.2 _,
assume f hf,
choose c hc using show βa, βs, s β g a β§ f a β s,
{ assume a, have : f a β ββ g a, { rw [hg], apply mem_univ }, simpa },
refine β¨pi univ (Ξ»a, if a β i then t a else (c : Ξ a, set (Ο a)) a), _, _, _β©,
{ simp [pi_if] },
{ refine generate_open.basic _ β¨_, assume a, _, rflβ©,
by_cases a β i; simp [*, pi] at * },
{ have : f β pi {a | a β i} c, { simp [*, pi] at * },
simpa [pi_if, hf] } }
end
end pi
section sigma
variables {ΞΉ : Type*} {Ο : ΞΉ β Type*} [Ξ i, topological_space (Ο i)]
@[continuity]
lemma continuous_sigma_mk {i : ΞΉ} : continuous (@sigma.mk ΞΉ Ο i) :=
continuous_supr_rng continuous_coinduced_rng
lemma is_open_sigma_iff {s : set (sigma Ο)} : is_open s β β i, is_open (sigma.mk i β»ΒΉ' s) :=
by simp only [is_open_supr_iff, is_open_coinduced]
lemma is_closed_sigma_iff {s : set (sigma Ο)} : is_closed s β β i, is_closed (sigma.mk i β»ΒΉ' s) :=
is_open_sigma_iff
lemma is_open_map_sigma_mk {i : ΞΉ} : is_open_map (@sigma.mk ΞΉ Ο i) :=
begin
intros s hs,
rw is_open_sigma_iff,
intro j,
classical,
by_cases h : i = j,
{ subst j,
convert hs,
exact set.preimage_image_eq _ sigma_mk_injective },
{ convert is_open_empty,
apply set.eq_empty_of_subset_empty,
rintro x β¨y, _, hyβ©,
have : i = j, by cc,
contradiction }
end
lemma is_open_range_sigma_mk {i : ΞΉ} : is_open (set.range (@sigma.mk ΞΉ Ο i)) :=
by { rw βset.image_univ, exact is_open_map_sigma_mk _ is_open_univ }
lemma is_closed_map_sigma_mk {i : ΞΉ} : is_closed_map (@sigma.mk ΞΉ Ο i) :=
begin
intros s hs,
rw is_closed_sigma_iff,
intro j,
classical,
by_cases h : i = j,
{ subst j,
convert hs,
exact set.preimage_image_eq _ sigma_mk_injective },
{ convert is_closed_empty,
apply set.eq_empty_of_subset_empty,
rintro x β¨y, _, hyβ©,
have : i = j, by cc,
contradiction }
end
lemma is_closed_sigma_mk {i : ΞΉ} : is_closed (set.range (@sigma.mk ΞΉ Ο i)) :=
by { rw βset.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ }
lemma open_embedding_sigma_mk {i : ΞΉ} : open_embedding (@sigma.mk ΞΉ Ο i) :=
open_embedding_of_continuous_injective_open
continuous_sigma_mk sigma_mk_injective is_open_map_sigma_mk
lemma closed_embedding_sigma_mk {i : ΞΉ} : closed_embedding (@sigma.mk ΞΉ Ο i) :=
closed_embedding_of_continuous_injective_closed
continuous_sigma_mk sigma_mk_injective is_closed_map_sigma_mk
lemma embedding_sigma_mk {i : ΞΉ} : embedding (@sigma.mk ΞΉ Ο i) :=
closed_embedding_sigma_mk.1
/-- A map out of a sum type is continuous if its restriction to each summand is. -/
@[continuity]
lemma continuous_sigma [topological_space Ξ²] {f : sigma Ο β Ξ²}
(h : β i, continuous (Ξ» a, f β¨i, aβ©)) : continuous f :=
continuous_supr_dom (Ξ» i, continuous_coinduced_dom (h i))
@[continuity]
lemma continuous_sigma_map {ΞΊ : Type*} {Ο : ΞΊ β Type*} [Ξ k, topological_space (Ο k)]
{fβ : ΞΉ β ΞΊ} {fβ : Ξ i, Ο i β Ο (fβ i)} (hf : β i, continuous (fβ i)) :
continuous (sigma.map fβ fβ) :=
continuous_sigma $ Ξ» i,
show continuous (Ξ» a, sigma.mk (fβ i) (fβ i a)),
from continuous_sigma_mk.comp (hf i)
lemma is_open_map_sigma [topological_space Ξ²] {f : sigma Ο β Ξ²}
(h : β i, is_open_map (Ξ» a, f β¨i, aβ©)) : is_open_map f :=
begin
intros s hs,
rw is_open_sigma_iff at hs,
have : s = β i, sigma.mk i '' (sigma.mk i β»ΒΉ' s),
{ rw Union_image_preimage_sigma_mk_eq_self },
rw this,
rw [image_Union],
apply is_open_Union,
intro i,
rw [image_image],
exact h i _ (hs i)
end
/-- The sum of embeddings is an embedding. -/
lemma embedding_sigma_map {Ο : ΞΉ β Type*} [Ξ i, topological_space (Ο i)]
{f : Ξ i, Ο i β Ο i} (hf : β i, embedding (f i)) : embedding (sigma.map id f) :=
begin
refine β¨β¨_β©, function.injective_id.sigma_map (Ξ» i, (hf i).inj)β©,
refine le_antisymm
(continuous_iff_le_induced.mp (continuous_sigma_map (Ξ» i, (hf i).continuous))) _,
intros s hs,
replace hs := is_open_sigma_iff.mp hs,
have : β i, β t, is_open t β§ f i β»ΒΉ' t = sigma.mk i β»ΒΉ' s,
{ intro i,
apply is_open_induced_iff.mp,
convert hs i,
exact (hf i).induced.symm },
choose t ht using this,
apply is_open_induced_iff.mpr,
refine β¨β i, sigma.mk i '' t i, is_open_Union (Ξ» i, is_open_map_sigma_mk _ (ht i).1), _β©,
ext β¨i, xβ©,
change (sigma.mk i (f i x) β β (i : ΞΉ), sigma.mk i '' t i) β x β sigma.mk i β»ΒΉ' s,
rw [β(ht i).2, mem_Union],
split,
{ rintro β¨j, hjβ©,
rw mem_image at hj,
rcases hj with β¨y, hyβ, hyββ©,
rcases sigma.mk.inj_iff.mp hyβ with β¨rfl, hyβ©,
replace hy := eq_of_heq hy,
subst y,
exact hyβ },
{ intro hx,
use i,
rw mem_image,
exact β¨f i x, hx, rflβ© }
end
end sigma
section ulift
@[continuity] lemma continuous_ulift_down [topological_space Ξ±] :
continuous (ulift.down : ulift.{v u} Ξ± β Ξ±) :=
continuous_induced_dom
@[continuity] lemma continuous_ulift_up [topological_space Ξ±] :
continuous (ulift.up : Ξ± β ulift.{v u} Ξ±) :=
continuous_induced_rng continuous_id
end ulift
lemma mem_closure_of_continuous [topological_space Ξ±] [topological_space Ξ²]
{f : Ξ± β Ξ²} {a : Ξ±} {s : set Ξ±} {t : set Ξ²}
(hf : continuous f) (ha : a β closure s) (h : maps_to f s (closure t)) :
f a β closure t :=
calc f a β f '' closure s : mem_image_of_mem _ ha
... β closure (f '' s) : image_closure_subset_closure_image hf
... β closure t : closure_minimal h.image_subset is_closed_closure
lemma mem_closure_of_continuous2 [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³]
{f : Ξ± β Ξ² β Ξ³} {a : Ξ±} {b : Ξ²} {s : set Ξ±} {t : set Ξ²} {u : set Ξ³}
(hf : continuous (Ξ»p:Ξ±ΓΞ², f p.1 p.2)) (ha : a β closure s) (hb : b β closure t)
(h : βaβs, βbβt, f a b β closure u) :
f a b β closure u :=
have (a,b) β closure (set.prod s t),
by simp [closure_prod_eq, ha, hb],
show f (a, b).1 (a, b).2 β closure u,
from @mem_closure_of_continuous (Ξ±ΓΞ²) _ _ _ (Ξ»p:Ξ±ΓΞ², f p.1 p.2) (a,b) _ u hf this $
assume β¨pβ, pββ© β¨hβ, hββ©, h pβ hβ pβ hβ
|
6054f5414ddfcf106ffcba4729e6b4b510ff99dd | eecbdfcd97327701a240f05d64290a19a45d198a | /type_classes/basic.lean | fff6177348b1522cd0dacc00da212986bd6dcb24 | [] | no_license | johoelzl/hanoifabs | d5ca27df51f9bccfb0152f03b480e9e1228a4b14 | 4235c6bc5d664897bbf5dde04e2237e4b20c9170 | refs/heads/master | 1,584,514,375,379 | 1,528,258,129,000 | 1,528,258,129,000 | 134,419,383 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 1,749 | lean | /- Tips and Tricks for the Type Class Hierarchy -/
/-
Type classes are the go to approach to model mathematical abstractions.
* To work with type classes the elaborator needs a way to find a unique instance.
Usually this is a type, sometimes its an operator.
* Use when when things are easy to index (usually by their type)
* Don't use them when you have multiple instances per index
* Uniqueness is important (at least by defeq), otherwise the elaborator fails at unexpected
places
* If you're lucky your theory has only one spine, i.e. a inheritance chain Γ la A β B β C β D
* Syntactic type classes (pure data):
`class has_add (Ξ± : Type*) := (add : Ξ± β Ξ± β Ξ±)`
* in Type
* only one syntactic element (e.g. +)
* no properties attached
* Property classes (in Prop): (TODO: is this the right name?)
`class is_commutative (Ξ± : Type*) (op : Ξ± β Ξ± β Ξ±) := (comm : βa b, op a b = op b a)`
* in Prop
* no data elements
* can depend on other type classes either by inheritance or by parameters
* Balance between
* Example: Topological structures in mathlib:
* `topological_space` β `uniform_space` β `metric_space`
* confusing for mathematicans: each metric space has a uniform space, has a topological space
assigned
* why not have separat type classes with relation instances?
-> wanted definitional equality & uniqueness
* another solution: have relational classes
`ordered_topology (Ξ± : Type*) [topological_space Ξ±] [preorder Ξ±] : Prop`
annoying to use, needs a long list of parameters for each abstract definition / theorem
-/
/-
TODO: reading the type class inference trace
-/ |
97315351d34a298117949937d36d536e4aa5bcb2 | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /examples/lean/set.lean | 7e2218d480cbc521623b8df379710ae83dc7f7a5 | [
"Apache-2.0"
] | permissive | codyroux/lean0.1 | 1ce92751d664aacff0529e139083304a7bbc8a71 | 0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef | refs/heads/master | 1,610,830,535,062 | 1,402,150,480,000 | 1,402,150,480,000 | 19,588,851 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 946 | lean | import macros
definition Set (A : Type) : Type := A β Bool
definition element {A : Type} (x : A) (s : Set A) := s x
infix 60 β : element
definition subset {A : Type} (s1 : Set A) (s2 : Set A) := β x, x β s1 β x β s2
infix 50 β : subset
theorem subset_trans {A : Type} {s1 s2 s3 : Set A} (H1 : s1 β s2) (H2 : s2 β s3) : s1 β s3
:= take x : A,
assume Hin : x β s1,
show x β s3, from
let L1 : x β s2 := H1 x Hin
in H2 x L1
theorem subset_ext {A : Type} {s1 s2 : Set A} (H : β x, x β s1 = x β s2) : s1 = s2
:= funext H
theorem subset_antisym {A : Type} {s1 s2 : Set A} (H1 : s1 β s2) (H2 : s2 β s1) : s1 = s2
:= subset_ext (show (β x, x β s1 = x β s2), from
take x, show x β s1 = x β s2, from
boolext (show x β s1 β x β s2, from H1 x)
(show x β s2 β x β s1, from H2 x))
|
8d8d1bf0ce4f8eee852f232db5512c020a880899 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/ring_theory/nilpotent.lean | c9ed1871557ce1382138189064986905729023ca | [
"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 | 5,492 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import data.nat.choose.sum
import algebra.algebra.bilinear
import ring_theory.ideal.operations
/-!
# Nilpotent elements
## Main definitions
* `is_nilpotent`
* `is_nilpotent_neg_iff`
* `commute.is_nilpotent_add`
* `commute.is_nilpotent_mul_left`
* `commute.is_nilpotent_mul_right`
* `commute.is_nilpotent_sub`
-/
universes u v
variables {R S : Type u} {x y : R}
/-- An element is said to be nilpotent if some natural-number-power of it equals zero.
Note that we require only the bare minimum assumptions for the definition to make sense. Even
`monoid_with_zero` is too strong since nilpotency is important in the study of rings that are only
power-associative. -/
def is_nilpotent [has_zero R] [has_pow R β] (x : R) : Prop := β (n : β), x^n = 0
lemma is_nilpotent.mk [has_zero R] [has_pow R β] (x : R) (n : β)
(e : x ^ n = 0) : is_nilpotent x := β¨n, eβ©
lemma is_nilpotent.zero [monoid_with_zero R] : is_nilpotent (0 : R) := β¨1, pow_one 0β©
lemma is_nilpotent.neg [ring R] (h : is_nilpotent x) : is_nilpotent (-x) :=
begin
obtain β¨n, hnβ© := h,
use n,
rw [neg_pow, hn, mul_zero],
end
@[simp] lemma is_nilpotent_neg_iff [ring R] : is_nilpotent (-x) β is_nilpotent x :=
β¨Ξ» h, neg_neg x βΈ h.neg, Ξ» h, h.negβ©
lemma is_nilpotent.map [monoid_with_zero R] [monoid_with_zero S] {r : R}
{F : Type*} [monoid_with_zero_hom_class F R S] (hr : is_nilpotent r) (f : F) :
is_nilpotent (f r) :=
by { use hr.some, rw [β map_pow, hr.some_spec, map_zero] }
/-- A structure that has zero and pow is reduced if it has no nonzero nilpotent elements. -/
class is_reduced (R : Type*) [has_zero R] [has_pow R β] : Prop :=
(eq_zero : β (x : R), is_nilpotent x β x = 0)
@[priority 900]
instance is_reduced_of_no_zero_divisors [monoid_with_zero R] [no_zero_divisors R] : is_reduced R :=
β¨Ξ» _ β¨_, hnβ©, pow_eq_zero hnβ©
@[priority 900]
instance is_reduced_of_subsingleton [has_zero R] [has_pow R β] [subsingleton R] :
is_reduced R := β¨Ξ» _ _, subsingleton.elim _ _β©
lemma is_nilpotent.eq_zero [has_zero R] [has_pow R β] [is_reduced R]
(h : is_nilpotent x) : x = 0 :=
is_reduced.eq_zero x h
@[simp] lemma is_nilpotent_iff_eq_zero [monoid_with_zero R] [is_reduced R] :
is_nilpotent x β x = 0 :=
β¨Ξ» h, h.eq_zero, Ξ» h, h.symm βΈ is_nilpotent.zeroβ©
lemma is_reduced_of_injective [monoid_with_zero R] [monoid_with_zero S]
{F : Type*} [monoid_with_zero_hom_class F R S] (f : F)
(hf : function.injective f) [_root_.is_reduced S] : _root_.is_reduced R :=
begin
constructor,
intros x hx,
apply hf,
rw map_zero,
exact (hx.map f).eq_zero,
end
namespace commute
section semiring
variables [semiring R] (h_comm : commute x y)
include h_comm
lemma is_nilpotent_add (hx : is_nilpotent x) (hy : is_nilpotent y) : is_nilpotent (x + y) :=
begin
obtain β¨n, hnβ© := hx,
obtain β¨m, hmβ© := hy,
use n + m - 1,
rw h_comm.add_pow',
apply finset.sum_eq_zero,
rintros β¨i, jβ© hij,
suffices : x^i * y^j = 0, { simp only [this, nsmul_eq_mul, mul_zero], },
cases nat.le_or_le_of_add_eq_add_pred (finset.nat.mem_antidiagonal.mp hij) with hi hj,
{ rw [pow_eq_zero_of_le hi hn, zero_mul], },
{ rw [pow_eq_zero_of_le hj hm, mul_zero], },
end
lemma is_nilpotent_mul_left (h : is_nilpotent x) : is_nilpotent (x * y) :=
begin
obtain β¨n, hnβ© := h,
use n,
rw [h_comm.mul_pow, hn, zero_mul],
end
lemma is_nilpotent_mul_right (h : is_nilpotent y) : is_nilpotent (x * y) :=
by { rw h_comm.eq, exact h_comm.symm.is_nilpotent_mul_left h, }
end semiring
section ring
variables [ring R] (h_comm : commute x y)
include h_comm
lemma is_nilpotent_sub (hx : is_nilpotent x) (hy : is_nilpotent y) : is_nilpotent (x - y) :=
begin
rw β neg_right_iff at h_comm,
rw β is_nilpotent_neg_iff at hy,
rw sub_eq_add_neg,
exact h_comm.is_nilpotent_add hx hy,
end
end ring
end commute
section comm_semiring
variable [comm_semiring R]
/-- The nilradical of a commutative semiring is the ideal of nilpotent elements. -/
def nilradical (R : Type*) [comm_semiring R] : ideal R := (0 : ideal R).radical
lemma mem_nilradical : x β nilradical R β is_nilpotent x := iff.rfl
lemma nilradical_eq_Inf (R : Type*) [comm_semiring R] :
nilradical R = Inf { J : ideal R | J.is_prime } :=
by { convert ideal.radical_eq_Inf 0, simp }
lemma nilpotent_iff_mem_prime : is_nilpotent x β β (J : ideal R), J.is_prime β x β J :=
by { rw [β mem_nilradical, nilradical_eq_Inf, submodule.mem_Inf], refl }
lemma nilradical_le_prime (J : ideal R) [H : J.is_prime] : nilradical R β€ J :=
(nilradical_eq_Inf R).symm βΈ Inf_le H
@[simp] lemma nilradical_eq_zero (R : Type*) [comm_semiring R] [is_reduced R] : nilradical R = 0 :=
ideal.ext $ Ξ» _, is_nilpotent_iff_eq_zero
end comm_semiring
namespace algebra
variables (R) {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
@[simp] lemma is_nilpotent_lmul_left_iff (a : A) :
is_nilpotent (lmul_left R a) β is_nilpotent a :=
begin
split; rintros β¨n, hnβ©; use n;
simp only [lmul_left_eq_zero_iff, pow_lmul_left] at β’ hn;
exact hn,
end
@[simp] lemma is_nilpotent_lmul_right_iff (a : A) :
is_nilpotent (lmul_right R a) β is_nilpotent a :=
begin
split; rintros β¨n, hnβ©; use n;
simp only [lmul_right_eq_zero_iff, pow_lmul_right] at β’ hn;
exact hn,
end
end algebra
|
fb3792b16929cc996be930547c7fb8eda8d85a34 | 367134ba5a65885e863bdc4507601606690974c1 | /src/topology/metric_space/gluing.lean | 61bcd9bbe26dc8e37c02025509d37ee0ff650a81 | [
"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 | 23,193 | lean | /-
Copyright (c) 2019 SΓ©bastien GouΓ«zel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Gluing metric spaces
Authors: SΓ©bastien GouΓ«zel
-/
import topology.metric_space.isometry
import topology.metric_space.premetric_space
/-!
# Metric space gluing
Gluing two metric spaces along a common subset. Formally, we are given
```
Ξ¦
Ξ³ ---> Ξ±
|
|Ξ¨
v
Ξ²
```
where `hΦ : isometry Φ` and `hΨ : isometry Ψ`.
We want to complete the square by a space `glue_space hΦ hΨ` and two isometries
`to_glue_l hΦ hΨ` and `to_glue_r hΦ hΨ` that make the square commute.
We start by defining a predistance on the disjoint union `Ξ± β Ξ²`, for which
points `Ξ¦ p` and `Ξ¨ p` are at distance 0. The (quotient) metric space associated
to this predistance is the desired space.
This is an instance of a more general construction, where `Ξ¦` and `Ξ¨` do not have to be isometries,
but the distances in the image almost coincide, up to `2Ξ΅` say. Then one can almost glue the two
spaces so that the images of a point under `Ξ¦` and `Ξ¨` are Ξ΅-close. If `Ξ΅ > 0`, this yields a metric
space structure on `Ξ± β Ξ²`, without the need to take a quotient. In particular, when `Ξ±` and `Ξ²` are
inhabited, this gives a natural metric space structure on `Ξ± β Ξ²`, where the basepoints are at
distance 1, say, and the distances between other points are obtained by going through the two
basepoints.
We also define the inductive limit of metric spaces. Given
```
f 0 f 1 f 2 f 3
X 0 -----> X 1 -----> X 2 -----> X 3 -----> ...
```
where the `X n` are metric spaces and `f n` isometric embeddings, we define the inductive
limit of the `X n`, also known as the increasing union of the `X n` in this context, if we
identify `X n` and `X (n+1)` through `f n`. This is a metric space in which all `X n` embed
isometrically and in a way compatible with `f n`.
-/
noncomputable theory
universes u v w
variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w}
open function set premetric
open_locale uniformity
namespace metric
section approx_gluing
variables [metric_space Ξ±] [metric_space Ξ²]
{Ξ¦ : Ξ³ β Ξ±} {Ξ¨ : Ξ³ β Ξ²} {Ξ΅ : β}
open sum (inl inr)
/-- Define a predistance on Ξ± β Ξ², for which Ξ¦ p and Ξ¨ p are at distance Ξ΅ -/
def glue_dist (Ξ¦ : Ξ³ β Ξ±) (Ξ¨ : Ξ³ β Ξ²) (Ξ΅ : β) : Ξ± β Ξ² β Ξ± β Ξ² β β
| (inl x) (inl y) := dist x y
| (inr x) (inr y) := dist x y
| (inl x) (inr y) := (β¨
p, dist x (Ξ¦ p) + dist y (Ξ¨ p)) + Ξ΅
| (inr x) (inl y) := (β¨
p, dist y (Ξ¦ p) + dist x (Ξ¨ p)) + Ξ΅
private lemma glue_dist_self (Ξ¦ : Ξ³ β Ξ±) (Ξ¨ : Ξ³ β Ξ²) (Ξ΅ : β) : βx, glue_dist Ξ¦ Ξ¨ Ξ΅ x x = 0
| (inl x) := dist_self _
| (inr x) := dist_self _
lemma glue_dist_glued_points [nonempty Ξ³] (Ξ¦ : Ξ³ β Ξ±) (Ξ¨ : Ξ³ β Ξ²) (Ξ΅ : β) (p : Ξ³) :
glue_dist Ξ¦ Ξ¨ Ξ΅ (inl (Ξ¦ p)) (inr (Ξ¨ p)) = Ξ΅ :=
begin
have : (β¨
q, dist (Ξ¦ p) (Ξ¦ q) + dist (Ξ¨ p) (Ξ¨ q)) = 0,
{ have A : βq, 0 β€ dist (Ξ¦ p) (Ξ¦ q) + dist (Ξ¨ p) (Ξ¨ q) :=
Ξ»q, by rw β add_zero (0 : β); exact add_le_add dist_nonneg dist_nonneg,
refine le_antisymm _ (le_cinfi A),
have : 0 = dist (Ξ¦ p) (Ξ¦ p) + dist (Ξ¨ p) (Ξ¨ p), by simp,
rw this,
exact cinfi_le β¨0, forall_range_iff.2 Aβ© p },
rw [glue_dist, this, zero_add]
end
private lemma glue_dist_comm (Ξ¦ : Ξ³ β Ξ±) (Ξ¨ : Ξ³ β Ξ²) (Ξ΅ : β) :
βx y, glue_dist Ξ¦ Ξ¨ Ξ΅ x y = glue_dist Ξ¦ Ξ¨ Ξ΅ y x
| (inl x) (inl y) := dist_comm _ _
| (inr x) (inr y) := dist_comm _ _
| (inl x) (inr y) := rfl
| (inr x) (inl y) := rfl
variable [nonempty Ξ³]
private lemma glue_dist_triangle (Ξ¦ : Ξ³ β Ξ±) (Ξ¨ : Ξ³ β Ξ²) (Ξ΅ : β)
(H : βp q, abs (dist (Ξ¦ p) (Ξ¦ q) - dist (Ξ¨ p) (Ξ¨ q)) β€ 2 * Ξ΅) :
βx y z, glue_dist Ξ¦ Ξ¨ Ξ΅ x z β€ glue_dist Ξ¦ Ξ¨ Ξ΅ x y + glue_dist Ξ¦ Ξ¨ Ξ΅ y z
| (inl x) (inl y) (inl z) := dist_triangle _ _ _
| (inr x) (inr y) (inr z) := dist_triangle _ _ _
| (inr x) (inl y) (inl z) := begin
have B : βa b, bdd_below (range (Ξ» (p : Ξ³), dist a (Ξ¦ p) + dist b (Ξ¨ p))) :=
Ξ»a b, β¨0, forall_range_iff.2 (Ξ»p, add_nonneg dist_nonneg dist_nonneg)β©,
unfold glue_dist,
have : (β¨
p, dist z (Ξ¦ p) + dist x (Ξ¨ p)) β€ (β¨
p, dist y (Ξ¦ p) + dist x (Ξ¨ p)) + dist y z,
{ have : (β¨
p, dist y (Ξ¦ p) + dist x (Ξ¨ p)) + dist y z =
infi ((Ξ»t, t + dist y z) β (Ξ»p, dist y (Ξ¦ p) + dist x (Ξ¨ p))),
{ refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _
(B _ _),
intros x y hx, simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (Ξ»p, _),
calc
dist z (Ξ¦ p) + dist x (Ξ¨ p) β€ (dist y z + dist y (Ξ¦ p)) + dist x (Ξ¨ p) :
add_le_add (dist_triangle_left _ _ _) (le_refl _)
... = dist y (Ξ¦ p) + dist x (Ξ¨ p) + dist y z : by ring },
linarith
end
| (inr x) (inr y) (inl z) := begin
have B : βa b, bdd_below (range (Ξ» (p : Ξ³), dist a (Ξ¦ p) + dist b (Ξ¨ p))) :=
Ξ»a b, β¨0, forall_range_iff.2 (Ξ»p, add_nonneg dist_nonneg dist_nonneg)β©,
unfold glue_dist,
have : (β¨
p, dist z (Ξ¦ p) + dist x (Ξ¨ p)) β€ dist x y + β¨
p, dist z (Ξ¦ p) + dist y (Ξ¨ p),
{ have : dist x y + (β¨
p, dist z (Ξ¦ p) + dist y (Ξ¨ p)) =
infi ((Ξ»t, dist x y + t) β (Ξ»p, dist z (Ξ¦ p) + dist y (Ξ¨ p))),
{ refine map_cinfi_of_continuous_at_of_monotone (continuous_at_const.add continuous_at_id) _
(B _ _),
intros x y hx, simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (Ξ»p, _),
calc
dist z (Ξ¦ p) + dist x (Ξ¨ p) β€ dist z (Ξ¦ p) + (dist x y + dist y (Ξ¨ p)) :
add_le_add (le_refl _) (dist_triangle _ _ _)
... = dist x y + (dist z (Ξ¦ p) + dist y (Ξ¨ p)) : by ring },
linarith
end
| (inl x) (inl y) (inr z) := begin
have B : βa b, bdd_below (range (Ξ» (p : Ξ³), dist a (Ξ¦ p) + dist b (Ξ¨ p))) :=
Ξ»a b, β¨0, forall_range_iff.2 (Ξ»p, add_nonneg dist_nonneg dist_nonneg)β©,
unfold glue_dist,
have : (β¨
p, dist x (Ξ¦ p) + dist z (Ξ¨ p)) β€ dist x y + β¨
p, dist y (Ξ¦ p) + dist z (Ξ¨ p),
{ have : dist x y + (β¨
p, dist y (Ξ¦ p) + dist z (Ξ¨ p)) =
infi ((Ξ»t, dist x y + t) β (Ξ»p, dist y (Ξ¦ p) + dist z (Ξ¨ p))),
{ refine map_cinfi_of_continuous_at_of_monotone (continuous_at_const.add continuous_at_id) _
(B _ _),
intros x y hx, simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (Ξ»p, _),
calc
dist x (Ξ¦ p) + dist z (Ξ¨ p) β€ (dist x y + dist y (Ξ¦ p)) + dist z (Ξ¨ p) :
add_le_add (dist_triangle _ _ _) (le_refl _)
... = dist x y + (dist y (Ξ¦ p) + dist z (Ξ¨ p)) : by ring },
linarith
end
| (inl x) (inr y) (inr z) := begin
have B : βa b, bdd_below (range (Ξ» (p : Ξ³), dist a (Ξ¦ p) + dist b (Ξ¨ p))) :=
Ξ»a b, β¨0, forall_range_iff.2 (Ξ»p, add_nonneg dist_nonneg dist_nonneg)β©,
unfold glue_dist,
have : (β¨
p, dist x (Ξ¦ p) + dist z (Ξ¨ p)) β€ (β¨
p, dist x (Ξ¦ p) + dist y (Ξ¨ p)) + dist y z,
{ have : (β¨
p, dist x (Ξ¦ p) + dist y (Ξ¨ p)) + dist y z =
infi ((Ξ»t, t + dist y z) β (Ξ»p, dist x (Ξ¦ p) + dist y (Ξ¨ p))),
{ refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _
(B _ _),
intros x y hx, simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (Ξ»p, _),
calc
dist x (Ξ¦ p) + dist z (Ξ¨ p) β€ dist x (Ξ¦ p) + (dist y z + dist y (Ξ¨ p)) :
add_le_add (le_refl _) (dist_triangle_left _ _ _)
... = dist x (Ξ¦ p) + dist y (Ξ¨ p) + dist y z : by ring },
linarith
end
| (inl x) (inr y) (inl z) := le_of_forall_pos_le_add $ λδ δpos, begin
obtain β¨p, hpβ© : β p, dist x (Ξ¦ p) + dist y (Ξ¨ p) < (β¨
p, dist x (Ξ¦ p) + dist y (Ξ¨ p)) + Ξ΄ / 2,
from exists_lt_of_cinfi_lt (by linarith),
obtain β¨q, hqβ© : β q, dist z (Ξ¦ q) + dist y (Ξ¨ q) < (β¨
p, dist z (Ξ¦ p) + dist y (Ξ¨ p)) + Ξ΄ / 2,
from exists_lt_of_cinfi_lt (by linarith),
have : dist (Ξ¦ p) (Ξ¦ q) β€ dist (Ξ¨ p) (Ξ¨ q) + 2 * Ξ΅,
{ have := le_trans (le_abs_self _) (H p q), by linarith },
calc dist x z β€ dist x (Ξ¦ p) + dist (Ξ¦ p) (Ξ¦ q) + dist (Ξ¦ q) z : dist_triangle4 _ _ _ _
... β€ dist x (Ξ¦ p) + dist (Ξ¨ p) (Ξ¨ q) + dist z (Ξ¦ q) + 2 * Ξ΅ : by rw [dist_comm z]; linarith
... β€ dist x (Ξ¦ p) + (dist y (Ξ¨ p) + dist y (Ξ¨ q)) + dist z (Ξ¦ q) + 2 * Ξ΅ :
add_le_add (add_le_add (add_le_add (le_refl _) (dist_triangle_left _ _ _)) le_rfl) le_rfl
... β€ ((β¨
p, dist x (Ξ¦ p) + dist y (Ξ¨ p)) + Ξ΅) +
((β¨
p, dist z (Ξ¦ p) + dist y (Ξ¨ p)) + Ξ΅) + Ξ΄ : by linarith
end
| (inr x) (inl y) (inr z) := le_of_forall_pos_le_add $ λδ δpos, begin
obtain β¨p, hpβ© : β p, dist y (Ξ¦ p) + dist x (Ξ¨ p) < (β¨
p, dist y (Ξ¦ p) + dist x (Ξ¨ p)) + Ξ΄ / 2,
from exists_lt_of_cinfi_lt (by linarith),
obtain β¨q, hqβ© : β q, dist y (Ξ¦ q) + dist z (Ξ¨ q) < (β¨
p, dist y (Ξ¦ p) + dist z (Ξ¨ p)) + Ξ΄ / 2,
from exists_lt_of_cinfi_lt (by linarith),
have : dist (Ξ¨ p) (Ξ¨ q) β€ dist (Ξ¦ p) (Ξ¦ q) + 2 * Ξ΅,
{ have := le_trans (neg_le_abs_self _) (H p q), by linarith },
calc dist x z β€ dist x (Ξ¨ p) + dist (Ξ¨ p) (Ξ¨ q) + dist (Ξ¨ q) z : dist_triangle4 _ _ _ _
... β€ dist x (Ξ¨ p) + dist (Ξ¦ p) (Ξ¦ q) + dist z (Ξ¨ q) + 2 * Ξ΅ : by rw [dist_comm z]; linarith
... β€ dist x (Ξ¨ p) + (dist y (Ξ¦ p) + dist y (Ξ¦ q)) + dist z (Ξ¨ q) + 2 * Ξ΅ :
add_le_add (add_le_add (add_le_add le_rfl (dist_triangle_left _ _ _)) le_rfl) le_rfl
... β€ ((β¨
p, dist y (Ξ¦ p) + dist x (Ξ¨ p)) + Ξ΅) +
((β¨
p, dist y (Ξ¦ p) + dist z (Ξ¨ p)) + Ξ΅) + Ξ΄ : by linarith
end
private lemma glue_eq_of_dist_eq_zero (Ξ¦ : Ξ³ β Ξ±) (Ξ¨ : Ξ³ β Ξ²) (Ξ΅ : β) (Ξ΅0 : 0 < Ξ΅) :
βp q : Ξ± β Ξ², glue_dist Ξ¦ Ξ¨ Ξ΅ p q = 0 β p = q
| (inl x) (inl y) h := by rw eq_of_dist_eq_zero h
| (inl x) (inr y) h := begin
have : 0 β€ (β¨
p, dist x (Ξ¦ p) + dist y (Ξ¨ p)) :=
le_cinfi (Ξ»p, by simpa using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)),
have : 0 + Ξ΅ β€ glue_dist Ξ¦ Ξ¨ Ξ΅ (inl x) (inr y) := add_le_add this (le_refl Ξ΅),
exfalso,
linarith
end
| (inr x) (inl y) h := begin
have : 0 β€ β¨
p, dist y (Ξ¦ p) + dist x (Ξ¨ p) :=
le_cinfi (Ξ»p, by simpa [add_comm]
using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)),
have : 0 + Ξ΅ β€ glue_dist Ξ¦ Ξ¨ Ξ΅ (inr x) (inl y) := add_le_add this (le_refl Ξ΅),
exfalso,
linarith
end
| (inr x) (inr y) h := by rw eq_of_dist_eq_zero h
/-- Given two maps Ξ¦ and Ξ¨ intro metric spaces Ξ± and Ξ² such that the distances between Ξ¦ p and Ξ¦ q,
and between Ξ¨ p and Ξ¨ q, coincide up to 2 Ξ΅ where Ξ΅ > 0, one can almost glue the two spaces Ξ±
and Ξ² along the images of Ξ¦ and Ξ¨, so that Ξ¦ p and Ξ¨ p are at distance Ξ΅. -/
def glue_metric_approx (Ξ¦ : Ξ³ β Ξ±) (Ξ¨ : Ξ³ β Ξ²) (Ξ΅ : β) (Ξ΅0 : 0 < Ξ΅)
(H : βp q, abs (dist (Ξ¦ p) (Ξ¦ q) - dist (Ξ¨ p) (Ξ¨ q)) β€ 2 * Ξ΅) : metric_space (Ξ± β Ξ²) :=
{ dist := glue_dist Ξ¦ Ξ¨ Ξ΅,
dist_self := glue_dist_self Ξ¦ Ξ¨ Ξ΅,
dist_comm := glue_dist_comm Ξ¦ Ξ¨ Ξ΅,
dist_triangle := glue_dist_triangle Ξ¦ Ξ¨ Ξ΅ H,
eq_of_dist_eq_zero := glue_eq_of_dist_eq_zero Ξ¦ Ξ¨ Ξ΅ Ξ΅0 }
end approx_gluing
section sum
/- A particular case of the previous construction is when one uses basepoints in Ξ± and Ξ² and one
glues only along the basepoints, putting them at distance 1. We give a direct definition of
the distance, without infi, as it is easier to use in applications, and show that it is equal to
the gluing distance defined above to take advantage of the lemmas we have already proved. -/
variables [metric_space Ξ±] [metric_space Ξ²] [inhabited Ξ±] [inhabited Ξ²]
open sum (inl inr)
/- Distance on a disjoint union. There are many (noncanonical) ways to put a distance compatible
with each factor.
If the two spaces are bounded, one can say for instance that each point in the first is at distance
`diam Ξ± + diam Ξ² + 1` of each point in the second.
Instead, we choose a construction that works for unbounded spaces, but requires basepoints.
We embed isometrically each factor, set the basepoints at distance 1,
arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to
their respective basepoints, plus the distance 1 between the basepoints.
Since there is an arbitrary choice in this construction, it is not an instance by default. -/
def sum.dist : Ξ± β Ξ² β Ξ± β Ξ² β β
| (inl a) (inl a') := dist a a'
| (inr b) (inr b') := dist b b'
| (inl a) (inr b) := dist a (default Ξ±) + 1 + dist (default Ξ²) b
| (inr b) (inl a) := dist b (default Ξ²) + 1 + dist (default Ξ±) a
lemma sum.dist_eq_glue_dist {p q : Ξ± β Ξ²} :
sum.dist p q = glue_dist (Ξ»_ : unit, default Ξ±) (Ξ»_ : unit, default Ξ²) 1 p q :=
by cases p; cases q; refl <|> simp [sum.dist, glue_dist, dist_comm, add_comm, add_left_comm]
private lemma sum.dist_comm (x y : Ξ± β Ξ²) : sum.dist x y = sum.dist y x :=
by cases x; cases y; simp only [sum.dist, dist_comm, add_comm, add_left_comm]
lemma sum.one_dist_le {x : Ξ±} {y : Ξ²} : 1 β€ sum.dist (inl x) (inr y) :=
le_trans (le_add_of_nonneg_right dist_nonneg) $
add_le_add_right (le_add_of_nonneg_left dist_nonneg) _
lemma sum.one_dist_le' {x : Ξ±} {y : Ξ²} : 1 β€ sum.dist (inr y) (inl x) :=
by rw sum.dist_comm; exact sum.one_dist_le
private lemma sum.mem_uniformity (s : set ((Ξ± β Ξ²) Γ (Ξ± β Ξ²))) :
s β π€ (Ξ± β Ξ²) β β Ξ΅ > 0, β a b, sum.dist a b < Ξ΅ β (a, b) β s :=
begin
split,
{ rintro β¨hsΞ±, hsΞ²β©,
rcases mem_uniformity_dist.1 hsΞ± with β¨Ξ΅Ξ±, Ρα0, hΞ±β©,
rcases mem_uniformity_dist.1 hsΞ² with β¨Ξ΅Ξ², Ρβ0, hΞ²β©,
refine β¨min (min Ρα Ρβ) 1, lt_min (lt_min Ρα0 Ρβ0) zero_lt_one, _β©,
rintro (a|a) (b|b) h,
{ exact hΞ± (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_left _ _))) },
{ cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le },
{ cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le' },
{ exact hΞ² (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_right _ _))) } },
{ rintro β¨Ξ΅, Ξ΅0, Hβ©,
split; rw [filter.mem_sets, filter.mem_map, mem_uniformity_dist];
exact β¨Ξ΅, Ξ΅0, Ξ» x y h, H _ _ (by exact h)β© }
end
/-- The distance on the disjoint union indeed defines a metric space. All the distance properties
follow from our choice of the distance. The harder work is to show that the uniform structure
defined by the distance coincides with the disjoint union uniform structure. -/
def metric_space_sum : metric_space (Ξ± β Ξ²) :=
{ dist := sum.dist,
dist_self := Ξ»x, by cases x; simp only [sum.dist, dist_self],
dist_comm := sum.dist_comm,
dist_triangle := Ξ»p q r,
by simp only [dist, sum.dist_eq_glue_dist]; exact glue_dist_triangle _ _ _ (by norm_num) _ _ _,
eq_of_dist_eq_zero := Ξ»p q,
by simp only [dist, sum.dist_eq_glue_dist]; exact glue_eq_of_dist_eq_zero _ _ _ zero_lt_one _ _,
to_uniform_space := sum.uniform_space,
uniformity_dist := uniformity_dist_of_mem_uniformity _ _ sum.mem_uniformity }
local attribute [instance] metric_space_sum
lemma sum.dist_eq {x y : Ξ± β Ξ²} : dist x y = sum.dist x y := rfl
/-- The left injection of a space in a disjoint union in an isometry -/
lemma isometry_on_inl : isometry (sum.inl : Ξ± β (Ξ± β Ξ²)) :=
isometry_emetric_iff_metric.2 $ Ξ»x y, rfl
/-- The right injection of a space in a disjoint union in an isometry -/
lemma isometry_on_inr : isometry (sum.inr : Ξ² β (Ξ± β Ξ²)) :=
isometry_emetric_iff_metric.2 $ Ξ»x y, rfl
end sum
section gluing
/- Exact gluing of two metric spaces along isometric subsets. -/
variables [nonempty Ξ³] [metric_space Ξ³] [metric_space Ξ±] [metric_space Ξ²]
{Ξ¦ : Ξ³ β Ξ±} {Ξ¨ : Ξ³ β Ξ²} {Ξ΅ : β}
open sum (inl inr)
local attribute [instance] premetric.dist_setoid
def glue_premetric (hΞ¦ : isometry Ξ¦) (hΞ¨ : isometry Ξ¨) : premetric_space (Ξ± β Ξ²) :=
{ dist := glue_dist Ξ¦ Ξ¨ 0,
dist_self := glue_dist_self Ξ¦ Ξ¨ 0,
dist_comm := glue_dist_comm Ξ¦ Ξ¨ 0,
dist_triangle := glue_dist_triangle Φ Ψ 0 $ λp q, by rw [hΦ.dist_eq, hΨ.dist_eq]; simp }
def glue_space (hΦ : isometry Φ) (hΨ : isometry Ψ) : Type* :=
@metric_quot _ (glue_premetric hΦ hΨ)
instance metric_space_glue_space (hΦ : isometry Φ) (hΨ : isometry Ψ) :
metric_space (glue_space hΦ hΨ) :=
@premetric.metric_space_quot _ (glue_premetric hΦ hΨ)
def to_glue_l (hΦ : isometry Φ) (hΨ : isometry Ψ) (x : α) : glue_space hΦ hΨ :=
by letI : premetric_space (Ξ± β Ξ²) := glue_premetric hΞ¦ hΞ¨; exact β¦inl xβ§
def to_glue_r (hΦ : isometry Φ) (hΨ : isometry Ψ) (y : β) : glue_space hΦ hΨ :=
by letI : premetric_space (Ξ± β Ξ²) := glue_premetric hΞ¦ hΞ¨; exact β¦inr yβ§
instance inhabited_left (hΦ : isometry Φ) (hΨ : isometry Ψ) [inhabited α] :
inhabited (glue_space hΦ hΨ) :=
β¨to_glue_l _ _ (default _)β©
instance inhabited_right (hΦ : isometry Φ) (hΨ : isometry Ψ) [inhabited β] :
inhabited (glue_space hΦ hΨ) :=
β¨to_glue_r _ _ (default _)β©
lemma to_glue_commute (hΦ : isometry Φ) (hΨ : isometry Ψ) :
(to_glue_l hΞ¦ hΞ¨) β Ξ¦ = (to_glue_r hΞ¦ hΞ¨) β Ξ¨ :=
begin
letI : premetric_space (Ξ± β Ξ²) := glue_premetric hΞ¦ hΞ¨,
funext,
simp only [comp, to_glue_l, to_glue_r, quotient.eq],
exact glue_dist_glued_points Ξ¦ Ξ¨ 0 x
end
lemma to_glue_l_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_l hΦ hΨ) :=
isometry_emetric_iff_metric.2 $ Ξ»_ _, rfl
lemma to_glue_r_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_r hΦ hΨ) :=
isometry_emetric_iff_metric.2 $ Ξ»_ _, rfl
end gluing --section
section inductive_limit
/- In this section, we define the inductive limit of
f 0 f 1 f 2 f 3
X 0 -----> X 1 -----> X 2 -----> X 3 -----> ...
where the X n are metric spaces and f n isometric embeddings. We do it by defining a premetric
space structure on Ξ£n, X n, where the predistance dist x y is obtained by pushing x and y in a
common X k using composition by the f n, and taking the distance there. This does not depend on
the choice of k as the f n are isometries. The metric space associated to this premetric space
is the desired inductive limit.-/
open nat
variables {X : β β Type u} [βn, metric_space (X n)] {f : Ξ n, X n β X (n+1)}
/-- Predistance on the disjoint union Ξ£n, X n. -/
def inductive_limit_dist (f : Ξ n, X n β X (n+1)) (x y : Ξ£n, X n) : β :=
dist (le_rec_on (le_max_left x.1 y.1) f x.2 : X (max x.1 y.1))
(le_rec_on (le_max_right x.1 y.1) f y.2 : X (max x.1 y.1))
/-- The predistance on the disjoint union Ξ£n, X n can be computed in any X k for large enough k.-/
lemma inductive_limit_dist_eq_dist (I : βn, isometry (f n))
(x y : Ξ£n, X n) (m : β) : βhx : x.1 β€ m, βhy : y.1 β€ m,
inductive_limit_dist f x y = dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m) :=
begin
induction m with m hm,
{ assume hx hy,
have A : max x.1 y.1 = 0, { rw [nonpos_iff_eq_zero.1 hx, nonpos_iff_eq_zero.1 hy], simp },
unfold inductive_limit_dist,
congr; simp only [A] },
{ assume hx hy,
by_cases h : max x.1 y.1 = m.succ,
{ unfold inductive_limit_dist,
congr; simp only [h] },
{ have : max x.1 y.1 β€ succ m := by simp [hx, hy],
have : max x.1 y.1 β€ m := by simpa [h] using of_le_succ this,
have xm : x.1 β€ m := le_trans (le_max_left _ _) this,
have ym : y.1 β€ m := le_trans (le_max_right _ _) this,
rw [le_rec_on_succ xm, le_rec_on_succ ym, (I m).dist_eq],
exact hm xm ym }}
end
/-- Premetric space structure on Ξ£n, X n.-/
def inductive_premetric (I : βn, isometry (f n)) :
premetric_space (Ξ£n, X n) :=
{ dist := inductive_limit_dist f,
dist_self := Ξ»x, by simp [dist, inductive_limit_dist],
dist_comm := Ξ»x y, begin
let m := max x.1 y.1,
have hx : x.1 β€ m := le_max_left _ _,
have hy : y.1 β€ m := le_max_right _ _,
unfold dist,
rw [inductive_limit_dist_eq_dist I x y m hx hy, inductive_limit_dist_eq_dist I y x m hy hx,
dist_comm]
end,
dist_triangle := Ξ»x y z, begin
let m := max (max x.1 y.1) z.1,
have hx : x.1 β€ m := le_trans (le_max_left _ _) (le_max_left _ _),
have hy : y.1 β€ m := le_trans (le_max_right _ _) (le_max_left _ _),
have hz : z.1 β€ m := le_max_right _ _,
calc inductive_limit_dist f x z
= dist (le_rec_on hx f x.2 : X m) (le_rec_on hz f z.2 : X m) :
inductive_limit_dist_eq_dist I x z m hx hz
... β€ dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m)
+ dist (le_rec_on hy f y.2 : X m) (le_rec_on hz f z.2 : X m) :
dist_triangle _ _ _
... = inductive_limit_dist f x y + inductive_limit_dist f y z :
by rw [inductive_limit_dist_eq_dist I x y m hx hy,
inductive_limit_dist_eq_dist I y z m hy hz]
end }
local attribute [instance] inductive_premetric premetric.dist_setoid
/-- The type giving the inductive limit in a metric space context. -/
def inductive_limit (I : βn, isometry (f n)) : Type* :=
@metric_quot _ (inductive_premetric I)
/-- Metric space structure on the inductive limit. -/
instance metric_space_inductive_limit (I : βn, isometry (f n)) :
metric_space (inductive_limit I) :=
@premetric.metric_space_quot _ (inductive_premetric I)
/-- Mapping each `X n` to the inductive limit. -/
def to_inductive_limit (I : βn, isometry (f n)) (n : β) (x : X n) : metric.inductive_limit I :=
by letI : premetric_space (Ξ£n, X n) := inductive_premetric I; exact β¦sigma.mk n xβ§
instance (I : β n, isometry (f n)) [inhabited (X 0)] : inhabited (inductive_limit I) :=
β¨to_inductive_limit _ 0 (default _)β©
/-- The map `to_inductive_limit n` mapping `X n` to the inductive limit is an isometry. -/
lemma to_inductive_limit_isometry (I : βn, isometry (f n)) (n : β) :
isometry (to_inductive_limit I n) := isometry_emetric_iff_metric.2 $ Ξ»x y,
begin
change inductive_limit_dist f β¨n, xβ© β¨n, yβ© = dist x y,
rw [inductive_limit_dist_eq_dist I β¨n, xβ© β¨n, yβ© n (le_refl n) (le_refl n),
le_rec_on_self, le_rec_on_self]
end
/-- The maps `to_inductive_limit n` are compatible with the maps `f n`. -/
lemma to_inductive_limit_commute (I : βn, isometry (f n)) (n : β) :
(to_inductive_limit I n.succ) β (f n) = to_inductive_limit I n :=
begin
funext,
simp only [comp, to_inductive_limit, quotient.eq],
show inductive_limit_dist f β¨n.succ, f n xβ© β¨n, xβ© = 0,
{ rw [inductive_limit_dist_eq_dist I β¨n.succ, f n xβ© β¨n, xβ© n.succ,
le_rec_on_self, le_rec_on_succ, le_rec_on_self, dist_self],
exact le_refl _,
exact le_refl _,
exact le_succ _ }
end
end inductive_limit --section
end metric --namespace
|
cea464ca40d19f2490407e3db5af6a843be946c1 | f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58 | /data/padics/padic_rationals.lean | ceb55079c07606bd96d740002c4b001efc1984e2 | [
"Apache-2.0"
] | permissive | semorrison/mathlib | 1be6f11086e0d24180fec4b9696d3ec58b439d10 | 20b4143976dad48e664c4847b75a85237dca0a89 | refs/heads/master | 1,583,799,212,170 | 1,535,634,130,000 | 1,535,730,505,000 | 129,076,205 | 0 | 0 | Apache-2.0 | 1,551,697,998,000 | 1,523,442,265,000 | Lean | UTF-8 | Lean | false | false | 20,867 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
Define the p-adic numbers (rationals) β_p as the completion of β wrt the p-adic norm.
Show that the p-adic norm extends to β_p, that β is embedded in β_p, and that β_p is complete
-/
import data.real.cau_seq_completion data.padics.padic_norm algebra.archimedean
noncomputable theory
local attribute [instance] classical.prop_decidable
open nat padic_val padic_norm cau_seq cau_seq.completion
@[reducible] def padic_seq {p : β} (hp : prime p) := cau_seq _ (padic_norm hp)
namespace padic_seq
section
variables {p : β} {hp : prime p}
lemma stationary {f : cau_seq β (padic_norm hp)} (hf : Β¬ f β 0) :
β N, β m n, m β₯ N β n β₯ N β padic_norm hp (f n) = padic_norm hp (f m) :=
have β Ξ΅ > 0, β N1, β j β₯ N1, Ξ΅ β€ padic_norm hp (f j),
from cau_seq.abv_pos_of_not_lim_zero $ not_lim_zero_of_not_congr_zero hf,
let β¨Ξ΅, hΞ΅, N1, hN1β© := this in
have β N2, β i j β₯ N2, padic_norm hp (f i - f j) < Ξ΅, from cau_seq.cauchyβ f hΞ΅,
let β¨N2, hN2β© := this in
β¨ max N1 N2,
Ξ» n m hn hm,
have padic_norm hp (f n - f m) < Ξ΅, from hN2 _ _ (max_le_iff.1 hn).2 (max_le_iff.1 hm).2,
have padic_norm hp (f n - f m) < padic_norm hp (f n),
from lt_of_lt_of_le this $ hN1 _ (max_le_iff.1 hn).1,
have padic_norm hp (f n - f m) < max (padic_norm hp (f n)) (padic_norm hp (f m)),
from lt_max_iff.2 (or.inl this),
begin
by_contradiction hne,
rw βpadic_norm.neg hp (f m) at hne,
have hnam := add_eq_max_of_ne hp hne,
rw [padic_norm.neg, max_comm] at hnam,
rw βhnam at this,
apply _root_.lt_irrefl _ (by simp at this; exact this)
end β©
def stationary_point {f : padic_seq hp} (hf : Β¬ f β 0) : β :=
classical.some $ stationary hf
lemma stationary_point_spec {f : padic_seq hp} (hf : Β¬ f β 0) :
β {m n}, m β₯ stationary_point hf β n β₯ stationary_point hf β
padic_norm hp (f n) = padic_norm hp (f m) :=
classical.some_spec $ stationary hf
def norm (f : padic_seq hp) : β :=
if hf : f β 0 then 0
else padic_norm hp (f (stationary_point hf))
lemma norm_zero_iff (f : padic_seq hp) : f.norm = 0 β f β 0 :=
begin
constructor,
{ intro h,
by_contradiction hf,
unfold norm at h, split_ifs at h,
apply hf,
intros Ξ΅ hΞ΅,
existsi stationary_point hf,
intros j hj,
have heq := stationary_point_spec hf (le_refl _) hj,
simpa [h, heq] },
{ intro h,
simp [norm, h] }
end
end
section embedding
open cau_seq
variables {p : β} {hp : prime p}
lemma equiv_zero_of_val_eq_of_equiv_zero {f g : padic_seq hp}
(h : β k, padic_norm hp (f k) = padic_norm hp (g k)) (hf : f β 0) : g β 0 :=
Ξ» Ξ΅ hΞ΅, let β¨i, hiβ© := hf _ hΞ΅ in
β¨i, Ξ» j hj, by simpa [h] using hi _ hjβ©
lemma norm_nonzero_of_not_equiv_zero {f : padic_seq hp} (hf : Β¬ f β 0) :
f.norm β 0 :=
hf β f.norm_zero_iff.1
lemma norm_eq_norm_app_of_nonzero {f : padic_seq hp} (hf : Β¬ f β 0) :
β k, f.norm = padic_norm hp k β§ k β 0 :=
have heq : f.norm = padic_norm hp (f $ stationary_point hf), by simp [norm, hf],
β¨f $ stationary_point hf, heq,
Ξ» h, norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)β©
lemma not_lim_zero_const_of_nonzero {q : β} (hq : q β 0) : Β¬ lim_zero (const (padic_norm hp) q) :=
Ξ» h', hq $ const_lim_zero.1 h'
lemma not_equiv_zero_const_of_nonzero {q : β} (hq : q β 0) : Β¬ (const (padic_norm hp) q) β 0 :=
Ξ» h : lim_zero (const (padic_norm hp) q - 0), not_lim_zero_const_of_nonzero hq $ by simpa using h
lemma norm_nonneg (f : padic_seq hp) : f.norm β₯ 0 :=
if hf : f β 0 then by simp [hf, norm]
else by simp [norm, hf, padic_norm.nonneg]
lemma norm_mul (f g : padic_seq hp) :
(f * g).norm = f.norm * g.norm :=
if hf : f β 0 then
have hg : f * g β 0, from mul_equiv_zero' _ hf,
by simp [hf, hg, norm]
else if hg : g β 0 then
have hf : f * g β 0, from mul_equiv_zero _ hg,
by simp [hf, hg, norm]
else
have hfg : Β¬ f * g β 0, by apply mul_not_equiv_zero; assumption,
let i := max (stationary_point hfg) (max (stationary_point hf) (stationary_point hg)) in
have hpnfg : padic_norm hp ((f * g) (stationary_point hfg)) = padic_norm hp ((f * g) i),
{ apply stationary_point_spec hfg,
apply le_max_left,
apply le_refl },
have hpnf : padic_norm hp (f (stationary_point hf)) = padic_norm hp (f i),
{ apply stationary_point_spec hf,
apply ge_trans,
apply le_max_right,
apply le_max_left,
apply le_refl },
have hpng : padic_norm hp (g (stationary_point hg)) = padic_norm hp (g i),
{ apply stationary_point_spec hg,
apply ge_trans,
apply le_max_right,
apply le_max_right,
apply le_refl },
begin
unfold norm,
split_ifs,
rw [hpnfg, hpnf, hpng],
apply padic_norm.mul hp
end
lemma eq_zero_iff_equiv_zero (f : padic_seq hp) : mk f = 0 β f β 0 :=
mk_eq
lemma ne_zero_iff_nequiv_zero (f : padic_seq hp) : mk f β 0 β Β¬ f β 0 :=
not_iff_not.2 (eq_zero_iff_equiv_zero _)
lemma norm_const (q : β) : norm (const (padic_norm hp) q) = padic_norm hp q :=
if hq : q = 0 then
have (const (padic_norm hp) q) β 0,
by simp [hq]; apply setoid.refl (const (padic_norm hp) 0),
by subst hq; simp [norm, this]
else
have Β¬ (const (padic_norm hp) q) β 0, from not_equiv_zero_const_of_nonzero hq,
by simp [norm, this]
lemma norm_image (a : padic_seq hp) (ha : Β¬ a β 0) :
(β (n : β€), a.norm = fpow βp (-n)) :=
let β¨k, hk, hk'β© := norm_eq_norm_app_of_nonzero ha in
by simpa [hk] using padic_norm.image hp hk'
lemma norm_one : norm (1 : padic_seq hp) = 1 :=
have h1 : Β¬ (1 : padic_seq hp) β 0, from one_not_equiv_zero _,
by simp [h1, norm, hp.gt_one]
private lemma norm_eq_of_equiv_aux {f g : padic_seq hp} (hf : Β¬ f β 0) (hg : Β¬ g β 0) (hfg : f β g)
(h : padic_norm hp (f (stationary_point hf)) β padic_norm hp (g (stationary_point hg)))
(hgt : padic_norm hp (f (stationary_point hf)) > padic_norm hp (g (stationary_point hg))) :
false :=
begin
have hpn : padic_norm hp (f (stationary_point hf)) - padic_norm hp (g (stationary_point hg)) > 0,
from sub_pos_of_lt hgt,
cases hfg _ hpn with N hN,
let i := max N (max (stationary_point hf) (stationary_point hg)),
have hfi : padic_norm hp (f (stationary_point hf)) = padic_norm hp (f i),
{ apply stationary_point_spec hf,
{ apply le_trans,
apply le_max_left,
tactic.rotate_left 1,
apply le_max_right },
{ apply le_refl } },
have hgi : padic_norm hp (g (stationary_point hg)) = padic_norm hp (g i),
{ apply stationary_point_spec hg,
{ apply le_trans,
apply le_max_right,
tactic.rotate_left 1,
apply le_max_right },
{ apply le_refl } },
have hi : i β₯ N, from le_max_left _ _,
have hN' := hN _ hi,
simp only [hfi, hgi] at hN',
have hpne : padic_norm hp (f i) β padic_norm hp (-(g i)),
by rwa [hfi, hgi, βpadic_norm.neg hp (g i)] at h,
let hpnem := add_eq_max_of_ne hp hpne,
have hpeq : padic_norm hp ((f - g) i) = max (padic_norm hp (f i)) (padic_norm hp (g i)),
{ rwa padic_norm.neg at hpnem },
have hfigi : padic_norm hp (g i) < padic_norm hp (f i),
{ rwa [hfi, hgi] at hgt },
rw [hpeq, max_eq_left_of_lt hfigi] at hN',
have : padic_norm hp (f i) < padic_norm hp (f i),
{ apply lt_of_lt_of_le hN', apply sub_le_self, apply padic_norm.nonneg },
exact lt_irrefl _ this
end
private lemma norm_eq_of_equiv {f g : padic_seq hp} (hf : Β¬ f β 0) (hg : Β¬ g β 0) (hfg : f β g) :
padic_norm hp (f (stationary_point hf)) = padic_norm hp (g (stationary_point hg)) :=
begin
by_contradiction h,
cases (decidable.em (padic_norm hp (f (stationary_point hf)) >
padic_norm hp (g (stationary_point hg))))
with hgt hngt,
{ exact norm_eq_of_equiv_aux hf hg hfg h hgt },
{ apply norm_eq_of_equiv_aux hg hf (setoid.symm hfg) (ne.symm h),
apply lt_of_le_of_ne,
apply le_of_not_gt hngt,
apply h }
end
theorem norm_equiv {f g : padic_seq hp} (hfg : f β g) :
f.norm = g.norm :=
if hf : f β 0 then
have hg : g β 0, from setoid.trans (setoid.symm hfg) hf,
by simp [norm, hf, hg]
else have hg : Β¬ g β 0, from hf β setoid.trans hfg,
by unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg
private lemma norm_nonarchimedean_aux {f g : padic_seq hp}
(hfg : Β¬ f + g β 0) (hf : Β¬ f β 0) (hg : Β¬ g β 0) :
(f + g).norm β€ max (f.norm) (g.norm) :=
let i := max (stationary_point hfg) (max (stationary_point hf) (stationary_point hg)) in
have hpnfg : padic_norm hp ((f + g) (stationary_point hfg)) = padic_norm hp ((f + g) i),
{ apply stationary_point_spec hfg,
apply le_max_left,
apply le_refl },
have hpnf : padic_norm hp (f (stationary_point hf)) = padic_norm hp (f i),
{ apply stationary_point_spec hf,
apply ge_trans,
apply le_max_right,
apply le_max_left,
apply le_refl },
have hpng : padic_norm hp (g (stationary_point hg)) = padic_norm hp (g i),
{ apply stationary_point_spec hg,
apply ge_trans,
apply le_max_right,
apply le_max_right,
apply le_refl },
begin
unfold norm, split_ifs,
rw [hpnfg, hpnf, hpng],
apply padic_norm.nonarchimedean
end
theorem norm_nonarchimedean (f g : padic_seq hp) :
(f + g).norm β€ max (f.norm) (g.norm) :=
if hfg : f + g β 0 then
have 0 β€ max (f.norm) (g.norm), from le_max_left_of_le (norm_nonneg _),
by simpa [hfg, norm]
else if hf : f β 0 then
have hfg' : f + g β g,
{ change lim_zero (f - 0) at hf,
show lim_zero (f + g - g), by simpa using hf },
have hcfg : (f + g).norm = g.norm, from norm_equiv hfg',
have hcl : f.norm = 0, from (norm_zero_iff f).2 hf,
have max (f.norm) (g.norm) = g.norm,
by rw hcl; exact max_eq_right (norm_nonneg _),
by rw [this, hcfg]
else if hg : g β 0 then
have hfg' : f + g β f,
{ change lim_zero (g - 0) at hg,
show lim_zero (f + g - f), by simpa [add_sub_cancel'] using hg },
have hcfg : (f + g).norm = f.norm, from norm_equiv hfg',
have hcl : g.norm = 0, from (norm_zero_iff g).2 hg,
have max (f.norm) (g.norm) = f.norm,
by rw hcl; exact max_eq_left (norm_nonneg _),
by rw [this, hcfg]
else norm_nonarchimedean_aux hfg hf hg
lemma norm_eq {f g : padic_seq hp} (h : β k, padic_norm hp (f k) = padic_norm hp (g k)) :
f.norm = g.norm :=
if hf : f β 0 then
have hg : g β 0, from equiv_zero_of_val_eq_of_equiv_zero h hf,
by simp [hf, hg, norm]
else
have hg : Β¬ g β 0, from Ξ» hg, hf $ equiv_zero_of_val_eq_of_equiv_zero (by simp [h]) hg,
begin
simp [hg, hf, norm],
let i := max (stationary_point hf) (stationary_point hg),
have hpf : padic_norm hp (f (stationary_point hf)) = padic_norm hp (f i),
{ apply stationary_point_spec, apply le_max_left, apply le_refl },
have hpg : padic_norm hp (g (stationary_point hg)) = padic_norm hp (g i),
{ apply stationary_point_spec, apply le_max_right, apply le_refl },
rw [hpf, hpg, h]
end
lemma norm_neg (a : padic_seq hp) : (-a).norm = a.norm :=
norm_eq $ by simp
end embedding
end padic_seq
def padic {p : β} (hp : prime p) := @Cauchy _ _ _ _ (padic_norm hp) _
notation `β_[` hp `]` := padic hp
namespace padic
section completion
variables {p : β} {hp : prime p}
instance discrete_field : discrete_field (padic hp) :=
cau_seq.completion.discrete_field
def mk : padic_seq hp β β_[hp] := quotient.mk
end completion
section completion
variables {p : β} (hp : prime p)
lemma mk_eq {f g : padic_seq hp} : mk f = mk g β f β g := quotient.eq
def of_rat : β β β_[hp] := cau_seq.completion.of_rat
@[simp] lemma of_rat_add : β (x y : β), of_rat hp (x + y) = of_rat hp x + of_rat hp y :=
cau_seq.completion.of_rat_add
@[simp] lemma of_rat_neg : β (x : β), of_rat hp (-x) = -of_rat hp x :=
cau_seq.completion.of_rat_neg
@[simp] lemma of_rat_mul : β (x y : β), of_rat hp (x * y) = of_rat hp x * of_rat hp y :=
cau_seq.completion.of_rat_mul
@[simp] lemma of_rat_sub : β (x y : β), of_rat hp (x - y) = of_rat hp x - of_rat hp y :=
cau_seq.completion.of_rat_sub
@[simp] lemma of_rat_div : β (x y : β), of_rat hp (x / y) = of_rat hp x / of_rat hp y :=
cau_seq.completion.of_rat_div
@[simp] lemma of_rat_one : of_rat hp 1 = 1 := rfl
@[simp] lemma of_rat_zero : of_rat hp 0 = 0 := rfl
@[simp] lemma cast_eq_of_rat_of_nat (n : β) : (βn : β_[hp]) = of_rat hp n :=
begin
induction n with n ih,
{ refl },
{ simp, ring, congr, apply ih }
end
@[simp] lemma cast_eq_of_rat_of_int (n : β€) : (βn : β_[hp]) = of_rat hp n :=
by induction n; simp
lemma cast_eq_of_rat : β (q : β), (βq : β_[hp]) = of_rat hp q
| β¨n, d, h1, h2β© :=
show βn / βd = _, from
have (β¨n, d, h1, h2β© : β) = rat.mk n d, from rat.num_denom _,
by simp [this, rat.mk_eq_div, of_rat_div]
lemma const_equiv {q r : β} : const (padic_norm hp) q β const (padic_norm hp) r β q = r :=
β¨ Ξ» heq : lim_zero (const (padic_norm hp) (q - r)),
eq_of_sub_eq_zero $ const_lim_zero.1 heq,
Ξ» heq, by rw heq; apply setoid.refl _ β©
lemma of_rat_eq {q r : β} : of_rat hp q = of_rat hp r β q = r :=
β¨(const_equiv hp).1 β quotient.eq.1, Ξ» h, by rw hβ©
instance : char_zero β_[hp] :=
β¨ Ξ» m n, suffices of_rat hp βm = of_rat hp βn β m = n, by simpa,
by simp [of_rat_eq] β©
end completion
end padic
def padic_norm_e {p : β} {hp : prime p} : β_[hp] β β :=
quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _
namespace padic_norm_e
section embedding
open padic_seq
variables {p : β} {hp : prime p}
lemma defn (f : padic_seq hp) {Ξ΅ : β} (hΞ΅ : Ξ΅ > 0) :
β N, β i β₯ N, padic_norm_e (β¦fβ§ - f i) < Ξ΅ :=
begin
simp only [padic.cast_eq_of_rat],
change β N, β i β₯ N, (f - const _ (f i)).norm < Ξ΅,
by_contradiction h,
cases cauchyβ f hΞ΅ with N hN,
have : β N, β i β₯ N, (f - const _ (f i)).norm β₯ Ξ΅,
by simpa [not_forall] using h,
rcases this N with β¨i, hi, hgeβ©,
have hne : Β¬ (f - const (padic_norm hp) (f i)) β 0,
{ intro h, unfold norm at hge; split_ifs at hge, exact not_lt_of_ge hge hΞ΅ },
unfold norm at hge; split_ifs at hge,
apply not_le_of_gt _ hge,
cases decidable.em ((stationary_point hne) β₯ N) with hgen hngen,
{ apply hN; assumption },
{ have := stationary_point_spec hne (le_refl _) (le_of_not_le hngen),
rw βthis,
apply hN,
apply le_refl, assumption }
end
protected lemma nonneg (q : β_[hp]) : padic_norm_e q β₯ 0 :=
quotient.induction_on q $ norm_nonneg
lemma zero_def : (0 : β_[hp]) = β¦0β§ := rfl
lemma zero_iff (q : β_[hp]) : padic_norm_e q = 0 β q = 0 :=
quotient.induction_on q $
by simpa only [zero_def, quotient.eq] using norm_zero_iff
@[simp] protected lemma zero : padic_norm_e (0 : β_[hp]) = 0 :=
(zero_iff _).2 rfl
@[simp] protected lemma one : padic_norm_e (1 : β_[hp]) = 1 :=
norm_one
@[simp] protected lemma neg (q : β_[hp]) : padic_norm_e (-q) = padic_norm_e q :=
quotient.induction_on q $ norm_neg
theorem nonarchimedean (q r : β_[hp]) :
padic_norm_e (q + r) β€ max (padic_norm_e q) (padic_norm_e r) :=
quotient.induction_onβ q r $ norm_nonarchimedean
protected lemma add (q r : β_[hp]) :
padic_norm_e (q + r) β€ (padic_norm_e q) + (padic_norm_e r) :=
calc
padic_norm_e (q + r) β€ max (padic_norm_e q) (padic_norm_e r) : nonarchimedean _ _
... β€ (padic_norm_e q) + (padic_norm_e r) :
max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _)
protected lemma mul (q r : β_[hp]) :
padic_norm_e (q * r) = (padic_norm_e q) * (padic_norm_e r) :=
quotient.induction_onβ q r $ norm_mul
instance : is_absolute_value (@padic_norm_e _ hp) :=
{ abv_nonneg := padic_norm_e.nonneg,
abv_eq_zero := zero_iff,
abv_add := padic_norm_e.add,
abv_mul := padic_norm_e.mul }
lemma eq_padic_norm (q : β) : padic_norm_e (padic.of_rat hp q) = padic_norm hp q :=
norm_const _
protected theorem image {q : β_[hp]} : q β 0 β β n : β€, padic_norm_e q = fpow p (-n) :=
quotient.induction_on q $ Ξ» f hf,
have Β¬ f β 0, from (ne_zero_iff_nequiv_zero f).1 hf,
norm_image f this
lemma sub_rev (q r : β_[hp]) : padic_norm_e (q - r) = padic_norm_e (r - q) :=
by rw β(padic_norm_e.neg); simp
end embedding
end padic_norm_e
namespace padic
section complete
open padic_seq padic
theorem rat_dense {p : β} {hp : prime p} (q : β_[hp]) {Ξ΅ : β} (hΞ΅ : Ξ΅ > 0) :
β r : β, padic_norm_e (q - r) < Ξ΅ :=
quotient.induction_on q $ Ξ» q',
have β N, β m n β₯ N, padic_norm hp (q' m - q' n) < Ξ΅, from cauchyβ _ hΞ΅,
let β¨N, hNβ© := this in
β¨q' N,
begin
simp only [padic.cast_eq_of_rat],
change padic_seq.norm (q' - const _ (q' N)) < Ξ΅,
cases decidable.em ((q' - const (padic_norm hp) (q' N)) β 0) with heq hne',
{ simpa only [heq, norm, dif_pos] },
{ simp only [norm, dif_neg hne'],
change padic_norm hp (q' _ - q' _) < Ξ΅,
have := stationary_point_spec hne',
cases decidable.em (N β₯ stationary_point hne') with hle hle,
{ have := eq.symm (this (le_refl _) hle),
simp at this, simpa [this] },
{ apply hN,
apply le_of_lt, apply lt_of_not_ge, apply hle, apply le_refl }}
endβ©
variables {p : β} {hp : prime p} (f : cau_seq _ (@padic_norm_e _ hp))
open classical
private lemma cast_succ_nat_pos (n : β) : (β(n + 1) : β) > 0 :=
nat.cast_pos.2 $ succ_pos _
private lemma div_nat_pos (n : β) : (1 / ((n + 1): β)) > 0 :=
div_pos zero_lt_one (cast_succ_nat_pos _)
def lim_seq : β β β := Ξ» n, classical.some (rat_dense (f n) (div_nat_pos n))
lemma exi_rat_seq_conv :
β Ξ΅ > 0, β N, β i β₯ N, padic_norm_e (f i - of_rat hp ((lim_seq f) i)) < Ξ΅ :=
begin
intros Ξ΅ hΞ΅,
existsi (ceil (1/Ξ΅)).nat_abs,
intros i hi,
let h := classical.some_spec (rat_dense (f i) (div_nat_pos i)),
rw βcast_eq_of_rat,
apply lt_of_lt_of_le,
apply h,
apply div_le_of_le_mul,
apply cast_succ_nat_pos,
have hi' := int.of_nat_le_of_nat_of_le hi,
have : ceil (1/Ξ΅) β₯ 0, from ceil_nonneg (le_of_lt (one_div_pos_of_pos hΞ΅)),
rw int.of_nat_nat_abs_eq_of_nonneg (this) at hi',
have hi'' := le_mul_of_div_le hΞ΅ (ceil_le.1 hi'),
rw right_distrib,
apply le_add_of_le_of_nonneg,
{ apply hi'' },
{ apply le_of_lt,
simpa }
end
lemma exi_rat_seq_conv_cauchy : is_cau_seq (padic_norm hp) (lim_seq f) :=
assume Ξ΅ hΞ΅,
have hΞ΅3 : Ξ΅ / 3 > 0, from div_pos hΞ΅ (by norm_num),
let β¨N, hNβ© := exi_rat_seq_conv f _ hΞ΅3,
β¨N2, hN2β© := f.cauchyβ hΞ΅3 in
begin
existsi max N N2,
intros j hj,
rw [βpadic_norm_e.eq_padic_norm, padic.of_rat_sub],
suffices : padic_norm_e ((β(lim_seq f j) - f (max N N2)) + (f (max N N2) - lim_seq f (max N N2))) < Ξ΅,
{ ring at this β’, simpa only [cast_eq_of_rat] },
{ apply lt_of_le_of_lt,
{ apply padic_norm_e.add },
{ have : (3 : β) β 0, by norm_num,
have : Ξ΅ = Ξ΅ / 3 + Ξ΅ / 3 + Ξ΅ / 3,
{ apply eq_of_mul_eq_mul_left this, simp [left_distrib, mul_div_cancel' _ this ], ring },
rw this,
apply add_lt_add,
{ suffices : padic_norm_e ((β(lim_seq f j) - f j) + (f j - f (max N N2))) < Ξ΅ / 3 + Ξ΅ / 3,
by simpa,
apply lt_of_le_of_lt,
{ apply padic_norm_e.add },
{ apply add_lt_add,
{ rw [padic_norm_e.sub_rev, cast_eq_of_rat], apply hN, apply le_of_max_le_left hj },
{ apply hN2, apply le_of_max_le_right hj, apply le_max_right } } },
{ rw cast_eq_of_rat, apply hN, apply le_max_left }}}
end
private def lim' : padic_seq hp := β¨_, exi_rat_seq_conv_cauchy fβ©
private def lim : β_[hp] := β¦lim' fβ§
theorem complete :
β q : β_[hp], β Ξ΅ > 0, β N, β i β₯ N, padic_norm_e (q - f i) < Ξ΅ :=
β¨ lim f,
Ξ» Ξ΅ hΞ΅,
let β¨N, hNβ© := exi_rat_seq_conv f _ (show Ξ΅ / 2 > 0, from div_pos hΞ΅ (by norm_num)),
β¨N2, hN2β© := padic_norm_e.defn (lim' f) (show Ξ΅ / 2 > 0, from div_pos hΞ΅ (by norm_num)) in
begin
existsi max N N2,
intros i hi,
suffices : padic_norm_e ((lim f - lim' f i) + (lim' f i - f i)) < Ξ΅,
{ ring at this; exact this },
{ apply lt_of_le_of_lt,
{ apply padic_norm_e.add },
{ have : (2 : β) β 0, by norm_num,
have : Ξ΅ = Ξ΅ / 2 + Ξ΅ / 2, by rw β(add_self_div_two Ξ΅); simp,
rw this,
apply add_lt_add,
{ apply hN2, apply le_of_max_le_right hi },
{ rw [padic_norm_e.sub_rev, cast_eq_of_rat], apply hN, apply le_of_max_le_left hi } } }
end β©
end complete
end padic |
f3c6c12596514454879d6de53b23e6c561fc2799 | 076f5040b63237c6dd928c6401329ed5adcb0e44 | /assignments/hw3_function_terms_lambda.lean | 33a7aede7c4503b445a73044b3c9772fb78db4d2 | [] | no_license | kevinsullivan/uva-cs-dm-f19 | 0f123689cf6cb078f263950b18382a7086bf30be | 09a950752884bd7ade4be33e9e89a2c4b1927167 | refs/heads/master | 1,594,771,841,541 | 1,575,853,850,000 | 1,575,853,850,000 | 205,433,890 | 4 | 9 | null | 1,571,592,121,000 | 1,567,188,539,000 | Lean | UTF-8 | Lean | false | false | 4,382 | lean | -- You can ignore this line for now, but don't remove it.
namespace hw3
/-
In this assignment, you will put into practice your new
knowledge of terms and definitions in predicate logic by
using it to implement a library of Boolean functions. You
will also gain practice using different forms of syntax
for defining functions.
-/
/-
To begin, we present one "unary" Boolean function (taking
one Boolean argument and returning a Boolean result) and one
"binary" function (taking two arguments), using each of three
styles of syntax.
-/
/-
First, here are three implementations of exactly the
same unary function, namely negation, in three styles.
-/
-- explicitly lambda expression
def neg_bool : bool β bool :=
Ξ» (b : bool),
match b with
| ff := tt
| tt := ff
end
-- by cases; note absence of := after function type
def neg_bool' : bool β bool
| ff := tt
| tt := ff
-- C-style; note return type is now between : and :=
def neg_bool'' (b : bool) : bool :=
match b with
| ff := tt
| tt := ff
end
/-
Second, here are three implementations of exactly the
same binary function (Boolean "and"), in the same three
styles.
-/
-- Note commas in match expression and in each case
def and_bool : bool β bool β bool :=
Ξ» (b1 b2 : bool), --shorthand for two lambdas
match b1, b2 with -- matching on two arguments
| ff, ff := ff
| ff, tt := ff
| tt, ff := ff
| tt, tt := tt
end
-- Note absence of := and of commas in each of the cases
def and_bool' : bool β bool β bool
| ff ff := ff
| ff tt := ff
| tt ff := ff
| tt tt := tt
-- should seem straightforward now
def and_bool'' (b1 b2 : bool) : bool :=
match b1, b2 with
| ff, ff := ff
| ff, tt := ff
| tt, ff := ff
| tt, tt := tt
end
/-
Your homework is to implement the remaining unary Boolean
functions, and several key binary Boolean functions, each
one in each of these styles: lambda, by-cases, and C-style.
-/
/-
1. Implement the always false unary Boolean function in each
of the three styles, lambda, by-cases, and C-style. Call the
functions false_bool, false_bool', and false_bool'', in that
order.
-/
-- Here's the first one, just to get you going.
def false_bool : bool β bool :=
Ξ» (b : bool),
ff
-- Now false_bool'
-- And now false_bool''
/-
2. Do the same for the always true unary Boolean function,
using true_bool as the function name (with zero, one, and
two ' marks to avoid name conflicts. You will use ' in this
way for each of the remaining parts of this assignment).
-/
/-
3. Do the same for the unary Boolean identity function,
using ident_bool (and ' variants) as the function name.
-/
/-
Congrats, you now have a small library of all unary Boolean
functions. Now turn to the binary functions. Each will take
two Boolean arguments, we can call them b1 and b2, and will
return a Boolean result.
-/
/-
4. The Boolean "or" function is true if and only if at least
one of b1 and b2 is true. Equivalently it is false if and only
if both b1 and b2 are false. Implement this function in each
of the three styles, using or_bool as the function name. You
may use the example of "and_bool" above as a model. While you
could just cut and paste, we strongly recommend that you type
your answers in full. Learning new syntax is an exercise is
"muscle memory", so don't take shortcuts here. Learn the
syntax now and it will save you frustration later.
-/
/-
5. The Boolean "exclusive or" function is true if and only if
exactly one of its arguments is true. Implement this function
in each style using xor_bool as the function name.
-/
/-
6. The Boolean "implies" function is true if and only if
either its first argument is false, or its first argument is
true and its second argument is also true. Equivalently it is
false if and only if its first argument is true and its second is false. Implement it in each style, calling it implies_bool.
-/
/-
7. The Boolean "equivalent-to" function is true if its two arguments are the same, either both true or both false;
otherwise it is false. Implement it in the three styles,
using equiv_bool as a function name.
-/
-- leave the following in place as the last line in this file
end hw3
|
613496ff5e40c2cca3ab8b980b63e950672ca0d7 | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /src/Lean/Elab/SyntheticMVars.lean | 46d25f2dfe18e4f61a82df752752bab0f1b11426 | [
"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",
"Apache-2.0",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | gebner/lean4 | d51c4922640a52a6f7426536ea669ef18a1d9af5 | 8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f | refs/heads/master | 1,685,732,780,391 | 1,672,962,627,000 | 1,673,459,398,000 | 373,307,283 | 0 | 0 | Apache-2.0 | 1,691,316,730,000 | 1,622,669,271,000 | Lean | UTF-8 | Lean | false | false | 24,310 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Meta.Tactic.Util
import Lean.Util.ForEachExpr
import Lean.Util.OccursCheck
import Lean.Elab.Tactic.Basic
namespace Lean.Elab.Term
open Tactic (TacticM evalTactic getUnsolvedGoals withTacticInfoContext)
open Meta
/-- Auxiliary function used to implement `synthesizeSyntheticMVars`. -/
private def resumeElabTerm (stx : Syntax) (expectedType? : Option Expr) (errToSorry := true) : TermElabM Expr :=
-- Remark: if `ctx.errToSorry` is already false, then we don't enable it. Recall tactics disable `errToSorry`
withReader (fun ctx => { ctx with errToSorry := ctx.errToSorry && errToSorry }) do
elabTerm stx expectedType? false
/--
Try to elaborate `stx` that was postponed by an elaboration method using `Expection.postpone`.
It returns `true` if it succeeded, and `false` otherwise.
It is used to implement `synthesizeSyntheticMVars`. -/
private def resumePostponed (savedContext : SavedContext) (stx : Syntax) (mvarId : MVarId) (postponeOnError : Bool) : TermElabM Bool :=
withRef stx <| mvarId.withContext do
let s β saveState
try
withSavedContext savedContext do
let mvarDecl β getMVarDecl mvarId
let expectedType β instantiateMVars mvarDecl.type
withInfoHole mvarId do
let result β resumeElabTerm stx expectedType (!postponeOnError)
/- We must ensure `result` has the expected type because it is the one expected by the method that postponed stx.
That is, the method does not have an opportunity to check whether `result` has the expected type or not. -/
let result β withRef stx <| ensureHasType expectedType result
/- We must perform `occursCheck` here since `result` may contain `mvarId` when it has synthetic `sorry`s. -/
if (β occursCheck mvarId result) then
mvarId.assign result
return true
else
return false
catch
| ex@(.internal id _) =>
if id == postponeExceptionId then
s.restore (restoreInfo := true)
return false
else
throw ex
| ex@(.error ..) =>
if postponeOnError then
s.restore (restoreInfo := true)
return false
else
logException ex
return true
/--
Similar to `synthesizeInstMVarCore`, but makes sure that `instMVar` local context and instances
are used. It also logs any error message produced. -/
private def synthesizePendingInstMVar (instMVar : MVarId) : TermElabM Bool :=
instMVar.withContext do
try
synthesizeInstMVarCore instMVar
catch
| ex@(.error ..) => logException ex; return true
| _ => unreachable!
/--
Try to synthesize `mvarId` by starting using a default instance with the give privority.
This method succeeds only if the metavariable of fully synthesized.
Remark: In the past, we would return a list of pending TC problems, but this was problematic since
a default instance may create subproblems that cannot be solved.
Remark: The new approach also has limitations because other pending metavariables are not taken into account
while backtraking. That is, we fail to synthesize `mvarId` because we reach subproblems that are stuck,
but we could "unstuck" them if we tried to solve other pending metavariables. Considering all pending metavariables
into a single backtracking search seems to be too expensive, and potentially generate incomprehensible error messages.
This is particularly true if we consider pending metavariables for "postponed" elaboration steps.
Here is an example that demonstrate this issue. The example considers we are using the old `binrel%` elaborator which was
disconnected from `binop%`.
```
example (a : Int) (b c : Nat) : a = βb - βc := sorry
```
We have two pending coercions for the `β` and `HSub ?m.220 ?m.221 ?m.222`.
When we did not use a backtracking search here, then the homogenous default instance for `HSub`.
```
instance [Sub Ξ±] : HSub Ξ± Ξ± Ξ± where
```
would be applied first, and would propagate the expected type `Int` to the pending coercions which would now be unblocked.
Instead of performing a backtracking search that considers all pending metavariables, we improved the `binrel%` elaborator.
-/
private partial def synthesizeUsingDefaultPrio (mvarId : MVarId) (prio : Nat) : TermElabM Bool :=
mvarId.withContext do
let mvarType β mvarId.getType
match (β isClass? mvarType) with
| none => return false
| some className =>
match (β getDefaultInstances className) with
| [] => return false
| defaultInstances =>
for (defaultInstance, instPrio) in defaultInstances do
if instPrio == prio then
if (β synthesizeUsingDefaultInstance mvarId defaultInstance) then
return true
return false
where
synthesizeUsingDefault (mvarId : MVarId) : TermElabM Bool := do
for prio in (β getDefaultInstancesPriorities) do
if (β synthesizeUsingDefaultPrio mvarId prio) then
return true
return false
synthesizePendingInstMVar' (mvarId : MVarId) : TermElabM Bool :=
commitWhen <| mvarId.withContext do
try
synthesizeInstMVarCore mvarId
catch _ =>
return false
synthesizeUsingInstancesStep (mvarIds : List MVarId) : TermElabM (List MVarId) :=
mvarIds.filterM fun mvarId => do
if (β synthesizePendingInstMVar' mvarId) then
return false
else
return true
synthesizeUsingInstances (mvarIds : List MVarId) : TermElabM (List MVarId) := do
let mvarIds' β synthesizeUsingInstancesStep mvarIds
if mvarIds'.length < mvarIds.length then
synthesizeUsingInstances mvarIds'
else
return mvarIds'
synthesizeUsingDefaultInstance (mvarId : MVarId) (defaultInstance : Name) : TermElabM Bool :=
commitWhen do
let candidate β mkConstWithFreshMVarLevels defaultInstance
let (mvars, bis, _) β forallMetaTelescopeReducing (β inferType candidate)
let candidate := mkAppN candidate mvars
trace[Elab.defaultInstance] "{toString (mkMVar mvarId)}, {mkMVar mvarId} : {β inferType (mkMVar mvarId)} =?= {candidate} : {β inferType candidate}"
/- The `coeAtOutParam` feature may mark output parameters of local instances as `syntheticOpaque`.
This kind of parameter is not assignable by default. We use `withAssignableSyntheticOpaque` to workaround this behavior
when processing default instances. TODO: try to avoid `withAssignableSyntheticOpaque`. -/
if (β withAssignableSyntheticOpaque <| isDefEqGuarded (mkMVar mvarId) candidate) then
-- Succeeded. Collect new TC problems
trace[Elab.defaultInstance] "isDefEq worked {mkMVar mvarId} : {β inferType (mkMVar mvarId)} =?= {candidate} : {β inferType candidate}"
let mut pending := []
for i in [:bis.size] do
if bis[i]! == BinderInfo.instImplicit then
pending := mvars[i]!.mvarId! :: pending
synthesizePending pending
else
return false
synthesizeSomeUsingDefault? (mvarIds : List MVarId) : TermElabM (Option (List MVarId)) := do
match mvarIds with
| [] => return none
| mvarId :: mvarIds =>
if (β synthesizeUsingDefault mvarId) then
return mvarIds
else if let some mvarIds' β synthesizeSomeUsingDefault? mvarIds then
return mvarId :: mvarIds'
else
return none
synthesizePending (mvarIds : List MVarId) : TermElabM Bool := do
let mvarIds β synthesizeUsingInstances mvarIds
if mvarIds.isEmpty then return true
let some mvarIds β synthesizeSomeUsingDefault? mvarIds | return false
synthesizePending mvarIds
/-- Used to implement `synthesizeUsingDefault`. This method only consider default instances with the given priority. -/
private def synthesizeSomeUsingDefaultPrio (prio : Nat) : TermElabM Bool := do
let rec visit (pendingMVars : List MVarId) (pendingMVarsNew : List MVarId) : TermElabM Bool := do
match pendingMVars with
| [] => return false
| mvarId :: pendingMVars =>
let some mvarDecl β getSyntheticMVarDecl? mvarId | visit pendingMVars (mvarId :: pendingMVarsNew)
match mvarDecl.kind with
| .typeClass =>
if (β withRef mvarDecl.stx <| synthesizeUsingDefaultPrio mvarId prio) then
modify fun s => { s with pendingMVars := pendingMVars.reverse ++ pendingMVarsNew }
return true
else
visit pendingMVars (mvarId :: pendingMVarsNew)
| _ => visit pendingMVars (mvarId :: pendingMVarsNew)
/- Recall that s.pendingMVars is essentially a stack. The first metavariable was the last one created.
We want to apply the default instance in reverse creation order. Otherwise,
`toString 0` will produce a `OfNat String _` cannot be synthesized error. -/
visit (β get).pendingMVars.reverse []
/--
Apply default value to any pending synthetic metavariable of kind `SyntheticMVarKind.withDefault`
Return true if something was synthesized. -/
private def synthesizeUsingDefault : TermElabM Bool := do
let prioSet β getDefaultInstancesPriorities
/- Recall that `prioSet` is stored in descending order -/
for prio in prioSet do
if (β synthesizeSomeUsingDefaultPrio prio) then
return true
return false
/--
We use this method to report typeclass (and coercion) resolution problems that are "stuck".
That is, there is nothing else to do, and we don't have enough information to synthesize them using TC resolution.
-/
def reportStuckSyntheticMVar (mvarId : MVarId) (ignoreStuckTC := false) : TermElabM Unit := do
let some mvarSyntheticDecl β getSyntheticMVarDecl? mvarId | return ()
withRef mvarSyntheticDecl.stx do
match mvarSyntheticDecl.kind with
| .typeClass =>
unless ignoreStuckTC do
mvarId.withContext do
let mvarDecl β getMVarDecl mvarId
unless (β MonadLog.hasErrors) do
throwError "typeclass instance problem is stuck, it is often due to metavariables{indentExpr mvarDecl.type}"
| .coe header expectedType e f? =>
mvarId.withContext do
throwTypeMismatchError header expectedType (β inferType e) e f?
m!"failed to create type class instance for{indentExpr (β getMVarDecl mvarId).type}"
| _ => unreachable! -- TODO handle other cases.
/--
Report an error for each synthetic metavariable that could not be resolved.
Remark: we set `ignoreStuckTC := true` when elaborating `simp` arguments.
-/
private def reportStuckSyntheticMVars (ignoreStuckTC := false) : TermElabM Unit := do
let pendingMVars β modifyGet fun s => (s.pendingMVars, { s with pendingMVars := [] })
for mvarId in pendingMVars do
reportStuckSyntheticMVar mvarId ignoreStuckTC
private def getSomeSynthethicMVarsRef : TermElabM Syntax := do
for mvarId in (β get).pendingMVars do
if let some decl β getSyntheticMVarDecl? mvarId then
if decl.stx.getPos?.isSome then
return decl.stx
return .missing
/--
Generate an nicer error message for stuck universe constraints.
-/
private def throwStuckAtUniverseCnstr : TermElabM Unit := do
-- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property
let entries β getPostponed
let mut found : HashSet (Level Γ Level) := {}
let mut uniqueEntries := #[]
for entry in entries do
let mut lhs := entry.lhs
let mut rhs := entry.rhs
if Level.normLt rhs lhs then
(lhs, rhs) := (rhs, lhs)
unless found.contains (lhs, rhs) do
found := found.insert (lhs, rhs)
uniqueEntries := uniqueEntries.push entry
for i in [1:uniqueEntries.size] do
logErrorAt uniqueEntries[i]!.ref (β mkLevelStuckErrorMessage uniqueEntries[i]!)
throwErrorAt uniqueEntries[0]!.ref (β mkLevelStuckErrorMessage uniqueEntries[0]!)
/--
Try to solve postponed universe constraints, and throws an exception if there are stuck constraints.
Remark: in previous versions, each `isDefEq u v` invocation would fail if there
were pending universe level constraints. With this old approach, we were not able
to process
```
Functor.map Prod.fst (x s)
```
because after elaborating `Prod.fst` and trying to ensure its type
match the expected one, we would be stuck at the universe constraint:
```
u =?= max u ?v
```
Another benefit of using `withoutPostponingUniverseConstraints` is better error messages. Instead
of getting a mysterious type mismatch constraint, we get a list of
universe contraints the system is stuck at.
-/
private def processPostponedUniverseContraints : TermElabM Unit := do
unless (β processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do
throwStuckAtUniverseCnstr
/--
Remove `mvarId` from the `syntheticMVars` table. We use this method after
the metavariable has been synthesized.
-/
private def markAsResolved (mvarId : MVarId) : TermElabM Unit :=
modify fun s => { s with syntheticMVars := s.syntheticMVars.erase mvarId }
mutual
/--
Try to synthesize a term `val` using the tactic code `tacticCode`, and then assign `mvarId := val`.
-/
partial def runTactic (mvarId : MVarId) (tacticCode : Syntax) : TermElabM Unit := withoutAutoBoundImplicit do
/- Recall, `tacticCode` is the whole `by ...` expression. -/
let code := tacticCode[1]
instantiateMVarDeclMVars mvarId
/-
TODO: consider using `runPendingTacticsAt` at `mvarId` local context and target type.
Issue #1380 demonstrates that the goal may still contain pending metavariables.
It happens in the following scenario we have a term `foo A (by tac)` where `A` has been postponed
and contains nested `by ...` terms. The pending metavar list contains two metavariables: ?m1 (for `A`) and
`?m2` (for `by tac`). When `A` is resumed, it creates a new metavariable `?m3` for the nested `by ...` term in `A`.
`?m3` is after `?m2` in the to-do list. Then, we execute `by tac` for synthesizing `?m2`, but its type depends on
`?m3`. We have considered putting `?m3` at `?m2` place in the to-do list, but this is not super robust.
The ideal solution is to make sure a tactic "resolves" all pending metavariables nested in their local contex and target type
before starting tactic execution. The procedure would be a generalization of `runPendingTacticsAt`. We can try to combine
it with `instantiateMVarDeclMVars` to make sure we do not perform two traversals.
Regarding issue #1380, we addressed the issue by avoiding the elaboration postponement step. However, the same issue can happen
in more complicated scenarios.
-/
try
let remainingGoals β withInfoHole mvarId <| Tactic.run mvarId do
withTacticInfoContext tacticCode (evalTactic code)
synthesizeSyntheticMVars (mayPostpone := false)
unless remainingGoals.isEmpty do
reportUnsolvedGoals remainingGoals
catch ex =>
if (β read).errToSorry then
for mvarId in (β getMVars (mkMVar mvarId)) do
mvarId.admit
logException ex
else
throw ex
/-- Try to synthesize the given pending synthetic metavariable. -/
private partial def synthesizeSyntheticMVar (mvarId : MVarId) (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := do
let some mvarSyntheticDecl β getSyntheticMVarDecl? mvarId | return true -- The metavariable has already been synthesized
withRef mvarSyntheticDecl.stx do
match mvarSyntheticDecl.kind with
| .typeClass => synthesizePendingInstMVar mvarId
| .coe _header? expectedType e _f? => mvarId.withContext do
if (β withDefault do isDefEq (β inferType e) expectedType) then
-- Types may be defeq now due to mvar assignments, type class
-- defaulting, etc.
if (β occursCheck mvarId e) then
mvarId.assign e
return true
if let .some coerced β coerce? e expectedType then
if (β occursCheck mvarId coerced) then
mvarId.assign coerced
return true
return false
-- NOTE: actual processing at `synthesizeSyntheticMVarsAux`
| .postponed savedContext => resumePostponed savedContext mvarSyntheticDecl.stx mvarId postponeOnError
| .tactic tacticCode savedContext =>
withSavedContext savedContext do
if runTactics then
runTactic mvarId tacticCode
return true
else
return false
/--
Try to synthesize the current list of pending synthetic metavariables.
Return `true` if at least one of them was synthesized. -/
private partial def synthesizeSyntheticMVarsStep (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := do
let ctx β read
traceAtCmdPos `Elab.resuming fun _ =>
m!"resuming synthetic metavariables, mayPostpone: {ctx.mayPostpone}, postponeOnError: {postponeOnError}"
let pendingMVars := (β get).pendingMVars
let numSyntheticMVars := pendingMVars.length
-- We reset `pendingMVars` because new synthetic metavariables may be created by `synthesizeSyntheticMVar`.
modify fun s => { s with pendingMVars := [] }
-- Recall that `pendingMVars` is a list where head is the most recent pending synthetic metavariable.
-- We use `filterRevM` instead of `filterM` to make sure we process the synthetic metavariables using the order they were created.
-- It would not be incorrect to use `filterM`.
let remainingPendingMVars β pendingMVars.filterRevM fun mvarId => do
-- We use `traceM` because we want to make sure the metavar local context is used to trace the message
traceM `Elab.postpone (mvarId.withContext do addMessageContext m!"resuming {mkMVar mvarId}")
let succeeded β synthesizeSyntheticMVar mvarId postponeOnError runTactics
if succeeded then markAsResolved mvarId
trace[Elab.postpone] if succeeded then format "succeeded" else format "not ready yet"
pure !succeeded
-- Merge new synthetic metavariables with `remainingPendingMVars`, i.e., metavariables that still couldn't be synthesized
modify fun s => { s with pendingMVars := s.pendingMVars ++ remainingPendingMVars }
return numSyntheticMVars != remainingPendingMVars.length
/--
Try to process pending synthetic metavariables. If `mayPostpone == false`,
then `pendingMVars` is `[]` after executing this method.
It keeps executing `synthesizeSyntheticMVarsStep` while progress is being made.
If `mayPostpone == false`, then it applies default instances to `SyntheticMVarKind.typeClass` (if available)
metavariables that are still unresolved, and then tries to resolve metavariables
with `mayPostpone == false`. That is, we force them to produce error messages and/or commit to
a "best option". If, after that, we still haven't made progress, we report "stuck" errors.
Remark: we set `ignoreStuckTC := true` when elaborating `simp` arguments. Then,
pending TC problems become implicit parameters for the simp theorem.
-/
partial def synthesizeSyntheticMVars (mayPostpone := true) (ignoreStuckTC := false) : TermElabM Unit := do
let rec loop (_ : Unit) : TermElabM Unit := do
withRef (β getSomeSynthethicMVarsRef) <| withIncRecDepth do
unless (β get).pendingMVars.isEmpty do
if β synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := false) then
loop ()
else if !mayPostpone then
/- Resume pending metavariables with "elaboration postponement" disabled.
We postpone elaboration errors in this step by setting `postponeOnError := true`.
Example:
```
#check let x := β¨1, 2β©; Prod.fst x
```
The term `β¨1, 2β©` can't be elaborated because the expected type is not know.
The `x` at `Prod.fst x` is not elaborated because the type of `x` is not known.
When we execute the following step with "elaboration postponement" disabled,
the elaborator fails at `β¨1, 2β©` and postpones it, and succeeds at `x` and learns
that its type must be of the form `Prod ?Ξ± ?Ξ²`.
Recall that we postponed `x` at `Prod.fst x` because its type it is not known.
We the type of `x` may learn later its type and it may contain implicit and/or auto arguments.
By disabling postponement, we are essentially giving up the opportunity of learning `x`s type
and assume it does not have implict and/or auto arguments. -/
if β withoutPostponing <| synthesizeSyntheticMVarsStep (postponeOnError := true) (runTactics := false) then
loop ()
else if β synthesizeUsingDefault then
loop ()
else if β withoutPostponing <| synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := false) then
loop ()
else if β synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := true) then
loop ()
else
reportStuckSyntheticMVars ignoreStuckTC
loop ()
unless mayPostpone do
processPostponedUniverseContraints
end
def synthesizeSyntheticMVarsNoPostponing (ignoreStuckTC := false) : TermElabM Unit :=
synthesizeSyntheticMVars (mayPostpone := false) (ignoreStuckTC := ignoreStuckTC)
/-- Keep invoking `synthesizeUsingDefault` until it returns false. -/
private partial def synthesizeUsingDefaultLoop : TermElabM Unit := do
if (β synthesizeUsingDefault) then
synthesizeSyntheticMVars (mayPostpone := true)
synthesizeUsingDefaultLoop
def synthesizeSyntheticMVarsUsingDefault : TermElabM Unit := do
synthesizeSyntheticMVars (mayPostpone := true)
synthesizeUsingDefaultLoop
private partial def withSynthesizeImp {Ξ±} (k : TermElabM Ξ±) (mayPostpone : Bool) (synthesizeDefault : Bool) : TermElabM Ξ± := do
let pendingMVarsSaved := (β get).pendingMVars
modify fun s => { s with pendingMVars := [] }
try
let a β k
synthesizeSyntheticMVars mayPostpone
if mayPostpone && synthesizeDefault then
synthesizeUsingDefaultLoop
return a
finally
modify fun s => { s with pendingMVars := s.pendingMVars ++ pendingMVarsSaved }
/--
Execute `k`, and synthesize pending synthetic metavariables created while executing `k` are solved.
If `mayPostpone == false`, then all of them must be synthesized.
Remark: even if `mayPostpone == true`, the method still uses `synthesizeUsingDefault` -/
@[inline] def withSynthesize [MonadFunctorT TermElabM m] [Monad m] (k : m Ξ±) (mayPostpone := false) : m Ξ± :=
monadMap (m := TermElabM) (withSynthesizeImp Β· mayPostpone (synthesizeDefault := true)) k
/-- Similar to `withSynthesize`, but sets `mayPostpone` to `true`, and do not use `synthesizeUsingDefault` -/
@[inline] def withSynthesizeLight [MonadFunctorT TermElabM m] [Monad m] (k : m Ξ±) : m Ξ± :=
monadMap (m := TermElabM) (withSynthesizeImp Β· (mayPostpone := true) (synthesizeDefault := false)) k
/-- Elaborate `stx`, and make sure all pending synthetic metavariables created while elaborating `stx` are solved. -/
def elabTermAndSynthesize (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr :=
withRef stx do
instantiateMVars (β withSynthesize <| elabTerm stx expectedType?)
/--
Collect unassigned metavariables at `e` that have associated tactic blocks, and then execute them using `runTactic`.
We use this method at the `match .. with` elaborator when it cannot be postponed anymore, but it is still waiting
the result of a tactic block.
-/
def runPendingTacticsAt (e : Expr) : TermElabM Unit := do
for mvarId in (β getMVars e) do
let mvarId β getDelayedMVarRoot mvarId
if let some { kind := .tactic tacticCode savedContext, .. } β getSyntheticMVarDecl? mvarId then
withSavedContext savedContext do
runTactic mvarId tacticCode
markAsResolved mvarId
builtin_initialize
registerTraceClass `Elab.resume
end Lean.Elab.Term
|
3fa9cb33f6c0288b53726f3b242a2df11624f8b3 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/topology/algebra/nonarchimedean/bases.lean | 2d43306ca28061beeeea13f46522c3b07b5dc9f4 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 12,478 | lean | /-
Copyright (c) 2021 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import topology.algebra.nonarchimedean.basic
import topology.algebra.filter_basis
import algebra.module.submodule.pointwise
/-!
# Neighborhood bases for non-archimedean rings and modules
This files contains special families of filter bases on rings and modules that give rise to
non-archimedean topologies.
The main definition is `ring_subgroups_basis` which is a predicate on a family of
additive subgroups of a ring. The predicate ensures there is a topology
`ring_subgroups_basis.topology` which is compatible with a ring structure and admits the given
family as a basis of neighborhoods of zero. In particular the given subgroups become open subgroups
(bundled in `ring_subgroups_basis.open_add_subgroup`) and we get a non-archimedean topological ring
(`ring_subgroups_basis.nonarchimedean`).
A special case of this construction is given by `submodules_basis` where the subgroups are
sub-modules in a commutative algebra. This important example gives rises to the adic topology
(studied in its own file).
-/
open set filter function lattice add_group_with_zero_nhd
open_locale topological_space filter pointwise
/-- A family of additive subgroups on a ring `A` is a subgroups basis if it satisfies some
axioms ensuring there is a topology on `A` which is compatible with the ring structure and
admits this family as a basis of neighborhoods of zero. -/
structure ring_subgroups_basis {A ΞΉ : Type*} [ring A] (B : ΞΉ β add_subgroup A) : Prop :=
(inter : β i j, β k, B k β€ B i β B j)
(mul : β i, β j, (B j : set A) * B j β B i)
(left_mul : β x : A, β i, β j, (B j : set A) β (Ξ» y : A, x*y) β»ΒΉ' (B i))
(right_mul : β x : A, β i, β j, (B j : set A) β (Ξ» y : A, y*x) β»ΒΉ' (B i))
namespace ring_subgroups_basis
variables {A ΞΉ : Type*} [ring A]
lemma of_comm {A ΞΉ : Type*} [comm_ring A] (B : ΞΉ β add_subgroup A)
(inter : β i j, β k, B k β€ B i β B j)
(mul : β i, β j, (B j : set A) * B j β B i)
(left_mul : β x : A, β i, β j, (B j : set A) β (Ξ» y : A, x*y) β»ΒΉ' (B i)) :
ring_subgroups_basis B :=
{ inter := inter,
mul := mul,
left_mul := left_mul,
right_mul := begin
intros x i,
cases left_mul x i with j hj,
use j,
simpa [mul_comm] using hj
end }
/-- Every subgroups basis on a ring leads to a ring filter basis. -/
def to_ring_filter_basis [nonempty ΞΉ] {B : ΞΉ β add_subgroup A}
(hB : ring_subgroups_basis B) : ring_filter_basis A :=
{ sets := {U | β i, U = B i},
nonempty := by { inhabit ΞΉ, exact β¨B default, default, rflβ© },
inter_sets := begin
rintros _ _ β¨i, rflβ© β¨j, rflβ©,
cases hB.inter i j with k hk,
use [B k, k, rfl, hk]
end,
zero' := by { rintros _ β¨i, rflβ©, exact (B i).zero_mem },
add' := begin
rintros _ β¨i, rflβ©,
use [B i, i, rfl],
rintros x β¨y, z, y_in, z_in, rflβ©,
exact (B i).add_mem y_in z_in
end,
neg' := begin
rintros _ β¨i, rflβ©,
use [B i, i, rfl],
intros x x_in,
exact (B i).neg_mem x_in
end,
conj' := begin
rintros xβ _ β¨i, rflβ©,
use [B i, i, rfl],
simp
end,
mul' := begin
rintros _ β¨i, rflβ©,
cases hB.mul i with k hk,
use [B k, k, rfl, hk]
end,
mul_left' := begin
rintros xβ _ β¨i, rflβ©,
cases hB.left_mul xβ i with k hk,
use [B k, k, rfl, hk]
end,
mul_right' := begin
rintros xβ _ β¨i, rflβ©,
cases hB.right_mul xβ i with k hk,
use [B k, k, rfl, hk]
end }
variables [nonempty ΞΉ] {B : ΞΉ β add_subgroup A} (hB : ring_subgroups_basis B)
lemma mem_add_group_filter_basis_iff {V : set A} :
V β hB.to_ring_filter_basis.to_add_group_filter_basis β β i, V = B i :=
iff.rfl
lemma mem_add_group_filter_basis (i) :
(B i : set A) β hB.to_ring_filter_basis.to_add_group_filter_basis :=
β¨i, rflβ©
/-- The topology defined from a subgroups basis, admitting the given subgroups as a basis
of neighborhoods of zero. -/
def topology : topological_space A :=
hB.to_ring_filter_basis.to_add_group_filter_basis.topology
lemma has_basis_nhds_zero : has_basis (@nhds A hB.topology 0) (Ξ» _, true) (Ξ» i, B i) :=
β¨begin
intros s,
rw hB.to_ring_filter_basis.to_add_group_filter_basis.nhds_zero_has_basis.mem_iff,
split,
{ rintro β¨-, β¨i, rflβ©, hiβ©,
exact β¨i, trivial, hiβ© },
{ rintro β¨i, -, hiβ©,
exact β¨B i, β¨i, rflβ©, hiβ© }
endβ©
lemma has_basis_nhds (a : A) :
has_basis (@nhds A hB.topology a) (Ξ» _, true) (Ξ» i, {b | b - a β B i}) :=
β¨begin
intros s,
rw (hB.to_ring_filter_basis.to_add_group_filter_basis.nhds_has_basis a).mem_iff,
simp only [exists_prop, exists_true_left],
split,
{ rintro β¨-, β¨i, rflβ©, hiβ©,
use i,
convert hi,
ext b,
split,
{ intros h,
use [b - a, h],
abel },
{ rintros β¨c, hc, rflβ©,
simpa using hc } },
{ rintros β¨i, hiβ©,
use [B i, i, rfl],
rw image_subset_iff,
rintro b b_in,
apply hi,
simpa using b_in }
endβ©
/-- Given a subgroups basis, the basis elements as open additive subgroups in the associated
topology. -/
def open_add_subgroup (i : ΞΉ) : @open_add_subgroup A _ hB.topology:=
{ is_open' := begin
letI := hB.topology,
rw is_open_iff_mem_nhds,
intros a a_in,
rw (hB.has_basis_nhds a).mem_iff,
use [i, trivial],
rintros b b_in,
simpa using (B i).add_mem a_in b_in
end,
..B i }
-- see Note [nonarchimedean non instances]
lemma nonarchimedean : @nonarchimedean_ring A _ hB.topology :=
begin
letI := hB.topology,
constructor,
intros U hU,
obtain β¨i, -, hi : (B i : set A) β Uβ© := hB.has_basis_nhds_zero.mem_iff.mp hU,
exact β¨hB.open_add_subgroup i, hiβ©
end
end ring_subgroups_basis
variables {ΞΉ R A : Type*} [comm_ring R] [comm_ring A] [algebra R A]
/-- A family of submodules in a commutative `R`-algebra `A` is a submodules basis if it satisfies
some axioms ensuring there is a topology on `A` which is compatible with the ring structure and
admits this family as a basis of neighborhoods of zero. -/
structure submodules_ring_basis (B : ΞΉ β submodule R A) : Prop :=
(inter : β i j, β k, B k β€ B i β B j)
(left_mul : β (a : A) i, β j, a β’ B j β€ B i)
(mul : β i, β j, (B j : set A) * B j β B i)
namespace submodules_ring_basis
variables {B : ΞΉ β submodule R A} (hB : submodules_ring_basis B)
lemma to_ring_subgroups_basis (hB : submodules_ring_basis B) :
ring_subgroups_basis (Ξ» i, (B i).to_add_subgroup) :=
begin
apply ring_subgroups_basis.of_comm (Ξ» i, (B i).to_add_subgroup) hB.inter hB.mul,
intros a i,
rcases hB.left_mul a i with β¨j, hjβ©,
use j,
rintros b (b_in : b β B j),
exact hj β¨b, b_in, rflβ©
end
/-- The topology associated to a basis of submodules in an algebra. -/
def topology [nonempty ΞΉ] (hB : submodules_ring_basis B) : topological_space A :=
hB.to_ring_subgroups_basis.topology
end submodules_ring_basis
variables {M : Type*} [add_comm_group M] [module R M]
/-- A family of submodules in an `R`-module `M` is a submodules basis if it satisfies
some axioms ensuring there is a topology on `M` which is compatible with the module structure and
admits this family as a basis of neighborhoods of zero. -/
structure submodules_basis [topological_space R]
(B : ΞΉ β submodule R M) : Prop :=
(inter : β i j, β k, B k β€ B i β B j)
(smul : β (m : M) (i : ΞΉ), βαΆ a in π (0 : R), a β’ m β B i)
namespace submodules_basis
variables [topological_space R] [nonempty ΞΉ] {B : ΞΉ β submodule R M}
(hB : submodules_basis B)
include hB
/-- The image of a submodules basis is a module filter basis. -/
def to_module_filter_basis : module_filter_basis R M :=
{ sets := {U | β i, U = B i},
nonempty := by { inhabit ΞΉ, exact β¨B default, default, rflβ© },
inter_sets := begin
rintros _ _ β¨i, rflβ© β¨j, rflβ©,
cases hB.inter i j with k hk,
use [B k, k, rfl, hk]
end,
zero' := by { rintros _ β¨i, rflβ©, exact (B i).zero_mem },
add' := begin
rintros _ β¨i, rflβ©,
use [B i, i, rfl],
rintros x β¨y, z, y_in, z_in, rflβ©,
exact (B i).add_mem y_in z_in
end,
neg' := begin
rintros _ β¨i, rflβ©,
use [B i, i, rfl],
intros x x_in,
exact (B i).neg_mem x_in
end,
conj' := begin
rintros xβ _ β¨i, rflβ©,
use [B i, i, rfl],
simp
end,
smul' := begin
rintros _ β¨i, rflβ©,
use [univ, univ_mem, B i, i, rfl],
rintros _ β¨a, m, -, hm, rflβ©,
exact (B i).smul_mem _ hm
end,
smul_left' := begin
rintros xβ _ β¨i, rflβ©,
use [B i, i, rfl],
intros m,
exact (B i).smul_mem _
end,
smul_right' := begin
rintros mβ _ β¨i, rflβ©,
exact hB.smul mβ i
end }
/-- The topology associated to a basis of submodules in a module. -/
def topology : topological_space M :=
hB.to_module_filter_basis.to_add_group_filter_basis.topology
/-- Given a submodules basis, the basis elements as open additive subgroups in the associated
topology. -/
def open_add_subgroup (i : ΞΉ) : @open_add_subgroup M _ hB.topology :=
{ is_open' := begin
letI := hB.topology,
rw is_open_iff_mem_nhds,
intros a a_in,
rw (hB.to_module_filter_basis.to_add_group_filter_basis.nhds_has_basis a).mem_iff,
use [B i, i, rfl],
rintros - β¨b, b_in, rflβ©,
exact (B i).add_mem a_in b_in
end,
..(B i).to_add_subgroup }
-- see Note [nonarchimedean non instances]
lemma nonarchimedean (hB : submodules_basis B) : @nonarchimedean_add_group M _ hB.topology:=
begin
letI := hB.topology,
constructor,
intros U hU,
obtain β¨-, β¨i, rflβ©, hi : (B i : set M) β Uβ© :=
hB.to_module_filter_basis.to_add_group_filter_basis.nhds_zero_has_basis.mem_iff.mp hU,
exact β¨hB.open_add_subgroup i, hiβ©
end
/-- The non archimedean subgroup basis lemmas cannot be instances because some instances
(such as `measure_theory.ae_eq_fun.add_monoid ` or `topological_add_group.to_has_continuous_add`)
cause the search for `@topological_add_group Ξ² ?m1 ?m2`, i.e. a search for a topological group where
the topology/group structure are unknown. -/
library_note "nonarchimedean non instances"
end submodules_basis
section
/-
In this section, we check that, in a `R`-algebra `A` over a ring equipped with a topology,
a basis of `R`-submodules which is compatible with the topology on `R` is also a submodule basis
in the sense of `R`-modules (forgetting about the ring structure on `A`) and those two points of
view definitionaly gives the same topology on `A`.
-/
variables [topological_space R] {B : ΞΉ β submodule R A} (hB : submodules_ring_basis B)
(hsmul : β (m : A) (i : ΞΉ), βαΆ (a : R) in π 0, a β’ m β B i)
lemma submodules_ring_basis.to_submodules_basis : submodules_basis B :=
{ inter := hB.inter,
smul := hsmul }
example [nonempty ΞΉ] : hB.topology = (hB.to_submodules_basis hsmul).topology := rfl
end
/-- Given a ring filter basis on a commutative ring `R`, define a compatibility condition
on a family of submodules of a `R`-module `M`. This compatibility condition allows to get
a topological module structure. -/
structure ring_filter_basis.submodules_basis (BR : ring_filter_basis R)
(B : ΞΉ β submodule R M) : Prop :=
(inter : β i j, β k, B k β€ B i β B j)
(smul : β (m : M) (i : ΞΉ), β U β BR, U β (Ξ» a, a β’ m) β»ΒΉ' B i)
lemma ring_filter_basis.submodules_basis_is_basis (BR : ring_filter_basis R) {B : ΞΉ β submodule R M}
(hB : BR.submodules_basis B) : @submodules_basis ΞΉ R _ M _ _ BR.topology B :=
{ inter := hB.inter,
smul := begin
letI := BR.topology,
intros m i,
rcases hB.smul m i with β¨V, V_in, hVβ©,
exact mem_of_superset (BR.to_add_group_filter_basis.mem_nhds_zero V_in) hV
end }
/-- The module filter basis associated to a ring filter basis and a compatible submodule basis.
This allows to build a topological module structure compatible with the given module structure
and the topology associated to the given ring filter basis. -/
def ring_filter_basis.module_filter_basis [nonempty ΞΉ] (BR : ring_filter_basis R)
{B : ΞΉ β submodule R M} (hB : BR.submodules_basis B) :
@module_filter_basis R M _ BR.topology _ _ :=
@submodules_basis.to_module_filter_basis ΞΉ R _ M _ _ BR.topology _ _
(BR.submodules_basis_is_basis hB)
|
8f56b09bd98ecdc96703c76fecb2dedfac71c084 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/nat/size.lean | ce81b1330f03112d8dd51ef88d4826fb1a08af35 | [
"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,646 | lean | /-
Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import data.nat.pow
import data.nat.bits
/-! Lemmas about `size`. -/
namespace nat
/-! ### `shiftl` and `shiftr` -/
lemma shiftl_eq_mul_pow (m) : β n, shiftl m n = m * 2 ^ n
| 0 := (nat.mul_one _).symm
| (k+1) := show bit0 (shiftl m k) = m * (2 * 2 ^ k),
by rw [bit0_val, shiftl_eq_mul_pow, mul_left_comm, mul_comm 2]
lemma shiftl'_tt_eq_mul_pow (m) : β n, shiftl' tt m n + 1 = (m + 1) * 2 ^ n
| 0 := by simp [shiftl, shiftl', pow_zero, nat.one_mul]
| (k+1) :=
begin
change bit1 (shiftl' tt m k) + 1 = (m + 1) * (2 * 2 ^ k),
rw bit1_val,
change 2 * (shiftl' tt m k + 1) = _,
rw [shiftl'_tt_eq_mul_pow, mul_left_comm, mul_comm 2],
end
lemma one_shiftl (n) : shiftl 1 n = 2 ^ n :=
(shiftl_eq_mul_pow _ _).trans (nat.one_mul _)
@[simp] lemma zero_shiftl (n) : shiftl 0 n = 0 :=
(shiftl_eq_mul_pow _ _).trans (nat.zero_mul _)
lemma shiftr_eq_div_pow (m) : β n, shiftr m n = m / 2 ^ n
| 0 := (nat.div_one _).symm
| (k+1) := (congr_arg div2 (shiftr_eq_div_pow k)).trans $
by rw [div2_val, nat.div_div_eq_div_mul, mul_comm]; refl
@[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 :=
(shiftr_eq_div_pow _ _).trans (nat.zero_div _)
theorem shiftl'_ne_zero_left (b) {m} (h : m β 0) (n) : shiftl' b m n β 0 :=
by induction n; simp [bit_ne_zero, shiftl', *]
theorem shiftl'_tt_ne_zero (m) : β {n} (h : n β 0), shiftl' tt m n β 0
| 0 h := absurd rfl h
| (succ n) _ := nat.bit1_ne_zero _
/-! ### `size` -/
@[simp] theorem size_zero : size 0 = 0 := by simp [size]
@[simp] theorem size_bit {b n} (h : bit b n β 0) : size (bit b n) = succ (size n) :=
begin
rw size,
conv { to_lhs, rw [binary_rec], simp [h] },
rw div2_bit,
end
@[simp] theorem size_bit0 {n} (h : n β 0) : size (bit0 n) = succ (size n) :=
@size_bit ff n (nat.bit0_ne_zero h)
@[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) :=
@size_bit tt n (nat.bit1_ne_zero n)
@[simp] theorem size_one : size 1 = 1 :=
show size (bit1 0) = 1, by rw [size_bit1, size_zero]
@[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n β 0) :
size (shiftl' b m n) = size m + n :=
begin
induction n with n IH; simp [shiftl'] at h β’,
rw [size_bit h, nat.add_succ],
by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]],
rw s0 at h β’,
cases b, {exact absurd rfl h},
have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0,
rw [shiftl'_tt_eq_mul_pow] at this,
obtain rfl := succ.inj (eq_one_of_dvd_one β¨_, this.symmβ©),
rw one_mul at this,
obtain rfl : n = 0 := nat.eq_zero_of_le_zero (le_of_not_gt $ Ξ» hn,
ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this),
refl
end
@[simp] theorem size_shiftl {m} (h : m β 0) (n) :
size (shiftl m n) = size m + n :=
size_shiftl' (shiftl'_ne_zero_left _ h _)
theorem lt_size_self (n : β) : n < 2^size n :=
begin
rw [β one_shiftl],
have : β {n}, n = 0 β n < shiftl 1 (size n), { simp },
apply binary_rec _ _ n, {apply this rfl},
intros b n IH,
by_cases bit b n = 0, {apply this h},
rw [size_bit h, shiftl_succ],
exact bit_lt_bit0 _ IH
end
theorem size_le {m n : β} : size m β€ n β m < 2^n :=
β¨Ξ» h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h),
begin
rw [β one_shiftl], revert n,
apply binary_rec _ _ m,
{ intros n h, simp },
{ intros b m IH n h,
by_cases e : bit b m = 0, { simp [e] },
rw [size_bit e],
cases n with n,
{ exact e.elim (nat.eq_zero_of_le_zero (le_of_lt_succ h)) },
{ apply succ_le_succ (IH _),
apply lt_imp_lt_of_le_imp_le (Ξ» h', bit0_le_bit _ h') h } }
endβ©
theorem lt_size {m n : β} : m < size n β 2^m β€ n :=
by rw [β not_lt, decidable.iff_not_comm, not_lt, size_le]
theorem size_pos {n : β} : 0 < size n β 0 < n :=
by rw lt_size; refl
theorem size_eq_zero {n : β} : size n = 0 β n = 0 :=
by have := @size_pos n; simp [pos_iff_ne_zero] at this;
exact decidable.not_iff_not.1 this
theorem size_pow {n : β} : size (2^n) = n+1 :=
le_antisymm
(size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _))
(lt_size.2 $ le_rfl)
theorem size_le_size {m n : β} (h : m β€ n) : size m β€ size n :=
size_le.2 $ lt_of_le_of_lt h (lt_size_self _)
lemma size_eq_bits_len (n : β) : n.bits.length = n.size :=
begin
induction n using nat.binary_rec' with b n h ih, { simp, },
rw [size_bit, bits_append_bit _ _ h],
{ simp [ih], },
{ simpa [bit_eq_zero_iff], }
end
end nat
|
efa904931047acc2cd2ebfa45996ed7ad3c55b68 | 3ef5255cebe505e5ab251615d9fbf31a132f461d | /lean/old/algebra.lean | 56d2cbae7a9c3090f4c9d6de53467eeb2b5c93a5 | [] | no_license | avigad/scratch | 42441a2ea94918049391e44d7adab304d3adea51 | 3fb9cef15bc5581c9602561427a7f295917990a2 | refs/heads/master | 1,608,917,412,424 | 1,473,078,921,000 | 1,473,078,921,000 | 17,224,172 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,383 | lean | ----------------------------------------------------------------------------------------------------
--
-- algebra.lean
-- Jeremy Avigad
--
-- Handling the algebraic hierarchy. Uses:
--
-- o unbundled type class encodings to overload constants and theorem names
-- o bundled records for structures
-- o instance declarations (unification hints) to relate the two
--
----------------------------------------------------------------------------------------------------
import macros
import tactic
-- simulate the "right" equality axioms
axiom subst' {A : (Type U)} {a b : A} {P : A β (Type 1)} (H1 : P a) (H2 : a = b) : P b
axiom subst'_heq {A : (Type U)} {a a' : A} {B : A β (Type 1)} (b : B a) (e : a = a') :
subst' b e == b
theorem eq_subst'_to_heq {A : (Type U)} {a a' : A} {B : A β (Type 1)} {b : B a} {e : a = a'}
{b' : B a'} (e2: b' = subst' b e) : b' == b
:= htrans (to_heq e2) (subst'_heq b e)
-- useful abbreviations
definition is_assoc {T : Type} (op : T β T β T) := β x y z, op (op x y) z = op x (op y z)
definition is_comm {T : Type} (op : T β T β T) := β x y, op x y = op y x
definition is_right_id {T : Type} (op : T β T β T) (e : T) := β x, op x e = x
definition is_left_id {T : Type} (op : T β T β T) (e : T) := β x, op e x = x
definition is_right_inv {T : Type} (op : T β T β T) (i : T β T) (e : T) := β x, op x (i x) = e
definition is_left_inv {T : Type} (op : T β T β T) (i : T β T) (e : T) := β x, op (i x) x = e
--
-- Type classes: overloaded constants
--
-- mul
definition has_mul (T : Type) (m : T β T β T) := true
definition mk_mul_instance (T : Type) (m : T β T β T) : has_mul T m := trivial
definition mul {T : Type} {m : T β T β T} {instance : has_mul T m} : T β T β T
:= m
theorem mul_def {T : Type} {m : T β T β T} (instance : has_mul T m) : @mul T m instance = m
:= refl _
set_opaque has_mul true
set_opaque mk_mul_instance true
set_opaque mul true
-- an abbreviation with the third argument explicit
definition mul_of {T : Type} {m : T β T β T} (instance : has_mul T m) : T β T β T
:= @mul T m instance
-- one
definition has_one (T : Type) (o : T) := true
definition mk_one_instance (T : Type) (o : T) : has_one T o := trivial
definition one {T : Type} {o : T} {instance : has_one T o} : T
:= o
theorem one_def {T : Type} {o : T} (instance : has_one T o) : @one T o instance = o
:= refl _
set_opaque has_one true
set_opaque mk_one_instance true
set_opaque one true
definition one_of {T : Type} {o : T} (instance : has_one T o) : T
:= @one T o instance
-- inv
definition has_inv (T : Type) (i : T β T) := true
definition mk_inv_instance (T : Type) (i : T β T) : has_inv T i := trivial
definition inv {T : Type} {i : T β T} {instance : has_inv T i} : T β T
:= i
theorem inv_def {T : Type} {i : T β T} (instance : has_inv T i) : @inv T i instance = i
:= refl _
set_opaque has_inv true
set_opaque mk_inv_instance true
set_opaque inv true
definition inv_of {T : Type} {i : T β T} (instance : has_inv T i) : T β T
:= @inv T i instance
--
-- Type classes: overloaded theorem names
--
-- mul_assoc
definition is_mul_assoc {T : Type} (m : T β T β T) := is_assoc m
definition mk_mul_assoc_instance {T : Type} {m : T β T β T} (H : is_assoc m) : is_mul_assoc m
:= H
theorem assoc_of_mul_assoc {T : Type} {m : T β T β T} (H : is_mul_assoc m) : is_assoc m
:= H
theorem mul_assoc {T : Type} {m : T β T β T} {mul_inst : has_mul T m}
{assoc_inst : is_mul_assoc m} : is_assoc (mul_of mul_inst)
:= subst assoc_inst (symm (mul_def mul_inst))
set_opaque is_mul_assoc true
set_opaque mk_mul_assoc_instance true
-- mul_comm
definition is_mul_comm {T : Type} (m : T β T β T) := is_comm m
definition mk_mul_comm_instance {T : Type} {m : T β T β T} (H : is_comm m) : is_mul_comm m
:= H
theorem comm_of_mul_comm {T : Type} {m : T β T β T} (H : is_mul_comm m) : is_comm m
:= H
theorem mul_comm {T : Type} {m : T β T β T} {mul_inst : has_mul T m}
{comm_inst : is_mul_comm m} : is_comm (mul_of mul_inst)
:= subst comm_inst (symm (mul_def mul_inst))
set_opaque is_mul_comm true
set_opaque mk_mul_comm_instance true
-- mul_right_id
definition is_mul_right_id {T : Type} (m : T β T β T) (o : T) := is_right_id m o
definition mk_mul_right_id_instance {T : Type} {m : T β T β T} {o : T} (H : is_right_id m o)
: is_mul_right_id m o
:= H
theorem right_id_of_mul_right_id {T : Type} {m : T β T β T} {o : T} (H : is_mul_right_id m o)
: is_right_id m o
:= H
theorem mul_right_id {T : Type} {m : T β T β T} {o : T} {mul_inst : has_mul T m}
{one_inst : has_one T o} {right_id_inst : is_mul_right_id m o} :
is_right_id (mul_of mul_inst) (one_of one_inst)
:= subst (subst right_id_inst (symm (mul_def mul_inst))) (symm (one_def one_inst))
set_opaque is_mul_right_id true
set_opaque mk_mul_right_id_instance true
-- mul_left_id
definition is_mul_left_id {T : Type} (m : T β T β T) (o : T) := is_left_id m o
definition mk_mul_left_id_instance {T : Type} {m : T β T β T} {o : T} (H : is_left_id m o)
: is_mul_left_id m o
:= H
theorem left_id_of_mul_left_id {T : Type} {m : T β T β T} {o : T} (H : is_mul_left_id m o)
: is_left_id m o
:= H
theorem mul_left_id {T : Type} {m : T β T β T} {o : T} {mul_inst : has_mul T m}
{one_inst : has_one T o} {left_id_inst : is_mul_left_id m o} :
is_left_id (mul_of mul_inst) (one_of one_inst)
:= subst (subst left_id_inst (symm (mul_def mul_inst))) (symm (one_def one_inst))
set_opaque is_mul_left_id true
set_opaque mk_mul_left_id_instance true
-- mul_right_inv
definition is_mul_right_inv {T : Type} (m : T β T β T) (i : T β T) (o : T) := is_right_inv m i o
definition mk_mul_right_inv_instance {T : Type} {m : T β T β T} {i : T β T} {o : T}
(H : is_right_inv m i o)
: is_mul_right_inv m i o
:= H
theorem right_inv_of_mul_right_inv {T : Type} {m : T β T β T} {i : T β T} {o : T}
(H : is_mul_right_inv m i o)
: is_right_inv m i o
:= H
theorem mul_right_inv {T : Type} {m : T β T β T} {i : T β T} {o : T} {mul_inst : has_mul T m}
{inv_inst : has_inv T i} {one_inst : has_one T o} {right_inv_inst : is_mul_right_inv m i o} :
is_right_inv (mul_of mul_inst) (inv_of inv_inst) (one_of one_inst)
:= subst (subst (subst right_inv_inst (symm (mul_def mul_inst))) (symm (inv_def inv_inst)))
(symm (one_def one_inst))
set_opaque is_mul_right_inv true
set_opaque mk_mul_right_inv_instance true
-- mul_left_inv
definition is_mul_left_inv {T : Type} (m : T β T β T) (i : T β T) (o : T) := is_left_inv m i o
definition mk_mul_left_inv_instance {T : Type} {m : T β T β T} {i : T β T} {o : T}
(H : is_left_inv m i o)
: is_mul_left_inv m i o
:= H
theorem left_inv_of_mul_left_inv {T : Type} {m : T β T β T} {i : T β T} {o : T}
(H : is_mul_left_inv m i o)
: is_left_inv m i o
:= H
theorem mul_left_inv {T : Type} {m : T β T β T} {i : T β T} {o : T} {mul_inst : has_mul T m}
{inv_inst : has_inv T i} {one_inst : has_one T o} {left_inv_inst : is_mul_left_inv m i o} :
is_left_inv (mul_of mul_inst) (inv_of inv_inst) (one_of one_inst)
:= subst (subst (subst left_inv_inst (symm (mul_def mul_inst))) (symm (inv_def inv_inst)))
(symm (one_def one_inst))
set_opaque is_mul_left_inv true
set_opaque mk_mul_left_inv_instance true
--
-- Semigroup Structure
--
-- semigroup record
variable Semigroup : (Type 1)
variable mk_Semigroup (T : Type) (m : T β T β T) (H : is_assoc m) : Semigroup
variable Semigroup_rec (P : Semigroup β (Type 1)) :
(β T : Type, β m : T β T β T, β H : is_assoc m, P (mk_Semigroup T m H)) β
β S : Semigroup, P S
axiom Semigroup_comp (P : Semigroup β (Type 1))
(f : β T : Type, β m : T β T β T, β H : is_assoc m, P (mk_Semigroup T m H))
(T : Type) (m : T β T β T) (H : is_assoc m) :
Semigroup_rec P f (mk_Semigroup T m H) = f T m H
definition Semigroup_carrier : Semigroup β Type
:= Semigroup_rec (Ξ» S, Type) (Ξ» T : Type, Ξ» m : T β T β T, Ξ» H : is_assoc m, T)
theorem Semigroup_carrier_eq : β T : Type, β m H, Semigroup_carrier (mk_Semigroup T m H) = T
:= Semigroup_comp (Ξ» S, Type) (Ξ» T : Type, Ξ» m : T β T β T, Ξ» H : is_assoc m, T)
definition Semigroup_mul : β S : Semigroup, Semigroup_carrier S β Semigroup_carrier S β
Semigroup_carrier S
:=
let P := Ξ» S, Semigroup_carrier S β Semigroup_carrier S β Semigroup_carrier S in
let f := Ξ» T : Type, Ξ» m : T β T β T, Ξ» H : is_assoc m,
(subst' m (symm (Semigroup_carrier_eq T m H))) in
Semigroup_rec P f -- without specifying P, elaborator freezes
theorem Semigroup_mul_eq' : β T m H, Semigroup_mul (mk_Semigroup T m H) =
subst' m (symm (Semigroup_carrier_eq T m H))
:= Semigroup_comp _ _
theorem Semigroup_mul_eq : β T m H, Semigroup_mul (mk_Semigroup T m H) == m
:= Ξ» T : Type, Ξ» m H, eq_subst'_to_heq (Semigroup_mul_eq' T m H)
-- This can be defined by the recursor as above, but now we need two casts.
-- For now, I am lazy.
axiom Semigroup_mul_assoc : β S : Semigroup, is_assoc (Semigroup_mul S)
-- We can replace "Bool" by "(Type 1)" here and in the next lemma, for new recursion
-- principles. But is that useful?
theorem Semigroup_bundle' (P : β T : Type, β m : T β T β T, Bool) :
(β T m, is_assoc m β P T m) β (β S : Semigroup, P (Semigroup_carrier S) (Semigroup_mul S))
:= take f S, f (Semigroup_carrier S) (Semigroup_mul S) (Semigroup_mul_assoc S)
theorem Semigroup_unbundle' (P : β T : Type, β m : T β T β T, Bool) :
(β S : Semigroup, P (Semigroup_carrier S) (Semigroup_mul S)) β (β T m, is_assoc m β P T m)
:=
take f T m, assume H : is_assoc m,
let S := mk_Semigroup T m H in
have e1 : Semigroup_carrier S == T, from to_heq (Semigroup_carrier_eq _ _ _),
have e2 : Semigroup_mul S == m, from Semigroup_mul_eq _ _ _,
have e3 : P (Semigroup_carrier S) == P T, from hcongr (hrefl _) e1,
-- note: simp doesn't work here, nor does plugging in the definition of e3
have e4 : P (Semigroup_carrier S) (Semigroup_mul S) == P T m, from hcongr e3 e2,
cast e4 (f S)
set_opaque Semigroup_carrier true
set_opaque Semigroup_mul true
-- type class instantiations
definition mul_of_Semigroup (S : Semigroup)
:= mk_mul_instance (Semigroup_carrier S) (Semigroup_mul S)
definition Semigroup_is_mul_assoc (S : Semigroup)
:= mk_mul_assoc_instance (Semigroup_mul_assoc S)
theorem mul_of_Semigroup_eq (S : Semigroup) : mul_of (mul_of_Semigroup S) = Semigroup_mul S
:= mul_def _
-- now bundle and unbundle with type class version of "mul"
theorem Semigroup_bundle (P : β T : Type, β m : T β T β T, Bool) :
(β T m, is_assoc m β P T m) β
(β S : Semigroup, P (Semigroup_carrier S) (mul_of (mul_of_Semigroup S)))
:= take f S, subst' (Semigroup_bundle' P f S) (symm (mul_of_Semigroup_eq S))
theorem Semigroup_unbundle (P : β T : Type, β m : T β T β T, Bool) :
(β S : Semigroup, P (Semigroup_carrier S) (mul_of (mul_of_Semigroup S))) β
(β T m, is_assoc m β P T m)
:= take f, let f' := Ξ» S, subst' (f S) (mul_of_Semigroup_eq S) in Semigroup_unbundle' P f'
-- converts theorems to type class versions
-- after synthesizing this term from P and f, the last four arguments should be made implicit
theorem Semigroup_unbundled_to_type_class
(P : β T : Type, β m : T β T β T, Bool) (f : β T m, is_assoc m β P T m)
(T : Type) (m : T β T β T) (mul_inst : has_mul T m) (assoc_inst : is_mul_assoc m) : P T m
:= f T m (assoc_of_mul_assoc assoc_inst)
theorem Semigroup_bundled_to_type_class
(P : β T : Type, β m : T β T β T, Bool)
(f : β S : Semigroup, P (Semigroup_carrier S) (mul_of (mul_of_Semigroup S)))
(T : Type) (m : T β T β T) (mul_inst : has_mul T m) (assoc_inst : is_mul_assoc m) : P T m
:= Semigroup_unbundle P f T m (assoc_of_mul_assoc assoc_inst)
set_opaque mul_of_Semigroup true
set_opaque Semigroup_is_mul_assoc true
print "Unification hints:"
check mul_of_Semigroup
check Semigroup_is_mul_assoc
-- In this example, the implicit arguments given explicitly in the definitions of mul' and
-- mul_assoc' would be inferred using the unification hints mul_of_Semigroup and
-- Semigroup_is_mul_assoc, using the fact that the arguments have type Semigroup_carrier S.
theorem example1: β S : Semigroup, β x y z w : Semigroup_carrier S,
let mul' := @mul _ _ (mul_of_Semigroup S) in
mul' (mul' (mul' x y) z) w = mul' x (mul' y (mul' z w))
:=
take S : Semigroup,
take x y z w : Semigroup_carrier S,
let mul' := @mul _ _ (mul_of_Semigroup S) in
let mul_assoc' := @mul_assoc _ _ (mul_of_Semigroup S) (Semigroup_is_mul_assoc S) in
calc
mul' (mul' (mul' x y) z) w = mul' (mul' x y) (mul' z w) : { mul_assoc' _ _ _}
... = mul' x (mul' y (mul' z w)) : { mul_assoc' _ _ _}
definition example1_body (T : Type) (m : T β T β T) := β x y z w : T,
m (m (m x y) z) w = m x (m y (m z w))
definition type_of {T : Type} (t : T) := T
print ""
print "*** Example 1: ***"
print ""
check example1
print ""
eval type_of example1
print ""
definition example1_unbundled := Semigroup_unbundle example1_body example1
check example1_unbundled
print ""
eval type_of example1_unbundled
print ""
definition example1_as_type_class := Semigroup_bundled_to_type_class example1_body example1
check example1_as_type_class
print ""
eval type_of example1_as_type_class
print ""
definition example1_rebundled := Semigroup_bundle example1_body example1_unbundled
check example1_rebundled
print ""
eval type_of example1_rebundled
print ""
definition example1_rebundled_as_record := Semigroup_bundle' example1_body example1_unbundled
check example1_rebundled_as_record
print ""
eval type_of example1_rebundled_as_record
print ""
--
-- Monoid Structure
--
-- monoid record
definition is_monoid {T : Type} (m : T β T β T) (o : T) :=
is_assoc m β§ is_right_id m o β§ is_left_id m o
variable Monoid : (Type 1)
variable mk_Monoid (T : Type) (m : T β T β T) (o : T) (H : is_monoid m o) : Monoid
variable Monoid_carrier : Monoid β Type
variable Monoid_mul : β S : Monoid, Monoid_carrier S β Monoid_carrier S β Monoid_carrier S
variable Monoid_one : β S : Monoid, Monoid_carrier S
variable Monoid_is_monoid : β S : Monoid, is_monoid (Monoid_mul S) (Monoid_one S)
axiom Monoid_carrier_eq : β T m o H, Monoid_carrier (mk_Monoid T m o H) = T
axiom Monoid_mul_eq : β T m o H, Monoid_mul (mk_Monoid T m o H) == m
axiom Monoid_one_eq : β T m o H, Monoid_one (mk_Monoid T m o H) == o
-- type class instantiations
definition mul_of_Monoid (S : Monoid)
:= mk_mul_instance (Monoid_carrier S) (Monoid_mul S)
definition one_of_Monoid (S : Monoid)
:= mk_one_instance (Monoid_carrier S) (Monoid_one S)
definition Monoid_is_mul_assoc (S : Monoid)
:= mk_mul_assoc_instance (and_eliml (Monoid_is_monoid S))
definition Monoid_is_right_id (S : Monoid)
:= mk_mul_right_id_instance (and_eliml (and_elimr (Monoid_is_monoid S)))
definition Monoid_is_left_id (S : Monoid)
:= mk_mul_left_id_instance (and_elimr (and_elimr (Monoid_is_monoid S)))
set_opaque mul_of_Monoid true
set_opaque one_of_Monoid true
set_opaque Monoid_is_mul_assoc true
set_opaque Monoid_is_right_id true
set_opaque Monoid_is_left_id true
print "Unification hints:"
check mul_of_Monoid
check one_of_Monoid
check Monoid_is_mul_assoc
check Monoid_is_right_id
check Monoid_is_left_id
-- This is the same example as before, except that a different mul and mul_assoc are inferred
theorem example2: β S : Monoid, β x y z w : Monoid_carrier S,
let mul' := @mul _ _ (mul_of_Monoid S) in
mul' (mul' (mul' x y) z) w = mul' x (mul' y (mul' z w))
:=
take S : Monoid,
take x y z w : Monoid_carrier S,
let mul' := @mul _ _ (mul_of_Monoid S) in
let mul_assoc' := @mul_assoc _ _ (mul_of_Monoid S) (Monoid_is_mul_assoc S) in
calc
mul' (mul' (mul' x y) z) w = mul' (mul' x y) (mul' z w) : { mul_assoc' _ _ _}
... = mul' x (mul' y (mul' z w)) : { mul_assoc' _ _ _}
-- here is another example
theorem example3: β S : Monoid, β x y : Monoid_carrier S,
let mul' := @mul _ _ (mul_of_Monoid S) in
let one' := @one _ _ (one_of_Monoid S) in
mul' (mul' x y) one' = mul' x y
:= take S x y, @mul_right_id _ _ _ (mul_of_Monoid S) (one_of_Monoid S) (Monoid_is_right_id S) _
|
51c57fd5091d999b607c7db45d38fc80215aec99 | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/Compiler/IR/EmitUtil.lean | 18feb899cbb77715b2036d970f7b7037a9457912 | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,163 | 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.Compiler.InitAttr
import Lean.Compiler.IR.CompilerM
/- Helper functions for backend code generators -/
namespace Lean
namespace IR
/- Return true iff `b` is of the form `let x := g ys; ret x` -/
def isTailCallTo (g : Name) (b : FnBody) : Bool :=
match b with
| FnBody.vdecl x _ (Expr.fap f _) (FnBody.ret (Arg.var y)) => x == y && f == g
| _ => false
def usesModuleFrom (env : Environment) (modulePrefix : Name) : Bool :=
env.allImportedModuleNames.toList.any $ fun modName => modulePrefix.isPrefixOf modName
namespace CollectUsedDecls
abbrev M := ReaderT Environment (StateM NameSet)
@[inline] def collect (f : FunId) : M Unit :=
modify $ fun s => s.insert f
partial def collectFnBody : FnBody β M Unit
| FnBody.vdecl _ _ v b =>
match v with
| Expr.fap f _ => collect f *> collectFnBody b
| Expr.pap f _ => collect f *> collectFnBody b
| other => collectFnBody b
| FnBody.jdecl _ _ v b => collectFnBody v *> collectFnBody b
| FnBody.case _ _ _ alts => alts.forM $ fun alt => collectFnBody alt.body
| e => unless e.isTerminal $ collectFnBody e.body
def collectInitDecl (fn : Name) : M Unit := do
env β read;
match getInitFnNameFor env fn with
| some initFn => collect initFn
| _ => pure ()
def collectDecl : Decl β M NameSet
| Decl.fdecl fn _ _ b => collectInitDecl fn *> CollectUsedDecls.collectFnBody b *> get
| Decl.extern fn _ _ _ => collectInitDecl fn *> get
end CollectUsedDecls
def collectUsedDecls (env : Environment) (decl : Decl) (used : NameSet := {}) : NameSet :=
(CollectUsedDecls.collectDecl decl env).run' used
abbrev VarTypeMap := Std.HashMap VarId IRType
abbrev JPParamsMap := Std.HashMap JoinPointId (Array Param)
namespace CollectMaps
abbrev Collector := (VarTypeMap Γ JPParamsMap) β (VarTypeMap Γ JPParamsMap)
@[inline] def collectVar (x : VarId) (t : IRType) : Collector
| (vs, js) => (vs.insert x t, js)
def collectParams (ps : Array Param) : Collector :=
fun s => ps.foldl (fun s p => collectVar p.x p.ty s) s
@[inline] def collectJP (j : JoinPointId) (xs : Array Param) : Collector
| (vs, js) => (vs, js.insert j xs)
/- `collectFnBody` assumes the variables in -/
partial def collectFnBody : FnBody β Collector
| FnBody.vdecl x t _ b => collectVar x t β collectFnBody b
| FnBody.jdecl j xs v b => collectJP j xs β collectParams xs β collectFnBody v β collectFnBody b
| FnBody.case _ _ _ alts => fun s => alts.foldl (fun s alt => collectFnBody alt.body s) s
| e => if e.isTerminal then id else collectFnBody e.body
def collectDecl : Decl β Collector
| Decl.fdecl _ xs _ b => collectParams xs β collectFnBody b
| _ => id
end CollectMaps
/- Return a pair `(v, j)`, where `v` is a mapping from variable/parameter to type,
and `j` is a mapping from join point to parameters.
This function assumes `d` has normalized indexes (see `normids.lean`). -/
def mkVarJPMaps (d : Decl) : VarTypeMap Γ JPParamsMap :=
CollectMaps.collectDecl d ({}, {})
end IR
end Lean
|
1ce0e132651dc94155350e27017facdcee79dd2c | 94e33a31faa76775069b071adea97e86e218a8ee | /src/topology/uniform_space/completion.lean | 0135982727cfd99d6a8a93970af74d95b94dd08d | [
"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 | 23,749 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes HΓΆlzl
-/
import topology.uniform_space.abstract_completion
/-!
# Hausdorff completions of uniform spaces
The goal is to construct a left-adjoint to the inclusion of complete Hausdorff uniform spaces
into all uniform spaces. Any uniform space `Ξ±` gets a completion `completion Ξ±` and a morphism
(ie. uniformly continuous map) `coe : Ξ± β completion Ξ±` which solves the universal
mapping problem of factorizing morphisms from `Ξ±` to any complete Hausdorff uniform space `Ξ²`.
It means any uniformly continuous `f : Ξ± β Ξ²` gives rise to a unique morphism
`completion.extension f : completion Ξ± β Ξ²` such that `f = completion.extension f β coe`.
Actually `completion.extension f` is defined for all maps from `Ξ±` to `Ξ²` but it has the desired
properties only if `f` is uniformly continuous.
Beware that `coe` is not injective if `Ξ±` is not Hausdorff. But its image is always
dense. The adjoint functor acting on morphisms is then constructed by the usual abstract nonsense.
For every uniform spaces `Ξ±` and `Ξ²`, it turns `f : Ξ± β Ξ²` into a morphism
`completion.map f : completion Ξ± β completion Ξ²`
such that
`coe β f = (completion.map f) β coe`
provided `f` is uniformly continuous. This construction is compatible with composition.
In this file we introduce the following concepts:
* `Cauchy Ξ±` the uniform completion of the uniform space `Ξ±` (using Cauchy filters). These are not
minimal filters.
* `completion Ξ± := quotient (separation_setoid (Cauchy Ξ±))` the Hausdorff completion.
## References
This formalization is mostly based on
N. Bourbaki: General Topology
I. M. James: Topologies and Uniformities
From a slightly different perspective in order to reuse material in topology.uniform_space.basic.
-/
noncomputable theory
open filter set
universes u v w x
open_locale uniformity classical topological_space filter
/-- Space of Cauchy filters
This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters.
This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all
entourages) is necessary for this.
-/
def Cauchy (Ξ± : Type u) [uniform_space Ξ±] : Type u := { f : filter Ξ± // cauchy f }
namespace Cauchy
section
parameters {Ξ± : Type u} [uniform_space Ξ±]
variables {Ξ² : Type v} {Ξ³ : Type w}
variables [uniform_space Ξ²] [uniform_space Ξ³]
def gen (s : set (Ξ± Γ Ξ±)) : set (Cauchy Ξ± Γ Cauchy Ξ±) :=
{p | s β p.1.val ΓαΆ p.2.val }
lemma monotone_gen : monotone gen :=
monotone_set_of $ assume p, @monotone_mem (Ξ±ΓΞ±) (p.1.val ΓαΆ p.2.val)
private lemma symm_gen : map prod.swap ((π€ Ξ±).lift' gen) β€ (π€ Ξ±).lift' gen :=
calc map prod.swap ((π€ Ξ±).lift' gen) =
(π€ Ξ±).lift' (Ξ»s:set (Ξ±ΓΞ±), {p | s β p.2.val ΓαΆ p.1.val }) :
begin
delta gen,
simp [map_lift'_eq, monotone_set_of, monotone_mem,
function.comp, image_swap_eq_preimage_swap, -subtype.val_eq_coe]
end
... β€ (π€ Ξ±).lift' gen :
uniformity_lift_le_swap
(monotone_principal.comp (monotone_set_of $ assume p,
@monotone_mem (Ξ±ΓΞ±) (p.2.val ΓαΆ p.1.val)))
begin
have h := Ξ»(p:Cauchy Ξ±ΓCauchy Ξ±), @filter.prod_comm _ _ (p.2.val) (p.1.val),
simp [function.comp, h, -subtype.val_eq_coe, mem_map'],
exact le_rfl,
end
private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (Ξ±ΓΞ±)} : comp_rel (gen s) (gen t) β
(gen (comp_rel s t) : set (Cauchy Ξ± Γ Cauchy Ξ±)) :=
assume β¨f, gβ© β¨h, hβ, hββ©,
let β¨tβ, (htβ : tβ β f.val), tβ, (htβ : tβ β h.val), (hβ : tβ ΓΛ’ tβ β s)β© :=
mem_prod_iff.mp hβ in
let β¨tβ, (htβ : tβ β h.val), tβ, (htβ : tβ β g.val), (hβ : tβ ΓΛ’ tβ β t)β© :=
mem_prod_iff.mp hβ in
have tβ β© tβ β h.val,
from inter_mem htβ htβ,
let β¨x, xtβ, xtββ© :=
h.property.left.nonempty_of_mem this in
(f.val ΓαΆ g.val).sets_of_superset
(prod_mem_prod htβ htβ)
(assume β¨a, bβ© β¨(ha : a β tβ), (hb : b β tβ)β©,
β¨x,
hβ (show (a, x) β tβ ΓΛ’ tβ, from β¨ha, xtββ©),
hβ (show (x, b) β tβ ΓΛ’ tβ, from β¨xtβ, hbβ©)β©)
private lemma comp_gen :
((π€ Ξ±).lift' gen).lift' (Ξ»s, comp_rel s s) β€ (π€ Ξ±).lift' gen :=
calc ((π€ Ξ±).lift' gen).lift' (Ξ»s, comp_rel s s) =
(π€ Ξ±).lift' (Ξ»s, comp_rel (gen s) (gen s)) :
begin
rw [lift'_lift'_assoc],
exact monotone_gen,
exact (monotone_comp_rel monotone_id monotone_id)
end
... β€ (π€ Ξ±).lift' (Ξ»s, gen $ comp_rel s s) :
lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel
... = ((π€ Ξ±).lift' $ Ξ»s:set(Ξ±ΓΞ±), comp_rel s s).lift' gen :
begin
rw [lift'_lift'_assoc],
exact (monotone_comp_rel monotone_id monotone_id),
exact monotone_gen
end
... β€ (π€ Ξ±).lift' gen : lift'_mono comp_le_uniformity le_rfl
instance : uniform_space (Cauchy Ξ±) :=
uniform_space.of_core
{ uniformity := (π€ Ξ±).lift' gen,
refl := principal_le_lift' $ assume s hs β¨a, bβ© (a_eq_b : a = b),
a_eq_b βΈ a.property.right hs,
symm := symm_gen,
comp := comp_gen }
theorem mem_uniformity {s : set (Cauchy Ξ± Γ Cauchy Ξ±)} :
s β π€ (Cauchy Ξ±) β β t β π€ Ξ±, gen t β s :=
mem_lift'_sets monotone_gen
theorem mem_uniformity' {s : set (Cauchy Ξ± Γ Cauchy Ξ±)} :
s β π€ (Cauchy Ξ±) β β t β π€ Ξ±, β f g : Cauchy Ξ±, t β f.1 ΓαΆ g.1 β (f, g) β s :=
mem_uniformity.trans $ bex_congr $ Ξ» t h, prod.forall
/-- Embedding of `Ξ±` into its completion `Cauchy Ξ±` -/
def pure_cauchy (a : Ξ±) : Cauchy Ξ± :=
β¨pure a, cauchy_pureβ©
lemma uniform_inducing_pure_cauchy : uniform_inducing (pure_cauchy : Ξ± β Cauchy Ξ±) :=
β¨have (preimage (Ξ» (x : Ξ± Γ Ξ±), (pure_cauchy (x.fst), pure_cauchy (x.snd))) β gen) = id,
from funext $ assume s, set.ext $ assume β¨aβ, aββ©,
by simp [preimage, gen, pure_cauchy, prod_principal_principal],
calc comap (Ξ» (x : Ξ± Γ Ξ±), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ((π€ Ξ±).lift' gen)
= (π€ Ξ±).lift'
(preimage (Ξ» (x : Ξ± Γ Ξ±), (pure_cauchy (x.fst), pure_cauchy (x.snd))) β gen) :
comap_lift'_eq
... = π€ Ξ± : by simp [this]β©
lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : Ξ± β Cauchy Ξ±) :=
{ inj := assume aβ aβ h, pure_injective $ subtype.ext_iff_val.1 h,
..uniform_inducing_pure_cauchy }
lemma dense_range_pure_cauchy : dense_range pure_cauchy :=
assume f,
have h_ex : β s β π€ (Cauchy Ξ±), βy:Ξ±, (f, pure_cauchy y) β s, from
assume s hs,
let β¨t'', ht''β, (ht''β : gen t'' β s)β© := (mem_lift'_sets monotone_gen).mp hs in
let β¨t', ht'β, ht'ββ© := comp_mem_uniformity_sets ht''β in
have t' β f.val ΓαΆ f.val,
from f.property.right ht'β,
let β¨t, ht, (h : t ΓΛ’ t β t')β© := mem_prod_same_iff.mp this in
let β¨x, (hx : x β t)β© := f.property.left.nonempty_of_mem ht in
have t'' β f.val ΓαΆ pure x,
from mem_prod_iff.mpr β¨t, ht, {y:Ξ± | (x, y) β t'},
h $ mk_mem_prod hx hx,
assume β¨a, bβ© β¨(hβ : a β t), (hβ : (x, b) β t')β©,
ht'β $ prod_mk_mem_comp_rel (@h (a, x) β¨hβ, hxβ©) hββ©,
β¨x, ht''β $ by dsimp [gen]; exact thisβ©,
begin
simp only [closure_eq_cluster_pts, cluster_pt, nhds_eq_uniformity, lift'_inf_principal_eq,
set.inter_comm _ (range pure_cauchy), mem_set_of_eq],
exact (lift'_ne_bot_iff $ monotone_const.inter monotone_preimage).mpr
(assume s hs,
let β¨y, hyβ© := h_ex s hs in
have pure_cauchy y β range pure_cauchy β© {y : Cauchy Ξ± | (f, y) β s},
from β¨mem_range_self y, hyβ©,
β¨_, thisβ©)
end
lemma dense_inducing_pure_cauchy : dense_inducing pure_cauchy :=
uniform_inducing_pure_cauchy.dense_inducing dense_range_pure_cauchy
lemma dense_embedding_pure_cauchy : dense_embedding pure_cauchy :=
uniform_embedding_pure_cauchy.dense_embedding dense_range_pure_cauchy
lemma nonempty_Cauchy_iff : nonempty (Cauchy Ξ±) β nonempty Ξ± :=
begin
split ; rintro β¨cβ©,
{ have := eq_univ_iff_forall.1 dense_embedding_pure_cauchy.to_dense_inducing.closure_range c,
obtain β¨_, β¨_, a, _β©β© := mem_closure_iff.1 this _ is_open_univ trivial,
exact β¨aβ© },
{ exact β¨pure_cauchy cβ© }
end
section
set_option eqn_compiler.zeta true
instance : complete_space (Cauchy Ξ±) :=
complete_space_extension
uniform_inducing_pure_cauchy
dense_range_pure_cauchy $
assume f hf,
let f' : Cauchy Ξ± := β¨f, hfβ© in
have map pure_cauchy f β€ (π€ $ Cauchy Ξ±).lift' (preimage (prod.mk f')),
from le_lift' $ assume s hs,
let β¨t, htβ, (htβ : gen t β s)β© := (mem_lift'_sets monotone_gen).mp hs in
let β¨t', ht', (h : t' ΓΛ’ t' β t)β© := mem_prod_same_iff.mp (hf.right htβ) in
have t' β { y : Ξ± | (f', pure_cauchy y) β gen t },
from assume x hx, (f ΓαΆ pure x).sets_of_superset (prod_mem_prod ht' hx) h,
f.sets_of_superset ht' $ subset.trans this (preimage_mono htβ),
β¨f', by simp [nhds_eq_uniformity]; assumptionβ©
end
instance [inhabited Ξ±] : inhabited (Cauchy Ξ±) :=
β¨pure_cauchy defaultβ©
instance [h : nonempty Ξ±] : nonempty (Cauchy Ξ±) :=
h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a
section extend
def extend (f : Ξ± β Ξ²) : (Cauchy Ξ± β Ξ²) :=
if uniform_continuous f then
dense_inducing_pure_cauchy.extend f
else
Ξ» x, f (classical.inhabited_of_nonempty $ nonempty_Cauchy_iff.1 β¨xβ©).default
section separated_space
variables [separated_space Ξ²]
lemma extend_pure_cauchy {f : Ξ± β Ξ²} (hf : uniform_continuous f) (a : Ξ±) :
extend f (pure_cauchy a) = f a :=
begin
rw [extend, if_pos hf],
exact uniformly_extend_of_ind uniform_inducing_pure_cauchy dense_range_pure_cauchy hf _
end
end separated_space
variables [_root_.complete_space Ξ²]
lemma uniform_continuous_extend {f : Ξ± β Ξ²} : uniform_continuous (extend f) :=
begin
by_cases hf : uniform_continuous f,
{ rw [extend, if_pos hf],
exact uniform_continuous_uniformly_extend uniform_inducing_pure_cauchy
dense_range_pure_cauchy hf },
{ rw [extend, if_neg hf],
exact uniform_continuous_of_const (assume a b, by congr) }
end
end extend
end
theorem Cauchy_eq {Ξ± : Type*} [inhabited Ξ±] [uniform_space Ξ±] [complete_space Ξ±]
[separated_space Ξ±] {f g : Cauchy Ξ±} :
Lim f.1 = Lim g.1 β (f, g) β separation_rel (Cauchy Ξ±) :=
begin
split,
{ intros e s hs,
rcases Cauchy.mem_uniformity'.1 hs with β¨t, tu, tsβ©,
apply ts,
rcases comp_mem_uniformity_sets tu with β¨d, du, dtβ©,
refine mem_prod_iff.2
β¨_, f.2.le_nhds_Lim (mem_nhds_right (Lim f.1) du),
_, g.2.le_nhds_Lim (mem_nhds_left (Lim g.1) du), Ξ» x h, _β©,
cases x with a b, cases h with hβ hβ,
rw β e at hβ,
exact dt β¨_, hβ, hββ© },
{ intros H,
refine separated_def.1 (by apply_instance) _ _ (Ξ» t tu, _),
rcases mem_uniformity_is_closed tu with β¨d, du, dc, dtβ©,
refine H {p | (Lim p.1.1, Lim p.2.1) β t}
(Cauchy.mem_uniformity'.2 β¨d, du, Ξ» f g h, _β©),
rcases mem_prod_iff.1 h with β¨x, xf, y, yg, hβ©,
have limc : β (f : Cauchy Ξ±) (x β f.1), Lim f.1 β closure x,
{ intros f x xf,
rw closure_eq_cluster_pts,
exact f.2.1.mono
(le_inf f.2.le_nhds_Lim (le_principal_iff.2 xf)) },
have := dc.closure_subset_iff.2 h,
rw closure_prod_eq at this,
refine dt (this β¨_, _β©); dsimp; apply limc; assumption }
end
section
local attribute [instance] uniform_space.separation_setoid
lemma separated_pure_cauchy_injective {Ξ± : Type*} [uniform_space Ξ±] [s : separated_space Ξ±] :
function.injective (Ξ»a:Ξ±, β¦pure_cauchy aβ§) | a b h :=
separated_def.1 s _ _ $ assume s hs,
let β¨t, ht, htsβ© :=
by rw [β (@uniform_embedding_pure_cauchy Ξ± _).comap_uniformity, filter.mem_comap] at hs;
exact hs in
have (pure_cauchy a, pure_cauchy b) β t, from quotient.exact h t ht,
@hts (a, b) this
end
end Cauchy
local attribute [instance] uniform_space.separation_setoid
open Cauchy set
namespace uniform_space
variables (Ξ± : Type*) [uniform_space Ξ±]
variables {Ξ² : Type*} [uniform_space Ξ²]
variables {Ξ³ : Type*} [uniform_space Ξ³]
instance complete_space_separation [h : complete_space Ξ±] :
complete_space (quotient (separation_setoid Ξ±)) :=
β¨assume f, assume hf : cauchy f,
have cauchy (f.comap (Ξ»x, β¦xβ§)), from
hf.comap' comap_quotient_le_uniformity $ hf.left.comap_of_surj (surjective_quotient_mk _),
let β¨x, (hx : f.comap (Ξ»x, β¦xβ§) β€ π x)β© := complete_space.complete this in
β¨β¦xβ§, (comap_le_comap_iff $ by simp).1
(hx.trans $ map_le_iff_le_comap.1 continuous_quotient_mk.continuous_at)β©β©
/-- Hausdorff completion of `Ξ±` -/
def completion := quotient (separation_setoid $ Cauchy Ξ±)
namespace completion
instance [inhabited Ξ±] : inhabited (completion Ξ±) :=
quotient.inhabited (separation_setoid (Cauchy Ξ±))
@[priority 50]
instance : uniform_space (completion Ξ±) := separation_setoid.uniform_space
instance : complete_space (completion Ξ±) := uniform_space.complete_space_separation (Cauchy Ξ±)
instance : separated_space (completion Ξ±) := uniform_space.separated_separation
instance : t3_space (completion Ξ±) := separated_t3
/-- Automatic coercion from `Ξ±` to its completion. Not always injective. -/
instance : has_coe_t Ξ± (completion Ξ±) := β¨quotient.mk β pure_cauchyβ© -- note [use has_coe_t]
protected lemma coe_eq : (coe : Ξ± β completion Ξ±) = quotient.mk β pure_cauchy := rfl
lemma comap_coe_eq_uniformity :
(π€ _).comap (Ξ»(p:Ξ±ΓΞ±), ((p.1 : completion Ξ±), (p.2 : completion Ξ±))) = π€ Ξ± :=
begin
have : (Ξ»x:Ξ±ΓΞ±, ((x.1 : completion Ξ±), (x.2 : completion Ξ±))) =
(Ξ»x:(Cauchy Ξ±)Γ(Cauchy Ξ±), (β¦x.1β§, β¦x.2β§)) β (Ξ»x:Ξ±ΓΞ±, (pure_cauchy x.1, pure_cauchy x.2)),
{ ext β¨a, bβ©; simp; refl },
rw [this, β filter.comap_comap],
change filter.comap _ (filter.comap _ (π€ $ quotient $ separation_setoid $ Cauchy Ξ±)) = π€ Ξ±,
rw [comap_quotient_eq_uniformity, uniform_embedding_pure_cauchy.comap_uniformity]
end
lemma uniform_inducing_coe : uniform_inducing (coe : Ξ± β completion Ξ±) :=
β¨comap_coe_eq_uniformity Ξ±β©
variables {Ξ±}
lemma dense_range_coe : dense_range (coe : Ξ± β completion Ξ±) :=
dense_range_pure_cauchy.quotient
variables (Ξ±)
def cpkg {Ξ± : Type*} [uniform_space Ξ±] : abstract_completion Ξ± :=
{ space := completion Ξ±,
coe := coe,
uniform_struct := by apply_instance,
complete := by apply_instance,
separation := by apply_instance,
uniform_inducing := completion.uniform_inducing_coe Ξ±,
dense := completion.dense_range_coe }
instance abstract_completion.inhabited : inhabited (abstract_completion Ξ±) :=
β¨cpkgβ©
local attribute [instance]
abstract_completion.uniform_struct abstract_completion.complete abstract_completion.separation
lemma nonempty_completion_iff : nonempty (completion Ξ±) β nonempty Ξ± :=
cpkg.dense.nonempty_iff.symm
lemma uniform_continuous_coe : uniform_continuous (coe : Ξ± β completion Ξ±) :=
cpkg.uniform_continuous_coe
lemma continuous_coe : continuous (coe : Ξ± β completion Ξ±) :=
cpkg.continuous_coe
lemma uniform_embedding_coe [separated_space Ξ±] : uniform_embedding (coe : Ξ± β completion Ξ±) :=
{ comap_uniformity := comap_coe_eq_uniformity Ξ±,
inj := separated_pure_cauchy_injective }
lemma coe_injective [separated_space Ξ±] : function.injective (coe : Ξ± β completion Ξ±) :=
uniform_embedding.inj (uniform_embedding_coe _)
variable {Ξ±}
lemma dense_inducing_coe : dense_inducing (coe : Ξ± β completion Ξ±) :=
{ dense := dense_range_coe,
..(uniform_inducing_coe Ξ±).inducing }
open topological_space
instance separable_space_completion [separable_space Ξ±] : separable_space (completion Ξ±) :=
completion.dense_inducing_coe.separable_space
lemma dense_embedding_coe [separated_space Ξ±]: dense_embedding (coe : Ξ± β completion Ξ±) :=
{ inj := separated_pure_cauchy_injective,
..dense_inducing_coe }
lemma dense_range_coeβ :
dense_range (Ξ»x:Ξ± Γ Ξ², ((x.1 : completion Ξ±), (x.2 : completion Ξ²))) :=
dense_range_coe.prod_map dense_range_coe
lemma dense_range_coeβ :
dense_range (Ξ»x:Ξ± Γ (Ξ² Γ Ξ³),
((x.1 : completion Ξ±), ((x.2.1 : completion Ξ²), (x.2.2 : completion Ξ³)))) :=
dense_range_coe.prod_map dense_range_coeβ
@[elab_as_eliminator]
lemma induction_on {p : completion Ξ± β Prop}
(a : completion Ξ±) (hp : is_closed {a | p a}) (ih : βa:Ξ±, p a) : p a :=
is_closed_property dense_range_coe hp ih a
@[elab_as_eliminator]
lemma induction_onβ {p : completion Ξ± β completion Ξ² β Prop}
(a : completion Ξ±) (b : completion Ξ²)
(hp : is_closed {x : completion Ξ± Γ completion Ξ² | p x.1 x.2})
(ih : β(a:Ξ±) (b:Ξ²), p a b) : p a b :=
have βx : completion Ξ± Γ completion Ξ², p x.1 x.2, from
is_closed_property dense_range_coeβ hp $ assume β¨a, bβ©, ih a b,
this (a, b)
@[elab_as_eliminator]
lemma induction_onβ {p : completion Ξ± β completion Ξ² β completion Ξ³ β Prop}
(a : completion Ξ±) (b : completion Ξ²) (c : completion Ξ³)
(hp : is_closed {x : completion Ξ± Γ completion Ξ² Γ completion Ξ³ | p x.1 x.2.1 x.2.2})
(ih : β(a:Ξ±) (b:Ξ²) (c:Ξ³), p a b c) : p a b c :=
have βx : completion Ξ± Γ completion Ξ² Γ completion Ξ³, p x.1 x.2.1 x.2.2, from
is_closed_property dense_range_coeβ hp $ assume β¨a, b, cβ©, ih a b c,
this (a, b, c)
lemma ext {Y : Type*} [topological_space Y] [t2_space Y] {f g : completion Ξ± β Y}
(hf : continuous f) (hg : continuous g) (h : βa:Ξ±, f a = g a) : f = g :=
cpkg.funext hf hg h
lemma ext' {Y : Type*} [topological_space Y] [t2_space Y] {f g : completion Ξ± β Y}
(hf : continuous f) (hg : continuous g) (h : βa:Ξ±, f a = g a) (a : completion Ξ±) :
f a = g a :=
congr_fun (ext hf hg h) a
section extension
variables {f : Ξ± β Ξ²}
/-- "Extension" to the completion. It is defined for any map `f` but
returns an arbitrary constant value if `f` is not uniformly continuous -/
protected def extension (f : Ξ± β Ξ²) : completion Ξ± β Ξ² :=
cpkg.extend f
section complete_space
variables [complete_space Ξ²]
lemma uniform_continuous_extension : uniform_continuous (completion.extension f) :=
cpkg.uniform_continuous_extend
lemma continuous_extension : continuous (completion.extension f) :=
cpkg.continuous_extend
end complete_space
@[simp] lemma extension_coe [separated_space Ξ²] (hf : uniform_continuous f) (a : Ξ±) :
(completion.extension f) a = f a :=
cpkg.extend_coe hf a
variables [separated_space Ξ²] [complete_space Ξ²]
lemma extension_unique (hf : uniform_continuous f) {g : completion Ξ± β Ξ²}
(hg : uniform_continuous g) (h : β a : Ξ±, f a = g (a : completion Ξ±)) :
completion.extension f = g :=
cpkg.extend_unique hf hg h
@[simp] lemma extension_comp_coe {f : completion Ξ± β Ξ²} (hf : uniform_continuous f) :
completion.extension (f β coe) = f :=
cpkg.extend_comp_coe hf
end extension
section map
variables {f : Ξ± β Ξ²}
/-- Completion functor acting on morphisms -/
protected def map (f : Ξ± β Ξ²) : completion Ξ± β completion Ξ² :=
cpkg.map cpkg f
lemma uniform_continuous_map : uniform_continuous (completion.map f) :=
cpkg.uniform_continuous_map cpkg f
lemma continuous_map : continuous (completion.map f) :=
cpkg.continuous_map cpkg f
@[simp] lemma map_coe (hf : uniform_continuous f) (a : Ξ±) : (completion.map f) a = f a :=
cpkg.map_coe cpkg hf a
lemma map_unique {f : Ξ± β Ξ²} {g : completion Ξ± β completion Ξ²}
(hg : uniform_continuous g) (h : βa:Ξ±, β(f a) = g a) : completion.map f = g :=
cpkg.map_unique cpkg hg h
@[simp] lemma map_id : completion.map (@id Ξ±) = id :=
cpkg.map_id
lemma extension_map [complete_space Ξ³] [separated_space Ξ³] {f : Ξ² β Ξ³} {g : Ξ± β Ξ²}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
completion.extension f β completion.map g = completion.extension (f β g) :=
completion.ext (continuous_extension.comp continuous_map) continuous_extension $
by intro a; simp only [hg, hf, hf.comp hg, (β), map_coe, extension_coe]
lemma map_comp {g : Ξ² β Ξ³} {f : Ξ± β Ξ²} (hg : uniform_continuous g) (hf : uniform_continuous f) :
completion.map g β completion.map f = completion.map (g β f) :=
extension_map ((uniform_continuous_coe _).comp hg) hf
end map
/- In this section we construct isomorphisms between the completion of a uniform space and the
completion of its separation quotient -/
section separation_quotient_completion
def completion_separation_quotient_equiv (Ξ± : Type u) [uniform_space Ξ±] :
completion (separation_quotient Ξ±) β completion Ξ± :=
begin
refine β¨completion.extension (separation_quotient.lift (coe : Ξ± β completion Ξ±)),
completion.map quotient.mk, _, _β©,
{ assume a,
refine induction_on a (is_closed_eq (continuous_map.comp continuous_extension) continuous_id) _,
rintros β¨aβ©,
show completion.map quotient.mk
(completion.extension (separation_quotient.lift coe) ββ¦aβ§) = ββ¦aβ§,
rw [extension_coe (separation_quotient.uniform_continuous_lift _),
separation_quotient.lift_mk (uniform_continuous_coe Ξ±),
completion.map_coe uniform_continuous_quotient_mk] ; apply_instance },
{ assume a,
refine completion.induction_on a
(is_closed_eq (continuous_extension.comp continuous_map) continuous_id) (Ξ» a, _),
rw [map_coe uniform_continuous_quotient_mk,
extension_coe (separation_quotient.uniform_continuous_lift _),
separation_quotient.lift_mk (uniform_continuous_coe Ξ±) _] ; apply_instance }
end
lemma uniform_continuous_completion_separation_quotient_equiv :
uniform_continuous β(completion_separation_quotient_equiv Ξ±) :=
uniform_continuous_extension
lemma uniform_continuous_completion_separation_quotient_equiv_symm :
uniform_continuous β(completion_separation_quotient_equiv Ξ±).symm :=
uniform_continuous_map
end separation_quotient_completion
section extensionβ
variables (f : Ξ± β Ξ² β Ξ³)
open function
protected def extensionβ (f : Ξ± β Ξ² β Ξ³) : completion Ξ± β completion Ξ² β Ξ³ :=
cpkg.extendβ cpkg f
section separated_space
variables [separated_space Ξ³] {f}
@[simp] lemma extensionβ_coe_coe (hf : uniform_continuousβ f) (a : Ξ±) (b : Ξ²) :
completion.extensionβ f a b = f a b :=
cpkg.extensionβ_coe_coe cpkg hf a b
end separated_space
variables [complete_space Ξ³] (f)
lemma uniform_continuous_extensionβ : uniform_continuousβ (completion.extensionβ f) :=
cpkg.uniform_continuous_extensionβ cpkg f
end extensionβ
section mapβ
open function
protected def mapβ (f : Ξ± β Ξ² β Ξ³) : completion Ξ± β completion Ξ² β completion Ξ³ :=
cpkg.mapβ cpkg cpkg f
lemma uniform_continuous_mapβ (f : Ξ± β Ξ² β Ξ³) : uniform_continuousβ (completion.mapβ f) :=
cpkg.uniform_continuous_mapβ cpkg cpkg f
lemma continuous_mapβ {Ξ΄} [topological_space Ξ΄] {f : Ξ± β Ξ² β Ξ³}
{a : Ξ΄ β completion Ξ±} {b : Ξ΄ β completion Ξ²} (ha : continuous a) (hb : continuous b) :
continuous (Ξ»d:Ξ΄, completion.mapβ f (a d) (b d)) :=
cpkg.continuous_mapβ cpkg cpkg ha hb
lemma mapβ_coe_coe (a : Ξ±) (b : Ξ²) (f : Ξ± β Ξ² β Ξ³) (hf : uniform_continuousβ f) :
completion.mapβ f (a : completion Ξ±) (b : completion Ξ²) = f a b :=
cpkg.mapβ_coe_coe cpkg cpkg a b f hf
end mapβ
end completion
end uniform_space
|
f303a9248d5ef1fa1a454114263e2f779eb37318 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/data/pnat/basic.lean | b778079441a6d80e40aa00a254b76e7d867416af | [
"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 | 17,816 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Neil Strickland
-/
import data.nat.basic
/-!
# The positive natural numbers
This file defines the type `β+` or `pnat`, the subtype of natural numbers that are positive.
-/
/-- `β+` is the type of positive natural numbers. It is defined as a subtype,
and the VM representation of `β+` is the same as `β` because the proof
is not stored. -/
@[derive linear_order]
def pnat := {n : β // 0 < n}
notation `β+` := pnat
instance coe_pnat_nat : has_coe β+ β := β¨subtype.valβ©
instance : has_repr β+ := β¨Ξ» n, repr n.1β©
namespace pnat
/-- Predecessor of a `β+`, as a `β`. -/
def nat_pred (i : β+) : β := i - 1
@[simp] lemma one_add_nat_pred (n : β+) : 1 + n.nat_pred = n :=
by rw [nat_pred, add_tsub_cancel_iff_le.mpr $ show 1 β€ (n : β), from n.2]
@[simp] lemma nat_pred_add_one (n : β+) : n.nat_pred + 1 = n :=
(add_comm _ _).trans n.one_add_nat_pred
@[simp] lemma nat_pred_eq_pred {n : β} (h : 0 < n) : nat_pred (β¨n, hβ© : β+) = n.pred := rfl
@[mono] lemma nat_pred_strict_mono : strict_mono nat_pred := Ξ» m n h, nat.pred_lt_pred m.2.ne' h
@[mono] lemma nat_pred_monotone : monotone nat_pred := nat_pred_strict_mono.monotone
lemma nat_pred_injective : function.injective nat_pred := nat_pred_strict_mono.injective
@[simp] lemma nat_pred_lt_nat_pred {m n : β+} : m.nat_pred < n.nat_pred β m < n :=
nat_pred_strict_mono.lt_iff_lt
@[simp] lemma nat_pred_le_nat_pred {m n : β+} : m.nat_pred β€ n.nat_pred β m β€ n :=
nat_pred_strict_mono.le_iff_le
@[simp] lemma nat_pred_inj {m n : β+} : m.nat_pred = n.nat_pred β m = n := nat_pred_injective.eq_iff
end pnat
namespace nat
/-- Convert a natural number to a positive natural number. The
positivity assumption is inferred by `dec_trivial`. -/
def to_pnat (n : β) (h : 0 < n . tactic.exact_dec_trivial) : β+ := β¨n, hβ©
/-- Write a successor as an element of `β+`. -/
def succ_pnat (n : β) : β+ := β¨succ n, succ_pos nβ©
@[simp] theorem succ_pnat_coe (n : β) : (succ_pnat n : β) = succ n := rfl
@[mono] theorem succ_pnat_strict_mono : strict_mono succ_pnat := Ξ» m n, nat.succ_lt_succ
@[mono] theorem succ_pnat_mono : monotone succ_pnat := succ_pnat_strict_mono.monotone
@[simp] theorem succ_pnat_lt_succ_pnat {m n : β} : m.succ_pnat < n.succ_pnat β m < n :=
succ_pnat_strict_mono.lt_iff_lt
@[simp] theorem succ_pnat_le_succ_pnat {m n : β} : m.succ_pnat β€ n.succ_pnat β m β€ n :=
succ_pnat_strict_mono.le_iff_le
theorem succ_pnat_injective : function.injective succ_pnat := succ_pnat_strict_mono.injective
@[simp] theorem succ_pnat_inj {n m : β} : succ_pnat n = succ_pnat m β n = m :=
succ_pnat_injective.eq_iff
@[simp] theorem nat_pred_succ_pnat (n : β) : n.succ_pnat.nat_pred = n := rfl
@[simp] theorem _root_.pnat.succ_pnat_nat_pred (n : β+) : n.nat_pred.succ_pnat = n :=
subtype.eq $ succ_pred_eq_of_pos n.2
/-- Convert a natural number to a pnat. `n+1` is mapped to itself,
and `0` becomes `1`. -/
def to_pnat' (n : β) : β+ := succ_pnat (pred n)
@[simp] theorem to_pnat'_coe : β (n : β),
((to_pnat' n) : β) = ite (0 < n) n 1
| 0 := rfl
| (m + 1) := by {rw [if_pos (succ_pos m)], refl}
end nat
namespace pnat
open nat
/-- We now define a long list of structures on β+ induced by
similar structures on β. Most of these behave in a completely
obvious way, but there are a few things to be said about
subtraction, division and powers.
-/
instance : decidable_eq β+ := Ξ» (a b : β+), by apply_instance
@[simp] lemma mk_le_mk (n k : β) (hn : 0 < n) (hk : 0 < k) :
(β¨n, hnβ© : β+) β€ β¨k, hkβ© β n β€ k := iff.rfl
@[simp] lemma mk_lt_mk (n k : β) (hn : 0 < n) (hk : 0 < k) :
(β¨n, hnβ© : β+) < β¨k, hkβ© β n < k := iff.rfl
@[simp, norm_cast] lemma coe_le_coe (n k : β+) : (n : β) β€ k β n β€ k := iff.rfl
@[simp, norm_cast] lemma coe_lt_coe (n k : β+) : (n : β) < k β n < k := iff.rfl
@[simp] theorem pos (n : β+) : 0 < (n : β) := n.2
-- see note [fact non_instances]
lemma fact_pos (n : β+) : fact (0 < βn) := β¨n.posβ©
theorem eq {m n : β+} : (m : β) = n β m = n := subtype.eq
@[simp] lemma coe_inj {m n : β+} : (m : β) = n β m = n := set_coe.ext_iff
lemma coe_injective : function.injective (coe : β+ β β) := subtype.coe_injective
@[simp] theorem mk_coe (n h) : ((β¨n, hβ© : β+) : β) = n := rfl
instance : has_add β+ := β¨Ξ» a b, β¨(a + b : β), add_pos a.pos b.posβ©β©
instance : add_comm_semigroup β+ := coe_injective.add_comm_semigroup coe (Ξ» _ _, rfl)
@[simp] theorem add_coe (m n : β+) : ((m + n : β+) : β) = m + n := rfl
/-- `pnat.coe` promoted to an `add_hom`, that is, a morphism which preserves addition. -/
def coe_add_hom : add_hom β+ β :=
{ to_fun := coe,
map_add' := add_coe }
instance : add_left_cancel_semigroup β+ :=
coe_injective.add_left_cancel_semigroup coe (Ξ» _ _, rfl)
instance : add_right_cancel_semigroup β+ :=
coe_injective.add_right_cancel_semigroup coe (Ξ» _ _, rfl)
/-- An equivalence between `β+` and `β` given by `pnat.nat_pred` and `nat.succ_pnat`. -/
@[simps { fully_applied := ff }] def _root_.equiv.pnat_equiv_nat : β+ β β :=
{ to_fun := pnat.nat_pred,
inv_fun := nat.succ_pnat,
left_inv := succ_pnat_nat_pred,
right_inv := nat.nat_pred_succ_pnat }
/-- The order isomorphism between β and β+ given by `succ`. -/
@[simps apply { fully_applied := ff }] def _root_.order_iso.pnat_iso_nat : β+ βo β :=
{ to_equiv := equiv.pnat_equiv_nat,
map_rel_iff' := Ξ» _ _, nat_pred_le_nat_pred }
@[simp] lemma _root_.order_iso.pnat_iso_nat_symm_apply :
βorder_iso.pnat_iso_nat.symm = nat.succ_pnat := rfl
@[priority 10]
instance : covariant_class β+ β+ ((+)) (β€) :=
β¨by { rintro β¨a, haβ© β¨b, hbβ© β¨c, hcβ©, simp [βpnat.coe_le_coe] }β©
@[simp] theorem ne_zero (n : β+) : (n : β) β 0 := n.2.ne'
theorem to_pnat'_coe {n : β} : 0 < n β (n.to_pnat' : β) = n := succ_pred_eq_of_pos
@[simp] theorem coe_to_pnat' (n : β+) : (n : β).to_pnat' = n := eq (to_pnat'_coe n.pos)
instance : has_mul β+ := β¨Ξ» m n, β¨m.1 * n.1, mul_pos m.2 n.2β©β©
instance : has_one β+ := β¨succ_pnat 0β©
instance : has_pow β+ β := β¨Ξ» x n, β¨x ^ n, pow_pos x.2 nβ©β©
instance : comm_monoid β+ := coe_injective.comm_monoid coe rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl)
theorem lt_add_one_iff : β {a b : β+}, a < b + 1 β a β€ b :=
Ξ» a b, nat.lt_add_one_iff
theorem add_one_le_iff : β {a b : β+}, a + 1 β€ b β a < b :=
Ξ» a b, nat.add_one_le_iff
@[simp] lemma one_le (n : β+) : (1 : β+) β€ n := n.2
@[simp] lemma not_lt_one (n : β+) : Β¬ n < 1 := not_lt_of_le n.one_le
instance : order_bot β+ :=
{ bot := 1,
bot_le := Ξ» a, a.property }
@[simp] lemma bot_eq_one : (β₯ : β+) = 1 := rfl
instance : inhabited β+ := β¨1β©
-- Some lemmas that rewrite `pnat.mk n h`, for `n` an explicit numeral, into explicit numerals.
@[simp] lemma mk_one {h} : (β¨1, hβ© : β+) = (1 : β+) := rfl
@[simp] lemma mk_bit0 (n) {h} : (β¨bit0 n, hβ© : β+) = (bit0 β¨n, pos_of_bit0_pos hβ© : β+) := rfl
@[simp] lemma mk_bit1 (n) {h} {k} : (β¨bit1 n, hβ© : β+) = (bit1 β¨n, kβ© : β+) := rfl
-- Some lemmas that rewrite inequalities between explicit numerals in `β+`
-- into the corresponding inequalities in `β`.
-- TODO: perhaps this should not be attempted by `simp`,
-- and instead we should expect `norm_num` to take care of these directly?
-- TODO: these lemmas are perhaps incomplete:
-- * 1 is not represented as a bit0 or bit1
-- * strict inequalities?
@[simp] lemma bit0_le_bit0 (n m : β+) : (bit0 n) β€ (bit0 m) β (bit0 (n : β)) β€ (bit0 (m : β)) :=
iff.rfl
@[simp] lemma bit0_le_bit1 (n m : β+) : (bit0 n) β€ (bit1 m) β (bit0 (n : β)) β€ (bit1 (m : β)) :=
iff.rfl
@[simp] lemma bit1_le_bit0 (n m : β+) : (bit1 n) β€ (bit0 m) β (bit1 (n : β)) β€ (bit0 (m : β)) :=
iff.rfl
@[simp] lemma bit1_le_bit1 (n m : β+) : (bit1 n) β€ (bit1 m) β (bit1 (n : β)) β€ (bit1 (m : β)) :=
iff.rfl
@[simp] theorem one_coe : ((1 : β+) : β) = 1 := rfl
@[simp] theorem mul_coe (m n : β+) : ((m * n : β+) : β) = m * n := rfl
/-- `pnat.coe` promoted to a `monoid_hom`. -/
def coe_monoid_hom : β+ β* β :=
{ to_fun := coe,
map_one' := one_coe,
map_mul' := mul_coe }
@[simp] lemma coe_coe_monoid_hom : (coe_monoid_hom : β+ β β) = coe := rfl
@[simp]
lemma coe_eq_one_iff {m : β+} : (m : β) = 1 β m = 1 := by rw [β one_coe, coe_inj]
@[simp] lemma le_one_iff {n : β+} : n β€ 1 β n = 1 := le_bot_iff
lemma lt_add_left (n m : β+) : n < m + n := lt_add_of_pos_left _ m.2
lemma lt_add_right (n m : β+) : n < n + m := (lt_add_left n m).trans_eq (add_comm _ _)
@[simp] lemma coe_bit0 (a : β+) : ((bit0 a : β+) : β) = bit0 (a : β) := rfl
@[simp] lemma coe_bit1 (a : β+) : ((bit1 a : β+) : β) = bit1 (a : β) := rfl
@[simp] theorem pow_coe (m : β+) (n : β) : ((m ^ n : β+) : β) = (m : β) ^ n :=
rfl
instance : ordered_cancel_comm_monoid β+ :=
{ mul_le_mul_left := by { intros, apply nat.mul_le_mul_left, assumption },
le_of_mul_le_mul_left := by { intros a b c h, apply nat.le_of_mul_le_mul_left h a.property, },
mul_left_cancel := Ξ» a b c h, by
{ replace h := congr_arg (coe : β+ β β) h,
exact eq ((nat.mul_right_inj a.pos).mp h)},
.. pnat.comm_monoid,
.. pnat.linear_order }
instance : distrib β+ := coe_injective.distrib coe (Ξ» _ _, rfl) (Ξ» _ _, rfl)
/-- Subtraction a - b is defined in the obvious way when
a > b, and by a - b = 1 if a β€ b.
-/
instance : has_sub β+ := β¨Ξ» a b, to_pnat' (a - b : β)β©
theorem sub_coe (a b : β+) : ((a - b : β+) : β) = ite (b < a) (a - b : β) 1 :=
begin
change (to_pnat' _ : β) = ite _ _ _,
split_ifs with h,
{ exact to_pnat'_coe (tsub_pos_of_lt h) },
{ rw tsub_eq_zero_iff_le.mpr (le_of_not_gt h : (a : β) β€ b), refl }
end
theorem add_sub_of_lt {a b : β+} : a < b β a + (b - a) = b :=
Ξ» h, eq $ by { rw [add_coe, sub_coe, if_pos h],
exact add_tsub_cancel_of_le h.le }
instance : has_well_founded β+ := β¨(<), measure_wf coeβ©
/-- Strong induction on `β+`. -/
def strong_induction_on {p : β+ β Sort*} : β (n : β+) (h : β k, (β m, m < k β p m) β p k), p n
| n := Ξ» IH, IH _ (Ξ» a h, strong_induction_on a IH)
using_well_founded { dec_tac := `[assumption] }
/-- If `n : β+` is different from `1`, then it is the successor of some `k : β+`. -/
lemma exists_eq_succ_of_ne_one : β {n : β+} (h1 : n β 1), β (k : β+), n = k + 1
| β¨1, _β© h1 := false.elim $ h1 rfl
| β¨n+2, _β© _ := β¨β¨n+1, by simpβ©, rflβ©
/-- Strong induction on `β+`, with `n = 1` treated separately. -/
def case_strong_induction_on {p : β+ β Sort*} (a : β+) (hz : p 1)
(hi : β n, (β m, m β€ n β p m) β p (n + 1)) : p a :=
begin
apply strong_induction_on a,
rintro β¨k, kpropβ© hk,
cases k with k,
{ exact (lt_irrefl 0 kprop).elim },
cases k with k,
{ exact hz },
exact hi β¨k.succ, nat.succ_pos _β© (Ξ» m hm, hk _ (lt_succ_iff.2 hm)),
end
/-- An induction principle for `β+`: it takes values in `Sort*`, so it applies also to Types,
not only to `Prop`. -/
@[elab_as_eliminator]
def rec_on (n : β+) {p : β+ β Sort*} (p1 : p 1) (hp : β n, p n β p (n + 1)) : p n :=
begin
rcases n with β¨n, hβ©,
induction n with n IH,
{ exact absurd h dec_trivial },
{ cases n with n,
{ exact p1 },
{ exact hp _ (IH n.succ_pos) } }
end
@[simp] theorem rec_on_one {p} (p1 hp) : @pnat.rec_on 1 p p1 hp = p1 := rfl
@[simp] theorem rec_on_succ (n : β+) {p : β+ β Sort*} (p1 hp) :
@pnat.rec_on (n + 1) p p1 hp = hp n (@pnat.rec_on n p p1 hp) :=
by { cases n with n h, cases n; [exact absurd h dec_trivial, refl] }
/-- We define `m % k` and `m / k` in the same way as for `β`
except that when `m = n * k` we take `m % k = k` and
`m / k = n - 1`. This ensures that `m % k` is always positive
and `m = (m % k) + k * (m / k)` in all cases. Later we
define a function `div_exact` which gives the usual `m / k`
in the case where `k` divides `m`.
-/
def mod_div_aux : β+ β β β β β β+ Γ β
| k 0 q := β¨k, q.predβ©
| k (r + 1) q := β¨β¨r + 1, nat.succ_pos rβ©, qβ©
lemma mod_div_aux_spec : β (k : β+) (r q : β) (h : Β¬ (r = 0 β§ q = 0)),
(((mod_div_aux k r q).1 : β) + k * (mod_div_aux k r q).2 = (r + k * q))
| k 0 0 h := (h β¨rfl, rflβ©).elim
| k 0 (q + 1) h := by
{ change (k : β) + (k : β) * (q + 1).pred = 0 + (k : β) * (q + 1),
rw [nat.pred_succ, nat.mul_succ, zero_add, add_comm]}
| k (r + 1) q h := rfl
/-- `mod_div m k = (m % k, m / k)`.
We define `m % k` and `m / k` in the same way as for `β`
except that when `m = n * k` we take `m % k = k` and
`m / k = n - 1`. This ensures that `m % k` is always positive
and `m = (m % k) + k * (m / k)` in all cases. Later we
define a function `div_exact` which gives the usual `m / k`
in the case where `k` divides `m`.
-/
def mod_div (m k : β+) : β+ Γ β := mod_div_aux k ((m : β) % (k : β)) ((m : β) / (k : β))
/-- We define `m % k` in the same way as for `β`
except that when `m = n * k` we take `m % k = k` This ensures that `m % k` is always positive.
-/
def mod (m k : β+) : β+ := (mod_div m k).1
/-- We define `m / k` in the same way as for `β` except that when `m = n * k` we take
`m / k = n - 1`. This ensures that `m = (m % k) + k * (m / k)` in all cases. Later we
define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`.
-/
def div (m k : β+) : β := (mod_div m k).2
theorem mod_add_div (m k : β+) : ((mod m k) + k * (div m k) : β) = m :=
begin
let hβ := nat.mod_add_div (m : β) (k : β),
have : Β¬ ((m : β) % (k : β) = 0 β§ (m : β) / (k : β) = 0),
by { rintro β¨hr, hqβ©, rw [hr, hq, mul_zero, zero_add] at hβ,
exact (m.ne_zero hβ.symm).elim },
have := mod_div_aux_spec k ((m : β) % (k : β)) ((m : β) / (k : β)) this,
exact (this.trans hβ),
end
theorem div_add_mod (m k : β+) : (k * (div m k) + mod m k : β) = m :=
(add_comm _ _).trans (mod_add_div _ _)
lemma mod_add_div' (m k : β+) : ((mod m k) + (div m k) * k : β) = m :=
by { rw mul_comm, exact mod_add_div _ _ }
lemma div_add_mod' (m k : β+) : ((div m k) * k + mod m k : β) = m :=
by { rw mul_comm, exact div_add_mod _ _ }
theorem mod_coe (m k : β+) :
((mod m k) : β) = ite ((m : β) % (k : β) = 0) (k : β) ((m : β) % (k : β)) :=
begin
dsimp [mod, mod_div],
cases (m : β) % (k : β),
{ rw [if_pos rfl], refl },
{ rw [if_neg n.succ_ne_zero], refl }
end
theorem div_coe (m k : β+) :
((div m k) : β) = ite ((m : β) % (k : β) = 0) ((m : β) / (k : β)).pred ((m : β) / (k : β)) :=
begin
dsimp [div, mod_div],
cases (m : β) % (k : β),
{ rw [if_pos rfl], refl },
{ rw [if_neg n.succ_ne_zero], refl }
end
theorem mod_le (m k : β+) : mod m k β€ m β§ mod m k β€ k :=
begin
change ((mod m k) : β) β€ (m : β) β§ ((mod m k) : β) β€ (k : β),
rw [mod_coe], split_ifs,
{ have hm : (m : β) > 0 := m.pos,
rw [β nat.mod_add_div (m : β) (k : β), h, zero_add] at hm β’,
by_cases h' : ((m : β) / (k : β)) = 0,
{ rw [h', mul_zero] at hm, exact (lt_irrefl _ hm).elim},
{ let h' := nat.mul_le_mul_left (k : β)
(nat.succ_le_of_lt (nat.pos_of_ne_zero h')),
rw [mul_one] at h', exact β¨h', le_refl (k : β)β© } },
{ exact β¨nat.mod_le (m : β) (k : β), (nat.mod_lt (m : β) k.pos).leβ© }
end
theorem dvd_iff {k m : β+} : k β£ m β (k : β) β£ (m : β) :=
begin
split; intro h, rcases h with β¨_, rflβ©, apply dvd_mul_right,
rcases h with β¨a, hβ©, cases a, { contrapose h, apply ne_zero, },
use a.succ, apply nat.succ_pos, rw [β coe_inj, h, mul_coe, mk_coe],
end
theorem dvd_iff' {k m : β+} : k β£ m β mod m k = k :=
begin
rw dvd_iff,
rw [nat.dvd_iff_mod_eq_zero], split,
{ intro h, apply eq, rw [mod_coe, if_pos h] },
{ intro h, by_cases h' : (m : β) % (k : β) = 0,
{ exact h'},
{ replace h : ((mod m k) : β) = (k : β) := congr_arg _ h,
rw [mod_coe, if_neg h'] at h,
exact ((nat.mod_lt (m : β) k.pos).ne h).elim } }
end
lemma le_of_dvd {m n : β+} : m β£ n β m β€ n :=
by { rw dvd_iff', intro h, rw β h, apply (mod_le n m).left }
/-- If `h : k | m`, then `k * (div_exact m k) = m`. Note that this is not equal to `m / k`. -/
def div_exact (m k : β+) : β+ :=
β¨(div m k).succ, nat.succ_pos _β©
theorem mul_div_exact {m k : β+} (h : k β£ m) : k * (div_exact m k) = m :=
begin
apply eq, rw [mul_coe],
change (k : β) * (div m k).succ = m,
rw [β div_add_mod m k, dvd_iff'.mp h, nat.mul_succ]
end
theorem dvd_antisymm {m n : β+} : m β£ n β n β£ m β m = n :=
Ξ» hmn hnm, (le_of_dvd hmn).antisymm (le_of_dvd hnm)
theorem dvd_one_iff (n : β+) : n β£ 1 β n = 1 :=
β¨Ξ» h, dvd_antisymm h (one_dvd n), Ξ» h, h.symm βΈ (dvd_refl 1)β©
lemma pos_of_div_pos {n : β+} {a : β} (h : a β£ n) : 0 < a :=
begin
apply pos_iff_ne_zero.2,
intro hzero,
rw hzero at h,
exact pnat.ne_zero n (eq_zero_of_zero_dvd h)
end
end pnat
section can_lift
instance nat.can_lift_pnat : can_lift β β+ :=
β¨coe, Ξ» n, 0 < n, Ξ» n hn, β¨nat.to_pnat' n, pnat.to_pnat'_coe hnβ©β©
instance int.can_lift_pnat : can_lift β€ β+ :=
β¨coe, Ξ» n, 0 < n, Ξ» n hn, β¨nat.to_pnat' (int.nat_abs n),
by rw [coe_coe, nat.to_pnat'_coe, if_pos (int.nat_abs_pos_of_ne_zero hn.ne'),
int.nat_abs_of_nonneg hn.le]β©β©
end can_lift
|
858c703e0aa7bf6d5831cd4f94c23203d3ea0caa | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/univ_vars.lean | 4ea3ba217af4304919ac5a006bf8af7df6f9b4f4 | [
"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 | 431 | lean | --
set_option pp.universes true
universe variable u
variable A : Type.{u}
definition id1 (a : A) : A := a
#check @id1
variable B : Type
definition id2 (a : B) : B := a
#check @id2
universe variable k
variable C : Type.{k}
definition id3 (a : C) := a
#check @id3
universe variables l m
variable Aβ : Type.{l}
variable Aβ : Type.{l}
definition foo (aβ : Aβ) (aβ : Aβ) := aβ == aβ
#check @foo
#check Type.{m}
|
6092304127cace281efe1d19497cc9bf0b20d0a3 | 5719a16e23dfc08cdea7a5bf035b81690f307965 | /stage0/src/Init/Lean/Meta/GeneralizeTelescope.lean | b3c5bccde1c0fdfe3dcd0b28cc5fb4a8f9591f24 | [
"Apache-2.0"
] | permissive | postmasters/lean4 | 488b03969a371e1507e1e8a4df9ebf63c7cbe7ac | f3976fc53a883ac7606fc59357d43f4b51016ca7 | refs/heads/master | 1,655,582,707,480 | 1,588,682,595,000 | 1,588,682,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,106 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.Meta.KAbstract
namespace Lean
namespace Meta
namespace GeneralizeTelescope
structure Entry :=
(expr : Expr)
(type : Expr)
(modified : Bool)
partial def updateTypes (e newE : Expr) : Array Entry β Nat β MetaM (Array Entry)
| entries, i =>
if h : i < entries.size then
let entry := entries.get β¨i, hβ©;
match entry with
| β¨_, type, _β© => do
typeAbst β kabstract type e;
if typeAbst.hasLooseBVars then do
let typeNew := typeAbst.instantiate1 newE;
let entries := entries.set β¨i, hβ© { type := typeNew, modified := true, .. entry };
updateTypes entries (i+1)
else
updateTypes entries (i+1)
else
pure entries
partial def generalizeTelescopeAux {Ξ±} (prefixForNewVars : Name) (k : Array Expr β MetaM Ξ±) : Array Entry β Nat β Nat β Array Expr β MetaM Ξ±
| entries, i, nextVarIdx, fvars =>
if h : i < entries.size then
let replace (e : Expr) (type : Expr) : MetaM Ξ± := do {
let userName := prefixForNewVars.appendIndexAfter nextVarIdx;
withLocalDecl userName type BinderInfo.default $ fun x => do
entries β updateTypes e x entries (i+1);
generalizeTelescopeAux entries (i+1) (nextVarIdx+1) (fvars.push x)
};
match entries.get β¨i, hβ© with
| β¨e@(Expr.fvar fvarId _), type, falseβ© => do
localDecl β getLocalDecl fvarId;
match localDecl with
| LocalDecl.cdecl _ _ _ _ _ => generalizeTelescopeAux entries (i+1) nextVarIdx (fvars.push e)
| LocalDecl.ldecl _ _ _ _ _ => replace e type
| β¨e, type, modifiedβ© => do
when modified $ unlessM (isTypeCorrect type) $
throwEx $ Exception.generalizeTelescope (entries.map Entry.expr);
replace e type
else
k fvars
end GeneralizeTelescope
open GeneralizeTelescope
/--
Given expressions `es := #[e_1, e_2, ..., e_n]`, execute `k` with the
free variables `(x_1 : A_1) (x_2 : A_2 [x_1]) ... (x_n : A_n [x_1, ... x_{n-1}])`.
Moreover,
- type of `e_1` is definitionally equal to `A_1`,
- type of `e_2` is definitionally equal to `A_2[e_1]`.
- ...
- type of `e_n` is definitionally equal to `A_n[e_1, ..., e_{n-1}]`.
This method tries to avoid the creation of new free variables. For example, if `e_i` is a
free variable `x_i` and it is not a let-declaration variable, and its type does not depend on
previous `e_j`s, the method will just use `x_i`.
The telescope `x_1 ... x_n` can be used to create lambda and forall abstractions.
Moreover, for any type correct lambda abstraction `f` constructed using `mkForall #[x_1, ..., x_n] ...`,
The application `f e_1 ... e_n` is also type correct.
The parameter `prefixForNewVars` is used to create new user facing names for the (new) variables `x_i`.
The `kabstract` method is used to "locate" and abstract forward dependencies.
That is, an occurrence of `e_i` in the of `e_j` for `j > i`.
The method checks whether the abstract types `A_i` are type correct. Here is an example
where `generalizeTelescope` fails to create the telescope `x_1 ... x_n`.
Assume the local context contains `(n : Nat := 10) (xs : Vec Nat n) (ys : Vec Nat 10) (h : xs = ys)`.
Then, assume we invoke `generalizeTelescope` with `es := #[10, xs, ys, h]` and `prefixForNewVars := aux`.
A type error is detected when processing `h`'s type. At this point, the method had successfully produced
```
(aux_1 : Nat) (xs : Vec Nat n) (aux_2 : Vec Nat aux_1)
```
and the type for the new variable abstracting `h` is `xs = aux_2` which is not type correct. -/
def generalizeTelescope {Ξ±} (es : Array Expr) (prefixForNewVars : Name) (k : Array Expr β MetaM Ξ±) : MetaM Ξ± := do
es β es.mapM $ fun e => do {
type β inferType e;
type β instantiateMVars type;
pure { Entry . expr := e, type := type, modified := false }
};
generalizeTelescopeAux prefixForNewVars k es 0 1 #[]
end Meta
end Lean
|
067fc1e12f01dc1228ad4912c8b2638327aff8df | 5df84495ec6c281df6d26411cc20aac5c941e745 | /src/formal_ml/exists_unique.lean | 2a18a256d3975456915904185e1813c3ede1d72d | [
"Apache-2.0"
] | permissive | eric-wieser/formal-ml | e278df5a8df78aa3947bc8376650419e1b2b0a14 | 630011d19fdd9539c8d6493a69fe70af5d193590 | refs/heads/master | 1,681,491,589,256 | 1,612,642,743,000 | 1,612,642,743,000 | 360,114,136 | 0 | 0 | Apache-2.0 | 1,618,998,189,000 | 1,618,998,188,000 | null | UTF-8 | Lean | false | false | 1,668 | lean | /-
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/
import tactic.simp_rw
namespace exists_unique
@[simp]
lemma proof_iff {P Q:Prop}:
(β! (H:P), Q) β (P β§ Q) :=
begin
split;intros h,
have h_exists := exists_of_exists_unique h,
cases h_exists with hP hQ,
apply and.intro hP hQ,
cases h with hP hQ,
apply exists_unique.intro hP hQ,
intros hP' hQ',
refl,
end
@[simp]
lemma in_set_iff {Ξ±:Type*} {s:set Ξ±}
{P:Ξ± β Prop}:
(β! aβs, P a) β (β! a, aβs β§ P a) :=
begin
simp_rw [exists_unique.proof_iff],
end
/--Technically, `β! (bβs), P s` reads "there exists a unique b such that
there exists a unique proof of `(bβs)` such that `P s`."
A more natural interpretation is there exists a unique b such that
bβs and P s. This performs the translation. -/
lemma intro_set {Ξ±:Type*} {s:set Ξ±}
{P:Ξ± β Prop} (a : Ξ±) (h : aβ s) (hPa : P a) (h_unique: β bβ s, P b β b = a):
β! cβs, P c :=
begin
rw exists_unique.in_set_iff,
apply exists_unique.intro a (and.intro h hPa),
intros y hy_in_s_and_Py,
apply h_unique y hy_in_s_and_Py.left hy_in_s_and_Py.right,
end
end exists_unique
|
cb327b2b7bc93c82ed55914f375efbd7130b939e | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/tactic/squeeze.lean | 257500584d94c64e6c426b75e7042564b169658d | [
"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 | 4,274 | lean | /-
Copyright (c) 2019 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Simon Hudon
-/
import category.traversable.basic
import tactic.simpa
open interactive interactive.types lean.parser
meta def loc.to_string_aux : option name β string
| none := "β’"
| (some x) := to_string x
meta def loc.to_string : loc β string
| (loc.ns []) := ""
| (loc.ns [none]) := ""
| (loc.ns ls) := string.join $ list.intersperse " " (" at" :: ls.map loc.to_string_aux)
| loc.wildcard := " at *"
namespace tactic
namespace interactive
meta def erase_simp_arg (s : name_set) : simp_arg_type β name_set
| simp_arg_type.all_hyps := s
| (simp_arg_type.except a) := s
| (simp_arg_type.expr e) :=
match e.get_app_fn e with
| (expr.const n _) := s.erase n
| _ := s
end
meta def arg.to_tactic_format : simp_arg_type β tactic format
| (simp_arg_type.expr e) := i_to_expr_no_subgoals e >>= pp
| simp_arg_type.all_hyps := pure "*"
| (simp_arg_type.except n) := pure format!"-{n}"
open list
meta def record_lit : lean.parser pexpr :=
do tk "{",
ls β sep_by (skip_info (tk ","))
( sum.inl <$> (tk ".." *> texpr) <|>
sum.inr <$> (prod.mk <$> ident <* tk ":=" <*> texpr)),
tk "}",
let (srcs,fields) := partition_map id ls,
let (names,values) := unzip fields,
pure $ pexpr.mk_structure_instance
{ field_names := names,
field_values := values,
sources := srcs }
meta def rec.to_tactic_format (e : pexpr) : tactic format :=
do r β e.get_structure_instance_info,
fs β mzip_with (Ξ» n v,
do v β to_expr v >>= pp,
pure $ format!"{n} := {v}" )
r.field_names r.field_values,
let ss := r.sources.map (Ξ» s, format!" .. {s}"),
let x : format := format.join $ list.intersperse ", " (fs ++ ss),
pure format!" {{{x}}"
local postfix `?`:9001 := optional
meta def parse_config : option pexpr β tactic (simp_config_ext Γ format)
| none := pure ({}, "")
| (some cfg) :=
do e β to_expr ``(%%cfg : simp_config_ext),
fmt β has_to_tactic_format.to_tactic_format cfg,
prod.mk <$> eval_expr simp_config_ext e
<*> rec.to_tactic_format cfg
meta def auto_simp_lemma := [``eq_self_iff_true]
meta def squeeze_simp
(use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)
(attr_names : parse with_ident_list) (locat : parse location)
(cfg : parse record_lit?) : tactic unit :=
do g β main_goal,
(cfg',c) β parse_config cfg,
hs' β hs.mmap arg.to_tactic_format,
simp use_iota_eqn no_dflt hs attr_names locat cfg',
g β instantiate_mvars g,
let vs := g.list_constant,
vs β vs.mfilter (succeeds β has_attribute `simp) >>= name_set.mmap strip_prefix,
let vs := auto_simp_lemma.foldl name_set.erase vs,
let vs := hs.foldl erase_simp_arg vs,
let use_iota_eqn := if use_iota_eqn.is_some then "!" else "",
let attrs := if attr_names.empty then "" else string.join (list.intersperse " " (" with" :: attr_names.map to_string)),
let loc := loc.to_string locat,
let args := hs' ++ vs.to_list.map to_fmt,
trace format!"simp{use_iota_eqn} only {args}{attrs}{loc}{c}"
meta def squeeze_simpa
(use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)
(attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?)
(cfg : parse record_lit?) : tactic unit :=
do g β main_goal,
(cfg',c) β parse_config cfg,
tgt' β traverse (Ξ» t, do t β to_expr t >>= pp,
pure format!" using {t}") tgt,
simpa use_iota_eqn no_dflt hs attr_names tgt cfg',
g β instantiate_mvars g,
let vs := g.list_constant,
vs β vs.mfilter (succeeds β has_attribute `simp) >>= name_set.mmap strip_prefix,
let vs := auto_simp_lemma.foldl name_set.erase vs,
let vs := hs.foldl erase_simp_arg vs,
let use_iota_eqn := if use_iota_eqn.is_some then "!" else "",
let attrs := if attr_names.empty then "" else string.join (list.intersperse " " (" with" :: attr_names.map to_string)),
let tgt' := tgt'.get_or_else "",
hs β hs.mmap arg.to_tactic_format,
let args := hs ++ vs.to_list.map to_fmt,
trace format!"simpa{use_iota_eqn} only {args}{attrs}{tgt'}{c}"
end interactive
end tactic
|
937367f97dcc84a31db0c20ab8d62845fda7daa3 | 5412d79aa1dc0b521605c38bef9f0d4557b5a29d | /src/Lean/ProjFns.lean | a1a366a4d9e771d804a7ad87c1ca7922d574ac3c | [
"Apache-2.0"
] | permissive | smunix/lean4 | a450ec0927dc1c74816a1bf2818bf8600c9fc9bf | 3407202436c141e3243eafbecb4b8720599b970a | refs/heads/master | 1,676,334,875,188 | 1,610,128,510,000 | 1,610,128,521,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,373 | 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.Environment
namespace Lean
/- Given a structure `S`, Lean automatically creates an auxiliary definition (projection function)
for each field. This structure caches information about these auxiliary definitions. -/
structure ProjectionFunctionInfo where
ctorName : Name -- Constructor associated with the auxiliary projection function.
nparams : Nat -- Number of parameters in the structure
i : Nat -- The field index associated with the auxiliary projection function.
fromClass : Bool -- `true` if the structure is a class
@[export lean_mk_projection_info]
def mkProjectionInfoEx (ctorName : Name) (nparams : Nat) (i : Nat) (fromClass : Bool) : ProjectionFunctionInfo :=
{ctorName := ctorName, nparams := nparams, i := i, fromClass := fromClass }
@[export lean_projection_info_from_class]
def ProjectionFunctionInfo.fromClassEx (info : ProjectionFunctionInfo) : Bool := info.fromClass
instance : Inhabited ProjectionFunctionInfo :=
β¨{ ctorName := arbitrary, nparams := arbitrary, i := 0, fromClass := false }β©
builtin_initialize projectionFnInfoExt : SimplePersistentEnvExtension (Name Γ ProjectionFunctionInfo) (NameMap ProjectionFunctionInfo) β
registerSimplePersistentEnvExtension {
name := `projinfo,
addImportedFn := fun as => {},
addEntryFn := fun s p => s.insert p.1 p.2,
toArrayFn := fun es => es.toArray.qsort (fun a b => Name.quickLt a.1 b.1)
}
@[export lean_add_projection_info]
def addProjectionFnInfo (env : Environment) (projName : Name) (ctorName : Name) (nparams : Nat) (i : Nat) (fromClass : Bool) : Environment :=
projectionFnInfoExt.addEntry env (projName, { ctorName := ctorName, nparams := nparams, i := i, fromClass := fromClass })
namespace Environment
@[export lean_get_projection_info]
def getProjectionFnInfo? (env : Environment) (projName : Name) : Option ProjectionFunctionInfo :=
match env.getModuleIdxFor? projName with
| some modIdx =>
match (projectionFnInfoExt.getModuleEntries env modIdx).binSearch (projName, arbitrary) (fun a b => Name.quickLt a.1 b.1) with
| some e => some e.2
| none => none
| none => (projectionFnInfoExt.getState env).find? projName
def isProjectionFn (env : Environment) (n : Name) : Bool :=
match env.getModuleIdxFor? n with
| some modIdx => (projectionFnInfoExt.getModuleEntries env modIdx).binSearchContains (n, arbitrary) (fun a b => Name.quickLt a.1 b.1)
| none => (projectionFnInfoExt.getState env).contains n
/-- If `projName` is the name of a projection function, return the associated structure name -/
def getProjectionStructureName? (env : Environment) (projName : Name) : Option Name :=
match env.getProjectionFnInfo? projName with
| none => none
| some projInfo =>
match env.find? projInfo.ctorName with
| some (ConstantInfo.ctorInfo val) => some val.induct
| _ => none
end Environment
def isProjectionFn [MonadEnv m] [Monad m] (declName : Name) : m Bool :=
return (β getEnv).isProjectionFn declName
def getProjectionFnInfo? [MonadEnv m] [Monad m] (declName : Name) : m (Option ProjectionFunctionInfo) :=
return (β getEnv).getProjectionFnInfo? declName
end Lean
|
fee0d7e02f66ead743101a18c7be9b1a56cc1a14 | 2c2aac4ae1d23cd0d1f9bf0f8c04b05427d38103 | /test/library_search/basic.lean | 46e09b38ec2d54d9d6bee6feaf92e9984e415ce1 | [
"Apache-2.0"
] | permissive | egsgaard/mathlib | 3f733823fbc8d34f8e104bf6f5d2d55f150c774e | 8e8037f5ce6f1633dba7f8b284a92a6dc2941abc | refs/heads/master | 1,650,473,269,445 | 1,586,936,514,000 | 1,586,936,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,961 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import data.nat.basic
/- Turn off trace messages so they don't pollute the test build: -/
set_option trace.silence_library_search true
/- For debugging purposes, we can display the list of lemmas: -/
-- set_option trace.suggest true
namespace test.library_search
-- Check that `library_search` fails if there are no goals.
example : true :=
begin
trivial,
success_if_fail { library_search },
end
-- Verify that `library_search` solves goals via `solve_by_elim` when the library isn't
-- even needed.
example (P : Prop) (p : P) : P :=
by library_search
example (P : Prop) (p : P) (np : Β¬P) : false :=
by library_search
example (X : Type) (P : Prop) (x : X) (h : Ξ x : X, x = x β P) : P :=
by library_search
def lt_one (n : β) := n < 1
lemma zero_lt_one (n : β) (h : n = 0) : lt_one n := by subst h; dsimp [lt_one]; simp
-- Verify that calls to solve_by_elim to discharge subgoals use `rfl`
example : lt_one 0 :=
by library_search
example (Ξ± : Prop) : Ξ± β Ξ± :=
by library_search -- says: `exact id`
example (p : Prop) [decidable p] : (¬¬p) β p :=
by library_search -- says: `exact not_not.mp`
example (a b : Prop) (h : a β§ b) : a :=
by library_search -- says: `exact h.left`
example (P Q : Prop) [decidable P] [decidable Q]: (Β¬ Q β Β¬ P) β (P β Q) :=
by library_search -- says: `exact not_imp_not.mp`
example (a b : β) : a + b = b + a :=
by library_search -- says: `exact add_comm a b`
example {a b : β} : a β€ a + b :=
by library_search -- says: `exact nat.le.intro rfl`
example (n m k : β) : n * (m - k) = n * m - n * k :=
by library_search -- says: `exact nat.mul_sub_left_distrib n m k`
-- TODO this doesn't work yet, and would require `library_search` to use `symmetry`
-- example (n m k : β) : n * m - n * k = n * (m - k) :=
-- by library_search -- says: `exact eq.symm (nat.mul_sub_left_distrib n m k)`
example {n m : β} (h : m < n) : m β€ n - 1 :=
by library_search -- says: `exact nat.le_pred_of_lt h`
example {Ξ± : Type} (x y : Ξ±) : x = y β y = x :=
by library_search -- says: `exact eq_comm`
example (a b : β) (ha : 0 < a) (hb : 0 < b) : 0 < a + b :=
by library_search -- says: `exact add_pos ha hb`
example (a b : β) : 0 < a β 0 < b β 0 < a + b :=
by library_search -- says: `exact add_pos`
example (a b : β) (h : a β£ b) (w : b > 0) : a β€ b :=
by library_search -- says: `exact nat.le_of_dvd w h`
-- We even find `iff` results:
example : β P : Prop, Β¬(P β Β¬P) :=
by library_search -- says: `Ξ» (a : Prop), (iff_not_self a).mp`
example {a b c : β} (ha : a > 0) (w : b β£ c) : a * b β£ a * c :=
by library_search -- exact mul_dvd_mul_left a w
example {a b c : β} (hβ : a β£ c) (hβ : a β£ b + c) : a β£ b :=
by library_search -- says `exact (nat.dvd_add_left hβ).mp hβ`
end test.library_search
|
6bf58fc004130ed5098dad6edf3c21cf7e84509b | bdb33f8b7ea65f7705fc342a178508e2722eb851 | /analysis/limits.lean | 6aefb10d80d4e4b402f89b0083ab62090ff5bbc5 | [
"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 | 8,019 | 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
A collection of limit properties.
-/
import algebra.big_operators algebra.group_power
analysis.real analysis.topology.infinite_sum
noncomputable theory
open classical set finset function filter
local attribute [instance] prop_decidable
section real
lemma has_sum_of_absolute_convergence {f : β β β}
(hf : βr, tendsto (Ξ»n, (range n).sum (Ξ»i, abs (f i))) at_top (nhds r)) : has_sum f :=
let f' := Ξ»s:finset β, s.sum (Ξ»i, abs (f i)) in
suffices cauchy (map (Ξ»s:finset β, s.sum f) at_top),
from complete_space.complete this,
cauchy_iff.mpr $ and.intro (map_ne_bot at_top_ne_bot) $
assume s hs,
let β¨Ξ΅, hΞ΅, hsΞ΅β© := mem_uniformity_dist.mp hs, β¨r, hrβ© := hf in
have hΞ΅' : {p : β Γ β | dist p.1 p.2 < Ξ΅ / 2} β (@uniformity β _).sets,
from mem_uniformity_dist.mpr β¨Ξ΅ / 2, div_pos_of_pos_of_pos hΞ΅ two_pos, assume a b h, hβ©,
have cauchy (at_top.map $ Ξ»n, f' (range n)),
from cauchy_downwards cauchy_nhds (map_ne_bot at_top_ne_bot) hr,
have βn, β{n'}, n β€ n' β dist (f' (range n)) (f' (range n')) < Ξ΅ / 2,
by simp [cauchy_iff, mem_at_top_sets] at this;
from let β¨t, β¨u, huβ©, htβ© := this _ hΞ΅' in
β¨u, assume n' hn, ht $ prod_mk_mem_set_prod_eq.mpr β¨hu _ (le_refl _), hu _ hnβ©β©,
let β¨n, hnβ© := this in
have β{s}, range n β s β abs ((s \ range n).sum f) < Ξ΅ / 2,
from assume s hs,
let β¨n', hn'β© := @exists_nat_subset_range s in
have range n β range n', from finset.subset.trans hs hn',
have f'_nn : 0 β€ f' (range n' \ range n), from zero_le_sum $ assume _ _, abs_nonneg _,
calc abs ((s \ range n).sum f) β€ f' (s \ range n) : abs_sum_le_sum_abs
... β€ f' (range n' \ range n) : sum_le_sum_of_subset_of_nonneg
(finset.sdiff_subset_sdiff hn' (finset.subset.refl _))
(assume _ _ _, abs_nonneg _)
... = abs (f' (range n' \ range n)) : (abs_of_nonneg f'_nn).symm
... = abs (f' (range n') - f' (range n)) :
by simp [f', (sum_sdiff βΉrange n β range n'βΊ).symm]
... = abs (f' (range n) - f' (range n')) : abs_sub _ _
... < Ξ΅ / 2 : hn $ range_subset.mp this,
have β{s t}, range n β s β range n β t β dist (s.sum f) (t.sum f) < Ξ΅,
from assume s t hs ht,
calc abs (s.sum f - t.sum f) = abs ((s \ range n).sum f + - (t \ range n).sum f) :
by rw [βsum_sdiff hs, βsum_sdiff ht]; simp
... β€ abs ((s \ range n).sum f) + abs ((t \ range n).sum f) :
le_trans (abs_add_le_abs_add_abs _ _) $ by rw [abs_neg]; exact le_refl _
... < Ξ΅ / 2 + Ξ΅ / 2 : add_lt_add (this hs) (this ht)
... = Ξ΅ : by rw [βadd_div, add_self_div_two],
β¨(Ξ»s:finset β, s.sum f) '' {s | range n β s}, image_mem_map $ mem_at_top (range n),
assume β¨a, bβ© β¨β¨t, ht, haβ©, β¨s, hs, hbβ©β©, by simp at ha hb; exact ha βΈ hb βΈ hsΞ΅ (this ht hs)β©
lemma is_sum_iff_tendsto_nat_of_nonneg {f : β β β} {r : β} (hf : βn, 0 β€ f n) :
is_sum f r β tendsto (Ξ»n, (range n).sum f) at_top (nhds r) :=
β¨tendsto_sum_nat_of_is_sum,
assume hr,
have tendsto (Ξ»n, (range n).sum (Ξ»n, abs (f n))) at_top (nhds r),
by simp [(Ξ»i, abs_of_nonneg (hf i)), hr],
let β¨p, hβ© := has_sum_of_absolute_convergence β¨r, thisβ© in
have hp : tendsto (Ξ»n, (range n).sum f) at_top (nhds p), from tendsto_sum_nat_of_is_sum h,
have p = r, from tendsto_nhds_unique at_top_ne_bot hp hr,
this βΈ hβ©
end real
lemma mul_add_one_le_pow {r : β} (hr : 0 β€ r) : β{n:β}, (n:β) * r + 1 β€ (r + 1) ^ n
| 0 := by simp; exact le_refl 1
| (n + 1) :=
let h : (n:β) β₯ 0 := nat.cast_nonneg n in
calc β(n + 1) * r + 1 β€ ((n + 1) * r + 1) + r * r * n :
le_add_of_le_of_nonneg (le_refl _) (mul_nonneg (mul_nonneg hr hr) h)
... = (r + 1) * (n * r + 1) : by simp [mul_add, add_mul, mul_comm, mul_assoc]
... β€ (r + 1) * (r + 1) ^ n : mul_le_mul (le_refl _) mul_add_one_le_pow
(add_nonneg (mul_nonneg h hr) zero_le_one) (add_nonneg hr zero_le_one)
lemma tendsto_pow_at_top_at_top_of_gt_1 {r : β} (h : r > 1) : tendsto (Ξ»n:β, r ^ n) at_top at_top :=
tendsto_infi.2 $ assume p, tendsto_principal.2 $
let β¨n, hnβ© := exists_nat_gt (p / (r - 1)) in
have hn_nn : (0:β) β€ n, from nat.cast_nonneg n,
have r - 1 > 0, from sub_lt_iff_lt_add.mp $ by simp; assumption,
have p β€ r ^ n,
from calc p = (p / (r - 1)) * (r - 1) : (div_mul_cancel _ $ ne_of_gt this).symm
... β€ n * (r - 1) : mul_le_mul (le_of_lt hn) (le_refl _) (le_of_lt this) hn_nn
... β€ n * (r - 1) + 1 : le_add_of_le_of_nonneg (le_refl _) zero_le_one
... β€ ((r - 1) + 1) ^ n : mul_add_one_le_pow $ le_of_lt this
... β€ r ^ n : by simp; exact le_refl _,
show {n | p β€ r ^ n} β at_top.sets,
from mem_at_top_sets.mpr β¨n, assume m hnm, le_trans this (pow_le_pow (le_of_lt h) hnm)β©
lemma tendsto_inverse_at_top_nhds_0 : tendsto (Ξ»r:β, rβ»ΒΉ) at_top (nhds 0) :=
tendsto_orderable_unbounded (no_top 0) (no_bot 0) $ assume l u hl hu,
mem_at_top_sets.mpr β¨uβ»ΒΉ + 1, assume b hb,
have uβ»ΒΉ < b, from lt_of_lt_of_le (lt_add_of_pos_right _ zero_lt_one) hb,
β¨lt_trans hl $ inv_pos $ lt_trans (inv_pos hu) this,
lt_of_one_div_lt_one_div hu $
begin
rw [inv_eq_one_div],
simp [-one_div_eq_inv, div_div_eq_mul_div, div_one],
simp [this]
endβ©β©
lemma map_succ_at_top_eq : map nat.succ at_top = at_top :=
le_antisymm
(assume s hs,
let β¨b, hbβ© := mem_at_top_sets.mp hs in
mem_at_top_sets.mpr β¨b, assume c hc, hb (c + 1) $ le_trans hc $ nat.le_succ _β©)
(assume s hs,
let β¨b, hbβ© := mem_at_top_sets.mp hs in
mem_at_top_sets.mpr β¨b + 1, assume c,
match c with
| 0 := assume h,
have 0 > 0, from lt_of_lt_of_le (lt_add_of_le_of_pos (nat.zero_le _) zero_lt_one) h,
(lt_irrefl 0 this).elim
| (c+1) := assume h, hb _ (nat.le_of_succ_le_succ h)
endβ©)
lemma tendsto_comp_succ_at_top_iff {Ξ± : Type*} {f : β β Ξ±} {x : filter Ξ±} :
tendsto (Ξ»n, f (nat.succ n)) at_top x β tendsto f at_top x :=
calc tendsto (f β nat.succ) at_top x β tendsto f (map nat.succ at_top) x : by simp [tendsto, map_map]
... β _ : by rw [map_succ_at_top_eq]
lemma tendsto_pow_at_top_nhds_0_of_lt_1 {r : β} (hβ : 0 β€ r) (hβ : r < 1) :
tendsto (Ξ»n:β, r^n) at_top (nhds 0) :=
by_cases
(assume : r = 0, tendsto_comp_succ_at_top_iff.mp $ by simp [pow_succ, this, tendsto_const_nhds])
(assume : r β 0,
have tendsto (Ξ»n, (rβ»ΒΉ ^ n)β»ΒΉ) at_top (nhds 0),
from (tendsto_pow_at_top_at_top_of_gt_1 $ one_lt_inv (lt_of_le_of_ne hβ this.symm) hβ).comp
tendsto_inverse_at_top_nhds_0,
tendsto_cong this $ univ_mem_sets' $ by simp *)
lemma sum_geometric' {r : β} (h : r β 0) :
β{n}, (finset.range n).sum (Ξ»i, (r + 1) ^ i) = ((r + 1) ^ n - 1) / r
| 0 := by simp [zero_div]
| (n+1) :=
by simp [@sum_geometric' n, h, pow_succ, add_div_eq_mul_add_div, add_mul, mul_comm, mul_assoc]
lemma sum_geometric {r : β} {n : β} (h : r β 1) :
(range n).sum (Ξ»i, r ^ i) = (r ^ n - 1) / (r - 1) :=
calc (range n).sum (Ξ»i, r ^ i) = (range n).sum (Ξ»i, ((r - 1) + 1) ^ i) :
by simp
... = (((r - 1) + 1) ^ n - 1) / (r - 1) :
sum_geometric' $ by simp [sub_eq_iff_eq_add, -sub_eq_add_neg, h]
... = (r ^ n - 1) / (r - 1) :
by simp
lemma is_sum_geometric {r : β} (hβ : 0 β€ r) (hβ : r < 1) :
is_sum (Ξ»n:β, r ^ n) (1 / (1 - r)) :=
have r β 1, from ne_of_lt hβ,
have r + -1 β 0,
by rw [βsub_eq_add_neg, ne, sub_eq_iff_eq_add]; simp; assumption,
have tendsto (Ξ»n, (r ^ n - 1) * (r - 1)β»ΒΉ) at_top (nhds ((0 - 1) * (r - 1)β»ΒΉ)),
from tendsto_mul
(tendsto_sub (tendsto_pow_at_top_nhds_0_of_lt_1 hβ hβ) tendsto_const_nhds) tendsto_const_nhds,
(is_sum_iff_tendsto_nat_of_nonneg $ pow_nonneg hβ).mpr $
by simp [neg_inv, sum_geometric, div_eq_mul_inv, *] at *
|
8e49ad2b6052afc72b0572e8558ad35d25e93883 | 5fbbd711f9bfc21ee168f46a4be146603ece8835 | /lean/natural_number_game/advanced_addition/05.lean | e631975d4f9b408453688c576af302bca8e55e08 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | goedel-gang/maths | 22596f71e3fde9c088e59931f128a3b5efb73a2c | a20a6f6a8ce800427afd595c598a5ad43da1408d | refs/heads/master | 1,623,055,941,960 | 1,621,599,441,000 | 1,621,599,441,000 | 169,335,840 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 167 | lean | theorem add_right_cancel (a t b : mynat) : a + t = b + t β a = b :=
begin
induction t with n hn,
simp,
repeat {rw add_succ},
rw succ_eq_succ_iff,
cc,
end
|
933113948b2a56ce6561171c5b1e8dfd7af68f6b | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/group_theory/group_action/sub_mul_action.lean | 30e466ad411cd8b874615bb0dce8443c1ac5eaa6 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 9,704 | lean | /-
Copyright (c) 2020 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import algebra.hom.group_action
import algebra.module.basic
import data.set_like.basic
import group_theory.group_action.basic
/-!
# Sets invariant to a `mul_action`
In this file we define `sub_mul_action R M`; a subset of a `mul_action R M` which is closed with
respect to scalar multiplication.
For most uses, typically `submodule R M` is more powerful.
## Main definitions
* `sub_mul_action.mul_action` - the `mul_action R M` transferred to the subtype.
* `sub_mul_action.mul_action'` - the `mul_action S M` transferred to the subtype when
`is_scalar_tower S R M`.
* `sub_mul_action.is_scalar_tower` - the `is_scalar_tower S R M` transferred to the subtype.
## Tags
submodule, mul_action
-/
open function
universes u u' u'' v
variables {S : Type u'} {T : Type u''} {R : Type u} {M : Type v}
set_option old_structure_cmd true
/-- `smul_mem_class S R M` says `S` is a type of subsets `s β€ M` that are closed under the
scalar action of `R` on `M`. -/
class smul_mem_class (S : Type*) (R M : out_param $ Type*) [has_smul R M] [set_like S M] :=
(smul_mem : β {s : S} (r : R) {m : M}, m β s β r β’ m β s)
/-- `vadd_mem_class S R M` says `S` is a type of subsets `s β€ M` that are closed under the
additive action of `R` on `M`. -/
class vadd_mem_class (S : Type*) (R M : out_param $ Type*) [has_vadd R M] [set_like S M] :=
(vadd_mem : β {s : S} (r : R) {m : M}, m β s β r +α΅₯ m β s)
attribute [to_additive] smul_mem_class
namespace set_like
variables [has_smul R M] [set_like S M] [hS : smul_mem_class S R M] (s : S)
include hS
open smul_mem_class
/-- A subset closed under the scalar action inherits that action. -/
@[to_additive "A subset closed under the additive action inherits that action.",
priority 900] -- lower priority so other instances are found first
instance has_smul : has_smul R s := β¨Ξ» r x, β¨r β’ x.1, smul_mem r x.2β©β©
@[simp, norm_cast, to_additive, priority 900]
-- lower priority so later simp lemmas are used first; to appease simp_nf
protected lemma coe_smul (r : R) (x : s) : (β(r β’ x) : M) = r β’ x := rfl
@[simp, to_additive, priority 900]
-- lower priority so later simp lemmas are used first; to appease simp_nf
lemma mk_smul_mk (r : R) (x : M) (hx : x β s) :
r β’ (β¨x, hxβ© : s) = β¨r β’ x, smul_mem r hxβ© := rfl
@[to_additive] lemma smul_def (r : R) (x : s) : r β’ x = β¨r β’ x, smul_mem r x.2β© := rfl
end set_like
/-- A sub_mul_action is a set which is closed under scalar multiplication. -/
structure sub_mul_action (R : Type u) (M : Type v) [has_smul R M] : Type v :=
(carrier : set M)
(smul_mem' : β (c : R) {x : M}, x β carrier β c β’ x β carrier)
namespace sub_mul_action
variables [has_smul R M]
instance : set_like (sub_mul_action R M) M :=
β¨sub_mul_action.carrier, Ξ» p q h, by cases p; cases q; congr'β©
instance : smul_mem_class (sub_mul_action R M) R M :=
{ smul_mem := smul_mem' }
@[simp] lemma mem_carrier {p : sub_mul_action R M} {x : M} : x β p.carrier β x β (p : set M) :=
iff.rfl
@[ext] theorem ext {p q : sub_mul_action R M} (h : β x, x β p β x β q) : p = q := set_like.ext h
/-- Copy of a sub_mul_action with a new `carrier` equal to the old one. Useful to fix definitional
equalities.-/
protected def copy (p : sub_mul_action R M) (s : set M) (hs : s = βp) : sub_mul_action R M :=
{ carrier := s,
smul_mem' := hs.symm βΈ p.smul_mem' }
@[simp] lemma coe_copy (p : sub_mul_action R M) (s : set M) (hs : s = βp) :
(p.copy s hs : set M) = s := rfl
lemma copy_eq (p : sub_mul_action R M) (s : set M) (hs : s = βp) : p.copy s hs = p :=
set_like.coe_injective hs
instance : has_bot (sub_mul_action R M) :=
β¨{ carrier := β
, smul_mem' := Ξ» c, set.not_mem_empty}β©
instance : inhabited (sub_mul_action R M) := β¨β₯β©
end sub_mul_action
namespace sub_mul_action
section has_smul
variables [has_smul R M]
variables (p : sub_mul_action R M)
variables {r : R} {x : M}
lemma smul_mem (r : R) (h : x β p) : r β’ x β p := p.smul_mem' r h
instance : has_smul R p :=
{ smul := Ξ» c x, β¨c β’ x.1, smul_mem _ c x.2β© }
variables {p}
@[simp, norm_cast] lemma coe_smul (r : R) (x : p) : ((r β’ x : p) : M) = r β’ βx := rfl
@[simp, norm_cast] lemma coe_mk (x : M) (hx : x β p) : ((β¨x, hxβ© : p) : M) = x := rfl
variables (p)
/-- Embedding of a submodule `p` to the ambient space `M`. -/
protected def subtype : p β[R] M :=
by refine {to_fun := coe, ..}; simp [coe_smul]
@[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl
lemma subtype_eq_val : ((sub_mul_action.subtype p) : p β M) = subtype.val := rfl
end has_smul
namespace smul_mem_class
variables [monoid R] [mul_action R M] {A : Type*} [set_like A M]
variables [hA : smul_mem_class A R M] (S' : A)
include hA
/-- A `sub_mul_action` of a `mul_action` is a `mul_action`. -/
@[priority 75] -- Prefer subclasses of `mul_action` over `smul_mem_class`.
instance to_mul_action : mul_action R S' :=
subtype.coe_injective.mul_action coe (set_like.coe_smul S')
/-- The natural `mul_action_hom` over `R` from a `sub_mul_action` of `M` to `M`. -/
protected def subtype : S' β[R] M := β¨coe, Ξ» _ _, rflβ©
@[simp] protected theorem coe_subtype : (smul_mem_class.subtype S' : S' β M) = coe := rfl
end smul_mem_class
section mul_action_monoid
variables [monoid R] [mul_action R M]
section
variables [has_smul S R] [has_smul S M] [is_scalar_tower S R M]
variables (p : sub_mul_action R M)
lemma smul_of_tower_mem (s : S) {x : M} (h : x β p) : s β’ x β p :=
by { rw [βone_smul R x, βsmul_assoc], exact p.smul_mem _ h }
instance has_smul' : has_smul S p :=
{ smul := Ξ» c x, β¨c β’ x.1, smul_of_tower_mem _ c x.2β© }
instance : is_scalar_tower S R p :=
{ smul_assoc := Ξ» s r x, subtype.ext $ smul_assoc s r βx }
instance is_scalar_tower' {S' : Type*} [has_smul S' R] [has_smul S' S]
[has_smul S' M] [is_scalar_tower S' R M] [is_scalar_tower S' S M] :
is_scalar_tower S' S p :=
{ smul_assoc := Ξ» s r x, subtype.ext $ smul_assoc s r βx }
@[simp, norm_cast] lemma coe_smul_of_tower (s : S) (x : p) : ((s β’ x : p) : M) = s β’ βx := rfl
@[simp] lemma smul_mem_iff' {G} [group G] [has_smul G R] [mul_action G M]
[is_scalar_tower G R M] (g : G) {x : M} :
g β’ x β p β x β p :=
β¨Ξ» h, inv_smul_smul g x βΈ p.smul_of_tower_mem gβ»ΒΉ h, p.smul_of_tower_mem gβ©
instance [has_smul Sα΅α΅α΅ R] [has_smul Sα΅α΅α΅ M] [is_scalar_tower Sα΅α΅α΅ R M]
[is_central_scalar S M] : is_central_scalar S p :=
{ op_smul_eq_smul := Ξ» r x, subtype.ext $ op_smul_eq_smul r x }
end
section
variables [monoid S] [has_smul S R] [mul_action S M] [is_scalar_tower S R M]
variables (p : sub_mul_action R M)
/-- If the scalar product forms a `mul_action`, then the subset inherits this action -/
instance mul_action' : mul_action S p :=
{ smul := (β’),
one_smul := Ξ» x, subtype.ext $ one_smul _ x,
mul_smul := Ξ» cβ cβ x, subtype.ext $ mul_smul cβ cβ x }
instance : mul_action R p := p.mul_action'
end
/-- Orbits in a `sub_mul_action` coincide with orbits in the ambient space. -/
lemma coe_image_orbit {p : sub_mul_action R M} (m : p) :
coe '' mul_action.orbit R m = mul_action.orbit R (m : M) := (set.range_comp _ _).symm
/- -- Previously, the relatively useless :
lemma orbit_of_sub_mul {p : sub_mul_action R M} (m : p) :
(mul_action.orbit R m : set M) = mul_action.orbit R (m : M) := rfl
-/
/-- Stabilizers in monoid sub_mul_action coincide with stabilizers in the ambient space -/
lemma stabilizer_of_sub_mul.submonoid {p : sub_mul_action R M} (m : p) :
mul_action.stabilizer.submonoid R m = mul_action.stabilizer.submonoid R (m : M) :=
begin
ext,
simp only [mul_action.mem_stabilizer_submonoid_iff,
β sub_mul_action.coe_smul, set_like.coe_eq_coe]
end
end mul_action_monoid
section mul_action_group
variables [group R] [mul_action R M]
/-- Stabilizers in group sub_mul_action coincide with stabilizers in the ambient space -/
lemma stabilizer_of_sub_mul {p : sub_mul_action R M} (m : p) :
mul_action.stabilizer R m = mul_action.stabilizer R (m : M) :=
begin
rw β subgroup.to_submonoid_eq,
exact stabilizer_of_sub_mul.submonoid m,
end
end mul_action_group
section module
variables [semiring R] [add_comm_monoid M]
variables [module R M]
variables (p : sub_mul_action R M)
lemma zero_mem (h : (p : set M).nonempty) : (0 : M) β p :=
let β¨x, hxβ© := h in zero_smul R (x : M) βΈ p.smul_mem 0 hx
/-- If the scalar product forms a `module`, and the `sub_mul_action` is not `β₯`, then the
subset inherits the zero. -/
instance [n_empty : nonempty p] : has_zero p :=
{ zero := β¨0, n_empty.elim $ Ξ» x, p.zero_mem β¨x, x.propβ©β© }
end module
section add_comm_group
variables [ring R] [add_comm_group M]
variables [module R M]
variables (p p' : sub_mul_action R M)
variables {r : R} {x y : M}
lemma neg_mem (hx : x β p) : -x β p := by { rw β neg_one_smul R, exact p.smul_mem _ hx }
@[simp] lemma neg_mem_iff : -x β p β x β p :=
β¨Ξ» h, by { rw βneg_neg x, exact neg_mem _ h}, neg_mem _β©
instance : has_neg p := β¨Ξ»x, β¨-x.1, neg_mem _ x.2β©β©
@[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl
end add_comm_group
end sub_mul_action
namespace sub_mul_action
variables [group_with_zero S] [monoid R] [mul_action R M]
variables [has_smul S R] [mul_action S M] [is_scalar_tower S R M]
variables (p : sub_mul_action R M) {s : S} {x y : M}
theorem smul_mem_iff (s0 : s β 0) : s β’ x β p β x β p :=
p.smul_mem_iff' (units.mk0 s s0)
end sub_mul_action
|
f95b7bc695cf6da3392fb7ff001ceb313be89d14 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/sheaves/presheaf.lean | e4c312be0326587c010686a4092117092519f2e2 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 15,394 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Mario Carneiro, Reid Barton, Andrew Yang
-/
import category_theory.limits.kan_extension
import topology.category.Top.opens
import category_theory.adjunction.opposites
/-!
# Presheaves on a topological space
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define `presheaf C X` simply as `(opens X)α΅α΅ β₯€ C`,
and inherit the category structure with natural transformations as morphisms.
We define
* `pushforward_obj {X Y : Top.{w}} (f : X βΆ Y) (β± : X.presheaf C) : Y.presheaf C`
with notation `f _* β±`
and for `β± : X.presheaf C` provide the natural isomorphisms
* `pushforward.id : (π X) _* β± β
β±`
* `pushforward.comp : (f β« g) _* β± β
g _* (f _* β±)`
along with their `@[simp]` lemmas.
We also define the functors `pushforward` and `pullback` between the categories
`X.presheaf C` and `Y.presheaf C`, and provide their adjunction at
`pushforward_pullback_adjunction`.
-/
universes w v u
open category_theory
open topological_space
open opposite
variables (C : Type u) [category.{v} C]
namespace Top
/-- The category of `C`-valued presheaves on a (bundled) topological space `X`. -/
@[derive category, nolint has_nonempty_instance]
def presheaf (X : Top.{w}) : Type (max u v w) := (opens X)α΅α΅ β₯€ C
variables {C}
namespace presheaf
local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun
/-- Tag lemmas to use in `Top.presheaf.restrict_tac`. -/
@[user_attribute]
meta def restrict_attr : user_attribute (tactic unit β tactic unit) unit :=
{ name := `sheaf_restrict,
descr := "tag lemmas to use in `Top.presheaf.restrict_tac`",
cache_cfg :=
{ mk_cache := Ξ» ns, pure $ Ξ» t, do
{ ctx <- tactic.local_context,
ctx.any_of (tactic.focus1 β (tactic.apply' >=> (Ξ» _, tactic.done)) >=> (Ξ» _, t)) <|>
ns.any_of (tactic.focus1 β (tactic.resolve_name >=> tactic.to_expr >=> tactic.apply' >=>
(Ξ» _, tactic.done)) >=> (Ξ» _, t)) },
dependencies := [] } }
/-- A tactic to discharge goals of type `U β€ V` for `Top.presheaf.restrict_open` -/
meta def restrict_tac : Ξ (n : β), tactic unit
| 0 := tactic.fail "`restrict_tac` failed"
| (n + 1) := monad.join (restrict_attr.get_cache <*> pure tactic.done) <|>
`[apply' le_trans, mjoin (restrict_attr.get_cache <*> pure (restrict_tac n))]
/-- A tactic to discharge goals of type `U β€ V` for `Top.presheaf.restrict_open`.
Defaults to three iterations. -/
meta def restrict_tac' := restrict_tac 3
attribute [sheaf_restrict] bot_le le_top le_refl inf_le_left inf_le_right le_sup_left le_sup_right
example {X : Top} {v w x y z : opens X} (hβ : v β€ x) (hβ : x β€ z β w) (hβ : x β€ y β z) :
v β€ y := by restrict_tac'
/-- The restriction of a section along an inclusion of open sets.
For `x : F.obj (op V)`, we provide the notation `x |_β i` (`h` stands for `hom`) for `i : U βΆ V`,
and the notation `x |_β U βͺiβ«` (`l` stands for `le`) for `i : U β€ V`.
-/
def restrict {X : Top} {C : Type*} [category C] [concrete_category C]
{F : X.presheaf C} {V : opens X} (x : F.obj (op V)) {U : opens X} (h : U βΆ V) : F.obj (op U) :=
F.map h.op x
localized "infixl ` |_β `: 80 := Top.presheaf.restrict" in algebraic_geometry
localized "notation x ` |_β `: 80 U ` βͺ` e `β« ` :=
@Top.presheaf.restrict _ _ _ _ _ _ x U (@hom_of_le (opens _) _ U _ e)" in algebraic_geometry
/-- The restriction of a section along an inclusion of open sets.
For `x : F.obj (op V)`, we provide the notation `x |_ U`, where the proof `U β€ V` is inferred by
the tactic `Top.presheaf.restrict_tac'` -/
abbreviation restrict_open {X : Top} {C : Type*} [category C] [concrete_category C]
{F : X.presheaf C} {V : opens X} (x : F.obj (op V)) (U : opens X)
(e : U β€ V . Top.presheaf.restrict_tac') : F.obj (op U) :=
x |_β U βͺeβ«
localized "infixl ` |_ `: 80 := Top.presheaf.restrict_open" in algebraic_geometry
@[simp]
lemma restrict_restrict {X : Top} {C : Type*} [category C] [concrete_category C]
{F : X.presheaf C} {U V W : opens X} (eβ : U β€ V) (eβ : V β€ W) (x : F.obj (op W)) :
x |_ V |_ U = x |_ U :=
by { delta restrict_open restrict, rw [β comp_apply, β functor.map_comp], refl }
@[simp]
lemma map_restrict {X : Top} {C : Type*} [category C] [concrete_category C]
{F G : X.presheaf C} (e : F βΆ G) {U V : opens X} (h : U β€ V) (x : F.obj (op V)) :
e.app _ (x |_ U) = (e.app _ x) |_ U :=
by { delta restrict_open restrict, rw [β comp_apply, nat_trans.naturality, comp_apply] }
/-- Pushforward a presheaf on `X` along a continuous map `f : X βΆ Y`, obtaining a presheaf
on `Y`. -/
def pushforward_obj {X Y : Top.{w}} (f : X βΆ Y) (β± : X.presheaf C) : Y.presheaf C :=
(opens.map f).op β β±
infix ` _* `: 80 := pushforward_obj
@[simp] lemma pushforward_obj_obj {X Y : Top.{w}} (f : X βΆ Y) (β± : X.presheaf C) (U : (opens Y)α΅α΅) :
(f _* β±).obj U = β±.obj ((opens.map f).op.obj U) := rfl
@[simp] lemma pushforward_obj_map {X Y : Top.{w}} (f : X βΆ Y) (β± : X.presheaf C)
{U V : (opens Y)α΅α΅} (i : U βΆ V) :
(f _* β±).map i = β±.map ((opens.map f).op.map i) := rfl
/--
An equality of continuous maps induces a natural isomorphism between the pushforwards of a presheaf
along those maps.
-/
def pushforward_eq {X Y : Top.{w}} {f g : X βΆ Y} (h : f = g) (β± : X.presheaf C) :
f _* β± β
g _* β± :=
iso_whisker_right (nat_iso.op (opens.map_iso f g h).symm) β±
lemma pushforward_eq' {X Y : Top.{w}} {f g : X βΆ Y} (h : f = g) (β± : X.presheaf C) :
f _* β± = g _* β± :=
by rw h
@[simp] lemma pushforward_eq_hom_app
{X Y : Top.{w}} {f g : X βΆ Y} (h : f = g) (β± : X.presheaf C) (U) :
(pushforward_eq h β±).hom.app U =
β±.map (begin dsimp [functor.op], apply quiver.hom.op, apply eq_to_hom, rw h, end) :=
by simp [pushforward_eq]
lemma pushforward_eq'_hom_app
{X Y : Top.{w}} {f g : X βΆ Y} (h : f = g) (β± : X.presheaf C) (U) :
nat_trans.app (eq_to_hom (pushforward_eq' h β±)) U = β±.map (eq_to_hom (by rw h)) :=
by simpa [eq_to_hom_map]
@[simp]
lemma pushforward_eq_rfl {X Y : Top.{w}} (f : X βΆ Y) (β± : X.presheaf C) (U) :
(pushforward_eq (rfl : f = f) β±).hom.app (op U) = π _ :=
begin
dsimp [pushforward_eq],
simp,
end
lemma pushforward_eq_eq {X Y : Top.{w}} {f g : X βΆ Y} (hβ hβ : f = g) (β± : X.presheaf C) :
β±.pushforward_eq hβ = β±.pushforward_eq hβ :=
rfl
namespace pushforward
variables {X : Top.{w}} (β± : X.presheaf C)
/-- The natural isomorphism between the pushforward of a presheaf along the identity continuous map
and the original presheaf. -/
def id : (π X) _* β± β
β± :=
(iso_whisker_right (nat_iso.op (opens.map_id X).symm) β±) βͺβ« functor.left_unitor _
lemma id_eq : (π X) _* β± = β± :=
by { unfold pushforward_obj, rw opens.map_id_eq, erw functor.id_comp }
@[simp] lemma id_hom_app' (U) (p) :
(id β±).hom.app (op β¨U, pβ©) = β±.map (π (op β¨U, pβ©)) :=
by { dsimp [id], simp, }
local attribute [tidy] tactic.op_induction'
@[simp, priority 990] lemma id_hom_app (U) :
(id β±).hom.app U = β±.map (eq_to_hom (opens.op_map_id_obj U)) :=
begin
-- was `tidy`
induction U using opposite.rec,
cases U,
rw [id_hom_app'],
congr
end
@[simp] lemma id_inv_app' (U) (p) : (id β±).inv.app (op β¨U, pβ©) = β±.map (π (op β¨U, pβ©)) :=
by { dsimp [id], simp, }
/-- The natural isomorphism between
the pushforward of a presheaf along the composition of two continuous maps and
the corresponding pushforward of a pushforward. -/
def comp {Y Z : Top.{w}} (f : X βΆ Y) (g : Y βΆ Z) : (f β« g) _* β± β
g _* (f _* β±) :=
iso_whisker_right (nat_iso.op (opens.map_comp f g).symm) β±
lemma comp_eq {Y Z : Top.{w}} (f : X βΆ Y) (g : Y βΆ Z) : (f β« g) _* β± = g _* (f _* β±) :=
rfl
@[simp] lemma comp_hom_app {Y Z : Top.{w}} (f : X βΆ Y) (g : Y βΆ Z) (U) :
(comp β± f g).hom.app U = π _ :=
by { dsimp [comp], tidy, }
@[simp] lemma comp_inv_app {Y Z : Top.{w}} (f : X βΆ Y) (g : Y βΆ Z) (U) :
(comp β± f g).inv.app U = π _ :=
by { dsimp [comp], tidy, }
end pushforward
/--
A morphism of presheaves gives rise to a morphisms of the pushforwards of those presheaves.
-/
@[simps]
def pushforward_map {X Y : Top.{w}} (f : X βΆ Y) {β± π’ : X.presheaf C} (Ξ± : β± βΆ π’) :
f _* β± βΆ f _* π’ :=
{ app := Ξ» U, Ξ±.app _,
naturality' := Ξ» U V i, by { erw Ξ±.naturality, refl, } }
open category_theory.limits
section pullback
variable [has_colimits C]
noncomputable theory
/--
Pullback a presheaf on `Y` along a continuous map `f : X βΆ Y`, obtaining a presheaf on `X`.
This is defined in terms of left Kan extensions, which is just a fancy way of saying
"take the colimits over the open sets whose preimage contains U".
-/
@[simps]
def pullback_obj {X Y : Top.{v}} (f : X βΆ Y) (β± : Y.presheaf C) : X.presheaf C :=
(Lan (opens.map f).op).obj β±
/-- Pulling back along continuous maps is functorial. -/
def pullback_map {X Y : Top.{v}} (f : X βΆ Y) {β± π’ : Y.presheaf C} (Ξ± : β± βΆ π’) :
pullback_obj f β± βΆ pullback_obj f π’ :=
(Lan (opens.map f).op).map Ξ±
/-- If `f '' U` is open, then `fβ»ΒΉβ± U β
β± (f '' U)`. -/
@[simps]
def pullback_obj_obj_of_image_open {X Y : Top.{v}} (f : X βΆ Y) (β± : Y.presheaf C) (U : opens X)
(H : is_open (f '' U)) : (pullback_obj f β±).obj (op U) β
β±.obj (op β¨_, Hβ©) :=
begin
let x : costructured_arrow (opens.map f).op (op U) := begin
refine @costructured_arrow.mk _ _ _ _ _ (op (opens.mk (f '' U) H)) _ _,
exact ((@hom_of_le _ _ _ ((opens.map f).obj β¨_, Hβ©) (set.image_preimage.le_u_l _)).op),
end,
have hx : is_terminal x :=
{ lift := Ξ» s,
begin
fapply costructured_arrow.hom_mk,
change op (unop _) βΆ op (β¨_, Hβ© : opens _),
refine (hom_of_le _).op,
exact (set.image_subset f s.X.hom.unop.le).trans (set.image_preimage.l_u_le β(unop s.X.left)),
simp
end },
exact is_colimit.cocone_point_unique_up_to_iso
(colimit.is_colimit _)
(colimit_of_diagram_terminal hx _),
end
namespace pullback
variables {X Y : Top.{v}} (β± : Y.presheaf C)
/-- The pullback along the identity is isomorphic to the original presheaf. -/
def id : pullback_obj (π _) β± β
β± :=
nat_iso.of_components
(Ξ» U, pullback_obj_obj_of_image_open (π _) β± (unop U) (by simpa using U.unop.2) βͺβ«
β±.map_iso (eq_to_iso (by simp)))
(Ξ» U V i,
begin
ext, simp,
erw colimit.pre_desc_assoc,
erw colimit.ΞΉ_desc_assoc,
erw colimit.ΞΉ_desc_assoc,
dsimp, simp only [ββ±.map_comp], congr
end)
lemma id_inv_app (U : opens Y) :
(id β±).inv.app (op U) = colimit.ΞΉ (Lan.diagram (opens.map (π Y)).op β± (op U))
(@costructured_arrow.mk _ _ _ _ _ (op U) _ (eq_to_hom (by simp))) :=
begin
rw [β category.id_comp ((id β±).inv.app (op U)), β nat_iso.app_inv, iso.comp_inv_eq],
dsimp [id],
rw colimit.ΞΉ_desc_assoc,
dsimp,
rw [β β±.map_comp, β β±.map_id], refl,
end
end pullback
end pullback
variable (C)
/--
The pushforward functor.
-/
def pushforward {X Y : Top.{w}} (f : X βΆ Y) : X.presheaf C β₯€ Y.presheaf C :=
{ obj := pushforward_obj f,
map := @pushforward_map _ _ X Y f }
@[simp]
lemma pushforward_map_app' {X Y : Top.{w}} (f : X βΆ Y)
{β± π’ : X.presheaf C} (Ξ± : β± βΆ π’) {U : (opens Y)α΅α΅} :
((pushforward C f).map Ξ±).app U = Ξ±.app (op $ (opens.map f).obj U.unop) := rfl
lemma id_pushforward {X : Top.{w}} : pushforward C (π X) = π (X.presheaf C) :=
begin
apply category_theory.functor.ext,
{ intros,
ext U,
have h := f.congr, erw h (opens.op_map_id_obj U),
simpa [eq_to_hom_map], },
{ intros, apply pushforward.id_eq },
end
section iso
/-- A homeomorphism of spaces gives an equivalence of categories of presheaves. -/
@[simps] def presheaf_equiv_of_iso {X Y : Top} (H : X β
Y) :
X.presheaf C β Y.presheaf C :=
equivalence.congr_left (opens.map_map_iso H).symm.op
variable {C}
/--
If `H : X β
Y` is a homeomorphism,
then given an `H _* β± βΆ π’`, we may obtain an `β± βΆ H β»ΒΉ _* π’`.
-/
def to_pushforward_of_iso {X Y : Top} (H : X β
Y) {β± : X.presheaf C} {π’ : Y.presheaf C}
(Ξ± : H.hom _* β± βΆ π’) : β± βΆ H.inv _* π’ :=
(presheaf_equiv_of_iso _ H).to_adjunction.hom_equiv β± π’ Ξ±
@[simp]
lemma to_pushforward_of_iso_app {X Y : Top} (Hβ : X β
Y) {β± : X.presheaf C} {π’ : Y.presheaf C}
(Hβ : Hβ.hom _* β± βΆ π’) (U : (opens X)α΅α΅) :
(to_pushforward_of_iso Hβ Hβ).app U =
β±.map (eq_to_hom (by simp [opens.map, set.preimage_preimage])) β«
Hβ.app (op ((opens.map Hβ.inv).obj (unop U))) :=
begin
delta to_pushforward_of_iso,
simp only [equiv.to_fun_as_coe, nat_trans.comp_app, equivalence.equivalence_mk'_unit,
eq_to_hom_map, eq_to_hom_op, eq_to_hom_trans, presheaf_equiv_of_iso_unit_iso_hom_app_app,
equivalence.to_adjunction, equivalence.equivalence_mk'_counit,
presheaf_equiv_of_iso_inverse_map_app, adjunction.mk_of_unit_counit_hom_equiv_apply],
congr,
end
/--
If `H : X β
Y` is a homeomorphism,
then given an `H _* β± βΆ π’`, we may obtain an `β± βΆ H β»ΒΉ _* π’`.
-/
def pushforward_to_of_iso {X Y : Top} (Hβ : X β
Y) {β± : Y.presheaf C} {π’ : X.presheaf C}
(Hβ : β± βΆ Hβ.hom _* π’) : Hβ.inv _* β± βΆ π’ :=
((presheaf_equiv_of_iso _ Hβ.symm).to_adjunction.hom_equiv β± π’).symm Hβ
@[simp]
lemma pushforward_to_of_iso_app {X Y : Top} (Hβ : X β
Y) {β± : Y.presheaf C} {π’ : X.presheaf C}
(Hβ : β± βΆ Hβ.hom _* π’) (U : (opens X)α΅α΅) :
(pushforward_to_of_iso Hβ Hβ).app U =
Hβ.app (op ((opens.map Hβ.inv).obj (unop U))) β«
π’.map (eq_to_hom (by simp [opens.map, set.preimage_preimage])) :=
by simpa [pushforward_to_of_iso, equivalence.to_adjunction]
end iso
variables (C) [has_colimits C]
/-- Pullback a presheaf on `Y` along a continuous map `f : X βΆ Y`, obtaining a presheaf
on `X`. -/
@[simps map_app]
def pullback {X Y : Top.{v}} (f : X βΆ Y) : Y.presheaf C β₯€ X.presheaf C := Lan (opens.map f).op
@[simp] lemma pullback_obj_eq_pullback_obj {C} [category C] [has_colimits C] {X Y : Top.{w}}
(f : X βΆ Y) (β± : Y.presheaf C) : (pullback C f).obj β± = pullback_obj f β± := rfl
/-- The pullback and pushforward along a continuous map are adjoint to each other. -/
@[simps unit_app_app counit_app_app]
def pushforward_pullback_adjunction {X Y : Top.{v}} (f : X βΆ Y) :
pullback C f β£ pushforward C f := Lan.adjunction _ _
/-- Pulling back along a homeomorphism is the same as pushing forward along its inverse. -/
def pullback_hom_iso_pushforward_inv {X Y : Top.{v}} (H : X β
Y) :
pullback C H.hom β
pushforward C H.inv :=
adjunction.left_adjoint_uniq
(pushforward_pullback_adjunction C H.hom)
(presheaf_equiv_of_iso C H.symm).to_adjunction
/-- Pulling back along the inverse of a homeomorphism is the same as pushing forward along it. -/
def pullback_inv_iso_pushforward_hom {X Y : Top.{v}} (H : X β
Y) :
pullback C H.inv β
pushforward C H.hom :=
adjunction.left_adjoint_uniq
(pushforward_pullback_adjunction C H.inv)
(presheaf_equiv_of_iso C H).to_adjunction
end presheaf
end Top
|
b84e37344d8bce83eef81dbf2c1c256ea58df34e | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/W.lean | d0ab9b2636c9fe9ea99d1ae8b9f11d4eb11eb30a | [
"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,366 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import data.equiv.list
/-!
# W types
Given `Ξ± : Type` and `Ξ² : Ξ± β Type`, the W type determined by this data, `W_type Ξ²`, is the
inductively defined type of trees where the nodes are labeled by elements of `Ξ±` and the children of
a node labeled `a` are indexed by elements of `Ξ² a`.
This file is currently a stub, awaiting a full development of the theory. Currently, the main result
is that if `Ξ±` is an encodable fintype and `Ξ² a` is encodable for every `a : Ξ±`, then `W_type Ξ²` is
encodable. This can be used to show the encodability of other inductive types, such as those that
are commonly used to formalize syntax, e.g. terms and expressions in a given language. The strategy
is illustrated in the example found in the file `prop_encodable` in the `archive/examples` folder of
mathlib.
## Implementation details
While the name `W_type` is somewhat verbose, it is preferable to putting a single character
identifier `W` in the root namespace.
-/
/--
Given `Ξ² : Ξ± β Type*`, `W_type Ξ²` is the type of finitely branching trees where nodes are labeled by
elements of `Ξ±` and the children of a node labeled `a` are indexed by elements of `Ξ² a`.
-/
inductive W_type {Ξ± : Type*} (Ξ² : Ξ± β Type*)
| mk (a : Ξ±) (f : Ξ² a β W_type) : W_type
instance : inhabited (W_type (Ξ» (_ : unit), empty)) :=
β¨W_type.mk unit.star empty.elimβ©
namespace W_type
variables {Ξ± : Type*} {Ξ² : Ξ± β Type*} [Ξ a : Ξ±, fintype (Ξ² a)]
/-- The depth of a finitely branching tree. -/
def depth : W_type Ξ² β β
| β¨a, fβ© := finset.sup finset.univ (Ξ» n, depth (f n)) + 1
lemma depth_pos (t : W_type Ξ²) : 0 < t.depth :=
by { cases t, apply nat.succ_pos }
lemma depth_lt_depth_mk (a : Ξ±) (f : Ξ² a β W_type Ξ²) (i : Ξ² a) :
depth (f i) < depth β¨a, fβ© :=
nat.lt_succ_of_le (finset.le_sup (finset.mem_univ i))
end W_type
/-
Show that W types are encodable when `Ξ±` is an encodable fintype and for every `a : Ξ±`, `Ξ² a` is
encodable.
We define an auxiliary type `W_type' Ξ² n` of trees of depth at most `n`, and then we show by
induction on `n` that these are all encodable. These auxiliary constructions are not interesting in
and of themselves, so we mark them as `private`.
-/
namespace encodable
@[reducible] private def W_type' {Ξ± : Type*} (Ξ² : Ξ± β Type*)
[Ξ a : Ξ±, fintype (Ξ² a)] [Ξ a : Ξ±, encodable (Ξ² a)] (n : β) :=
{ t : W_type Ξ² // t.depth β€ n}
variables {Ξ± : Type*} {Ξ² : Ξ± β Type*} [Ξ a : Ξ±, fintype (Ξ² a)] [Ξ a : Ξ±, encodable (Ξ² a)]
private def encodable_zero : encodable (W_type' Ξ² 0) :=
let f : W_type' Ξ² 0 β empty := Ξ» β¨x, hβ©, false.elim $ not_lt_of_ge h (W_type.depth_pos _),
finv : empty β W_type' Ξ² 0 := by { intro x, cases x} in
have β x, finv (f x) = x, from Ξ» β¨x, hβ©, false.elim $ not_lt_of_ge h (W_type.depth_pos _),
encodable.of_left_inverse f finv this
private def f (n : β) : W_type' Ξ² (n + 1) β Ξ£ a : Ξ±, Ξ² a β W_type' Ξ² n
| β¨t, hβ© :=
begin
cases t with a f,
have hβ : β i : Ξ² a, W_type.depth (f i) β€ n,
from Ξ» i, nat.le_of_lt_succ (lt_of_lt_of_le (W_type.depth_lt_depth_mk a f i) h),
exact β¨a, Ξ» i : Ξ² a, β¨f i, hβ iβ©β©
end
private def finv (n : β) :
(Ξ£ a : Ξ±, Ξ² a β W_type' Ξ² n) β W_type' Ξ² (n + 1)
| β¨a, fβ© :=
let f' := Ξ» i : Ξ² a, (f i).val in
have W_type.depth β¨a, f'β© β€ n + 1,
from add_le_add_right (finset.sup_le (Ξ» b h, (f b).2)) 1,
β¨β¨a, f'β©, thisβ©
variables [encodable Ξ±]
private def encodable_succ (n : nat) (h : encodable (W_type' Ξ² n)) :
encodable (W_type' Ξ² (n + 1)) :=
encodable.of_left_inverse (f n) (finv n) (by { rintro β¨β¨_, _β©, _β©, refl })
/-- `W_type` is encodable when `Ξ±` is an encodable fintype and for every `a : Ξ±`, `Ξ² a` is
encodable. -/
instance : encodable (W_type Ξ²) :=
begin
haveI h' : Ξ n, encodable (W_type' Ξ² n) :=
Ξ» n, nat.rec_on n encodable_zero encodable_succ,
let f : W_type Ξ² β Ξ£ n, W_type' Ξ² n := Ξ» t, β¨t.depth, β¨t, le_refl _β©β©,
let finv : (Ξ£ n, W_type' Ξ² n) β W_type Ξ² := Ξ» p, p.2.1,
have : β t, finv (f t) = t, from Ξ» t, rfl,
exact encodable.of_left_inverse f finv this
end
end encodable
|
69ea0559eeb91d487e4f1edc0f73f33b500b74fe | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/calculus/tangent_cone.lean | 9e8ab6413dd151d98eb1548b89a9f9690edb17f8 | [
"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 | 20,174 | lean | /-
Copyright (c) 2019 SΓ©bastien GouΓ«zel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: SΓ©bastien GouΓ«zel
-/
import analysis.convex.topology
import analysis.normed_space.basic
import analysis.specific_limits.basic
/-!
# Tangent cone
In this file, we define two predicates `unique_diff_within_at π s x` and `unique_diff_on π s`
ensuring that, if a function has two derivatives, then they have to coincide. As a direct
definition of this fact (quantifying on all target types and all functions) would depend on
universes, we use a more intrinsic definition: if all the possible tangent directions to the set
`s` at the point `x` span a dense subset of the whole subset, it is easy to check that the
derivative has to be unique.
Therefore, we introduce the set of all tangent directions, named `tangent_cone_at`,
and express `unique_diff_within_at` and `unique_diff_on` in terms of it.
One should however think of this definition as an implementation detail: the only reason to
introduce the predicates `unique_diff_within_at` and `unique_diff_on` is to ensure the uniqueness
of the derivative. This is why their names reflect their uses, and not how they are defined.
## Implementation details
Note that this file is imported by `fderiv.lean`. Hence, derivatives are not defined yet. The
property of uniqueness of the derivative is therefore proved in `fderiv.lean`, but based on the
properties of the tangent cone we prove here.
-/
variables (π : Type*) [nontrivially_normed_field π]
open filter set
open_locale topological_space
section tangent_cone
variables {E : Type*} [add_comm_monoid E] [module π E] [topological_space E]
/-- The set of all tangent directions to the set `s` at the point `x`. -/
def tangent_cone_at (s : set E) (x : E) : set E :=
{y : E | β(c : β β π) (d : β β E), (βαΆ n in at_top, x + d n β s) β§
(tendsto (Ξ»n, βc nβ) at_top at_top) β§ (tendsto (Ξ»n, c n β’ d n) at_top (π y))}
/-- A property ensuring that the tangent cone to `s` at `x` spans a dense subset of the whole space.
The main role of this property is to ensure that the differential within `s` at `x` is unique,
hence this name. The uniqueness it asserts is proved in `unique_diff_within_at.eq` in `fderiv.lean`.
To avoid pathologies in dimension 0, we also require that `x` belongs to the closure of `s` (which
is automatic when `E` is not `0`-dimensional).
-/
@[mk_iff] structure unique_diff_within_at (s : set E) (x : E) : Prop :=
(dense_tangent_cone : dense ((submodule.span π (tangent_cone_at π s x)) : set E))
(mem_closure : x β closure s)
/-- A property ensuring that the tangent cone to `s` at any of its points spans a dense subset of
the whole space. The main role of this property is to ensure that the differential along `s` is
unique, hence this name. The uniqueness it asserts is proved in `unique_diff_on.eq` in
`fderiv.lean`. -/
def unique_diff_on (s : set E) : Prop :=
βx β s, unique_diff_within_at π s x
end tangent_cone
variables {E : Type*} [normed_add_comm_group E] [normed_space π E]
variables {F : Type*} [normed_add_comm_group F] [normed_space π F]
variables {G : Type*} [normed_add_comm_group G] [normed_space β G]
variables {π} {x y : E} {s t : set E}
section tangent_cone
/- This section is devoted to the properties of the tangent cone. -/
open normed_field
lemma tangent_cone_univ : tangent_cone_at π univ x = univ :=
begin
refine univ_subset_iff.1 (Ξ»y hy, _),
rcases exists_one_lt_norm π with β¨w, hwβ©,
refine β¨Ξ»n, w^n, Ξ»n, (w^n)β»ΒΉ β’ y, univ_mem' (Ξ»n, mem_univ _), _, _β©,
{ simp only [norm_pow],
exact tendsto_pow_at_top_at_top_of_one_lt hw },
{ convert tendsto_const_nhds,
ext n,
have : w ^ n * (w ^ n)β»ΒΉ = 1,
{ apply mul_inv_cancel,
apply pow_ne_zero,
simpa [norm_eq_zero] using (ne_of_lt (lt_trans zero_lt_one hw)).symm },
rw [smul_smul, this, one_smul] }
end
lemma tangent_cone_mono (h : s β t) :
tangent_cone_at π s x β tangent_cone_at π t x :=
begin
rintros y β¨c, d, ds, ctop, climβ©,
exact β¨c, d, mem_of_superset ds (Ξ»n hn, h hn), ctop, climβ©
end
/-- Auxiliary lemma ensuring that, under the assumptions defining the tangent cone,
the sequence `d` tends to 0 at infinity. -/
lemma tangent_cone_at.lim_zero {Ξ± : Type*} (l : filter Ξ±) {c : Ξ± β π} {d : Ξ± β E}
(hc : tendsto (Ξ»n, βc nβ) l at_top) (hd : tendsto (Ξ»n, c n β’ d n) l (π y)) :
tendsto d l (π 0) :=
begin
have A : tendsto (Ξ»n, βc nββ»ΒΉ) l (π 0) := tendsto_inv_at_top_zero.comp hc,
have B : tendsto (Ξ»n, βc n β’ d nβ) l (π βyβ) :=
(continuous_norm.tendsto _).comp hd,
have C : tendsto (Ξ»n, βc nββ»ΒΉ * βc n β’ d nβ) l (π (0 * βyβ)) := A.mul B,
rw zero_mul at C,
have : βαΆ n in l, βc nββ»ΒΉ * βc n β’ d nβ = βd nβ,
{ apply (eventually_ne_of_tendsto_norm_at_top hc 0).mono (Ξ»n hn, _),
rw [norm_smul, β mul_assoc, inv_mul_cancel, one_mul],
rwa [ne.def, norm_eq_zero] },
have D : tendsto (Ξ» n, βd nβ) l (π 0) :=
tendsto.congr' this C,
rw tendsto_zero_iff_norm_tendsto_zero,
exact D
end
lemma tangent_cone_mono_nhds (h : π[s] x β€ π[t] x) :
tangent_cone_at π s x β tangent_cone_at π t x :=
begin
rintros y β¨c, d, ds, ctop, climβ©,
refine β¨c, d, _, ctop, climβ©,
suffices : tendsto (Ξ» n, x + d n) at_top (π[t] x),
from tendsto_principal.1 (tendsto_inf.1 this).2,
refine (tendsto_inf.2 β¨_, tendsto_principal.2 dsβ©).mono_right h,
simpa only [add_zero] using tendsto_const_nhds.add (tangent_cone_at.lim_zero at_top ctop clim)
end
/-- Tangent cone of `s` at `x` depends only on `π[s] x`. -/
lemma tangent_cone_congr (h : π[s] x = π[t] x) :
tangent_cone_at π s x = tangent_cone_at π t x :=
subset.antisymm
(tangent_cone_mono_nhds $ le_of_eq h)
(tangent_cone_mono_nhds $ le_of_eq h.symm)
/-- Intersecting with a neighborhood of the point does not change the tangent cone. -/
lemma tangent_cone_inter_nhds (ht : t β π x) :
tangent_cone_at π (s β© t) x = tangent_cone_at π s x :=
tangent_cone_congr (nhds_within_restrict' _ ht).symm
/-- The tangent cone of a product contains the tangent cone of its left factor. -/
lemma subset_tangent_cone_prod_left {t : set F} {y : F} (ht : y β closure t) :
linear_map.inl π E F '' (tangent_cone_at π s x) β tangent_cone_at π (s ΓΛ’ t) (x, y) :=
begin
rintros _ β¨v, β¨c, d, hd, hc, hyβ©, rflβ©,
have : βn, βd', y + d' β t β§ βc n β’ d'β < ((1:β)/2)^n,
{ assume n,
rcases mem_closure_iff_nhds.1 ht _ (eventually_nhds_norm_smul_sub_lt (c n) y
(pow_pos one_half_pos n)) with β¨z, hz, hztβ©,
exact β¨z - y, by simpa using hzt, by simpa using hzβ© },
choose d' hd' using this,
refine β¨c, Ξ»n, (d n, d' n), _, hc, _β©,
show βαΆ n in at_top, (x, y) + (d n, d' n) β s ΓΛ’ t,
{ filter_upwards [hd] with n hn,
simp [hn, (hd' n).1] },
{ apply tendsto.prod_mk_nhds hy _,
refine squeeze_zero_norm (Ξ»n, (hd' n).2.le) _,
exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one }
end
/-- The tangent cone of a product contains the tangent cone of its right factor. -/
lemma subset_tangent_cone_prod_right {t : set F} {y : F}
(hs : x β closure s) :
linear_map.inr π E F '' (tangent_cone_at π t y) β tangent_cone_at π (s ΓΛ’ t) (x, y) :=
begin
rintros _ β¨w, β¨c, d, hd, hc, hyβ©, rflβ©,
have : βn, βd', x + d' β s β§ βc n β’ d'β < ((1:β)/2)^n,
{ assume n,
rcases mem_closure_iff_nhds.1 hs _ (eventually_nhds_norm_smul_sub_lt (c n) x
(pow_pos one_half_pos n)) with β¨z, hz, hzsβ©,
exact β¨z - x, by simpa using hzs, by simpa using hzβ© },
choose d' hd' using this,
refine β¨c, Ξ»n, (d' n, d n), _, hc, _β©,
show βαΆ n in at_top, (x, y) + (d' n, d n) β s ΓΛ’ t,
{ filter_upwards [hd] with n hn,
simp [hn, (hd' n).1] },
{ apply tendsto.prod_mk_nhds _ hy,
refine squeeze_zero_norm (Ξ»n, (hd' n).2.le) _,
exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one }
end
/-- The tangent cone of a product contains the tangent cone of each factor. -/
lemma maps_to_tangent_cone_pi {ΞΉ : Type*} [decidable_eq ΞΉ] {E : ΞΉ β Type*}
[Ξ i, normed_add_comm_group (E i)] [Ξ i, normed_space π (E i)]
{s : Ξ i, set (E i)} {x : Ξ i, E i} {i : ΞΉ} (hi : β j β i, x j β closure (s j)) :
maps_to (linear_map.single i : E i ββ[π] Ξ j, E j) (tangent_cone_at π (s i) (x i))
(tangent_cone_at π (set.pi univ s) x) :=
begin
rintros w β¨c, d, hd, hc, hyβ©,
have : β n (j β i), β d', x j + d' β s j β§ βc n β’ d'β < (1 / 2 : β) ^ n,
{ assume n j hj,
rcases mem_closure_iff_nhds.1 (hi j hj) _ (eventually_nhds_norm_smul_sub_lt (c n) (x j)
(pow_pos one_half_pos n)) with β¨z, hz, hzsβ©,
exact β¨z - x j, by simpa using hzs, by simpa using hzβ© },
choose! d' hd's hcd',
refine β¨c, Ξ» n, function.update (d' n) i (d n), hd.mono (Ξ» n hn j hj', _), hc,
tendsto_pi_nhds.2 $ Ξ» j, _β©,
{ rcases em (j = i) with rfl|hj; simp * },
{ rcases em (j = i) with rfl|hj,
{ simp [hy] },
{ suffices : tendsto (Ξ» n, c n β’ d' n j) at_top (π 0), by simpa [hj],
refine squeeze_zero_norm (Ξ» n, (hcd' n j hj).le) _,
exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } }
end
/-- If a subset of a real vector space contains an open segment, then the direction of this
segment belongs to the tangent cone at its endpoints. -/
lemma mem_tangent_cone_of_open_segment_subset {s : set G} {x y : G} (h : open_segment β x y β s) :
y - x β tangent_cone_at β s x :=
begin
let c := Ξ»n:β, (2:β)^(n+1),
let d := Ξ»n:β, (c n)β»ΒΉ β’ (y-x),
refine β¨c, d, filter.univ_mem' (Ξ»n, h _), _, _β©,
show x + d n β open_segment β x y,
{ rw open_segment_eq_image,
refine β¨(c n)β»ΒΉ, β¨_, _β©, _β©,
{ rw inv_pos, apply pow_pos, norm_num },
{ apply inv_lt_one, apply one_lt_pow _ (nat.succ_ne_zero _), norm_num },
{ simp only [d, sub_smul, smul_sub, one_smul], abel } },
show filter.tendsto (Ξ» (n : β), βc nβ) filter.at_top filter.at_top,
{ have : (Ξ» (n : β), βc nβ) = c,
by { ext n, exact abs_of_nonneg (pow_nonneg (by norm_num) _) },
rw this,
exact (tendsto_pow_at_top_at_top_of_one_lt (by norm_num)).comp (tendsto_add_at_top_nat 1) },
show filter.tendsto (Ξ» (n : β), c n β’ d n) filter.at_top (π (y - x)),
{ have : (Ξ» (n : β), c n β’ d n) = (Ξ»n, y - x),
{ ext n,
simp only [d, smul_smul],
rw [mul_inv_cancel, one_smul],
exact pow_ne_zero _ (by norm_num) },
rw this,
apply tendsto_const_nhds }
end
/-- If a subset of a real vector space contains a segment, then the direction of this
segment belongs to the tangent cone at its endpoints. -/
lemma mem_tangent_cone_of_segment_subset {s : set G} {x y : G} (h : segment β x y β s) :
y - x β tangent_cone_at β s x :=
mem_tangent_cone_of_open_segment_subset ((open_segment_subset_segment β x y).trans h)
end tangent_cone
section unique_diff
/-!
### Properties of `unique_diff_within_at` and `unique_diff_on`
This section is devoted to properties of the predicates
`unique_diff_within_at` and `unique_diff_on`. -/
lemma unique_diff_on.unique_diff_within_at {s : set E} {x} (hs : unique_diff_on π s) (h : x β s) :
unique_diff_within_at π s x :=
hs x h
lemma unique_diff_within_at_univ : unique_diff_within_at π univ x :=
by { rw [unique_diff_within_at_iff, tangent_cone_univ], simp }
lemma unique_diff_on_univ : unique_diff_on π (univ : set E) :=
Ξ»x hx, unique_diff_within_at_univ
lemma unique_diff_on_empty : unique_diff_on π (β
: set E) :=
Ξ» x hx, hx.elim
lemma unique_diff_within_at.mono_nhds (h : unique_diff_within_at π s x)
(st : π[s] x β€ π[t] x) :
unique_diff_within_at π t x :=
begin
simp only [unique_diff_within_at_iff] at *,
rw [mem_closure_iff_nhds_within_ne_bot] at h β’,
exact β¨h.1.mono $ submodule.span_mono $ tangent_cone_mono_nhds st,
h.2.mono stβ©
end
lemma unique_diff_within_at.mono (h : unique_diff_within_at π s x) (st : s β t) :
unique_diff_within_at π t x :=
h.mono_nhds $ nhds_within_mono _ st
lemma unique_diff_within_at_congr (st : π[s] x = π[t] x) :
unique_diff_within_at π s x β unique_diff_within_at π t x :=
β¨Ξ» h, h.mono_nhds $ le_of_eq st, Ξ» h, h.mono_nhds $ le_of_eq st.symmβ©
lemma unique_diff_within_at_inter (ht : t β π x) :
unique_diff_within_at π (s β© t) x β unique_diff_within_at π s x :=
unique_diff_within_at_congr $ (nhds_within_restrict' _ ht).symm
lemma unique_diff_within_at.inter (hs : unique_diff_within_at π s x) (ht : t β π x) :
unique_diff_within_at π (s β© t) x :=
(unique_diff_within_at_inter ht).2 hs
lemma unique_diff_within_at_inter' (ht : t β π[s] x) :
unique_diff_within_at π (s β© t) x β unique_diff_within_at π s x :=
unique_diff_within_at_congr $ (nhds_within_restrict'' _ ht).symm
lemma unique_diff_within_at.inter' (hs : unique_diff_within_at π s x) (ht : t β π[s] x) :
unique_diff_within_at π (s β© t) x :=
(unique_diff_within_at_inter' ht).2 hs
lemma unique_diff_within_at_of_mem_nhds (h : s β π x) : unique_diff_within_at π s x :=
by simpa only [univ_inter] using unique_diff_within_at_univ.inter h
lemma is_open.unique_diff_within_at (hs : is_open s) (xs : x β s) : unique_diff_within_at π s x :=
unique_diff_within_at_of_mem_nhds (is_open.mem_nhds hs xs)
lemma unique_diff_on.inter (hs : unique_diff_on π s) (ht : is_open t) : unique_diff_on π (s β© t) :=
Ξ»x hx, (hs x hx.1).inter (is_open.mem_nhds ht hx.2)
lemma is_open.unique_diff_on (hs : is_open s) : unique_diff_on π s :=
Ξ»x hx, is_open.unique_diff_within_at hs hx
/-- The product of two sets of unique differentiability at points `x` and `y` has unique
differentiability at `(x, y)`. -/
lemma unique_diff_within_at.prod {t : set F} {y : F}
(hs : unique_diff_within_at π s x) (ht : unique_diff_within_at π t y) :
unique_diff_within_at π (s ΓΛ’ t) (x, y) :=
begin
rw [unique_diff_within_at_iff] at β’ hs ht,
rw [closure_prod_eq],
refine β¨_, hs.2, ht.2β©,
have : _ β€ submodule.span π (tangent_cone_at π (s ΓΛ’ t) (x, y)) :=
submodule.span_mono (union_subset (subset_tangent_cone_prod_left ht.2)
(subset_tangent_cone_prod_right hs.2)),
rw [linear_map.span_inl_union_inr, set_like.le_def] at this,
exact (hs.1.prod ht.1).mono this
end
lemma unique_diff_within_at.univ_pi (ΞΉ : Type*) [finite ΞΉ] (E : ΞΉ β Type*)
[Ξ i, normed_add_comm_group (E i)] [Ξ i, normed_space π (E i)]
(s : Ξ i, set (E i)) (x : Ξ i, E i) (h : β i, unique_diff_within_at π (s i) (x i)) :
unique_diff_within_at π (set.pi univ s) x :=
begin
classical,
simp only [unique_diff_within_at_iff, closure_pi_set] at h β’,
refine β¨(dense_pi univ (Ξ» i _, (h i).1)).mono _, Ξ» i _, (h i).2β©,
norm_cast,
simp only [β submodule.supr_map_single, supr_le_iff, linear_map.map_span, submodule.span_le,
β maps_to'],
exact Ξ» i, (maps_to_tangent_cone_pi $ Ξ» j hj, (h j).2).mono subset.rfl submodule.subset_span
end
lemma unique_diff_within_at.pi (ΞΉ : Type*) [finite ΞΉ] (E : ΞΉ β Type*)
[Ξ i, normed_add_comm_group (E i)] [Ξ i, normed_space π (E i)]
(s : Ξ i, set (E i)) (x : Ξ i, E i) (I : set ΞΉ)
(h : β i β I, unique_diff_within_at π (s i) (x i)) :
unique_diff_within_at π (set.pi I s) x :=
begin
classical,
rw [β set.univ_pi_piecewise],
refine unique_diff_within_at.univ_pi _ _ _ _ (Ξ» i, _),
by_cases hi : i β I; simp [*, unique_diff_within_at_univ],
end
/-- The product of two sets of unique differentiability is a set of unique differentiability. -/
lemma unique_diff_on.prod {t : set F} (hs : unique_diff_on π s) (ht : unique_diff_on π t) :
unique_diff_on π (s ΓΛ’ t) :=
Ξ» β¨x, yβ© h, unique_diff_within_at.prod (hs x h.1) (ht y h.2)
/-- The finite product of a family of sets of unique differentiability is a set of unique
differentiability. -/
lemma unique_diff_on.pi (ΞΉ : Type*) [finite ΞΉ] (E : ΞΉ β Type*)
[Ξ i, normed_add_comm_group (E i)] [Ξ i, normed_space π (E i)]
(s : Ξ i, set (E i)) (I : set ΞΉ) (h : β i β I, unique_diff_on π (s i)) :
unique_diff_on π (set.pi I s) :=
Ξ» x hx, unique_diff_within_at.pi _ _ _ _ _ $ Ξ» i hi, h i hi (x i) (hx i hi)
/-- The finite product of a family of sets of unique differentiability is a set of unique
differentiability. -/
lemma unique_diff_on.univ_pi (ΞΉ : Type*) [finite ΞΉ] (E : ΞΉ β Type*)
[Ξ i, normed_add_comm_group (E i)] [Ξ i, normed_space π (E i)]
(s : Ξ i, set (E i)) (h : β i, unique_diff_on π (s i)) :
unique_diff_on π (set.pi univ s) :=
unique_diff_on.pi _ _ _ _ $ Ξ» i _, h i
/-- In a real vector space, a convex set with nonempty interior is a set of unique
differentiability at every point of its closure. -/
theorem unique_diff_within_at_convex {s : set G} (conv : convex β s) (hs : (interior s).nonempty)
{x : G} (hx : x β closure s) : unique_diff_within_at β s x :=
begin
rcases hs with β¨y, hyβ©,
suffices : y - x β interior (tangent_cone_at β s x),
{ refine β¨dense.of_closure _, hxβ©,
simp [(submodule.span β (tangent_cone_at β s x)).eq_top_of_nonempty_interior'
β¨y - x, interior_mono submodule.subset_span thisβ©] },
rw [mem_interior_iff_mem_nhds],
replace hy : interior s β π y := is_open.mem_nhds is_open_interior hy,
apply mem_of_superset ((is_open_map_sub_right x).image_mem_nhds hy),
rintros _ β¨z, zs, rflβ©,
refine mem_tangent_cone_of_open_segment_subset (subset.trans _ interior_subset),
exact conv.open_segment_closure_interior_subset_interior hx zs,
end
/-- In a real vector space, a convex set with nonempty interior is a set of unique
differentiability. -/
theorem unique_diff_on_convex {s : set G} (conv : convex β s) (hs : (interior s).nonempty) :
unique_diff_on β s :=
Ξ» x xs, unique_diff_within_at_convex conv hs (subset_closure xs)
lemma unique_diff_on_Ici (a : β) : unique_diff_on β (Ici a) :=
unique_diff_on_convex (convex_Ici a) $ by simp only [interior_Ici, nonempty_Ioi]
lemma unique_diff_on_Iic (a : β) : unique_diff_on β (Iic a) :=
unique_diff_on_convex (convex_Iic a) $ by simp only [interior_Iic, nonempty_Iio]
lemma unique_diff_on_Ioi (a : β) : unique_diff_on β (Ioi a) :=
is_open_Ioi.unique_diff_on
lemma unique_diff_on_Iio (a : β) : unique_diff_on β (Iio a) :=
is_open_Iio.unique_diff_on
lemma unique_diff_on_Icc {a b : β} (hab : a < b) : unique_diff_on β (Icc a b) :=
unique_diff_on_convex (convex_Icc a b) $ by simp only [interior_Icc, nonempty_Ioo, hab]
lemma unique_diff_on_Ico (a b : β) : unique_diff_on β (Ico a b) :=
if hab : a < b
then unique_diff_on_convex (convex_Ico a b) $ by simp only [interior_Ico, nonempty_Ioo, hab]
else by simp only [Ico_eq_empty hab, unique_diff_on_empty]
lemma unique_diff_on_Ioc (a b : β) : unique_diff_on β (Ioc a b) :=
if hab : a < b
then unique_diff_on_convex (convex_Ioc a b) $ by simp only [interior_Ioc, nonempty_Ioo, hab]
else by simp only [Ioc_eq_empty hab, unique_diff_on_empty]
lemma unique_diff_on_Ioo (a b : β) : unique_diff_on β (Ioo a b) :=
is_open_Ioo.unique_diff_on
/-- The real interval `[0, 1]` is a set of unique differentiability. -/
lemma unique_diff_on_Icc_zero_one : unique_diff_on β (Icc (0:β) 1) :=
unique_diff_on_Icc zero_lt_one
lemma unique_diff_within_at_Ioo {a b t : β} (ht : t β set.Ioo a b) :
unique_diff_within_at β (set.Ioo a b) t :=
is_open.unique_diff_within_at is_open_Ioo ht
lemma unique_diff_within_at_Ioi (a : β) : unique_diff_within_at β (Ioi a) a :=
unique_diff_within_at_convex (convex_Ioi a) (by simp) (by simp)
lemma unique_diff_within_at_Iio (a : β) : unique_diff_within_at β (Iio a) a :=
unique_diff_within_at_convex (convex_Iio a) (by simp) (by simp)
end unique_diff
|
e499f1ab6c50863f2997dbc06f89a0643b794104 | d65db56b17d72b62013ed1f438f74457ad25b140 | /src/lib/algebra.lean | 3cb5941ec65e5ae220bc2ac70892f27aede070d6 | [] | no_license | swgillespie/proofs | cfa65722fdb4bb7d7910a0856d0cbea8e8b9a3f9 | 168ef7ef33d372ae0ed6ee4ca336137a52b89f8f | refs/heads/master | 1,585,700,692,028 | 1,540,162,775,000 | 1,540,162,775,000 | 152,695,805 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 871 | lean | universe u
namespace algebra
variable {Ξ±: Type u}
/-
- Semigroup Proofs
-/
section semigroup
theorem mul_left_inj [left_cancel_semigroup Ξ±] (a : Ξ±) {b c : Ξ±} : a * b = a * c β b = c :=
β¨mul_left_cancel, congr_arg _β©
end semigroup
/-
- Group Proofs
-/
section group
variables [group Ξ±] {a b : Ξ±}
theorem same_inverse_implies_equality : aβ»ΒΉ = bβ»ΒΉ β a = b :=
begin
apply iff.intro,
{
intro h,
rw βinv_inv a,
rw h,
rw inv_inv,
},
{
intro h,
apply congr_arg,
exact h,
}
end
theorem mul_self_iff_one : a * a = a β a = 1 :=
begin
have q := @mul_left_inj _ _ a a 1,
rw mul_one at q,
exact q
end
theorem inv_one_iff_one : aβ»ΒΉ = 1 β a = 1 :=
begin
rw β@same_inverse_implies_equality _ _ a 1,
rw one_inv,
end
end group
end algebra |
8252e15b9ed83800578d75c7bac122451a1570e0 | 8cd4726d66eec7673bcc0325fed07d5ba5bf17c4 | /exam1.lean | a736d0005030e251f9e8fe47e48fc6c1f10a3349 | [] | no_license | justinqcai/CS2102 | 8c5fddedffa6147fedd4b6ee7d5d39fc21f0ddab | d309f0db3f1df52eb77206ee1e8665a3b49d7a0c | refs/heads/master | 1,590,108,991,894 | 1,557,610,044,000 | 1,557,610,044,000 | 186,064,169 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,482 | lean | /- Justin cai, jc5pz-/
/-
POINTS: Welcome to the first CS2102 exam. The exam has 12
questions. Points for each question are as indicated, for a
total of 100 points.
READ CAREFULLY: If you are unable to answer a question in
a way that Lean accepts as syntactically correct, *comment
out your malformed answer*. Otherwise an error in your answer
can cause Lean not to recognize correct answers to other
questions. If you are sure an answer is correct but Lean is
not accepting it, look for problems in the preceding logic.
Do not change or delete any of the questions.
WHAT TO DO: Complete the exam by following the instructions
for each question. Save your file then upload the completed
and saved file to Collab. You have 75 minutes from the start
of the exam to the time where it must be uploaded to Collab.
OPEN NOTES: You may use the class notes for this exam, whether
provided to you by the instructors or taken by you (or for you).
STRICTLY INDIVIDUAL EFFORT: This is a strictly individual exam,
taken under the honor system. Do not communicate with anyone except
for the instructor about the content of this exam, by any means,
until you are sure that each person you are communicating with
has already completed the test.
-/
/- 1. (5 points)
What is the type of function1 (just below)? Give you answer by
replacing the hole (underscore) in the subsequent definition
with your answer.
-/
def function1 (f: β β β) (g: β β β) :=
Ξ» (x: β), 3
#check function1
def function1_type : Type :=
(β β β ) β (β β β ) β β β β
/- 2. (10 points)
Define three equivalent functions, called product1,
product2, and product3. Each must take two natural
numbers as its arguments and return their product.
Define the first version using C-style notation,
the second using a lambda abstraction, and the third
using a tactic script.
-/
-- Answer below:
-- ANSWER
-- C-style here
def product1 (a b: β ) : β := a * b
-- Lambda abstraction here
def product2: β β β β β :=
Ξ» a b : β,
a * b
-- Tactic script here
def product3 (a b : β ) : β :=
begin
exact a * b
end
/- 3. (5 points)
Given the definition of product1, what function
is (product1 5)? Answer by replacing the hole in
the following definition with a lambda abstraction.
-/
def product1_5 := Ξ» a : β, product1 5 a
/- 4. (5 points)
Which of the following properties does "product1_5" have?
Answer by placing a Y (for yes, it has this property), or
N (for no, it doesn't have this property), BEFORE the name
of each property, just after the dash.
-- ANSWER
- Y injective
- N surjective
- N one-to-many
- N strictly partial
- N bijective
-/
/- 5. (5 points)
Complete the proof of the following conjecture, that
(product1 4 6) = 24. Fill in the proposition to be
proved in the first hole (underscore) and a proof in
the second hole.
-/
-- ANSWER
example : (product1 4 6) = 24 := rfl
/- 6. (10 points)
Prove the proposition that, for any natural
numbers, a, b, and c, if b = a, then if c = b, then a = c.
Fill in the hole in the following example accordingly,
replacing the underscore with a proof.
-/
-- Complete by replacing the hole with a proof:
example: β a b c: β, b = a β c = b β a = c :=
Ξ» a b c,
Ξ» ba : b = a,
Ξ» cb : c = b,
eq.trans (eq.symm ba) (eq.symm cb)
/- 7. (10 points)
In the context of the following assumptions, use
"example" to formally state and prove the proposition
that "Jane is nice."
-/
axiom Person : Type
axioms Jill Jane : Person
axiom IsNice : Person β Prop
axiom JillIsNice : IsNice Jill
axiom JillIsJane : Jill = Jane
-- Fill in the holes with your proposition and proof
example : IsNice Jane :=
eq.subst JillIsJane JillIsNice
/- 8. (10 points)
Use "example" to prove that true β§ true implies
true. Give two proofs, the first using a term-style
proof (e.g., a lambda expression term), and the
second, using a tactic script.
-/
-- Your answers here
example : true β§ true β true := and.elim_left
example : true β§ true β true :=
begin
exact and.elim_left
end
/- 9. (10 points)
Define a function, called exfalso, that takes a proof
of false as an argument, and that returns a proof of
3 = 7 as a result.
-/
-- ANSWER
def exfalso (f: false) : 3 = 7 :=
begin
exact false.elim f
end
/- 10. (10 points)
Formally state and prove the proposition,
that, for any propositions, A, B, and C,
A β§ B β§ C β C β§ A β§ B. You may write the
proof in any style you wish. One way to do it
would be to define a function that takes the
propositions, A, B, and C, and a proof of the
premise as its arguments and that returns a
proof of the conclusion as a result. You
might also use a tactic script.
-/
-- ANSWER
example: β (A B C : Prop ) , A β§ B β§ C β C β§ A β§ B :=
begin
intros A B C,
assume abc,
have c := abc.2.2,
have a := abc.1,
have b:= abc.2.1,
exact and.intro c (and.intro a b),
end
/- 11. (10 points)
Formally (in Lean), prove that if A, B, and C
are any propositions, and if C is true, then
A β§ B β§ C β B β§ A.
-/
-- Complete the following by replacing _ with a proof:
theorem temp : β(A B C: Prop), C β (A β§ B β§ C β B β§ A) :=
begin
assume A B C,
assume c,
assume abc,
have a := abc.1,
have bc := abc.2,
have b := bc.1,
have ba := and.intro b a,
exact ba,
end
/- 12. (10 points)
Define a predicate, gt5, that is true for all and only for
natural numbers greater than 5. You may use the expression,
n > 5, in your answer. Then fill in the hole in the following
definition with the type of the term (gt5 4).
-/
-- ANSWER
def gt5 : β β Prop :=
Ξ» n : β ,
if n > 5 then tt else ff
-- ANSWER
def type_of_gt5_4 := (5 > 4 : Prop)
/- 13. EXTRA CREDIT 5 points
Give brief natural-language (in English) rendition
of the following formal proposition.
β n, m : β, isPrime n β§ isPrime m β§ m = n + 2
Answer: There exists an n and m, both Nats,
n is prime and m is prime, and m is equal to n + 2
If by isPrime we mean the ordinary concept of primeness
from basic arithmetic, then this proposition is true.
Prove it by giving values for n and m that satisfy the
predicate along with a very brief argument that the two
numbers do actually satisfy the predicate.
Answer:
n = 1
m = 3
Argument:
1 is prime and 3 is prime, and 1 + 2 = 3, thus n=1 and m=3
satisfies this predicate
-/
|
be3bd2aef08b5ebccf125b4c6ad9b5a697a1af92 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /05_Interacting_with_Lean.org.1.lean | 313ec13e9ccd64e1effae6a0aa4084f272cee56d | [] | 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 | 426 | lean | /- page 62 -/
import standard
import data.nat
-- examples with equality
check eq
check @eq
check eq.symm
check @eq.symm
print eq.symm
-- examples with and
check and
check and.intro
check @and.intro
-- examples with addition
open nat
check add
check @add
eval add 3 2
print definition add
-- a user-defined function
definition foo {A : Type} (x : A) : A := x
check foo
check @foo
eval foo
eval (foo @nat.zero)
print foo
|
77b20e976473771ee182d51218fedde26909d6a3 | 3f7026ea8bef0825ca0339a275c03b911baef64d | /src/category_theory/limits/shapes/finite_products.lean | a716539b1b13a2519869f14f3329c9ccf320ce10 | [
"Apache-2.0"
] | permissive | rspencer01/mathlib | b1e3afa5c121362ef0881012cc116513ab09f18c | c7d36292c6b9234dc40143c16288932ae38fdc12 | refs/heads/master | 1,595,010,346,708 | 1,567,511,503,000 | 1,567,511,503,000 | 206,071,681 | 0 | 0 | Apache-2.0 | 1,567,513,643,000 | 1,567,513,643,000 | null | UTF-8 | Lean | false | false | 1,494 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.limits.shapes.products
import category_theory.limits.shapes.finite_limits
import category_theory.discrete_category
import data.fintype
universes v u
open category_theory
namespace category_theory.limits
variables (C : Type u) [π : category.{v+1} C]
include π
class has_finite_products :=
(has_limits_of_shape : Ξ (J : Type v) [fintype J], has_limits_of_shape.{v} (discrete J) C)
class has_finite_coproducts :=
(has_colimits_of_shape : Ξ (J : Type v) [fintype J], has_colimits_of_shape.{v} (discrete J) C)
attribute [instance] has_finite_products.has_limits_of_shape has_finite_coproducts.has_colimits_of_shape
instance has_finite_products_of_has_products [has_products.{v} C] : has_finite_products.{v} C :=
{ has_limits_of_shape := Ξ» J _, by apply_instance }
instance has_finite_coproducts_of_has_coproducts [has_coproducts.{v} C] : has_finite_coproducts.{v} C :=
{ has_colimits_of_shape := Ξ» J _, by apply_instance }
instance has_finite_products_of_has_finite_limits [has_finite_limits.{v} C] : has_finite_products.{v} C :=
{ has_limits_of_shape := Ξ» J _, by { resetI, apply_instance } }
instance has_finite_coproducts_of_has_finite_colimits [has_finite_colimits.{v} C] : has_finite_coproducts.{v} C :=
{ has_colimits_of_shape := Ξ» J _, by { resetI, apply_instance } }
end category_theory.limits
|
b8666b73dffacbeaa976e3a03f7303e1ad373b27 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/data/real/ennreal.lean | 8c8be7cf6f5a0fa6ef7a050a237b231ea0576468 | [
"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 | 26,727 | 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
Extended non-negative reals
-/
import data.real.nnreal order.bounds tactic.norm_num
noncomputable theory
open classical set lattice
local attribute [instance] prop_decidable
variables {Ξ± : Type*} {Ξ² : Type*}
/-- The extended nonnegative real numbers. This is usually denoted [0, β],
and is relevant as the codomain of a measure. -/
def ennreal := with_top nnreal
local notation `β` := (β€ : ennreal)
namespace ennreal
variables {a b c d : ennreal} {r p q : nnreal}
instance : canonically_ordered_comm_semiring ennreal := by unfold ennreal; apply_instance
instance : decidable_linear_order ennreal := by unfold ennreal; apply_instance
instance : complete_linear_order ennreal := by unfold ennreal; apply_instance
instance : inhabited ennreal := β¨0β©
instance : densely_ordered ennreal := with_top.densely_ordered
instance : has_coe nnreal ennreal := β¨ option.some β©
lemma none_eq_top : (none : ennreal) = (β€ : ennreal) := rfl
lemma some_eq_coe (a : nnreal) : (some a : ennreal) = (βa : ennreal) := rfl
/-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/
protected def to_nnreal : ennreal β nnreal
| (some r) := r
| none := 0
/-- `to_real x` returns `x` if it is real, `0` otherwise. -/
protected def to_real (a : ennreal) : real := coe (a.to_nnreal)
/-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/
protected def of_real (r : real) : ennreal := coe (nnreal.of_real r)
@[simp] lemma to_nnreal_coe : (r : ennreal).to_nnreal = r := rfl
@[simp] lemma coe_to_nnreal : β{a:ennreal}, a β β β β(a.to_nnreal) = a
| (some r) h := rfl
| none h := (h rfl).elim
@[simp] lemma of_real_to_real {a : ennreal} (h : a β β) : ennreal.of_real (a.to_real) = a :=
by simp [ennreal.to_real, ennreal.of_real, h]
@[simp] lemma to_real_of_real {r : real} (h : 0 β€ r) : ennreal.to_real (ennreal.of_real r) = r :=
by simp [ennreal.to_real, ennreal.of_real, nnreal.coe_of_real _ h]
lemma coe_to_nnreal_le_self : β{a:ennreal}, β(a.to_nnreal) β€ a
| (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _
| none := le_top
@[simp] lemma coe_zero : β(0 : nnreal) = (0 : ennreal) := rfl
@[simp] lemma coe_one : β(1 : nnreal) = (1 : ennreal) := rfl
@[simp] lemma to_real_nonneg {a : ennreal} : 0 β€ a.to_real := by simp [ennreal.to_real]
@[simp] lemma top_to_nnreal : β.to_nnreal = 0 := rfl
@[simp] lemma top_to_real : β.to_real = 0 := rfl
@[simp] lemma zero_to_nnreal : (0 : ennreal).to_nnreal = 0 := rfl
@[simp] lemma zero_to_real : (0 : ennreal).to_real = 0 := rfl
@[simp] lemma of_real_zero : ennreal.of_real (0 : β) = 0 :=
by simp [ennreal.of_real]; refl
@[simp] lemma of_real_one : ennreal.of_real (1 : β) = (1 : ennreal) :=
by simp [ennreal.of_real]
lemma forall_ennreal {p : ennreal β Prop} : (βa, p a) β (βr:nnreal, p r) β§ p β :=
β¨assume h, β¨assume r, h _, h _β©,
assume β¨hβ, hββ© a, match a with some r := hβ _ | none := hβ endβ©
lemma to_nnreal_eq_zero_iff (x : ennreal) : x.to_nnreal = 0 β x = 0 β¨ x = β€ :=
β¨begin
cases x,
{ simp [none_eq_top] },
{ have A : some (0:nnreal) = (0:ennreal) := rfl,
simp [ennreal.to_nnreal, A] {contextual := tt} }
end,
by intro h; cases h; simp [h]β©
lemma to_real_eq_zero_iff (x : ennreal) : x.to_real = 0 β x = 0 β¨ x = β€ :=
by simp [ennreal.to_real, to_nnreal_eq_zero_iff]
@[simp] lemma coe_ne_top : (r : ennreal) β β := with_top.coe_ne_top
@[simp] lemma top_ne_coe : β β (r : ennreal) := with_top.top_ne_coe
@[simp] lemma of_real_ne_top {r : β} : ennreal.of_real r β β := by simp [ennreal.of_real]
@[simp] lemma top_ne_of_real {r : β} : β β ennreal.of_real r := by simp [ennreal.of_real]
@[simp] lemma zero_ne_top : 0 β β := coe_ne_top
@[simp] lemma top_ne_zero : β β 0 := top_ne_coe
@[simp] lemma one_ne_top : 1 β β := coe_ne_top
@[simp] lemma top_ne_one : β β 1 := top_ne_coe
@[simp] lemma coe_eq_coe : (βr : ennreal) = βq β r = q := with_top.coe_eq_coe
@[simp] lemma coe_le_coe : (βr : ennreal) β€ βq β r β€ q := with_top.coe_le_coe
@[simp] lemma coe_lt_coe : (βr : ennreal) < βq β r < q := with_top.coe_lt_coe
@[simp] lemma coe_eq_zero : (βr : ennreal) = 0 β r = 0 := coe_eq_coe
@[simp] lemma zero_eq_coe : 0 = (βr : ennreal) β 0 = r := coe_eq_coe
@[simp] lemma coe_eq_one : (βr : ennreal) = 1 β r = 1 := coe_eq_coe
@[simp] lemma one_eq_coe : 1 = (βr : ennreal) β 1 = r := coe_eq_coe
@[simp] lemma coe_nonneg : 0 β€ (βr : ennreal) β 0 β€ r := coe_le_coe
@[simp] lemma coe_pos : 0 < (βr : ennreal) β 0 < r := coe_lt_coe
@[simp] lemma coe_add : β(r + p) = (r + p : ennreal) := with_top.coe_add
@[simp] lemma coe_mul : β(r * p) = (r * p : ennreal) := with_top.coe_mul
@[simp] lemma coe_bit0 : (β(bit0 r) : ennreal) = bit0 r := coe_add
@[simp] lemma coe_bit1 : (β(bit1 r) : ennreal) = bit1 r := by simp [bit1]
@[simp] lemma add_top : a + β = β := with_top.add_top
@[simp] lemma top_add : β + a = β := with_top.top_add
instance : is_semiring_hom (coe : nnreal β ennreal) :=
by refine_struct {..}; simp
lemma add_eq_top : a + b = β β a = β β¨ b = β := with_top.add_eq_top _ _
lemma add_lt_top : a + b < β β a < β β§ b < β := with_top.add_lt_top _ _
lemma to_nnreal_add {rβ rβ : ennreal} (hβ : rβ < β€) (hβ : rβ < β€) :
(rβ + rβ).to_nnreal = rβ.to_nnreal + rβ.to_nnreal :=
begin
rw [β coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal];
apply @ne_top_of_lt ennreal _ _ β€,
exact hβ,
exact hβ,
exact add_lt_top.2 β¨hβ, hββ©
end
/- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot
(contrary to erw). This is solved with the next lemmas -/
protected lemma lt_top_iff_ne_top : a < β β a β β := lt_top_iff_ne_top
protected lemma bot_lt_iff_ne_bot : 0 < a β a β 0 := bot_lt_iff_ne_bot
lemma mul_top : a * β = (if a = 0 then 0 else β) :=
begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end
lemma top_mul : β * a = (if a = 0 then 0 else β) :=
begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end
@[simp] lemma top_mul_top : β * β = β := with_top.top_mul_top
lemma mul_eq_top {a b : ennreal} : a * b = β€ β (a β 0 β§ b = β€) β¨ (a = β€ β§ b β 0) :=
with_top.mul_eq_top_iff
lemma mul_lt_top {a b : ennreal} : a < β€ β b < β€ β a * b < β€ :=
by simp [ennreal.lt_top_iff_ne_top, (β ), mul_eq_top] {contextual := tt}
@[simp] lemma coe_finset_sum {s : finset Ξ±} {f : Ξ± β nnreal} : β(s.sum f) = (s.sum (Ξ»a, f a) : ennreal) :=
(finset.sum_hom coe).symm
@[simp] lemma coe_finset_prod {s : finset Ξ±} {f : Ξ± β nnreal} : β(s.prod f) = (s.prod (Ξ»a, f a) : ennreal) :=
(finset.prod_hom coe).symm
@[simp] lemma bot_eq_zero : (β₯ : ennreal) = 0 := rfl
section order
@[simp] lemma coe_lt_top : coe r < β := with_top.coe_lt_top r
@[simp] lemma not_top_le_coe : Β¬ (β€:ennreal) β€ βr := with_top.not_top_le_coe r
@[simp] lemma zero_lt_coe_iff : 0 < (βp : ennreal) β 0 < p := coe_lt_coe
@[simp] lemma one_le_coe_iff : (1:ennreal) β€ βr β 1 β€ r := coe_le_coe
@[simp] lemma coe_le_one_iff : βr β€ (1:ennreal) β r β€ 1 := coe_le_coe
@[simp] lemma coe_lt_one_iff : (βp : ennreal) < 1 β p < 1 := coe_lt_coe
@[simp] lemma one_lt_zero_iff : 1 < (βp : ennreal) β 1 < p := coe_lt_coe
@[simp] lemma coe_nat (n : nat) : ((n : nnreal) : ennreal) = n := with_top.coe_nat n
@[simp] lemma nat_ne_top (n : nat) : (n : ennreal) β β€ := with_top.nat_ne_top n
@[simp] lemma top_ne_nat (n : nat) : (β€ : ennreal) β n := with_top.top_ne_nat n
lemma le_coe_iff : a β€ βr β (βp:nnreal, a = p β§ p β€ r) := with_top.le_coe_iff r a
lemma coe_le_iff : βr β€ a β (βp:nnreal, a = p β r β€ p) := with_top.coe_le_iff r a
lemma lt_iff_exists_coe : a < b β (βp:nnreal, a = p β§ βp < b) := with_top.lt_iff_exists_coe a b
-- TODO: move to canonically ordered semiring ...
protected lemma zero_lt_one : 0 < (1 : ennreal) := zero_lt_coe_iff.mpr zero_lt_one
@[simp] lemma not_lt_zero : Β¬ a < 0 := by simp
lemma add_lt_add_iff_left : a < β€ β (a + c < a + b β c < b) :=
with_top.add_lt_add_iff_left
lemma add_lt_add_iff_right : a < β€ β (c + a < b + a β c < b) :=
with_top.add_lt_add_iff_right
lemma lt_add_right (ha : a < β€) (hb : 0 < b) : a < a + b :=
by rwa [β add_lt_add_iff_left ha, add_zero] at hb
lemma le_of_forall_epsilon_le : β{a b : ennreal}, (βΞ΅:nnreal, Ξ΅ > 0 β b < β β a β€ b + Ξ΅) β a β€ b
| a none h := le_top
| none (some a) h :=
have (β€:ennreal) β€ βa + β(1:nnreal), from h 1 zero_lt_one coe_lt_top,
by rw [β coe_add] at this; exact (not_top_le_coe this).elim
| (some a) (some b) h :=
by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *;
exact nnreal.le_of_forall_epsilon_le h
lemma lt_iff_exists_rat_btwn :
a < b β (βq:β, 0 β€ q β§ a < nnreal.of_real q β§ (nnreal.of_real q:ennreal) < b) :=
β¨Ξ» h,
begin
rcases lt_iff_exists_coe.1 h with β¨p, rfl, _β©,
rcases dense h with β¨c, pc, cbβ©,
rcases lt_iff_exists_coe.1 cb with β¨r, rfl, _β©,
rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with β¨q, hq0, pq, qrβ©,
exact β¨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cbβ©
end,
Ξ» β¨q, q0, qa, qbβ©, lt_trans qa qbβ©
lemma lt_iff_exists_real_btwn :
a < b β (βr:β, 0 β€ r β§ a < ennreal.of_real r β§ (ennreal.of_real r:ennreal) < b) :=
β¨Ξ» h, let β¨q, q0, aq, qbβ© := ennreal.lt_iff_exists_rat_btwn.1 h in
β¨q, rat.cast_nonneg.2 q0, aq, qbβ©,
Ξ» β¨q, q0, qa, qbβ©, lt_trans qa qbβ©
protected lemma exists_nat_gt {r : ennreal} (h : r β β€) : βn:β, r < n :=
begin
rcases lt_iff_exists_coe.1 (lt_top_iff_ne_top.2 h) with β¨r, rfl, hbβ©,
rcases exists_nat_gt r with β¨n, hnβ©,
refine β¨n, _β©,
rwa [β ennreal.coe_nat, ennreal.coe_lt_coe],
end
lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d :=
begin
rcases dense ac with β¨a', aa', a'cβ©,
rcases lt_iff_exists_coe.1 aa' with β¨aR, rfl, _β©,
rcases lt_iff_exists_coe.1 a'c with β¨a'R, rfl, _β©,
rcases dense bd with β¨b', bb', b'dβ©,
rcases lt_iff_exists_coe.1 bb' with β¨bR, rfl, _β©,
rcases lt_iff_exists_coe.1 b'd with β¨b'R, rfl, _β©,
have I : βaR + βbR < βa'R + βb'R :=
begin
rw [β coe_add, β coe_add, coe_lt_coe],
apply add_lt_add (coe_lt_coe.1 aa') (coe_lt_coe.1 bb')
end,
have J : βa'R + βb'R β€ c + d := add_le_add' (le_of_lt a'c) (le_of_lt b'd),
apply lt_of_lt_of_le I J
end
end order
section complete_lattice
lemma coe_Sup {s : set nnreal} : bdd_above s β (β(Sup s) : ennreal) = (β¨aβs, βa) := with_top.coe_Sup
lemma coe_Inf {s : set nnreal} : s β β
β (β(Inf s) : ennreal) = (β¨
aβs, βa) := with_top.coe_Inf
@[simp] lemma top_mem_upper_bounds {s : set ennreal} : β β upper_bounds s :=
assume x hx, le_top
lemma coe_mem_upper_bounds {s : set nnreal} :
βr β upper_bounds ((coe : nnreal β ennreal) '' s) β r β upper_bounds s :=
by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt}
lemma infi_ennreal {Ξ± : Type*} [complete_lattice Ξ±] {f : ennreal β Ξ±} :
(β¨
n, f n) = (β¨
n:nnreal, f n) β f β€ :=
le_antisymm
(le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _))
(le_infi $ forall_ennreal.2 β¨assume r, inf_le_left_of_le $ infi_le _ _, inf_le_rightβ©)
end complete_lattice
section mul
lemma mul_eq_mul_left : a β 0 β a β β€ β (a * b = a * c β b = c) :=
begin
cases a; cases b; cases c;
simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm,
nnreal.mul_eq_mul_left] {contextual := tt},
end
lemma mul_le_mul_left : a β 0 β a β β€ β (a * b β€ a * c β b β€ c) :=
begin
cases a; cases b; cases c;
simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt},
assume h, exact mul_le_mul_left (zero_lt_iff_ne_zero.2 h)
end
lemma mul_eq_zero {a b : ennreal} : a * b = 0 β a = 0 β¨ b = 0 :=
canonically_ordered_comm_semiring.mul_eq_zero_iff _ _
end mul
section sub
instance : has_sub ennreal := β¨Ξ»a b, Inf {d | a β€ d + b}β©
lemma coe_sub : β(p - r) = (βp:ennreal) - r :=
le_antisymm
(le_Inf $ assume b (hb : βp β€ b + r), coe_le_iff.2 $
by rintros d rfl; rwa [β coe_add, coe_le_coe, β nnreal.sub_le_iff_le_add] at hb)
(Inf_le $ show (βp : ennreal) β€ β(p - r) + βr,
by rw [β coe_add, coe_le_coe, β nnreal.sub_le_iff_le_add])
@[simp] lemma top_sub_coe : β - βr = β :=
top_unique $ le_Inf $ by simp [add_eq_top]
@[simp] lemma sub_eq_zero_of_le (h : a β€ b) : a - b = 0 :=
le_antisymm (Inf_le $ le_add_left h) (zero_le _)
@[simp] lemma zero_sub : 0 - a = 0 :=
le_antisymm (Inf_le $ zero_le _) (zero_le _)
@[simp] lemma sub_infty : a - β = 0 :=
le_antisymm (Inf_le $ by simp) (zero_le _)
lemma sub_le_sub (hβ : a β€ b) (hβ : d β€ c) : a - c β€ b - d :=
Inf_le_Inf $ assume e (h : b β€ e + d),
calc a β€ b : hβ
... β€ e + d : h
... β€ e + c : add_le_add' (le_refl _) hβ
@[simp] lemma add_sub_self : β{a b : ennreal}, b < β β (a + b) - b = a
| a none := by simp [none_eq_top]
| none (some b) := by simp [none_eq_top, some_eq_coe]
| (some a) (some b) :=
by simp [some_eq_coe]; rw [β coe_add, β coe_sub, coe_eq_coe, nnreal.add_sub_cancel]
@[simp] lemma add_sub_self' (h : a < β) : (a + b) - a = b :=
by rw [add_comm, add_sub_self h]
lemma add_left_inj (h : a < β) : a + b = a + c β b = c :=
β¨Ξ» e, by simpa [h] using congr_arg (Ξ» x, x - a) e, congr_arg _β©
lemma add_right_inj (h : a < β) : b + a = c + a β b = c :=
by rw [add_comm, add_comm c, add_left_inj h]
@[simp] lemma sub_add_cancel_of_le : β{a b : ennreal}, b β€ a β (a - b) + b = a :=
begin
simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt},
rintros r p x rfl h,
rw [β coe_sub, β coe_add, nnreal.sub_add_cancel_of_le h]
end
@[simp] lemma add_sub_cancel_of_le (h : b β€ a) : b + (a - b) = a :=
by rwa [add_comm, sub_add_cancel_of_le]
lemma sub_add_self_eq_max : (a - b) + b = max a b :=
match le_total a b with
| or.inl h := by simp [h, max_eq_right]
| or.inr h := by simp [h, max_eq_left]
end
@[simp] protected lemma sub_le_iff_le_add : a - b β€ c β a β€ c + b :=
iff.intro
(assume h : a - b β€ c,
calc a β€ (a - b) + b : by rw [sub_add_self_eq_max]; exact le_max_left _ _
... β€ c + b : add_le_add' h (le_refl _))
(assume h : a β€ c + b,
calc a - b β€ (c + b) - b : sub_le_sub h (le_refl _)
... β€ c : Inf_le (le_refl (c + b)))
@[simp] lemma sub_eq_zero_iff_le : a - b = 0 β a β€ b :=
by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0
@[simp] lemma zero_lt_sub_iff_lt : 0 < a - b β b < a :=
by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b)
lemma sub_le_self (a b : ennreal) : a - b β€ a :=
ennreal.sub_le_iff_le_add.2 $ le_add_of_nonneg_right' $ zero_le _
@[simp] lemma sub_zero : a - 0 = a :=
eq.trans (add_zero (a - 0)).symm $ by simp
lemma sub_sub_cancel (h : a < β) (h2 : b β€ a) : a - (a - b) = b :=
by rw [β add_right_inj (lt_of_le_of_lt (sub_le_self _ _) h),
sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2]
end sub
section bit
@[simp] lemma bit0_inj : bit0 a = bit0 b β a = b :=
β¨Ξ»h, begin
rcases (lt_trichotomy a b) with hβ| hβ| hβ,
{ exact (absurd h (ne_of_lt (add_lt_add hβ hβ))) },
{ exact hβ },
{ exact (absurd h.symm (ne_of_lt (add_lt_add hβ hβ))) }
end,
Ξ»h, congr_arg _ hβ©
@[simp] lemma bit0_eq_zero_iff : bit0 a = 0 β a = 0 :=
by simpa only [bit0_zero] using @bit0_inj a 0
@[simp] lemma bit0_eq_top_iff : bit0 a = β β a = β :=
by rw [bit0, add_eq_top, or_self]
@[simp] lemma bit1_inj : bit1 a = bit1 b β a = b :=
β¨Ξ»h, begin
unfold bit1 at h,
rwa [add_right_inj, bit0_inj] at h,
simp [lt_top_iff_ne_top]
end,
Ξ»h, congr_arg _ hβ©
@[simp] lemma bit1_ne_zero : bit1 a β 0 :=
by unfold bit1; simp
@[simp] lemma bit1_eq_one_iff : bit1 a = 1 β a = 0 :=
by simpa only [bit1_zero] using @bit1_inj a 0
@[simp] lemma bit1_eq_top_iff : bit1 a = β β a = β :=
by unfold bit1; rw add_eq_top; simp
end bit
section inv
instance : has_inv ennreal := β¨Ξ»a, Inf {b | 1 β€ a * b}β©
instance : has_div ennreal := β¨Ξ»a b, a * bβ»ΒΉβ©
lemma div_def : a / b = a * bβ»ΒΉ := rfl
@[simp] lemma inv_zero : (0 : ennreal)β»ΒΉ = β :=
show Inf {b : ennreal | 1 β€ 0 * b} = β, by simp; refl
@[simp] lemma inv_top : (β : ennreal)β»ΒΉ = 0 :=
bot_unique $ le_of_forall_le_of_dense $ Ξ» a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul]
@[simp] lemma coe_inv (hr : r β 0) : (βrβ»ΒΉ : ennreal) = (βr)β»ΒΉ :=
le_antisymm
(le_Inf $ assume b (hb : 1 β€ βr * b), coe_le_iff.2 $
by rintros b rfl; rwa [β coe_mul, β coe_one, coe_le_coe, β nnreal.inv_le hr] at hb)
(Inf_le $ by simp; rw [β coe_mul, nnreal.mul_inv_cancel hr]; exact le_refl 1)
@[simp] lemma coe_div (hr : r β 0) : (β(p / r) : ennreal) = p / r :=
show β(p * rβ»ΒΉ) = βp * (βr)β»ΒΉ, by rw [coe_mul, coe_inv hr]
@[simp] lemma inv_inv : (aβ»ΒΉ)β»ΒΉ = a :=
by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe,
-coe_inv, (coe_inv _).symm] at *
@[simp] lemma inv_eq_top : aβ»ΒΉ = β β a = 0 :=
by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe,
-coe_inv, (coe_inv _).symm] at *
lemma inv_ne_top : aβ»ΒΉ β β β a β 0 := by simp
@[simp] lemma inv_eq_zero : aβ»ΒΉ = 0 β a = β :=
by rw [β inv_eq_top, inv_inv]
lemma inv_ne_zero : aβ»ΒΉ β 0 β a β β := by simp
lemma le_div_iff_mul_le : β{b}, b β 0 β b β β€ β (a β€ c / b β a * b β€ c)
| none h0 ht := (ht rfl).elim
| (some r) h0 ht :=
begin
have hr : r β 0, from mt coe_eq_coe.2 h0,
rw [β ennreal.mul_le_mul_left h0 ht],
suffices : βr * a β€ (βr * βrβ»ΒΉ) * c β a * βr β€ c,
{ simpa [some_eq_coe, div_def, hr, mul_left_comm, mul_comm, mul_assoc] },
rw [β coe_mul, nnreal.mul_inv_cancel hr, coe_one, one_mul, mul_comm]
end
lemma div_le_iff_le_mul (hb0 : b β 0) (hbt : b β β€) : a / b β€ c β a β€ c * b :=
suffices a * bβ»ΒΉ β€ c β a β€ c / bβ»ΒΉ, by simpa [div_def],
(le_div_iff_mul_le (inv_ne_zero.2 hbt) (inv_ne_top.2 hb0)).symm
lemma inv_le_iff_le_mul : (b = β€ β a β 0) β (a = β€ β b β 0) β (aβ»ΒΉ β€ b β 1 β€ a * b) :=
begin
cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt},
by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le]
end
@[simp] lemma le_inv_iff_mul_le : a β€ bβ»ΒΉ β a * b β€ 1 :=
begin
cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] },
by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le],
suffices : a β€ 1 / b β a * b β€ 1, { simpa [div_def, h] },
exact le_div_iff_mul_le (mt coe_eq_coe.1 h) coe_ne_top
end
lemma mul_inv_cancel : β{r : ennreal}, r β 0 β r β β€ β r * rβ»ΒΉ = 1 :=
begin
refine forall_ennreal.2 β¨Ξ» r, _, _β©; simp [-coe_inv, (coe_inv _).symm] {contextual := tt},
assume h, rw [β ennreal.coe_mul, nnreal.mul_inv_cancel h, coe_one]
end
lemma mul_le_if_le_inv {a b r : ennreal} (hrβ : r β 0) (hrβ : r β β€) : (r * a β€ b β a β€ rβ»ΒΉ * b) :=
by rw [β @ennreal.mul_le_mul_left _ a _ hrβ hrβ, β mul_assoc, mul_inv_cancel hrβ hrβ, one_mul]
lemma le_of_forall_lt_one_mul_lt : β{x y : ennreal}, (βa<1, a * x β€ y) β x β€ y :=
forall_ennreal.2 $ and.intro
(assume r, forall_ennreal.2 $ and.intro
(assume q h, coe_le_coe.2 $ nnreal.le_of_forall_lt_one_mul_lt $ assume a ha,
begin rw [β coe_le_coe, coe_mul], exact h _ (coe_lt_coe.2 ha) end)
(assume h, le_top))
(assume r hr,
have ((1 / 2 : nnreal) : ennreal) * β€ β€ r :=
hr _ (coe_lt_coe.2 ((@nnreal.coe_lt (1/2) 1).2 one_half_lt_one)),
have ne : ((1 / 2 : nnreal) : ennreal) β 0,
begin
rw [(β ), coe_eq_zero],
refine zero_lt_iff_ne_zero.1 _,
show 0 < (1 / 2 : β),
exact div_pos zero_lt_one two_pos
end,
by rwa [mul_top, if_neg ne] at this)
lemma div_add_div_same {a b c : ennreal} : a / c + b / c = (a + b) / c :=
eq.symm $ right_distrib a b (cβ»ΒΉ)
lemma div_self {a : ennreal} (h0 : a β 0) (hI : a β β) : a / a = 1 :=
have A : 1 β€ a / a := by simp [le_div_iff_mul_le h0 hI, le_refl],
have B : a / a β€ 1 := by simp [div_le_iff_le_mul h0 hI, le_refl],
le_antisymm B A
lemma add_halves (a : ennreal) : a / 2 + a / 2 = a :=
have Β¬((2 : nnreal) : ennreal) = (0 : nnreal) := by rw [coe_eq_coe]; norm_num,
have A : (2:ennreal) * 2β»ΒΉ = 1 := by rw [βdiv_def, div_self]; [assumption, apply coe_ne_top],
calc
a / 2 + a / 2 = (a + a) / 2 : by rw div_add_div_same
... = (a * 1 + a * 1) / 2 : by rw mul_one
... = (a * (1 + 1)) / 2 : by rw left_distrib
... = (a * 2) / 2 : by rw one_add_one_eq_two
... = (a * 2) * 2β»ΒΉ : by rw div_def
... = a * (2 * 2β»ΒΉ) : by rw mul_assoc
... = a * 1 : by rw A
... = a : by rw mul_one
@[simp] lemma div_zero_iff {a b : ennreal} : a / b = 0 β a = 0 β¨ b = β€ :=
by simp [div_def, mul_eq_zero]
@[simp] lemma div_pos_iff {a b : ennreal} : 0 < a / b β a β 0 β§ b β β€ :=
by simp [zero_lt_iff_ne_zero, not_or_distrib]
lemma half_pos {a : ennreal} (h : 0 < a) : 0 < a / 2 :=
by simp [ne_of_gt h]
lemma half_lt_self {a : ennreal} (hz : a β 0) (ht : a β β€) : a / 2 < a :=
begin
cases a,
{ cases ht none_eq_top },
{ simp [some_eq_coe] at hz,
simpa [-coe_lt_coe, coe_div two_ne_zero'] using
coe_lt_coe.2 (nnreal.half_lt_self hz) }
end
lemma exists_inv_nat_lt {a : ennreal} (h : a β 0) :
βn:β, (n:ennreal)β»ΒΉ < a :=
begin
rcases dense (bot_lt_iff_ne_bot.2 h) with β¨b, bz, baβ©,
have bz' : b β 0 := bot_lt_iff_ne_bot.1 bz,
have : bβ»ΒΉ β β€ := by simp [bz'],
rcases ennreal.exists_nat_gt this with β¨n, bnβ©,
have I : ((n : β) : ennreal)β»ΒΉ β€ b := begin
rw [ennreal.inv_le_iff_le_mul, mul_comm, β ennreal.inv_le_iff_le_mul],
exact le_of_lt bn,
simp only [h, ennreal.nat_ne_top, forall_prop_of_false, ne.def, not_false_iff],
exact Ξ»_, ne_bot_of_gt bn,
exact Ξ»_, ne_bot_of_gt bn,
exact Ξ»_, bz'
end,
exact β¨n, lt_of_le_of_lt I baβ©
end
end inv
section real
lemma to_real_add (ha : a β β€) (hb : b β β€) : (a+b).to_real = a.to_real + b.to_real :=
begin
cases a,
{ simpa [none_eq_top] using ha },
cases b,
{ simpa [none_eq_top] using hb },
refl
end
lemma of_real_add {p q : β} (hp : 0 β€ p) (hq : 0 β€ q) :
ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q :=
by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, β coe_add,
coe_eq_coe, nnreal.of_real_add hp hq]
@[simp] lemma to_real_le_to_real (ha : a β β€) (hb : b β β€) : a.to_real β€ b.to_real β a β€ b :=
begin
cases a,
{ simpa [none_eq_top] using ha },
cases b,
{ simpa [none_eq_top] using hb },
simp only [ennreal.to_real, nnreal.coe_le.symm, with_top.some_le_some],
refl
end
@[simp] lemma to_real_lt_to_real (ha : a β β€) (hb : b β β€) : a.to_real < b.to_real β a < b :=
begin
cases a,
{ simpa [none_eq_top] using ha },
cases b,
{ simpa [none_eq_top] using hb },
rw [with_top.some_lt_some],
refl
end
lemma of_real_le_of_real {p q : β} (h : p β€ q) : ennreal.of_real p β€ ennreal.of_real q :=
by simp [ennreal.of_real, nnreal.of_real_le_of_real h]
@[simp] lemma of_real_le_of_real_iff {p q : β} (h : 0 β€ q) : ennreal.of_real p β€ ennreal.of_real q β p β€ q :=
by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, nnreal.of_real_le_of_real_iff h]
@[simp] lemma of_real_lt_of_real_iff {p q : β} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q β p < q :=
by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff h]
@[simp] lemma of_real_pos {p : β} : 0 < ennreal.of_real p β 0 < p :=
by simp [ennreal.of_real]
@[simp] lemma of_real_eq_zero {p : β} : ennreal.of_real p = 0 β p β€ 0 :=
by simp [ennreal.of_real]
end real
section infi
variables {ΞΉ : Sort*} {f g : ΞΉ β ennreal}
lemma infi_add : infi f + a = β¨
i, f i + a :=
le_antisymm
(le_infi $ assume i, add_le_add' (infi_le _ _) $ le_refl _)
(ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _)
lemma supr_sub : (β¨i, f i) - a = (β¨i, f i - a) :=
le_antisymm
(ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i)
(supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a))
lemma sub_infi : a - (β¨
i, f i) = (β¨i, a - f i) :=
begin
refine (eq_of_forall_ge_iff $ Ξ» c, _),
rw [ennreal.sub_le_iff_le_add, add_comm, infi_add],
simp [ennreal.sub_le_iff_le_add]
end
lemma Inf_add {s : set ennreal} : Inf s + a = β¨
bβs, b + a :=
by simp [Inf_eq_infi, infi_add]
lemma add_infi {a : ennreal} : a + infi f = β¨
b, a + f b :=
by rw [add_comm, infi_add]; simp
lemma infi_add_infi (h : βi j, βk, f k + g k β€ f i + g j) : infi f + infi g = (β¨
a, f a + g a) :=
suffices (β¨
a, f a + g a) β€ infi f + infi g,
from le_antisymm (le_infi $ assume a, add_le_add' (infi_le _ _) (infi_le _ _)) this,
calc (β¨
a, f a + g a) β€ (β¨
a a', f a + g a') :
le_infi $ assume a, le_infi $ assume a',
let β¨k, hβ© := h a a' in infi_le_of_le k h
... β€ infi f + infi g :
by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _
lemma infi_sum {f : ΞΉ β Ξ± β ennreal} {s : finset Ξ±} [nonempty ΞΉ]
(h : β(t : finset Ξ±) (i j : ΞΉ), βk, βaβt, f k a β€ f i a β§ f k a β€ f j a) :
(β¨
i, s.sum (f i)) = s.sum (Ξ»a, β¨
i, f i a) :=
finset.induction_on s (by simp) $ assume a s ha ih,
have β (i j : ΞΉ), β (k : ΞΉ), f k a + s.sum (f k) β€ f i a + s.sum (f j),
from assume i j,
let β¨k, hkβ© := h (insert a s) i j in
β¨k, add_le_add' (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum' $
assume a ha, (hk _ $ finset.mem_insert_of_mem ha).rightβ©,
by simp [ha, ih.symm, infi_add_infi this]
end infi
section supr
lemma supr_coe_nat : (β¨n:β, (n : ennreal)) = β€ :=
(lattice.supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb)
end supr
end ennreal
|
482d906c540b364cdfedd4488ae1f6a3b258ed5e | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/combinatorics/simple_graph/inc_matrix.lean | 359048d787636772d2cddea0c8491ba262ad90c9 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 6,822 | lean | /-
Copyright (c) 2021 Gabriel Moise. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Moise, YaΓ«l Dillies, Kyle Miller
-/
import combinatorics.simple_graph.basic
import data.matrix.basic
/-!
# Incidence matrix of a simple graph
This file defines the unoriented incidence matrix of a simple graph.
## Main definitions
* `simple_graph.inc_matrix`: `G.inc_matrix R` is the incidence matrix of `G` over the ring `R`.
## Main results
* `simple_graph.inc_matrix_mul_transpose_diag`: The diagonal entries of the product of
`G.inc_matrix R` and its transpose are the degrees of the vertices.
* `simple_graph.inc_matrix_mul_transpose`: Gives a complete description of the product of
`G.inc_matrix R` and its transpose; the diagonal is the degrees of each vertex, and the
off-diagonals are 1 or 0 depending on whether or not the vertices are adjacent.
* `simple_graph.inc_matrix_transpose_mul_diag`: The diagonal entries of the product of the
transpose of `G.inc_matrix R` and `G.inc_matrix R` are `2` or `0` depending on whether or
not the unordered pair is an edge of `G`.
## Implementation notes
The usual definition of an incidence matrix has one row per vertex and one column per edge.
However, this definition has columns indexed by all of `sym2 Ξ±`, where `Ξ±` is the vertex type.
This appears not to change the theory, and for simple graphs it has the nice effect that every
incidence matrix for each `simple_graph Ξ±` has the same type.
## TODO
* Define the oriented incidence matrices for oriented graphs.
* Define the graph Laplacian of a simple graph using the oriented incidence matrix from an
arbitrary orientation of a simple graph.
-/
open finset matrix simple_graph sym2
open_locale big_operators matrix
namespace simple_graph
variables (R : Type*) {Ξ± : Type*} (G : simple_graph Ξ±)
/-- `G.inc_matrix R` is the `Ξ± Γ sym2 Ξ±` matrix whose `(a, e)`-entry is `1` if `e` is incident to
`a` and `0` otherwise. -/
noncomputable def inc_matrix [has_zero R] [has_one R] : matrix Ξ± (sym2 Ξ±) R :=
Ξ» a, (G.incidence_set a).indicator 1
variables {R}
lemma inc_matrix_apply [has_zero R] [has_one R] {a : Ξ±} {e : sym2 Ξ±} :
G.inc_matrix R a e = (G.incidence_set a).indicator 1 e := rfl
/-- Entries of the incidence matrix can be computed given additional decidable instances. -/
lemma inc_matrix_apply' [has_zero R] [has_one R] [decidable_eq Ξ±] [decidable_rel G.adj]
{a : Ξ±} {e : sym2 Ξ±} :
G.inc_matrix R a e = if e β G.incidence_set a then 1 else 0 :=
by convert rfl
section mul_zero_one_class
variables [mul_zero_one_class R] {a b : Ξ±} {e : sym2 Ξ±}
lemma inc_matrix_apply_mul_inc_matrix_apply :
G.inc_matrix R a e * G.inc_matrix R b e = (G.incidence_set a β© G.incidence_set b).indicator 1 e :=
begin
classical,
simp only [inc_matrix, set.indicator_apply, βite_and_mul_zero,
pi.one_apply, mul_one, set.mem_inter_eq],
end
lemma inc_matrix_apply_mul_inc_matrix_apply_of_not_adj (hab : a β b) (h : Β¬ G.adj a b) :
G.inc_matrix R a e * G.inc_matrix R b e = 0 :=
begin
rw [inc_matrix_apply_mul_inc_matrix_apply, set.indicator_of_not_mem],
rw [G.incidence_set_inter_incidence_set_of_not_adj h hab],
exact set.not_mem_empty e,
end
lemma inc_matrix_of_not_mem_incidence_set (h : e β G.incidence_set a) :
G.inc_matrix R a e = 0 :=
by rw [inc_matrix_apply, set.indicator_of_not_mem h]
lemma inc_matrix_of_mem_incidence_set (h : e β G.incidence_set a) : G.inc_matrix R a e = 1 :=
by rw [inc_matrix_apply, set.indicator_of_mem h, pi.one_apply]
variables [nontrivial R]
lemma inc_matrix_apply_eq_zero_iff : G.inc_matrix R a e = 0 β e β G.incidence_set a :=
begin
simp only [inc_matrix_apply, set.indicator_apply_eq_zero, pi.one_apply, one_ne_zero],
exact iff.rfl,
end
lemma inc_matrix_apply_eq_one_iff : G.inc_matrix R a e = 1 β e β G.incidence_set a :=
by { convert one_ne_zero.ite_eq_left_iff, assumption }
end mul_zero_one_class
section non_assoc_semiring
variables [fintype Ξ±] [non_assoc_semiring R] {a b : Ξ±} {e : sym2 Ξ±}
lemma sum_inc_matrix_apply [decidable_eq Ξ±] [decidable_rel G.adj] :
β e, G.inc_matrix R a e = G.degree a :=
by simp [inc_matrix_apply', sum_boole, set.filter_mem_univ_eq_to_finset]
lemma inc_matrix_mul_transpose_diag [decidable_eq Ξ±] [decidable_rel G.adj] :
(G.inc_matrix R β¬ (G.inc_matrix R)α΅) a a = G.degree a :=
begin
rw βsum_inc_matrix_apply,
simp [matrix.mul_apply, inc_matrix_apply', βite_and_mul_zero],
end
lemma sum_inc_matrix_apply_of_mem_edge_set : e β G.edge_set β β a, G.inc_matrix R a e = 2 :=
begin
classical,
refine e.ind _,
intros a b h,
rw mem_edge_set at h,
rw [βnat.cast_two, βcard_doubleton h.ne],
simp only [inc_matrix_apply', sum_boole, mk_mem_incidence_set_iff, h, true_and],
congr' 2,
ext e,
simp only [mem_filter, mem_univ, true_and, mem_insert, mem_singleton],
end
lemma sum_inc_matrix_apply_of_not_mem_edge_set (h : e β G.edge_set) : β a, G.inc_matrix R a e = 0 :=
sum_eq_zero $ Ξ» a _, G.inc_matrix_of_not_mem_incidence_set $ Ξ» he, h he.1
lemma inc_matrix_transpose_mul_diag [decidable_rel G.adj] :
((G.inc_matrix R)α΅ β¬ G.inc_matrix R) e e = if e β G.edge_set then 2 else 0 :=
begin
classical,
simp only [matrix.mul_apply, inc_matrix_apply', transpose_apply, βite_and_mul_zero,
one_mul, sum_boole, and_self],
split_ifs with h,
{ revert h,
refine e.ind _,
intros v w h,
rw [βnat.cast_two, βcard_doubleton (G.ne_of_adj h)],
simp [mk_mem_incidence_set_iff, G.mem_edge_set.mp h],
congr' 2,
ext u,
simp, },
{ revert h,
refine e.ind _,
intros v w h,
simp [mk_mem_incidence_set_iff, G.mem_edge_set.not.mp h], },
end
end non_assoc_semiring
section semiring
variables [fintype (sym2 Ξ±)] [semiring R] {a b : Ξ±} {e : sym2 Ξ±}
lemma inc_matrix_mul_transpose_apply_of_adj (h : G.adj a b) :
(G.inc_matrix R β¬ (G.inc_matrix R)α΅) a b = (1 : R) :=
begin
classical,
simp_rw [matrix.mul_apply, matrix.transpose_apply, inc_matrix_apply_mul_inc_matrix_apply,
set.indicator_apply, pi.one_apply, sum_boole],
convert nat.cast_one,
convert card_singleton β¦(a, b)β§,
rw [βcoe_eq_singleton, coe_filter_univ],
exact G.incidence_set_inter_incidence_set_of_adj h,
end
lemma inc_matrix_mul_transpose [fintype Ξ±] [decidable_eq Ξ±] [decidable_rel G.adj] :
G.inc_matrix R β¬ (G.inc_matrix R)α΅ = Ξ» a b,
if a = b then G.degree a else if G.adj a b then 1 else 0 :=
begin
ext a b,
split_ifs with h h',
{ subst b,
convert G.inc_matrix_mul_transpose_diag },
{ exact G.inc_matrix_mul_transpose_apply_of_adj h' },
{ simp only [matrix.mul_apply, matrix.transpose_apply,
G.inc_matrix_apply_mul_inc_matrix_apply_of_not_adj h h', sum_const_zero] }
end
end semiring
end simple_graph
|
377a3eab958d5d79cec9e3a90536437ea35dc5b7 | 026eca3e4f104406f03192524c0ebed8b40e468b | /library/init/data/int/order.lean | f0ce4a351ffd208e393964119467c483af02c74e | [
"Apache-2.0"
] | permissive | jpablo/lean | 99bebe8f1c3e3df37e19fc4af27d4261efa40bc6 | bec8f0688552bc64f9c08fe0459f3fb20f93cb33 | refs/heads/master | 1,679,677,848,004 | 1,615,913,211,000 | 1,615,913,211,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 37,014 | 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 order relation on the integers.
-/
prelude
import init.data.int.basic init.data.ordering.basic
namespace int
def nonneg (a : β€) : Prop := int.cases_on a (assume n, true) (assume n, false)
protected def le (a b : β€) : Prop := nonneg (b - a)
instance : has_le int := β¨int.leβ©
protected def lt (a b : β€) : Prop := (a + 1) β€ b
instance : has_lt int := β¨int.ltβ©
def decidable_nonneg (a : β€) : decidable (nonneg a) :=
int.cases_on a (assume a, decidable.true) (assume a, decidable.false)
instance decidable_le (a b : β€) : decidable (a β€ b) := decidable_nonneg _
instance decidable_lt (a b : β€) : decidable (a < b) := decidable_nonneg _
lemma lt_iff_add_one_le (a b : β€) : a < b β a + 1 β€ b := iff.refl _
lemma nonneg.elim {a : β€} : nonneg a β β n : β, a = n :=
int.cases_on a (assume n H, exists.intro n rfl) (assume n', false.elim)
lemma nonneg_or_nonneg_neg (a : β€) : nonneg a β¨ nonneg (-a) :=
int.cases_on a (assume n, or.inl trivial) (assume n, or.inr trivial)
lemma le.intro_sub {a b : β€} {n : β} (h : b - a = n) : a β€ b :=
show nonneg (b - a), by rw h; trivial
local attribute [simp] int.sub_eq_add_neg int.add_assoc int.add_right_neg int.add_left_neg
int.zero_add int.add_zero int.neg_add int.neg_neg int.neg_zero
lemma le.intro {a b : β€} {n : β} (h : a + n = b) : a β€ b :=
le.intro_sub (by rw [β h, int.add_comm]; simp)
lemma le.dest_sub {a b : β€} (h : a β€ b) : β n : β, b - a = n := nonneg.elim h
lemma le.dest {a b : β€} (h : a β€ b) : β n : β, a + n = b :=
match (le.dest_sub h) with
| β¨n, hββ© := exists.intro n begin rw [β hβ, int.add_comm], simp end
end
lemma le.elim {a b : β€} (h : a β€ b) {P : Prop} (h' : β n : β, a + βn = b β P) : P :=
exists.elim (le.dest h) h'
protected lemma le_total (a b : β€) : a β€ b β¨ b β€ a :=
or.imp_right
(assume H : nonneg (-(b - a)),
have -(b - a) = a - b, by simp [int.add_comm],
show nonneg (a - b), from this βΈ H)
(nonneg_or_nonneg_neg (b - a))
lemma coe_nat_le_coe_nat_of_le {m n : β} (h : m β€ n) : (βm : β€) β€ βn :=
match nat.le.dest h with
| β¨k, (hk : m + k = n)β© := le.intro (begin rw [β hk], reflexivity end)
end
lemma le_of_coe_nat_le_coe_nat {m n : β} (h : (βm : β€) β€ βn) : m β€ n :=
le.elim h (assume k, assume hk : βm + βk = βn,
have m + k = n, from int.coe_nat_inj ((int.coe_nat_add m k).trans hk),
nat.le.intro this)
lemma coe_nat_le_coe_nat_iff (m n : β) : (βm : β€) β€ βn β m β€ n :=
iff.intro le_of_coe_nat_le_coe_nat coe_nat_le_coe_nat_of_le
lemma coe_zero_le (n : β) : 0 β€ (βn : β€) :=
coe_nat_le_coe_nat_of_le n.zero_le
lemma eq_coe_of_zero_le {a : β€} (h : 0 β€ a) : β n : β, a = n :=
by { have t := le.dest_sub h, simp at t, exact t }
lemma eq_succ_of_zero_lt {a : β€} (h : 0 < a) : β n : β, a = n.succ :=
let β¨n, (h : β(1+n) = a)β© := le.dest h in
β¨n, by rw nat.add_comm at h; exact h.symmβ©
lemma lt_add_succ (a : β€) (n : β) : a < a + β(nat.succ n) :=
le.intro (show a + 1 + n = a + nat.succ n,
by { simp [int.coe_nat_eq, int.add_comm, int.add_left_comm], reflexivity })
lemma lt.intro {a b : β€} {n : β} (h : a + nat.succ n = b) : a < b :=
h βΈ lt_add_succ a n
lemma lt.dest {a b : β€} (h : a < b) : β n : β, a + β(nat.succ n) = b :=
le.elim h (assume n, assume hn : a + 1 + n = b,
exists.intro n begin rw [β hn, int.add_assoc, int.add_comm 1], reflexivity end)
lemma lt.elim {a b : β€} (h : a < b) {P : Prop} (h' : β n : β, a + β(nat.succ n) = b β P) : P :=
exists.elim (lt.dest h) h'
lemma coe_nat_lt_coe_nat_iff (n m : β) : (βn : β€) < βm β n < m :=
begin rw [lt_iff_add_one_le, β int.coe_nat_succ, coe_nat_le_coe_nat_iff], reflexivity end
lemma lt_of_coe_nat_lt_coe_nat {m n : β} (h : (βm : β€) < βn) : m < n :=
(coe_nat_lt_coe_nat_iff _ _).mp h
lemma coe_nat_lt_coe_nat_of_lt {m n : β} (h : m < n) : (βm : β€) < βn :=
(coe_nat_lt_coe_nat_iff _ _).mpr h
/- show that the integers form an ordered additive group -/
protected lemma le_refl (a : β€) : a β€ a :=
le.intro (int.add_zero a)
protected lemma le_trans {a b c : β€} (hβ : a β€ b) (hβ : b β€ c) : a β€ c :=
le.elim hβ (assume n, assume hn : a + n = b,
le.elim hβ (assume m, assume hm : b + m = c,
begin apply le.intro, rw [β hm, β hn, int.add_assoc], reflexivity end))
protected lemma le_antisymm {a b : β€} (hβ : a β€ b) (hβ : b β€ a) : a = b :=
le.elim hβ (assume n, assume hn : a + n = b,
le.elim hβ (assume m, assume hm : b + m = a,
have a + β(n + m) = a + 0, by rw [int.coe_nat_add, β int.add_assoc, hn, hm, int.add_zero a],
have (β(n + m) : β€) = 0, from int.add_left_cancel this,
have n + m = 0, from int.coe_nat_inj this,
have n = 0, from nat.eq_zero_of_add_eq_zero_right this,
show a = b, begin rw [β hn, this, int.coe_nat_zero, int.add_zero a] end))
protected lemma lt_irrefl (a : β€) : Β¬ a < a :=
assume : a < a,
lt.elim this (assume n, assume hn : a + nat.succ n = a,
have a + nat.succ n = a + 0, by rw [hn, int.add_zero],
have nat.succ n = 0, from int.coe_nat_inj (int.add_left_cancel this),
show false, from nat.succ_ne_zero _ this)
protected lemma ne_of_lt {a b : β€} (h : a < b) : a β b :=
(assume : a = b, absurd (begin rewrite this at h, exact h end) (int.lt_irrefl b))
lemma le_of_lt {a b : β€} (h : a < b) : a β€ b :=
lt.elim h (assume n, assume hn : a + nat.succ n = b, le.intro hn)
protected lemma lt_iff_le_and_ne (a b : β€) : a < b β (a β€ b β§ a β b) :=
iff.intro
(assume h, β¨le_of_lt h, int.ne_of_lt hβ©)
(assume β¨aleb, anebβ©,
le.elim aleb (assume n, assume hn : a + n = b,
have n β 0,
from (assume : n = 0, aneb begin rw [β hn, this, int.coe_nat_zero, int.add_zero] end),
have n = nat.succ (nat.pred n),
from eq.symm (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero this)),
lt.intro (begin rewrite this at hn, exact hn end)))
lemma lt_succ (a : β€) : a < a + 1 :=
int.le_refl (a + 1)
protected lemma add_le_add_left {a b : β€} (h : a β€ b) (c : β€) : c + a β€ c + b :=
le.elim h (assume n, assume hn : a + n = b,
le.intro (show c + a + n = c + b, begin rw [int.add_assoc, hn] end))
protected lemma add_lt_add_left {a b : β€} (h : a < b) (c : β€) : c + a < c + b :=
iff.mpr (int.lt_iff_le_and_ne _ _)
(and.intro
(int.add_le_add_left (le_of_lt h) _)
(assume heq, int.lt_irrefl b begin rw int.add_left_cancel heq at h, exact h end))
protected lemma mul_nonneg {a b : β€} (ha : 0 β€ a) (hb : 0 β€ b) : 0 β€ a * b :=
le.elim ha (assume n, assume hn,
le.elim hb (assume m, assume hm,
le.intro (show 0 + βn * βm = a * b, begin rw [β hn, β hm], simp [int.zero_add] end)))
protected lemma mul_pos {a b : β€} (ha : 0 < a) (hb : 0 < b) : 0 < a * b :=
lt.elim ha (assume n, assume hn,
lt.elim hb (assume m, assume hm,
lt.intro (show 0 + β(nat.succ (nat.succ n * m + n)) = a * b,
begin rw [β hn, β hm], simp [int.coe_nat_zero],
rw [β int.coe_nat_mul], simp [nat.mul_succ, nat.succ_add] end)))
protected lemma zero_lt_one : (0 : β€) < 1 := trivial
protected lemma lt_iff_le_not_le {a b : β€} : a < b β (a β€ b β§ Β¬ b β€ a) :=
begin
simp [int.lt_iff_le_and_ne], split; intro h,
{ cases h with hab hn, split,
{ assumption },
{ intro hba, simp [int.le_antisymm hab hba] at *, contradiction } },
{ cases h with hab hn, split,
{ assumption },
{ intro h, simp [*] at * } }
end
instance : linear_order int :=
{ le := int.le,
le_refl := int.le_refl,
le_trans := @int.le_trans,
le_antisymm := @int.le_antisymm,
lt := int.lt,
lt_iff_le_not_le := @int.lt_iff_le_not_le,
le_total := int.le_total,
decidable_eq := int.decidable_eq,
decidable_le := int.decidable_le,
decidable_lt := int.decidable_lt }
lemma eq_nat_abs_of_zero_le {a : β€} (h : 0 β€ a) : a = nat_abs a :=
let β¨n, eβ© := eq_coe_of_zero_le h in by rw e; refl
lemma le_nat_abs {a : β€} : a β€ nat_abs a :=
or.elim (le_total 0 a)
(Ξ»h, by rw eq_nat_abs_of_zero_le h; refl)
(Ξ»h, le_trans h (coe_zero_le _))
lemma neg_succ_lt_zero (n : β) : -[1+ n] < 0 :=
lt_of_not_ge $ Ξ» h, let β¨m, hβ© := eq_coe_of_zero_le h in by contradiction
lemma eq_neg_succ_of_lt_zero : β {a : β€}, a < 0 β β n : β, a = -[1+ n]
| (n : β) h := absurd h (not_lt_of_ge (coe_zero_le _))
| -[1+ n] h := β¨n, rflβ©
/- int is an ordered add comm group -/
protected lemma eq_neg_of_eq_neg {a b : β€} (h : a = -b) : b = -a :=
by rw [h, int.neg_neg]
protected lemma neg_add_cancel_left (a b : β€) : -a + (a + b) = b :=
by rw [β int.add_assoc, int.add_left_neg, int.zero_add]
protected lemma add_neg_cancel_left (a b : β€) : a + (-a + b) = b :=
by rw [β int.add_assoc, int.add_right_neg, int.zero_add]
protected lemma add_neg_cancel_right (a b : β€) : a + b + -b = a :=
by rw [int.add_assoc, int.add_right_neg, int.add_zero]
protected lemma neg_add_cancel_right (a b : β€) : a + -b + b = a :=
by rw [int.add_assoc, int.add_left_neg, int.add_zero]
protected lemma sub_self (a : β€) : a - a = 0 :=
by rw [int.sub_eq_add_neg, int.add_right_neg]
protected lemma sub_eq_zero_of_eq {a b : β€} (h : a = b) : a - b = 0 :=
by rw [h, int.sub_self]
protected lemma eq_of_sub_eq_zero {a b : β€} (h : a - b = 0) : a = b :=
have 0 + b = b, by rw int.zero_add,
have (a - b) + b = b, by rwa h,
by rwa [int.sub_eq_add_neg, int.neg_add_cancel_right] at this
protected lemma sub_eq_zero_iff_eq {a b : β€} : a - b = 0 β a = b :=
β¨int.eq_of_sub_eq_zero, int.sub_eq_zero_of_eqβ©
@[simp] protected lemma neg_eq_of_add_eq_zero {a b : β€} (h : a + b = 0) : -a = b :=
by rw [β int.add_zero (-a), βh, βint.add_assoc, int.add_left_neg, int.zero_add]
protected lemma neg_mul_eq_neg_mul (a b : β€) : -(a * b) = -a * b :=
int.neg_eq_of_add_eq_zero
begin rw [β int.distrib_right, int.add_right_neg, int.zero_mul] end
protected lemma neg_mul_eq_mul_neg (a b : β€) : -(a * b) = a * -b :=
int.neg_eq_of_add_eq_zero
begin rw [β int.distrib_left, int.add_right_neg, int.mul_zero] end
lemma neg_mul_eq_neg_mul_symm (a b : β€) : - a * b = - (a * b) :=
eq.symm (int.neg_mul_eq_neg_mul a b)
lemma mul_neg_eq_neg_mul_symm (a b : β€) : a * - b = - (a * b) :=
eq.symm (int.neg_mul_eq_mul_neg a b)
local attribute [simp] neg_mul_eq_neg_mul_symm mul_neg_eq_neg_mul_symm
protected lemma neg_mul_neg (a b : β€) : -a * -b = a * b :=
by simp
protected lemma neg_mul_comm (a b : β€) : -a * b = a * -b :=
by simp
protected lemma mul_sub (a b c : β€) : a * (b - c) = a * b - a * c :=
calc
a * (b - c) = a * b + a * -c : int.distrib_left a b (-c)
... = a * b - a * c : by simp
protected lemma sub_mul (a b c : β€) : (a - b) * c = a * c - b * c :=
calc
(a - b) * c = a * c + -b * c : int.distrib_right a (-b) c
... = a * c - b * c : by simp
section
protected lemma le_of_add_le_add_left {a b c : β€} (h : a + b β€ a + c) : b β€ c :=
have -a + (a + b) β€ -a + (a + c), from int.add_le_add_left h _,
begin simp [int.neg_add_cancel_left] at this, assumption end
protected lemma lt_of_add_lt_add_left {a b c : β€} (h : a + b < a + c) : b < c :=
have -a + (a + b) < -a + (a + c), from int.add_lt_add_left h _,
begin simp [int.neg_add_cancel_left] at this, assumption end
protected lemma add_le_add_right {a b : β€} (h : a β€ b) (c : β€) : a + c β€ b + c :=
int.add_comm c a βΈ int.add_comm c b βΈ int.add_le_add_left h c
protected theorem add_lt_add_right {a b : β€} (h : a < b) (c : β€) : a + c < b + c :=
begin
rw [int.add_comm a c, int.add_comm b c],
exact (int.add_lt_add_left h c)
end
protected lemma add_le_add {a b c d : β€} (hβ : a β€ b) (hβ : c β€ d) : a + c β€ b + d :=
le_trans (int.add_le_add_right hβ c) (int.add_le_add_left hβ b)
protected lemma le_add_of_nonneg_right {a b : β€} (h : 0 β€ b) : a β€ a + b :=
have a + b β₯ a + 0, from int.add_le_add_left h a,
by rwa int.add_zero at this
protected lemma le_add_of_nonneg_left {a b : β€} (h : 0 β€ b) : a β€ b + a :=
have 0 + a β€ b + a, from int.add_le_add_right h a,
by rwa int.zero_add at this
protected lemma add_lt_add {a b c d : β€} (hβ : a < b) (hβ : c < d) : a + c < b + d :=
lt_trans (int.add_lt_add_right hβ c) (int.add_lt_add_left hβ b)
protected lemma add_lt_add_of_le_of_lt {a b c d : β€} (hβ : a β€ b) (hβ : c < d) : a + c < b + d :=
lt_of_le_of_lt (int.add_le_add_right hβ c) (int.add_lt_add_left hβ b)
protected lemma add_lt_add_of_lt_of_le {a b c d : β€} (hβ : a < b) (hβ : c β€ d) : a + c < b + d :=
lt_of_lt_of_le (int.add_lt_add_right hβ c) (int.add_le_add_left hβ b)
protected lemma lt_add_of_pos_right (a : β€) {b : β€} (h : 0 < b) : a < a + b :=
have a + 0 < a + b, from int.add_lt_add_left h a,
by rwa [int.add_zero] at this
protected lemma lt_add_of_pos_left (a : β€) {b : β€} (h : 0 < b) : a < b + a :=
have 0 + a < b + a, from int.add_lt_add_right h a,
by rwa [int.zero_add] at this
protected lemma le_of_add_le_add_right {a b c : β€} (h : a + b β€ c + b) : a β€ c :=
int.le_of_add_le_add_left
(show b + a β€ b + c, begin rw [int.add_comm b a, int.add_comm b c], assumption end)
protected lemma lt_of_add_lt_add_right {a b c : β€} (h : a + b < c + b) : a < c :=
int.lt_of_add_lt_add_left
(show b + a < b + c, begin rw [int.add_comm b a, int.add_comm b c], assumption end)
-- here we start using properties of zero.
protected lemma add_nonneg {a b : β€} (ha : 0 β€ a) (hb : 0 β€ b) : 0 β€ a + b :=
int.zero_add (0:β€) βΈ (int.add_le_add ha hb)
protected lemma add_pos {a b : β€} (ha : 0 < a) (hb : 0 < b) : 0 < a + b :=
int.zero_add (0:β€) βΈ (int.add_lt_add ha hb)
protected lemma add_pos_of_pos_of_nonneg {a b : β€} (ha : 0 < a) (hb : 0 β€ b) : 0 < a + b :=
int.zero_add (0:β€) βΈ (int.add_lt_add_of_lt_of_le ha hb)
protected lemma add_pos_of_nonneg_of_pos {a b : β€} (ha : 0 β€ a) (hb : 0 < b) : 0 < a + b :=
int.zero_add (0:β€) βΈ (int.add_lt_add_of_le_of_lt ha hb)
protected lemma add_nonpos {a b : β€} (ha : a β€ 0) (hb : b β€ 0) : a + b β€ 0 :=
int.zero_add (0:β€) βΈ (int.add_le_add ha hb)
protected lemma add_neg {a b : β€} (ha : a < 0) (hb : b < 0) : a + b < 0 :=
int.zero_add (0:β€) βΈ (int.add_lt_add ha hb)
protected lemma add_neg_of_neg_of_nonpos {a b : β€} (ha : a < 0) (hb : b β€ 0) : a + b < 0 :=
int.zero_add (0:β€) βΈ (int.add_lt_add_of_lt_of_le ha hb)
protected lemma add_neg_of_nonpos_of_neg {a b : β€} (ha : a β€ 0) (hb : b < 0) : a + b < 0 :=
int.zero_add (0:β€) βΈ (int.add_lt_add_of_le_of_lt ha hb)
protected lemma lt_add_of_le_of_pos {a b c : β€} (hbc : b β€ c) (ha : 0 < a) : b < c + a :=
int.add_zero b βΈ int.add_lt_add_of_le_of_lt hbc ha
protected lemma sub_add_cancel (a b : β€) : a - b + b = a :=
int.neg_add_cancel_right a b
protected lemma add_sub_cancel (a b : β€) : a + b - b = a :=
int.add_neg_cancel_right a b
protected lemma add_sub_assoc (a b c : β€) : a + b - c = a + (b - c) :=
by rw [int.sub_eq_add_neg, int.add_assoc, βint.sub_eq_add_neg]
protected lemma neg_le_neg {a b : β€} (h : a β€ b) : -b β€ -a :=
have 0 β€ -a + b, from int.add_left_neg a βΈ int.add_le_add_left h (-a),
have 0 + -b β€ -a + b + -b, from int.add_le_add_right this (-b),
by rwa [int.add_neg_cancel_right, int.zero_add] at this
protected lemma le_of_neg_le_neg {a b : β€} (h : -b β€ -a) : a β€ b :=
suffices -(-a) β€ -(-b), from
begin simp [int.neg_neg] at this, assumption end,
int.neg_le_neg h
protected lemma nonneg_of_neg_nonpos {a : β€} (h : -a β€ 0) : 0 β€ a :=
have -a β€ -0, by rwa int.neg_zero,
int.le_of_neg_le_neg this
protected lemma neg_nonpos_of_nonneg {a : β€} (h : 0 β€ a) : -a β€ 0 :=
have -a β€ -0, from int.neg_le_neg h,
by rwa int.neg_zero at this
protected lemma nonpos_of_neg_nonneg {a : β€} (h : 0 β€ -a) : a β€ 0 :=
have -0 β€ -a, by rwa int.neg_zero,
int.le_of_neg_le_neg this
protected lemma neg_nonneg_of_nonpos {a : β€} (h : a β€ 0) : 0 β€ -a :=
have -0 β€ -a, from int.neg_le_neg h,
by rwa int.neg_zero at this
protected lemma neg_lt_neg {a b : β€} (h : a < b) : -b < -a :=
have 0 < -a + b, from int.add_left_neg a βΈ int.add_lt_add_left h (-a),
have 0 + -b < -a + b + -b, from int.add_lt_add_right this (-b),
by rwa [int.add_neg_cancel_right, int.zero_add] at this
protected lemma lt_of_neg_lt_neg {a b : β€} (h : -b < -a) : a < b :=
int.neg_neg a βΈ int.neg_neg b βΈ int.neg_lt_neg h
protected lemma pos_of_neg_neg {a : β€} (h : -a < 0) : 0 < a :=
have -a < -0, by rwa int.neg_zero,
int.lt_of_neg_lt_neg this
protected lemma neg_neg_of_pos {a : β€} (h : 0 < a) : -a < 0 :=
have -a < -0, from int.neg_lt_neg h,
by rwa int.neg_zero at this
protected lemma neg_of_neg_pos {a : β€} (h : 0 < -a) : a < 0 :=
have -0 < -a, by rwa int.neg_zero,
int.lt_of_neg_lt_neg this
protected lemma neg_pos_of_neg {a : β€} (h : a < 0) : 0 < -a :=
have -0 < -a, from int.neg_lt_neg h,
by rwa int.neg_zero at this
protected lemma le_neg_of_le_neg {a b : β€} (h : a β€ -b) : b β€ -a :=
begin
have h := int.neg_le_neg h,
rwa int.neg_neg at h
end
protected lemma neg_le_of_neg_le {a b : β€} (h : -a β€ b) : -b β€ a :=
begin
have h := int.neg_le_neg h,
rwa int.neg_neg at h
end
protected lemma lt_neg_of_lt_neg {a b : β€} (h : a < -b) : b < -a :=
begin
have h := int.neg_lt_neg h,
rwa int.neg_neg at h
end
protected lemma neg_lt_of_neg_lt {a b : β€} (h : -a < b) : -b < a :=
begin
have h := int.neg_lt_neg h,
rwa int.neg_neg at h
end
protected lemma sub_nonneg_of_le {a b : β€} (h : b β€ a) : 0 β€ a - b :=
begin
have h := int.add_le_add_right h (-b),
rwa int.add_right_neg at h
end
protected lemma le_of_sub_nonneg {a b : β€} (h : 0 β€ a - b) : b β€ a :=
begin
have h := int.add_le_add_right h b,
rwa [int.sub_add_cancel, int.zero_add] at h
end
protected lemma sub_nonpos_of_le {a b : β€} (h : a β€ b) : a - b β€ 0 :=
begin
have h := int.add_le_add_right h (-b),
rwa int.add_right_neg at h
end
protected lemma le_of_sub_nonpos {a b : β€} (h : a - b β€ 0) : a β€ b :=
begin
have h := int.add_le_add_right h b,
rwa [int.sub_add_cancel, int.zero_add] at h
end
protected lemma sub_pos_of_lt {a b : β€} (h : b < a) : 0 < a - b :=
begin
have h := int.add_lt_add_right h (-b),
rwa int.add_right_neg at h
end
protected lemma lt_of_sub_pos {a b : β€} (h : 0 < a - b) : b < a :=
begin
have h := int.add_lt_add_right h b,
rwa [int.sub_add_cancel, int.zero_add] at h
end
protected lemma sub_neg_of_lt {a b : β€} (h : a < b) : a - b < 0 :=
begin
have h := int.add_lt_add_right h (-b),
rwa int.add_right_neg at h
end
protected lemma lt_of_sub_neg {a b : β€} (h : a - b < 0) : a < b :=
begin
have h := int.add_lt_add_right h b,
rwa [int.sub_add_cancel, int.zero_add] at h
end
protected lemma add_le_of_le_neg_add {a b c : β€} (h : b β€ -a + c) : a + b β€ c :=
begin
have h := int.add_le_add_left h a,
rwa int.add_neg_cancel_left at h
end
protected lemma le_neg_add_of_add_le {a b c : β€} (h : a + b β€ c) : b β€ -a + c :=
begin
have h := int.add_le_add_left h (-a),
rwa int.neg_add_cancel_left at h
end
protected lemma add_le_of_le_sub_left {a b c : β€} (h : b β€ c - a) : a + b β€ c :=
begin
have h := int.add_le_add_left h a,
rwa [β int.add_sub_assoc, int.add_comm a c, int.add_sub_cancel] at h
end
protected lemma le_sub_left_of_add_le {a b c : β€} (h : a + b β€ c) : b β€ c - a :=
begin
have h := int.add_le_add_right h (-a),
rwa [int.add_comm a b, int.add_neg_cancel_right] at h
end
protected lemma add_le_of_le_sub_right {a b c : β€} (h : a β€ c - b) : a + b β€ c :=
begin
have h := int.add_le_add_right h b,
rwa int.sub_add_cancel at h
end
protected lemma le_sub_right_of_add_le {a b c : β€} (h : a + b β€ c) : a β€ c - b :=
begin
have h := int.add_le_add_right h (-b),
rwa int.add_neg_cancel_right at h
end
protected lemma le_add_of_neg_add_le {a b c : β€} (h : -b + a β€ c) : a β€ b + c :=
begin
have h := int.add_le_add_left h b,
rwa int.add_neg_cancel_left at h
end
protected lemma neg_add_le_of_le_add {a b c : β€} (h : a β€ b + c) : -b + a β€ c :=
begin
have h := int.add_le_add_left h (-b),
rwa int.neg_add_cancel_left at h
end
protected lemma le_add_of_sub_left_le {a b c : β€} (h : a - b β€ c) : a β€ b + c :=
begin
have h := int.add_le_add_right h b,
rwa [int.sub_add_cancel, int.add_comm] at h
end
protected lemma sub_left_le_of_le_add {a b c : β€} (h : a β€ b + c) : a - b β€ c :=
begin
have h := int.add_le_add_right h (-b),
rwa [int.add_comm b c, int.add_neg_cancel_right] at h
end
protected lemma le_add_of_sub_right_le {a b c : β€} (h : a - c β€ b) : a β€ b + c :=
begin
have h := int.add_le_add_right h c,
rwa int.sub_add_cancel at h
end
protected lemma sub_right_le_of_le_add {a b c : β€} (h : a β€ b + c) : a - c β€ b :=
begin
have h := int.add_le_add_right h (-c),
rwa int.add_neg_cancel_right at h
end
protected lemma le_add_of_neg_add_le_left {a b c : β€} (h : -b + a β€ c) : a β€ b + c :=
begin
rw int.add_comm at h,
exact int.le_add_of_sub_left_le h
end
protected lemma neg_add_le_left_of_le_add {a b c : β€} (h : a β€ b + c) : -b + a β€ c :=
begin
rw int.add_comm,
exact int.sub_left_le_of_le_add h
end
protected lemma le_add_of_neg_add_le_right {a b c : β€} (h : -c + a β€ b) : a β€ b + c :=
begin
rw int.add_comm at h,
exact int.le_add_of_sub_right_le h
end
protected lemma neg_add_le_right_of_le_add {a b c : β€} (h : a β€ b + c) : -c + a β€ b :=
begin
rw int.add_comm at h,
exact int.neg_add_le_left_of_le_add h
end
protected lemma le_add_of_neg_le_sub_left {a b c : β€} (h : -a β€ b - c) : c β€ a + b :=
int.le_add_of_neg_add_le_left (int.add_le_of_le_sub_right h)
protected lemma neg_le_sub_left_of_le_add {a b c : β€} (h : c β€ a + b) : -a β€ b - c :=
begin
have h := int.le_neg_add_of_add_le (int.sub_left_le_of_le_add h),
rwa int.add_comm at h
end
protected lemma le_add_of_neg_le_sub_right {a b c : β€} (h : -b β€ a - c) : c β€ a + b :=
int.le_add_of_sub_right_le (int.add_le_of_le_sub_left h)
protected lemma neg_le_sub_right_of_le_add {a b c : β€} (h : c β€ a + b) : -b β€ a - c :=
int.le_sub_left_of_add_le (int.sub_right_le_of_le_add h)
protected lemma sub_le_of_sub_le {a b c : β€} (h : a - b β€ c) : a - c β€ b :=
int.sub_left_le_of_le_add (int.le_add_of_sub_right_le h)
protected lemma sub_le_sub_left {a b : β€} (h : a β€ b) (c : β€) : c - b β€ c - a :=
int.add_le_add_left (int.neg_le_neg h) c
protected lemma sub_le_sub_right {a b : β€} (h : a β€ b) (c : β€) : a - c β€ b - c :=
int.add_le_add_right h (-c)
protected lemma sub_le_sub {a b c d : β€} (hab : a β€ b) (hcd : c β€ d) : a - d β€ b - c :=
int.add_le_add hab (int.neg_le_neg hcd)
protected lemma add_lt_of_lt_neg_add {a b c : β€} (h : b < -a + c) : a + b < c :=
begin
have h := int.add_lt_add_left h a,
rwa int.add_neg_cancel_left at h
end
protected lemma lt_neg_add_of_add_lt {a b c : β€} (h : a + b < c) : b < -a + c :=
begin
have h := int.add_lt_add_left h (-a),
rwa int.neg_add_cancel_left at h
end
protected lemma add_lt_of_lt_sub_left {a b c : β€} (h : b < c - a) : a + b < c :=
begin
have h := int.add_lt_add_left h a,
rwa [β int.add_sub_assoc, int.add_comm a c, int.add_sub_cancel] at h
end
protected lemma lt_sub_left_of_add_lt {a b c : β€} (h : a + b < c) : b < c - a :=
begin
have h := int.add_lt_add_right h (-a),
rwa [int.add_comm a b, int.add_neg_cancel_right] at h
end
protected lemma add_lt_of_lt_sub_right {a b c : β€} (h : a < c - b) : a + b < c :=
begin
have h := int.add_lt_add_right h b,
rwa int.sub_add_cancel at h
end
protected lemma lt_sub_right_of_add_lt {a b c : β€} (h : a + b < c) : a < c - b :=
begin
have h := int.add_lt_add_right h (-b),
rwa int.add_neg_cancel_right at h
end
protected lemma lt_add_of_neg_add_lt {a b c : β€} (h : -b + a < c) : a < b + c :=
begin
have h := int.add_lt_add_left h b,
rwa int.add_neg_cancel_left at h
end
protected lemma neg_add_lt_of_lt_add {a b c : β€} (h : a < b + c) : -b + a < c :=
begin
have h := int.add_lt_add_left h (-b),
rwa int.neg_add_cancel_left at h
end
protected lemma lt_add_of_sub_left_lt {a b c : β€} (h : a - b < c) : a < b + c :=
begin
have h := int.add_lt_add_right h b,
rwa [int.sub_add_cancel, int.add_comm] at h
end
protected lemma sub_left_lt_of_lt_add {a b c : β€} (h : a < b + c) : a - b < c :=
begin
have h := int.add_lt_add_right h (-b),
rwa [int.add_comm b c, int.add_neg_cancel_right] at h
end
protected lemma lt_add_of_sub_right_lt {a b c : β€} (h : a - c < b) : a < b + c :=
begin
have h := int.add_lt_add_right h c,
rwa int.sub_add_cancel at h
end
protected lemma sub_right_lt_of_lt_add {a b c : β€} (h : a < b + c) : a - c < b :=
begin
have h := int.add_lt_add_right h (-c),
rwa int.add_neg_cancel_right at h
end
protected lemma lt_add_of_neg_add_lt_left {a b c : β€} (h : -b + a < c) : a < b + c :=
begin
rw int.add_comm at h,
exact int.lt_add_of_sub_left_lt h
end
protected lemma neg_add_lt_left_of_lt_add {a b c : β€} (h : a < b + c) : -b + a < c :=
begin
rw int.add_comm,
exact int.sub_left_lt_of_lt_add h
end
protected lemma lt_add_of_neg_add_lt_right {a b c : β€} (h : -c + a < b) : a < b + c :=
begin
rw int.add_comm at h,
exact int.lt_add_of_sub_right_lt h
end
protected lemma neg_add_lt_right_of_lt_add {a b c : β€} (h : a < b + c) : -c + a < b :=
begin
rw int.add_comm at h,
exact int.neg_add_lt_left_of_lt_add h
end
protected lemma lt_add_of_neg_lt_sub_left {a b c : β€} (h : -a < b - c) : c < a + b :=
int.lt_add_of_neg_add_lt_left (int.add_lt_of_lt_sub_right h)
protected lemma neg_lt_sub_left_of_lt_add {a b c : β€} (h : c < a + b) : -a < b - c :=
begin
have h := int.lt_neg_add_of_add_lt (int.sub_left_lt_of_lt_add h),
rwa int.add_comm at h
end
protected lemma lt_add_of_neg_lt_sub_right {a b c : β€} (h : -b < a - c) : c < a + b :=
int.lt_add_of_sub_right_lt (int.add_lt_of_lt_sub_left h)
protected lemma neg_lt_sub_right_of_lt_add {a b c : β€} (h : c < a + b) : -b < a - c :=
int.lt_sub_left_of_add_lt (int.sub_right_lt_of_lt_add h)
protected lemma sub_lt_of_sub_lt {a b c : β€} (h : a - b < c) : a - c < b :=
int.sub_left_lt_of_lt_add (int.lt_add_of_sub_right_lt h)
protected lemma sub_lt_sub_left {a b : β€} (h : a < b) (c : β€) : c - b < c - a :=
int.add_lt_add_left (int.neg_lt_neg h) c
protected lemma sub_lt_sub_right {a b : β€} (h : a < b) (c : β€) : a - c < b - c :=
int.add_lt_add_right h (-c)
protected lemma sub_lt_sub {a b c d : β€} (hab : a < b) (hcd : c < d) : a - d < b - c :=
int.add_lt_add hab (int.neg_lt_neg hcd)
protected lemma sub_lt_sub_of_le_of_lt {a b c d : β€} (hab : a β€ b) (hcd : c < d) : a - d < b - c :=
int.add_lt_add_of_le_of_lt hab (int.neg_lt_neg hcd)
protected lemma sub_lt_sub_of_lt_of_le {a b c d : β€} (hab : a < b) (hcd : c β€ d) : a - d < b - c :=
int.add_lt_add_of_lt_of_le hab (int.neg_le_neg hcd)
protected lemma sub_le_self (a : β€) {b : β€} (h : 0 β€ b) : a - b β€ a :=
calc
a - b = a + -b : rfl
... β€ a + 0 : int.add_le_add_left (int.neg_nonpos_of_nonneg h) _
... = a : by rw int.add_zero
protected lemma sub_lt_self (a : β€) {b : β€} (h : 0 < b) : a - b < a :=
calc
a - b = a + -b : rfl
... < a + 0 : int.add_lt_add_left (int.neg_neg_of_pos h) _
... = a : by rw int.add_zero
protected lemma add_le_add_three {a b c d e f : β€} (hβ : a β€ d) (hβ : b β€ e) (hβ : c β€ f) :
a + b + c β€ d + e + f :=
begin
apply le_trans,
apply int.add_le_add,
apply int.add_le_add,
assumption',
apply le_refl
end
end
/- missing facts -/
protected lemma mul_lt_mul_of_pos_left {a b c : β€}
(hβ : a < b) (hβ : 0 < c) : c * a < c * b :=
have 0 < b - a, from int.sub_pos_of_lt hβ,
have 0 < c * (b - a), from int.mul_pos hβ this,
begin
rw int.mul_sub at this,
exact int.lt_of_sub_pos this
end
protected lemma mul_lt_mul_of_pos_right {a b c : β€}
(hβ : a < b) (hβ : 0 < c) : a * c < b * c :=
have 0 < b - a, from int.sub_pos_of_lt hβ,
have 0 < (b - a) * c, from int.mul_pos this hβ,
begin
rw int.sub_mul at this,
exact int.lt_of_sub_pos this
end
protected lemma mul_le_mul_of_nonneg_left {a b c : β€} (hβ : a β€ b) (hβ : 0 β€ c) : c * a β€ c * b :=
begin
by_cases hba : b β€ a, { simp [le_antisymm hba hβ] },
by_cases hc0 : c β€ 0, { simp [le_antisymm hc0 hβ, int.zero_mul] },
exact (le_not_le_of_lt (int.mul_lt_mul_of_pos_left
(lt_of_le_not_le hβ hba) (lt_of_le_not_le hβ hc0))).left,
end
protected lemma mul_le_mul_of_nonneg_right {a b c : β€} (hβ : a β€ b) (hβ : 0 β€ c) : a * c β€ b * c :=
begin
by_cases hba : b β€ a, { simp [le_antisymm hba hβ] },
by_cases hc0 : c β€ 0, { simp [le_antisymm hc0 hβ, int.mul_zero] },
exact (le_not_le_of_lt
(int.mul_lt_mul_of_pos_right (lt_of_le_not_le hβ hba) (lt_of_le_not_le hβ hc0))).left,
end
-- TODO: there are four variations, depending on which variables we assume to be nonneg
protected lemma mul_le_mul {a b c d : β€} (hac : a β€ c) (hbd : b β€ d) (nn_b : 0 β€ b) (nn_c : 0 β€ c) :
a * b β€ c * d :=
calc
a * b β€ c * b : int.mul_le_mul_of_nonneg_right hac nn_b
... β€ c * d : int.mul_le_mul_of_nonneg_left hbd nn_c
protected lemma mul_nonpos_of_nonneg_of_nonpos {a b : β€} (ha : 0 β€ a) (hb : b β€ 0) : a * b β€ 0 :=
have h : a * b β€ a * 0, from int.mul_le_mul_of_nonneg_left hb ha,
by rwa int.mul_zero at h
protected lemma mul_nonpos_of_nonpos_of_nonneg {a b : β€} (ha : a β€ 0) (hb : 0 β€ b) : a * b β€ 0 :=
have h : a * b β€ 0 * b, from int.mul_le_mul_of_nonneg_right ha hb,
by rwa int.zero_mul at h
protected lemma mul_lt_mul {a b c d : β€} (hac : a < c) (hbd : b β€ d) (pos_b : 0 < b)
(nn_c : 0 β€ c) : a * b < c * d :=
calc
a * b < c * b : int.mul_lt_mul_of_pos_right hac pos_b
... β€ c * d : int.mul_le_mul_of_nonneg_left hbd nn_c
protected lemma mul_lt_mul' {a b c d : β€} (h1 : a β€ c) (h2 : b < d) (h3 : 0 β€ b) (h4 : 0 < c) :
a * b < c * d :=
calc
a * b β€ c * b : int.mul_le_mul_of_nonneg_right h1 h3
... < c * d : int.mul_lt_mul_of_pos_left h2 h4
protected lemma mul_neg_of_pos_of_neg {a b : β€} (ha : 0 < a) (hb : b < 0) : a * b < 0 :=
have h : a * b < a * 0, from int.mul_lt_mul_of_pos_left hb ha,
by rwa int.mul_zero at h
protected lemma mul_neg_of_neg_of_pos {a b : β€} (ha : a < 0) (hb : 0 < b) : a * b < 0 :=
have h : a * b < 0 * b, from int.mul_lt_mul_of_pos_right ha hb,
by rwa int.zero_mul at h
protected lemma mul_le_mul_of_nonpos_right {a b c : β€} (h : b β€ a) (hc : c β€ 0) : a * c β€ b * c :=
have -c β₯ 0, from int.neg_nonneg_of_nonpos hc,
have b * -c β€ a * -c, from int.mul_le_mul_of_nonneg_right h this,
have -(b * c) β€ -(a * c), by rwa [β int.neg_mul_eq_mul_neg, β int.neg_mul_eq_mul_neg] at this,
int.le_of_neg_le_neg this
protected lemma mul_nonneg_of_nonpos_of_nonpos {a b : β€} (ha : a β€ 0) (hb : b β€ 0) : 0 β€ a * b :=
have 0 * b β€ a * b, from int.mul_le_mul_of_nonpos_right ha hb,
by rwa int.zero_mul at this
protected lemma mul_lt_mul_of_neg_left {a b c : β€} (h : b < a) (hc : c < 0) : c * a < c * b :=
have -c > 0, from int.neg_pos_of_neg hc,
have -c * b < -c * a, from int.mul_lt_mul_of_pos_left h this,
have -(c * b) < -(c * a), by rwa [β int.neg_mul_eq_neg_mul, β int.neg_mul_eq_neg_mul] at this,
int.lt_of_neg_lt_neg this
protected lemma mul_lt_mul_of_neg_right {a b c : β€} (h : b < a) (hc : c < 0) : a * c < b * c :=
have -c > 0, from int.neg_pos_of_neg hc,
have b * -c < a * -c, from int.mul_lt_mul_of_pos_right h this,
have -(b * c) < -(a * c), by rwa [β int.neg_mul_eq_mul_neg, β int.neg_mul_eq_mul_neg] at this,
int.lt_of_neg_lt_neg this
protected lemma mul_pos_of_neg_of_neg {a b : β€} (ha : a < 0) (hb : b < 0) : 0 < a * b :=
have 0 * b < a * b, from int.mul_lt_mul_of_neg_right ha hb,
by rwa int.zero_mul at this
protected lemma mul_self_le_mul_self {a b : β€} (h1 : 0 β€ a) (h2 : a β€ b) : a * a β€ b * b :=
int.mul_le_mul h2 h2 h1 (le_trans h1 h2)
protected lemma mul_self_lt_mul_self {a b : β€} (h1 : 0 β€ a) (h2 : a < b) : a * a < b * b :=
int.mul_lt_mul' (le_of_lt h2) h2 h1 (lt_of_le_of_lt h1 h2)
/- more facts specific to int -/
theorem of_nat_nonneg (n : β) : 0 β€ of_nat n := trivial
theorem coe_succ_pos (n : nat) : 0 < (nat.succ n : β€) :=
coe_nat_lt_coe_nat_of_lt (nat.succ_pos _)
theorem exists_eq_neg_of_nat {a : β€} (H : a β€ 0) : βn : β, a = -n :=
let β¨n, hβ© := eq_coe_of_zero_le (int.neg_nonneg_of_nonpos H) in
β¨n, int.eq_neg_of_eq_neg h.symmβ©
theorem nat_abs_of_nonneg {a : β€} (H : 0 β€ a) : (nat_abs a : β€) = a :=
match a, eq_coe_of_zero_le H with ._, β¨n, rflβ© := rfl end
theorem of_nat_nat_abs_of_nonpos {a : β€} (H : a β€ 0) : (nat_abs a : β€) = -a :=
by rw [β nat_abs_neg, nat_abs_of_nonneg (int.neg_nonneg_of_nonpos H)]
theorem lt_of_add_one_le {a b : β€} (H : a + 1 β€ b) : a < b := H
theorem add_one_le_of_lt {a b : β€} (H : a < b) : a + 1 β€ b := H
theorem lt_add_one_of_le {a b : β€} (H : a β€ b) : a < b + 1 :=
int.add_le_add_right H 1
theorem le_of_lt_add_one {a b : β€} (H : a < b + 1) : a β€ b :=
int.le_of_add_le_add_right H
theorem sub_one_le_of_lt {a b : β€} (H : a β€ b) : a - 1 < b :=
int.sub_right_lt_of_lt_add $ lt_add_one_of_le H
theorem lt_of_sub_one_le {a b : β€} (H : a - 1 < b) : a β€ b :=
le_of_lt_add_one $ int.lt_add_of_sub_right_lt H
theorem le_sub_one_of_lt {a b : β€} (H : a < b) : a β€ b - 1 :=
int.le_sub_right_of_add_le H
theorem lt_of_le_sub_one {a b : β€} (H : a β€ b - 1) : a < b :=
int.add_le_of_le_sub_right H
theorem sign_of_succ (n : nat) : sign (nat.succ n) = 1 := rfl
theorem sign_eq_one_of_pos {a : β€} (h : 0 < a) : sign a = 1 :=
match a, eq_succ_of_zero_lt h with ._, β¨n, rflβ© := rfl end
theorem sign_eq_neg_one_of_neg {a : β€} (h : a < 0) : sign a = -1 :=
match a, eq_neg_succ_of_lt_zero h with ._, β¨n, rflβ© := rfl end
lemma eq_zero_of_sign_eq_zero : Ξ {a : β€}, sign a = 0 β a = 0
| 0 _ := rfl
theorem pos_of_sign_eq_one : β {a : β€}, sign a = 1 β 0 < a
| (n+1:β) _ := coe_nat_lt_coe_nat_of_lt (nat.succ_pos _)
theorem neg_of_sign_eq_neg_one : β {a : β€}, sign a = -1 β a < 0
| (n+1:β) h := match h with end
| 0 h := match h with end
| -[1+ n] _ := neg_succ_lt_zero _
theorem sign_eq_one_iff_pos (a : β€) : sign a = 1 β 0 < a :=
β¨pos_of_sign_eq_one, sign_eq_one_of_posβ©
theorem sign_eq_neg_one_iff_neg (a : β€) : sign a = -1 β a < 0 :=
β¨neg_of_sign_eq_neg_one, sign_eq_neg_one_of_negβ©
theorem sign_eq_zero_iff_zero (a : β€) : sign a = 0 β a = 0 :=
β¨eq_zero_of_sign_eq_zero, Ξ» h, by rw [h, sign_zero]β©
protected lemma eq_zero_or_eq_zero_of_mul_eq_zero
{a b : β€} (h : a * b = 0) : a = 0 β¨ b = 0 :=
match decidable.lt_trichotomy 0 a with
| or.inl hltβ :=
match decidable.lt_trichotomy 0 b with
| or.inl hltβ :=
have 0 < a * b, from int.mul_pos hltβ hltβ,
begin rw h at this, exact absurd this (lt_irrefl _) end
| or.inr (or.inl heqβ) := or.inr heqβ.symm
| or.inr (or.inr hgtβ) :=
have 0 > a * b, from int.mul_neg_of_pos_of_neg hltβ hgtβ,
begin rw h at this, exact absurd this (lt_irrefl _) end
end
| or.inr (or.inl heqβ) := or.inl heqβ.symm
| or.inr (or.inr hgtβ) :=
match decidable.lt_trichotomy 0 b with
| or.inl hltβ :=
have 0 > a * b, from int.mul_neg_of_neg_of_pos hgtβ hltβ,
begin rw h at this, exact absurd this (lt_irrefl _) end
| or.inr (or.inl heqβ) := or.inr heqβ.symm
| or.inr (or.inr hgtβ) :=
have 0 < a * b, from int.mul_pos_of_neg_of_neg hgtβ hgtβ,
begin rw h at this, exact absurd this (lt_irrefl _) end
end
end
protected lemma eq_of_mul_eq_mul_right {a b c : β€} (ha : a β 0) (h : b * a = c * a) : b = c :=
have b * a - c * a = 0, from int.sub_eq_zero_of_eq h,
have (b - c) * a = 0, by rw [int.sub_mul, this],
have b - c = 0, from (int.eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha,
int.eq_of_sub_eq_zero this
protected lemma eq_of_mul_eq_mul_left {a b c : β€} (ha : a β 0) (h : a * b = a * c) : b = c :=
have a * b - a * c = 0, from int.sub_eq_zero_of_eq h,
have a * (b - c) = 0, by rw [int.mul_sub, this],
have b - c = 0, from (int.eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha,
int.eq_of_sub_eq_zero this
theorem eq_one_of_mul_eq_self_left {a b : β€} (Hpos : a β 0) (H : b * a = a) : b = 1 :=
int.eq_of_mul_eq_mul_right Hpos (by rw [int.one_mul, H])
theorem eq_one_of_mul_eq_self_right {a b : β€} (Hpos : b β 0) (H : b * a = b) : a = 1 :=
int.eq_of_mul_eq_mul_left Hpos (by rw [int.mul_one, H])
end int
|
beddbd2449bea2ef37b188fc248c3b43561b639c | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/real/hyperreal.lean | d9eb3f049ee610012bf203a52e1b67e66fd56e6d | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 37,188 | lean | /-
Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Abhimanyu Pallavi Sudhir
-/
import order.filter.filter_product
import analysis.specific_limits
/-!
# Construction of the hyperreal numbers as an ultraproduct of real sequences.
-/
open filter filter.germ
open_locale topological_space classical
/-- Hyperreal numbers on the ultrafilter extending the cofinite filter -/
def hyperreal : Type := germ (@hyperfilter β) β
namespace hyperreal
notation `β*` := hyperreal
private def U : is_ultrafilter (@hyperfilter β) := is_ultrafilter_hyperfilter
noncomputable instance : discrete_linear_ordered_field β* :=
germ.discrete_linear_ordered_field U
noncomputable instance : inhabited β* := β¨0β©
noncomputable instance : has_coe_t β β* := β¨Ξ» x, (βx : germ _ _)β©
@[simp, norm_cast]
lemma coe_eq_coe {x y : β} : (x : β*) = y β x = y :=
germ.const_inj
@[simp, norm_cast] lemma coe_eq_zero {x : β} : (x : β*) = 0 β x = 0 := coe_eq_coe
@[simp, norm_cast] lemma coe_eq_one {x : β} : (x : β*) = 1 β x = 1 := coe_eq_coe
@[simp, norm_cast] lemma coe_one : β(1 : β) = (1 : β*) := rfl
@[simp, norm_cast] lemma coe_zero : β(0 : β) = (0 : β*) := rfl
@[simp, norm_cast] lemma coe_inv (x : β) : β(xβ»ΒΉ) = (xβ»ΒΉ : β*) := rfl
@[simp, norm_cast] lemma coe_neg (x : β) : β(-x) = (-x : β*) := rfl
@[simp, norm_cast] lemma coe_add (x y : β) : β(x + y) = (x + y : β*) := rfl
@[simp, norm_cast] lemma coe_bit0 (x : β) : β(bit0 x) = (bit0 x : β*) := rfl
@[simp, norm_cast] lemma coe_bit1 (x : β) : β(bit1 x) = (bit1 x : β*) := rfl
@[simp, norm_cast] lemma coe_mul (x y : β) : β(x * y) = (x * y : β*) := rfl
@[simp, norm_cast] lemma coe_div (x y : β) : β(x / y) = (x / y : β*) := rfl
@[simp, norm_cast] lemma coe_sub (x y : β) : β(x - y) = (x - y : β*) := rfl
@[simp, norm_cast] lemma coe_lt_coe {x y : β} : (x : β*) < y β x < y := germ.const_lt U
@[simp, norm_cast] lemma coe_pos {x : β} : 0 < (x : β*) β 0 < x :=
coe_lt_coe
@[simp, norm_cast] lemma coe_le_coe {x y : β} : (x : β*) β€ y β x β€ y := germ.const_le_iff
@[simp, norm_cast] lemma coe_abs (x : β) : ((abs x : β) : β*) = abs x := germ.const_abs _ _
@[simp, norm_cast] lemma coe_max (x y : β) : ((max x y : β) : β*) = max x y := germ.const_max _ _ _
@[simp, norm_cast] lemma coe_min (x y : β) : ((min x y : β) : β*) = min x y := germ.const_min _ _ _
/-- Construct a hyperreal number from a sequence of real numbers. -/
noncomputable def of_seq (f : β β β) : β* := (βf : germ (@hyperfilter β) β)
/-- A sample infinitesimal hyperreal-/
noncomputable def epsilon : β* := of_seq $ Ξ» n, nβ»ΒΉ
/-- A sample infinite hyperreal-/
noncomputable def omega : β* := of_seq coe
localized "notation `Ξ΅` := hyperreal.epsilon" in hyperreal
localized "notation `Ο` := hyperreal.omega" in hyperreal
lemma epsilon_eq_inv_omega : Ξ΅ = Οβ»ΒΉ := rfl
lemma inv_epsilon_eq_omega : Ξ΅β»ΒΉ = Ο := @inv_inv' _ _ Ο
lemma epsilon_pos : 0 < Ξ΅ :=
suffices βαΆ i in hyperfilter, (0 : β) < (i : β)β»ΒΉ, by rwa lt_def U,
have h0' : {n : β | Β¬ 0 < n} = {0} :=
by simp only [not_lt, (set.set_of_eq_eq_singleton).symm]; ext; exact nat.le_zero_iff,
begin
simp only [inv_pos, nat.cast_pos],
exact mem_hyperfilter_of_finite_compl (by convert set.finite_singleton _),
end
lemma epsilon_ne_zero : Ξ΅ β 0 := ne_of_gt epsilon_pos
lemma omega_pos : 0 < Ο := by rw βinv_epsilon_eq_omega; exact inv_pos.2 epsilon_pos
lemma omega_ne_zero : Ο β 0 := ne_of_gt omega_pos
theorem epsilon_mul_omega : Ξ΅ * Ο = 1 := @inv_mul_cancel _ _ Ο omega_ne_zero
lemma lt_of_tendsto_zero_of_pos {f : β β β} (hf : tendsto f at_top (π 0)) :
β {r : β}, 0 < r β of_seq f < (r : β*) :=
begin
simp only [metric.tendsto_at_top, dist_zero_right, norm, lt_def U] at hf β’,
intros r hr, cases hf r hr with N hf',
have hs : {i : β | f i < r}αΆ β {i : β | i β€ N} :=
Ξ» i hi1, le_of_lt (by simp only [lt_iff_not_ge];
exact Ξ» hi2, hi1 (lt_of_le_of_lt (le_abs_self _) (hf' i hi2)) : i < N),
exact mem_hyperfilter_of_finite_compl
((set.finite_le_nat N).subset hs)
end
lemma neg_lt_of_tendsto_zero_of_pos {f : β β β} (hf : tendsto f at_top (π 0)) :
β {r : β}, 0 < r β (-r : β*) < of_seq f :=
Ξ» r hr, have hg : _ := hf.neg,
neg_lt_of_neg_lt (by rw [neg_zero] at hg; exact lt_of_tendsto_zero_of_pos hg hr)
lemma gt_of_tendsto_zero_of_neg {f : β β β} (hf : tendsto f at_top (π 0)) :
β {r : β}, r < 0 β (r : β*) < of_seq f :=
Ξ» r hr, by rw [βneg_neg r, coe_neg];
exact neg_lt_of_tendsto_zero_of_pos hf (neg_pos.mpr hr)
lemma epsilon_lt_pos (x : β) : 0 < x β Ξ΅ < x :=
lt_of_tendsto_zero_of_pos tendsto_inverse_at_top_nhds_0_nat
/-- Standard part predicate -/
def is_st (x : β*) (r : β) := β Ξ΄ : β, 0 < Ξ΄ β (r - Ξ΄ : β*) < x β§ x < r + Ξ΄
/-- Standard part function: like a "round" to β instead of β€ -/
noncomputable def st : β* β β :=
Ξ» x, if h : β r, is_st x r then classical.some h else 0
/-- A hyperreal number is infinitesimal if its standard part is 0 -/
def infinitesimal (x : β*) := is_st x 0
/-- A hyperreal number is positive infinite if it is larger than all real numbers -/
def infinite_pos (x : β*) := β r : β, βr < x
/-- A hyperreal number is negative infinite if it is smaller than all real numbers -/
def infinite_neg (x : β*) := β r : β, x < r
/-- A hyperreal number is infinite if it is infinite positive or infinite negative -/
def infinite (x : β*) := infinite_pos x β¨ infinite_neg x
/-!
### Some facts about `st`
-/
private lemma is_st_unique' (x : β*) (r s : β) (hr : is_st x r) (hs : is_st x s) (hrs : r < s) :
false :=
have hrs' : _ := half_pos $ sub_pos_of_lt hrs,
have hr' : _ := (hr _ hrs').2,
have hs' : _ := (hs _ hrs').1,
have h : s - ((s - r) / 2) = r + (s - r) / 2 := by linarith,
begin
norm_cast at *,
rw h at hs',
exact not_lt_of_lt hs' hr'
end
theorem is_st_unique {x : β*} {r s : β} (hr : is_st x r) (hs : is_st x s) : r = s :=
begin
rcases lt_trichotomy r s with h | h | h,
{ exact false.elim (is_st_unique' x r s hr hs h) },
{ exact h },
{ exact false.elim (is_st_unique' x s r hs hr h) }
end
theorem not_infinite_of_exists_st {x : β*} : (β r : β, is_st x r) β Β¬ infinite x :=
Ξ» he hi, Exists.dcases_on he $ Ξ» r hr, hi.elim
(Ξ» hip, not_lt_of_lt (hr 2 two_pos).2 (hip $ r + 2))
(Ξ» hin, not_lt_of_lt (hr 2 two_pos).1 (hin $ r - 2))
theorem is_st_Sup {x : β*} (hni : Β¬ infinite x) : is_st x (Sup {y : β | (y : β*) < x}) :=
let S : set β := {y : β | (y : β*) < x} in
let R : _ := Sup S in
have hnile : _ := not_forall.mp (not_or_distrib.mp hni).1,
have hnige : _ := not_forall.mp (not_or_distrib.mp hni).2,
Exists.dcases_on hnile $ Exists.dcases_on hnige $ Ξ» rβ hrβ rβ hrβ,
have HRβ : β y : β, y β S :=
β¨rβ - 1, lt_of_lt_of_le (coe_lt_coe.2 $ sub_one_lt _) (not_lt.mp hrβ) β©,
have HRβ : β z : β, β y β S, y β€ z :=
β¨ rβ, Ξ» y hy, le_of_lt (coe_lt_coe.1 (lt_of_lt_of_le hy (not_lt.mp hrβ))) β©,
Ξ» Ξ΄ hΞ΄,
β¨ lt_of_not_ge' $ Ξ» c,
have hc : β y β S, y β€ R - Ξ΄ := Ξ» y hy, coe_le_coe.1 $ le_of_lt $ lt_of_lt_of_le hy c,
not_lt_of_le ((real.Sup_le _ HRβ HRβ).mpr hc) $ sub_lt_self R hΞ΄,
lt_of_not_ge' $ Ξ» c,
have hc : β(R + Ξ΄ / 2) < x :=
lt_of_lt_of_le (add_lt_add_left (coe_lt_coe.2 (half_lt_self hΞ΄)) R) c,
not_lt_of_le (real.le_Sup _ HRβ hc) $ (lt_add_iff_pos_right _).mpr $ half_pos hΞ΄β©
theorem exists_st_of_not_infinite {x : β*} (hni : Β¬ infinite x) : β r : β, is_st x r :=
β¨Sup {y : β | (y : β*) < x}, is_st_Sup hniβ©
theorem st_eq_Sup {x : β*} : st x = Sup {y : β | (y : β*) < x} :=
begin
unfold st, split_ifs,
{ exact is_st_unique (classical.some_spec h) (is_st_Sup (not_infinite_of_exists_st h)) },
{ cases not_imp_comm.mp exists_st_of_not_infinite h with H H,
{ rw (set.ext (Ξ» i, β¨Ξ» hi, set.mem_univ i, Ξ» hi, H iβ©) : {y : β | (y : β*) < x} = set.univ),
exact (real.Sup_univ).symm },
{ rw (set.ext (Ξ» i, β¨Ξ» hi, false.elim (not_lt_of_lt (H i) hi),
Ξ» hi, false.elim (set.not_mem_empty i hi)β©) : {y : β | (y : β*) < x} = β
),
exact (real.Sup_empty).symm } }
end
theorem exists_st_iff_not_infinite {x : β*} : (β r : β, is_st x r) β Β¬ infinite x :=
β¨ not_infinite_of_exists_st, exists_st_of_not_infinite β©
theorem infinite_iff_not_exists_st {x : β*} : infinite x β Β¬ β r : β, is_st x r :=
iff_not_comm.mp exists_st_iff_not_infinite
theorem st_infinite {x : β*} (hi : infinite x) : st x = 0 :=
begin
unfold st, split_ifs,
{ exact false.elim ((infinite_iff_not_exists_st.mp hi) h) },
{ refl }
end
lemma st_of_is_st {x : β*} {r : β} (hxr : is_st x r) : st x = r :=
begin
unfold st, split_ifs,
{ exact is_st_unique (classical.some_spec h) hxr },
{ exact false.elim (h β¨r, hxrβ©) }
end
lemma is_st_st_of_is_st {x : β*} {r : β} (hxr : is_st x r) : is_st x (st x) :=
by rwa [st_of_is_st hxr]
lemma is_st_st_of_exists_st {x : β*} (hx : β r : β, is_st x r) : is_st x (st x) :=
Exists.dcases_on hx (Ξ» r, is_st_st_of_is_st)
lemma is_st_st {x : β*} (hx : st x β 0) : is_st x (st x) :=
begin
unfold st, split_ifs,
{ exact classical.some_spec h },
{ exact false.elim (hx (by unfold st; split_ifs; refl)) }
end
lemma is_st_st' {x : β*} (hx : Β¬ infinite x) : is_st x (st x) :=
is_st_st_of_exists_st $ exists_st_of_not_infinite hx
lemma is_st_refl_real (r : β) : is_st r r :=
Ξ» Ξ΄ hΞ΄, β¨ sub_lt_self _ (coe_lt_coe.2 hΞ΄), (lt_add_of_pos_right _ (coe_lt_coe.2 hΞ΄)) β©
lemma st_id_real (r : β) : st r = r := st_of_is_st (is_st_refl_real r)
lemma eq_of_is_st_real {r s : β} : is_st r s β r = s := is_st_unique (is_st_refl_real r)
lemma is_st_real_iff_eq {r s : β} : is_st r s β r = s :=
β¨eq_of_is_st_real, Ξ» hrs, by rw [hrs]; exact is_st_refl_real sβ©
lemma is_st_symm_real {r s : β} : is_st r s β is_st s r :=
by rw [is_st_real_iff_eq, is_st_real_iff_eq, eq_comm]
lemma is_st_trans_real {r s t : β} : is_st r s β is_st s t β is_st r t :=
by rw [is_st_real_iff_eq, is_st_real_iff_eq, is_st_real_iff_eq]; exact eq.trans
lemma is_st_inj_real {rβ rβ s : β} (h1 : is_st rβ s) (h2 : is_st rβ s) : rβ = rβ :=
eq.trans (eq_of_is_st_real h1) (eq_of_is_st_real h2).symm
lemma is_st_iff_abs_sub_lt_delta {x : β*} {r : β} :
is_st x r β β (Ξ΄ : β), 0 < Ξ΄ β abs (x - r) < Ξ΄ :=
by simp only [abs_sub_lt_iff, @sub_lt _ _ (r : β*) x _,
@sub_lt_iff_lt_add' _ _ x (r : β*) _, and_comm]; refl
lemma is_st_add {x y : β*} {r s : β} : is_st x r β is_st y s β is_st (x + y) (r + s) :=
Ξ» hxr hys d hd,
have hxr' : _ := hxr (d / 2) (half_pos hd),
have hys' : _ := hys (d / 2) (half_pos hd),
β¨by convert add_lt_add hxr'.1 hys'.1 using 1; norm_cast; linarith,
by convert add_lt_add hxr'.2 hys'.2 using 1; norm_cast; linarithβ©
lemma is_st_neg {x : β*} {r : β} (hxr : is_st x r) : is_st (-x) (-r) :=
Ξ» d hd, by show -(r : β*) - d < -x β§ -x < -r + d; cases (hxr d hd); split; linarith
lemma is_st_sub {x y : β*} {r s : β} : is_st x r β is_st y s β is_st (x - y) (r - s) :=
Ξ» hxr hys, by rw [sub_eq_add_neg, sub_eq_add_neg]; exact is_st_add hxr (is_st_neg hys)
/- (st x < st y) β (x < y) β (x β€ y) β (st x β€ st y) -/
lemma lt_of_is_st_lt {x y : β*} {r s : β} (hxr : is_st x r) (hys : is_st y s) :
r < s β x < y :=
Ξ» hrs, have hrs' : 0 < (s - r) / 2 := half_pos (sub_pos.mpr hrs),
have hxr' : _ := (hxr _ hrs').2, have hys' : _ := (hys _ hrs').1,
have H1 : r + ((s - r) / 2) = (r + s) / 2 := by linarith,
have H2 : s - ((s - r) / 2) = (r + s) / 2 := by linarith,
begin
norm_cast at *,
rw H1 at hxr',
rw H2 at hys',
exact lt_trans hxr' hys'
end
lemma is_st_le_of_le {x y : β*} {r s : β} (hrx : is_st x r) (hsy : is_st y s) :
x β€ y β r β€ s := by rw [βnot_lt, βnot_lt, not_imp_not]; exact lt_of_is_st_lt hsy hrx
lemma st_le_of_le {x y : β*} (hix : Β¬ infinite x) (hiy : Β¬ infinite y) :
x β€ y β st x β€ st y :=
have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy,
is_st_le_of_le hx' hy'
lemma lt_of_st_lt {x y : β*} (hix : Β¬ infinite x) (hiy : Β¬ infinite y) :
st x < st y β x < y :=
have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy,
lt_of_is_st_lt hx' hy'
/-!
### Basic lemmas about infinite
-/
lemma infinite_pos_def {x : β*} : infinite_pos x β β r : β, βr < x := by rw iff_eq_eq; refl
lemma infinite_neg_def {x : β*} : infinite_neg x β β r : β, x < r := by rw iff_eq_eq; refl
lemma ne_zero_of_infinite {x : β*} : infinite x β x β 0 :=
Ξ» hI h0, or.cases_on hI
(Ξ» hip, lt_irrefl (0 : β*) ((by rwa βh0 : infinite_pos 0) 0))
(Ξ» hin, lt_irrefl (0 : β*) ((by rwa βh0 : infinite_neg 0) 0))
lemma not_infinite_zero : Β¬ infinite 0 := Ξ» hI, ne_zero_of_infinite hI rfl
lemma pos_of_infinite_pos {x : β*} : infinite_pos x β 0 < x := Ξ» hip, hip 0
lemma neg_of_infinite_neg {x : β*} : infinite_neg x β x < 0 := Ξ» hin, hin 0
lemma not_infinite_pos_of_infinite_neg {x : β*} : infinite_neg x β Β¬ infinite_pos x :=
Ξ» hn hp, not_lt_of_lt (hn 1) (hp 1)
lemma not_infinite_neg_of_infinite_pos {x : β*} : infinite_pos x β Β¬ infinite_neg x :=
imp_not_comm.mp not_infinite_pos_of_infinite_neg
lemma infinite_neg_neg_of_infinite_pos {x : β*} : infinite_pos x β infinite_neg (-x) :=
Ξ» hp r, neg_lt.mp (hp (-r))
lemma infinite_pos_neg_of_infinite_neg {x : β*} : infinite_neg x β infinite_pos (-x) :=
Ξ» hp r, lt_neg.mp (hp (-r))
lemma infinite_pos_iff_infinite_neg_neg {x : β*} : infinite_pos x β infinite_neg (-x) :=
β¨ infinite_neg_neg_of_infinite_pos, Ξ» hin, neg_neg x βΈ infinite_pos_neg_of_infinite_neg hin β©
lemma infinite_neg_iff_infinite_pos_neg {x : β*} : infinite_neg x β infinite_pos (-x) :=
β¨ infinite_pos_neg_of_infinite_neg, Ξ» hin, neg_neg x βΈ infinite_neg_neg_of_infinite_pos hin β©
lemma infinite_iff_infinite_neg {x : β*} : infinite x β infinite (-x) :=
β¨ Ξ» hi, or.cases_on hi
(Ξ» hip, or.inr (infinite_neg_neg_of_infinite_pos hip))
(Ξ» hin, or.inl (infinite_pos_neg_of_infinite_neg hin)),
Ξ» hi, or.cases_on hi
(Ξ» hipn, or.inr (infinite_neg_iff_infinite_pos_neg.mpr hipn))
(Ξ» hinp, or.inl (infinite_pos_iff_infinite_neg_neg.mpr hinp))β©
lemma not_infinite_of_infinitesimal {x : β*} : infinitesimal x β Β¬ infinite x :=
Ξ» hi hI, have hi' : _ := (hi 2 two_pos), or.dcases_on hI
(Ξ» hip, have hip' : _ := hip 2, not_lt_of_lt hip' (by convert hi'.2; exact (zero_add 2).symm))
(Ξ» hin, have hin' : _ := hin (-2), not_lt_of_lt hin' (by convert hi'.1; exact (zero_sub 2).symm))
lemma not_infinitesimal_of_infinite {x : β*} : infinite x β Β¬ infinitesimal x :=
imp_not_comm.mp not_infinite_of_infinitesimal
lemma not_infinitesimal_of_infinite_pos {x : β*} : infinite_pos x β Β¬ infinitesimal x :=
Ξ» hp, not_infinitesimal_of_infinite (or.inl hp)
lemma not_infinitesimal_of_infinite_neg {x : β*} : infinite_neg x β Β¬ infinitesimal x :=
Ξ» hn, not_infinitesimal_of_infinite (or.inr hn)
lemma infinite_pos_iff_infinite_and_pos {x : β*} : infinite_pos x β (infinite x β§ 0 < x) :=
β¨ Ξ» hip, β¨or.inl hip, hip 0β©,
Ξ» β¨hi, hpβ©, hi.cases_on (Ξ» hip, hip) (Ξ» hin, false.elim (not_lt_of_lt hp (hin 0))) β©
lemma infinite_neg_iff_infinite_and_neg {x : β*} : infinite_neg x β (infinite x β§ x < 0) :=
β¨ Ξ» hip, β¨or.inr hip, hip 0β©,
Ξ» β¨hi, hpβ©, hi.cases_on (Ξ» hin, false.elim (not_lt_of_lt hp (hin 0))) (Ξ» hip, hip) β©
lemma infinite_pos_iff_infinite_of_pos {x : β*} (hp : 0 < x) : infinite_pos x β infinite x :=
by rw [infinite_pos_iff_infinite_and_pos]; exact β¨Ξ» hI, hI.1, Ξ» hI, β¨hI, hpβ©β©
lemma infinite_pos_iff_infinite_of_nonneg {x : β*} (hp : 0 β€ x) : infinite_pos x β infinite x :=
or.cases_on (lt_or_eq_of_le hp) (infinite_pos_iff_infinite_of_pos)
(Ξ» h, by rw h.symm; exact
β¨Ξ» hIP, false.elim (not_infinite_zero (or.inl hIP)), Ξ» hI, false.elim (not_infinite_zero hI)β©)
lemma infinite_neg_iff_infinite_of_neg {x : β*} (hn : x < 0) : infinite_neg x β infinite x :=
by rw [infinite_neg_iff_infinite_and_neg]; exact β¨Ξ» hI, hI.1, Ξ» hI, β¨hI, hnβ©β©
lemma infinite_pos_abs_iff_infinite_abs {x : β*} : infinite_pos (abs x) β infinite (abs x) :=
infinite_pos_iff_infinite_of_nonneg (abs_nonneg _)
lemma infinite_iff_infinite_pos_abs {x : β*} : infinite x β infinite_pos (abs x) :=
β¨ Ξ» hi d, or.cases_on hi
(Ξ» hip, by rw [abs_of_pos (hip 0)]; exact hip d)
(Ξ» hin, by rw [abs_of_neg (hin 0)]; exact lt_neg.mp (hin (-d))),
Ξ» hipa, by { rcases (lt_trichotomy x 0) with h | h | h,
{ exact or.inr (infinite_neg_iff_infinite_pos_neg.mpr (by rwa abs_of_neg h at hipa)) },
{ exact false.elim (ne_zero_of_infinite (or.inl (by rw [h]; rwa [h, abs_zero] at hipa)) h) },
{ exact or.inl (by rwa abs_of_pos h at hipa) } } β©
lemma infinite_iff_infinite_abs {x : β*} : infinite x β infinite (abs x) :=
by rw [βinfinite_pos_iff_infinite_of_nonneg (abs_nonneg _), infinite_iff_infinite_pos_abs]
lemma infinite_iff_abs_lt_abs {x : β*} : infinite x β β r : β, (abs r : β*) < abs x :=
β¨ Ξ» hI r, (coe_abs r) βΈ infinite_iff_infinite_pos_abs.mp hI (abs r),
Ξ» hR, or.cases_on (max_choice x (-x))
(Ξ» h, or.inl $ Ξ» r, lt_of_le_of_lt (le_abs_self _) (h βΈ (hR r)))
(Ξ» h, or.inr $ Ξ» r, neg_lt_neg_iff.mp $ lt_of_le_of_lt (neg_le_abs_self _) (h βΈ (hR r)))β©
lemma infinite_pos_add_not_infinite_neg {x y : β*} :
infinite_pos x β Β¬ infinite_neg y β infinite_pos (x + y) :=
begin
intros hip hnin r,
cases not_forall.mp hnin with rβ hrβ,
convert add_lt_add_of_lt_of_le (hip (r + -rβ)) (not_lt.mp hrβ) using 1,
simp
end
lemma not_infinite_neg_add_infinite_pos {x y : β*} :
Β¬ infinite_neg x β infinite_pos y β infinite_pos (x + y) :=
Ξ» hx hy, by rw [add_comm]; exact infinite_pos_add_not_infinite_neg hy hx
lemma infinite_neg_add_not_infinite_pos {x y : β*} :
infinite_neg x β Β¬ infinite_pos y β infinite_neg (x + y) :=
by rw [@infinite_neg_iff_infinite_pos_neg x, @infinite_pos_iff_infinite_neg_neg y,
@infinite_neg_iff_infinite_pos_neg (x + y), neg_add];
exact infinite_pos_add_not_infinite_neg
lemma not_infinite_pos_add_infinite_neg {x y : β*} :
Β¬ infinite_pos x β infinite_neg y β infinite_neg (x + y) :=
Ξ» hx hy, by rw [add_comm]; exact infinite_neg_add_not_infinite_pos hy hx
lemma infinite_pos_add_infinite_pos {x y : β*} :
infinite_pos x β infinite_pos y β infinite_pos (x + y) :=
Ξ» hx hy, infinite_pos_add_not_infinite_neg hx (not_infinite_neg_of_infinite_pos hy)
lemma infinite_neg_add_infinite_neg {x y : β*} :
infinite_neg x β infinite_neg y β infinite_neg (x + y) :=
Ξ» hx hy, infinite_neg_add_not_infinite_pos hx (not_infinite_pos_of_infinite_neg hy)
lemma infinite_pos_add_not_infinite {x y : β*} :
infinite_pos x β Β¬ infinite y β infinite_pos (x + y) :=
Ξ» hx hy, infinite_pos_add_not_infinite_neg hx (not_or_distrib.mp hy).2
lemma infinite_neg_add_not_infinite {x y : β*} :
infinite_neg x β Β¬ infinite y β infinite_neg (x + y) :=
Ξ» hx hy, infinite_neg_add_not_infinite_pos hx (not_or_distrib.mp hy).1
theorem infinite_pos_of_tendsto_top {f : β β β} (hf : tendsto f at_top at_top) :
infinite_pos (of_seq f) :=
Ξ» r, have hf' : _ := (tendsto_at_top_at_top _).mp hf,
Exists.cases_on (hf' (r + 1)) $ Ξ» i hi,
have hi' : β (a : β), f a < (r + 1) β a < i :=
Ξ» a, by rw [βnot_le, βnot_le]; exact not_imp_not.mpr (hi a),
have hS : {a : β | r < f a}αΆ β {a : β | a β€ i} :=
by simp only [set.compl_set_of, not_lt];
exact Ξ» a har, le_of_lt (hi' a (lt_of_le_of_lt har (lt_add_one _))),
(germ.coe_lt U).2 $ mem_hyperfilter_of_finite_compl $
(set.finite_le_nat _).subset hS
theorem infinite_neg_of_tendsto_bot {f : β β β} (hf : tendsto f at_top at_bot) :
infinite_neg (of_seq f) :=
Ξ» r, have hf' : _ := (tendsto_at_top_at_bot _).mp hf,
Exists.cases_on (hf' (r - 1)) $ Ξ» i hi,
have hi' : β (a : β), r - 1 < f a β a < i :=
Ξ» a, by rw [βnot_le, βnot_le]; exact not_imp_not.mpr (hi a),
have hS : {a : β | f a < r}αΆ β {a : β | a β€ i} :=
by simp only [set.compl_set_of, not_lt];
exact Ξ» a har, le_of_lt (hi' a (lt_of_lt_of_le (sub_one_lt _) har)),
(germ.coe_lt U).2 $ mem_hyperfilter_of_finite_compl $
(set.finite_le_nat _).subset hS
lemma not_infinite_neg {x : β*} : Β¬ infinite x β Β¬ infinite (-x) :=
not_imp_not.mpr infinite_iff_infinite_neg.mpr
lemma not_infinite_add {x y : β*} (hx : Β¬ infinite x) (hy : Β¬ infinite y) :
Β¬ infinite (x + y) :=
have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy,
Exists.cases_on hx' $ Exists.cases_on hy' $
Ξ» r hr s hs, not_infinite_of_exists_st $ β¨s + r, is_st_add hs hrβ©
theorem not_infinite_iff_exist_lt_gt {x : β*} : Β¬ infinite x β β r s : β, (r : β*) < x β§ x < s :=
β¨ Ξ» hni,
Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).1) $
Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).2) $ Ξ» r hr s hs,
by rw [not_lt] at hr hs; exact β¨r - 1, s + 1,
β¨ lt_of_lt_of_le (by rw sub_eq_add_neg; norm_num) hr,
lt_of_le_of_lt hs (by norm_num)β© β©,
Ξ» hrs, Exists.dcases_on hrs $ Ξ» r hr, Exists.dcases_on hr $ Ξ» s hs,
not_or_distrib.mpr β¨not_forall.mpr β¨s, lt_asymm (hs.2)β©, not_forall.mpr β¨r, lt_asymm (hs.1) β©β©β©
theorem not_infinite_real (r : β) : Β¬ infinite r := by rw not_infinite_iff_exist_lt_gt; exact
β¨ r - 1, r + 1, coe_lt_coe.2 $ sub_one_lt r, coe_lt_coe.2 $ lt_add_one rβ©
theorem not_real_of_infinite {x : β*} : infinite x β β r : β, x β r :=
Ξ» hi r hr, not_infinite_real r $ @eq.subst _ infinite _ _ hr hi
/-!
### Facts about `st` that require some infinite machinery
-/
private lemma is_st_mul' {x y : β*} {r s : β} (hxr : is_st x r) (hys : is_st y s) (hs : s β 0) :
is_st (x * y) (r * s) :=
have hxr' : _ := is_st_iff_abs_sub_lt_delta.mp hxr,
have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys,
have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $
not_infinite_of_exists_st β¨r, hxrβ©,
Exists.cases_on h $ Ξ» u h', Exists.cases_on h' $ Ξ» t β¨hu, htβ©,
is_st_iff_abs_sub_lt_delta.mpr $ Ξ» d hd,
calc abs (x * y - r * s)
= abs (x * (y - s) + (x - r) * s) :
by rw [mul_sub, sub_mul, add_sub, sub_add_cancel]
... β€ abs (x * (y - s)) + abs ((x - r) * s) : abs_add _ _
... β€ abs x * abs (y - s) + abs (x - r) * abs s : by simp only [abs_mul]
... β€ abs x * ((d / t) / 2 : β) + ((d / abs s) / 2 : β) * abs s : add_le_add
(mul_le_mul_of_nonneg_left (le_of_lt $ hys' _ $ half_pos $ div_pos hd $
coe_pos.1 $ lt_of_le_of_lt (abs_nonneg x) ht) $ abs_nonneg _)
(mul_le_mul_of_nonneg_right (le_of_lt $ hxr' _ $ half_pos $ div_pos hd $
abs_pos_of_ne_zero hs) $ abs_nonneg _)
... = (d / 2 * (abs x / t) + d / 2 : β*) : by
{ push_cast,
have : (abs s : β*) β 0, by simpa,
field_simp [this, @two_ne_zero β* _, add_mul, mul_add, mul_assoc, mul_comm, mul_left_comm] }
... < (d / 2 * 1 + d / 2 : β*) :
add_lt_add_right (mul_lt_mul_of_pos_left
((div_lt_one $ lt_of_le_of_lt (abs_nonneg x) ht).mpr ht) $
half_pos $ coe_pos.2 hd) _
... = (d : β*) : by rw [mul_one, add_halves]
lemma is_st_mul {x y : β*} {r s : β} (hxr : is_st x r) (hys : is_st y s) :
is_st (x * y) (r * s) :=
have h : _ := not_infinite_iff_exist_lt_gt.mp $
not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st β¨r, hxrβ©,
Exists.cases_on h $ Ξ» u h', Exists.cases_on h' $ Ξ» t β¨hu, htβ©,
begin
by_cases hs : s = 0,
{ apply is_st_iff_abs_sub_lt_delta.mpr, intros d hd,
have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys (d / t)
(div_pos hd (coe_pos.1 (lt_of_le_of_lt (abs_nonneg x) ht))),
rw [hs, coe_zero, sub_zero] at hys',
rw [hs, mul_zero, coe_zero, sub_zero, abs_mul, mul_comm,
βdiv_mul_cancel (d : β*) (ne_of_gt (lt_of_le_of_lt (abs_nonneg x) ht)),
βcoe_div],
exact mul_lt_mul'' hys' ht (abs_nonneg _) (abs_nonneg _) },
exact is_st_mul' hxr hys hs,
end
--AN INFINITE LEMMA THAT REQUIRES SOME MORE ST MACHINERY
lemma not_infinite_mul {x y : β*} (hx : Β¬ infinite x) (hy : Β¬ infinite y) :
Β¬ infinite (x * y) :=
have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy,
Exists.cases_on hx' $ Exists.cases_on hy' $ Ξ» r hr s hs, not_infinite_of_exists_st $
β¨s * r, is_st_mul hs hrβ©
---
lemma st_add {x y : β*} (hx : Β¬infinite x) (hy : Β¬infinite y) : st (x + y) = st x + st y :=
have hx' : _ := is_st_st' hx,
have hy' : _ := is_st_st' hy,
have hxy : _ := is_st_st' (not_infinite_add hx hy),
have hxy' : _ := is_st_add hx' hy',
is_st_unique hxy hxy'
lemma st_neg (x : β*) : st (-x) = - st x :=
if h : infinite x
then by rw [st_infinite h, st_infinite (infinite_iff_infinite_neg.mp h), neg_zero]
else is_st_unique (is_st_st' (not_infinite_neg h)) (is_st_neg (is_st_st' h))
lemma st_mul {x y : β*} (hx : Β¬infinite x) (hy : Β¬infinite y) : st (x * y) = (st x) * (st y) :=
have hx' : _ := is_st_st' hx,
have hy' : _ := is_st_st' hy,
have hxy : _ := is_st_st' (not_infinite_mul hx hy),
have hxy' : _ := is_st_mul hx' hy',
is_st_unique hxy hxy'
/-!
### Basic lemmas about infinitesimal
-/
theorem infinitesimal_def {x : β*} :
infinitesimal x β (β r : β, 0 < r β -(r : β*) < x β§ x < r) :=
β¨ Ξ» hi r hr, by { convert (hi r hr); simp },
Ξ» hi d hd, by { convert (hi d hd); simp } β©
theorem lt_of_pos_of_infinitesimal {x : β*} : infinitesimal x β β r : β, 0 < r β x < r :=
Ξ» hi r hr, ((infinitesimal_def.mp hi) r hr).2
theorem lt_neg_of_pos_of_infinitesimal {x : β*} : infinitesimal x β β r : β, 0 < r β -βr < x :=
Ξ» hi r hr, ((infinitesimal_def.mp hi) r hr).1
theorem gt_of_neg_of_infinitesimal {x : β*} : infinitesimal x β β r : β, r < 0 β βr < x :=
Ξ» hi r hr, by convert ((infinitesimal_def.mp hi) (-r) (neg_pos.mpr hr)).1;
exact (neg_neg βr).symm
theorem abs_lt_real_iff_infinitesimal {x : β*} :
infinitesimal x β β r : β, r β 0 β abs x < abs r :=
β¨ Ξ» hi r hr, abs_lt.mpr (by rw βcoe_abs;
exact infinitesimal_def.mp hi (abs r) (abs_pos_of_ne_zero hr)),
Ξ» hR, infinitesimal_def.mpr $ Ξ» r hr, abs_lt.mp $
(abs_of_pos $ coe_pos.2 hr) βΈ hR r $ ne_of_gt hr β©
lemma infinitesimal_zero : infinitesimal 0 := is_st_refl_real 0
lemma zero_of_infinitesimal_real {r : β} : infinitesimal r β r = 0 := eq_of_is_st_real
lemma zero_iff_infinitesimal_real {r : β} : infinitesimal r β r = 0 :=
β¨zero_of_infinitesimal_real, Ξ» hr, by rw hr; exact infinitesimal_zeroβ©
lemma infinitesimal_add {x y : β*} (hx : infinitesimal x) (hy : infinitesimal y) :
infinitesimal (x + y) :=
by simpa only [add_zero] using is_st_add hx hy
lemma infinitesimal_neg {x : β*} (hx : infinitesimal x) : infinitesimal (-x) :=
by simpa only [neg_zero] using is_st_neg hx
lemma infinitesimal_neg_iff {x : β*} : infinitesimal x β infinitesimal (-x) :=
β¨infinitesimal_neg, Ξ» h, (neg_neg x) βΈ @infinitesimal_neg (-x) hβ©
lemma infinitesimal_mul {x y : β*} (hx : infinitesimal x) (hy : infinitesimal y) :
infinitesimal (x * y) :=
by simpa only [mul_zero] using is_st_mul hx hy
theorem infinitesimal_of_tendsto_zero {f : β β β} :
tendsto f at_top (π 0) β infinitesimal (of_seq f) :=
Ξ» hf d hd, by rw [sub_eq_add_neg, βcoe_neg, βcoe_add, βcoe_add, zero_add, zero_add];
exact β¨neg_lt_of_tendsto_zero_of_pos hf hd, lt_of_tendsto_zero_of_pos hf hdβ©
theorem infinitesimal_epsilon : infinitesimal Ξ΅ :=
infinitesimal_of_tendsto_zero tendsto_inverse_at_top_nhds_0_nat
lemma not_real_of_infinitesimal_ne_zero (x : β*) :
infinitesimal x β x β 0 β β r : β, x β r :=
Ξ» hi hx r hr, hx $ hr.trans $ coe_eq_zero.2 $
is_st_unique (hr.symm βΈ is_st_refl_real r : is_st x r) hi
theorem infinitesimal_sub_is_st {x : β*} {r : β} (hxr : is_st x r) : infinitesimal (x - r) :=
show is_st (x + -r) 0, by rw βadd_neg_self r; exact is_st_add hxr (is_st_refl_real (-r))
theorem infinitesimal_sub_st {x : β*} (hx : Β¬infinite x) : infinitesimal (x - st x) :=
infinitesimal_sub_is_st $ is_st_st' hx
lemma infinite_pos_iff_infinitesimal_inv_pos {x : β*} :
infinite_pos x β (infinitesimal xβ»ΒΉ β§ 0 < xβ»ΒΉ) :=
β¨ Ξ» hip, β¨ infinitesimal_def.mpr $ Ξ» r hr,
β¨ lt_trans (coe_lt_coe.2 (neg_neg_of_pos hr)) (inv_pos.2 (hip 0)),
(inv_lt (coe_lt_coe.2 hr) (hip 0)).mp (by convert hip rβ»ΒΉ) β©,
inv_pos.2 $ hip 0 β©,
Ξ» β¨hi, hpβ© r, @classical.by_cases (r = 0) (βr < x) (Ξ» h, eq.substr h (inv_pos.mp hp)) $
Ξ» h, lt_of_le_of_lt (coe_le_coe.2 (le_abs_self r))
((inv_lt_inv (inv_pos.mp hp) (coe_lt_coe.2 (abs_pos_of_ne_zero h))).mp
((infinitesimal_def.mp hi) ((abs r)β»ΒΉ) (inv_pos.2 (abs_pos_of_ne_zero h))).2) β©
lemma infinite_neg_iff_infinitesimal_inv_neg {x : β*} :
infinite_neg x β (infinitesimal xβ»ΒΉ β§ xβ»ΒΉ < 0) :=
β¨ Ξ» hin, have hin' : _ := infinite_pos_iff_infinitesimal_inv_pos.mp
(infinite_pos_neg_of_infinite_neg hin),
by rwa [infinitesimal_neg_iff, βneg_pos, neg_inv],
Ξ» hin, have h0 : x β 0 := Ξ» h0, (lt_irrefl (0 : β*) (by convert hin.2; rw [h0, inv_zero])),
by rwa [βneg_pos, infinitesimal_neg_iff, neg_inv,
βinfinite_pos_iff_infinitesimal_inv_pos, βinfinite_neg_iff_infinite_pos_neg] at hin β©
theorem infinitesimal_inv_of_infinite {x : β*} : infinite x β infinitesimal xβ»ΒΉ :=
Ξ» hi, or.cases_on hi
(Ξ» hip, (infinite_pos_iff_infinitesimal_inv_pos.mp hip).1)
(Ξ» hin, (infinite_neg_iff_infinitesimal_inv_neg.mp hin).1)
theorem infinite_of_infinitesimal_inv {x : β*} (h0 : x β 0) (hi : infinitesimal xβ»ΒΉ ) :
infinite x :=
begin
cases (lt_or_gt_of_ne h0) with hn hp,
{ exact or.inr (infinite_neg_iff_infinitesimal_inv_neg.mpr β¨hi, inv_lt_zero.mpr hnβ©) },
{ exact or.inl (infinite_pos_iff_infinitesimal_inv_pos.mpr β¨hi, inv_pos.mpr hpβ©) }
end
theorem infinite_iff_infinitesimal_inv {x : β*} (h0 : x β 0) : infinite x β infinitesimal xβ»ΒΉ :=
β¨ infinitesimal_inv_of_infinite, infinite_of_infinitesimal_inv h0 β©
lemma infinitesimal_pos_iff_infinite_pos_inv {x : β*} :
infinite_pos xβ»ΒΉ β (infinitesimal x β§ 0 < x) :=
by convert infinite_pos_iff_infinitesimal_inv_pos; simp only [inv_inv']
lemma infinitesimal_neg_iff_infinite_neg_inv {x : β*} :
infinite_neg xβ»ΒΉ β (infinitesimal x β§ x < 0) :=
by convert infinite_neg_iff_infinitesimal_inv_neg; simp only [inv_inv']
theorem infinitesimal_iff_infinite_inv {x : β*} (h : x β 0) : infinitesimal x β infinite xβ»ΒΉ :=
by convert (infinite_iff_infinitesimal_inv (inv_ne_zero h)).symm; simp only [inv_inv']
/-!
### `st` stuff that requires infinitesimal machinery
-/
theorem is_st_of_tendsto {f : β β β} {r : β} (hf : tendsto f at_top (π r)) :
is_st (of_seq f) r :=
have hg : tendsto (Ξ» n, f n - r) at_top (π 0) :=
(sub_self r) βΈ (hf.sub tendsto_const_nhds),
by rw [β(zero_add r), β(sub_add_cancel f (Ξ» n, r))];
exact is_st_add (infinitesimal_of_tendsto_zero hg) (is_st_refl_real r)
lemma is_st_inv {x : β*} {r : β} (hi : Β¬ infinitesimal x) : is_st x r β is_st xβ»ΒΉ rβ»ΒΉ :=
Ξ» hxr, have h : x β 0 := (Ξ» h, hi (h.symm βΈ infinitesimal_zero)),
have H : _ := exists_st_of_not_infinite $ not_imp_not.mpr (infinitesimal_iff_infinite_inv h).mpr hi,
Exists.cases_on H $ Ξ» s hs,
have H' : is_st 1 (r * s) := mul_inv_cancel h βΈ is_st_mul hxr hs,
have H'' : s = rβ»ΒΉ := one_div r βΈ eq_one_div_of_mul_eq_one (eq_of_is_st_real H').symm,
H'' βΈ hs
lemma st_inv (x : β*) : st xβ»ΒΉ = (st x)β»ΒΉ :=
begin
by_cases h0 : x = 0,
rw [h0, inv_zero, βcoe_zero, st_id_real, inv_zero],
by_cases h1 : infinitesimal x,
rw [st_infinite ((infinitesimal_iff_infinite_inv h0).mp h1), st_of_is_st h1, inv_zero],
by_cases h2 : infinite x,
rw [st_of_is_st (infinitesimal_inv_of_infinite h2), st_infinite h2, inv_zero],
exact st_of_is_st (is_st_inv h1 (is_st_st' h2)),
end
/-!
### Infinite stuff that requires infinitesimal machinery
-/
lemma infinite_pos_omega : infinite_pos Ο :=
infinite_pos_iff_infinitesimal_inv_pos.mpr β¨infinitesimal_epsilon, epsilon_posβ©
lemma infinite_omega : infinite Ο :=
(infinite_iff_infinitesimal_inv omega_ne_zero).mpr infinitesimal_epsilon
lemma infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos {x y : β*} :
infinite_pos x β Β¬ infinitesimal y β 0 < y β infinite_pos (x * y) :=
Ξ» hx hyβ hyβ r, have hyβ' : _ := not_forall.mp (by rw infinitesimal_def at hyβ; exact hyβ),
Exists.dcases_on hyβ' $ Ξ» rβ hyβ'',
have hyr : _ := by rw [not_imp, βabs_lt, not_lt, abs_of_pos hyβ] at hyβ''; exact hyβ'',
by rw [βdiv_mul_cancel r (ne_of_gt hyr.1), coe_mul];
exact mul_lt_mul (hx (r / rβ)) hyr.2 (coe_lt_coe.2 hyr.1) (le_of_lt (hx 0))
lemma infinite_pos_mul_of_not_infinitesimal_pos_infinite_pos {x y : β*} :
Β¬ infinitesimal x β 0 < x β infinite_pos y β infinite_pos (x * y) :=
Ξ» hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hy hx hp
lemma infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg {x y : β*} :
infinite_neg x β Β¬ infinitesimal y β y < 0 β infinite_pos (x * y) :=
by rw [infinite_neg_iff_infinite_pos_neg, βneg_pos, βneg_mul_neg, infinitesimal_neg_iff];
exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos
lemma infinite_pos_mul_of_not_infinitesimal_neg_infinite_neg {x y : β*} :
Β¬ infinitesimal x β x < 0 β infinite_neg y β infinite_pos (x * y) :=
Ξ» hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hy hx hp
lemma infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg {x y : β*} :
infinite_pos x β Β¬ infinitesimal y β y < 0 β infinite_neg (x * y) :=
by rw [infinite_neg_iff_infinite_pos_neg, βneg_pos, neg_mul_eq_mul_neg, infinitesimal_neg_iff];
exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos
lemma infinite_neg_mul_of_not_infinitesimal_neg_infinite_pos {x y : β*} :
Β¬ infinitesimal x β x < 0 β infinite_pos y β infinite_neg (x * y) :=
Ξ» hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hy hx hp
lemma infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos {x y : β*} :
infinite_neg x β Β¬ infinitesimal y β 0 < y β infinite_neg (x * y) :=
by rw [infinite_neg_iff_infinite_pos_neg, infinite_neg_iff_infinite_pos_neg, neg_mul_eq_neg_mul];
exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos
lemma infinite_neg_mul_of_not_infinitesimal_pos_infinite_neg {x y : β*} :
Β¬ infinitesimal x β 0 < x β infinite_neg y β infinite_neg (x * y) :=
Ξ» hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hy hx hp
lemma infinite_pos_mul_infinite_pos {x y : β*} :
infinite_pos x β infinite_pos y β infinite_pos (x * y) :=
Ξ» hx hy, infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos
hx (not_infinitesimal_of_infinite_pos hy) (hy 0)
lemma infinite_neg_mul_infinite_neg {x y : β*} :
infinite_neg x β infinite_neg y β infinite_pos (x * y) :=
Ξ» hx hy, infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg
hx (not_infinitesimal_of_infinite_neg hy) (hy 0)
lemma infinite_pos_mul_infinite_neg {x y : β*} :
infinite_pos x β infinite_neg y β infinite_neg (x * y) :=
Ξ» hx hy, infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg
hx (not_infinitesimal_of_infinite_neg hy) (hy 0)
lemma infinite_neg_mul_infinite_pos {x y : β*} :
infinite_neg x β infinite_pos y β infinite_neg (x * y) :=
Ξ» hx hy, infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos
hx (not_infinitesimal_of_infinite_pos hy) (hy 0)
lemma infinite_mul_of_infinite_not_infinitesimal {x y : β*} :
infinite x β Β¬ infinitesimal y β infinite (x * y) :=
Ξ» hx hy, have h0 : y < 0 β¨ 0 < y := lt_or_gt_of_ne (Ξ» H0, hy (eq.substr H0 (is_st_refl_real 0))),
or.dcases_on hx
(or.dcases_on h0
(Ξ» H0 Hx, or.inr (infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg Hx hy H0))
(Ξ» H0 Hx, or.inl (infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos Hx hy H0)))
(or.dcases_on h0
(Ξ» H0 Hx, or.inl (infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg Hx hy H0))
(Ξ» H0 Hx, or.inr (infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos Hx hy H0)))
lemma infinite_mul_of_not_infinitesimal_infinite {x y : β*} :
Β¬ infinitesimal x β infinite y β infinite (x * y) :=
Ξ» hx hy, by rw [mul_comm]; exact infinite_mul_of_infinite_not_infinitesimal hy hx
lemma infinite_mul_infinite {x y : β*} : infinite x β infinite y β infinite (x * y) :=
Ξ» hx hy, infinite_mul_of_infinite_not_infinitesimal hx (not_infinitesimal_of_infinite hy)
end hyperreal
|
e7fbf00c2af84c59958cbf1c61174ea49c782ec0 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/order/bounded.lean | 052e94d41851611a56a94c8339dd532aa51e5c5d | [
"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 | 14,160 | lean | /-
Copyright (c) 2022 Violeta HernΓ‘ndez Palacios. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Violeta HernΓ‘ndez Palacios
-/
import order.rel_classes
import data.set.intervals.basic
/-!
# Bounded and unbounded sets
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We prove miscellaneous lemmas about bounded and unbounded sets. Many of these are just variations on
the same ideas, or similar results with a few minor differences. The file is divided into these
different general ideas.
-/
namespace set
variables {Ξ± : Type*} {r : Ξ± β Ξ± β Prop} {s t : set Ξ±}
/-! ### Subsets of bounded and unbounded sets -/
theorem bounded.mono (hst : s β t) (hs : bounded r t) : bounded r s :=
hs.imp $ Ξ» a ha b hb, ha b (hst hb)
theorem unbounded.mono (hst : s β t) (hs : unbounded r s) : unbounded r t :=
Ξ» a, let β¨b, hb, hb'β© := hs a in β¨b, hst hb, hb'β©
/-! ### Alternate characterizations of unboundedness on orders -/
lemma unbounded_le_of_forall_exists_lt [preorder Ξ±] (h : β a, β b β s, a < b) : unbounded (β€) s :=
Ξ» a, let β¨b, hb, hb'β© := h a in β¨b, hb, Ξ» hba, hba.not_lt hb'β©
lemma unbounded_le_iff [linear_order Ξ±] : unbounded (β€) s β β a, β b β s, a < b :=
by simp only [unbounded, not_le]
lemma unbounded_lt_of_forall_exists_le [preorder Ξ±] (h : β a, β b β s, a β€ b) : unbounded (<) s :=
Ξ» a, let β¨b, hb, hb'β© := h a in β¨b, hb, Ξ» hba, hba.not_le hb'β©
lemma unbounded_lt_iff [linear_order Ξ±] : unbounded (<) s β β a, β b β s, a β€ b :=
by simp only [unbounded, not_lt]
lemma unbounded_ge_of_forall_exists_gt [preorder Ξ±] (h : β a, β b β s, b < a) : unbounded (β₯) s :=
@unbounded_le_of_forall_exists_lt Ξ±α΅α΅ _ _ h
lemma unbounded_ge_iff [linear_order Ξ±] : unbounded (β₯) s β β a, β b β s, b < a :=
β¨Ξ» h a, let β¨b, hb, hbaβ© := h a in β¨b, hb, lt_of_not_ge hbaβ©, unbounded_ge_of_forall_exists_gtβ©
lemma unbounded_gt_of_forall_exists_ge [preorder Ξ±] (h : β a, β b β s, b β€ a) : unbounded (>) s :=
Ξ» a, let β¨b, hb, hb'β© := h a in β¨b, hb, Ξ» hba, not_le_of_gt hba hb'β©
lemma unbounded_gt_iff [linear_order Ξ±] : unbounded (>) s β β a, β b β s, b β€ a :=
β¨Ξ» h a, let β¨b, hb, hbaβ© := h a in β¨b, hb, le_of_not_gt hbaβ©, unbounded_gt_of_forall_exists_geβ©
/-! ### Relation between boundedness by strict and nonstrict orders. -/
/-! #### Less and less or equal -/
lemma bounded.rel_mono {r' : Ξ± β Ξ± β Prop} (h : bounded r s) (hrr' : r β€ r') : bounded r' s :=
let β¨a, haβ© := h in β¨a, Ξ» b hb, hrr' b a (ha b hb)β©
lemma bounded_le_of_bounded_lt [preorder Ξ±] (h : bounded (<) s) : bounded (β€) s :=
h.rel_mono $ Ξ» _ _, le_of_lt
lemma unbounded.rel_mono {r' : Ξ± β Ξ± β Prop} (hr : r' β€ r) (h : unbounded r s) : unbounded r' s :=
Ξ» a, let β¨b, hb, hbaβ© := h a in β¨b, hb, Ξ» hba', hba (hr b a hba')β©
lemma unbounded_lt_of_unbounded_le [preorder Ξ±] (h : unbounded (β€) s) :
unbounded (<) s :=
h.rel_mono $ Ξ» _ _, le_of_lt
lemma bounded_le_iff_bounded_lt [preorder Ξ±] [no_max_order Ξ±] : bounded (β€) s β bounded (<) s :=
begin
refine β¨Ξ» h, _, bounded_le_of_bounded_ltβ©,
cases h with a ha,
cases exists_gt a with b hb,
exact β¨b, Ξ» c hc, lt_of_le_of_lt (ha c hc) hbβ©
end
lemma unbounded_lt_iff_unbounded_le [preorder Ξ±] [no_max_order Ξ±] :
unbounded (<) s β unbounded (β€) s :=
by simp_rw [β not_bounded_iff, bounded_le_iff_bounded_lt]
/-! #### Greater and greater or equal -/
lemma bounded_ge_of_bounded_gt [preorder Ξ±] (h : bounded (>) s) : bounded (β₯) s :=
let β¨a, haβ© := h in β¨a, Ξ» b hb, le_of_lt (ha b hb)β©
lemma unbounded_gt_of_unbounded_ge [preorder Ξ±] (h : unbounded (β₯) s) : unbounded (>) s :=
Ξ» a, let β¨b, hb, hbaβ© := h a in β¨b, hb, Ξ» hba', hba (le_of_lt hba')β©
lemma bounded_ge_iff_bounded_gt [preorder Ξ±] [no_min_order Ξ±] : bounded (β₯) s β bounded (>) s :=
@bounded_le_iff_bounded_lt Ξ±α΅α΅ _ _ _
lemma unbounded_gt_iff_unbounded_ge [preorder Ξ±] [no_min_order Ξ±] :
unbounded (>) s β unbounded (β₯) s :=
@unbounded_lt_iff_unbounded_le Ξ±α΅α΅ _ _ _
/-! ### The universal set -/
theorem unbounded_le_univ [has_le Ξ±] [no_top_order Ξ±] : unbounded (β€) (@set.univ Ξ±) :=
Ξ» a, let β¨b, hbβ© := exists_not_le a in β¨b, β¨β©, hbβ©
theorem unbounded_lt_univ [preorder Ξ±] [no_top_order Ξ±] : unbounded (<) (@set.univ Ξ±) :=
unbounded_lt_of_unbounded_le unbounded_le_univ
theorem unbounded_ge_univ [has_le Ξ±] [no_bot_order Ξ±] : unbounded (β₯) (@set.univ Ξ±) :=
Ξ» a, let β¨b, hbβ© := exists_not_ge a in β¨b, β¨β©, hbβ©
theorem unbounded_gt_univ [preorder Ξ±] [no_bot_order Ξ±] : unbounded (>) (@set.univ Ξ±) :=
unbounded_gt_of_unbounded_ge unbounded_ge_univ
/-! ### Bounded and unbounded intervals -/
theorem bounded_self (a : Ξ±) : bounded r {b | r b a} :=
β¨a, Ξ» x, idβ©
/-! #### Half-open bounded intervals -/
theorem bounded_lt_Iio [preorder Ξ±] (a : Ξ±) : bounded (<) (set.Iio a) :=
bounded_self a
theorem bounded_le_Iio [preorder Ξ±] (a : Ξ±) : bounded (β€) (set.Iio a) :=
bounded_le_of_bounded_lt (bounded_lt_Iio a)
theorem bounded_le_Iic [preorder Ξ±] (a : Ξ±) : bounded (β€) (set.Iic a) :=
bounded_self a
theorem bounded_lt_Iic [preorder Ξ±] [no_max_order Ξ±] (a : Ξ±) : bounded (<) (set.Iic a) :=
by simp only [β bounded_le_iff_bounded_lt, bounded_le_Iic]
theorem bounded_gt_Ioi [preorder Ξ±] (a : Ξ±) : bounded (>) (set.Ioi a) :=
bounded_self a
theorem bounded_ge_Ioi [preorder Ξ±] (a : Ξ±) : bounded (β₯) (set.Ioi a) :=
bounded_ge_of_bounded_gt (bounded_gt_Ioi a)
theorem bounded_ge_Ici [preorder Ξ±] (a : Ξ±) : bounded (β₯) (set.Ici a) :=
bounded_self a
theorem bounded_gt_Ici [preorder Ξ±] [no_min_order Ξ±] (a : Ξ±) : bounded (>) (set.Ici a) :=
by simp only [β bounded_ge_iff_bounded_gt, bounded_ge_Ici]
/-! #### Other bounded intervals -/
theorem bounded_lt_Ioo [preorder Ξ±] (a b : Ξ±) : bounded (<) (set.Ioo a b) :=
(bounded_lt_Iio b).mono set.Ioo_subset_Iio_self
theorem bounded_lt_Ico [preorder Ξ±] (a b : Ξ±) : bounded (<) (set.Ico a b) :=
(bounded_lt_Iio b).mono set.Ico_subset_Iio_self
theorem bounded_lt_Ioc [preorder Ξ±] [no_max_order Ξ±] (a b : Ξ±) : bounded (<) (set.Ioc a b) :=
(bounded_lt_Iic b).mono set.Ioc_subset_Iic_self
theorem bounded_lt_Icc [preorder Ξ±] [no_max_order Ξ±] (a b : Ξ±) : bounded (<) (set.Icc a b) :=
(bounded_lt_Iic b).mono set.Icc_subset_Iic_self
theorem bounded_le_Ioo [preorder Ξ±] (a b : Ξ±) : bounded (β€) (set.Ioo a b) :=
(bounded_le_Iio b).mono set.Ioo_subset_Iio_self
theorem bounded_le_Ico [preorder Ξ±] (a b : Ξ±) : bounded (β€) (set.Ico a b) :=
(bounded_le_Iio b).mono set.Ico_subset_Iio_self
theorem bounded_le_Ioc [preorder Ξ±] (a b : Ξ±) : bounded (β€) (set.Ioc a b) :=
(bounded_le_Iic b).mono set.Ioc_subset_Iic_self
theorem bounded_le_Icc [preorder Ξ±] (a b : Ξ±) : bounded (β€) (set.Icc a b) :=
(bounded_le_Iic b).mono set.Icc_subset_Iic_self
theorem bounded_gt_Ioo [preorder Ξ±] (a b : Ξ±) : bounded (>) (set.Ioo a b) :=
(bounded_gt_Ioi a).mono set.Ioo_subset_Ioi_self
theorem bounded_gt_Ioc [preorder Ξ±] (a b : Ξ±) : bounded (>) (set.Ioc a b) :=
(bounded_gt_Ioi a).mono set.Ioc_subset_Ioi_self
theorem bounded_gt_Ico [preorder Ξ±] [no_min_order Ξ±] (a b : Ξ±) : bounded (>) (set.Ico a b) :=
(bounded_gt_Ici a).mono set.Ico_subset_Ici_self
theorem bounded_gt_Icc [preorder Ξ±] [no_min_order Ξ±] (a b : Ξ±) : bounded (>) (set.Icc a b) :=
(bounded_gt_Ici a).mono set.Icc_subset_Ici_self
theorem bounded_ge_Ioo [preorder Ξ±] (a b : Ξ±) : bounded (β₯) (set.Ioo a b) :=
(bounded_ge_Ioi a).mono set.Ioo_subset_Ioi_self
theorem bounded_ge_Ioc [preorder Ξ±] (a b : Ξ±) : bounded (β₯) (set.Ioc a b) :=
(bounded_ge_Ioi a).mono set.Ioc_subset_Ioi_self
theorem bounded_ge_Ico [preorder Ξ±] (a b : Ξ±) : bounded (β₯) (set.Ico a b) :=
(bounded_ge_Ici a).mono set.Ico_subset_Ici_self
theorem bounded_ge_Icc [preorder Ξ±] (a b : Ξ±) : bounded (β₯) (set.Icc a b) :=
(bounded_ge_Ici a).mono set.Icc_subset_Ici_self
/-! #### Unbounded intervals -/
theorem unbounded_le_Ioi [semilattice_sup Ξ±] [no_max_order Ξ±] (a : Ξ±) : unbounded (β€) (set.Ioi a) :=
Ξ» b, let β¨c, hcβ© := exists_gt (a β b) in
β¨c, le_sup_left.trans_lt hc, (le_sup_right.trans_lt hc).not_leβ©
theorem unbounded_le_Ici [semilattice_sup Ξ±] [no_max_order Ξ±] (a : Ξ±) : unbounded (β€) (set.Ici a) :=
(unbounded_le_Ioi a).mono set.Ioi_subset_Ici_self
theorem unbounded_lt_Ioi [semilattice_sup Ξ±] [no_max_order Ξ±] (a : Ξ±) : unbounded (<) (set.Ioi a) :=
unbounded_lt_of_unbounded_le (unbounded_le_Ioi a)
theorem unbounded_lt_Ici [semilattice_sup Ξ±] (a : Ξ±) : unbounded (<) (set.Ici a) :=
Ξ» b, β¨a β b, le_sup_left, le_sup_right.not_ltβ©
/-! ### Bounded initial segments -/
theorem bounded_inter_not (H : β a b, β m, β c, r c a β¨ r c b β r c m) (a : Ξ±) :
bounded r (s β© {b | Β¬ r b a}) β bounded r s :=
begin
refine β¨_, bounded.mono (set.inter_subset_left s _)β©,
rintro β¨b, hbβ©,
cases H a b with m hm,
exact β¨m, Ξ» c hc, hm c (or_iff_not_imp_left.2 (Ξ» hca, (hb c β¨hc, hcaβ©)))β©
end
theorem unbounded_inter_not (H : β a b, β m, β c, r c a β¨ r c b β r c m) (a : Ξ±) :
unbounded r (s β© {b | Β¬ r b a}) β unbounded r s :=
by simp_rw [β not_bounded_iff, bounded_inter_not H]
/-! #### Less or equal -/
theorem bounded_le_inter_not_le [semilattice_sup Ξ±] (a : Ξ±) :
bounded (β€) (s β© {b | Β¬ b β€ a}) β bounded (β€) s :=
bounded_inter_not (Ξ» x y, β¨x β y, Ξ» z h, h.elim le_sup_of_le_left le_sup_of_le_rightβ©) a
theorem unbounded_le_inter_not_le [semilattice_sup Ξ±] (a : Ξ±) :
unbounded (β€) (s β© {b | Β¬ b β€ a}) β unbounded (β€) s :=
begin
rw [βnot_bounded_iff, βnot_bounded_iff, not_iff_not],
exact bounded_le_inter_not_le a
end
theorem bounded_le_inter_lt [linear_order Ξ±] (a : Ξ±) :
bounded (β€) (s β© {b | a < b}) β bounded (β€) s :=
by simp_rw [β not_le, bounded_le_inter_not_le]
theorem unbounded_le_inter_lt [linear_order Ξ±] (a : Ξ±) :
unbounded (β€) (s β© {b | a < b}) β unbounded (β€) s :=
by { convert unbounded_le_inter_not_le a, ext, exact lt_iff_not_le }
theorem bounded_le_inter_le [linear_order Ξ±] (a : Ξ±) :
bounded (β€) (s β© {b | a β€ b}) β bounded (β€) s :=
begin
refine β¨_, bounded.mono (set.inter_subset_left s _)β©,
rw β@bounded_le_inter_lt _ s _ a,
exact bounded.mono (Ξ» x β¨hx, hx'β©, β¨hx, le_of_lt hx'β©)
end
theorem unbounded_le_inter_le [linear_order Ξ±] (a : Ξ±) :
unbounded (β€) (s β© {b | a β€ b}) β unbounded (β€) s :=
begin
rw [βnot_bounded_iff, βnot_bounded_iff, not_iff_not],
exact bounded_le_inter_le a
end
/-! #### Less than -/
theorem bounded_lt_inter_not_lt [semilattice_sup Ξ±] (a : Ξ±) :
bounded (<) (s β© {b | Β¬ b < a}) β bounded (<) s :=
bounded_inter_not (Ξ» x y, β¨x β y, Ξ» z h, h.elim lt_sup_of_lt_left lt_sup_of_lt_rightβ©) a
theorem unbounded_lt_inter_not_lt [semilattice_sup Ξ±] (a : Ξ±) :
unbounded (<) (s β© {b | Β¬ b < a}) β unbounded (<) s :=
begin
rw [βnot_bounded_iff, βnot_bounded_iff, not_iff_not],
exact bounded_lt_inter_not_lt a
end
theorem bounded_lt_inter_le [linear_order Ξ±] (a : Ξ±) :
bounded (<) (s β© {b | a β€ b}) β bounded (<) s :=
by { convert bounded_lt_inter_not_lt a, ext, exact not_lt.symm }
theorem unbounded_lt_inter_le [linear_order Ξ±] (a : Ξ±) :
unbounded (<) (s β© {b | a β€ b}) β unbounded (<) s :=
by { convert unbounded_lt_inter_not_lt a, ext, exact not_lt.symm }
theorem bounded_lt_inter_lt [linear_order Ξ±] [no_max_order Ξ±] (a : Ξ±) :
bounded (<) (s β© {b | a < b}) β bounded (<) s :=
begin
rw [βbounded_le_iff_bounded_lt, βbounded_le_iff_bounded_lt],
exact bounded_le_inter_lt a
end
theorem unbounded_lt_inter_lt [linear_order Ξ±] [no_max_order Ξ±] (a : Ξ±) :
unbounded (<) (s β© {b | a < b}) β unbounded (<) s :=
begin
rw [βnot_bounded_iff, βnot_bounded_iff, not_iff_not],
exact bounded_lt_inter_lt a
end
/-! #### Greater or equal -/
theorem bounded_ge_inter_not_ge [semilattice_inf Ξ±] (a : Ξ±) :
bounded (β₯) (s β© {b | Β¬ a β€ b}) β bounded (β₯) s :=
@bounded_le_inter_not_le Ξ±α΅α΅ s _ a
theorem unbounded_ge_inter_not_ge [semilattice_inf Ξ±] (a : Ξ±) :
unbounded (β₯) (s β© {b | Β¬ a β€ b}) β unbounded (β₯) s :=
@unbounded_le_inter_not_le Ξ±α΅α΅ s _ a
theorem bounded_ge_inter_gt [linear_order Ξ±] (a : Ξ±) :
bounded (β₯) (s β© {b | b < a}) β bounded (β₯) s :=
@bounded_le_inter_lt Ξ±α΅α΅ s _ a
theorem unbounded_ge_inter_gt [linear_order Ξ±] (a : Ξ±) :
unbounded (β₯) (s β© {b | b < a}) β unbounded (β₯) s :=
@unbounded_le_inter_lt Ξ±α΅α΅ s _ a
theorem bounded_ge_inter_ge [linear_order Ξ±] (a : Ξ±) :
bounded (β₯) (s β© {b | b β€ a}) β bounded (β₯) s :=
@bounded_le_inter_le Ξ±α΅α΅ s _ a
theorem unbounded_ge_iff_unbounded_inter_ge [linear_order Ξ±] (a : Ξ±) :
unbounded (β₯) (s β© {b | b β€ a}) β unbounded (β₯) s :=
@unbounded_le_inter_le Ξ±α΅α΅ s _ a
/-! #### Greater than -/
theorem bounded_gt_inter_not_gt [semilattice_inf Ξ±] (a : Ξ±) :
bounded (>) (s β© {b | Β¬ a < b}) β bounded (>) s :=
@bounded_lt_inter_not_lt Ξ±α΅α΅ s _ a
theorem unbounded_gt_inter_not_gt [semilattice_inf Ξ±] (a : Ξ±) :
unbounded (>) (s β© {b | Β¬ a < b}) β unbounded (>) s :=
@unbounded_lt_inter_not_lt Ξ±α΅α΅ s _ a
theorem bounded_gt_inter_ge [linear_order Ξ±] (a : Ξ±) :
bounded (>) (s β© {b | b β€ a}) β bounded (>) s :=
@bounded_lt_inter_le Ξ±α΅α΅ s _ a
theorem unbounded_inter_ge [linear_order Ξ±] (a : Ξ±) :
unbounded (>) (s β© {b | b β€ a}) β unbounded (>) s :=
@unbounded_lt_inter_le Ξ±α΅α΅ s _ a
theorem bounded_gt_inter_gt [linear_order Ξ±] [no_min_order Ξ±] (a : Ξ±) :
bounded (>) (s β© {b | b < a}) β bounded (>) s :=
@bounded_lt_inter_lt Ξ±α΅α΅ s _ _ a
theorem unbounded_gt_inter_gt [linear_order Ξ±] [no_min_order Ξ±] (a : Ξ±) :
unbounded (>) (s β© {b | b < a}) β unbounded (>) s :=
@unbounded_lt_inter_lt Ξ±α΅α΅ s _ _ a
end set
|
c23c9918b73e7e3cb2245a66117a6d32f7998f43 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/polynomial/default.lean | 86f50b00e1f0f55ae74a428c7da16f7fa2dfe14a | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 331 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.polynomial.algebra_map
import Mathlib.data.polynomial.field_division
import Mathlib.data.polynomial.derivative
import Mathlib.data.polynomial.identities
import Mathlib.data.polynomial.integral_normalization
import Mathlib.PostPort
namespace Mathlib
|
c177da4cbde2ec64192b6c490ddbd4f6291e18d8 | 367134ba5a65885e863bdc4507601606690974c1 | /src/linear_algebra/linear_pmap.lean | 03c39708b6c4196d1180dc035e48a00251f6df51 | [
"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 | 16,635 | lean | /-
Copyright (c) 2020 Yury Kudryashov All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import linear_algebra.basic
import linear_algebra.prod
/-!
# Partially defined linear maps
A `linear_pmap R E F` is a linear map from a submodule of `E` to `F`. We define
a `semilattice_inf_bot` instance on this this, and define three operations:
* `mk_span_singleton` defines a partial linear map defined on the span of a singleton.
* `sup` takes two partial linear maps `f`, `g` that agree on the intersection of their
domains, and returns the unique partial linear map on `f.domain β g.domain` that
extends both `f` and `g`.
* `Sup` takes a `directed_on (β€)` set of partial linear maps, and returns the unique
partial linear map on the `Sup` of their domains that extends all these maps.
Partially defined maps are currently used in `mathlib` to prove Hahn-Banach theorem
and its variations. Namely, `linear_pmap.Sup` implies that every chain of `linear_pmap`s
is bounded above.
Another possible use (not yet in `mathlib`) would be the theory of unbounded linear operators.
-/
open set
universes u v w
/-- A `linear_pmap R E F` is a linear map from a submodule of `E` to `F`. -/
structure linear_pmap (R : Type u) [ring R] (E : Type v) [add_comm_group E] [module R E]
(F : Type w) [add_comm_group F] [module R F] :=
(domain : submodule R E)
(to_fun : domain ββ[R] F)
variables {R : Type*} [ring R] {E : Type*} [add_comm_group E] [module R E]
{F : Type*} [add_comm_group F] [module R F]
{G : Type*} [add_comm_group G] [module R G]
namespace linear_pmap
open submodule
instance : has_coe_to_fun (linear_pmap R E F) :=
β¨Ξ» f : linear_pmap R E F, f.domain β F, Ξ» f, f.to_funβ©
@[simp] lemma to_fun_eq_coe (f : linear_pmap R E F) (x : f.domain) :
f.to_fun x = f x := rfl
@[simp] lemma map_zero (f : linear_pmap R E F) : f 0 = 0 := f.to_fun.map_zero
lemma map_add (f : linear_pmap R E F) (x y : f.domain) : f (x + y) = f x + f y :=
f.to_fun.map_add x y
lemma map_neg (f : linear_pmap R E F) (x : f.domain) : f (-x) = -f x :=
f.to_fun.map_neg x
lemma map_sub (f : linear_pmap R E F) (x y : f.domain) : f (x - y) = f x - f y :=
f.to_fun.map_sub x y
lemma map_smul (f : linear_pmap R E F) (c : R) (x : f.domain) : f (c β’ x) = c β’ f x :=
f.to_fun.map_smul c x
@[simp] lemma mk_apply (p : submodule R E) (f : p ββ[R] F) (x : p) :
mk p f x = f x := rfl
/-- The unique `linear_pmap` on `R β x` that sends `x` to `y`. This version works for modules
over rings, and requires a proof of `β c, c β’ x = 0 β c β’ y = 0`. -/
noncomputable def mk_span_singleton' (x : E) (y : F) (H : β c : R, c β’ x = 0 β c β’ y = 0) :
linear_pmap R E F :=
begin
replace H : β cβ cβ : R, cβ β’ x = cβ β’ x β cβ β’ y = cβ β’ y,
{ intros cβ cβ h,
rw [β sub_eq_zero, β sub_smul] at h β’,
exact H _ h },
refine β¨R β x, Ξ» z, _, _, _β©,
{ exact (classical.some (mem_span_singleton.1 z.prop) β’ y) },
{ intros zβ zβ,
rw [β add_smul],
apply H,
simp only [add_smul, sub_smul, classical.some_spec (mem_span_singleton.1 _)],
apply coe_add },
{ intros c z,
rw [smul_smul],
apply H,
simp only [mul_smul, classical.some_spec (mem_span_singleton.1 _)],
apply coe_smul }
end
@[simp] lemma domain_mk_span_singleton (x : E) (y : F) (H : β c : R, c β’ x = 0 β c β’ y = 0) :
(mk_span_singleton' x y H).domain = R β x := rfl
@[simp] lemma mk_span_singleton_apply (x : E) (y : F) (H : β c : R, c β’ x = 0 β c β’ y = 0)
(c : R) (h) :
mk_span_singleton' x y H β¨c β’ x, hβ© = c β’ y :=
begin
dsimp [mk_span_singleton'],
rw [β sub_eq_zero, β sub_smul],
apply H,
simp only [sub_smul, one_smul, sub_eq_zero],
apply classical.some_spec (mem_span_singleton.1 h),
end
/-- The unique `linear_pmap` on `span R {x}` that sends a non-zero vector `x` to `y`.
This version works for modules over division rings. -/
@[reducible] noncomputable def mk_span_singleton {K E F : Type*} [division_ring K]
[add_comm_group E] [module K E] [add_comm_group F] [module K F] (x : E) (y : F) (hx : x β 0) :
linear_pmap K E F :=
mk_span_singleton' x y $ Ξ» c hc, (smul_eq_zero.1 hc).elim
(Ξ» hc, by rw [hc, zero_smul]) (Ξ» hx', absurd hx' hx)
/-- Projection to the first coordinate as a `linear_pmap` -/
protected def fst (p : submodule R E) (p' : submodule R F) : linear_pmap R (E Γ F) E :=
{ domain := p.prod p',
to_fun := (linear_map.fst R E F).comp (p.prod p').subtype }
@[simp] lemma fst_apply (p : submodule R E) (p' : submodule R F) (x : p.prod p') :
linear_pmap.fst p p' x = (x : E Γ F).1 := rfl
/-- Projection to the second coordinate as a `linear_pmap` -/
protected def snd (p : submodule R E) (p' : submodule R F) : linear_pmap R (E Γ F) F :=
{ domain := p.prod p',
to_fun := (linear_map.snd R E F).comp (p.prod p').subtype }
@[simp] lemma snd_apply (p : submodule R E) (p' : submodule R F) (x : p.prod p') :
linear_pmap.snd p p' x = (x : E Γ F).2 := rfl
instance : has_neg (linear_pmap R E F) :=
β¨Ξ» f, β¨f.domain, -f.to_funβ©β©
@[simp] lemma neg_apply (f : linear_pmap R E F) (x) : (-f) x = -(f x) := rfl
instance : has_le (linear_pmap R E F) :=
β¨Ξ» f g, f.domain β€ g.domain β§ β β¦x : f.domainβ¦ β¦y : g.domainβ¦ (h : (x:E) = y), f x = g yβ©
lemma eq_of_le_of_domain_eq {f g : linear_pmap R E F} (hle : f β€ g) (heq : f.domain = g.domain) :
f = g :=
begin
rcases f with β¨f_dom, fβ©,
rcases g with β¨g_dom, gβ©,
change f_dom = g_dom at heq,
subst g_dom,
have : f = g, from linear_map.ext (Ξ» x, hle.2 rfl),
subst g
end
/-- Given two partial linear maps `f`, `g`, the set of points `x` such that
both `f` and `g` are defined at `x` and `f x = g x` form a submodule. -/
def eq_locus (f g : linear_pmap R E F) : submodule R E :=
{ carrier := {x | β (hf : x β f.domain) (hg : x β g.domain), f β¨x, hfβ© = g β¨x, hgβ©},
zero_mem' := β¨zero_mem _, zero_mem _, f.map_zero.trans g.map_zero.symmβ©,
add_mem' := Ξ» x y β¨hfx, hgx, hxβ© β¨hfy, hgy, hyβ©, β¨add_mem _ hfx hfy, add_mem _ hgx hgy,
by erw [f.map_add β¨x, hfxβ© β¨y, hfyβ©, g.map_add β¨x, hgxβ© β¨y, hgyβ©, hx, hy]β©,
smul_mem' := Ξ» c x β¨hfx, hgx, hxβ©, β¨smul_mem _ c hfx, smul_mem _ c hgx,
by erw [f.map_smul c β¨x, hfxβ©, g.map_smul c β¨x, hgxβ©, hx]β© }
instance : has_inf (linear_pmap R E F) :=
β¨Ξ» f g, β¨f.eq_locus g, f.to_fun.comp $ of_le $ Ξ» x hx, hx.fstβ©β©
instance : has_bot (linear_pmap R E F) := β¨β¨β₯, 0β©β©
instance : inhabited (linear_pmap R E F) := β¨β₯β©
instance : semilattice_inf_bot (linear_pmap R E F) :=
{ le := (β€),
le_refl := Ξ» f, β¨le_refl f.domain, Ξ» x y h, subtype.eq h βΈ rflβ©,
le_trans := Ξ» f g h β¨fg_le, fg_eqβ© β¨gh_le, gh_eqβ©,
β¨le_trans fg_le gh_le, Ξ» x z hxz,
have hxy : (x:E) = of_le fg_le x, from rfl,
(fg_eq hxy).trans (gh_eq $ hxy.symm.trans hxz)β©,
le_antisymm := Ξ» f g fg gf, eq_of_le_of_domain_eq fg (le_antisymm fg.1 gf.1),
bot := β₯,
bot_le := Ξ» f, β¨bot_le, Ξ» x y h,
have hx : x = 0, from subtype.eq ((mem_bot R).1 x.2),
have hy : y = 0, from subtype.eq (h.symm.trans (congr_arg _ hx)),
by rw [hx, hy, map_zero, map_zero]β©,
inf := (β),
le_inf := Ξ» f g h β¨fg_le, fg_eqβ© β¨fh_le, fh_eqβ©,
β¨Ξ» x hx, β¨fg_le hx, fh_le hx,
by refine (fg_eq _).symm.trans (fh_eq _); [exact β¨x, hxβ©, refl, refl]β©,
Ξ» x β¨y, yg, hyβ© h, by { apply fg_eq, exact h }β©,
inf_le_left := Ξ» f g, β¨Ξ» x hx, hx.fst,
Ξ» x y h, congr_arg f $ subtype.eq $ by exact hβ©,
inf_le_right := Ξ» f g, β¨Ξ» x hx, hx.snd.fst,
Ξ» β¨x, xf, xg, hxβ© y h, hx.trans $ congr_arg g $ subtype.eq $ by exact hβ© }
lemma le_of_eq_locus_ge {f g : linear_pmap R E F} (H : f.domain β€ f.eq_locus g) :
f β€ g :=
suffices f β€ f β g, from le_trans this inf_le_right,
β¨H, Ξ» x y hxy, ((inf_le_left : f β g β€ f).2 hxy.symm).symmβ©
lemma domain_mono : strict_mono (@domain R _ E _ _ F _ _) :=
Ξ» f g hlt, lt_of_le_of_ne hlt.1.1 $ Ξ» heq, ne_of_lt hlt $
eq_of_le_of_domain_eq (le_of_lt hlt) heq
private lemma sup_aux (f g : linear_pmap R E F)
(h : β (x : f.domain) (y : g.domain), (x:E) = y β f x = g y) :
β fg : β₯(f.domain β g.domain) ββ[R] F,
β (x : f.domain) (y : g.domain) (z),
(x:E) + y = βz β fg z = f x + g y :=
begin
choose x hx y hy hxy using Ξ» z : f.domain β g.domain, mem_sup.1 z.prop,
set fg := Ξ» z, f β¨x z, hx zβ© + g β¨y z, hy zβ©,
have fg_eq : β (x' : f.domain) (y' : g.domain) (z' : f.domain β g.domain) (H : (x':E) + y' = z'),
fg z' = f x' + g y',
{ intros x' y' z' H,
dsimp [fg],
rw [add_comm, β sub_eq_sub_iff_add_eq_add, eq_comm, β map_sub, β map_sub],
apply h,
simp only [β eq_sub_iff_add_eq] at hxy,
simp only [coe_sub, coe_mk, coe_mk, hxy, β sub_add, β sub_sub, sub_self, zero_sub, β H],
apply neg_add_eq_sub },
refine β¨β¨fg, _, _β©, fg_eqβ©,
{ rintros β¨zβ, hzββ© β¨zβ, hzββ©,
rw [β add_assoc, add_right_comm (f _), β map_add, add_assoc, β map_add],
apply fg_eq,
simp only [coe_add, coe_mk, β add_assoc],
rw [add_right_comm (x _), hxy, add_assoc, hxy, coe_mk, coe_mk] },
{ intros c z,
rw [smul_add, β map_smul, β map_smul],
apply fg_eq,
simp only [coe_smul, coe_mk, β smul_add, hxy] },
end
/-- Given two partial linear maps that agree on the intersection of their domains,
`f.sup g h` is the unique partial linear map on `f.domain β g.domain` that agrees
with `f` and `g`. -/
protected noncomputable def sup (f g : linear_pmap R E F)
(h : β (x : f.domain) (y : g.domain), (x:E) = y β f x = g y) :
linear_pmap R E F :=
β¨_, classical.some (sup_aux f g h)β©
@[simp] lemma domain_sup (f g : linear_pmap R E F)
(h : β (x : f.domain) (y : g.domain), (x:E) = y β f x = g y) :
(f.sup g h).domain = f.domain β g.domain :=
rfl
lemma sup_apply {f g : linear_pmap R E F}
(H : β (x : f.domain) (y : g.domain), (x:E) = y β f x = g y)
(x y z) (hz : (βx:E) + βy = βz) :
f.sup g H z = f x + g y :=
classical.some_spec (sup_aux f g H) x y z hz
protected lemma left_le_sup (f g : linear_pmap R E F)
(h : β (x : f.domain) (y : g.domain), (x:E) = y β f x = g y) :
f β€ f.sup g h :=
begin
refine β¨le_sup_left, Ξ» zβ zβ hz, _β©,
rw [β add_zero (f _), β g.map_zero],
refine (sup_apply h _ _ _ _).symm,
simpa
end
protected lemma right_le_sup (f g : linear_pmap R E F)
(h : β (x : f.domain) (y : g.domain), (x:E) = y β f x = g y) :
g β€ f.sup g h :=
begin
refine β¨le_sup_right, Ξ» zβ zβ hz, _β©,
rw [β zero_add (g _), β f.map_zero],
refine (sup_apply h _ _ _ _).symm,
simpa
end
protected lemma sup_le {f g h : linear_pmap R E F}
(H : β (x : f.domain) (y : g.domain), (x:E) = y β f x = g y)
(fh : f β€ h) (gh : g β€ h) :
f.sup g H β€ h :=
have Hf : f β€ (f.sup g H) β h, from le_inf (f.left_le_sup g H) fh,
have Hg : g β€ (f.sup g H) β h, from le_inf (f.right_le_sup g H) gh,
le_of_eq_locus_ge $ sup_le Hf.1 Hg.1
/-- Hypothesis for `linear_pmap.sup` holds, if `f.domain` is disjoint with `g.domain`. -/
lemma sup_h_of_disjoint (f g : linear_pmap R E F) (h : disjoint f.domain g.domain)
(x : f.domain) (y : g.domain) (hxy : (x:E) = y) :
f x = g y :=
begin
rw [disjoint_def] at h,
have hy : y = 0, from subtype.eq (h y (hxy βΈ x.2) y.2),
have hx : x = 0, from subtype.eq (hxy.trans $ congr_arg _ hy),
simp [*]
end
section
variables {K : Type*} [division_ring K] [module K E] [module K F]
/-- Extend a `linear_pmap` to `f.domain β K β x`. -/
noncomputable def sup_span_singleton (f : linear_pmap K E F) (x : E) (y : F) (hx : x β f.domain) :
linear_pmap K E F :=
f.sup (mk_span_singleton x y (Ξ» hβ, hx $ hβ.symm βΈ f.domain.zero_mem)) $
sup_h_of_disjoint _ _ $ by simpa [disjoint_span_singleton]
@[simp] lemma domain_sup_span_singleton (f : linear_pmap K E F) (x : E) (y : F)
(hx : x β f.domain) :
(f.sup_span_singleton x y hx).domain = f.domain β K β x := rfl
@[simp] lemma sup_span_singleton_apply_mk (f : linear_pmap K E F) (x : E) (y : F)
(hx : x β f.domain) (x' : E) (hx' : x' β f.domain) (c : K) :
f.sup_span_singleton x y hx β¨x' + c β’ x,
mem_sup.2 β¨x', hx', _, mem_span_singleton.2 β¨c, rflβ©, rflβ©β© = f β¨x', hx'β© + c β’ y :=
begin
erw [sup_apply _ β¨x', hx'β© β¨c β’ x, _β©, mk_span_singleton_apply],
refl,
exact mem_span_singleton.2 β¨c, rflβ©
end
end
private lemma Sup_aux (c : set (linear_pmap R E F)) (hc : directed_on (β€) c) :
β f : β₯(Sup (domain '' c)) ββ[R] F, (β¨_, fβ© : linear_pmap R E F) β upper_bounds c :=
begin
cases c.eq_empty_or_nonempty with ceq cne, { subst c, simp },
have hdir : directed_on (β€) (domain '' c),
from directed_on_image.2 (hc.mono domain_mono.monotone),
have P : Ξ x : Sup (domain '' c), {p : c // (x : E) β p.val.domain },
{ rintros x,
apply classical.indefinite_description,
have := (mem_Sup_of_directed (cne.image _) hdir).1 x.2,
rwa [bex_image_iff, set_coe.exists'] at this },
set f : Sup (domain '' c) β F := Ξ» x, (P x).val.val β¨x, (P x).propertyβ©,
have f_eq : β (p : c) (x : Sup (domain '' c)) (y : p.1.1) (hxy : (x : E) = y), f x = p.1 y,
{ intros p x y hxy,
rcases hc (P x).1.1 (P x).1.2 p.1 p.2 with β¨q, hqc, hxq, hpqβ©,
refine (hxq.2 _).trans (hpq.2 _).symm,
exacts [of_le hpq.1 y, hxy, rfl] },
refine β¨β¨f, _, _β©, _β©,
{ intros x y,
rcases hc (P x).1.1 (P x).1.2 (P y).1.1 (P y).1.2 with β¨p, hpc, hpx, hpyβ©,
set x' := of_le hpx.1 β¨x, (P x).2β©,
set y' := of_le hpy.1 β¨y, (P y).2β©,
rw [f_eq β¨p, hpcβ© x x' rfl, f_eq β¨p, hpcβ© y y' rfl, f_eq β¨p, hpcβ© (x + y) (x' + y') rfl,
map_add] },
{ intros c x,
rw [f_eq (P x).1 (c β’ x) (c β’ β¨x, (P x).2β©) rfl, β map_smul] },
{ intros p hpc,
refine β¨le_Sup $ mem_image_of_mem domain hpc, Ξ» x y hxy, eq.symm _β©,
exact f_eq β¨p, hpcβ© _ _ hxy.symm }
end
/-- Glue a collection of partially defined linear maps to a linear map defined on `Sup`
of these submodules. -/
protected noncomputable def Sup (c : set (linear_pmap R E F)) (hc : directed_on (β€) c) :
linear_pmap R E F :=
β¨_, classical.some $ Sup_aux c hcβ©
protected lemma le_Sup {c : set (linear_pmap R E F)} (hc : directed_on (β€) c)
{f : linear_pmap R E F} (hf : f β c) : f β€ linear_pmap.Sup c hc :=
classical.some_spec (Sup_aux c hc) hf
protected lemma Sup_le {c : set (linear_pmap R E F)} (hc : directed_on (β€) c)
{g : linear_pmap R E F} (hg : β f β c, f β€ g) : linear_pmap.Sup c hc β€ g :=
le_of_eq_locus_ge $ Sup_le $ Ξ» _ β¨f, hf, eqβ©, eq βΈ
have f β€ (linear_pmap.Sup c hc) β g, from le_inf (linear_pmap.le_Sup _ hf) (hg f hf),
this.1
end linear_pmap
namespace linear_map
/-- Restrict a linear map to a submodule, reinterpreting the result as a `linear_pmap`. -/
def to_pmap (f : E ββ[R] F) (p : submodule R E) : linear_pmap R E F :=
β¨p, f.comp p.subtypeβ©
@[simp] lemma to_pmap_apply (f : E ββ[R] F) (p : submodule R E) (x : p) :
f.to_pmap p x = f x := rfl
/-- Compose a linear map with a `linear_pmap` -/
def comp_pmap (g : F ββ[R] G) (f : linear_pmap R E F) : linear_pmap R E G :=
{ domain := f.domain,
to_fun := g.comp f.to_fun }
@[simp] lemma comp_pmap_apply (g : F ββ[R] G) (f : linear_pmap R E F) (x) :
g.comp_pmap f x = g (f x) := rfl
end linear_map
namespace linear_pmap
/-- Restrict codomain of a `linear_pmap` -/
def cod_restrict (f : linear_pmap R E F) (p : submodule R F) (H : β x, f x β p) :
linear_pmap R E p :=
{ domain := f.domain,
to_fun := f.to_fun.cod_restrict p H }
/-- Compose two `linear_pmap`s -/
def comp (g : linear_pmap R F G) (f : linear_pmap R E F)
(H : β x : f.domain, f x β g.domain) :
linear_pmap R E G :=
g.to_fun.comp_pmap $ f.cod_restrict _ H
/-- `f.coprod g` is the partially defined linear map defined on `f.domain Γ g.domain`,
and sending `p` to `f p.1 + g p.2`. -/
def coprod (f : linear_pmap R E G) (g : linear_pmap R F G) :
linear_pmap R (E Γ F) G :=
{ domain := f.domain.prod g.domain,
to_fun := (f.comp (linear_pmap.fst f.domain g.domain) (Ξ» x, x.2.1)).to_fun +
(g.comp (linear_pmap.snd f.domain g.domain) (Ξ» x, x.2.2)).to_fun }
@[simp] lemma coprod_apply (f : linear_pmap R E G) (g : linear_pmap R F G) (x) :
f.coprod g x = f β¨(x : E Γ F).1, x.2.1β© + g β¨(x : E Γ F).2, x.2.2β© :=
rfl
end linear_pmap
|
674166b2932bcac3536fbd192c01c3dcd95afd7e | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/field_power.lean | 8ebb4bbe7a611dc083c179f37d16f157c43859a9 | [
"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 | 6,806 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
-/
import algebra.group_with_zero.power
import algebra.ring.equiv
import tactic.linarith
/-!
# Integer power operation on fields and division rings
This file collects basic facts about the operation of raising an element of a `division_ring` to an
integer power. More specialised results are provided in the case of a linearly ordered field.
-/
open function int
variables {Ξ± Ξ² : Type*}
section division_ring
variables [division_ring Ξ±] [division_ring Ξ²]
@[simp] lemma ring_hom.map_zpow (f : Ξ± β+* Ξ²) : β (a : Ξ±) (n : β€), f (a ^ n) = f a ^ n :=
f.to_monoid_with_zero_hom.map_zpow
@[simp] lemma ring_equiv.map_zpow (f : Ξ± β+* Ξ²) : β (a : Ξ±) (n : β€), f (a ^ n) = f a ^ n :=
f.to_ring_hom.map_zpow
@[simp] lemma zpow_bit1_neg (x : Ξ±) (n : β€) : (-x) ^ bit1 n = - x ^ bit1 n :=
by rw [zpow_bit1', zpow_bit1', neg_mul_neg, neg_mul_eq_mul_neg]
@[simp, norm_cast] lemma rat.cast_zpow [char_zero Ξ±] (q : β) (n : β€) : ((q ^ n : β) : Ξ±) = q ^ n :=
(rat.cast_hom Ξ±).map_zpow q n
end division_ring
section linear_ordered_semifield
variables [linear_ordered_semifield Ξ±] {a b x : Ξ±} {m n : β€}
lemma zpow_nonneg (ha : 0 β€ a) : β (z : β€), 0 β€ a ^ z
| (n : β) := by { rw zpow_coe_nat, exact pow_nonneg ha _ }
| -[1+n] := by { rw zpow_neg_succ_of_nat, exact inv_nonneg.2 (pow_nonneg ha _) }
lemma zpow_pos_of_pos (ha : 0 < a) : β (z : β€), 0 < a ^ z
| (n : β) := by { rw zpow_coe_nat, exact pow_pos ha _ }
| -[1+n] := by { rw zpow_neg_succ_of_nat, exact inv_pos.2 (pow_pos ha _) }
lemma zpow_le_of_le (ha : 1 β€ a) (h : m β€ n) : a ^ m β€ a ^ n :=
begin
induction m with m m; induction n with n n,
{ simp only [of_nat_eq_coe, zpow_coe_nat],
exact pow_le_pow ha (le_of_coe_nat_le_coe_nat h) },
{ cases h.not_lt ((neg_succ_lt_zero _).trans_le $ of_nat_nonneg _) },
{ simp only [zpow_neg_succ_of_nat, one_div, of_nat_eq_coe, zpow_coe_nat],
apply le_trans (inv_le_one _); apply one_le_pow_of_one_le ha },
{ simp only [zpow_neg_succ_of_nat],
apply (inv_le_inv _ _).2,
{ apply pow_le_pow ha,
have : -(β(m+1) : β€) β€ -(β(n+1) : β€), from h,
have h' := le_of_neg_le_neg this,
apply le_of_coe_nat_le_coe_nat h' },
repeat { apply pow_pos (zero_lt_one.trans_le ha) } }
end
lemma pow_le_max_of_min_le (hx : 1 β€ x) {a b c : β€} (h : min a b β€ c) :
x ^ (-c) β€ max (x ^ (-a)) (x ^ (-b)) :=
begin
wlog hle : a β€ b,
have hnle : -b β€ -a, from neg_le_neg hle,
have hfle : x ^ (-b) β€ x ^ (-a), from zpow_le_of_le hx hnle,
have : x ^ (-c) β€ x ^ (-a),
{ apply zpow_le_of_le hx,
simpa only [min_eq_left hle, neg_le_neg_iff] using h },
simpa only [max_eq_left hfle]
end
lemma zpow_le_one_of_nonpos (ha : 1 β€ a) (hn : n β€ 0) : a ^ n β€ 1 :=
(zpow_le_of_le ha hn).trans_eq $ zpow_zero _
lemma one_le_zpow_of_nonneg (ha : 1 β€ a) (hn : 0 β€ n) : 1 β€ a ^ n :=
(zpow_zero _).symm.trans_le $ zpow_le_of_le ha hn
protected lemma nat.zpow_pos_of_pos {a : β} (h : 0 < a) (n : β€) : 0 < (a : Ξ±)^n :=
by { apply zpow_pos_of_pos, exact_mod_cast h }
lemma nat.zpow_ne_zero_of_pos {a : β} (h : 0 < a) (n : β€) : (a : Ξ±)^n β 0 :=
(nat.zpow_pos_of_pos h n).ne'
lemma one_lt_zpow (ha : 1 < a) : β n : β€, 0 < n β 1 < a ^ n
| (n : β) h := (zpow_coe_nat _ _).symm.subst (one_lt_pow ha $ int.coe_nat_ne_zero.mp h.ne')
| -[1+ n] h := ((int.neg_succ_not_pos _).mp h).elim
lemma zpow_strict_mono (hx : 1 < x) : strict_mono ((^) x : β€ β Ξ±) :=
strict_mono_int_of_lt_succ $ Ξ» n,
have xpos : 0 < x, from zero_lt_one.trans hx,
calc x ^ n < x ^ n * x : lt_mul_of_one_lt_right (zpow_pos_of_pos xpos _) hx
... = x ^ (n + 1) : (zpow_add_oneβ xpos.ne' _).symm
lemma zpow_strict_anti (hβ : 0 < x) (hβ : x < 1) : strict_anti ((^) x : β€ β Ξ±) :=
strict_anti_int_of_succ_lt $ Ξ» n,
calc x ^ (n + 1) = x ^ n * x : zpow_add_oneβ hβ.ne' _
... < x ^ n * 1 : (mul_lt_mul_left $ zpow_pos_of_pos hβ _).2 hβ
... = x ^ n : mul_one _
@[simp] lemma zpow_lt_iff_lt (hx : 1 < x) : x ^ m < x ^ n β m < n := (zpow_strict_mono hx).lt_iff_lt
@[simp] lemma zpow_le_iff_le (hx : 1 < x) : x ^ m β€ x ^ n β m β€ n := (zpow_strict_mono hx).le_iff_le
lemma min_le_of_zpow_le_max (hx : 1 < x) {a b c : β€}
(h_max : x ^ (-c) β€ max (x ^ (-a)) (x ^ (-b))) : min a b β€ c :=
begin
rw min_le_iff,
refine or.imp (Ξ» h, _) (Ξ» h, _) (le_max_iff.mp h_max);
rwa [zpow_le_iff_le hx, neg_le_neg_iff] at h
end
@[simp] lemma pos_div_pow_pos (ha : 0 < a) (hb : 0 < b) (k : β) : 0 < a/b^k :=
div_pos ha (pow_pos hb k)
@[simp] lemma div_pow_le (ha : 0 < a) (hb : 1 β€ b) (k : β) : a/b^k β€ a :=
(div_le_iff $ pow_pos (lt_of_lt_of_le zero_lt_one hb) k).mpr
(calc a = a * 1 : (mul_one a).symm
... β€ a*b^k : (mul_le_mul_left ha).mpr $ one_le_pow_of_one_le hb _)
lemma zpow_injective (hβ : 0 < x) (hβ : x β 1) : injective ((^) x : β€ β Ξ±) :=
begin
intros m n h,
rcases hβ.lt_or_lt with H|H,
{ apply (zpow_strict_mono (one_lt_inv hβ H)).injective,
show xβ»ΒΉ ^ m = xβ»ΒΉ ^ n,
rw [β zpow_neg_one, β zpow_mul, β zpow_mul, mul_comm _ m, mul_comm _ n, zpow_mul, zpow_mul,
h], },
{ exact (zpow_strict_mono H).injective h, },
end
@[simp] lemma zpow_inj (hβ : 0 < x) (hβ : x β 1) : x ^ m = x ^ n β m = n :=
(zpow_injective hβ hβ).eq_iff
end linear_ordered_semifield
section linear_ordered_field
variables [linear_ordered_field Ξ±] {a x : Ξ±} {m n : β€}
lemma zpow_bit0_nonneg (a : Ξ±) (n : β€) : 0 β€ a ^ bit0 n :=
(mul_self_nonneg _).trans_eq $ (zpow_bit0 _ _).symm
lemma zpow_two_nonneg (a : Ξ±) : 0 β€ a ^ (2 : β€) := zpow_bit0_nonneg _ _
lemma zpow_bit0_pos (h : a β 0) (n : β€) : 0 < a ^ bit0 n :=
(zpow_bit0_nonneg a n).lt_of_ne (zpow_ne_zero _ h).symm
lemma zpow_two_pos_of_ne_zero (h : a β 0) : 0 < a ^ (2 : β€) := zpow_bit0_pos h _
@[simp] theorem zpow_bit1_neg_iff : a ^ bit1 n < 0 β a < 0 :=
β¨Ξ» h, not_le.1 $ Ξ» h', not_le.2 h $ zpow_nonneg h' _,
Ξ» h, by rw [bit1, zpow_add_oneβ h.ne]; exact mul_neg_of_pos_of_neg (zpow_bit0_pos h.ne _) hβ©
@[simp] theorem zpow_bit1_nonneg_iff : 0 β€ a ^ bit1 n β 0 β€ a :=
le_iff_le_iff_lt_iff_lt.2 zpow_bit1_neg_iff
@[simp] theorem zpow_bit1_nonpos_iff : a ^ bit1 n β€ 0 β a β€ 0 :=
begin
rw [le_iff_lt_or_eq, zpow_bit1_neg_iff],
split,
{ rintro (h | h),
{ exact h.le },
{ exact (zpow_eq_zero h).le } },
{ intro h,
rcases eq_or_lt_of_le h with rfl|h,
{ exact or.inr (zero_zpow _ (bit1_ne_zero n)) },
{ exact or.inl h } }
end
@[simp] theorem zpow_bit1_pos_iff : 0 < a ^ bit1 n β 0 < a :=
lt_iff_lt_of_le_iff_le zpow_bit1_nonpos_iff
end linear_ordered_field
|
93bb805b41625cdf675ae1be83b81d011b1e2935 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /src/Init/Data/Format/Syntax.lean | 1559212093ba633b6c825c7026d2c2fc75215001 | [
"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 | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 2,194 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.Data.Format.Macro
import Init.Data.Format.Instances
import Init.Meta
namespace Lean.Syntax
open Std
open Std.Format
private def formatInfo (showInfo : Bool) (info : SourceInfo) (f : Format) : Format :=
match showInfo, info with
| true, SourceInfo.original lead pos trail endPos => f!"{lead}:{pos}:{f}:{endPos}:{trail}"
| true, SourceInfo.synthetic pos endPos true => f!"{pos}!:{f}:{endPos}"
| true, SourceInfo.synthetic pos endPos false => f!"{pos}:{f}:{endPos}"
| _, _ => f
partial def formatStxAux (maxDepth : Option Nat) (showInfo : Bool) : Nat β Syntax β Format
| _, atom info val => formatInfo showInfo info $ format (repr val)
| _, ident info _ val _ => formatInfo showInfo info $ format "`" ++ format val
| _, missing => "<missing>"
| depth, node _ kind args =>
let depth := depth + 1;
if kind == nullKind then
sbracket $
if args.size > 0 && depth > maxDepth.getD depth then
".."
else
joinSep (args.toList.map (formatStxAux maxDepth showInfo depth)) line
else
let shorterName := kind.replacePrefix `Lean.Parser Name.anonymous;
let header := format shorterName;
let body : List Format :=
if args.size > 0 && depth > maxDepth.getD depth then [".."] else args.toList.map (formatStxAux maxDepth showInfo depth);
paren $ joinSep (header :: body) line
/-- Pretty print the given syntax `stx` as a `Format`.
Nodes deeper than `maxDepth` are omitted.
Setting the `showInfo` flag will also print the `SourceInfo` for each node. -/
def formatStx (stx : Syntax) (maxDepth : Option Nat := none) (showInfo := false) : Format :=
formatStxAux maxDepth showInfo 0 stx
instance : ToFormat (Syntax) := β¨formatStxβ©
instance : ToString (Syntax) := β¨@toString Format _ β formatβ©
instance : ToFormat (TSyntax k) := β¨(format Β·.raw)β©
instance : ToString (TSyntax k) := β¨(toString Β·.raw)β©
end Lean.Syntax
|
d1c46ed4c97eaf760f544724568985737ec61e5a | f5f7e6fae601a5fe3cac7cc3ed353ed781d62419 | /src/number_theory/dioph.lean | cb0a3246bb944512138401bb9766bd6e5b15cac3 | [
"Apache-2.0"
] | permissive | EdAyers/mathlib | 9ecfb2f14bd6caad748b64c9c131befbff0fb4e0 | ca5d4c1f16f9c451cf7170b10105d0051db79e1b | refs/heads/master | 1,626,189,395,845 | 1,555,284,396,000 | 1,555,284,396,000 | 144,004,030 | 0 | 0 | Apache-2.0 | 1,533,727,664,000 | 1,533,727,663,000 | null | UTF-8 | Lean | false | false | 36,080 | 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 number_theory.pell data.set data.pfun
universe u
open nat function
namespace int
lemma eq_nat_abs_iff_mul (x n) : nat_abs x = n β (x - n) * (x + n) = 0 :=
begin
refine iff.trans _ mul_eq_zero.symm,
refine iff.trans _ (or_congr sub_eq_zero add_eq_zero_iff_eq_neg).symm,
exact β¨Ξ»e, by rw β e; apply nat_abs_eq,
Ξ»o, by cases o; subst x; simp [nat_abs_of_nat]β©
end
end int
/-- An alternate definition of `fin n` defined as an inductive type
instead of a subtype of `nat`. This is useful for its induction
principle and different definitional equalities. -/
inductive fin2 : β β Type
| fz {n} : fin2 (succ n)
| fs {n} : fin2 n β fin2 (succ n)
namespace fin2
@[elab_as_eliminator]
protected def cases' {n} {C : fin2 (succ n) β Sort u} (H1 : C fz) (H2 : Ξ n, C (fs n)) :
Ξ (i : fin2 (succ n)), C i
| fz := H1
| (fs n) := H2 n
def elim0 {C : fin2 0 β Sort u} : Ξ (i : fin2 0), C i.
/-- convert a `fin2` into a `nat` -/
def to_nat : Ξ {n}, fin2 n β β
| ._ (@fz n) := 0
| ._ (@fs n i) := succ (to_nat i)
/-- convert a `nat` into a `fin2` if it is in range -/
def opt_of_nat : Ξ {n} (k : β), option (fin2 n)
| 0 _ := none
| (succ n) 0 := some fz
| (succ n) (succ k) := fs <$> @opt_of_nat n k
/-- `i + k : fin2 (n + k)` when `i : fin2 n` and `k : β` -/
def add {n} (i : fin2 n) : Ξ k, fin2 (n + k)
| 0 := i
| (succ k) := fs (add k)
/-- `left k` is the embedding `fin2 n β fin2 (k + n)` -/
def left (k) : Ξ {n}, fin2 n β fin2 (k + n)
| ._ (@fz n) := fz
| ._ (@fs n i) := fs (left i)
/-- `insert_perm a` is a permutation of `fin2 n` with the following properties:
* `insert_perm a i = i+1` if `i < a`
* `insert_perm a a = 0`
* `insert_perm a i = i` if `i > a` -/
def insert_perm : Ξ {n}, fin2 n β fin2 n β fin2 n
| ._ (@fz n) (@fz ._) := fz
| ._ (@fz n) (@fs ._ j) := fs j
| ._ (@fs (succ n) i) (@fz ._) := fs fz
| ._ (@fs (succ n) i) (@fs ._ j) := match insert_perm i j with fz := fz | fs k := fs (fs k) end
/-- `remap_left f k : fin2 (m + k) β fin2 (n + k)` applies the function
`f : fin2 m β fin2 n` to inputs less than `m`, and leaves the right part
on the right (that is, `remap_left f k (m + i) = n + i`). -/
def remap_left {m n} (f : fin2 m β fin2 n) : Ξ k, fin2 (m + k) β fin2 (n + k)
| 0 i := f i
| (succ k) (@fz ._) := fz
| (succ k) (@fs ._ i) := fs (remap_left _ i)
/-- This is a simple type class inference prover for proof obligations
of the form `m < n` where `m n : β`. -/
class is_lt (m n : β) := (h : m < n)
instance is_lt.zero (n) : is_lt 0 (succ n) := β¨succ_pos _β©
instance is_lt.succ (m n) [l : is_lt m n] : is_lt (succ m) (succ n) := β¨succ_lt_succ l.hβ©
/-- Use type class inference to infer the boundedness proof, so that we
can directly convert a `nat` into a `fin2 n`. This supports
notation like `&1 : fin 3`. -/
def of_nat' : Ξ {n} m [is_lt m n], fin2 n
| 0 m β¨hβ© := absurd h (not_lt_zero _)
| (succ n) 0 β¨hβ© := fz
| (succ n) (succ m) β¨hβ© := fs (@of_nat' n m β¨lt_of_succ_lt_succ hβ©)
local prefix `&`:max := of_nat'
end fin2
open fin2
/-- Alternate definition of `vector` based on `fin2`. -/
def vector3 (Ξ± : Type u) (n : β) : Type u := fin2 n β Ξ±
namespace vector3
/-- The empty vector -/
@[pattern] def nil {Ξ±} : vector3 Ξ± 0.
/-- The vector cons operation -/
@[pattern] def cons {Ξ±} {n} (a : Ξ±) (v : vector3 Ξ± n) : vector3 Ξ± (succ n) :=
Ξ»i, by {refine i.cases' _ _, exact a, exact v}
notation a :: b := cons a b
notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l
@[simp] theorem cons_fz {Ξ±} {n} (a : Ξ±) (v : vector3 Ξ± n) : (a :: v) fz = a := rfl
@[simp] theorem cons_fs {Ξ±} {n} (a : Ξ±) (v : vector3 Ξ± n) (i) : (a :: v) (fs i) = v i := rfl
/-- Get the `i`th element of a vector -/
@[reducible] def nth {Ξ±} {n} (i : fin2 n) (v : vector3 Ξ± n) : Ξ± := v i
/-- Construct a vector from a function on `fin2`. -/
@[reducible] def of_fn {Ξ±} {n} (f : fin2 n β Ξ±) : vector3 Ξ± n := f
/-- Get the head of a nonempty vector. -/
def head {Ξ±} {n} (v : vector3 Ξ± (succ n)) : Ξ± := v fz
/-- Get the tail of a nonempty vector. -/
def tail {Ξ±} {n} (v : vector3 Ξ± (succ n)) : vector3 Ξ± n := Ξ»i, v (fs i)
theorem eq_nil {Ξ±} (v : vector3 Ξ± 0) : v = [] :=
funext $ Ξ»i, match i with end
theorem cons_head_tail {Ξ±} {n} (v : vector3 Ξ± (succ n)) : head v :: tail v = v :=
funext $ Ξ»i, fin2.cases' rfl (Ξ»_, rfl) i
def nil_elim {Ξ±} {C : vector3 Ξ± 0 β Sort u} (H : C []) (v : vector3 Ξ± 0) : C v :=
by rw eq_nil v; apply H
def cons_elim {Ξ± n} {C : vector3 Ξ± (succ n) β Sort u} (H : Ξ (a : Ξ±) (t : vector3 Ξ± n), C (a :: t))
(v : vector3 Ξ± (succ n)) : C v :=
by rw β (cons_head_tail v); apply H
@[simp] theorem cons_elim_cons {Ξ± n C H a t} : @cons_elim Ξ± n C H (a :: t) = H a t := rfl
@[elab_as_eliminator]
protected def rec_on {Ξ±} {C : Ξ {n}, vector3 Ξ± n β Sort u} {n} (v : vector3 Ξ± n)
(H0 : C [])
(Hs : Ξ {n} (a) (w : vector3 Ξ± n), C w β C (a :: w)) : C v :=
nat.rec_on n
(Ξ»v, v.nil_elim H0)
(Ξ»n IH v, v.cons_elim (Ξ»a t, Hs _ _ (IH _))) v
@[simp] theorem rec_on_nil {Ξ± C H0 Hs} : @vector3.rec_on Ξ± @C 0 [] H0 @Hs = H0 :=
rfl
@[simp] theorem rec_on_cons {Ξ± C H0 Hs n a v} :
@vector3.rec_on Ξ± @C (succ n) (a :: v) H0 @Hs = Hs a v (@vector3.rec_on Ξ± @C n v H0 @Hs) :=
rfl
/-- Append two vectors -/
def append {Ξ±} {m} (v : vector3 Ξ± m) {n} (w : vector3 Ξ± n) : vector3 Ξ± (n+m) :=
nat.rec_on m (Ξ»_, w) (Ξ»m IH v, v.cons_elim $ Ξ»a t, @fin2.cases' (n+m) (Ξ»_, Ξ±) a (IH t)) v
infix ` +-+ `:65 := append
@[simp] theorem append_nil {Ξ±} {n} (w : vector3 Ξ± n) : [] +-+ w = w := rfl
@[simp] theorem append_cons {Ξ±} (a : Ξ±) {m} (v : vector3 Ξ± m) {n} (w : vector3 Ξ± n) :
(a::v) +-+ w = a :: (v +-+ w) := rfl
@[simp] theorem append_left {Ξ±} : β {m} (i : fin2 m) (v : vector3 Ξ± m) {n} (w : vector3 Ξ± n),
(v +-+ w) (left n i) = v i
| ._ (@fz m) v n w := v.cons_elim (Ξ»a t, by simp [*, left])
| ._ (@fs m i) v n w := v.cons_elim (Ξ»a t, by simp [*, left])
@[simp] theorem append_add {Ξ±} : β {m} (v : vector3 Ξ± m) {n} (w : vector3 Ξ± n) (i : fin2 n),
(v +-+ w) (add i m) = w i
| 0 v n w i := rfl
| (succ m) v n w i := v.cons_elim (Ξ»a t, by simp [*, add])
/-- Insert `a` into `v` at index `i`. -/
def insert {Ξ±} (a : Ξ±) {n} (v : vector3 Ξ± n) (i : fin2 (succ n)) : vector3 Ξ± (succ n) :=
Ξ»j, (a :: v) (insert_perm i j)
@[simp] theorem insert_fz {Ξ±} (a : Ξ±) {n} (v : vector3 Ξ± n) : insert a v fz = a :: v :=
by refine funext (Ξ»j, j.cases' _ _); intros; refl
@[simp] theorem insert_fs {Ξ±} (a : Ξ±) {n} (b : Ξ±) (v : vector3 Ξ± n) (i : fin2 (succ n)) :
insert a (b :: v) (fs i) = b :: insert a v i :=
funext $ Ξ»j, by {
refine j.cases' _ (Ξ»j, _); simp [insert, insert_perm],
refine fin2.cases' _ _ (insert_perm i j); simp [insert_perm] }
theorem append_insert {Ξ±} (a : Ξ±) {k} (t : vector3 Ξ± k) {n} (v : vector3 Ξ± n) (i : fin2 (succ n)) (e : succ n + k = succ (n + k)) :
insert a (t +-+ v) (eq.rec_on e (i.add k)) = eq.rec_on e (t +-+ insert a v i) :=
begin
refine vector3.rec_on t (Ξ»e, _) (Ξ»k b t IH e, _) e, refl,
have e' := succ_add n k,
change insert a (b :: (t +-+ v)) (eq.rec_on (congr_arg succ e') (fs (add i k)))
= eq.rec_on (congr_arg succ e') (b :: (t +-+ insert a v i)),
rw β (eq.drec_on e' rfl : fs (eq.rec_on e' (i.add k) : fin2 (succ (n + k))) = eq.rec_on (congr_arg succ e') (fs (i.add k))),
simp, rw IH, exact eq.drec_on e' rfl
end
end vector3
open vector3
/-- "Curried" exists, i.e. β x1 ... xn, f [x1, ..., xn] -/
def vector_ex {Ξ±} : Ξ k, (vector3 Ξ± k β Prop) β Prop
| 0 f := f []
| (succ k) f := βx : Ξ±, vector_ex k (Ξ»v, f (x :: v))
/-- "Curried" forall, i.e. β x1 ... xn, f [x1, ..., xn] -/
def vector_all {Ξ±} : Ξ k, (vector3 Ξ± k β Prop) β Prop
| 0 f := f []
| (succ k) f := βx : Ξ±, vector_all k (Ξ»v, f (x :: v))
theorem exists_vector_zero {Ξ±} (f : vector3 Ξ± 0 β Prop) : Exists f β f [] :=
β¨Ξ»β¨v, fvβ©, by rw β (eq_nil v); exact fv, Ξ»f0, β¨[], f0β©β©
theorem exists_vector_succ {Ξ± n} (f : vector3 Ξ± (succ n) β Prop) : Exists f β βx v, f (x :: v) :=
β¨Ξ»β¨v, fvβ©, β¨_, _, by rw cons_head_tail v; exact fvβ©, Ξ»β¨x, v, fxvβ©, β¨_, fxvβ©β©
theorem vector_ex_iff_exists {Ξ±} : β {n} (f : vector3 Ξ± n β Prop), vector_ex n f β Exists f
| 0 f := (exists_vector_zero f).symm
| (succ n) f := iff.trans (exists_congr (Ξ»x, vector_ex_iff_exists _)) (exists_vector_succ f).symm
theorem vector_all_iff_forall {Ξ±} : β {n} (f : vector3 Ξ± n β Prop), vector_all n f β β v, f v
| 0 f := β¨Ξ»f0 v, v.nil_elim f0, Ξ»al, al []β©
| (succ n) f := (forall_congr (Ξ»x, vector_all_iff_forall (Ξ»v, f (x :: v)))).trans
β¨Ξ»al v, v.cons_elim al, Ξ»al x v, al (x::v)β©
/-- `vector_allp p v` is equivalent to `β i, p (v i)`, but unfolds directly to a conjunction,
i.e. `vector_allp p [0, 1, 2] = p 0 β§ p 1 β§ p 2`. -/
def vector_allp {Ξ±} (p : Ξ± β Prop) {n} (v : vector3 Ξ± n) : Prop :=
vector3.rec_on v true (Ξ»n a v IH, @vector3.rec_on _ (Ξ»n v, Prop) _ v (p a) (Ξ»n b v' _, p a β§ IH))
@[simp] theorem vector_allp_nil {Ξ±} (p : Ξ± β Prop) : vector_allp p [] = true := rfl
@[simp] theorem vector_allp_singleton {Ξ±} (p : Ξ± β Prop) (x : Ξ±) : vector_allp p [x] = p x := rfl
@[simp] theorem vector_allp_cons {Ξ±} (p : Ξ± β Prop) {n} (x : Ξ±) (v : vector3 Ξ± n) :
vector_allp p (x :: v) β p x β§ vector_allp p v :=
vector3.rec_on v (and_true _).symm (Ξ»n a v IH, iff.rfl)
theorem vector_allp_iff_forall {Ξ±} (p : Ξ± β Prop) {n} (v : vector3 Ξ± n) : vector_allp p v β β i, p (v i) :=
begin refine v.rec_on _ _,
{ exact β¨Ξ»_, fin2.elim0, Ξ»_, trivialβ© },
{ simp, refine Ξ»n a v IH, (and_congr_right (Ξ»_, IH)).trans
β¨Ξ»β¨pa, hβ© i, by {refine i.cases' _ _, exacts [pa, h]}, Ξ»h, β¨_, Ξ»i, _β©β©,
{ have h0 := h fz, simp at h0, exact h0 },
{ have hs := h (fs i), simp at hs, exact hs } }
end
theorem vector_allp.imp {Ξ±} {p q : Ξ± β Prop} (h : β x, p x β q x)
{n} {v : vector3 Ξ± n} (al : vector_allp p v) : vector_allp q v :=
(vector_allp_iff_forall _ _).2 (Ξ»i, h _ $ (vector_allp_iff_forall _ _).1 al _)
/-- `list_all p l` is equivalent to `β a β l, p a`, but unfolds directly to a conjunction,
i.e. `list_all p [0, 1, 2] = p 0 β§ p 1 β§ p 2`. -/
@[simp] def list_all {Ξ±} (p : Ξ± β Prop) : list Ξ± β Prop
| [] := true
| (x :: []) := p x
| (x :: l) := p x β§ list_all l
@[simp] theorem list_all_cons {Ξ±} (p : Ξ± β Prop) (x : Ξ±) : β (l : list Ξ±), list_all p (x :: l) β p x β§ list_all p l
| [] := (and_true _).symm
| (x :: l) := iff.rfl
theorem list_all_iff_forall {Ξ±} (p : Ξ± β Prop) : β (l : list Ξ±), list_all p l β β x β l, p x
| [] := (iff_true_intro $ list.ball_nil _).symm
| (x :: l) := by rw [list.ball_cons, β list_all_iff_forall l]; simp
theorem list_all.imp {Ξ±} {p q : Ξ± β Prop} (h : β x, p x β q x) : β {l : list Ξ±}, list_all p l β list_all q l
| [] := id
| (x :: l) := by simpa using and.imp (h x) list_all.imp
@[simp] theorem list_all_map {Ξ± Ξ²} {p : Ξ² β Prop} (f : Ξ± β Ξ²) {l : list Ξ±} : list_all p (l.map f) β list_all (p β f) l :=
by induction l; simp *
theorem list_all_congr {Ξ±} {p q : Ξ± β Prop} (h : β x, p x β q x) {l : list Ξ±} : list_all p l β list_all q l :=
β¨list_all.imp (Ξ»x, (h x).1), list_all.imp (Ξ»x, (h x).2)β©
instance decidable_list_all {Ξ±} (p : Ξ± β Prop) [decidable_pred p] (l : list Ξ±) : decidable (list_all p l) :=
decidable_of_decidable_of_iff (by apply_instance) (list_all_iff_forall _ _).symm
/- poly -/
/-- A predicate asserting that a function is a multivariate integer polynomial.
(We are being a bit lazy here by allowing many representations for multiplication,
rather than only allowing monomials and addition, but the definition is equivalent
and this is easier to use.) -/
inductive is_poly {Ξ±} : ((Ξ± β β) β β€) β Prop
| proj : β i, is_poly (Ξ»x : Ξ± β β, x i)
| const : Ξ (n : β€), is_poly (Ξ»x : Ξ± β β, n)
| sub : Ξ {f g : (Ξ± β β) β β€}, is_poly f β is_poly g β is_poly (Ξ»x, f x - g x)
| mul : Ξ {f g : (Ξ± β β) β β€}, is_poly f β is_poly g β is_poly (Ξ»x, f x * g x)
/-- The type of multivariate integer polynomials -/
def poly (Ξ± : Type u) := {f : (Ξ± β β) β β€ // is_poly f}
namespace poly
section
parameter {Ξ± : Type u}
instance : has_coe_to_fun (poly Ξ±) := β¨_, Ξ» f, f.1β©
/-- The underlying function of a `poly` is a polynomial -/
def isp (f : poly Ξ±) : is_poly f := f.2
/-- Extensionality for `poly Ξ±` -/
def ext {f g : poly Ξ±} (e : βx, f x = g x) : f = g :=
subtype.eq (funext e)
/-- Construct a `poly` given an extensionally equivalent `poly`. -/
def subst (f : poly Ξ±) (g : (Ξ± β β) β β€) (e : βx, f x = g x) : poly Ξ± :=
β¨g, by rw β (funext e : coe_fn f = g); exact f.ispβ©
@[simp] theorem subst_eval (f g e x) : subst f g e x = g x := rfl
/-- The `i`th projection function, `x_i`. -/
def proj (i) : poly Ξ± := β¨_, is_poly.proj iβ©
@[simp] theorem proj_eval (i x) : proj i x = x i := rfl
/-- The constant function with value `n : β€`. -/
def const (n) : poly Ξ± := β¨_, is_poly.const nβ©
@[simp] theorem const_eval (n x) : const n x = n := rfl
/-- The zero polynomial -/
def zero : poly Ξ± := const 0
instance : has_zero (poly Ξ±) := β¨poly.zeroβ©
@[simp] theorem zero_eval (x) : (0 : poly Ξ±) x = 0 := rfl
/-- The zero polynomial -/
def one : poly Ξ± := const 1
instance : has_one (poly Ξ±) := β¨poly.oneβ©
@[simp] theorem one_eval (x) : (1 : poly Ξ±) x = 1 := rfl
/-- Subtraction of polynomials -/
def sub : poly Ξ± β poly Ξ± β poly Ξ± | β¨f, pfβ© β¨g, pgβ© :=
β¨_, is_poly.sub pf pgβ©
instance : has_sub (poly Ξ±) := β¨poly.subβ©
@[simp] theorem sub_eval : Ξ (f g x), (f - g : poly Ξ±) x = f x - g x
| β¨f, pfβ© β¨g, pgβ© x := rfl
/-- Negation of a polynomial -/
def neg (f : poly Ξ±) : poly Ξ± := 0 - f
instance : has_neg (poly Ξ±) := β¨poly.negβ©
@[simp] theorem neg_eval (f x) : (-f : poly Ξ±) x = -f x :=
show (0-f) x = _, by simp
/-- Addition of polynomials -/
def add : poly Ξ± β poly Ξ± β poly Ξ± | β¨f, pfβ© β¨g, pgβ© :=
subst (β¨f, pfβ© - -β¨g, pgβ©) _
(Ξ»x, show f x - (0 - g x) = f x + g x, by simp)
instance : has_add (poly Ξ±) := β¨poly.addβ©
@[simp] theorem add_eval : Ξ (f g x), (f + g : poly Ξ±) x = f x + g x
| β¨f, pfβ© β¨g, pgβ© x := rfl
/-- Multiplication of polynomials -/
def mul : poly Ξ± β poly Ξ± β poly Ξ± | β¨f, pfβ© β¨g, pgβ© :=
β¨_, is_poly.mul pf pgβ©
instance : has_mul (poly Ξ±) := β¨poly.mulβ©
@[simp] theorem mul_eval : Ξ (f g x), (f * g : poly Ξ±) x = f x * g x
| β¨f, pfβ© β¨g, pgβ© x := rfl
instance : comm_ring (poly Ξ±) := by refine
{ add := (+),
zero := 0,
neg := has_neg.neg,
mul := (*),
one := 1, .. }; {intros, exact ext (Ξ»x, by simp [mul_add, mul_left_comm, mul_comm])}
def induction {C : poly Ξ± β Prop}
(H1 : βi, C (proj i)) (H2 : βn, C (const n))
(H3 : βf g, C f β C g β C (f - g))
(H4 : βf g, C f β C g β C (f * g)) (f : poly Ξ±) : C f :=
begin
cases f with f pf,
induction pf with i n f g pf pg ihf ihg f g pf pg ihf ihg,
apply H1, apply H2, apply H3 _ _ ihf ihg, apply H4 _ _ ihf ihg
end
/-- The sum of squares of a list of polynomials. This is relevant for
Diophantine equations, because it means that a list of equations
can be encoded as a single equation: `x = 0 β§ y = 0 β§ z = 0` is
equivalent to `x^2 + y^2 + z^2 = 0`. -/
def sumsq : list (poly Ξ±) β poly Ξ±
| [] := 0
| (p::ps) := p*p + sumsq ps
theorem sumsq_nonneg (x) : β l, 0 β€ sumsq l x
| [] := le_refl 0
| (p::ps) := by rw sumsq; simp [-add_comm];
exact add_nonneg (mul_self_nonneg _) (sumsq_nonneg ps)
theorem sumsq_eq_zero (x) : β l, sumsq l x = 0 β list_all (Ξ»a : poly Ξ±, a x = 0) l
| [] := eq_self_iff_true _
| (p::ps) := by rw [list_all_cons, β sumsq_eq_zero ps]; rw sumsq; simp [-add_comm]; exact
β¨Ξ»(h : p x * p x + sumsq ps x = 0),
have p x = 0, from eq_zero_of_mul_self_eq_zero $ le_antisymm
(by rw β h; have t := add_le_add_left (sumsq_nonneg x ps) (p x * p x); rwa [add_zero] at t)
(mul_self_nonneg _),
β¨this, by simp [this] at h; exact hβ©,
Ξ»β¨h1, h2β©, by rw [h1, h2]; reflβ©
end
/-- Map the index set of variables, replacing `x_i` with `x_(f i)`. -/
def remap {Ξ± Ξ²} (f : Ξ± β Ξ²) (g : poly Ξ±) : poly Ξ² :=
β¨Ξ»v, g $ v β f, g.induction
(Ξ»i, by simp; apply is_poly.proj)
(Ξ»n, by simp; apply is_poly.const)
(Ξ»f g pf pg, by simp; apply is_poly.sub pf pg)
(Ξ»f g pf pg, by simp; apply is_poly.mul pf pg)β©
@[simp] theorem remap_eval {Ξ± Ξ²} (f : Ξ± β Ξ²) (g : poly Ξ±) (v) : remap f g v = g (v β f) := rfl
end poly
namespace sum
/-- combine two functions into a function on the disjoint union -/
def join {Ξ± Ξ² Ξ³} (f : Ξ± β Ξ³) (g : Ξ² β Ξ³) : Ξ± β Ξ² β Ξ³ :=
by {refine sum.rec _ _, exacts [f, g]}
end sum
local infixr ` β `:65 := sum.join
open sum
namespace option
/-- Functions from `option` can be combined similarly to `vector.cons` -/
def cons {Ξ± Ξ²} (a : Ξ²) (v : Ξ± β Ξ²) : option Ξ± β Ξ² :=
by {refine option.rec _ _, exacts [a, v]}
notation a :: b := cons a b
@[simp] theorem cons_head_tail {Ξ± Ξ²} (v : option Ξ± β Ξ²) : v none :: v β some = v :=
funext $ Ξ»o, by cases o; refl
end option
/- dioph -/
/-- A set `S β β^Ξ±` is diophantine if there exists a polynomial on
`Ξ± β Ξ²` such that `v β S` iff there exists `t : β^Ξ²` with `p (v, t) = 0`. -/
def dioph {Ξ± : Type u} (S : set (Ξ± β β)) : Prop :=
β {Ξ² : Type u} (p : poly (Ξ± β Ξ²)), β (v : Ξ± β β), S v β βt, p (v β t) = 0
namespace dioph
section
variables {Ξ± Ξ² Ξ³ : Type u}
theorem ext {S S' : set (Ξ± β β)} (d : dioph S) (H : βv, S v β S' v) : dioph S' :=
eq.rec d $ show S = S', from set.ext H
theorem of_no_dummies (S : set (Ξ± β β)) (p : poly Ξ±) (h : β (v : Ξ± β β), S v β p v = 0) : dioph S :=
β¨ulift empty, p.remap inl, Ξ»v, (h v).trans
β¨Ξ»h, β¨Ξ»t, empty.rec _ t.down, by simp; rw [
show (v β Ξ»t:ulift empty, empty.rec _ t.down) β inl = v, from rfl, h]β©,
Ξ»β¨t, htβ©, by simp at ht; rwa [show (v β t) β inl = v, from rfl] at htβ©β©
lemma inject_dummies_lem (f : Ξ² β Ξ³) (g : Ξ³ β option Ξ²) (inv : β x, g (f x) = some x)
(p : poly (Ξ± β Ξ²)) (v : Ξ± β β) : (βt, p (v β t) = 0) β
(βt, p.remap (inl β (inr β f)) (v β t) = 0) :=
begin
simp, refine β¨Ξ»t, _, Ξ»t, _β©; cases t with t ht,
{ have : (v β (0 :: t) β g) β (inl β inr β f) = v β t :=
funext (Ξ»s, by cases s with a b; dsimp [join, (β)]; try {rw inv}; refl),
exact β¨(0 :: t) β g, by rwa thisβ© },
{ have : v β t β f = (v β t) β (inl β inr β f) :=
funext (Ξ»s, by cases s with a b; refl),
exact β¨t β f, by rwa thisβ© }
end
theorem inject_dummies {S : set (Ξ± β β)} (f : Ξ² β Ξ³) (g : Ξ³ β option Ξ²) (inv : β x, g (f x) = some x)
(p : poly (Ξ± β Ξ²)) (h : β (v : Ξ± β β), S v β βt, p (v β t) = 0) :
β q : poly (Ξ± β Ξ³), β (v : Ξ± β β), S v β βt, q (v β t) = 0 :=
β¨p.remap (inl β (inr β f)), Ξ»v, (h v).trans $ inject_dummies_lem f g inv _ _β©
theorem reindex_dioph {S : set (Ξ± β β)} : Ξ (d : dioph S) (f : Ξ± β Ξ²), dioph (Ξ»v, S (v β f))
| β¨Ξ³, p, peβ© f := β¨Ξ³, p.remap ((inl β f) β inr), Ξ»v, (pe _).trans $ exists_congr $ Ξ»t,
suffices v β f β t = (v β t) β (inl β f β inr), by simp [this],
funext $ Ξ»s, by cases s with a b; reflβ©
theorem dioph_list_all (l) (d : list_all dioph l) : dioph (Ξ»v, list_all (Ξ»S : set (Ξ± β β), S v) l) :=
suffices β Ξ² (pl : list (poly (Ξ± β Ξ²))), β v, list_all (Ξ»S : set _, S v) l β βt, list_all (Ξ»p : poly (Ξ± β Ξ²), p (v β t) = 0) pl,
from let β¨Ξ², pl, hβ© := this in β¨Ξ², poly.sumsq pl, Ξ»v, (h v).trans $ exists_congr $ Ξ»t, (poly.sumsq_eq_zero _ _).symmβ©,
begin
induction l with S l IH,
exact β¨ulift empty, [], Ξ»v, by simp; exact β¨Ξ»β¨tβ©, empty.rec _ t, trivialβ©β©,
simp at d,
exact let β¨β¨Ξ², p, peβ©, dlβ© := d, β¨Ξ³, pl, pleβ© := IH dl in
β¨Ξ² β Ξ³, p.remap (inl β inr β inl) :: pl.map (Ξ»q, q.remap (inl β (inr β inr))), Ξ»v,
by simp; exact iff.trans (and_congr (pe v) (ple v))
β¨Ξ»β¨β¨m, hmβ©, β¨n, hnβ©β©,
β¨m β n, by rw [
show (v β m β n) β (inl β inr β inl) = v β m,
from funext $ Ξ»s, by cases s with a b; refl]; exact hm,
by { refine list_all.imp (Ξ»q hq, _) hn, dsimp [(β)],
rw [show (Ξ» (x : Ξ± β Ξ³), (v β m β n) ((inl β Ξ» (x : Ξ³), inr (inr x)) x)) = v β n,
from funext $ Ξ»s, by cases s with a b; refl]; exact hq }β©,
Ξ»β¨t, hl, hrβ©,
β¨β¨t β inl, by rwa [
show (v β t) β (inl β inr β inl) = v β t β inl,
from funext $ Ξ»s, by cases s with a b; refl] at hlβ©,
β¨t β inr, by {
refine list_all.imp (Ξ»q hq, _) hr, dsimp [(β)] at hq,
rwa [show (Ξ» (x : Ξ± β Ξ³), (v β t) ((inl β Ξ» (x : Ξ³), inr (inr x)) x)) = v β t β inr,
from funext $ Ξ»s, by cases s with a b; refl] at hq }β©β©β©β©
end
theorem and_dioph {S S' : set (Ξ± β β)} (d : dioph S) (d' : dioph S') : dioph (Ξ»v, S v β§ S' v) :=
dioph_list_all [S, S'] β¨d, d'β©
theorem or_dioph {S S' : set (Ξ± β β)} : β (d : dioph S) (d' : dioph S'), dioph (Ξ»v, S v β¨ S' v)
| β¨Ξ², p, peβ© β¨Ξ³, q, qeβ© := β¨Ξ² β Ξ³, p.remap (inl β inr β inl) * q.remap (inl β inr β inr), Ξ»v,
begin
refine iff.trans (or_congr ((pe v).trans _) ((qe v).trans _)) (exists_or_distrib.symm.trans (exists_congr $ Ξ»t,
(@mul_eq_zero_iff_eq_zero_or_eq_zero _ _ (p ((v β t) β (inl β inr β inl))) (q ((v β t) β (inl β inr β inr)))).symm)),
exact inject_dummies_lem _ (some β (Ξ»_, none)) (Ξ»x, rfl) _ _,
exact inject_dummies_lem _ ((Ξ»_, none) β some) (Ξ»x, rfl) _ _,
endβ©
/-- A partial function is Diophantine if its graph is Diophantine. -/
def dioph_pfun (f : (Ξ± β β) β. β) := dioph (Ξ»v : option Ξ± β β, f.graph (v β some, v none))
/-- A function is Diophantine if its graph is Diophantine. -/
def dioph_fn (f : (Ξ± β β) β β) := dioph (Ξ»v : option Ξ± β β, f (v β some) = v none)
theorem reindex_dioph_fn {f : (Ξ± β β) β β} (d : dioph_fn f) (g : Ξ± β Ξ²) : dioph_fn (Ξ»v, f (v β g)) :=
reindex_dioph d (functor.map g)
theorem ex_dioph {S : set (Ξ± β Ξ² β β)} : dioph S β dioph (Ξ»v, βx, S (v β x))
| β¨Ξ³, p, peβ© := β¨Ξ² β Ξ³, p.remap ((inl β inr β inl) β inr β inr), Ξ»v,
β¨Ξ»β¨x, hxβ©, let β¨t, htβ© := (pe _).1 hx in β¨x β t, by simp; rw [
show (v β x β t) β ((inl β inr β inl) β inr β inr) = (v β x) β t,
from funext $ Ξ»s, by cases s with a b; try {cases a}; refl]; exact htβ©,
Ξ»β¨t, htβ©, β¨t β inl, (pe _).2 β¨t β inr, by simp at ht; rwa [
show (v β t) β ((inl β inr β inl) β inr β inr) = (v β t β inl) β t β inr,
from funext $ Ξ»s, by cases s with a b; try {cases a}; refl] at htβ©β©β©β©
theorem ex1_dioph {S : set (option Ξ± β β)} : dioph S β dioph (Ξ»v, βx, S (x :: v))
| β¨Ξ², p, peβ© := β¨option Ξ², p.remap (inr none :: inl β inr β some), Ξ»v,
β¨Ξ»β¨x, hxβ©, let β¨t, htβ© := (pe _).1 hx in β¨x :: t, by simp; rw [
show (v β x :: t) β (inr none :: inl β inr β some) = x :: v β t,
from funext $ Ξ»s, by cases s with a b; try {cases a}; refl]; exact htβ©,
Ξ»β¨t, htβ©, β¨t none, (pe _).2 β¨t β some, by simp at ht; rwa [
show (v β t) β (inr none :: inl β inr β some) = t none :: v β t β some,
from funext $ Ξ»s, by cases s with a b; try {cases a}; refl] at htβ©β©β©β©
theorem dom_dioph {f : (Ξ± β β) β. β} (d : dioph_pfun f) : dioph f.dom :=
cast (congr_arg dioph $ set.ext $ Ξ»v, (pfun.dom_iff_graph _ _).symm) (ex1_dioph d)
theorem dioph_fn_iff_pfun (f : (Ξ± β β) β β) : dioph_fn f = @dioph_pfun Ξ± f :=
by refine congr_arg dioph (set.ext $ Ξ»v, _); exact pfun.lift_graph.symm
theorem abs_poly_dioph (p : poly Ξ±) : dioph_fn (Ξ»v, (p v).nat_abs) :=
by refine of_no_dummies _ ((p.remap some - poly.proj none) * (p.remap some + poly.proj none)) (Ξ»v, _);
apply int.eq_nat_abs_iff_mul
theorem proj_dioph (i : Ξ±) : dioph_fn (Ξ»v, v i) :=
abs_poly_dioph (poly.proj i)
theorem dioph_pfun_comp1 {S : set (option Ξ± β β)} (d : dioph S) {f} (df : dioph_pfun f) :
dioph (Ξ»v : Ξ± β β, β h : f.dom v, S (f.fn v h :: v)) :=
ext (ex1_dioph (and_dioph d df)) $ Ξ»v,
β¨Ξ»β¨x, hS, (h: Exists _)β©, by
rw [show (x :: v) β some = v, from funext $ Ξ»s, rfl] at h;
cases h with hf h; refine β¨hf, _β©; rw [pfun.fn, h]; exact hS,
Ξ»β¨x, hSβ©, β¨f.fn v x, hS, show Exists _,
by rw [show (f.fn v x :: v) β some = v, from funext $ Ξ»s, rfl]; exact β¨x, rflβ©β©β©
theorem dioph_fn_comp1 {S : set (option Ξ± β β)} (d : dioph S) {f : (Ξ± β β) β β} (df : dioph_fn f) :
dioph (Ξ»v : Ξ± β β, S (f v :: v)) :=
ext (dioph_pfun_comp1 d (cast (dioph_fn_iff_pfun f) df)) $ Ξ»v,
β¨Ξ»β¨_, hβ©, h, Ξ»h, β¨trivial, hβ©β©
end
section
variables {Ξ± Ξ² Ξ³ : Type}
theorem dioph_fn_vec_comp1 {n} {S : set (vector3 β (succ n))} (d : dioph S) {f : (vector3 β n) β β} (df : dioph_fn f) :
dioph (Ξ»v : vector3 β n, S (cons (f v) v)) :=
ext (dioph_fn_comp1 (reindex_dioph d (none :: some)) df) $ Ξ»v, by rw [
show option.cons (f v) v β (cons none some) = f v :: v,
from funext $ Ξ»s, by cases s with a b; refl]
theorem vec_ex1_dioph (n) {S : set (vector3 β (succ n))} (d : dioph S) : dioph (Ξ»v : vector3 β n, βx, S (x :: v)) :=
ext (ex1_dioph $ reindex_dioph d (none :: some)) $ Ξ»v, exists_congr $ Ξ»x, by rw [
show (option.cons x v) β (cons none some) = x :: v,
from funext $ Ξ»s, by cases s with a b; refl]
theorem dioph_fn_vec {n} (f : vector3 β n β β) : dioph_fn f β dioph (Ξ»v : vector3 β (succ n), f (v β fs) = v fz) :=
β¨Ξ»h, reindex_dioph h (fz :: fs), Ξ»h, reindex_dioph h (none :: some)β©
theorem dioph_pfun_vec {n} (f : vector3 β n β. β) : dioph_pfun f β dioph (Ξ»v : vector3 β (succ n), f.graph (v β fs, v fz)) :=
β¨Ξ»h, reindex_dioph h (fz :: fs), Ξ»h, reindex_dioph h (none :: some)β©
theorem dioph_fn_compn {Ξ± : Type} : β {n} {S : set (Ξ± β fin2 n β β)} (d : dioph S) {f : vector3 ((Ξ± β β) β β) n} (df : vector_allp dioph_fn f),
dioph (Ξ»v : Ξ± β β, S (v β Ξ»i, f i v))
| 0 S d f := Ξ»df, ext (reindex_dioph d (id β fin2.elim0)) $ Ξ»v,
by refine eq.to_iff (congr_arg S $ funext $ Ξ»s, _); {cases s with a b, refl, cases b}
| (succ n) S d f := f.cons_elim $ Ξ»f fl, by simp; exact Ξ» df dfl,
have dioph (Ξ»v, S (v β inl β f (v β inl) :: v β inr)),
from ext (dioph_fn_comp1 (reindex_dioph d (some β inl β none :: some β inr)) (reindex_dioph_fn df inl)) $
Ξ»v, by {refine eq.to_iff (congr_arg S $ funext $ Ξ»s, _); cases s with a b, refl, cases b; refl},
have dioph (Ξ»v, S (v β f v :: Ξ» (i : fin2 n), fl i v)),
from @dioph_fn_compn n (Ξ»v, S (v β inl β f (v β inl) :: v β inr)) this _ dfl,
ext this $ Ξ»v, by rw [
show cons (f v) (Ξ» (i : fin2 n), fl i v) = Ξ» (i : fin2 (succ n)), (f :: fl) i v,
from funext $ Ξ»s, by cases s with a b; refl]
theorem dioph_comp {n} {S : set (vector3 β n)} (d : dioph S)
(f : vector3 ((Ξ± β β) β β) n) (df : vector_allp dioph_fn f) : dioph (Ξ»v, S (Ξ»i, f i v)) :=
dioph_fn_compn (reindex_dioph d inr) df
theorem dioph_fn_comp {n} {f : vector3 β n β β} (df : dioph_fn f)
(g : vector3 ((Ξ± β β) β β) n) (dg : vector_allp dioph_fn g) : dioph_fn (Ξ»v, f (Ξ»i, g i v)) :=
dioph_comp ((dioph_fn_vec _).1 df) ((Ξ»v, v none) :: Ξ»i v, g i (v β some)) $
by simp; exact β¨proj_dioph none, (vector_allp_iff_forall _ _).2 $ Ξ»i,
reindex_dioph_fn ((vector_allp_iff_forall _ _).1 dg _) _β©
local notation x ` Dβ§ `:35 y := and_dioph x y
local notation x ` D⨠`:35 y := or_dioph x y
local notation `Dβ`:30 := vec_ex1_dioph
local prefix `&`:max := of_nat'
theorem proj_dioph_of_nat {n : β} (m : β) [is_lt m n] : dioph_fn (Ξ»v : vector3 β n, v &m) :=
proj_dioph &m
local prefix `D&`:100 := proj_dioph_of_nat
theorem const_dioph (n : β) : dioph_fn (const (Ξ± β β) n) :=
abs_poly_dioph (poly.const n)
local prefix `D.`:100 := const_dioph
variables {f g : (Ξ± β β) β β} (df : dioph_fn f) (dg : dioph_fn g)
include df dg
theorem dioph_comp2 {S : β β β β Prop} (d : dioph (Ξ»v:vector3 β 2, S (v &0) (v &1))) :
dioph (Ξ»v, S (f v) (g v)) :=
dioph_comp d [f, g] (by exact β¨df, dgβ©)
theorem dioph_fn_comp2 {h : β β β β β} (d : dioph_fn (Ξ»v:vector3 β 2, h (v &0) (v &1))) :
dioph_fn (Ξ»v, h (f v) (g v)) :=
dioph_fn_comp d [f, g] (by exact β¨df, dgβ©)
theorem eq_dioph : dioph (Ξ»v, f v = g v) :=
dioph_comp2 df dg $ of_no_dummies _ (poly.proj &0 - poly.proj &1)
(Ξ»v, (int.coe_nat_eq_coe_nat_iff _ _).symm.trans
β¨@sub_eq_zero_of_eq β€ _ (v &0) (v &1), eq_of_sub_eq_zeroβ©)
local infix ` D= `:50 := eq_dioph
theorem add_dioph : dioph_fn (Ξ»v, f v + g v) :=
dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 + poly.proj &1)
local infix ` D+ `:80 := add_dioph
theorem mul_dioph : dioph_fn (Ξ»v, f v * g v) :=
dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 * poly.proj &1)
local infix ` D* `:90 := mul_dioph
theorem le_dioph : dioph (Ξ»v, f v β€ g v) :=
dioph_comp2 df dg $ ext (Dβ2 $ D&1 D+ D&0 D= D&2) (Ξ»v, β¨Ξ»β¨x, hxβ©, le.intro hx, le.destβ©)
local infix ` Dβ€ `:50 := le_dioph
theorem lt_dioph : dioph (Ξ»v, f v < g v) := df D+ (D. 1) Dβ€ dg
local infix ` D< `:50 := lt_dioph
theorem ne_dioph : dioph (Ξ»v, f v β g v) :=
ext (df D< dg D⨠dg D< df) $ λv, ne_iff_lt_or_gt.symm
local infix ` Dβ `:50 := ne_dioph
theorem sub_dioph : dioph_fn (Ξ»v, f v - g v) :=
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $
ext (D&1 D= D&0 D+ D&2 D⨠D&1 D†D&2 D⧠D&0 D= D.0) $ (vector_all_iff_forall _).1 $ λx y z,
show (y = x + z β¨ y β€ z β§ x = 0) β y - z = x, from
β¨Ξ»o, begin
rcases o with ae | β¨yz, x0β©,
{ rw [ae, nat.add_sub_cancel] },
{ rw [x0, nat.sub_eq_zero_of_le yz] }
end, Ξ»h, begin
subst x,
cases le_total y z with yz zy,
{ exact or.inr β¨yz, nat.sub_eq_zero_of_le yzβ© },
{ exact or.inl (nat.sub_add_cancel zy).symm },
endβ©
local infix ` D- `:80 := sub_dioph
theorem dvd_dioph : dioph (Ξ»v, f v β£ g v) :=
dioph_comp (Dβ2 $ D&2 D= D&1 D* D&0) [f, g] (by exact β¨df, dgβ©)
local infix ` Dβ£ `:50 := dvd_dioph
theorem mod_dioph : dioph_fn (Ξ»v, f v % g v) :=
have dioph (Ξ»v : vector3 β 3, (v &2 = 0 β¨ v &0 < v &2) β§ β (x : β), v &0 + v &2 * x = v &1),
from (D&2 D= D.0 Dβ¨ D&0 D< D&2) Dβ§ (Dβ3 $ D&1 D+ D&3 D* D&0 D= D&2),
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ Ξ»z x y,
show ((y = 0 β¨ z < y) β§ β c, z + y * c = x) β x % y = z, from
β¨Ξ»β¨h, c, hcβ©, begin rw β hc; simp; cases h with x0 hl, rw [x0, mod_zero], exact mod_eq_of_lt hl end,
Ξ»e, by rw β e; exact β¨or_iff_not_imp_left.2 $ Ξ»h, mod_lt _ (nat.pos_of_ne_zero h), x / y, mod_add_div _ _β©β©
local infix ` D% `:80 := mod_dioph
theorem modeq_dioph {h : (Ξ± β β) β β} (dh : dioph_fn h) : dioph (Ξ»v, f v β‘ g v [MOD h v]) :=
df D% dh D= dg D% dh
local notation `Dβ‘` := modeq_dioph
theorem div_dioph : dioph_fn (Ξ»v, f v / g v) :=
have dioph (Ξ»v : vector3 β 3, v &2 = 0 β§ v &0 = 0 β¨ v &0 * v &2 β€ v &1 β§ v &1 < (v &0 + 1) * v &2),
from (D&2 D= D.0 D⧠D&0 D= D.0) D⨠D&0 D* D&2 D†D&1 D⧠D&1 D< (D&0 D+ D.1) D* D&2,
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ Ξ»z x y,
show y = 0 β§ z = 0 β¨ z * y β€ x β§ x < (z + 1) * y β x / y = z,
by refine iff.trans _ eq_comm; exact y.eq_zero_or_pos.elim
(Ξ»y0, by rw [y0, nat.div_zero]; exact
β¨Ξ»o, (o.resolve_right $ Ξ»β¨_, h2β©, not_lt_zero _ h2).right, Ξ»z0, or.inl β¨rfl, z0β©β©)
(Ξ»ypos, iff.trans β¨Ξ»o, o.resolve_left $ Ξ»β¨h1, _β©, ne_of_gt ypos h1, or.inrβ©
(le_antisymm_iff.trans $ and_congr (nat.le_div_iff_mul_le _ _ ypos) $
iff.trans β¨lt_succ_of_le, le_of_lt_succβ© (div_lt_iff_lt_mul _ _ ypos)).symm)
local infix ` D/ `:80 := div_dioph
omit df dg
open pell
theorem pell_dioph : dioph (Ξ»v:vector3 β 4, β h : v &0 > 1,
xn h (v &1) = v &2 β§ yn h (v &1) = v &3) :=
have dioph {v : vector3 β 4 |
v &0 > 1 β§ v &1 β€ v &3 β§
(v &2 = 1 β§ v &3 = 0 β¨
β (u w s t b : β),
v &2 * v &2 - (v &0 * v &0 - 1) * v &3 * v &3 = 1 β§
u * u - (v &0 * v &0 - 1) * w * w = 1 β§
s * s - (b * b - 1) * t * t = 1 β§
b > 1 β§ (b β‘ 1 [MOD 4 * v &3]) β§ (b β‘ v &0 [MOD u]) β§
w > 0 β§ v &3 * v &3 β£ w β§
(s β‘ v &2 [MOD u]) β§
(t β‘ v &1 [MOD 4 * v &3]))}, from
D.1 D< D&0 Dβ§ D&1 Dβ€ D&3 Dβ§
((D&2 D= D.1 Dβ§ D&3 D= D.0) Dβ¨
(Dβ4 $ Dβ5 $ Dβ6 $ Dβ7 $ Dβ8 $
D&7 D* D&7 D- (D&5 D* D&5 D- D.1) D* D&8 D* D&8 D= D.1 Dβ§
D&4 D* D&4 D- (D&5 D* D&5 D- D.1) D* D&3 D* D&3 D= D.1 Dβ§
D&2 D* D&2 D- (D&0 D* D&0 D- D.1) D* D&1 D* D&1 D= D.1 Dβ§
D.1 D< D&0 Dβ§ (Dβ‘ (D&0) (D.1) (D.4 D* D&8)) Dβ§ (Dβ‘ (D&0) (D&5) D&4) Dβ§
D.0 D< D&3 Dβ§ D&8 D* D&8 Dβ£ D&3 Dβ§
(Dβ‘ (D&2) (D&7) D&4) Dβ§
(Dβ‘ (D&1) (D&6) (D.4 D* D&8)))),
dioph.ext this $ Ξ»v, matiyasevic.symm
theorem xn_dioph : dioph_pfun (Ξ»v:vector3 β 2, β¨v &0 > 1, Ξ»h, xn h (v &1)β©) :=
have dioph (Ξ»v:vector3 β 3, β y, β h : v &1 > 1, xn h (v &2) = v &0 β§ yn h (v &2) = y), from
let D_pell := @reindex_dioph _ (fin2 4) _ pell_dioph [&2, &3, &1, &0] in Dβ3 D_pell,
(dioph_pfun_vec _).2 $ dioph.ext this $ Ξ»v, β¨Ξ»β¨y, h, xe, yeβ©, β¨h, xeβ©, Ξ»β¨h, xeβ©, β¨_, h, xe, rflβ©β©
include df dg
theorem pow_dioph : dioph_fn (Ξ»v, f v ^ g v) :=
have dioph {v : vector3 β 3 |
v &2 = 0 β§ v &0 = 1 β¨ v &2 > 0 β§
(v &1 = 0 β§ v &0 = 0 β¨ v &1 > 0 β§
β (w a t z x y : β),
(β (a1 : a > 1), xn a1 (v &2) = x β§ yn a1 (v &2) = y) β§
(x β‘ y * (a - v &1) + v &0 [MOD t]) β§
2 * a * v &1 = t + (v &1 * v &1 + 1) β§
v &0 < t β§ v &1 β€ w β§ v &2 β€ w β§
a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)}, from
let D_pell := @reindex_dioph _ (fin2 9) _ pell_dioph [&4, &8, &1, &0] in
(D&2 D= D.0 Dβ§ D&0 D= D.1) Dβ¨ (D.0 D< D&2 Dβ§
((D&1 D= D.0 Dβ§ D&0 D= D.0) Dβ¨ (D.0 D< D&1 Dβ§
(Dβ3 $ Dβ4 $ Dβ5 $ Dβ6 $ Dβ7 $ Dβ8 $ D_pell Dβ§
(Dβ‘ (D&1) (D&0 D* (D&4 D- D&7) D+ D&6) (D&3)) Dβ§
D.2 D* D&4 D* D&7 D= D&3 D+ (D&7 D* D&7 D+ D.1) Dβ§
D&6 D< D&3 Dβ§ D&7 Dβ€ D&5 Dβ§ D&8 Dβ€ D&5 Dβ§
D&4 D* D&4 D- ((D&5 D+ D.1) D* (D&5 D+ D.1) D- D.1) D* (D&5 D* D&2) D* (D&5 D* D&2) D= D.1)))),
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ dioph.ext this $ Ξ»v, iff.symm $
eq_pow_of_pell.trans $ or_congr iff.rfl $ and_congr iff.rfl $ or_congr iff.rfl $ and_congr iff.rfl $
β¨Ξ»β¨w, a, t, z, a1, hβ©, β¨w, a, t, z, _, _, β¨a1, rfl, rflβ©, hβ©,
Ξ»β¨w, a, t, z, ._, ._, β¨a1, rfl, rflβ©, hβ©, β¨w, a, t, z, a1, hβ©β©
end
end dioph
|
453151764e1b29ad0ec41f2bf97223787c97a762 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/order/sub.lean | 997400f128e390dba79620a6eb7cabc73d41242e | [
"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 | 30,204 | lean | /-
Copyright (c) 2021 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import algebra.order.monoid
/-!
# Ordered Subtraction
This file proves lemmas relating (truncated) subtraction with an order. We provide a class
`has_ordered_sub` stating that `a - b β€ c β a β€ c + b`.
The subtraction discussed here could both be normal subtraction in an additive group or truncated
subtraction on a canonically ordered monoid (`β`, `multiset`, `enat`, `ennreal`, ...)
## Implementation details
`has_ordered_sub` is a mixin type-class, so that we can use the results in this file even in cases
where we don't have a `canonically_ordered_add_monoid` instance
(even though that is our main focus). Conversely, this means we can use
`canonically_ordered_add_monoid` without necessarily having to define a subtraction.
The results in this file are ordered by the type-class assumption needed to prove it.
This means that similar results might not be close to each other. Furthermore, we don't prove
implications if a bi-implication can be proven under the same assumptions.
Lemmas using this class are named using `tsub` instead of `sub` (short for "truncated subtraction").
This is to avoid naming conflicts with similar lemmas about ordered groups.
We provide a second version of most results that require `[contravariant_class Ξ± Ξ± (+) (β€)]`. In the
second version we replace this type-class assumption by explicit `add_le_cancellable` assumptions.
TODO: maybe we should make a multiplicative version of this, so that we can replace some identical
lemmas about subtraction/division in `ordered_[add_]comm_group` with these.
TODO: generalize `nat.le_of_le_of_sub_le_sub_right`, `nat.sub_le_sub_right_iff`,
`nat.mul_self_sub_mul_self_eq`
-/
variables {Ξ± Ξ² : Type*}
/-- `has_ordered_sub Ξ±` means that `Ξ±` has a subtraction characterized by `a - b β€ c β a β€ c + b`.
In other words, `a - b` is the least `c` such that `a β€ b + c`.
This is satisfied both by the subtraction in additive ordered groups and by truncated subtraction
in canonically ordered monoids on many specific types.
-/
class has_ordered_sub (Ξ± : Type*) [has_le Ξ±] [has_add Ξ±] [has_sub Ξ±] :=
(tsub_le_iff_right : β a b c : Ξ±, a - b β€ c β a β€ c + b)
section has_add
variables [preorder Ξ±] [has_add Ξ±] [has_sub Ξ±] [has_ordered_sub Ξ±] {a b c d : Ξ±}
@[simp] lemma tsub_le_iff_right : a - b β€ c β a β€ c + b :=
has_ordered_sub.tsub_le_iff_right a b c
/-- See `add_tsub_cancel_right` for the equality if `contravariant_class Ξ± Ξ± (+) (β€)`. -/
lemma add_tsub_le_right : a + b - b β€ a :=
tsub_le_iff_right.mpr le_rfl
lemma le_tsub_add : b β€ (b - a) + a :=
tsub_le_iff_right.mp le_rfl
lemma add_hom.le_map_tsub [preorder Ξ²] [has_add Ξ²] [has_sub Ξ²] [has_ordered_sub Ξ²]
(f : add_hom Ξ± Ξ²) (hf : monotone f) (a b : Ξ±) :
f a - f b β€ f (a - b) :=
by { rw [tsub_le_iff_right, β f.map_add], exact hf le_tsub_add }
lemma le_mul_tsub {R : Type*} [distrib R] [preorder R] [has_sub R] [has_ordered_sub R]
[covariant_class R R (*) (β€)] {a b c : R} :
a * b - a * c β€ a * (b - c) :=
(add_hom.mul_left a).le_map_tsub (monotone_id.const_mul' a) _ _
lemma le_tsub_mul {R : Type*} [comm_semiring R] [preorder R] [has_sub R] [has_ordered_sub R]
[covariant_class R R (*) (β€)] {a b c : R} :
a * c - b * c β€ (a - b) * c :=
by simpa only [mul_comm _ c] using le_mul_tsub
end has_add
/-- An order isomorphism between types with ordered subtraction preserves subtraction provided that
it preserves addition. -/
lemma order_iso.map_tsub {M N : Type*} [preorder M] [has_add M] [has_sub M] [has_ordered_sub M]
[partial_order N] [has_add N] [has_sub N] [has_ordered_sub N] (e : M βo N)
(h_add : β a b, e (a + b) = e a + e b) (a b : M) :
e (a - b) = e a - e b :=
begin
set e_add : M β+ N := { map_add' := h_add, .. e },
refine le_antisymm _ (e_add.to_add_hom.le_map_tsub e.monotone a b),
suffices : e (e.symm (e a) - e.symm (e b)) β€ e (e.symm (e a - e b)), by simpa,
exact e.monotone (e_add.symm.to_add_hom.le_map_tsub e.symm.monotone _ _)
end
/-! ### Preorder -/
section ordered_add_comm_monoid
section preorder
variables [preorder Ξ±]
section add_comm_semigroup
variables [add_comm_semigroup Ξ±] [has_sub Ξ±] [has_ordered_sub Ξ±] {a b c d : Ξ±}
lemma tsub_le_iff_left : a - b β€ c β a β€ b + c :=
by rw [tsub_le_iff_right, add_comm]
lemma le_add_tsub : a β€ b + (a - b) :=
tsub_le_iff_left.mp le_rfl
/-- See `add_tsub_cancel_left` for the equality if `contravariant_class Ξ± Ξ± (+) (β€)`. -/
lemma add_tsub_le_left : a + b - a β€ b :=
tsub_le_iff_left.mpr le_rfl
lemma tsub_le_tsub_right (h : a β€ b) (c : Ξ±) : a - c β€ b - c :=
tsub_le_iff_left.mpr $ h.trans le_add_tsub
lemma tsub_le_iff_tsub_le : a - b β€ c β a - c β€ b :=
by rw [tsub_le_iff_left, tsub_le_iff_right]
/-- See `tsub_tsub_cancel_of_le` for the equality. -/
lemma tsub_tsub_le : b - (b - a) β€ a :=
tsub_le_iff_right.mpr le_add_tsub
section cov
variable [covariant_class Ξ± Ξ± (+) (β€)]
lemma tsub_le_tsub_left (h : a β€ b) (c : Ξ±) : c - b β€ c - a :=
tsub_le_iff_left.mpr $ le_add_tsub.trans $ add_le_add_right h _
lemma tsub_le_tsub (hab : a β€ b) (hcd : c β€ d) : a - d β€ b - c :=
(tsub_le_tsub_right hab _).trans $ tsub_le_tsub_left hcd _
/-- See `add_tsub_assoc_of_le` for the equality. -/
lemma add_tsub_le_assoc : a + b - c β€ a + (b - c) :=
by { rw [tsub_le_iff_left, add_left_comm], exact add_le_add_left le_add_tsub a }
lemma add_le_add_add_tsub : a + b β€ (a + c) + (b - c) :=
by { rw [add_assoc], exact add_le_add_left le_add_tsub a }
lemma le_tsub_add_add : a + b β€ (a - c) + (b + c) :=
by { rw [add_comm a, add_comm (a - c)], exact add_le_add_add_tsub }
lemma tsub_le_tsub_add_tsub : a - c β€ (a - b) + (b - c) :=
begin
rw [tsub_le_iff_left, β add_assoc, add_right_comm],
exact le_add_tsub.trans (add_le_add_right le_add_tsub _),
end
lemma tsub_tsub_tsub_le_tsub : (c - a) - (c - b) β€ b - a :=
begin
rw [tsub_le_iff_left, tsub_le_iff_left, add_left_comm],
exact le_tsub_add.trans (add_le_add_left le_add_tsub _),
end
lemma tsub_tsub_le_tsub_add {a b c : Ξ±} : a - (b - c) β€ a - b + c :=
tsub_le_iff_right.2 $ calc
a β€ a - b + b : le_tsub_add
... β€ a - b + (c + (b - c)) : add_le_add_left le_add_tsub _
... = a - b + c + (b - c) : (add_assoc _ _ _).symm
end cov
/-! #### Lemmas that assume that an element is `add_le_cancellable` -/
namespace add_le_cancellable
protected lemma le_add_tsub_swap (hb : add_le_cancellable b) : a β€ b + a - b := hb le_add_tsub
protected lemma le_add_tsub (hb : add_le_cancellable b) : a β€ a + b - b :=
by { rw add_comm, exact hb.le_add_tsub_swap }
protected lemma le_tsub_of_add_le_left (ha : add_le_cancellable a) (h : a + b β€ c) : b β€ c - a :=
ha $ h.trans le_add_tsub
protected lemma le_tsub_of_add_le_right (hb : add_le_cancellable b) (h : a + b β€ c) : a β€ c - b :=
hb.le_tsub_of_add_le_left $ by rwa add_comm
end add_le_cancellable
/-! ### Lemmas where addition is order-reflecting -/
section contra
variable [contravariant_class Ξ± Ξ± (+) (β€)]
lemma le_add_tsub_swap : a β€ b + a - b := contravariant.add_le_cancellable.le_add_tsub_swap
lemma le_add_tsub' : a β€ a + b - b := contravariant.add_le_cancellable.le_add_tsub
lemma le_tsub_of_add_le_left (h : a + b β€ c) : b β€ c - a :=
contravariant.add_le_cancellable.le_tsub_of_add_le_left h
lemma le_tsub_of_add_le_right (h : a + b β€ c) : a β€ c - b :=
contravariant.add_le_cancellable.le_tsub_of_add_le_right h
end contra
end add_comm_semigroup
variables [add_comm_monoid Ξ±] [has_sub Ξ±] [has_ordered_sub Ξ±] {a b c d : Ξ±}
lemma tsub_nonpos : a - b β€ 0 β a β€ b := by rw [tsub_le_iff_left, add_zero]
alias tsub_nonpos β _ tsub_nonpos_of_le
lemma add_monoid_hom.le_map_tsub [preorder Ξ²] [add_comm_monoid Ξ²] [has_sub Ξ²]
[has_ordered_sub Ξ²] (f : Ξ± β+ Ξ²) (hf : monotone f) (a b : Ξ±) :
f a - f b β€ f (a - b) :=
f.to_add_hom.le_map_tsub hf a b
end preorder
/-! ### Partial order -/
variables [partial_order Ξ±] [add_comm_semigroup Ξ±] [has_sub Ξ±] [has_ordered_sub Ξ±] {a b c d : Ξ±}
lemma tsub_tsub (b a c : Ξ±) : b - a - c = b - (a + c) :=
begin
apply le_antisymm,
{ rw [tsub_le_iff_left, tsub_le_iff_left, β add_assoc, β tsub_le_iff_left] },
{ rw [tsub_le_iff_left, add_assoc, β tsub_le_iff_left, β tsub_le_iff_left] }
end
section cov
variable [covariant_class Ξ± Ξ± (+) (β€)]
lemma tsub_add_eq_tsub_tsub (a b c : Ξ±) : a - (b + c) = a - b - c :=
begin
refine le_antisymm (tsub_le_iff_left.mpr _)
(tsub_le_iff_left.mpr $ tsub_le_iff_left.mpr _),
{ rw [add_assoc], refine le_trans le_add_tsub (add_le_add_left le_add_tsub _) },
{ rw [β add_assoc], apply le_add_tsub }
end
lemma tsub_add_eq_tsub_tsub_swap (a b c : Ξ±) : a - (b + c) = a - c - b :=
by { rw [add_comm], apply tsub_add_eq_tsub_tsub }
lemma tsub_right_comm : a - b - c = a - c - b :=
by simp_rw [β tsub_add_eq_tsub_tsub, add_comm]
end cov
/-! ### Lemmas that assume that an element is `add_le_cancellable`. -/
namespace add_le_cancellable
protected lemma tsub_eq_of_eq_add (hb : add_le_cancellable b) (h : a = c + b) : a - b = c :=
le_antisymm (tsub_le_iff_right.mpr h.le) $
by { rw h, exact hb.le_add_tsub }
protected lemma eq_tsub_of_add_eq (hc : add_le_cancellable c) (h : a + c = b) : a = b - c :=
(hc.tsub_eq_of_eq_add h.symm).symm
protected theorem tsub_eq_of_eq_add_rev (hb : add_le_cancellable b) (h : a = b + c) : a - b = c :=
hb.tsub_eq_of_eq_add $ by rw [add_comm, h]
@[simp]
protected lemma add_tsub_cancel_right (hb : add_le_cancellable b) : a + b - b = a :=
hb.tsub_eq_of_eq_add $ by rw [add_comm]
@[simp]
protected lemma add_tsub_cancel_left (ha : add_le_cancellable a) : a + b - a = b :=
ha.tsub_eq_of_eq_add $ add_comm a b
protected lemma lt_add_of_tsub_lt_left (hb : add_le_cancellable b) (h : a - b < c) : a < b + c :=
begin
rw [lt_iff_le_and_ne, β tsub_le_iff_left],
refine β¨h.le, _β©,
rintro rfl,
simpa [hb] using h,
end
protected lemma lt_add_of_tsub_lt_right (hc : add_le_cancellable c) (h : a - c < b) : a < b + c :=
begin
rw [lt_iff_le_and_ne, β tsub_le_iff_right],
refine β¨h.le, _β©,
rintro rfl,
simpa [hc] using h,
end
end add_le_cancellable
/-! #### Lemmas where addition is order-reflecting. -/
section contra
variable [contravariant_class Ξ± Ξ± (+) (β€)]
lemma tsub_eq_of_eq_add (h : a = c + b) : a - b = c :=
contravariant.add_le_cancellable.tsub_eq_of_eq_add h
lemma eq_tsub_of_add_eq (h : a + c = b) : a = b - c :=
contravariant.add_le_cancellable.eq_tsub_of_add_eq h
lemma tsub_eq_of_eq_add_rev (h : a = b + c) : a - b = c :=
contravariant.add_le_cancellable.tsub_eq_of_eq_add_rev h
@[simp]
lemma add_tsub_cancel_right (a b : Ξ±) : a + b - b = a :=
contravariant.add_le_cancellable.add_tsub_cancel_right
@[simp]
lemma add_tsub_cancel_left (a b : Ξ±) : a + b - a = b :=
contravariant.add_le_cancellable.add_tsub_cancel_left
lemma lt_add_of_tsub_lt_left (h : a - b < c) : a < b + c :=
contravariant.add_le_cancellable.lt_add_of_tsub_lt_left h
lemma lt_add_of_tsub_lt_right (h : a - c < b) : a < b + c :=
contravariant.add_le_cancellable.lt_add_of_tsub_lt_right h
end contra
section both
variables [covariant_class Ξ± Ξ± (+) (β€)] [contravariant_class Ξ± Ξ± (+) (β€)]
lemma add_tsub_add_eq_tsub_right (a c b : Ξ±) : (a + c) - (b + c) = a - b :=
begin
apply le_antisymm,
{ rw [tsub_le_iff_left, add_right_comm], exact add_le_add_right le_add_tsub c },
{ rw [tsub_le_iff_left, add_comm b],
apply le_of_add_le_add_right,
rw [add_assoc],
exact le_tsub_add }
end
lemma add_tsub_add_eq_tsub_left (a b c : Ξ±) : (a + b) - (a + c) = b - c :=
by rw [add_comm a b, add_comm a c, add_tsub_add_eq_tsub_right]
end both
end ordered_add_comm_monoid
/-! ### Lemmas in a linearly ordered monoid. -/
section linear_order
variables {a b c d : Ξ±} [linear_order Ξ±] [add_comm_semigroup Ξ±] [has_sub Ξ±] [has_ordered_sub Ξ±]
/-- See `lt_of_tsub_lt_tsub_right_of_le` for a weaker statement in a partial order. -/
lemma lt_of_tsub_lt_tsub_right (h : a - c < b - c) : a < b :=
lt_imp_lt_of_le_imp_le (Ξ» h, tsub_le_tsub_right h c) h
/-- See `lt_tsub_iff_right_of_le` for a weaker statement in a partial order. -/
lemma lt_tsub_iff_right : a < b - c β a + c < b :=
lt_iff_lt_of_le_iff_le tsub_le_iff_right
/-- See `lt_tsub_iff_left_of_le` for a weaker statement in a partial order. -/
lemma lt_tsub_iff_left : a < b - c β c + a < b :=
lt_iff_lt_of_le_iff_le tsub_le_iff_left
lemma lt_tsub_comm : a < b - c β c < b - a :=
lt_tsub_iff_left.trans lt_tsub_iff_right.symm
section cov
variable [covariant_class Ξ± Ξ± (+) (β€)]
/-- See `lt_of_tsub_lt_tsub_left_of_le` for a weaker statement in a partial order. -/
lemma lt_of_tsub_lt_tsub_left (h : a - b < a - c) : c < b :=
lt_imp_lt_of_le_imp_le (Ξ» h, tsub_le_tsub_left h a) h
end cov
end linear_order
/-! ### Lemmas in a canonically ordered monoid. -/
section canonically_ordered_add_monoid
variables [canonically_ordered_add_monoid Ξ±] [has_sub Ξ±] [has_ordered_sub Ξ±] {a b c d : Ξ±}
@[simp] lemma add_tsub_cancel_of_le (h : a β€ b) : a + (b - a) = b :=
begin
refine le_antisymm _ le_add_tsub,
obtain β¨c, rflβ© := le_iff_exists_add.1 h,
exact add_le_add_left add_tsub_le_left a,
end
lemma tsub_add_cancel_of_le (h : a β€ b) : b - a + a = b :=
by { rw [add_comm], exact add_tsub_cancel_of_le h }
lemma add_tsub_cancel_iff_le : a + (b - a) = b β a β€ b :=
β¨Ξ» h, le_iff_exists_add.mpr β¨b - a, h.symmβ©, add_tsub_cancel_of_leβ©
lemma tsub_add_cancel_iff_le : b - a + a = b β a β€ b :=
by { rw [add_comm], exact add_tsub_cancel_iff_le }
lemma add_le_of_le_tsub_right_of_le (h : b β€ c) (h2 : a β€ c - b) : a + b β€ c :=
(add_le_add_right h2 b).trans_eq $ tsub_add_cancel_of_le h
lemma add_le_of_le_tsub_left_of_le (h : a β€ c) (h2 : b β€ c - a) : a + b β€ c :=
(add_le_add_left h2 a).trans_eq $ add_tsub_cancel_of_le h
lemma tsub_le_tsub_iff_right (h : c β€ b) : a - c β€ b - c β a β€ b :=
by rw [tsub_le_iff_right, tsub_add_cancel_of_le h]
lemma tsub_left_inj (h1 : c β€ a) (h2 : c β€ b) : a - c = b - c β a = b :=
by simp_rw [le_antisymm_iff, tsub_le_tsub_iff_right h1, tsub_le_tsub_iff_right h2]
/-- See `lt_of_tsub_lt_tsub_right` for a stronger statement in a linear order. -/
lemma lt_of_tsub_lt_tsub_right_of_le (h : c β€ b) (h2 : a - c < b - c) : a < b :=
by { refine ((tsub_le_tsub_iff_right h).mp h2.le).lt_of_ne _, rintro rfl, exact h2.false }
@[simp] lemma tsub_eq_zero_iff_le : a - b = 0 β a β€ b :=
by rw [β nonpos_iff_eq_zero, tsub_le_iff_left, add_zero]
/-- One direction of `tsub_eq_zero_iff_le`, as a `@[simp]`-lemma. -/
@[simp] lemma tsub_eq_zero_of_le (h : a β€ b) : a - b = 0 :=
tsub_eq_zero_iff_le.mpr h
@[simp] lemma tsub_self (a : Ξ±) : a - a = 0 :=
tsub_eq_zero_iff_le.mpr le_rfl
@[simp] lemma tsub_le_self : a - b β€ a :=
tsub_le_iff_left.mpr $ le_add_left le_rfl
@[simp] lemma tsub_zero (a : Ξ±) : a - 0 = a :=
le_antisymm tsub_le_self $ le_add_tsub.trans_eq $ zero_add _
@[simp] lemma zero_tsub (a : Ξ±) : 0 - a = 0 :=
tsub_eq_zero_iff_le.mpr $ zero_le a
lemma tsub_self_add (a b : Ξ±) : a - (a + b) = 0 :=
by { rw [tsub_eq_zero_iff_le], apply self_le_add_right }
lemma tsub_inj_left (hβ : a β€ b) (hβ : a β€ c) (hβ : b - a = c - a) : b = c :=
by rw [β tsub_add_cancel_of_le hβ, β tsub_add_cancel_of_le hβ, hβ]
lemma tsub_pos_iff_not_le : 0 < a - b β Β¬ a β€ b :=
by rw [pos_iff_ne_zero, ne.def, tsub_eq_zero_iff_le]
lemma tsub_pos_of_lt (h : a < b) : 0 < b - a :=
tsub_pos_iff_not_le.mpr h.not_le
lemma tsub_add_tsub_cancel (hab : b β€ a) (hbc : c β€ b) : (a - b) + (b - c) = a - c :=
begin
convert tsub_add_cancel_of_le (tsub_le_tsub_right hab c) using 2,
rw [tsub_tsub, add_tsub_cancel_of_le hbc],
end
lemma tsub_tsub_tsub_cancel_right (h : c β€ b) : (a - c) - (b - c) = a - b :=
by rw [tsub_tsub, add_tsub_cancel_of_le h]
/-! ### Lemmas that assume that an element is `add_le_cancellable`. -/
namespace add_le_cancellable
protected lemma eq_tsub_iff_add_eq_of_le (hc : add_le_cancellable c) (h : c β€ b) :
a = b - c β a + c = b :=
begin
split,
{ rintro rfl, exact tsub_add_cancel_of_le h },
{ rintro rfl, exact (hc.add_tsub_cancel_right).symm }
end
protected lemma tsub_eq_iff_eq_add_of_le (hb : add_le_cancellable b) (h : b β€ a) :
a - b = c β a = c + b :=
by rw [eq_comm, hb.eq_tsub_iff_add_eq_of_le h, eq_comm]
protected lemma add_tsub_assoc_of_le (hc : add_le_cancellable c) (h : c β€ b) (a : Ξ±) :
a + b - c = a + (b - c) :=
by conv_lhs { rw [β add_tsub_cancel_of_le h, add_comm c, β add_assoc,
hc.add_tsub_cancel_right] }
protected lemma tsub_add_eq_add_tsub (hb : add_le_cancellable b) (h : b β€ a) :
a - b + c = a + c - b :=
by rw [add_comm a, hb.add_tsub_assoc_of_le h, add_comm]
protected lemma tsub_tsub_assoc (hbc : add_le_cancellable (b - c)) (hβ : b β€ a) (hβ : c β€ b) :
a - (b - c) = a - b + c :=
by rw [hbc.tsub_eq_iff_eq_add_of_le (tsub_le_self.trans hβ), add_assoc,
add_tsub_cancel_of_le hβ, tsub_add_cancel_of_le hβ]
protected lemma le_tsub_iff_left (ha : add_le_cancellable a) (h : a β€ c) : b β€ c - a β a + b β€ c :=
β¨add_le_of_le_tsub_left_of_le h, ha.le_tsub_of_add_le_leftβ©
protected lemma le_tsub_iff_right (ha : add_le_cancellable a) (h : a β€ c) : b β€ c - a β b + a β€ c :=
by { rw [add_comm], exact ha.le_tsub_iff_left h }
protected lemma tsub_lt_iff_left (hb : add_le_cancellable b) (hba : b β€ a) :
a - b < c β a < b + c :=
begin
refine β¨hb.lt_add_of_tsub_lt_left, _β©,
intro h, refine (tsub_le_iff_left.mpr h.le).lt_of_ne _,
rintro rfl, exact h.ne' (add_tsub_cancel_of_le hba)
end
protected lemma tsub_lt_iff_right (hb : add_le_cancellable b) (hba : b β€ a) :
a - b < c β a < c + b :=
by { rw [add_comm], exact hb.tsub_lt_iff_left hba }
protected lemma lt_tsub_of_add_lt_right (hc : add_le_cancellable c) (h : a + c < b) : a < b - c :=
begin
apply lt_of_le_of_ne,
{ rw [β add_tsub_cancel_of_le h.le, add_right_comm, add_assoc],
rw [hc.add_tsub_assoc_of_le], refine le_self_add, refine le_add_self },
{ rintro rfl, apply h.not_le, exact le_tsub_add }
end
protected lemma lt_tsub_of_add_lt_left (ha : add_le_cancellable a) (h : a + c < b) : c < b - a :=
by { apply ha.lt_tsub_of_add_lt_right, rwa add_comm }
protected lemma tsub_lt_iff_tsub_lt (hb : add_le_cancellable b) (hc : add_le_cancellable c)
(hβ : b β€ a) (hβ : c β€ a) : a - b < c β a - c < b :=
by rw [hb.tsub_lt_iff_left hβ, hc.tsub_lt_iff_right hβ]
protected lemma le_tsub_iff_le_tsub (ha : add_le_cancellable a) (hc : add_le_cancellable c)
(hβ : a β€ b) (hβ : c β€ b) : a β€ b - c β c β€ b - a :=
by rw [ha.le_tsub_iff_left hβ, hc.le_tsub_iff_right hβ]
protected lemma lt_tsub_iff_right_of_le (hc : add_le_cancellable c) (h : c β€ b) :
a < b - c β a + c < b :=
begin
refine β¨_, hc.lt_tsub_of_add_lt_rightβ©,
intro h2,
refine (add_le_of_le_tsub_right_of_le h h2.le).lt_of_ne _,
rintro rfl,
apply h2.not_le,
rw [hc.add_tsub_cancel_right]
end
protected lemma lt_tsub_iff_left_of_le (hc : add_le_cancellable c) (h : c β€ b) :
a < b - c β c + a < b :=
by { rw [add_comm], exact hc.lt_tsub_iff_right_of_le h }
protected lemma lt_of_tsub_lt_tsub_left_of_le [contravariant_class Ξ± Ξ± (+) (<)]
(hb : add_le_cancellable b) (hca : c β€ a) (h : a - b < a - c) : c < b :=
begin
conv_lhs at h { rw [β tsub_add_cancel_of_le hca] },
exact lt_of_add_lt_add_left (hb.lt_add_of_tsub_lt_right h),
end
protected lemma tsub_le_tsub_iff_left (ha : add_le_cancellable a) (hc : add_le_cancellable c)
(h : c β€ a) : a - b β€ a - c β c β€ b :=
begin
refine β¨_, Ξ» h, tsub_le_tsub_left h aβ©,
rw [tsub_le_iff_left, β hc.add_tsub_assoc_of_le h,
hc.le_tsub_iff_right (h.trans le_add_self), add_comm b],
apply ha,
end
protected lemma tsub_right_inj (ha : add_le_cancellable a) (hb : add_le_cancellable b)
(hc : add_le_cancellable c) (hba : b β€ a) (hca : c β€ a) : a - b = a - c β b = c :=
by simp_rw [le_antisymm_iff, ha.tsub_le_tsub_iff_left hb hba, ha.tsub_le_tsub_iff_left hc hca,
and_comm]
protected lemma tsub_lt_tsub_right_of_le (hc : add_le_cancellable c) (h : c β€ a) (h2 : a < b) :
a - c < b - c :=
by { apply hc.lt_tsub_of_add_lt_left, rwa [add_tsub_cancel_of_le h] }
protected lemma tsub_inj_right (hab : add_le_cancellable (a - b)) (hβ : b β€ a) (hβ : c β€ a)
(hβ : a - b = a - c) : b = c :=
by { rw β hab.inj, rw [tsub_add_cancel_of_le hβ, hβ, tsub_add_cancel_of_le hβ] }
protected lemma tsub_lt_tsub_iff_left_of_le_of_le [contravariant_class Ξ± Ξ± (+) (<)]
(hb : add_le_cancellable b) (hab : add_le_cancellable (a - b)) (hβ : b β€ a) (hβ : c β€ a) :
a - b < a - c β c < b :=
begin
refine β¨hb.lt_of_tsub_lt_tsub_left_of_le hβ, _β©,
intro h, refine (tsub_le_tsub_left h.le _).lt_of_ne _,
rintro h2, exact h.ne' (hab.tsub_inj_right hβ hβ h2)
end
@[simp] protected lemma add_tsub_tsub_cancel (hac : add_le_cancellable (a - c)) (h : c β€ a) :
(a + b) - (a - c) = b + c :=
(hac.tsub_eq_iff_eq_add_of_le $ tsub_le_self.trans le_self_add).mpr $
by rw [add_assoc, add_tsub_cancel_of_le h, add_comm]
protected lemma tsub_tsub_cancel_of_le (hba : add_le_cancellable (b - a)) (h : a β€ b) :
b - (b - a) = a :=
by rw [hba.tsub_eq_iff_eq_add_of_le tsub_le_self, add_tsub_cancel_of_le h]
end add_le_cancellable
section contra
/-! ### Lemmas where addition is order-reflecting. -/
variable [contravariant_class Ξ± Ξ± (+) (β€)]
lemma eq_tsub_iff_add_eq_of_le (h : c β€ b) : a = b - c β a + c = b :=
contravariant.add_le_cancellable.eq_tsub_iff_add_eq_of_le h
lemma tsub_eq_iff_eq_add_of_le (h : b β€ a) : a - b = c β a = c + b :=
contravariant.add_le_cancellable.tsub_eq_iff_eq_add_of_le h
/-- See `add_tsub_le_assoc` for an inequality. -/
lemma add_tsub_assoc_of_le (h : c β€ b) (a : Ξ±) : a + b - c = a + (b - c) :=
contravariant.add_le_cancellable.add_tsub_assoc_of_le h a
lemma tsub_add_eq_add_tsub (h : b β€ a) : a - b + c = a + c - b :=
contravariant.add_le_cancellable.tsub_add_eq_add_tsub h
lemma tsub_tsub_assoc (hβ : b β€ a) (hβ : c β€ b) : a - (b - c) = a - b + c :=
contravariant.add_le_cancellable.tsub_tsub_assoc hβ hβ
lemma le_tsub_iff_left (h : a β€ c) : b β€ c - a β a + b β€ c :=
contravariant.add_le_cancellable.le_tsub_iff_left h
lemma le_tsub_iff_right (h : a β€ c) : b β€ c - a β b + a β€ c :=
contravariant.add_le_cancellable.le_tsub_iff_right h
lemma tsub_lt_iff_left (hbc : b β€ a) : a - b < c β a < b + c :=
contravariant.add_le_cancellable.tsub_lt_iff_left hbc
lemma tsub_lt_iff_right (hbc : b β€ a) : a - b < c β a < c + b :=
contravariant.add_le_cancellable.tsub_lt_iff_right hbc
/-- This lemma (and some of its corollaries also holds for `ennreal`,
but this proof doesn't work for it.
Maybe we should add this lemma as field to `has_ordered_sub`? -/
lemma lt_tsub_of_add_lt_right (h : a + c < b) : a < b - c :=
contravariant.add_le_cancellable.lt_tsub_of_add_lt_right h
lemma lt_tsub_of_add_lt_left (h : a + c < b) : c < b - a :=
contravariant.add_le_cancellable.lt_tsub_of_add_lt_left h
lemma tsub_lt_iff_tsub_lt (hβ : b β€ a) (hβ : c β€ a) : a - b < c β a - c < b :=
contravariant.add_le_cancellable.tsub_lt_iff_tsub_lt contravariant.add_le_cancellable hβ hβ
lemma le_tsub_iff_le_tsub (hβ : a β€ b) (hβ : c β€ b) : a β€ b - c β c β€ b - a :=
contravariant.add_le_cancellable.le_tsub_iff_le_tsub contravariant.add_le_cancellable hβ hβ
/-- See `lt_tsub_iff_right` for a stronger statement in a linear order. -/
lemma lt_tsub_iff_right_of_le (h : c β€ b) : a < b - c β a + c < b :=
contravariant.add_le_cancellable.lt_tsub_iff_right_of_le h
/-- See `lt_tsub_iff_left` for a stronger statement in a linear order. -/
lemma lt_tsub_iff_left_of_le (h : c β€ b) : a < b - c β c + a < b :=
contravariant.add_le_cancellable.lt_tsub_iff_left_of_le h
/-- See `lt_of_tsub_lt_tsub_left` for a stronger statement in a linear order. -/
lemma lt_of_tsub_lt_tsub_left_of_le [contravariant_class Ξ± Ξ± (+) (<)]
(hca : c β€ a) (h : a - b < a - c) : c < b :=
contravariant.add_le_cancellable.lt_of_tsub_lt_tsub_left_of_le hca h
lemma tsub_le_tsub_iff_left (h : c β€ a) : a - b β€ a - c β c β€ b :=
contravariant.add_le_cancellable.tsub_le_tsub_iff_left contravariant.add_le_cancellable h
lemma tsub_right_inj (hba : b β€ a) (hca : c β€ a) : a - b = a - c β b = c :=
contravariant.add_le_cancellable.tsub_right_inj contravariant.add_le_cancellable
contravariant.add_le_cancellable hba hca
lemma tsub_lt_tsub_right_of_le (h : c β€ a) (h2 : a < b) : a - c < b - c :=
contravariant.add_le_cancellable.tsub_lt_tsub_right_of_le h h2
lemma tsub_inj_right (hβ : b β€ a) (hβ : c β€ a) (hβ : a - b = a - c) : b = c :=
contravariant.add_le_cancellable.tsub_inj_right hβ hβ hβ
/-- See `tsub_lt_tsub_iff_left_of_le` for a stronger statement in a linear order. -/
lemma tsub_lt_tsub_iff_left_of_le_of_le [contravariant_class Ξ± Ξ± (+) (<)]
(hβ : b β€ a) (hβ : c β€ a) : a - b < a - c β c < b :=
contravariant.add_le_cancellable.tsub_lt_tsub_iff_left_of_le_of_le
contravariant.add_le_cancellable hβ hβ
@[simp] lemma add_tsub_tsub_cancel (h : c β€ a) : (a + b) - (a - c) = b + c :=
contravariant.add_le_cancellable.add_tsub_tsub_cancel h
/-- See `tsub_tsub_le` for an inequality. -/
lemma tsub_tsub_cancel_of_le (h : a β€ b) : b - (b - a) = a :=
contravariant.add_le_cancellable.tsub_tsub_cancel_of_le h
end contra
end canonically_ordered_add_monoid
/-! ### Lemmas in a linearly canonically ordered monoid. -/
section canonically_linear_ordered_add_monoid
variables [canonically_linear_ordered_add_monoid Ξ±] [has_sub Ξ±] [has_ordered_sub Ξ±] {a b c d : Ξ±}
@[simp] lemma tsub_pos_iff_lt : 0 < a - b β b < a :=
by rw [tsub_pos_iff_not_le, not_le]
lemma tsub_eq_tsub_min (a b : Ξ±) : a - b = a - min a b :=
begin
cases le_total a b with h h,
{ rw [min_eq_left h, tsub_self, tsub_eq_zero_iff_le.mpr h] },
{ rw [min_eq_right h] },
end
namespace add_le_cancellable
protected lemma lt_tsub_iff_right (hc : add_le_cancellable c) : a < b - c β a + c < b :=
β¨lt_imp_lt_of_le_imp_le tsub_le_iff_right.mpr, hc.lt_tsub_of_add_lt_rightβ©
protected lemma lt_tsub_iff_left (hc : add_le_cancellable c) : a < b - c β c + a < b :=
β¨lt_imp_lt_of_le_imp_le tsub_le_iff_left.mpr, hc.lt_tsub_of_add_lt_leftβ©
protected lemma tsub_lt_tsub_iff_right (hc : add_le_cancellable c) (h : c β€ a) :
a - c < b - c β a < b :=
by rw [hc.lt_tsub_iff_left, add_tsub_cancel_of_le h]
protected lemma tsub_lt_self (ha : add_le_cancellable a) (hb : add_le_cancellable b)
(hβ : 0 < a) (hβ : 0 < b) : a - b < a :=
begin
refine tsub_le_self.lt_of_ne _,
intro h,
rw [β h, tsub_pos_iff_lt] at hβ,
have := h.ge,
rw [hb.le_tsub_iff_left hβ.le, ha.add_le_iff_nonpos_left] at this,
exact hβ.not_le this,
end
protected lemma tsub_lt_self_iff (ha : add_le_cancellable a) (hb : add_le_cancellable b) :
a - b < a β 0 < a β§ 0 < b :=
begin
refine β¨_, Ξ» h, ha.tsub_lt_self hb h.1 h.2β©,
intro h,
refine β¨(zero_le _).trans_lt h, (zero_le b).lt_of_ne _β©,
rintro rfl,
rw [tsub_zero] at h,
exact h.false
end
/-- See `lt_tsub_iff_left_of_le_of_le` for a weaker statement in a partial order. -/
protected lemma tsub_lt_tsub_iff_left_of_le (ha : add_le_cancellable a) (hb : add_le_cancellable b)
(h : b β€ a) : a - b < a - c β c < b :=
lt_iff_lt_of_le_iff_le $ ha.tsub_le_tsub_iff_left hb h
end add_le_cancellable
section contra
variable [contravariant_class Ξ± Ξ± (+) (β€)]
/-- This lemma also holds for `ennreal`, but we need a different proof for that. -/
lemma tsub_lt_tsub_iff_right (h : c β€ a) : a - c < b - c β a < b :=
contravariant.add_le_cancellable.tsub_lt_tsub_iff_right h
lemma tsub_lt_self (hβ : 0 < a) (hβ : 0 < b) : a - b < a :=
contravariant.add_le_cancellable.tsub_lt_self contravariant.add_le_cancellable hβ hβ
lemma tsub_lt_self_iff : a - b < a β 0 < a β§ 0 < b :=
contravariant.add_le_cancellable.tsub_lt_self_iff contravariant.add_le_cancellable
/-- See `lt_tsub_iff_left_of_le_of_le` for a weaker statement in a partial order. -/
lemma tsub_lt_tsub_iff_left_of_le (h : b β€ a) : a - b < a - c β c < b :=
contravariant.add_le_cancellable.tsub_lt_tsub_iff_left_of_le contravariant.add_le_cancellable h
end contra
/-! ### Lemmas about `max` and `min`. -/
lemma tsub_add_eq_max : a - b + b = max a b :=
begin
cases le_total a b with h h,
{ rw [max_eq_right h, tsub_eq_zero_iff_le.mpr h, zero_add] },
{ rw [max_eq_left h, tsub_add_cancel_of_le h] }
end
lemma add_tsub_eq_max : a + (b - a) = max a b :=
by rw [add_comm, max_comm, tsub_add_eq_max]
lemma tsub_min : a - min a b = a - b :=
begin
cases le_total a b with h h,
{ rw [min_eq_left h, tsub_self, tsub_eq_zero_iff_le.mpr h] },
{ rw [min_eq_right h] }
end
lemma tsub_add_min : a - b + min a b = a :=
by { rw [β tsub_min, tsub_add_cancel_of_le], apply min_le_left }
end canonically_linear_ordered_add_monoid
namespace with_top
section
variables [has_sub Ξ±] [has_zero Ξ±]
/-- If `Ξ±` has subtraction and `0`, we can extend the subtraction to `with_top Ξ±`. -/
protected def sub : Ξ (a b : with_top Ξ±), with_top Ξ±
| _ β€ := 0
| β€ (x : Ξ±) := β€
| (x : Ξ±) (y : Ξ±) := (x - y : Ξ±)
instance : has_sub (with_top Ξ±) :=
β¨with_top.subβ©
@[simp, norm_cast] lemma coe_sub {a b : Ξ±} : (β(a - b) : with_top Ξ±) = βa - βb := rfl
@[simp] lemma top_sub_coe {a : Ξ±} : (β€ : with_top Ξ±) - a = β€ := rfl
@[simp] lemma sub_top {a : with_top Ξ±} : a - β€ = 0 := by { cases a; refl }
end
variables [canonically_ordered_add_monoid Ξ±] [has_sub Ξ±] [has_ordered_sub Ξ±]
instance : has_ordered_sub (with_top Ξ±) :=
begin
constructor,
rintro x y z,
induction y using with_top.rec_top_coe, { simp },
induction x using with_top.rec_top_coe, { simp },
induction z using with_top.rec_top_coe, { simp },
norm_cast, exact tsub_le_iff_right
end
end with_top
|
50e854e708bf0b31f0bbf655af5292957758d997 | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/data/num/lemmas.lean | 6bd8c4b789d9b10ddccd18d621ee82a6fd8b735e | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 50,194 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Properties of the binary representation of integers.
-/
import data.num.bitwise
import data.int.basic
import data.nat.gcd
namespace pos_num
variables {Ξ± : Type*}
@[simp, norm_cast] theorem cast_one [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±] : ((1 : pos_num) : Ξ±) = 1 := rfl
@[simp] theorem cast_one' [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±] : (pos_num.one : Ξ±) = 1 := rfl
@[simp, norm_cast] theorem cast_bit0 [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±] (n : pos_num) : (n.bit0 : Ξ±) = _root_.bit0 n := rfl
@[simp, norm_cast] theorem cast_bit1 [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±] (n : pos_num) : (n.bit1 : Ξ±) = _root_.bit1 n := rfl
@[simp, norm_cast] theorem cast_to_nat [add_monoid Ξ±] [has_one Ξ±] : β n : pos_num, ((n : β) : Ξ±) = n
| 1 := nat.cast_one
| (bit0 p) := (nat.cast_bit0 _).trans $ congr_arg _root_.bit0 p.cast_to_nat
| (bit1 p) := (nat.cast_bit1 _).trans $ congr_arg _root_.bit1 p.cast_to_nat
@[simp, norm_cast] theorem to_nat_to_int (n : pos_num) : ((n : β) : β€) = n :=
by rw [β int.nat_cast_eq_coe_nat, cast_to_nat]
@[simp, norm_cast] theorem cast_to_int [add_group Ξ±] [has_one Ξ±] (n : pos_num) : ((n : β€) : Ξ±) = n :=
by rw [β to_nat_to_int, int.cast_coe_nat, cast_to_nat]
theorem succ_to_nat : β n, (succ n : β) = n + 1
| 1 := rfl
| (bit0 p) := rfl
| (bit1 p) := (congr_arg _root_.bit0 (succ_to_nat p)).trans $
show βp + 1 + βp + 1 = βp + βp + 1 + 1, by simp [add_left_comm]
theorem one_add (n : pos_num) : 1 + n = succ n := by cases n; refl
theorem add_one (n : pos_num) : n + 1 = succ n := by cases n; refl
@[norm_cast]
theorem add_to_nat : β m n, ((m + n : pos_num) : β) = m + n
| 1 b := by rw [one_add b, succ_to_nat, add_comm]; refl
| a 1 := by rw [add_one a, succ_to_nat]; refl
| (bit0 a) (bit0 b) := (congr_arg _root_.bit0 (add_to_nat a b)).trans $
show ((a + b) + (a + b) : β) = (a + a) + (b + b), by simp [add_left_comm]
| (bit0 a) (bit1 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $
show ((a + b) + (a + b) + 1 : β) = (a + a) + (b + b + 1), by simp [add_left_comm]
| (bit1 a) (bit0 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $
show ((a + b) + (a + b) + 1 : β) = (a + a + 1) + (b + b), by simp [add_comm, add_left_comm]
| (bit1 a) (bit1 b) :=
show (succ (a + b) + succ (a + b) : β) = (a + a + 1) + (b + b + 1),
by rw [succ_to_nat, add_to_nat]; simp [add_left_comm]
theorem add_succ : β (m n : pos_num), m + succ n = succ (m + n)
| 1 b := by simp [one_add]
| (bit0 a) 1 := congr_arg bit0 (add_one a)
| (bit1 a) 1 := congr_arg bit1 (add_one a)
| (bit0 a) (bit0 b) := rfl
| (bit0 a) (bit1 b) := congr_arg bit0 (add_succ a b)
| (bit1 a) (bit0 b) := rfl
| (bit1 a) (bit1 b) := congr_arg bit1 (add_succ a b)
theorem bit0_of_bit0 : Ξ n, _root_.bit0 n = bit0 n
| 1 := rfl
| (bit0 p) := congr_arg bit0 (bit0_of_bit0 p)
| (bit1 p) := show bit0 (succ (_root_.bit0 p)) = _, by rw bit0_of_bit0; refl
theorem bit1_of_bit1 (n : pos_num) : _root_.bit1 n = bit1 n :=
show _root_.bit0 n + 1 = bit1 n, by rw [add_one, bit0_of_bit0]; refl
@[norm_cast]
theorem mul_to_nat (m) : β n, ((m * n : pos_num) : β) = m * n
| 1 := (mul_one _).symm
| (bit0 p) := show (β(m * p) + β(m * p) : β) = βm * (p + p), by rw [mul_to_nat, left_distrib]
| (bit1 p) := (add_to_nat (bit0 (m * p)) m).trans $
show (β(m * p) + β(m * p) + βm : β) = βm * (p + p) + m, by rw [mul_to_nat, left_distrib]
theorem to_nat_pos : β n : pos_num, 0 < (n : β)
| 1 := zero_lt_one
| (bit0 p) := let h := to_nat_pos p in add_pos h h
| (bit1 p) := nat.succ_pos _
theorem cmp_to_nat_lemma {m n : pos_num} : (m:β) < n β (bit1 m : β) < bit0 n :=
show (m:β) < n β (m + m + 1 + 1 : β) β€ n + n,
by intro h; rw [nat.add_right_comm m m 1, add_assoc]; exact add_le_add h h
theorem cmp_swap (m) : βn, (cmp m n).swap = cmp n m :=
by induction m with m IH m IH; intro n;
cases n with n n; try {unfold cmp}; try {refl}; rw βIH; cases cmp m n; refl
theorem cmp_to_nat : β (m n), (ordering.cases_on (cmp m n) ((m:β) < n) (m = n) ((m:β) > n) : Prop)
| 1 1 := rfl
| (bit0 a) 1 := let h : (1:β) β€ a := to_nat_pos a in add_le_add h h
| (bit1 a) 1 := nat.succ_lt_succ $ to_nat_pos $ bit0 a
| 1 (bit0 b) := let h : (1:β) β€ b := to_nat_pos b in add_le_add h h
| 1 (bit1 b) := nat.succ_lt_succ $ to_nat_pos $ bit0 b
| (bit0 a) (bit0 b) := begin
have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro,
{ exact add_lt_add this this },
{ rw this },
{ exact add_lt_add this this }
end
| (bit0 a) (bit1 b) := begin dsimp [cmp],
have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro,
{ exact nat.le_succ_of_le (add_lt_add this this) },
{ rw this, apply nat.lt_succ_self },
{ exact cmp_to_nat_lemma this }
end
| (bit1 a) (bit0 b) := begin dsimp [cmp],
have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro,
{ exact cmp_to_nat_lemma this },
{ rw this, apply nat.lt_succ_self },
{ exact nat.le_succ_of_le (add_lt_add this this) },
end
| (bit1 a) (bit1 b) := begin
have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro,
{ exact nat.succ_lt_succ (add_lt_add this this) },
{ rw this },
{ exact nat.succ_lt_succ (add_lt_add this this) }
end
@[norm_cast]
theorem lt_to_nat {m n : pos_num} : (m:β) < n β m < n :=
show (m:β) < n β cmp m n = ordering.lt, from
match cmp m n, cmp_to_nat m n with
| ordering.lt, h := by simp at h; simp [h]
| ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial
| ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial
end
@[norm_cast]
theorem le_to_nat {m n : pos_num} : (m:β) β€ n β m β€ n :=
by rw β not_lt; exact not_congr lt_to_nat
end pos_num
namespace num
variables {Ξ± : Type*}
open pos_num
theorem add_zero (n : num) : n + 0 = n := by cases n; refl
theorem zero_add (n : num) : 0 + n = n := by cases n; refl
theorem add_one : β n : num, n + 1 = succ n
| 0 := rfl
| (pos p) := by cases p; refl
theorem add_succ : β (m n : num), m + succ n = succ (m + n)
| 0 n := by simp [zero_add]
| (pos p) 0 := show pos (p + 1) = succ (pos p + 0),
by rw [pos_num.add_one, add_zero]; refl
| (pos p) (pos q) := congr_arg pos (pos_num.add_succ _ _)
@[simp, norm_cast] theorem add_of_nat (m) : β n, ((m + n : β) : num) = m + n
| 0 := (add_zero _).symm
| (n+1) := show ((m + n : β) + 1 : num) = m + (β n + 1),
by rw [add_one, add_one, add_succ, add_of_nat]
theorem bit0_of_bit0 : β n : num, bit0 n = n.bit0
| 0 := rfl
| (pos p) := congr_arg pos p.bit0_of_bit0
theorem bit1_of_bit1 : β n : num, bit1 n = n.bit1
| 0 := rfl
| (pos p) := congr_arg pos p.bit1_of_bit1
@[simp, norm_cast] theorem cast_zero [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±] :
((0 : num) : Ξ±) = 0 := rfl
@[simp] theorem cast_zero' [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±] :
(num.zero : Ξ±) = 0 := rfl
@[simp, norm_cast] theorem cast_one [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±] :
((1 : num) : Ξ±) = 1 := rfl
@[simp] theorem cast_pos [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±]
(n : pos_num) : (num.pos n : Ξ±) = n := rfl
theorem succ'_to_nat : β n, (succ' n : β) = n + 1
| 0 := (_root_.zero_add _).symm
| (pos p) := pos_num.succ_to_nat _
theorem succ_to_nat (n) : (succ n : β) = n + 1 := succ'_to_nat n
@[simp, norm_cast] theorem cast_to_nat [add_monoid Ξ±] [has_one Ξ±] : β n : num, ((n : β) : Ξ±) = n
| 0 := nat.cast_zero
| (pos p) := p.cast_to_nat
@[simp, norm_cast] theorem to_nat_to_int (n : num) : ((n : β) : β€) = n :=
by rw [β int.nat_cast_eq_coe_nat, cast_to_nat]
@[simp, norm_cast] theorem cast_to_int [add_group Ξ±] [has_one Ξ±] (n : num) : ((n : β€) : Ξ±) = n :=
by rw [β to_nat_to_int, int.cast_coe_nat, cast_to_nat]
@[norm_cast]
theorem to_of_nat : Ξ (n : β), ((n : num) : β) = n
| 0 := rfl
| (n+1) := by rw [nat.cast_add_one, add_one, succ_to_nat, to_of_nat]
@[simp, norm_cast]
theorem of_nat_cast [add_monoid Ξ±] [has_one Ξ±] (n : β) : ((n : num) : Ξ±) = n :=
by rw [β cast_to_nat, to_of_nat]
@[norm_cast] theorem of_nat_inj {m n : β} : (m : num) = n β m = n :=
β¨Ξ» h, function.injective_of_left_inverse to_of_nat h, congr_arg _β©
@[norm_cast]
theorem add_to_nat : β m n, ((m + n : num) : β) = m + n
| 0 0 := rfl
| 0 (pos q) := (_root_.zero_add _).symm
| (pos p) 0 := rfl
| (pos p) (pos q) := pos_num.add_to_nat _ _
@[norm_cast]
theorem mul_to_nat : β m n, ((m * n : num) : β) = m * n
| 0 0 := rfl
| 0 (pos q) := (zero_mul _).symm
| (pos p) 0 := rfl
| (pos p) (pos q) := pos_num.mul_to_nat _ _
theorem cmp_to_nat : β (m n), (ordering.cases_on (cmp m n) ((m:β) < n) (m = n) ((m:β) > n) : Prop)
| 0 0 := rfl
| 0 (pos b) := to_nat_pos _
| (pos a) 0 := to_nat_pos _
| (pos a) (pos b) :=
by { have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp];
cases pos_num.cmp a b, exacts [id, congr_arg pos, id] }
@[norm_cast]
theorem lt_to_nat {m n : num} : (m:β) < n β m < n :=
show (m:β) < n β cmp m n = ordering.lt, from
match cmp m n, cmp_to_nat m n with
| ordering.lt, h := by simp at h; simp [h]
| ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial
| ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial
end
@[norm_cast]
theorem le_to_nat {m n : num} : (m:β) β€ n β m β€ n :=
by rw β not_lt; exact not_congr lt_to_nat
end num
namespace pos_num
@[simp] theorem of_to_nat : Ξ (n : pos_num), ((n : β) : num) = num.pos n
| 1 := rfl
| (bit0 p) :=
show β(p + p : β) = num.pos p.bit0,
by rw [num.add_of_nat, of_to_nat];
exact congr_arg num.pos p.bit0_of_bit0
| (bit1 p) :=
show ((p + p : β) : num) + 1 = num.pos p.bit1,
by rw [num.add_of_nat, of_to_nat];
exact congr_arg num.pos p.bit1_of_bit1
end pos_num
namespace num
@[simp, norm_cast] theorem of_to_nat : Ξ (n : num), ((n : β) : num) = n
| 0 := rfl
| (pos p) := p.of_to_nat
@[norm_cast] theorem to_nat_inj {m n : num} : (m : β) = n β m = n :=
β¨Ξ» h, function.injective_of_left_inverse of_to_nat h, congr_arg _β©
meta def transfer_rw : tactic unit :=
`[repeat {rw β to_nat_inj <|> rw β lt_to_nat <|> rw β le_to_nat},
repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}]
meta def transfer : tactic unit := `[intros, transfer_rw, try {simp}]
instance : comm_semiring num :=
by refine {
add := (+),
zero := 0,
zero_add := zero_add,
add_zero := add_zero,
mul := (*),
one := 1, .. }; try {transfer}; simp [mul_add, mul_left_comm, mul_comm, add_comm]
instance : ordered_cancel_add_comm_monoid num :=
{ add_left_cancel := by {intros a b c, transfer_rw, apply add_left_cancel},
add_right_cancel := by {intros a b c, transfer_rw, apply add_right_cancel},
lt := (<),
lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le},
le := (β€),
le_refl := by transfer,
le_trans := by {intros a b c, transfer_rw, apply le_trans},
le_antisymm := by {intros a b, transfer_rw, apply le_antisymm},
add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact Ξ» h, add_le_add_left h c},
le_of_add_le_add_left := by {intros a b c, transfer_rw, apply le_of_add_le_add_left},
..num.comm_semiring }
instance : decidable_linear_ordered_semiring num :=
{ le_total := by {intros a b, transfer_rw, apply le_total},
zero_lt_one := dec_trivial,
mul_lt_mul_of_pos_left := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_left},
mul_lt_mul_of_pos_right := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_right},
decidable_lt := num.decidable_lt,
decidable_le := num.decidable_le,
decidable_eq := num.decidable_eq,
..num.comm_semiring, ..num.ordered_cancel_add_comm_monoid }
@[norm_cast]
theorem dvd_to_nat (m n : num) : (m : β) β£ n β m β£ n :=
β¨Ξ» β¨k, eβ©, β¨k, by rw [β of_to_nat n, e]; simpβ©,
Ξ» β¨k, eβ©, β¨k, by simp [e, mul_to_nat]β©β©
end num
namespace pos_num
variables {Ξ± : Type*}
open num
@[norm_cast] theorem to_nat_inj {m n : pos_num} : (m : β) = n β m = n :=
β¨Ξ» h, num.pos.inj $ by rw [β pos_num.of_to_nat, β pos_num.of_to_nat, h],
congr_arg _β©
theorem pred'_to_nat : β n, (pred' n : β) = nat.pred n
| 1 := rfl
| (bit0 n) :=
have nat.succ β(pred' n) = βn,
by rw [pred'_to_nat n, nat.succ_pred_eq_of_pos (to_nat_pos n)],
match pred' n, this : β k : num, nat.succ βk = βn β
β(num.cases_on k 1 bit1 : pos_num) = nat.pred (_root_.bit0 n) with
| 0, (h : ((1:num):β) = n) := by rw β to_nat_inj.1 h; refl
| num.pos p, (h : nat.succ βp = n) :=
by rw β h; exact (nat.succ_add p p).symm
end
| (bit1 n) := rfl
@[simp] theorem pred'_succ' (n) : pred' (succ' n) = n :=
num.to_nat_inj.1 $ by rw [pred'_to_nat, succ'_to_nat,
nat.add_one, nat.pred_succ]
@[simp] theorem succ'_pred' (n) : succ' (pred' n) = n :=
to_nat_inj.1 $ by rw [succ'_to_nat, pred'_to_nat,
nat.add_one, nat.succ_pred_eq_of_pos (to_nat_pos _)]
theorem size_to_nat : β n, (size n : β) = nat.size n
| 1 := nat.size_one.symm
| (bit0 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit0,
nat.size_bit0 $ ne_of_gt $ to_nat_pos n]
| (bit1 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit1,
nat.size_bit1]
theorem size_eq_nat_size : β n, (size n : β) = nat_size n
| 1 := rfl
| (bit0 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size]
| (bit1 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size]
theorem nat_size_to_nat (n) : nat_size n = nat.size n :=
by rw [β size_eq_nat_size, size_to_nat]
theorem nat_size_pos (n) : 0 < nat_size n :=
by cases n; apply nat.succ_pos
meta def transfer_rw : tactic unit :=
`[repeat {rw β to_nat_inj <|> rw β lt_to_nat <|> rw β le_to_nat},
repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}]
meta def transfer : tactic unit :=
`[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}]
instance : add_comm_semigroup pos_num :=
by refine {add := (+), ..}; transfer
instance : comm_monoid pos_num :=
by refine {mul := (*), one := 1, ..}; transfer
instance : distrib pos_num :=
by refine {add := (+), mul := (*), ..}; {transfer, simp [mul_add, mul_comm]}
instance : decidable_linear_order pos_num :=
{ lt := (<),
lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le},
le := (β€),
le_refl := by transfer,
le_trans := by {intros a b c, transfer_rw, apply le_trans},
le_antisymm := by {intros a b, transfer_rw, apply le_antisymm},
le_total := by {intros a b, transfer_rw, apply le_total},
decidable_lt := by apply_instance,
decidable_le := by apply_instance,
decidable_eq := by apply_instance }
@[simp] theorem cast_to_num (n : pos_num) : βn = num.pos n :=
by rw [β cast_to_nat, β of_to_nat n]
@[simp, norm_cast]
theorem bit_to_nat (b n) : (bit b n : β) = nat.bit b n :=
by cases b; refl
@[simp, norm_cast]
theorem cast_add [add_monoid Ξ±] [has_one Ξ±] (m n) : ((m + n : pos_num) : Ξ±) = m + n :=
by rw [β cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat]
@[simp, norm_cast, priority 500]
theorem cast_succ [add_monoid Ξ±] [has_one Ξ±] (n : pos_num) : (succ n : Ξ±) = n + 1 :=
by rw [β add_one, cast_add, cast_one]
@[simp, norm_cast]
theorem cast_inj [add_monoid Ξ±] [has_one Ξ±] [char_zero Ξ±] {m n : pos_num} : (m:Ξ±) = n β m = n :=
by rw [β cast_to_nat m, β cast_to_nat n, nat.cast_inj, to_nat_inj]
@[simp]
theorem one_le_cast [linear_ordered_semiring Ξ±] (n : pos_num) : (1 : Ξ±) β€ n :=
by rw [β cast_to_nat, β nat.cast_one, nat.cast_le]; apply to_nat_pos
@[simp]
theorem cast_pos [linear_ordered_semiring Ξ±] (n : pos_num) : 0 < (n : Ξ±) :=
lt_of_lt_of_le zero_lt_one (one_le_cast n)
@[simp, norm_cast]
theorem cast_mul [semiring Ξ±] (m n) : ((m * n : pos_num) : Ξ±) = m * n :=
by rw [β cast_to_nat, mul_to_nat, nat.cast_mul, cast_to_nat, cast_to_nat]
@[simp]
theorem cmp_eq (m n) : cmp m n = ordering.eq β m = n :=
begin
have := cmp_to_nat m n,
cases cmp m n; simp at this β’; try {exact this};
{ simp [show m β n, from Ξ» e, by rw e at this; exact lt_irrefl _ this] }
end
@[simp, norm_cast]
theorem cast_lt [linear_ordered_semiring Ξ±] {m n : pos_num} : (m:Ξ±) < n β m < n :=
by rw [β cast_to_nat m, β cast_to_nat n, nat.cast_lt, lt_to_nat]
@[simp, norm_cast]
theorem cast_le [linear_ordered_semiring Ξ±] {m n : pos_num} : (m:Ξ±) β€ n β m β€ n :=
by rw β not_lt; exact not_congr cast_lt
end pos_num
namespace num
variables {Ξ± : Type*}
open pos_num
theorem bit_to_nat (b n) : (bit b n : β) = nat.bit b n :=
by cases b; cases n; refl
theorem cast_succ' [add_monoid Ξ±] [has_one Ξ±] (n) : (succ' n : Ξ±) = n + 1 :=
by rw [β pos_num.cast_to_nat, succ'_to_nat, nat.cast_add_one, cast_to_nat]
theorem cast_succ [add_monoid Ξ±] [has_one Ξ±] (n) : (succ n : Ξ±) = n + 1 := cast_succ' n
@[simp, norm_cast] theorem cast_add [semiring Ξ±] (m n) : ((m + n : num) : Ξ±) = m + n :=
by rw [β cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat]
@[simp, norm_cast] theorem cast_bit0 [semiring Ξ±] (n : num) : (n.bit0 : Ξ±) = _root_.bit0 n :=
by rw [β bit0_of_bit0, _root_.bit0, cast_add]; refl
@[simp, norm_cast] theorem cast_bit1 [semiring Ξ±] (n : num) : (n.bit1 : Ξ±) = _root_.bit1 n :=
by rw [β bit1_of_bit1, _root_.bit1, bit0_of_bit0, cast_add, cast_bit0]; refl
@[simp, norm_cast] theorem cast_mul [semiring Ξ±] : β m n, ((m * n : num) : Ξ±) = m * n
| 0 0 := (zero_mul _).symm
| 0 (pos q) := (zero_mul _).symm
| (pos p) 0 := (mul_zero _).symm
| (pos p) (pos q) := pos_num.cast_mul _ _
theorem size_to_nat : β n, (size n : β) = nat.size n
| 0 := nat.size_zero.symm
| (pos p) := p.size_to_nat
theorem size_eq_nat_size : β n, (size n : β) = nat_size n
| 0 := rfl
| (pos p) := p.size_eq_nat_size
theorem nat_size_to_nat (n) : nat_size n = nat.size n :=
by rw [β size_eq_nat_size, size_to_nat]
@[simp] theorem of_nat'_eq : β n, num.of_nat' n = n :=
nat.binary_rec rfl $ Ξ» b n IH, begin
rw of_nat' at IH β’,
rw [nat.binary_rec_eq, IH],
{ cases b; simp [nat.bit, bit0_of_bit0, bit1_of_bit1] },
{ refl }
end
theorem zneg_to_znum (n : num) : -n.to_znum = n.to_znum_neg := by cases n; refl
theorem zneg_to_znum_neg (n : num) : -n.to_znum_neg = n.to_znum := by cases n; refl
theorem to_znum_inj {m n : num} : m.to_znum = n.to_znum β m = n :=
β¨Ξ» h, by cases m; cases n; cases h; refl, congr_arg _β©
@[simp, norm_cast squash] theorem cast_to_znum [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±] [has_neg Ξ±] :
β n : num, (n.to_znum : Ξ±) = n
| 0 := rfl
| (num.pos p) := rfl
@[simp] theorem cast_to_znum_neg [add_group Ξ±] [has_one Ξ±] :
β n : num, (n.to_znum_neg : Ξ±) = -n
| 0 := neg_zero.symm
| (num.pos p) := rfl
@[simp] theorem add_to_znum (m n : num) : num.to_znum (m + n) = m.to_znum + n.to_znum :=
by cases m; cases n; refl
end num
namespace pos_num
open num
theorem pred_to_nat {n : pos_num} (h : n > 1) : (pred n : β) = nat.pred n :=
begin
unfold pred,
have := pred'_to_nat n,
cases e : pred' n,
{ have : (1:β) β€ nat.pred n :=
nat.pred_le_pred ((@cast_lt β _ _ _).2 h),
rw [β pred'_to_nat, e] at this,
exact absurd this dec_trivial },
{ rw [β pred'_to_nat, e], refl }
end
theorem sub'_one (a : pos_num) : sub' a 1 = (pred' a).to_znum :=
by cases a; refl
theorem one_sub' (a : pos_num) : sub' 1 a = (pred' a).to_znum_neg :=
by cases a; refl
theorem lt_iff_cmp {m n} : m < n β cmp m n = ordering.lt := iff.rfl
theorem le_iff_cmp {m n} : m β€ n β cmp m n β ordering.gt :=
not_congr $ lt_iff_cmp.trans $
by rw β cmp_swap; cases cmp m n; exact dec_trivial
end pos_num
namespace num
variables {Ξ± : Type*}
open pos_num
theorem pred_to_nat : β (n : num), (pred n : β) = nat.pred n
| 0 := rfl
| (pos p) := by rw [pred, pos_num.pred'_to_nat]; refl
theorem ppred_to_nat : β (n : num), coe <$> ppred n = nat.ppred n
| 0 := rfl
| (pos p) := by rw [ppred, option.map_some, nat.ppred_eq_some.2];
rw [pos_num.pred'_to_nat, nat.succ_pred_eq_of_pos (pos_num.to_nat_pos _)]; refl
theorem cmp_swap (m n) : (cmp m n).swap = cmp n m :=
by cases m; cases n; try {unfold cmp}; try {refl}; apply pos_num.cmp_swap
theorem cmp_eq (m n) : cmp m n = ordering.eq β m = n :=
begin
have := cmp_to_nat m n,
cases cmp m n; simp at this β’; try {exact this};
{ simp [show m β n, from Ξ» e, by rw e at this; exact lt_irrefl _ this] }
end
@[simp, norm_cast]
theorem cast_lt [linear_ordered_semiring Ξ±] {m n : num} : (m:Ξ±) < n β m < n :=
by rw [β cast_to_nat m, β cast_to_nat n, nat.cast_lt, lt_to_nat]
@[simp, norm_cast]
theorem cast_le [linear_ordered_semiring Ξ±] {m n : num} : (m:Ξ±) β€ n β m β€ n :=
by rw β not_lt; exact not_congr cast_lt
@[simp, norm_cast]
theorem cast_inj [linear_ordered_semiring Ξ±] {m n : num} : (m:Ξ±) = n β m = n :=
by rw [β cast_to_nat m, β cast_to_nat n, nat.cast_inj, to_nat_inj]
theorem lt_iff_cmp {m n} : m < n β cmp m n = ordering.lt := iff.rfl
theorem le_iff_cmp {m n} : m β€ n β cmp m n β ordering.gt :=
not_congr $ lt_iff_cmp.trans $
by rw β cmp_swap; cases cmp m n; exact dec_trivial
theorem bitwise_to_nat {f : num β num β num} {g : bool β bool β bool}
(p : pos_num β pos_num β num)
(gff : g ff ff = ff)
(f00 : f 0 0 = 0)
(f0n : β n, f 0 (pos n) = cond (g ff tt) (pos n) 0)
(fn0 : β n, f (pos n) 0 = cond (g tt ff) (pos n) 0)
(fnn : β m n, f (pos m) (pos n) = p m n)
(p11 : p 1 1 = cond (g tt tt) 1 0)
(p1b : β b n, p 1 (pos_num.bit b n) = bit (g tt b) (cond (g ff tt) (pos n) 0))
(pb1 : β a m, p (pos_num.bit a m) 1 = bit (g a tt) (cond (g tt ff) (pos m) 0))
(pbb : β a b m n, p (pos_num.bit a m) (pos_num.bit b n) = bit (g a b) (p m n))
: β m n : num, (f m n : β) = nat.bitwise g m n :=
begin
intros, cases m with m; cases n with n;
try { change zero with 0 };
try { change ((0:num):β) with 0 },
{ rw [f00, nat.bitwise_zero]; refl },
{ unfold nat.bitwise, rw [f0n, nat.binary_rec_zero],
cases g ff tt; refl },
{ unfold nat.bitwise,
generalize h : (pos m : β) = m', revert h,
apply nat.bit_cases_on m' _, intros b m' h,
rw [fn0, nat.binary_rec_eq, nat.binary_rec_zero, βh],
cases g tt ff; refl,
apply nat.bitwise_bit_aux gff },
{ rw fnn,
have : βb (n : pos_num), (cond b βn 0 : β) = β(cond b (pos n) 0 : num) :=
by intros; cases b; refl,
induction m with m IH m IH generalizing n; cases n with n n,
any_goals { change one with 1 },
any_goals { change pos 1 with 1 },
any_goals { change pos_num.bit0 with pos_num.bit ff },
any_goals { change pos_num.bit1 with pos_num.bit tt },
any_goals { change ((1:num):β) with nat.bit tt 0 },
all_goals {
repeat {
rw show β b n, (pos (pos_num.bit b n) : β) = nat.bit b βn,
by intros; cases b; refl },
rw nat.bitwise_bit },
any_goals { assumption },
any_goals { rw [nat.bitwise_zero, p11], cases g tt tt; refl },
any_goals { rw [nat.bitwise_zero_left, this, β bit_to_nat, p1b] },
any_goals { rw [nat.bitwise_zero_right _ gff, this, β bit_to_nat, pb1] },
all_goals { rw [β show β n, β(p m n) = nat.bitwise g βm βn, from IH],
rw [β bit_to_nat, pbb] } }
end
@[simp, norm_cast] theorem lor_to_nat : β m n, (lor m n : β) = nat.lor m n :=
by apply bitwise_to_nat (Ξ»x y, pos (pos_num.lor x y)); intros; try {cases a}; try {cases b}; refl
@[simp, norm_cast] theorem land_to_nat : β m n, (land m n : β) = nat.land m n :=
by apply bitwise_to_nat pos_num.land; intros; try {cases a}; try {cases b}; refl
@[simp, norm_cast] theorem ldiff_to_nat : β m n, (ldiff m n : β) = nat.ldiff m n :=
by apply bitwise_to_nat pos_num.ldiff; intros; try {cases a}; try {cases b}; refl
@[simp, norm_cast] theorem lxor_to_nat : β m n, (lxor m n : β) = nat.lxor m n :=
by apply bitwise_to_nat pos_num.lxor; intros; try {cases a}; try {cases b}; refl
@[simp, norm_cast] theorem shiftl_to_nat (m n) : (shiftl m n : β) = nat.shiftl m n :=
begin
cases m; dunfold shiftl, {symmetry, apply nat.zero_shiftl},
simp, induction n with n IH, {refl},
simp [pos_num.shiftl, nat.shiftl_succ], rw βIH
end
@[simp, norm_cast] theorem shiftr_to_nat (m n) : (shiftr m n : β) = nat.shiftr m n :=
begin
cases m with m; dunfold shiftr, {symmetry, apply nat.zero_shiftr},
induction n with n IH generalizing m, {cases m; refl},
cases m with m m; dunfold pos_num.shiftr,
{ rw [nat.shiftr_eq_div_pow], symmetry, apply nat.div_eq_of_lt,
exact @nat.pow_lt_pow_of_lt_right 2 dec_trivial 0 (n+1) (nat.succ_pos _) },
{ transitivity, apply IH,
change nat.shiftr m n = nat.shiftr (bit1 m) (n+1),
rw [add_comm n 1, nat.shiftr_add],
apply congr_arg (Ξ»x, nat.shiftr x n), unfold nat.shiftr,
change (bit1 βm : β) with nat.bit tt m,
rw nat.div2_bit },
{ transitivity, apply IH,
change nat.shiftr m n = nat.shiftr (bit0 m) (n + 1),
rw [add_comm n 1, nat.shiftr_add],
apply congr_arg (Ξ»x, nat.shiftr x n), unfold nat.shiftr,
change (bit0 βm : β) with nat.bit ff m,
rw nat.div2_bit }
end
@[simp] theorem test_bit_to_nat (m n) : test_bit m n = nat.test_bit m n :=
begin
cases m with m; unfold test_bit nat.test_bit,
{ change (zero : nat) with 0, rw nat.zero_shiftr, refl },
induction n with n IH generalizing m;
cases m; dunfold pos_num.test_bit, {refl},
{ exact (nat.bodd_bit _ _).symm },
{ exact (nat.bodd_bit _ _).symm },
{ change ff = nat.bodd (nat.shiftr 1 (n + 1)),
rw [add_comm, nat.shiftr_add], change nat.shiftr 1 1 with 0,
rw nat.zero_shiftr; refl },
{ change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit tt m) (n + 1)),
rw [add_comm, nat.shiftr_add], unfold nat.shiftr,
rw nat.div2_bit, apply IH },
{ change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit ff m) (n + 1)),
rw [add_comm, nat.shiftr_add], unfold nat.shiftr,
rw nat.div2_bit, apply IH },
end
end num
namespace znum
variables {Ξ± : Type*}
open pos_num
@[simp, norm_cast] theorem cast_zero [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±] [has_neg Ξ±] :
((0 : znum) : Ξ±) = 0 := rfl
@[simp] theorem cast_zero' [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±] [has_neg Ξ±] :
(znum.zero : Ξ±) = 0 := rfl
@[simp, norm_cast] theorem cast_one [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±] [has_neg Ξ±] :
((1 : znum) : Ξ±) = 1 := rfl
@[simp] theorem cast_pos [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±] [has_neg Ξ±]
(n : pos_num) : (pos n : Ξ±) = n := rfl
@[simp] theorem cast_neg [has_zero Ξ±] [has_one Ξ±] [has_add Ξ±] [has_neg Ξ±]
(n : pos_num) : (neg n : Ξ±) = -n := rfl
@[simp, norm_cast] theorem cast_zneg [add_group Ξ±] [has_one Ξ±] : β n, ((-n : znum) : Ξ±) = -n
| 0 := neg_zero.symm
| (pos p) := rfl
| (neg p) := (neg_neg _).symm
theorem neg_zero : (-0 : znum) = 0 := rfl
theorem zneg_pos (n : pos_num) : -pos n = neg n := rfl
theorem zneg_neg (n : pos_num) : -neg n = pos n := rfl
theorem zneg_zneg (n : znum) : - -n = n := by cases n; refl
theorem zneg_bit1 (n : znum) : -n.bit1 = (-n).bitm1 := by cases n; refl
theorem zneg_bitm1 (n : znum) : -n.bitm1 = (-n).bit1 := by cases n; refl
theorem zneg_succ (n : znum) : -n.succ = (-n).pred :=
by cases n; try {refl}; rw [succ, num.zneg_to_znum_neg]; refl
theorem zneg_pred (n : znum) : -n.pred = (-n).succ :=
by rw [β zneg_zneg (succ (-n)), zneg_succ, zneg_zneg]
@[simp, norm_cast] theorem neg_of_int : β n, ((-n : β€) : znum) = -n
| (n+1:β) := rfl
| 0 := rfl
| -[1+n] := (zneg_zneg _).symm
@[simp] theorem abs_to_nat : β n, (abs n : β) = int.nat_abs n
| 0 := rfl
| (pos p) := congr_arg int.nat_abs p.to_nat_to_int
| (neg p) := show int.nat_abs ((p:β):β€) = int.nat_abs (- p),
by rw [p.to_nat_to_int, int.nat_abs_neg]
@[simp] theorem abs_to_znum : β n : num, abs n.to_znum = n
| 0 := rfl
| (num.pos p) := rfl
@[simp, norm_cast] theorem cast_to_int [add_group Ξ±] [has_one Ξ±] : β n : znum, ((n : β€) : Ξ±) = n
| 0 := rfl
| (pos p) := by rw [cast_pos, cast_pos, pos_num.cast_to_int]
| (neg p) := by rw [cast_neg, cast_neg, int.cast_neg, pos_num.cast_to_int]
theorem bit0_of_bit0 : β n : znum, _root_.bit0 n = n.bit0
| 0 := rfl
| (pos a) := congr_arg pos a.bit0_of_bit0
| (neg a) := congr_arg neg a.bit0_of_bit0
theorem bit1_of_bit1 : β n : znum, _root_.bit1 n = n.bit1
| 0 := rfl
| (pos a) := congr_arg pos a.bit1_of_bit1
| (neg a) := show pos_num.sub' 1 (_root_.bit0 a) = _,
by rw [pos_num.one_sub', a.bit0_of_bit0]; refl
@[simp, norm_cast] theorem cast_bit0 [add_group Ξ±] [has_one Ξ±] :
β n : znum, (n.bit0 : Ξ±) = bit0 n
| 0 := (add_zero _).symm
| (pos p) := by rw [znum.bit0, cast_pos, cast_pos]; refl
| (neg p) := by rw [znum.bit0, cast_neg, cast_neg, pos_num.cast_bit0,
_root_.bit0, _root_.bit0, neg_add_rev]
@[simp, norm_cast] theorem cast_bit1 [add_group Ξ±] [has_one Ξ±] :
β n : znum, (n.bit1 : Ξ±) = bit1 n
| 0 := by simp [znum.bit1, _root_.bit1, _root_.bit0]
| (pos p) := by rw [znum.bit1, cast_pos, cast_pos]; refl
| (neg p) := begin
rw [znum.bit1, cast_neg, cast_neg],
cases e : pred' p;
have : p = _ := (succ'_pred' p).symm.trans
(congr_arg num.succ' e),
{ change p=1 at this, subst p,
simp [_root_.bit1, _root_.bit0] },
{ rw [num.succ'] at this, subst p,
have : (β(-βa:β€) : Ξ±) = -1 + β(-βa + 1 : β€), {simp [add_comm]},
simpa [_root_.bit1, _root_.bit0, -add_comm] },
end
@[simp] theorem cast_bitm1 [add_group Ξ±] [has_one Ξ±]
(n : znum) : (n.bitm1 : Ξ±) = bit0 n - 1 :=
begin
conv { to_lhs, rw β zneg_zneg n },
rw [β zneg_bit1, cast_zneg, cast_bit1],
have : ((-1 + n + n : β€) : Ξ±) = (n + n + -1 : β€), {simp [add_comm, add_left_comm]},
simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg]
end
theorem add_zero (n : znum) : n + 0 = n := by cases n; refl
theorem zero_add (n : znum) : 0 + n = n := by cases n; refl
theorem add_one : β n : znum, n + 1 = succ n
| 0 := rfl
| (pos p) := congr_arg pos p.add_one
| (neg p) := by cases p; refl
end znum
namespace pos_num
variables {Ξ± : Type*}
theorem cast_to_znum : β n : pos_num, (n : znum) = znum.pos n
| 1 := rfl
| (bit0 p) := (znum.bit0_of_bit0 p).trans $ congr_arg _ (cast_to_znum p)
| (bit1 p) := (znum.bit1_of_bit1 p).trans $ congr_arg _ (cast_to_znum p)
theorem cast_sub' [add_group Ξ±] [has_one Ξ±] : β m n : pos_num, (sub' m n : Ξ±) = m - n
| a 1 := by rw [sub'_one, num.cast_to_znum,
β num.cast_to_nat, pred'_to_nat, β nat.sub_one];
simp [pos_num.cast_pos]
| 1 b := by rw [one_sub', num.cast_to_znum_neg, β neg_sub, neg_inj',
β num.cast_to_nat, pred'_to_nat, β nat.sub_one];
simp [pos_num.cast_pos]
| (bit0 a) (bit0 b) := begin
rw [sub', znum.cast_bit0, cast_sub'],
have : ((a + -b + (a + -b) : β€) : Ξ±) = a + a + (-b + -b), {simp [add_left_comm]},
simpa [_root_.bit0, sub_eq_add_neg]
end
| (bit0 a) (bit1 b) := begin
rw [sub', znum.cast_bitm1, cast_sub'],
have : ((-b + (a + (-b + -1)) : β€) : Ξ±) = (a + -1 + (-b + -b):β€),
{ simp [add_comm, add_left_comm] },
simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg]
end
| (bit1 a) (bit0 b) := begin
rw [sub', znum.cast_bit1, cast_sub'],
have : ((-b + (a + (-b + 1)) : β€) : Ξ±) = (a + 1 + (-b + -b):β€),
{ simp [add_comm, add_left_comm] },
simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg]
end
| (bit1 a) (bit1 b) := begin
rw [sub', znum.cast_bit0, cast_sub'],
have : ((-b + (a + -b) : β€) : Ξ±) = a + (-b + -b), {simp [add_left_comm]},
simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg]
end
theorem to_nat_eq_succ_pred (n : pos_num) : (n:β) = n.pred' + 1 :=
by rw [β num.succ'_to_nat, n.succ'_pred']
theorem to_int_eq_succ_pred (n : pos_num) : (n:β€) = (n.pred' : β) + 1 :=
by rw [β n.to_nat_to_int, to_nat_eq_succ_pred]; refl
end pos_num
namespace num
variables {Ξ± : Type*}
@[simp] theorem cast_sub' [add_group Ξ±] [has_one Ξ±] : β m n : num, (sub' m n : Ξ±) = m - n
| 0 0 := (sub_zero _).symm
| (pos a) 0 := (sub_zero _).symm
| 0 (pos b) := (zero_sub _).symm
| (pos a) (pos b) := pos_num.cast_sub' _ _
@[simp] theorem of_nat_to_znum : β n : β, to_znum n = n
| 0 := rfl
| (n+1) := by rw [nat.cast_add_one, nat.cast_add_one,
znum.add_one, add_one, β of_nat_to_znum]; cases (n:num); refl
@[simp] theorem of_nat_to_znum_neg (n : β) : to_znum_neg n = -n :=
by rw [β of_nat_to_znum, zneg_to_znum]
theorem mem_of_znum' : β {m : num} {n : znum}, m β of_znum' n β n = to_znum m
| 0 0 := β¨Ξ» _, rfl, Ξ» _, rflβ©
| (pos m) 0 := β¨Ξ» h, by cases h, Ξ» h, by cases hβ©
| m (znum.pos p) := option.some_inj.trans $
by cases m; split; intro h; try {cases h}; refl
| m (znum.neg p) := β¨Ξ» h, by cases h, Ξ» h, by cases m; cases hβ©
theorem of_znum'_to_nat : β (n : znum), coe <$> of_znum' n = int.to_nat' n
| 0 := rfl
| (znum.pos p) := show _ = int.to_nat' p, by rw [β pos_num.to_nat_to_int p]; refl
| (znum.neg p) := congr_arg (Ξ» x, int.to_nat' (-x)) $
show ((p.pred' + 1 : β) : β€) = p, by rw β succ'_to_nat; simp
@[simp] theorem of_znum_to_nat : β (n : znum), (of_znum n : β) = int.to_nat n
| 0 := rfl
| (znum.pos p) := show _ = int.to_nat p, by rw [β pos_num.to_nat_to_int p]; refl
| (znum.neg p) := congr_arg (Ξ» x, int.to_nat (-x)) $
show ((p.pred' + 1 : β) : β€) = p, by rw β succ'_to_nat; simp
@[simp] theorem cast_of_znum [add_group Ξ±] [has_one Ξ±] (n : znum) :
(of_znum n : Ξ±) = int.to_nat n :=
by rw [β cast_to_nat, of_znum_to_nat]
@[simp, norm_cast] theorem sub_to_nat (m n) : ((m - n : num) : β) = m - n :=
show (of_znum _ : β) = _, by rw [of_znum_to_nat, cast_sub',
β to_nat_to_int, β to_nat_to_int, int.to_nat_sub]
end num
namespace znum
variables {Ξ± : Type*}
@[simp, norm_cast] theorem cast_add [add_group Ξ±] [has_one Ξ±] : β m n, ((m + n : znum) : Ξ±) = m + n
| 0 a := by cases a; exact (_root_.zero_add _).symm
| b 0 := by cases b; exact (_root_.add_zero _).symm
| (pos a) (pos b) := pos_num.cast_add _ _
| (pos a) (neg b) := pos_num.cast_sub' _ _
| (neg a) (pos b) := (pos_num.cast_sub' _ _).trans $
show βb + -βa = -βa + βb, by rw [β pos_num.cast_to_int a, β pos_num.cast_to_int b,
β int.cast_neg, β int.cast_add (-a)]; simp [add_comm]
| (neg a) (neg b) := show -(β(a + b) : Ξ±) = -a + -b, by rw [
pos_num.cast_add, neg_eq_iff_neg_eq, neg_add_rev, neg_neg, neg_neg,
β pos_num.cast_to_int a, β pos_num.cast_to_int b, β int.cast_add]; simp [add_comm]
@[simp] theorem cast_succ [add_group Ξ±] [has_one Ξ±] (n) : ((succ n : znum) : Ξ±) = n + 1 :=
by rw [β add_one, cast_add, cast_one]
@[simp, norm_cast] theorem mul_to_int : β m n, ((m * n : znum) : β€) = m * n
| 0 a := by cases a; exact (_root_.zero_mul _).symm
| b 0 := by cases b; exact (_root_.mul_zero _).symm
| (pos a) (pos b) := pos_num.cast_mul a b
| (pos a) (neg b) := show -β(a * b) = βa * -βb, by rw [pos_num.cast_mul, neg_mul_eq_mul_neg]
| (neg a) (pos b) := show -β(a * b) = -βa * βb, by rw [pos_num.cast_mul, neg_mul_eq_neg_mul]
| (neg a) (neg b) := show β(a * b) = -βa * -βb, by rw [pos_num.cast_mul, neg_mul_neg]
theorem cast_mul [ring Ξ±] (m n) : ((m * n : znum) : Ξ±) = m * n :=
by rw [β cast_to_int, mul_to_int, int.cast_mul, cast_to_int, cast_to_int]
@[simp, norm_cast] theorem of_to_int : Ξ (n : znum), ((n : β€) : znum) = n
| 0 := rfl
| (pos a) := by rw [cast_pos, β pos_num.cast_to_nat,
int.cast_coe_nat', β num.of_nat_to_znum, pos_num.of_to_nat]; refl
| (neg a) := by rw [cast_neg, neg_of_int, β pos_num.cast_to_nat,
int.cast_coe_nat', β num.of_nat_to_znum_neg, pos_num.of_to_nat]; refl
@[norm_cast]
theorem to_of_int : Ξ (n : β€), ((n : znum) : β€) = n
| (n : β) := by rw [int.cast_coe_nat,
β num.of_nat_to_znum, num.cast_to_znum, β num.cast_to_nat,
int.nat_cast_eq_coe_nat, num.to_of_nat]
| -[1+ n] := by rw [int.cast_neg_succ_of_nat, cast_zneg,
add_one, cast_succ, int.neg_succ_of_nat_eq,
β num.of_nat_to_znum, num.cast_to_znum, β num.cast_to_nat,
int.nat_cast_eq_coe_nat, num.to_of_nat]
theorem to_int_inj {m n : znum} : (m : β€) = n β m = n :=
β¨Ξ» h, function.injective_of_left_inverse of_to_int h, congr_arg _β©
@[simp, norm_cast] theorem of_int_cast [add_group Ξ±] [has_one Ξ±] (n : β€) : ((n : znum) : Ξ±) = n :=
by rw [β cast_to_int, to_of_int]
@[simp, norm_cast] theorem of_nat_cast [add_group Ξ±] [has_one Ξ±] (n : β) : ((n : znum) : Ξ±) = n :=
of_int_cast n
@[simp] theorem of_int'_eq : β n, znum.of_int' n = n
| (n : β) := to_int_inj.1 $ by simp [znum.of_int']
| -[1+ n] := to_int_inj.1 $ by simp [znum.of_int']
theorem cmp_to_int : β (m n), (ordering.cases_on (cmp m n) ((m:β€) < n) (m = n) ((m:β€) > n) : Prop)
| 0 0 := rfl
| (pos a) (pos b) := begin
have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp];
cases pos_num.cmp a b; dsimp;
[simp, exact congr_arg pos, simp [gt]]
end
| (neg a) (neg b) := begin
have := pos_num.cmp_to_nat b a; revert this; dsimp [cmp];
cases pos_num.cmp b a; dsimp;
[simp, simp {contextual := tt}, simp [gt]]
end
| (pos a) 0 := pos_num.cast_pos _
| (pos a) (neg b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _)
| 0 (neg b) := neg_lt_zero.2 $ pos_num.cast_pos _
| (neg a) 0 := neg_lt_zero.2 $ pos_num.cast_pos _
| (neg a) (pos b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _)
| 0 (pos b) := pos_num.cast_pos _
@[norm_cast]
theorem lt_to_int {m n : znum} : (m:β€) < n β m < n :=
show (m:β€) < n β cmp m n = ordering.lt, from
match cmp m n, cmp_to_int m n with
| ordering.lt, h := by simp at h; simp [h]
| ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial
| ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial
end
theorem le_to_int {m n : znum} : (m:β€) β€ n β m β€ n :=
by rw β not_lt; exact not_congr lt_to_int
@[simp, norm_cast]
theorem cast_lt [linear_ordered_ring Ξ±] {m n : znum} : (m:Ξ±) < n β m < n :=
by rw [β cast_to_int m, β cast_to_int n, int.cast_lt, lt_to_int]
@[simp, norm_cast]
theorem cast_le [linear_ordered_ring Ξ±] {m n : znum} : (m:Ξ±) β€ n β m β€ n :=
by rw β not_lt; exact not_congr cast_lt
@[simp, norm_cast]
theorem cast_inj [linear_ordered_ring Ξ±] {m n : znum} : (m:Ξ±) = n β m = n :=
by rw [β cast_to_int m, β cast_to_int n, int.cast_inj, to_int_inj]
meta def transfer_rw : tactic unit :=
`[repeat {rw β to_int_inj <|> rw β lt_to_int <|> rw β le_to_int},
repeat {rw cast_add <|> rw mul_to_int <|> rw cast_one <|> rw cast_zero}]
meta def transfer : tactic unit :=
`[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}]
instance : decidable_linear_order znum :=
{ lt := (<),
lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le},
le := (β€),
le_refl := by transfer,
le_trans := by {intros a b c, transfer_rw, apply le_trans},
le_antisymm := by {intros a b, transfer_rw, apply le_antisymm},
le_total := by {intros a b, transfer_rw, apply le_total},
decidable_eq := znum.decidable_eq,
decidable_le := znum.decidable_le,
decidable_lt := znum.decidable_lt }
instance : add_comm_group znum :=
{ add := (+),
add_assoc := by transfer,
zero := 0,
zero_add := zero_add,
add_zero := add_zero,
add_comm := by transfer,
neg := has_neg.neg,
add_left_neg := by transfer }
instance : decidable_linear_ordered_comm_ring znum :=
{ mul := (*),
mul_assoc := by transfer,
one := 1,
one_mul := by transfer,
mul_one := by transfer,
left_distrib := by {transfer, simp [mul_add]},
right_distrib := by {transfer, simp [mul_add, mul_comm]},
mul_comm := by transfer,
zero_ne_one := dec_trivial,
add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact Ξ» h, add_le_add_left h c},
mul_pos := Ξ» a b, show 0 < a β 0 < b β 0 < a * b, by {transfer_rw, apply mul_pos},
zero_lt_one := dec_trivial,
..znum.decidable_linear_order, ..znum.add_comm_group }
@[simp, norm_cast] theorem dvd_to_int (m n : znum) : (m : β€) β£ n β m β£ n :=
β¨Ξ» β¨k, eβ©, β¨k, by rw [β of_to_int n, e]; simpβ©,
Ξ» β¨k, eβ©, β¨k, by simp [e]β©β©
end znum
namespace pos_num
theorem divmod_to_nat_aux {n d : pos_num} {q r : num}
(hβ : (r:β) + d * _root_.bit0 q = n)
(hβ : (r:β) < 2 * d) :
((divmod_aux d q r).2 + d * (divmod_aux d q r).1 : β) = βn β§
((divmod_aux d q r).2 : β) < d :=
begin
unfold divmod_aux,
have : β {rβ}, num.of_znum' (num.sub' r (num.pos d)) = some rβ β (r : β) = rβ + d,
{ intro rβ,
apply num.mem_of_znum'.trans,
rw [β znum.to_int_inj, num.cast_to_znum,
num.cast_sub', sub_eq_iff_eq_add, β int.coe_nat_inj'],
simp },
cases e : num.of_znum' (num.sub' r (num.pos d)) with rβ;
simp [divmod_aux],
{ refine β¨hβ, lt_of_not_ge (Ξ» h, _)β©,
cases nat.le.dest h with rβ e',
rw [β num.to_of_nat rβ, add_comm] at e',
cases e.symm.trans (this.2 e'.symm) },
{ have := this.1 e,
split,
{ rwa [_root_.bit1, add_comm _ 1, mul_add, mul_one,
β add_assoc, β this] },
{ rwa [this, two_mul, add_lt_add_iff_right] at hβ } }
end
theorem divmod_to_nat (d n : pos_num) :
(n / d : β) = (divmod d n).1 β§
(n % d : β) = (divmod d n).2 :=
begin
rw nat.div_mod_unique (pos_num.cast_pos _),
induction n with n IH n IH,
{ exact divmod_to_nat_aux (by simp; refl)
(nat.mul_le_mul_left 2
(pos_num.cast_pos d : (0 : β) < d)) },
{ unfold divmod,
cases divmod d n with q r, simp only [divmod] at IH β’,
apply divmod_to_nat_aux; simp,
{ rw [_root_.bit1, _root_.bit1, add_right_comm,
bit0_eq_two_mul βn, β IH.1,
mul_add, β bit0_eq_two_mul,
mul_left_comm, β bit0_eq_two_mul] },
{ rw β bit0_eq_two_mul,
exact nat.bit1_lt_bit0 IH.2 } },
{ unfold divmod,
cases divmod d n with q r, simp only [divmod] at IH β’,
apply divmod_to_nat_aux; simp,
{ rw [bit0_eq_two_mul βn, β IH.1,
mul_add, β bit0_eq_two_mul,
mul_left_comm, β bit0_eq_two_mul] },
{ rw β bit0_eq_two_mul,
exact nat.bit0_lt IH.2 } }
end
@[simp] theorem div'_to_nat (n d) : (div' n d : β) = n / d :=
(divmod_to_nat _ _).1.symm
@[simp] theorem mod'_to_nat (n d) : (mod' n d : β) = n % d :=
(divmod_to_nat _ _).2.symm
end pos_num
namespace num
@[simp, norm_cast] theorem div_to_nat : β n d, ((n / d : num) : β) = n / d
| 0 0 := rfl
| 0 (pos d) := (nat.zero_div _).symm
| (pos n) 0 := (nat.div_zero _).symm
| (pos n) (pos d) := pos_num.div'_to_nat _ _
@[simp, norm_cast] theorem mod_to_nat : β n d, ((n % d : num) : β) = n % d
| 0 0 := rfl
| 0 (pos d) := (nat.zero_mod _).symm
| (pos n) 0 := (nat.mod_zero _).symm
| (pos n) (pos d) := pos_num.mod'_to_nat _ _
theorem gcd_to_nat_aux : β {n} {a b : num},
a β€ b β (a * b).nat_size β€ n β (gcd_aux n a b : β) = nat.gcd a b
| 0 0 b ab h := (nat.gcd_zero_left _).symm
| 0 (pos a) 0 ab h := (not_lt_of_ge ab).elim rfl
| 0 (pos a) (pos b) ab h :=
(not_lt_of_le h).elim $ pos_num.nat_size_pos _
| (nat.succ n) 0 b ab h := (nat.gcd_zero_left _).symm
| (nat.succ n) (pos a) b ab h := begin
simp [gcd_aux],
rw [nat.gcd_rec, gcd_to_nat_aux, mod_to_nat], {refl},
{ rw [β le_to_nat, mod_to_nat],
exact le_of_lt (nat.mod_lt _ (pos_num.cast_pos _)) },
rw [nat_size_to_nat, mul_to_nat, nat.size_le] at h β’,
rw [mod_to_nat, mul_comm],
rw [nat.pow_succ, β nat.mod_add_div b (pos a)] at h,
refine lt_of_mul_lt_mul_right (lt_of_le_of_lt _ h) (nat.zero_le 2),
rw [mul_two, mul_add],
refine add_le_add_left (nat.mul_le_mul_left _
(le_trans (le_of_lt (nat.mod_lt _ (pos_num.cast_pos _))) _)) _,
suffices : 1 β€ _, simpa using nat.mul_le_mul_left (pos a) this,
rw [nat.le_div_iff_mul_le _ _ a.cast_pos, one_mul],
exact le_to_nat.2 ab
end
@[simp] theorem gcd_to_nat : β a b, (gcd a b : β) = nat.gcd a b :=
have β a b : num, (a * b).nat_size β€ a.nat_size + b.nat_size,
begin
intros,
simp [nat_size_to_nat],
rw [nat.size_le, nat.pow_add],
exact mul_lt_mul'' (nat.lt_size_self _)
(nat.lt_size_self _) (nat.zero_le _) (nat.zero_le _)
end,
begin
intros, unfold gcd, split_ifs,
{ exact gcd_to_nat_aux h (this _ _) },
{ rw nat.gcd_comm,
exact gcd_to_nat_aux (le_of_not_le h) (this _ _) }
end
theorem dvd_iff_mod_eq_zero {m n : num} : m β£ n β n % m = 0 :=
by rw [β dvd_to_nat, nat.dvd_iff_mod_eq_zero,
β to_nat_inj, mod_to_nat]; refl
instance : decidable_rel ((β£) : num β num β Prop)
| a b := decidable_of_iff' _ dvd_iff_mod_eq_zero
end num
namespace znum
@[simp, norm_cast] theorem div_to_int : β n d, ((n / d : znum) : β€) = n / d
| 0 0 := rfl
| 0 (pos d) := (int.zero_div _).symm
| 0 (neg d) := (int.zero_div _).symm
| (pos n) 0 := (int.div_zero _).symm
| (neg n) 0 := (int.div_zero _).symm
| (pos n) (pos d) := (num.cast_to_znum _).trans $
by rw β num.to_nat_to_int; simp
| (pos n) (neg d) := (num.cast_to_znum_neg _).trans $
by rw β num.to_nat_to_int; simp
| (neg n) (pos d) := show - _ = (-_/βd), begin
rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred,
β pos_num.to_nat_to_int, num.succ'_to_nat,
num.div_to_nat],
change -[1+ n.pred' / βd] = -[1+ n.pred' / (d.pred' + 1)],
rw d.to_nat_eq_succ_pred
end
| (neg n) (neg d) := show β(pos_num.pred' n / num.pos d).succ' = (-_ / -βd), begin
rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred,
β pos_num.to_nat_to_int, num.succ'_to_nat,
num.div_to_nat],
change (nat.succ (_/d) : β€) = nat.succ (n.pred'/(d.pred' + 1)),
rw d.to_nat_eq_succ_pred
end
@[simp, norm_cast] theorem mod_to_int : β n d, ((n % d : znum) : β€) = n % d
| 0 d := (int.zero_mod _).symm
| (pos n) d := (num.cast_to_znum _).trans $
by rw [β num.to_nat_to_int, cast_pos, num.mod_to_nat,
β pos_num.to_nat_to_int, abs_to_nat]; refl
| (neg n) d := (num.cast_sub' _ _).trans $
by rw [β num.to_nat_to_int, cast_neg, β num.to_nat_to_int,
num.succ_to_nat, num.mod_to_nat, abs_to_nat,
β int.sub_nat_nat_eq_coe, n.to_int_eq_succ_pred]; refl
@[simp] theorem gcd_to_nat (a b) : (gcd a b : β) = int.gcd a b :=
(num.gcd_to_nat _ _).trans $ by simpa
theorem dvd_iff_mod_eq_zero {m n : znum} : m β£ n β n % m = 0 :=
by rw [β dvd_to_int, int.dvd_iff_mod_eq_zero,
β to_int_inj, mod_to_int]; refl
instance : decidable_rel ((β£) : znum β znum β Prop)
| a b := decidable_of_iff' _ dvd_iff_mod_eq_zero
end znum
namespace int
def of_snum : snum β β€ :=
snum.rec' (Ξ» a, cond a (-1) 0) (Ξ»a p IH, cond a (bit1 IH) (bit0 IH))
instance snum_coe : has_coe snum β€ := β¨of_snumβ©
end int
instance : has_lt snum := β¨Ξ»a b, (a : β€) < bβ©
instance : has_le snum := β¨Ξ»a b, (a : β€) β€ bβ©
|
285d8e2881f2d6adbdba831e792eafad055df304 | f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58 | /algebra/big_operators.lean | 9a552e56ba9705c5722ea6140655e67c049afefd | [
"Apache-2.0"
] | permissive | semorrison/mathlib | 1be6f11086e0d24180fec4b9696d3ec58b439d10 | 20b4143976dad48e664c4847b75a85237dca0a89 | refs/heads/master | 1,583,799,212,170 | 1,535,634,130,000 | 1,535,730,505,000 | 129,076,205 | 0 | 0 | Apache-2.0 | 1,551,697,998,000 | 1,523,442,265,000 | Lean | UTF-8 | Lean | false | false | 18,381 | 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
Some big operators for lists and finite sets.
-/
import data.list.basic data.list.perm data.finset
algebra.group algebra.ordered_group algebra.group_power
universes u v w
variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w}
namespace finset
variables {s sβ sβ : finset Ξ±} {a : Ξ±} {f g : Ξ± β Ξ²}
/-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/
@[to_additive finset.sum]
protected def prod [comm_monoid Ξ²] (s : finset Ξ±) (f : Ξ± β Ξ²) : Ξ² := (s.1.map f).prod
attribute [to_additive finset.sum.equations._eqn_1] finset.prod.equations._eqn_1
@[to_additive finset.sum_eq_fold]
theorem prod_eq_fold [comm_monoid Ξ²] (s : finset Ξ±) (f : Ξ± β Ξ²) : s.prod f = s.fold (*) 1 f := rfl
section comm_monoid
variables [comm_monoid Ξ²]
@[simp, to_additive finset.sum_empty]
lemma prod_empty {Ξ± : Type u} {f : Ξ± β Ξ²} : (β
:finset Ξ±).prod f = 1 := rfl
@[simp, to_additive finset.sum_insert]
lemma prod_insert [decidable_eq Ξ±] : a β s β (insert a s).prod f = f a * s.prod f := fold_insert
@[simp, to_additive finset.sum_singleton]
lemma prod_singleton : (singleton a).prod f = f a :=
eq.trans fold_singleton (by simp)
@[simp] lemma prod_const_one : s.prod (Ξ»x, (1 : Ξ²)) = 1 :=
by simp [finset.prod]
@[simp] lemma sum_const_zero {Ξ²} {s : finset Ξ±} [add_comm_monoid Ξ²] : s.sum (Ξ»x, (0 : Ξ²)) = 0 :=
@prod_const_one _ (multiplicative Ξ²) _ _
attribute [to_additive finset.sum_const_zero] prod_const_one
@[simp, to_additive finset.sum_image]
lemma prod_image [decidable_eq Ξ±] [decidable_eq Ξ³] {s : finset Ξ³} {g : Ξ³ β Ξ±} :
(βxβs, βyβs, g x = g y β x = y) β (s.image g).prod f = s.prod (Ξ»x, f (g x)) :=
fold_image
@[congr, to_additive finset.sum_congr]
lemma prod_congr (h : sβ = sβ) : (βxβsβ, f x = g x) β sβ.prod f = sβ.prod g :=
by rw [h]; exact fold_congr
attribute [congr] finset.sum_congr
@[to_additive finset.sum_union_inter]
lemma prod_union_inter [decidable_eq Ξ±] : (sβ βͺ sβ).prod f * (sβ β© sβ).prod f = sβ.prod f * sβ.prod f :=
fold_union_inter
@[to_additive finset.sum_union]
lemma prod_union [decidable_eq Ξ±] (h : sβ β© sβ = β
) : (sβ βͺ sβ).prod f = sβ.prod f * sβ.prod f :=
by rw [βprod_union_inter, h]; simp
@[to_additive finset.sum_sdiff]
lemma prod_sdiff [decidable_eq Ξ±] (h : sβ β sβ) : (sβ \ sβ).prod f * sβ.prod f = sβ.prod f :=
by rw [βprod_union (sdiff_inter_self _ _), sdiff_union_of_subset h]
@[to_additive finset.sum_bind]
lemma prod_bind [decidable_eq Ξ±] {s : finset Ξ³} {t : Ξ³ β finset Ξ±} :
(βxβs, βyβs, x β y β t x β© t y = β
) β (s.bind t).prod f = s.prod (Ξ»x, (t x).prod f) :=
by haveI := classical.dec_eq Ξ³; exact
finset.induction_on s (by simp)
(assume x s hxs ih hd,
have hd' : βxβs, βyβs, x β y β t x β© t y = β
,
from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy),
have t x β© finset.bind s t = β
,
from ext.2 $ assume a,
by simp [mem_bind];
from assume hβ y hys hyβ,
have ha : a β t x β© t y, by simp [*],
have t x β© t y = β
,
from hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hys) $ assume h, hxs $ h.symm βΈ hys,
by rwa [this] at ha,
by simp [hxs, prod_union this, ih hd'] {contextual := tt})
@[to_additive finset.sum_product]
lemma prod_product {s : finset Ξ³} {t : finset Ξ±} {f : Ξ³ΓΞ± β Ξ²} :
(s.product t).prod f = s.prod (Ξ»x, t.prod $ Ξ»y, f (x, y)) :=
begin
haveI := classical.dec_eq Ξ±, haveI := classical.dec_eq Ξ³,
rw [product_eq_bind, prod_bind (Ξ» x hx y hy h, ext.2 _)], {simp [prod_image]},
simp [mem_image], intros, intro, refine h _, cc
end
@[to_additive finset.sum_sigma]
lemma prod_sigma {Ο : Ξ± β Type*}
{s : finset Ξ±} {t : Ξ a, finset (Ο a)} {f : sigma Ο β Ξ²} :
(s.sigma t).prod f = s.prod (Ξ»a, (t a).prod $ Ξ»s, f β¨a, sβ©) :=
by haveI := classical.dec_eq Ξ±; haveI := (Ξ» a, classical.dec_eq (Ο a)); exact
have βaβ aβ:Ξ±, βsβ : finset (Ο aβ), βsβ : finset (Ο aβ), aβ β aβ β
sβ.image (sigma.mk aβ) β© sβ.image (sigma.mk aβ) = β
,
from assume bβ bβ sβ sβ h, ext.2 $ assume β¨bβ, cββ©,
by simp [mem_image, sigma.mk.inj_iff, heq_iff_eq] {contextual := tt}; cc,
calc (s.sigma t).prod f =
(s.bind (Ξ»a, (t a).image (Ξ»s, sigma.mk a s))).prod f : by rw sigma_eq_bind
... = s.prod (Ξ»a, ((t a).image (Ξ»s, sigma.mk a s)).prod f) :
prod_bind $ assume aβ ha aβ haβ h, this aβ aβ (t aβ) (t aβ) h
... = (s.prod $ Ξ»a, (t a).prod $ Ξ»s, f β¨a, sβ©) :
by simp [prod_image, sigma.mk.inj_iff, heq_iff_eq]
@[to_additive finset.sum_add_distrib]
lemma prod_mul_distrib : s.prod (Ξ»x, f x * g x) = s.prod f * s.prod g :=
eq.trans (by simp; refl) fold_op_distrib
@[to_additive finset.sum_comm]
lemma prod_comm [decidable_eq Ξ³] {s : finset Ξ³} {t : finset Ξ±} {f : Ξ³ β Ξ± β Ξ²} :
s.prod (Ξ»x, t.prod $ f x) = t.prod (Ξ»y, s.prod $ Ξ»x, f x y) :=
finset.induction_on s (by simp) (by simp [prod_mul_distrib] {contextual := tt})
@[to_additive finset.sum_hom]
lemma prod_hom [comm_monoid Ξ³] (g : Ξ² β Ξ³)
(hβ : g 1 = 1) (hβ : βx y, g (x * y) = g x * g y) : s.prod (Ξ»x, g (f x)) = g (s.prod f) :=
eq.trans (by rw [hβ]; refl) (fold_hom hβ)
lemma sum_nat_cast [add_comm_monoid Ξ²] [has_one Ξ²] (s : finset Ξ±) (f : Ξ± β β) :
β(s.sum f) = s.sum (Ξ»a, f a : Ξ± β Ξ²) :=
(sum_hom _ nat.cast_zero nat.cast_add).symm
@[to_additive finset.sum_subset]
lemma prod_subset (h : sβ β sβ) (hf : βxβsβ, x β sβ β f x = 1) : sβ.prod f = sβ.prod f :=
by haveI := classical.dec_eq Ξ±; exact
have (sβ \ sβ).prod f = (sβ \ sβ).prod (Ξ»x, 1),
from prod_congr rfl begin simp [hf] {contextual := tt} end,
by rw [βprod_sdiff h]; simp [this]
@[to_additive sum_attach]
lemma prod_attach {f : Ξ± β Ξ²} : s.attach.prod (Ξ»x, f x.val) = s.prod f :=
by haveI := classical.dec_eq Ξ±; exact
calc s.attach.prod (Ξ»x, f x.val) = ((s.attach).image subtype.val).prod f :
by rw [prod_image]; exact assume x _ y _, subtype.eq
... = _ : by rw [attach_image_val]
@[to_additive finset.sum_bij]
lemma prod_bij {s : finset Ξ±} {t : finset Ξ³} {f : Ξ± β Ξ²} {g : Ξ³ β Ξ²}
(i : Ξ aβs, Ξ³) (hi : βa ha, i a ha β t) (h : βa ha, f a = g (i a ha))
(i_inj : βaβ aβ haβ haβ, i aβ haβ = i aβ haβ β aβ = aβ) (i_surj : βbβt, βa ha, b = i a ha) :
s.prod f = t.prod g :=
by haveI := classical.prop_decidable; exact
calc s.prod f = s.attach.prod (Ξ»x, f x.val) : prod_attach.symm
... = s.attach.prod (Ξ»x, g (i x.1 x.2)) : prod_congr rfl $ assume x hx, h _ _
... = (s.attach.image $ Ξ»x:{x // x β s}, i x.1 x.2).prod g :
(prod_image $ assume (aβ:{x // x β s}) _ aβ _ eq, subtype.eq $ i_inj aβ.1 aβ.1 aβ.2 aβ.2 eq).symm
... = _ :
prod_subset
(by simp [subset_iff]; intros b a h eq; subst eq; exact hi _ _)
(assume b hb, not_imp_comm.mp $ assume hbβ,
let β¨a, ha, eqβ© := i_surj b hb in by simp [eq]; exact β¨_, _, rflβ©)
@[to_additive finset.sum_bij_ne_zero]
lemma prod_bij_ne_one {s : finset Ξ±} {t : finset Ξ³} {f : Ξ± β Ξ²} {g : Ξ³ β Ξ²}
(i : Ξ aβs, f a β 1 β Ξ³) (hiβ : βa hβ hβ, i a hβ hβ β t)
(hiβ : βaβ aβ hββ hββ hββ hββ, i aβ hββ hββ = i aβ hββ hββ β aβ = aβ)
(hiβ : βbβt, g b β 1 β βa hβ hβ, b = i a hβ hβ)
(h : βa hβ hβ, f a = g (i a hβ hβ)) :
s.prod f = t.prod g :=
by haveI := classical.prop_decidable; exact
calc s.prod f = (s.filter $ Ξ»x, f x β 1).prod f :
(prod_subset (filter_subset _) $ by simp {contextual:=tt}).symm
... = (t.filter $ Ξ»x, g x β 1).prod g :
prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2)
(assume a ha, (mem_filter.mp ha).elim $ Ξ»hβ hβ, mem_filter.mpr
β¨hiβ a hβ hβ, Ξ» hg, hβ (hg βΈ h a hβ hβ)β©)
(assume a ha, (mem_filter.mp ha).elim $ h a)
(assume aβ aβ haβ haβ,
(mem_filter.mp haβ).elim $ Ξ»haββ haββ, (mem_filter.mp haβ).elim $ Ξ»haββ haββ, hiβ aβ aβ _ _ _ _)
(assume b hb, (mem_filter.mp hb).elim $ Ξ»hβ hβ,
let β¨a, haβ, haβ, eqβ© := hiβ b hβ hβ in β¨a, mem_filter.mpr β¨haβ, haββ©, eqβ©)
... = t.prod g :
(prod_subset (filter_subset _) $ by simp {contextual:=tt})
@[to_additive finset.exists_ne_zero_of_sum_ne_zero]
lemma exists_ne_one_of_prod_ne_one : s.prod f β 1 β βaβs, f a β 1 :=
by haveI := classical.dec_eq Ξ±; exact
finset.induction_on s (by simp) (assume a s has ih h,
classical.by_cases
(assume ha : f a = 1,
have s.prod f β 1, by simpa [ha, has] using h,
let β¨a, ha, hfaβ© := ih this in
β¨a, mem_insert_of_mem ha, hfaβ©)
(assume hna : f a β 1,
β¨a, mem_insert_self _ _, hnaβ©))
@[to_additive finset.sum_range_succ]
lemma prod_range_succ (f : β β Ξ²) (n : β) :
(range (nat.succ n)).prod f = f n * (range n).prod f := by simp
lemma prod_range_succ' (f : β β Ξ²) :
β n : β, (range (nat.succ n)).prod f = (range n).prod (f β nat.succ) * f 0
| 0 := by simp
| (n + 1) := by rw [prod_range_succ (Ξ» m, f (nat.succ m)), mul_assoc, β prod_range_succ'];
exact prod_range_succ _ _
@[simp] lemma prod_const [decidable_eq Ξ±] (b : Ξ²) : s.prod (Ξ» a, b) = b ^ s.card :=
finset.induction_on s rfl (by simp [pow_add, mul_comm] {contextual := tt})
end comm_monoid
@[simp] lemma sum_const [add_comm_monoid Ξ²] [decidable_eq Ξ±] (b : Ξ²) :
s.sum (Ξ» a, b) = add_monoid.smul s.card b :=
@prod_const _ (multiplicative Ξ²) _ _ _ _
attribute [to_additive finset.sum_const] prod_const
lemma sum_range_succ' [add_comm_monoid Ξ²] (f : β β Ξ²) :
β n : β, (range (nat.succ n)).sum f = (range n).sum (f β nat.succ) + f 0 :=
@prod_range_succ' (multiplicative Ξ²) _ _
attribute [to_additive finset.sum_range_succ'] prod_range_succ'
section comm_group
variables [comm_group Ξ²]
@[simp, to_additive finset.sum_neg_distrib]
lemma prod_inv_distrib : s.prod (Ξ»x, (f x)β»ΒΉ) = (s.prod f)β»ΒΉ :=
prod_hom has_inv.inv one_inv mul_inv
end comm_group
@[simp] theorem card_sigma {Ο : Ξ± β Type*} (s : finset Ξ±) (t : Ξ a, finset (Ο a)) :
card (s.sigma t) = s.sum (Ξ» a, card (t a)) :=
multiset.card_sigma _ _
end finset
namespace finset
variables {s sβ sβ : finset Ξ±} {f g : Ξ± β Ξ²} {b : Ξ²} {a : Ξ±}
@[simp] lemma sum_sub_distrib [add_comm_group Ξ²] : s.sum (Ξ»x, f x - g x) = s.sum f - s.sum g :=
by simp [sum_add_distrib]
section ordered_cancel_comm_monoid
variables [decidable_eq Ξ±] [ordered_cancel_comm_monoid Ξ²]
lemma sum_le_sum : (βxβs, f x β€ g x) β s.sum f β€ s.sum g :=
finset.induction_on s (by simp) $ assume a s ha ih h,
have f a + s.sum f β€ g a + s.sum g,
from add_le_add (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx),
by simp [*]
lemma zero_le_sum (h : βxβs, 0 β€ f x) : 0 β€ s.sum f := le_trans (by simp) (sum_le_sum h)
lemma sum_le_zero (h : βxβs, f x β€ 0) : s.sum f β€ 0 := le_trans (sum_le_sum h) (by simp)
end ordered_cancel_comm_monoid
section semiring
variables [semiring Ξ²]
lemma sum_mul : s.sum f * b = s.sum (Ξ»x, f x * b) :=
(sum_hom (Ξ»x, x * b) (zero_mul b) (assume a c, add_mul a c b)).symm
lemma mul_sum : b * s.sum f = s.sum (Ξ»x, b * f x) :=
(sum_hom (Ξ»x, b * x) (mul_zero b) (assume a c, mul_add b a c)).symm
end semiring
section comm_semiring
variables [decidable_eq Ξ±] [comm_semiring Ξ²]
lemma prod_eq_zero (ha : a β s) (h : f a = 0) : s.prod f = 0 :=
calc s.prod f = (insert a (erase s a)).prod f : by simp [ha, insert_erase]
... = 0 : by simp [h]
lemma prod_sum {Ξ΄ : Ξ± β Type*} [βa, decidable_eq (Ξ΄ a)]
{s : finset Ξ±} {t : Ξ a, finset (Ξ΄ a)} {f : Ξ a, Ξ΄ a β Ξ²} :
s.prod (Ξ»a, (t a).sum (Ξ»b, f a b)) =
(s.pi t).sum (Ξ»p, s.attach.prod (Ξ»x, f x.1 (p x.1 x.2))) :=
begin
induction s using finset.induction with a s ha ih,
{ simp },
{ have hβ : βx β t a, βyβt a, βh : x β y,
image (pi.cons s a x) (pi s t) β© image (pi.cons s a y) (pi s t) = β
,
{ assume x hx y hy h,
apply eq_empty_of_forall_not_mem,
simp,
assume pβ pβ hp eq pβ hpβ eq', subst eq',
have : pi.cons s a x pβ a (mem_insert_self _ _) = pi.cons s a y pβ a (mem_insert_self _ _),
{ rw [eq] },
rw [pi.cons_same, pi.cons_same] at this,
exact h this },
have hβ : βb:Ξ΄ a, βpββpi s t, βpββpi s t, pi.cons s a b pβ = pi.cons s a b pβ β pβ = pβ, from
assume b pβ hβ pβ hβ eq, injective_pi_cons ha eq,
have hβ : β(v:{x // x β s}) (b:Ξ΄ a) (h : v.1 β insert a s) (p : Ξ a, a β s β Ξ΄ a),
pi.cons s a b p v.1 h = p v.1 v.2, from
assume v b h p, pi.cons_ne $ assume eq, ha $ eq.symm βΈ v.2,
simp [ha, ih, sum_bind hβ, sum_image (hβ _), sum_mul, hβ],
simp [mul_sum] }
end
end comm_semiring
section integral_domain /- add integral_semi_domain to support nat and ennreal -/
variables [decidable_eq Ξ±] [integral_domain Ξ²]
lemma prod_eq_zero_iff : s.prod f = 0 β (βaβs, f a = 0) :=
finset.induction_on s (by simp)
begin
intros a s,
rw [bex_def, bex_def, exists_mem_insert],
simp [mul_eq_zero_iff_eq_zero_or_eq_zero] {contextual := tt}
end
end integral_domain
section ordered_comm_monoid
variables [decidable_eq Ξ±] [ordered_comm_monoid Ξ²]
lemma sum_le_sum' : (βxβs, f x β€ g x) β s.sum f β€ s.sum g :=
finset.induction_on s (by simp; refl) $ assume a s ha ih h,
have f a + s.sum f β€ g a + s.sum g,
from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx),
by simp [*]
lemma zero_le_sum' (h : βxβs, 0 β€ f x) : 0 β€ s.sum f := le_trans (by simp) (sum_le_sum' h)
lemma sum_le_zero' (h : βxβs, f x β€ 0) : s.sum f β€ 0 := le_trans (sum_le_sum' h) (by simp)
lemma sum_le_sum_of_subset_of_nonneg
(h : sβ β sβ) (hf : βxβsβ, x β sβ β 0 β€ f x) : sβ.sum f β€ sβ.sum f :=
calc sβ.sum f β€ (sβ \ sβ).sum f + sβ.sum f :
le_add_of_nonneg_left' $ zero_le_sum' $ by simp [hf] {contextual := tt}
... = (sβ \ sβ βͺ sβ).sum f : (sum_union (sdiff_inter_self _ _)).symm
... = sβ.sum f : by rw [sdiff_union_of_subset h]
lemma sum_eq_zero_iff_of_nonneg : (βxβs, 0 β€ f x) β (s.sum f = 0 β βxβs, f x = 0) :=
finset.induction_on s (by simp) $
by simp [or_imp_distrib, forall_and_distrib, zero_le_sum' ,
add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg'] {contextual := tt}
lemma single_le_sum (hf : βxβs, 0 β€ f x) {a} (h : a β s) : f a β€ s.sum f :=
by simpa using show (singleton a).sum f β€ s.sum f,
from sum_le_sum_of_subset_of_nonneg
(Ξ» x e, (mem_singleton.1 e).symm βΈ h) (Ξ» x h _, hf x h)
end ordered_comm_monoid
section canonically_ordered_monoid
variables [decidable_eq Ξ±] [canonically_ordered_monoid Ξ²] [@decidable_rel Ξ² (β€)]
lemma sum_le_sum_of_subset (h : sβ β sβ) : sβ.sum f β€ sβ.sum f :=
sum_le_sum_of_subset_of_nonneg h $ assume x hβ hβ, zero_le _
lemma sum_le_sum_of_ne_zero (h : βxβsβ, f x β 0 β x β sβ) : sβ.sum f β€ sβ.sum f :=
calc sβ.sum f = (sβ.filter (Ξ»x, f x = 0)).sum f + (sβ.filter (Ξ»x, f x β 0)).sum f :
by rw [βsum_union, filter_union_filter_neg_eq]; apply filter_inter_filter_neg_eq
... β€ sβ.sum f : add_le_of_nonpos_of_le'
(sum_le_zero' $ by simp {contextual:=tt})
(sum_le_sum_of_subset $ by simp [subset_iff, *] {contextual:=tt})
end canonically_ordered_monoid
section discrete_linear_ordered_field
variables [discrete_linear_ordered_field Ξ±] [decidable_eq Ξ²]
lemma abs_sum_le_sum_abs {f : Ξ² β Ξ±} {s : finset Ξ²} : abs (s.sum f) β€ s.sum (Ξ»a, abs (f a)) :=
finset.induction_on s (by simp [abs_zero]) $
assume a s has ih,
calc abs (sum (insert a s) f) β€ abs (f a) + abs (sum s f) :
by simp [has]; exact abs_add_le_abs_add_abs _ _
... β€ abs (f a) + s.sum (Ξ»a, abs (f a)) : add_le_add (le_refl _) ih
... β€ sum (insert a s) (Ξ» (a : Ξ²), abs (f a)) : by simp [has]
end discrete_linear_ordered_field
@[simp] lemma card_pi [decidable_eq Ξ±] {Ξ΄ : Ξ± β Type*}
(s : finset Ξ±) (t : Ξ a, finset (Ξ΄ a)) :
(s.pi t).card = s.prod (Ξ» a, card (t a)) :=
multiset.card_pi _ _
end finset
section group
open list
variables [group Ξ±] [group Ξ²]
theorem is_group_hom.prod (f : Ξ± β Ξ²) [is_group_hom f] (l : list Ξ±) :
f (prod l) = prod (map f l) :=
by induction l; simp [*, is_group_hom.mul f, is_group_hom.one f]
theorem is_group_anti_hom.prod (f : Ξ± β Ξ²) [is_group_anti_hom f] (l : list Ξ±) :
f (prod l) = prod (map f (reverse l)) :=
by induction l; simp [*, is_group_anti_hom.mul f, is_group_anti_hom.one f]
theorem inv_prod : β l : list Ξ±, (prod l)β»ΒΉ = prod (map (Ξ» x, xβ»ΒΉ) (reverse l)) :=
Ξ» l, @is_group_anti_hom.prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this
end group
namespace multiset
variables [decidable_eq Ξ±]
@[simp] lemma to_finset_sum_count_eq (s : multiset Ξ±) :
s.to_finset.sum (Ξ»a, s.count a) = s.card :=
multiset.induction_on s (by simp)
(assume a s ih,
calc (to_finset (a :: s)).sum (Ξ»x, count x (a :: s)) =
(to_finset (a :: s)).sum (Ξ»x, (if x = a then 1 else 0) + count x s) :
by congr; funext x; split_ifs; simp [h, nat.one_add]
... = card (a :: s) :
begin
by_cases a β s.to_finset,
{ have : (to_finset s).sum (Ξ»x, ite (x = a) 1 0) = ({a}:finset Ξ±).sum (Ξ»x, ite (x = a) 1 0),
{ apply (finset.sum_subset _ _).symm,
{ simp [finset.subset_iff, *] at * },
{ simp [if_neg] {contextual := tt} } },
simp [h, ih, this, finset.sum_add_distrib] },
{ have : a β s, by simp * at *,
have : (to_finset s).sum (Ξ»x, ite (x = a) 1 0) = (to_finset s).sum (Ξ»x, 0), from
finset.sum_congr rfl begin assume a ha, split_ifs; simp [*] at * end,
simp [*, finset.sum_add_distrib], }
end)
end multiset
|
ecd884768f8207fa1e7974b50eede90a548e618a | 842b7df4a999c5c50bbd215b8617dd705e43c2e1 | /nat_num_game/src/Advanced_Addition_World/adv_add_wrld7.lean | 1ea9c1953c56a7f2acf2bbee639acd3152a38371 | [] | no_license | Samyak-Surti/LeanCode | 1c245631f74b00057d20483c8ac75916e8643b14 | 944eac3e5f43e2614ed246083b97fbdf24181d83 | refs/heads/master | 1,669,023,730,828 | 1,595,534,784,000 | 1,595,534,784,000 | 282,037,186 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 165 | lean | theorem add_right_cancel_iff (t a b : β) : a + t = b + t β a = b :=
begin
split,
intro h,
apply nat.add_right_cancel h,
intro f,
rw f,
end |
5ecbbd7c067586d690e8f0a01f6bfe616df0f06e | 3c9dc4ea6cc92e02634ef557110bde9eae393338 | /stage0/src/Lean/Elab/Frontend.lean | 52d8dda5cf760980bbaadbf2466956ca4077d908 | [
"Apache-2.0"
] | permissive | shingtaklam1324/lean4 | 3d7efe0c8743a4e33d3c6f4adbe1300df2e71492 | 351285a2e8ad0cef37af05851cfabf31edfb5970 | refs/heads/master | 1,676,827,679,740 | 1,610,462,623,000 | 1,610,552,340,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,413 | 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.Elab.Import
import Lean.Elab.Command
import Lean.Util.Profile
namespace Lean.Elab.Frontend
structure State where
commandState : Command.State
parserState : Parser.ModuleParserState
cmdPos : String.Pos
commands : Array Syntax := #[]
structure Context where
inputCtx : Parser.InputContext
abbrev FrontendM := ReaderT Context $ StateRefT State IO
def setCommandState (commandState : Command.State) : FrontendM Unit :=
modify fun s => { s with commandState := commandState }
@[inline] def runCommandElabM (x : Command.CommandElabM Unit) : FrontendM Unit := do
let ctx β read
let s β get
let cmdCtx : Command.Context := { cmdPos := s.cmdPos, fileName := ctx.inputCtx.fileName, fileMap := ctx.inputCtx.fileMap }
let sNew? β liftM $ EIO.toIO (fun _ => IO.Error.userError "unexpected error") (do let (_, s) β (x cmdCtx).run s.commandState; pure $ some s)
match sNew? with
| some sNew => setCommandState sNew
| none => pure ()
def elabCommandAtFrontend (stx : Syntax) : FrontendM Unit := do
runCommandElabM (Command.elabCommand stx)
def updateCmdPos : FrontendM Unit := do
modify fun s => { s with cmdPos := s.parserState.pos }
def getParserState : FrontendM Parser.ModuleParserState := do pure (β get).parserState
def getCommandState : FrontendM Command.State := do pure (β get).commandState
def setParserState (ps : Parser.ModuleParserState) : FrontendM Unit := modify fun s => { s with parserState := ps }
def setMessages (msgs : MessageLog) : FrontendM Unit := modify fun s => { s with commandState := { s.commandState with messages := msgs } }
def getInputContext : FrontendM Parser.InputContext := do pure (β read).inputCtx
def processCommand : FrontendM Bool := do
updateCmdPos
let cmdState β getCommandState
let ictx β getInputContext
let pstate β getParserState
let scope := cmdState.scopes.head!
let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls }
let pos := ictx.fileMap.toPosition pstate.pos
match profileit "parsing" pos fun _ => Parser.parseCommand ictx pmctx pstate cmdState.messages with
| (cmd, ps, messages) =>
modify fun s => { s with commands := s.commands.push cmd }
setParserState ps
setMessages messages
if Parser.isEOI cmd || Parser.isExitCommand cmd then
pure true -- Done
else
profileitM IO.Error "elaboration" pos $ elabCommandAtFrontend cmd
pure false
partial def processCommands : FrontendM Unit := do
let done β processCommand
unless done do
processCommands
end Frontend
open Frontend
def IO.processCommands (inputCtx : Parser.InputContext) (parserState : Parser.ModuleParserState) (commandState : Command.State) : IO State := do
let (_, s) β (Frontend.processCommands.run { inputCtx := inputCtx }).run { commandState := commandState, parserState := parserState, cmdPos := parserState.pos }
pure s
def process (input : String) (env : Environment) (opts : Options) (fileName : Option String := none) : IO (Environment Γ MessageLog) := do
let fileName := fileName.getD "<input>"
let inputCtx := Parser.mkInputContext input fileName
let s β IO.processCommands inputCtx { : Parser.ModuleParserState } (Command.mkState env {} opts)
pure (s.commandState.env, s.commandState.messages)
@[export lean_process_input]
def processExport (env : Environment) (input : String) (opts : Options) (fileName : String) : IO (Environment Γ List Message) := do
let (env, messages) β process input env opts fileName
pure (env, messages.toList)
@[export lean_run_frontend]
def runFrontend (input : String) (opts : Options) (fileName : String) (mainModuleName : Name) : IO (Environment Γ List Message Γ Module) := do
let inputCtx := Parser.mkInputContext input fileName
let (header, parserState, messages) β Parser.parseHeader inputCtx
let (env, messages) β processHeader header opts messages inputCtx
let env := env.setMainModule mainModuleName
let s β IO.processCommands inputCtx parserState (Command.mkState env messages opts)
pure (s.commandState.env, s.commandState.messages.toList, { header := header, commands := s.commands })
end Lean.Elab
|
c0e9e1209883b3b7bc0025d926fa896d0ca9d532 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/topology/G_delta.lean | d083170bcbafd0cd4269ea83437b381f892a220a | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 6,947 | lean | /-
Copyright (c) 2019 SΓ©bastien GouΓ«zel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: SΓ©bastien GouΓ«zel, Yury Kudryashov
-/
import topology.uniform_space.basic
import topology.separation
/-!
# `GΞ΄` sets
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define `GΞ΄` sets and prove their basic properties.
## Main definitions
* `is_GΞ΄`: a set `s` is a `GΞ΄` set if it can be represented as an intersection
of countably many open sets;
* `residual`: the filter of residual sets. A set `s` is called *residual* if it includes a dense
`GΞ΄` set. In a Baire space (e.g., in a complete (e)metric space), residual sets form a filter.
For technical reasons, we define `residual` in any topological space but the definition agrees
with the description above only in Baire spaces.
## Main results
We prove that finite or countable intersections of GΞ΄ sets is a GΞ΄ set. We also prove that the
continuity set of a function from a topological space to an (e)metric space is a GΞ΄ set.
## Tags
GΞ΄ set, residual set
-/
noncomputable theory
open_locale classical topology filter uniformity
open filter encodable set
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {ΞΉ : Type*}
section is_GΞ΄
variable [topological_space Ξ±]
/-- A GΞ΄ set is a countable intersection of open sets. -/
def is_GΞ΄ (s : set Ξ±) : Prop :=
βT : set (set Ξ±), (βt β T, is_open t) β§ T.countable β§ s = (ββ T)
/-- An open set is a GΞ΄ set. -/
lemma is_open.is_GΞ΄ {s : set Ξ±} (h : is_open s) : is_GΞ΄ s :=
β¨{s}, by simp [h], countable_singleton _, (set.sInter_singleton _).symmβ©
@[simp] lemma is_GΞ΄_empty : is_GΞ΄ (β
: set Ξ±) := is_open_empty.is_GΞ΄
@[simp] lemma is_GΞ΄_univ : is_GΞ΄ (univ : set Ξ±) := is_open_univ.is_GΞ΄
lemma is_GΞ΄_bInter_of_open {I : set ΞΉ} (hI : I.countable) {f : ΞΉ β set Ξ±}
(hf : βi β I, is_open (f i)) : is_GΞ΄ (βiβI, f i) :=
β¨f '' I, by rwa ball_image_iff, hI.image _, by rw sInter_imageβ©
lemma is_GΞ΄_Inter_of_open [encodable ΞΉ] {f : ΞΉ β set Ξ±}
(hf : βi, is_open (f i)) : is_GΞ΄ (βi, f i) :=
β¨range f, by rwa forall_range_iff, countable_range _, by rw sInter_rangeβ©
/-- The intersection of an encodable family of GΞ΄ sets is a GΞ΄ set. -/
lemma is_GΞ΄_Inter [encodable ΞΉ] {s : ΞΉ β set Ξ±} (hs : β i, is_GΞ΄ (s i)) : is_GΞ΄ (β i, s i) :=
begin
choose T hTo hTc hTs using hs,
obtain rfl : s = Ξ» i, ββ T i := funext hTs,
refine β¨β i, T i, _, countable_Union hTc, (sInter_Union _).symmβ©,
simpa [@forall_swap ΞΉ] using hTo
end
lemma is_GΞ΄_bInter {s : set ΞΉ} (hs : s.countable) {t : Ξ i β s, set Ξ±}
(ht : β i β s, is_GΞ΄ (t i βΉ_βΊ)) : is_GΞ΄ (β i β s, t i βΉ_βΊ) :=
begin
rw [bInter_eq_Inter],
haveI := hs.to_encodable,
exact is_GΞ΄_Inter (Ξ» x, ht x x.2)
end
/-- A countable intersection of GΞ΄ sets is a GΞ΄ set. -/
lemma is_GΞ΄_sInter {S : set (set Ξ±)} (h : βsβS, is_GΞ΄ s) (hS : S.countable) : is_GΞ΄ (ββ S) :=
by simpa only [sInter_eq_bInter] using is_GΞ΄_bInter hS h
lemma is_GΞ΄.inter {s t : set Ξ±} (hs : is_GΞ΄ s) (ht : is_GΞ΄ t) : is_GΞ΄ (s β© t) :=
by { rw inter_eq_Inter, exact is_GΞ΄_Inter (bool.forall_bool.2 β¨ht, hsβ©) }
/-- The union of two GΞ΄ sets is a GΞ΄ set. -/
lemma is_GΞ΄.union {s t : set Ξ±} (hs : is_GΞ΄ s) (ht : is_GΞ΄ t) : is_GΞ΄ (s βͺ t) :=
begin
rcases hs with β¨S, Sopen, Scount, rflβ©,
rcases ht with β¨T, Topen, Tcount, rflβ©,
rw [sInter_union_sInter],
apply is_GΞ΄_bInter_of_open (Scount.prod Tcount),
rintros β¨a, bβ© β¨ha, hbβ©,
exact (Sopen a ha).union (Topen b hb)
end
/-- The union of finitely many GΞ΄ sets is a GΞ΄ set. -/
lemma is_GΞ΄_bUnion {s : set ΞΉ} (hs : s.finite) {f : ΞΉ β set Ξ±} (h : β i β s, is_GΞ΄ (f i)) :
is_GΞ΄ (β i β s, f i) :=
begin
refine finite.induction_on hs (by simp) _ h,
simp only [ball_insert_iff, bUnion_insert],
exact Ξ» a s _ _ ihs H, H.1.union (ihs H.2)
end
lemma is_closed.is_GΞ΄ {Ξ±} [uniform_space Ξ±] [is_countably_generated (π€ Ξ±)]
{s : set Ξ±} (hs : is_closed s) : is_GΞ΄ s :=
begin
rcases (@uniformity_has_basis_open Ξ± _).exists_antitone_subbasis with β¨U, hUo, hU, -β©,
rw [β hs.closure_eq, β hU.bInter_bUnion_ball],
refine is_GΞ΄_bInter (to_countable _) (Ξ» n hn, is_open.is_GΞ΄ _),
exact is_open_bUnion (Ξ» x hx, uniform_space.is_open_ball _ (hUo _).2)
end
section t1_space
variable [t1_space Ξ±]
lemma is_GΞ΄_compl_singleton (a : Ξ±) : is_GΞ΄ ({a}αΆ : set Ξ±) :=
is_open_compl_singleton.is_GΞ΄
lemma set.countable.is_GΞ΄_compl {s : set Ξ±} (hs : s.countable) : is_GΞ΄ sαΆ :=
begin
rw [β bUnion_of_singleton s, compl_Unionβ],
exact is_GΞ΄_bInter hs (Ξ» x _, is_GΞ΄_compl_singleton x)
end
lemma set.finite.is_GΞ΄_compl {s : set Ξ±} (hs : s.finite) : is_GΞ΄ sαΆ :=
hs.countable.is_GΞ΄_compl
lemma set.subsingleton.is_GΞ΄_compl {s : set Ξ±} (hs : s.subsingleton) : is_GΞ΄ sαΆ :=
hs.finite.is_GΞ΄_compl
lemma finset.is_GΞ΄_compl (s : finset Ξ±) : is_GΞ΄ (sαΆ : set Ξ±) :=
s.finite_to_set.is_GΞ΄_compl
open topological_space
variables [first_countable_topology Ξ±]
lemma is_GΞ΄_singleton (a : Ξ±) : is_GΞ΄ ({a} : set Ξ±) :=
begin
rcases (nhds_basis_opens a).exists_antitone_subbasis with β¨U, hU, h_basisβ©,
rw [β bInter_basis_nhds h_basis.to_has_basis],
exact is_GΞ΄_bInter (to_countable _) (Ξ» n hn, (hU n).2.is_GΞ΄),
end
lemma set.finite.is_GΞ΄ {s : set Ξ±} (hs : s.finite) : is_GΞ΄ s :=
finite.induction_on hs is_GΞ΄_empty $ Ξ» a s _ _ hs, (is_GΞ΄_singleton a).union hs
end t1_space
end is_GΞ΄
section continuous_at
open topological_space
open_locale uniformity
variables [topological_space Ξ±]
/-- The set of points where a function is continuous is a GΞ΄ set. -/
lemma is_GΞ΄_set_of_continuous_at [uniform_space Ξ²] [is_countably_generated (π€ Ξ²)] (f : Ξ± β Ξ²) :
is_GΞ΄ {x | continuous_at f x} :=
begin
obtain β¨U, hUo, hUβ© := (@uniformity_has_basis_open_symmetric Ξ² _).exists_antitone_subbasis,
simp only [uniform.continuous_at_iff_prod, nhds_prod_eq],
simp only [(nhds_basis_opens _).prod_self.tendsto_iff hU.to_has_basis, forall_prop_of_true,
set_of_forall, id],
refine is_GΞ΄_Inter (Ξ» k, is_open.is_GΞ΄ $ is_open_iff_mem_nhds.2 $ Ξ» x, _),
rintros β¨s, β¨hsx, hsoβ©, hsUβ©,
filter_upwards [is_open.mem_nhds hso hsx] with _ hy using β¨s, β¨hy, hsoβ©, hsUβ©,
end
end continuous_at
/-- A set `s` is called *residual* if it includes a dense `GΞ΄` set. If `Ξ±` is a Baire space
(e.g., a complete metric space), then residual sets form a filter, see `mem_residual`.
For technical reasons we define the filter `residual` in any topological space but in a non-Baire
space it is not useful because it may contain some non-residual sets. -/
def residual (Ξ± : Type*) [topological_space Ξ±] : filter Ξ± :=
β¨
t (ht : is_GΞ΄ t) (ht' : dense t), π t
|
3f30afe57e461329296762de6fcbdfd85633ae17 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/tactic/norm_num.lean | 0d70e6fa9d0b2cf14dca6f7bda3c81ef4e60b840 | [
"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 | 69,492 | lean | /-
Copyright (c) 2017 Simon Hudon All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Mario Carneiro
-/
import data.rat.cast
import data.rat.meta_defs
/-!
# `norm_num`
Evaluating arithmetic expressions including `*`, `+`, `-`, `^`, `β€`.
-/
universes u v w
namespace tactic
namespace instance_cache
/-- Faster version of `mk_app ``bit0 [e]`. -/
meta def mk_bit0 (c : instance_cache) (e : expr) : tactic (instance_cache Γ expr) :=
do (c, ai) β c.get ``has_add,
return (c, (expr.const ``bit0 [c.univ]).mk_app [c.Ξ±, ai, e])
/-- Faster version of `mk_app ``bit1 [e]`. -/
meta def mk_bit1 (c : instance_cache) (e : expr) : tactic (instance_cache Γ expr) :=
do (c, ai) β c.get ``has_add,
(c, oi) β c.get ``has_one,
return (c, (expr.const ``bit1 [c.univ]).mk_app [c.Ξ±, oi, ai, e])
end instance_cache
end tactic
open tactic
/-!
Each lemma in this file is written the way it is to exactly match (with no defeq reduction allowed)
the conclusion of some lemma generated by the proof procedure that uses it. That proof procedure
should describe the shape of the generated lemma in its docstring.
-/
namespace norm_num
variable {Ξ± : Type u}
lemma subst_into_add {Ξ±} [has_add Ξ±] (l r tl tr t)
(prl : (l : Ξ±) = tl) (prr : r = tr) (prt : tl + tr = t) : l + r = t :=
by rw [prl, prr, prt]
lemma subst_into_mul {Ξ±} [has_mul Ξ±] (l r tl tr t)
(prl : (l : Ξ±) = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t :=
by rw [prl, prr, prt]
lemma subst_into_neg {Ξ±} [has_neg Ξ±] (a ta t : Ξ±) (pra : a = ta) (prt : -ta = t) : -a = t :=
by simp [pra, prt]
/-- The result type of `match_numeral`, either `0`, `1`, or a top level
decomposition of `bit0 e` or `bit1 e`. The `other` case means it is not a numeral. -/
meta inductive match_numeral_result
| zero | one | bit0 (e : expr) | bit1 (e : expr) | other
/-- Unfold the top level constructor of the numeral expression. -/
meta def match_numeral : expr β match_numeral_result
| `(bit0 %%e) := match_numeral_result.bit0 e
| `(bit1 %%e) := match_numeral_result.bit1 e
| `(@has_zero.zero _ _) := match_numeral_result.zero
| `(@has_one.one _ _) := match_numeral_result.one
| _ := match_numeral_result.other
theorem zero_succ {Ξ±} [semiring Ξ±] : (0 + 1 : Ξ±) = 1 := zero_add _
theorem one_succ {Ξ±} [semiring Ξ±] : (1 + 1 : Ξ±) = 2 := rfl
theorem bit0_succ {Ξ±} [semiring Ξ±] (a : Ξ±) : bit0 a + 1 = bit1 a := rfl
theorem bit1_succ {Ξ±} [semiring Ξ±] (a b : Ξ±) (h : a + 1 = b) : bit1 a + 1 = bit0 b :=
h βΈ by simp [bit1, bit0, add_left_comm, add_assoc]
section
open match_numeral_result
/-- Given `a`, `b` natural numerals, proves `β’ a + 1 = b`, assuming that this is provable.
(It may prove garbage instead of failing if `a + 1 = b` is false.) -/
meta def prove_succ : instance_cache β expr β expr β tactic (instance_cache Γ expr)
| c e r := match match_numeral e with
| zero := c.mk_app ``zero_succ []
| one := c.mk_app ``one_succ []
| bit0 e := c.mk_app ``bit0_succ [e]
| bit1 e := do
let r := r.app_arg,
(c, p) β prove_succ c e r,
c.mk_app ``bit1_succ [e, r, p]
| _ := failed
end
end
/-- Given `a` natural numeral, returns `(b, β’ a + 1 = b)`. -/
meta def prove_succ' (c : instance_cache) (a : expr) : tactic (instance_cache Γ expr Γ expr) :=
do na β a.to_nat,
(c, b) β c.of_nat (na + 1),
(c, p) β prove_succ c a b,
return (c, b, p)
theorem zero_adc {Ξ±} [semiring Ξ±] (a b : Ξ±) (h : a + 1 = b) : 0 + a + 1 = b := by rwa zero_add
theorem adc_zero {Ξ±} [semiring Ξ±] (a b : Ξ±) (h : a + 1 = b) : a + 0 + 1 = b := by rwa add_zero
theorem one_add {Ξ±} [semiring Ξ±] (a b : Ξ±) (h : a + 1 = b) : 1 + a = b := by rwa add_comm
theorem add_bit0_bit0 {Ξ±} [semiring Ξ±] (a b c : Ξ±) (h : a + b = c) : bit0 a + bit0 b = bit0 c :=
h βΈ by simp [bit0, add_left_comm, add_assoc]
theorem add_bit0_bit1 {Ξ±} [semiring Ξ±] (a b c : Ξ±) (h : a + b = c) : bit0 a + bit1 b = bit1 c :=
h βΈ by simp [bit0, bit1, add_left_comm, add_assoc]
theorem add_bit1_bit0 {Ξ±} [semiring Ξ±] (a b c : Ξ±) (h : a + b = c) : bit1 a + bit0 b = bit1 c :=
h βΈ by simp [bit0, bit1, add_left_comm, add_comm, add_assoc]
theorem add_bit1_bit1 {Ξ±} [semiring Ξ±] (a b c : Ξ±) (h : a + b + 1 = c) : bit1 a + bit1 b = bit0 c :=
h βΈ by simp [bit0, bit1, add_left_comm, add_comm, add_assoc]
theorem adc_one_one {Ξ±} [semiring Ξ±] : (1 + 1 + 1 : Ξ±) = 3 := rfl
theorem adc_bit0_one {Ξ±} [semiring Ξ±] (a b : Ξ±) (h : a + 1 = b) : bit0 a + 1 + 1 = bit0 b :=
h βΈ by simp [bit0, add_left_comm, add_assoc]
theorem adc_one_bit0 {Ξ±} [semiring Ξ±] (a b : Ξ±) (h : a + 1 = b) : 1 + bit0 a + 1 = bit0 b :=
h βΈ by simp [bit0, add_left_comm, add_assoc]
theorem adc_bit1_one {Ξ±} [semiring Ξ±] (a b : Ξ±) (h : a + 1 = b) : bit1 a + 1 + 1 = bit1 b :=
h βΈ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_one_bit1 {Ξ±} [semiring Ξ±] (a b : Ξ±) (h : a + 1 = b) : 1 + bit1 a + 1 = bit1 b :=
h βΈ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit0_bit0 {Ξ±} [semiring Ξ±] (a b c : Ξ±) (h : a + b = c) : bit0 a + bit0 b + 1 = bit1 c :=
h βΈ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit1_bit0 {Ξ±} [semiring Ξ±] (a b c : Ξ±) (h : a + b + 1 = c) :
bit1 a + bit0 b + 1 = bit0 c :=
h βΈ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit0_bit1 {Ξ±} [semiring Ξ±] (a b c : Ξ±) (h : a + b + 1 = c) :
bit0 a + bit1 b + 1 = bit0 c :=
h βΈ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit1_bit1 {Ξ±} [semiring Ξ±] (a b c : Ξ±) (h : a + b + 1 = c) :
bit1 a + bit1 b + 1 = bit1 c :=
h βΈ by simp [bit1, bit0, add_left_comm, add_assoc]
section
open match_numeral_result
meta mutual def prove_add_nat, prove_adc_nat
with prove_add_nat : instance_cache β expr β expr β expr β tactic (instance_cache Γ expr)
| c a b r := do
match match_numeral a, match_numeral b with
| zero, _ := c.mk_app ``zero_add [b]
| _, zero := c.mk_app ``add_zero [a]
| _, one := prove_succ c a r
| one, _ := do (c, p) β prove_succ c b r, c.mk_app ``one_add [b, r, p]
| bit0 a, bit0 b :=
do let r := r.app_arg, (c, p) β prove_add_nat c a b r, c.mk_app ``add_bit0_bit0 [a, b, r, p]
| bit0 a, bit1 b :=
do let r := r.app_arg, (c, p) β prove_add_nat c a b r, c.mk_app ``add_bit0_bit1 [a, b, r, p]
| bit1 a, bit0 b :=
do let r := r.app_arg, (c, p) β prove_add_nat c a b r, c.mk_app ``add_bit1_bit0 [a, b, r, p]
| bit1 a, bit1 b :=
do let r := r.app_arg, (c, p) β prove_adc_nat c a b r, c.mk_app ``add_bit1_bit1 [a, b, r, p]
| _, _ := failed
end
with prove_adc_nat : instance_cache β expr β expr β expr β tactic (instance_cache Γ expr)
| c a b r := do
match match_numeral a, match_numeral b with
| zero, _ := do (c, p) β prove_succ c b r, c.mk_app ``zero_adc [b, r, p]
| _, zero := do (c, p) β prove_succ c b r, c.mk_app ``adc_zero [b, r, p]
| one, one := c.mk_app ``adc_one_one []
| bit0 a, one :=
do let r := r.app_arg, (c, p) β prove_succ c a r, c.mk_app ``adc_bit0_one [a, r, p]
| one, bit0 b :=
do let r := r.app_arg, (c, p) β prove_succ c b r, c.mk_app ``adc_one_bit0 [b, r, p]
| bit1 a, one :=
do let r := r.app_arg, (c, p) β prove_succ c a r, c.mk_app ``adc_bit1_one [a, r, p]
| one, bit1 b :=
do let r := r.app_arg, (c, p) β prove_succ c b r, c.mk_app ``adc_one_bit1 [b, r, p]
| bit0 a, bit0 b :=
do let r := r.app_arg, (c, p) β prove_add_nat c a b r, c.mk_app ``adc_bit0_bit0 [a, b, r, p]
| bit0 a, bit1 b :=
do let r := r.app_arg, (c, p) β prove_adc_nat c a b r, c.mk_app ``adc_bit0_bit1 [a, b, r, p]
| bit1 a, bit0 b :=
do let r := r.app_arg, (c, p) β prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit0 [a, b, r, p]
| bit1 a, bit1 b :=
do let r := r.app_arg, (c, p) β prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit1 [a, b, r, p]
| _, _ := failed
end
/-- Given `a`,`b`,`r` natural numerals, proves `β’ a + b = r`. -/
add_decl_doc prove_add_nat
/-- Given `a`,`b`,`r` natural numerals, proves `β’ a + b + 1 = r`. -/
add_decl_doc prove_adc_nat
/-- Given `a`,`b` natural numerals, returns `(r, β’ a + b = r)`. -/
meta def prove_add_nat' (c : instance_cache) (a b : expr) : tactic (instance_cache Γ expr Γ expr) :=
do na β a.to_nat,
nb β b.to_nat,
(c, r) β c.of_nat (na + nb),
(c, p) β prove_add_nat c a b r,
return (c, r, p)
end
theorem bit0_mul {Ξ±} [semiring Ξ±] (a b c : Ξ±) (h : a * b = c) :
bit0 a * b = bit0 c := h βΈ by simp [bit0, add_mul]
theorem mul_bit0' {Ξ±} [semiring Ξ±] (a b c : Ξ±) (h : a * b = c) :
a * bit0 b = bit0 c := h βΈ by simp [bit0, mul_add]
theorem mul_bit0_bit0 {Ξ±} [semiring Ξ±] (a b c : Ξ±) (h : a * b = c) :
bit0 a * bit0 b = bit0 (bit0 c) := bit0_mul _ _ _ (mul_bit0' _ _ _ h)
theorem mul_bit1_bit1 {Ξ±} [semiring Ξ±] (a b c d e : Ξ±)
(hc : a * b = c) (hd : a + b = d) (he : bit0 c + d = e) :
bit1 a * bit1 b = bit1 e :=
by rw [β he, β hd, β hc]; simp [bit1, bit0, mul_add, add_mul, add_left_comm, add_assoc]
section
open match_numeral_result
/-- Given `a`,`b` natural numerals, returns `(r, β’ a * b = r)`. -/
meta def prove_mul_nat : instance_cache β expr β expr β tactic (instance_cache Γ expr Γ expr)
| ic a b :=
match match_numeral a, match_numeral b with
| zero, _ := do
(ic, z) β ic.mk_app ``has_zero.zero [],
(ic, p) β ic.mk_app ``zero_mul [b],
return (ic, z, p)
| _, zero := do
(ic, z) β ic.mk_app ``has_zero.zero [],
(ic, p) β ic.mk_app ``mul_zero [a],
return (ic, z, p)
| one, _ := do (ic, p) β ic.mk_app ``one_mul [b], return (ic, b, p)
| _, one := do (ic, p) β ic.mk_app ``mul_one [a], return (ic, a, p)
| bit0 a, bit0 b := do
(ic, c, p) β prove_mul_nat ic a b,
(ic, p) β ic.mk_app ``mul_bit0_bit0 [a, b, c, p],
(ic, c') β ic.mk_bit0 c,
(ic, c') β ic.mk_bit0 c',
return (ic, c', p)
| bit0 a, _ := do
(ic, c, p) β prove_mul_nat ic a b,
(ic, p) β ic.mk_app ``bit0_mul [a, b, c, p],
(ic, c') β ic.mk_bit0 c,
return (ic, c', p)
| _, bit0 b := do
(ic, c, p) β prove_mul_nat ic a b,
(ic, p) β ic.mk_app ``mul_bit0' [a, b, c, p],
(ic, c') β ic.mk_bit0 c,
return (ic, c', p)
| bit1 a, bit1 b := do
(ic, c, pc) β prove_mul_nat ic a b,
(ic, d, pd) β prove_add_nat' ic a b,
(ic, c') β ic.mk_bit0 c,
(ic, e, pe) β prove_add_nat' ic c' d,
(ic, p) β ic.mk_app ``mul_bit1_bit1 [a, b, c, d, e, pc, pd, pe],
(ic, e') β ic.mk_bit1 e,
return (ic, e', p)
| _, _ := failed
end
end
section
open match_numeral_result
/-- Given `a` a positive natural numeral, returns `β’ 0 < a`. -/
meta def prove_pos_nat (c : instance_cache) : expr β tactic (instance_cache Γ expr)
| e :=
match match_numeral e with
| one := c.mk_app ``zero_lt_one' []
| bit0 e := do (c, p) β prove_pos_nat e, c.mk_app ``bit0_pos [e, p]
| bit1 e := do (c, p) β prove_pos_nat e, c.mk_app ``bit1_pos' [e, p]
| _ := failed
end
end
/-- Given `a` a rational numeral, returns `β’ 0 < a`. -/
meta def prove_pos (c : instance_cache) : expr β tactic (instance_cache Γ expr)
| `(%%eβ / %%eβ) := do
(c, pβ) β prove_pos_nat c eβ, (c, pβ) β prove_pos_nat c eβ,
c.mk_app ``div_pos [eβ, eβ, pβ, pβ]
| e := prove_pos_nat c e
/-- `match_neg (- e) = some e`, otherwise `none` -/
meta def match_neg : expr β option expr
| `(- %%e) := some e
| _ := none
/-- `match_sign (- e) = inl e`, `match_sign 0 = inr ff`, otherwise `inr tt` -/
meta def match_sign : expr β expr β bool
| `(- %%e) := sum.inl e
| `(has_zero.zero) := sum.inr ff
| _ := sum.inr tt
theorem ne_zero_of_pos {Ξ±} [ordered_add_comm_group Ξ±] (a : Ξ±) : 0 < a β a β 0 := ne_of_gt
theorem ne_zero_neg {Ξ±} [add_group Ξ±] (a : Ξ±) : a β 0 β -a β 0 := mt neg_eq_zero.1
/-- Given `a` a rational numeral, returns `β’ a β 0`. -/
meta def prove_ne_zero' (c : instance_cache) : expr β tactic (instance_cache Γ expr)
| a :=
match match_neg a with
| some a := do (c, p) β prove_ne_zero' a, c.mk_app ``ne_zero_neg [a, p]
| none := do (c, p) β prove_pos c a, c.mk_app ``ne_zero_of_pos [a, p]
end
theorem clear_denom_div {Ξ±} [division_ring Ξ±] (a b b' c d : Ξ±)
(hβ : b β 0) (hβ : b * b' = d) (hβ : a * b' = c) : (a / b) * d = c :=
by rwa [β hβ, β mul_assoc, div_mul_cancel _ hβ]
/-- Given `a` nonnegative rational and `d` a natural number, returns `(b, β’ a * d = b)`.
(`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/
meta def prove_clear_denom'
(prove_ne_zero : instance_cache β expr β β β tactic (instance_cache Γ expr))
(c : instance_cache) (a d : expr) (na : β) (nd : β) :
tactic (instance_cache Γ expr Γ expr) :=
if na.denom = 1 then
prove_mul_nat c a d
else do
[_, _, a, b] β return a.get_app_args,
(c, b') β c.of_nat (nd / na.denom),
(c, pβ) β prove_ne_zero c b (rat.of_int na.denom),
(c, _, pβ) β prove_mul_nat c b b',
(c, r, pβ) β prove_mul_nat c a b',
(c, p) β c.mk_app ``clear_denom_div [a, b, b', r, d, pβ, pβ, pβ],
return (c, r, p)
theorem nonneg_pos {Ξ±} [ordered_cancel_add_comm_monoid Ξ±] (a : Ξ±) : 0 < a β 0 β€ a := le_of_lt
theorem lt_one_bit0 {Ξ±} [linear_ordered_semiring Ξ±] (a : Ξ±) (h : 1 β€ a) : 1 < bit0 a :=
lt_of_lt_of_le one_lt_two (bit0_le_bit0.2 h)
theorem lt_one_bit1 {Ξ±} [linear_ordered_semiring Ξ±] (a : Ξ±) (h : 0 < a) : 1 < bit1 a :=
one_lt_bit1.2 h
theorem lt_bit0_bit0 {Ξ±} [linear_ordered_semiring Ξ±] (a b : Ξ±) : a < b β bit0 a < bit0 b :=
bit0_lt_bit0.2
theorem lt_bit0_bit1 {Ξ±} [linear_ordered_semiring Ξ±] (a b : Ξ±) (h : a β€ b) : bit0 a < bit1 b :=
lt_of_le_of_lt (bit0_le_bit0.2 h) (lt_add_one _)
theorem lt_bit1_bit0 {Ξ±} [linear_ordered_semiring Ξ±] (a b : Ξ±) (h : a + 1 β€ b) : bit1 a < bit0 b :=
lt_of_lt_of_le (by simp [bit0, bit1, zero_lt_one, add_assoc]) (bit0_le_bit0.2 h)
theorem lt_bit1_bit1 {Ξ±} [linear_ordered_semiring Ξ±] (a b : Ξ±) : a < b β bit1 a < bit1 b :=
bit1_lt_bit1.2
theorem le_one_bit0 {Ξ±} [linear_ordered_semiring Ξ±] (a : Ξ±) (h : 1 β€ a) : 1 β€ bit0 a :=
le_of_lt (lt_one_bit0 _ h)
-- deliberately strong hypothesis because bit1 0 is not a numeral
theorem le_one_bit1 {Ξ±} [linear_ordered_semiring Ξ±] (a : Ξ±) (h : 0 < a) : 1 β€ bit1 a :=
le_of_lt (lt_one_bit1 _ h)
theorem le_bit0_bit0 {Ξ±} [linear_ordered_semiring Ξ±] (a b : Ξ±) : a β€ b β bit0 a β€ bit0 b :=
bit0_le_bit0.2
theorem le_bit0_bit1 {Ξ±} [linear_ordered_semiring Ξ±] (a b : Ξ±) (h : a β€ b) : bit0 a β€ bit1 b :=
le_of_lt (lt_bit0_bit1 _ _ h)
theorem le_bit1_bit0 {Ξ±} [linear_ordered_semiring Ξ±] (a b : Ξ±) (h : a + 1 β€ b) : bit1 a β€ bit0 b :=
le_of_lt (lt_bit1_bit0 _ _ h)
theorem le_bit1_bit1 {Ξ±} [linear_ordered_semiring Ξ±] (a b : Ξ±) : a β€ b β bit1 a β€ bit1 b :=
bit1_le_bit1.2
theorem sle_one_bit0 {Ξ±} [linear_ordered_semiring Ξ±] (a : Ξ±) : 1 β€ a β 1 + 1 β€ bit0 a :=
bit0_le_bit0.2
theorem sle_one_bit1 {Ξ±} [linear_ordered_semiring Ξ±] (a : Ξ±) : 1 β€ a β 1 + 1 β€ bit1 a :=
le_bit0_bit1 _ _
theorem sle_bit0_bit0 {Ξ±} [linear_ordered_semiring Ξ±] (a b : Ξ±) : a + 1 β€ b β bit0 a + 1 β€ bit0 b :=
le_bit1_bit0 _ _
theorem sle_bit0_bit1 {Ξ±} [linear_ordered_semiring Ξ±] (a b : Ξ±) (h : a β€ b) : bit0 a + 1 β€ bit1 b :=
bit1_le_bit1.2 h
theorem sle_bit1_bit0 {Ξ±} [linear_ordered_semiring Ξ±] (a b : Ξ±) (h : a + 1 β€ b) :
bit1 a + 1 β€ bit0 b :=
(bit1_succ a _ rfl).symm βΈ bit0_le_bit0.2 h
theorem sle_bit1_bit1 {Ξ±} [linear_ordered_semiring Ξ±] (a b : Ξ±) (h : a + 1 β€ b) :
bit1 a + 1 β€ bit1 b :=
(bit1_succ a _ rfl).symm βΈ le_bit0_bit1 _ _ h
/-- Given `a` a rational numeral, returns `β’ 0 β€ a`. -/
meta def prove_nonneg (ic : instance_cache) : expr β tactic (instance_cache Γ expr)
| e@`(has_zero.zero) := ic.mk_app ``le_refl [e]
| e :=
if ic.Ξ± = `(β) then
return (ic, `(nat.zero_le).mk_app [e])
else do
(ic, p) β prove_pos ic e,
ic.mk_app ``nonneg_pos [e, p]
section
open match_numeral_result
/-- Given `a` a rational numeral, returns `β’ 1 β€ a`. -/
meta def prove_one_le_nat (ic : instance_cache) : expr β tactic (instance_cache Γ expr)
| a :=
match match_numeral a with
| one := ic.mk_app ``le_refl [a]
| bit0 a := do (ic, p) β prove_one_le_nat a, ic.mk_app ``le_one_bit0 [a, p]
| bit1 a := do (ic, p) β prove_pos_nat ic a, ic.mk_app ``le_one_bit1 [a, p]
| _ := failed
end
meta mutual def prove_le_nat, prove_sle_nat (ic : instance_cache)
with prove_le_nat : expr β expr β tactic (instance_cache Γ expr)
| a b :=
if a = b then ic.mk_app ``le_refl [a] else
match match_numeral a, match_numeral b with
| zero, _ := prove_nonneg ic b
| one, bit0 b := do (ic, p) β prove_one_le_nat ic b, ic.mk_app ``le_one_bit0 [b, p]
| one, bit1 b := do (ic, p) β prove_pos_nat ic b, ic.mk_app ``le_one_bit1 [b, p]
| bit0 a, bit0 b := do (ic, p) β prove_le_nat a b, ic.mk_app ``le_bit0_bit0 [a, b, p]
| bit0 a, bit1 b := do (ic, p) β prove_le_nat a b, ic.mk_app ``le_bit0_bit1 [a, b, p]
| bit1 a, bit0 b := do (ic, p) β prove_sle_nat a b, ic.mk_app ``le_bit1_bit0 [a, b, p]
| bit1 a, bit1 b := do (ic, p) β prove_le_nat a b, ic.mk_app ``le_bit1_bit1 [a, b, p]
| _, _ := failed
end
with prove_sle_nat : expr β expr β tactic (instance_cache Γ expr)
| a b :=
match match_numeral a, match_numeral b with
| zero, _ := prove_nonneg ic b
| one, bit0 b := do (ic, p) β prove_one_le_nat ic b, ic.mk_app ``sle_one_bit0 [b, p]
| one, bit1 b := do (ic, p) β prove_one_le_nat ic b, ic.mk_app ``sle_one_bit1 [b, p]
| bit0 a, bit0 b := do (ic, p) β prove_sle_nat a b, ic.mk_app ``sle_bit0_bit0 [a, b, p]
| bit0 a, bit1 b := do (ic, p) β prove_le_nat a b, ic.mk_app ``sle_bit0_bit1 [a, b, p]
| bit1 a, bit0 b := do (ic, p) β prove_sle_nat a b, ic.mk_app ``sle_bit1_bit0 [a, b, p]
| bit1 a, bit1 b := do (ic, p) β prove_sle_nat a b, ic.mk_app ``sle_bit1_bit1 [a, b, p]
| _, _ := failed
end
/-- Given `a`,`b` natural numerals, proves `β’ a β€ b`. -/
add_decl_doc prove_le_nat
/-- Given `a`,`b` natural numerals, proves `β’ a + 1 β€ b`. -/
add_decl_doc prove_sle_nat
/-- Given `a`,`b` natural numerals, proves `β’ a < b`. -/
meta def prove_lt_nat (ic : instance_cache) : expr β expr β tactic (instance_cache Γ expr)
| a b :=
match match_numeral a, match_numeral b with
| zero, _ := prove_pos ic b
| one, bit0 b := do (ic, p) β prove_one_le_nat ic b, ic.mk_app ``lt_one_bit0 [b, p]
| one, bit1 b := do (ic, p) β prove_pos_nat ic b, ic.mk_app ``lt_one_bit1 [b, p]
| bit0 a, bit0 b := do (ic, p) β prove_lt_nat a b, ic.mk_app ``lt_bit0_bit0 [a, b, p]
| bit0 a, bit1 b := do (ic, p) β prove_le_nat ic a b, ic.mk_app ``lt_bit0_bit1 [a, b, p]
| bit1 a, bit0 b := do (ic, p) β prove_sle_nat ic a b, ic.mk_app ``lt_bit1_bit0 [a, b, p]
| bit1 a, bit1 b := do (ic, p) β prove_lt_nat a b, ic.mk_app ``lt_bit1_bit1 [a, b, p]
| _, _ := failed
end
end
theorem clear_denom_lt {Ξ±} [linear_ordered_semiring Ξ±] (a a' b b' d : Ξ±)
(hβ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' < b') : a < b :=
lt_of_mul_lt_mul_right (by rwa [ha, hb]) (le_of_lt hβ)
/-- Given `a`,`b` nonnegative rational numerals, proves `β’ a < b`. -/
meta def prove_lt_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : β) :
tactic (instance_cache Γ expr) :=
if na.denom = 1 β§ nb.denom = 1 then
prove_lt_nat ic a b
else do
let nd := na.denom.lcm nb.denom,
(ic, d) β ic.of_nat nd,
(ic, pβ) β prove_pos ic d,
(ic, a', pa) β prove_clear_denom' (Ξ» ic e _, prove_ne_zero' ic e) ic a d na nd,
(ic, b', pb) β prove_clear_denom' (Ξ» ic e _, prove_ne_zero' ic e) ic b d nb nd,
(ic, p) β prove_lt_nat ic a' b',
ic.mk_app ``clear_denom_lt [a, a', b, b', d, pβ, pa, pb, p]
lemma lt_neg_pos {Ξ±} [ordered_add_comm_group Ξ±] (a b : Ξ±) (ha : 0 < a) (hb : 0 < b) : -a < b :=
lt_trans (neg_neg_of_pos ha) hb
/-- Given `a`,`b` rational numerals, proves `β’ a < b`. -/
meta def prove_lt_rat (ic : instance_cache) (a b : expr) (na nb : β) :
tactic (instance_cache Γ expr) :=
match match_sign a, match_sign b with
| sum.inl a, sum.inl b := do
-- we have to switch the order of `a` and `b` because `a < b β -b < -a`
(ic, p) β prove_lt_nonneg_rat ic b a (-nb) (-na),
ic.mk_app ``neg_lt_neg [b, a, p]
| sum.inl a, sum.inr ff := do
(ic, p) β prove_pos ic a,
ic.mk_app ``neg_neg_of_pos [a, p]
| sum.inl a, sum.inr tt := do
(ic, pa) β prove_pos ic a,
(ic, pb) β prove_pos ic b,
ic.mk_app ``lt_neg_pos [a, b, pa, pb]
| sum.inr ff, _ := prove_pos ic b
| sum.inr tt, _ := prove_lt_nonneg_rat ic a b na nb
end
theorem clear_denom_le {Ξ±} [linear_ordered_semiring Ξ±] (a a' b b' d : Ξ±)
(hβ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' β€ b') : a β€ b :=
le_of_mul_le_mul_right (by rwa [ha, hb]) hβ
/-- Given `a`,`b` nonnegative rational numerals, proves `β’ a β€ b`. -/
meta def prove_le_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : β) :
tactic (instance_cache Γ expr) :=
if na.denom = 1 β§ nb.denom = 1 then
prove_le_nat ic a b
else do
let nd := na.denom.lcm nb.denom,
(ic, d) β ic.of_nat nd,
(ic, pβ) β prove_pos ic d,
(ic, a', pa) β prove_clear_denom' (Ξ» ic e _, prove_ne_zero' ic e) ic a d na nd,
(ic, b', pb) β prove_clear_denom' (Ξ» ic e _, prove_ne_zero' ic e) ic b d nb nd,
(ic, p) β prove_le_nat ic a' b',
ic.mk_app ``clear_denom_le [a, a', b, b', d, pβ, pa, pb, p]
lemma le_neg_pos {Ξ±} [ordered_add_comm_group Ξ±] (a b : Ξ±) (ha : 0 β€ a) (hb : 0 β€ b) : -a β€ b :=
le_trans (neg_nonpos_of_nonneg ha) hb
/-- Given `a`,`b` rational numerals, proves `β’ a β€ b`. -/
meta def prove_le_rat (ic : instance_cache) (a b : expr) (na nb : β) :
tactic (instance_cache Γ expr) :=
match match_sign a, match_sign b with
| sum.inl a, sum.inl b := do
(ic, p) β prove_le_nonneg_rat ic a b (-na) (-nb),
ic.mk_app ``neg_le_neg [a, b, p]
| sum.inl a, sum.inr ff := do
(ic, p) β prove_nonneg ic a,
ic.mk_app ``neg_nonpos_of_nonneg [a, p]
| sum.inl a, sum.inr tt := do
(ic, pa) β prove_nonneg ic a,
(ic, pb) β prove_nonneg ic b,
ic.mk_app ``le_neg_pos [a, b, pa, pb]
| sum.inr ff, _ := prove_nonneg ic b
| sum.inr tt, _ := prove_le_nonneg_rat ic a b na nb
end
/-- Given `a`,`b` rational numerals, proves `β’ a β b`. This version tries to prove
`β’ a < b` or `β’ b < a`, and so is not appropriate for types without an order relation. -/
meta def prove_ne_rat (ic : instance_cache) (a b : expr) (na nb : β) :
tactic (instance_cache Γ expr) :=
if na < nb then do
(ic, p) β prove_lt_rat ic a b na nb,
ic.mk_app ``ne_of_lt [a, b, p]
else do
(ic, p) β prove_lt_rat ic b a nb na,
ic.mk_app ``ne_of_gt [a, b, p]
theorem nat_cast_zero {Ξ±} [semiring Ξ±] : β(0 : β) = (0 : Ξ±) := nat.cast_zero
theorem nat_cast_one {Ξ±} [semiring Ξ±] : β(1 : β) = (1 : Ξ±) := nat.cast_one
theorem nat_cast_bit0 {Ξ±} [semiring Ξ±] (a : β) (a' : Ξ±) (h : βa = a') : β(bit0 a) = bit0 a' :=
h βΈ nat.cast_bit0 _
theorem nat_cast_bit1 {Ξ±} [semiring Ξ±] (a : β) (a' : Ξ±) (h : βa = a') : β(bit1 a) = bit1 a' :=
h βΈ nat.cast_bit1 _
theorem int_cast_zero {Ξ±} [ring Ξ±] : β(0 : β€) = (0 : Ξ±) := int.cast_zero
theorem int_cast_one {Ξ±} [ring Ξ±] : β(1 : β€) = (1 : Ξ±) := int.cast_one
theorem int_cast_bit0 {Ξ±} [ring Ξ±] (a : β€) (a' : Ξ±) (h : βa = a') : β(bit0 a) = bit0 a' :=
h βΈ int.cast_bit0 _
theorem int_cast_bit1 {Ξ±} [ring Ξ±] (a : β€) (a' : Ξ±) (h : βa = a') : β(bit1 a) = bit1 a' :=
h βΈ int.cast_bit1 _
theorem rat_cast_bit0 {Ξ±} [division_ring Ξ±] [char_zero Ξ±] (a : β) (a' : Ξ±) (h : βa = a') :
β(bit0 a) = bit0 a' :=
h βΈ rat.cast_bit0 _
theorem rat_cast_bit1 {Ξ±} [division_ring Ξ±] [char_zero Ξ±] (a : β) (a' : Ξ±) (h : βa = a') :
β(bit1 a) = bit1 a' :=
h βΈ rat.cast_bit1 _
/-- Given `a' : Ξ±` a natural numeral, returns `(a : β, β’ βa = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_nat_uncast (ic nc : instance_cache) : β (a' : expr),
tactic (instance_cache Γ instance_cache Γ expr Γ expr)
| a' :=
match match_numeral a' with
| match_numeral_result.zero := do
(nc, e) β nc.mk_app ``has_zero.zero [],
(ic, p) β ic.mk_app ``nat_cast_zero [],
return (ic, nc, e, p)
| match_numeral_result.one := do
(nc, e) β nc.mk_app ``has_one.one [],
(ic, p) β ic.mk_app ``nat_cast_one [],
return (ic, nc, e, p)
| match_numeral_result.bit0 a' := do
(ic, nc, a, p) β prove_nat_uncast a',
(nc, a0) β nc.mk_bit0 a,
(ic, p) β ic.mk_app ``nat_cast_bit0 [a, a', p],
return (ic, nc, a0, p)
| match_numeral_result.bit1 a' := do
(ic, nc, a, p) β prove_nat_uncast a',
(nc, a1) β nc.mk_bit1 a,
(ic, p) β ic.mk_app ``nat_cast_bit1 [a, a', p],
return (ic, nc, a1, p)
| _ := failed
end
/-- Given `a' : Ξ±` a natural numeral, returns `(a : β€, β’ βa = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_int_uncast_nat (ic zc : instance_cache) : β (a' : expr),
tactic (instance_cache Γ instance_cache Γ expr Γ expr)
| a' :=
match match_numeral a' with
| match_numeral_result.zero := do
(zc, e) β zc.mk_app ``has_zero.zero [],
(ic, p) β ic.mk_app ``int_cast_zero [],
return (ic, zc, e, p)
| match_numeral_result.one := do
(zc, e) β zc.mk_app ``has_one.one [],
(ic, p) β ic.mk_app ``int_cast_one [],
return (ic, zc, e, p)
| match_numeral_result.bit0 a' := do
(ic, zc, a, p) β prove_int_uncast_nat a',
(zc, a0) β zc.mk_bit0 a,
(ic, p) β ic.mk_app ``int_cast_bit0 [a, a', p],
return (ic, zc, a0, p)
| match_numeral_result.bit1 a' := do
(ic, zc, a, p) β prove_int_uncast_nat a',
(zc, a1) β zc.mk_bit1 a,
(ic, p) β ic.mk_app ``int_cast_bit1 [a, a', p],
return (ic, zc, a1, p)
| _ := failed
end
/-- Given `a' : Ξ±` a natural numeral, returns `(a : β, β’ βa = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_rat_uncast_nat (ic qc : instance_cache) (cz_inst : expr) : β (a' : expr),
tactic (instance_cache Γ instance_cache Γ expr Γ expr)
| a' :=
match match_numeral a' with
| match_numeral_result.zero := do
(qc, e) β qc.mk_app ``has_zero.zero [],
(ic, p) β ic.mk_app ``rat.cast_zero [],
return (ic, qc, e, p)
| match_numeral_result.one := do
(qc, e) β qc.mk_app ``has_one.one [],
(ic, p) β ic.mk_app ``rat.cast_one [],
return (ic, qc, e, p)
| match_numeral_result.bit0 a' := do
(ic, qc, a, p) β prove_rat_uncast_nat a',
(qc, a0) β qc.mk_bit0 a,
(ic, p) β ic.mk_app ``rat_cast_bit0 [cz_inst, a, a', p],
return (ic, qc, a0, p)
| match_numeral_result.bit1 a' := do
(ic, qc, a, p) β prove_rat_uncast_nat a',
(qc, a1) β qc.mk_bit1 a,
(ic, p) β ic.mk_app ``rat_cast_bit1 [cz_inst, a, a', p],
return (ic, qc, a1, p)
| _ := failed
end
theorem rat_cast_div {Ξ±} [division_ring Ξ±] [char_zero Ξ±] (a b : β) (a' b' : Ξ±)
(ha : βa = a') (hb : βb = b') : β(a / b) = a' / b' :=
ha βΈ hb βΈ rat.cast_div _ _
/-- Given `a' : Ξ±` a nonnegative rational numeral, returns `(a : β, β’ βa = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_rat_uncast_nonneg (ic qc : instance_cache) (cz_inst a' : expr) (na' : β) :
tactic (instance_cache Γ instance_cache Γ expr Γ expr) :=
if na'.denom = 1 then
prove_rat_uncast_nat ic qc cz_inst a'
else do
[_, _, a', b'] β return a'.get_app_args,
(ic, qc, a, pa) β prove_rat_uncast_nat ic qc cz_inst a',
(ic, qc, b, pb) β prove_rat_uncast_nat ic qc cz_inst b',
(qc, e) β qc.mk_app ``has_div.div [a, b],
(ic, p) β ic.mk_app ``rat_cast_div [cz_inst, a, b, a', b', pa, pb],
return (ic, qc, e, p)
theorem int_cast_neg {Ξ±} [ring Ξ±] (a : β€) (a' : Ξ±) (h : βa = a') : β-a = -a' :=
h βΈ int.cast_neg _
theorem rat_cast_neg {Ξ±} [division_ring Ξ±] (a : β) (a' : Ξ±) (h : βa = a') : β-a = -a' :=
h βΈ rat.cast_neg _
/-- Given `a' : Ξ±` an integer numeral, returns `(a : β€, β’ βa = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_int_uncast (ic zc : instance_cache) (a' : expr) :
tactic (instance_cache Γ instance_cache Γ expr Γ expr) :=
match match_neg a' with
| some a' := do
(ic, zc, a, p) β prove_int_uncast_nat ic zc a',
(zc, e) β zc.mk_app ``has_neg.neg [a],
(ic, p) β ic.mk_app ``int_cast_neg [a, a', p],
return (ic, zc, e, p)
| none := prove_int_uncast_nat ic zc a'
end
/-- Given `a' : Ξ±` a rational numeral, returns `(a : β, β’ βa = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_rat_uncast (ic qc : instance_cache) (cz_inst a' : expr) (na' : β) :
tactic (instance_cache Γ instance_cache Γ expr Γ expr) :=
match match_neg a' with
| some a' := do
(ic, qc, a, p) β prove_rat_uncast_nonneg ic qc cz_inst a' (-na'),
(qc, e) β qc.mk_app ``has_neg.neg [a],
(ic, p) β ic.mk_app ``rat_cast_neg [a, a', p],
return (ic, qc, e, p)
| none := prove_rat_uncast_nonneg ic qc cz_inst a' na'
end
theorem nat_cast_ne {Ξ±} [semiring Ξ±] [char_zero Ξ±] (a b : β) (a' b' : Ξ±)
(ha : βa = a') (hb : βb = b') (h : a β b) : a' β b' :=
ha βΈ hb βΈ mt nat.cast_inj.1 h
theorem int_cast_ne {Ξ±} [ring Ξ±] [char_zero Ξ±] (a b : β€) (a' b' : Ξ±)
(ha : βa = a') (hb : βb = b') (h : a β b) : a' β b' :=
ha βΈ hb βΈ mt int.cast_inj.1 h
theorem rat_cast_ne {Ξ±} [division_ring Ξ±] [char_zero Ξ±] (a b : β) (a' b' : Ξ±)
(ha : βa = a') (hb : βb = b') (h : a β b) : a' β b' :=
ha βΈ hb βΈ mt rat.cast_inj.1 h
/-- Given `a`,`b` rational numerals, proves `β’ a β b`. Currently it tries two methods:
* Prove `β’ a < b` or `β’ b < a`, if the base type has an order
* Embed `β(a':β) = a` and `β(b':β) = b`, and then prove `a' β b'`.
This requires that the base type be `char_zero`, and also that it be a `division_ring`
so that the coercion from `β` is well defined.
We may also add coercions to `β€` and `β` as well in order to support `char_zero`
rings and semirings. -/
meta def prove_ne : instance_cache β expr β expr β β β β β tactic (instance_cache Γ expr)
| ic a b na nb := prove_ne_rat ic a b na nb <|> do
cz_inst β mk_mapp ``char_zero [ic.Ξ±, none] >>= mk_instance,
if na.denom = 1 β§ nb.denom = 1 then
if na β₯ 0 β§ nb β₯ 0 then do
guard (ic.Ξ± β `(β)),
nc β mk_instance_cache `(β),
(ic, nc, a', pa) β prove_nat_uncast ic nc a,
(ic, nc, b', pb) β prove_nat_uncast ic nc b,
(nc, p) β prove_ne_rat nc a' b' na nb,
ic.mk_app ``nat_cast_ne [cz_inst, a', b', a, b, pa, pb, p]
else do
guard (ic.Ξ± β `(β€)),
zc β mk_instance_cache `(β€),
(ic, zc, a', pa) β prove_int_uncast ic zc a,
(ic, zc, b', pb) β prove_int_uncast ic zc b,
(zc, p) β prove_ne_rat zc a' b' na nb,
ic.mk_app ``int_cast_ne [cz_inst, a', b', a, b, pa, pb, p]
else do
guard (ic.Ξ± β `(β)),
qc β mk_instance_cache `(β),
(ic, qc, a', pa) β prove_rat_uncast ic qc cz_inst a na,
(ic, qc, b', pb) β prove_rat_uncast ic qc cz_inst b nb,
(qc, p) β prove_ne_rat qc a' b' na nb,
ic.mk_app ``rat_cast_ne [cz_inst, a', b', a, b, pa, pb, p]
/-- Given `a` a rational numeral, returns `β’ a β 0`. -/
meta def prove_ne_zero (ic : instance_cache) : expr β β β tactic (instance_cache Γ expr)
| a na := do
(ic, z) β ic.mk_app ``has_zero.zero [],
prove_ne ic a z na 0
/-- Given `a` nonnegative rational and `d` a natural number, returns `(b, β’ a * d = b)`.
(`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/
meta def prove_clear_denom : instance_cache β expr β expr β β β β β
tactic (instance_cache Γ expr Γ expr) := prove_clear_denom' prove_ne_zero
theorem clear_denom_add {Ξ±} [division_ring Ξ±] (a a' b b' c c' d : Ξ±)
(hβ : d β 0) (ha : a * d = a') (hb : b * d = b') (hc : c * d = c')
(h : a' + b' = c') : a + b = c :=
mul_right_cancelβ hβ $ by rwa [add_mul, ha, hb, hc]
/-- Given `a`,`b`,`c` nonnegative rational numerals, returns `β’ a + b = c`. -/
meta def prove_add_nonneg_rat (ic : instance_cache) (a b c : expr) (na nb nc : β) :
tactic (instance_cache Γ expr) :=
if na.denom = 1 β§ nb.denom = 1 then
prove_add_nat ic a b c
else do
let nd := na.denom.lcm nb.denom,
(ic, d) β ic.of_nat nd,
(ic, pβ) β prove_ne_zero ic d (rat.of_int nd),
(ic, a', pa) β prove_clear_denom ic a d na nd,
(ic, b', pb) β prove_clear_denom ic b d nb nd,
(ic, c', pc) β prove_clear_denom ic c d nc nd,
(ic, p) β prove_add_nat ic a' b' c',
ic.mk_app ``clear_denom_add [a, a', b, b', c, c', d, pβ, pa, pb, pc, p]
theorem add_pos_neg_pos {Ξ±} [add_group Ξ±] (a b c : Ξ±) (h : c + b = a) : a + -b = c :=
h βΈ by simp
theorem add_pos_neg_neg {Ξ±} [add_group Ξ±] (a b c : Ξ±) (h : c + a = b) : a + -b = -c :=
h βΈ by simp
theorem add_neg_pos_pos {Ξ±} [add_group Ξ±] (a b c : Ξ±) (h : a + c = b) : -a + b = c :=
h βΈ by simp
theorem add_neg_pos_neg {Ξ±} [add_group Ξ±] (a b c : Ξ±) (h : b + c = a) : -a + b = -c :=
h βΈ by simp
theorem add_neg_neg {Ξ±} [add_group Ξ±] (a b c : Ξ±) (h : b + a = c) : -a + -b = -c :=
h βΈ by simp
/-- Given `a`,`b`,`c` rational numerals, returns `β’ a + b = c`. -/
meta def prove_add_rat (ic : instance_cache) (ea eb ec : expr) (a b c : β) :
tactic (instance_cache Γ expr) :=
match match_neg ea, match_neg eb, match_neg ec with
| some ea, some eb, some ec := do
(ic, p) β prove_add_nonneg_rat ic eb ea ec (-b) (-a) (-c),
ic.mk_app ``add_neg_neg [ea, eb, ec, p]
| some ea, none, some ec := do
(ic, p) β prove_add_nonneg_rat ic eb ec ea b (-c) (-a),
ic.mk_app ``add_neg_pos_neg [ea, eb, ec, p]
| some ea, none, none := do
(ic, p) β prove_add_nonneg_rat ic ea ec eb (-a) c b,
ic.mk_app ``add_neg_pos_pos [ea, eb, ec, p]
| none, some eb, some ec := do
(ic, p) β prove_add_nonneg_rat ic ec ea eb (-c) a (-b),
ic.mk_app ``add_pos_neg_neg [ea, eb, ec, p]
| none, some eb, none := do
(ic, p) β prove_add_nonneg_rat ic ec eb ea c (-b) a,
ic.mk_app ``add_pos_neg_pos [ea, eb, ec, p]
| _, _, _ := prove_add_nonneg_rat ic ea eb ec a b c
end
/-- Given `a`,`b` rational numerals, returns `(c, β’ a + b = c)`. -/
meta def prove_add_rat' (ic : instance_cache) (a b : expr) :
tactic (instance_cache Γ expr Γ expr) :=
do na β a.to_rat,
nb β b.to_rat,
let nc := na + nb,
(ic, c) β ic.of_rat nc,
(ic, p) β prove_add_rat ic a b c na nb nc,
return (ic, c, p)
theorem clear_denom_simple_nat {Ξ±} [division_ring Ξ±] (a : Ξ±) :
(1:Ξ±) β 0 β§ a * 1 = a := β¨one_ne_zero, mul_one _β©
theorem clear_denom_simple_div {Ξ±} [division_ring Ξ±] (a b : Ξ±) (h : b β 0) :
b β 0 β§ a / b * b = a := β¨h, div_mul_cancel _ hβ©
/-- Given `a` a nonnegative rational numeral, returns `(b, c, β’ a * b = c)`
where `b` and `c` are natural numerals. (`b` will be the denominator of `a`.) -/
meta def prove_clear_denom_simple (c : instance_cache) (a : expr) (na : β) :
tactic (instance_cache Γ expr Γ expr Γ expr) :=
if na.denom = 1 then do
(c, d) β c.mk_app ``has_one.one [],
(c, p) β c.mk_app ``clear_denom_simple_nat [a],
return (c, d, a, p)
else do
[Ξ±, _, a, b] β return a.get_app_args,
(c, pβ) β prove_ne_zero c b (rat.of_int na.denom),
(c, p) β c.mk_app ``clear_denom_simple_div [a, b, pβ],
return (c, b, a, p)
theorem clear_denom_mul {Ξ±} [field Ξ±] (a a' b b' c c' dβ dβ d : Ξ±)
(ha : dβ β 0 β§ a * dβ = a') (hb : dβ β 0 β§ b * dβ = b')
(hc : c * d = c') (hd : dβ * dβ = d)
(h : a' * b' = c') : a * b = c :=
mul_right_cancelβ ha.1 $ mul_right_cancelβ hb.1 $
by rw [mul_assoc c, hd, hc, β h, β ha.2, β hb.2, β mul_assoc, mul_right_comm a]
/-- Given `a`,`b` nonnegative rational numerals, returns `(c, β’ a * b = c)`. -/
meta def prove_mul_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : β) :
tactic (instance_cache Γ expr Γ expr) :=
if na.denom = 1 β§ nb.denom = 1 then
prove_mul_nat ic a b
else do
let nc := na * nb, (ic, c) β ic.of_rat nc,
(ic, dβ, a', pa) β prove_clear_denom_simple ic a na,
(ic, dβ, b', pb) β prove_clear_denom_simple ic b nb,
(ic, d, pd) β prove_mul_nat ic dβ dβ, nd β d.to_nat,
(ic, c', pc) β prove_clear_denom ic c d nc nd,
(ic, _, p) β prove_mul_nat ic a' b',
(ic, p) β ic.mk_app ``clear_denom_mul [a, a', b, b', c, c', dβ, dβ, d, pa, pb, pc, pd, p],
return (ic, c, p)
theorem mul_neg_pos {Ξ±} [ring Ξ±] (a b c : Ξ±) (h : a * b = c) : -a * b = -c := h βΈ by simp
theorem mul_pos_neg {Ξ±} [ring Ξ±] (a b c : Ξ±) (h : a * b = c) : a * -b = -c := h βΈ by simp
theorem mul_neg_neg {Ξ±} [ring Ξ±] (a b c : Ξ±) (h : a * b = c) : -a * -b = c := h βΈ by simp
/-- Given `a`,`b` rational numerals, returns `(c, β’ a * b = c)`. -/
meta def prove_mul_rat (ic : instance_cache) (a b : expr) (na nb : β) :
tactic (instance_cache Γ expr Γ expr) :=
match match_sign a, match_sign b with
| sum.inl a, sum.inl b := do
(ic, c, p) β prove_mul_nonneg_rat ic a b (-na) (-nb),
(ic, p) β ic.mk_app ``mul_neg_neg [a, b, c, p],
return (ic, c, p)
| sum.inr ff, _ := do
(ic, z) β ic.mk_app ``has_zero.zero [],
(ic, p) β ic.mk_app ``zero_mul [b],
return (ic, z, p)
| _, sum.inr ff := do
(ic, z) β ic.mk_app ``has_zero.zero [],
(ic, p) β ic.mk_app ``mul_zero [a],
return (ic, z, p)
| sum.inl a, sum.inr tt := do
(ic, c, p) β prove_mul_nonneg_rat ic a b (-na) nb,
(ic, p) β ic.mk_app ``mul_neg_pos [a, b, c, p],
(ic, c') β ic.mk_app ``has_neg.neg [c],
return (ic, c', p)
| sum.inr tt, sum.inl b := do
(ic, c, p) β prove_mul_nonneg_rat ic a b na (-nb),
(ic, p) β ic.mk_app ``mul_pos_neg [a, b, c, p],
(ic, c') β ic.mk_app ``has_neg.neg [c],
return (ic, c', p)
| sum.inr tt, sum.inr tt := prove_mul_nonneg_rat ic a b na nb
end
theorem inv_neg {Ξ±} [division_ring Ξ±] (a b : Ξ±) (h : aβ»ΒΉ = b) : (-a)β»ΒΉ = -b :=
h βΈ by simp only [inv_eq_one_div, one_div_neg_eq_neg_one_div]
theorem inv_one {Ξ±} [division_ring Ξ±] : (1 : Ξ±)β»ΒΉ = 1 := inv_one
theorem inv_one_div {Ξ±} [division_ring Ξ±] (a : Ξ±) : (1 / a)β»ΒΉ = a :=
by rw [one_div, inv_inv]
theorem inv_div_one {Ξ±} [division_ring Ξ±] (a : Ξ±) : aβ»ΒΉ = 1 / a :=
inv_eq_one_div _
theorem inv_div {Ξ±} [division_ring Ξ±] (a b : Ξ±) : (a / b)β»ΒΉ = b / a :=
by simp only [inv_eq_one_div, one_div_div]
/-- Given `a` a rational numeral, returns `(b, β’ aβ»ΒΉ = b)`. -/
meta def prove_inv : instance_cache β expr β β β tactic (instance_cache Γ expr Γ expr)
| ic e n :=
match match_sign e with
| sum.inl e := do
(ic, e', p) β prove_inv ic e (-n),
(ic, r) β ic.mk_app ``has_neg.neg [e'],
(ic, p) β ic.mk_app ``inv_neg [e, e', p],
return (ic, r, p)
| sum.inr ff := do
(ic, p) β ic.mk_app ``inv_zero [],
return (ic, e, p)
| sum.inr tt :=
if n.num = 1 then
if n.denom = 1 then do
(ic, p) β ic.mk_app ``inv_one [],
return (ic, e, p)
else do
let e := e.app_arg,
(ic, p) β ic.mk_app ``inv_one_div [e],
return (ic, e, p)
else if n.denom = 1 then do
(ic, p) β ic.mk_app ``inv_div_one [e],
e β infer_type p,
return (ic, e.app_arg, p)
else do
[_, _, a, b] β return e.get_app_args,
(ic, e') β ic.mk_app ``has_div.div [b, a],
(ic, p) β ic.mk_app ``inv_div [a, b],
return (ic, e', p)
end
theorem div_eq {Ξ±} [division_ring Ξ±] (a b b' c : Ξ±)
(hb : bβ»ΒΉ = b') (h : a * b' = c) : a / b = c :=
by rwa [ β hb, β div_eq_mul_inv] at h
/-- Given `a`,`b` rational numerals, returns `(c, β’ a / b = c)`. -/
meta def prove_div (ic : instance_cache) (a b : expr) (na nb : β) :
tactic (instance_cache Γ expr Γ expr) :=
do (ic, b', pb) β prove_inv ic b nb,
(ic, c, p) β prove_mul_rat ic a b' na nbβ»ΒΉ,
(ic, p) β ic.mk_app ``div_eq [a, b, b', c, pb, p],
return (ic, c, p)
/-- Given `a` a rational numeral, returns `(b, β’ -a = b)`. -/
meta def prove_neg (ic : instance_cache) (a : expr) : tactic (instance_cache Γ expr Γ expr) :=
match match_sign a with
| sum.inl a := do
(ic, p) β ic.mk_app ``neg_neg [a],
return (ic, a, p)
| sum.inr ff := do
(ic, p) β ic.mk_app ``neg_zero [],
return (ic, a, p)
| sum.inr tt := do
(ic, a') β ic.mk_app ``has_neg.neg [a],
p β mk_eq_refl a',
return (ic, a', p)
end
theorem sub_pos {Ξ±} [add_group Ξ±] (a b b' c : Ξ±) (hb : -b = b') (h : a + b' = c) : a - b = c :=
by rwa [β hb, β sub_eq_add_neg] at h
theorem sub_neg {Ξ±} [add_group Ξ±] (a b c : Ξ±) (h : a + b = c) : a - -b = c :=
by rwa sub_neg_eq_add
/-- Given `a`,`b` rational numerals, returns `(c, β’ a - b = c)`. -/
meta def prove_sub (ic : instance_cache) (a b : expr) : tactic (instance_cache Γ expr Γ expr) :=
match match_sign b with
| sum.inl b := do
(ic, c, p) β prove_add_rat' ic a b,
(ic, p) β ic.mk_app ``sub_neg [a, b, c, p],
return (ic, c, p)
| sum.inr ff := do
(ic, p) β ic.mk_app ``sub_zero [a],
return (ic, a, p)
| sum.inr tt := do
(ic, b', pb) β prove_neg ic b,
(ic, c, p) β prove_add_rat' ic a b',
(ic, p) β ic.mk_app ``sub_pos [a, b, b', c, pb, p],
return (ic, c, p)
end
theorem sub_nat_pos (a b c : β) (h : b + c = a) : a - b = c :=
h βΈ add_tsub_cancel_left _ _
theorem sub_nat_neg (a b c : β) (h : a + c = b) : a - b = 0 :=
tsub_eq_zero_iff_le.mpr $ h βΈ nat.le_add_right _ _
/-- Given `a : nat`,`b : nat` natural numerals, returns `(c, β’ a - b = c)`. -/
meta def prove_sub_nat (ic : instance_cache) (a b : expr) : tactic (expr Γ expr) :=
do na β a.to_nat, nb β b.to_nat,
if nb β€ na then do
(ic, c) β ic.of_nat (na - nb),
(ic, p) β prove_add_nat ic b c a,
return (c, `(sub_nat_pos).mk_app [a, b, c, p])
else do
(ic, c) β ic.of_nat (nb - na),
(ic, p) β prove_add_nat ic a c b,
return (`(0 : β), `(sub_nat_neg).mk_app [a, b, c, p])
/-- Evaluates the basic field operations `+`,`neg`,`-`,`*`,`inv`,`/` on numerals.
Also handles nat subtraction. Does not do recursive simplification; that is,
`1 + 1 + 1` will not simplify but `2 + 1` will. This is handled by the top level
`simp` call in `norm_num.derive`. -/
meta def eval_field : expr β tactic (expr Γ expr)
| `(%%eβ + %%eβ) := do
nβ β eβ.to_rat, nβ β eβ.to_rat,
c β infer_type eβ >>= mk_instance_cache,
let nβ := nβ + nβ,
(c, eβ) β c.of_rat nβ,
(_, p) β prove_add_rat c eβ eβ eβ nβ nβ nβ,
return (eβ, p)
| `(%%eβ * %%eβ) := do
nβ β eβ.to_rat, nβ β eβ.to_rat,
c β infer_type eβ >>= mk_instance_cache,
prod.snd <$> prove_mul_rat c eβ eβ nβ nβ
| `(- %%e) := do
c β infer_type e >>= mk_instance_cache,
prod.snd <$> prove_neg c e
| `(@has_sub.sub %%Ξ± %%inst %%a %%b) := do
c β mk_instance_cache Ξ±,
if Ξ± = `(nat) then prove_sub_nat c a b
else prod.snd <$> prove_sub c a b
| `(has_inv.inv %%e) := do
n β e.to_rat,
c β infer_type e >>= mk_instance_cache,
prod.snd <$> prove_inv c e n
| `(%%eβ / %%eβ) := do
nβ β eβ.to_rat, nβ β eβ.to_rat,
c β infer_type eβ >>= mk_instance_cache,
prod.snd <$> prove_div c eβ eβ nβ nβ
| _ := failed
lemma pow_bit0 [monoid Ξ±] (a c' c : Ξ±) (b : β)
(h : a ^ b = c') (hβ : c' * c' = c) : a ^ bit0 b = c :=
hβ βΈ by simp [pow_bit0, h]
lemma pow_bit1 [monoid Ξ±] (a cβ cβ c : Ξ±) (b : β)
(h : a ^ b = cβ) (hβ : cβ * cβ = cβ) (hβ : cβ * a = c) : a ^ bit1 b = c :=
by rw [β hβ, β hβ]; simp [pow_bit1, h]
section
open match_numeral_result
/-- Given `a` a rational numeral and `b : nat`, returns `(c, β’ a ^ b = c)`. -/
meta def prove_pow (a : expr) (na : β) :
instance_cache β expr β tactic (instance_cache Γ expr Γ expr)
| ic b :=
match match_numeral b with
| zero := do
(ic, p) β ic.mk_app ``pow_zero [a],
(ic, o) β ic.mk_app ``has_one.one [],
return (ic, o, p)
| one := do
(ic, p) β ic.mk_app ``pow_one [a],
return (ic, a, p)
| bit0 b := do
(ic, c', p) β prove_pow ic b,
nc' β expr.to_rat c',
(ic, c, pβ) β prove_mul_rat ic c' c' nc' nc',
(ic, p) β ic.mk_app ``pow_bit0 [a, c', c, b, p, pβ],
return (ic, c, p)
| bit1 b := do
(ic, cβ, p) β prove_pow ic b,
ncβ β expr.to_rat cβ,
(ic, cβ, pβ) β prove_mul_rat ic cβ cβ ncβ ncβ,
(ic, c, pβ) β prove_mul_rat ic cβ a (ncβ * ncβ) na,
(ic, p) β ic.mk_app ``pow_bit1 [a, cβ, cβ, c, b, p, pβ, pβ],
return (ic, c, p)
| _ := failed
end
end
lemma zpow_pos {Ξ±} [div_inv_monoid Ξ±] (a : Ξ±) (b : β€) (b' : β) (c : Ξ±)
(hb : b = b') (h : a ^ b' = c) : a ^ b = c := by rw [β h, hb, zpow_coe_nat]
lemma zpow_neg {Ξ±} [div_inv_monoid Ξ±] (a : Ξ±) (b : β€) (b' : β) (c c' : Ξ±)
(b0 : 0 < b') (hb : b = b') (h : a ^ b' = c) (hc : cβ»ΒΉ = c') : a ^ -b = c' :=
by rw [β hc, β h, hb, zpow_neg_coe_of_pos _ b0]
/-- Given `a` a rational numeral and `b : β€`, returns `(c, β’ a ^ b = c)`. -/
meta def prove_zpow (ic zc nc : instance_cache) (a : expr) (na : β) (b : expr) :
tactic (instance_cache Γ instance_cache Γ instance_cache Γ expr Γ expr) :=
match match_sign b with
| sum.inl b := do
(zc, nc, b', hb) β prove_nat_uncast zc nc b,
(nc, b0) β prove_pos nc b',
(ic, c, h) β prove_pow a na ic b',
(ic, c', hc) β c.to_rat >>= prove_inv ic c,
(ic, p) β ic.mk_app ``zpow_neg [a, b, b', c, c', b0, hb, h, hc],
pure (ic, zc, nc, c', p)
| sum.inr ff := do
(ic, o) β ic.mk_app ``has_one.one [],
(ic, p) β ic.mk_app ``zpow_zero [a],
pure (ic, zc, nc, o, p)
| sum.inr tt := do
(zc, nc, b', hb) β prove_nat_uncast zc nc b,
(ic, c, h) β prove_pow a na ic b',
(ic, p) β ic.mk_app ``zpow_pos [a, b, b', c, hb, h],
pure (ic, zc, nc, c, p)
end
/-- Evaluates expressions of the form `a ^ b`, `monoid.npow a b` or `nat.pow a b`. -/
meta def eval_pow : expr β tactic (expr Γ expr)
| `(@has_pow.pow %%Ξ± _ %%m %%eβ %%eβ) := do
nβ β eβ.to_rat,
c β mk_instance_cache Ξ±,
match m with
| `(@monoid.has_pow %%_ %%_) := prod.snd <$> prove_pow eβ nβ c eβ
| `(@div_inv_monoid.has_pow %%_ %%_) := do
zc β mk_instance_cache `(β€),
nc β mk_instance_cache `(β),
(prod.snd β prod.snd β prod.snd) <$> prove_zpow c zc nc eβ nβ eβ
| _ := failed
end
| `(monoid.npow %%eβ %%eβ) := do
nβ β eβ.to_rat,
c β infer_type eβ >>= mk_instance_cache,
prod.snd <$> prove_pow eβ nβ c eβ
| `(div_inv_monoid.zpow %%eβ %%eβ) := do
nβ β eβ.to_rat,
c β infer_type eβ >>= mk_instance_cache,
zc β mk_instance_cache `(β€),
nc β mk_instance_cache `(β),
(prod.snd β prod.snd β prod.snd) <$> prove_zpow c zc nc eβ nβ eβ
| _ := failed
/-- Given `β’ p`, returns `(true, β’ p = true)`. -/
meta def true_intro (p : expr) : tactic (expr Γ expr) :=
prod.mk `(true) <$> mk_app ``eq_true_intro [p]
/-- Given `β’ Β¬ p`, returns `(false, β’ p = false)`. -/
meta def false_intro (p : expr) : tactic (expr Γ expr) :=
prod.mk `(false) <$> mk_app ``eq_false_intro [p]
theorem not_refl_false_intro {Ξ±} (a : Ξ±) : (a β a) = false :=
eq_false_intro $ not_not_intro rfl
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem gt_intro {Ξ±} [has_lt Ξ±] (a b : Ξ±) (c) (h : a < b = c) : b > a = c := h
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem ge_intro {Ξ±} [has_le Ξ±] (a b : Ξ±) (c) (h : a β€ b = c) : b β₯ a = c := h
/-- Evaluates the inequality operations `=`,`<`,`>`,`β€`,`β₯`,`β ` on numerals. -/
meta def eval_ineq : expr β tactic (expr Γ expr)
| `(%%eβ < %%eβ) := do
nβ β eβ.to_rat, nβ β eβ.to_rat,
c β infer_type eβ >>= mk_instance_cache,
if nβ < nβ then
do (_, p) β prove_lt_rat c eβ eβ nβ nβ, true_intro p
else if nβ = nβ then do
(_, p) β c.mk_app ``lt_irrefl [eβ],
false_intro p
else do
(c, p') β prove_lt_rat c eβ eβ nβ nβ,
(_, p) β c.mk_app ``not_lt_of_gt [eβ, eβ, p'],
false_intro p
| `(%%eβ β€ %%eβ) := do
nβ β eβ.to_rat, nβ β eβ.to_rat,
c β infer_type eβ >>= mk_instance_cache,
if nβ β€ nβ then do
(_, p) β
if nβ = nβ then c.mk_app ``le_refl [eβ]
else prove_le_rat c eβ eβ nβ nβ,
true_intro p
else do
(c, p) β prove_lt_rat c eβ eβ nβ nβ,
(_, p) β c.mk_app ``not_le_of_gt [eβ, eβ, p],
false_intro p
| `(%%eβ = %%eβ) := do
nβ β eβ.to_rat, nβ β eβ.to_rat,
c β infer_type eβ >>= mk_instance_cache,
if nβ = nβ then mk_eq_refl eβ >>= true_intro
else do (_, p) β prove_ne c eβ eβ nβ nβ, false_intro p
| `(%%eβ > %%eβ) := do
(e, p) β mk_app ``has_lt.lt [eβ, eβ] >>= eval_ineq,
prod.mk e <$> mk_app ``gt_intro [eβ, eβ, e, p]
| `(%%eβ β₯ %%eβ) := do
(e, p) β mk_app ``has_le.le [eβ, eβ] >>= eval_ineq,
prod.mk e <$> mk_app ``ge_intro [eβ, eβ, e, p]
| `(%%eβ β %%eβ) := do
nβ β eβ.to_rat, nβ β eβ.to_rat,
c β infer_type eβ >>= mk_instance_cache,
if nβ = nβ then
prod.mk `(false) <$> mk_app ``not_refl_false_intro [eβ]
else do (_, p) β prove_ne c eβ eβ nβ nβ, true_intro p
| _ := failed
theorem nat_succ_eq (a b c : β) (hβ : a = b) (hβ : b + 1 = c) : nat.succ a = c := by rwa hβ
/-- Evaluates the expression `nat.succ ... (nat.succ n)` where `n` is a natural numeral.
(We could also just handle `nat.succ n` here and rely on `simp` to work bottom up, but we figure
that towers of successors coming from e.g. `induction` are a common case.) -/
meta def prove_nat_succ (ic : instance_cache) : expr β tactic (instance_cache Γ β Γ expr Γ expr)
| `(nat.succ %%a) := do
(ic, n, b, pβ) β prove_nat_succ a,
let n' := n + 1,
(ic, c) β ic.of_nat n',
(ic, pβ) β prove_add_nat ic b `(1) c,
return (ic, n', c, `(nat_succ_eq).mk_app [a, b, c, pβ, pβ])
| e := do
n β e.to_nat,
p β mk_eq_refl e,
return (ic, n, e, p)
lemma nat_div (a b q r m : β) (hm : q * b = m) (h : r + m = a) (hβ : r < b) : a / b = q :=
by rw [β h, β hm, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) hβ),
nat.div_eq_of_lt hβ, zero_add]
lemma int_div (a b q r m : β€) (hm : q * b = m) (h : r + m = a) (hβ : 0 β€ r) (hβ : r < b) :
a / b = q :=
by rw [β h, β hm, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt hβ hβ)),
int.div_eq_zero_of_lt hβ hβ, zero_add]
lemma nat_mod (a b q r m : β) (hm : q * b = m) (h : r + m = a) (hβ : r < b) : a % b = r :=
by rw [β h, β hm, nat.add_mul_mod_self_right, nat.mod_eq_of_lt hβ]
lemma int_mod (a b q r m : β€) (hm : q * b = m) (h : r + m = a) (hβ : 0 β€ r) (hβ : r < b) :
a % b = r :=
by rw [β h, β hm, int.add_mul_mod_self, int.mod_eq_of_lt hβ hβ]
lemma int_div_neg (a b c' c : β€) (h : a / b = c') (hβ : -c' = c) : a / -b = c :=
hβ βΈ h βΈ int.div_neg _ _
lemma int_mod_neg (a b c : β€) (h : a % b = c) : a % -b = c :=
(int.mod_neg _ _).trans h
/-- Given `a`,`b` numerals in `nat` or `int`,
* `prove_div_mod ic a b ff` returns `(c, β’ a / b = c)`
* `prove_div_mod ic a b tt` returns `(c, β’ a % b = c)`
-/
meta def prove_div_mod (ic : instance_cache) :
expr β expr β bool β tactic (instance_cache Γ expr Γ expr)
| a b mod :=
match match_neg b with
| some b := do
(ic, c', p) β prove_div_mod a b mod,
if mod then
return (ic, c', `(int_mod_neg).mk_app [a, b, c', p])
else do
(ic, c, pβ) β prove_neg ic c',
return (ic, c, `(int_div_neg).mk_app [a, b, c', c, p, pβ])
| none := do
nb β b.to_nat,
na β a.to_int,
let nq := na / nb,
let nr := na % nb,
let nm := nq * nr,
(ic, q) β ic.of_int nq,
(ic, r) β ic.of_int nr,
(ic, m, pm) β prove_mul_rat ic q b (rat.of_int nq) (rat.of_int nb),
(ic, p) β prove_add_rat ic r m a (rat.of_int nr) (rat.of_int nm) (rat.of_int na),
(ic, p') β prove_lt_nat ic r b,
if ic.Ξ± = `(nat) then
if mod then return (ic, r, `(nat_mod).mk_app [a, b, q, r, m, pm, p, p'])
else return (ic, q, `(nat_div).mk_app [a, b, q, r, m, pm, p, p'])
else if ic.Ξ± = `(int) then do
(ic, pβ) β prove_nonneg ic r,
if mod then return (ic, r, `(int_mod).mk_app [a, b, q, r, m, pm, p, pβ, p'])
else return (ic, q, `(int_div).mk_app [a, b, q, r, m, pm, p, pβ, p'])
else failed
end
theorem dvd_eq_nat (a b c : β) (p) (hβ : b % a = c) (hβ : (c = 0) = p) : (a β£ b) = p :=
(propext $ by rw [β hβ, nat.dvd_iff_mod_eq_zero]).trans hβ
theorem dvd_eq_int (a b c : β€) (p) (hβ : b % a = c) (hβ : (c = 0) = p) : (a β£ b) = p :=
(propext $ by rw [β hβ, int.dvd_iff_mod_eq_zero]).trans hβ
theorem int_to_nat_pos (a : β€) (b : β) (h : (by haveI := @nat.cast_coe β€; exact b : β€) = a) :
a.to_nat = b := by rw β h; simp
theorem int_to_nat_neg (a : β€) (h : 0 < a) : (-a).to_nat = 0 :=
by simp only [int.to_nat_of_nonpos, h.le, neg_nonpos]
theorem nat_abs_pos (a : β€) (b : β) (h : (by haveI := @nat.cast_coe β€; exact b : β€) = a) :
a.nat_abs = b := by rw β h; simp
theorem nat_abs_neg (a : β€) (b : β) (h : (by haveI := @nat.cast_coe β€; exact b : β€) = a) :
(-a).nat_abs = b := by rw β h; simp
theorem neg_succ_of_nat (a b : β) (c : β€) (hβ : a + 1 = b)
(hβ : (by haveI := @nat.cast_coe β€; exact b : β€) = c) :
-[1+ a] = -c := by rw [β hβ, β hβ]; refl
/-- Evaluates some extra numeric operations on `nat` and `int`, specifically
`nat.succ`, `/` and `%`, and `β£` (divisibility). -/
meta def eval_nat_int_ext : expr β tactic (expr Γ expr)
| e@`(nat.succ _) := do
ic β mk_instance_cache `(β),
(_, _, ep) β prove_nat_succ ic e,
return ep
| `(%%a / %%b) := do
c β infer_type a >>= mk_instance_cache,
prod.snd <$> prove_div_mod c a b ff
| `(%%a % %%b) := do
c β infer_type a >>= mk_instance_cache,
prod.snd <$> prove_div_mod c a b tt
| `(%%a β£ %%b) := do
Ξ± β infer_type a,
ic β mk_instance_cache Ξ±,
th β if Ξ± = `(nat) then return (`(dvd_eq_nat):expr) else
if Ξ± = `(int) then return `(dvd_eq_int) else failed,
(ic, c, pβ) β prove_div_mod ic b a tt,
(ic, z) β ic.mk_app ``has_zero.zero [],
(e', pβ) β mk_app ``eq [c, z] >>= eval_ineq,
return (e', th.mk_app [a, b, c, e', pβ, pβ])
| `(int.to_nat %%a) := do
n β a.to_int,
ic β mk_instance_cache `(β€),
if n β₯ 0 then do
nc β mk_instance_cache `(β),
(_, _, b, p) β prove_nat_uncast ic nc a,
pure (b, `(int_to_nat_pos).mk_app [a, b, p])
else do
a β match_neg a,
(_, p) β prove_pos ic a,
pure (`(0), `(int_to_nat_neg).mk_app [a, p])
| `(int.nat_abs %%a) := do
n β a.to_int,
ic β mk_instance_cache `(β€),
nc β mk_instance_cache `(β),
if n β₯ 0 then do
(_, _, b, p) β prove_nat_uncast ic nc a,
pure (b, `(nat_abs_pos).mk_app [a, b, p])
else do
a β match_neg a,
(_, _, b, p) β prove_nat_uncast ic nc a,
pure (b, `(nat_abs_neg).mk_app [a, b, p])
| `(int.neg_succ_of_nat %%a) := do
na β a.to_nat,
ic β mk_instance_cache `(β€),
nc β mk_instance_cache `(β),
let nb := na + 1,
(nc, b) β nc.of_nat nb,
(nc, pβ) β prove_add_nat nc a `(1) b,
(ic, c) β ic.of_nat nb,
(_, _, _, pβ) β prove_nat_uncast ic nc c,
pure (`(-%%c : β€), `(neg_succ_of_nat).mk_app [a, b, c, pβ, pβ])
| _ := failed
theorem int_to_nat_cast (a : β) (b : β€)
(h : (by haveI := @nat.cast_coe β€; exact a : β€) = b) :
βa = b := eq.trans (by simp) h
/-- Evaluates the `βn` cast operation from `β`, `β€`, `β` to an arbitrary type `Ξ±`. -/
meta def eval_cast : expr β tactic (expr Γ expr)
| `(@coe β %%Ξ± %%inst %%a) := do
if inst.is_app_of ``coe_to_lift then
if inst.app_arg.is_app_of ``nat.cast_coe then do
n β a.to_nat,
ic β mk_instance_cache Ξ±,
nc β mk_instance_cache `(β),
(ic, b) β ic.of_nat n,
(_, _, _, p) β prove_nat_uncast ic nc b,
pure (b, p)
else if inst.app_arg.is_app_of ``int.cast_coe then do
n β a.to_int,
ic β mk_instance_cache Ξ±,
zc β mk_instance_cache `(β€),
(ic, b) β ic.of_int n,
(_, _, _, p) β prove_int_uncast ic zc b,
pure (b, p)
else if inst.app_arg.is_app_of ``rat.cast_coe then do
n β a.to_rat,
cz_inst β mk_mapp ``char_zero [Ξ±, none] >>= mk_instance,
ic β mk_instance_cache Ξ±,
qc β mk_instance_cache `(β),
(ic, b) β ic.of_rat n,
(_, _, _, p) β prove_rat_uncast ic qc cz_inst b n,
pure (b, p)
else failed
else if inst = `(@coe_base nat int int.has_coe) then do
n β a.to_nat,
ic β mk_instance_cache `(β€),
nc β mk_instance_cache `(β),
(ic, b) β ic.of_nat n,
(_, _, _, p) β prove_nat_uncast ic nc b,
pure (b, `(int_to_nat_cast).mk_app [a, b, p])
else failed
| _ := failed
/-- This version of `derive` does not fail when the input is already a numeral -/
meta def derive.step (e : expr) : tactic (expr Γ expr) :=
eval_field e <|> eval_pow e <|> eval_ineq e <|> eval_cast e <|> eval_nat_int_ext e
/-- An attribute for adding additional extensions to `norm_num`. To use this attribute, put
`@[norm_num]` on a tactic of type `expr β tactic (expr Γ expr)`; the tactic will be called on
subterms by `norm_num`, and it is responsible for identifying that the expression is a numerical
function applied to numerals, for example `nat.fib 17`, and should return the reduced numerical
expression (which must be in `norm_num`-normal form: a natural or rational numeral, i.e. `37`,
`12 / 7` or `-(2 / 3)`, although this can be an expression in any type), and the proof that the
original expression is equal to the rewritten expression.
Failure is used to indicate that this tactic does not apply to the term. For performance reasons,
it is best to detect non-applicability as soon as possible so that the next tactic can have a go,
so generally it will start with a pattern match and then checking that the arguments to the term
are numerals or of the appropriate form, followed by proof construction, which should not fail.
Propositions are treated like any other term. The normal form for propositions is `true` or
`false`, so it should produce a proof of the form `p = true` or `p = false`. `eq_true_intro` can be
used to help here.
-/
@[user_attribute]
protected meta def attr : user_attribute (expr β tactic (expr Γ expr)) unit :=
{ name := `norm_num,
descr := "Add norm_num derivers",
cache_cfg :=
{ mk_cache := Ξ» ns, do
{ t β ns.mfoldl
(Ξ» (t : expr β tactic (expr Γ expr)) n, do
t' β eval_expr (expr β tactic (expr Γ expr)) (expr.const n []),
pure (Ξ» e, t' e <|> t e))
(Ξ» _, failed),
pure (Ξ» e, derive.step e <|> t e) },
dependencies := [] } }
add_tactic_doc
{ name := "norm_num",
category := doc_category.attr,
decl_names := [`norm_num.attr],
tags := ["arithmetic", "decision_procedure"] }
/-- Look up the `norm_num` extensions in the cache and return a tactic extending `derive.step` with
additional reduction procedures. -/
meta def get_step : tactic (expr β tactic (expr Γ expr)) := norm_num.attr.get_cache
/-- Simplify an expression bottom-up using `step` to simplify the subexpressions. -/
meta def derive' (step : expr β tactic (expr Γ expr)) : expr β tactic (expr Γ expr)
| e := do
e β instantiate_mvars e,
(_, e', pr) β ext_simplify_core
() {} simp_lemmas.mk (Ξ» _, failed) (Ξ» _ _ _ _ _, failed)
(Ξ» _ _ _ _ e, do
(new_e, pr) β step e,
guard (Β¬ new_e =β e),
pure ((), new_e, some pr, tt))
`eq e,
pure (e', pr)
/-- Simplify an expression bottom-up using the default `norm_num` set to simplify the
subexpressions. -/
meta def derive (e : expr) : tactic (expr Γ expr) := do f β get_step, derive' f e
end norm_num
/-- Basic version of `norm_num` that does not call `simp`. It uses the provided `step` tactic
to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for
the basic builtin set of simplifications. -/
meta def tactic.norm_num1 (step : expr β tactic (expr Γ expr))
(loc : interactive.loc) : tactic unit :=
do ns β loc.get_locals,
success β tactic.replace_at (norm_num.derive' step) ns loc.include_goal,
when loc.include_goal $ try tactic.triv,
when (Β¬ ns.empty) $ try tactic.contradiction,
monad.unlessb success $ done <|> fail "norm_num failed to simplify"
/-- Normalize numerical expressions. It uses the provided `step` tactic to simplify the expression;
use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of
simplifications. -/
meta def tactic.norm_num (step : expr β tactic (expr Γ expr))
(hs : list simp_arg_type) (l : interactive.loc) : tactic unit :=
repeat1 $ orelse' (tactic.norm_num1 step l) $
interactive.simp_core {} (tactic.norm_num1 step (interactive.loc.ns [none]))
ff (simp_arg_type.except ``one_div :: hs) [] l >> skip
/-- Carry out similar operations as `tactic.norm_num` but on an `expr` rather than a location.
Given an expression `e`, returns `(e', β’ e = e')`.
The `no_dflt`, `hs`, and `attr_names` are passed on to `simp`.
Unlike `norm_num`, this tactic does not fail. -/
meta def _root_.expr.norm_num (step : expr β tactic (expr Γ expr))
(no_dflt : bool := ff) (hs : list simp_arg_type := []) (attr_names : list name := []) :
expr β tactic (expr Γ expr) :=
let simp_step (e : expr) := do
(e', p, _) β e.simp {} (tactic.norm_num1 step (interactive.loc.ns [none]))
no_dflt attr_names (simp_arg_type.except ``one_div :: hs),
return (e', p)
in or_refl_conv $ Ξ» e, do
(e', p') β norm_num.derive' step e <|> simp_step e,
(e'', p'') β _root_.expr.norm_num e',
p β mk_eq_trans p' p'',
return (e'', p)
namespace tactic.interactive
open norm_num interactive interactive.types
/-- Basic version of `norm_num` that does not call `simp`. -/
meta def norm_num1 (loc : parse location) : tactic unit :=
do f β get_step, tactic.norm_num1 f loc
/-- Normalize numerical expressions. Supports the operations
`+` `-` `*` `/` `^` and `%` over numerical types such as
`β`, `β€`, `β`, `β`, `β` and some general algebraic types,
and can prove goals of the form `A = B`, `A β B`, `A < B` and `A β€ B`,
where `A` and `B` are numerical expressions.
It also has a relatively simple primality prover. -/
meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit :=
do f β get_step, tactic.norm_num f hs l
add_hint_tactic "norm_num"
/-- Normalizes a numerical expression and tries to close the goal with the result. -/
meta def apply_normed (x : parse texpr) : tactic unit :=
do xβ β to_expr x,
(xβ,_) β derive xβ,
tactic.exact xβ
/--
Normalises numerical expressions. It supports the operations `+` `-` `*` `/` `^` and `%` over
numerical types such as `β`, `β€`, `β`, `β`, `β`, and can prove goals of the form `A = B`, `A β B`,
`A < B` and `A β€ B`, where `A` and `B` are numerical expressions.
Add-on tactics marked as `@[norm_num]` can extend the behavior of `norm_num` to include other
functions. This is used to support several other functions on `nat` like `prime`, `min_fac` and
`factors`.
```lean
import data.real.basic
example : (2 : β) + 2 = 4 := by norm_num
example : (12345.2 : β) β 12345.3 := by norm_num
example : (73 : β) < 789/2 := by norm_num
example : 123456789 + 987654321 = 1111111110 := by norm_num
example (R : Type*) [ring R] : (2 : R) + 2 = 4 := by norm_num
example (F : Type*) [linear_ordered_field F] : (2 : F) + 2 < 5 := by norm_num
example : nat.prime (2^13 - 1) := by norm_num
example : Β¬ nat.prime (2^11 - 1) := by norm_num
example (x : β) (h : x = 123 + 456) : x = 579 := by norm_num at h; assumption
```
The variant `norm_num1` does not call `simp`.
Both `norm_num` and `norm_num1` can be called inside the `conv` tactic.
The tactic `apply_normed` normalises a numerical expression and tries to close the goal with
the result. Compare:
```lean
def a : β := 2^100
#print a -- 2 ^ 100
def normed_a : β := by apply_normed 2^100
#print normed_a -- 1267650600228229401496703205376
```
-/
add_tactic_doc
{ name := "norm_num",
category := doc_category.tactic,
decl_names := [`tactic.interactive.norm_num1, `tactic.interactive.norm_num,
`tactic.interactive.apply_normed],
tags := ["arithmetic", "decision procedure"] }
end tactic.interactive
/-! ## `conv` tactic -/
namespace conv.interactive
open conv interactive tactic.interactive
open norm_num (derive)
/-- Basic version of `norm_num` that does not call `simp`. -/
meta def norm_num1 : conv unit := replace_lhs derive
/-- Normalize numerical expressions. Supports the operations
`+` `-` `*` `/` `^` and `%` over numerical types such as
`β`, `β€`, `β`, `β`, `β` and some general algebraic types,
and can prove goals of the form `A = B`, `A β B`, `A < B` and `A β€ B`,
where `A` and `B` are numerical expressions.
It also has a relatively simple primality prover. -/
meta def norm_num (hs : parse simp_arg_list) : conv unit :=
repeat1 $ orelse' norm_num1 $
conv.interactive.simp ff (simp_arg_type.except ``one_div :: hs) []
{ discharger := tactic.interactive.norm_num1 (loc.ns [none]) }
end conv.interactive
/-!
## `#norm_num` command
A user command to run `norm_num`. Mostly copied from the `#simp` command.
-/
namespace tactic
setup_tactic_parser
/- With this option, turn off the messages if the result is exactly `true` -/
declare_trace silence_norm_num_if_true
/--
The basic usage is `#norm_num e`, where `e` is an expression,
which will print the `norm_num` form of `e`.
Syntax: `#norm_num` (`only`)? (`[` simp lemma list `]`)? (`with` simp sets)? `:`? expression
This accepts the same options as the `#simp` command.
You can specify additional simp lemmas as usual, for example using
`#norm_num [f, g] : e`, or `#norm_num with attr : e`.
(The colon is optional but helpful for the parser.)
The `only` restricts `norm_num` to using only the provided lemmas, and so
`#norm_num only : e` behaves similarly to `norm_num1`.
Unlike `norm_num`, this command does not fail when no simplifications are made.
`#norm_num` understands local variables, so you can use them to
introduce parameters.
-/
@[user_command] meta def norm_num_cmd (_ : parse $ tk "#norm_num") : lean.parser unit :=
do
no_dflt β only_flag,
hs β simp_arg_list,
attr_names β with_ident_list,
o β optional (tk ":"),
e β texpr,
/- Retrieve the `pexpr`s parsed as part of the simp args, and collate them into a big list. -/
let hs_es := list.join $ hs.map $ option.to_list β simp_arg_type.to_pexpr,
/- Synthesize a `tactic_state` including local variables as hypotheses under which `expr.simp`
may be safely called with expected behaviour given the `variables` in the environment. -/
(ts, mappings) β synthesize_tactic_state_with_variables_as_hyps (e :: hs_es),
/- Enter the `tactic` monad, *critically* using the synthesized tactic state `ts`. -/
result β lean.parser.of_tactic $ Ξ» _, do
{ /- Resolve the local variables added by the parser to `e` (when it was parsed) against the local
hypotheses added to the `ts : tactic_state` which we are using. -/
e β to_expr e,
/- Replace the variables referenced in the passed `simp_arg_list` with the `expr`s corresponding
to the local hypotheses we created.
We would prefer to just elaborate the `pexpr`s encoded in the `simp_arg_list` against the
tactic state we have created (as we could with `e` above), but the simplifier expects
`pexpr`s and not `expr`s. Thus, we just modify the `pexpr`s now and let `simp` do the
elaboration when the time comes.
You might think that we could just examine each of these `pexpr`s, call `to_expr` on them,
and then call `to_pexpr` afterward and save the results over the original `pexprs`. Due to
how functions like `simp_lemmas.add_pexpr` are implemented in the core library, the `simp`
framework is not robust enough to handle this method. When pieces of expressions like
annotation macros are injected, the direct patten matches in the `simp_lemmas.*` codebase
fail, and the lemmas we want don't get added.
-/
let hs := hs.map $ Ξ» sat, sat.replace_subexprs mappings,
/- Try simplifying the expression. -/
step β norm_num.get_step,
prod.fst <$> e.norm_num step no_dflt hs attr_names } ts,
/- Trace the result. -/
when (Β¬ is_trace_enabled_for `silence_norm_num_if_true β¨ result β expr.const `true [])
(trace result)
add_tactic_doc
{ name := "#norm_num",
category := doc_category.cmd,
decl_names := [`tactic.norm_num_cmd],
tags := ["simplification", "arithmetic", "decision procedure"] }
end tactic
|
f40183ce479c5163ca544420329d6b1f9b7a0165 | 9cb9db9d79fad57d80ca53543dc07efb7c4f3838 | /src/polyhedral_lattice/basic.lean | 798c34c4e7e0b5064010787150a07affad418d08 | [] | no_license | mr-infty/lean-liquid | 3ff89d1f66244b434654c59bdbd6b77cb7de0109 | a8db559073d2101173775ccbd85729d3a4f1ed4d | refs/heads/master | 1,678,465,145,334 | 1,614,565,310,000 | 1,614,565,310,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,476 | lean | import analysis.normed_space.basic
import ring_theory.finiteness
import algebra.direct_sum
-- import hacks_and_tricks.by_exactI_hack
-- import hacks_and_tricks.type_pow
noncomputable theory
open_locale big_operators classical nnreal
section move_this
-- rewrite to include multiplicative version
-- also write version for modules, glue to version for groups
def torsion_free (A : Type*) [add_comm_group A] : Prop :=
β (a : A) (ha : a β 0) (n : β), n β’ a = 0 β n = 0
variables {R ΞΉ : Type*} [comm_ring R] [fintype ΞΉ]
variables (M : ΞΉ β Type*) [Ξ i, add_comm_group (M i)] [Ξ i, module R (M i)]
-- instance module.finite.pi : module.finite R (Ξ i, M i) :=
-- sorry
end move_this
section generates_norm
variables {Ξ ΞΉ : Type*} [normed_group Ξ] [fintype ΞΉ]
/-- A finite family `x : ΞΉ β Ξ` generates the norm on `Ξ`
if for every `l : Ξ`,
there exists a scaling factor `d : β`, and coefficients `c : ΞΉ β β`,
such that `d β’ l = β i, c i β’ x i` and `d * β₯lβ₯ = β i, (c i) * β₯x iβ₯`.
-/
def generates_norm (x : ΞΉ β Ξ) :=
β l : Ξ, β (d : β) (hd : 0 < d) (c : ΞΉ β β),
(d β’ l = β i, c i β’ x i) β§ ((d : β) * β₯lβ₯ = β i, (c i : β) * β₯x iβ₯)
lemma generates_norm_iff_generates_nnnorm (x : ΞΉ β Ξ) :
generates_norm x β
β l : Ξ, β (d : β) (hd : 0 < d) (c : ΞΉ β β),
(d β’ l = β i, c i β’ x i) β§ ((d : ββ₯0) * nnnorm l = β i, (c i : ββ₯0) * nnnorm (x i)) :=
begin
apply forall_congr, intro l,
simp only [β nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_sum, nnreal.coe_nat_cast, coe_nnnorm]
end
lemma generates_norm.generates_nnnorm {x : ΞΉ β Ξ} (hl : generates_norm x) :
β l : Ξ, β (d : β) (hd : 0 < d) (c : ΞΉ β β),
(d β’ l = β i, c i β’ x i) β§ ((d : ββ₯0) * nnnorm l = β i, (c i : ββ₯0) * nnnorm (x i)) :=
(generates_norm_iff_generates_nnnorm x).mp hl
lemma generates_norm_of_generates_nnnorm {x : ΞΉ β Ξ}
(H : β l : Ξ, β (d : β) (hd : 0 < d) (c : ΞΉ β β),
(d β’ l = β i, c i β’ x i) β§ ((d : ββ₯0) * nnnorm l = β i, (c i : ββ₯0) * nnnorm (x i))) :
generates_norm x :=
(generates_norm_iff_generates_nnnorm x).mpr H
end generates_norm
class polyhedral_lattice (Ξ : Type*) [normed_group Ξ] :=
[fg : module.finite β€ Ξ]
(tf : torsion_free Ξ)
(rational : β l : Ξ, β q : β, β₯lβ₯ = q)
(polyhedral [] : β (ΞΉ : Type) [fintype ΞΉ] (x : ΞΉ β Ξ), generates_norm x)
namespace polyhedral_lattice
attribute [instance] polyhedral_lattice.fg
variables {ΞΉ : Type} [fintype ΞΉ] (Ξ : ΞΉ β Type*)
variables [Ξ i, normed_group (Ξ i)] [Ξ i, polyhedral_lattice (Ξ i)]
open_locale direct_sum big_operators
instance : has_norm (β¨ i, Ξ i) :=
β¨Ξ» x, β i, β₯x iβ₯β©
lemma direct_sum_norm_def (x : β¨ i, Ξ i) : β₯xβ₯ = β i, β₯x iβ₯ := rfl
instance : normed_group (β¨ i, Ξ i) :=
normed_group.of_core _ $
{ norm_eq_zero_iff :=
begin
intros x,
simp only [direct_sum_norm_def, β coe_nnnorm, β nnreal.coe_sum, finset.mem_univ,
nnreal.coe_eq_zero, finset.sum_eq_zero_iff, nnnorm_eq_zero, forall_prop_of_true],
split,
{ intro h, ext, rw direct_sum.zero_apply, apply h, },
{ rintro rfl, intro, rw direct_sum.zero_apply, }
end,
triangle :=
begin
intros x y,
simp only [direct_sum_norm_def, β finset.sum_add_distrib, direct_sum.add_apply],
apply finset.sum_le_sum,
rintro i -,
apply norm_add_le,
end,
norm_neg :=
begin
intro x,
simp only [direct_sum_norm_def],
apply finset.sum_congr rfl,
rintro i -,
rw β norm_neg (x i),
congr' 1,
apply dfinsupp.neg_apply -- this is missing for direct_sum
end }
instance : polyhedral_lattice (β¨ i, Ξ i) :=
{ fg := sorry,
tf := sorry,
rational :=
begin
intro l,
have := Ξ» i, polyhedral_lattice.rational (l i),
choose q hq using this,
use β i, q i,
simp only [direct_sum_norm_def, hq],
change β i, algebra_map β β (q i) = algebra_map β β (β i, q i),
rw ring_hom.map_sum,
end,
polyhedral :=
begin
have := Ξ» i, polyhedral_lattice.polyhedral (Ξ i),
choose J _instJ x hx using this, resetI,
refine β¨Ξ£ i, J i, infer_instance, Ξ» j, direct_sum.of _ j.1 (x _ j.2), _β©,
intro l,
have := Ξ» i, hx i (l i),
choose d hd c H1 H2 using this,
let d' : ΞΉ β β := Ξ» iβ, β i in (finset.univ.erase iβ), d i,
have hl : l = β i, direct_sum.of _ i (l i),
{ sorry },
refine β¨β i, d i, _, Ξ» j, d' j.1 * c j.1 j.2, _, _β©,
sorry,
{ rw [hl, finset.smul_sum, β finset.univ_sigma_univ, finset.sum_sigma],
apply fintype.sum_congr,
intro i,
dsimp,
simp only [mul_smul, β finset.smul_sum], sorry },
sorry
end }
end polyhedral_lattice
lemma int.norm_coe_units (e : units β€) : β₯(e : β€)β₯ = 1 :=
begin
obtain (rfl|rfl) := int.units_eq_one_or e;
simp only [units.coe_neg_one, units.coe_one, norm_neg, norm_one_class.norm_one]
end
--move this
@[simp]
lemma int.units_univ : (finset.univ : finset (units β€)) = {1, -1} := rfl
lemma int.sum_units_to_nat_aux : β (n : β€), n.to_nat β’ 1 + -((-n).to_nat β’ 1) = n
| (0 : β) := rfl
| (n+1 : β) := show ((n+1) β’ 1 + -(0 β’ 1) : β€) = _,
begin
simp only [add_zero, mul_one, int.coe_nat_zero, add_left_inj, algebra.smul_def'', zero_mul,
int.coe_nat_inj', int.coe_nat_succ, ring_hom.eq_nat_cast, int.nat_cast_eq_coe_nat, neg_zero],
end
| -[1+ n] :=
begin
show (0 β’ 1 + -((n+1) β’ 1) : β€) = _,
simp only [mul_one, int.coe_nat_zero, algebra.smul_def'', zero_mul, int.coe_nat_succ, zero_add,
ring_hom.eq_nat_cast, int.nat_cast_eq_coe_nat],
refl
end
lemma int.sum_units_to_nat (n : β€) :
β (i : units β€), int.to_nat (i * n) β’ (i : β€) = n :=
begin
simp only [int.units_univ],
-- simp makes no further progress :head bandage: :scream: :shock: :see no evil:
show (1 * n).to_nat β’ 1 + (((-1) * n).to_nat β’ -1 + 0) = n,
simp only [neg_mul_eq_neg_mul_symm, add_zero, one_mul, smul_neg],
exact int.sum_units_to_nat_aux n
end
@[simp] lemma int.norm_coe_nat (n : β) : β₯(n : β€)β₯ = n :=
real.norm_coe_nat _
lemma give_better_name : β (n : β€), β₯nβ₯ = β(n.to_nat) + β((-n).to_nat)
| (0 : β) := by simp only [add_zero, norm_zero, int.coe_nat_zero, nat.cast_zero, int.to_nat_zero, neg_zero]
| (n+1 : β) := show β₯(β(n+1):β€)β₯ = n+1 + 0, by rw [add_zero, int.norm_coe_nat, nat.cast_succ]
| -[1+ n] := show β₯-β(n+1:β)β₯ = 0 + (n+1), by rw [zero_add, norm_neg, int.norm_coe_nat, nat.cast_succ]
instance int.polyhedral_lattice : polyhedral_lattice β€ :=
{ fg := by convert module.finite.self _,
tf := Ξ» m hm n h,
begin
rw [β nsmul_eq_smul, nsmul_eq_mul, mul_eq_zero] at h,
simpa only [hm, int.coe_nat_eq_zero, or_false, int.nat_cast_eq_coe_nat] using h
end,
rational :=
begin
intro n, refine β¨abs n, _β©,
simpa only [rat.cast_abs, rat.cast_coe_int] using rfl
end,
polyhedral :=
begin
refine β¨units β€, infer_instance, coe, _β©,
intro n,
refine β¨1, zero_lt_one, (Ξ» e, int.to_nat (e * n)), _, _β©,
{ rw [int.sum_units_to_nat, one_smul] },
{ simp only [int.norm_coe_units, mul_one, nat.cast_one, one_mul, int.units_univ],
show β₯nβ₯ = ((1 * n).to_nat) + (β(((-1) * n).to_nat) + 0),
simp only [neg_mul_eq_neg_mul_symm, add_zero, one_mul],
exact give_better_name n }
end }
|
317a29dc5238f0983b6275ffb1c24c1a5c3b1347 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /stage0/src/Lean/Hygiene.lean | d5534d5c179132124e90401b538def5000941048 | [
"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 | 4,612 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Lean.Data.Name
import Lean.Data.Options
import Lean.Data.Format
namespace Lean
/- Remark: `MonadQuotation` class is part of the `Init` package and loaded by default since it is used in the builtin command `macro`. -/
structure Unhygienic.Context where
ref : Syntax
scope : MacroScope
/-- Simplistic MonadQuotation that does not guarantee globally fresh names, that
is, between different runs of this or other MonadQuotation implementations.
It is only safe if the syntax quotations do not introduce bindings around
antiquotations, and if references to globals are prefixed with `_root_.`
(which is not allowed to refer to a local variable).
`Unhygienic` can also be seen as a model implementation of `MonadQuotation`
(since it is completely hygienic as long as it is "run" only once and can
assume that there are no other implentations in use, as is the case for the
elaboration monads that carry their macro scope state through the entire
processing of a file). It uses the state monad to query and allocate the
next macro scope, and uses the reader monad to store the stack of scopes
corresponding to `withFreshMacroScope` calls. -/
abbrev Unhygienic := ReaderT Lean.Unhygienic.Context $ StateM MacroScope
namespace Unhygienic
instance : MonadQuotation Unhygienic where
getRef := do (β read).ref
withRef := fun ref => withReader ({ Β· with ref := ref })
getCurrMacroScope := do (β read).scope
getMainModule := pure `UnhygienicMain
withFreshMacroScope := fun x => do
let fresh β modifyGet fun n => (n, n + 1)
withReader ({ Β· with scope := fresh}) x
protected def run {Ξ± : Type} (x : Unhygienic Ξ±) : Ξ± := (x β¨Syntax.missing, firstFrontendMacroScopeβ©).run' (firstFrontendMacroScope+1)
end Unhygienic
private def mkInaccessibleUserNameAux (unicode : Bool) (name : Name) (idx : Nat) : Name :=
if unicode then
if idx == 0 then
name.appendAfter "β"
else
name.appendAfter ("β" ++ idx.toSuperscriptString)
else
name ++ Name.mkNum "_inaccessible" idx
private def mkInaccessibleUserName (unicode : Bool) : Name β Name
| Name.num p@(Name.str _ _ _) idx _ =>
mkInaccessibleUserNameAux unicode p idx
| Name.num Name.anonymous idx _ =>
mkInaccessibleUserNameAux unicode Name.anonymous idx
| Name.num p idx _ =>
if unicode then
(mkInaccessibleUserName unicode p).appendAfter ("β»" ++ idx.toSuperscriptString)
else
Name.mkNum (mkInaccessibleUserName unicode p) idx
| n => n
def sanitizeNamesDefault := true
def getSanitizeNames (o : Options) : Bool:= o.get `pp.sanitizeNames sanitizeNamesDefault
builtin_initialize
registerOption `pp.sanitizeNames {
defValue := sanitizeNamesDefault,
group := "pp",
descr := "add suffix '_{<idx>}' to shadowed/inaccessible variables when pretty printing"
}
structure NameSanitizerState where
options : Options
-- `x` ~> 2 if we're already using `xβ`, `xβΒΉ`
nameStem2Idx : NameMap Nat := {}
-- `x._hyg...` ~> `xβ`
userName2Sanitized : NameMap Name := {}
private partial def mkFreshInaccessibleUserName (userName : Name) (idx : Nat) : StateM NameSanitizerState Name := do
let s β get
let userNameNew := mkInaccessibleUserName (Std.Format.getUnicode s.options) (Name.mkNum userName idx)
if s.nameStem2Idx.contains userNameNew then
mkFreshInaccessibleUserName userName (idx+1)
else do
modify fun s => { s with nameStem2Idx := s.nameStem2Idx.insert userName (idx+1) }
pure userNameNew
def sanitizeName (userName : Name) : StateM NameSanitizerState Name := do
let stem := userName.eraseMacroScopes;
let idx := (β get).nameStem2Idx.find? stem |>.getD 0
let san β mkFreshInaccessibleUserName stem idx
modify fun s => { s with userName2Sanitized := s.userName2Sanitized.insert userName san }
pure san
private partial def sanitizeSyntaxAux : Syntax β StateM NameSanitizerState Syntax
| Syntax.ident _ _ n _ => do
mkIdent <$> match (β get).userName2Sanitized.find? n with
| some n' => pure n'
| none => if n.hasMacroScopes then sanitizeName n else pure n
| Syntax.node k args => Syntax.node k <$> args.mapM sanitizeSyntaxAux
| stx => pure stx
def sanitizeSyntax (stx : Syntax) : StateM NameSanitizerState Syntax := do
if getSanitizeNames (β get).options then
sanitizeSyntaxAux stx
else
pure stx
end Lean
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.